diff --git a/.gitignore b/.gitignore index 2324c9a..36bf792 100644 --- a/.gitignore +++ b/.gitignore @@ -55,3 +55,4 @@ installer/previous-release/*.exe # Local publish/bundle output (SK-era Build-Installer staging and old bundle exes) installer/_toolpublish/ build_out/ +out/ diff --git a/BUILD.md b/BUILD.md index 1fb24f0..15776e1 100644 --- a/BUILD.md +++ b/BUILD.md @@ -9,6 +9,35 @@ RynthCore is the injection framework. RynthSuite (separate repo) contains the pl - Visual Studio 2022 Build Tools with the **.NET desktop** and **C++ desktop** workloads (required by the NativeAOT ILC linker) - Asheron's Call client installed +## The unloadable engine (the default since 2026-09-29) + +The engine now runs on CoreCLR, and a hot reload really frees the old engine and its plugins +(`docs/UNLOADABLE_ENGINE_PLAN.md`, Status section). What ships and deploys: + +``` +C:\Games\RynthCore\Runtime\ +├── RynthCore.Loader.dll ← native loader (native\Loader, C/cl.exe): injection target, hosts CoreCLR once +├── RynthCore.Shim.dll ← the only RynthCore code in CoreCLR's default context +├── RynthCore.Engine.dll(+pdb)← the engine, a managed assembly (-p:EngineHost=coreclr, ReadyToRun) +├── Avalonia.*, ImGui.NET ... ← the engine's own dependencies (load and unload with each engine) +├── cimgui, minhook, Skia ... ← native libraries (loaded once) +└── dotnet\ ← the app-local x86 .NET runtime (from the NuGet runtime pack) +C:\Games\RynthSuite\\ ← each plugin as a managed assembly + its dependency DLLs +``` + +| Task | Command | +|---|---| +| Full local deploy (engine, loader, managed plugins, launcher) | `scripts\Deploy-RynthCore.ps1` (close every client first; `-SkipLauncher` while the launcher runs) | +| Engine change, clients running | `scripts\Publish-EngineCoreClr.ps1 -EngineOnly` — each running client hot-reloads onto it by itself | +| Loader/Shim change, clients running | `scripts\Publish-EngineCoreClr.ps1` — the in-use copies are renamed aside; new launches get the new ones | +| Installer | `installer\Build-Installer.ps1` (release plugins stay NativeAOT: the new engine loads them) | +| Hot-reload test on a local server | `scripts\Test-ClrWorld.ps1 -Reloads 3` (see its header) | +| Why didn't a generation unload? | `tools\AlcRoots ` (build it: `dotnet build tools\AlcRoots -c Release`) | + +`-NativeAot` on `Deploy-RynthCore.ps1` and `Build-Installer.ps1` builds the old NativeAOT engine, +loader and plugins; the sections below describe that path. The engine and plugins use the same +source either way. Rules that keep an engine or plugin unloadable are in `CLAUDE.md` ("Unloadable engine"). + ## Projects | Project | Type | Output | @@ -92,7 +121,7 @@ C:\Games\RynthCore\ ├── RynthCore.Loader.dll ← Loader (NativeAOT x86) — injection target ├── RynthCore.Engine.dll ← Engine (NativeAOT x86) ├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint - ├── cimgui.dll ← ImGui C bindings (x86, docking branch) + ├── cimgui.dll ← ImGui C bindings (x86, docking branch; our build) └── Plugins\ └── *.dll ← Built-in plugin directory @@ -162,7 +191,7 @@ If AC is already running, click **RL** on the RynthCore overlay bar to hot-reloa | `Runtime\RynthCore.Loader.dll` | small (~1–2 MB) | NativeAOT didn't run — check for `Generating native code` in build output | | `Runtime\RynthCore.Engine.dll` | ~26 MB | NativeAOT didn't run — same diagnosis | | `RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` | ~7 MB | Built `dotnet build` instead of `dotnet publish` | -| `Runtime\cimgui.dll` | ~1.5 MB | Must match ImGui.NET 1.91.6.1 | +| `Runtime\cimgui.dll` | ~1.2 MB | Must be our build (`scripts\Build-Cimgui.ps1`); with ImGui on, the log shows `ImGuiSelfTest: OK` | To confirm NativeAOT actually ran, check that `.lib` and `.exp` files exist alongside the DLL in the publish output's `native\` directory. @@ -239,6 +268,7 @@ If your AC client ever gets a real-world patch, apply it to both copies (or `rob - **Clean before plugin publish.** Incremental NativeAOT builds can silently reuse stale output. Delete `obj\Release` and `bin\Release` before every plugin publish to guarantee a fresh compile. - **Engine deploy path is `Runtime\`**, not `C:\Games\RynthCore\` directly. The injector resolves `Runtime\RynthCore.Loader.dll` (preferred) and `Runtime\RynthCore.Engine.dll` (legacy) by default. - **Close AC before redeploying Loader or Engine.** Both are loaded into `acclient.exe` and locked while the game is running. Plugins are shadow-copied so they can be hot-swapped without closing AC. -- **cimgui.dll version must match ImGui.NET NuGet.** Post-1.90 struct layouts changed. A mismatched cimgui.dll causes `DisplaySize = <1, 1>` or font crashes on frame 2. +- **cimgui.dll is built by us, not taken from NuGet.** `scripts\Build-Cimgui.ps1` fetches cimgui 1.91.6dock into `native\cimgui\_src` (git-ignored), builds it with MSVC (VS 2022 Build Tools, C++ workload) and writes `src\RynthCore.Engine\Native\cimgui.dll`, which is committed. The stock NuGet x86 DLL does not match ImGui.NET's structs (64-bit `ImTextureID`); the engine's `ImGuiSelfTest` refuses it and any other non-matching build. Only rerun the script when changing the cimgui build itself. - **vswhere.exe must be on PATH** for the NativeAOT link step. Add `C:\Program Files (x86)\Microsoft Visual Studio\Installer` to PATH if missing. -- **Decal coexistence mode.** If `decal.dll`, `UBLoader.dll`, `Decal.Adapter.dll`, or `phatacd.dll` is loaded into acclient.exe, the engine skips the entire D3D9/ImGui path and runs plugins on a 30 Hz worker tick with Avalonia floating panels via `LayeredWindow` (GDI). This is intentional — two D3D9 hookers can't symmetrically save/restore render state. Check `RynthCore.log` for `D3D9: Decal coexistence` to confirm. +- **Decal.** `src\RynthCore.DecalBridge` (net48) builds with the solution when Decal is installed (an empty assembly and a warning otherwise); every installer stages it (`Build-Installer.ps1` fails without Decal; `-SkipDecalBridge` for a dev build). The launcher registers it only for accounts set to "Decal + RynthCore (experimental)"; their choice is kept in `%APPDATA%\RynthCore\decal-accounts.json`, never in the shared `appsettings.json`. Bridge mode and in-game ImGui under Decal: `docs/DECAL_BRIDGE_PLAN.md`. +- **Decal coexistence mode.** If `decal.dll`, `UBLoader.dll`, `Decal.Adapter.dll`, or `phatacd.dll` is loaded into acclient.exe and neither bridge mode nor `DecalInGameImGui` applies, the engine skips the entire D3D9/ImGui path and runs plugins on a 30 Hz worker tick with Avalonia floating panels via `LayeredWindow` (GDI). This is intentional — two D3D9 hookers can't symmetrically save/restore render state. Check `RynthCore.log` for `D3D9: Decal coexistence` to confirm. diff --git a/Changelog/2026-10-05-aelrynth-2026.10.5.1-merge.md b/Changelog/2026-10-05-aelrynth-2026.10.5.1-merge.md new file mode 100644 index 0000000..1db4197 --- /dev/null +++ b/Changelog/2026-10-05-aelrynth-2026.10.5.1-merge.md @@ -0,0 +1,131 @@ +# Merge: upstream aelrynth RynthCore 2026.10.5.1 into SK-local + +**Date:** 2026-10-05 +**Branch:** `merge/aelrynth-2026.10.5.1` (local only, not pushed) +**Upstream:** https://aelrynth.com/git/rynth/RynthCore (`upstream/main`, c3e1548) +**Component:** RynthCore (engine, plugin SDK, launcher, installer). RynthSuite is not part of this merge. + +## Summary + +Brings the upstream 2026.10.5.1 snapshot into our fork. Upstream publishes squashed +snapshots with no shared history, so the snapshot we had already ported (9b5e276, +2026.9.27.2) was recorded first as the merge base. This merge is a 3-way merge on top of it. + +Upstream's architecture wins wherever the two sides overlapped. Our features were ported +into the new structure rather than kept beside it. + +## What upstream brings + +- **UI data hub:** panels now read from `UiSources` and act through command classes + (`RynthAiCommands`, `ItemsCommands`, `NavCommands`, `SettingsCommands`). Plugin exports + are bound through `PluginExportBinder` and run on the pump thread (`UiDataHub.Post`). +- **ImGui "faces":** ImGui versions of the panels (`ImGui/Panels/*Face.cs`). +- **Chat:** chat model and router in `UI/Data/ChatData.cs`, with rules that have an + action, a "when" condition and a colour. +- **Settings:** data-driven settings (`SettingsSchema` / `SettingRow`). +- **Frame pipeline:** `EngineFrameController` replaces `ImGuiController` (deleted). + ImGui is now drawn *before* the Avalonia overlay, so draw order matches mouse hit-testing. +- **Unloadable engine:** a CoreCLR engine hosted by a native C loader (`native/Loader`, + `RynthCore.Shim`, app-local .NET runtime in `Runtime\dotnet`). The NativeAOT engine + is still available. +- **Plugin API stubs:** every plugin API slot is routed through native loader stubs. +- **Decal bridge (experimental):** a Decal network filter that lets an account run as + "Decal + RynthCore", with installer and launcher registration. +- **Item data:** a full PublicWeenieDesc byte snapshot (`PwdLayout`) for off-thread item reads. +- **Monster HUD, Lua panel**, plus many other fixes in the snapshot. + +## Our features kept + +- **Plugin API v77 (ABI change):** `GetMergeStackResultFn` moves to the end of the + API struct, after upstream's v68–v76 slots. Our previous slot position collided with + upstream's, so `PluginContract.Current`, `RynthCoreApiNative` and + `RynthCoreHost.CurrentApiVersion` are now 77. `HasGetMergeStackResult` requires v77. +- **Plugin overlay windows:** the ILT Hub, Item Info, Lua and Map overlay windows still + render when the ImGui shell is off. This is a new branch in + `EngineFrameController`, using `PluginManager.HasOverlayPlugins` and the + `EnablePluginOverlayWindows` setting. +- **Engine settings:** `LoggingLevel` is kept next to upstream's Decal settings. + The Decal keys were added to `OwnedFields` so settings.json never gets duplicate keys. +- **Window messages:** the layered-window self-destroy message moved from 0x8005 to + 0x8051. Upstream now uses 0x8005 for `WM_RYNTH_POST_ACTION` on the game window. +- **Chat standard filters and match modes:** ported into upstream's `ChatModel` and + `ChatRouter`. + - Contains / Starts with / Ends with / Regex modes for each rule. + - Standard (canned) filters run after custom rules and can hide lines or move them to a tab. + - Both the Avalonia filters panel and the ImGui `ChatFiltersFace` have the mode picker + and the Standard filters section. + - Settings JSON is unchanged (`filters[].mode`, `presets[]`). `RynthChatPresets` + state is `volatile` because routing runs on the pump thread. +- **Items panel Shields:** the Shields section is now backed by + `ItemsCommands.AddSelectedShield` (`RynthPluginAddSelectedShield`). +- **Inventory HUDs button:** a new `SettingKind.Button` row type in `SettingsSchema` + (Avalonia panel and ImGui face). It opens the HUD / Mini Remote window through + `RynthAiCommands.ApplyRemoteCommand("huds", "show")`. +- **RynthAi dashboard:** + - Char → `hub show`. + - Hub → `remote toggle`; right-click → `huds show`. + - The Map half of the Nav/Map button → `map toggle`. + - All four go through `RynthAiCommands.ApplyRemoteCommand`. +- **Meta folder:** `MetaData.MetaFolder` follows the install path + (`RynthInstallPaths.RynthAiDir\MetaFiles`) instead of a hard-coded `C:\Games` path. +- **Nav panel:** waypoint list polling pauses while the pointer is over the list. + +## Dropped in favour of upstream + +- `PropertyUpdateHooks` int/bool caches and `AppraisalHooks.PatchCachedInt/Bool`. + Upstream folds property updates into its appraisal cache. +- Our duplicate PublicWeenieDesc int snapshot in `ClientObjectHooks`. Off-thread + `TryReadPwdInt32` now reads upstream's byte snapshot via `TryGetPwdSnapshotRawInt32`. +- The deferred ImGui draw path (`RenderDeferredImGui`) and the multi-viewport experiment + (`ViewportProbe`, `ViewportPlatformBackend`, `ViewportRendererBackend`, `ViewportOffsets`). +- The launcher's "allow multiple clients" bypass of the duplicate-session check. + Upstream now keys sessions by account and server. + +## Installer and release scripts + +- `Build-Installer.ps1` keeps our layout: two install folders (`staging\core` / + `staging\suite`), experimental plugins, Monster Editor, release package and manifest. + New options: + - **Default engine is now upstream's unloadable CoreCLR engine** plus the native loader + (`scripts\Publish-EngineCoreClr.ps1`; needs the Visual Studio C++ tools). + `-NativeAot` builds the previous NativeAOT engine and loader. + - **Decal bridge:** built and staged to `{app}\DecalBridge` when Decal 3.0 is installed + (or `-DecalDir`). Without Decal the build continues with a warning. + `-IncludeDecalBridge` makes a missing Decal an error; `-SkipDecalBridge` leaves it out. + - The required-files check also covers the CoreCLR shim and runtime, and the bridge when built. +- `RynthCore.iss`: our Suite-folder pages and publisher info, plus upstream's Decal bridge + registration on install/update (`CurStepChanged`) and unregistration on uninstall. +- `Publish-Update.ps1`: our paths. A missing Decal bridge now only gives a warning + instead of blocking the publish. + +## Verification + +- `dotnet build RynthCore.sln -c Release`: 0 errors. +- NativeAOT publish of `RynthCore.Engine` and `RynthCore.Loader`: OK. +- `scripts\Publish-EngineCoreClr.ps1` (CoreCLR engine, native loader, shim, .NET 10.0.5 + app-local runtime) to a scratch folder: OK. +- Not yet tested in game. + +### RynthSuite against the v77 SDK + +- RynthSuite's own upstream merge (`merge/aelrynth-2026.10.5.1`, 532fa67) was checked out + next to this worktree (`D:\rynth-merge\RynthSuite`), so its `..\RynthCore` project + references resolve to this branch's SDK. +- RynthAi NativeAOT publish: OK. Full `RynthSuite.slnx` Release build: 0 errors. +- `RynthCore.RynthAiHostTests`: 356 passed, 0 failed (5 known failures). +- No RynthSuite code changes were needed. That branch's `InventoryManager` uses + upstream's `MergeStackInternal` and no longer calls `GetMergeStackResult`, so it needs + no v77 gate. +- A RynthAi built from SK-local RynthSuite (0.6.32 and earlier) reads + `GetMergeStackResultFn` at its old v68 slot, which upstream now uses for something else. + Only pair this engine with a RynthAi built from the merged RynthSuite. + +## Follow-ups + +- The installer's default engine is upstream's CoreCLR engine (confirmed). Test it in + game before releasing; `-NativeAot` is the fallback. +- Several new upstream paths are hard-coded to `C:\Games\...` (native loader log dir, + `RynthUpdater` default Suite dir, NavData, usage-stats dumps, ImGui pop-outs, + Decal bridge log dir). Installs in other folders may be affected. +- The ImGui `ItemsFace` has no Shields section yet (the Avalonia Items panel does). +- The `ImGuiStackRecovery` work in the main checkout is uncommitted and not part of this branch. diff --git a/Changelog/2026-10-05-char-panel-rework-progression-pets-quests.md b/Changelog/2026-10-05-char-panel-rework-progression-pets-quests.md new file mode 100644 index 0000000..fbeafc4 --- /dev/null +++ b/Changelog/2026-10-05-char-panel-rework-progression-pets-quests.md @@ -0,0 +1,73 @@ +# Char panel rework: Progression on the Skills panel, Pets and Quests windows (RynthAi 0.5.4-legacy-ui) + +Date: 2026-10-05 +Branches (local): RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands` +Previous plugin version: 0.5.3-legacy-ui + +## Why + +The ILT Hub's Character tab mixed three different things: + +- live session stats; +- character progression (XP, augmentations, enlightenment), which belongs with skills; +- quests. + +Pets and quests are things you keep open while playing, so they get their own windows. + +## Skills panel: new Progression tab (ILT worlds only) + +The engine's Skills panel gains a third tab, **Progression**, next to Skills and Attributes & +Vitals. It shows only when RynthAi reports an ILT-like world. It has three sections: + +- **XP planner**: XP for the next raise and for the next N raises (slider 1-100) of every attribute + and vital. Costs are computed exactly from the client's XP tables (`SkillDat.CostOf`). The Hub's + version used `/xp all` and +7.5-7.7% per-level estimates. Raising stays on the Attributes & Vitals + tab. +- **Augmentations**: the Hub's planner with the same controls. It has Load /aug, Lum per Enlightened + Coin, and per-aug targets. It shows luminance and coin totals, coins short and banked luminance. +- **Enlightenment**: same controls as the Hub had: + - next step, plan-to-level totals, coins per token and tokens short; + - the requirement checklist; + - Enlighten now, auto-enlighten (arm / spend XP first / check interval). + - "Enlighten now" and arming auto-enlighten ask in a Skills-panel confirmation first. The server + still shows its own Yes/No dialog. + +How it works: + +- RynthAi still owns the planner math and the saved inputs, so the numbers can't drift from the + Hub's. +- New export `RynthPluginGetProgressionJson` (built by `IltHubController.BuildProgressionJson` and + `IltProgression.AppendSnapshotJson`). The engine polls it through the new + `UiSources.Progression` (once a second while the Skills panel is open). +- Edits go back as the remote command `prog `, handled by `IltProgression.HandleRemote` + on the pump thread. The subcommands are `augload`, `augtarget`, `lumpercoin`, `enltarget`, + `coinspertoken`, `enlighten`, `autoenl on|off|arm`, `spendfirst` and `checkevery`. + +## Pets and Quests windows + +- **Pets**: new undocked "Pets" window. Open it with `/ra pets [show|hide|toggle]`, the Pet tab's + "Pop out" button, or Char right-click > Pets window. Closing it docks the roster back into the Pet + tab. It draws only on ILT worlds. The open state is saved per character (`PetsWindowOpen`). +- **Quests**: the existing undocked quest window now carries Quest bonus (`/qb`) above the tracker. + Open it with `/ra quests window [show|hide|toggle]` or Char right-click > Quests window. + +## ILT Hub layout + +- Tabs: **Character · Quests · Pet · Banking · Gear · Games**. Tab buttons are narrower (92 px) so + all six fit the Hub's width. +- **Character**: Session rates, plus a note pointing to the Skills panel's Progression tab. +- **Quests** (new tab): Quest tracker + Quest bonus. It shows "open in its own window / Dock back" + while the Quests window is open. +- **Pet**: the roster with a "Pop out" button. It shows "Dock back" while the Pets window is open. +- Saved tab selections still open the same tab. New tabs are appended to the persisted index list, + and only the display order changed. +- Removed from the Hub: the XP calculator (replaced by the exact Skills-panel planner) and the Hub's + copies of the Augmentations / Enlightenment UI. Unused `/xp all` capture and `/attr` raise code + went with them. The spend-XP-before-auto-enlighten loop is unchanged. + +## Dashboard + +- **Char** launcher, left-click: ILT Hub (unchanged). +- **Char** launcher, right-click (new menu): ILT Hub, Pets window, Quests window, and + Progression (Skills panel). Progression opens the Skills panel on the Progression tab + (`SkillsFace.ShowProgression`). diff --git a/Changelog/2026-10-05-charms-tracking-tab.md b/Changelog/2026-10-05-charms-tracking-tab.md new file mode 100644 index 0000000..39b4690 --- /dev/null +++ b/Changelog/2026-10-05-charms-tracking-tab.md @@ -0,0 +1,58 @@ +# Charms Tracking tab (Settings) - RynthAi 0.5.10-legacy-ui + +Date: 2026-10-05 +Previous RynthAi version: 0.5.9-legacy-ui +Next installer: 2026.10.5.9 (not built yet; includes the Nav breadcrumb / route overlay toggles) + +## Charm list check against ACECustom + +RynthAi's charm registry (`IltHub/IltInventory.cs`, `Charms`) was compared with ACECustom's +`CharmAbilityRegistry.cs`. All 13 registry charms are present with every tier WCID: + +| Charm | WCIDs | Player ability flag | +|-------|-------|---------------------| +| Mana Barrier | 777700001, 777700054, 777710004, 777720004 | 50010 | +| Infinite Casting Stone | 777700019, 777700055 | 50028 | +| Asheron's Favor | 777700020, 777710002, 777720002 | 50030 | +| Artisan's | 777700021, 777710003, 777720003 | 50031 | +| Shrapnel | 777700022 | 50032 | +| Agony | 777700023 | 50033 | +| Split Cast | 777700024 | 50035 | +| Explosive Arrow | 777700025, 777710005, 777720005 | 50036 | +| Omni Strike | 777700026 | 50037 | +| Fork | 777700027, 777710007, 777720007 | 50039 | +| Auto-Rebuff | 777700300 | none (server keeps it in memory) | +| Summon Essence Refill | 78780030 | 9049 | +| Universal Summoning Mastery (universal pet charm) | 78780031 | 50038 | + +Guardian Hand is not an ACECustom registry charm; RynthAi still recognises it by name on the Gear window. + +## New: Settings > Charms Tracking + +The engine Settings panel has a new last sidebar tab, **Charms Tracking**, with one row per charm: + +- **Acquired**: `Carried` (in your pack or equipped, with a count when you have several), + `Stored` (this character carried it before; RynthAi remembers it per character in + `ilt-hub.json`, because the client only sees carried items) or `Not yet`. +- **Status**: `ON` / `OFF` from the charm's appraisal text ("Status: ON"), falling back to the + character's ability flag. Appraisal is requested automatically (throttled to every 30 s per item). +- **Tier**: current / max tier (CharmLevel / CharmMaxLevel, or "Charm [Tier x/y]" from the appraisal). +- **Server**: `Disabled` when the server refused the charm (Auto-Rebuff, Universal Summoning + Mastery) or a feature dump reported it off, `Enabled` when reported on, otherwise `-` + (players can't query the server's /charms list). +- Hover a charm name for its effect. A summary line shows how many are acquired and active. +- Off ILT worlds the tab says so and points to `/ra hub force on`. + +## Fix + +- Pets: an Infinite Casting Stone that is switched OFF no longer counts as "casting supplies" + (an OFF stone doesn't waive spell components). + +## Files + +- RynthSuite: `IltHub/IltCharmTracker.cs` (new), `IltHub/IltInventory.cs` (charm flags, effects, + tier reader, casting-stone check), `IltHub/IltHubState.cs` / `IltHubStore.cs` (`CharmsSeen`), + `IltHub/IltHubController.cs`, `PluginExports.cs` (`RynthPluginGetCharmsJson`), + `RynthAiPlugin.LocalFeatures.cs`, `RynthAiVersionCommand.cs` (0.5.10-legacy-ui). +- RynthCore: `UI/Data/CharmsData.cs` (new `CharmsSource`), `UI/Data/UiSources.cs`, + `ImGui/Panels/SettingsFace.cs` (Charms Tracking tab). \ No newline at end of file diff --git a/Changelog/2026-10-05-floating-window-placement.md b/Changelog/2026-10-05-floating-window-placement.md new file mode 100644 index 0000000..b53319c --- /dev/null +++ b/Changelog/2026-10-05-floating-window-placement.md @@ -0,0 +1,63 @@ +# Floating windows open where they can be seen (RynthAi 0.5.5-legacy-ui) + +Date: 2026-10-05 +Branches (local): RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands` +Previous plugin version: 0.5.4-legacy-ui + +## Problem + +New windows with no saved position opened in the top-left corner of the game view: + +- the Pets window at ImGui's default (60,60); +- the Item HUD at (20,220); +- the Mini Remote at (20,120); +- the Dungeon Map in the panel cascade (100,100 and onwards). + +Popped-out panels are separate Windows windows above the game window. They often sit in that +corner, and nothing drawn inside the game frame (ImGui windows included) can appear over them. So +the new windows opened hidden underneath. The draw-order fix (`2026-10-05-imgui-over-avalonia-port.md`) +only covers the Avalonia layer painted inside the game frame. + +## Changes + +### RynthAi (plugin) + +- New `UiPlacement` helper: + - `CenterFirstUse(offset)`: before `Begin`, sets a `FirstUseEver` position centred in the game + view (pivot 0.5,0.5). It only applies when imgui.ini has nothing saved for the window. + - `RescueOncePerShow(ref checked)`: once per show, moves the window to the middle if less than + 40 px of it is on screen. The test is the ILT Hub's existing off-screen check, now shared as + `UiPlacement.IsOnScreen`. +- First-use spots (centre plus offset): + + | Window | First-use spot | + | --- | --- | + | ILT Hub | centre | + | Pets | centre | + | Quests (popped out) | centre + (40,40) | + | Item HUD | centre + (220,-160) | + | Mini Remote | centre + (-220,-160) | + + All five also get the off-screen check each time they're shown. +- The ILT Hub's off-screen rescue now moves the window to the middle of the game view instead of + (40,40), which is where popped-out panels usually sit. + +### Engine + +- `PanelSpec.OpenCentered`: a panel with nothing saved and no `DefaultPos` opens centred in the game + view instead of the cascade. The Dungeon Map uses it. +- Docked panels open clear of popped-out windows. + - When an engine panel opens docked, `ImGuiPanelHost` checks the visible popped-out windows + (`LayeredWindow.VisibleContentRects`: every Avalonia and ImGui pop-out and the floating bar). + - If more than half of the panel would be hidden, it opens at the nearest spot on a 9x9 grid over + the game view that's hidden the least. The open's normal save records that spot. + - Each move is logged as `ImGuiPanelHost: would open under a popped-out window; moved from + (x,y) to (x,y).` + +## Limits + +- Plugin windows (Pets, Quests, Item HUD, Mini Remote, Hub) are centred on first use and pulled back + if off-screen. They don't yet avoid popped-out panels: the plugin can't see where those are. That + would need a new PluginSdk host call. +- ImGui windows still can't draw above popped-out panels. To keep both visible, dock the panel, or + move it away from where the windows open. diff --git a/Changelog/2026-10-05-guardian-and-remote-slots.md b/Changelog/2026-10-05-guardian-and-remote-slots.md new file mode 100644 index 0000000..a462a8b --- /dev/null +++ b/Changelog/2026-10-05-guardian-and-remote-slots.md @@ -0,0 +1,58 @@ +# 2026-10-05 - ILT Guardian window, Mini Remote slot assignment + +RynthAi 0.5.11-legacy-ui (previous 0.5.10-legacy-ui) with the RynthCore engine changes below. +Ships in installer 2026.10.5.10. + +## Guardian window (ported from UB-IT's Guardian tab) + +Open it from the Mini Remote's Options, the dashboard Char button's right-click menu, or +`/ra hub open guardian` (`/ra guardian window`). + +- **Riddle translator.** Translates incoming "Guardian of the Temple of Enlightenment" and + "Guardian of Attribute Enlightenment" tells and says (all 18 Temple spell words and the full + attribute-riddle table, typo-tolerant), plus a paste box for manual translation. The answer + shows in the window and as a "Guardian:" row on the Mini Remote for 10 minutes, with a + Give button. +- **Hand-in.** Gives one of the answer item to the guardian (whole item when it isn't a stack). + For the Temple guardian, when you carry none and "Buy if missing" is on, it first buys one + from the open or nearest vendor through the engine's vendor trade API. It waits out the busy + hourglass, has per-step timeouts, and reports every failure in chat. "Auto hand-in" runs it + after each chat answer (off by default). +- **Attribute turn-ins.** One row per Fiun attribute NPC plus the riddle. Counts and cooldowns + come from /myquests when the server reports the flag, otherwise from "/qb list" wait stamps + (a stamp appearing counts a turn-in and starts an estimated cooldown; "Assumed cooldown" + sets its length). Rows can be overridden with `infi attribute.csv` in the RynthAi folder or + UB's `Documents\Asheron's Call` location. +- **Commands:** `/ra guardian [window|translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status]`. +- **Not ported:** UB's `/fillcomps` + "buy all" spell-component restock during the Temple + hand-in. It is unrelated to the guardian quest, and the engine buys specific items rather + than the client's buy list. + +New files: `IltHub/IltGuardian.cs`, `IltHub/IltGuardianPhrasebook.cs`, `IltHub/IltTempleAttributes.cs`. +Settings persist per character in `ilt-hub.json` (`Guardian` block, `GuardianWindowOpen`). + +## Mini Remote slot assignment + +Previously, items could not be put into Mini Remote slots from the game inventory or from a +popped-out RynthCore Inventory. + +- **Game inventory drag-and-drop (engine `ItemDragBridge`).** A left drag that starts on a + carried item in AC's own inventory is now published to ImGui. Releasing it on an **empty** + Mini Remote slot assigns it. A game drag released over any RynthCore window is handed back + to AC at its starting point, so the item is never dropped on the ground. +- **Popped-out RynthCore Inventory.** Drags from a popped-out Inventory window now reach the + Mini Remote (the pop-out runs in its own ImGui context). +- **Click to assign.** Clicking an item in the RynthCore Inventory also selects it in the game. + The Mini Remote remembers the last carried item you selected for 2 minutes, so the combat + bot re-selecting monsters no longer loses it before you click an empty slot. +- **Inventory right-click: "Add to Mini Remote".** Adds the item to the first empty slot or a + chosen slot (remote command `remoteslot <slot|first> <objectId>`). +- Empty-slot tooltips explain all three ways to assign. + +### Known limits + +- The engine infers a game-inventory drag from AC's selection. Dragging an AC panel while a + pack item is selected looks the same, which is why game drags only fill empty slots. + Dragging from the RynthCore Inventory can replace a filled slot. +- If an AC panel is dragged and released over a RynthCore window while a pack item is selected, + the panel returns to where the drag started. diff --git a/Changelog/2026-10-05-guardian-vendor-and-item-lookup.md b/Changelog/2026-10-05-guardian-vendor-and-item-lookup.md new file mode 100644 index 0000000..bbdbd7b --- /dev/null +++ b/Changelog/2026-10-05-guardian-vendor-and-item-lookup.md @@ -0,0 +1,38 @@ +# ILT Guardian: hand-in finds the vendor and the item in your pack + +**Date:** 2026-10-05 +**Component:** RynthAi 0.5.13-legacy-ui (previous 0.5.12-legacy-ui), `IltHub/IltGuardian.cs` + +## Problem + +The riddle was translated correctly, but the hand-in never got further: + +- **Temple guardian** (Myrrh, Saffron): every attempt failed within ~30 ms with + "no Myrrh carried and no vendor nearby", while Archmage Yuzai Zhen (`0x77F15002`) stood next to you. +- **Attribute guardian** (Ashwood Talisman): after buying the talisman, every attempt failed with + "no Ashwood Talisman in your packs". + +## Causes + +1. The vendor search looked for `ObjectClass == Vendor`. The world cache classifies every creature, + vendors included, as Monster (or Npc later); nothing is ever classed Vendor, so no vendor could match. +2. The item search used the world cache's inventory set. That set is filled asynchronously (a fresh + purchase can be missing), and items from an open vendor's stock land in it too (they have no + position), so it isn't a reliable "what's in my pack" list. + +## Fix + +- Vendors are recognised by the weenie **BF_VENDOR** bitfield flag (`0x200`) through + `TryGetObjectBitfield` (a cache entry classed Vendor still counts). +- The hand-in item is looked up in a **live walk of your pack and side packs** + (`GetDirectInventory(forceRefresh: true)`, AC's container contents with live names). Worn items are skipped. +- Item and vendor-stock names are compared ignoring case and extra spaces. +- When something isn't found, the IltHub log says why: + - `[IltGuardian] no '<item>' among N carried items; similar names: ...` + - `[IltGuardian] vendor search: N landscape objects, bitfield=yes, vendors: '<name>' 0x... <dist> m` + - `[IltGuardian] vendor for '<item>': <name> 0x...` when a vendor is picked. + +## Not changed + +- Buying applies to the Temple guardian only (Attribute guardian items must be carried). +- Search range stays 60 m for the vendor and the guardian. diff --git a/Changelog/2026-10-05-ilt-hub-context-char-hub-logging.md b/Changelog/2026-10-05-ilt-hub-context-char-hub-logging.md new file mode 100644 index 0000000..8d546da --- /dev/null +++ b/Changelog/2026-10-05-ilt-hub-context-char-hub-logging.md @@ -0,0 +1,59 @@ +# ILT Hub windows draw again, Char/Hub on the ImGui dashboard, hidden-log warning + +**Date:** 2026-10-05 +**Component:** RynthCore Engine (merge branch `merge/aelrynth-2026.10.5.1`, after installer 2026.10.5.2) + +## Summary + +Fixes three problems found testing installer 2026.10.5.2. + +## ILT Hub (and the other RynthAi windows) never appeared + +RynthAi logged `[Overlay] OnRenderOverlay skipped: no ImGui context.` on both clients. + +- **Cause:** the merged engine handed plugins the ImGui context only when the ImGui shell is on. + In this build the shell can only be turned on through an environment variable. RynthAi's own + ImGui windows (ILT Hub, Mini Remote, Inventory HUDs, Item Info, translator window, nav overlay) + draw only with that context, so they all skipped. UbRythai also refused to start without it + (its `Initialize` returns 11). +- **Fix (`ImGui/EngineFrameController.cs`):** plugins also get the context when plugin overlay + windows are enabled (`EnablePluginOverlayWindows`, default on) and the ImGui layer is on. + The plugin host copies the context once at init, so plugin init waits for the first ImGui + frame. The wait is capped at about 5 s (300 pump frames). If ImGui init fails or stalls, + plugins start anyway and a warning is logged. +- The merged RynthAi reads the context only for those windows, so this does not switch it into + its old legacy ImGui UI (the reason upstream withheld it). + +## Char and Hub buttons were missing + +With the ImGui layer on, the engine always shows upstream's ImGui RynthAi dashboard +(`RynthAiFace`) in the game window. Char and Hub had only been ported to the Avalonia dashboard, +which is no longer shown there. + +- **Fix (`ImGui/Panels/RynthAiFace.cs`):** the launcher row now has 10 buttons. After Patrol: + - **Char:** opens the ILT Hub (`/ra hub show`). + - **Hub:** left-click toggles the Mini Remote (`/ra remote`); right-click opens the Inventory + HUDs setup (`/ra huds`). + +## Engine log nearly empty + +The 2026.10.5.2 session logs had only loader lines and two warnings. + +- **Cause:** `engine.json` had `LoggingLevel: Info` with every `LogCategories` entry at + `Trace`. A category's value is the level its lines are written at, so every engine and + plugin line became a Trace line and was dropped by the Info global level. The startup banner + went through the same filter. +- **Fix (`EntryPoint.cs`, `LogSettings.cs`):** + - The startup banner (build, OS/CLR, logging summary) is always written. + - A new warning names any category set above the global level. It is logged at startup and + whenever `engine.json` changes, e.g. `LogSettings: General=Trace, ... write above the + global LoggingLevel (Info), so those lines are NOT logged.` +- Your `engine.json` now has `LoggingLevel: Trace` (changed at 09:10), so the next session + logs everything as-is. + +## Files + +- `src/RynthCore.Engine/ImGui/EngineFrameController.cs` +- `src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs` +- `src/RynthCore.Engine/LogSettings.cs` +- `src/RynthCore.Engine/EntryPoint.cs` diff --git a/Changelog/2026-10-05-imgui-over-avalonia-port.md b/Changelog/2026-10-05-imgui-over-avalonia-port.md new file mode 100644 index 0000000..438a8e7 --- /dev/null +++ b/Changelog/2026-10-05-imgui-over-avalonia-port.md @@ -0,0 +1,41 @@ +# ImGui windows draw over the Avalonia panels again (merge branch) + +Date: 2026-10-05 +Branch: RynthCore `merge/aelrynth-2026.10.5.1` (local) +Restores: SK-local 6b94752 (draw order part) + +## Problem + +In 2026.10.5.4 the ILT Hub, Mini Remote and Inventory HUDs open, but an Avalonia panel covering +the same screen area hides them. The Hub, saved at about (540,105), 633x786, only shows where no +panel covers it. + +SK-local 6b94752 submitted ImGui draw data after the Avalonia blit. The aelrynth merge took +upstream's `EngineFrameController`. Upstream builds the ImGui frame in `BuildImGuiFrame` and +submits it inside `OnEndScene`, before `EndSceneHook` blits the Avalonia quad. So the panels drew +on top again. + +## Fix + +- `EngineFrameController.OnEndScene` keeps the built frame (device + timing) instead of submitting + it. The pending frame is cleared at the start of every `OnEndScene`, so a frame that throws early + never resubmits stale draw data. +- New `EngineFrameController.RenderDeferredImGui()` submits it once. `UiFrameStats` gets build + + pop-out + submit time, as before. +- `EndSceneHook` calls `RenderDeferredImGui()` after `OverlayTextureRenderer.Render`. It runs even + when the Avalonia blit doesn't (character select), so ImGui draws exactly as before there. +- Popped-out panels still render inside `OnEndScene`. They use their own render targets and restore + AC's target and viewport. + +## Mouse priority (checked, unchanged) + +6b94752's `Win32Backend.ImGuiOwnsMouseOverAvalonia` survived the merge. A mouse message skips the +Avalonia forward while ImGui wants the mouse (`io.WantCaptureMouse` or a monster nameplate), unless +an Avalonia drag/resize holds pointer capture. So clicks on a visible ImGui window go to ImGui, not +to the panel underneath. Only a misplaced doc comment was fixed. + +## Notes + +- ImGui windows and in-client ImGui panels now cover any Avalonia panel or popup they overlap. + Avalonia gets the click only where no ImGui window is under the cursor. +- Engine build only; not in an installer yet. diff --git a/Changelog/2026-10-05-inventory-add-to-item-count-hud.md b/Changelog/2026-10-05-inventory-add-to-item-count-hud.md new file mode 100644 index 0000000..f9ba2ad --- /dev/null +++ b/Changelog/2026-10-05-inventory-add-to-item-count-hud.md @@ -0,0 +1,22 @@ +# Inventory: "Add to item count HUD" (RynthAi 0.5.3-legacy-ui) + +Date: 2026-10-05 +Branches (local): RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands` +Previous plugin version: 0.5.2-legacy-ui + +## What's new + +- The in-client **Inventory** panel's right-click menu has **Add to item count HUD** for any item + that isn't a pack. It adds the item, by name, to RynthAi's floating item count HUD and shows the + HUD. You no longer have to select the item in the game first and use the HUD setup window. +- Typed equivalent: `/ra itemhud add <item name>`. +- RynthAi confirms in chat: `Added <name> to the item count HUD.` or `<name> is already on the item + count HUD.` The icon and WCID fill in on the HUD's next pack scan. + +## How it works + +- Engine `InventoryFace` sends the remote command `itemhudadd=<item name>` through + `RynthAiCommands.ApplyRemoteCommand`. +- RynthAi's `ApplyRemoteCommand` queues it to the pump thread and calls + `HudController.AddToItemHudAndShow` (new). `/ra itemhud add` uses the same handler. +- `/ra itemhud [show|hide|toggle]` is unchanged. diff --git a/Changelog/2026-10-05-mini-remote-is-ilt-hub.md b/Changelog/2026-10-05-mini-remote-is-ilt-hub.md new file mode 100644 index 0000000..af2a03b --- /dev/null +++ b/Changelog/2026-10-05-mini-remote-is-ilt-hub.md @@ -0,0 +1,63 @@ +# Mini Remote is the ILT Hub (RynthAi 0.5.8-legacy-ui) + +Date: 2026-10-05 +Branches: RynthCore `merge/aelrynth-2026.10.5.1`, RynthSuite `fix/rynthai-launcher-remote-commands` + +## What changed + +The tabbed **ILT Hub** window is retired. The **Mini Remote** is now the Hub, the same way +UtilityBelt's ILT Mini Remote works. + +### Mini Remote +- New top row with two buttons: + - **V/H** switches between stacked sections (vertical) and three side-by-side columns + (horizontal). The columns are: status (stats, target, pet, Reset XP / Report), actions + (item slots, toggles) and economy (bank, rebuff, translate). The choice is saved + (`HudState.MiniRemoteHorizontal`). + - **Options** opens the same menu as right-clicking the remote. +- The Options menu has a new **ILT Hub** group at the top: + - Character, Quests, Pets, Banking, Gear and Games each open or close their own window. + An item is ticked while its window is open, and greyed out until the server reports the + feature on. + - A pointer to the Skills panel for Progression. + - On non-ILT worlds: the world status, **Treat this world as ILT** and **Refresh server + features**. +- The Options menu also has a **Horizontal layout** checkbox (same as V/H). +- The empty-bank hint now reads "Options > Banking". + +### Hub section windows +- Each former tab is its own window. Each one opens near the centre the first time and is + moved back on screen if its saved position leaves it off-screen. + - **ILT Character**: world / server-options header (Refresh, Force ILT, Profiles), session + rates, and the Progression note. This window also explains why the Hub is idle on other + worlds. + - **Quests**: quest bonus and quest tracker. The old "Pop out" button is gone, because this + window is now the tracker's only home. + - **Pets**, **Banking**, **Gear**, **Games**. +- Open/closed state is saved per character (`IltCharacterState.CharacterWindowOpen`, + `BankingWindowOpen`, `GearWindowOpen`, `GamesWindowOpen`, plus the existing + `PetsWindowOpen` and `QuestTrackerPoppedOut`). +- The Games HUD, the quest favorites HUD and the confirmation dialog are unchanged. +- Bank auto-refresh and the gear / split-arrow scans used to run only while the Hub window was + open. They now run while the Mini Remote or any Hub section window is open. + +### Commands +- `/ra hub` and `/ra hub show|hide|toggle` now show, hide or toggle the Mini Remote. +- New: `/ra hub open character|quests|pets|banking|gear|games [show|hide|toggle]`. + Aliases: `char`, `rates`, `quest`, `pet`, `bank`, `game`. +- `/ra pets` and `/ra quests window` still work. They are the same as `/ra hub open pets` and + `/ra hub open quests`. + +### Engine dashboard (RynthAiFace) +- **Char** left-click opens the Mini Remote (the Hub). +- **Char** right-click menu: Mini Remote (ILT Hub), then Character, Quests, Pets, Banking, + Gear and Games (each toggles its window), then Progression (Skills panel). + +## Not ported from UtilityBelt's Mini Remote +- Storm and Reset Storm, the Guardian textbox, and the Fellow toggle. +- The LumS, KillL, PassL and Conv rate lines (RynthAi doesn't track these yet). +- Loot-profile and character-profile pickers on the remote. + +## Versions +- RynthAi plugin: 0.5.8-legacy-ui (previous 0.5.7-legacy-ui). +- The next installer is 2026.10.5.8 (previous 2026.10.5.7). diff --git a/Changelog/2026-10-05-native-drag-real-item.md b/Changelog/2026-10-05-native-drag-real-item.md new file mode 100644 index 0000000..19b40f0 --- /dev/null +++ b/Changelog/2026-10-05-native-drag-real-item.md @@ -0,0 +1,49 @@ +# Mini Remote: dragging from the game inventory uses the item you dragged + +**Date:** 2026-10-05 +**Components:** RynthCore.Engine (next installer 2026.10.5.11), RynthAi 0.5.12-legacy-ui (previous 0.5.11-legacy-ui) + +## Problem + +Dragging an item from AC's own inventory onto a Mini Remote slot assigned whatever item was +selected before the drag, not the item being dragged. AC does not change the selected object +when a drag starts, and the engine's drag bridge read the dragged item from the selection. + +Log evidence (session pid 33152): three drags of different items all published +`0x803AAE1B` (Frozen Valley Everlasting Portal Gem, the last clicked item), which landed in slot 17. + +## Fix + +- **New `Compatibility/DragDropHooks.cs`** hooks `UIElementManager::StartDragandDrop` + (`0x0045E120`, thiscall). It resolves the dragged UI element to an object id with AC's own + `UIElement_ItemList::InqDropIconInfo` (`0x004E3380`, cdecl). Same approach as Chorizite's UIHooks. + - Both addresses are resolved by byte patterns that are unique in the shipped client. If either + pattern misses, the hook is skipped (no hard-coded fallback) and the old behavior remains. +- **`ItemDragBridge`** + - `OnNativeDragStart(itemId)` takes the hooked item while a game-owned left press is held, for + carried items only (pack, side pack or worn). Spell-bar drags are ignored. + - Hooked drags are published as `RYNTH_INV_ITEM`, so they can go on **any** slot (and replace an + assigned one), exactly like drags from the RynthCore Inventory. + - The selection guess (`RYNTH_GAME_ITEM`, empty slots only) now runs only when the hook is not installed. + - Released over an ImGui window, the drop is still handed back to AC at the drag's start, so the + item never lands on the ground. +- **RynthAi** — `MiniRemoteHud` comment updated to describe both payloads; version 0.5.12-legacy-ui. + +## Verifying + +The engine log shows, at startup: + +- `HookResolver[DragDrop.InqDropIconInfo]: RESOLVED via pattern-unique @ 0x004E3380` +- `HookResolver[DragDrop.StartDragandDrop]: RESOLVED via pattern-unique @ 0x0045E120` +- `Compat: drag-start hook ready` + +Then, on each AC inventory drag: + +- `DragDropHooks: AC drag start item=0x........` (first 20 drags) +- `ItemDragBridge: native inventory drag 0x........ published to ImGui.` + +## Unchanged + +- Click an item (game inventory or RynthCore Inventory), then click an empty Mini Remote slot. +- RynthCore Inventory right-click **Add to Mini Remote**. +- Drag from the RynthCore Inventory or a popped-out Inventory. diff --git a/Changelog/2026-10-05-nav-breadcrumbs-route-overlay-toggles.md b/Changelog/2026-10-05-nav-breadcrumbs-route-overlay-toggles.md new file mode 100644 index 0000000..271a21b --- /dev/null +++ b/Changelog/2026-10-05-nav-breadcrumbs-route-overlay-toggles.md @@ -0,0 +1,36 @@ +# Nav panel: Breadcrumbs and Route overlay toggles (RynthAi 0.5.9-legacy-ui) + +Date: 2026-10-05 +Branches: RynthCore `merge/aelrynth-2026.10.5.1`, RynthSuite `fix/rynthai-launcher-remote-commands` + +## What changed + +### Nav panel (engine, `NavFace`) +A new row under Route / Insert has two checkbox-style toggles. A ticked box and teal text means +on. Both are saved per character in RynthAi's settings. +- **Breadcrumbs**: records the trail you walk and draws it on the ground. Turning it off stops + recording and hides the trail. Turning it back on starts a new trail segment, so the trail + never draws a line across the stretch you walked while it was off. +- **Route overlay**: draws the route in the world: waypoint rings and connecting lines, waypoint + labels, and the guide line to the active waypoint. The waypoint HUD window keeps its own + switch (`/ra navhud`). + +### RynthAi +- `NavOverlaySettings.ShowRouteMarkers` now does something. It was saved but never read, so + route rings always drew. `NavMarkerRenderer` now skips the rings and lines when it is off, + and the waypoint labels and guide line follow it too. +- `NavOverlaySettings.TrackBreadcrumbs` now also hides the drawn trail when off. +- Nav bridge: the snapshot carries `TrackBreadcrumbs` and `ShowRouteOverlay`. New commands + `setBreadcrumbs` and `setRouteOverlay` (with `On`) save the settings. +- Chat commands: + - `/ra navtrail on|off|toggle` (the existing `clear` and the status report still work; the + report now says whether tracking is on). + - New `/ra navoverlay [on|off]` (no argument toggles). + +### Compatibility +- An older RynthAi doesn't send the two flags, so both toggles show off; clicking them does + nothing until RynthAi is updated. + +## Versions +- RynthAi plugin: 0.5.9-legacy-ui (previous 0.5.8-legacy-ui). +- The next installer is 2026.10.5.9 (previous 2026.10.5.8). diff --git a/Changelog/2026-10-05-release-2026.10.5.10.md b/Changelog/2026-10-05-release-2026.10.5.10.md new file mode 100644 index 0000000..178a73f --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.10.md @@ -0,0 +1,25 @@ +# Release 2026.10.5.10 + +Date: 2026-10-05 +Previous release: 2026.10.5.9 +RynthAi plugin: 0.5.11-legacy-ui + +## Installer + +- File: `installer/Output/RynthCore-Setup-2026.10.5.10.exe` (130748020 bytes) +- SHA256: `F63859E43033581B9BC90CB92663F2B2BD9233C6E24E5893775E3DCF1BB4FAAD` +- Deploy zip: `installer/Output/RynthCore-2026.10.5.10-deploy.zip` + +## Included changes + +- ILT Guardian window, ported from UB-IT's Guardian tab: Temple / Attribute guardian riddle + translator (chat auto-detect and paste box), hand-in to the guardian with an optional vendor + buy for the Temple guardian, and the attribute turn-in tracker (/myquests, falling back to + /qb wait stamps). The last answer also shows on the Mini Remote with a Give button. + `/ra guardian ...`. +- Mini Remote slots can now be filled by dragging from AC's own inventory (empty slots) or from + a popped-out RynthCore Inventory. Clicking an item in the RynthCore Inventory selects it in the + game, the remote remembers the last selected pack item for 2 minutes, and the Inventory's + right-click menu has "Add to Mini Remote". + +See `2026-10-05-guardian-and-remote-slots.md` for details and known limits. diff --git a/Changelog/2026-10-05-release-2026.10.5.11.md b/Changelog/2026-10-05-release-2026.10.5.11.md new file mode 100644 index 0000000..06f0c0a --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.11.md @@ -0,0 +1,30 @@ +# Release 2026.10.5.11 + +Date: 2026-10-05 +Previous release: 2026.10.5.10 (saved in `installer/previous-release/`) +RynthAi plugin: 0.5.13-legacy-ui + +## Installer + +- File: `installer/Output/RynthCore-Setup-2026.10.5.11.exe` (130761857 bytes) +- SHA256: `9BE7F21A15C0D175F5F00C252EEA7BF4CAADAF798676EA96B3673E47267C424E` +- Deploy zip: `installer/Output/RynthCore-2026.10.5.11-deploy.zip` + +## Included changes + +- **Mini Remote: drags from AC's own inventory use the dragged item.** The engine hooks AC's + drag start (`UIElementManager::StartDragandDrop`) instead of reading the selection, which AC + leaves on the last clicked item. These drags can now go on any slot, including assigned ones. + See `2026-10-05-native-drag-real-item.md`. +- **ILT Guardian hand-in finds the vendor and the item.** Vendors are recognised by the weenie + vendor flag (nothing was ever classed Vendor, so the nearby vendor was never found), and the + hand-in item is looked up in a live walk of your packs (a fresh purchase was missed). + See `2026-10-05-guardian-vendor-and-item-lookup.md`. + +## What to check in game + +- Engine log at startup: `Compat: drag-start hook ready`. +- Drag an item from the game inventory onto a Mini Remote slot; the log shows + `DragDropHooks: AC drag start item=0x...` with that item's id. +- Temple guardian answer with the item not carried: the IltHub log shows + `[IltGuardian] vendor for '<item>': <vendor>`, then the buy and the give. diff --git a/Changelog/2026-10-05-release-2026.10.5.2.md b/Changelog/2026-10-05-release-2026.10.5.2.md new file mode 100644 index 0000000..11d4ead --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.2.md @@ -0,0 +1,33 @@ +# Release 2026.10.5.2: first build on the aelrynth 2026.10.5.1 merge + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.2.exe` (previous release: 2026.10.4.22) +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `merge/aelrynth-2026.10.5.1` (532fa67) + +## Summary + +The first installer built from the merge of upstream aelrynth 2026.10.5.1 with SK-local. +The version sorts above upstream's 2026.10.5.1, so the launcher's updater sees it as newer. +This is a test build of the merge: it has not been tested in game yet. + +## What's in it + +- **Engine:** upstream's unloadable CoreCLR engine, hosted by the native loader, with an + app-local .NET 10 runtime in `Runtime\dotnet`. This is the installer's new default; + the previous NativeAOT engine is still available via `Build-Installer.ps1 -NativeAot`. +- **Plugin API v77:** the RynthAi in this installer is built against it. Do not use an + older SK-local RynthAi (0.6.32 or earlier) with this engine. It reads the + merge-stack-result entry from a slot that upstream now uses for something else. +- **RynthAi:** the upstream plugin with the SK-local features wired on (ILT Hub, HUDs, + translation, item info, ground loot, nav overlay). It reports `0.5.1-legacy-ui`. +- **Upstream features and SK-local ports:** see + `2026-10-05-aelrynth-2026.10.5.1-merge.md` for the full list. +- **Decal bridge:** not included in this build (Decal 3.0 is not installed on the build + machine). "Decal + RynthCore" accounts can't run from this installer. + +## Known gaps + +- Several new upstream paths are hard-coded to `C:\Games\...`. Installs in other folders + may log or save to the wrong place. +- The ImGui Items view has no Shields section yet; the Avalonia Items panel has one. +- RynthAi's 0.6.33 augmentation clamp fix is still stashed on SK-local and is not in this build. diff --git a/Changelog/2026-10-05-release-2026.10.5.3.md b/Changelog/2026-10-05-release-2026.10.5.3.md new file mode 100644 index 0000000..8de883a --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.3.md @@ -0,0 +1,30 @@ +# Release 2026.10.5.3: ILT Hub windows, Char/Hub buttons, logging warning + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.3.exe` (previous release: 2026.10.5.2) +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `merge/aelrynth-2026.10.5.1` (532fa67, unchanged) + +## Summary + +A second test build of the aelrynth 2026.10.5.1 merge, fixing what 2026.10.5.2 got wrong in game. +Details: `2026-10-05-ilt-hub-context-char-hub-logging.md`. + +## Fixes + +- **ILT Hub and RynthAi's other ImGui windows** (Mini Remote, Inventory HUDs, Item Info, + translator, nav overlay) draw again. Plugins now get the engine's ImGui context when plugin + overlay windows are enabled. **UbRythai** starts again too; it refuses to start without that context. +- **Char and Hub buttons** are back on the in-game RynthAi dashboard (the ImGui one): + - Char opens the ILT Hub. + - Hub: left-click toggles the Mini Remote; right-click opens the Inventory HUDs setup. +- **Logging:** + - The engine's startup banner is always written. + - A warning names any log category set above the global LoggingLevel; those categories + are not logged at all. + +## Still open + +- No Decal bridge in this build (Decal 3.0 is not installed on the build machine). +- Several new upstream paths are hard-coded to `C:\Games\...`. +- The ImGui Items view has no Shields section yet. +- RynthAi's 0.6.33 augmentation clamp fix is still stashed on SK-local. diff --git a/Changelog/2026-10-05-release-2026.10.5.4.md b/Changelog/2026-10-05-release-2026.10.5.4.md new file mode 100644 index 0000000..4e057a0 --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.4.md @@ -0,0 +1,29 @@ +# Release 2026.10.5.4: Char/Hub buttons open their windows + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.4.exe` (previous release: 2026.10.5.3) +**SHA-256:** `0546B00D544DF8C97899C62F47FB96EF4655CD0E9662A9E43CE43C962E98F494` +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands` (8a25c5f, on top of 532fa67) +**Engine:** CoreCLR (app-local runtime) + +## Summary + +A third test build of the aelrynth 2026.10.5.1 merge. Details: +`2026-10-05-rynthai-launcher-remote-commands.md`. + +## Fixes + +- **Char / Hub dashboard buttons** open their windows. 2026.10.5.3 showed the buttons, but RynthAi + threw away the commands they send. The aelrynth merge had dropped `hub` / `huds` / `remote` from + RynthAi's remote-command switch. + - Char opens the ILT Hub (`/ra hub show`). + - Hub: left-click toggles the Mini Remote (`/ra remote toggle`); right-click opens Inventory HUDs (`/ra huds show`). +- RynthAi logs an unknown remote command as `ignored`, not `applied`. +- RynthAi plugin version is 0.5.2-legacy-ui (previous: 0.5.1-legacy-ui). + +## Still open + +- No Decal bridge in this build (Decal 3.0 is not installed on the build machine). +- Several new upstream paths are hard-coded to `C:\Games\...`. +- The ImGui Items view has no Shields section yet. +- RynthAi's 0.6.33 augmentation clamp fix is still stashed on SK-local. diff --git a/Changelog/2026-10-05-release-2026.10.5.5.md b/Changelog/2026-10-05-release-2026.10.5.5.md new file mode 100644 index 0000000..09409ff --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.5.md @@ -0,0 +1,39 @@ +# Release 2026.10.5.5: ImGui draws over Avalonia, Char panel rework, inventory to item count HUD + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.5.exe` (previous release: 2026.10.5.4) +**SHA-256:** `5343A879A06C308094E840C49E14B2F86A4D5E8111E9FE150FE06B7ED4CD09C5` +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (69cfe75); RynthSuite `fix/rynthai-launcher-remote-commands` (52f8f95) +**Engine:** CoreCLR (app-local runtime) +**RynthAi:** 0.5.4-legacy-ui + +## Summary + +The fourth test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game. + +## Fixes + +- **ImGui windows draw on top of Avalonia panels.** The ImGui frame is still built in + `EndScene`, but its draw data is now submitted after `OverlayTextureRenderer.Render`. Before + this, the ILT Hub and other ImGui windows could be hidden behind a docked Avalonia panel. Mouse + priority over ImGui windows (`Win32Backend.ImGuiOwnsMouseOverAvalonia`) survived the merge + unchanged. Details: `2026-10-05-imgui-over-avalonia-port.md`. + +## Features + +- **Inventory panel > right-click > "Add to item count HUD"** adds the item (by name) to the + floating item count HUD and shows it. Typed equivalent: `/ra itemhud add <name>`. Details: + `2026-10-05-inventory-add-to-item-count-hud.md`. +- **Char panel rework**. Details: `2026-10-05-char-panel-rework-progression-pets-quests.md`. + - The Skills panel has a Progression tab (ILT worlds) with: + - an exact XP planner; + - the Augmentation and Enlightenment planners. + - Pets has its own window (`/ra pets`). The Quests window (`/ra quests window`) now includes + Quest bonus. + - ILT Hub tabs: Character (Session rates), Quests, Pet, Banking, Gear, Games. + - Char launcher right-click menu: ILT Hub, Pets window, Quests window, Progression. + +## Build notes + +- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge; + and CS0618 in `EntryPoint.cs`. diff --git a/Changelog/2026-10-05-release-2026.10.5.6.md b/Changelog/2026-10-05-release-2026.10.5.6.md new file mode 100644 index 0000000..b6d4dee --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.6.md @@ -0,0 +1,29 @@ +# Release 2026.10.5.6: Floating windows open where they can be seen + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.6.exe` (previous release: 2026.10.5.5) +**SHA-256:** `B4F4410EBC67AAD91CE8FCEAD402CAA046446A3C28501921A350B1E3CCDA77FE` +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (3f06ed3); RynthSuite `fix/rynthai-launcher-remote-commands` (871c5d9) +**Engine:** CoreCLR (app-local runtime) +**RynthAi:** 0.5.5-legacy-ui + +## Summary + +The fifth test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game. +Details: `2026-10-05-floating-window-placement.md`. + +## Fixes + +- **Plugin windows open near the middle the first time.** This covers Pets, the popped-out Quests + window, the Item HUD, the Mini Remote and the ILT Hub. Before, they opened in the top-left corner, + hidden under popped-out panels. +- **Off-screen check.** Each time one of those windows is shown, it moves to the middle if less than + 40 px of it is on screen. The ILT Hub's rescue now uses the middle instead of (40,40). +- **Dungeon Map** opens centred when nothing is saved for it. +- **Engine panels open clear of popped-out windows.** A docked panel that would be more than half + hidden opens at the nearest clearer spot. The move is saved and logged by `ImGuiPanelHost`. + +## Build notes + +- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge; + and CS0618 in `EntryPoint.cs`. diff --git a/Changelog/2026-10-05-release-2026.10.5.7.md b/Changelog/2026-10-05-release-2026.10.5.7.md new file mode 100644 index 0000000..80dc4e7 --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.7.md @@ -0,0 +1,29 @@ +# Release 2026.10.5.7: RynthAi windows appear again + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.7.exe` (previous release: 2026.10.5.6) +**SHA-256:** `14CD10DAC7F7245528C7BE94A35395A21FA6EDD5679B5EA3A51FA23EB28D4BED` +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (b63b9fe); RynthSuite `fix/rynthai-launcher-remote-commands` (3ddd7ea) +**Engine:** CoreCLR (app-local runtime) +**RynthAi:** 0.5.7-legacy-ui + +## Summary + +The sixth test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game. +Details: `2026-10-05-rynthai-cimgui-binding.md`. + +## Fixes + +- **RynthAi's own windows draw again.** This covers the Mini Remote, Pets, Quests, ILT Hub, Item HUD + and Inventory HUDs. + - Cause: since the merge, the engine loads `RynthCore.cimgui.dll`, so RynthAi's ImGui calls went to + a second `cimgui.dll` that the engine never draws. + - Fix: RynthAi now binds to the engine's module, as ub-Rythai does. The RynthAi UI log should show + `[ImGui] cimgui bound to loaded RynthCore.cimgui.dll`. +- **Two clients no longer overwrite each other's RynthAi logs.** The second client writes + `{name}.{pid}.txt` beside the first client's file. + +## Build notes + +- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge; + and CS0618 in `EntryPoint.cs`. diff --git a/Changelog/2026-10-05-release-2026.10.5.8.md b/Changelog/2026-10-05-release-2026.10.5.8.md new file mode 100644 index 0000000..3c1a42f --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.8.md @@ -0,0 +1,35 @@ +# Release 2026.10.5.8: the Mini Remote is the ILT Hub + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.8.exe` (previous release: 2026.10.5.7) +**SHA-256:** `DBB04B9A5FF1B8DC986B4C50421E42814F64DF072BFB805634ECE0F2BBD5A784` +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (9408852); RynthSuite `fix/rynthai-launcher-remote-commands` (4d700e3) +**Engine:** CoreCLR (app-local runtime) +**RynthAi:** 0.5.8-legacy-ui + +## Summary + +The seventh test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game. +Details: `2026-10-05-mini-remote-is-ilt-hub.md`. + +## Changes + +- **The tabbed ILT Hub window is gone; the Mini Remote is the Hub** (UtilityBelt style). + - The new **V/H** button switches between stacked sections and three columns. + - The new **Options** button (or right-click) opens the Hub's windows: Character, Quests, Pets, + Banking, Gear and Games. Each is its own window. +- `/ra hub` and the dashboard's **Char** button now open the Mini Remote. + - New command: `/ra hub open <section>`. + - Char's right-click menu lists the section windows. +- Bank auto-refresh and the gear scans now run while the Mini Remote or any Hub window is open. + +## Not yet ported from UtilityBelt's Mini Remote + +- Storm and Reset Storm, the Guardian textbox, and the Fellow toggle. +- The LumS, KillL, PassL and Conv rate lines. +- The loot-profile and character-profile pickers. + +## Build notes + +- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge; + CS0618 in `EntryPoint.cs`; and the existing nullable warnings. diff --git a/Changelog/2026-10-05-release-2026.10.5.9.md b/Changelog/2026-10-05-release-2026.10.5.9.md new file mode 100644 index 0000000..e38a982 --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.9.md @@ -0,0 +1,21 @@ +# Release 2026.10.5.9 + +Date: 2026-10-05 +Previous release: 2026.10.5.8 +RynthAi plugin: 0.5.10-legacy-ui + +## Installer + +- File: `installer/Output/RynthCore-Setup-2026.10.5.9.exe` (130756527 bytes) +- SHA256: `E59D61BF61DE7089D56731F40273661FEF9DF1CEA548759C333DF1077CE138E9` +- Deploy zip: `installer/Output/RynthCore-2026.10.5.9-deploy.zip` + +## Included changes + +- Settings > Charms Tracking tab: every ACECustom registry charm with acquired (Carried / Stored / + Not yet), ON/OFF status, tier and server state. See `2026-10-05-charms-tracking-tab.md`. + The charm list was checked against ACECustom: all 13 charms, including the Infinite Casting Stone + and Universal Summoning Mastery, are present with every tier WCID. +- Nav: Breadcrumbs on/off and Route overlay on/off toggles (Nav panel, `/ra navtrail on|off`, + `/ra navoverlay on|off`). See `2026-10-05-nav-breadcrumbs-route-overlay-toggles.md`. +- Pets: an Infinite Casting Stone switched OFF no longer counts as casting supplies. \ No newline at end of file diff --git a/Changelog/2026-10-05-rynthai-cimgui-binding.md b/Changelog/2026-10-05-rynthai-cimgui-binding.md new file mode 100644 index 0000000..65c0a30 --- /dev/null +++ b/Changelog/2026-10-05-rynthai-cimgui-binding.md @@ -0,0 +1,52 @@ +# RynthAi overlay windows draw again: bind to the engine's cimgui (RynthAi 0.5.6-legacy-ui) + +Date: 2026-10-05 +Branches (local): RynthSuite `fix/rynthai-launcher-remote-commands` +Previous plugin version: 0.5.5-legacy-ui + +## Problem + +Since the aelrynth merge, none of RynthAi's own ImGui windows appear. That covers the ILT Hub, the +Pets and Quests windows, the Mini Remote, the Item HUD and the Inventory HUDs setup. The launcher +buttons and `/ra` commands reach the plugin (`applied remote command: remote=toggle` / +`pets=toggle`), but nothing shows. + +## Cause + +The engine now loads its ImGui build as `RynthCore.cimgui.dll` (log: `ImGuiNative: Loading +...\Runtime\RynthCore.cimgui.dll`). + +RynthAi is NativeAOT. Its ImGui.NET P/Invokes ask for `cimgui`, which no loaded module is named. +Windows therefore loaded a second, different `cimgui.dll` from the install's `Runtime` folder. RynthAi +set that module's context pointer to the engine's context and built its windows through a separate +ImGui instance, so they never reached the engine's draw data. The engine heartbeat shows this: the +plugin's overlay call runs every frame (`overlayCalls` = frames), but `drawLists=3` doesn't change +after `/ra hub show` or `/ra remote toggle`. + +ub-Rythai already avoids this with a DllImport resolver bound to the engine's module (log: +`ub-Rythai: ImGui native resolver bound to engine cimgui.`). RynthAi had no such resolver. + +## Fix + +- New `ImGuiNativeBinding`, called at the top of `RynthAiPlugin.Initialize` before any ImGui call. It + registers `NativeLibrary.SetDllImportResolver` for the ImGui.NET assembly. + - `cimgui` resolves to the loaded `RynthCore.cimgui.dll`, else a loaded `cimgui.dll`, else the + default search (the old behaviour). + - It's registered once per process, so a reused plugin DLL copy doesn't throw. + - Logged in the UI log as `[ImGui] native resolver registered ...` and, on the first ImGui call, + `[ImGui] cimgui bound to loaded RynthCore.cimgui.dll (0x...)`. +- No changes to the windows themselves. The Mini Remote looks as it did before the merge: stats, + ResetXP / Report, item buttons, toggles, profile pickers, Guardian, Translate, Chat XL and Rebuff. + +## Two clients no longer overwrite each other's RynthAi logs (RynthAi 0.5.7-legacy-ui) + +- Before: with two clients running, RynthAi's shared log files (`Logs\Diagnostics\rynthai_*.txt`, + `exceptions_*.txt`, `Trace\*.txt`) lost and garbled lines. Each process opened the file in Append + mode once with `FileShare.ReadWrite`, kept a buffered writer, and wrote at its own end-of-file + offset, overwriting the other client's lines. +- Now each file has one writing process. `RynthLog.OpenWriter` opens it with `FileShare.Read`, so + readers are fine but a second writer is refused. When another client already holds the file, this + process writes `{name}.{pid}.txt` beside it, e.g. `rynthai_2026-10-05.30060.txt`. The engine's own + logs (`RynthCore.{pid}.log`) are per process the same way. +- Retention and pruning are unchanged. The per-process files are `*.txt` in the same folders, so + they age out with the rest. diff --git a/Changelog/2026-10-05-rynthai-launcher-remote-commands.md b/Changelog/2026-10-05-rynthai-launcher-remote-commands.md new file mode 100644 index 0000000..1f22d41 --- /dev/null +++ b/Changelog/2026-10-05-rynthai-launcher-remote-commands.md @@ -0,0 +1,44 @@ +# RynthAi 0.5.2-legacy-ui: Char / Hub launchers open their windows again + +Date: 2026-10-05 +Branch: RynthSuite `fix/rynthai-launcher-remote-commands` (local, based on `merge/aelrynth-2026.10.5.1` @ 532fa67) +Previous plugin version: 0.5.1-legacy-ui + +## Problem + +On 2026.10.5.3 the dashboard's **Char** and **Hub** launcher buttons showed, but clicking them did +nothing: no ILT Hub, no Mini Remote, no Inventory HUDs window. + +The engine log showed every click arriving at RynthAi +(`[RynthAi] applied remote command: hub=show`, `remote=toggle`, `huds=show`), and the overlay was +drawing (`OnRenderOverlay drawing (iltHub=ready)`). The ILT Hub diagnostics had no +`command: /ra hub ...` line for any click. + +## Cause + +The launchers send remote commands through the engine broker into `RynthAiPlugin.ApplyRemoteCommand`. +The aelrynth 2026.10.5.1 version of that switch has no `hub` / `quests` / `huds` / `itemhud` / +`remote` / `miniremote` cases. SK-local had them, and the merge dropped them. The commands fell +through the switch untouched, and the trailing log line still reported them as "applied". + +Typed `/ra hub ...` commands use a separate dispatcher (`DispatchRaCommand`) that still had the cases. +That is why `/ra hub status`, `force on` and `refresh` worked, but no button did. + +## Fix + +- `ApplyRemoteCommand` routes `hub` / `quests` to `IltHubController.HandleCommand`, and routes + `huds` / `itemhud` / `remote` / `miniremote` to `HandleHudCommand`. These are the same handlers as + the typed commands, and both run on the pump thread. +- Unknown remote commands log `ignored unknown remote command: ...` instead of falsely logging + "applied". +- `map` / `lua` were not restored. Upstream's engine owns those windows now. + +## Typed equivalents + +- `/ra hub show`: ILT Hub (the Char button) +- `/ra remote toggle`: Mini Remote (Hub button, left-click) +- `/ra huds show`: Inventory HUDs setup (Hub button, right-click) + +## Not yet shipped + +Built locally; not in an installer yet (next would be 2026.10.5.4). Nothing pushed. diff --git a/README.md b/README.md index b126ccc..198e226 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ RynthCore is a modern .NET 10 modding host for Asheron's Call. It combines an x86 NativeAOT in-process engine, a hot-reload-capable loader, an injector, an Avalonia desktop launcher, and a plugin surface that replaces the legacy Decal + UBService + VTank stack with a self-contained RynthCore-native API. -The plugin code (RynthAi etc.) lives in a sibling repository: [RynthSuite](https://aelrynth.com/rynth.html) (`git clone https://aelrynth.com/git/RynthSuite.git`). +The plugin code (RynthAi etc.) lives in a sibling repository: [RynthSuite](https://aelrynth.com/git/rynth/RynthSuite). ## What it does @@ -86,7 +86,7 @@ For full deploy details, the Inno Setup installer, and gotchas, see [`BUILD.md`] ## Repository notes - Local settings, machine-specific files, generated `bin/`, `obj/`, `.vs/`, `.dotnet-home/` content, and launcher data (profiles, runtime state) are kept out of source control via `.gitignore` -- Plugin code lives in the [RynthSuite](https://aelrynth.com/rynth.html) repo as a sibling clone (`git clone https://aelrynth.com/git/RynthSuite.git`) +- Plugin code lives in the [RynthSuite](https://aelrynth.com/git/rynth/RynthSuite) repo as a sibling clone ## Security and secrets diff --git a/RynthCore.sln b/RynthCore.sln index 70c5781..e450961 100644 --- a/RynthCore.sln +++ b/RynthCore.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 @@ -29,6 +29,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.Core EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.UI", "tools\HookResolver.UI\RynthCore.HookResolver.UI.csproj", "{C1A2B3D4-0009-0009-0009-000000000009}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.DecalBridge", "src\RynthCore.DecalBridge\RynthCore.DecalBridge.csproj", "{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x86 = Debug|x86 @@ -135,6 +137,18 @@ Global {C1A2B3D4-0007-0007-0007-000000000007}.Release|Any CPU.Build.0 = Release|Any CPU {C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.ActiveCfg = Release|Any CPU {C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.Build.0 = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.ActiveCfg = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.Build.0 = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.ActiveCfg = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.Build.0 = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.ActiveCfg = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.Build.0 = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.Build.0 = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.ActiveCfg = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.Build.0 = Release|Any CPU {C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.ActiveCfg = Debug|Any CPU {C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.Build.0 = Debug|Any CPU {C1A2B3D4-0008-0008-0008-000000000008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -159,18 +173,18 @@ Global {C1A2B3D4-0009-0009-0009-000000000009}.Release|Any CPU.Build.0 = Release|Any CPU {C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.ActiveCfg = Release|Any CPU {C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.Build.0 = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.ActiveCfg = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.Build.0 = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.ActiveCfg = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.Build.0 = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.ActiveCfg = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.Build.0 = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.Build.0 = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.ActiveCfg = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.Build.0 = Release|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x86.ActiveCfg = Debug|x86 + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x86.Build.0 = Debug|x86 + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x64.ActiveCfg = Debug|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x64.Build.0 = Debug|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x86.ActiveCfg = Release|x86 + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x86.Build.0 = Release|x86 + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|Any CPU.Build.0 = Release|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x64.ActiveCfg = Release|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -183,5 +197,6 @@ Global {C1A2B3D4-0007-0007-0007-000000000007} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {C1A2B3D4-0008-0008-0008-000000000008} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89} {C1A2B3D4-0009-0009-0009-000000000009} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89} + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} EndGlobalSection EndGlobal diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md new file mode 100644 index 0000000..0c72283 --- /dev/null +++ b/THIRD-PARTY-NOTICES.md @@ -0,0 +1,34 @@ +# Third-party notices + +RynthCore ships the following third-party material inside its own files. + +## Phosphor Icons + +- What: the Phosphor icon font (`Phosphor.ttf`, version 2.1, regular weight), used for the icons in the ImGui panels. +- Where: `src/RynthCore.Engine/Assets/Fonts/Phosphor.ttf`, embedded in `RynthCore.Engine.dll` as a resource. +- Source: https://phosphoricons.com (Tobias Fried and Helena Zhang) +- Licence: MIT, reproduced below and in `src/RynthCore.Engine/Assets/Fonts/Phosphor.LICENSE`. + +``` +MIT License + +Copyright (c) 2020-2021 Phosphor Icons + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/installer/Build-Installer.ps1 b/installer/Build-Installer.ps1 index 4f2d62b..53f9912 100644 --- a/installer/Build-Installer.ps1 +++ b/installer/Build-Installer.ps1 @@ -7,16 +7,20 @@ .DESCRIPTION 0. Makes sure a .NET 10 SDK is available; installs one per-user when missing (see -NoDotNetInstall) 1. Publishes the Avalonia launcher (self-contained, x86) - 2. Publishes RynthCore.Engine (NativeAOT, x86 -- ~2 min) - 3. Publishes RynthCore.Loader (NativeAOT, x86) -- the DLL the launcher injects + 2+3. The engine and the loader (the DLL the launcher injects). By default the unloadable + engine (docs/UNLOADABLE_ENGINE_PLAN.md): scripts\Publish-EngineCoreClr.ps1 stages the + native loader (native\Loader), RynthCore.Shim, the CoreCLR engine (ReadyToRun) and the + app-local .NET runtime (Runtime\dotnet) into staging\core\Runtime; needs Visual Studio's + C++ tools. -NativeAot publishes the NativeAOT engine + loader instead (~2 min). 4. Publishes RynthCore.Plugin.RynthAi (NativeAOT, x86) from RynthSuite 5. Publishes the Loot Editor (self-contained, x86) 6. Publishes the Monster Editor (self-contained, x86) from RynthSuite 7. Publishes the experimental plugins (RynthChat, RynthJuice, RynthNav, RynthTracker, RynthVision, UbRythai; NativeAOT, x86) -- optional components in the installer 8. Stages RynthCore under installer\staging\core\ and RynthSuite under - installer\staging\suite\, plus the hand-built RynthCore.SehTrampoline.dll, - and checks every required runtime file is there + installer\staging\suite\, plus the hand-built RynthCore.SehTrampoline.dll and the + Decal bridge (staging\core\DecalBridge, built against Decal's reference assemblies when + Decal is installed), and checks every required runtime file is there 9. Archives the previous installer (installer\previous-release\) when -Version changes 10. Invokes ISCC.exe to produce installer\Output\RynthCore-Setup-<version>.exe (and a RynthCore-Setup.exe copy) @@ -59,6 +63,18 @@ .PARAMETER NoPackage With -Version, stop after the installer .exe (skip the Release-<version> package and zip). +.PARAMETER NativeAot + Build the NativeAOT engine + loader instead of the default unloadable CoreCLR engine. + +.PARAMETER SkipDecalBridge + Leave the Decal bridge out even when Decal is installed. + +.PARAMETER IncludeDecalBridge + Require the Decal bridge: a missing Decal install fails the build instead of skipping it. + +.PARAMETER DecalDir + Decal's install folder, when not the default C:\Program Files (x86)\Decal 3.0. + .EXAMPLE .\Build-Installer.ps1 -Version 2026.10.4.7 #> @@ -74,7 +90,19 @@ param( [switch]$SkipBuild, [switch]$NoDotNetInstall, [switch]$AllowDirty, - [switch]$NoPackage + [switch]$NoPackage, + # The old NativeAOT engine + loader (a hot reload leaks every engine generation). + [switch]$NativeAot, + # The Decal bridge (src\RynthCore.DecalBridge, docs/DECAL_BRIDGE_PLAN.md) is staged into + # {app}\DecalBridge when Decal is installed (experimental, opt-in per account; nothing + # registers it unless the player picks "Decal + RynthCore"). Building it needs Decal's + # public reference assemblies; without Decal it is skipped with a warning. + # -SkipDecalBridge leaves it out even when Decal is present. + [switch]$SkipDecalBridge, + # Makes the bridge mandatory: no Decal means a failed build rather than a skipped bridge. + [switch]$IncludeDecalBridge, + # Decal's install folder, when not the default C:\Program Files (x86)\Decal 3.0. + [string]$DecalDir = "" ) $ErrorActionPreference = "Stop" @@ -225,7 +253,9 @@ $CoreStaging = "$StagingRoot\core" $SuiteStaging = "$StagingRoot\suite" # ── Validate projects ─────────────────────────────────────────────────────── -$allProjects = @($LauncherProject, $EngineProject, $LoaderProject, $PluginProject, $LootEditorProject, $MonsterEditorProject) + +# The managed loader project is only built for -NativeAot; the default uses the native C loader. +$allProjects = @($LauncherProject, $EngineProject, $PluginProject, $LootEditorProject, $MonsterEditorProject) + + @(if ($NativeAot) { $LoaderProject }) + @($ExperimentalPlugins | ForEach-Object { Get-ExperimentalProject $_ }) foreach ($p in $allProjects) { if (-not (Test-Path $p)) { @@ -240,17 +270,20 @@ if (-not $SkipBuild) { dotnet publish $LauncherProject -c $Configuration -r win-x86 --self-contained true @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Launcher publish failed (exit $LASTEXITCODE)" } - # ── 2. Engine (NativeAOT — the slow one) ────────────────────────────────── - Write-Host "" - Write-Host "[2/7] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan - dotnet publish $EngineProject -c $Configuration @VersionArgs - if ($LASTEXITCODE -ne 0) { throw "Engine publish failed (exit $LASTEXITCODE)" } + if ($NativeAot) { + # ── 2. Engine (NativeAOT — the slow one) ────────────────────────────── + Write-Host "" + Write-Host "[2/7] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan + dotnet publish $EngineProject -c $Configuration @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "Engine publish failed (exit $LASTEXITCODE)" } - # ── 3. Loader (NativeAOT, small) ────────────────────────────────────────── - Write-Host "" - Write-Host "[3/7] Publishing Loader (NativeAOT)..." -ForegroundColor Cyan - dotnet publish $LoaderProject -c $Configuration @VersionArgs - if ($LASTEXITCODE -ne 0) { throw "Loader publish failed (exit $LASTEXITCODE)" } + # ── 3. Loader (NativeAOT, small) ────────────────────────────────────── + Write-Host "" + Write-Host "[3/7] Publishing Loader (NativeAOT)..." -ForegroundColor Cyan + dotnet publish $LoaderProject -c $Configuration @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "Loader publish failed (exit $LASTEXITCODE)" } + } + # (Default: the CoreCLR engine and native loader are built straight into staging below.) # ── 4. RynthAi plugin (NativeAOT; keeps its own version) ───────────────── Write-Host "" @@ -315,18 +348,30 @@ foreach ($file in (Get-ChildItem "$LauncherPublish" -File)) { Copy-Item $file.FullName "$CoreStaging\$destName" -Force } -# Engine runtime files (into Runtime\, skip .pdb) -foreach ($file in (Get-ChildItem "$EnginePublish" -File)) { - if ($file.Extension -eq '.pdb') { continue } - Copy-Item $file.FullName "$CoreStaging\Runtime\$($file.Name)" -Force -} +if ($NativeAot) { + # Engine runtime files (into Runtime\, skip .pdb) + foreach ($file in (Get-ChildItem "$EnginePublish" -File)) { + if ($file.Extension -eq '.pdb') { continue } + Copy-Item $file.FullName "$CoreStaging\Runtime\$($file.Name)" -Force + } -# Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it -# maps RynthCore.Engine.dll and provides hot-reload. Without it a fresh install's -# launcher can't auto-find an engine to inject. -$loaderDll = "$LoaderPublish\RynthCore.Loader.dll" -if (-not (Test-Path $loaderDll)) { throw "Loader DLL not found at: $loaderDll" } -Copy-Item $loaderDll "$CoreStaging\Runtime\" -Force + # Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it + # maps RynthCore.Engine.dll and provides hot-reload. Without it a fresh install's + # launcher can't auto-find an engine to inject. + $loaderDll = "$LoaderPublish\RynthCore.Loader.dll" + if (-not (Test-Path $loaderDll)) { throw "Loader DLL not found at: $loaderDll" } + Copy-Item $loaderDll "$CoreStaging\Runtime\" -Force +} else { + # The unloadable engine: native loader (same RynthCoreInit contract with the launcher's + # injector), RynthCore.Shim, the CoreCLR engine (ReadyToRun) + its dependencies, and + # Runtime\dotnet (the app-local x86 .NET runtime). Needs Visual Studio's C++ tools (cl.exe) + # for the loader, like the SEH trampoline. + Write-Host "" + Write-Host "[2+3/7] Building the unloadable engine + native loader into staging..." -ForegroundColor Cyan + & "$RepoRoot\scripts\Publish-EngineCoreClr.ps1" -Target "$CoreStaging\Runtime" -Configuration $Configuration -MsBuildArgs $VersionArgs + # Keep the engine's pdb (its stack traces get line numbers); drop the loader's and shim's. + Remove-Item "$CoreStaging\Runtime\RynthCore.Loader.pdb", "$CoreStaging\Runtime\RynthCore.Shim.pdb" -Force -ErrorAction SilentlyContinue +} # SEH trampoline — hand-built native DLL (native\SehTrampoline\Build-SehTrampoline.ps1), # NOT part of the engine publish output. Without it SehTrampoline.IsAvailable stays @@ -353,8 +398,8 @@ if ((Test-Path $sehSrc) -and (Get-SehSourceTime) -gt (Get-Item $sehDll).LastWrit } Copy-Item $sehDll "$CoreStaging\Runtime\" -Force -# Engine Native subfolder -if (Test-Path "$EnginePublish\Native") { +# Engine Native subfolder (NativeAOT layout) +if ($NativeAot -and (Test-Path "$EnginePublish\Native")) { foreach ($file in (Get-ChildItem "$EnginePublish\Native" -File)) { if ($file.Extension -eq '.pdb') { continue } Copy-Item $file.FullName "$CoreStaging\Runtime\Native\$($file.Name)" -Force @@ -387,6 +432,44 @@ if (-not (Test-Path $NavPortalsTsv)) { throw "RynthNav portals.tsv not found at: New-Item -ItemType Directory -Path "$StagingRoot\navdata" -Force | Out-Null Copy-Item $NavPortalsTsv "$StagingRoot\navdata\" -Force +# Decal bridge (docs/DECAL_BRIDGE_PLAN.md, experimental): the net48 x86 Decal network filter +# goes to {app}\DecalBridge\, the folder the launcher registers for "Decal + RynthCore" +# accounts (and only for those). Built against Decal's public reference assemblies, so the +# build machine needs Decal; -p:RequireDecal=true turns "no Decal" into a build error rather +# than the empty assembly a plain solution build makes. Never ships any Decal file. +# Same probe as the bridge csproj (DecalAvailable): Decal.Adapter.dll in the Decal folder. +$decalProbeDir = if ($DecalDir) { $DecalDir } else { "${env:ProgramFiles(x86)}\Decal 3.0" } +$decalInstalled = Test-Path (Join-Path $decalProbeDir "Decal.Adapter.dll") +$buildDecalBridge = -not $SkipDecalBridge -and ($decalInstalled -or $IncludeDecalBridge) +if ($SkipDecalBridge) { + Write-Warning "-SkipDecalBridge: this build has no Decal bridge; 'Decal + RynthCore' accounts can't launch with it." +} elseif (-not $buildDecalBridge) { + Write-Warning "Decal not found in '$decalProbeDir': this build has no Decal bridge; 'Decal + RynthCore' accounts can't launch with it. (-DecalDir for another folder, -IncludeDecalBridge to make this an error.)" +} else { + Write-Host "" + Write-Host "Building the Decal bridge (net48 x86, against Decal's reference assemblies)..." -ForegroundColor Cyan + $bridgeProject = "$RepoRoot\src\RynthCore.DecalBridge\RynthCore.DecalBridge.csproj" + $bridgeDll = "$RepoRoot\src\RynthCore.DecalBridge\bin\$Configuration\RynthCore.DecalBridge.dll" + $decalArgs = @("-p:RequireDecal=true") + if ($DecalDir) { $decalArgs += "-p:DecalDir=$DecalDir" } + # A DLL left over from an earlier build must never be shipped in place of this one. + Remove-Item $bridgeDll -Force -ErrorAction SilentlyContinue + if (Test-Path $bridgeDll) { throw "Could not remove the old $bridgeDll (in use by a Decal client?)" } + dotnet build $bridgeProject -c $Configuration -nologo -v q @decalArgs @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "Decal bridge build failed (exit $LASTEXITCODE). Is Decal 3.0 installed? (-DecalDir for another folder, -SkipDecalBridge to leave it out)" } + if (-not (Test-Path $bridgeDll)) { throw "Decal bridge not built at $bridgeDll" } + # The real bridge has its filter type; the no-Decal build is an empty assembly. + $bridgeBytes = [System.IO.File]::ReadAllBytes($bridgeDll) + if ([System.Text.Encoding]::ASCII.GetString($bridgeBytes).IndexOf("BridgeFilter") -lt 0) { + throw "$bridgeDll has no BridgeFilter type - it was built without Decal's reference assemblies." + } + New-Item -ItemType Directory -Path "$CoreStaging\DecalBridge" -Force | Out-Null + Copy-Item $bridgeDll "$CoreStaging\DecalBridge\" -Force + $staleDecal = @(Get-ChildItem "$CoreStaging\DecalBridge" -File | Where-Object { $_.Name -ne "RynthCore.DecalBridge.dll" }) + if ($staleDecal.Count -gt 0) { throw "Unexpected files in the staged DecalBridge folder: $($staleDecal.Name -join ', ')" } + Write-Host " RynthCore.DecalBridge.dll $((Get-Item $bridgeDll).VersionInfo.FileVersion)" +} + # release.txt — which core release this install is ($release, from -Version at the top). Set-Content -Path "$CoreStaging\release.txt" -Value @($release, $Version) -Encoding ASCII @@ -407,6 +490,17 @@ $required = @( "$SuiteStaging\RynthAi\MonsterEditor\RynthCore.MonsterEditor.exe", "$StagingRoot\navdata\portals.tsv" ) + @($ExperimentalPlugins | ForEach-Object { "$SuiteStaging\$_\RynthCore.Plugin.$_.dll" }) +# The unloadable engine also needs its shim and the app-local CoreCLR runtime. +if (-not $NativeAot) { + $required += @( + "$CoreStaging\Runtime\RynthCore.Shim.dll", + "$CoreStaging\Runtime\dotnet\coreclr.dll", + "$CoreStaging\Runtime\dotnet\System.Private.CoreLib.dll" + ) +} +if ($buildDecalBridge) { + $required += "$CoreStaging\DecalBridge\RynthCore.DecalBridge.dll" +} $missing = @($required | Where-Object { -not (Test-Path $_) }) if ($missing.Count -gt 0) { throw "Staging is missing required files:`n $($missing -join "`n ")" } diff --git a/installer/Publish-Update.ps1 b/installer/Publish-Update.ps1 index 7be424b..a3f1e72 100644 --- a/installer/Publish-Update.ps1 +++ b/installer/Publish-Update.ps1 @@ -7,7 +7,8 @@ One command per release: 1. Refuses if the signing key isn't set up or isn't trusted by the launcher being shipped, if either repo has uncommitted changes, or if -Version isn't newer than the live feed. - 2. Builds the installer (Build-Installer.ps1 -Version) and the RynthSuite plugins into + 2. Builds the installer (Build-Installer.ps1 -Version; it includes the Decal bridge, so the + build machine needs Decal installed) and the RynthSuite plugins into installer\Releases\<release>\ — never into the live C:\Games folders. 3. Writes the manifest (sizes + SHA-256 of every file), signs it with the DPAPI key (Sign-Update.ps1, no prompt) and checks the signature the way the launcher will. @@ -37,7 +38,12 @@ param( [string]$BaseUrl = "https://aelrynth.com/downloads/rynth", [string]$KeyDir = (Join-Path $env:USERPROFILE ".rynthcore-update-signing"), [string]$RynthSuiteRoot = "", - [string]$TrustFile = "" # defaults to the launcher's UpdateTrust.cs; override for tests + [string]$TrustFile = "", # defaults to the launcher's UpdateTrust.cs; override for tests + # RynthNav's data shipped to launchers as the signed "navdata" archive: tiles (nav_XXXX.tile), + # portals.tsv and locations.json from this folder. Only re-uploaded when the set changes + # (its id is a hash of every file); otherwise the live feed's entry is carried over. + [string]$NavDataDir = "C:\Games\RynthCore\NavData", + [switch]$SkipNavData # leave navdata out of this feed (launchers then keep what they have) ) $ErrorActionPreference = "Stop" @@ -48,6 +54,7 @@ if (-not $TrustFile) { $TrustFile = Join-Path $RepoRoot "src\RynthCore.App.Avalo function Step($m) { Write-Host ""; Write-Host "== $m" -ForegroundColor Cyan } function Sha256([string]$path) { (Get-FileHash $path -Algorithm SHA256).Hash.ToLowerInvariant() } +function Sha256Text([string]$text) { [Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($text))).ToLowerInvariant() } # Same check as RynthUpdater.VerifyEnvelope: any trusted key's signature over the payload bytes. function Test-Envelope([string]$path, [string[]]$keys) { @@ -99,9 +106,11 @@ if (-not $AllowDirty) { Write-Host " RynthCore $(git -C $RepoRoot rev-parse --short HEAD), RynthSuite $(git -C $RynthSuiteRoot rev-parse --short HEAD)" } +$liveManifest = $null try { $live = Invoke-RestMethod "$BaseUrl/update.json" -TimeoutSec 20 - $liveRelease = ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($live.payload)) | ConvertFrom-Json).release + $liveManifest = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($live.payload)) | ConvertFrom-Json + $liveRelease = $liveManifest.release if ($release -le $liveRelease) { throw "Release $release is not newer than the live feed's $liveRelease — bump -Version." } Write-Host " live feed is at $liveRelease; publishing $release" } catch [Microsoft.PowerShell.Commands.HttpResponseException] { @@ -116,12 +125,20 @@ New-Item -ItemType Directory -Force "$rel\plugins", "$rel\build" | Out-Null Step "Building the installer ($Version)" & (Join-Path $ScriptDir "Build-Installer.ps1") -Version $Version -RynthSuiteRoot $RynthSuiteRoot if (-not $?) { throw "Build-Installer.ps1 failed" } +# The Decal bridge (experimental, opt-in per account) is only in installers built where Decal is +# installed; a launcher updating through this feed without it can't run "Decal + RynthCore" accounts. +$bridgeStaged = Join-Path $ScriptDir "staging\core\DecalBridge\RynthCore.DecalBridge.dll" +if (Test-Path $bridgeStaged) { + Write-Host " Decal bridge in the installer: $((Get-Item $bridgeStaged).VersionInfo.FileVersion)" +} else { + Write-Warning "This installer has no Decal bridge ($bridgeStaged missing); 'Decal + RynthCore' accounts won't work from it." +} # The versioned installer is the primary artifact (the RynthCore-Setup.exe copy is best effort). Copy-Item (Join-Path $ScriptDir "Output\RynthCore-Setup-$Version.exe") "$rel\RynthCore-Setup.exe" # Build-Installer.ps1 stages RynthSuite files under staging\suite\ (RynthAi -> staging\suite\RynthAi\). Copy-Item (Join-Path $ScriptDir "staging\suite\RynthAi\RynthCore.Plugin.RynthAi.dll") "$rel\plugins\" -$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision" +$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory" foreach ($name in $suitePlugins) { Step "Building $name" $proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj" @@ -136,11 +153,26 @@ $zipRoot = "$rel\build\zip" foreach ($name in $suitePlugins) { New-Item -ItemType Directory -Force "$zipRoot\RynthSuite\$name" | Out-Null Copy-Item "$rel\plugins\RynthCore.Plugin.$name.dll" "$zipRoot\RynthSuite\$name\" + # Third-party licence notices travel with the plugin (RynthOracle: Oracle of Dereth, MIT). + $notice = "$rel\build\$name\THIRD_PARTY_NOTICES.md" + if (Test-Path $notice) { Copy-Item $notice "$zipRoot\RynthSuite\$name\" } } -$navSrc = "C:\Games\RynthCore\NavData" +$navSrc = $NavDataDir New-Item -ItemType Directory -Force "$zipRoot\RynthCore\NavData" | Out-Null -Get-ChildItem $navSrc -File | Where-Object { $_.Extension -eq ".tile" -or $_.Name -eq "portals.tsv" } | +# The route planner's portals.tsv and the Atlas's locations.json (both made by +# tools\navdata\gen_locations.py from the world database), and the Town Network's townnet.json +# (tools\navdata\Build-TownNet.ps1: the world database plus the walks inside from the dats). +# Never the player's own files +# there (atlas.txt, recalls.txt, _player.txt). The tiles are no longer in this zip (the whole +# world is ~40,000 of them): the launcher installs them from the feed's navdata archive. +Get-ChildItem $navSrc -File | Where-Object { $_.Name -eq "portals.tsv" -or $_.Name -eq "locations.json" -or $_.Name -eq "townnet.json" } | Copy-Item -Destination "$zipRoot\RynthCore\NavData\" +if (-not (Test-Path "$navSrc\locations.json")) { + Write-Warning "NavData has no locations.json: RynthNav's Atlas ships empty. Run tools\navdata\gen_locations.py and copy its output there." +} +if (-not (Test-Path "$navSrc\townnet.json")) { + Write-Warning "NavData has no townnet.json: routes won't use the Town Network. Run tools\navdata\Build-TownNet.ps1 and copy its townnet.json there." +} @" RynthSuite plugins for RynthCore (Asheron's Call, retail client) - $Version @@ -149,28 +181,108 @@ Extract this zip into C:\Games - it creates: C:\Games\RynthSuite\RynthNav\ RynthNav plugin C:\Games\RynthSuite\RynthTracker\ RynthTracker plugin C:\Games\RynthSuite\RynthVision\ RynthVision plugin - C:\Games\RynthCore\NavData\ RynthNav's baked navmesh tiles + C:\Games\RynthSuite\RynthLua\ RynthLua plugin (Lua scripting; was part of RynthAi) + C:\Games\RynthSuite\RynthOracle\ RynthOracle plugin (quests, character, titles; based on Oracle of Dereth by Advis Eveldan) + C:\Games\RynthSuite\RynthInventory\ RynthInventory plugin (search every character's items) + C:\Games\RynthCore\NavData\ RynthNav's portals and Atlas Then, in the RynthCore launcher's Plugins tab, add the full path of each plugin DLL you want. Install RynthCore first (RynthCore-Setup.exe), which also installs RynthAi and the Loot Editor. After that the launcher keeps -the plugins up to date by itself. +the plugins up to date by itself, and once RynthNav is in the list it also +downloads RynthNav's navmesh tiles into C:\Games\RynthCore\NavData. MIT licensed. https://aelrynth.com/projects.html "@ -replace "`n", "`r`n" | Set-Content "$zipRoot\README.txt" -NoNewline Compress-Archive -Path "$zipRoot\*" -DestinationPath "$rel\RynthSuite-Plugins.zip" -CompressionLevel Optimal +# RynthNav's data for the launchers (RynthUpdater.NavData.cs): one archive, flat, only the file +# names RynthNav reads. Its id is a hash over every file's name and SHA-256, so an unchanged +# set reuses the live entry (and the archive already on the server) instead of re-uploading. +$navData = $null +$navZip = $null +if (-not $SkipNavData) { + Step "RynthNav data (tiles, route graph, portals, Atlas, Town Network) from $NavDataDir" + $navFiles = @(Get-ChildItem $NavDataDir -File | Where-Object { $_.Name -match '^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json)$' } | Sort-Object Name) + $tileCount = @($navFiles | Where-Object { $_.Extension -eq ".tile" }).Count + if ($tileCount -eq 0) { throw "$NavDataDir has no tiles. Pass -NavDataDir, or -SkipNavData to publish without them." } + # The long-range route graph (RynthNav.Baker --graph) must come from these very tiles: the + # plugin ignores a graph whose tiles don't match (long gotos then walk the straight line). + $graph = $navFiles | Where-Object { $_.Name -eq "navgraph.bin" } + $newestTile = ($navFiles | Where-Object { $_.Extension -eq ".tile" } | Measure-Object LastWriteTimeUtc -Maximum).Maximum + if (-not $graph) { Write-Warning "No navgraph.bin in ${NavDataDir}: long gotos will walk the straight line. Run: RynthNav.Baker --graph $NavDataDir" } + elseif ($graph.LastWriteTimeUtc -lt $newestTile) { Write-Warning "navgraph.bin is older than the newest tile: rebuild it (RynthNav.Baker --graph $NavDataDir), or RynthNav will ignore it." } + $idText = ($navFiles | ForEach-Object { "$($_.Name) $(Sha256 $_.FullName)" }) -join "`n" + $navId = (Sha256Text $idText).Substring(0, 32) + # [long]: Measure-Object's Sum is a double, which ConvertTo-Json writes as 1383002945.0, and the + # launcher reads "bytes" with GetInt64 - a ".0" failed every launcher's update check (2026.10.3.1/2). + $navBytes = [long](($navFiles | Measure-Object Length -Sum).Sum) + if ($liveManifest -and $liveManifest.navdata -and $liveManifest.navdata.id -eq $navId) { + $navData = $liveManifest.navdata + # Carried over from the live feed (ConvertFrom-Json): force the whole numbers back to integers. + $navData = [ordered]@{ + id = [string]$navData.id + release = [long]$navData.release + url = [string]$navData.url + size = [long]$navData.size + sha256 = [string]$navData.sha256 + files = [long]$navData.files + bytes = [long]$navData.bytes + } + Write-Host " unchanged ($($navFiles.Count) files, id $navId): the live archive from release $($navData.release) stays" + } else { + $navZip = "$rel\RynthNav-NavData.zip" + Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem + $fs = [IO.File]::Open($navZip, 'CreateNew') + try { + $za = New-Object IO.Compression.ZipArchive($fs, [IO.Compression.ZipArchiveMode]::Create) + foreach ($f in $navFiles) { + [void][IO.Compression.ZipFileExtensions]::CreateEntryFromFile($za, $f.FullName, $f.Name, [IO.Compression.CompressionLevel]::Optimal) + } + $za.Dispose() + } finally { $fs.Dispose() } + $zi = Get-Item $navZip + $navData = [ordered]@{ + id = $navId + release = $release + url = "$BaseUrl/releases/$release/RynthNav-NavData.zip" + size = $zi.Length + sha256 = Sha256 $zi.FullName + files = $navFiles.Count + bytes = $navBytes + } + Write-Host (" new set: {0} files ({1} tiles), {2:N0} MB packed into {3:N0} MB, id {4}" -f $navFiles.Count, $tileCount, ($navBytes / 1MB), ($zi.Length / 1MB), $navId) + } +} + # ── 3. Manifest + signature ────────────────────────────────────────────────── Step "Writing and signing the manifest" $setup = Get-Item "$rel\RynthCore-Setup.exe" +# One line per plugin for the launcher's Available plugins list (launchers from 2026.10.5 on; +# older ones ignore the field, and a plugin without one falls back to the launcher's own table +# in RynthUpdater.Available.cs). Plain English for players, no names. +$pluginDescriptions = @{ + RynthAi = "The bot: combat, buffs, looting, navigation routes and metas." + RynthChat = "A chat window that sorts messages into tabs." + RynthTracker = "Kills, experience and luminance per hour for each session." + RynthNav = "Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB)." + RynthVision = "Shows unclimbable slopes, impassable water and your radar range in the world." + RynthLua = "Lua scripting for metas and your own scripts." + RynthOracle = "Quests, character, titles and leaderboards." + RynthInventory = "Search every character's items." +} $plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Name) { - [ordered]@{ - name = $dll.BaseName -replace '^RynthCore\.Plugin\.', '' + $pluginName = $dll.BaseName -replace '^RynthCore\.Plugin\.', '' + $entry = [ordered]@{ + name = $pluginName file = $dll.Name url = "$BaseUrl/releases/$release/plugins/$($dll.Name)" size = $dll.Length sha256 = Sha256 $dll.FullName } + if ($pluginDescriptions[$pluginName]) { $entry.description = $pluginDescriptions[$pluginName] } + else { Write-Warning "No description for $pluginName - the launcher shows its own (or none). Add one to `$pluginDescriptions." } + $entry } $manifest = [ordered]@{ schema = 1 @@ -178,6 +290,9 @@ $manifest = [ordered]@{ version = $Version published = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") notes = $Notes + # The changes, one line each: the launcher's update card shows a few as "What's new" + # (signed with the rest; launchers before 2026.10.5 ignore it and show the notes). + changes = @($Changes) core = [ordered]@{ release = $release version = $Version @@ -187,6 +302,7 @@ $manifest = [ordered]@{ } plugins = @($plugins) } +if ($navData) { $manifest.navdata = $navData } Set-Content "$rel\update.payload.json" ($manifest | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM & (Join-Path $ScriptDir "Sign-Update.ps1") -PayloadPath "$rel\update.payload.json" -OutPath "$rel\update.json" -KeyDir $KeyDir if (-not (Test-Envelope "$rel\update.json" $trusted)) { throw "Signed feed does not verify against UpdateTrust.cs" } @@ -215,9 +331,16 @@ scp -q "$rel\RynthCore-Setup.exe" "${SshHost}:$remoteRel/RynthCore-Setup.exe" if ($LASTEXITCODE -ne 0) { throw "scp of the installer failed" } scp -q (Get-ChildItem "$rel\plugins\*.dll").FullName "${SshHost}:$remoteRel/plugins/" if ($LASTEXITCODE -ne 0) { throw "scp of the plugins failed" } +$navSum = "" +if ($navZip) { + scp -q $navZip "${SshHost}:$remoteRel/RynthNav-NavData.zip" + if ($LASTEXITCODE -ne 0) { throw "scp of the RynthNav data archive failed" } + $navSum = " RynthNav-NavData.zip" +} -$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll" +$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll$navSum" $expect = @{ "RynthCore-Setup.exe" = $manifest.core.sha256 } +if ($navZip) { $expect["RynthNav-NavData.zip"] = $navData.sha256 } foreach ($pl in $plugins) { $expect["plugins/$($pl.file)"] = $pl.sha256 } foreach ($line in $remoteSums) { $sum, $name = $line -split '\s+', 2 diff --git a/installer/RynthCore.iss b/installer/RynthCore.iss index e5ab67c..a1842da 100644 --- a/installer/RynthCore.iss +++ b/installer/RynthCore.iss @@ -161,6 +161,16 @@ Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Description: "Launch Rynth ; bring it back when the upgrade is done. Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Flags: nowait runasoriginaluser; Check: CmdLineParamExists('/RELAUNCH') +[UninstallRun] +; Decal + RynthCore (experimental): remove the Decal bridge's registration, only +; what the launcher added (see docs/DECAL_BRIDGE_PLAN.md). Builds made with Decal installed ship +; the bridge ({app}\DecalBridge, staged by Build-Installer.ps1); this always runs; with nothing +; registered it changes nothing. Runs before the files are removed. It removes both entries +; the installer writes (see RegisterDecalBridge in [Code]): the per-user one, and the +; machine-wide one - directly when the uninstaller is elevated, otherwise after Windows' +; administrator prompt, which appears only when a machine-wide entry exists. +Filename: "{app}\RynthCore.exe"; Parameters: "--decal-bridge-unregister"; Flags: runhidden waituntilterminated; RunOnceId: "RynthCoreDecalBridgeUnregister" + [Code] const DefaultSuiteDir = 'C:\Games\RynthSuite'; @@ -487,3 +497,106 @@ begin if MemoTasksInfo <> '' then Result := Result + NewLine + MemoTasksInfo; end; + +(* ------------------------------------------------------------------------------------- + Decal + RynthCore (experimental): register the RynthCore Decal bridge on every install + AND every update (the launcher's updater runs this installer with /SILENT), in BOTH + places a Decal client can read its filter list from: + + 1. Machine-wide: HKLM\SOFTWARE\WOW6432Node\Decal\NetworkFilters\{5B3E0D57-...} + (32-bit view). An elevated AC (RynthCore or AC run as administrator), or any AC when + UAC or its registry virtualization is off, reads ONLY this key - the per-user entry + is invisible to it (a player's Decal + RynthCore client never loaded the bridge, + 2026-10-03). A non-elevated AC without a per-user copy reads it too. + 2. Per-user: this user's VirtualStore copy of that key, ONLY if the copy already exists. + A non-elevated AC is virtualized and, once a copy exists, reads nothing but the copy. + A missing copy is never created: it would hide every HKLM filter added later from + this user's non-elevated clients. + + Both entries are harmless while no account uses Decal + RynthCore: every Decal client + loads the bridge, which stays idle (no hooks, no threads) unless the RynthCore loader is + in the same client. Uninstall removes both ([UninstallRun] --decal-bridge-unregister). + + Rights. This installer runs with the lowest privileges (PrivilegesRequired=lowest; the + updater starts it without elevation). Writing HKLM needs administrator rights, so: + - Setup already elevated (installed "for all users", or started by an elevated + launcher): written directly, no prompt. + - Not elevated: Windows' administrator prompt is shown ONCE - only when Decal is + installed, the machine-wide entry is missing or points at another folder, and this + user has a Decal + RynthCore account (decal-accounts.json). Saying no is harmless: + the launcher checks before every Decal + RynthCore launch and repairs it (writing it + directly when it runs elevated, the case that needs it). + The commands are RynthCore.exe's own (Program.cs): --decal-bridge-register-machine and + --decal-bridge-install-user, so the installer and the launcher write identical entries. + ------------------------------------------------------------------------------------- *) +const + BridgeEntryKey = 'SOFTWARE\Decal\NetworkFilters\{5B3E0D57-2C41-4F8A-9D6E-8C1B70DECA11}'; + BridgeObject = 'RynthCore.DecalBridge.BridgeFilter'; + +function DecalInstalled: Boolean; +begin + Result := RegKeyExists(HKLM32, 'SOFTWARE\Decal\Agent'); +end; + +function BridgeDir: String; +begin + Result := ExpandConstant('{app}\DecalBridge'); +end; + +function MachineBridgeEntryCurrent: Boolean; +var + P, O: String; + E: Cardinal; +begin + Result := RegQueryStringValue(HKLM32, BridgeEntryKey, 'Path', P) and + (CompareText(RemoveBackslashUnlessRoot(P), BridgeDir) = 0) and + RegQueryStringValue(HKLM32, BridgeEntryKey, 'Object', O) and (O = BridgeObject) and + RegQueryDWordValue(HKLM32, BridgeEntryKey, 'Enabled', E) and (E = 1); +end; + +function UsesDecalBridge: Boolean; +begin + Result := FileExists(ExpandConstant('{userappdata}\RynthCore\decal-accounts.json')); +end; + +procedure RegisterDecalBridge; +var + Exe, Params: String; + Code: Integer; +begin + if not DecalInstalled then Exit; + if not FileExists(BridgeDir + '\RynthCore.DecalBridge.dll') then Exit; + Exe := ExpandConstant('{app}\RynthCore.exe'); + Params := '--decal-bridge-register-machine "' + BridgeDir + '"'; + if not MachineBridgeEntryCurrent then + begin + if IsAdmin then + begin + if not Exec(Exe, Params, ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, Code) then + Log('Decal bridge: machine-wide registration did not start: ' + SysErrorMessage(Code)) + else + Log('Decal bridge: machine-wide registration exit code ' + IntToStr(Code)); + end + else if UsesDecalBridge then + begin + if not ShellExec('runas', Exe, Params, ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, Code) then + Log('Decal bridge: elevated machine-wide registration not done (declined or failed): ' + SysErrorMessage(Code)) + else + Log('Decal bridge: elevated machine-wide registration exit code ' + IntToStr(Code)); + end + else + Log('Decal bridge: machine-wide entry missing; not elevated and no Decal + RynthCore account - left to the launcher.'); + end; + { Per-user half, as the user who started Setup (the same user unless Setup was elevated + with other credentials). } + if not ExecAsOriginalUser(Exe, '--decal-bridge-install-user "' + BridgeDir + '"', ExpandConstant('{app}'), + SW_HIDE, ewWaitUntilTerminated, Code) then + Log('Decal bridge: per-user step did not start: ' + SysErrorMessage(Code)); +end; + +procedure CurStepChanged(CurStep: TSetupStep); +begin + { After the files, before [Run] (which relaunches the launcher after an update). } + if CurStep = ssPostInstall then + RegisterDecalBridge; +end; diff --git a/installer/previous-release/last-built-version.txt b/installer/previous-release/last-built-version.txt index f5a2c8c..2ea516c 100644 --- a/installer/previous-release/last-built-version.txt +++ b/installer/previous-release/last-built-version.txt @@ -1 +1 @@ -2026.10.4.22 \ No newline at end of file +2026.10.5.11 \ No newline at end of file diff --git a/installer/previous-release/last-release-manifest.json b/installer/previous-release/last-release-manifest.json index 85295af..20d4260 100644 --- a/installer/previous-release/last-release-manifest.json +++ b/installer/previous-release/last-release-manifest.json @@ -1,24 +1,24 @@ { "schema": 1, "product": "RynthCore + RynthSuite", - "version": "2026.10.4.22", - "release": 2026100422, - "builtUtc": "2026-10-05T05:05:36Z", - "previous": "2026.10.4.21", + "version": "2026.10.5.11", + "release": 2026100511, + "builtUtc": "2026-10-05T17:09:44Z", + "previous": "2026.10.5.10", "installer": { - "file": "RynthCore-Setup-2026.10.4.22.exe", - "size": 108550595, - "sha256": "9e29c47918dfae7cbcf6def51386e55d9ecb9b7d410d9e2fea5d29ce86911379" + "file": "RynthCore-Setup-2026.10.5.11.exe", + "size": 130761857, + "sha256": "9be7f21a15c0d175f5f00c252eea7bf4caadaf798676ea96b3673e47267c424e" }, "source": { "rynthCore": { - "branch": "SK-local", - "commit": "ae775110769b1367288ff8979525bbb3a1a55535", + "branch": "merge/aelrynth-2026.10.5.1", + "commit": "1c75df5351ab20b05bbd0493f6a4097e72f0ddcf", "dirty": false }, "rynthSuite": { - "branch": "SK-local", - "commit": "dc9b6a48849161866d90a252303b6ff9b2d610b2", + "branch": "fix/rynthai-launcher-remote-commands", + "commit": "27f962fa89daac495fc5c92cd252225d1b237b45", "dirty": false } }, @@ -26,71 +26,72 @@ { "name": "Launcher (RynthCore.exe)", "file": "core\\RynthCore.exe", - "version": "2026.10.4.22+ae775110769b1367288ff8979525bbb3a1a55535" + "version": "2026.10.5.11+1c75df5351ab20b05bbd0493f6a4097e72f0ddcf" }, { "name": "Engine", "file": "core\\Runtime\\RynthCore.Engine.dll", - "version": "2026.10.4.22+ae775110769b1367288ff8979525bbb3a1a55535" + "version": "2026.10.5.11+1c75df5351ab20b05bbd0493f6a4097e72f0ddcf" }, { "name": "Loader", "file": "core\\Runtime\\RynthCore.Loader.dll", - "version": "2026.10.4.22+ae775110769b1367288ff8979525bbb3a1a55535" + "version": "" }, { "name": "Loot Editor", "file": "core\\Tools\\LootEditor\\RynthCore.LootEditor.exe", - "version": "2026.10.4.22+dc9b6a48849161866d90a252303b6ff9b2d610b2" + "version": "2026.10.5.11+27f962fa89daac495fc5c92cd252225d1b237b45" }, { "name": "RynthAi plugin", "file": "suite\\RynthAi\\RynthCore.Plugin.RynthAi.dll", - "version": "0.6.32-legacy-ui+dc9b6a48849161866d90a252303b6ff9b2d610b2" + "version": "1.0.0+27f962fa89daac495fc5c92cd252225d1b237b45" }, { "name": "Monster Editor", "file": "suite\\RynthAi\\MonsterEditor\\RynthCore.MonsterEditor.exe", - "version": "2026.10.4.22+dc9b6a48849161866d90a252303b6ff9b2d610b2" + "version": "2026.10.5.11+27f962fa89daac495fc5c92cd252225d1b237b45" }, { "name": "RynthChat (experimental)", "file": "suite\\RynthChat\\RynthCore.Plugin.RynthChat.dll", - "version": "0.1.1-experimental+dc9b6a48849161866d90a252303b6ff9b2d610b2" + "version": "1.0.0+27f962fa89daac495fc5c92cd252225d1b237b45" }, { "name": "RynthJuice (experimental)", "file": "suite\\RynthJuice\\RynthCore.Plugin.RynthJuice.dll", - "version": "0.1.2-experimental+dc9b6a48849161866d90a252303b6ff9b2d610b2" + "version": "0.1.2-experimental+27f962fa89daac495fc5c92cd252225d1b237b45" }, { "name": "RynthNav (experimental)", "file": "suite\\RynthNav\\RynthCore.Plugin.RynthNav.dll", - "version": "0.5.5-experimental+dc9b6a48849161866d90a252303b6ff9b2d610b2" + "version": "1.0.0+27f962fa89daac495fc5c92cd252225d1b237b45" }, { "name": "RynthTracker (experimental)", "file": "suite\\RynthTracker\\RynthCore.Plugin.RynthTracker.dll", - "version": "0.1.1-experimental+dc9b6a48849161866d90a252303b6ff9b2d610b2" + "version": "1.0.0+27f962fa89daac495fc5c92cd252225d1b237b45" }, { "name": "RynthVision (experimental)", "file": "suite\\RynthVision\\RynthCore.Plugin.RynthVision.dll", - "version": "0.1.1-experimental+dc9b6a48849161866d90a252303b6ff9b2d610b2" + "version": "1.0.0+27f962fa89daac495fc5c92cd252225d1b237b45" }, { "name": "UbRythai (experimental)", "file": "suite\\UbRythai\\RynthCore.Plugin.UbRythai.dll", - "version": "3.1.10+dc9b6a48849161866d90a252303b6ff9b2d610b2" + "version": "3.1.10+27f962fa89daac495fc5c92cd252225d1b237b45" } ], "changelog": [ - "RynthCore/Changelog/2026-10-05-chat-translation.md", - "RynthCore/Changelog/2026-10-05-installer-2026.10.4.21-release.md" + "RynthCore/Changelog/2026-10-05-guardian-vendor-and-item-lookup.md", + "RynthCore/Changelog/2026-10-05-native-drag-real-item.md", + "RynthCore/Changelog/2026-10-05-release-2026.10.5.10.md" ], "changelogSince": { - "rynthCore": "51307657d971ff81c61aa6532fb1ad941c54ca7f", - "rynthSuite": "a7754b972b26a78a2e28f3d0938c68e522cea0af", + "rynthCore": "0bff4931842c0cc0bd67057fb4b670b204e6e1a8", + "rynthSuite": "e3982b4d5171cd1339745fa464bd86d0aab721dc", "date": "" } } \ No newline at end of file diff --git a/native/Loader/Build-Loader.ps1 b/native/Loader/Build-Loader.ps1 new file mode 100644 index 0000000..89d22c9 --- /dev/null +++ b/native/Loader/Build-Loader.ps1 @@ -0,0 +1,36 @@ +# Build-Loader.ps1 +# Compiles the native RynthCore.Loader.dll (x86 MSVC) into native\Loader\bin. +# Does not deploy: copy it to Runtime\ yourself (a running client keeps the old loader +# until it restarts; the loader is injected once per process). + +$ErrorActionPreference = "Stop" + +$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" ` + -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 ` + -property installationPath 2>$null +if (-not $vsPath) { Write-Error "Visual Studio with C++ tools not found."; exit 1 } + +$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name +$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer" +$cl = "$vcBase\bin\Hostx86\x86\cl.exe" +$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name +$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer" +$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer" +$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared" +$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86" + +$src = $PSScriptRoot +$out = Join-Path $src "bin" +$obj = Join-Path $out "obj" +New-Item -ItemType Directory -Path $out, $obj -Force | Out-Null + +Write-Host "Compiling RynthCore.Loader.dll (MSVC $vcVer, x86)..." +Push-Location $obj +try { + & $cl /nologo /O2 /MT /GS /W4 /wd4100 /LD /Zi "$src\Loader.c" "$src\Hooks.c" "$src\Clr.c" "$src\Services.c" user32.lib ` + /link /MACHINE:X86 /DEF:"$src\Loader.def" /DEBUG /OPT:REF /OUT:"$out\RynthCore.Loader.dll" /PDB:"$out\RynthCore.Loader.pdb" + if ($LASTEXITCODE -ne 0) { Write-Error "Compilation failed."; exit $LASTEXITCODE } +} finally { Pop-Location } + +$size = (Get-Item "$out\RynthCore.Loader.dll").Length +Write-Host "Built: $out\RynthCore.Loader.dll ($size bytes)" diff --git a/native/Loader/Clr.c b/native/Loader/Clr.c new file mode 100644 index 0000000..3db0e30 --- /dev/null +++ b/native/Loader/Clr.c @@ -0,0 +1,175 @@ +// ============================================================================ +// Clr.c - hosts CoreCLR once, from the app-local runtime in Runtime\dotnet\, and +// talks to RynthCore.Shim.dll (default ALC), which owns the collectible +// AssemblyLoadContext each engine generation lives in. +// +// The raw coreclr_* API is used (no hostfxr, runtimeconfig.json or deps.json): the +// TPA list is every managed DLL in Runtime\dotnet\ plus the Shim. The engine and its +// own dependencies (Avalonia, ImGui.NET, ...) are NOT on the TPA list: the Shim loads +// them into the engine's collectible ALC, so they go away with it. +// ============================================================================ + +#include "Loader.h" +#include <stdio.h> + +typedef int (__stdcall *coreclr_initialize_fn)(const char* exePath, const char* appDomainFriendlyName, + int propertyCount, const char** propertyKeys, const char** propertyValues, + void** hostHandle, unsigned int* domainId); +typedef int (__stdcall *coreclr_create_delegate_fn)(void* hostHandle, unsigned int domainId, + const char* assemblyName, const char* typeName, const char* methodName, void** fn); + +// Shared with RynthCore.Shim (ShimHost.cs): keep the layouts in step. +typedef struct LoaderApi { + int size; + void (__stdcall *log)(const char* level, const char* utf8); + int (__stdcall *freeMb)(int* largestMb); + const char* loaderDir; + int (__stdcall *hookCount)(void); +} LoaderApi; + +typedef struct ShimApi { + int size; + int (__stdcall *loadEngine)(int generation, const char* stagedPathUtf8); + int (__stdcall *unloadEngine)(void); // 1 = the ALC was freed + void* (__stdcall *engineExport)(const char* nameUtf8); +} ShimApi; + +typedef int (__stdcall *shim_init_fn)(LoaderApi* api, ShimApi* out); + +static LoaderApi g_loaderApi; +static ShimApi g_shim; +static int g_started; + +int __stdcall RcHooks_Count(void); + +static void __stdcall ShimLog(const char* level, const char* utf8) { LoaderLog(level ? level : "INF", "[shim] %s", utf8); } +static int __stdcall ShimFreeMb(int* largestMb) +{ + long largest; + long free = LoaderFreeAddressSpaceMb(&largest); + if (largestMb) *largestMb = (int)largest; + return (int)free; +} + +static int IsNativeRuntimeFile(const char* n) +{ + static const char* natives[] = { + "coreclr.dll", "clrjit.dll", "clrgc.dll", "clrgcexp.dll", "hostfxr.dll", "hostpolicy.dll", + "mscordaccore.dll", "mscordbi.dll", "mscorrc.dll", "clretwrc.dll", "msquic.dll", + "System.IO.Compression.Native.dll", "Microsoft.DiaSymReader.Native.x86.dll", + }; + for (int i = 0; i < (int)(sizeof natives / sizeof natives[0]); i++) + if (!_stricmp(n, natives[i])) return 1; + return !_strnicmp(n, "mscordaccore_", 13); +} + +static int AppendDlls(char* tpa, size_t cap, const char* dir) +{ + char pattern[MAX_PATH]; + _snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\*.dll", dir); + WIN32_FIND_DATAA fd; + HANDLE h = FindFirstFileA(pattern, &fd); + if (h == INVALID_HANDLE_VALUE) return 0; + int n = 0; + do { + if (IsNativeRuntimeFile(fd.cFileName)) continue; + strcat_s(tpa, cap, dir); + strcat_s(tpa, cap, "\\"); + strcat_s(tpa, cap, fd.cFileName); + strcat_s(tpa, cap, ";"); + n++; + } while (FindNextFileA(h, &fd)); + FindClose(h); + return n; +} + +int ClrStart(const char* loaderDir) +{ + if (g_started) return 0; + char runtimeDir[MAX_PATH], coreclrPath[MAX_PATH], shimPath[MAX_PATH]; + _snprintf_s(runtimeDir, sizeof runtimeDir, _TRUNCATE, "%s\\dotnet", loaderDir); + _snprintf_s(coreclrPath, sizeof coreclrPath, _TRUNCATE, "%s\\coreclr.dll", runtimeDir); + _snprintf_s(shimPath, sizeof shimPath, _TRUNCATE, "%s\\RynthCore.Shim.dll", loaderDir); + if (GetFileAttributesA(shimPath) == INVALID_FILE_ATTRIBUTES) { + LoaderLog("ERR", "CLR: %s is missing", shimPath); + return 1; + } + + long free0 = LoaderFreeAddressSpaceMb(NULL); + DWORD t0 = GetTickCount(); + HMODULE clr = LoadLibraryExA(coreclrPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); + if (!clr) { + LoaderLog("ERR", "CLR: LoadLibrary %s failed (error %lu)", coreclrPath, GetLastError()); + return 2; + } + coreclr_initialize_fn init = (coreclr_initialize_fn)GetProcAddress(clr, "coreclr_initialize"); + coreclr_create_delegate_fn create = (coreclr_create_delegate_fn)GetProcAddress(clr, "coreclr_create_delegate"); + if (!init || !create) return 3; + + static char tpa[128 * 1024]; + tpa[0] = 0; + int count = AppendDlls(tpa, sizeof tpa, runtimeDir); + strcat_s(tpa, sizeof tpa, shimPath); + strcat_s(tpa, sizeof tpa, ";"); + + char nativeDirs[2 * MAX_PATH + 4], baseDir[MAX_PATH + 2]; + _snprintf_s(nativeDirs, sizeof nativeDirs, _TRUNCATE, "%s;%s;", loaderDir, runtimeDir); + _snprintf_s(baseDir, sizeof baseDir, _TRUNCATE, "%s\\", loaderDir); + const char* keys[] = { + "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "APP_CONTEXT_BASE_DIRECTORY", + "System.GC.Server", "System.GC.Concurrent", "System.Globalization.Invariant", "System.GC.RetainVM", + }; + // Concurrent (background) GC on: the engine and the managed plugins share this one GC, + // and with it off every gen2 (~every 10 s, driven by large allocations) was a fully + // blocking 55-66 ms pause that AC's main thread hit whenever it was in managed code. + const char* values[] = { + tpa, "", nativeDirs, baseDir, + "false", "true", "true", "false", + }; + char exePath[MAX_PATH]; + GetModuleFileNameA(NULL, exePath, MAX_PATH); + void* hostHandle = NULL; + unsigned int domainId = 0; + int hr = init(exePath, "RynthCore", (int)(sizeof keys / sizeof keys[0]), keys, values, &hostHandle, &domainId); + if (hr < 0) { + LoaderLog("ERR", "CLR: coreclr_initialize failed 0x%08x", hr); + return 4; + } + + shim_init_fn shimInit = NULL; + hr = create(hostHandle, domainId, "RynthCore.Shim", "RynthCore.Shim.ShimHost", "Init", (void**)&shimInit); + if (hr < 0 || !shimInit) { + LoaderLog("ERR", "CLR: RynthCore.Shim.ShimHost.Init not found (0x%08x)", hr); + return 5; + } + g_loaderApi.size = sizeof g_loaderApi; + g_loaderApi.log = ShimLog; + g_loaderApi.freeMb = ShimFreeMb; + g_loaderApi.loaderDir = LoaderDirectory(); + g_loaderApi.hookCount = RcHooks_Count; + g_shim.size = sizeof g_shim; + int rc = shimInit(&g_loaderApi, &g_shim); + if (rc != 0 || !g_shim.loadEngine || !g_shim.unloadEngine || !g_shim.engineExport) { + LoaderLog("ERR", "CLR: Shim init failed (rc=%d)", rc); + return 6; + } + g_started = 1; + LoaderLog("INF", "CLR: CoreCLR up in %lu ms from %s (%d framework assemblies), %ld MB of address space used.", + GetTickCount() - t0, runtimeDir, count, free0 - LoaderFreeAddressSpaceMb(NULL)); + return 0; +} + +int ClrLoadEngine(int generation, const char* stagedPath) +{ + return g_started ? g_shim.loadEngine(generation, stagedPath) : -1; +} + +void ClrUnloadEngine(void) +{ + if (g_started) g_shim.unloadEngine(); +} + +void* ClrEngineExport(const char* name) +{ + return g_started ? g_shim.engineExport(name) : NULL; +} diff --git a/native/Loader/Hooks.c b/native/Loader/Hooks.c new file mode 100644 index 0000000..2f0afce --- /dev/null +++ b/native/Loader/Hooks.c @@ -0,0 +1,332 @@ +// ============================================================================ +// Hooks.c - MinHook facade with permanent stubs +// +// Exports MinHook's API (MH_Initialize, MH_CreateHook, MH_EnableHook, ...) with the +// same signatures and status codes, so the engine's Hooking/MinHook.cs can call either +// this facade or minhook.x86.dll. +// +// The difference: nothing native ever points at engine code directly. For every target +// the facade allocates a permanent 6-byte stub, `jmp dword ptr [slot]`, and installs the +// real MinHook hook once, with the stub as the detour. The slot holds either the +// engine's detour (hook enabled) or MinHook's trampoline (hook disabled: a transparent +// pass-through to the original, whatever the calling convention). A reload only +// re-points slots, so an engine generation can be unloaded as soon as no thread is +// inside its code, and the next generation's MH_CreateHook for the same target reuses +// the same stub and gets the same trampoline back. +// +// Hooks are "owned" by the generation that created them: MH_CreateHook on a target +// created by an earlier generation succeeds (no MH_ERROR_ALREADY_CREATED), and +// HooksPassThroughAll() (every reload) turns every slot back into a pass-through and +// takes the patch out of the target (MinHook disable: original bytes back), so the next +// generation's pattern scans see AC's real prologues; its MH_CreateHook puts it back. +// The stub and trampoline are never freed, so a thread still returning through them is +// safe. +// +// Patching is batched. Every MinHook enable/disable freezes all the process's threads +// (a system-wide thread snapshot, ~100 ms here), and an engine installs ~60 hooks: one +// freeze each made up ~7 s of every reload. The facade records which targets should be +// patched and applies them in one queued MinHook freeze: straight after the engine's +// init export returns (HooksFlush; on a first launch AC's main thread is still suspended +// then), on every reload, and ~20 ms after the last change otherwise (a background +// flusher). A hook's slot is set at once; its patch follows within that window. +// ============================================================================ + +#include "Loader.h" +#include <stdio.h> + +#define MH_OK 0 +#define MH_ERROR_ALREADY_INITIALIZED 1 +#define MH_ERROR_NOT_INITIALIZED 2 +#define MH_ERROR_ALREADY_CREATED 3 +#define MH_ERROR_NOT_CREATED 4 +#define MH_ERROR_ENABLED 5 +#define MH_ERROR_DISABLED 6 +#define MH_ERROR_MEMORY_ALLOC 9 +#define MH_UNKNOWN -1 + +#define MAX_HOOKS 1024 +#define STUB_SIZE 8 + +typedef int (__stdcall *mh_init_fn)(void); +typedef int (__stdcall *mh_create_fn)(void* target, void* detour, void** original); +typedef int (__stdcall *mh_target_fn)(void* target); +typedef const char* (__stdcall *mh_status_fn)(int status); + +typedef struct HookEntry { + void* target; + void* trampoline; // MinHook's call-the-original trampoline (never freed) + void* detour; // the owning generation's detour, or NULL once removed + int generation; // generation that last created it + int created; // created (and not removed) by `generation` + int enabled; // slot == detour + int patched; // MinHook's jump is in the target + int want; // it should be (applied by the next flush) +} HookEntry; + +static CRITICAL_SECTION g_lock; +static int g_ready; +static int g_generation; +static HMODULE g_minhook; +static mh_init_fn p_init; +static mh_create_fn p_create; +static mh_target_fn p_enable; +static mh_target_fn p_disable; +static mh_target_fn p_queueDisable; +static mh_target_fn p_queueEnable; +static mh_init_fn p_applyQueued; +static mh_status_fn p_status; + +static HookEntry g_hooks[MAX_HOOKS]; +static void* volatile g_slots[MAX_HOOKS]; +static unsigned char* g_stubs; +static int g_count; +static HANDLE g_dirtyEvent; +static volatile DWORD g_lastChange; + +static void FlushLocked(const char* why); + +static DWORD WINAPI Flusher(LPVOID unused) +{ + (void)unused; + for (;;) { + WaitForSingleObject(g_dirtyEvent, INFINITE); + do Sleep(20); while (GetTickCount() - g_lastChange < 20); // settle: one freeze per burst + EnterCriticalSection(&g_lock); + FlushLocked("batched"); + LeaveCriticalSection(&g_lock); + } +} + +int HooksInit(const char* loaderDir) +{ + InitializeCriticalSection(&g_lock); + char path[MAX_PATH]; + _snprintf_s(path, sizeof path, _TRUNCATE, "%s\\minhook.x86.dll", loaderDir); + g_minhook = LoadLibraryA(path); + if (!g_minhook) g_minhook = LoadLibraryA("minhook.x86.dll"); + if (!g_minhook) return 0; + p_init = (mh_init_fn)GetProcAddress(g_minhook, "MH_Initialize"); + p_create = (mh_create_fn)GetProcAddress(g_minhook, "MH_CreateHook"); + p_enable = (mh_target_fn)GetProcAddress(g_minhook, "MH_EnableHook"); + p_disable = (mh_target_fn)GetProcAddress(g_minhook, "MH_DisableHook"); + p_queueDisable = (mh_target_fn)GetProcAddress(g_minhook, "MH_QueueDisableHook"); + p_queueEnable = (mh_target_fn)GetProcAddress(g_minhook, "MH_QueueEnableHook"); + p_applyQueued = (mh_init_fn)GetProcAddress(g_minhook, "MH_ApplyQueued"); + p_status = (mh_status_fn)GetProcAddress(g_minhook, "MH_StatusToString"); + if (!p_init || !p_create || !p_enable || !p_disable) return 0; + int st = p_init(); + if (st != MH_OK && st != MH_ERROR_ALREADY_INITIALIZED) { + LoaderLog("ERR", "Hooks: MH_Initialize = %d", st); + return 0; + } + g_stubs = (unsigned char*)VirtualAlloc(NULL, MAX_HOOKS * STUB_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + if (!g_stubs) return 0; + g_dirtyEvent = CreateEventA(NULL, FALSE, FALSE, NULL); + if (p_queueEnable && p_queueDisable && p_applyQueued && g_dirtyEvent) { + HANDLE t = CreateThread(NULL, 0, Flusher, NULL, 0, NULL); + if (t) CloseHandle(t); + } + g_ready = 1; + LoaderLog("INF", "Hooks: MinHook facade ready (%s, %d stub slots, %s patching).", path, MAX_HOOKS, + p_queueEnable ? "batched" : "per-hook"); + return 1; +} + +void HooksBeginGeneration(int generation) +{ + EnterCriticalSection(&g_lock); + g_generation = generation; + LeaveCriticalSection(&g_lock); +} + +static void SetPatched(int i, int patched) +{ + HookEntry* e = &g_hooks[i]; + if (e->patched == patched) return; + int st = patched ? p_enable(e->target) : p_disable(e->target); + if (st == MH_OK) e->patched = patched; + else LoaderLog("ERR", "Hooks: MinHook %s %p failed: %d", patched ? "enable" : "disable", e->target, st); +} + +// Records whether target i should be patched; the next flush applies it. (Caller holds g_lock.) +static void Want(int i, int patched) +{ + HookEntry* e = &g_hooks[i]; + e->want = patched; + if (e->want == e->patched) return; + if (!p_queueEnable || !p_queueDisable || !p_applyQueued || !g_dirtyEvent) { + SetPatched(i, patched); // no queue in this MinHook: one at a time + return; + } + g_lastChange = GetTickCount(); + SetEvent(g_dirtyEvent); +} + +// Applies every pending patch/unpatch in one MinHook freeze. (Caller holds g_lock.) +static void FlushLocked(const char* why) +{ + static int queued[MAX_HOOKS]; + int n = 0; + for (int i = 0; i < g_count; i++) { + HookEntry* e = &g_hooks[i]; + if (e->want == e->patched) continue; + int st = e->want ? p_queueEnable(e->target) : p_queueDisable(e->target); + if (st == MH_OK) queued[n++] = i; + else SetPatched(i, e->want); + } + if (n == 0) return; + DWORD t0 = GetTickCount(); + int st = p_applyQueued(); + if (st == MH_OK) { + for (int k = 0; k < n; k++) g_hooks[queued[k]].patched = g_hooks[queued[k]].want; + LoaderLog("INF", "Hooks: %d patch(es) applied in one freeze (%lu ms, %s).", n, GetTickCount() - t0, why); + } else { + LoaderLog("ERR", "Hooks: MH_ApplyQueued (%d, %s) = %d; applying one at a time.", n, why, st); + for (int k = 0; k < n; k++) SetPatched(queued[k], g_hooks[queued[k]].want); + } +} + +void HooksFlush(void) +{ + if (!g_ready) return; + EnterCriticalSection(&g_lock); + FlushLocked("engine init"); + LeaveCriticalSection(&g_lock); +} + +static void SetSlot(int i, int enabled) +{ + HookEntry* e = &g_hooks[i]; + e->enabled = enabled; + InterlockedExchangePointer((PVOID volatile*)&g_slots[i], enabled ? e->detour : e->trampoline); +} + +void HooksPassThroughAll(void) +{ + if (!g_ready) return; + EnterCriticalSection(&g_lock); + int live = 0; + for (int i = 0; i < g_count; i++) { + if (g_hooks[i].enabled) live++; + SetSlot(i, 0); + Want(i, 0); + g_hooks[i].created = 0; + g_hooks[i].detour = NULL; + } + FlushLocked("reload"); // AC's own prologues back, now + LeaveCriticalSection(&g_lock); + LoaderLog("INF", "Hooks: %d hook(s) now pass straight through (%d were still enabled).", g_count, live); +} + +static int Find(void* target) +{ + for (int i = 0; i < g_count; i++) + if (g_hooks[i].target == target) return i; + return -1; +} + +// --- MinHook API ------------------------------------------------------------ + +int __stdcall MH_Initialize(void) { return g_ready ? MH_ERROR_ALREADY_INITIALIZED : MH_ERROR_NOT_INITIALIZED; } + +// Hooks outlive every engine generation; "uninitialize" only turns them into pass-throughs. +int __stdcall MH_Uninitialize(void) { HooksPassThroughAll(); return MH_OK; } + +int __stdcall MH_CreateHook(void* target, void* detour, void** original) +{ + if (!g_ready) return MH_ERROR_NOT_INITIALIZED; + int st = MH_OK; + EnterCriticalSection(&g_lock); + int i = Find(target); + if (i >= 0) { + HookEntry* e = &g_hooks[i]; + if (e->created && e->generation == g_generation) { + st = MH_ERROR_ALREADY_CREATED; + } else { + e->detour = detour; + e->generation = g_generation; + e->created = 1; + SetSlot(i, 0); + Want(i, 1); + if (original) *original = e->trampoline; + } + } else if (g_count >= MAX_HOOKS) { + st = MH_ERROR_MEMORY_ALLOC; + } else { + i = g_count; + unsigned char* stub = g_stubs + i * STUB_SIZE; + void* volatile* slot = &g_slots[i]; + stub[0] = 0xFF; stub[1] = 0x25; // jmp dword ptr [slot] + *(void* volatile**)(stub + 2) = slot; + stub[6] = 0xCC; stub[7] = 0xCC; + FlushInstructionCache(GetCurrentProcess(), stub, STUB_SIZE); + + void* tramp = NULL; + st = p_create(target, stub, &tramp); + if (st == MH_OK) { + HookEntry* e = &g_hooks[i]; + e->target = target; + e->trampoline = tramp; + e->detour = detour; + e->generation = g_generation; + e->created = 1; + e->enabled = 0; + *slot = tramp; // pass-through until the engine enables it + g_count++; + e->patched = 0; + Want(i, 1); // the patch goes in (slot passes through) + st = MH_OK; + if (original) *original = tramp; + } + } + LeaveCriticalSection(&g_lock); + return st; +} + +int __stdcall MH_RemoveHook(void* target) +{ + if (!g_ready) return MH_ERROR_NOT_INITIALIZED; + int st = MH_OK; + EnterCriticalSection(&g_lock); + int i = Find(target); + if (i < 0 || !g_hooks[i].created) st = MH_ERROR_NOT_CREATED; + else { + SetSlot(i, 0); + Want(i, 0); // original bytes back, like MinHook's remove + g_hooks[i].created = 0; + g_hooks[i].detour = NULL; + } + LeaveCriticalSection(&g_lock); + return st; +} + +static int SetEnabled(void* target, int enable) +{ + if (!g_ready) return MH_ERROR_NOT_INITIALIZED; + int st = MH_OK; + EnterCriticalSection(&g_lock); + if (target == NULL) { // MH_ALL_HOOKS + for (int i = 0; i < g_count; i++) + if (g_hooks[i].created && g_hooks[i].enabled != enable) SetSlot(i, enable); + } else { + int i = Find(target); + if (i < 0 || !g_hooks[i].created) st = MH_ERROR_NOT_CREATED; + else if (g_hooks[i].enabled == enable) st = enable ? MH_ERROR_ENABLED : MH_ERROR_DISABLED; + else SetSlot(i, enable); + } + LeaveCriticalSection(&g_lock); + return st; +} + +int __stdcall MH_EnableHook(void* target) { return SetEnabled(target, 1); } +int __stdcall MH_DisableHook(void* target) { return SetEnabled(target, 0); } + +const char* __stdcall MH_StatusToString(int status) +{ + if (p_status) return p_status(status); + return status == MH_OK ? "MH_OK" : "MH_UNKNOWN"; +} + +// Lets the engine tell this facade from minhook.x86.dll (and an old NativeAOT loader). +int __stdcall RcHooks_Version(void) { return 1; } +int __stdcall RcHooks_Count(void) { return g_count; } diff --git a/native/Loader/Loader.c b/native/Loader/Loader.c new file mode 100644 index 0000000..a9dd57b --- /dev/null +++ b/native/Loader/Loader.c @@ -0,0 +1,407 @@ +// ============================================================================ +// RynthCore.Loader.dll - native loader (docs/UNLOADABLE_ENGINE_PLAN.md, Phase 1) +// +// Injected into acclient.exe by RynthCore.Injector / the launcher, which call the +// RynthCoreInit export on a remote thread (same contract as the old NativeAOT loader). +// +// Two engine hosts, chosen by looking at Runtime\RynthCore.Engine.dll: +// - NativeAOT engine (a native DLL exporting RynthCoreEngineInit): staged to +// .engine_loads\, LoadLibrary'd, never freed. Today's behaviour. +// - Managed engine (a PE with a CLR header): the loader starts CoreCLR once from +// Runtime\dotnet\ and hands the engine to RynthCore.Shim.dll (default ALC), which +// loads each generation into a collectible AssemblyLoadContext and unloads it on +// reload, so a reload gives its memory back. +// +// Either way the loader owns the reload event, the file watcher, the address-space +// guard and a MinHook facade (Hooks.c): every hook is installed once, through a +// permanent stub, and a reload only re-points the stub. +// ============================================================================ + +#include "Loader.h" + +#include <stdio.h> +#include <stdarg.h> + +#define ENGINE_DLL_NAME "RynthCore.Engine.dll" +#define ENGINE_INIT_EXPORT "RynthCoreEngineInit" +#define ENGINE_SHUTDOWN_EXPORT "RynthCoreShutdown" +#define ENGINE_REFUSED_EXPORT "RynthCoreReloadRefused" +#define LOG_DIR "C:\\Games\\RynthCore\\Logs" +#define STAGING_SUBDIR ".engine_loads" +#define MIN_RELOAD_INTERVAL_MS 1500 +// A managed engine gives its memory back on reload, so the guard only has to keep +// room for one more generation; the NativeAOT engine leaks every generation. +#define MIN_FREE_MB_AOT 1200 +#define MIN_FREE_MB_CLR 500 + +typedef unsigned int (__stdcall *engine_u32_fn)(void* param); +typedef unsigned int (__stdcall *engine_refused_fn)(int freeMb); + +static volatile LONG g_initialized; +static char g_loaderDir[MAX_PATH]; +static char g_enginePath[MAX_PATH]; +static int g_engineIsManaged; +static HMODULE g_engineModule; // NativeAOT host only +static int g_initCount; +static HANDLE g_reloadEvent; +static FILETIME g_canonicalWrite; +static volatile LONG g_reloadInFlight; +static volatile ULONGLONG g_lastReloadDone; +static CRITICAL_SECTION g_logLock; + +// --------------------------------------------------------------------------- +// Logging: same per-client file and line format as the engine (LogPaths.cs). +// --------------------------------------------------------------------------- + +void LoaderLog(const char* level, const char* fmt, ...) +{ + char msg[3072]; + va_list ap; + va_start(ap, fmt); + _vsnprintf_s(msg, sizeof msg, _TRUNCATE, fmt, ap); + va_end(ap); + + SYSTEMTIME t; + GetLocalTime(&t); + char line[3300]; + int n = _snprintf_s(line, sizeof line, _TRUNCATE, "[%02d:%02d:%02d.%03d] [pid:%lu] [%s] [loader] %s\r\n", + t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, GetCurrentProcessId(), level, msg); + if (n < 0) n = (int)strlen(line); + + char path[MAX_PATH]; + _snprintf_s(path, sizeof path, _TRUNCATE, LOG_DIR "\\RynthCore.%lu.log", GetCurrentProcessId()); + EnterCriticalSection(&g_logLock); + CreateDirectoryA("C:\\Games\\RynthCore", NULL); + CreateDirectoryA(LOG_DIR, NULL); + for (int attempt = 0; attempt < 4; attempt++) { + HANDLE h = CreateFileA(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (h != INVALID_HANDLE_VALUE) { + DWORD written; + WriteFile(h, line, (DWORD)n, &written, NULL); + CloseHandle(h); + break; + } + Sleep(5); + } + LeaveCriticalSection(&g_logLock); + OutputDebugStringA(line); +} + +// --------------------------------------------------------------------------- +// Address space +// --------------------------------------------------------------------------- + +long LoaderFreeAddressSpaceMb(long* largestMb) +{ + SYSTEM_INFO si; + GetSystemInfo(&si); + unsigned char* p = (unsigned char*)si.lpMinimumApplicationAddress; + unsigned char* end = (unsigned char*)si.lpMaximumApplicationAddress; + unsigned long long total = 0, largest = 0; + MEMORY_BASIC_INFORMATION mbi; + while (p < end && VirtualQuery(p, &mbi, sizeof mbi) == sizeof mbi) { + if (mbi.RegionSize == 0) break; + if (mbi.State == MEM_FREE) { + total += mbi.RegionSize; + if (mbi.RegionSize > largest) largest = mbi.RegionSize; + } + p = (unsigned char*)mbi.BaseAddress + mbi.RegionSize; + } + if (largestMb) *largestMb = (long)(largest / (1024 * 1024)); + return (long)(total / (1024 * 1024)); +} + +// --------------------------------------------------------------------------- +// Engine file: staging and kind +// --------------------------------------------------------------------------- + +static int FileLastWrite(const char* path, FILETIME* out) +{ + WIN32_FILE_ATTRIBUTE_DATA d; + if (!GetFileAttributesExA(path, GetFileExInfoStandard, &d)) return 0; + *out = d.ftLastWriteTime; + return 1; +} + +// 1 = the file is a .NET assembly (PE with a CLR header), 0 = native, -1 = unreadable. +static int IsManagedPe(const char* path) +{ + HANDLE h = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (h == INVALID_HANDLE_VALUE) return -1; + unsigned char buf[4096]; + DWORD read = 0; + BOOL ok = ReadFile(h, buf, sizeof buf, &read, NULL); + CloseHandle(h); + if (!ok || read < sizeof(IMAGE_DOS_HEADER)) return -1; + IMAGE_DOS_HEADER* dos = (IMAGE_DOS_HEADER*)buf; + if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew <= 0 || + (DWORD)dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32) > read) return -1; + IMAGE_NT_HEADERS32* nt = (IMAGE_NT_HEADERS32*)(buf + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE) return -1; + if (nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return 0; + if (nt->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR) return 0; + return nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress != 0; +} + +static void CleanStaleStagingFiles(const char* stagingDir) +{ + char pattern[MAX_PATH]; + _snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\RynthCore.Engine.p*.gen*.*", stagingDir); // .dll + .pdb + WIN32_FIND_DATAA fd; + HANDLE f = FindFirstFileA(pattern, &fd); + if (f == INVALID_HANDLE_VALUE) return; + do { + char p[MAX_PATH]; + _snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", stagingDir, fd.cFileName); + DeleteFileA(p); // fails for files a live process still maps: fine + } while (FindNextFileA(f, &fd)); + FindClose(f); +} + +// Copies the canonical engine to .engine_loads\RynthCore.Engine.p<pid>.gen<N>.dll so the +// canonical file is never locked (a developer can copy over it) and every generation is +// a distinct module/assembly path. +static int StageEngine(int generation, char* stagedPath, size_t cap) +{ + char stagingDir[MAX_PATH]; + _snprintf_s(stagingDir, sizeof stagingDir, _TRUNCATE, "%s\\" STAGING_SUBDIR, g_loaderDir); + CreateDirectoryA(stagingDir, NULL); + CleanStaleStagingFiles(stagingDir); + _snprintf_s(stagedPath, cap, _TRUNCATE, "%s\\RynthCore.Engine.p%lu.gen%d.dll", + stagingDir, GetCurrentProcessId(), generation); + if (!CopyFileA(g_enginePath, stagedPath, FALSE)) { + LoaderLog("ERR", "StageEngine: copy to %s failed (error %lu)", stagedPath, GetLastError()); + return 0; + } + if (g_engineIsManaged) { + // The debug symbols travel with the assembly so stack traces keep line numbers. + char srcPdb[MAX_PATH], dstPdb[MAX_PATH]; + _snprintf_s(srcPdb, sizeof srcPdb, _TRUNCATE, "%s\\RynthCore.Engine.pdb", g_loaderDir); + _snprintf_s(dstPdb, sizeof dstPdb, _TRUNCATE, "%.*s.pdb", (int)(strlen(stagedPath) - 4), stagedPath); + CopyFileA(srcPdb, dstPdb, FALSE); + } + LoaderLog("INF", "Staged engine for gen %d at %s", generation, stagedPath); + return 1; +} + +// --------------------------------------------------------------------------- +// Engine calls, whichever host +// --------------------------------------------------------------------------- + +static void* EngineExport(const char* name) +{ + if (g_engineIsManaged) return ClrEngineExport(name); + return g_engineModule ? (void*)GetProcAddress(g_engineModule, name) : NULL; +} + +static unsigned int LoadAndInitEngine(void) +{ + g_initCount++; + HooksBeginGeneration(g_initCount); + + char staged[MAX_PATH]; + if (!StageEngine(g_initCount, staged, sizeof staged)) return 11; + if (!FileLastWrite(g_enginePath, &g_canonicalWrite)) GetSystemTimeAsFileTime(&g_canonicalWrite); + + if (g_engineIsManaged) { + int rc = ClrLoadEngine(g_initCount, staged); + if (rc != 0) { + LoaderLog("ERR", "Managed engine gen %d failed to load (rc=%d)", g_initCount, rc); + return 4; + } + } else { + HMODULE m = LoadLibraryA(staged); + if (!m) { + LoaderLog("ERR", "LoadLibrary failed for engine (path=%s, error %lu)", staged, GetLastError()); + return 4; + } + g_engineModule = m; + LoaderLog("INF", "Engine module loaded at 0x%08p from %s", (void*)m, staged); + } + + engine_u32_fn init = (engine_u32_fn)EngineExport(ENGINE_INIT_EXPORT); + if (!init) { + LoaderLog("ERR", "Engine missing export '%s'", ENGINE_INIT_EXPORT); + return 5; + } + unsigned int rc = init((void*)(INT_PTR)g_initCount); + // The hooks the engine installed during init go in now, in one freeze, before the + // injector resumes AC's main thread (first launch) or the new generation runs. + HooksFlush(); + LoaderLog("INF", ENGINE_INIT_EXPORT "(initCount=%d) returned %u.", g_initCount, rc); + return rc; +} + +static void Reload(void) +{ + long largest; + long freeBefore = LoaderFreeAddressSpaceMb(&largest); + LoaderLog("INF", "Reload requested (gen %d, %ld MB free, largest %ld MB).", g_initCount, freeBefore, largest); + + engine_u32_fn shutdown = (engine_u32_fn)EngineExport(ENGINE_SHUTDOWN_EXPORT); + if (shutdown) { + unsigned int rc = shutdown(NULL); + LoaderLog("INF", ENGINE_SHUTDOWN_EXPORT " returned %u.", rc); + } else { + LoaderLog("WRN", "Engine has no '%s' export; skipping graceful shutdown.", ENGINE_SHUTDOWN_EXPORT); + } + + // Whatever the engine left enabled now passes straight through to AC. + HooksPassThroughAll(); + ServicesReleaseAll(); + Sleep(150); + + if (g_engineIsManaged) { + ClrUnloadEngine(); + } else if (g_engineModule) { + // A NativeAOT module can't be freed (its runtime keeps threads with frames in it). + LoaderLog("INF", "Reload: NativeAOT engine 0x%08p left mapped (can't unload).", (void*)g_engineModule); + g_engineModule = NULL; + } + + unsigned int rc = LoadAndInitEngine(); + long freeAfter = LoaderFreeAddressSpaceMb(&largest); + LoaderLog(rc == 0 ? "INF" : "ERR", "Reload: %s (gen %d, %ld MB free, %+ld MB vs before the reload).", + rc == 0 ? "complete" : "re-init FAILED", g_initCount, freeAfter, freeAfter - freeBefore); +} + +// --------------------------------------------------------------------------- +// Reload triggers: the engine's named event, and the canonical DLL changing on disk +// --------------------------------------------------------------------------- + +static DWORD WINAPI ReloadWatcher(LPVOID unused) +{ + (void)unused; + for (;;) { + if (WaitForSingleObject(g_reloadEvent, INFINITE) != WAIT_OBJECT_0) { Sleep(100); continue; } + + ULONGLONG last = g_lastReloadDone; + if (last != 0 && GetTickCount64() - last < MIN_RELOAD_INTERVAL_MS) { + LoaderLog("INF", "ReloadWatcher: signal %llu ms after the last reload; coalesced.", GetTickCount64() - last); + continue; + } + + long minFree = g_engineIsManaged ? MIN_FREE_MB_CLR : MIN_FREE_MB_AOT; + long freeMb = LoaderFreeAddressSpaceMb(NULL); + if (freeMb < minFree) { + LoaderLog("WRN", "ReloadWatcher: reload REFUSED - only %ld MB of address space free (need %ld MB). " + "Restart the client to load the new engine.", freeMb, minFree); + engine_refused_fn refused = (engine_refused_fn)EngineExport(ENGINE_REFUSED_EXPORT); + if (refused) refused((int)freeMb); + continue; + } + + if (InterlockedCompareExchange(&g_reloadInFlight, 1, 0) != 0) { + LoaderLog("INF", "ReloadWatcher: reload already in flight; coalesced."); + continue; + } + Reload(); + g_lastReloadDone = GetTickCount64(); + InterlockedExchange(&g_reloadInFlight, 0); + + int drained = 0; + while (WaitForSingleObject(g_reloadEvent, 0) == WAIT_OBJECT_0) drained++; + if (drained) LoaderLog("INF", "ReloadWatcher: drained %d signal(s) received during the reload.", drained); + } +} + +static DWORD WINAPI FileWatcher(LPVOID unused) +{ + (void)unused; + for (;;) { + Sleep(1000); + FILETIME now; + if (!FileLastWrite(g_enginePath, &now) || CompareFileTime(&now, &g_canonicalWrite) <= 0) continue; + // Let the writer (cp, dotnet publish) finish before staging from it. + Sleep(500); + FILETIME stable; + if (!FileLastWrite(g_enginePath, &stable) || CompareFileTime(&stable, &now) != 0) continue; + LoaderLog("INF", "FileWatcher: %s changed; signaling reload.", g_enginePath); + g_canonicalWrite = stable; + SetEvent(g_reloadEvent); + } +} + +// --------------------------------------------------------------------------- +// Exports +// --------------------------------------------------------------------------- + +const char* LoaderDirectory(void) { return g_loaderDir; } +int LoaderGeneration(void) { return g_initCount; } + +unsigned int __stdcall RynthCoreInit(void* param) +{ + (void)param; + if (InterlockedCompareExchange(&g_initialized, 1, 0) != 0) { + LoaderLog("WRN", "RynthCoreInit called twice; ignoring the second call."); + return 1; + } + + HMODULE self = NULL; + GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + (LPCSTR)&RynthCoreInit, &self); + GetModuleFileNameA(self, g_loaderDir, MAX_PATH); + char* slash = strrchr(g_loaderDir, '\\'); + if (slash) *slash = 0; + + LoaderLog("INF", "RynthCoreInit (native loader %s) starting in %s.", LOADER_VERSION, g_loaderDir); + { + // Test clients (tools\TestClient, scripts\Test-Clr*.ps1) say so first, so monitors can skip them. + char tag[128]; + if (GetEnvironmentVariableA("RYNTHCORE_TEST_CLIENT", tag, sizeof tag) > 0) + LoaderLog("INF", "TestClient: %s", tag); + } + + _snprintf_s(g_enginePath, sizeof g_enginePath, _TRUNCATE, "%s\\" ENGINE_DLL_NAME, g_loaderDir); + int managed = IsManagedPe(g_enginePath); + if (managed < 0) { + LoaderLog("ERR", "FATAL: engine DLL not found or unreadable at %s", g_enginePath); + return 3; + } + g_engineIsManaged = managed; + long largest; + long freeMb = LoaderFreeAddressSpaceMb(&largest); + LoaderLog("INF", "Engine is %s; %ld MB of address space free (largest %ld MB).", + managed ? "a managed assembly: hosting CoreCLR" : "NativeAOT", freeMb, largest); + + if (!HooksInit(g_loaderDir)) { + LoaderLog("ERR", "FATAL: MinHook could not be loaded from %s", g_loaderDir); + return 6; + } + if (managed) { + int rc = ClrStart(g_loaderDir); + if (rc != 0) { + LoaderLog("ERR", "FATAL: CoreCLR did not start (rc=%d)", rc); + return 7; + } + } + + unsigned int rc = LoadAndInitEngine(); + if (rc != 0) return rc; + + char eventName[128]; + _snprintf_s(eventName, sizeof eventName, _TRUNCATE, "Local\\RynthCore.Engine.RequestReload.p%lu", GetCurrentProcessId()); + g_reloadEvent = CreateEventA(NULL, FALSE, FALSE, eventName); + if (!g_reloadEvent) { + LoaderLog("WRN", "CreateEvent failed (error %lu); reload disabled.", GetLastError()); + return 0; + } + HANDLE t = CreateThread(NULL, 0, ReloadWatcher, NULL, 0, NULL); + if (t) CloseHandle(t); + t = CreateThread(NULL, 0, FileWatcher, NULL, 0, NULL); + if (t) CloseHandle(t); + LoaderLog("INF", "Reload watcher armed on '%s'; file watcher on '%s' (poll 1 s).", eventName, g_enginePath); + return 0; +} + +BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID reserved) +{ + (void)h; (void)reserved; + if (reason == DLL_PROCESS_ATTACH) { + InitializeCriticalSection(&g_logLock); + DisableThreadLibraryCalls(h); + } + return TRUE; +} diff --git a/native/Loader/Loader.def b/native/Loader/Loader.def new file mode 100644 index 0000000..ae7afd2 --- /dev/null +++ b/native/Loader/Loader.def @@ -0,0 +1,16 @@ +LIBRARY "RynthCore.Loader.dll" +EXPORTS + RynthCoreInit + MH_Initialize + MH_Uninitialize + MH_CreateHook + MH_RemoveHook + MH_EnableHook + MH_DisableHook + MH_StatusToString + RcHooks_Version + RcHooks_Count + RcSubclass_Install + RcSubclass_Release + RcApiStub + RcServices_Version diff --git a/native/Loader/Loader.h b/native/Loader/Loader.h new file mode 100644 index 0000000..f233b78 --- /dev/null +++ b/native/Loader/Loader.h @@ -0,0 +1,26 @@ +#pragma once +#define WIN32_LEAN_AND_MEAN +#include <windows.h> + +#define LOADER_VERSION "2.0" + +// Loader.c +void LoaderLog(const char* level, const char* fmt, ...); +long LoaderFreeAddressSpaceMb(long* largestMb); +const char* LoaderDirectory(void); +int LoaderGeneration(void); + +// Hooks.c: MinHook facade (see the header comment there) +int HooksInit(const char* loaderDir); +void HooksBeginGeneration(int generation); +void HooksPassThroughAll(void); +void HooksFlush(void); + +// Services.c: permanent window subclass + plugin API stubs +void ServicesReleaseAll(void); + +// Clr.c: CoreCLR host for a managed engine +int ClrStart(const char* loaderDir); +int ClrLoadEngine(int generation, const char* stagedPath); +void ClrUnloadEngine(void); +void* ClrEngineExport(const char* name); diff --git a/native/Loader/Services.c b/native/Loader/Services.c new file mode 100644 index 0000000..d740329 --- /dev/null +++ b/native/Loader/Services.c @@ -0,0 +1,176 @@ +// ============================================================================ +// Services.c - the other native entry points the engine hands out, made permanent +// (docs/UNLOADABLE_ENGINE_PLAN.md: "nothing native points into collectible code"). +// +// 1. Window subclass: RcSubclass_Install puts the loader's own WndProc on a window, +// once for the life of the process, and forwards to the current engine's handler. +// RcSubclass_Release (and every reload) makes it a pure pass-through to the window's +// previous proc. The engine never has to unhook, so a foreign subclasser stacked on +// top of us (Decal, DirectInput) can never be ripped out of the chain, and nothing +// in the chain ever points at an unloaded engine. +// +// 2. Plugin API stubs: RcApiStub(index, fn) returns a permanent stub for table slot +// `index` that jumps to `fn`. Plugins copy the table and can't give it back; after a +// reload the slots are empty until the next engine fills them, and a plugin thread +// that calls one in between waits (any calling convention: registers and stack are +// untouched) and then runs the new engine's function. +// ============================================================================ + +#include "Loader.h" + +// --- 1. window subclass -------------------------------------------------------- + +#define MAX_SUBCLASSED 16 + +typedef LRESULT (CALLBACK *wndproc_fn)(HWND, UINT, WPARAM, LPARAM); + +typedef struct Subclass { + HWND hwnd; + WNDPROC previous; // the proc we replaced (AC's, or whoever was there) + wndproc_fn volatile handler; // current engine's handler, or NULL = pass-through +} Subclass; + +static Subclass g_subclassed[MAX_SUBCLASSED]; +static volatile LONG g_subclassCount; +static CRITICAL_SECTION g_servicesLock; +static int g_servicesReady; + +static void EnsureServices(void) +{ + if (!g_servicesReady) { + InitializeCriticalSection(&g_servicesLock); + g_servicesReady = 1; + } +} + +static Subclass* FindSubclass(HWND hwnd) +{ + LONG n = g_subclassCount; + for (LONG i = 0; i < n; i++) + if (g_subclassed[i].hwnd == hwnd) return &g_subclassed[i]; + return NULL; +} + +static LRESULT CALLBACK LoaderWndProc(HWND hwnd, UINT msg, WPARAM w, LPARAM l) +{ + Subclass* s = FindSubclass(hwnd); + if (!s) return DefWindowProcA(hwnd, msg, w, l); + wndproc_fn h = s->handler; + if (h) return h(hwnd, msg, w, l); + return CallWindowProcA(s->previous, hwnd, msg, w, l); +} + +// Returns 1 and the window's previous proc (what the engine's handler must forward to). +int __stdcall RcSubclass_Install(HWND hwnd, void* handler, void** previousOut) +{ + EnsureServices(); + int ok = 1; + EnterCriticalSection(&g_servicesLock); + Subclass* s = FindSubclass(hwnd); + if (!s) { + if (g_subclassCount >= MAX_SUBCLASSED) ok = 0; + else { + s = &g_subclassed[g_subclassCount]; + s->hwnd = hwnd; + s->handler = NULL; + SetLastError(0); + s->previous = (WNDPROC)SetWindowLongA(hwnd, GWL_WNDPROC, (LONG)(LONG_PTR)LoaderWndProc); + if (!s->previous) { + LoaderLog("ERR", "Subclass: SetWindowLong on 0x%p failed (error %lu)", (void*)hwnd, GetLastError()); + ok = 0; + } else { + InterlockedIncrement(&g_subclassCount); + LoaderLog("INF", "Subclass: 0x%p subclassed for good (previous proc 0x%p).", (void*)hwnd, (void*)s->previous); + } + } + } + if (ok) { + s->handler = (wndproc_fn)handler; + if (previousOut) *previousOut = (void*)s->previous; + } + LeaveCriticalSection(&g_servicesLock); + return ok; +} + +int __stdcall RcSubclass_Release(HWND hwnd) +{ + Subclass* s = FindSubclass(hwnd); + if (!s) return 0; + s->handler = NULL; + return 1; +} + +// --- 2. plugin API stubs -------------------------------------------------------- + +#define MAX_API_STUBS 512 +#define API_STUB_SIZE 32 + +static void* volatile g_apiSlots[MAX_API_STUBS]; +static unsigned char* g_apiStubs; +static volatile LONG g_apiWaitLogged; + +// Called from a stub whose slot is empty (between engine generations). Blocks until the +// next engine fills the table. stdcall, one argument; the stub saves every register. +static void __stdcall ApiWait(int index) +{ + DWORD start = GetTickCount(); + int logged = 0; + while (g_apiSlots[index] == NULL) { + Sleep(10); + if (!logged && GetTickCount() - start > 10000) { + logged = 1; + LoaderLog("WRN", "ApiStub: a plugin thread has waited 10 s for API slot %d (no engine loaded?).", index); + } + } +} + +static void BuildApiStub(int i) +{ + unsigned char* p = g_apiStubs + i * API_STUB_SIZE; + unsigned char* start = p; + void* volatile* slot = &g_apiSlots[i]; + *p++ = 0xA1; *(void* volatile**)p = slot; p += 4; // mov eax, [slot] + *p++ = 0x85; *p++ = 0xC0; // test eax, eax + *p++ = 0x74; *p++ = 0x02; // jz +2 (wait) + *p++ = 0xFF; *p++ = 0xE0; // jmp eax + *p++ = 0x60; // pushad + *p++ = 0x68; *(int*)p = i; p += 4; // push i + *p++ = 0xE8; *(int*)p = (int)((unsigned char*)ApiWait - (p + 4)); p += 4; // call ApiWait + *p++ = 0x61; // popad + *p++ = 0xE9; *(int*)p = (int)(start - (p + 4)); p += 4; // jmp start + while (p < start + API_STUB_SIZE) *p++ = 0xCC; +} + +void* __stdcall RcApiStub(int index, void* fn) +{ + EnsureServices(); + if (index < 0 || index >= MAX_API_STUBS) return fn; + EnterCriticalSection(&g_servicesLock); + if (!g_apiStubs) { + g_apiStubs = (unsigned char*)VirtualAlloc(NULL, MAX_API_STUBS * API_STUB_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + if (g_apiStubs) { + for (int i = 0; i < MAX_API_STUBS; i++) BuildApiStub(i); + FlushInstructionCache(GetCurrentProcess(), g_apiStubs, MAX_API_STUBS * API_STUB_SIZE); + } + } + LeaveCriticalSection(&g_servicesLock); + if (!g_apiStubs) return fn; + // Already one of ours (a table wrapped twice): never point a slot at a stub. + if ((unsigned char*)fn >= g_apiStubs && (unsigned char*)fn < g_apiStubs + MAX_API_STUBS * API_STUB_SIZE) + return fn; + InterlockedExchangePointer((PVOID volatile*)&g_apiSlots[index], fn); + return g_apiStubs + index * API_STUB_SIZE; +} + +// Every reload: nothing we hand out may keep pointing into the old engine. +void ServicesReleaseAll(void) +{ + EnsureServices(); + EnterCriticalSection(&g_servicesLock); + for (LONG i = 0; i < g_subclassCount; i++) g_subclassed[i].handler = NULL; + for (int i = 0; i < MAX_API_STUBS; i++) g_apiSlots[i] = NULL; + LeaveCriticalSection(&g_servicesLock); + LoaderLog("INF", "Services: %ld window subclass(es) pass through, plugin API slots emptied until the next engine.", g_subclassCount); +} + +int __stdcall RcServices_Version(void) { return 1; } diff --git a/native/cimgui/.gitattributes b/native/cimgui/.gitattributes new file mode 100644 index 0000000..eaaa0b2 --- /dev/null +++ b/native/cimgui/.gitattributes @@ -0,0 +1,2 @@ +# Applied with git apply to an LF checkout: keep the bytes as committed. +*.patch -text diff --git a/native/cimgui/.gitignore b/native/cimgui/.gitignore new file mode 100644 index 0000000..fe0ee83 --- /dev/null +++ b/native/cimgui/.gitignore @@ -0,0 +1,3 @@ +_src/ +_build/ +_textedit/ diff --git a/native/cimgui/CMakeLists.txt b/native/cimgui/CMakeLists.txt new file mode 100644 index 0000000..ca30a0f --- /dev/null +++ b/native/cimgui/CMakeLists.txt @@ -0,0 +1,47 @@ +# RynthCore cimgui build: upstream cimgui 1.91.6dock (fetched into _src by +# scripts/Build-Cimgui.ps1) plus rynth_imconfig.h and rynth_cimgui_ext.cpp, +# and ImGuiColorTextEdit (fetched into _textedit, patched by +# textedit-rynth.patch) with its C exports in rynth_textedit_ext.cpp. +# Output: a 32-bit cimgui.dll whose structs match ImGui.NET 1.91.6.1. +cmake_minimum_required(VERSION 3.15) +cmake_policy(SET CMP0091 NEW) +project(rynth_cimgui CXX) + +set(CMAKE_CXX_STANDARD 17) +# Static CRT, like the stock ImGui.NET native build: no VC++ redistributable needed. +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") + +set(SRC ${CMAKE_CURRENT_SOURCE_DIR}/_src) +set(TEXTEDIT ${CMAKE_CURRENT_SOURCE_DIR}/_textedit) + +add_library(cimgui SHARED + ${SRC}/cimgui.cpp + ${SRC}/imgui/imgui.cpp + ${SRC}/imgui/imgui_draw.cpp + ${SRC}/imgui/imgui_demo.cpp + ${SRC}/imgui/imgui_tables.cpp + ${SRC}/imgui/imgui_widgets.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rynth_cimgui_ext.cpp + ${TEXTEDIT}/TextEditor.cpp + ${TEXTEDIT}/LanguageDefinitions.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rynth_textedit_ext.cpp +) + +# Same defines as upstream cimgui's CMakeLists, except the user config. +target_compile_definitions(cimgui PRIVATE + IMGUI_USER_CONFIG=\"rynth_imconfig.h\" + IMGUI_DISABLE_OBSOLETE_FUNCTIONS=1 + "IMGUI_IMPL_API=extern \"C\" __declspec(dllexport)" +) +target_include_directories(cimgui PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + ${SRC} + ${SRC}/imgui + ${TEXTEDIT} + ${CMAKE_CURRENT_SOURCE_DIR}/textedit_shim +) +# ImGuiColorTextEdit uses std::string/printf-style code MSVC warns about. +set_source_files_properties(${TEXTEDIT}/TextEditor.cpp ${TEXTEDIT}/LanguageDefinitions.cpp + PROPERTIES COMPILE_OPTIONS "/wd4244;/wd4267;/wd4018;/wd4305") +set_target_properties(cimgui PROPERTIES PREFIX "") +target_link_libraries(cimgui imm32) diff --git a/native/cimgui/rynth_cimgui_ext.cpp b/native/cimgui/rynth_cimgui_ext.cpp new file mode 100644 index 0000000..3dc6e0e --- /dev/null +++ b/native/cimgui/rynth_cimgui_ext.cpp @@ -0,0 +1,118 @@ +// ============================================================================ +// RynthCore cimgui build - extra exports compiled into cimgui.dll. +// +// RynthImGui_BuildTag identifies this build (the engine refuses others). +// RynthImGui_GetLayout sizes/offsets/enum counts the engine compares +// against ImGui.NET's structs before creating a +// context (see ImGuiSelfTest.cs; same index order). +// RynthImGui_ReportAssert IM_ASSERT target (rynth_imconfig.h); records into +// a ring buffer the engine polls from AC's thread. +// ============================================================================ + +#include "imgui.h" +#include <stddef.h> +#include <stdio.h> +#include <string.h> + +#define RYNTH_EXPORT extern "C" __declspec(dllexport) + +// ---- Build tag ------------------------------------------------------------- +// Bump the trailing number whenever the layout table or config changes. +RYNTH_EXPORT const char* RynthImGui_BuildTag(void) +{ + return "rynth-cimgui 1.91.6dock ImTextureID=void* soft-assert layout-1 textedit-264bee4"; +} + +// ---- Layout table ------------------------------------------------------------ +// Index order is a contract with ImGuiSelfTest.ExpectedLayout(); append only. +RYNTH_EXPORT int RynthImGui_GetLayout(int* out, int capacity) +{ + const int values[] = + { + 1, // 0 table version + (int)sizeof(ImTextureID), // 1 + (int)sizeof(ImWchar), // 2 + (int)sizeof(ImDrawIdx), // 3 + (int)sizeof(ImDrawVert), // 4 + (int)sizeof(ImDrawCmd), // 5 + (int)offsetof(ImDrawCmd, TextureId), // 6 + (int)offsetof(ImDrawCmd, VtxOffset), // 7 + (int)offsetof(ImDrawCmd, IdxOffset), // 8 + (int)offsetof(ImDrawCmd, ElemCount), // 9 + (int)offsetof(ImDrawCmd, UserCallback), // 10 + (int)sizeof(ImDrawList), // 11 + (int)offsetof(ImDrawList, VtxBuffer), // 12 + (int)sizeof(ImDrawData), // 13 + (int)offsetof(ImDrawData, CmdLists), // 14 + (int)offsetof(ImDrawData, DisplayPos), // 15 + (int)offsetof(ImDrawData, DisplaySize), // 16 + (int)sizeof(ImFontAtlas), // 17 + (int)offsetof(ImFontAtlas, TexID), // 18 + (int)sizeof(ImFont), // 19 + (int)sizeof(ImFontGlyph), // 20 + (int)sizeof(ImFontConfig), // 21 + (int)sizeof(ImGuiIO), // 22 + (int)offsetof(ImGuiIO, Fonts), // 23 + (int)offsetof(ImGuiIO, WantCaptureMouse), // 24 + (int)offsetof(ImGuiIO, WantTextInput), // 25 + (int)sizeof(ImGuiStyle), // 26 + (int)sizeof(ImGuiViewport), // 27 + (int)sizeof(ImGuiPlatformIO), // 28 + (int)sizeof(ImGuiInputTextCallbackData), // 29 + (int)sizeof(ImGuiListClipper), // 30 + (int)sizeof(ImGuiPayload), // 31 + (int)sizeof(ImGuiTableSortSpecs), // 32 + (int)sizeof(ImGuiTableColumnSortSpecs), // 33 + (int)sizeof(ImGuiStorage), // 34 + (int)sizeof(ImGuiWindowClass), // 35 + (int)sizeof(ImGuiSizeCallbackData), // 36 + (int)ImGuiCol_COUNT, // 37 + (int)ImGuiKey_NamedKey_END, // 38 + (int)ImGuiStyleVar_COUNT, // 39 + (int)ImGuiMouseCursor_COUNT, // 40 + }; + const int count = (int)(sizeof(values) / sizeof(values[0])); + if (out != NULL) + for (int i = 0; i < count && i < capacity; i++) + out[i] = values[i]; + return count; +} + +// ---- Soft asserts ------------------------------------------------------------ +// ImGui runs on one thread (AC's render thread); the engine polls on the same +// thread, so plain statics are enough. The ring keeps the last 16 failures. +static const int kAssertSlots = 16; +static const int kAssertTextLen = 256; +static int g_assertCount; +static char g_assertText[kAssertSlots][kAssertTextLen]; + +extern "C" void RynthImGui_ReportAssert(const char* expr, const char* file, int line) +{ + const char* base = file; + for (const char* p = file; *p; p++) + if (*p == '\\' || *p == '/') + base = p + 1; + char* slot = g_assertText[g_assertCount % kAssertSlots]; + _snprintf_s(slot, kAssertTextLen, _TRUNCATE, "%s:%d: %s", base, line, expr); + g_assertCount++; +} + +// Total failures since load (monotonic; wraps only after 2^31). +RYNTH_EXPORT int RynthImGui_GetAssertCount(void) +{ + return g_assertCount; +} + +// Copies failure number `index` (0-based, < count) into buf. Returns the +// length copied, or -1 when that entry was already overwritten or not yet made. +RYNTH_EXPORT int RynthImGui_GetAssertText(int index, char* buf, int capacity) +{ + if (buf == NULL || capacity <= 0 || index < 0 || index >= g_assertCount || index < g_assertCount - kAssertSlots) + return -1; + const char* src = g_assertText[index % kAssertSlots]; + int len = (int)strnlen(src, kAssertTextLen); + if (len >= capacity) len = capacity - 1; + memcpy(buf, src, (size_t)len); + buf[len] = '\0'; + return len; +} diff --git a/native/cimgui/rynth_imconfig.h b/native/cimgui/rynth_imconfig.h new file mode 100644 index 0000000..ea07092 --- /dev/null +++ b/native/cimgui/rynth_imconfig.h @@ -0,0 +1,26 @@ +// ============================================================================ +// RynthCore cimgui build - Dear ImGui user config (IMGUI_USER_CONFIG). +// Replaces upstream cimgui's cimconfig.h (which only did #undef NDEBUG). +// ============================================================================ +#pragma once + +// ImGui.NET 1.91.6.1 declares ImTextureID as IntPtr (pointer-sized). Dear ImGui +// 1.91.4+ defaults it to ImU64, which on x86 makes ImDrawCmd, ImDrawList and +// ImFontAtlas wider than ImGui.NET's structs and shifts every by-value texture +// argument (SetTexID, Image, AddImage, ...). This is why the stock NuGet x86 +// cimgui.dll does not match its own wrapper. A named typedef (not a bare +// "void*" macro) keeps functional casts like ImTextureID() valid. +typedef void* RynthImTextureID; +#define ImTextureID RynthImTextureID + +// Soft asserts. A failed IM_ASSERT is recorded in a small native ring buffer +// (rynth_cimgui_ext.cpp) that the engine polls and logs; control flow then +// continues exactly as in a release build with asserts compiled out. The +// handler never calls into managed code (a managed exception inside a native +// frame fail-fasts the process). +#ifdef __cplusplus +extern "C" +#endif +void RynthImGui_ReportAssert(const char* expr, const char* file, int line); + +#define IM_ASSERT(_EXPR) do { if (!(_EXPR)) RynthImGui_ReportAssert(#_EXPR, __FILE__, __LINE__); } while (0) diff --git a/native/cimgui/rynth_textedit_ext.cpp b/native/cimgui/rynth_textedit_ext.cpp new file mode 100644 index 0000000..20b85a1 --- /dev/null +++ b/native/cimgui/rynth_textedit_ext.cpp @@ -0,0 +1,308 @@ +// ============================================================================ +// RynthCore cimgui build - C exports for ImGuiColorTextEdit (santaclose fork, +// fetched into _textedit and patched by textedit-rynth.patch). +// +// The engine P/Invokes these by hand (ImGui/TextEditorNative.cs). Every call +// is made on AC's render thread inside an ImGui frame (Create reads the style, +// so it needs a current context too). Strings are UTF-8; returned pointers +// stay valid until the next call of the same export. +// +// Languages: 1 = Meta (.af source: coloured by the tokenizer below from the +// vocabulary the engine passes in), 2 = Lua (the fork's own definition). +// ============================================================================ + +#include <algorithm> +#include <string> +#include <unordered_set> +#include "TextEditor.h" + +#define RYNTH_EXPORT extern "C" __declspec(dllexport) + +struct RynthTextEditAccess +{ + typedef TextEditor::PaletteIndex PI; + + static std::unordered_set<std::string>& StructWords() { static std::unordered_set<std::string> s; return s; } + static std::unordered_set<std::string>& ConditionWords() { static std::unordered_set<std::string> s; return s; } + static std::unordered_set<std::string>& ActionWords() { static std::unordered_set<std::string> s; return s; } + + static bool IsWordStart(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; } + static bool IsDigit(char c) { return c >= '0' && c <= '9'; } + static bool IsWordChar(char c) { return IsWordStart(c) || IsDigit(c); } + + // Mirrors MetaSourceEditor.MetaColorizer: "~~" comments to the end of the + // line, braces, numbers (hex and signed too), STATE:/IF:/DO:/NAV: (the + // colon included), condition keywords, action keywords. + static bool TokenizeMeta(const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end, PI& color) + { + while (in_begin < in_end && (*in_begin == ' ' || *in_begin == '\t')) + in_begin++; + if (in_begin == in_end) + { + out_begin = out_end = in_end; + color = PI::Default; + return true; + } + + const char* p = in_begin; + out_begin = p; + char c = *p; + + if (c == '~' && p + 1 < in_end && p[1] == '~') + { + out_end = in_end; + color = PI::Comment; + return true; + } + if (c == '{' || c == '}') + { + out_end = p + 1; + color = PI::Punctuation; + return true; + } + if (IsDigit(c) || (c == '-' && p + 1 < in_end && IsDigit(p[1]))) + { + p++; + while (p < in_end && (IsWordChar(*p) || *p == '.')) + p++; + out_end = p; + color = PI::Number; + return true; + } + if (IsWordStart(c)) + { + p++; + while (p < in_end && IsWordChar(*p)) + p++; + std::string word(in_begin, p); + std::transform(word.begin(), word.end(), word.begin(), [](char ch) { return (char)::toupper((unsigned char)ch); }); + color = PI::Default; + if (p < in_end && *p == ':' && StructWords().count(word) != 0) + { + p++; + color = PI::Keyword; + } + else if (ConditionWords().count(word) != 0) + color = PI::KnownIdentifier; + else if (ActionWords().count(word) != 0) + color = PI::PreprocIdentifier; + out_end = p; + return true; + } + + // Anything else (punctuation, UTF-8 bytes): one byte, default colour. + out_end = p + 1; + color = PI::Default; + return true; + } + + static const TextEditor::LanguageDefinition& MetaLanguage() + { + static TextEditor::LanguageDefinition def; + static bool built = false; + if (!built) + { + built = true; + def.mName = "Meta"; + def.mTokenize = &TokenizeMeta; + def.mSingleLineComment = "~~"; // Ctrl+/ toggles "~~" + // An empty block-comment start matches everywhere in ColorizeInternal, + // so give it one that never occurs in text. + def.mCommentStart = "\x01\x02"; + def.mCommentEnd = "\x02\x01"; + def.mPreprocChar = '\x01'; + def.mCaseSensitive = false; + def.mTokenizerOwnsComments = true; // TokenizeMeta colours "~~" itself + } + return def; + } + + static void SetLanguage(TextEditor* ed, int language) + { + if (language == 1) + { + ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::None); + ed->mLanguageDefinition = &MetaLanguage(); + ed->Colorize(); + } + else if (language == 2) + ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::Lua); + else + ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::None); + } + + static void SetPalette(TextEditor* ed, const ImU32* colors, int count) + { + int n = std::min(count, (int)PI::Max); + for (int i = 0; i < n; i++) + ed->mPalette[i] = colors[i]; + } + + static void CursorScreenPos(TextEditor* ed, float* x, float* y) + { + TextEditor::Coordinates at = ed->GetSanitizedCursorCoordinates(); + *x = ed->mTextOrigin.x + ed->mTextStart + ed->TextDistanceToLineStart(at); + *y = ed->mTextOrigin.y + (at.mLine + 1) * ed->mCharAdvance.y; + } + + static std::string LinePrefix(TextEditor* ed) + { + TextEditor::Coordinates at = ed->GetSanitizedCursorCoordinates(); + return ed->GetText(TextEditor::Coordinates(at.mLine, 0), at); + } + + // Completion: replace the `bytes` characters before the cursor with `text`, + // as one undo step. + static void ReplaceBeforeCursor(TextEditor* ed, int bytes, const char* text) + { + if (ed->mReadOnly) + return; + ed->ClearExtraCursors(); + ed->ClearSelections(); + TextEditor::Coordinates end = ed->GetSanitizedCursorCoordinates(); + int endIndex = ed->GetCharacterIndexR(end); + int startIndex = std::max(0, endIndex - std::max(0, bytes)); + TextEditor::Coordinates start(end.mLine, ed->GetCharacterColumn(end.mLine, startIndex)); + + TextEditor::UndoRecord u; + u.mBefore = ed->mState; + if (start < end) + { + ed->SetSelection(start, end); + u.mOperations.push_back({ ed->GetSelectedText(), start, end, TextEditor::UndoOperationType::Delete }); + ed->DeleteSelection(); + } + TextEditor::Coordinates insertAt = ed->GetSanitizedCursorCoordinates(); + ed->InsertTextAtCursor(text); + u.mOperations.push_back({ std::string(text), insertAt, ed->GetSanitizedCursorCoordinates(), TextEditor::UndoOperationType::Add }); + u.mAfter = ed->mState; + ed->AddUndo(u); + } +}; + +static void FillWordSet(std::unordered_set<std::string>& set, const char* words) +{ + set.clear(); + if (words == nullptr) + return; + std::string current; + for (const char* p = words;; p++) + { + if (*p == '\n' || *p == '\0') + { + if (!current.empty()) + set.insert(current); + current.clear(); + if (*p == '\0') + break; + } + else + current.push_back((char)::toupper((unsigned char)*p)); + } +} + +RYNTH_EXPORT TextEditor* RynthTE_Create(void) +{ + TextEditor* ed = new TextEditor(); + ed->SetShowWhitespacesEnabled(false); + return ed; +} + +RYNTH_EXPORT void RynthTE_Destroy(TextEditor* ed) +{ + delete ed; +} + +/// Newline-separated words, matched case-insensitively. Applies to every Meta editor. +RYNTH_EXPORT void RynthTE_SetMetaVocabulary(const char* structWords, const char* conditionWords, const char* actionWords) +{ + FillWordSet(RynthTextEditAccess::StructWords(), structWords); + FillWordSet(RynthTextEditAccess::ConditionWords(), conditionWords); + FillWordSet(RynthTextEditAccess::ActionWords(), actionWords); +} + +RYNTH_EXPORT void RynthTE_SetLanguage(TextEditor* ed, int language) +{ + RynthTextEditAccess::SetLanguage(ed, language); +} + +/// `count` ImU32 colours in TextEditor::PaletteIndex order. +RYNTH_EXPORT void RynthTE_SetPalette(TextEditor* ed, const ImU32* colors, int count) +{ + RynthTextEditAccess::SetPalette(ed, colors, count); +} + +RYNTH_EXPORT void RynthTE_SetOptions(TextEditor* ed, int readOnly, int showWhitespaces, int showLineNumbers, int tabSize) +{ + ed->SetReadOnlyEnabled(readOnly != 0); + ed->SetShowWhitespacesEnabled(showWhitespaces != 0); + ed->SetShowLineNumbersEnabled(showLineNumbers != 0); + ed->SetTabSize(tabSize); +} + +RYNTH_EXPORT void RynthTE_SetText(TextEditor* ed, const char* utf8) +{ + ed->SetText(utf8 != nullptr ? std::string(utf8) : std::string()); +} + +RYNTH_EXPORT const char* RynthTE_GetText(TextEditor* ed, int* length) +{ + static std::string text; + text = ed->GetText(); + if (length != nullptr) + *length = (int)text.size(); + return text.c_str(); +} + +RYNTH_EXPORT unsigned RynthTE_GetChangeCount(TextEditor* ed) +{ + return ed->GetChangeCount(); +} + +/// Draws the editor as a child window; returns whether it has keyboard focus. +RYNTH_EXPORT int RynthTE_Render(TextEditor* ed, const char* id, float width, float height, int border) +{ + return ed->Render(id, false, ImVec2(width, height), border != 0) ? 1 : 0; +} + +RYNTH_EXPORT void RynthTE_GetCursor(TextEditor* ed, int* line, int* column) +{ + ed->GetCursorPosition(*line, *column); +} + +RYNTH_EXPORT void RynthTE_SetCursor(TextEditor* ed, int line, int charIndex) +{ + ed->SetCursorPosition(line, charIndex); +} + +/// Screen position of the bottom-left corner of the cursor's cell (valid after Render). +RYNTH_EXPORT void RynthTE_GetCursorScreenPos(TextEditor* ed, float* x, float* y) +{ + RynthTextEditAccess::CursorScreenPos(ed, x, y); +} + +/// The cursor's line up to the cursor. +RYNTH_EXPORT const char* RynthTE_GetLinePrefix(TextEditor* ed, int* length) +{ + static std::string prefix; + prefix = RynthTextEditAccess::LinePrefix(ed); + if (length != nullptr) + *length = (int)prefix.size(); + return prefix.c_str(); +} + +RYNTH_EXPORT void RynthTE_ReplaceBeforeCursor(TextEditor* ed, int bytes, const char* utf8) +{ + RynthTextEditAccess::ReplaceBeforeCursor(ed, bytes, utf8 != nullptr ? utf8 : ""); +} + +/// While set, the editor ignores Up/Down/PageUp/PageDown/Enter/Tab/Escape (the host's completion list uses them). +RYNTH_EXPORT void RynthTE_SetCompletionKeysHeld(TextEditor* ed, int held) +{ + ed->SetCompletionKeysHeld(held != 0); +} + +RYNTH_EXPORT void RynthTE_RequestFocus(TextEditor* ed) +{ + ed->RequestFocus(); +} diff --git a/native/cimgui/textedit-rynth.patch b/native/cimgui/textedit-rynth.patch new file mode 100644 index 0000000..4c71d83 --- /dev/null +++ b/native/cimgui/textedit-rynth.patch @@ -0,0 +1,129 @@ +diff --git a/TextEditor.cpp b/TextEditor.cpp +index 013111f..9cd55a1 100644 +--- a/TextEditor.cpp ++++ b/TextEditor.cpp +@@ -325,13 +325,19 @@ void TextEditor::Paste() + void TextEditor::Undo(int aSteps) + { + while (CanUndo() && aSteps-- > 0) ++ { + mUndoBuffer[--mUndoIndex].Undo(this); ++ ++mChangeCount; ++ } + } + + void TextEditor::Redo(int aSteps) + { + while (CanRedo() && aSteps-- > 0) ++ { + mUndoBuffer[mUndoIndex++].Redo(this); ++ ++mChangeCount; ++ } + } + + void TextEditor::SetText(const std::string& aText) +@@ -355,6 +361,7 @@ void TextEditor::SetText(const std::string& aText) + + mUndoBuffer.clear(); + mUndoIndex = 0; ++ ++mChangeCount; + + Colorize(); + } +@@ -392,6 +399,7 @@ void TextEditor::SetTextLines(const std::vector<std::string>& aLines) + + mUndoBuffer.clear(); + mUndoIndex = 0; ++ ++mChangeCount; + + Colorize(); + } +@@ -428,6 +436,11 @@ bool TextEditor::Render(const char* aTitle, bool aParentIsFocused, const ImVec2& + + ImGui::BeginChild(aTitle, aSize, aBorder, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNavInputs); + ++ if (mFocusRequested) ++ { ++ ImGui::SetWindowFocus(); ++ mFocusRequested = false; ++ } + bool isFocused = ImGui::IsWindowFocused(); + HandleKeyboardInputs(aParentIsFocused); + HandleMouseInputs(); +@@ -1993,7 +2006,12 @@ void TextEditor::HandleKeyboardInputs(bool aParentIsFocused) + io.WantCaptureKeyboard = true; + io.WantTextInput = true; + +- if (!mReadOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Z)) ++ if (mCompletionKeysHeld && (ImGui::IsKeyPressed(ImGuiKey_UpArrow) || ImGui::IsKeyPressed(ImGuiKey_DownArrow) || ++ ImGui::IsKeyPressed(ImGuiKey_PageUp) || ImGui::IsKeyPressed(ImGuiKey_PageDown) || ++ ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter) || ++ ImGui::IsKeyPressed(ImGuiKey_Tab) || ImGui::IsKeyPressed(ImGuiKey_Escape))) ++ ; // the host's completion list owns these keys ++ else if (!mReadOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Z)) + Undo(); + else if (!mReadOnly && isAltOnly && ImGui::IsKeyPressed(ImGuiKey_Backspace)) + Undo(); +@@ -2238,6 +2256,7 @@ void TextEditor::Render(bool aParentIsFocused) + } + + ImVec2 cursorScreenPos = ImGui::GetCursorScreenPos(); ++ mTextOrigin = cursorScreenPos; + mScrollX = ImGui::GetScrollX(); + mScrollY = ImGui::GetScrollY(); + UpdateViewVariables(mScrollX, mScrollY); +@@ -2549,6 +2568,7 @@ void TextEditor::AddUndo(UndoRecord& aValue) + mUndoBuffer.resize((size_t)(mUndoIndex + 1)); + mUndoBuffer.back() = aValue; + ++mUndoIndex; ++ ++mChangeCount; + } + + // TODO +@@ -2687,6 +2707,8 @@ void TextEditor::ColorizeInternal() + if (mLines.empty() || mLanguageDefinition == nullptr) + return; + ++ if (mCheckComments && mLanguageDefinition->mTokenizerOwnsComments) ++ mCheckComments = false; + if (mCheckComments) + { + auto endLine = mLines.size(); +diff --git a/TextEditor.h b/TextEditor.h +index 19ad61b..6883412 100644 +--- a/TextEditor.h ++++ b/TextEditor.h +@@ -97,6 +97,14 @@ public: + void ImGuiDebugPanel(const std::string& panelName = "Debug"); + void UnitTests(); + ++ // RynthCore (native/cimgui/textedit-rynth.patch): a text change counter, a ++ // hold-off on the keys the host's completion list uses, a focus request, ++ // and access for the C exports in rynth_textedit_ext.cpp. ++ inline unsigned GetChangeCount() const { return mChangeCount; } ++ inline void SetCompletionKeysHeld(bool aValue) { mCompletionKeysHeld = aValue; } ++ inline void RequestFocus() { mFocusRequested = true; } ++ friend struct RynthTextEditAccess; ++ + private: + // ------------- Generic utils ------------- // + +@@ -280,6 +288,7 @@ private: + TokenizeCallback mTokenize = nullptr; + std::vector<TokenRegexString> mTokenRegexStrings; + bool mCaseSensitive = true; ++ bool mTokenizerOwnsComments = false; // RynthCore: skip the whole-text comment scan + + static const LanguageDefinition& Cpp(); + static const LanguageDefinition& Hlsl(); +@@ -452,6 +461,10 @@ private: + Palette mPalette; + LanguageDefinitionId mLanguageDefinitionId; + const LanguageDefinition* mLanguageDefinition = nullptr; ++ unsigned mChangeCount = 0; ++ bool mCompletionKeysHeld = false; ++ bool mFocusRequested = false; ++ ImVec2 mTextOrigin; + + inline bool IsHorizontalScrollbarVisible() const { return mCurrentSpaceWidth > mContentWidth; } + inline bool IsVerticalScrollbarVisible() const { return mCurrentSpaceHeight > mContentHeight; } diff --git a/native/cimgui/textedit_shim/boost/regex.hpp b/native/cimgui/textedit_shim/boost/regex.hpp new file mode 100644 index 0000000..1cde777 --- /dev/null +++ b/native/cimgui/textedit_shim/boost/regex.hpp @@ -0,0 +1,13 @@ +// RynthCore: ImGuiColorTextEdit (santaclose fork) includes <boost/regex.hpp>. +// Its regex path only runs for languages without a hand-written tokenizer, and +// the two we use (Meta, Lua) both have one, so std::regex stands in for Boost. +#pragma once +#include <regex> + +namespace boost +{ + using std::regex; + using std::cmatch; + using std::regex_search; + namespace regex_constants = std::regex_constants; +} diff --git a/scripts/Build-Cimgui.ps1 b/scripts/Build-Cimgui.ps1 new file mode 100644 index 0000000..3154a99 --- /dev/null +++ b/scripts/Build-Cimgui.ps1 @@ -0,0 +1,93 @@ +<# +.SYNOPSIS + Builds the engine's 32-bit cimgui.dll from pinned upstream sources. + +.DESCRIPTION + Fetches cimgui at tag 1.91.6dock (and its Dear ImGui submodule) into + native\cimgui\_src, verifies both commits, fetches ImGuiColorTextEdit + (santaclose fork, the Meta/Lua source editor) into native\cimgui\_textedit + at a pinned commit and applies native\cimgui\textedit-rynth.patch, builds + with MSVC via CMake (Win32, Release, static CRT) using + native\cimgui\CMakeLists.txt, and copies + the result to src\RynthCore.Engine\Native\cimgui.dll. + + Why a custom build: ImGui.NET 1.91.6.1 treats ImTextureID as a pointer, + but Dear ImGui 1.91.6 defaults it to a 64-bit integer, so on x86 the stock + NuGet cimgui.dll does not match the wrapper (see native\cimgui\rynth_imconfig.h). + + Needs git and Visual Studio 2022 (Build Tools is enough) with the C++ + workload; CMake is taken from PATH or from the VS install. + +.PARAMETER Clean + Delete the CMake build directory first. +#> +[CmdletBinding()] +param( + [switch]$Clean +) + +$ErrorActionPreference = 'Stop' + +$Tag = '1.91.6dock' +$CimguiCommit = '970c614802935f51f451aa21ae06e838bdcf9349' +$ImguiCommit = '947aa9c9722bd6ff740dd757da609ff41f4d3ba3' +$TextEditCommit = '264bee49ddc3c789b05d928d09c628649458da47' + +$repoRoot = Split-Path -Parent $PSScriptRoot +$nativeDir = Join-Path $repoRoot 'native\cimgui' +$srcDir = Join-Path $nativeDir '_src' +$textEditDir = Join-Path $nativeDir '_textedit' +$textEditPatch = Join-Path $nativeDir 'textedit-rynth.patch' +$buildDir = Join-Path $nativeDir '_build' +$outDll = Join-Path $repoRoot 'src\RynthCore.Engine\Native\cimgui.dll' + +function Invoke-Checked([string]$What, [scriptblock]$Command) { + & $Command + if ($LASTEXITCODE -ne 0) { throw "$What failed (exit $LASTEXITCODE)" } +} + +# ---- Sources ---- +if (-not (Test-Path -LiteralPath $srcDir)) { + Write-Host "Fetching cimgui $Tag ..." + Invoke-Checked 'git clone' { git clone -q --depth 1 --branch $Tag --recurse-submodules --shallow-submodules https://github.com/cimgui/cimgui $srcDir } +} +$head = (git -C $srcDir rev-parse HEAD).Trim() +$imguiHead = (git -C (Join-Path $srcDir 'imgui') rev-parse HEAD).Trim() +if ($head -ne $CimguiCommit) { throw "native\cimgui\_src is at $head, expected $CimguiCommit ($Tag). Delete _src and rerun." } +if ($imguiHead -ne $ImguiCommit) { throw "native\cimgui\_src\imgui is at $imguiHead, expected $ImguiCommit. Delete _src and rerun." } + +# ImGuiColorTextEdit: no submodules (its Boost.Regex is replaced by +# textedit_shim\boost\regex.hpp). LF checkout so the committed patch applies. +if (-not (Test-Path -LiteralPath $textEditDir)) { + Write-Host "Fetching ImGuiColorTextEdit $TextEditCommit ..." + Invoke-Checked 'git clone (textedit)' { git -c core.autocrlf=false clone -q --no-checkout https://github.com/santaclose/ImGuiColorTextEdit $textEditDir } + Invoke-Checked 'git checkout (textedit)' { git -C $textEditDir -c core.autocrlf=false checkout -q $TextEditCommit } +} +$teHead = (git -C $textEditDir rev-parse HEAD).Trim() +if ($teHead -ne $TextEditCommit) { throw "native\cimgui\_textedit is at $teHead, expected $TextEditCommit. Delete _textedit and rerun." } +git -C $textEditDir apply --reverse --check $textEditPatch 2>$null +if ($LASTEXITCODE -ne 0) { + Invoke-Checked 'git apply (textedit patch)' { git -C $textEditDir apply $textEditPatch } +} + +# ---- CMake ---- +$cmake = (Get-Command cmake -ErrorAction SilentlyContinue).Source +if (-not $cmake) { + $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' + $vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath + if (-not $vs) { throw 'Visual Studio with the C++ x86/x64 tools was not found.' } + $cmake = Join-Path $vs 'Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe' + if (-not (Test-Path -LiteralPath $cmake)) { throw "CMake not found on PATH or at $cmake" } +} + +if ($Clean -and (Test-Path -LiteralPath $buildDir)) { Remove-Item -LiteralPath $buildDir -Recurse -Force } + +Invoke-Checked 'cmake configure' { & $cmake -S $nativeDir -B $buildDir -G 'Visual Studio 17 2022' -A Win32 } +Invoke-Checked 'cmake build' { & $cmake --build $buildDir --config Release } + +$built = Join-Path $buildDir 'Release\cimgui.dll' +if (-not (Test-Path -LiteralPath $built)) { throw "Build produced no $built" } + +Copy-Item -LiteralPath $built -Destination $outDll -Force +$size = (Get-Item -LiteralPath $outDll).Length +Write-Host "cimgui.dll ($size bytes) -> $outDll" diff --git a/scripts/Deploy-RynthCore.ps1 b/scripts/Deploy-RynthCore.ps1 index 74caba6..fa4f8f5 100644 --- a/scripts/Deploy-RynthCore.ps1 +++ b/scripts/Deploy-RynthCore.ps1 @@ -15,7 +15,13 @@ param( # -AcClient overrides the binary it checks (default: auto-detect the private # copy under $Destination\AcClient, else C:\Turbine\Asheron's Call). [switch]$SkipPatternCheck, - [string]$AcClient = "" + [string]$AcClient = "", + # The old deploy: NativeAOT loader, engine and plugins (a hot reload leaks every + # generation). The default since 2026-09-29 is the unloadable engine + # (docs/UNLOADABLE_ENGINE_PLAN.md): native loader + CoreCLR engine + app-local runtime + # in Runtime\ (scripts\Publish-EngineCoreClr.ps1), and managed plugins, all of which + # a hot reload frees. Releases (installer\) still ship NativeAOT: players run that engine. + [switch]$NativeAot ) $ErrorActionPreference = "Stop" @@ -38,7 +44,6 @@ $loaderProject = Join-Path $repoRoot "src\RynthCore.Loader\RynthCore.Loader.cspr $rynthAiSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi" $rynthChatSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthChat" $rynthVisionSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthVision" -$rynthJuiceSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthJuice" $pluginProjects = @( @{ Project = Join-Path $rynthAiSourceRoot "RynthCore.Plugin.RynthAi.csproj" @@ -67,15 +72,6 @@ $pluginProjects = @( DllName = "RynthCore.Plugin.RynthTracker.dll" DestSubdir = "RynthTracker" }, - # RynthJuice sets <PublishDir> to its deploy home (like RynthVision), so - # publish lands directly in $PluginsDestination\RynthJuice and the copy step - # below detects source == dest and skips the redundant self-copy. - @{ - Project = Join-Path $rynthJuiceSourceRoot "RynthCore.Plugin.RynthJuice.csproj" - Publish = Join-Path $PluginsDestination "RynthJuice" - DllName = "RynthCore.Plugin.RynthJuice.dll" - DestSubdir = "RynthJuice" - }, # RynthNav also publishes straight to its deploy home via <PublishDir>. # It was missing from this list entirely, so full deploys never refreshed it. @{ @@ -83,6 +79,13 @@ $pluginProjects = @( Publish = Join-Path $PluginsDestination "RynthNav" DllName = "RynthCore.Plugin.RynthNav.dll" DestSubdir = "RynthNav" + }, + # RynthLua: Lua scripting, split out of RynthAi on 2026-09-29. + @{ + Project = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthLua\RynthCore.Plugin.RynthLua.csproj" + Publish = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthLua\bin\Release\net10.0-windows\win-x86\publish" + DllName = "RynthCore.Plugin.RynthLua.dll" + DestSubdir = "RynthLua" } ) @@ -158,6 +161,13 @@ function Invoke-Publish { } } +# Managed plugins publish to (and deploy from) out\plugins-clr\<name>, -SkipPublish too. +if (-not $NativeAot) { + foreach ($plugin in $pluginProjects) { + $plugin.Publish = Join-Path $repoRoot ("out\plugins-clr\" + $plugin.DestSubdir) + } +} + if (-not $SkipPublish) { $env:DOTNET_CLI_HOME = Join-Path $repoRoot ".dotnet-home-deploy-clean" $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = "1" @@ -166,10 +176,24 @@ if (-not $SkipPublish) { # --self-contained false is required: omitting it with the launcher's IncludeNativeLibrariesForSelfExtract=true produces a broken half-payload (apphost + coreclr.dll, no framework) that reports ".NET is not installed". Invoke-Publish -What "launcher" -Arguments @('publish', $launcherProject, '-c', 'Release', '-r', 'win-x86', '--self-contained', 'false') } - Invoke-Publish -What "engine" -Arguments @('publish', $engineProject, '-c', 'Release') - Invoke-Publish -What "loader" -Arguments @('publish', $loaderProject, '-c', 'Release') + if ($NativeAot) { + Invoke-Publish -What "engine" -Arguments @('publish', $engineProject, '-c', 'Release') + Invoke-Publish -What "loader" -Arguments @('publish', $loaderProject, '-c', 'Release') + } + # (CoreCLR: the engine, loader and shim are built by Publish-EngineCoreClr.ps1 below, + # after Runtime\ is wiped.) foreach ($plugin in $pluginProjects) { - Invoke-Publish -What $plugin.DllName -Arguments @('publish', $plugin.Project, '-c', 'Release') + if ($NativeAot) { + Invoke-Publish -What $plugin.DllName -Arguments @('publish', $plugin.Project, '-c', 'Release') + } else { + # Same source, managed: loads into its own collectible context in the CoreCLR + # engine (Plugins/ManagedPlugins.cs). Staged under out\plugins-clr, then copied. + $stage = $plugin.Publish + if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } + Invoke-Publish -What "$($plugin.DllName) (managed)" -Arguments @('publish', $plugin.Project, '-c', 'Release', + '-p:PublishAot=false', '-p:NativeLib=', '-p:SelfContained=false', '-p:RuntimeIdentifier=win-x86', + '-p:GenerateRuntimeConfigurationFiles=false', '-o', $stage) + } } } @@ -256,13 +280,20 @@ if (-not $SkipLauncher) { Copy-FilteredChildren -Source $launcherPublish -Target $Destination -ExcludeNames @("RynthCore.App.Avalonia.exe") -ExcludeExtensions @(".pdb") } -# Engine payload to Runtime\. Skip the bundled Plugins\ subfolder - plugins -# are deployed separately to $PluginsDestination so they have a single home. -Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeNames @("Plugins") -ExcludeExtensions @(".pdb") +if ($NativeAot) { + # Engine payload to Runtime\. Skip the bundled Plugins\ subfolder - plugins + # are deployed separately to $PluginsDestination so they have a single home. + Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeNames @("Plugins") -ExcludeExtensions @(".pdb") -# Loader DLL - this is what RynthCore.Injector loads into acclient.exe; the -# Loader then maps RynthCore.Engine.dll and provides hot-reload support. -Copy-Item -LiteralPath (Join-Path $loaderPublish "RynthCore.Loader.dll") -Destination (Join-Path $runtimeDir "RynthCore.Loader.dll") -Force + # Loader DLL - this is what RynthCore.Injector loads into acclient.exe; the + # Loader then maps RynthCore.Engine.dll and provides hot-reload support. + Copy-Item -LiteralPath (Join-Path $loaderPublish "RynthCore.Loader.dll") -Destination (Join-Path $runtimeDir "RynthCore.Loader.dll") -Force +} else { + # Native loader (native\Loader) + RynthCore.Shim + CoreCLR engine (ReadyToRun) + its + # dependencies + Runtime\dotnet (app-local CoreCLR x86). Same contract with the + # injector (RynthCoreInit); the loader also hosts a NativeAOT engine if one is dropped in. + & (Join-Path $PSScriptRoot "Publish-EngineCoreClr.ps1") -Target $runtimeDir +} # SEH trampoline - small native x86 MSVC DLL providing __try/__except wrappers # around dangerous AC API calls so object-teardown AVs are caught instead of @@ -302,6 +333,16 @@ foreach ($plugin in $pluginProjects) { New-Item -ItemType Directory -Path $pluginTargetDir -Force | Out-Null } + if (-not $NativeAot) { + # A managed plugin is its DLL plus its dependencies (RynthCore.PluginSdk, + # PluginCore, MoonSharp, ImGui.NET...) and pdbs; copy those, leave user data. + foreach ($f in Get-ChildItem -LiteralPath $plugin.Publish -File | Where-Object { $_.Extension -in '.dll', '.pdb' }) { + Copy-Item -LiteralPath $f.FullName -Destination (Join-Path $pluginTargetDir $f.Name) -Force + } + Write-Host "Plugin $($plugin.DllName) (managed) deployed to $pluginTargetDir" + continue + } + # Only the DLL - leave any user data (LootProfiles\, imgui.ini, etc.) # in place by not touching anything else under $pluginTargetDir. $pluginDest = Join-Path $pluginTargetDir $plugin.DllName @@ -318,7 +359,10 @@ foreach ($plugin in $pluginProjects) { # Scoped pdb sweep: root + Runtime\ only. A $Destination-wide recurse walked # the ~1.4 GB private AcClient copy on every deploy for nothing. Get-ChildItem -Path $Destination -Filter *.pdb -File | Remove-Item -Force -Get-ChildItem -Path $runtimeDir -Recurse -Filter *.pdb -File | Remove-Item -Force +# (The CoreCLR engine's own pdbs stay: they give its stack traces line numbers.) +Get-ChildItem -Path $runtimeDir -Recurse -Filter *.pdb -File | + Where-Object { $NativeAot -or $_.Name -notin 'RynthCore.Engine.pdb', 'RynthCore.Shim.pdb', 'RynthCore.Loader.pdb' } | + Remove-Item -Force if (-not $SkipLauncher) { Write-Host "Launcher deployed to $Destination" diff --git a/scripts/Publish-EngineCoreClr.ps1 b/scripts/Publish-EngineCoreClr.ps1 new file mode 100644 index 0000000..cad170e --- /dev/null +++ b/scripts/Publish-EngineCoreClr.ps1 @@ -0,0 +1,122 @@ +# Publish-EngineCoreClr.ps1 +# Builds the CoreCLR-hosted engine (docs/UNLOADABLE_ENGINE_PLAN.md) and lays it out in a +# Runtime folder: +# RynthCore.Loader.dll native loader (native\Loader), hosts CoreCLR +# RynthCore.Shim.dll default-ALC shim (src\RynthCore.Shim) +# RynthCore.Engine.dll (+pdb) the engine as a managed assembly (-p:EngineHost=coreclr) +# Avalonia*, ImGui.NET, ... the engine's managed dependencies (load into its collectible ALC) +# cimgui, minhook, Skia, ... native libraries (process-wide, loaded once) +# dotnet\ app-local CoreCLR x86 (from the NuGet runtime pack) +# +# Default target is the live install; a running client hot-reloads onto a new engine by itself: +# .\scripts\Publish-EngineCoreClr.ps1 -> C:\Games\RynthCore\Runtime +# .\scripts\Publish-EngineCoreClr.ps1 -Target <dir> -EngineOnly (engine + deps only: a hot reload) + +param( + [string]$Target = "C:\Games\RynthCore\Runtime", + [string]$Configuration = "Release", + [switch]$EngineOnly, + # The engine is precompiled (ReadyToRun) unless -NoReadyToRun: each generation then + # loads in ~130 ms instead of ~750 (less JIT); the DLL is ~5 MB instead of ~2. + [switch]$NoReadyToRun, + # Extra MSBuild arguments for the engine and shim builds (the installer passes -p:Version=...). + [string[]]$MsBuildArgs = @(), + # Deploy to the live Runtime even though status-export has commits this checkout lacks. + [switch]$AllowBehind +) + +$ErrorActionPreference = "Stop" +$repo = Split-Path $PSScriptRoot -Parent + +# Deploying to the live install from a checkout that lacks status-export's commits rolls +# back other sessions' engine fixes on every running client (2026-09-29, API v70). Refuse. +$liveRuntime = "C:\Games\RynthCore\Runtime" +if ([IO.Path]::GetFullPath($Target).TrimEnd('\') -ieq $liveRuntime -and -not $AllowBehind) { + git -C $repo merge-base --is-ancestor status-export HEAD 2>$null + if ($LASTEXITCODE -ne 0) { + $missing = git -C $repo log --oneline HEAD..status-export + throw "This checkout is missing status-export commits; deploying it to the live Runtime would roll them back:`n$($missing -join "`n")`nMerge status-export first (or pass -AllowBehind if you really mean it)." + } +} +$env:PATH += ";C:\Program Files (x86)\Microsoft Visual Studio\Installer" +New-Item -ItemType Directory -Force -Path $Target | Out-Null + +$stage = Join-Path $repo "out\engine-clr" +if (Test-Path $stage) { Remove-Item $stage -Recurse -Force } +Write-Host "Building the engine (EngineHost=coreclr)..." +$r2r = if (-not $NoReadyToRun) { "-p:PublishReadyToRun=true" } else { "-p:PublishReadyToRun=false" } +dotnet publish "$repo\src\RynthCore.Engine\RynthCore.Engine.csproj" -c $Configuration -p:EngineHost=coreclr $r2r -o $stage -nologo -v q @MsBuildArgs +if ($LASTEXITCODE -ne 0) { throw "engine build failed" } + +if (-not $EngineOnly) { + Write-Host "Building the native loader..." + & "$repo\native\Loader\Build-Loader.ps1" + Write-Host "Building the shim..." + dotnet build "$repo\src\RynthCore.Shim\RynthCore.Shim.csproj" -c $Configuration -nologo -v q @MsBuildArgs + if ($LASTEXITCODE -ne 0) { throw "shim build failed" } + + # The loader and the shim load once per client: a running client keeps its copy (and + # locks the file) until it restarts. Skip them with a warning rather than fail. + $hostFiles = @( + "$repo\native\Loader\bin\RynthCore.Loader.dll", "$repo\native\Loader\bin\RynthCore.Loader.pdb", + "$repo\src\RynthCore.Shim\bin\$Configuration\net10.0-windows\RynthCore.Shim.dll", + "$repo\src\RynthCore.Shim\bin\$Configuration\net10.0-windows\RynthCore.Shim.pdb") + # A running client holds these files; Windows lets a loaded DLL be renamed, so the old + # copy is moved aside (the client keeps using it) and the new one goes in for the next + # launch. Earlier moved-aside copies are deleted once no client holds them. + Get-ChildItem $Target -Filter "RynthCore.*.old-*" -ErrorAction SilentlyContinue | + ForEach-Object { Remove-Item $_.FullName -Force -ErrorAction SilentlyContinue } + foreach ($f in $hostFiles) { + $dest = Join-Path $Target (Split-Path $f -Leaf) + try { Copy-Item $f $dest -Force -ErrorAction Stop } + catch { + try { + Rename-Item $dest ("{0}.old-{1:yyyyMMddHHmmss}" -f (Split-Path $dest -Leaf), (Get-Date)) -ErrorAction Stop + Copy-Item $f $dest -Force -ErrorAction Stop + Write-Host "$(Split-Path $f -Leaf) was in use: moved the old one aside; new launches get the new one." + } + catch { Write-Warning "$(Split-Path $f -Leaf) is in use by a running client; it keeps the old one until it restarts." } + } + } + + $seh = "$repo\native\SehTrampoline\bin\RynthCore.SehTrampoline.dll" + if (-not (Test-Path $seh)) { $seh = "C:\Games\RynthCore\Runtime\RynthCore.SehTrampoline.dll" } + $sehDest = Join-Path (Resolve-Path $Target).Path "RynthCore.SehTrampoline.dll" + $sameSeh = (Test-Path $sehDest) -and ((Resolve-Path $seh).Path -eq $sehDest -or + (Get-FileHash $seh).Hash -eq (Get-FileHash $sehDest).Hash) + if (-not $sameSeh) { + try { Copy-Item $seh $sehDest -Force -ErrorAction Stop } + catch { Write-Warning "RynthCore.SehTrampoline.dll changed but is in use by a running client; it gets the new one when it restarts." } + } + + # App-local runtime: the win-x86 runtime pack the SDK restores (same version the engine was built against). + $dotnet = Join-Path $Target "dotnet" + if (-not (Test-Path "$dotnet\coreclr.dll")) { + $pack = Join-Path $env:USERPROFILE ".nuget\packages\microsoft.netcore.app.runtime.win-x86" + $ver = (Get-ChildItem $pack | Where-Object Name -like "10.*" | Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1).Name + if (-not $ver) { throw "microsoft.netcore.app.runtime.win-x86 10.x not in the NuGet cache (restore any win-x86 self-contained project once)" } + $rt = "$pack\$ver\runtimes\win-x86" + New-Item -ItemType Directory -Force -Path $dotnet | Out-Null + Copy-Item "$rt\native\*" $dotnet -Force + Copy-Item "$rt\lib\net10.0\*.dll" $dotnet -Force + # Diagnostics-only natives the host never loads. + Remove-Item "$dotnet\createdump.exe", "$dotnet\mscordaccore_*.dll", "$dotnet\msquic.dll" -Force -ErrorAction SilentlyContinue + Write-Host "App-local runtime $ver -> $dotnet" + } +} + +# Engine + dependencies. The canonical RynthCore.Engine.dll goes last: the loader's file +# watcher reloads on its timestamp, so everything it needs must already be in place. +# Only what changed. Native libraries (cimgui, Skia...) are loaded once per client and +# locked while it runs; they rarely change, so a locked unchanged one is simply skipped. +foreach ($f in Get-ChildItem $stage -File | Where-Object { $_.Name -notlike "RynthCore.Engine.*" -and $_.Name -ne "minhook.x86.dll" }) { + $dest = Join-Path $Target $f.Name + if ((Test-Path $dest) -and (Get-Item $dest).Length -eq $f.Length -and + (Get-FileHash $dest).Hash -eq (Get-FileHash $f.FullName).Hash) { continue } + try { Copy-Item $f.FullName $dest -Force -ErrorAction Stop } + catch { Write-Warning "$($f.Name) changed but is in use by a running client; it gets the new one when it restarts." } +} +if (-not (Test-Path "$Target\minhook.x86.dll")) { Copy-Item "$stage\minhook.x86.dll" $Target -Force } +Copy-Item "$stage\RynthCore.Engine.pdb" $Target -Force +Copy-Item "$stage\RynthCore.Engine.dll" $Target -Force +Write-Host "Published the CoreCLR engine to $Target" diff --git a/scripts/Publish-PluginsCoreClr.ps1 b/scripts/Publish-PluginsCoreClr.ps1 new file mode 100644 index 0000000..bc4454f --- /dev/null +++ b/scripts/Publish-PluginsCoreClr.ps1 @@ -0,0 +1,28 @@ +# Publish-PluginsCoreClr.ps1 +# Builds RynthSuite plugins as MANAGED assemblies for the CoreCLR engine (plan Phase 4): the +# same source as the NativeAOT build, with PublishAot off (command-line properties override +# the csproj). Each plugin lands in its own folder with its dependencies (RynthCore.PluginSdk, +# PluginCore, MoonSharp, ...), which the engine loads into the plugin's collectible context. +# +# For a test build into a separate folder; scripts\Deploy-RynthCore.ps1 is what deploys the +# managed plugins to C:\Games\RynthSuite. The plugins reference ..\..\..\RynthCore\src\... (the +# SDK), so they build against whatever RynthCore checkout sits next to -RynthSuite. +# .\scripts\Publish-PluginsCoreClr.ps1 [-Plugins RynthAi,RynthChat] [-Out <dir>] +param( + [string]$RynthSuite = "C:\Projects\RynthSuite", + [string]$Out = "C:\Games\RynthCore\Test\plugins-clr", + [string[]]$Plugins = @("RynthAi", "RynthChat", "RynthNav", "RynthTracker", "RynthLua", "RynthVision") +) + +$ErrorActionPreference = "Stop" +foreach ($name in $Plugins) { + $proj = Join-Path $RynthSuite "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj" + if (-not (Test-Path $proj)) { Write-Warning "${name}: no project at $proj"; continue } + $dest = Join-Path $Out $name + if (Test-Path $dest) { Remove-Item $dest -Recurse -Force } + Write-Host "Building $name (managed)..." + dotnet publish $proj -c Release -p:PublishAot=false -p:NativeLib= -p:SelfContained=false ` + -p:RuntimeIdentifier=win-x86 -p:GenerateRuntimeConfigurationFiles=false -o $dest -nologo -v q + if ($LASTEXITCODE -ne 0) { throw "$name build failed" } + Write-Host " -> $dest\RynthCore.Plugin.$name.dll" +} diff --git a/scripts/Test-ClrReload.ps1 b/scripts/Test-ClrReload.ps1 new file mode 100644 index 0000000..757fd8f --- /dev/null +++ b/scripts/Test-ClrReload.ps1 @@ -0,0 +1,62 @@ +# Test-ClrReload.ps1 - hot-reload test for the CoreCLR-hosted engine in a throwaway client. +# +# Starts acclient from the private copy against -Server (default: a closed local port, so +# nothing logs in), with its own engine.json (-Settings), reloads it -Reloads times, +# and after each reload prints the loader/shim lines. If a generation did not unload, +# runs tools\AlcRoots against the client to show what still holds it. Kills the client at +# the end unless -Keep. +param( + [string]$Runtime = "C:\Games\RynthCore\Runtime", + [string]$Settings = "C:\Games\RynthCore\Test\engine-noplugins.json", + [int]$Reloads = 1, + [int]$WarmupSeconds = 20, + [int]$SettleSeconds = 15, + [string[]]$ClientArgs = @("-h", "127.0.0.1", "-p", "9", "-a", "spike", "-v", "spike"), + [switch]$Keep, + [switch]$AlwaysRoots +) + +$ErrorActionPreference = "Stop" +$repo = Split-Path $PSScriptRoot -Parent +$testClient = "$repo\tools\TestClient\bin\TestClient.exe" +$alcRoots = "$repo\tools\AlcRoots\bin\Release\net10.0\win-x86\AlcRoots.exe" + +$env:RYNTHCORE_ENGINE_SETTINGS = $Settings +$env:RYNTHCORE_TEST_CLIENT = "Test-ClrReload" # the loader logs "TestClient: ..." (monitors skip test clients) +# Panel layout (panel_state.txt) lives in %LOCALAPPDATA%\RynthCore and is shared with real +# clients: a test client gets its own so it never moves the player's bar or panels. +$env:LOCALAPPDATA = "C:\Games\RynthCore\Test\localappdata" +New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null +$out = & $testClient "C:\Games\RynthCore\AcClient\acclient.exe" "$Runtime\RynthCore.Loader.dll" RynthCoreInit 0 @ClientArgs +$clientPid = [int](($out | Select-String "TEST_PID=(\d+)").Matches[0].Groups[1].Value) +$log = "C:\Games\RynthCore\Logs\RynthCore.$clientPid.log" +Write-Host "client pid $clientPid, log $log" +Start-Sleep $WarmupSeconds + +$seen = 0 +function Show-NewLoaderLines { + $lines = @(Get-Content $log | Select-String "\[loader\]|\[ERR\]|\[WRN\]") + $lines[$script:seen..($lines.Count - 1)] | ForEach-Object { $_.Line } + $script:seen = $lines.Count +} +Show-NewLoaderLines + +for ($i = 1; $i -le $Reloads; $i++) { + if (-not (Get-Process -Id $clientPid -ErrorAction SilentlyContinue)) { Write-Host "client died"; break } + Write-Host "---- reload $i" + $ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$clientPid") + [void]$ev.Set() + $ev.Dispose() + Start-Sleep $SettleSeconds + Show-NewLoaderLines + $notFreed = Select-String -Path $log -Pattern "NOT unloaded" -Quiet + if ($AlwaysRoots -or ($notFreed -and $i -eq 1)) { + Write-Host "---- AlcRoots" + & $alcRoots $clientPid 30 + } +} + +if (-not $Keep) { + Stop-Process -Id $clientPid -Force -ErrorAction SilentlyContinue + Write-Host "client $clientPid stopped" +} diff --git a/scripts/Test-ClrWorld.ps1 b/scripts/Test-ClrWorld.ps1 new file mode 100644 index 0000000..d03e8db --- /dev/null +++ b/scripts/Test-ClrWorld.ps1 @@ -0,0 +1,97 @@ +# Test-ClrWorld.ps1 - logs a test character into a LOCAL server with the CoreCLR engine and +# hot-reloads it N times, reporting per generation: unloaded or not, pattern misses, hangs, +# and the frame rate afterwards. Runs tools\AlcRoots when a generation doesn't unload. +# +# Uses the injector's headless --launch with a saved account profile (the password stays in +# the launcher's settings). Only point it at a server you run yourself. +# .\scripts\Test-ClrWorld.ps1 -Account Buffi -Server ACEmulator -Character "+Buffi" -Reloads 5 +param( + [string]$Account = "Buffi", + [string]$Server = "ACEmulator", + [string]$Character = "+Buffi", + [string]$Runtime = "C:\Games\RynthCore\Runtime", + [string]$Settings = "C:\Games\RynthCore\Test\engine-plugins.json", + [int]$Reloads = 3, + [int]$WarmupSeconds = 45, + [int]$SettleSeconds = 25, + # Chat commands to run after login and again after every reload (through the test + # client's own dispatch file), e.g. "/rc ui popout Radar". + [string[]]$Commands = @(), + [switch]$Keep +) + +$ErrorActionPreference = "Stop" +$repo = Split-Path $PSScriptRoot -Parent +$injector = "$repo\out\injector\RynthCore.Injector.exe" +if (-not (Test-Path $injector)) { + dotnet publish "$repo\src\RynthCore.Injector\RynthCore.Injector.csproj" -c Release -o "$repo\out\injector" -nologo -v q | Out-Null + if (-not (Test-Path $injector)) { throw "could not build the injector" } +} +$alcRoots = "$repo\tools\AlcRoots\bin\Release\net10.0\win-x86\AlcRoots.exe" +$pidFile = "C:\Games\RynthCore\Test\current-pid.txt" + +# A client killed without logging off keeps its session on the server for about a minute. +if (Test-Path $pidFile) { + $old = [int](Get-Content $pidFile) + if (Get-Process -Id $old -ErrorAction SilentlyContinue) { + Stop-Process -Id $old -Force + Write-Host "stopped previous test client $old; waiting 65 s for the server to drop its session" + Start-Sleep 65 + } +} + +$env:RYNTHCORE_ENGINE_SETTINGS = $Settings +$env:RYNTHCORE_TEST_CLIENT = "Test-ClrWorld" # the loader logs "TestClient: ..." (monitors skip test clients) +# Panel layout (panel_state.txt) lives in %LOCALAPPDATA%\RynthCore and is shared with real +# clients: a test client gets its own so it never moves the player's bar or panels. +$env:LOCALAPPDATA = "C:\Games\RynthCore\Test\localappdata" +New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null +$dispatch = "C:\Games\RynthCore\Test\dispatch.txt" +$env:RYNTHCORE_DISPATCH_FILE = $dispatch +Set-Content $dispatch "# test dispatch file" +function Send-Commands { + foreach ($c in $Commands) { + Set-Content $dispatch "force:$c" + Start-Sleep 2 + } +} +$out = & $injector --launch --account $Account --server $Server --engine "$Runtime\RynthCore.Loader.dll" --character $Character 2>&1 +$clientPid = [int](($out | Select-String "LAUNCHED_PID=(\d+)").Matches[0].Groups[1].Value) +Set-Content $pidFile $clientPid +$log = "C:\Games\RynthCore\Logs\RynthCore.$clientPid.log" +Write-Host "client $clientPid, log $log" +Start-Sleep $WarmupSeconds + +function Summarize([int]$from) { + $lines = @(Get-Content $log | Select-Object -Skip $from) + $lines | Select-String "unloaded in|NOT unloaded|unloaded since|Reload: |PATTERN MISS|HANG DETECTED|prologue not found|\[ERR\]|still running|ChatFileDispatcher: dispatching|PopOut|pop-out" | + ForEach-Object { Write-Host (" " + ($_.Line -replace '^\[(\S+)\] \[pid:\d+\] ', '$1 ')) } + $fps = $lines | Select-String "hb #\d+ .*fps=(\d+).*login=(\d)" | Select-Object -Last 8 | + ForEach-Object { $_.Matches[0].Groups[1].Value } + Write-Host " fps (last 8 heartbeats): $($fps -join ' ')" + return (Get-Content $log).Count +} + +Send-Commands +Start-Sleep 5 +$mark = 0 +Write-Host "---- gen 1" +$mark = Summarize $mark +for ($i = 1; $i -le $Reloads; $i++) { + if (-not (Get-Process -Id $clientPid -ErrorAction SilentlyContinue)) { Write-Host "CLIENT DIED"; break } + Write-Host "---- reload $i" + $ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$clientPid") + [void]$ev.Set(); $ev.Dispose() + Start-Sleep $SettleSeconds + Send-Commands + Start-Sleep 5 + $before = $mark + $mark = Summarize $mark + if (Get-Content $log | Select-Object -Skip $before | Select-String "NOT unloaded" -Quiet) { + Write-Host "---- AlcRoots" + & $alcRoots $clientPid 15 + } +} +$p = Get-Process -Id $clientPid -ErrorAction SilentlyContinue +Write-Host ("client " + $(if ($p) { "alive, responding=$($p.Responding)" } else { "DEAD" })) +if (-not $Keep -and $p) { Stop-Process -Id $clientPid -Force; Write-Host "client stopped" } diff --git a/scripts/Watch-AcFreeze.ps1 b/scripts/Watch-AcFreeze.ps1 index 6289ce9..7829719 100644 --- a/scripts/Watch-AcFreeze.ps1 +++ b/scripts/Watch-AcFreeze.ps1 @@ -7,7 +7,8 @@ # (MaybeRestartWedgedClients), so it can run with the launcher closed: # # * fps=0 with login=1 sustained >= WedgeHoldSeconds (render dead, alive) -# * main-thread queue qd > QueueWedgeDepth with login=1 (queue not draining) +# * (inert since 2026-10-01: the engine reports qdrop, a running total of dropped +# actions, not a queue depth; healthy clients were being killed on it) # * combat-mode "stuck Ns" >= StanceStuckSeconds (item-action hard-lock) # * heartbeat file silent > HbStaleSeconds while alive (engine died in-proc) # diff --git a/spikes/CoreClrHost/Build.ps1 b/spikes/CoreClrHost/Build.ps1 new file mode 100644 index 0000000..ca8d6ff --- /dev/null +++ b/spikes/CoreClrHost/Build.ps1 @@ -0,0 +1,52 @@ +# Build.ps1 - builds the Phase 0 CoreCLR hosting spike into .\bin +# bin\SpikeHostExe.exe, SpikeHost.dll native x86 (cl.exe) +# bin\Shim.dll, Contracts.dll default ALC (in the TPA list) +# bin\payload\Payload.dll loaded into a collectible ALC per generation +# bin\runtime\ app-local CoreCLR x86 from the NuGet runtime pack +# Run: .\bin\SpikeHostExe.exe <cycles> <mode> (mode bits: see Payload.cs) + +$ErrorActionPreference = "Stop" +$root = $PSScriptRoot +$bin = Join-Path $root "bin" +New-Item -ItemType Directory -Force -Path $bin, "$bin\payload", "$bin\runtime", "$bin\obj" | Out-Null + +# --- native --- +$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" ` + -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name +$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer" +$cl = "$vcBase\bin\Hostx86\x86\cl.exe" +$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name +$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer" +$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer" +$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared" +$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86" + +Push-Location "$bin\obj" +try { + & $cl /nologo /O2 /MT /W3 /LD "$root\native\SpikeHost.c" /link /MACHINE:X86 /OUT:"$bin\SpikeHost.dll" + if ($LASTEXITCODE -ne 0) { throw "SpikeHost.dll failed" } + & $cl /nologo /O2 /MT /W3 "$root\native\SpikeHostExe.c" /link /MACHINE:X86 /LARGEADDRESSAWARE /OUT:"$bin\SpikeHostExe.exe" + if ($LASTEXITCODE -ne 0) { throw "SpikeHostExe.exe failed" } + & $cl /nologo /O2 /MT /W3 "$root\native\SpikeInject.c" /link /MACHINE:X86 /OUT:"$bin\SpikeInject.exe" + if ($LASTEXITCODE -ne 0) { throw "SpikeInject.exe failed" } +} finally { Pop-Location } + +# --- managed --- +foreach ($p in "Contracts", "Shim", "Payload") { + dotnet build "$root\$p\$p.csproj" -c Release -nologo -v q + if ($LASTEXITCODE -ne 0) { throw "$p build failed" } +} +Copy-Item "$root\Shim\bin\Release\net10.0\Shim.dll" $bin -Force +Copy-Item "$root\Contracts\bin\Release\net10.0\Contracts.dll" $bin -Force +Copy-Item "$root\Payload\bin\Release\net10.0\Payload.dll" "$bin\payload" -Force + +# --- app-local runtime --- +$pack = Join-Path $env:USERPROFILE ".nuget\packages\microsoft.netcore.app.runtime.win-x86" +$ver = (Get-ChildItem $pack | Where-Object Name -like "10.*" | Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1).Name +$rt = "$pack\$ver\runtimes\win-x86" +if (-not (Test-Path "$bin\runtime\coreclr.dll")) { + Copy-Item "$rt\native\*" "$bin\runtime" -Force + Copy-Item "$rt\lib\net10.0\*.dll" "$bin\runtime" -Force +} +Write-Host "Built spike with runtime $ver into $bin" diff --git a/spikes/CoreClrHost/Contracts/Contracts.csproj b/spikes/CoreClrHost/Contracts/Contracts.csproj new file mode 100644 index 0000000..2cb3dc9 --- /dev/null +++ b/spikes/CoreClrHost/Contracts/Contracts.csproj @@ -0,0 +1,8 @@ +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFramework>net10.0</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <Nullable>enable</Nullable> + <AssemblyName>Contracts</AssemblyName> + </PropertyGroup> +</Project> diff --git a/spikes/CoreClrHost/Contracts/IPayload.cs b/spikes/CoreClrHost/Contracts/IPayload.cs new file mode 100644 index 0000000..569d7b0 --- /dev/null +++ b/spikes/CoreClrHost/Contracts/IPayload.cs @@ -0,0 +1,17 @@ +namespace Contracts; + +/// <summary>What the Shim (default ALC) sees of a payload living in a collectible ALC.</summary> +public interface IPayload +{ + /// <summary>Address of an [UnmanagedCallersOnly] stdcall (int,int)->int method, or 0 with an error.</summary> + nint GetUcoPointer(out string? error); + + /// <summary>Marshal.GetFunctionPointerForDelegate of a stdcall (int,int)->int delegate the payload keeps alive.</summary> + nint GetDelegatePointer(); + + /// <summary>Does the work selected by the mode bits; returns a short description.</summary> + string Work(int mode); + + /// <summary>Stops everything Work started.</summary> + void Shutdown(); +} diff --git a/spikes/CoreClrHost/Payload/Payload.cs b/spikes/CoreClrHost/Payload/Payload.cs new file mode 100644 index 0000000..341ca00 --- /dev/null +++ b/spikes/CoreClrHost/Payload/Payload.cs @@ -0,0 +1,153 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.Json; +using Contracts; + +namespace Payload; + +// Mode bits (the Shim passes the host's mode through): +// 0x01 System.Text.Json reflection serialize/deserialize of payload types +// 0x02 start a Thread and join it in Shutdown +// 0x04 Task.Run work + a System.Threading.Timer, both finished/disposed in Shutdown +// 0x08 hold a 32 MB static array (the GC heap should give it back) +// 0x10 LEAK ON PURPOSE: subscribe to AppDomain.ProcessExit and never unsubscribe +// 0x20 JIT a lot of code (many generic instantiations over payload types) +// 0x40 allocate 8 MB with NativeMemory and free it in Shutdown +// 0x80 System.Text.Json reflection with a JsonSerializerOptions the payload owns +// 0x100 (Shim side) load a private copy of System.Text.Json into the collectible ALC +public sealed class Entry : IPayload +{ + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int BinaryFn(int a, int b); + + private static byte[]? s_big; + private static BinaryFn? s_mul; + private Thread? _thread; + private volatile bool _stop; + private Timer? _timer; + private Task? _task; + private unsafe void* _native; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int Add(int a, int b) => a + b; + + public unsafe nint GetUcoPointer(out string? error) + { + try + { + error = null; + return (nint)(delegate* unmanaged[Stdcall]<int, int, int>)&Add; + } + catch (Exception ex) + { + error = ex.GetType().Name + ": " + ex.Message; + return 0; + } + } + + public nint GetDelegatePointer() + { + s_mul = (a, b) => a * b; + return Marshal.GetFunctionPointerForDelegate(s_mul); + } + + public unsafe string Work(int mode) + { + var did = new List<string>(); + if ((mode & 0x01) != 0) + { + var rec = new Record { Name = "gen", Values = Enumerable.Range(0, 100).ToList(), Child = new Record { Name = "c" } }; + string json = JsonSerializer.Serialize(rec); + var back = JsonSerializer.Deserialize<Record>(json)!; + did.Add($"json {json.Length}b {back.Values.Count} stj alc {System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(typeof(JsonSerializer).Assembly)?.Name}"); + } + if ((mode & 0x80) != 0) + { + var opts = new JsonSerializerOptions { WriteIndented = false }; + var rec = new Record { Name = "own", Values = Enumerable.Range(0, 10).ToList() }; + string json = JsonSerializer.Serialize(rec, opts); + var back = JsonSerializer.Deserialize<Record>(json, opts)!; + did.Add($"json(own opts) {json.Length}b {back.Values.Count} stj@{typeof(JsonSerializer).Assembly.GetName().Name}:{System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(typeof(JsonSerializer).Assembly)?.Name}"); + } + if ((mode & 0x02) != 0) + { + _thread = new Thread(() => { while (!_stop) Thread.Sleep(5); }) { IsBackground = true, Name = "payload" }; + _thread.Start(); + did.Add("thread"); + } + if ((mode & 0x04) != 0) + { + _task = Task.Run(() => Thread.Sleep(20)); + _timer = new Timer(_ => { }, null, 0, 10); + did.Add("task+timer"); + } + if ((mode & 0x08) != 0) + { + s_big = new byte[32 * 1024 * 1024]; + s_big[^1] = 1; + did.Add("32MB static"); + } + if ((mode & 0x10) != 0) + { + AppDomain.CurrentDomain.ProcessExit += OnExit; + did.Add("LEAK ProcessExit"); + } + if ((mode & 0x20) != 0) + { + int n = JitMany(); + did.Add($"jit {n}"); + } + if ((mode & 0x40) != 0) + { + _native = NativeMemory.Alloc(8 * 1024 * 1024); + did.Add("native 8MB"); + } + return did.Count == 0 ? "basic" : string.Join(", ", did); + } + + private void OnExit(object? s, EventArgs e) { } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int JitMany() + { + int sum = 0; + sum += Gen<A1>.Run(); sum += Gen<A2>.Run(); sum += Gen<A3>.Run(); sum += Gen<A4>.Run(); + sum += Gen<A5>.Run(); sum += Gen<A6>.Run(); sum += Gen<A7>.Run(); sum += Gen<A8>.Run(); + var d = new Dictionary<A1, List<A2>>(); d[new A1()] = new List<A2> { new() }; + sum += d.Count + d.Values.SelectMany(x => x).Count(); + return sum; + } + + public unsafe void Shutdown() + { + _stop = true; + _thread?.Join(); + _timer?.Dispose(); + _task?.Wait(); + if (_native != null) { NativeMemory.Free(_native); _native = null; } + s_big = null; + // s_mul stays: a static in the collectible ALC, it dies with the ALC. + } + + public sealed class Record + { + public string Name { get; set; } = ""; + public List<int> Values { get; set; } = new(); + public Record? Child { get; set; } + } + + private sealed class A1 { } private sealed class A2 { } private sealed class A3 { } private sealed class A4 { } + private sealed class A5 { } private sealed class A6 { } private sealed class A7 { } private sealed class A8 { } + + private static class Gen<T> where T : new() + { + public static int Run() + { + var list = new List<T>(); + for (int i = 0; i < 16; i++) list.Add(new T()); + var set = new HashSet<T>(list); + var dict = list.Select((x, i) => (x, i)).ToDictionary(p => p.x, p => p.i); + return list.Where(x => x != null).OrderBy(x => x!.GetHashCode()).Count() + set.Count + dict.Count; + } + } +} diff --git a/spikes/CoreClrHost/Payload/Payload.csproj b/spikes/CoreClrHost/Payload/Payload.csproj new file mode 100644 index 0000000..24df78a --- /dev/null +++ b/spikes/CoreClrHost/Payload/Payload.csproj @@ -0,0 +1,14 @@ +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFramework>net10.0</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <AssemblyName>Payload</AssemblyName> + </PropertyGroup> + <ItemGroup> + <!-- Contracts must come from the default ALC: don't copy it next to the payload. --> + <ProjectReference Include="..\Contracts\Contracts.csproj" Private="false" /> + </ItemGroup> +</Project> diff --git a/spikes/CoreClrHost/Shim/Entry.cs b/spikes/CoreClrHost/Shim/Entry.cs new file mode 100644 index 0000000..b3be594 --- /dev/null +++ b/spikes/CoreClrHost/Shim/Entry.cs @@ -0,0 +1,134 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Loader; +using System.Text; +using Contracts; + +namespace Shim; + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct HostApi +{ + public int Size; + public delegate* unmanaged[Stdcall]<double*, double> FreeMb; + public delegate* unmanaged[Stdcall]<byte*, void> Log; + public delegate* unmanaged[Stdcall]<nint, int, int, int> CallBinary; + public delegate* unmanaged[Stdcall]<uint> CommittedMb; +} + +public static unsafe class Entry +{ + private static HostApi* s_api; + + private static void Log(string msg) + { + byte[] bytes = Encoding.UTF8.GetBytes(msg + "\0"); + fixed (byte* p = bytes) s_api->Log(p); + } + + private static (double free, double largest) Free() + { + double largest; + double free = s_api->FreeMb(&largest); + return (free, largest); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + public static int Run(HostApi* api, int cycles, int mode) + { + s_api = api; + try + { + string dir = Path.GetDirectoryName(typeof(Entry).Assembly.Location)!; + string payloadPath = Path.Combine(dir, "payload", "Payload.dll"); + Log($"Shim up: CLR {Environment.Version}, {RuntimeInformation.ProcessArchitecture}, mode 0x{mode:x}, {cycles} cycles, payload {payloadPath}"); + + var (free0, _) = Free(); + uint commit0 = s_api->CommittedMb(); + double firstGenFree = 0; + int failures = 0; + for (int i = 1; i <= cycles; i++) + { + var sw = Stopwatch.StartNew(); + WeakReference alcRef = RunGeneration(i, payloadPath, mode, out string report); + long loadMs = sw.ElapsedMilliseconds; + sw.Restart(); + int collections = 0; + while (alcRef.IsAlive && sw.ElapsedMilliseconds < 5000) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + collections++; + if (alcRef.IsAlive) Thread.Sleep(5); + } + GC.Collect(); + bool freed = !alcRef.IsAlive; + if (!freed) failures++; + var (free, largest) = Free(); + if (i == 1) firstGenFree = free; + Log($"gen {i,2}: {report} | load+run {loadMs} ms | alc {(freed ? "freed" : "NOT freed")} after {collections} GCs, {sw.ElapsedMilliseconds} ms | free {free:F0} MB (largest {largest:F0}), vs gen1 {free - firstGenFree:+0;-0} MB | commit {s_api->CommittedMb()} MB | gc heap {GC.GetTotalMemory(false) / 1048576.0:F1} MB"); + } + var (freeEnd, _) = Free(); + Log($"done: {cycles} cycles, {failures} not freed; free {free0:F0} -> {freeEnd:F0} MB ({freeEnd - free0:+0;-0}), after gen1 {freeEnd - firstGenFree:+0;-0} MB; commit {commit0} -> {s_api->CommittedMb()} MB"); + return failures; + } + catch (Exception ex) + { + Log("Shim.Run failed: " + ex); + return -100; + } + } + + // NoInlining so no local in Run keeps the ALC, the assembly or the payload alive. + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference RunGeneration(int gen, string payloadPath, int mode, out string report) + { + var alc = new PayloadAlc($"gen{gen}", Path.GetDirectoryName(payloadPath)!, (mode & 0x100) != 0); + Assembly asm; + using (var fs = File.OpenRead(payloadPath)) asm = alc.LoadFromStream(fs); + var payload = (IPayload)Activator.CreateInstance(asm.GetType("Payload.Entry", throwOnError: true)!)!; + + var parts = new List<string>(); + nint uco = payload.GetUcoPointer(out string? ucoError); + parts.Add(uco != 0 ? $"uco 2+3={s_api->CallBinary(uco, 2, 3)}" : $"uco FAILED {ucoError}"); + nint del = payload.GetDelegatePointer(); + parts.Add($"delegate 6*7={s_api->CallBinary(del, 6, 7)}"); + parts.Add(payload.Work(mode)); + payload.Shutdown(); + + report = string.Join("; ", parts); + alc.Unload(); + return new WeakReference(alc, trackResurrection: true); + } + + private sealed class PayloadAlc : AssemblyLoadContext + { + private static readonly string s_runtimeDir = Path.GetDirectoryName(typeof(object).Assembly.Location)!; + private static readonly HashSet<string> s_private = new(StringComparer.OrdinalIgnoreCase) + { + "System.Text.Json", "System.Text.Encodings.Web", "System.IO.Pipelines", + }; + private readonly string _dir; + private readonly bool _privateFramework; + + public PayloadAlc(string name, string dir, bool privateFramework) : base(name, isCollectible: true) + { + _dir = dir; + _privateFramework = privateFramework; + } + + protected override Assembly? Load(AssemblyName name) + { + // Contracts and the framework come from the default ALC; anything else next to the payload loads here. + if (name.Name == "Contracts") return null; + if (_privateFramework && s_private.Contains(name.Name!)) + return LoadFromAssemblyPath(Path.Combine(s_runtimeDir, name.Name + ".dll")); + string candidate = Path.Combine(_dir, name.Name + ".dll"); + if (!File.Exists(candidate)) return null; + using var fs = File.OpenRead(candidate); + return LoadFromStream(fs); + } + } +} diff --git a/spikes/CoreClrHost/Shim/Shim.csproj b/spikes/CoreClrHost/Shim/Shim.csproj new file mode 100644 index 0000000..83ef59e --- /dev/null +++ b/spikes/CoreClrHost/Shim/Shim.csproj @@ -0,0 +1,14 @@ +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFramework>net10.0</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <AssemblyName>Shim</AssemblyName> + <GenerateDocumentationFile>false</GenerateDocumentationFile> + </PropertyGroup> + <ItemGroup> + <ProjectReference Include="..\Contracts\Contracts.csproj" /> + </ItemGroup> +</Project> diff --git a/spikes/CoreClrHost/native/SpikeHost.c b/spikes/CoreClrHost/native/SpikeHost.c new file mode 100644 index 0000000..776ae3d --- /dev/null +++ b/spikes/CoreClrHost/native/SpikeHost.c @@ -0,0 +1,216 @@ +// SpikeHost: Phase 0 spike for docs/UNLOADABLE_ENGINE_PLAN.md. +// +// Starts an app-local CoreCLR (x86) through the raw coreclr_* hosting API, loads +// Shim.dll into the default ALC and calls Shim.Entry.Run, which loads Payload.dll +// into a collectible ALC N times, calls into it from native code, unloads it and +// measures free address space through the HostApi below. +// +// Built as a DLL (SpikeHost.dll, export SpikeRun) so the same code can be injected +// into acclient; SpikeHostExe.exe is a console driver that LoadLibrary's it. + +#include <windows.h> +#include <stdio.h> +#include <stdarg.h> + +typedef int (__stdcall *coreclr_initialize_fn)(const char* exePath, const char* appDomainFriendlyName, + int propertyCount, const char** propertyKeys, const char** propertyValues, + void** hostHandle, unsigned int* domainId); +typedef int (__stdcall *coreclr_create_delegate_fn)(void* hostHandle, unsigned int domainId, + const char* assemblyName, const char* typeName, const char* methodName, void** fn); + +typedef struct HostApi { + int size; + double (__stdcall *freeMb)(double* largestFreeMb); + void (__stdcall *log)(const char* utf8); + int (__stdcall *callBinary)(void* fn, int a, int b); // native frame -> managed fn pointer + unsigned int (__stdcall *committedMb)(void); +} HostApi; + +typedef int (__stdcall *shim_run_fn)(HostApi* api, int cycles, int mode); + +static char g_dir[MAX_PATH]; +static FILE* g_log; + +static void LogLine(const char* fmt, ...) +{ + char buf[2048]; + va_list ap; + va_start(ap, fmt); + _vsnprintf_s(buf, sizeof buf, _TRUNCATE, fmt, ap); + va_end(ap); + SYSTEMTIME t; + GetLocalTime(&t); + char line[2200]; + _snprintf_s(line, sizeof line, _TRUNCATE, "[%02d:%02d:%02d.%03d] [pid:%lu] %s\n", + t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, GetCurrentProcessId(), buf); + fputs(line, stdout); + fflush(stdout); + if (g_log) { fputs(line, g_log); fflush(g_log); } + OutputDebugStringA(line); +} + +static double __stdcall FreeMb(double* largestFreeMb) +{ + SYSTEM_INFO si; + GetSystemInfo(&si); + unsigned char* p = (unsigned char*)si.lpMinimumApplicationAddress; + unsigned char* end = (unsigned char*)si.lpMaximumApplicationAddress; + unsigned long long total = 0, largest = 0; + MEMORY_BASIC_INFORMATION mbi; + while (p < end && VirtualQuery(p, &mbi, sizeof mbi) == sizeof mbi) { + if (mbi.State == MEM_FREE) { + total += mbi.RegionSize; + if (mbi.RegionSize > largest) largest = mbi.RegionSize; + } + p = (unsigned char*)mbi.BaseAddress + mbi.RegionSize; + } + if (largestFreeMb) *largestFreeMb = largest / (1024.0 * 1024.0); + return total / (1024.0 * 1024.0); +} + +static unsigned int __stdcall CommittedMb(void) +{ + SYSTEM_INFO si; + GetSystemInfo(&si); + unsigned char* p = (unsigned char*)si.lpMinimumApplicationAddress; + unsigned char* end = (unsigned char*)si.lpMaximumApplicationAddress; + unsigned long long total = 0; + MEMORY_BASIC_INFORMATION mbi; + while (p < end && VirtualQuery(p, &mbi, sizeof mbi) == sizeof mbi) { + if (mbi.State == MEM_COMMIT && mbi.Type == MEM_PRIVATE) total += mbi.RegionSize; + p = (unsigned char*)mbi.BaseAddress + mbi.RegionSize; + } + return (unsigned int)(total / (1024 * 1024)); +} + +static void __stdcall ManagedLog(const char* utf8) { LogLine("[shim] %s", utf8); } + +static int __stdcall CallBinary(void* fn, int a, int b) +{ + typedef int (__stdcall *bin_fn)(int, int); + return ((bin_fn)fn)(a, b); +} + +// Appends every *.dll in dir to the ';'-separated TPA list. +static void AppendDlls(char* tpa, size_t cap, const char* dir) +{ + char pattern[MAX_PATH]; + _snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\*.dll", dir); + WIN32_FIND_DATAA fd; + HANDLE h = FindFirstFileA(pattern, &fd); + if (h == INVALID_HANDLE_VALUE) return; + do { + // Native runtime DLLs sit in the same folder; skip what isn't managed. + const char* n = fd.cFileName; + if (!_stricmp(n, "coreclr.dll") || !_stricmp(n, "clrjit.dll") || !_stricmp(n, "clrgc.dll") || + !_stricmp(n, "hostfxr.dll") || !_stricmp(n, "hostpolicy.dll") || !_stricmp(n, "mscordaccore.dll") || + !_stricmp(n, "mscordbi.dll") || !_stricmp(n, "mscorrc.dll") || !_stricmp(n, "clretwrc.dll") || + !_strnicmp(n, "mscordaccore_", 13) || !_stricmp(n, "msquic.dll") || + !_stricmp(n, "System.IO.Compression.Native.dll") || !_stricmp(n, "Microsoft.DiaSymReader.Native.x86.dll") || + !_stricmp(n, "SpikeHost.dll")) + continue; + strcat_s(tpa, cap, dir); + strcat_s(tpa, cap, "\\"); + strcat_s(tpa, cap, n); + strcat_s(tpa, cap, ";"); + } while (FindNextFileA(h, &fd)); + FindClose(h); +} + +__declspec(dllexport) int __stdcall SpikeRun(int cycles, int mode) +{ + HMODULE self; + GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + (LPCSTR)&SpikeRun, &self); + GetModuleFileNameA(self, g_dir, MAX_PATH); + *strrchr(g_dir, '\\') = 0; + + char logPath[MAX_PATH]; + _snprintf_s(logPath, sizeof logPath, _TRUNCATE, "%s\\spike.%lu.log", g_dir, GetCurrentProcessId()); + fopen_s(&g_log, logPath, "a"); + + double largest; + double free0 = FreeMb(&largest); + LogLine("host: start, free %.0f MB (largest %.0f), private commit %u MB", free0, largest, CommittedMb()); + + char runtimeDir[MAX_PATH], coreclrPath[MAX_PATH]; + _snprintf_s(runtimeDir, sizeof runtimeDir, _TRUNCATE, "%s\\runtime", g_dir); + _snprintf_s(coreclrPath, sizeof coreclrPath, _TRUNCATE, "%s\\coreclr.dll", runtimeDir); + + DWORD t0 = GetTickCount(); + HMODULE clr = LoadLibraryExA(coreclrPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); + if (!clr) { LogLine("host: LoadLibrary coreclr failed %lu", GetLastError()); return -1; } + coreclr_initialize_fn init = (coreclr_initialize_fn)GetProcAddress(clr, "coreclr_initialize"); + coreclr_create_delegate_fn create = (coreclr_create_delegate_fn)GetProcAddress(clr, "coreclr_create_delegate"); + if (!init || !create) { LogLine("host: coreclr exports missing"); return -2; } + + static char tpa[64 * 1024]; + tpa[0] = 0; + AppendDlls(tpa, sizeof tpa, runtimeDir); + AppendDlls(tpa, sizeof tpa, g_dir); // Shim.dll + Contracts.dll (default ALC) + + // Mode bit 0x200: concurrent (background) GC on. + const char* keys[] = { + "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", + "System.GC.Server", "System.GC.Concurrent", "System.Globalization.Invariant", + "System.GC.RetainVM", + }; + char nativeDirs[2 * MAX_PATH + 4]; + _snprintf_s(nativeDirs, sizeof nativeDirs, _TRUNCATE, "%s;%s;", runtimeDir, g_dir); + const char* values[] = { + tpa, "", nativeDirs, + "false", (mode & 0x200) ? "true" : "false", "true", + "false", + }; + int count = sizeof keys / sizeof keys[0]; + + char exePath[MAX_PATH]; + GetModuleFileNameA(NULL, exePath, MAX_PATH); + void* hostHandle = NULL; + unsigned int domainId = 0; + int hr = init(exePath, "RynthCoreSpike", count, keys, values, &hostHandle, &domainId); + if (hr < 0) { LogLine("host: coreclr_initialize failed 0x%08x", hr); return -3; } + LogLine("host: CoreCLR up in %lu ms, free %.0f MB (cost %.0f MB), private commit %u MB", + GetTickCount() - t0, FreeMb(&largest), free0 - FreeMb(NULL), CommittedMb()); + + shim_run_fn run = NULL; + hr = create(hostHandle, domainId, "Shim", "Shim.Entry", "Run", (void**)&run); + if (hr < 0 || !run) { LogLine("host: create_delegate Shim.Entry.Run failed 0x%08x", hr); return -4; } + + static HostApi api; + api.size = sizeof api; + api.freeMb = FreeMb; + api.log = ManagedLog; + api.callBinary = CallBinary; + api.committedMb = CommittedMb; + int rc = run(&api, cycles, mode); + LogLine("host: Shim.Run returned %d, free %.0f MB (largest %.0f)", rc, FreeMb(&largest), largest); + if (g_log) { fclose(g_log); g_log = NULL; } + return rc; +} + +// Injected use: RYNTH_SPIKE_AUTORUN="cycles,mode,delayMs" in the target's environment +// makes DllMain start a worker (no CLR work under the loader lock). +static int g_autoCycles = 20, g_autoMode = 0, g_autoDelay = 3000; + +static DWORD WINAPI AutoRun(LPVOID p) +{ + (void)p; + Sleep(g_autoDelay); + SpikeRun(g_autoCycles, g_autoMode); + return 0; +} + +BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID reserved) +{ + (void)h; (void)reserved; + if (reason == DLL_PROCESS_ATTACH) { + char v[64]; + if (GetEnvironmentVariableA("RYNTH_SPIKE_AUTORUN", v, sizeof v) > 0) { + sscanf_s(v, "%d,%i,%d", &g_autoCycles, &g_autoMode, &g_autoDelay); + HANDLE t = CreateThread(NULL, 0, AutoRun, NULL, 0, NULL); + if (t) CloseHandle(t); + } + } + return TRUE; +} diff --git a/spikes/CoreClrHost/native/SpikeHostExe.c b/spikes/CoreClrHost/native/SpikeHostExe.c new file mode 100644 index 0000000..e9e087a --- /dev/null +++ b/spikes/CoreClrHost/native/SpikeHostExe.c @@ -0,0 +1,19 @@ +// Console driver: SpikeHostExe.exe [cycles] [mode]. LoadLibrary's SpikeHost.dll the +// way an injected loader would and calls SpikeRun. +#include <windows.h> +#include <stdio.h> +#include <stdlib.h> + +typedef int (__stdcall *spike_run_fn)(int cycles, int mode); + +int main(int argc, char** argv) +{ + int cycles = argc > 1 ? atoi(argv[1]) : 20; + int mode = argc > 2 ? (int)strtol(argv[2], NULL, 0) : 0; + HMODULE h = LoadLibraryA("SpikeHost.dll"); + if (!h) { printf("LoadLibrary SpikeHost.dll failed %lu\n", GetLastError()); return 1; } + spike_run_fn run = (spike_run_fn)GetProcAddress(h, "_SpikeRun@8"); + if (!run) run = (spike_run_fn)GetProcAddress(h, "SpikeRun"); + if (!run) { printf("SpikeRun export missing\n"); return 2; } + return run(cycles, mode); +} diff --git a/spikes/CoreClrHost/native/SpikeInject.c b/spikes/CoreClrHost/native/SpikeInject.c new file mode 100644 index 0000000..25f2eb4 --- /dev/null +++ b/spikes/CoreClrHost/native/SpikeInject.c @@ -0,0 +1,53 @@ +// SpikeInject: starts acclient.exe suspended, LoadLibrary's SpikeHost.dll into it with +// RYNTH_SPIKE_AUTORUN set, resumes it, waits, then terminates it. +// SpikeInject.exe <acclient.exe> <SpikeHost.dll> <cycles,mode,delayMs> <waitSeconds> [acclient args...] +#include <windows.h> +#include <stdio.h> +#include <string.h> + +int main(int argc, char** argv) +{ + if (argc < 5) { printf("usage: SpikeInject <acclient.exe> <SpikeHost.dll> <cycles,mode,delayMs> <waitSeconds> [args]\n"); return 1; } + const char* exe = argv[1]; + const char* dll = argv[2]; + int waitSeconds = atoi(argv[4]); + SetEnvironmentVariableA("RYNTH_SPIKE_AUTORUN", argv[3]); + + char cmd[4096]; + _snprintf_s(cmd, sizeof cmd, _TRUNCATE, "\"%s\"", exe); + for (int i = 5; i < argc; i++) { strcat_s(cmd, sizeof cmd, " "); strcat_s(cmd, sizeof cmd, argv[i]); } + char dir[MAX_PATH]; + strcpy_s(dir, sizeof dir, exe); + *strrchr(dir, '\\') = 0; + + STARTUPINFOA si = { sizeof si }; + PROCESS_INFORMATION pi; + if (!CreateProcessA(exe, cmd, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, dir, &si, &pi)) { + printf("CreateProcess failed %lu\n", GetLastError()); return 2; + } + printf("SPIKE_PID=%lu\n", pi.dwProcessId); + + size_t len = strlen(dll) + 1; + void* remote = VirtualAllocEx(pi.hProcess, NULL, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + WriteProcessMemory(pi.hProcess, remote, dll, len, NULL); + FARPROC loadLib = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA"); + HANDLE t = CreateRemoteThread(pi.hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)loadLib, remote, 0, NULL); + if (!t) { printf("CreateRemoteThread failed %lu\n", GetLastError()); TerminateProcess(pi.hProcess, 1); return 3; } + WaitForSingleObject(t, 30000); + DWORD mod = 0; + GetExitCodeThread(t, &mod); + printf("LoadLibrary in target -> 0x%08lx\n", mod); + CloseHandle(t); + ResumeThread(pi.hThread); + + DWORD r = WaitForSingleObject(pi.hProcess, waitSeconds * 1000); + if (r == WAIT_OBJECT_0) { + DWORD code = 0; + GetExitCodeProcess(pi.hProcess, &code); + printf("acclient exited by itself, code 0x%08lx\n", code); + } else { + TerminateProcess(pi.hProcess, 0); + printf("acclient terminated after %d s\n", waitSeconds); + } + return 0; +} diff --git a/spikes/DecalBridge/AcWindow.py b/spikes/DecalBridge/AcWindow.py new file mode 100644 index 0000000..546b845 --- /dev/null +++ b/spikes/DecalBridge/AcWindow.py @@ -0,0 +1,169 @@ +"""AcWindow.py - look at and click ONE test client's game window, by its process id. + +Spike helper (Decal bridge): used once, to drive the retail character-creation screen of a +test client. Everything goes to the HWND of the given pid (PostMessage), so no other window +- and no other client - is touched, and nothing moves the real mouse or keyboard. + + python AcWindow.py shot <pid> <out.png> + python AcWindow.py click <pid> <x> <y> client coordinates of the game window + python AcWindow.py type <pid> <text> + python AcWindow.py key <pid> <vk> e.g. 0x0D (Enter), 0x08 (Backspace) +""" +import ctypes +import ctypes.wintypes as wt +import sys +import time + +user32 = ctypes.WinDLL("user32", use_last_error=True) +gdi32 = ctypes.WinDLL("gdi32", use_last_error=True) +user32.PostMessageW.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p] +user32.GetClientRect.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.RECT)] +user32.GetWindowThreadProcessId.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.DWORD)] +user32.GetClassNameW.argtypes = [ctypes.c_void_p, wt.LPWSTR, ctypes.c_int] +user32.IsWindowVisible.argtypes = [ctypes.c_void_p] +user32.PrintWindow.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint] +user32.GetDC.argtypes = [ctypes.c_void_p] +user32.GetDC.restype = ctypes.c_void_p +user32.ReleaseDC.argtypes = [ctypes.c_void_p, ctypes.c_void_p] +gdi32.CreateCompatibleDC.argtypes = [ctypes.c_void_p] +gdi32.CreateCompatibleDC.restype = ctypes.c_void_p +gdi32.CreateCompatibleBitmap.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] +gdi32.CreateCompatibleBitmap.restype = ctypes.c_void_p +gdi32.SelectObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p] +gdi32.GetDIBits.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint] +gdi32.DeleteObject.argtypes = [ctypes.c_void_p] +gdi32.DeleteDC.argtypes = [ctypes.c_void_p] + +WM_MOUSEMOVE, WM_LBUTTONDOWN, WM_LBUTTONUP = 0x0200, 0x0201, 0x0202 +WM_KEYDOWN, WM_KEYUP, WM_CHAR = 0x0100, 0x0101, 0x0102 + + +def game_window(pid): + found = [] + proto = ctypes.WINFUNCTYPE(wt.BOOL, ctypes.c_void_p, ctypes.c_void_p) + + def cb(hwnd, _): + owner = wt.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + if owner.value == pid and user32.IsWindowVisible(hwnd): + cls = ctypes.create_unicode_buffer(128) + user32.GetClassNameW(hwnd, cls, 128) + if cls.value == "Turbine Device Class": + found.append(hwnd) + return True + + user32.EnumWindows(proto(cb), None) + if not found: + raise SystemExit(f"no game window for pid {pid}") + return found[0] + + +def dialogs(pid): + """Message boxes (#32770) the process has open, with their static text.""" + proto = ctypes.WINFUNCTYPE(wt.BOOL, ctypes.c_void_p, ctypes.c_void_p) + user32.GetWindowTextW.argtypes = [ctypes.c_void_p, wt.LPWSTR, ctypes.c_int] + out = [] + + def top(hwnd, _): + owner = wt.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + cls = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(hwnd, cls, 64) + if owner.value == pid and cls.value == "#32770" and user32.IsWindowVisible(hwnd): + texts = [] + + def child(ch, _): + c = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(ch, c, 64) + t = ctypes.create_unicode_buffer(1024) + user32.GetWindowTextW(ch, t, 1024) + if t.value: + texts.append(f"{c.value}: {t.value}") + return True + + user32.EnumChildWindows(ctypes.c_void_p(hwnd), proto(child), None) + out.append((hwnd, texts)) + return True + + user32.EnumWindows(proto(top), None) + for hwnd, texts in out: + print(f"dialog 0x{hwnd:X}: " + " | ".join(texts)) + if not out: + print("no dialogs") + + +def shot(pid, out): + from PIL import Image + hwnd = game_window(pid) + r = wt.RECT() + user32.GetClientRect(hwnd, ctypes.byref(r)) + w, h = r.right, r.bottom + hdc = user32.GetDC(hwnd) + mdc = gdi32.CreateCompatibleDC(hdc) + bmp = gdi32.CreateCompatibleBitmap(hdc, w, h) + gdi32.SelectObject(mdc, bmp) + user32.PrintWindow(hwnd, mdc, 3) # PW_CLIENTONLY | PW_RENDERFULLCONTENT + bmi = (ctypes.c_byte * 40)() + ctypes.memmove(bmi, (ctypes.c_int * 3)(40, w, -h), 12) + ctypes.memmove(ctypes.byref(bmi, 12), (ctypes.c_short * 2)(1, 32), 4) + buf = (ctypes.c_byte * (w * h * 4))() + gdi32.GetDIBits(mdc, bmp, 0, h, buf, bmi, 0) + Image.frombuffer("RGB", (w, h), bytes(buf), "raw", "BGRX", 0, 1).save(out) + gdi32.DeleteObject(bmp) + gdi32.DeleteDC(mdc) + user32.ReleaseDC(hwnd, hdc) + print(f"{w}x{h} -> {out}") + + +def click(pid, x, y): + hwnd = game_window(pid) + lp = (y << 16) | (x & 0xFFFF) + user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp) + time.sleep(0.05) + user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, lp) + time.sleep(0.08) + user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp) + + +def drag(pid, x0, y0, x1, y1): + hwnd = game_window(pid) + user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, (y0 << 16) | x0) + time.sleep(0.05) + user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, (y0 << 16) | x0) + for i in range(1, 11): + x = x0 + (x1 - x0) * i // 10 + y = y0 + (y1 - y0) * i // 10 + time.sleep(0.03) + user32.PostMessageW(hwnd, WM_MOUSEMOVE, 1, (y << 16) | x) + time.sleep(0.05) + user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, (y1 << 16) | x1) + + +def type_text(pid, text): + hwnd = game_window(pid) + for ch in text: + user32.PostMessageW(hwnd, WM_CHAR, ord(ch), 1) + time.sleep(0.04) + + +def key(pid, vk): + hwnd = game_window(pid) + user32.PostMessageW(hwnd, WM_KEYDOWN, vk, 1) + time.sleep(0.05) + user32.PostMessageW(hwnd, WM_KEYUP, vk, 0xC0000001) + + +if __name__ == "__main__": + cmd, pid = sys.argv[1], int(sys.argv[2]) + if cmd == "shot": + shot(pid, sys.argv[3]) + elif cmd == "click": + click(pid, int(sys.argv[3]), int(sys.argv[4])) + elif cmd == "dialogs": + dialogs(pid) + elif cmd == "drag": + drag(pid, *(int(v) for v in sys.argv[3:7])) + elif cmd == "type": + type_text(pid, sys.argv[3]) + elif cmd == "key": + key(pid, int(sys.argv[3], 0)) diff --git a/spikes/DecalBridge/BridgeProbePlugin/BridgeProbePlugin.cs b/spikes/DecalBridge/BridgeProbePlugin/BridgeProbePlugin.cs new file mode 100644 index 0000000..8657bd9 --- /dev/null +++ b/spikes/DecalBridge/BridgeProbePlugin/BridgeProbePlugin.cs @@ -0,0 +1,157 @@ +// BridgeProbe - a trivial RynthCore plugin for the Decal-bridge spike. It logs the first +// few of every event it receives, and a count per event every 15 s, through the host log, +// so the engine log shows what reached a plugin in bridge mode. +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.PluginCore; + +namespace RynthCore.Plugin.BridgeProbe; + +public sealed class BridgeProbePlugin : RynthPluginBase +{ + internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("BridgeProbe"); + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0"); + + private int _raLines; + private int _chat, _chatBar, _create, _delete, _update, _health, _damage, _enchAdd, _enchRem, _kill, _ticks; + private long _lastSummary; + private const int FirstN = 5; + // Every chat line, for reading command output on a test client: BRIDGEPROBE_ALLCHAT=1, or a + // file "bridgeprobe-allchat.flag" next to the client's dispatch file (read at plugin load). + private static readonly bool AllChat = Environment.GetEnvironmentVariable("BRIDGEPROBE_ALLCHAT") == "1" || FlagFileExists(); + + private static bool FlagFileExists() + { + try + { + string? dispatch = Environment.GetEnvironmentVariable("RYNTHCORE_DISPATCH_FILE"); + string? dir = string.IsNullOrEmpty(dispatch) ? null : System.IO.Path.GetDirectoryName(dispatch); + return dir != null && System.IO.File.Exists(System.IO.Path.Combine(dir, "bridgeprobe-allchat.flag")); + } + catch { return false; } + } + + public override int Initialize() + { + Log("BridgeProbe: initialized."); + return 0; + } + + public override void OnLoginComplete() => Log("BridgeProbe: OnLoginComplete"); + + public override void OnChatWindowText(string? text, int chatType, ref int eat) + { + // BRIDGEPROBE_ALLCHAT=1: log every chat line (reading command output on a test client). + if (_chat++ < FirstN || AllChat) Log($"BridgeProbe: OnChatWindowText type={chatType} '{text?.TrimEnd('\n')}'"); + // RynthAi's answers to the harness's "/ra cache": its object cache, as seen in chat. + else if (text != null && text.Contains("[RynthAi]") && _raLines++ < 30) + Log($"BridgeProbe: RynthAi said: '{text.TrimEnd('\n')}'"); + } + + public override void OnChatBarEnter(string? text, ref int eat) + { + if (_chatBar++ < FirstN) Log($"BridgeProbe: OnChatBarEnter '{text}'"); + } + + public override void OnCreateObject(uint objectId) + { + if (_create++ < FirstN) Log($"BridgeProbe: OnCreateObject 0x{objectId:X8}"); + } + + public override void OnDeleteObject(uint objectId) + { + if (_delete++ < FirstN) Log($"BridgeProbe: OnDeleteObject 0x{objectId:X8}"); + } + + public override void OnUpdateObject(uint objectId) => _update++; + + public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) + { + if (_health++ < FirstN) Log($"BridgeProbe: OnUpdateHealth 0x{targetId:X8} ratio={healthRatio:0.00} {currentHealth}/{maxHealth}"); + } + + public override void OnCombatDamage(uint damage, uint damageType, bool crit, bool isAttacker) + { + if (_damage++ < FirstN) Log($"BridgeProbe: OnCombatDamage {damage} type={damageType} crit={crit} attacker={isAttacker}"); + } + + public override void OnKillNotification(string? deathMessage) + { + if (_kill++ < FirstN) Log($"BridgeProbe: OnKillNotification '{deathMessage}'"); + } + + public override void OnEnchantmentAdded(uint spellId, double durationSeconds) + { + if (_enchAdd++ < FirstN) Log($"BridgeProbe: OnEnchantmentAdded spell={spellId} dur={durationSeconds:0}"); + } + + public override void OnEnchantmentRemoved(uint enchantmentId) + { + if (_enchRem++ < FirstN) Log($"BridgeProbe: OnEnchantmentRemoved {enchantmentId}"); + } + + public override void OnTick() + { + _ticks++; + long now = Environment.TickCount64; + if (now - _lastSummary < 15000) return; + _lastSummary = now; + Log($"BridgeProbe: counts ticks={_ticks} chat={_chat} chatBar={_chatBar} create={_create} delete={_delete} update={_update} " + + $"health={_health} damage={_damage} kill={_kill} enchAdd={_enchAdd} enchRem={_enchRem}"); + } +} + +public static unsafe class PluginExports +{ + private static readonly RynthPluginRuntime<BridgeProbePlugin> Runtime = new(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Init(RynthCore.PluginSdk.RynthCoreApiNative* api) => Runtime.Init(api); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Shutdown() => Runtime.Shutdown(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetName() => BridgeProbePlugin.NamePointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetVersion() => BridgeProbePlugin.VersionPointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Tick() => Runtime.OnTick(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLoginComplete() => Runtime.OnLoginComplete(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUpdateObject(uint objectId) => Runtime.OnUpdateObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) + => Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatDamage", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnCombatDamage(uint damage, uint damageType, uint crit, uint isAttacker) => Runtime.OnCombatDamage(damage, damageType, crit, isAttacker); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnKillNotification", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnKillNotification(IntPtr textUtf16) => Runtime.OnKillNotification(textUtf16); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentAdded", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnEnchantmentAdded(uint spellId, double durationSeconds) => Runtime.OnEnchantmentAdded(spellId, durationSeconds); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentRemoved", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnEnchantmentRemoved(uint enchantmentId) => Runtime.OnEnchantmentRemoved(enchantmentId); +} diff --git a/spikes/DecalBridge/BridgeProbePlugin/RynthCore.Plugin.BridgeProbe.csproj b/spikes/DecalBridge/BridgeProbePlugin/RynthCore.Plugin.BridgeProbe.csproj new file mode 100644 index 0000000..eb2dd54 --- /dev/null +++ b/spikes/DecalBridge/BridgeProbePlugin/RynthCore.Plugin.BridgeProbe.csproj @@ -0,0 +1,23 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- Spike (Decal bridge): a managed plugin for the CoreCLR engine that logs what it receives. + dotnet publish -c Release -o C:\Games\RynthCore\Test\plugins-decal\BridgeProbe --> + <PropertyGroup> + <TargetFramework>net10.0-windows</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <RuntimeIdentifier>win-x86</RuntimeIdentifier> + <SelfContained>false</SelfContained> + <GenerateRuntimeConfigurationFiles>false</GenerateRuntimeConfigurationFiles> + <OutputType>Library</OutputType> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <Nullable>enable</Nullable> + <AssemblyName>RynthCore.Plugin.BridgeProbe</AssemblyName> + <RootNamespace>RynthCore.Plugin.BridgeProbe</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <ProjectReference Include="..\..\..\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" /> + <ProjectReference Include="..\..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" /> + </ItemGroup> + +</Project> diff --git a/spikes/DecalBridge/Inject-BridgeRecords.py b/spikes/DecalBridge/Inject-BridgeRecords.py new file mode 100644 index 0000000..d73a225 --- /dev/null +++ b/spikes/DecalBridge/Inject-BridgeRecords.py @@ -0,0 +1,65 @@ +"""Inject-BridgeRecords.py <pid> - append SYNTHETIC records to a test client's Decal-bridge ring. + +For testing the engine half of the bridge while no server is available: it writes the same +records the bridge would (BridgeProtocol.cs layout) into Local\\RynthCore.DecalBridge.p<pid>. +Only use it on a test client whose bridge is idle (pre-login), or the two writers race. +""" +import mmap +import struct +import sys + +# BridgeProtocol.cs version 2: header, 64 KB command ring, then the event ring. +HEADER, CMD, RING = 4096, 64 * 1024, 16 * 1024 * 1024 +RING_BASE = HEADER + CMD +OFF_WRITE, OFF_READ, OFF_RECORDS = 16, 24, 40 +K_CHAT, K_CHATBAR, K_CREATE, K_RELEASE, K_CHANGE, K_SERVER = 2, 3, 4, 5, 6, 7 + + +def main(): + pid = int(sys.argv[1]) + m = mmap.mmap(-1, RING_BASE + RING, tagname=f"Local\\RynthCore.DecalBridge.p{pid}") + magic, version = struct.unpack_from("<II", m, 0) + assert magic == 0x42444352 and version == 2, (hex(magic), version) + + def write(kind, a0=0, a1=0, payload=b""): + w, r = struct.unpack_from("<qq", m, OFF_WRITE) + rec = 16 + len(payload) + rec = (rec + 3) & ~3 + pad = rec - 16 - len(payload) + pos = w % RING + assert RING - pos >= rec and RING - (w - r) > rec + base = RING_BASE + pos + struct.pack_into("<iHHII", m, base, rec, kind, pad, a0, a1) + m[base + 16: base + 16 + len(payload)] = payload + struct.pack_into("<q", m, OFF_WRITE, w + rec) # publish + struct.pack_into("<q", m, OFF_RECORDS, struct.unpack_from("<q", m, OFF_RECORDS)[0] + 1) + + def game_event(ev, body): + return struct.pack("<IIII", 0xF7B0, 0x50000001, 7, ev) + body + + write(K_CHAT, 0x03, 0, "[synthetic] You say, \"hello from the bridge test\"\n".encode("utf-16-le")) + write(K_CHAT, 0x17, 0, "[synthetic] Welcome to Asheron's Call\n".encode("utf-16-le")) + write(K_CHATBAR, 0, 0, "[synthetic] hello world".encode("utf-16-le")) + for oid in (0x80000101, 0x80000102, 0x80000103): + write(K_CREATE, oid) + write(K_CHANGE, 0x80000102, 2) + write(K_RELEASE, 0x80000103) + # Game events, as Decal's Message.RawData: [F7B0][objectId][sequence][eventType][payload] + write(K_SERVER, 0xF7B0, 0, game_event(0x01C7, struct.pack("<I", 0))) # UseDone, no error + write(K_SERVER, 0xF7B0, 0, game_event(0x028A, struct.pack("<I", 0x0402))) # WeenieError + write(K_SERVER, 0xF7B0, 0, game_event(0x01C0, struct.pack("<If", 0x80000101, 0.5))) # UpdateHealth 50 % + # spellId, layer, category, hasSpellSet, powerLevel, startTime, duration (+20), then 32 bytes + ench = struct.pack("<HHHHI", 2, 1, 0, 0, 1) + struct.pack("<dd", 0.0, 1800.0) + b"\0" * 32 + assert len(ench) == 60 + write(K_SERVER, 0xF7B0, 0, game_event(0x02C2, ench)) # UpdateEnchantment spell 2 + write(K_SERVER, 0xF7B0, 0, game_event(0x02C3, struct.pack("<HH", 2, 1))) # RemoveEnchantment spell 2 + name = b"Drudge" + s16 = struct.pack("<H", len(name)) + name + s16 += b"\0" * (((len(s16) + 3) // 4) * 4 - len(s16)) + write(K_SERVER, 0xF7B0, 0, game_event(0x01B1, s16 + struct.pack("<IdII", 4, 0.3, 57, 1))) # we hit: 57, crit + write(K_SERVER, 0xF745, 0, struct.pack("<II", 0xF745, 0x80000104)) # some other message + print("wrote synthetic records; ring now", struct.unpack_from("<qq", m, OFF_WRITE)) + + +if __name__ == "__main__": + main() diff --git a/spikes/DecalBridge/Measure-HookRace.ps1 b/spikes/DecalBridge/Measure-HookRace.ps1 new file mode 100644 index 0000000..002890b --- /dev/null +++ b/spikes/DecalBridge/Measure-HookRace.ps1 @@ -0,0 +1,30 @@ +# Measure-HookRace.ps1 - how often Decal's patch ends up on top of ours at the entry points +# both of us detour (old coexistence mode, no bridge), and what a hot reload then does. +# No server needed (the race is decided in the first seconds). TEST clients only. +param([int]$Launches = 6, [string]$Runtime = "C:\Games\RynthCore\Test\rt-decal") +$ErrorActionPreference = "Stop" +$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent +$watch = "$repo\tools\WatchPatch.py" +$addrs = @("0x005649F0", "0x004CBF70", "0x005821A0") # AddTextToScroll, gmSalvageUI::OpenSalvagePanel, outgoing chat +for ($i = 1; $i -le $Launches; $i++) { + & "$PSScriptRoot\Start-DecalTestClient.ps1" -Mode Both -NoBridge -Runtime $Runtime *> $null + $tp = [int]((Get-Content C:\Games\RynthCore\Test\decal-spike-pids.txt -Tail 1).Split(' ')[2]) + Write-Host "==== launch $i pid $tp" + $lines = python $watch $tp 25 @addrs 2>&1 + $lines | ForEach-Object { Write-Host " $_" } + $final = @{} + foreach ($l in $lines) { if ($l -match '^\S+ (0x[0-9A-F]{8}) \S+ -> (.*)$') { $final[$Matches[1]] = $Matches[2] } } + $lost = $addrs[0..1] | Where-Object { $final[$_] -like "Decal*" } + Write-Host " final: $(($addrs | ForEach-Object { "$_=$($final[$_])" }) -join '; ')" + if ($lost) { + Write-Host " Decal is on top at $($lost -join ', ') -> hot reload, watching" + $job = Start-Job { python $using:watch $using:tp 14 @using:addrs 2>&1 } + Start-Sleep 1 + $ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$tp") + [void]$ev.Set(); $ev.Dispose() + Wait-Job $job -Timeout 30 | Out-Null + Receive-Job $job | ForEach-Object { Write-Host " $_" } + } + Stop-Process -Id $tp -Force -ErrorAction SilentlyContinue + Start-Sleep 2 +} diff --git a/spikes/DecalBridge/Register-DecalBridge.ps1 b/spikes/DecalBridge/Register-DecalBridge.ps1 new file mode 100644 index 0000000..dfcf3b8 --- /dev/null +++ b/spikes/DecalBridge/Register-DecalBridge.ps1 @@ -0,0 +1,37 @@ +# Register-DecalBridge.ps1 - registers (or removes) the RynthCore Decal bridge for this +# Windows user, for TEST clients. A thin wrapper over the real code +# (src\RynthCore.App\DecalBridgeRegistration.cs, the same class the launcher uses for +# "Decal + RynthCore" accounts), reached through RynthCore.Injector --decal-bridge. +# +# What it does (docs\DECAL_BRIDGE_PLAN.md, "Registration"): no admin rights, nothing under +# HKLM. The bridge's entry goes into the per-user registry VirtualStore copy of Decal's +# NetworkFilters key, which the virtualized 32-bit acclient.exe reads instead of HKLM's. If +# that per-user key has to be created, every HKLM filter entry is mirrored into it first +# (otherwise Decal would see only the bridge: no WorldFilter, VTank refuses to start). +# Everything added is recorded in %APPDATA%\RynthCore\decal-bridge-registration.json and +# -Remove takes away exactly that. +# +# The bridge idles in every Decal client of this user until RynthCore is in the same client. +# +# .\Register-DecalBridge.ps1 build the bridge, copy it to Test\decal-bridge, register +# .\Register-DecalBridge.ps1 -Status show what a Decal client would load +# .\Register-DecalBridge.ps1 -Remove remove what the registration added +param([switch]$Remove, [switch]$Status) +$ErrorActionPreference = "Stop" +$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent +$dir = "C:\Games\RynthCore\Test\decal-bridge" +$injector = "$repo\out\injector-spike\RynthCore.Injector.exe" +dotnet publish "$repo\src\RynthCore.Injector\RynthCore.Injector.csproj" -c Release -o "$repo\out\injector-spike" -nologo -v q | Out-Null +if ($LASTEXITCODE -ne 0) { throw "injector build failed" } + +if ($Status) { & $injector --decal-bridge status; return } +if ($Remove) { & $injector --decal-bridge unregister; return } + +dotnet build "$repo\src\RynthCore.DecalBridge\RynthCore.DecalBridge.csproj" -c Release -nologo -v q | Out-Null +if ($LASTEXITCODE -ne 0) { throw "bridge build failed" } +$built = "$repo\src\RynthCore.DecalBridge\bin\Release\RynthCore.DecalBridge.dll" +if (-not (Test-Path $built)) { throw "bridge not built (is Decal installed?)" } +New-Item -ItemType Directory -Force $dir | Out-Null +# Decal clients that loaded the old copy keep it locked until they exit. +Copy-Item $built $dir -Force +& $injector --decal-bridge register --dir $dir diff --git a/spikes/DecalBridge/Start-DecalTestClient.ps1 b/spikes/DecalBridge/Start-DecalTestClient.ps1 new file mode 100644 index 0000000..31c8182 --- /dev/null +++ b/spikes/DecalBridge/Start-DecalTestClient.ps1 @@ -0,0 +1,59 @@ +# Start-DecalTestClient.ps1 - Decal-bridge spike: start ONE test client with Decal and/or +# the CoreCLR RynthCore engine from a TEST runtime folder, against Tom's local server. +# +# -Mode DecalOnly Decal alone (Inject.dll + DecalStartup) - baseline +# -Mode EngineOnly RynthCore alone - baseline +# -Mode Both Decal first, then RynthCore (the coexistence case) +# +# Same isolation as scripts\Test-ClrWorld.ps1: its own engine settings, LOCALAPPDATA and +# dispatch file; RYNTHCORE_TEST_CLIENT marks it. -Bridge sets the engine's bridge mode for this +# client only (RYNTHCORE_DECAL_BRIDGE: Auto = unset, the engine.json default; On = 1; Off = 0, +# which also keeps the bridge filter itself idle); -InGameUi does the same for DecalInGameImGui. +# The bridge arms by itself when the RynthCore loader is in the client, so it must be registered +# (RynthCore.Injector --decal-bridge register). +# Never point -Runtime at C:\Games\RynthCore\Runtime (the live runtime every client shares). +param( + [ValidateSet("DecalOnly", "EngineOnly", "Both")] [string]$Mode = "Both", + [string]$Account = "Buffi", + [string]$Server = "ACEmulator", + [string]$Character = "+Buffi", + [string]$Runtime = "C:\Games\RynthCore\Test\rt-decal", + [string]$Settings = "C:\Games\RynthCore\Test\engine-decal.json", + # Override the server profile's host/port for this launch (the profile is not changed). + [string]$HostName = "", + [int]$Port = 0, + [ValidateSet("Auto", "On", "Off")] [string]$Bridge = "Auto", + [switch]$NoBridge, # = -Bridge Off + # In-game ImGui under Decal (engine.json DecalInGameImGui, default on): Default leaves + # RYNTHCORE_DECAL_IMGUI unset; On = 1; Off = 0 (the old coexistence path, no D3D9). + [ValidateSet("Default", "On", "Off")] [string]$InGameUi = "Default" +) +$ErrorActionPreference = "Stop" +if ([IO.Path]::GetFullPath($Runtime).TrimEnd('\') -ieq "C:\Games\RynthCore\Runtime") { throw "refusing the live runtime" } +$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent +$injector = "$repo\out\injector-spike\RynthCore.Injector.exe" +if (-not (Test-Path $injector)) { + dotnet publish "$repo\src\RynthCore.Injector\RynthCore.Injector.csproj" -c Release -o "$repo\out\injector-spike" -nologo -v q | Out-Null +} +$env:RYNTHCORE_ENGINE_SETTINGS = $Settings +$env:RYNTHCORE_TEST_CLIENT = "DecalBridgeSpike" +$env:LOCALAPPDATA = "C:\Games\RynthCore\Test\localappdata" +New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null +$env:RYNTHCORE_DISPATCH_FILE = "C:\Games\RynthCore\Test\dispatch-decal.txt" +Set-Content $env:RYNTHCORE_DISPATCH_FILE "# decal spike dispatch file" +# Set or clear both every time: a script run in the same session must not inherit the last run's. +if ($NoBridge) { $Bridge = "Off" } +$env:RYNTHCORE_DECAL_BRIDGE = switch ($Bridge) { "On" { "1" } "Off" { "0" } default { $null } } +$env:RYNTHCORE_DECAL_IMGUI = switch ($InGameUi) { "On" { "1" } "Off" { "0" } default { $null } } + +$launchArgs = @("--launch", "--account", $Account, "--server", $Server, "--engine", "$Runtime\RynthCore.Loader.dll", "--character", $Character) +if ($Mode -eq "DecalOnly") { $launchArgs += "--decal-only" } elseif ($Mode -eq "Both") { $launchArgs += "--decal" } +if ($HostName) { $launchArgs += @("--host", $HostName) } +if ($Port -gt 0) { $launchArgs += @("--port", "$Port") } +$out = & $injector $launchArgs 2>&1 +$out | ForEach-Object { Write-Host " $_" } +$m = $out | Select-String "LAUNCHED_PID=(\d+)" +if (-not $m) { throw "launch failed" } +$clientPid = [int]$m.Matches[0].Groups[1].Value +Add-Content "C:\Games\RynthCore\Test\decal-spike-pids.txt" "$(Get-Date -Format s) $Mode $clientPid" +Write-Host "TEST_PID=$clientPid" diff --git a/spikes/DecalBridge/Test-DecalBridgeInWorld.ps1 b/spikes/DecalBridge/Test-DecalBridgeInWorld.ps1 new file mode 100644 index 0000000..5848ede --- /dev/null +++ b/spikes/DecalBridge/Test-DecalBridgeInWorld.ps1 @@ -0,0 +1,168 @@ +# Test-DecalBridgeInWorld.ps1 - the in-world half of the Decal-bridge spike, in one command. +# Needs Tom's LOCAL server running and the bridge registered (Register-DecalBridge.ps1, or +# RynthCore.Injector --decal-bridge register --dir <folder with RynthCore.DecalBridge.dll>). +# TEST CLIENTS ONLY: it starts its own clients from C:\Games\RynthCore\AcClient and kills only +# the PIDs it started. Three runs, one test client at a time: +# A Decal only (opt-in: -Runs A,B,C; nothing auto-selects the character without the +# engine, so pick it by hand) -> which code Decal + its plugins patch in world +# B Decal + RynthCore, bridge (DecalBridge=Auto) -> bridge traffic, a plugin receiving it, +# a TYPED chat-bar command, a line sent to AC through +# Decal (/loc), 2 hot reloads, VTank loaded, the own-device +# ImGui pop-out (snapshot BMP) +# C Decal + RynthCore, DecalBridge=Off (the old coexistence mode) -> who owns the contested hooks +# D RynthCore only, no Decal (normal hook mode must be unchanged) +# Everything lands in C:\Games\RynthCore\Test\decal-bridge\inworld-<time>\. +# +# .\spikes\DecalBridge\Test-DecalBridgeInWorld.ps1 -Account Buffi -Server ACEmulator -Character "+Buffi" +param( + [string]$Account = "Buffi", + [string]$Server = "ACEmulator", + [string]$Character = "+Buffi", + [string]$HostName = "", + [int]$Port = 0, + [string[]]$Runs = @("B", "C", "D"), + [int]$LoginTimeout = 150, + [string]$Runtime = "C:\Games\RynthCore\Test\rt-decal", + [string]$Settings = "C:\Games\RynthCore\Test\engine-decal.json", + [int]$Settle = 30 +) +$ErrorActionPreference = "Stop" +$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent +$start = "$PSScriptRoot\Start-DecalTestClient.ps1" +$diff = "$repo\tools\ProcPatchDiff.py" +$out = "C:\Games\RynthCore\Test\decal-bridge\inworld-$(Get-Date -Format yyyyMMdd-HHmmss)" +New-Item -ItemType Directory -Force $out | Out-Null +$report = "$out\report.txt" +function Say([string]$s) { Write-Host $s; Add-Content $report $s } + +$checkPort = if ($Port -gt 0) { $Port } else { 9000 } +if (-not (Get-NetUDPEndpoint -ErrorAction SilentlyContinue | Where-Object LocalPort -eq $checkPort)) { + throw "Nothing listens on UDP ${checkPort}: start the local ACE server first." +} +$vs = "HKCU:\Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\NetworkFilters" +if (-not (Get-ChildItem $vs -ErrorAction SilentlyContinue | Where-Object { (Get-ItemProperty $_.PSPath).Object -eq "RynthCore.DecalBridge.BridgeFilter" })) { + throw "The bridge is not registered: run Register-DecalBridge.ps1 first." +} + +function Start-One([string]$mode, [string[]]$extra) { + $opts = @{ Mode = $mode; Account = $Account; Server = $Server; Character = $Character; HostName = $HostName; Port = $Port; Runtime = $Runtime; Settings = $Settings } + foreach ($e in $extra) { $opts[$e] = $true } + & $start @opts *> $null + return [int]((Get-Content C:\Games\RynthCore\Test\decal-spike-pids.txt -Tail 1).Split(' ')[2]) +} +function Wait-Match([string]$path, [string]$pattern, [int]$seconds) { + $t0 = Get-Date + while (((Get-Date) - $t0).TotalSeconds -lt $seconds) { + if ((Test-Path $path) -and (Select-String -Path $path -Pattern $pattern -Quiet)) { return $true } + Start-Sleep 2 + } + return $false +} +function Stop-One([int]$tp) { + Stop-Process -Id $tp -Force -ErrorAction SilentlyContinue + Say "stopped $tp; waiting 65 s for the server to drop the session" + Start-Sleep 65 +} +function Grab([string]$path, [string]$pattern, [int]$max = 60) { + if (Test-Path $path) { + Select-String -Path $path -Pattern $pattern | Select-Object -Last $max | + ForEach-Object { Say (" " + $_.Line.Substring(0, [Math]::Min(300, $_.Line.Length))) } + } +} +function Send([string]$cmd) { + # Through the test client's dispatch file -> AC's main thread -> plugins' OnChatBarEnter. + Set-Content "C:\Games\RynthCore\Test\dispatch-decal.txt" "force:$cmd" + Start-Sleep 4 +} +function Typed([int]$tp, [string]$cmd) { + # Into the test client's own window (PostMessage by pid): Enter, the text, Enter. + python "$PSScriptRoot\AcWindow.py" key $tp 0x0D | Out-Null + Start-Sleep -Milliseconds 400 + python "$PSScriptRoot\AcWindow.py" type $tp $cmd | Out-Null + python "$PSScriptRoot\AcWindow.py" key $tp 0x0D | Out-Null + Start-Sleep 4 +} +function HasModule([int]$tp, [string]$name) { + $p = Get-Process -Id $tp -ErrorAction SilentlyContinue + return [bool]($p -and ($p.Modules | Where-Object { $_.ModuleName -ieq $name })) +} +function Reload([int]$tp) { + $ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$tp") + [void]$ev.Set(); $ev.Dispose() +} + +if ($Runs -contains "A") { + Say "==== A: Decal only" + $tp = Start-One "DecalOnly" @() + $blog = "C:\Games\RynthCore\Logs\DecalBridge.$tp.log" + Say "pid $tp; in world: $(Wait-Match $blog 'LoginComplete' $LoginTimeout)" + Start-Sleep $Settle + python $diff $tp --json "$out\A-decal-only.json" *> "$out\A-decal-only.txt" + Say "patch diff -> $out\A-decal-only.txt" + Grab $blog "." 30 + Stop-One $tp +} + +if ($Runs -contains "B") { + Say "==== B: Decal + RynthCore, bridge mode Auto (in-game ImGui: engine.json default)" + $tp = Start-One "Both" @() + $log = "C:\Games\RynthCore\Logs\RynthCore.$tp.log" + Say "pid $tp; in world: $(Wait-Match $log 'starting plugin tick pump|BridgeProbe: OnLoginComplete' $LoginTimeout)" + Start-Sleep $Settle + python $diff $tp --names $log --json "$out\B-bridge.json" *> "$out\B-bridge.txt" + Say " VTank loaded (uTank2.dll): $(HasModule $tp 'uTank2.dll')" + Send "/ra cache" + Say "-- typed /ra cache (Decal CommandLineText -> bridge -> engine)" + Typed $tp "/ra cache" + Say "-- /loc through the engine's dispatcher -> bridge -> Decal InvokeChatParser" + Send "/loc" + for ($i = 1; $i -le 2; $i++) { + Say "-- reload $i" + Reload $tp + Start-Sleep 30 + Send "/ra cache" + } + Grab $log "BRIDGE MODE|bridge is up|skipped - bridge|bridge fallback|DecalBridge:|BridgeProbe:|location|unloaded|Reload: complete|EndSceneHook: INSTALLED|tick pump|UseTime \(no EndScene|\[ERR\]" 140 + $fps = Select-String -Path $log -Pattern "hb #\d+ .*fps=(\d+)" | Select-Object -Last 10 | ForEach-Object { $_.Matches[0].Groups[1].Value } + Say " fps (last 10 heartbeats): $($fps -join ' ')" + Grab "C:\Games\RynthCore\Logs\DecalBridge.$tp.log" "." 40 + $p = Get-Process -Id $tp -ErrorAction SilentlyContinue + Say " client alive=$([bool]$p) responding=$($p.Responding)" + Stop-One $tp +} + +if ($Runs -contains "C") { + Say "==== C: Decal + RynthCore, DecalBridge=Off (old coexistence mode)" + $tp = Start-One "Both" @("NoBridge") + $log = "C:\Games\RynthCore\Logs\RynthCore.$tp.log" + Say "pid $tp; in world: $(Wait-Match $log 'starting plugin tick pump' $LoginTimeout)" + Start-Sleep $Settle + python $diff $tp --names $log --json "$out\C-coexistence.json" *> "$out\C-coexistence.txt" + Send "/ra cache" + Say "-- reload" + Reload $tp + Start-Sleep 30 + Send "/ra cache" + Grab $log "PATTERN MISS|Decal|unloaded|Reload: complete|tick pump|BridgeProbe:|\[ERR\]" 80 + $p = Get-Process -Id $tp -ErrorAction SilentlyContinue + Say " client alive=$([bool]$p) responding=$($p.Responding)" + Stop-One $tp +} +if ($Runs -contains "D") { + Say "==== D: RynthCore only, no Decal (normal hook mode)" + $tp = Start-One "EngineOnly" @() + $log = "C:\Games\RynthCore\Logs\RynthCore.$tp.log" + Say "pid $tp; in world: $(Wait-Match $log 'OnLoginComplete observed' $LoginTimeout)" + Start-Sleep $Settle + Send "/ra cache" + Say "-- reload" + Reload $tp + Start-Sleep 30 + Send "/ra cache" + # Bridge code must stay silent here: no "DecalBridge:" line, no skipped step. + Grab $log "DecalBridge|skipped - bridge|Decal coexistence|Cache:|unloaded|Reload: complete|\[ERR\]" 60 + $p = Get-Process -Id $tp -ErrorAction SilentlyContinue + Say " client alive=$([bool]$p) responding=$($p.Responding)" + Stop-One $tp +} +Say "done: $out" diff --git a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs index 0a530d1..8ec66c6 100644 --- a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs +++ b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs @@ -27,9 +27,11 @@ internal partial class AccountProfileDialog : Window AccountBox.Text = profile.AccountName; AliasBox.Text = profile.Alias; UserPrefsPathBox.Text = profile.UserPrefsPath; - PasswordHintText.Text = string.IsNullOrEmpty(profile.Password) - ? "No password is saved for this profile yet." - : "A password is already saved for this profile. It stays hidden unless you replace or clear it."; + PasswordHintText.Text = profile.PasswordNeedsReentry + ? "Password needs re-entering: the saved one can't be read on this Windows user (settings copied from another user or PC?). Type it again to launch this account." + : !profile.HasSavedPassword + ? "No password is saved for this profile yet." + : "A password is saved for this profile, encrypted for this Windows user. It stays hidden unless you replace or clear it."; SaveButton.Click += (_, _) => SaveAndClose(); CancelButton.Click += (_, _) => Close(false); @@ -116,12 +118,14 @@ internal partial class AccountProfileDialog : Window _profile.AccountName = AccountBox.Text.Trim(); if (ClearPasswordCheckBox.IsChecked == true) { - _profile.Password = string.Empty; + _profile.ClearPassword(); } else if (!string.IsNullOrEmpty(PasswordBox.Text)) { - _profile.Password = PasswordBox.Text; + // Encrypted at once (DPAPI, this Windows user); the plain text isn't kept on the profile. + _profile.SetPassword(PasswordBox.Text); } + PasswordBox.Text = string.Empty; _profile.Alias = AliasBox.Text?.Trim() ?? string.Empty; _profile.UserPrefsPath = UserPrefsPathBox.Text?.Trim() ?? string.Empty; diff --git a/src/RynthCore.App.Avalonia/DecalBridgeDialog.cs b/src/RynthCore.App.Avalonia/DecalBridgeDialog.cs new file mode 100644 index 0000000..b6ee2d0 --- /dev/null +++ b/src/RynthCore.App.Avalonia/DecalBridgeDialog.cs @@ -0,0 +1,128 @@ +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; +using RynthCore.App; + +namespace RynthCore.App.Avalonia; + +/// <summary> +/// Small code-built dialogs for the Decal bridge: the "Check Decal bridge" report (with +/// Repair / Copy) and the yes/no before the one administrator step. +/// </summary> +internal static class DecalBridgeDialog +{ + private static readonly IBrush Back = new SolidColorBrush(Color.Parse("#132028")); + private static readonly IBrush Text = new SolidColorBrush(Color.Parse("#EAF0F4")); + private static readonly IBrush Muted = new SolidColorBrush(Color.Parse("#9AA8B3")); + private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#26C1A6")); + + /// <summary>Yes/no. True = the person pressed <paramref name="yes"/>.</summary> + public static async Task<bool> AskAsync(Window owner, string title, string message, string yes, string no) + { + var dialog = NewWindow(title, 560); + var yesButton = new Button { Content = yes, IsDefault = true }; + var noButton = new Button { Content = no, IsCancel = true }; + yesButton.Click += (_, _) => dialog.Close(true); + noButton.Click += (_, _) => dialog.Close(false); + dialog.Content = Layout(title, + new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap, Foreground = Text }, + yesButton, noButton); + bool? result = await dialog.ShowDialog<bool?>(owner); + return result == true; + } + + /// <summary> + /// Shows the check's report. With <paramref name="offerRepair"/>, a Repair button; returns + /// true when the person pressed it. + /// </summary> + public static async Task<bool> ShowReportAsync(Window owner, DecalBridgeCheck.Result check, bool offerRepair) + { + string title = check.Blocking ? "Decal bridge check: it would NOT load" : "Decal bridge check: OK"; + string report = check.ToReport(); + var dialog = NewWindow(title, 760); + + var body = new TextBox + { + Text = report, + IsReadOnly = true, + TextWrapping = TextWrapping.Wrap, + FontFamily = new FontFamily("Consolas, Cascadia Mono, monospace"), + FontSize = 12, + MaxHeight = 420, + Foreground = Text, + Background = new SolidColorBrush(Color.Parse("#0F161D")), + }; + var copy = new Button { Content = "Copy report" }; + copy.Click += async (_, _) => + { + try + { + var clipboard = TopLevel.GetTopLevel(dialog)?.Clipboard; + if (clipboard != null) await clipboard.SetTextAsync(report); + copy.Content = "Copied"; + } + catch { copy.Content = "Copy failed"; } + }; + var close = new Button { Content = "Close", IsCancel = true }; + close.Click += (_, _) => dialog.Close(false); + + Control[] buttons; + if (offerRepair) + { + var repair = new Button { Content = check.NeedsMachineWideRegistration ? "Repair (asks for administrator)" : "Repair", IsDefault = true }; + repair.Click += (_, _) => dialog.Close(true); + buttons = new Control[] { repair, copy, close }; + } + else + { + buttons = new Control[] { copy, close }; + } + + string hint = check.Blocking + ? "A Decal + RynthCore client started now would run without the bridge: no RynthCore overlay, then a crash. " + + (offerRepair ? "Repair registers the bridge where Decal reads on this PC and checks again." : "Fix the FAIL lines, then check again.") + : "A Decal + RynthCore client started now will load the bridge."; + dialog.Content = Layout(title, + new StackPanel + { + Spacing = 8, + Children = + { + new TextBlock { Text = hint, TextWrapping = TextWrapping.Wrap, Foreground = Muted }, + body, + }, + }, + buttons); + bool? result = await dialog.ShowDialog<bool?>(owner); + return result == true; + } + + private static Window NewWindow(string title, double width) => new() + { + Title = title, + Width = width, + SizeToContent = SizeToContent.Height, + CanResize = false, + WindowStartupLocation = WindowStartupLocation.CenterOwner, + Background = Back, + }; + + private static Control Layout(string title, Control body, params Control[] buttons) + { + var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right }; + foreach (Control b in buttons) row.Children.Add(b); + return new StackPanel + { + Margin = new Thickness(18), + Spacing = 12, + Children = + { + new TextBlock { Text = title, FontSize = 16, FontWeight = FontWeight.SemiBold, Foreground = Accent }, + body, + row, + }, + }; + } +} diff --git a/src/RynthCore.App.Avalonia/DownloadProgress.cs b/src/RynthCore.App.Avalonia/DownloadProgress.cs new file mode 100644 index 0000000..1050b9e --- /dev/null +++ b/src/RynthCore.App.Avalonia/DownloadProgress.cs @@ -0,0 +1,146 @@ +using System; +using System.Diagnostics; +using System.Globalization; + +namespace RynthCore.App.Avalonia; + +/// <summary>The step a launcher download is on.</summary> +public enum DownloadStage +{ + /// <summary>Bytes arriving: Done/Total are bytes, against the signed size from the feed.</summary> + Downloading, + /// <summary>The download finished and matched the signed size and SHA-256.</summary> + Verified, + /// <summary>Unpacking an archive: Done/Total are files.</summary> + Unpacking, + /// <summary>Putting the files in place (no measurable progress).</summary> + Installing, +} + +/// <summary> +/// One progress report for the launcher's download area. <see cref="What"/> names the download +/// ("RynthNav map", "RynthOracle", "RynthCore 2026.10.5.1"). Reports come from the updater at a +/// few a second at most (<see cref="DownloadMeter"/>); the first, the last and every stage change +/// always come through. +/// </summary> +public sealed record DownloadProgress(string What, DownloadStage Stage, long Done, long Total, + double BytesPerSecond = 0, TimeSpan? Remaining = null, TimeSpan Elapsed = default) +{ + /// <summary>0..100, or null when the step has no measurable progress.</summary> + public double? Percent => Total > 0 ? Math.Clamp(Done * 100.0 / Total, 0, 100) : null; + + /// <summary>The line under the progress bar.</summary> + public string Detail => Stage switch + { + DownloadStage.Downloading => FormatDownloading(), + DownloadStage.Verified => $"{FormatMb(Total)} downloaded and verified against the signed feed.", + DownloadStage.Unpacking => Total > 0 + ? $"Unpacking {Done.ToString("N0", CultureInfo.InvariantCulture)} of {Total.ToString("N0", CultureInfo.InvariantCulture)} files…" + : "Unpacking…", + _ => "Installing…", + }; + + /// <summary>The activity-log line when a download is done: "RynthNav map: 539 MB in 2m10s, verified".</summary> + public string Summary => $"{What}: {FormatMb(Total)} in {FormatDuration(Elapsed)}, verified"; + + private string FormatDownloading() + { + string s = $"{FormatMb(Done, withUnit: false)} of {FormatMb(Total)}"; + if (BytesPerSecond > 0) s += $" · {FormatMb((long)BytesPerSecond)}/s"; + if (Remaining is { } r) s += $" · about {FormatDuration(r)} left"; + return s; + } + + /// <summary>"539 MB", "12.4 MB", "0.3 MB" (one decimal under 100 MB).</summary> + public static string FormatMb(long bytes, bool withUnit = true) + { + double mb = bytes / (1024.0 * 1024.0); + string n = mb >= 100 ? mb.ToString("N0", CultureInfo.InvariantCulture) : mb.ToString("0.0", CultureInfo.InvariantCulture); + return withUnit ? n + " MB" : n; + } + + /// <summary>"8s", "2m10s", "1h05m".</summary> + public static string FormatDuration(TimeSpan t) + { + if (t < TimeSpan.Zero) t = TimeSpan.Zero; + if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h{t.Minutes:00}m"; + if (t.TotalMinutes >= 1) return $"{(int)t.TotalMinutes}m{t.Seconds:00}s"; + return $"{Math.Max(0, (int)Math.Round(t.TotalSeconds))}s"; + } +} + +/// <summary> +/// Measures one download: speed over the last few seconds, time left, and throttling so the UI +/// gets a handful of reports a second rather than one per 80 KB read. The clock is injectable +/// for tests. +/// </summary> +public sealed class DownloadMeter +{ + public static readonly TimeSpan ReportEvery = TimeSpan.FromMilliseconds(250); + private static readonly TimeSpan SpeedWindow = TimeSpan.FromSeconds(4); + + private readonly string _what; + private readonly long _total; + private readonly IProgress<DownloadProgress>? _progress; + private readonly Func<TimeSpan> _clock; + private readonly TimeSpan _start; + private TimeSpan _lastReport = TimeSpan.MinValue; + // A ring of (time, bytes) samples for the speed over the last few seconds. + private readonly (TimeSpan T, long Bytes)[] _samples = new (TimeSpan, long)[32]; + private int _sampleCount, _sampleHead; + + public DownloadMeter(string what, long total, IProgress<DownloadProgress>? progress, Func<TimeSpan>? clock = null) + { + _what = what; + _total = total; + _progress = progress; + if (clock == null) + { + var sw = Stopwatch.StartNew(); + clock = () => sw.Elapsed; + } + _clock = clock; + _start = _clock(); + AddSample(_start, 0); + } + + public TimeSpan Elapsed => _clock() - _start; + + /// <summary>Called after each read; reports at most every <see cref="ReportEvery"/>, and always at the end.</summary> + public void Report(long done) + { + if (_progress == null) return; + TimeSpan now = _clock(); + bool last = done >= _total; + if (!last && _lastReport != TimeSpan.MinValue && now - _lastReport < ReportEvery) return; + _lastReport = now; + AddSample(now, done); + double speed = Speed(now, done); + TimeSpan? remaining = speed > 0 && !last ? TimeSpan.FromSeconds((_total - done) / speed) : last ? TimeSpan.Zero : null; + _progress.Report(new DownloadProgress(_what, DownloadStage.Downloading, done, _total, speed, remaining, now - _start)); + } + + /// <summary>The download matched the signed size and hash.</summary> + public void Verified() => + _progress?.Report(new DownloadProgress(_what, DownloadStage.Verified, _total, _total, 0, TimeSpan.Zero, Elapsed)); + + private void AddSample(TimeSpan t, long bytes) + { + _samples[_sampleHead] = (t, bytes); + _sampleHead = (_sampleHead + 1) % _samples.Length; + if (_sampleCount < _samples.Length) _sampleCount++; + } + + private double Speed(TimeSpan now, long done) + { + // The oldest sample still inside the window (or the oldest kept) is the baseline. + (TimeSpan T, long Bytes) baseline = (now, done); + for (int i = 0; i < _sampleCount; i++) + { + var s = _samples[(_sampleHead - _sampleCount + i + _samples.Length) % _samples.Length]; + if (now - s.T <= SpeedWindow || i == _sampleCount - 1) { baseline = s; break; } + } + double secs = (now - baseline.T).TotalSeconds; + return secs > 0.05 ? (done - baseline.Bytes) / secs : 0; + } +} diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml b/src/RynthCore.App.Avalonia/MainWindow.axaml index fc51aee..31ba128 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml @@ -108,10 +108,39 @@ </Border> <Grid Grid.Row="1" ColumnDefinitions="3*,Auto,2*"> - <TabControl Grid.Column="0" Margin="14,0,0,0" Padding="0"> + <TabControl x:Name="MainTabs" Grid.Column="0" Margin="14,0,0,0" Padding="0"> <TabItem Header="Launcher"> <ScrollViewer> <StackPanel Spacing="12" Margin="6"> + <!-- Updates: the card is built by UpdateCardModel (MainWindow.RefreshUpdateCard). --> + <Border x:Name="UpdateCardBorder" Background="#132028" CornerRadius="16" Padding="18" + BorderBrush="#243742" BorderThickness="1"> + <StackPanel Spacing="8"> + <Grid ColumnDefinitions="*,Auto"> + <StackPanel Grid.Column="0" Spacing="4" VerticalAlignment="Center"> + <TextBlock x:Name="UpdateCardTitle" Text="Updates" FontSize="16" FontWeight="SemiBold" + Foreground="#26C1A6" TextWrapping="Wrap" /> + <TextBlock x:Name="UpdateCardDetail" Text="Not checked yet." TextWrapping="Wrap" Foreground="#9AA8B3" /> + </StackPanel> + <WrapPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Top" Margin="12,0,0,0"> + <Button x:Name="UpdateCardActionButton" IsVisible="False" Margin="0,0,8,6" + Background="#26C1A6" Foreground="#0B1218" FontWeight="SemiBold" /> + <Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,0,6" /> + </WrapPanel> + </Grid> + <StackPanel x:Name="UpdateCardWhatsNewPanel" Spacing="2" IsVisible="False" /> + <Grid x:Name="DownloadArea" ColumnDefinitions="*,Auto" IsVisible="False"> + <ProgressBar x:Name="DownloadProgressBar" Grid.Column="0" Minimum="0" Maximum="100" + Height="10" MinHeight="10" VerticalAlignment="Center" + Foreground="#26C1A6" Background="#0F161D" /> + <Button x:Name="CancelDownloadButton" Grid.Column="1" Content="Cancel" Margin="10,0,0,0" + ToolTip.Tip="Stops the download. Nothing half-installed is left behind: the partial file is deleted and what you have stays as it is." /> + </Grid> + <Button x:Name="UpdateCardNewPluginsButton" IsVisible="False" HorizontalAlignment="Left" + Background="Transparent" BorderThickness="0" Padding="0" Foreground="#F2C14E" /> + </StackPanel> + </Border> + <Border Background="#132028" CornerRadius="16" Padding="18"> <StackPanel Spacing="8"> <TextBlock Text="Launch Targets" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" /> @@ -170,7 +199,7 @@ <Grid RowDefinitions="Auto,Auto,*,Auto"> <TextBlock Text="Account Profiles" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" /> <TextBlock Grid.Row="1" - Text="Passwords stay persisted in settings." + Text="Passwords are saved encrypted for this Windows user." TextWrapping="Wrap" Foreground="#9AA8B3" Margin="0,8,0,0" /> @@ -234,36 +263,58 @@ </ScrollViewer> </TabItem> - <TabItem Header="Plugins"> - <ScrollViewer> + <TabItem x:Name="PluginsTab" Header="Plugins"> + <ScrollViewer x:Name="PluginsScroll"> <StackPanel Spacing="12" Margin="6"> <Border Background="#132028" CornerRadius="16" Padding="18"> <StackPanel Spacing="8"> <TextBlock Text="Updates" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" /> + <!-- Compact: the update card with its buttons is on the Launcher tab. --> <TextBlock x:Name="UpdateStatusText" Text="Not checked yet." TextWrapping="Wrap" Foreground="#9AA8B3" /> - <WrapPanel Orientation="Horizontal"> - <Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,8,6" /> - <Button x:Name="UpdatePluginsButton" Content="Update plugins" IsVisible="False" Margin="0,0,8,6" /> - <Button x:Name="InstallCoreUpdateButton" Content="Install RynthCore update" IsVisible="False" Margin="0,0,8,6" /> - </WrapPanel> + <ProgressBar x:Name="PluginsTabProgressBar" Minimum="0" Maximum="100" Height="6" MinHeight="6" + IsVisible="False" Foreground="#26C1A6" Background="#0F161D" /> + <Button x:Name="ShowUpdateCardButton" Content="Updates on the Launcher tab" HorizontalAlignment="Left" + Background="Transparent" BorderThickness="0" Padding="0" Foreground="#26C1A6" /> <CheckBox x:Name="AutoUpdatePluginsCheckBox" Content="Update plugins automatically (a running bot keeps its version until AC restarts)" Foreground="#EAF0F4" /> </StackPanel> </Border> + <Border Background="#132028" CornerRadius="16" Padding="18"> + <StackPanel Spacing="8"> + <TextBlock Text="Usage statistics" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" /> + <CheckBox x:Name="UsageStatsCheckBox" + Content="Help improve RynthCore: send an anonymous usage report once a day" + Foreground="#EAF0F4" /> + <TextBlock x:Name="UsageStatsWhatText" TextWrapping="Wrap" Foreground="#9AA8B3" /> + <TextBlock x:Name="UsageStatsNeverText" TextWrapping="Wrap" Foreground="#9AA8B3" /> + <TextBlock x:Name="UsageStatsStopText" TextWrapping="Wrap" Foreground="#9AA8B3" /> + <Button x:Name="ShowUsageReportButton" Content="Show what is sent" HorizontalAlignment="Left" /> + </StackPanel> + </Border> <Border Background="#132028" CornerRadius="16" Padding="18"> <StackPanel Spacing="8"> <TextBlock Text="Plugins" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" /> - <TextBlock Text="Manage the runtime modules loaded into RynthCore. Add plugins by browsing for their DLL file." + <TextBlock Text="The plugins RynthCore loads. Untick one to skip it; the X takes it out of the list (its files stay on disk). RynthSuite plugins you don't have are under Available plugins below; Add Plugin is for any other plugin DLL." TextWrapping="Wrap" Foreground="#9AA8B3" /> <StackPanel x:Name="PluginLoadoutPanel" Spacing="10" /> <Button x:Name="AddPluginDllButton" Content="Add Plugin" HorizontalAlignment="Left" /> </StackPanel> </Border> + <Border x:Name="AvailablePluginsBorder" Background="#132028" CornerRadius="16" Padding="18"> + <StackPanel Spacing="8"> + <TextBlock Text="Available plugins" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" /> + <TextBlock x:Name="AvailablePluginsHint" + Text="Plugins you can add appear here after the first update check." + TextWrapping="Wrap" + Foreground="#9AA8B3" /> + <StackPanel x:Name="AvailablePluginsPanel" Spacing="10" /> + </StackPanel> + </Border> </StackPanel> </ScrollViewer> </TabItem> @@ -362,6 +413,9 @@ <CheckBox x:Name="EnableDcompOverlayCheckBox" Content="Use DComp overlay (experimental, GPU-rendered)" ToolTip.Tip="When ON, the engine starts the new DirectComposition overlay instead of the production AvaloniaOverlay. Mutually exclusive — Avalonia is single-app-per-process. Toggle takes effect on next AC client launch (a hot reload won't switch overlays)." /> + <CheckBox x:Name="EnableImGuiBackendCheckBox" + Content="ImGui panels (preview)" + ToolTip.Tip="When ON, the engine runs its in-client ImGui layer, which docked panels move to as their ImGui versions are finished (choose per panel with /rc ui). Popped-out panels stay Avalonia windows. Costs nothing while no ImGui panel is open. Takes effect on next AC client launch or engine reload (RL)." /> </StackPanel> </Border> @@ -412,6 +466,8 @@ <Button x:Name="RefreshSessionsButton" Content="Refresh Sessions" Margin="0,0,8,8" /> <Button x:Name="ResetOverlayBarButton" Content="Reset Overlay Bar" Margin="0,0,8,8" ToolTip.Tip="Drags the in-game RynthCore overlay bar back to the top-left corner. Use this if the bar was moved off-screen and can no longer be reached. Applies to every running RynthCore client." /> + <Button x:Name="CheckDecalBridgeButton" Content="Check Decal bridge" Margin="0,0,8,8" + ToolTip.Tip="For Decal + RynthCore (experimental): checks whether a client started now will load the RynthCore Decal bridge - where Decal reads its plugin list on this PC, whether the bridge is listed and enabled there, Decal's version and its .NET part. Changes nothing unless you press Repair." /> </WrapPanel> <TextBlock Text="Manual inject target scope follows the 'Inject all running AC sessions' launch behavior toggle. Reset Overlay Bar signals all running RynthCore clients via the dispatch file." TextWrapping="Wrap" diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index c208ade..9ed873d 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -158,6 +158,7 @@ internal partial class MainWindow : Window _updateTimer.Tick += async (_, _) => await CheckForUpdatesAsync(); _updateTimer.Start(); _ = CheckForUpdatesAsync(); + Opened += async (_, _) => await AskAboutUsageStatsOnceAsync(); } private void WireEvents() @@ -182,16 +183,25 @@ internal partial class MainWindow : Window InjectRunningAcButton.Click += async (_, _) => await InjectRunningAcAsync(); RefreshSessionsButton.Click += (_, _) => RefreshSessionState(); ResetOverlayBarButton.Click += (_, _) => ResetOverlayBar(); + CheckDecalBridgeButton.Click += async (_, _) => await CheckDecalBridgeAsync(); AddPluginDllButton.Click += async (_, _) => await AddPluginDllAsync(); CheckUpdatesButton.Click += async (_, _) => await CheckForUpdatesAsync(); - UpdatePluginsButton.Click += async (_, _) => await UpdatePluginsAsync(); - InstallCoreUpdateButton.Click += async (_, _) => await InstallCoreUpdateAsync(); + UpdateCardActionButton.Click += async (_, _) => await OnUpdateCardActionAsync(); + CancelDownloadButton.Click += (_, _) => CancelDownload(); + UpdateCardNewPluginsButton.Click += (_, _) => ShowAvailablePlugins(); + ShowUpdateCardButton.Click += (_, _) => MainTabs.SelectedIndex = 0; AutoUpdatePluginsCheckBox.IsChecked = _settings.AutoUpdatePlugins; AutoUpdatePluginsCheckBox.IsCheckedChanged += (_, _) => { _settings.AutoUpdatePlugins = AutoUpdatePluginsCheckBox.IsChecked == true; SaveSettings(); }; + UsageStatsWhatText.Text = UsageStatsDialog.WhatIsSent; + UsageStatsNeverText.Text = UsageStatsDialog.NeverSent; + UsageStatsStopText.Text = UsageStatsDialog.HowToStop; + UsageStatsCheckBox.IsChecked = _settings.UsageStatsEnabled; + UsageStatsCheckBox.IsCheckedChanged += (_, _) => SetUsageStats(UsageStatsCheckBox.IsChecked == true); + ShowUsageReportButton.Click += async (_, _) => await ShowUsageReportAsync(); ServerProfilesList.SelectionChanged += (_, _) => OnPrimarySelectionChanged(); AccountProfilesList.SelectionChanged += (_, _) => OnPrimarySelectionChanged(); @@ -205,6 +215,22 @@ internal partial class MainWindow : Window LauncherDiag.Info("SETTINGS: " + loadDiag); try { AppendActivity("Settings: " + loadDiag); } catch { } } + if (AppSettingsStore.LastMigrationNote is string migration) + { + LauncherDiag.Info("SETTINGS: " + migration); + try { AppendActivity("Settings: " + migration); } catch { } + } + // Password notes carry counts and account names only, never a password. + if (AppSettingsStore.LastPasswordMigrationNote is string passwordMigration) + { + LauncherDiag.Info("SETTINGS: " + passwordMigration); + try { AppendActivity("Settings: " + passwordMigration); } catch { } + } + if (AppSettingsStore.LastPasswordProblemNote is string passwordProblem) + { + LauncherDiag.Info("SETTINGS: " + passwordProblem); + try { AppendActivity("Settings: " + passwordProblem); } catch { } + } _settings.ServerProfiles ??= []; _settings.AccountProfiles ??= []; _settings.CheckedLaunchAccountProfileIds ??= []; @@ -300,6 +326,23 @@ internal partial class MainWindow : Window // just provides a UI window into the same file. EnableDcompOverlayCheckBox.IsChecked = EngineJsonStore.GetBool("EnableDcompOverlay") ?? false; EnableDcompOverlayCheckBox.IsCheckedChanged += OnEnableDcompOverlayChanged; + // The engine treats a missing key as true. + EnableImGuiBackendCheckBox.IsChecked = EngineJsonStore.GetBool("EnableImGuiBackend") ?? true; + EnableImGuiBackendCheckBox.IsCheckedChanged += OnEnableImGuiBackendChanged; + } + + private void OnEnableImGuiBackendChanged(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e) + { + bool value = EnableImGuiBackendCheckBox.IsChecked == true; + try + { + EngineJsonStore.SetBool("EnableImGuiBackend", value); + AppendActivity($"Engine setting saved: EnableImGuiBackend={value}. Takes effect on next AC client launch or engine reload."); + } + catch (Exception ex) + { + AppendActivity($"Failed to save EnableImGuiBackend to engine.json: {ex.Message}"); + } } private void OnEnableDcompOverlayChanged(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e) @@ -353,32 +396,137 @@ internal partial class MainWindow : Window PluginLoadoutPanel.Children.Add(BuildPluginCard(checkBox, capturedPath, () => { - for (int j = _pluginDllPaths.Count - 1; j >= 0; j--) - { - if (string.Equals(_pluginDllPaths[j], capturedPath, StringComparison.OrdinalIgnoreCase)) - { - _pluginDllPaths.RemoveAt(j); - break; - } - } - // Also forget any disabled-marker for this path so re-adding - // it later starts in the enabled state. - if (_settings.DisabledPluginDllPaths != null) - { - for (int j = _settings.DisabledPluginDllPaths.Count - 1; j >= 0; j--) - { - if (string.Equals(_settings.DisabledPluginDllPaths[j], capturedPath, StringComparison.OrdinalIgnoreCase)) - { - _settings.DisabledPluginDllPaths.RemoveAt(j); - break; - } - } - } + // Out of the list (and out of the disabled list, so adding it back starts it + // enabled). The files stay where they are. + if (!PluginListEdits.Remove(_pluginDllPaths, _settings.DisabledPluginDllPaths, capturedPath)) return; SavePluginDllPaths(); BuildPluginLoadout(); - AppendActivity($"Removed plugin: {Path.GetFileName(capturedPath)}"); + bool fromFeed = _updateCheck?.Manifest.Plugins.Any(e => + string.Equals(e.File, Path.GetFileName(capturedPath), StringComparison.OrdinalIgnoreCase)) == true; + AppendActivity($"Removed plugin: {Path.GetFileName(capturedPath)}. Its files stay in {Path.GetDirectoryName(capturedPath)}." + + (fromFeed ? " It is back under Available plugins if you want it again." : "")); + RefreshUpdateCard(); })); } + + BuildAvailablePlugins(); + } + + // ── Available plugins (feed plugins not in the list) ────────────────────── + + private List<RynthUpdater.AvailablePlugin> _available = new(); + + private void BuildAvailablePlugins() + { + AvailablePluginsPanel.Children.Clear(); + _available = _updateCheck == null ? new() : _updater.GetAvailable(_updateCheck, _pluginDllPaths); + if (_updateCheck == null) + { + AvailablePluginsHint.Text = _updater.IsConfigured + ? "Plugins you can add appear here after the first update check." + : "Updates aren't set up in this build, so there is no plugin list to install from."; + return; + } + if (_available.Count == 0) + { + AvailablePluginsHint.Text = "You have every RynthSuite plugin."; + return; + } + string suite = Path.GetDirectoryName(Path.GetDirectoryName(_available[0].Path)) ?? RynthUpdater.DefaultSuiteDir; + AvailablePluginsHint.Text = $"RynthSuite plugins you don't have. Install downloads one into {suite} and adds it to the list above; it loads the next time AC starts."; + foreach (RynthUpdater.AvailablePlugin a in _available) + AvailablePluginsPanel.Children.Add(BuildAvailableCard(a)); + } + + private Border BuildAvailableCard(RynthUpdater.AvailablePlugin a) + { + var name = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; + name.Children.Add(new TextBlock { Text = a.Entry.Name, FontWeight = FontWeight.SemiBold, Foreground = Brush.Parse("#EAF0F4"), VerticalAlignment = VerticalAlignment.Center }); + if (a.IsNew) + name.Children.Add(new Border + { + Background = Brush.Parse("#F2C14E"), + CornerRadius = new CornerRadius(6), + Padding = new Thickness(6, 1), + VerticalAlignment = VerticalAlignment.Center, + Child = new TextBlock { Text = "New", FontSize = 11, FontWeight = FontWeight.SemiBold, Foreground = Brush.Parse("#0B1218") }, + }); + + var stack = new StackPanel { Spacing = 4 }; + stack.Children.Add(name); + if (a.Description.Length > 0) + stack.Children.Add(new TextBlock { Text = a.Description, TextWrapping = TextWrapping.Wrap, Foreground = Brush.Parse("#9AA8B3") }); + stack.Children.Add(new TextBlock + { + Text = $"Version {a.Version} · {DownloadProgress.FormatMb(a.Entry.Size)}", + FontSize = 11, + Foreground = Brush.Parse("#6F7F8A"), + }); + + var install = new Button + { + Content = "Install", + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(12, 0, 0, 0), + IsEnabled = !_updateBusy, + }; + ToolTip.SetTip(install, $"Download {a.Entry.Name} (checked against the signed update feed) into {Path.GetDirectoryName(a.Path)} and add it to your plugins."); + install.Click += async (_, _) => await InstallAvailablePluginAsync(a); + + var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*, Auto") }; + Grid.SetColumn(stack, 0); + Grid.SetColumn(install, 1); + row.Children.Add(stack); + row.Children.Add(install); + return new Border + { + Background = Brush.Parse("#0F161D"), + BorderBrush = Brush.Parse(a.IsNew ? "#5A4A1E" : "#243742"), + BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(12), + Padding = new Thickness(12), + Child = row, + }; + } + + private async Task InstallAvailablePluginAsync(RynthUpdater.AvailablePlugin a) + { + if (_updateBusy || _updateCheck is not { } check) return; + _updateBusy = true; + BuildAvailablePlugins(); // greys the Install buttons + bool installed = false; + try + { + RynthUpdater.PluginInstall r = await RunDownloadAsync((progress, ct) => + _updater.InstallPluginAsync(check, a.Entry.Name, _pluginDllPaths.ToList(), progress, ct)); + if (PluginListEdits.Add(_pluginDllPaths, r.Path)) SavePluginDllPaths(); + installed = true; + _pluginsUpdatedThisSession.Add($"{r.Entry.Name} (new)"); + string what = r.Description.Length > 0 ? $" ({r.Description.TrimEnd('.')})" : ""; + AppendActivity($"Plugin added: {r.Entry.Name}{what}, {r.Path}{(r.Downloaded ? "" : " (the copy already there)")}. It loads the next time AC starts."); + } + catch (OperationCanceledException) + { + AppendActivity($"{a.Entry.Name}: download cancelled. Nothing was installed."); + } + catch (Exception ex) + { + AppendActivity($"Could not install {a.Entry.Name}: {ex.Message}"); + } + finally + { + _updateBusy = false; + BuildPluginLoadout(); + RefreshUpdateCard(); + } + // A fresh check shows the new plugin's status (and, for RynthNav, offers its map). + if (installed) await CheckForUpdatesAsync(); + } + + private void ShowAvailablePlugins() + { + MainTabs.SelectedItem = PluginsTab; + Dispatcher.UIThread.Post(() => AvailablePluginsBorder.BringIntoView(), DispatcherPriority.Background); } private static Border BuildPluginCard(CheckBox checkBox, string description, Action? onRemove) @@ -418,6 +566,7 @@ internal partial class MainWindow : Window Foreground = Brush.Parse("#9AA8B3"), BorderThickness = new Thickness(0) }; + ToolTip.SetTip(removeButton, "Take this plugin out of the list. Its files stay on disk."); removeButton.Click += (_, _) => onRemove(); Grid.SetColumn(stack, 0); @@ -598,28 +747,35 @@ internal partial class MainWindow : Window LaunchAccountProfile removed = _settings.AccountProfiles[index]; string removedId = removed.Id; - // Delete all character cache files for this account name - DeleteCharacterCacheFiles(removed.AccountName); - + // Delete this profile's character cache (its own server only). The same + // account name on another server keeps its list; the legacy account-only + // file goes only when no other profile still uses the name. + string removedServerName = ResolveServerForAccount(removed)?.Name ?? string.Empty; _settings.AccountProfiles.RemoveAt(index); + bool nameStillUsed = _settings.AccountProfiles.Any(a => + string.Equals(a.AccountName?.Trim(), removed.AccountName?.Trim(), StringComparison.OrdinalIgnoreCase)); + DeleteCharacterCacheFiles(removed.AccountName, removedServerName, includeLegacy: !nameStillUsed); + _settings.CheckedLaunchAccountProfileIds = _settings.CheckedLaunchAccountProfileIds .Where(id => !string.Equals(id, removedId, StringComparison.OrdinalIgnoreCase)) .ToList(); if (string.Equals(removedId, _settings.SelectedAccountProfileId, StringComparison.OrdinalIgnoreCase)) _settings.SelectedAccountProfileId = _settings.AccountProfiles.FirstOrDefault()?.Id ?? string.Empty; SaveSettings(); + if (removed.InjectionMode == InjectionMode.DecalBridge) + UnregisterDecalBridgeIfUnused(); RefreshLists(); AccountProfilesList.SelectedIndex = Math.Min(index, _settings.AccountProfiles.Count - 1); RefreshSummary(); AppendActivity($"Account removed: {removed.DisplayName}"); } - private static void DeleteCharacterCacheFiles(string accountName) + private static void DeleteCharacterCacheFiles(string accountName, string serverName, bool includeLegacy) { if (string.IsNullOrWhiteSpace(accountName)) return; - CharacterCacheStore.DeleteForAccount(accountName); + CharacterCacheStore.DeleteForAccount(accountName, serverName, includeLegacy); } private List<string> GetDetectedCharacters(string accountName, string serverName = "") @@ -900,16 +1056,37 @@ internal partial class MainWindow : Window IsEnabled = decalAvailable }; + var bridgeItem = new ComboBoxItem + { + Content = decalAvailable ? "Decal + RynthCore (experimental)" : "Decal + RynthCore (experimental, no Decal)", + Tag = InjectionMode.DecalBridge, + IsEnabled = decalAvailable + }; + global::Avalonia.Controls.ToolTip.SetTip(bridgeItem, + "EXPERIMENTAL. Decal and RynthCore in the same client: Decal's plugins and RynthCore's " + + "in-game UI run side by side. RynthCore gets chat from Decal through the RynthCore Decal " + + "bridge, which this launcher adds to Decal's filter list before the launch: for your Windows " + + "user, or (when AC runs as administrator on this PC) once for all users after a Windows " + + "administrator prompt. Recovery Actions > Check Decal bridge shows whether it will load. Run one bot per client (VTank or the RynthAi macro, not both). To stop using it, " + + "set the account back to RynthCore or Decal: once no account uses it, the launcher takes the " + + "bridge out of Decal's list again (uninstalling RynthCore does too)."); + dropdown.Items.Add(rynthItem); dropdown.Items.Add(decalItem); + dropdown.Items.Add(bridgeItem); - // If the account is set to Decal but Decal isn't installed, fall back to + // If the account is set to a Decal mode but Decal isn't installed, fall back to // RynthCore in the UI so the user can't accidentally launch into a // disabled mode. We don't mutate the saved profile until they click. - InjectionMode effectiveMode = (account.InjectionMode == InjectionMode.Decal && !decalAvailable) + InjectionMode effectiveMode = (account.InjectionMode != InjectionMode.RynthCore && !decalAvailable) ? InjectionMode.RynthCore : account.InjectionMode; - dropdown.SelectedItem = effectiveMode == InjectionMode.Decal ? decalItem : rynthItem; + dropdown.SelectedItem = effectiveMode switch + { + InjectionMode.Decal => decalItem, + InjectionMode.DecalBridge => bridgeItem, + _ => rynthItem, + }; dropdown.SelectionChanged += (_, _) => { @@ -917,15 +1094,134 @@ internal partial class MainWindow : Window { if (account.InjectionMode == mode) return; + bool wasBridge = account.InjectionMode == InjectionMode.DecalBridge; account.InjectionMode = mode; SaveSettings(); - AppendActivity($"{account.DisplayName}: injection method set to {mode}."); + AppendActivity(mode == InjectionMode.DecalBridge + ? $"{account.DisplayName}: injection method set to Decal + RynthCore (experimental). " + + "The Decal bridge is registered for your Windows user at this account's next launch." + : $"{account.DisplayName}: injection method set to {mode}."); + if (wasBridge) + UnregisterDecalBridgeIfUnused(); } }; return dropdown; } + /// <summary> + /// The last "Decal + RynthCore" account was switched to another mode: take the Decal bridge + /// out of Decal's filter list for this Windows user again (registration is opt-in and only + /// lasts while an account uses it). Running clients keep what they loaded; the next + /// "Decal + RynthCore" launch registers again. + /// </summary> + private void UnregisterDecalBridgeIfUnused() + { + if (_settings.AccountProfiles.Any(a => a.InjectionMode == InjectionMode.DecalBridge)) + return; + try + { + DecalBridgeRegistration.Status status = DecalBridgeRegistration.GetStatus(); + if (status.RegisteredMachineWide) + AppendActivity("No account uses Decal + RynthCore any more. The Decal bridge's entry for all users stays (removing it needs administrator rights; uninstalling RynthCore removes it). " + + "It stays idle in Decal clients without RynthCore."); + if (!status.RegisteredPerUser) + return; + bool ok = DecalBridgeRegistration.Unregister(out string report); + LauncherDiag.Info($"DECALBRIDGE: no Decal + RynthCore account left - unregister: {report}"); + AppendActivity(ok + ? $"No account uses Decal + RynthCore any more - Decal bridge removed from Decal's filter list. {report}" + : $"No account uses Decal + RynthCore any more, but removing the Decal bridge did not finish: {report}"); + } + catch (Exception ex) + { + LauncherDiag.Info($"DECALBRIDGE: unregister failed ({ex.GetType().Name}: {ex.Message})"); + AppendActivity($"Removing the Decal bridge failed: {ex.Message}"); + } + } + + // ── Decal bridge: register where this PC's client reads, check, explain ───────────── + + private string DecalBridgeAcClientPath => + DecalLocator.TryGetDecalAcClientPath() ?? AcClientPathTextBox.Text?.Trim() ?? string.Empty; + + /// <summary> + /// Registers the Decal bridge where a client started now will read Decal's filter list + /// (DecalBridgeRegistration.RegisterForClients) and checks the result. When that place is + /// the machine-wide list (AC runs with administrator rights on this PC), asks first and runs + /// the one elevated step. False = a Decal + RynthCore client would not load the bridge. + /// Automatic launches never prompt: they log the reason and stay blocked. + /// </summary> + private async Task<bool> EnsureDecalBridgeAsync(string acClientPath, bool interactive) + { + string dir = DecalBridgeRegistration.DefaultBridgeDirectory; + var outcome = DecalBridgeRegistration.RegisterForClients(dir, acClientPath, EngineJsonStore.Path, out string report, out DecalBridgeCheck.Result? check); + LauncherDiag.Info($"DECALBRIDGE: register for clients: {outcome}: {report}"); + if (check != null) + LauncherDiag.Info($"DECALBRIDGE: check after register:{Environment.NewLine}{check.ToReport()}"); + if (outcome == DecalBridgeRegistration.Outcome.Registered) + { + AppendActivity(report); + return true; + } + + if (outcome == DecalBridgeRegistration.Outcome.NeedsAdmin) + { + AppendActivity(report); + if (!interactive) + return false; + bool yes = await DecalBridgeDialog.AskAsync(this, + "Decal + RynthCore: one administrator step", + "On this PC, Asheron's Call reads Decal's plugin list for all users, not just for you" + + (check != null && check.ClientReason.Length > 0 ? $" ({check.ClientReason})" : "") + ".\n\n" + + "RynthCore has to add its Decal bridge to that list once, so Decal loads it next to your other Decal plugins. " + + "Windows will now ask for administrator permission. Nothing else changes; switching every account away from " + + "Decal + RynthCore, or uninstalling RynthCore, takes the entry out again.", + "Add it (asks for administrator)", "Cancel"); + if (!yes) + { + AppendActivity("Decal bridge: the administrator step was cancelled."); + return false; + } + string? self = Environment.ProcessPath; + if (self == null) + { + AppendActivity("Decal bridge: can't find the launcher's own exe for the administrator step."); + return false; + } + var elevated = DecalBridgeRegistration.RunElevated(self, $"--decal-bridge-register-machine \"{dir}\"", out string eReport); + LauncherDiag.Info($"DECALBRIDGE: elevated register: {elevated}: {eReport}"); + AppendActivity("Decal bridge: " + eReport); + check = RealDecalCheckHost.Check(dir, acClientPath, EngineJsonStore.Path); + LauncherDiag.Info($"DECALBRIDGE: check after the administrator step:{Environment.NewLine}{check.ToReport()}"); + AppendActivity(check.Summary); + if (!check.Blocking) + return true; + } + else + { + AppendActivity(report); + } + + if (interactive && check != null) + await DecalBridgeDialog.ShowReportAsync(this, check, offerRepair: false); + return false; + } + + /// <summary>Recovery Actions > Check Decal bridge: the read-only check, with a Repair button when it fails.</summary> + private async Task CheckDecalBridgeAsync() + { + string acClientPath = DecalBridgeAcClientPath; + DecalBridgeCheck.Result check = RealDecalCheckHost.Check(DecalBridgeRegistration.DefaultBridgeDirectory, acClientPath, EngineJsonStore.Path); + LauncherDiag.Info($"DECALBRIDGE: check (button):{Environment.NewLine}{check.ToReport()}"); + AppendActivity(check.Summary); + bool repair = await DecalBridgeDialog.ShowReportAsync(this, check, offerRepair: check.Blocking && check.DecalInstalled); + if (!repair) + return; + bool ok = await EnsureDecalBridgeAsync(acClientPath, interactive: true); + AppendActivity(ok ? "Decal bridge repaired: a Decal + RynthCore client started now will load it." : "Decal bridge repair did not finish (see above)."); + } + private void UpdateCheckedLaunchTargetsFromUi() { _settings.CheckedLaunchAccountProfileIds = LaunchTargetsPanel.Children @@ -1110,7 +1406,7 @@ internal partial class MainWindow : Window // Engine plugin must be selected when at least one chosen account is // RynthCore-mode AND auto-inject is on. Decal-mode accounts don't need // it because they don't load the engine. - bool anyRynthCoreMode = accountsToLaunch.Any(a => a.InjectionMode == InjectionMode.RynthCore); + bool anyRynthCoreMode = accountsToLaunch.Any(a => a.InjectionMode is InjectionMode.RynthCore or InjectionMode.DecalBridge); if (shouldInject && anyRynthCoreMode && !GetSelectedPluginIds().Contains("rynthcore-engine", StringComparer.OrdinalIgnoreCase)) { AppendActivity("Launch blocked: RynthCore Engine must stay selected in Runtime Loadout when auto-inject is enabled for any RynthCore-mode account."); @@ -1118,15 +1414,32 @@ internal partial class MainWindow : Window } // Pre-resolve Decal Inject.dll once if any account needs it. - string? decalInjectPath = accountsToLaunch.Any(a => a.InjectionMode == InjectionMode.Decal && shouldInject) + bool anyDecalMode = accountsToLaunch.Any(a => a.InjectionMode is InjectionMode.Decal or InjectionMode.DecalBridge); + string? decalInjectPath = anyDecalMode && shouldInject ? DecalLocator.TryGetInjectDllPath() : null; - if (shouldInject && accountsToLaunch.Any(a => a.InjectionMode == InjectionMode.Decal) && decalInjectPath == null) + if (shouldInject && anyDecalMode && decalInjectPath == null) { AppendActivity("Launch blocked: one or more accounts are set to Decal mode but Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent\\AgentPath\\Inject.dll missing)."); return; } + // "Decal + RynthCore" accounts: make sure the Decal bridge is registered for this + // Windows user (idempotent; opt-in - only these accounts ever trigger it). + // Registered where THIS PC's AC client reads Decal's filter list, then checked: a + // client that wouldn't load the bridge runs the old coexistence path (no overlay, then + // a crash), so such a launch is blocked with the reason. + if (shouldInject && accountsToLaunch.Any(a => a.InjectionMode == InjectionMode.DecalBridge)) + { + string decalAcPath = DecalLocator.TryGetDecalAcClientPath() ?? acPath; + if (!await EnsureDecalBridgeAsync(decalAcPath, interactive: !isAutomaticLaunch)) + { + AppendActivity("Launch blocked: a Decal + RynthCore client would not load the Decal bridge on this PC (see the lines above, or Recovery Actions > Check Decal bridge). " + + "Pick RynthCore or Decal for those accounts until it passes."); + return; + } + } + SaveRuntimePaths(appendActivity: !isAutomaticLaunch); SaveLaunchBehavior(appendActivity: !isAutomaticLaunch); @@ -1151,7 +1464,7 @@ internal partial class MainWindow : Window { foreach (LaunchAccountProfile account in accountsToLaunch) { - string key = BuildAccountKey(account.AccountName); + string key = BuildAccountKey(account); if (!string.IsNullOrEmpty(key)) { _crashHistoryByAccount.Remove(key); @@ -1178,12 +1491,8 @@ internal partial class MainWindow : Window } LaunchServerProfile? contextServer = ResolveServerForAccount(account); - string accountKey = BuildAccountKey(account.AccountName); - bool allowMultipleClients = _settings.AllowMultipleClients; - // In single-client mode, keep one active session per account to avoid accidental duplicate launches. - if (!allowMultipleClients && - !string.IsNullOrWhiteSpace(accountKey) && - activeAccountKeys.Contains(accountKey)) + string accountKey = BuildAccountKey(account.AccountName, contextServer?.Name); + if (!string.IsNullOrWhiteSpace(accountKey) && IsAccountKeyActive(activeAccountKeys, accountKey)) { string serverLabel = contextServer?.DisplayName ?? "the configured server"; AppendActivity($"Skipped {account.DisplayName}: account '{account.AccountName}' already has a running session on {serverLabel}."); @@ -1225,7 +1534,13 @@ internal partial class MainWindow : Window // C:\Turbine\Asheron's Call install, while the RynthCore // path may point at the private AcClient duplicate. string decalAcPath = DecalLocator.TryGetDecalAcClientPath() ?? acPath; - launchTask = LaunchOneDecalInjectedAsync(p.Account, decalAcPath, p.Args, decalInjectPath!, p.Summary, p.Context); + launchTask = LaunchOneDecalInjectedAsync(p.Account, decalAcPath, p.Args, decalInjectPath!, null, p.Summary, p.Context); + } + else if (p.Account.InjectionMode == InjectionMode.DecalBridge) + { + // Decal first, then RynthCore, in Decal's client (as Decal mode above). + string decalAcPath = DecalLocator.TryGetDecalAcClientPath() ?? acPath; + launchTask = LaunchOneDecalInjectedAsync(p.Account, decalAcPath, p.Args, decalInjectPath!, enginePath, p.Summary, p.Context); } else { @@ -1256,10 +1571,10 @@ internal partial class MainWindow : Window string launchSummary, LaunchContextRecord launchContext) { - string resolvedPrefsPath = ResolveUserPrefsPath(account); + string resolvedPrefsPath = ResolveUserPrefsPath(account, launchContext.ServerName); bool needsPrefsSwap = !string.IsNullOrEmpty(resolvedPrefsPath) && File.Exists(resolvedPrefsPath); - string entryAccountKey = BuildAccountKey(launchContext.AccountName); + string entryAccountKey = BuildAccountKey(launchContext.AccountName, launchContext.ServerName); int crashHistCount = _crashHistoryByAccount.TryGetValue(entryAccountKey, out List<DateTime>? hist0) ? hist0.Count : 0; LauncherDiag.Info($"LaunchOneInjected ENTRY account='{launchContext.AccountName}' needsPrefsSwap={needsPrefsSwap} semCount={_userPrefsSwapLock.CurrentCount} sessionPids={_launchedSessionPids.Count} pidInfo={_launchedPidInfo.Count} crashHist={crashHistCount}"); @@ -1289,7 +1604,7 @@ internal partial class MainWindow : Window WritePendingSessionState(processId, launchContext); })); - string accountKey = BuildAccountKey(launchContext.AccountName); + string accountKey = BuildAccountKey(launchContext.AccountName, launchContext.ServerName); LauncherDiag.Info($"LaunchOneInjected injection result: success={result.Success} pid={(result.ProcessId is int p ? p.ToString() : "null")} summary='{result.Summary}'"); @@ -1332,13 +1647,14 @@ internal partial class MainWindow : Window string acPath, string launchArguments, string decalInjectDllPath, + string? enginePath, string launchSummary, LaunchContextRecord launchContext) { - string resolvedPrefsPath = ResolveUserPrefsPath(account); + string resolvedPrefsPath = ResolveUserPrefsPath(account, launchContext.ServerName); bool needsPrefsSwap = !string.IsNullOrEmpty(resolvedPrefsPath) && File.Exists(resolvedPrefsPath); - string entryAccountKey = BuildAccountKey(launchContext.AccountName); + string entryAccountKey = BuildAccountKey(launchContext.AccountName, launchContext.ServerName); int crashHistCount = _crashHistoryByAccount.TryGetValue(entryAccountKey, out List<DateTime>? hist0) ? hist0.Count : 0; LauncherDiag.Info($"LaunchOneDecal ENTRY account='{launchContext.AccountName}' needsPrefsSwap={needsPrefsSwap} semCount={_userPrefsSwapLock.CurrentCount} sessionPids={_launchedSessionPids.Count} pidInfo={_launchedPidInfo.Count} crashHist={crashHistCount}"); @@ -1356,11 +1672,14 @@ internal partial class MainWindow : Window _launchSettings.SwapUserPreferences(resolvedPrefsPath, _settings.AllowMultipleClients, AppendActivity); } + // enginePath != null: "Decal + RynthCore" - Decal is injected first, then the + // RynthCore loader, before the client resumes. InjectionResult result = await Task.Run(() => - _injector.LaunchSuspendedAndInjectDecal( + _injector.LaunchSuspendedAndInjectDecalThenEngine( acPath, launchArguments, decalInjectDllPath, + enginePath, AppendActivity, processId => { @@ -1368,7 +1687,7 @@ internal partial class MainWindow : Window WritePendingSessionState(processId, launchContext); })); - string accountKey = BuildAccountKey(launchContext.AccountName); + string accountKey = BuildAccountKey(launchContext.AccountName, launchContext.ServerName); LauncherDiag.Info($"LaunchOneDecal injection result: success={result.Success} pid={(result.ProcessId is int p ? p.ToString() : "null")} summary='{result.Summary}'"); @@ -1413,7 +1732,7 @@ internal partial class MainWindow : Window string launchSummary, LaunchContextRecord launchContext) { - string resolvedPrefsPath = ResolveUserPrefsPath(account); + string resolvedPrefsPath = ResolveUserPrefsPath(account, launchContext.ServerName); bool needsPrefsSwap = !string.IsNullOrEmpty(resolvedPrefsPath) && File.Exists(resolvedPrefsPath); LauncherDiag.Info($"LaunchOneNoInject ENTRY account='{launchContext.AccountName}' needsPrefsSwap={needsPrefsSwap} semCount={_userPrefsSwapLock.CurrentCount} sessionPids={_launchedSessionPids.Count} pidInfo={_launchedPidInfo.Count}"); @@ -1461,7 +1780,7 @@ internal partial class MainWindow : Window if (proc != null) { _launchedSessionPids.Add(proc.Id); - _launchedPidInfo[proc.Id] = (BuildAccountKey(launchContext.AccountName), DateTime.UtcNow); + _launchedPidInfo[proc.Id] = (BuildAccountKey(launchContext.AccountName, launchContext.ServerName), DateTime.UtcNow); RegisterPidExitWatch(proc.Id); LaunchContextStore.WriteForProcess(proc.Id, launchContext); WritePendingSessionState(proc.Id, launchContext); @@ -1736,6 +2055,32 @@ internal partial class MainWindow : Window foreach (string path in _settings.PluginDllPaths) _pluginDllPaths.Add(path); } + + // Plugins added to engine.json by something else (a deploy script, another launcher, + // an older setup) join the list, so the next sync - which writes engine.json from this + // list - can't silently drop them (RynthRemote and RynthLua were missing here, 2026-09-29). + try + { + if (EngineJsonStore.Read().TryGetValue("PluginPaths", out System.Text.Json.JsonElement paths) + && paths.ValueKind == System.Text.Json.JsonValueKind.Array) + { + bool adopted = false; + foreach (System.Text.Json.JsonElement p in paths.EnumerateArray()) + { + string? path = p.ValueKind == System.Text.Json.JsonValueKind.String ? p.GetString() : null; + if (string.IsNullOrWhiteSpace(path)) continue; + if (_pluginDllPaths.Any(x => string.Equals(x, path, StringComparison.OrdinalIgnoreCase))) continue; + _pluginDllPaths.Add(path); + adopted = true; + } + if (adopted) + { + _settings.PluginDllPaths = _pluginDllPaths.ToList(); + SaveSettings(); + } + } + } + catch { /* engine.json unreadable: keep the launcher's own list */ } } private async Task AddPluginDllAsync() @@ -1818,35 +2163,294 @@ internal partial class MainWindow : Window private readonly List<string> _pluginsUpdatedThisSession = new(); + private DateTime? _lastUpdateCheckLocal; + private string? _updateError; + private bool _updateChecking; + // The download in progress (shown on the update card and the Plugins tab), its Cancel, and a + // generation number so a late progress report from a finished download is ignored. + private DownloadProgress? _download; + private CancellationTokenSource? _downloadCts; + private int _downloadGeneration; + // Cancel on the RynthNav map: automatic updates don't start it again this session (the + // Update plugins button still does). + private bool _navDataCancelledThisSession; + private UpdateCard? _updateCard; + private async Task CheckForUpdatesAsync() { if (_updateBusy) return; if (!_updater.IsConfigured) { - UpdateStatusText.Text = "Updates aren't set up in this build."; + RefreshUpdateCard(); CheckUpdatesButton.IsEnabled = false; return; } _updateBusy = true; + _updateChecking = true; CheckUpdatesButton.IsEnabled = false; - UpdateStatusText.Text = "Checking for updates…"; + RefreshUpdateCard(); try { _updateCheck = await _updater.CheckAsync(_pluginDllPaths.ToList()); - if (_settings.AutoUpdatePlugins && _updateCheck.PluginsToUpdate.Any()) - await ApplyPluginUpdatesAsync(); - ShowUpdateState(); + _updateError = null; + _lastUpdateCheckLocal = DateTime.Now; + _updateChecking = false; + AnnounceNewPlugins(_updateCheck); + BuildAvailablePlugins(); + if (_settings.AutoUpdatePlugins && (_updateCheck.PluginsToUpdate.Any() || _updateCheck.Companions.Count > 0 + || (_updateCheck.NavDataUpdateAvailable && !_navDataCancelledThisSession))) + await ApplyPluginUpdatesAsync(automatic: true); + SendUsageReportIfDue(); // opt-in only, at most once a day, never awaited } catch (Exception ex) { - UpdateStatusText.Text = $"Update check failed: {ex.Message}"; + _updateError = ex.Message; AppendActivity($"Update check failed: {ex.Message}"); } finally { _updateBusy = false; + _updateChecking = false; CheckUpdatesButton.IsEnabled = true; + BuildAvailablePlugins(); + RefreshUpdateCard(); + } + } + + /// <summary>Once per plugin, the first time the feed has it: "New plugins available: …".</summary> + private void AnnounceNewPlugins(RynthUpdater.CheckResult c) + { + if (c.NewlyAnnounced.Count == 0) return; + string list = string.Join(", ", c.NewlyAnnounced.Select(a => + a.Description.Length > 0 ? $"{a.Entry.Name} ({a.Description.TrimEnd('.')})" : a.Entry.Name)); + AppendActivity($"New plugins available: {list}. Install them from Available plugins on the Plugins tab, or leave them out."); + } + + // ── Downloads: one progress display for every download ──────────────────── + + /// <summary>Hands progress from the updater (any thread) to the UI thread.</summary> + private sealed class UiProgress(MainWindow window, int generation) : IProgress<DownloadProgress> + { + public void Report(DownloadProgress p) => Dispatcher.UIThread.Post(() => window.OnDownloadProgress(p, generation)); + } + + private void OnDownloadProgress(DownloadProgress p, int generation) + { + // The finished line always reaches the log, even when it arrives after the download ended. + if (p.Stage == DownloadStage.Verified && p.Elapsed > TimeSpan.Zero) + AppendActivity(p.Summary + "."); + if (generation != _downloadGeneration || _downloadCts == null) return; + _download = p; + RefreshUpdateCard(); + } + + /// <summary>Runs one download operation with the progress display and its Cancel button.</summary> + private async Task<T> RunDownloadAsync<T>(Func<IProgress<DownloadProgress>, CancellationToken, Task<T>> op) + { + using var cts = new CancellationTokenSource(); + _downloadCts = cts; + int generation = ++_downloadGeneration; + RefreshUpdateCard(); + try + { + return await op(new UiProgress(this, generation), cts.Token); + } + finally + { + _downloadCts = null; + _download = null; + _downloadGeneration++; + RefreshUpdateCard(); + } + } + + private void CancelDownload() + { + if (_downloadCts is not { IsCancellationRequested: false } cts) return; + cts.Cancel(); + CancelDownloadButton.IsEnabled = false; + } + + private async Task OnUpdateCardActionAsync() + { + switch (_updateCard?.Kind) + { + case UpdateCardKind.CoreUpdate: await InstallCoreUpdateAsync(); break; + case UpdateCardKind.PluginUpdates: await UpdatePluginsAsync(); break; + } + } + + private List<string> PendingUpdateNames(RynthUpdater.CheckResult? c) + { + if (c == null) return new(); + var pending = c.PluginsToUpdate.Select(p => p.Entry.Name).Distinct() + .Concat(c.Companions.Select(x => $"{x.Entry.Name} (new: {x.Reason})")).ToList(); + if (c.NavDataUpdateAvailable) + pending.Add($"RynthNav map ({DownloadProgress.FormatMb(c.NavData!.Entry.Size)} download)"); + return pending; + } + + /// <summary>Redraws the front page's update card, the Plugins tab's status line and the header.</summary> + private void RefreshUpdateCard() + { + RynthUpdater.CheckResult? c = _updateCheck; + bool coreUpdate = c?.CoreUpdateAvailable == true; + var card = UpdateCardModel.Build(new UpdateCardInput + { + Configured = _updater.IsConfigured, + Checking = _updateChecking, + Error = _updateError, + LastChecked = _lastUpdateCheckLocal, + HasCheck = c != null, + InstalledVersion = FormatRelease(c?.InstalledCoreRelease ?? _updater.InstalledCoreRelease), + CoreUpdateAvailable = coreUpdate, + AvailableVersion = c?.Manifest.Core.Version ?? "", + Notes = c?.Manifest.Notes ?? "", + Changes = c?.Manifest.Changes ?? Array.Empty<string>(), + PendingPluginUpdates = PendingUpdateNames(c), + NewPlugins = _available.Where(a => a.IsNew).Select(a => a.Entry.Name).ToList(), + // Only worth the process scan when there is a RynthCore update to wait for. + ClientsRunning = coreUpdate && _download == null ? RynthCoreClientsRunning() : 0, + Download = _download, + CanCancel = _downloadCts is { IsCancellationRequested: false }, + }); + _updateCard = card; + + UpdateCardTitle.Text = card.Title; + UpdateCardTitle.Foreground = Brush.Parse(card.Kind switch + { + UpdateCardKind.CoreUpdate or UpdateCardKind.PluginUpdates => "#F2C14E", + UpdateCardKind.Error => "#E57373", + _ => "#26C1A6", + }); + UpdateCardBorder.BorderBrush = Brush.Parse(card.Kind is UpdateCardKind.CoreUpdate or UpdateCardKind.PluginUpdates ? "#F2C14E" : "#243742"); + UpdateCardDetail.Text = card.Detail; + UpdateCardDetail.IsVisible = card.Detail.Length > 0; + UpdateCardActionButton.IsVisible = card.ActionButton != null; + UpdateCardActionButton.Content = card.ActionButton ?? ""; + UpdateCardActionButton.IsEnabled = !_updateBusy; + CheckUpdatesButton.IsVisible = card.ShowCheckButton; + + UpdateCardWhatsNewPanel.Children.Clear(); + if (card.WhatsNew.Count > 0) + { + UpdateCardWhatsNewPanel.Children.Add(new TextBlock { Text = "What's new", FontWeight = FontWeight.SemiBold, Foreground = Brush.Parse("#EAF0F4") }); + foreach (string line in card.WhatsNew) + UpdateCardWhatsNewPanel.Children.Add(new TextBlock { Text = "• " + line, TextWrapping = TextWrapping.Wrap, Foreground = Brush.Parse("#C5D0D8") }); + } + UpdateCardWhatsNewPanel.IsVisible = card.WhatsNew.Count > 0; + + DownloadArea.IsVisible = card.ShowProgress; + DownloadProgressBar.IsIndeterminate = card.ShowProgress && card.ProgressPercent == null; + DownloadProgressBar.Value = card.ProgressPercent ?? 0; + CancelDownloadButton.IsVisible = card.ShowProgress && _downloadCts != null; + CancelDownloadButton.IsEnabled = card.ShowCancel; + + UpdateCardNewPluginsButton.IsVisible = card.NewPluginsLine != null; + UpdateCardNewPluginsButton.Content = card.NewPluginsLine ?? ""; + + // Plugins tab: one compact status (the buttons are on the card), its own small bar, and + // what this session did. + var lines = new List<string> { card.Compact }; + if (_pluginsUpdatedThisSession.Count > 0) + lines.Add($"Updated this session: {string.Join(", ", _pluginsUpdatedThisSession)}. Loads the next time AC starts."); + var local = c?.Plugins.Where(p => p.State == RynthUpdater.PluginState.LocalBuild).Select(p => p.Entry.Name).Distinct().ToList(); + if (local is { Count: > 0 }) lines.Add($"Left alone (newer local builds): {string.Join(", ", local)}."); + UpdateStatusText.Text = string.Join("\n", lines); + PluginsTabProgressBar.IsVisible = card.ShowProgress; + PluginsTabProgressBar.IsIndeterminate = card.ShowProgress && card.ProgressPercent == null; + PluginsTabProgressBar.Value = card.ProgressPercent ?? 0; + + bool headerShows = card.Kind is UpdateCardKind.CoreUpdate or UpdateCardKind.PluginUpdates or UpdateCardKind.Downloading; + HeaderUpdateText.IsVisible = headerShows; + HeaderUpdateText.Text = card.Kind == UpdateCardKind.Downloading && card.ProgressPercent is { } pct + ? $"{card.Title} ({pct:0}%)" + : card.Kind == UpdateCardKind.Downloading ? card.Title : card.Compact; + } + + // ── Usage statistics (opt-in; UsageStats.cs says exactly what is sent) ──── + + private readonly UsageStats _usageStats = new(); + + private void SetUsageStats(bool on) + { + if (_settings.UsageStatsEnabled == on) return; + _settings.UsageStatsEnabled = on; + _settings.UsageStatsAsked = true; + SaveSettings(); + if (on) + { + _usageStats.OptIn(DateTime.UtcNow); + AppendActivity("Usage statistics on: one anonymous report a day. Thank you."); + SendUsageReportIfDue(); + } + else + { + _usageStats.OptOut(); + AppendActivity("Usage statistics off: no more reports, and the random ID was deleted from this PC."); + } + } + + /// <summary>Explains usage statistics once and asks; "No thanks" (or closing the window) keeps them off.</summary> + private async Task AskAboutUsageStatsOnceAsync() + { + if (_settings.UsageStatsAsked) return; + await Task.Delay(TimeSpan.FromSeconds(2)); + if (_settings.UsageStatsAsked) return; // already answered with the checkbox + bool on; + try { on = await UsageStatsDialog.AskAsync(this); } + catch { return; } + _settings.UsageStatsAsked = true; + SaveSettings(); + if (on) UsageStatsCheckBox.IsChecked = true; // -> SetUsageStats(true) + } + + private (List<string> EnabledPaths, Dictionary<string, string> FeedNames) SnapshotPluginsForStats() + { + var disabled = new HashSet<string>(_settings.DisabledPluginDllPaths ?? new List<string>(), StringComparer.OrdinalIgnoreCase); + List<string> enabled = _pluginDllPaths.Where(p => !disabled.Contains(p)).ToList(); + var names = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + foreach (RynthUpdater.PluginEntry e in _updateCheck?.Manifest.Plugins ?? (IReadOnlyList<RynthUpdater.PluginEntry>)Array.Empty<RynthUpdater.PluginEntry>()) + names.TryAdd(e.File, e.Name); + return (enabled, names); + } + + private static string CoreVersionForStats() => + typeof(MainWindow).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? ""; + + /// <summary>Fire and forget, after a successful update check: silent on every failure.</summary> + private void SendUsageReportIfDue() + { + if (!_settings.UsageStatsEnabled || _updateCheck == null) return; + var (enabled, names) = SnapshotPluginsForStats(); + string version = CoreVersionForStats(); + _ = Task.Run(async () => + { + try + { + var (known, other) = UsageStats.DescribePlugins(enabled, names); + if (await _usageStats.MaybeSendAsync(() => _settings.UsageStatsEnabled, version, known, other, DateTime.UtcNow)) + LauncherDiag.Info("USAGESTATS: today's anonymous report was sent"); + } + catch { } + }); + } + + private async Task ShowUsageReportAsync() + { + try + { + var (enabled, names) = SnapshotPluginsForStats(); + var (known, other) = UsageStats.DescribePlugins(enabled, names); + string json = _usageStats.Preview(CoreVersionForStats(), known, other, DateTime.UtcNow); + if (_updateCheck == null) + json += "\n\n(The plugin list is filled in after the first successful update check.)"; + await UsageStatsDialog.ShowPayloadAsync(this, json, _settings.UsageStatsEnabled); + } + catch (Exception ex) + { + AppendActivity($"Could not show the usage report: {ex.Message}"); } } @@ -1854,31 +2458,78 @@ internal partial class MainWindow : Window { if (_updateBusy || _updateCheck == null) return; _updateBusy = true; - UpdatePluginsButton.IsEnabled = false; + RefreshUpdateCard(); try { - await ApplyPluginUpdatesAsync(); - ShowUpdateState(); + await ApplyPluginUpdatesAsync(automatic: false); } catch (Exception ex) { - UpdateStatusText.Text = $"Plugin update failed: {ex.Message}"; AppendActivity($"Plugin update failed: {ex.Message}"); } finally { _updateBusy = false; - UpdatePluginsButton.IsEnabled = true; + BuildAvailablePlugins(); + RefreshUpdateCard(); } } - private async Task ApplyPluginUpdatesAsync() + /// <summary> + /// Plugin updates, companions and the RynthNav map, under one progress display. Cancel stops + /// the download in progress; what finished before it stays finished, nothing is half-installed. + /// </summary> + private async Task ApplyPluginUpdatesAsync(bool automatic) { - UpdateStatusText.Text = "Updating plugins…"; - foreach (string done in await _updater.UpdatePluginsAsync(_updateCheck!)) + if (!automatic) _navDataCancelledThisSession = false; + try { - _pluginsUpdatedThisSession.Add(done); - AppendActivity($"Plugin updated: {done}. Running clients keep their version; it loads the next time AC starts."); + await RunDownloadAsync(async (progress, ct) => + { + foreach (string done in await _updater.UpdatePluginsAsync(_updateCheck!, progress, ct)) + { + _pluginsUpdatedThisSession.Add(done); + AppendActivity($"Plugin updated: {done}. Running clients keep their version; it loads the next time AC starts."); + } + // Plugins split out of one the player has (RynthLua from RynthAi): installed and added. + bool added = false; + foreach (var c in await _updater.InstallCompanionsAsync(_updateCheck!, progress, ct)) + { + added |= PluginListEdits.Add(_pluginDllPaths, c.Path); + _pluginsUpdatedThisSession.Add($"{c.Entry.Name} (new)"); + AppendActivity($"Plugin added: {c.Entry.Name} ({c.Reason}), {c.Path}. It loads the next time AC starts."); + } + if (added) SavePluginDllPaths(); + // RynthNav's map (only with RynthNav in the plugin list). Separate from the + // plugins: a failure here (disk space, a client holding the folder) leaves the plugin + // updates done and is reported on its own. + if (_updateCheck!.NavDataUpdateAvailable && !(automatic && _navDataCancelledThisSession)) + { + try + { + string line = await _updater.UpdateNavDataAsync(_updateCheck!, progress, ct); + if (line.Length > 0) + { + _pluginsUpdatedThisSession.Add("RynthNav map"); + AppendActivity(line); + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + _navDataCancelledThisSession = true; + AppendActivity("RynthNav map download cancelled. Nothing was changed: the map you had is still in place. Update plugins on the Launcher tab starts it again."); + } + catch (Exception ex) + { + AppendActivity($"RynthNav map update failed: {ex.Message}"); + } + } + return true; + }); + } + catch (OperationCanceledException) + { + AppendActivity("Download cancelled. Updates that finished before it are kept; nothing is half-installed."); } // Re-check so the panel reflects the files now on disk, and redraw the plugin // rows so they show the new versions. @@ -1886,68 +2537,43 @@ internal partial class MainWindow : Window BuildPluginLoadout(); } - private void ShowUpdateState() - { - if (_updateCheck is not { } c) return; - var pending = c.PluginsToUpdate.Select(p => p.Entry.Name).Distinct().ToList(); - var local = c.Plugins.Where(p => p.State == RynthUpdater.PluginState.LocalBuild) - .Select(p => p.Entry.Name).Distinct().ToList(); - - var lines = new List<string> - { - c.CoreUpdateAvailable - ? $"RynthCore {c.Manifest.Core.Version} is available (installed: {FormatRelease(c.InstalledCoreRelease)})." - : $"RynthCore is up to date ({FormatRelease(c.InstalledCoreRelease)})." - }; - if (pending.Count > 0) lines.Add($"Plugin updates ready: {string.Join(", ", pending)}."); - else if (c.Plugins.Count > 0) lines.Add("Plugins are up to date."); - if (_pluginsUpdatedThisSession.Count > 0) - lines.Add($"Updated this session: {string.Join(", ", _pluginsUpdatedThisSession)} — loads the next time AC starts."); - if (local.Count > 0) lines.Add($"Left alone (newer local builds): {string.Join(", ", local)}."); - if ((c.CoreUpdateAvailable || pending.Count > 0) && !string.IsNullOrWhiteSpace(c.Manifest.Notes)) - lines.Add(c.Manifest.Notes); - - UpdateStatusText.Text = string.Join("\n", lines); - UpdatePluginsButton.IsVisible = pending.Count > 0; - InstallCoreUpdateButton.IsVisible = c.CoreUpdateAvailable; - HeaderUpdateText.IsVisible = c.CoreUpdateAvailable || pending.Count > 0; - HeaderUpdateText.Text = c.CoreUpdateAvailable ? $"Update available: {c.Manifest.Core.Version}" : "Plugin updates ready"; - } - private async Task InstallCoreUpdateAsync() { if (_updateBusy || _updateCheck is not { CoreUpdateAvailable: true } c) return; int running = RynthCoreClientsRunning(); if (running > 0) { - UpdateStatusText.Text = $"Close your {running} RynthCore game client(s) first — the update replaces files they have open."; + AppendActivity($"Close your {running} game client(s) running RynthCore or its Decal bridge first: the update replaces files they have open."); + RefreshUpdateCard(); return; } _updateBusy = true; - InstallCoreUpdateButton.IsEnabled = false; + RefreshUpdateCard(); try { - UpdateStatusText.Text = $"Downloading RynthCore {c.Manifest.Core.Version}…"; - string installer = await _updater.DownloadInstallerAsync(c); + string installer = await RunDownloadAsync((progress, ct) => _updater.DownloadInstallerAsync(c, progress, ct)); if (RynthCoreClientsRunning() > 0) { - UpdateStatusText.Text = "A RynthCore client started meanwhile — close it, then press Install again."; + AppendActivity("A RynthCore client started meanwhile. Close it, then press Update RynthCore again."); return; } AppendActivity($"Installing RynthCore {c.Manifest.Core.Version}; the launcher restarts when it's done."); RynthUpdater.RunInstaller(installer); (Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown(); } + catch (OperationCanceledException) + { + AppendActivity($"RynthCore {c.Manifest.Core.Version} download cancelled. Nothing was changed."); + } catch (Exception ex) { - UpdateStatusText.Text = $"RynthCore update failed: {ex.Message}"; AppendActivity($"RynthCore update failed: {ex.Message}"); } finally { _updateBusy = false; - InstallCoreUpdateButton.IsEnabled = true; + RefreshUpdateCard(); } } @@ -1956,7 +2582,9 @@ internal partial class MainWindow : Window int n = 0; foreach (Process p in Process.GetProcessesByName("acclient")) { - try { if (_injector.IsRynthCoreLoaded(p)) n++; } + // Decal clients with the Decal bridge loaded count too: the installer replaces + // DecalBridge\RynthCore.DecalBridge.dll, which they keep open. + try { if (_injector.IsRynthCoreLoaded(p) || _injector.IsDecalBridgeLoaded(p)) n++; } catch { } finally { p.Dispose(); } } @@ -2318,13 +2946,13 @@ internal partial class MainWindow : Window // Resolve the account profile to gate on injection mode. If we // can't find a matching profile, skip rather than kill blindly. - string? accountName = sess?.AccountName - ?? (activeContexts.TryGetValue(pid, out LaunchContextRecord? ctx) ? ctx.AccountName : null); + activeContexts.TryGetValue(pid, out LaunchContextRecord? ctx); + string? accountName = sess?.AccountName ?? ctx?.AccountName; + string? serverName = !string.IsNullOrWhiteSpace(sess?.ServerName) ? sess.ServerName : ctx?.ServerName; if (string.IsNullOrWhiteSpace(accountName)) continue; - LaunchAccountProfile? profile = _settings.AccountProfiles.FirstOrDefault(a => - string.Equals(a.AccountName, accountName, StringComparison.OrdinalIgnoreCase)); + LaunchAccountProfile? profile = FindAccountProfile(accountName, serverName); if (profile == null || profile.InjectionMode != InjectionMode.RynthCore) continue; @@ -2379,7 +3007,7 @@ internal partial class MainWindow : Window // 30s), so DetectQuickExits classifies it "normal close" — and // auto-launch would relaunch a perpetually-stuck client in an // endless kill/relaunch loop, bypassing the circuit breaker. - string crashKey = BuildAccountKey(accountName); + string crashKey = BuildAccountKey(accountName, serverName); if (!string.IsNullOrEmpty(crashKey)) { RecordCrash(crashKey); @@ -2424,9 +3052,6 @@ internal partial class MainWindow : Window // misses — observed 2026-06-14: fps=60, item-locked for 2h before fps→0. private static readonly System.Text.RegularExpressions.Regex StanceStuckRegex = new(@"ChangeCombatMode\([^)]*\) retry #\d+ \(stuck (\d+)s", System.Text.RegularExpressions.RegexOptions.Compiled); - // qd ~0 on a healthy client (the AcMainThreadQueue drains every tick); it - // explodes to tens of thousands once AC's main thread stops draining = wedged. - private const int QueueWedgeDepth = 2000; // Can't enter combat mode for this long while in-world = item-action hard-lock. private const int StanceStuckWedgeSeconds = 300; @@ -2551,11 +3176,13 @@ internal partial class MainWindow : Window // tens of fps); plug=0 = the plugin pump itself died. bool fpsZero = last.Groups[1].Value == "0"; bool pumpDead = last.Groups[2].Value == "0"; - int qd = (last.Groups[4].Success && int.TryParse(last.Groups[4].Value, out int q)) ? q : 0; + // No queue rule: the engine's qd (qdrop since 2026-10-01) is a running total of + // DROPPED actions, not a queue depth, so "qd > 2000 for 90 s" killed healthy + // 60 fps clients after a long session (a tester's, 2026-10-01). A truly wedged + // main thread stops rendering, which fpsZero already catches. string? wedgeReason = fpsZero ? "fps=0 with login=1 (render dead)" : pumpDead ? "plugin pump dead (plug=0/s) with login=1" - : qd > QueueWedgeDepth ? $"main-thread queue backing up (qd={qd}, login=1)" : null; if (wedgeReason == null) @@ -2588,8 +3215,9 @@ internal partial class MainWindow : Window _wedgeZeroFpsSinceUtc.Remove(pid); activeSessions.TryGetValue(pid, out SessionStateRecord? sess); - string? accountName = sess?.AccountName - ?? (activeContexts.TryGetValue(pid, out LaunchContextRecord? ctx) ? ctx.AccountName : null); + activeContexts.TryGetValue(pid, out LaunchContextRecord? ctx); + string? accountName = sess?.AccountName ?? ctx?.AccountName; + string? serverName = !string.IsNullOrWhiteSpace(sess?.ServerName) ? sess.ServerName : ctx?.ServerName; try { @@ -2604,7 +3232,7 @@ internal partial class MainWindow : Window // repeatedly-wedging account and stops the loop. if (!string.IsNullOrWhiteSpace(accountName)) { - string key = BuildAccountKey(accountName); + string key = BuildAccountKey(accountName, serverName); if (!string.IsNullOrEmpty(key)) RecordCrash(key); } @@ -2760,12 +3388,8 @@ internal partial class MainWindow : Window { try { - string args = _launchArgumentBuilder.BuildArguments(server, account); - string password = account.Password ?? string.Empty; - if (!string.IsNullOrEmpty(password)) - args = args.Replace(password, "********", StringComparison.Ordinal); - - return args; + // Never decrypts: a saved password shows as the mask. + return _launchArgumentBuilder.BuildMaskedArguments(server, account); } catch (Exception ex) { @@ -2804,14 +3428,14 @@ internal partial class MainWindow : Window var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (LaunchContextRecord context in LaunchContextStore.ReadForActiveProcesses(activePids).Values) { - string key = BuildAccountKey(context.AccountName); + string key = BuildAccountKey(context.AccountName, context.ServerName); if (!string.IsNullOrWhiteSpace(key)) keys.Add(key); } foreach (SessionStateRecord session in SessionStateStore.ReadForActiveProcesses(activePids).Values) { - string key = BuildAccountKey(session.AccountName); + string key = BuildAccountKey(session.AccountName, session.ServerName); if (!string.IsNullOrWhiteSpace(key)) keys.Add(key); } @@ -2847,10 +3471,72 @@ internal partial class MainWindow : Window return _launchedSessionPids.Contains(process.Id) ? "launched here" : "external"; } - private static string BuildAccountKey(string? accountName) => + // Account identity for running-client detection, crash history and prefs + // snapshots. The same account name can exist on several servers (e.g. + // "Buffi" on ACEmulator and on RynthAce), so the key is NAME@SERVER. A + // session/context with no server name yields "NAME@", which + // IsAccountKeyActive treats as matching any server for that name. + private const char AccountKeyServerSeparator = '@'; + + private static string BuildAccountKey(string? accountName, string? serverName) => string.IsNullOrWhiteSpace(accountName) ? string.Empty - : accountName.Trim().ToUpperInvariant(); + : $"{accountName.Trim().ToUpperInvariant()}{AccountKeyServerSeparator}{(serverName ?? string.Empty).Trim().ToUpperInvariant()}"; + + private string BuildAccountKey(LaunchAccountProfile account) => + BuildAccountKey(account.AccountName, ResolveServerForAccount(account)?.Name); + + private static bool IsAccountKeyActive(HashSet<string> activeKeys, string accountKey) + { + if (activeKeys.Contains(accountKey)) + return true; + + // A running client whose server is unknown blocks every server for that + // name, and a profile with no server is blocked by that name anywhere. + int sep = accountKey.IndexOf(AccountKeyServerSeparator); + if (sep < 0) + return false; + + string namePrefix = accountKey[..(sep + 1)]; + if (activeKeys.Contains(namePrefix)) + return true; + + return sep == accountKey.Length - 1 && + activeKeys.Any(k => k.StartsWith(namePrefix, StringComparison.OrdinalIgnoreCase)); + } + + /// <summary> + /// Finds the account profile for a running client. Matches on account name + /// AND server, because two profiles can share an account name on different + /// servers. With no server name, falls back to the first name match. + /// </summary> + private LaunchAccountProfile? FindAccountProfile(string? accountName, string? serverName) + { + if (string.IsNullOrWhiteSpace(accountName)) + return null; + + string name = accountName.Trim(); + List<LaunchAccountProfile> byName = _settings.AccountProfiles + .Where(a => string.Equals(a.AccountName?.Trim(), name, StringComparison.OrdinalIgnoreCase)) + .ToList(); + if (byName.Count == 0) + return null; + + if (string.IsNullOrWhiteSpace(serverName)) + return byName[0]; + + string server = serverName.Trim(); + LaunchAccountProfile? exact = byName.FirstOrDefault(a => + string.Equals(ResolveServerForAccount(a)?.Name?.Trim(), server, StringComparison.OrdinalIgnoreCase)); + if (exact != null) + return exact; + + // Server name not among the saved server profiles (renamed or removed): + // nothing better to match on, so keep the old name-only behaviour. + bool knownServer = _settings.ServerProfiles.Any(sp => + string.Equals(sp.Name?.Trim(), server, StringComparison.OrdinalIgnoreCase)); + return knownServer ? null : byName[0]; + } /// <summary> /// Walks <see cref="_launchedPidInfo"/> and counts any client that exited @@ -3039,20 +3725,9 @@ internal partial class MainWindow : Window if (string.IsNullOrWhiteSpace(accountName)) return; - // Resolve the server profile ID from the server name so we can match - // account profiles precisely — two profiles can share an account name - // on different servers (e.g. "Drakkon" on ACEmulator vs Reefcull). - string? serverId = null; - if (!string.IsNullOrWhiteSpace(serverName)) - { - serverId = _settings.ServerProfiles - .FirstOrDefault(sp => string.Equals(sp.Name, serverName, StringComparison.OrdinalIgnoreCase)) - ?.Id; - } - - LaunchAccountProfile? profile = _settings.AccountProfiles.FirstOrDefault(a => - string.Equals(a.AccountName, accountName, StringComparison.OrdinalIgnoreCase) - && (serverId == null || string.Equals(a.ServerId, serverId, StringComparison.OrdinalIgnoreCase))); + // Match on account name AND server — two profiles can share an account + // name on different servers (e.g. "Drakkon" on ACEmulator vs Reefcull). + LaunchAccountProfile? profile = FindAccountProfile(accountName, serverName); if (profile == null) return; @@ -3094,7 +3769,7 @@ internal partial class MainWindow : Window if (hwnd == IntPtr.Zero) { - LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}): hwnd=0 — cannot restore or capture."); + LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): hwnd=0 — cannot restore or capture."); return; } @@ -3108,7 +3783,7 @@ internal partial class MainWindow : Window profile.WindowWidth!.Value, profile.WindowHeight!.Value, SWP_NOZORDER | SWP_NOACTIVATE); - LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}): restored to ({profile.WindowX},{profile.WindowY},{profile.WindowWidth}x{profile.WindowHeight})."); + LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): restored to ({profile.WindowX},{profile.WindowY},{profile.WindowWidth}x{profile.WindowHeight})."); return; } // No saved position — don't capture immediately. The window may still @@ -3191,7 +3866,7 @@ internal partial class MainWindow : Window } if (refW > 0 && refH > 0 && (long)w * h * 2L < (long)refW * refH) { - LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}): ignored char-select/login shrink ({w}x{h}, <50% of in-game {refW}x{refH})."); + LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): ignored char-select/login shrink ({w}x{h}, <50% of in-game {refW}x{refH})."); return; } @@ -3201,7 +3876,7 @@ internal partial class MainWindow : Window profile.WindowWidth = w; profile.WindowHeight = h; SaveSettings(); - LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}): saved ({x},{y},{w}x{h})."); + LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): saved ({x},{y},{w}x{h})."); } /// <summary> @@ -3276,10 +3951,14 @@ internal partial class MainWindow : Window /// Resolves the per-account UserPreferences.ini stash path. If the profile /// has an explicit path set, that wins (advanced override). Otherwise the /// launcher uses an auto-managed file under %APPDATA%\RynthCore\prefs\ - /// keyed by account name. Returns empty when the account has no name yet - /// (new profile, can't pick a filename). + /// keyed by account name and server ("name@server.ini"), since the same + /// account name can exist on several servers. The old name-only file + /// ("name.ini") is copied (not moved) to seed a missing per-server file, so + /// existing users keep their prefs on every server that shares the name. + /// Returns empty when the account has no name yet (new profile, can't pick + /// a filename). /// </summary> - private static string ResolveUserPrefsPath(LaunchAccountProfile account) + private static string ResolveUserPrefsPath(LaunchAccountProfile account, string? serverName) { if (!string.IsNullOrWhiteSpace(account.UserPrefsPath)) return account.UserPrefsPath.Trim(); @@ -3289,10 +3968,24 @@ internal partial class MainWindow : Window string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string prefsDir = Path.Combine(appdata, "RynthCore", "prefs"); - string safeName = string.Join("_", account.AccountName.Trim().Split(Path.GetInvalidFileNameChars())); - return Path.Combine(prefsDir, $"{safeName}.ini"); + string safeName = SafePrefsFileName(account.AccountName); + string legacyPath = Path.Combine(prefsDir, $"{safeName}.ini"); + if (string.IsNullOrWhiteSpace(serverName)) + return legacyPath; + + string scopedPath = Path.Combine(prefsDir, $"{safeName}@{SafePrefsFileName(serverName)}.ini"); + if (!File.Exists(scopedPath) && File.Exists(legacyPath)) + { + try { File.Copy(legacyPath, scopedPath, overwrite: false); } + catch { return legacyPath; } + } + + return scopedPath; } + private static string SafePrefsFileName(string name) => + string.Join("_", name.Trim().Split(Path.GetInvalidFileNameChars())); + /// <summary> /// Copies the current live UserPreferences.ini to the resolved stash for /// the named account. Called on tracked-client exit so per-account prefs @@ -3305,11 +3998,11 @@ internal partial class MainWindow : Window return; LaunchAccountProfile? profile = _settings.AccountProfiles.FirstOrDefault(a => - string.Equals(BuildAccountKey(a.AccountName), accountKey, StringComparison.OrdinalIgnoreCase)); + string.Equals(BuildAccountKey(a), accountKey, StringComparison.OrdinalIgnoreCase)); if (profile == null) return; - string stashPath = ResolveUserPrefsPath(profile); + string stashPath = ResolveUserPrefsPath(profile, ResolveServerForAccount(profile)?.Name); if (string.IsNullOrEmpty(stashPath)) return; @@ -3359,7 +4052,7 @@ internal partial class MainWindow : Window private void MaybeLogCircuitBreaker(LaunchAccountProfile account, DateTime nowUtc) { - string accountKey = BuildAccountKey(account.AccountName); + string accountKey = BuildAccountKey(account); if (_crashBreakerLogTimesUtc.TryGetValue(accountKey, out DateTime lastLogUtc) && nowUtc - lastLogUtc < CrashBreakerLogCooldown) { @@ -3411,7 +4104,7 @@ internal partial class MainWindow : Window continue; } - string accountKey = BuildAccountKey(account.AccountName); + string accountKey = BuildAccountKey(account.AccountName, server?.Name); if (IsAccountInCircuitBreaker(accountKey, nowUtc)) { MaybeLogCircuitBreaker(account, nowUtc); @@ -3782,7 +4475,8 @@ internal partial class MainWindow : Window { int digits = Math.Max(2, _settings.AccountProfiles.Count.ToString().Length); return _settings.AccountProfiles - .Select((account, index) => $"{FormatOrdinal(index, digits)} {account.DisplayName}") + .Select((account, index) => $"{FormatOrdinal(index, digits)} {account.DisplayName}" + + (account.PasswordNeedsReentry ? " [password needs re-entering]" : string.Empty)) .ToArray(); } diff --git a/src/RynthCore.App.Avalonia/Program.cs b/src/RynthCore.App.Avalonia/Program.cs index c66358d..d532485 100644 --- a/src/RynthCore.App.Avalonia/Program.cs +++ b/src/RynthCore.App.Avalonia/Program.cs @@ -7,7 +7,67 @@ namespace RynthCore.App.Avalonia; internal static class Program { [STAThread] - public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); + public static int Main(string[] args) + { + // The uninstaller removes the Decal bridge registration (docs/DECAL_BRIDGE_PLAN.md): + // no window, just the per-user registry entries this launcher added. + if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-unregister", StringComparison.OrdinalIgnoreCase))) + { + bool ok = RynthCore.App.DecalBridgeRegistration.Unregister(out string report); + LauncherDiag.Info($"DECALBRIDGE: unregister (command line): {report}"); + // A machine-wide entry (added with administrator rights when AC runs elevated on this + // PC) goes too: the uninstaller removes the DLL it points at. Ask for the rights only + // when there is one. + if (RynthCore.App.DecalBridgeRegistration.MachineEntryIsOurs()) + { + var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string mReport); + if (outcome == RynthCore.App.DecalBridgeRegistration.Outcome.NeedsAdmin && Environment.ProcessPath is string self) + outcome = RynthCore.App.DecalBridgeRegistration.RunElevated(self, "--decal-bridge-unregister-machine", out mReport); + LauncherDiag.Info($"DECALBRIDGE: unregister machine-wide (command line): {mReport}"); + ok &= outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered; + } + return ok ? 0 : 1; + } + if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-unregister-machine", StringComparison.OrdinalIgnoreCase))) + { + var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string report); + LauncherDiag.Info($"DECALBRIDGE: unregister machine-wide (elevated step): {report}"); + return outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered ? 0 : 1; + } + // The launcher's elevated step for "AC reads Decal's filter list for all users" + // (MainWindow.EnsureDecalBridgeAsync): --decal-bridge-register-machine "<bridge folder>". + int rm = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge-register-machine", StringComparison.OrdinalIgnoreCase)); + if (rm >= 0) + { + string dir = rm + 1 < args.Length ? args[rm + 1] : RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory; + var outcome = RynthCore.App.DecalBridgeRegistration.RegisterMachineWide(dir, out string report); + LauncherDiag.Info($"DECALBRIDGE: register machine-wide (elevated step): {report}"); + return outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered ? 0 : 1; + } + // The installer's per-user half (installer\RynthCore.iss, as the installing user, every + // install and update): our entry into an EXISTING per-user copy of Decal's filter list. + int iu = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge-install-user", StringComparison.OrdinalIgnoreCase)); + if (iu >= 0) + { + string dir = iu + 1 < args.Length ? args[iu + 1] : RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory; + bool ok = RynthCore.App.DecalBridgeRegistration.InstallPerUser(dir, out string report); + LauncherDiag.Info($"DECALBRIDGE: install per-user (installer): {report}"); + return ok ? 0 : 1; + } + if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-status", StringComparison.OrdinalIgnoreCase))) + { + LauncherDiag.Info($"DECALBRIDGE: status (command line): {RynthCore.App.DecalBridgeRegistration.GetStatus()}"); + return 0; + } + if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-check", StringComparison.OrdinalIgnoreCase))) + { + var check = RynthCore.App.RealDecalCheckHost.Check(RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory, + RynthCore.App.DecalLocator.TryGetDecalAcClientPath(), EngineJsonStore.Path); + LauncherDiag.Info($"DECALBRIDGE: check (command line):{Environment.NewLine}{check.ToReport()}"); + return check.Blocking ? 1 : 0; + } + return BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); + } public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<App>() diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index 38c7305..e4e75f5 100644 --- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj +++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj @@ -44,8 +44,12 @@ <ItemGroup> <Compile Include="..\RynthCore.App\LaunchServerProfile.cs" Link="Shared\LaunchServerProfile.cs" /> <Compile Include="..\RynthCore.App\LaunchAccountProfile.cs" Link="Shared\LaunchAccountProfile.cs" /> + <Compile Include="..\RynthCore.App\AccountPasswordProtection.cs" Link="Shared\AccountPasswordProtection.cs" /> <Compile Include="..\RynthCore.App\InjectionMode.cs" Link="Shared\InjectionMode.cs" /> <Compile Include="..\RynthCore.App\DecalLocator.cs" Link="Shared\DecalLocator.cs" /> + <Compile Include="..\RynthCore.App\DecalBridgeRegistration.cs" Link="Shared\DecalBridgeRegistration.cs" /> + <Compile Include="..\RynthCore.App\DecalBridgeCheck.cs" Link="Shared\DecalBridgeCheck.cs" /> + <Compile Include="..\RynthCore.App\RealDecalCheckHost.cs" Link="Shared\RealDecalCheckHost.cs" /> <Compile Include="..\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="Shared\AcLaunchArgumentBuilder.cs" /> <Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" /> <Compile Include="..\RynthCore.App\AcClientLoginAutomationService.cs" Link="Shared\AcClientLoginAutomationService.cs" /> @@ -55,6 +59,7 @@ <Compile Include="..\RynthCore.App\BuildVersion.cs" Link="Shared\BuildVersion.cs" /> <Compile Include="..\RynthCore.App\AppSettings.cs" Link="Shared\AppSettings.cs" /> <Compile Include="..\RynthCore.App\AppSettingsStore.cs" Link="Shared\AppSettingsStore.cs" /> + <Compile Include="..\RynthCore.App\DecalAccountModes.cs" Link="Shared\DecalAccountModes.cs" /> <Compile Include="..\RynthCore.App\PluginDefinition.cs" Link="Shared\PluginDefinition.cs" /> <Compile Include="..\RynthCore.Injector\EngineInjectionService.cs" Link="Shared\EngineInjectionService.cs" /> <Compile Include="..\RynthCore.Injector\InjectionResult.cs" Link="Shared\InjectionResult.cs" /> diff --git a/src/RynthCore.App.Avalonia/RynthUpdater.Available.cs b/src/RynthCore.App.Avalonia/RynthUpdater.Available.cs new file mode 100644 index 0000000..57478fa --- /dev/null +++ b/src/RynthCore.App.Avalonia/RynthUpdater.Available.cs @@ -0,0 +1,301 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace RynthCore.App.Avalonia; + +/// <summary> +/// "Available plugins": every plugin in the signed feed that isn't in the player's plugin list, +/// for the player to install or not. +/// +/// Install downloads the feed's file (verified against the signed size and SHA-256, like every +/// update) into C:\Games\RynthSuite\<Name>\<File> - the folder beside RynthAi's, or the +/// default - and the caller adds it to the plugin list. Only plugins named in the signed manifest +/// can be installed, from the URLs it carries; nothing else. +/// +/// Removing a plugin from the list never deletes its files; a feed plugin that leaves the list is +/// simply available again. +/// +/// "New": a plugin the launcher sees in the feed for the first time is marked New for a month and +/// said once in the activity log. The first time this runs (no update-seen-plugins.json yet), +/// what the feed already had counts as old except <see cref="RecentlyAdded"/>, which a player +/// who never got them should hear about. +/// </summary> +internal sealed partial class RynthUpdater +{ + public const string DefaultSuiteDir = @"C:\Games\RynthSuite"; + private const string RynthAiFile = "RynthCore.Plugin.RynthAi.dll"; + private const int MaxDescriptionLength = 160; + private const int MaxChanges = 20; + private static readonly TimeSpan NewBadgeFor = TimeSpan.FromDays(30); + private static readonly Regex SafeFolderName = new(@"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", RegexOptions.CultureInvariant); + + /// <summary>A feed plugin the player can install: where it would go, what it is, and whether it's new.</summary> + public sealed record AvailablePlugin(PluginEntry Entry, string Path, string Description, string Version, bool IsNew); + + /// <summary>What <see cref="InstallPluginAsync"/> did: Downloaded is false when a good copy was already there.</summary> + public sealed record PluginInstall(PluginEntry Entry, string Path, string Description, bool Downloaded); + + /// <summary> + /// Plugins new in the feed before this list existed (2026.10.3.4). 2026.10.4.3 installed them + /// beside RynthAi automatically; from this launcher on they are offered, not forced. + /// </summary> + private static readonly string[] RecentlyAdded = { "RynthOracle", "RynthInventory" }; + + /// <summary>One line per plugin for feeds that carry no "description" (every feed before 2026.10.5).</summary> + private static readonly Dictionary<string, string> BuiltInDescriptions = new(StringComparer.OrdinalIgnoreCase) + { + ["RynthAi"] = "The bot: combat, buffs, looting, navigation routes and metas.", + ["RynthChat"] = "A chat window that sorts messages into tabs.", + ["RynthTracker"] = "Kills, experience and luminance per hour for each session.", + ["RynthNav"] = "Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB).", + ["RynthVision"] = "Shows unclimbable slopes, impassable water and your radar range in the world.", + ["RynthLua"] = "Lua scripting for metas and your own scripts.", + ["RynthOracle"] = "Quests, character, titles and leaderboards.", + ["RynthInventory"] = "Search every character's items.", + }; + + /// <summary>The feed's description, else the launcher's own line, else "".</summary> + public static string DescribePlugin(PluginEntry e) => + e.Description.Length > 0 ? e.Description + : BuiltInDescriptions.TryGetValue(e.Name, out string? d) ? d : ""; + + private string? _suiteDirOverride; + /// <summary>Tests: the folder to use when no plugin in the list shows where RynthSuite lives.</summary> + internal void SetDefaultSuiteDir(string dir) => _suiteDirOverride = dir; + /// <summary>Tests: the clock for the New badge.</summary> + internal Func<DateTime> UtcNow { get; set; } = () => DateTime.UtcNow; + + /// <summary> + /// Where RynthSuite plugins go: beside RynthAi (C:\Games\RynthSuite\RynthAi\x.dll -> C:\Games\RynthSuite), + /// else beside any feed plugin that sits in a folder named after it, else the default. + /// </summary> + public string SuiteDir(Manifest manifest, IEnumerable<string> pluginPaths) + { + List<string> paths = pluginPaths.ToList(); + string? FromPlugin(string path) + { + string? folder = Path.GetDirectoryName(path); + string? suite = Path.GetDirectoryName(folder); + return string.IsNullOrEmpty(folder) || string.IsNullOrEmpty(suite) ? null : suite; + } + string? ai = paths.FirstOrDefault(p => string.Equals(Path.GetFileName(p), RynthAiFile, StringComparison.OrdinalIgnoreCase)); + if (ai != null && FromPlugin(ai) is { } s1) return s1; + foreach (string p in paths) + { + PluginEntry? e = manifest.Plugins.FirstOrDefault(x => string.Equals(x.File, Path.GetFileName(p), StringComparison.OrdinalIgnoreCase)); + if (e != null && string.Equals(Path.GetFileName(Path.GetDirectoryName(p)), e.Name, StringComparison.OrdinalIgnoreCase) + && FromPlugin(p) is { } s2) + return s2; + } + return _suiteDirOverride ?? DefaultSuiteDir; + } + + /// <summary>C:\Games\RynthSuite\<Name>\<File>; null for a name that isn't a plain folder name.</summary> + private static string? TargetPath(PluginEntry e, string suiteDir) => + SafeFolderName.IsMatch(e.Name) && e.Name != "." && e.Name != ".." ? Path.Combine(suiteDir, e.Name, e.File) : null; + + /// <summary> + /// Every feed plugin whose file isn't in <paramref name="pluginPaths"/> (by file name, like the + /// updates), except companions about to be installed anyway. + /// </summary> + public List<AvailablePlugin> GetAvailable(Manifest manifest, IEnumerable<string> pluginPaths, IEnumerable<CompanionInstall>? pending = null) + { + List<string> paths = pluginPaths.ToList(); + var listed = new HashSet<string>(paths.Select(Path.GetFileName).OfType<string>(), StringComparer.OrdinalIgnoreCase); + var skip = new HashSet<string>((pending ?? Array.Empty<CompanionInstall>()).Select(c => c.Entry.File), StringComparer.OrdinalIgnoreCase); + string suite = SuiteDir(manifest, paths); + Dictionary<string, DateTime> seen = ReadSeenPlugins(out _); + DateTime now = UtcNow(); + var result = new List<AvailablePlugin>(); + foreach (PluginEntry e in manifest.Plugins) + { + if (listed.Contains(e.File) || skip.Contains(e.File)) continue; + if (TargetPath(e, suite) is not { } target) continue; + bool isNew = seen.TryGetValue(e.Name, out DateTime first) && now - first < NewBadgeFor; + result.Add(new AvailablePlugin(e, target, DescribePlugin(e), manifest.Version, isNew)); + } + // New ones first, then by name. + return result.OrderByDescending(a => a.IsNew).ThenBy(a => a.Entry.Name, StringComparer.OrdinalIgnoreCase).ToList(); + } + + /// <summary>The Available list for a check, against the plugin list as it is now.</summary> + public List<AvailablePlugin> GetAvailable(CheckResult check, IEnumerable<string> pluginPaths) => + GetAvailable(check.Manifest, pluginPaths, check.Companions); + + /// <summary> + /// Installs one plugin from the signed feed for the caller to add to the plugin list. A file + /// already at the target is kept when it is the release build or newer (someone's own build); + /// an older one is replaced and kept beside it as .previous. Throws, with nothing changed, + /// when the download doesn't match the signed size and hash or is cancelled. + /// </summary> + public async Task<PluginInstall> InstallPluginAsync(CheckResult check, string name, IEnumerable<string> pluginPaths, + IProgress<DownloadProgress>? progress = null, CancellationToken ct = default) + { + List<string> paths = pluginPaths.ToList(); + PluginEntry e = check.Manifest.Plugins.FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)) + ?? throw new InvalidOperationException($"{name} is not in the update feed"); + if (paths.Any(p => string.Equals(Path.GetFileName(p), e.File, StringComparison.OrdinalIgnoreCase))) + throw new InvalidOperationException($"{e.Name} is already in your plugin list"); + string target = TargetPath(e, SuiteDir(check.Manifest, paths)) + ?? throw new InvalidDataException($"bad plugin name '{e.Name}' in the feed"); + + if (File.Exists(target)) + { + bool same = string.Equals(Sha256File(target), e.Sha256, StringComparison.OrdinalIgnoreCase); + bool localBuild = File.GetLastWriteTimeUtc(target) > check.Manifest.PublishedUtc.AddMinutes(1); + if (same || localBuild) + return new PluginInstall(e, target, DescribePlugin(e), Downloaded: false); + } + + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll"); + try + { + await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct, e.Name, progress); + progress?.Report(new DownloadProgress(e.Name, DownloadStage.Installing, 0, 0)); + // Stamp the release time so a later check never mistakes it for a local build. + File.SetLastWriteTimeUtc(temp, check.Manifest.PublishedUtc); + if (File.Exists(target)) File.Copy(target, target + ".previous", overwrite: true); + File.Move(temp, target, overwrite: true); + } + finally + { + try { File.Delete(temp); } catch { } + } + return new PluginInstall(e, target, DescribePlugin(e), Downloaded: true); + } + + // ── Manifest fields (optional, backward-compatible) ─────────────────────── + + /// <summary>The plugin entry's optional "description": one line, plain text, at most 160 characters.</summary> + private static string ReadDescription(JsonElement p) + { + if (!p.TryGetProperty("description", out JsonElement d) || d.ValueKind != JsonValueKind.String) return ""; + return OneLine(d.GetString(), MaxDescriptionLength); + } + + /// <summary>The manifest's optional "changes": up to 20 lines.</summary> + private static IReadOnlyList<string> ReadChanges(JsonElement r) + { + if (!r.TryGetProperty("changes", out JsonElement c) || c.ValueKind != JsonValueKind.Array) return Array.Empty<string>(); + var list = new List<string>(); + foreach (JsonElement e in c.EnumerateArray()) + { + if (e.ValueKind != JsonValueKind.String) continue; + string line = OneLine(e.GetString(), 300); + if (line.Length > 0) list.Add(line); + if (list.Count >= MaxChanges) break; + } + return list; + } + + private static string OneLine(string? s, int max) + { + if (string.IsNullOrWhiteSpace(s)) return ""; + var sb = new StringBuilder(Math.Min(s.Length, max + 1)); + bool space = false; + foreach (char ch in s) + { + if (char.IsWhiteSpace(ch) || char.IsControl(ch)) { space = sb.Length > 0; continue; } + if (space) { sb.Append(' '); space = false; } + sb.Append(ch); + if (sb.Length > max) break; + } + string line = sb.ToString(); + return line.Length > max ? line[..(max - 1)].TrimEnd() + "…" : line; + } + + // ── Seen plugins (the New badge) ────────────────────────────────────────── + + private string SeenPath => Path.Combine(_stateDir, "update-seen-plugins.json"); + + private Dictionary<string, DateTime> ReadSeenPlugins(out bool existed) + { + var map = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase); + existed = false; + try + { + if (!File.Exists(SeenPath)) return map; + using var doc = JsonDocument.Parse(File.ReadAllText(SeenPath)); + foreach (JsonProperty p in doc.RootElement.EnumerateObject()) + if (p.Value.ValueKind == JsonValueKind.String && DateTime.TryParse(p.Value.GetString(), null, + System.Globalization.DateTimeStyles.AdjustToUniversal | System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime t)) + map[p.Name] = t; + existed = true; + } + catch { map.Clear(); existed = false; } + return map; + } + + /// <summary>Records the feed's plugins as seen; returns the ones seen for the first time that count as new.</summary> + private HashSet<string> RecordSeenPlugins(Manifest manifest) + { + var fresh = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + Dictionary<string, DateTime> seen = ReadSeenPlugins(out bool existed); + HashSet<string> offered = ReadOfferedCompanions(); + DateTime now = UtcNow(); + bool changed = !existed; + foreach (PluginEntry e in manifest.Plugins) + { + if (seen.ContainsKey(e.Name)) continue; + // First run of this list: only the recent additions are news, and not to a player who + // already had them offered (2026.10.4.3 installed them; removing one keeps it removed). + bool isNew = existed || (RecentlyAdded.Contains(e.Name, StringComparer.OrdinalIgnoreCase) && !offered.Contains(e.Name)); + seen[e.Name] = isNew ? now : DateTime.UnixEpoch; + if (isNew) fresh.Add(e.Name); + changed = true; + } + if (changed) + { + try + { + Directory.CreateDirectory(_stateDir); + string tmp = SeenPath + ".tmp"; + var ordered = seen.OrderBy(kv => kv.Key, StringComparer.OrdinalIgnoreCase) + .ToDictionary(kv => kv.Key, kv => kv.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")); + File.WriteAllText(tmp, JsonSerializer.Serialize(ordered, new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8); + File.Move(tmp, SeenPath, overwrite: true); + } + catch { } + } + return fresh; + } +} + +/// <summary>Edits to the launcher's plugin list (kept apart from the window so tests can run them).</summary> +internal static class PluginListEdits +{ + /// <summary>Adds <paramref name="path"/> once; false when it was already listed.</summary> + public static bool Add(IList<string> paths, string path) + { + if (paths.Any(p => string.Equals(p, path, StringComparison.OrdinalIgnoreCase))) return false; + paths.Add(path); + return true; + } + + /// <summary> + /// Takes <paramref name="path"/> out of the list, and out of the disabled list so adding it back + /// later starts it enabled. Never touches the file. + /// </summary> + public static bool Remove(IList<string> paths, IList<string>? disabled, string path) + { + bool removed = RemoveAll(paths, path) > 0; + if (disabled != null) RemoveAll(disabled, path); + return removed; + } + + private static int RemoveAll(IList<string> list, string path) + { + int n = 0; + for (int i = list.Count - 1; i >= 0; i--) + if (string.Equals(list[i], path, StringComparison.OrdinalIgnoreCase)) { list.RemoveAt(i); n++; } + return n; + } +} diff --git a/src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs b/src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs new file mode 100644 index 0000000..2d2d27f --- /dev/null +++ b/src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs @@ -0,0 +1,298 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace RynthCore.App.Avalonia; + +/// <summary> +/// RynthNav's data folder (C:\Games\RynthCore\NavData by default): the navmesh tiles, portals.tsv +/// and locations.json, shipped as one archive. +/// +/// Feed: an optional "navdata" object in the signed manifest — +/// {"id": hash of the tile set, "release": n, "url", "size", "sha256", "files": file count, +/// "bytes": unpacked size}. +/// The signature covers it exactly like the plugins; the archive is checked against the signed +/// size and SHA-256 before it is opened, and only plain file names RynthNav reads +/// (nav_XXXX.tile, portals.tsv, locations.json, navgraph.bin: the long-range route graph, +/// townnet.json: the Town Network's portals and the walks inside) are +/// accepted from it. +/// +/// Install: only when RynthNav is in the plugin list and the folder's navdata.id differs from the +/// feed's id. The archive is unpacked beside the folder (NavData.new), the player's own files there +/// (atlas.txt, recalls.txt, anything else not shipped) are copied across, then the folders swap: +/// the old one is kept as NavData.previous (one generation). Old tiles never mix with new ones — +/// tiles from different bakes don't link. A folder with a navdata.local file in it is never touched +/// (someone baking their own tiles). Running clients keep the tiles they already loaded; new ones +/// load as they move (a relog picks up everything). +/// </summary> +internal sealed partial class RynthUpdater +{ + public const string NavDataDefaultDir = @"C:\Games\RynthCore\NavData"; + public const string NavDataIdFile = "navdata.id"; + public const string NavDataLocalMarker = "navdata.local"; + private const string RynthNavFile = "RynthCore.Plugin.RynthNav.dll"; + private const long MaxNavDataBytes = 3L << 30; // the archive + private const long MaxNavDataEntryBytes = 32L << 20; // one file in it + + private static readonly Regex ShippedName = new(@"^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json)$", RegexOptions.CultureInvariant); + private static readonly Regex IdPattern = new(@"^[0-9a-f]{16,64}$", RegexOptions.CultureInvariant); + + public sealed record NavDataEntry(string Id, int Release, string Url, long Size, string Sha256, int Files, long Bytes); + public enum NavDataState { UpToDate, NeedsUpdate, LocalTiles } + public sealed record NavDataStatus(NavDataEntry Entry, string Dir, string InstalledId, NavDataState State); + + /// <summary>True for a file name the archive may carry (and that an update replaces).</summary> + public static bool IsShippedNavFile(string name) => ShippedName.IsMatch(name); + + /// <summary> + /// A whole number written either way: 1383002945 or 1383002945.0. PowerShell's ConvertTo-Json writes + /// a double with ".0", and GetInt64 refused it - which failed the whole update check for every + /// launcher on 2026.10.3.1/2 ("One of the identified items was in an invalid format"). + /// </summary> + private static long WholeNumber(JsonElement e) + { + if (e.TryGetInt64(out long l)) return l; + double d = e.GetDouble(); + if (d < 0 || d > long.MaxValue || d != Math.Floor(d)) throw new InvalidDataException($"not a whole number: {e.GetRawText()}"); + return (long)d; + } + + /// <summary>A navdata entry that can't be read leaves the tiles out of this check; the core and plugins still update.</summary> + private NavDataEntry? TryParseNavData(JsonElement nd) + { + try { return ParseNavData(nd); } + catch (Exception ex) when (ex is InvalidDataException or FormatException or InvalidOperationException or KeyNotFoundException) + { + System.Diagnostics.Debug.WriteLine($"RynthUpdater: navdata entry unreadable ({ex.Message}); tiles skipped this check."); + return null; + } + } + + private NavDataEntry ParseNavData(JsonElement nd) + { + string id = (nd.GetProperty("id").GetString() ?? "").ToLowerInvariant(); + if (!IdPattern.IsMatch(id)) throw new InvalidDataException($"bad navdata id '{id}'"); + int files = (int)WholeNumber(nd.GetProperty("files")); + if (files <= 0) throw new InvalidDataException("navdata lists no files"); + return new NavDataEntry(id, (int)WholeNumber(nd.GetProperty("release")), CheckUrl(nd.GetProperty("url").GetString()), + WholeNumber(nd.GetProperty("size")), nd.GetProperty("sha256").GetString() ?? "", files, + nd.TryGetProperty("bytes", out JsonElement b) ? WholeNumber(b) : 0); + } + + /// <summary> + /// Where RynthNav reads its data: "navDataDir" in %APPDATA%\RynthCore\rynthnav.json (the same + /// file the plugin reads; see the plugin's NavDataConfig), else the default. + /// </summary> + public string NavDataDir + { + get + { + try + { + string settings = Path.Combine(_stateDir, "rynthnav.json"); + if (File.Exists(settings)) + { + using var doc = JsonDocument.Parse(File.ReadAllText(settings), + new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }); + if (doc.RootElement.ValueKind == JsonValueKind.Object) + foreach (JsonProperty p in doc.RootElement.EnumerateObject()) + if (p.Name.Equals("navDataDir", StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.String + && p.Value.GetString() is { } dir && Path.IsPathFullyQualified(dir.Trim())) + return dir.Trim().TrimEnd('\\', '/'); + } + } + catch { } + return _navDataDirOverride ?? NavDataDefaultDir; + } + } + + private string? _navDataDirOverride; + /// <summary>Where the archive is downloaded to; null = %LOCALAPPDATA%\RynthCore\updates (tests set their own).</summary> + internal string? NavDataCacheDir { get; set; } + /// <summary>Tests: the folder to use when rynthnav.json doesn't name one.</summary> + internal void SetDefaultNavDataDir(string dir) => _navDataDirOverride = dir; + + private NavDataStatus? CheckNavData(Manifest manifest, IEnumerable<string> pluginPaths) + { + if (manifest.NavData is not { } e) return null; + bool hasNav = pluginPaths.Any(p => string.Equals(Path.GetFileName(p), RynthNavFile, StringComparison.OrdinalIgnoreCase) && File.Exists(p)); + if (!hasNav) return null; + string dir = NavDataDir; + string installed = ""; + try { if (File.Exists(Path.Combine(dir, NavDataIdFile))) installed = File.ReadAllText(Path.Combine(dir, NavDataIdFile)).Trim().ToLowerInvariant(); } + catch { } + NavDataState state = File.Exists(Path.Combine(dir, NavDataLocalMarker)) ? NavDataState.LocalTiles + : installed == e.Id ? NavDataState.UpToDate : NavDataState.NeedsUpdate; + return new NavDataStatus(e, dir, installed, state); + } + + /// <summary> + /// Downloads, verifies and installs the feed's RynthNav data (see the class notes). Returns a + /// line for the activity log. Throws on anything wrong, leaving the installed folder as it was. + /// </summary> + public const string NavDataDisplayName = "RynthNav map"; + + /// <summary> + /// Cancel is safe at any point before the folder swap: the partial download is deleted, an + /// unpacked staging folder is removed, and the installed tiles stay as they were. A fully + /// downloaded, verified archive stays in the cache and is reused by the next try. The swap + /// itself (two folder renames) doesn't stop half way. + /// </summary> + public async Task<string> UpdateNavDataAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default) + { + if (check.NavData is not { State: NavDataState.NeedsUpdate } st) return ""; + NavDataEntry e = st.Entry; + string dir = st.Dir.TrimEnd('\\', '/'); + string parent = Path.GetDirectoryName(dir) ?? throw new InvalidOperationException($"bad NavData folder {dir}"); + Directory.CreateDirectory(parent); + + // Room for the archive, the unpacked copy and the old folder kept as .previous. + long need = e.Size + Math.Max(e.Bytes, e.Size * 3) + (64L << 20); + long free = new DriveInfo(Path.GetPathRoot(Path.GetFullPath(dir))!).AvailableFreeSpace; + if (free < need) + throw new IOException($"not enough disk space for the navmesh tiles: {need >> 20} MB needed, {free >> 20} MB free on {Path.GetPathRoot(dir)}"); + + string cache = NavDataCacheDir ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "updates"); + Directory.CreateDirectory(cache); + string zip = Path.Combine(cache, $"navdata-{e.Id}.zip"); + if (!(File.Exists(zip) && new FileInfo(zip).Length == e.Size && string.Equals(Sha256File(zip), e.Sha256, StringComparison.OrdinalIgnoreCase))) + { + await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxNavDataBytes, zip + ".part", ct, NavDataDisplayName, progress); + File.Move(zip + ".part", zip, overwrite: true); + } + + // Unpacking tens of thousands of files takes a while: off the caller's (UI) thread. + await Task.Run(() => + { + progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Unpacking, 0, e.Files)); + string staging = dir + ".new"; + if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true); + Directory.CreateDirectory(staging); + try + { + int count = ExtractNavData(zip, staging, ct, + n => progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Unpacking, n, e.Files))); + if (count != e.Files) throw new InvalidDataException($"the tile archive has {count} files, the feed says {e.Files}"); + + // The player's own files (atlas.txt, recalls.txt, …) and anything else not shipped come along. + if (Directory.Exists(dir)) CopyUnshipped(dir, staging); + File.WriteAllText(Path.Combine(staging, NavDataIdFile), e.Id); + + // Last chance to cancel: from here the swap runs to the end. + ct.ThrowIfCancellationRequested(); + progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Installing, 0, 0)); + SwapNavData(dir, staging); + } + catch + { + try { if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true); } catch { } + throw; + } + }, ct); + try { File.Delete(zip); } catch { } + return $"RynthNav navmesh tiles updated: {e.Files} files into {dir} (the old ones are in {Path.GetFileName(dir)}.previous). Running clients load the new tiles as they move; a relog picks up all of them."; + } + + /// <summary>Unpacks only plain, known file names; returns how many files were written.</summary> + internal static int ExtractNavData(string zipPath, string dest, CancellationToken ct = default, Action<int>? unpacked = null) + { + int n = 0; + var sinceReport = System.Diagnostics.Stopwatch.StartNew(); + var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + using ZipArchive za = ZipFile.OpenRead(zipPath); + foreach (ZipArchiveEntry z in za.Entries) + { + ct.ThrowIfCancellationRequested(); + if (z.FullName.EndsWith('/') && z.Length == 0) continue; // a folder entry + string name = z.FullName; + if (name != z.Name || !IsShippedNavFile(name)) + throw new InvalidDataException($"unexpected file in the tile archive: '{name}'"); + if (!seen.Add(name)) throw new InvalidDataException($"'{name}' is in the tile archive twice"); + if (z.Length > MaxNavDataEntryBytes) throw new InvalidDataException($"'{name}' is too large ({z.Length} bytes)"); + string target = Path.Combine(dest, name); + using (Stream src = z.Open()) + using (var f = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + byte[] buf = new byte[81920]; + long total = 0; int r; + while ((r = src.Read(buf, 0, buf.Length)) > 0) + { + total += r; + if (total > MaxNavDataEntryBytes) throw new InvalidDataException($"'{name}' unpacks larger than it says"); + f.Write(buf, 0, r); + } + } + n++; + if (unpacked != null && sinceReport.Elapsed >= DownloadMeter.ReportEvery) + { + unpacked(n); + sinceReport.Restart(); + } + } + unpacked?.Invoke(n); + return n; + } + + private static void CopyUnshipped(string from, string to) + { + foreach (string f in Directory.GetFiles(from)) + { + string name = Path.GetFileName(f); + if (IsShippedNavFile(name) || name.Equals(NavDataIdFile, StringComparison.OrdinalIgnoreCase)) continue; + string target = Path.Combine(to, name); + if (!File.Exists(target)) File.Copy(f, target); + } + foreach (string d in Directory.GetDirectories(from)) + { + string target = Path.Combine(to, Path.GetFileName(d)); + Directory.CreateDirectory(target); + CopyTree(d, target); + } + } + + private static void CopyTree(string from, string to) + { + foreach (string f in Directory.GetFiles(from)) File.Copy(f, Path.Combine(to, Path.GetFileName(f)), overwrite: false); + foreach (string d in Directory.GetDirectories(from)) + { + string t = Path.Combine(to, Path.GetFileName(d)); + Directory.CreateDirectory(t); + CopyTree(d, t); + } + } + + // dir -> dir.previous, staging -> dir. A client reading a tile at that moment holds it open for + // a few milliseconds, so each move is retried; if the second fails the first is undone. + private static void SwapNavData(string dir, string staging) + { + string previous = dir + ".previous"; + bool hadOld = Directory.Exists(dir); + if (hadOld) + { + if (Directory.Exists(previous)) Directory.Delete(previous, recursive: true); + Retry(() => Directory.Move(dir, previous)); + } + try { Retry(() => Directory.Move(staging, dir)); } + catch + { + if (hadOld && !Directory.Exists(dir)) { try { Directory.Move(previous, dir); } catch { } } + throw; + } + } + + private static void Retry(Action a) + { + for (int i = 0; ; i++) + { + try { a(); return; } + catch (IOException) when (i < 9) { Thread.Sleep(500); } + catch (UnauthorizedAccessException) when (i < 9) { Thread.Sleep(500); } + } + } +} diff --git a/src/RynthCore.App.Avalonia/RynthUpdater.cs b/src/RynthCore.App.Avalonia/RynthUpdater.cs index bca0c4a..7a4d0c4 100644 --- a/src/RynthCore.App.Avalonia/RynthUpdater.cs +++ b/src/RynthCore.App.Avalonia/RynthUpdater.cs @@ -25,8 +25,12 @@ namespace RynthCore.App.Avalonia; /// touches a running bot: the new version loads the next time AC starts, or on RL if the player /// chooses — the updater never reloads anything. The core (engine, Loader, launcher) updates by /// running the release's installer, and only while no RynthCore client is running. +/// +/// RynthNav's data (navmesh tiles, portals.tsv, locations.json) is an optional signed archive in +/// the same manifest ("navdata"), installed only for players who have RynthNav in their plugin +/// list, and only when its id (a hash of the tile set) changes. See RynthUpdater.NavData.cs. /// </summary> -internal sealed class RynthUpdater +internal sealed partial class RynthUpdater { public const string DefaultFeedUrl = "https://aelrynth.com/downloads/rynth/update.json"; @@ -34,21 +38,60 @@ internal sealed class RynthUpdater private const long MaxPluginBytes = 64L << 20; private const long MaxInstallerBytes = 256L << 20; - public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256); + /// <summary> + /// One plugin in the feed. <paramref name="Description"/> is the optional one-line "description" + /// (written since 2026.10.5); older feeds have none and the launcher's own table fills in + /// (<see cref="DescribePlugin"/>). Launchers before it ignore the field. + /// </summary> + public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256, string Description = ""); public sealed record InstallerEntry(int Release, string Version, string Url, long Size, string Sha256); public sealed record Manifest(int Release, string Version, DateTime PublishedUtc, string Notes, - InstallerEntry Core, IReadOnlyList<PluginEntry> Plugins); + InstallerEntry Core, IReadOnlyList<PluginEntry> Plugins, NavDataEntry? NavData = null) + { + /// <summary> + /// The release's changes, one line each: the optional "changes" array (written since 2026.10.5; + /// signed with the rest). Empty for older feeds, which only have <see cref="Notes"/>. + /// </summary> + public IReadOnlyList<string> Changes { get; init; } = Array.Empty<string>(); + } /// <summary>One installed copy of a plugin the feed knows.</summary> public sealed record PluginStatus(PluginEntry Entry, string Path, PluginState State); public enum PluginState { UpToDate, NeedsUpdate, LocalBuild } + /// <summary>A plugin split out of one the player has, to be installed beside it (see <see cref="Companions"/>).</summary> + public sealed record CompanionInstall(PluginEntry Entry, string Path, string Reason); + public sealed record CheckResult(Manifest Manifest, int InstalledCoreRelease, IReadOnlyList<PluginStatus> Plugins) { public bool CoreUpdateAvailable => Manifest.Core.Release > InstalledCoreRelease; public IEnumerable<PluginStatus> PluginsToUpdate => Plugins.Where(p => p.State == PluginState.NeedsUpdate); + /// <summary>New plugins that came out of an installed one; installed with the plugin updates.</summary> + public IReadOnlyList<CompanionInstall> Companions { get; init; } = Array.Empty<CompanionInstall>(); + /// <summary>Feed plugins not in the plugin list, for the player to install or not (see <see cref="GetAvailable"/>).</summary> + public IReadOnlyList<AvailablePlugin> Available { get; init; } = Array.Empty<AvailablePlugin>(); + /// <summary>Available plugins this launcher sees in the feed for the first time: said once in the activity log.</summary> + public IReadOnlyList<AvailablePlugin> NewlyAnnounced { get; init; } = Array.Empty<AvailablePlugin>(); + /// <summary>RynthNav's tiles: null when the feed has none or RynthNav isn't in the plugin list.</summary> + public NavDataStatus? NavData { get; init; } + public bool NavDataUpdateAvailable => NavData is { State: NavDataState.NeedsUpdate }; } + /// <summary> + /// Features that moved out of a plugin into their own. When the player has the parent and not the + /// child, the child is installed in a sibling folder and registered, once: a player who removes it + /// afterwards keeps it removed. + /// + /// Only for a split, where the player's scripts stop working without the child. A plugin that is + /// simply new (RynthOracle, RynthInventory: 2026.10.4.3 auto-installed them this way) is offered + /// instead, under Available plugins with a "New" badge (<see cref="RecentlyAdded"/>); players who + /// already got them keep them. + /// </summary> + private static readonly (string ParentFile, string ChildName, string Reason)[] Companions = + { + ("RynthCore.Plugin.RynthAi.dll", "RynthLua", "Lua scripting, which moved out of RynthAi"), + }; + private static readonly HttpClient Http = CreateHttp(); private readonly string _feedUrl; @@ -124,7 +167,71 @@ internal sealed class RynthUpdater statuses.Add(new PluginStatus(entry, path, state)); } - return new CheckResult(manifest, InstalledCoreRelease, statuses); + List<CompanionInstall> companions = FindCompanions(manifest, pluginPaths); + HashSet<string> fresh = RecordSeenPlugins(manifest); // before GetAvailable: it reads the New badges + List<AvailablePlugin> available = GetAvailable(manifest, pluginPaths, companions); + return new CheckResult(manifest, InstalledCoreRelease, statuses) + { + Companions = companions, + NavData = CheckNavData(manifest, pluginPaths), + Available = available, + NewlyAnnounced = available.Where(a => fresh.Contains(a.Entry.Name)).ToList(), + }; + } + + private List<CompanionInstall> FindCompanions(Manifest manifest, IEnumerable<string> pluginPaths) + { + var result = new List<CompanionInstall>(); + List<string> paths = pluginPaths.ToList(); + HashSet<string> offered = ReadOfferedCompanions(); + foreach (var (parentFile, childName, reason) in Companions) + { + if (offered.Contains(childName)) continue; + string? parent = paths.FirstOrDefault(p => + string.Equals(Path.GetFileName(p), parentFile, StringComparison.OrdinalIgnoreCase) && File.Exists(p)); + PluginEntry? child = manifest.Plugins.FirstOrDefault(e => string.Equals(e.Name, childName, StringComparison.OrdinalIgnoreCase)); + if (parent == null || child == null) continue; + if (paths.Any(p => string.Equals(Path.GetFileName(p), child.File, StringComparison.OrdinalIgnoreCase))) + { + MarkCompanionOffered(childName); // already there: nothing to do, ever + continue; + } + // C:\Games\RynthSuite\RynthAi\x.dll -> C:\Games\RynthSuite\RynthLua\<file> + string? suiteDir = Path.GetDirectoryName(Path.GetDirectoryName(parent)); + if (string.IsNullOrEmpty(suiteDir)) continue; + result.Add(new CompanionInstall(child, Path.Combine(suiteDir, childName, child.File), reason)); + } + return result; + } + + /// <summary> + /// Installs <see cref="CheckResult.Companions"/> (verified like every plugin; an existing file at the + /// target is kept) and returns their paths for the caller to register in the plugin list. + /// </summary> + public async Task<List<CompanionInstall>> InstallCompanionsAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default) + { + var done = new List<CompanionInstall>(); + foreach (CompanionInstall c in check.Companions) + { + if (!File.Exists(c.Path)) + { + Directory.CreateDirectory(Path.GetDirectoryName(c.Path)!); + string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll"); + try + { + await DownloadVerifiedAsync(c.Entry.Url, c.Entry.Size, c.Entry.Sha256, MaxPluginBytes, temp, ct, c.Entry.Name, progress); + File.SetLastWriteTimeUtc(temp, check.Manifest.PublishedUtc); + File.Move(temp, c.Path, overwrite: false); + } + finally + { + try { File.Delete(temp); } catch { } + } + } + MarkCompanionOffered(c.Entry.Name); + done.Add(c); + } + return done; } // ── Plugins ─────────────────────────────────────────────────────────────── @@ -133,7 +240,7 @@ internal sealed class RynthUpdater /// Swaps each outdated plugin DLL for the verified release build. The previous file is kept /// beside it as .previous. Running clients keep the version they started with. /// </summary> - public async Task<List<string>> UpdatePluginsAsync(CheckResult check, CancellationToken ct = default) + public async Task<List<string>> UpdatePluginsAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default) { var done = new List<string>(); foreach (var group in check.PluginsToUpdate.GroupBy(p => p.Entry)) @@ -142,7 +249,7 @@ internal sealed class RynthUpdater string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll"); try { - await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct); + await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct, e.Name, progress); foreach (PluginStatus p in group) { string staged = p.Path + ".new"; @@ -165,7 +272,7 @@ internal sealed class RynthUpdater // ── Core ────────────────────────────────────────────────────────────────── /// <summary>Downloads (or reuses) the release installer, verified, and returns its path.</summary> - public async Task<string> DownloadInstallerAsync(CheckResult check, CancellationToken ct = default) + public async Task<string> DownloadInstallerAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default) { InstallerEntry core = check.Manifest.Core; string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @@ -177,7 +284,7 @@ internal sealed class RynthUpdater return path; string temp = path + ".part"; - await DownloadVerifiedAsync(core.Url, core.Size, core.Sha256, MaxInstallerBytes, temp, ct); + await DownloadVerifiedAsync(core.Url, core.Size, core.Sha256, MaxInstallerBytes, temp, ct, $"RynthCore {core.Version}", progress); File.Move(temp, path, overwrite: true); return path; } @@ -238,12 +345,17 @@ internal sealed class RynthUpdater if (file.Length == 0 || file != Path.GetFileName(file) || !file.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException($"bad plugin file name '{file}'"); plugins.Add(new PluginEntry(p.GetProperty("name").GetString() ?? file, file, - CheckUrl(p.GetProperty("url").GetString()), p.GetProperty("size").GetInt64(), p.GetProperty("sha256").GetString() ?? "")); + CheckUrl(p.GetProperty("url").GetString()), p.GetProperty("size").GetInt64(), p.GetProperty("sha256").GetString() ?? "", + ReadDescription(p))); } return new Manifest(r.GetProperty("release").GetInt32(), r.GetProperty("version").GetString() ?? "", r.GetProperty("published").GetDateTime().ToUniversalTime(), - r.TryGetProperty("notes", out JsonElement n) ? n.GetString() ?? "" : "", core, plugins); + r.TryGetProperty("notes", out JsonElement n) ? n.GetString() ?? "" : "", core, plugins, + r.TryGetProperty("navdata", out JsonElement nd) && nd.ValueKind == JsonValueKind.Object ? TryParseNavData(nd) : null) + { + Changes = ReadChanges(r), + }; } private string CheckUrl(string? url) @@ -271,31 +383,49 @@ internal sealed class RynthUpdater return ms.ToArray(); } - private static async Task DownloadVerifiedAsync(string url, long size, string sha256, long max, string dest, CancellationToken ct) + /// <summary> + /// Downloads to <paramref name="dest"/> and checks it against the signed size and SHA-256. On any + /// failure (a wrong hash, a lost connection, Cancel) the partial file is deleted. Progress, when + /// asked for, goes to <paramref name="progress"/> a few times a second (<see cref="DownloadMeter"/>), + /// then one <see cref="DownloadStage.Verified"/> report once the hash matched. + /// </summary> + private static async Task DownloadVerifiedAsync(string url, long size, string sha256, long max, string dest, CancellationToken ct, + string? what = null, IProgress<DownloadProgress>? progress = null) { if (size <= 0 || size > max) throw new InvalidDataException($"{url}: size {size} out of range"); - using var resp = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct); - resp.EnsureSuccessStatusCode(); - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - long total = 0; - await using (var s = await resp.Content.ReadAsStreamAsync(ct)) - await using (var f = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None)) + var meter = new DownloadMeter(what ?? Path.GetFileName(url), size, progress); + try { - byte[] buf = new byte[81920]; - int n; - while ((n = await s.ReadAsync(buf, ct)) > 0) + using var resp = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct); + resp.EnsureSuccessStatusCode(); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + long total = 0; + meter.Report(0); + await using (var s = await resp.Content.ReadAsStreamAsync(ct)) + await using (var f = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None)) { - total += n; - if (total > size) throw new InvalidDataException($"{url} is larger than the signed size"); - hash.AppendData(buf, 0, n); - await f.WriteAsync(buf.AsMemory(0, n), ct); + byte[] buf = new byte[81920]; + int n; + while ((n = await s.ReadAsync(buf, ct)) > 0) + { + ct.ThrowIfCancellationRequested(); + total += n; + if (total > size) throw new InvalidDataException($"{url} is larger than the signed size"); + hash.AppendData(buf, 0, n); + await f.WriteAsync(buf.AsMemory(0, n), ct); + meter.Report(total); + } } + string got = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant(); + if (total != size || !string.Equals(got, sha256, StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException($"{Path.GetFileName(url)} does not match the signed hash — not installed"); + meter.Verified(); } - string got = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant(); - if (total != size || !string.Equals(got, sha256, StringComparison.OrdinalIgnoreCase)) + catch { + // The file stream is closed by now (its using block ended), so the delete can't be refused by it. try { File.Delete(dest); } catch { } - throw new InvalidDataException($"{Path.GetFileName(url)} does not match the signed hash — not installed"); + throw; } } @@ -315,6 +445,35 @@ internal sealed class RynthUpdater // ── State ───────────────────────────────────────────────────────────────── private string StatePath => Path.Combine(_stateDir, "update-state.json"); + private string CompanionsPath => Path.Combine(_stateDir, "update-companions.json"); + + private HashSet<string> ReadOfferedCompanions() + { + var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + try + { + if (!File.Exists(CompanionsPath)) return set; + using var doc = JsonDocument.Parse(File.ReadAllText(CompanionsPath)); + foreach (JsonElement e in doc.RootElement.EnumerateArray()) + if (e.GetString() is { Length: > 0 } s) set.Add(s); + } + catch { } + return set; + } + + private void MarkCompanionOffered(string name) + { + try + { + HashSet<string> set = ReadOfferedCompanions(); + if (!set.Add(name)) return; + Directory.CreateDirectory(_stateDir); + string tmp = CompanionsPath + ".tmp"; + File.WriteAllText(tmp, "[" + string.Join(", ", set.OrderBy(s => s).Select(s => JsonSerializer.Serialize(s))) + "]", Encoding.UTF8); + File.Move(tmp, CompanionsPath, overwrite: true); + } + catch { } + } private int ReadHighestRelease() { diff --git a/src/RynthCore.App.Avalonia/UpdateCardModel.cs b/src/RynthCore.App.Avalonia/UpdateCardModel.cs new file mode 100644 index 0000000..501f764 --- /dev/null +++ b/src/RynthCore.App.Avalonia/UpdateCardModel.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace RynthCore.App.Avalonia; + +/// <summary>What the update card on the launcher's front page is showing.</summary> +public enum UpdateCardKind { NotConfigured, NotChecked, Checking, Error, UpToDate, CoreUpdate, PluginUpdates, Downloading } + +/// <summary>Everything the card needs to know, gathered by the window (no UI types, so tests can build it).</summary> +public sealed record UpdateCardInput +{ + public bool Configured { get; init; } = true; + public bool Checking { get; init; } + /// <summary>The last check's error; null when it worked.</summary> + public string? Error { get; init; } + /// <summary>When the last check succeeded (local time); null before the first.</summary> + public DateTime? LastChecked { get; init; } + /// <summary>True once a check has succeeded this session.</summary> + public bool HasCheck { get; init; } + public string InstalledVersion { get; init; } = ""; + public bool CoreUpdateAvailable { get; init; } + public string AvailableVersion { get; init; } = ""; + public string Notes { get; init; } = ""; + public IReadOnlyList<string> Changes { get; init; } = Array.Empty<string>(); + /// <summary>Plugin updates (and new companions, the RynthNav map) waiting to be installed.</summary> + public IReadOnlyList<string> PendingPluginUpdates { get; init; } = Array.Empty<string>(); + /// <summary>Available plugins with the New badge.</summary> + public IReadOnlyList<string> NewPlugins { get; init; } = Array.Empty<string>(); + /// <summary>Game clients running RynthCore (a RynthCore update waits for them to close).</summary> + public int ClientsRunning { get; init; } + /// <summary>The download in progress, if any.</summary> + public DownloadProgress? Download { get; init; } + public bool CanCancel { get; init; } +} + +/// <summary>The card's text and which buttons show.</summary> +public sealed record UpdateCard( + UpdateCardKind Kind, + string Title, + string Detail, + IReadOnlyList<string> WhatsNew, + bool ShowCheckButton, + string? ActionButton, + bool ShowProgress, + double? ProgressPercent, + bool ShowCancel, + string? NewPluginsLine, + /// <summary>One line for the Plugins tab and the header.</summary> + string Compact); + +/// <summary> +/// The front page's update card as a pure function of <see cref="UpdateCardInput"/>: up to date, +/// RynthCore update (installs once every game client is closed), plugin updates, downloading +/// (bar, MB, speed, time left, step), errors, and a line about new plugins. +/// </summary> +public static class UpdateCardModel +{ + public const int MaxWhatsNew = 4; + public const string UpdateCoreButton = "Update RynthCore"; + public const string UpdatePluginsButton = "Update plugins"; + + public static UpdateCard Build(UpdateCardInput i) + { + string? newLine = i.NewPlugins.Count > 0 + ? $"New plugins available: {string.Join(", ", i.NewPlugins)}. See Available plugins on the Plugins tab." + : null; + string installed = i.InstalledVersion.Length > 0 ? i.InstalledVersion : "unknown"; + + if (!i.Configured) + return new UpdateCard(UpdateCardKind.NotConfigured, "Updates", "Updates aren't set up in this build.", + Array.Empty<string>(), false, null, false, null, false, null, "Updates aren't set up in this build."); + + if (i.Download is { } d) + { + string title = d.Stage switch + { + DownloadStage.Downloading => $"Downloading {d.What}", + DownloadStage.Verified => $"{d.What}: verified", + DownloadStage.Unpacking => $"Unpacking {d.What}", + _ => $"Installing {d.What}", + }; + // Installing is the last step (files moving into place): it always runs to the end. + bool cancel = i.CanCancel && d.Stage != DownloadStage.Installing; + return new UpdateCard(UpdateCardKind.Downloading, title, d.Detail, Array.Empty<string>(), false, null, + true, d.Percent, cancel, newLine, $"{title}: {d.Detail}"); + } + + if (i.Checking) + return new UpdateCard(UpdateCardKind.Checking, "Checking for updates…", $"RynthCore {installed}", + Array.Empty<string>(), false, null, false, null, false, newLine, "Checking for updates…"); + + if (i.Error != null) + { + string when = i.LastChecked is { } t ? $" Last good check: {FormatWhen(t)}." : ""; + return new UpdateCard(UpdateCardKind.Error, "Couldn't check for updates", i.Error.TrimEnd('.', ' ') + "." + when, + Array.Empty<string>(), true, null, false, null, false, newLine, $"Update check failed: {i.Error}"); + } + + if (!i.HasCheck) + return new UpdateCard(UpdateCardKind.NotChecked, $"RynthCore {installed}", "Not checked for updates yet.", + Array.Empty<string>(), true, null, false, null, false, newLine, "Not checked yet."); + + string checkedLine = i.LastChecked is { } lc ? $"Last checked {FormatWhen(lc)}." : ""; + IReadOnlyList<string> whatsNew = WhatsNew(i.Changes, i.Notes); + + if (i.CoreUpdateAvailable) + { + var detail = new List<string> { $"You have {installed}. The update installs once every game client is closed." }; + if (i.ClientsRunning > 0) + detail.Add($"Close your {i.ClientsRunning} game client{(i.ClientsRunning == 1 ? "" : "s")} running RynthCore first."); + if (i.PendingPluginUpdates.Count > 0) + detail.Add($"Plugin updates ready too: {string.Join(", ", i.PendingPluginUpdates)}."); + if (checkedLine.Length > 0) detail.Add(checkedLine); + return new UpdateCard(UpdateCardKind.CoreUpdate, $"RynthCore {i.AvailableVersion} is available", string.Join(" ", detail), + whatsNew, true, UpdateCoreButton, false, null, false, newLine, $"Update available: RynthCore {i.AvailableVersion}"); + } + + if (i.PendingPluginUpdates.Count > 0) + { + string detail = $"{string.Join(", ", i.PendingPluginUpdates)}. Running bots keep their version until AC restarts."; + if (checkedLine.Length > 0) detail += " " + checkedLine; + return new UpdateCard(UpdateCardKind.PluginUpdates, "Plugin updates ready", detail, + whatsNew, true, UpdatePluginsButton, false, null, false, newLine, $"Plugin updates ready: {string.Join(", ", i.PendingPluginUpdates)}"); + } + + return new UpdateCard(UpdateCardKind.UpToDate, $"RynthCore {installed} - up to date", checkedLine, + Array.Empty<string>(), true, null, false, null, false, newLine, $"RynthCore {installed} - up to date."); + } + + /// <summary>A few of the release's changes; the notes when the feed has no list (feeds before 2026.10.5).</summary> + public static IReadOnlyList<string> WhatsNew(IReadOnlyList<string> changes, string notes) + { + if (changes.Count > 0) + { + var list = changes.Take(MaxWhatsNew).ToList(); + if (changes.Count > MaxWhatsNew) list.Add($"…and {changes.Count - MaxWhatsNew} more."); + return list; + } + if (string.IsNullOrWhiteSpace(notes)) return Array.Empty<string>(); + string n = notes.Trim(); + return new[] { n.Length > 300 ? n[..299].TrimEnd() + "…" : n }; + } + + /// <summary>"at 14:05" today, else "Oct 3 at 14:05".</summary> + public static string FormatWhen(DateTime local, DateTime? now = null) + { + DateTime today = (now ?? DateTime.Now).Date; + string time = local.ToString("HH:mm", CultureInfo.InvariantCulture); + return local.Date == today ? $"at {time}" : $"{local.ToString("MMM d", CultureInfo.InvariantCulture)} at {time}"; + } +} diff --git a/src/RynthCore.App.Avalonia/UsageStats.cs b/src/RynthCore.App.Avalonia/UsageStats.cs new file mode 100644 index 0000000..44f9617 --- /dev/null +++ b/src/RynthCore.App.Avalonia/UsageStats.cs @@ -0,0 +1,292 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace RynthCore.App.Avalonia; + +/// <summary> +/// Opt-in, anonymous usage statistics ("Help improve RynthCore"). OFF unless the player turns it on. +/// +/// When on, at most one small report a day goes to aelrynth.com (never to a game server), sent +/// after a successful update check. The report holds exactly: +/// - a random install ID (a GUID made when the player opts in, stored only in usage-stats.json, +/// tied to nothing else); +/// - the RynthCore version; +/// - the enabled plugins the update feed ships (RynthSuite), with their versions; other plugins +/// only as a count, never by name (a private plugin's name could identify its author); +/// - how many crash_*.dmp files the engine wrote since the last report (a count only); +/// - the Windows major version ("10" or "11"). +/// Never: character, account or server names, file paths, or anything else identifying. +/// +/// Turning it off deletes usage-stats.json (and with it the install ID) and cancels a report in +/// flight. Every failure is silent, and nothing here ever delays or fails the update check. +/// </summary> +internal sealed class UsageStats +{ + public const string DefaultEndpoint = "https://aelrynth.com/rynth/ping"; + + /// <summary>Where the engine writes crash/hang minidumps (RynthCore.Engine CrashDump / LogPaths).</summary> + public const string DefaultDumpDirectory = @"C:\Games\RynthCore\Logs\dumps"; + + public const int Schema = 1; + private const int MaxCrashes = 1000; + private const int MaxPlugins = 32; + + public sealed record PluginInfo(string Name, string Version); + + private static readonly HttpClient Http = CreateHttp(); + private static readonly Regex ReleaseVersion = new(@"^\d{4}\.\d{1,2}\.\d{1,2}(\.\d{1,4})?$", RegexOptions.CultureInvariant); + private static readonly Regex SafeName = new(@"^[A-Za-z0-9 ._-]{1,40}$", RegexOptions.CultureInvariant); + + private readonly string _endpoint; + private readonly string _stateDir; + private readonly string _dumpDir; + private CancellationTokenSource _cts = new(); + private int _sending; + + public UsageStats(string endpoint = DefaultEndpoint, string? stateDir = null, string dumpDir = DefaultDumpDirectory) + { + _endpoint = endpoint; + _stateDir = stateDir ?? Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore"); + _dumpDir = dumpDir; + } + + public string StatePath => Path.Combine(_stateDir, "usage-stats.json"); + + // ── Opt in / out ────────────────────────────────────────────────────────── + + /// <summary>Called when the player turns statistics on: makes the install ID if there is none.</summary> + public void OptIn(DateTime utcNow) + { + if (ReadState() != null) return; + // Crashes count from the moment of opting in, never from before. + WriteState(new State(Guid.NewGuid().ToString("D"), "", utcNow)); + } + + /// <summary>Called when the player turns statistics off: cancels a report in flight and deletes the ID.</summary> + public void OptOut() + { + try { _cts.Cancel(); } catch { } + _cts = new CancellationTokenSource(); + try { File.Delete(StatePath); } catch { } + try { File.Delete(StatePath + ".tmp"); } catch { } + } + + /// <summary>The install ID, or null when the player hasn't opted in (or it was deleted).</summary> + public string? InstallId => ReadState()?.InstallId; + + // ── Report ──────────────────────────────────────────────────────────────── + + /// <summary> + /// Sends today's report if one hasn't gone out yet (UTC day). <paramref name="stillEnabled"/> is + /// asked again right before sending, so turning it off mid-way stops it. Returns true only + /// when a report was accepted. Never throws. + /// </summary> + public async Task<bool> MaybeSendAsync(Func<bool> stillEnabled, string coreVersion, + IReadOnlyList<PluginInfo> plugins, int otherPlugins, DateTime utcNow) + { + if (Interlocked.Exchange(ref _sending, 1) == 1) return false; + try + { + if (!stillEnabled()) return false; + State? state = ReadState(); + if (state == null) + { + OptIn(utcNow); // enabled but the file is gone (deleted by hand): start a new ID + state = ReadState(); + if (state == null) return false; + } + string today = utcNow.ToString("yyyy-MM-dd"); + if (state.LastPingDay == today) return false; + + int crashes = CountCrashDumps(_dumpDir, state.CrashesSinceUtc, utcNow); + string json = BuildPayload(state.InstallId, coreVersion, plugins, otherPlugins, crashes, WindowsMajor()); + + CancellationToken ct = _cts.Token; + if (!stillEnabled() || ct.IsCancellationRequested) return false; + using var content = new StringContent(json, Encoding.UTF8, "application/json"); + using var resp = await Http.PostAsync(_endpoint, content, ct).ConfigureAwait(false); + if (!resp.IsSuccessStatusCode) return false; + + // Opted out while the request was out: the file is gone, keep it gone. + if (!stillEnabled() || ct.IsCancellationRequested || ReadState()?.InstallId != state.InstallId) return true; + WriteState(state with { LastPingDay = today, CrashesSinceUtc = utcNow }); + return true; + } + catch + { + return false; + } + finally + { + Interlocked.Exchange(ref _sending, 0); + } + } + + /// <summary>The report that would go out now (for "Show what is sent"); nothing is sent or saved.</summary> + public string Preview(string coreVersion, IReadOnlyList<PluginInfo> plugins, int otherPlugins, DateTime utcNow) + { + State? state = ReadState(); + string id = state?.InstallId ?? "(a random ID, made when you turn this on)"; + int crashes = state == null ? 0 : CountCrashDumps(_dumpDir, state.CrashesSinceUtc, utcNow); + return BuildPayload(id, coreVersion, plugins, otherPlugins, crashes, WindowsMajor()); + } + + /// <summary>The report body, exactly as sent. Public for the launcher's "Show what is sent" and the tests.</summary> + public static string BuildPayload(string installId, string coreVersion, IReadOnlyList<PluginInfo> plugins, + int otherPlugins, int crashes, string windows) + { + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true })) + { + w.WriteStartObject(); + w.WriteNumber("schema", Schema); + w.WriteString("install", installId); + w.WriteString("version", ShortVersion(coreVersion)); + w.WriteString("windows", windows); + w.WriteNumber("crashes", Math.Clamp(crashes, 0, MaxCrashes)); + w.WriteStartArray("plugins"); + foreach (PluginInfo p in plugins + .Where(p => SafeName.IsMatch(p.Name)) + .GroupBy(p => p.Name, StringComparer.OrdinalIgnoreCase).Select(g => g.First()) + .OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase) + .Take(MaxPlugins)) + { + w.WriteStartObject(); + w.WriteString("name", p.Name); + w.WriteString("version", ShortVersion(p.Version)); + w.WriteEndObject(); + } + w.WriteEndArray(); + w.WriteNumber("otherPlugins", Math.Clamp(otherPlugins, 0, 100)); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(ms.ToArray()); + } + + /// <summary> + /// The enabled plugins to report: those whose file name the update feed ships (by the feed's name + /// for them, with the DLL's own version), and a count of every other enabled plugin. + /// </summary> + public static (List<PluginInfo> Known, int Other) DescribePlugins(IEnumerable<string> enabledPaths, + IReadOnlyDictionary<string, string> feedNameByFile) + { + var known = new List<PluginInfo>(); + int other = 0; + foreach (string path in enabledPaths.Distinct(StringComparer.OrdinalIgnoreCase)) + { + string file = Path.GetFileName(path); + if (feedNameByFile.TryGetValue(file, out string? name) && File.Exists(path)) + { + string version; + try { version = FileVersionInfo.GetVersionInfo(path).ProductVersion ?? ""; } + catch { version = ""; } + known.Add(new PluginInfo(name, version)); + } + else + { + other++; + } + } + return (known, other); + } + + /// <summary>"2026.10.2.1" for a release build, "dev" for an unversioned build, else "unknown". Drops the commit.</summary> + public static string ShortVersion(string? productVersion) + { + string v = (productVersion ?? "").Trim(); + int plus = v.IndexOf('+'); + if (plus >= 0) v = v[..plus]; + int space = v.IndexOf(' '); + if (space >= 0) v = v[..space]; + if (v is "1.0.0" or "1.0.0.0" or "dev") return "dev"; + return ReleaseVersion.IsMatch(v) ? v : "unknown"; + } + + /// <summary>"11" (build 22000 and up), "10", or "other".</summary> + public static string WindowsMajor() + { + Version os = Environment.OSVersion.Version; + if (!OperatingSystem.IsWindows()) return "other"; + if (os.Major == 10) return os.Build >= 22000 ? "11" : "10"; + return "other"; + } + + /// <summary>crash_*.dmp files written after <paramref name="sinceUtc"/> (hang dumps are not crashes).</summary> + public static int CountCrashDumps(string dir, DateTime sinceUtc, DateTime utcNow) + { + try + { + if (!Directory.Exists(dir)) return 0; + int n = 0; + foreach (string f in Directory.EnumerateFiles(dir, "crash_*.dmp")) + { + DateTime t = File.GetLastWriteTimeUtc(f); + if (t > sinceUtc && t <= utcNow.AddMinutes(5)) n++; + if (n >= MaxCrashes) break; + } + return n; + } + catch { return 0; } + } + + // ── State file ──────────────────────────────────────────────────────────── + + private sealed record State(string InstallId, string LastPingDay, DateTime CrashesSinceUtc); + + private State? ReadState() + { + try + { + if (!File.Exists(StatePath)) return null; + using var doc = JsonDocument.Parse(File.ReadAllText(StatePath)); + JsonElement r = doc.RootElement; + string id = r.GetProperty("installId").GetString() ?? ""; + if (!Guid.TryParseExact(id, "D", out _)) return null; + string last = r.TryGetProperty("lastPingDay", out JsonElement l) ? l.GetString() ?? "" : ""; + DateTime since = r.TryGetProperty("crashesSinceUtc", out JsonElement s) && s.TryGetDateTime(out DateTime d) + ? d.ToUniversalTime() : DateTime.UtcNow; + return new State(id, last, since); + } + catch { return null; } + } + + private void WriteState(State s) + { + try + { + Directory.CreateDirectory(_stateDir); + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true })) + { + w.WriteStartObject(); + w.WriteString("about", "RynthCore usage statistics (opt-in). Deleted when you turn them off."); + w.WriteString("installId", s.InstallId); + w.WriteString("lastPingDay", s.LastPingDay); + w.WriteString("crashesSinceUtc", DateTime.SpecifyKind(s.CrashesSinceUtc, DateTimeKind.Utc)); + w.WriteEndObject(); + } + string tmp = StatePath + ".tmp"; + File.WriteAllBytes(tmp, ms.ToArray()); + File.Move(tmp, StatePath, overwrite: true); + } + catch { } + } + + private static HttpClient CreateHttp() + { + // Short: a slow stats server must never hold anything up (and nothing awaits this anyway). + var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; + http.DefaultRequestHeaders.UserAgent.ParseAdd("RynthCore-Launcher"); + return http; + } +} diff --git a/src/RynthCore.App.Avalonia/UsageStatsDialog.cs b/src/RynthCore.App.Avalonia/UsageStatsDialog.cs new file mode 100644 index 0000000..081fa6d --- /dev/null +++ b/src/RynthCore.App.Avalonia/UsageStatsDialog.cs @@ -0,0 +1,121 @@ +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; + +namespace RynthCore.App.Avalonia; + +/// <summary> +/// The one-time "Help improve RynthCore?" question and the "Show what is sent" window. +/// Plain words; "No thanks" is the safe answer (Escape and closing the window both mean no). +/// </summary> +internal static class UsageStatsDialog +{ + private static readonly IBrush Back = new SolidColorBrush(Color.Parse("#132028")); + private static readonly IBrush Text = new SolidColorBrush(Color.Parse("#EAF0F4")); + private static readonly IBrush Muted = new SolidColorBrush(Color.Parse("#9AA8B3")); + private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#26C1A6")); + + public const string WhatIsSent = + "Sent once a day, only if you turn it on: a random ID made just for this, the RynthCore version, " + + "which RynthSuite plugins you have enabled and their versions (other plugins only as a number), " + + "how many times RynthCore crashed since the last report (a number), and whether you run Windows 10 or 11."; + + public const string NeverSent = + "Never sent: character, account or server names, file paths, or anything else about you or your game. " + + "It goes to aelrynth.com only, never to a game server."; + + public const string HowToStop = + "Turning it off stops the reports at once and deletes the random ID from this PC."; + + /// <summary>True when the player chose to turn statistics on.</summary> + public static async Task<bool> AskAsync(Window owner) + { + var dialog = NewWindow("Help improve RynthCore?", 560); + var on = new Button { Content = "Turn it on" }; + var off = new Button { Content = "No thanks", IsCancel = true }; + on.Click += (_, _) => dialog.Close(true); + off.Click += (_, _) => dialog.Close(false); + dialog.Content = Layout("Help improve RynthCore?", + new StackPanel + { + Spacing = 10, + Children = + { + Para("RynthCore can send a small anonymous report once a day, so we can see how many people use it, " + + "which versions and plugins are in use, and whether a new release crashes more than the last one.", Text), + Para(WhatIsSent, Muted), + Para(NeverSent, Muted), + Para("It stays off unless you turn it on. You can change your mind any time on the Plugins tab, " + + "under Usage statistics. " + HowToStop, Muted), + }, + }, + on, off); + bool? result = await dialog.ShowDialog<bool?>(owner); + return result == true; + } + + /// <summary>Shows the report exactly as it would be sent now.</summary> + public static async Task ShowPayloadAsync(Window owner, string json, bool enabled) + { + var dialog = NewWindow("Usage statistics: what is sent", 620); + var body = new TextBox + { + Text = json, + IsReadOnly = true, + TextWrapping = TextWrapping.Wrap, + FontFamily = new FontFamily("Consolas, Cascadia Mono, monospace"), + FontSize = 12, + MaxHeight = 380, + Foreground = Text, + Background = new SolidColorBrush(Color.Parse("#0F161D")), + }; + var close = new Button { Content = "Close", IsCancel = true, IsDefault = true }; + close.Click += (_, _) => dialog.Close(null); + dialog.Content = Layout("Usage statistics: what is sent", + new StackPanel + { + Spacing = 8, + Children = + { + Para(enabled + ? "This is today's report, exactly as it goes to aelrynth.com (at most once a day)." + : "Statistics are off, so nothing is sent. If you turned them on, this is what would go out.", Muted), + body, + }, + }, + close); + await dialog.ShowDialog<object?>(owner); + } + + private static TextBlock Para(string text, IBrush brush) => + new() { Text = text, TextWrapping = TextWrapping.Wrap, Foreground = brush }; + + private static Window NewWindow(string title, double width) => new() + { + Title = title, + Width = width, + SizeToContent = SizeToContent.Height, + CanResize = false, + WindowStartupLocation = WindowStartupLocation.CenterOwner, + Background = Back, + }; + + private static Control Layout(string title, Control body, params Control[] buttons) + { + var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right }; + foreach (Control b in buttons) row.Children.Add(b); + return new StackPanel + { + Margin = new Thickness(18), + Spacing = 12, + Children = + { + new TextBlock { Text = title, FontSize = 16, FontWeight = FontWeight.SemiBold, Foreground = Accent }, + body, + row, + }, + }; + } +} diff --git a/src/RynthCore.App/AcLaunchArgumentBuilder.cs b/src/RynthCore.App/AcLaunchArgumentBuilder.cs index 7508979..871a2e8 100644 --- a/src/RynthCore.App/AcLaunchArgumentBuilder.cs +++ b/src/RynthCore.App/AcLaunchArgumentBuilder.cs @@ -6,6 +6,14 @@ namespace RynthCore.App; internal sealed class AcLaunchArgumentBuilder { + /// <summary>Text shown in place of the password in previews.</summary> + public const string PasswordMask = "********"; + + /// <summary> + /// The client's command line, with the saved password decrypted now. The result carries the + /// password: hand it to the process and never log, display or keep it. Throws when the saved + /// password can't be decrypted on this Windows user (never launches with an empty one instead). + /// </summary> public string BuildArguments(LaunchServerProfile server, LaunchAccountProfile account) { ArgumentNullException.ThrowIfNull(server); @@ -13,17 +21,42 @@ internal sealed class AcLaunchArgumentBuilder Validate(server, account); + if (!account.TryGetPasswordForLaunch(out string password, out string problem)) + throw new InvalidOperationException(problem); + + return Build(server, account, password); + } + + /// <summary> + /// The same command line for display: the password is never decrypted, a saved one shows as + /// <see cref="PasswordMask"/>. + /// </summary> + public string BuildMaskedArguments(LaunchServerProfile server, LaunchAccountProfile account) + { + ArgumentNullException.ThrowIfNull(server); + ArgumentNullException.ThrowIfNull(account); + + Validate(server, account); + + if (account.PasswordNeedsReentry) + return LaunchAccountProfile.PasswordNeedsReentryMessage(account.AccountName); + + return Build(server, account, account.HasSavedPassword ? PasswordMask : string.Empty); + } + + private static string Build(LaunchServerProfile server, LaunchAccountProfile account, string password) + { return server.Emulator switch { AcEmulatorKind.Ace => string.Join(" ", "-a", Quote(account.AccountName), - "-v", Quote(account.Password), + "-v", Quote(password), "-h", Quote(server.ConnectionString), "-rodat", server.RodatEnabled ? "on" : "off"), AcEmulatorKind.Gdle => string.Join(" ", "-h", Quote(server.Host), "-p", server.Port.ToString(CultureInfo.InvariantCulture), - "-a", Quote($"{account.AccountName}:{account.Password}"), + "-a", Quote($"{account.AccountName}:{password}"), "-rodat", server.RodatEnabled ? "on" : "off"), _ => throw new InvalidOperationException($"Unsupported emulator type '{server.Emulator}'.") }; diff --git a/src/RynthCore.App/AccountPasswordProtection.cs b/src/RynthCore.App/AccountPasswordProtection.cs new file mode 100644 index 0000000..e99b14f --- /dev/null +++ b/src/RynthCore.App/AccountPasswordProtection.cs @@ -0,0 +1,138 @@ +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; + +namespace RynthCore.App; + +/// <summary> +/// Saved account passwords are encrypted with Windows DPAPI (CryptProtectData, CurrentUser +/// scope, the same call System.Security.Cryptography.ProtectedData makes) plus an app-specific +/// entropy constant, and kept in settings as base64 (LaunchAccountProfile.PasswordProtected). +/// Only the Windows user that saved a password can decrypt it; settings copied to another user +/// or PC can't be decrypted, and such an account shows "password needs re-entering". +/// +/// Decrypt only at the moment of use (building the client's launch arguments) and never keep +/// the result in a long-lived object. Never log, display or copy a password. +/// +/// Shared source: compiled into the launcher, RynthCore.Injector (--launch) and +/// tools\LauncherSettingsTests. +/// </summary> +internal static class AccountPasswordProtection +{ + // Changing this makes every saved password unreadable. Bump the suffix only with a migration. + private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("RynthCore.Launcher.AccountPassword.v1"); + + private const int CryptProtectUiForbidden = 0x1; + + /// <summary>Encrypts a password for this Windows user. Empty in, empty out.</summary> + public static string Protect(string? plainText) + { + if (string.IsNullOrEmpty(plainText)) + return string.Empty; + + byte[] plain = Encoding.UTF8.GetBytes(plainText); + try + { + return Convert.ToBase64String(Transform(plain, protect: true)); + } + finally + { + Array.Clear(plain); + } + } + + /// <summary> + /// Decrypts a value written by <see cref="Protect"/>. False when it can't be read on this + /// Windows user (copied from another user or PC, damaged base64, wrong entropy). + /// </summary> + public static bool TryUnprotect(string? protectedBase64, out string plainText) + { + plainText = string.Empty; + if (string.IsNullOrEmpty(protectedBase64)) + return false; + + byte[] blob; + try + { + blob = Convert.FromBase64String(protectedBase64); + } + catch (FormatException) + { + return false; + } + + byte[]? plain = null; + try + { + plain = Transform(blob, protect: false); + plainText = Encoding.UTF8.GetString(plain); + return true; + } + catch (Exception ex) when (ex is Win32Exception or PlatformNotSupportedException or EntryPointNotFoundException or DllNotFoundException) + { + return false; + } + finally + { + if (plain != null) + Array.Clear(plain); + } + } + + /// <summary>True when the value decrypts on this Windows user (the password itself is discarded).</summary> + public static bool CanUnprotect(string? protectedBase64) => TryUnprotect(protectedBase64, out _); + + private static byte[] Transform(byte[] input, bool protect) + { + GCHandle inputHandle = GCHandle.Alloc(input, GCHandleType.Pinned); + GCHandle entropyHandle = GCHandle.Alloc(Entropy, GCHandleType.Pinned); + var output = new DataBlob(); + try + { + var inputBlob = new DataBlob { cbData = input.Length, pbData = inputHandle.AddrOfPinnedObject() }; + var entropyBlob = new DataBlob { cbData = Entropy.Length, pbData = entropyHandle.AddrOfPinnedObject() }; + + bool ok = protect + ? CryptProtectData(ref inputBlob, null, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output) + : CryptUnprotectData(ref inputBlob, IntPtr.Zero, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output); + if (!ok) + throw new Win32Exception(Marshal.GetLastWin32Error()); + + byte[] result = new byte[output.cbData]; + if (output.cbData > 0) + Marshal.Copy(output.pbData, result, 0, output.cbData); + return result; + } + finally + { + if (output.pbData != IntPtr.Zero) + { + // Wipe the native copy (the plain text, when decrypting) before freeing it. + for (int i = 0; i < output.cbData; i++) + Marshal.WriteByte(output.pbData, i, 0); + LocalFree(output.pbData); + } + inputHandle.Free(); + entropyHandle.Free(); + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct DataBlob + { + public int cbData; + public IntPtr pbData; + } + + [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern bool CryptProtectData(ref DataBlob pDataIn, string? szDataDescr, ref DataBlob pOptionalEntropy, + IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut); + + [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern bool CryptUnprotectData(ref DataBlob pDataIn, IntPtr ppszDataDescr, ref DataBlob pOptionalEntropy, + IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut); + + [DllImport("kernel32.dll")] + private static extern IntPtr LocalFree(IntPtr hMem); +} diff --git a/src/RynthCore.App/AppSettings.cs b/src/RynthCore.App/AppSettings.cs index 4231655..0da12e9 100644 --- a/src/RynthCore.App/AppSettings.cs +++ b/src/RynthCore.App/AppSettings.cs @@ -29,6 +29,13 @@ internal sealed class AppSettings /// with; the new one loads on the next AC start. Core updates always ask first. public bool AutoUpdatePlugins { get; set; } = true; + /// "Help improve RynthCore": one anonymous usage report a day (see the launcher's + /// UsageStats.cs for exactly what is sent). OFF unless the player turns it on. + public bool UsageStatsEnabled { get; set; } + + /// True once the launcher has explained usage statistics and asked (shown once). + public bool UsageStatsAsked { get; set; } + /// When true, the launcher kills any RynthCore-mode acclient.exe it /// launched that hasn't reached IsLoggedIn within /// <see cref="StuckClientTimeoutSeconds"/>. Catches stuck char-select, diff --git a/src/RynthCore.App/AppSettingsStore.cs b/src/RynthCore.App/AppSettingsStore.cs index c3b4826..c9c48f8 100644 --- a/src/RynthCore.App/AppSettingsStore.cs +++ b/src/RynthCore.App/AppSettingsStore.cs @@ -1,5 +1,7 @@ using System; +using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; @@ -12,15 +14,22 @@ internal static class AppSettingsStore WriteIndented = true, Converters = { + // Before the general enum converter: InjectionMode is written so that every + // launcher can read it ("Decal + RynthCore" lives in decal-accounts.json). + new SharedInjectionModeConverter(), new JsonStringEnumConverter() } }; - private static string SettingsDirectory => + /// <summary>Tests only (tools\LauncherSettingsTests): a folder used instead of %APPDATA%\RynthCore.</summary> + internal static string? DirectoryOverride { get; set; } + + private static string SettingsDirectory => DirectoryOverride ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore"); private static string SettingsPath => Path.Combine(SettingsDirectory, "appsettings.json"); private static string BackupPath => SettingsPath + ".bak"; + private static string DecalAccountsPath => DecalAccountModes.PathIn(SettingsDirectory); /// <summary> /// Set when the last Load() hit a corrupt/unreadable file (quarantined it, @@ -30,10 +39,123 @@ internal static class AppSettingsStore /// </summary> public static string? LastLoadDiagnostic { get; private set; } + /// <summary> + /// Set when the last Load() moved "Decal + RynthCore" accounts out of appsettings.json + /// into decal-accounts.json (a file written by a pre-release Decal bridge build), or found + /// decal-accounts.json unreadable. Null otherwise. + /// </summary> + public static string? LastMigrationNote { get; private set; } + + /// <summary> + /// Set when the last Load() encrypted plain-text account passwords from an older settings + /// file ("migrated N account password(s) to encrypted storage"), or could not. Never holds a + /// password. Null otherwise. + /// </summary> + public static string? LastPasswordMigrationNote { get; private set; } + + /// <summary> + /// Set when the last Load() found saved passwords this Windows user can't decrypt (settings + /// copied from another user or PC); those accounts have PasswordNeedsReentry set. Null otherwise. + /// </summary> + public static string? LastPasswordProblemNote { get; private set; } + public static AppSettings Load() { LastLoadDiagnostic = null; + LastMigrationNote = null; + LastPasswordMigrationNote = null; + LastPasswordProblemNote = null; + // Passwords after the Decal accounts: a save before ApplyDecalAccounts would drop + // decal-accounts.json (every account still reads as RynthCore at that point). + AppSettings settings = ApplyDecalAccounts(LoadShared()); + MigratePasswords(settings); + return settings; + } + /// <summary> + /// Encrypts plain-text passwords from an older appsettings.json (LaunchAccountProfile + /// "Password") into PasswordProtected and saves once, .bak included, so the plain text is + /// gone from both files. Also marks accounts whose encrypted password this Windows user can't + /// decrypt. Never logs or reports a password. + /// </summary> + private static void MigratePasswords(AppSettings settings) + { + int migrated = 0, cleared = 0, failed = 0; + var unreadable = new List<string>(); + foreach (LaunchAccountProfile account in settings.AccountProfiles ?? new List<LaunchAccountProfile>()) + { + if (account.LegacyPlainPassword != null) + { + if (account.LegacyPlainPassword.Length == 0) + { + account.LegacyPlainPassword = null; + cleared++; + continue; + } + try + { + account.PasswordProtected = AccountPasswordProtection.Protect(account.LegacyPlainPassword); + account.LegacyPlainPassword = null; + account.PasswordNeedsReentry = false; + migrated++; + } + catch + { + failed++; // kept as it was (still usable); the next load tries again + } + continue; + } + + if (!string.IsNullOrEmpty(account.PasswordProtected) && + !AccountPasswordProtection.CanUnprotect(account.PasswordProtected)) + { + account.PasswordNeedsReentry = true; + unreadable.Add(string.IsNullOrWhiteSpace(account.AccountName) ? account.Id : account.AccountName); + } + } + + if (unreadable.Count > 0) + { + LastPasswordProblemNote = $"{unreadable.Count} saved account password(s) can't be decrypted on this Windows user " + + $"(settings copied from another user or PC?) and need re-entering: {string.Join(", ", unreadable)}."; + } + + if (migrated + cleared == 0) + { + if (failed > 0) + LastPasswordMigrationNote = $"Could not encrypt {failed} account password(s); they stay as they were and the next start tries again."; + return; + } + + try + { + Save(settings); + // Save() moved the old file (plain text) to .bak: replace it with the encrypted one. + File.Copy(SettingsPath, BackupPath, overwrite: true); + if (migrated == 0 && failed == 0) + return; // only empty plain-text fields removed + LastPasswordMigrationNote = $"migrated {migrated} account password(s) to encrypted storage"; + if (failed > 0) + LastPasswordMigrationNote += $"; {failed} could not be encrypted and stay as they were"; + int quarantined = CountQuarantinedFiles(); + if (quarantined > 0) + LastPasswordMigrationNote += $". {quarantined} older appsettings.json.corrupt-* file(s) in {SettingsDirectory} " + + "may still hold plain-text passwords; delete them when no longer needed"; + } + catch (Exception ex) + { + LastPasswordMigrationNote = $"Could not save the encrypted account passwords ({ex.GetType().Name}); the next save retries."; + } + } + + private static int CountQuarantinedFiles() + { + try { return Directory.GetFiles(SettingsDirectory, "appsettings.json.corrupt-*").Length; } + catch { return 0; } + } + + private static AppSettings LoadShared() + { if (!File.Exists(SettingsPath)) return new AppSettings(); @@ -85,13 +207,56 @@ internal static class AppSettingsStore } } + /// <summary> + /// Puts back the "Decal + RynthCore" accounts listed in decal-accounts.json (those that + /// appsettings.json still lists as RynthCore). An appsettings.json that itself says + /// "DecalBridge" (written by a pre-release bridge build) is rewritten at once, .bak + /// included, so no launcher finds that value there again. + /// </summary> + private static AppSettings ApplyDecalAccounts(AppSettings settings) + { + List<LaunchAccountProfile> accounts = settings.AccountProfiles ?? new List<LaunchAccountProfile>(); + int legacy = accounts.Count(a => a.InjectionMode == InjectionMode.DecalBridge); + + HashSet<string> ids = DecalAccountModes.ReadIds(DecalAccountsPath, out string? error); + if (error != null) + LastMigrationNote = error; + foreach (LaunchAccountProfile account in accounts) + if (DecalAccountModes.IsDecalBridge(ids, account.Id, account.InjectionMode)) + account.InjectionMode = InjectionMode.DecalBridge; + + if (legacy > 0) + { + try + { + Save(settings); + File.Copy(SettingsPath, BackupPath, overwrite: true); + LastMigrationNote = $"Moved {legacy} \"Decal + RynthCore\" account(s) from appsettings.json to " + + $"{DecalAccountModes.FileName}, so older launchers can still read appsettings.json."; + } + catch (Exception ex) + { + LastMigrationNote = $"Could not move \"Decal + RynthCore\" accounts to {DecalAccountModes.FileName} " + + $"({ex.GetType().Name}: {ex.Message}); the next save retries."; + } + } + return settings; + } + public static void Save(AppSettings settings) { + // "Decal + RynthCore" accounts go to decal-accounts.json first; appsettings.json + // lists them as RynthCore (SharedInjectionModeConverter). + Directory.CreateDirectory(SettingsDirectory); + DecalAccountModes.WriteIds(DecalAccountsPath, + (settings.AccountProfiles ?? new List<LaunchAccountProfile>()) + .Where(a => a.InjectionMode == InjectionMode.DecalBridge) + .Select(a => a.Id)); + // Atomic write: serialize to a temp file, then swap it in. A crash or // power cut mid-write can no longer truncate the live file (which holds // every server/account profile and is rewritten constantly); the swap // also maintains a .bak Load() can recover from. - Directory.CreateDirectory(SettingsDirectory); string tmp = SettingsPath + ".tmp"; File.WriteAllText(tmp, JsonSerializer.Serialize(settings, JsonOptions)); if (File.Exists(SettingsPath)) @@ -99,4 +264,32 @@ internal static class AppSettingsStore else File.Move(tmp, SettingsPath); } + + /// <summary> + /// InjectionMode in appsettings.json. Writes only names every launcher knows: DecalBridge is + /// written as <see cref="DecalAccountModes.SharedMode"/> (decal-accounts.json holds the real + /// choice). Reads names and numbers; a name or number this build doesn't know reads as RynthCore + /// instead of making the whole file unreadable. + /// </summary> + private sealed class SharedInjectionModeConverter : JsonConverter<InjectionMode> + { + public override InjectionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt32(out int number)) + return Enum.IsDefined((InjectionMode)number) ? (InjectionMode)number : InjectionMode.RynthCore; + if (reader.TokenType == JsonTokenType.String) + { + return Enum.TryParse(reader.GetString(), ignoreCase: true, out InjectionMode mode) && Enum.IsDefined(mode) + ? mode + : InjectionMode.RynthCore; + } + throw new JsonException($"InjectionMode: unexpected {reader.TokenType}."); + } + + public override void Write(Utf8JsonWriter writer, InjectionMode value, JsonSerializerOptions options) + { + InjectionMode shared = value == InjectionMode.DecalBridge ? DecalAccountModes.SharedMode : value; + writer.WriteStringValue(shared.ToString()); + } + } } diff --git a/src/RynthCore.App/CharacterCacheStore.cs b/src/RynthCore.App/CharacterCacheStore.cs index 0e27deb..5bafb11 100644 --- a/src/RynthCore.App/CharacterCacheStore.cs +++ b/src/RynthCore.App/CharacterCacheStore.cs @@ -46,6 +46,13 @@ internal static class CharacterCacheStore List<string> serverCharacters = ReadCharacterFile(GetServerScopedPath(safeServer, safeAccount)); if (serverCharacters.Count > 0) return serverCharacters; + + // The same account name can exist on several servers. The legacy + // account-only file predates server scoping, so it is only trusted + // while no server-scoped file exists for this account at all; + // otherwise it would hand one server's characters to another. + if (HasAnyServerScopedFile(safeAccount)) + return []; } return ReadCharacterFile(GetAccountScopedPath(safeAccount)); @@ -84,7 +91,11 @@ internal static class CharacterCacheStore if (string.IsNullOrWhiteSpace(accountName) || string.IsNullOrWhiteSpace(characterName)) return; - List<string> characters = Read(accountName, serverName); + // With a server, seed only from that server's own file so a legacy + // account-only list cannot be merged into the wrong server. + List<string> characters = string.IsNullOrWhiteSpace(serverName) + ? Read(accountName, serverName) + : ReadStrict(accountName, serverName); if (!characters.Any(existing => IsSameCharacter(existing, characterName))) characters.Add(characterName); @@ -96,27 +107,34 @@ internal static class CharacterCacheStore private static bool IsSameCharacter(string a, string b) => string.Equals(a.Trim().TrimStart('+'), b.Trim().TrimStart('+'), StringComparison.OrdinalIgnoreCase); - public static void DeleteForAccount(string accountName) + /// Deletes the character cache for one (account, server) pair. Other servers' + /// files for the same account name are left alone. The legacy account-only + /// file is removed only when <paramref name="includeLegacy"/> is set (the + /// caller knows whether another profile still uses this account name). + public static void DeleteForAccount(string accountName, string serverName, bool includeLegacy) { if (string.IsNullOrWhiteSpace(accountName)) return; try { - string rootDirectory = GetRootDirectory(); - if (!Directory.Exists(rootDirectory)) - return; - string safeAccount = SanitizeFileName(accountName); - foreach (string file in Directory.GetFiles(rootDirectory, $"characters_*_{safeAccount}.json")) + if (!string.IsNullOrWhiteSpace(serverName)) { - try { File.Delete(file); } catch { } + string serverScopedPath = GetServerScopedPath(SanitizeFileName(serverName), safeAccount); + if (File.Exists(serverScopedPath)) + { + try { File.Delete(serverScopedPath); } catch { } + } } - string accountScopedPath = GetAccountScopedPath(safeAccount); - if (File.Exists(accountScopedPath)) + if (includeLegacy) { - try { File.Delete(accountScopedPath); } catch { } + string accountScopedPath = GetAccountScopedPath(safeAccount); + if (File.Exists(accountScopedPath)) + { + try { File.Delete(accountScopedPath); } catch { } + } } } catch @@ -124,6 +142,20 @@ internal static class CharacterCacheStore } } + private static bool HasAnyServerScopedFile(string safeAccountName) + { + try + { + string rootDirectory = GetRootDirectory(); + return Directory.Exists(rootDirectory) && + Directory.EnumerateFiles(rootDirectory, $"characters_*_{safeAccountName}.json").Any(); + } + catch + { + return false; + } + } + private static string GetRootDirectory() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore"); diff --git a/src/RynthCore.App/DecalAccountModes.cs b/src/RynthCore.App/DecalAccountModes.cs new file mode 100644 index 0000000..b5e8f25 --- /dev/null +++ b/src/RynthCore.App/DecalAccountModes.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; + +namespace RynthCore.App; + +/// <summary> +/// Which accounts run as "Decal + RynthCore" (<see cref="InjectionMode.DecalBridge"/>), kept in +/// <c>decal-accounts.json</c> next to <c>%APPDATA%\RynthCore\appsettings.json</c> and keyed by +/// account profile id. +/// +/// Why a file of its own: every launcher of this Windows user shares appsettings.json, and a +/// launcher released before the Decal bridge has no "DecalBridge" value in its InjectionMode. +/// Its AppSettingsStore takes a file with that value for corrupt, quarantines it and falls back +/// to the .bak, or to empty defaults (and then saves those). So appsettings.json always lists a +/// "Decal + RynthCore" account as <see cref="SharedMode"/> (RynthCore), and this file says which +/// of those are really "Decal + RynthCore". +/// +/// An entry only counts while appsettings.json still says RynthCore for that account: an older +/// launcher that switched the account to Decal (or that deleted it) wins, and the next save of a +/// newer launcher drops the stale entry. Shared with the injector (LaunchCommand). +/// </summary> +internal static class DecalAccountModes +{ + public const string FileName = "decal-accounts.json"; + + /// <summary>What appsettings.json says for a "Decal + RynthCore" account.</summary> + public const InjectionMode SharedMode = InjectionMode.RynthCore; + + private const int SchemaVersion = 1; + + private const string Note = + "Accounts the RynthCore launcher runs as \"Decal + RynthCore\" (experimental). " + + "appsettings.json lists them as RynthCore, so launchers without that mode can still read it. " + + "Delete this file to set them all back to RynthCore."; + + private sealed class FileModel + { + public int Version { get; set; } = SchemaVersion; + public string Note { get; set; } = DecalAccountModes.Note; + public List<string> DecalBridgeAccountIds { get; set; } = new(); + } + + private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true }; + + public static string PathIn(string settingsDirectory) => Path.Combine(settingsDirectory, FileName); + + /// <summary> + /// The account ids listed in <paramref name="path"/>. An absent file is an empty set; an + /// unreadable one too, with the reason in <paramref name="error"/> (the accounts then run + /// as appsettings.json says, which is RynthCore). + /// </summary> + public static HashSet<string> ReadIds(string path, out string? error) + { + error = null; + var ids = new HashSet<string>(StringComparer.Ordinal); + try + { + if (!File.Exists(path)) + return ids; + FileModel? model = JsonSerializer.Deserialize<FileModel>(File.ReadAllText(path)); + foreach (string id in model?.DecalBridgeAccountIds ?? new List<string>()) + if (!string.IsNullOrWhiteSpace(id)) + ids.Add(id); + } + catch (Exception ex) + { + error = $"{FileName} could not be read ({ex.GetType().Name}: {ex.Message}); " + + "its accounts run as RynthCore until the mode is picked again."; + ids.Clear(); + } + return ids; + } + + /// <summary> + /// True when an account that appsettings.json lists with <paramref name="sharedMode"/> is a + /// "Decal + RynthCore" account: it is in <paramref name="ids"/> and still says RynthCore. + /// </summary> + public static bool IsDecalBridge(IReadOnlySet<string> ids, string? accountId, InjectionMode sharedMode) => + sharedMode == SharedMode && !string.IsNullOrEmpty(accountId) && ids.Contains(accountId); + + /// <summary> + /// Records <paramref name="ids"/> as the "Decal + RynthCore" accounts. Writes only when the + /// list changed; with no accounts left, the file is removed. Atomic (temp file + swap). + /// </summary> + public static void WriteIds(string path, IEnumerable<string> ids) + { + List<string> sorted = ids.Where(id => !string.IsNullOrWhiteSpace(id)) + .Distinct(StringComparer.Ordinal) + .OrderBy(id => id, StringComparer.Ordinal) + .ToList(); + if (sorted.Count == 0) + { + if (File.Exists(path)) + File.Delete(path); + return; + } + + if (File.Exists(path)) + { + HashSet<string> current = ReadIds(path, out string? error); + if (error == null && current.SetEquals(sorted)) + return; + } + + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + string tmp = path + ".tmp"; + File.WriteAllText(tmp, JsonSerializer.Serialize(new FileModel { DecalBridgeAccountIds = sorted }, WriteOptions)); + File.Move(tmp, path, overwrite: true); + } +} diff --git a/src/RynthCore.App/DecalBridgeCheck.cs b/src/RynthCore.App/DecalBridgeCheck.cs new file mode 100644 index 0000000..501c147 --- /dev/null +++ b/src/RynthCore.App/DecalBridgeCheck.cs @@ -0,0 +1,495 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; + +namespace RynthCore.App; + +/// <summary>Registry roots the Decal check reads. "32" = the 32-bit view (WOW6432Node on 64-bit Windows).</summary> +internal enum RegRoot { Machine32, Machine64, User32, User64 } + +/// <summary>A read-only registry key (real one, or a fake in tools\DecalBridgeCheckTests).</summary> +internal interface IRegKey : IDisposable +{ + object? GetValue(string name); + string[] GetSubKeyNames(); + string[] GetValueNames(); +} + +/// <summary> +/// Everything <see cref="DecalBridgeCheck"/> reads from the machine. The real one is +/// <see cref="RealDecalCheckHost"/>; the offline tests use a fake. +/// </summary> +internal interface IDecalCheckHost +{ + bool Is64BitOs { get; } + /// <summary>The launcher (or injector) runs elevated. A client it starts is elevated too.</summary> + bool LauncherElevated { get; } + /// <summary>UAC registry virtualization is on for this process (as it is for a non-elevated AC).</summary> + bool LauncherVirtualized { get; } + /// <summary>The real registry: no UAC virtualization (HKLM is HKLM, the VirtualStore is its own key).</summary> + IRegKey? OpenReal(RegRoot root, string subKey); + /// <summary> + /// HKLM (32-bit view) as THIS process sees it, virtualized when the process is. Only the + /// bridge's own entry is asked for (the real host snapshots it before virtualization is + /// switched off for the rest of the check). + /// </summary> + IRegKey? OpenOwnViewMachine32(string subKey); + bool FileExists(string path); + /// <summary>The file carries a Zone.Identifier stream ("downloaded from the internet").</summary> + bool HasZoneIdentifier(string path); + Version? AssemblyVersionOf(string path); + Version? ReferenceVersionOf(string assemblyPath, string referenceName); + /// <summary>requestedExecutionLevel from the exe's embedded manifest or its .manifest file, null if none.</summary> + string? ExecutionLevelOf(string exePath); + string? ReadTextFile(string path); +} + +/// <summary> +/// "Check Decal bridge": can a Decal + RynthCore client started now load the RynthCore Decal +/// bridge? (docs/DECAL_BRIDGE_PLAN.md, "Where Decal reads its filters"). +/// +/// Decal lists network filters from HKLM\SOFTWARE\Decal\NetworkFilters (decalnet.dll), read +/// by the 32-bit client through the 32-bit view (WOW6432Node), and Decal.Adapter reads each +/// .NET filter's Path/Assembly/Object from SOFTWARE\Decal\NetworkFilters\{id}. Which key that +/// really is depends on the CLIENT's token: +/// - a non-elevated acclient.exe (no manifest, UAC on) is virtualized: when the per-user copy +/// HKCU\Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\NetworkFilters +/// exists, Decal reads ONLY that copy; otherwise the real HKLM key; +/// - an elevated client (the launcher runs as administrator, acclient.exe set to "Run as +/// administrator", UAC off), or one with a manifest, or with virtualization off by policy, +/// is not virtualized and reads the real HKLM key - a per-user registration is invisible. +/// The check predicts that, reads our entry from where Decal will read it, and where it can +/// (the launcher's token is virtualized exactly when the client's will be) reads it again +/// through the launcher's own view, which is the client's view. +/// </summary> +internal static class DecalBridgeCheck +{ + public enum Level { Ok, Info, Warn, Fail } + + public sealed record Line(Level Level, string Text); + + public sealed class Result + { + public List<Line> Lines { get; } = new(); + public bool DecalInstalled { get; set; } + public string? DecalVersion { get; set; } + public bool ClientVirtualized { get; set; } + public string ClientReason { get; set; } = string.Empty; + /// <summary>Where Decal reads its filter list on this machine, for people.</summary> + public string FiltersReadFrom { get; set; } = string.Empty; + public bool ReadsPerUserCopy { get; set; } + /// <summary>Our entry is where Decal reads, enabled, with the DLL in place.</summary> + public bool BridgeVisibleToDecal { get; set; } + /// <summary>Not registered where Decal reads, and that place is HKLM: needs administrator rights once.</summary> + public bool NeedsMachineWideRegistration { get; set; } + public bool Blocking => Lines.Any(l => l.Level == Level.Fail); + + public void Add(Level level, string text) => Lines.Add(new Line(level, text)); + + public string Summary => Blocking + ? "Decal bridge check: FAILED - " + string.Join(" ", Lines.Where(l => l.Level == Level.Fail).Select(l => l.Text)) + : "Decal bridge check: OK - " + FiltersReadFrom + (DecalVersion != null ? $"; Decal {DecalVersion}" : ""); + + public string ToReport() + { + var sb = new StringBuilder(); + foreach (Line l in Lines) + { + string tag = l.Level switch { Level.Ok => "OK ", Level.Info => " ", Level.Warn => "WARN", _ => "FAIL" }; + sb.Append(tag).Append(" ").AppendLine(l.Text); + } + sb.AppendLine(); + sb.AppendLine(Blocking + ? "Result: a Decal + RynthCore client started now would NOT load the bridge (no RynthCore overlay, then a crash). Fix the FAIL lines first." + : "Result: a Decal + RynthCore client started now will load the bridge."); + return sb.ToString(); + } + } + + /// <summary>Decal's .NET surrogate CLSID (Decal.Adapter.Surrogate).</summary> + public const string SurrogateClsid = "{71A69713-6593-47EC-0002-0000000DECA1}"; + /// <summary>The bridge targets .NET Framework 4.8 (Release key 528040).</summary> + private const int Net48Release = 528040; + + public static string VirtualStoreDecalPath(bool is64BitOs, string group) => is64BitOs + ? @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\" + group + : @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\Decal\" + group; + + public static string MachineDecalPath(string group) => @"SOFTWARE\Decal\" + group; + + /// <summary> + /// Will a client started by this launcher get UAC registry virtualization? False when it + /// runs elevated or Windows doesn't virtualize it (reason says which). + /// </summary> + public static bool PredictClientVirtualized(IDecalCheckHost host, string? acClientPath, out string reason) + { + int? lua = DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableLUA"); + if (lua == 0) + { + reason = "UAC is turned off on this PC (EnableLUA=0), so Windows gives every program the real machine registry"; + return false; + } + int? virt = DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableVirtualization"); + if (virt == 0) + { + reason = "UAC registry virtualization is turned off by policy (EnableVirtualization=0)"; + return false; + } + if (host.LauncherElevated) + { + reason = "RynthCore runs as administrator, so the AC client it starts does too, and Windows gives it the real machine registry"; + return false; + } + if (!string.IsNullOrEmpty(acClientPath)) + { + string? level = host.ExecutionLevelOf(acClientPath); + if (level != null) + { + reason = $"{Path.GetFileName(acClientPath)} has a manifest (requestedExecutionLevel={level}), so Windows doesn't virtualize it"; + return false; + } + string? layer = RunAsAdminLayer(host, acClientPath); + if (layer != null) + { + reason = $"{acClientPath} is set to \"Run this program as an administrator\" ({layer})"; + return false; + } + } + reason = "AC runs without administrator rights, so Windows virtualizes its registry"; + return true; + } + + /// <summary> + /// Where a client (virtualized or not) reads SOFTWARE\Decal\<group>: the per-user + /// VirtualStore copy when it is virtualized and the copy exists, else the real HKLM key. + /// </summary> + public static (RegRoot Root, string Path, bool PerUser) WhereDecalReads(IDecalCheckHost host, bool clientVirtualized, string group) + { + if (clientVirtualized) + { + string vs = VirtualStoreDecalPath(host.Is64BitOs, group); + using IRegKey? k = host.OpenReal(RegRoot.User64, vs); + if (k != null) + return (RegRoot.User64, vs, true); + } + return (RegRoot.Machine32, MachineDecalPath(group), false); + } + + /// <summary> + /// What the installer (and every update) writes, so a client finds the bridge whatever + /// its rights (installer\RynthCore.iss: <see cref="DecalBridgeRegistration.RegisterMachineWide"/> + /// elevated, <see cref="DecalBridgeRegistration.InstallPerUser"/> as the installing user): + /// - Machine: always (when Decal is installed). Elevated and unvirtualized clients read + /// only HKLM; a virtualized client without a per-user copy reads HKLM too. + /// - PerUser: only into a per-user copy that ALREADY exists. A virtualized client then + /// reads that copy and nothing else, so the HKLM entry is hidden from it. Creating a + /// copy that doesn't exist would be harmful: it would hide every HKLM filter added later + /// (a Decal plugin installed for all users) from this user's non-elevated clients. + /// </summary> + public static (bool Machine, bool PerUser) PlanInstall(IDecalCheckHost host) + { + bool decal = StringOf(host, RegRoot.Machine32, MachineDecalPath("Agent"), "AgentPath") != null; + if (!decal) return (false, false); + using IRegKey? copy = host.OpenReal(RegRoot.User64, VirtualStoreDecalPath(host.Is64BitOs, "NetworkFilters")); + return (true, copy != null); + } + + public static string Describe(bool is64BitOs, RegRoot root, string path) => root switch + { + RegRoot.Machine32 => is64BitOs ? @"HKLM\SOFTWARE\WOW6432Node\" + path.Substring("SOFTWARE\\".Length) : @"HKLM\" + path, + RegRoot.Machine64 => @"HKLM\" + path, + _ => @"HKCU\" + path, + }; + + /// <summary>Runs every check. Reads only; changes nothing.</summary> + public static Result Run(IDecalCheckHost host, string bridgeDirectory, string? acClientPath, string? engineJsonPath) + { + var r = new Result(); + string dir = bridgeDirectory.TrimEnd('\\'); + + // 1. Decal and its version. + string? agentPath = StringOf(host, RegRoot.Machine32, MachineDecalPath("Agent"), "AgentPath"); + r.DecalInstalled = agentPath != null && host.FileExists(Path.Combine(agentPath, "Inject.dll")); + if (!r.DecalInstalled) + { + r.Add(Level.Fail, @"Decal is not installed (HKLM\SOFTWARE\Decal\Agent AgentPath\Inject.dll not found)."); + return r; + } + string adapter = Path.Combine(agentPath!, "Decal.Adapter.dll"); + Version? installed = host.FileExists(adapter) ? host.AssemblyVersionOf(adapter) : null; + string bridgeDll = Path.Combine(dir, DecalBridgeRegistration.AssemblyFile); + bool bridgePresent = host.FileExists(bridgeDll); + Version? needed = bridgePresent ? host.ReferenceVersionOf(bridgeDll, "Decal.Adapter") : null; + r.DecalVersion = installed?.ToString(); + if (installed == null) + r.Add(Level.Fail, $"Decal.Adapter.dll is missing or unreadable in {agentPath} - reinstall Decal."); + else if (needed != null && installed < needed) + r.Add(Level.Fail, $"Decal {installed} is older than the {needed} the bridge is built for - update Decal (decaldev.com), then check again."); + else + r.Add(Level.Ok, $"Decal {installed} in {agentPath}" + (needed != null ? $" (bridge built for {needed})." : ".")); + + // 2. The bridge DLL itself. + if (!bridgePresent) + r.Add(Level.Fail, $"{DecalBridgeRegistration.AssemblyFile} is missing from {dir} - reinstall RynthCore."); + else if (host.HasZoneIdentifier(bridgeDll)) + r.Add(Level.Warn, $"{bridgeDll} is marked as downloaded from the internet; .NET may refuse to load it. Repair removes the mark (or: right-click > Properties > Unblock)."); + else + r.Add(Level.Ok, $"Bridge DLL present: {bridgeDll}."); + + // 3. How the client will see the registry. + r.ClientVirtualized = PredictClientVirtualized(host, acClientPath, out string why); + r.ClientReason = why; + r.Add(Level.Info, "AC client: " + why + "."); + + // 4. Where Decal reads its filters, and our entry there. + var where = WhereDecalReads(host, r.ClientVirtualized, "NetworkFilters"); + r.ReadsPerUserCopy = where.PerUser; + string whereText = Describe(host.Is64BitOs, where.Root, where.Path); + r.FiltersReadFrom = "Decal reads its filters from " + whereText + (where.PerUser ? " (your Windows user's copy)" : ""); + r.Add(Level.Info, r.FiltersReadFrom + "."); + + string? entryProblem = EntryProblem(host, where.Root, where.Path + "\\" + DecalBridgeRegistration.FilterGuid, out string? registeredPath); + if (entryProblem == null) + { + r.BridgeVisibleToDecal = true; + r.Add(Level.Ok, $"RynthCore Decal Bridge is registered there and enabled ({registeredPath})."); + } + else + { + r.NeedsMachineWideRegistration = !where.PerUser; + r.Add(Level.Fail, $"Decal will not load the bridge: {entryProblem} in {whereText}." + + (where.PerUser + ? " Repair (or a Decal + RynthCore launch) registers it for your Windows user." + : " That key is shared by all users: Repair adds it there once and Windows asks for administrator permission.")); + } + + // Other places, for people (a registration Decal won't read explains a "registered but nothing happens"). + if (where.PerUser) + { + using IRegKey? m = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid); + if (m != null && IsOurs(m) && entryProblem != null) + r.Add(Level.Info, "(A machine-wide entry exists, but your per-user copy hides it from AC.)"); + } + else + { + using IRegKey? u = host.OpenReal(RegRoot.User64, VirtualStoreDecalPath(host.Is64BitOs, "NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid); + if (u != null && IsOurs(u) && entryProblem != null) + r.Add(Level.Info, "(A per-user registration exists, but this AC client doesn't read it: " + why + ".)"); + } + + // 5. The same entry through this process's own view, when that view IS the client's. + bool sameView = host.LauncherVirtualized == r.ClientVirtualized; + if (sameView) + { + using IRegKey? live = host.OpenOwnViewMachine32(MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid); + bool liveOk = live != null && IsOurs(live) && IsEnabled(live); + if (liveOk == r.BridgeVisibleToDecal) + r.Add(Level.Ok, $"Read back as AC will see it: {(liveOk ? "bridge listed and enabled" : "bridge not listed")}."); + else + r.Add(liveOk ? Level.Warn : Level.Fail, + $"Read back as AC will see it: {(liveOk ? "bridge listed" : "bridge NOT listed")}, which disagrees with {whereText}. Windows serves this PC's registry differently than expected."); + } + else + { + r.Add(Level.Info, "Not read back live: AC will run with other rights than this launcher."); + } + + // 6. Hidden machine filters (a per-user list hides every HKLM entry it lacks). + if (where.PerUser) + { + List<string> hidden = HiddenMachineFilters(host, where.Path); + if (hidden.Count > 0) + r.Add(Level.Warn, "Hidden from AC by your per-user filter list (in HKLM, not in the copy): " + string.Join(", ", hidden) + + ". If 'World Object Filter' is among them, VTank won't start."); + } + + // 7. Decal's .NET surrogate: Decal must be able to create it, and must not have it disabled. + var surWhere = WhereDecalReads(host, r.ClientVirtualized, "Surrogates"); + using (IRegKey? s = host.OpenReal(surWhere.Root, surWhere.Path + "\\" + SurrogateClsid)) + { + if (s == null) + r.Add(Level.Fail, $"Decal's .NET surrogate is not listed in {Describe(host.Is64BitOs, surWhere.Root, surWhere.Path)} - no .NET filter or plugin can load. Reinstall Decal."); + else if (!IsEnabled(s)) + r.Add(Level.Fail, "Decal's .NET surrogate (Decal.Adapter Surrogate) is disabled in Decal - enable it in Decal's agent (or reinstall Decal)."); + else + r.Add(Level.Ok, "Decal's .NET surrogate is enabled."); + } + string? comProblem = SurrogateComProblem(host, clientElevated: !r.ClientVirtualized && IsClientElevated(host, acClientPath), out string comWhere); + if (comProblem != null) + r.Add(Level.Fail, comProblem); + else + r.Add(Level.Ok, $"Decal.Adapter's COM class resolves ({comWhere}). The bridge itself needs no COM registration: Decal.Adapter loads it from Path\\Assembly."); + + // 8. .NET Framework 4.8. + int? release = DwordOf(host, RegRoot.Machine32, @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", "Release"); + if (release == null) + r.Add(Level.Fail, ".NET Framework 4 is not installed (Decal needs it)."); + else if (release < Net48Release) + r.Add(Level.Warn, $".NET Framework older than 4.8 (Release {release}); the bridge targets 4.8 - install .NET Framework 4.8."); + + // 9. engine.json settings that turn bridge mode off. + if (engineJsonPath != null) + { + (string? mode, bool? inGame) = ReadEngineSettings(host, engineJsonPath); + if (mode != null && (mode.Equals("Off", StringComparison.OrdinalIgnoreCase) || mode.Equals("false", StringComparison.OrdinalIgnoreCase))) + r.Add(Level.Fail, $"engine.json has \"DecalBridge\": {mode} - bridge mode is off for every client. Remove that line ({engineJsonPath})."); + if (inGame == false) + r.Add(Level.Warn, "engine.json has \"DecalInGameImGui\": false - no RynthCore overlay under Decal (by choice)."); + } + return r; + } + + // ── pieces (internal for the tests) ───────────────────────────────────── + + internal static string? EntryProblem(IDecalCheckHost host, RegRoot root, string entryPath, out string? registeredPath) + { + registeredPath = null; + using IRegKey? k = host.OpenReal(root, entryPath); + if (k == null) return "the RynthCore Decal Bridge is not registered"; + if (!IsOurs(k)) return "another filter uses the bridge's id"; + registeredPath = k.GetValue("Path") as string; + if (!IsEnabled(k)) return "the RynthCore Decal Bridge is registered but disabled"; + if (!string.Equals(k.GetValue("Surrogate") as string, SurrogateClsid, StringComparison.OrdinalIgnoreCase)) + return "the bridge entry has the wrong Surrogate"; + string? file = k.GetValue("Assembly") as string; + if (string.IsNullOrEmpty(registeredPath) || string.IsNullOrEmpty(file)) + return "the bridge entry has no Path/Assembly"; + if (!host.FileExists(Path.Combine(registeredPath, file))) + return $"the registered bridge DLL is missing ({Path.Combine(registeredPath, file)})"; + return null; + } + + internal static List<string> HiddenMachineFilters(IDecalCheckHost host, string perUserPath) + { + var hidden = new List<string>(); + using IRegKey? machine = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters")); + using IRegKey? user = host.OpenReal(RegRoot.User64, perUserPath); + if (machine == null || user == null) return hidden; + var seen = new HashSet<string>(user.GetSubKeyNames(), StringComparer.OrdinalIgnoreCase); + foreach (string name in machine.GetSubKeyNames()) + { + if (seen.Contains(name) || string.Equals(name, DecalBridgeRegistration.FilterGuid, StringComparison.OrdinalIgnoreCase)) + continue; + using IRegKey? k = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters") + "\\" + name); + hidden.Add(k?.GetValue("") is string friendly && friendly.Length > 0 ? friendly : name); + } + return hidden; + } + + /// <summary> + /// Decal.Adapter's surrogate is an mscoree COM class. A non-elevated client resolves it + /// per-user first (HKCU\Software\Classes), then machine-wide; an elevated one ignores + /// per-user COM registrations. + /// </summary> + internal static string? SurrogateComProblem(IDecalCheckHost host, bool clientElevated, out string where) + { + where = string.Empty; + string sub = @"\CLSID\" + SurrogateClsid + @"\InprocServer32"; + var candidates = new List<(RegRoot Root, string Path, string Label)>(); + if (!clientElevated) candidates.Add((RegRoot.User32, @"Software\Classes" + sub, "per-user")); + candidates.Add((RegRoot.Machine32, @"SOFTWARE\Classes" + sub, "machine-wide")); + foreach (var c in candidates) + { + using IRegKey? k = host.OpenReal(c.Root, c.Path); + if (k == null) continue; + where = c.Label; + string server = k.GetValue("") as string ?? string.Empty; + if (!server.EndsWith("mscoree.dll", StringComparison.OrdinalIgnoreCase)) + return $"Decal.Adapter's COM class ({c.Label}) points at '{server}', not mscoree.dll - reinstall Decal."; + if (string.IsNullOrEmpty(k.GetValue("Assembly") as string)) + return $"Decal.Adapter's COM class ({c.Label}) names no assembly - reinstall Decal."; + if (k.GetValue("CodeBase") is string cb && cb.Length > 0) + { + string file = cb.StartsWith("file:", StringComparison.OrdinalIgnoreCase) ? cb.Substring(5).TrimStart('/') : cb; + if (!host.FileExists(file.Replace('/', '\\'))) + return $"Decal.Adapter's COM class ({c.Label}) points at a missing file ({file}) - reinstall Decal."; + } + return null; + } + bool perUserOnly = clientElevated && OpenExists(host, RegRoot.User32, @"Software\Classes" + sub); + return perUserOnly + ? "Decal.Adapter's COM class is registered only for your Windows user, and an AC running as administrator ignores per-user COM classes - reinstall Decal for all users." + : "Decal.Adapter's COM class (Decal.Adapter.Surrogate) is not registered - reinstall Decal."; + } + + private static bool IsClientElevated(IDecalCheckHost host, string? acClientPath) + { + if (host.LauncherElevated) return true; + if (string.IsNullOrEmpty(acClientPath)) return false; + string? level = host.ExecutionLevelOf(acClientPath); + if (level != null && (level.Equals("requireAdministrator", StringComparison.OrdinalIgnoreCase) || level.Equals("highestAvailable", StringComparison.OrdinalIgnoreCase))) + return true; + if (RunAsAdminLayer(host, acClientPath) != null) return true; + // UAC off: an administrator's programs run with the full token. + return DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableLUA") == 0; + } + + private static string? RunAsAdminLayer(IDecalCheckHost host, string exePath) + { + foreach ((RegRoot root, string key) in new[] + { + (RegRoot.User64, @"Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"), + (RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"), + }) + { + using IRegKey? k = host.OpenReal(root, key); + if (k == null) continue; + foreach (string name in k.GetValueNames()) + { + if (!string.Equals(name, exePath, StringComparison.OrdinalIgnoreCase)) continue; + string flags = k.GetValue(name) as string ?? string.Empty; + string[] parts = flags.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Any(p => p.Equals("RUNASADMIN", StringComparison.OrdinalIgnoreCase) || p.Equals("RUNASHIGHEST", StringComparison.OrdinalIgnoreCase))) + return (root == RegRoot.User64 ? "your compatibility settings" : "compatibility settings for all users") + ": " + flags.Trim(); + } + } + return null; + } + + private static (string? Mode, bool? InGame) ReadEngineSettings(IDecalCheckHost host, string path) + { + try + { + string? text = host.ReadTextFile(path); + if (text == null) return (null, null); + using JsonDocument doc = JsonDocument.Parse(text, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }); + string? mode = null; + bool? inGame = null; + if (doc.RootElement.TryGetProperty("DecalBridge", out JsonElement m)) + mode = m.ValueKind switch { JsonValueKind.String => m.GetString(), JsonValueKind.True => "true", JsonValueKind.False => "false", _ => null }; + if (doc.RootElement.TryGetProperty("DecalInGameImGui", out JsonElement g) && (g.ValueKind == JsonValueKind.True || g.ValueKind == JsonValueKind.False)) + inGame = g.GetBoolean(); + return (mode, inGame); + } + catch + { + return (null, null); + } + } + + internal static bool IsOurs(IRegKey k) => + string.Equals(k.GetValue("Object") as string, DecalBridgeRegistration.FilterObject, StringComparison.Ordinal); + + internal static bool IsEnabled(IRegKey k) => k.GetValue("Enabled") is int e && e != 0; + + private static bool OpenExists(IDecalCheckHost host, RegRoot root, string path) + { + using IRegKey? k = host.OpenReal(root, path); + return k != null; + } + + private static int? DwordOf(IDecalCheckHost host, RegRoot root, string path, string name) + { + using IRegKey? k = host.OpenReal(root, path); + return k?.GetValue(name) is int v ? v : null; + } + + private static string? StringOf(IDecalCheckHost host, RegRoot root, string path, string name) + { + using IRegKey? k = host.OpenReal(root, path); + return k?.GetValue(name) is string s && s.Length > 0 ? s : null; + } +} diff --git a/src/RynthCore.App/DecalBridgeRegistration.cs b/src/RynthCore.App/DecalBridgeRegistration.cs new file mode 100644 index 0000000..65f2c1b --- /dev/null +++ b/src/RynthCore.App/DecalBridgeRegistration.cs @@ -0,0 +1,810 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using Microsoft.Win32; + +namespace RynthCore.App; + +/// <summary> +/// Registers (and cleanly unregisters) the RynthCore Decal bridge - the small Decal +/// network filter in src\RynthCore.DecalBridge - in Decal's filter list. See +/// docs\DECAL_BRIDGE_PLAN.md, "Where Decal reads its filters". +/// +/// <see cref="RegisterForClients"/> picks the place: the per-user copy below when the AC +/// client will be virtualized (the usual, non-elevated case), the machine-wide HKLM list +/// (administrator rights, once) when it won't be. An elevated or unvirtualized client never +/// reads the per-user copy (2026-10-03: a player's Decal + RynthCore client never loaded the +/// bridge). <see cref="DecalBridgeCheck"/> verifies the result. +/// +/// Per-user. The launcher runs without admin rights, so it can't write Decal's own +/// key (HKLM\SOFTWARE\WOW6432Node\Decal\NetworkFilters). acclient.exe is a legacy 32-bit +/// program that Windows "virtualizes": its reads of that HKLM key are served from the +/// per-user copy under HKCU\Software\Classes\VirtualStore when one exists. Registering +/// there makes every Decal client this user starts load the bridge (it stays idle unless +/// RynthCore is in the same client). +/// +/// The trap (measured 2026-09-29): once the per-user NetworkFilters key exists, Decal +/// sees ONLY its entries - HKLM's filters (World Object Filter, Echo Filter, ...) vanish, +/// Decal's WorldFilter is null and VTank refuses to start. So when this class has to +/// create that key, it first mirrors every HKLM filter entry into it, and on each +/// Register call it copies over HKLM entries added since. +/// +/// What it adds is recorded in %APPDATA%\RynthCore\decal-bridge-registration.json; +/// Unregister removes exactly that: the bridge's own entry, the mirrored copies nobody has +/// changed since, and the per-user key itself only if this class created it and nothing +/// else is left in it. Register is idempotent. +/// +/// Opt-in only: nothing calls Register unless the user picked "Decal + RynthCore" for an +/// account (or ran the injector's --decal-bridge register). +/// </summary> +internal static class DecalBridgeRegistration +{ + /// <summary>The bridge's fixed filter id (one entry, whatever the install path).</summary> + public const string FilterGuid = "{5B3E0D57-2C41-4F8A-9D6E-8C1B70DECA11}"; + public const string FilterObject = "RynthCore.DecalBridge.BridgeFilter"; + public const string AssemblyFile = "RynthCore.DecalBridge.dll"; + public const string FilterName = "RynthCore Decal Bridge"; + /// <summary>Decal's .NET surrogate, the value every Decal.Adapter filter registers with.</summary> + private const string DotNetSurrogate = "{71A69713-6593-47EC-0002-0000000DECA1}"; + + private const string DecalFiltersSubKey = @"SOFTWARE\Decal\NetworkFilters"; // seen through the 32-bit view + private const RegistryView MachineView = RegistryView.Registry32; // what the 32-bit client reads + + private static string StatePath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "decal-bridge-registration.json"); + + /// <summary>HKCU path of the per-user copy the virtualized 32-bit client reads.</summary> + public static string VirtualStoreFiltersSubKey => Environment.Is64BitOperatingSystem + ? @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\NetworkFilters" + : @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\Decal\NetworkFilters"; + + /// <summary>The folder the launcher registers: <install>\DecalBridge.</summary> + public static string DefaultBridgeDirectory => Path.Combine(AppContext.BaseDirectory, "DecalBridge"); + + public sealed class Status + { + public bool DecalInstalled; + public bool PerUserKeyExists; + public bool PerUserKeyCreatedByUs; + public bool RegisteredPerUser; + public bool RegisteredMachineWide; + public bool Enabled; + public bool MachineEnabled; + public string? RegisteredPath; + public bool DllPresent; + /// <summary>A client started by this process gets UAC registry virtualization (reads the per-user copy when it exists).</summary> + public bool ClientVirtualized = true; + public string ClientReason = string.Empty; + /// <summary>HKLM filters a Decal client of this user can't see (hidden by the per-user key).</summary> + public List<string> HiddenMachineFilters = new(); + + /// <summary>What a Decal client started now will load (see DecalBridgeCheck for the full check).</summary> + public bool EffectiveForClients => ClientVirtualized && PerUserKeyExists + ? RegisteredPerUser && Enabled + : RegisteredMachineWide && MachineEnabled; + + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append($"Decal installed: {DecalInstalled}. "); + sb.Append($"Bridge registered for clients started now: {(EffectiveForClients ? "yes" : "no")}"); + if (RegisteredPerUser) sb.Append(" (per-user entry present)"); + if (RegisteredMachineWide) sb.Append(" (machine-wide entry present)"); + if (RegisteredPath != null) sb.Append($", path {RegisteredPath}{(DllPresent ? "" : " (DLL MISSING)")}"); + sb.Append('.'); + if (ClientReason.Length > 0) sb.Append($" Client: {ClientReason}."); + if (PerUserKeyExists) + sb.Append($" Per-user filter list: {(PerUserKeyCreatedByUs ? "created by RynthCore" : "existed before RynthCore")}."); + if (HiddenMachineFilters.Count > 0) + sb.Append($" Hidden from Decal clients (in HKLM, not in the per-user list): {string.Join(", ", HiddenMachineFilters)}."); + return sb.ToString(); + } + } + + private sealed class State + { + public bool CreatedFiltersKey { get; set; } + public string BridgePath { get; set; } = string.Empty; + public DateTime RegisteredUtc { get; set; } + /// <summary>Mirrored HKLM subkey -> fingerprint of the copy as written.</summary> + public Dictionary<string, string> MirroredKeys { get; set; } = new(StringComparer.OrdinalIgnoreCase); + /// <summary>Mirrored values of the NetworkFilters key itself -> fingerprint.</summary> + public Dictionary<string, string> MirroredValues { get; set; } = new(StringComparer.OrdinalIgnoreCase); + } + + // ── public API ─────────────────────────────────────────────────────────── + + public static Status GetStatus(string? acClientPath = null) + { + bool virt = RealDecalCheckHost.PredictClientVirtualized(acClientPath ?? DecalLocator.TryGetDecalAcClientPath(), out string reason, out _); + Status s; + using (RealRegistryView.Enter()) s = GetStatusCore(); + s.ClientVirtualized = virt; + s.ClientReason = reason; + return s; + } + + private static Status GetStatusCore() + { + var s = new Status { DecalInstalled = DecalLocator.IsInstalled() }; + State? state = LoadState(); + using RegistryKey? machine = OpenMachineFilters(); + using RegistryKey? user = OpenUserFilters(writable: false); + s.PerUserKeyExists = user != null; + s.PerUserKeyCreatedByUs = user != null && state?.CreatedFiltersKey == true; + + using (RegistryKey? m = machine?.OpenSubKey(FilterGuid)) + { + if (m != null && IsOurs(m)) + { + s.RegisteredMachineWide = true; + s.MachineEnabled = Enabled(m); + if (user == null) ReadEntry(m, s); + } + } + using (RegistryKey? u = user?.OpenSubKey(FilterGuid)) + { + if (u != null && IsOurs(u)) + { + s.RegisteredPerUser = true; + ReadEntry(u, s); + } + } + if (machine != null && user != null) + { + HashSet<string> seen = new(user.GetSubKeyNames(), StringComparer.OrdinalIgnoreCase); + foreach (string name in machine.GetSubKeyNames()) + if (!seen.Contains(name)) + s.HiddenMachineFilters.Add(DescribeFilter(machine, name)); + } + return s; + } + + public enum Outcome { Registered, NeedsAdmin, Failed } + + /// <summary> + /// Registers the bridge where a Decal client started now reads its filter list, then + /// verifies it with <see cref="DecalBridgeCheck"/> (reading back from that place, and + /// through this process's own view when it is the client's). + /// - Client virtualized (non-elevated AC, the usual case): the per-user VirtualStore copy, + /// as before (no administrator rights needed). + /// - Client not virtualized (RynthCore/AC run as administrator, UAC off, a manifest, + /// virtualization off by policy): Decal reads the real + /// HKLM\SOFTWARE\(WOW6432Node\)Decal\NetworkFilters, where a per-user entry is + /// invisible. Written directly when this process may; otherwise <see cref="Outcome.NeedsAdmin"/>, + /// and the caller runs <c>--decal-bridge-register-machine</c> elevated (<see cref="RunElevated"/>). + /// Idempotent. Also removes a "downloaded from the internet" mark from the bridge DLL. + /// </summary> + public static Outcome RegisterForClients(string bridgeDirectory, string? acClientPath, string? engineJsonPath, + out string report, out DecalBridgeCheck.Result? check) + { + check = null; + var log = new List<string>(); + string dir; + try { dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\'); } + catch (Exception ex) { report = $"Bad bridge folder '{bridgeDirectory}': {ex.Message}"; return Outcome.Failed; } + + string dll = Path.Combine(dir, AssemblyFile); + if (File.Exists(dll) && File.Exists(dll + ":Zone.Identifier")) + log.Add(RealDecalCheckHost.RemoveZoneIdentifier(dll) + ? "removed the 'downloaded from the internet' mark from the bridge DLL" + : "could not remove the 'downloaded from the internet' mark from the bridge DLL"); + + bool virtualized = RealDecalCheckHost.PredictClientVirtualized(acClientPath, out string why, out _); + bool ok; + string step; + if (virtualized) + { + ok = RegisterPerUser(dir, out step); + } + else + { + Outcome mw = RegisterMachineWide(dir, out step); + if (mw == Outcome.NeedsAdmin) + { + log.Add($"AC reads Decal's filter list for all users on this PC ({why}); adding the bridge there needs administrator rights once."); + report = string.Join(" ", log); + return Outcome.NeedsAdmin; + } + ok = mw == Outcome.Registered; + step = $"({why}) " + step; + } + log.Add(step); + + check = RealDecalCheckHost.Check(dir, acClientPath, engineJsonPath); + log.Add(check.Summary); + report = string.Join(" ", log); + if (!ok) return Outcome.Failed; + if (check.Blocking) return check.NeedsMachineWideRegistration ? Outcome.NeedsAdmin : Outcome.Failed; + return Outcome.Registered; + } + + /// <summary> + /// <see cref="RegisterForClients"/> for Decal's own acclient.exe (PortalPath). False (with + /// the reason) when it needs administrator rights or the check fails. + /// </summary> + public static bool Register(string bridgeDirectory, out string report) => + RegisterForClients(bridgeDirectory, DecalLocator.TryGetDecalAcClientPath(), null, out report, out _) == Outcome.Registered; + + /// <summary> + /// Adds the bridge to the machine-wide list, HKLM\SOFTWARE\(WOW6432Node\)Decal\NetworkFilters + /// (32-bit view). Needs administrator rights: run elevated (--decal-bridge-register-machine). + /// Virtualization is off while it writes, so a non-elevated process gets "access denied" + /// (NeedsAdmin) instead of a silent write into the per-user copy. Idempotent; nothing to mirror + /// (the machine list is the one every other filter is in). + /// </summary> + public static Outcome RegisterMachineWide(string bridgeDirectory, out string report) + { + var log = new List<string>(); + using (RealRegistryView.Enter()) + { + try + { + if (!DecalLocator.IsInstalled()) + { + report = "Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent) - nothing registered."; + return Outcome.Failed; + } + string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\'); + if (!File.Exists(Path.Combine(dir, AssemblyFile))) + { + report = $"{AssemblyFile} not found in {dir} - nothing registered."; + return Outcome.Failed; + } + using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView); + using RegistryKey filters = hklm.CreateSubKey(DecalFiltersSubKey, writable: true); + using (RegistryKey? existing = filters.OpenSubKey(FilterGuid)) + { + if (existing != null && !IsOurs(existing)) + { + report = $"another filter uses the bridge's id {FilterGuid} in the machine-wide list - nothing changed."; + return Outcome.Failed; + } + } + using (RegistryKey entry = filters.CreateSubKey(FilterGuid, writable: true)) + { + SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log); + SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log); + SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log); + SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log); + SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log); + SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log); + } + report = log.Count == 0 + ? $"Decal bridge already registered for all users ({dir}); nothing changed." + : $"Decal bridge registered for all users ({dir}): {string.Join("; ", log)}."; + return Outcome.Registered; + } + catch (Exception ex) when (ex is UnauthorizedAccessException or System.Security.SecurityException) + { + report = "Registering the Decal bridge for all users needs administrator rights."; + return Outcome.NeedsAdmin; + } + catch (Exception ex) + { + report = $"Decal bridge registration for all users failed: {Describe(ex)}"; + return Outcome.Failed; + } + } + } + + /// <summary> + /// The installer's per-user half (installer\RynthCore.iss, run as the installing user on + /// every install and update; the elevated half is <see cref="RegisterMachineWide"/>). + /// Writes our entry into this user's VirtualStore copy of Decal's filter list ONLY when + /// that copy already exists - see <see cref="DecalBridgeCheck.PlanInstall"/> for why both + /// places are written and why a missing copy is never created here. The entry is ours + /// (Object = <see cref="FilterObject"/>), so <see cref="Unregister"/> removes it. + /// </summary> + public static bool InstallPerUser(string bridgeDirectory, out string report) + { + try + { + var plan = RealDecalCheckHost.PlanInstall(); + if (!plan.Machine) + { + report = "Decal is not installed - nothing to do for this user."; + return true; + } + if (!plan.PerUser) + { + report = "This user has no per-user copy of Decal's filter list - the machine-wide entry is the one AC reads; nothing written."; + return true; + } + string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\'); + if (!File.Exists(Path.Combine(dir, AssemblyFile))) + { + report = $"{AssemblyFile} not found in {dir} - nothing written."; + return false; + } + var log = new List<string>(); + using (RealRegistryView.Enter()) + { + using RegistryKey? user = OpenUserFilters(writable: true); + if (user == null) + { + report = "The per-user copy disappeared - nothing written."; + return true; + } + using (RegistryKey? existing = user.OpenSubKey(FilterGuid)) + { + if (existing != null && !IsOurs(existing)) + { + report = $"another filter uses the bridge's id {FilterGuid} in the per-user copy - nothing changed."; + return false; + } + } + using RegistryKey entry = user.CreateSubKey(FilterGuid, writable: true); + SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log); + SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log); + SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log); + SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log); + SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log); + SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log); + } + report = log.Count == 0 + ? $"Decal bridge already in this user's per-user copy ({dir}); nothing changed." + : $"Decal bridge added to this user's existing per-user copy ({dir}): {string.Join("; ", log)}."; + return true; + } + catch (Exception ex) + { + report = $"Per-user Decal bridge entry failed: {Describe(ex)}"; + return false; + } + } + + /// <summary>The machine-wide list holds our entry (the launcher/injector never adds it without being asked).</summary> + public static bool MachineEntryIsOurs() + { + using (RealRegistryView.Enter()) + { + try + { + using RegistryKey? machine = OpenMachineFilters(); + using RegistryKey? m = machine?.OpenSubKey(FilterGuid); + return m != null && IsOurs(m); + } + catch { return false; } + } + } + + /// <summary>Removes our machine-wide entry (only ours). Needs administrator rights.</summary> + public static Outcome UnregisterMachineWide(out string report) + { + using (RealRegistryView.Enter()) + { + try + { + using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView); + using RegistryKey? probe = hklm.OpenSubKey(DecalFiltersSubKey); + using RegistryKey? m = probe?.OpenSubKey(FilterGuid); + if (m == null || !IsOurs(m)) + { + report = "No machine-wide Decal bridge entry; nothing to remove."; + return Outcome.Registered; + } + using RegistryKey filters = hklm.OpenSubKey(DecalFiltersSubKey, writable: true)!; + filters.DeleteSubKeyTree(FilterGuid, throwOnMissingSubKey: false); + report = "Removed the machine-wide Decal bridge entry."; + return Outcome.Registered; + } + catch (Exception ex) when (ex is UnauthorizedAccessException or System.Security.SecurityException) + { + report = "Removing the machine-wide Decal bridge entry needs administrator rights."; + return Outcome.NeedsAdmin; + } + catch (Exception ex) + { + report = $"Removing the machine-wide Decal bridge entry failed: {Describe(ex)}"; + return Outcome.Failed; + } + } + } + + /// <summary> + /// Runs <paramref name="exePath"/> elevated (Windows shows its administrator prompt) and + /// waits for it. NeedsAdmin when the person said no at the prompt. + /// </summary> + public static Outcome RunElevated(string exePath, string arguments, out string report) + { + try + { + var psi = new System.Diagnostics.ProcessStartInfo(exePath, arguments) + { + UseShellExecute = true, + Verb = "runas", + WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, + }; + using System.Diagnostics.Process? p = System.Diagnostics.Process.Start(psi); + if (p == null) + { + report = "Windows did not start the administrator step."; + return Outcome.Failed; + } + if (!p.WaitForExit(120_000)) + { + report = "The administrator step did not finish within 2 minutes."; + return Outcome.Failed; + } + report = p.ExitCode == 0 ? "The administrator step finished." : $"The administrator step failed (exit code {p.ExitCode})."; + return p.ExitCode == 0 ? Outcome.Registered : Outcome.Failed; + } + catch (System.ComponentModel.Win32Exception ex) when (ex.NativeErrorCode == 1223) + { + report = "Cancelled at the Windows administrator prompt."; + return Outcome.NeedsAdmin; + } + catch (Exception ex) + { + report = $"Could not start the administrator step: {ex.Message}"; + return Outcome.Failed; + } + } + + /// <summary> + /// Makes Decal clients of this user load the bridge from <paramref name="bridgeDirectory"/> + /// through the per-user VirtualStore copy (virtualized clients only: see + /// <see cref="RegisterForClients"/>). Idempotent. Returns false (with the reason in + /// <paramref name="report"/>) when Decal isn't installed or the bridge DLL isn't there. + /// </summary> + public static bool RegisterPerUser(string bridgeDirectory, out string report) + { + using (RealRegistryView.Enter()) return RegisterCore(bridgeDirectory, out report); + } + + private static bool RegisterCore(string bridgeDirectory, out string report) + { + var log = new List<string>(); + try + { + if (!DecalLocator.IsInstalled()) + { + report = "Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent) - nothing registered."; + return false; + } + string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\'); + if (!File.Exists(Path.Combine(dir, AssemblyFile))) + { + report = $"{AssemblyFile} not found in {dir} - nothing registered."; + return false; + } + + State state = LoadState() ?? new State(); + using RegistryKey? machine = OpenMachineFilters(); + using RegistryKey? existingUser = OpenUserFilters(writable: true); + if (existingUser == null && state.CreatedFiltersKey) + { + // Someone removed the key we created; start the record over. + state = new State(); + } + + RegistryKey? user = existingUser; + try + { + if (user == null) + { + // No per-user list yet. If an administrator already registered the bridge in + // HKLM with this path, clients see it without us creating anything. + using (RegistryKey? m = machine?.OpenSubKey(FilterGuid)) + { + if (m != null && IsOurs(m) && Enabled(m) && + string.Equals((m.GetValue("Path") as string)?.TrimEnd('\\'), dir, StringComparison.OrdinalIgnoreCase)) + { + report = "Already registered machine-wide (HKLM) with this path; nothing changed."; + return true; + } + } + user = UserHive().CreateSubKey(VirtualStoreFiltersSubKey, writable: true); + state.CreatedFiltersKey = true; + log.Add($"created HKCU\\{VirtualStoreFiltersSubKey}"); + } + + if (state.CreatedFiltersKey && machine != null) + SyncMirror(machine, user, state, log); + + using (RegistryKey entry = user.CreateSubKey(FilterGuid, writable: true)) + { + SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log); + SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log); + SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log); + SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log); + SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log); + SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log); + } + } + finally + { + if (!ReferenceEquals(user, existingUser)) user?.Dispose(); + } + + state.BridgePath = dir; + state.RegisteredUtc = DateTime.UtcNow; + SaveState(state); + report = log.Count == 0 + ? $"Decal bridge already registered for this user ({dir}); nothing changed." + : $"Decal bridge registered for this user ({dir}): {string.Join("; ", log)}."; + return true; + } + catch (Exception ex) + { + report = $"Decal bridge registration failed: {ex.GetType().Name}: {ex.Message}" + + (log.Count > 0 ? $" (done before the failure: {string.Join("; ", log)})" : ""); + return false; + } + } + + /// <summary> + /// Removes what <see cref="Register"/> added: the bridge's entry, the mirrored copies of + /// HKLM filters, and the per-user key if this class created it and nothing foreign is + /// left in it. A mirrored copy that changed since (Decal plugins write to "HKLM" through + /// UAC virtualization, so their writes land in our per-user copy) is removed as well when + /// RynthCore created the key: HKLM still holds the original, and a per-user list left with + /// a few entries would hide every other HKLM filter from Decal clients (VTank then has no + /// WorldFilter). Anything RynthCore didn't add is left in place and reported, and the + /// record (%APPDATA%\RynthCore\decal-bridge-registration.json) is kept until nothing of + /// ours remains, so a later unregister can finish the job. + /// </summary> + public static bool Unregister(out string report) + { + using (RealRegistryView.Enter()) return UnregisterCore(out report); + } + + private static bool UnregisterCore(out string report) + { + var log = new List<string>(); + var failed = new List<string>(); + try + { + State? state = LoadState(); + bool done = true; + using RegistryKey? user = OpenUserFilters(writable: true); + if (user != null) + { + foreach (string name in user.GetSubKeyNames()) + { + try + { + bool ours; + using (RegistryKey? k = user.OpenSubKey(name)) + ours = k != null && IsOurs(k); + if (!ours) continue; + user.DeleteSubKeyTree(name, throwOnMissingSubKey: false); + log.Add($"removed bridge entry {name}"); + } + catch (Exception ex) { failed.Add($"{name}: {Describe(ex)}"); } + } + + if (state?.CreatedFiltersKey == true) + { + int same = 0, changed = 0; + foreach (KeyValuePair<string, string> kv in state.MirroredKeys) + { + try + { + bool unchanged; + using (RegistryKey? k = user.OpenSubKey(kv.Key)) + { + if (k == null) continue; + unchanged = Fingerprint(k) == kv.Value; + } + user.DeleteSubKeyTree(kv.Key, throwOnMissingSubKey: false); + if (unchanged) same++; else changed++; + } + catch (Exception ex) { failed.Add($"{kv.Key}: {Describe(ex)}"); } + } + foreach (KeyValuePair<string, string> kv in state.MirroredValues) + { + try { user.DeleteValue(kv.Key, throwOnMissingValue: false); } + catch (Exception ex) { failed.Add($"value {kv.Key}: {Describe(ex)}"); } + } + log.Add($"removed {same + changed} mirrored filter entr{(same + changed == 1 ? "y" : "ies")}" + + (changed > 0 ? $" ({changed} changed by Decal plugins since; HKLM keeps the originals)" : "")); + + var foreign = new List<string>(); + foreach (string n in user.GetSubKeyNames()) foreign.Add(n); + foreach (string n in user.GetValueNames()) if (n.Length > 0) foreign.Add(n); + if (foreign.Count == 0 && failed.Count == 0) + { + user.Dispose(); + UserHive().DeleteSubKey(VirtualStoreFiltersSubKey, throwOnMissingSubKey: false); + log.Add($"removed HKCU\\{VirtualStoreFiltersSubKey} (created by RynthCore)"); + } + else + { + done = false; + log.Add($"left HKCU\\{VirtualStoreFiltersSubKey} in place" + + (foreign.Count > 0 ? $": it holds entries RynthCore didn't add ({string.Join(", ", foreign)})" : "")); + } + } + } + + if (failed.Count > 0) + done = false; + if (done && File.Exists(StatePath)) + File.Delete(StatePath); + else if (!done) + log.Add($"kept {StatePath} for the next unregister"); + if (failed.Count > 0) + { + report = $"Decal bridge unregistration incomplete: {string.Join("; ", failed)}" + + (log.Count > 0 ? $" (done: {string.Join("; ", log)})" : ""); + return false; + } + report = log.Count == 0 ? "Decal bridge was not registered for this user; nothing to remove." : string.Join("; ", log) + "."; + return true; + } + catch (Exception ex) + { + report = $"Decal bridge unregistration failed: {Describe(ex)}" + + (log.Count > 0 ? $" (done before the failure: {string.Join("; ", log)})" : ""); + return false; + } + } + + // Exception type, message and the innermost frame, for a one-line report. + private static string Describe(Exception ex) + { + string? frame = ex.StackTrace?.Split('\n').Select(l => l.Trim()).FirstOrDefault(l => l.Length > 0); + return $"{ex.GetType().Name}: {ex.Message}" + (frame != null ? $" [{frame}]" : ""); + } + + // ── mirror ─────────────────────────────────────────────────────────────── + + // Copies HKLM entries the per-user list lacks, and refreshes copies nobody changed + // since we wrote them (so a filter the user enables/disables machine-wide follows). + private static void SyncMirror(RegistryKey machine, RegistryKey user, State state, List<string> log) + { + int added = 0, refreshed = 0; + foreach (string name in machine.GetValueNames()) + { + if (name.Length == 0) continue; + object? v = machine.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames); + if (v == null) continue; + RegistryValueKind kind = machine.GetValueKind(name); + object? have = user.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames); + bool ours = state.MirroredValues.TryGetValue(name, out string? print); + if (have == null || (ours && ValuePrint(user.GetValueKind(name), have) == print)) + { + user.SetValue(name, v, kind); + state.MirroredValues[name] = ValuePrint(kind, v); + } + } + foreach (string name in machine.GetSubKeyNames()) + { + if (string.Equals(name, FilterGuid, StringComparison.OrdinalIgnoreCase)) continue; + using RegistryKey? src = machine.OpenSubKey(name); + if (src == null) continue; + string srcPrint = Fingerprint(src); + using RegistryKey? existing = user.OpenSubKey(name); + if (existing == null) + { + using RegistryKey dst = user.CreateSubKey(name, writable: true); + CopyTree(src, dst); + state.MirroredKeys[name] = Fingerprint(dst); + added++; + } + else if (state.MirroredKeys.TryGetValue(name, out string? written) && + Fingerprint(existing) == written && srcPrint != written) + { + existing.Dispose(); + user.DeleteSubKeyTree(name, throwOnMissingSubKey: false); + using RegistryKey dst = user.CreateSubKey(name, writable: true); + CopyTree(src, dst); + state.MirroredKeys[name] = Fingerprint(dst); + refreshed++; + } + } + if (added > 0) log.Add($"mirrored {added} HKLM filter entr{(added == 1 ? "y" : "ies")} (so Decal still sees them)"); + if (refreshed > 0) log.Add($"refreshed {refreshed} mirrored entr{(refreshed == 1 ? "y" : "ies")} from HKLM"); + } + + private static void CopyTree(RegistryKey src, RegistryKey dst) + { + foreach (string name in src.GetValueNames()) + { + object? v = src.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames); + if (v != null) dst.SetValue(name, v, src.GetValueKind(name)); + } + foreach (string sub in src.GetSubKeyNames()) + { + using RegistryKey? s = src.OpenSubKey(sub); + if (s == null) continue; + using RegistryKey d = dst.CreateSubKey(sub, writable: true); + CopyTree(s, d); + } + } + + /// <summary>A stable text form of a key's values and subkeys, to tell "still as we wrote it".</summary> + private static string Fingerprint(RegistryKey key) + { + var sb = new StringBuilder(); + foreach (string name in key.GetValueNames().OrderBy(n => n, StringComparer.OrdinalIgnoreCase)) + { + object? v = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames); + if (v == null) continue; + RegistryValueKind kind; + try { kind = key.GetValueKind(name); } + catch (IOException) { continue; } // removed between the listing and the read + sb.Append(name.ToLowerInvariant()).Append('=').Append(ValuePrint(kind, v)).Append(';'); + } + foreach (string sub in key.GetSubKeyNames().OrderBy(n => n, StringComparer.OrdinalIgnoreCase)) + { + using RegistryKey? s = key.OpenSubKey(sub); + if (s != null) sb.Append('[').Append(sub.ToLowerInvariant()).Append(':').Append(Fingerprint(s)).Append(']'); + } + return sb.ToString(); + } + + private static string ValuePrint(RegistryValueKind kind, object v) => kind + ":" + v switch + { + byte[] b => Convert.ToHexString(b), + string[] a => string.Join("\u0001", a), + _ => Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty, + }; + + // ── registry helpers ───────────────────────────────────────────────────── + + private static RegistryKey UserHive() => RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, + Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Default); + + private static RegistryKey? OpenUserFilters(bool writable) => UserHive().OpenSubKey(VirtualStoreFiltersSubKey, writable); + + private static RegistryKey? OpenMachineFilters() => + RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView).OpenSubKey(DecalFiltersSubKey); + + private static bool IsOurs(RegistryKey k) => + string.Equals(k.GetValue("Object") as string, FilterObject, StringComparison.Ordinal); + + private static bool Enabled(RegistryKey k) => k.GetValue("Enabled") is int e && e != 0; + + private static void ReadEntry(RegistryKey k, Status s) + { + s.Enabled = Enabled(k); + s.RegisteredPath = k.GetValue("Path") as string; + s.DllPresent = s.RegisteredPath != null && File.Exists(Path.Combine(s.RegisteredPath, AssemblyFile)); + } + + private static string DescribeFilter(RegistryKey parent, string name) + { + using RegistryKey? k = parent.OpenSubKey(name); + return k?.GetValue("") is string friendly && friendly.Length > 0 ? friendly : name; + } + + private static void SetIfDifferent(RegistryKey key, string name, object value, RegistryValueKind kind, List<string> log) + { + object? have = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames); + if (have != null && key.GetValueKind(name) == kind && Equals(have, value)) + return; + key.SetValue(name, value, kind); + log.Add($"set {(name.Length == 0 ? "(default)" : name)}"); + } + + private static State? LoadState() + { + try + { + if (!File.Exists(StatePath)) return null; + State? s = JsonSerializer.Deserialize<State>(File.ReadAllText(StatePath)); + if (s == null) return null; + // Dictionary comparers don't survive serialization. + s.MirroredKeys = new Dictionary<string, string>(s.MirroredKeys, StringComparer.OrdinalIgnoreCase); + s.MirroredValues = new Dictionary<string, string>(s.MirroredValues, StringComparer.OrdinalIgnoreCase); + return s; + } + catch + { + return null; + } + } + + private static void SaveState(State s) + { + string? dir = Path.GetDirectoryName(StatePath); + if (dir != null) Directory.CreateDirectory(dir); + File.WriteAllText(StatePath, JsonSerializer.Serialize(s, new JsonSerializerOptions { WriteIndented = true })); + } +} diff --git a/src/RynthCore.App/InjectionMode.cs b/src/RynthCore.App/InjectionMode.cs index 05e7ae2..b91714a 100644 --- a/src/RynthCore.App/InjectionMode.cs +++ b/src/RynthCore.App/InjectionMode.cs @@ -14,4 +14,10 @@ internal enum InjectionMode /// account runs against Decal + UBService + VTank or whatever Decal plugins /// the user has registered.</summary> Decal = 1, + + /// <summary>Decal first, then RynthCore in the same client ("Decal + RynthCore"). The + /// engine takes chat from Decal through the RynthCore Decal bridge, which the launcher + /// registers for this Windows user before the launch (DecalBridgeRegistration; + /// docs/DECAL_BRIDGE_PLAN.md).</summary> + DecalBridge = 2, } diff --git a/src/RynthCore.App/LaunchAccountProfile.cs b/src/RynthCore.App/LaunchAccountProfile.cs index ac75d6b..c66b3ce 100644 --- a/src/RynthCore.App/LaunchAccountProfile.cs +++ b/src/RynthCore.App/LaunchAccountProfile.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; namespace RynthCore.App; @@ -12,7 +13,26 @@ internal sealed class LaunchAccountProfile public string Id { get; set; } = Guid.NewGuid().ToString("N"); public string AccountName { get; set; } = string.Empty; - public string Password { get; set; } = string.Empty; + + /// The saved password, DPAPI-encrypted for the current Windows user (base64, see + /// AccountPasswordProtection). Empty = no password saved. Decrypt only when launching: + /// TryGetPasswordForLaunch. + public string PasswordProtected { get; set; } = string.Empty; + + /// Plain-text "Password" from a settings file written before passwords were encrypted. + /// Read only: AppSettingsStore.Load encrypts it into PasswordProtected and clears this, so it + /// is never written again (null is skipped on save). Stays set only if encryption failed. + [JsonPropertyName("Password")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? LegacyPlainPassword { get; set; } + + /// Set when the saved password can't be decrypted on this Windows user (settings copied + /// from another user or PC). The UI asks for the password again; launching is refused. + [JsonIgnore] + public bool PasswordNeedsReentry { get; set; } + + [JsonIgnore] + public bool HasSavedPassword => !string.IsNullOrEmpty(PasswordProtected) || !string.IsNullOrEmpty(LegacyPlainPassword); public string CharacterName { get; set; } = string.Empty; public string Alias { get; set; } = string.Empty; public string ServerId { get; set; } = string.Empty; @@ -65,7 +85,9 @@ internal sealed class LaunchAccountProfile { Id = Id, AccountName = AccountName, - Password = Password, + PasswordProtected = PasswordProtected, + LegacyPlainPassword = LegacyPlainPassword, + PasswordNeedsReentry = PasswordNeedsReentry, CharacterName = CharacterName, Alias = Alias, ServerId = ServerId, @@ -84,7 +106,9 @@ internal sealed class LaunchAccountProfile { Id = source.Id; AccountName = source.AccountName; - Password = source.Password; + PasswordProtected = source.PasswordProtected; + LegacyPlainPassword = source.LegacyPlainPassword; + PasswordNeedsReentry = source.PasswordNeedsReentry; CharacterName = source.CharacterName; Alias = source.Alias; ServerId = source.ServerId; @@ -98,6 +122,55 @@ internal sealed class LaunchAccountProfile OnLoginWaitMs = source.OnLoginWaitMs; } + /// <summary>Saves a new password (encrypted at once; the plain text is not kept).</summary> + public void SetPassword(string? plainText) + { + PasswordProtected = AccountPasswordProtection.Protect(plainText); + LegacyPlainPassword = null; + PasswordNeedsReentry = false; + } + + public void ClearPassword() + { + PasswordProtected = string.Empty; + LegacyPlainPassword = null; + PasswordNeedsReentry = false; + } + + /// <summary> + /// The password to hand the client, decrypted now. True with "" when none is saved. False + /// (and PasswordNeedsReentry set) when the saved one can't be decrypted on this Windows user; + /// the caller must not launch with an empty password instead. Use the result at once and + /// don't store it. + /// </summary> + public bool TryGetPasswordForLaunch(out string password, out string problem) + { + problem = string.Empty; + if (!string.IsNullOrEmpty(LegacyPlainPassword)) + { + password = LegacyPlainPassword; + return true; + } + if (string.IsNullOrEmpty(PasswordProtected)) + { + password = string.Empty; + return true; + } + if (AccountPasswordProtection.TryUnprotect(PasswordProtected, out password)) + { + PasswordNeedsReentry = false; + return true; + } + + PasswordNeedsReentry = true; + problem = PasswordNeedsReentryMessage(AccountName); + return false; + } + + public static string PasswordNeedsReentryMessage(string? accountName) => + $"The saved password for account '{accountName}' can't be read on this Windows user " + + "(settings copied from another user or PC?). Password needs re-entering: edit the account and type it again."; + public override string ToString() { return DisplayName; diff --git a/src/RynthCore.App/RealDecalCheckHost.cs b/src/RynthCore.App/RealDecalCheckHost.cs new file mode 100644 index 0000000..e0755d5 --- /dev/null +++ b/src/RynthCore.App/RealDecalCheckHost.cs @@ -0,0 +1,274 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.Win32; + +namespace RynthCore.App; + +/// <summary>A registry key copied into memory (also the tests' fake key).</summary> +internal sealed class RegSnapshot : IRegKey +{ + public Dictionary<string, object> Values { get; } = new(StringComparer.OrdinalIgnoreCase); + public List<string> SubKeys { get; } = new(); + + public object? GetValue(string name) => Values.TryGetValue(name, out object? v) ? v : null; + public string[] GetSubKeyNames() => SubKeys.ToArray(); + public string[] GetValueNames() => new List<string>(Values.Keys).ToArray(); + public void Dispose() { } + + public static RegSnapshot? Of(RegistryKey? key) + { + if (key == null) return null; + var s = new RegSnapshot(); + foreach (string n in key.GetValueNames()) + { + object? v = key.GetValue(n, null, RegistryValueOptions.DoNotExpandEnvironmentNames); + if (v != null) s.Values[n] = v; + } + s.SubKeys.AddRange(key.GetSubKeyNames()); + return s; + } +} + +/// <summary>The real machine for <see cref="DecalBridgeCheck"/>.</summary> +internal sealed class RealDecalCheckHost : IDecalCheckHost +{ + private const int TokenElevation = 20, TokenVirtualizationEnabled = 24; + private static readonly string BridgeEntryMachinePath = + DecalBridgeCheck.MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid; + + private readonly RegSnapshot? _ownViewBridgeEntry; + private readonly Dictionary<string, string?> _levels = new(StringComparer.OrdinalIgnoreCase); + + public bool Is64BitOs => Environment.Is64BitOperatingSystem; + public bool LauncherElevated { get; } + public bool LauncherVirtualized { get; } + + /// <summary>Construct OUTSIDE a <see cref="RealRegistryView"/> scope: it reads the process's own view.</summary> + private RealDecalCheckHost() + { + LauncherElevated = TokenFlag(TokenElevation); + LauncherVirtualized = TokenFlag(TokenVirtualizationEnabled); + try + { + using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default); + using RegistryKey? k = hklm.OpenSubKey(BridgeEntryMachinePath); + _ownViewBridgeEntry = RegSnapshot.Of(k); + } + catch { _ownViewBridgeEntry = null; } + } + + /// <summary>Runs the check against this machine. Reads only.</summary> + public static DecalBridgeCheck.Result Check(string bridgeDirectory, string? acClientPath, string? engineJsonPath) + { + var host = new RealDecalCheckHost(); + using (RealRegistryView.Enter()) + return DecalBridgeCheck.Run(host, bridgeDirectory, acClientPath, engineJsonPath); + } + + /// <summary>Only the client-virtualization prediction (registration uses it to pick the key).</summary> + public static bool PredictClientVirtualized(string? acClientPath, out string reason, out bool launcherElevated) + { + var host = new RealDecalCheckHost(); + launcherElevated = host.LauncherElevated; + using (RealRegistryView.Enter()) + return DecalBridgeCheck.PredictClientVirtualized(host, acClientPath, out reason); + } + + public static bool IsProcessElevated() => TokenFlag(TokenElevation); + + /// <summary><see cref="DecalBridgeCheck.PlanInstall"/> on this machine.</summary> + public static (bool Machine, bool PerUser) PlanInstall() + { + var host = new RealDecalCheckHost(); + using (RealRegistryView.Enter()) + return DecalBridgeCheck.PlanInstall(host); + } + + public IRegKey? OpenReal(RegRoot root, string subKey) + { + try + { + (RegistryHive hive, RegistryView view) = root switch + { + RegRoot.Machine32 => (RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default), + RegRoot.Machine64 => (RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry64 : RegistryView.Default), + RegRoot.User32 => (RegistryHive.CurrentUser, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default), + _ => (RegistryHive.CurrentUser, Is64BitOs ? RegistryView.Registry64 : RegistryView.Default), + }; + using RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, view); + using RegistryKey? k = baseKey.OpenSubKey(subKey); + return RegSnapshot.Of(k); + } + catch + { + return null; + } + } + + public IRegKey? OpenOwnViewMachine32(string subKey) => + string.Equals(subKey, BridgeEntryMachinePath, StringComparison.OrdinalIgnoreCase) ? _ownViewBridgeEntry : null; + + public bool FileExists(string path) + { + try { return File.Exists(path); } catch { return false; } + } + + public bool HasZoneIdentifier(string path) + { + try { return File.Exists(path + ":Zone.Identifier"); } catch { return false; } + } + + /// <summary>Removes the "downloaded from the internet" mark. True if none is left.</summary> + public static bool RemoveZoneIdentifier(string path) + { + try + { + string ads = path + ":Zone.Identifier"; + if (File.Exists(ads)) File.Delete(ads); + return !File.Exists(ads); + } + catch { return false; } + } + + public Version? AssemblyVersionOf(string path) + { + try { return AssemblyName.GetAssemblyName(path).Version; } catch { return null; } + } + + public Version? ReferenceVersionOf(string assemblyPath, string referenceName) + { + try + { + using FileStream fs = File.OpenRead(assemblyPath); + using var pe = new PEReader(fs); + if (!pe.HasMetadata) return null; + MetadataReader md = pe.GetMetadataReader(); + foreach (AssemblyReferenceHandle h in md.AssemblyReferences) + { + AssemblyReference r = md.GetAssemblyReference(h); + if (string.Equals(md.GetString(r.Name), referenceName, StringComparison.OrdinalIgnoreCase)) + return r.Version; + } + } + catch { } + return null; + } + + public string? ExecutionLevelOf(string exePath) + { + if (_levels.TryGetValue(exePath, out string? cached)) return cached; + string? level = null; + try + { + if (File.Exists(exePath)) + level = LevelIn(Encoding.UTF8.GetString(File.ReadAllBytes(exePath))); + // An external manifest counts only when the exe has none embedded. + if (level == null && File.Exists(exePath + ".manifest")) + level = LevelIn(File.ReadAllText(exePath + ".manifest")); + } + catch { } + _levels[exePath] = level; + return level; + } + + /// <summary>The level="..." of a requestedExecutionLevel element, or null.</summary> + internal static string? LevelIn(string text) + { + int i = text.IndexOf("requestedExecutionLevel", StringComparison.Ordinal); + if (i < 0) return null; + int end = text.IndexOf('>', i); + string element = end > i ? text.Substring(i, end - i) : text.Substring(i, Math.Min(200, text.Length - i)); + int l = element.IndexOf("level=", StringComparison.Ordinal); + if (l < 0) return null; + int q = l + 6; + if (q >= element.Length) return null; + char quote = element[q]; + int close = element.IndexOf(quote, q + 1); + return close > q ? element.Substring(q + 1, close - q - 1) : null; + } + + public string? ReadTextFile(string path) + { + try { return File.Exists(path) ? File.ReadAllText(path) : null; } catch { return null; } + } + + private static bool TokenFlag(int infoClass) + { + try + { + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out IntPtr token)) return false; + try + { + int v = 0; + return GetTokenInformation(token, infoClass, ref v, sizeof(int), out _) && v != 0; + } + finally { CloseHandle(token); } + } + catch { return false; } + } + + private const uint TOKEN_QUERY = 0x0008; + [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess(); + [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle); + [DllImport("advapi32.dll", SetLastError = true)] private static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token); + [DllImport("advapi32.dll", SetLastError = true)] private static extern bool GetTokenInformation(IntPtr token, int infoClass, ref int info, int length, out int returned); +} + +/// <summary> +/// The launcher has no requestedExecutionLevel in its manifest, so Windows runs it with UAC +/// registry virtualization: its HKLM reads return the per-user VirtualStore copy where one +/// exists, and its HKLM writes land there silently (measured 2026-09-30). Registration and +/// the check have to see (and write) the real HKLM and the real per-user copy, so +/// virtualization is switched off for this process while they run and switched back on +/// after. A process without virtualization (the injector, an elevated launcher) is left alone. +/// </summary> +internal sealed class RealRegistryView : IDisposable +{ + private const int TokenVirtualizationEnabled = 24; + private const uint TOKEN_QUERY = 0x0008, TOKEN_ADJUST_DEFAULT = 0x0080; + private IntPtr _token; + + public static IDisposable Enter() + { + var scope = new RealRegistryView(); + try + { + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_DEFAULT, out IntPtr token)) + return scope; + int on = 0; + if (GetTokenInformation(token, TokenVirtualizationEnabled, ref on, sizeof(int), out _) && on != 0) + { + int off = 0; + if (SetTokenInformation(token, TokenVirtualizationEnabled, ref off, sizeof(int))) + { + scope._token = token; // restored in Dispose + return scope; + } + } + CloseHandle(token); + } + catch { } + return scope; + } + + public void Dispose() + { + if (_token == IntPtr.Zero) return; + int on = 1; + SetTokenInformation(_token, TokenVirtualizationEnabled, ref on, sizeof(int)); + CloseHandle(_token); + _token = IntPtr.Zero; + } + + [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess(); + [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle); + [DllImport("advapi32.dll", SetLastError = true)] private static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token); + [DllImport("advapi32.dll", SetLastError = true)] private static extern bool GetTokenInformation(IntPtr token, int infoClass, ref int info, int length, out int returned); + [DllImport("advapi32.dll", SetLastError = true)] private static extern bool SetTokenInformation(IntPtr token, int infoClass, ref int info, int length); +} diff --git a/src/RynthCore.DecalBridge/BridgeFilter.cs b/src/RynthCore.DecalBridge/BridgeFilter.cs new file mode 100644 index 0000000..22bd5a0 --- /dev/null +++ b/src/RynthCore.DecalBridge/BridgeFilter.cs @@ -0,0 +1,394 @@ +// ============================================================================ +// RynthCore.DecalBridge - BridgeFilter.cs +// +// A Decal network filter written only against Decal's PUBLIC plugin API +// (Decal.Adapter: FilterBase, CoreManager, WorldFilter, CharacterFilter, HooksWrapper). +// It lets the RynthCore engine run in the same acclient.exe as Decal without the two +// patching the same AC functions ("bridge mode", docs/DECAL_BRIDGE_PLAN.md): +// +// events -> engine: chat lines, chat-bar commands (and eats the engine's own +// commands), login/logoff; optionally object create/release/change and +// raw server messages. The engine says which kinds it wants (want mask). +// commands <- engine: run on AC's main thread through Decal's public API - chat lines +// (InvokeChatParser) and the salvage panel (SalvagePanelAdd/Salvage). +// +// A network filter (not a plugin) so it starts with Decal, before login. +// +// Idle unless RynthCore is in the same client: registering it (the launcher does, for +// "Decal + RynthCore" accounts) makes every Decal client of that Windows user load it, +// but until the RynthCore loader shows up in the process it only counts frames. It never +// blocks, never throws into Decal, and holds nothing of the engine's. +// RYNTHCORE_DECAL_BRIDGE=0 in a client's environment keeps it off entirely. +// ============================================================================ +using System; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using Decal.Adapter; +using Decal.Adapter.Wrappers; + +namespace RynthCore.DecalBridge +{ + [FriendlyName("RynthCore Decal Bridge")] + public sealed unsafe class BridgeFilter : FilterBase + { + private const string LogDir = @"C:\Games\RynthCore\Logs"; + private const string LoaderModule = "RynthCore.Loader.dll"; + private const int ArmCheckEveryFrames = 120; // ~2 s at 60 fps + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr GetModuleHandleW(string name); + + private BridgeChannel _ch; + private int _pid; + private bool _disabled; + private bool _worldWired; + private bool _invoking; // true while a command of ours runs InvokeChatParser + private int _frames; + private string[] _prefixes = new string[0]; + private int _prefixStamp = -1; + private long _serverMessages; + private int _loggedServer; + private int _loggedChatBar; + private bool _devicePublished; + + protected override void Startup() + { + _pid = Process.GetCurrentProcess().Id; + if (Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_BRIDGE") == "0") + { + _disabled = true; + return; + } + try + { + Core.RenderFrame += OnRenderFrame; + TryArm(); + } + catch (Exception ex) + { + Log("startup failed: " + ex); + } + } + + protected override void Shutdown() + { + if (_disabled) + return; + try + { + Core.RenderFrame -= OnRenderFrame; + if (_ch != null) + { + ServerDispatch -= OnServerDispatch; + Core.ChatBoxMessage -= OnChatBoxMessage; + Core.CommandLineText -= OnCommandLineText; + Core.ItemSelected -= OnItemSelected; + Core.FilterInitComplete -= OnFilterInitComplete; + Core.PluginInitComplete -= OnFilterInitComplete; + } + if (_worldWired) + { + Core.WorldFilter.CreateObject -= OnCreateObject; + Core.WorldFilter.ReleaseObject -= OnReleaseObject; + Core.WorldFilter.ChangeObject -= OnChangeObject; + Core.CharacterFilter.LoginComplete -= OnLoginComplete; + Core.CharacterFilter.Logoff -= OnLogoff; + } + } + catch { } + if (_ch != null) + { + Log("shutdown after " + _serverMessages + " server messages, " + + _ch.ReadLong(BridgeLayout.OffRecords) + " records, " + _ch.ReadLong(BridgeLayout.OffDropped) + " dropped, " + + _ch.ReadLong(BridgeLayout.OffCmdDone) + " commands run"); + _ch.WriteInt(BridgeLayout.OffBridgeState, 0); + _ch.Dispose(); + _ch = null; + } + } + + // Arms once the RynthCore loader is in this client (injected with Decal, or later). + private void TryArm() + { + if (_ch != null || GetModuleHandleW(LoaderModule) == IntPtr.Zero) + return; + BridgeChannel ch = BridgeChannel.OpenOrCreate(_pid); + if (!ch.Valid) + { + Log("mapping has another protocol version (magic 0x" + ch.ReadInt(BridgeLayout.OffMagic).ToString("X8") + + ", version " + ch.ReadInt(BridgeLayout.OffVersion) + ", ours " + BridgeLayout.Version + + ") - the engine and the bridge are from different builds; staying idle."); + ch.Dispose(); + _disabled = true; + return; + } + _ch = ch; + _ch.WriteInt(BridgeLayout.OffBridgePid, _pid); + _ch.WriteString(BridgeRecordKind.Hello, BridgeLayout.Version, 0, + "RynthCore Decal Bridge " + typeof(BridgeFilter).Assembly.GetName().Version + " on " + + Environment.Version + " (" + (IntPtr.Size * 8) + "-bit)"); + ServerDispatch += OnServerDispatch; + Core.ChatBoxMessage += OnChatBoxMessage; + Core.CommandLineText += OnCommandLineText; + Core.ItemSelected += OnItemSelected; + // WorldFilter / CharacterFilter exist once Decal's filters are up. + Core.FilterInitComplete += OnFilterInitComplete; + Core.PluginInitComplete += OnFilterInitComplete; + TryWireWorld(); + _ch.WriteInt(BridgeLayout.OffBridgeState, 1); // the engine waits for this + Log("armed (RynthCore is in this client); mapping " + BridgeLayout.MappingName(_pid) + ", world wired=" + _worldWired); + } + + private void OnFilterInitComplete(object sender, EventArgs e) + { + TryWireWorld(); + } + + private void TryWireWorld() + { + if (_worldWired) return; + try + { + WorldFilter wf = Core.WorldFilter; + CharacterFilter cf = Core.CharacterFilter; + if (wf == null || cf == null) return; + wf.CreateObject += OnCreateObject; + wf.ReleaseObject += OnReleaseObject; + wf.ChangeObject += OnChangeObject; + cf.LoginComplete += OnLoginComplete; + cf.Logoff += OnLogoff; + _worldWired = true; + Log("WorldFilter and CharacterFilter wired (Decal's world filters are up)."); + } + catch (Exception ex) + { + Log("wiring WorldFilter failed: " + ex.Message); + } + } + + // ── once per frame, AC's main thread ───────────────────────────────── + private void OnRenderFrame(object sender, EventArgs e) + { + try + { + if (_disabled) + return; + if (_ch == null) + { + if (++_frames % ArmCheckEveryFrames == 0) + TryArm(); + return; + } + if (!_devicePublished) + PublishDevice(); + if (_ch.HasCommands) + _ch.DrainCommands(RunCommand, 64); + ServeReplay(); + } + catch (Exception ex) + { + Log("frame handler failed: " + ex.Message); + } + } + + // The device Decal renders with, through Decal's public IDecalCore.GetD3DDevice: an + // address for the engine to read (its vtable says whether Decal wraps AC's device). + // No reference is kept and nothing is called on it here. + private void PublishDevice() + { + _devicePublished = true; + try + { + Guid iid = new Guid("D0223B96-BF7A-43FD-92BD-A43B0D82B9EB"); // IID_IDirect3DDevice9 + object dev = Core.Decal.Underlying.GetD3DDevice(ref iid); + if (dev == null) { Log("GetD3DDevice returned null"); return; } + IntPtr unk = Marshal.GetIUnknownForObject(dev); + IntPtr d3d; + int hr = Marshal.QueryInterface(unk, ref iid, out d3d); + if (hr >= 0 && d3d != IntPtr.Zero) + { + _ch.WriteInt(BridgeLayout.OffD3DDevice, d3d.ToInt32()); + Marshal.Release(d3d); + } + Marshal.Release(unk); + Marshal.ReleaseComObject(dev); + _ch.WriteInt(BridgeLayout.OffDecalHwnd, Core.Decal.Hwnd.ToInt32()); + Log("Decal's D3D device 0x" + _ch.ReadInt(BridgeLayout.OffD3DDevice).ToString("X8") + " (QI hr=0x" + hr.ToString("X8") + + "), hwnd 0x" + Core.Decal.Hwnd.ToInt32().ToString("X")); + } + catch (Exception ex) + { + Log("GetD3DDevice failed: " + ex.GetType().Name + ": " + ex.Message); + } + } + + // An engine generation that takes objects from the bridge starts with none (a hot + // reload, or an engine injected late): it bumps the replay request. + private void ServeReplay() + { + int want = _ch.ReadInt(BridgeLayout.OffReplayRequest); + if (want == 0 || want == _ch.ReadInt(BridgeLayout.OffReplayDone) || !_worldWired) + return; + int n = 0; + if (_ch.Wants(BridgeRecordKind.CreateObject)) + { + foreach (WorldObject o in Core.WorldFilter.GetAll()) + { + _ch.Write(BridgeRecordKind.CreateObject, unchecked((uint)o.Id), 1, null, 0); + n++; + } + } + _ch.WriteInt(BridgeLayout.OffReplayDone, want); + Log("replayed " + n + " world objects for engine request " + want); + } + + private void RunCommand(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int len) + { + string failure = null; + try + { + switch (kind) + { + case BridgeRecordKind.CmdInvokeChatParser: + string line = len >= 2 ? new string((char*)payload, 0, len / 2) : string.Empty; + _invoking = true; + try { Core.Actions.InvokeChatParser(line); } + finally { _invoking = false; } + break; + case BridgeRecordKind.CmdSalvagePanelAdd: + Core.Actions.SalvagePanelAdd(unchecked((int)arg0)); + break; + case BridgeRecordKind.CmdSalvagePanelSalvage: + Core.Actions.SalvagePanelSalvage(); + break; + default: + failure = "unknown command " + (int)kind; + break; + } + } + catch (Exception ex) + { + failure = ex.GetType().Name + ": " + ex.Message; + } + if (failure != null) + { + Log("command " + kind + " failed: " + failure); + _ch.WriteString(BridgeRecordKind.CommandResult, (uint)kind, 0, failure); + } + } + + // ── forwarders (AC's main thread; never block, never throw) ────────── + private void OnServerDispatch(object sender, NetworkMessageEventArgs e) + { + try + { + _serverMessages++; + if (!_ch.Wants(BridgeRecordKind.ServerMessage)) + return; // the engine reads these from its own hooks: don't copy them + Message m = e.Message; + byte[] raw = m.RawData; + if (_loggedServer < 4) + { + _loggedServer++; + Log("server message type=0x" + m.Type.ToString("X4") + " len=" + (raw == null ? 0 : raw.Length)); + } + _ch.WriteBytes(BridgeRecordKind.ServerMessage, unchecked((uint)m.Type), 0, raw); + } + catch { } + } + + private void OnChatBoxMessage(object sender, ChatTextInterceptEventArgs e) + { + try { _ch.WriteString(BridgeRecordKind.ChatText, unchecked((uint)e.Color), unchecked((uint)e.Target), e.Text); } + catch { } + } + + private void OnCommandLineText(object sender, ChatParserInterceptEventArgs e) + { + try + { + // A line the engine sent through InvokeChatParser: it already went through the + // engine's own dispatch; let Decal and AC have it. + if (_invoking) + return; + string text = e.Text ?? string.Empty; + // The engine's commands (and its plugins') must not reach the server: eat the + // lines whose prefix the engine published; forward every line either way. + bool eat = MatchesPrefix(text); + if (eat) e.Eat = true; + if (_loggedChatBar < 10) + { + _loggedChatBar++; + Log("chat bar: '" + text + "' eaten=" + eat); + } + _ch.WriteString(BridgeRecordKind.ChatBarEnter, eat ? 1u : 0u, 0, text); + } + catch { } + } + + private void OnItemSelected(object sender, ItemSelectedEventArgs e) + { + try { _ch.Write(BridgeRecordKind.ItemSelected, unchecked((uint)e.ItemGuid), 0, null, 0); } catch { } + } + + private void OnCreateObject(object sender, CreateObjectEventArgs e) + { + try { _ch.Write(BridgeRecordKind.CreateObject, unchecked((uint)e.New.Id), 0, null, 0); } catch { } + } + + private void OnReleaseObject(object sender, ReleaseObjectEventArgs e) + { + try { _ch.Write(BridgeRecordKind.ReleaseObject, unchecked((uint)e.Released.Id), 0, null, 0); } catch { } + } + + private void OnChangeObject(object sender, ChangeObjectEventArgs e) + { + try { _ch.Write(BridgeRecordKind.ChangeObject, unchecked((uint)e.Changed.Id), (uint)e.Change, null, 0); } catch { } + } + + private void OnLoginComplete(object sender, EventArgs e) + { + try { _ch.Write(BridgeRecordKind.LoginComplete, unchecked((uint)Core.CharacterFilter.Id), 0, null, 0); } catch { } + } + + private void OnLogoff(object sender, LogoffEventArgs e) + { + try { _ch.Write(BridgeRecordKind.Logoff, (uint)e.Type, 0, null, 0); } catch { } + } + + // ── helpers ──────────────────────────────────────────────────────────── + private bool MatchesPrefix(string text) + { + if (_ch.ReadInt(BridgeLayout.OffEngineAttached) == 0) + return false; // no engine to run it: let AC have the line + // The engine rewrites the prefix list when it attaches; re-read it when it changes. + int gen = _ch.ReadInt(BridgeLayout.OffEngineGeneration); + if (gen != _prefixStamp) + { + _prefixStamp = gen; + char* p = (char*)(_ch.Header + BridgeLayout.OffPrefixes); + int n = 0; + while (n < BridgeLayout.PrefixChars && p[n] != '\0') n++; + _prefixes = new string(p, 0, n).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + } + foreach (string pre in _prefixes) + { + if (text.StartsWith(pre, StringComparison.OrdinalIgnoreCase) && + (text.Length == pre.Length || text[pre.Length] == ' ')) + return true; + } + return false; + } + + private void Log(string msg) + { + try + { + File.AppendAllText(System.IO.Path.Combine(LogDir, "DecalBridge." + _pid + ".log"), + "[" + DateTime.Now.ToString("HH:mm:ss.fff") + "] " + msg + Environment.NewLine); + } + catch { } + } + } +} diff --git a/src/RynthCore.DecalBridge/BridgeProtocol.cs b/src/RynthCore.DecalBridge/BridgeProtocol.cs new file mode 100644 index 0000000..cfa22e8 --- /dev/null +++ b/src/RynthCore.DecalBridge/BridgeProtocol.cs @@ -0,0 +1,302 @@ +// ============================================================================ +// RynthCore.DecalBridge - BridgeProtocol.cs +// +// The in-process channel between the Decal bridge filter (.NET Framework, Decal's +// desktop CLR) and the RynthCore engine (CoreCLR, unloadable). Compiled into BOTH +// assemblies (the engine links this file), so it stays C# 9 / net48-compatible. +// docs/DECAL_BRIDGE_PLAN.md has the design. +// +// A named, pagefile-backed file mapping holds a header and two single-producer / +// single-consumer byte rings: +// event ring (bridge -> engine): producer = the bridge, on AC's main thread (Decal +// raises its events there); consumer = the engine's plugin pump thread. +// command ring (engine -> bridge): producer = the engine (any thread, serialised by +// the engine); consumer = the bridge, on AC's main thread (RenderFrame), +// which runs each command through Decal's public API. +// Nothing crosses the runtimes but bytes: no function pointer, delegate or COM object +// is ever handed from one runtime to the other. That is what makes it safe with the +// unloadable engine - a generation that goes away leaves nothing behind that the +// bridge could call into, and neither side ever blocks on the other (a full ring +// drops the record and counts it). The mapping lives as long as either side holds it, +// so the read positions survive an engine hot reload. +// +// The engine publishes which event kinds it wants (OffWantMask); the bridge writes +// only those, so a stream the engine takes from its own hooks costs Decal nothing. +// +// Record: [int length (multiple of 4, header included)][ushort kind][ushort pad bytes] +// [uint arg0][uint arg1][payload...] +// Write/read positions are monotonic byte counts (64-bit, Interlocked on x86). +// +// Version 2 (2026-09-30): want mask, command ring, bridge hello/state fields. +// ============================================================================ +#nullable disable +using System; +using System.IO.MemoryMappedFiles; +using System.Threading; + +namespace RynthCore.DecalBridge +{ + internal enum BridgeRecordKind : ushort + { + Pad = 0, + // ── events, bridge -> engine ── + Hello = 1, // arg0 = protocol version, payload = UTF-16 bridge description (always written) + ChatText = 2, // arg0 = Decal ChatBoxMessage.Color (AC chat type), arg1 = Target, payload = UTF-16 text + ChatBarEnter = 3, // arg0 = 1 when the bridge ate the line, payload = UTF-16 text + CreateObject = 4, // arg0 = object id, arg1 = 1 when part of a replay (WorldFilter.GetAll) + ReleaseObject = 5, // arg0 = object id + ChangeObject = 6, // arg0 = object id, arg1 = WorldChangeType + ServerMessage = 7, // arg0 = message type (opcode), payload = Message.RawData + LoginComplete = 8, // arg0 = character id + Logoff = 9, // arg0 = LogoffEventType + ItemSelected = 10, // arg0 = object id + CommandResult = 11, // arg0 = command kind, arg1 = 1 ok / 0 failed, payload = UTF-16 detail (failures only) + + // ── commands, engine -> bridge (run on AC's main thread through Decal's public API) ── + CmdInvokeChatParser = 100, // payload = UTF-16 line -> Actions.InvokeChatParser + CmdSalvagePanelAdd = 101, // arg0 = item id -> Actions.SalvagePanelAdd + CmdSalvagePanelSalvage = 102,// -> Actions.SalvagePanelSalvage + } + + internal static unsafe class BridgeLayout + { + public const uint Magic = 0x42444352; // "RCDB" + public const int Version = 2; + public const int HeaderSize = 4096; + public const int CommandRingSize = 64 * 1024; + public const int EventRingSize = 16 * 1024 * 1024; + public const int TotalSize = HeaderSize + CommandRingSize + EventRingSize; + public const int RecordHeaderSize = 16; + public const int MaxRecord = 256 * 1024; + + // Header offsets. + public const int OffMagic = 0; + public const int OffVersion = 4; + public const int OffBridgeState = 8; // 1 while a bridge is started (its "hello") + public const int OffBridgeBeats = 12; // bridge: bumped per record written + public const int OffWritePos = 16; // long, event ring, producer-owned + public const int OffReadPos = 24; // long, event ring, consumer-owned + public const int OffDropped = 32; // long, event records the bridge dropped (ring full) + public const int OffRecords = 40; // long, event records written + public const int OffEngineAttached = 48; // 1 while an engine generation drains + public const int OffEngineGeneration = 52; + public const int OffBridgePid = 56; + public const int OffReplayRequest = 60; // engine -> bridge: bump to get WorldFilter.GetAll() as CreateObject records + public const int OffReplayDone = 64; // bridge -> engine: the request value last served + public const int OffWantMask = 68; // engine -> bridge: bit (1 << kind) for each event kind to forward + public const int OffCmdWritePos = 72; // long, command ring, engine-owned + public const int OffCmdReadPos = 80; // long, command ring, bridge-owned + public const int OffCmdDropped = 88; // long, commands the engine dropped (ring full) + public const int OffCmdDone = 96; // long, commands the bridge ran + // Added in v2 without a version bump (zero from an older bridge = unknown): + public const int OffD3DDevice = 104; // bridge -> engine: IDirect3DDevice9* Decal renders with (IDecalCore.GetD3DDevice), 0 = unknown + public const int OffDecalHwnd = 108; // bridge -> engine: the game window as Decal knows it + public const int OffPrefixes = 256; // engine -> bridge: ';'-separated chat prefixes to eat, UTF-16, 0-terminated + public const int PrefixChars = 1024; + + public static string MappingName(int pid) { return "Local\\RynthCore.DecalBridge.p" + pid; } + + public static int Align4(int n) { return (n + 3) & ~3; } + + public static uint Bit(BridgeRecordKind kind) { return (uint)kind < 32 ? 1u << (int)kind : 0u; } + } + + /// <summary>One side's view of the mapping (the bridge and the engine each open their own).</summary> + internal sealed unsafe class BridgeChannel : IDisposable + { + private MemoryMappedFile _file; + private MemoryMappedViewAccessor _view; + private byte* _base; + + public byte* Header { get { return _base; } } + private byte* CommandRing { get { return _base + BridgeLayout.HeaderSize; } } + private byte* EventRing { get { return _base + BridgeLayout.HeaderSize + BridgeLayout.CommandRingSize; } } + + public static BridgeChannel OpenOrCreate(int pid) + { + var c = new BridgeChannel(); + c._file = MemoryMappedFile.CreateOrOpen(BridgeLayout.MappingName(pid), BridgeLayout.TotalSize); + c._view = c._file.CreateViewAccessor(0, BridgeLayout.TotalSize); + byte* p = null; + c._view.SafeMemoryMappedViewHandle.AcquirePointer(ref p); + c._base = p + c._view.PointerOffset; + // The first opener stamps the header; the pages start zeroed either way. + Interlocked.CompareExchange(ref *(int*)(c._base + BridgeLayout.OffVersion), BridgeLayout.Version, 0); + Interlocked.CompareExchange(ref *(int*)(c._base + BridgeLayout.OffMagic), unchecked((int)BridgeLayout.Magic), 0); + return c; + } + + /// <summary>True when some side already created the mapping for <paramref name="pid"/>.</summary> + public static bool Exists(int pid) + { + try + { + using (MemoryMappedFile f = MemoryMappedFile.OpenExisting(BridgeLayout.MappingName(pid))) + return true; + } + catch + { + return false; + } + } + + public int ReadInt(int off) { return Volatile.Read(ref *(int*)(_base + off)); } + public void WriteInt(int off, int v) { Volatile.Write(ref *(int*)(_base + off), v); } + public long ReadLong(int off) { return Interlocked.Read(ref *(long*)(_base + off)); } + public void WriteLong(int off, long v) { Interlocked.Exchange(ref *(long*)(_base + off), v); } + public void AddLong(int off, long v) { Interlocked.Add(ref *(long*)(_base + off), v); } + + public bool Valid { get { return (uint)ReadInt(BridgeLayout.OffMagic) == BridgeLayout.Magic && ReadInt(BridgeLayout.OffVersion) == BridgeLayout.Version; } } + + /// <summary>Whether the engine asked for <paramref name="kind"/> (Hello always goes).</summary> + public bool Wants(BridgeRecordKind kind) + { + return kind == BridgeRecordKind.Hello || (unchecked((uint)ReadInt(BridgeLayout.OffWantMask)) & BridgeLayout.Bit(kind)) != 0; + } + + // ── event ring (bridge -> engine) ───────────────────────────────────── + public bool Write(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen) + { + if (!Wants(kind)) + return false; + bool ok = Put(EventRing, BridgeLayout.EventRingSize, BridgeLayout.OffWritePos, BridgeLayout.OffReadPos, + BridgeLayout.OffDropped, kind, arg0, arg1, payload, payloadLen); + if (ok) + { + AddLong(BridgeLayout.OffRecords, 1); + Interlocked.Increment(ref *(int*)(_base + BridgeLayout.OffBridgeBeats)); + } + return ok; + } + + public bool WriteString(BridgeRecordKind kind, uint arg0, uint arg1, string text) + { + if (text == null) text = string.Empty; + fixed (char* c = text) + return Write(kind, arg0, arg1, (byte*)c, text.Length * 2); + } + + public bool WriteBytes(BridgeRecordKind kind, uint arg0, uint arg1, byte[] data) + { + if (data == null || data.Length == 0) + return Write(kind, arg0, arg1, null, 0); + fixed (byte* b = data) + return Write(kind, arg0, arg1, b, data.Length); + } + + public delegate void RecordHandler(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen); + + /// <summary>Hands every event written so far to <paramref name="handler"/> (payload valid only during the call).</summary> + public int Drain(RecordHandler handler, int maxRecords) + { + return Take(EventRing, BridgeLayout.EventRingSize, BridgeLayout.OffWritePos, BridgeLayout.OffReadPos, handler, maxRecords); + } + + // ── command ring (engine -> bridge) ─────────────────────────────────── + /// <summary>Queues a command for the bridge. One producer at a time (the engine serialises).</summary> + public bool WriteCommand(BridgeRecordKind kind, uint arg0, uint arg1, string text) + { + if (text == null) + return Put(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos, + BridgeLayout.OffCmdDropped, kind, arg0, arg1, null, 0); + fixed (char* c = text) + return Put(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos, + BridgeLayout.OffCmdDropped, kind, arg0, arg1, (byte*)c, text.Length * 2); + } + + /// <summary>Bridge: runs every queued command through <paramref name="handler"/>.</summary> + public int DrainCommands(RecordHandler handler, int maxRecords) + { + int n = Take(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos, handler, maxRecords); + if (n > 0) AddLong(BridgeLayout.OffCmdDone, n); + return n; + } + + public bool HasCommands { get { return ReadLong(BridgeLayout.OffCmdWritePos) != ReadLong(BridgeLayout.OffCmdReadPos); } } + + // ── ring primitives ─────────────────────────────────────────────────── + private bool Put(byte* ring, int size, int offWrite, int offRead, int offDropped, + BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen) + { + if (payloadLen < 0 || payloadLen > BridgeLayout.MaxRecord || payloadLen > size / 4) + { + AddLong(offDropped, 1); + return false; + } + int recLen = BridgeLayout.Align4(BridgeLayout.RecordHeaderSize + payloadLen); + long w = ReadLong(offWrite); + long r = ReadLong(offRead); + int pos = (int)(w % size); + int tail = size - pos; + int need = recLen + (tail < recLen ? tail : 0); + if (need > size - (w - r)) + { + AddLong(offDropped, 1); + return false; + } + if (tail < recLen) + { + // Doesn't fit before the end: pad to the end, start again at 0. A tail shorter + // than a record header is skipped by the reader without being read. + if (tail >= BridgeLayout.RecordHeaderSize) + { + *(int*)(ring + pos) = tail; + *(ushort*)(ring + pos + 4) = (ushort)BridgeRecordKind.Pad; + } + pos = 0; + } + byte* rec = ring + pos; + *(int*)rec = recLen; + *(ushort*)(rec + 4) = (ushort)kind; + *(ushort*)(rec + 6) = (ushort)(recLen - BridgeLayout.RecordHeaderSize - payloadLen); // pad bytes + *(uint*)(rec + 8) = arg0; + *(uint*)(rec + 12) = arg1; + for (int i = 0; i < payloadLen; i++) + rec[BridgeLayout.RecordHeaderSize + i] = payload[i]; + WriteLong(offWrite, w + need); // publish (full fence) + return true; + } + + private int Take(byte* ring, int size, int offWrite, int offRead, RecordHandler handler, int maxRecords) + { + long r = ReadLong(offRead); + long w = ReadLong(offWrite); + int n = 0; + while (r < w && n < maxRecords) + { + int pos = (int)(r % size); + int tail = size - pos; + if (tail < BridgeLayout.RecordHeaderSize) { r += tail; continue; } + int len = *(int*)(ring + pos); + if (len < BridgeLayout.RecordHeaderSize || len > tail || (len & 3) != 0) + { + r = w; // corrupt: resynchronise at the writer + break; + } + var kind = (BridgeRecordKind)(*(ushort*)(ring + pos + 4)); + if (kind != BridgeRecordKind.Pad) + { + int pad = *(ushort*)(ring + pos + 6) & 3; + handler(kind, *(uint*)(ring + pos + 8), *(uint*)(ring + pos + 12), + ring + pos + BridgeLayout.RecordHeaderSize, len - BridgeLayout.RecordHeaderSize - pad); + n++; + } + r += len; + } + WriteLong(offRead, r); + return n; + } + + public void Dispose() + { + if (_view != null) + { + if (_base != null) _view.SafeMemoryMappedViewHandle.ReleasePointer(); + _view.Dispose(); + _view = null; + } + _base = null; + if (_file != null) { _file.Dispose(); _file = null; } + } + } +} diff --git a/src/RynthCore.DecalBridge/RynthCore.DecalBridge.csproj b/src/RynthCore.DecalBridge/RynthCore.DecalBridge.csproj new file mode 100644 index 0000000..e9458c6 --- /dev/null +++ b/src/RynthCore.DecalBridge/RynthCore.DecalBridge.csproj @@ -0,0 +1,71 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + RynthCore Decal Bridge: a Decal network filter that lets the RynthCore engine run in + the same acclient.exe as Decal (docs/DECAL_BRIDGE_PLAN.md). + + net48 / x86: it loads into Decal's desktop CLR inside the 32-bit client. Built only + against Decal's public reference assemblies (Decal.Adapter and the interop PIAs it + exposes in its signatures), never shipped with them (Private=false). + + dotnet build -c Release (also part of RynthCore.sln) + + Needs Decal installed (default C:\Program Files (x86)\Decal 3.0, or -p:DecalDir=...). + Without it the project builds nothing useful: a warning, and an empty assembly under + bin\<Configuration>-NoDecal\ (never the real output folder), so a machine without + Decal can still build the whole solution. + --> + <PropertyGroup> + <TargetFramework>net48</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <Platforms>AnyCPU;x86</Platforms> + <OutputType>Library</OutputType> + <AssemblyName>RynthCore.DecalBridge</AssemblyName> + <RootNamespace>RynthCore.DecalBridge</RootNamespace> + <LangVersion>9.0</LangVersion> + <Nullable>disable</Nullable> + <ImplicitUsings>disable</ImplicitUsings> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath> + <CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies> + <Deterministic>true</Deterministic> + <Version>0.2.0</Version> + <DecalDir Condition="'$(DecalDir)' == ''">C:\Program Files (x86)\Decal 3.0</DecalDir> + <DecalAvailable Condition="Exists('$(DecalDir)\Decal.Adapter.dll')">true</DecalAvailable> + <OutputPath>bin\$(Configuration)\</OutputPath> + <OutputPath Condition="'$(DecalAvailable)' != 'true'">bin\$(Configuration)-NoDecal\</OutputPath> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" /> + </ItemGroup> + + <ItemGroup Condition="'$(DecalAvailable)' == 'true'"> + <Reference Include="Decal.Adapter"> + <HintPath>$(DecalDir)\Decal.Adapter.dll</HintPath> + <Private>false</Private> + </Reference> + <!-- Public interop assemblies that appear in Decal.Adapter's own signatures. --> + <Reference Include="Decal.Interop.Core"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Core.DLL</HintPath><Private>false</Private></Reference> + <Reference Include="Decal.Interop.Filters"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Filters.DLL</HintPath><Private>false</Private></Reference> + <Reference Include="Decal.Interop.Net"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Net.DLL</HintPath><Private>false</Private></Reference> + <Reference Include="Decal.Interop.Inject"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Inject.dll</HintPath><Private>false</Private></Reference> + <Reference Include="Decal.Interop.D3DService"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.D3DService.DLL</HintPath><Private>false</Private></Reference> + <Reference Include="Decal.Interop.Render"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Render.DLL</HintPath><Private>false</Private></Reference> + <Reference Include="System.Drawing" /> + </ItemGroup> + + <ItemGroup Condition="'$(DecalAvailable)' != 'true'"> + <Compile Remove="**\*.cs" /> + </ItemGroup> + + <Target Name="WarnNoDecal" BeforeTargets="CoreCompile" Condition="'$(DecalAvailable)' != 'true' and '$(RequireDecal)' != 'true'"> + <Warning Text="RynthCore.DecalBridge: Decal.Adapter.dll not found in '$(DecalDir)' - the Decal bridge is not built (install Decal or pass -p:DecalDir=...)." /> + </Target> + + <!-- Release builds (installer\Build-Installer.ps1) pass -p:RequireDecal=true: no Decal, no build. --> + <Target Name="RequireDecal" BeforeTargets="BeforeBuild" Condition="'$(RequireDecal)' == 'true' and '$(DecalAvailable)' != 'true'"> + <Error Text="RynthCore.DecalBridge: Decal.Adapter.dll not found in '$(DecalDir)'. The release ships the Decal bridge, so it must be built against Decal's reference assemblies: install Decal 3.0 or pass -p:DecalDir=..." /> + </Target> + +</Project> diff --git a/src/RynthCore.Engine/Assets/Fonts/Phosphor.LICENSE b/src/RynthCore.Engine/Assets/Fonts/Phosphor.LICENSE new file mode 100644 index 0000000..c04a19d --- /dev/null +++ b/src/RynthCore.Engine/Assets/Fonts/Phosphor.LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-2021 Phosphor Icons + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/RynthCore.Engine/Assets/Fonts/Phosphor.ttf b/src/RynthCore.Engine/Assets/Fonts/Phosphor.ttf new file mode 100644 index 0000000..7c1b8a7 Binary files /dev/null and b/src/RynthCore.Engine/Assets/Fonts/Phosphor.ttf differ diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 17cca0c..0b445d6 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -106,6 +106,51 @@ internal static class AcMainThreadQueue // class. Carries the 5 hold-flags packed into A (bit0=shift, bit1=W, // bit2=X, bit3=Z, bit4=C). LaunchJumpWithMotion, + // v70 WieldItem: CM_Inventory::Event_GetAndWieldItem (the 0x001A GetAndWieldItem + // game action) is an inventory send like GiveObjectTo, so it runs here too. + WieldItem, + // v72 player-to-player trade: CM_Trade::Event_* / ClientTradeSystem::Accept/DeclineTrade + // send trade game actions (and Accept/Decline touch the client's Trade object), so they + // run here too. A = PlayerTrade.TradeOp, B/C = its arguments. + Trade, + // Salvage panel marshalled 2026-09-29: CM_Inventory::SendNotice_OpenSalvagePanel, + // gmSalvageUI::AddNewItem and gmSalvageUI::Salvage were called straight from + // the plugin pump (RynthAi SalvageManager, Meta expressions). AddNewItem and + // Salvage are thiscall on the live gmSalvageUI and mutate its UIElement tree + // (same class as the SetSelectedObject 0x60D1D AV). A = toolId / itemId. + // The instance pointer is NOT carried: the drain re-enters the helper, which + // re-reads SalvageHooks.GmSalvageUIInstance on the main thread. + SalvageOpen, + SalvageAddItem, + SalvageExecute, + // CancelAttack marshalled 2026-09-29: CM_Combat::Event_CancelAttack (0x1B7) is + // the same CM_Combat game-action sender class as Melee/Missile/ChangeCombatMode + // but was called straight from the plugin pump. It rides the RING (not a side + // queue) on purpose: every RynthAi caller pairs it with ring actions + // (StopCompletely, ChangeCombatMode, MoveItemInternal) and it must land after + // any attack already queued, so FIFO order with those is what matters. When a + // gesture defers the ring, the paired actions wait too, so the teardown stays + // one ordered group. + CancelAttack, + // SetAutonomyLevel marshalled 2026-09-29: CM_Movement::Event_AutonomyLevel + // (0xF752 game-action send) is exported to plugins as SetAutonomyLevelFn and + // was the only movement sender still called straight from the plugin pump. + // Rides the ring beside DoMovement/StopMovement/Jump so it stays ordered with + // them. A = level. + SetAutonomyLevel, + // DropItem (2026-09-30, Inventory panel): CM_Inventory::Event_DropItem (0x001B game + // action) is an inventory send like WieldItem / GiveObjectTo. A = item id. + DropItem, + // Skills panel raises (2026-09-30): CM_Train::Event_TrainAttribute / _TrainAttribute2nd / + // _TrainSkill send the RaiseAttribute / RaiseVital / RaiseSkill game actions. A game-action + // send like Trade, so it rides the ring too. A = PlayerTraining.TrainKind, B = stype, C = XP + // (skill credits for TrainKind.TrainWithCredits: Event_TrainSkillAdvancementClass, 0x0047). + Train, + // v76 CloseContainer (2026-10-04): CM_Inventory::Event_NoLongerViewingContents (the + // 0x0195 game action the client sends when a corpse/chest window closes). An inventory + // send like DropItem; in the ring so a close queued before the next corpse's UseObject + // goes out first, in the same drain. A = container id. + CloseContainer, } // Four payload slots cover every routed action (the 4th was added for @@ -167,6 +212,9 @@ internal static class AcMainThreadQueue Enqueue(ActionKind.MissileAttack, targetId, unchecked((uint)attackHeight), BitConverter.SingleToUInt32Bits(accuracyLevel)); + public static bool EnqueueCancelAttack() => + Enqueue(ActionKind.CancelAttack, 0, 0, 0); + public static bool EnqueueDoMovement(uint motion, float speed, int holdKey) => Enqueue(ActionKind.DoMovement, motion, unchecked((uint)holdKey), BitConverter.SingleToUInt32Bits(speed)); @@ -183,12 +231,82 @@ internal static class AcMainThreadQueue public static bool EnqueueStopCompletely() => Enqueue(ActionKind.StopCompletely, 0, 0, 0); + // ── Direct-heading slot (coalesced, latest value wins) ────────────────────── + // PlayerPhysicsHooks.SetPlayerHeadingDirect snaps the player's CPhysicsObj + // orientation quaternion with two raw stores (qw, then qz). Plugins call it + // (Host.TurnToHeading) from the pump thread on every nav tick; run there it + // raced AC's own physics integration and could leave a torn, non-unit + // quaternion (new qw with old qz). Off-thread callers now park the heading + // here and Drain applies it on the main thread. One slot, not a ring entry: + // nav re-issues the heading every tick and only the newest one matters, so a + // steering bot can never fill the action ring with headings. Lock-free and + // allocation-free; never drops (a newer heading simply replaces an older one). + // Deliberately NOT ActionKind.TurnToHeading: that dispatches the gradual + // CommandInterpreter turn, which would change the steering behaviour. + private static int _directHeadingPending; + private static uint _directHeadingBits; + + public static bool EnqueueDirectHeading(float headingDegrees) + { + Volatile.Write(ref _directHeadingBits, BitConverter.SingleToUInt32Bits(headingDegrees)); + Volatile.Write(ref _directHeadingPending, 1); + return true; + } + + // Main thread only (from Drain). Same order as the pre-queue code: the direct + // snap first, the CommandInterpreter turn only when there is no player. + private static void DrainDirectHeading() + { + if (Interlocked.Exchange(ref _directHeadingPending, 0) == 0) return; + float heading = BitConverter.UInt32BitsToSingle(Volatile.Read(ref _directHeadingBits)); + try + { + if (!PlayerPhysicsHooks.SetPlayerHeadingDirect(heading)) + CommandInterpreterHooks.TurnToHeading(heading); + } + catch { } + } + + // ── Overlay click-to-select slot (coalesced, latest click wins) ───────────── + // A click on a Radar dot or a monster nameplate (ImGui overlays, 2026-09-30) + // parks the object id here; Drain runs ClientHelperHooks.SelectFromOverlay on + // the main thread, which re-checks that the object still exists and that the + // client isn't portaling or logging out right before AC's SetSelectedObject. + // The faces always park here (never select inside the ImGui frame build), so + // the select runs in the same main-thread phase as every other queued action. + // One slot, not a ring entry: a click is one select, two clicks in one frame + // collapse to the newer one, and the slot sits before the ring's gesture + // defer (a selection is a UI change, not a motion; a click in the 3D world + // selects mid-gesture too). Lock-free and allocation-free. + private static int _overlaySelectPending; + private static uint _overlaySelectId; + + public static bool EnqueueOverlaySelect(uint objectId) + { + if (objectId == 0) return false; + Volatile.Write(ref _overlaySelectId, objectId); + Volatile.Write(ref _overlaySelectPending, 1); + return true; + } + + // Main thread only (from Drain). + private static void DrainOverlaySelect() + { + if (Interlocked.Exchange(ref _overlaySelectPending, 0) == 0) return; + uint id = Volatile.Read(ref _overlaySelectId); + try { ClientHelperHooks.SelectFromOverlay(id); } + catch { } + } + public static bool EnqueueSetMotion(uint motion, bool enabled) => Enqueue(ActionKind.SetMotion, motion, enabled ? 1u : 0u, 0); public static bool EnqueueJump(float extent) => Enqueue(ActionKind.Jump, BitConverter.SingleToUInt32Bits(extent), 0, 0); + public static bool EnqueueSetAutonomyLevel(uint level) => + Enqueue(ActionKind.SetAutonomyLevel, level, 0, 0); + public static bool EnqueueUseObject(uint objectId) => Enqueue(ActionKind.UseObject, objectId, 0, 0); @@ -213,6 +331,30 @@ internal static class AcMainThreadQueue public static bool EnqueueGiveObjectTo(uint objectId, uint targetId, int amount) => Enqueue(ActionKind.GiveObjectTo, objectId, targetId, unchecked((uint)amount)); + public static bool EnqueueWieldItem(uint objectId, uint equipMask) => + Enqueue(ActionKind.WieldItem, objectId, equipMask, 0); + + public static bool EnqueueDropItem(uint objectId) => + Enqueue(ActionKind.DropItem, objectId, 0, 0); + + public static bool EnqueueCloseContainer(uint containerId) => + Enqueue(ActionKind.CloseContainer, containerId, 0, 0); + + public static bool EnqueueTrade(uint op, uint a, uint b) => + Enqueue(ActionKind.Trade, op, a, b); + + public static bool EnqueueTrain(uint kind, uint stype, uint xp) => + Enqueue(ActionKind.Train, kind, stype, xp); + + public static bool EnqueueSalvageOpen(uint toolId) => + Enqueue(ActionKind.SalvageOpen, toolId, 0, 0); + + public static bool EnqueueSalvageAddItem(uint itemId) => + Enqueue(ActionKind.SalvageAddItem, itemId, 0, 0); + + public static bool EnqueueSalvageExecute() => + Enqueue(ActionKind.SalvageExecute, 0, 0, 0); + public static bool EnqueueSetSelectedObject(uint objectId) => Enqueue(ActionKind.SetSelectedObject, objectId, 0, 0); @@ -243,6 +385,9 @@ internal static class AcMainThreadQueue /// <summary>Stop executing queued actions/casts permanently (engine teardown).</summary> public static void Disarm() => _disarmed = true; + /// <summary>Engine teardown has begun (ChatCallbackHooks stops holding chat).</summary> + public static bool IsDisarmed => _disarmed; + // Single-consumer drain on AC's main thread (EngineFrameController.OnEndScene). // Re-invokes the public action methods; on the main thread they execute the // real AC call directly (their IsOnMainThread gate is satisfied here). @@ -254,7 +399,25 @@ internal static class AcMainThreadQueue public static void Drain() { - if (_disarmed) return; + if (_disarmed) + { + // Held incoming chat still prints during teardown (the AddTextToScroll detour + // stays live until MH_DisableHook(ALL)): it is AC's own line, not a plugin action. + try { ChatCallbackHooks.OnMainThreadDrain(disarmed: true); } catch { } + return; + } + + // We are on AC's main thread by definition. Latch it here too: after a hot + // reload the first SmartBox/combat detour (the other latches) can come well + // after the first drain, and until the latch is set every dispatch below + // thinks it's off-thread and re-queues itself. A chat command a plugin queued + // straight after the reload then spun the main thread forever + // (DrainChatCommands -> Dispatch -> EnqueueChatCommand, 2026-09-29). + MainThreadGuard.RecordIfFirst(); + + // Incoming chat held for the plugins' verdict prints first, before anything below + // writes its own lines, so the chat window keeps the order lines arrived in. + try { ChatCallbackHooks.OnMainThreadDrain(disarmed: false); } catch { } // Deep-audit finding #22 (2026-06-18): these three queues are // documented as deliberately separate from the gesture-gated action @@ -268,12 +431,27 @@ internal static class AcMainThreadQueue DrainChat(); DrainChatCommands(); DrainRequestIds(); + DrainQueryHealth(); // Vendor buy/sell: a packet send through the client's own SendShopEvent, not a // motion, so it sits with the non-gesture queues above. Also polls whether the // vendor window is still open. Idle fast path when no vendor is open. try { VendorTrade.MainThreadTick(); } catch { } + // Char-select service: publishes the UIFlow mode, runs a pending auto-login + // LogOnCharacter request and snapshots the native character list (throttled). + // Pre-login this runs from the Client::UseTime drain (EndScene is not hooked + // until after login). Idle in the world. + try { CharacterManagementHooks.MainThreadTick(); } catch { } - int head = _head; // only the main thread writes _head + // Plugin heading snap (coalesced slot). Before the ring and its gesture + // defer: the pre-queue raw write landed immediately, gesture or not, and + // ahead of the SetAutoRun a nav tick queues right after it. Keep both. + DrainDirectHeading(); + + // Overlay click-to-select (Radar dot / nameplate click): also before the + // gesture defer, so a click selects at once even while the bot swings. + DrainOverlaySelect(); + + int head = _head; // only the main thread writes _head int tail = Volatile.Read(ref _tail); // ── Gesture-phase serialization (extends the 56e6946 anim-walk guard @@ -315,6 +493,9 @@ internal static class AcMainThreadQueue CombatActionHooks.MissileAttack(e.A, unchecked((int)e.B), BitConverter.UInt32BitsToSingle(e.C)); break; + case ActionKind.CancelAttack: + CombatActionHooks.CancelAttack(); + break; case ActionKind.DoMovement: MovementActionHooks.DoMovement(e.A, BitConverter.UInt32BitsToSingle(e.C), unchecked((int)e.B)); @@ -325,6 +506,9 @@ internal static class AcMainThreadQueue case ActionKind.Jump: MovementActionHooks.JumpNonAutonomous(BitConverter.UInt32BitsToSingle(e.A)); break; + case ActionKind.SetAutonomyLevel: + MovementActionHooks.SetAutonomyLevel(e.A); + break; case ActionKind.UseObject: ClientHelperHooks.UseObject(e.A); break; @@ -349,6 +533,30 @@ internal static class AcMainThreadQueue case ActionKind.GiveObjectTo: ClientHelperHooks.GiveObjectTo(e.A, e.B, unchecked((int)e.C)); break; + case ActionKind.WieldItem: + ClientHelperHooks.WieldItem(e.A, e.B); + break; + case ActionKind.DropItem: + ClientHelperHooks.DropItem(e.A); + break; + case ActionKind.CloseContainer: + ClientHelperHooks.CloseContainer(e.A); + break; + case ActionKind.Trade: + PlayerTrade.RunQueued(e.A, e.B, e.C); + break; + case ActionKind.Train: + PlayerTraining.RunQueued(e.A, e.B, e.C); + break; + case ActionKind.SalvageOpen: + ClientHelperHooks.SalvagePanelOpen(e.A); + break; + case ActionKind.SalvageAddItem: + ClientHelperHooks.SalvagePanelAddItem(e.A); + break; + case ActionKind.SalvageExecute: + ClientHelperHooks.SalvagePanelExecute(); + break; case ActionKind.SetSelectedObject: // On the main thread now -> SetSelectedObjectId's gate is // satisfied and it calls AC's SetSelectedObject directly. @@ -400,7 +608,9 @@ internal static class AcMainThreadQueue } } - // ── RequestId slot (0xC8 appraisal sends from AutoIdService) ────────────────── + // ── RequestId slot (0xC8 appraisal sends from AutoIdService, and every other + // off-thread CombatActionHooks.RequestId caller: plugin RequestIdFn, the + // PluginManager.TickAll login self-identify) ───────────────────────────── // AutoIdService runs on a Timer thread; sending 0xC8 directly there does AC heap // allocation + a non-atomic shared UI-counter increment off AC's main thread (the // off-thread-send class flagged for RequestId). Marshal onto the main thread here. @@ -431,7 +641,10 @@ internal static class AcMainThreadQueue // CombatActionHooks.RequestId sends the 0xC8 directly. private static void DrainRequestIds() { - while (true) + // Bounded like DrainChatCommands: a re-queue never spins the main thread. + int budget; + lock (_requestIdLock) budget = _requestIdQueue.Count; + while (budget-- > 0) { uint id; lock (_requestIdLock) @@ -443,6 +656,58 @@ internal static class AcMainThreadQueue } } + // ── QueryHealth slot (0x1BF CM_Combat::Event_QueryHealth sends) ───────────────── + // Plugins (RynthAi CombatManager, once per fight target) call QueryHealthFn from the + // plugin pump; the send allocates an AC blob and pushes AC's send queue, so it is + // main-thread-only like 0xC8. Same shape as the RequestId slot: its own small + // queue, NOT the gesture-deferred action ring (a packet send doesn't perturb the + // motion graph and a health query must not wait out a swing). Callers ignore the + // result and only want the async 0x01C0 reply, so a target already waiting here is + // not queued twice. Pre-sized, so enqueue does not allocate. + private const int MaxQueryHealthQueue = 64; + private static readonly System.Collections.Generic.Queue<uint> _queryHealthQueue = new(MaxQueryHealthQueue); + private static readonly object _queryHealthLock = new(); + private static int _queryHealthPending; // lock-free "anything queued?" for the per-frame drain + + // Pump-thread enqueue. Drops (returns false) if the queue is full. + public static bool EnqueueQueryHealth(uint targetId) + { + if (targetId == 0) return false; + lock (_queryHealthLock) + { + if (_queryHealthQueue.Contains(targetId)) + return true; // already pending; one reply answers both + if (_queryHealthQueue.Count >= MaxQueryHealthQueue) + { + Interlocked.Increment(ref _dropped); + return false; + } + _queryHealthQueue.Enqueue(targetId); + Volatile.Write(ref _queryHealthPending, _queryHealthQueue.Count); + return true; + } + } + + // Single-consumer drain on AC's main thread (from Drain()). On the main thread + // CombatActionHooks.QueryHealth sends the 0x1BF directly. + private static void DrainQueryHealth() + { + if (Volatile.Read(ref _queryHealthPending) == 0) return; + int budget; + lock (_queryHealthLock) budget = _queryHealthQueue.Count; + while (budget-- > 0) + { + uint id; + lock (_queryHealthLock) + { + if (_queryHealthQueue.Count == 0) { Volatile.Write(ref _queryHealthPending, 0); return; } + id = _queryHealthQueue.Dequeue(); + Volatile.Write(ref _queryHealthPending, _queryHealthQueue.Count); + } + try { CombatActionHooks.QueryHealth(id); } catch { } + } + } + // ── Chat slot (WriteToChat strings) ────────────────────────────────────────── // WriteToChat carries a string, which can't ride the uint Entry queue. Off-thread // AddTextToScroll races AC's chat-scroll buffer and corrupts it (the recurring @@ -473,7 +738,10 @@ internal static class AcMainThreadQueue // IsOnMainThread gate is satisfied here so it runs AddTextToScroll directly. private static void DrainChat() { - while (true) + // Bounded like DrainChatCommands: a re-queue never spins the main thread. + int budget; + lock (_chatLock) budget = _chatQueue.Count; + while (budget-- > 0) { (string Text, int ChatType) item; lock (_chatLock) @@ -522,7 +790,11 @@ internal static class AcMainThreadQueue // instead of re-enqueuing. private static void DrainChatCommands() { - while (true) + // Only what was queued before this drain: anything a dispatch queues again + // waits for the next frame instead of spinning here. + int budget; + lock (_chatCommandLock) budget = _chatCommandQueue.Count; + while (budget-- > 0) { string text; lock (_chatCommandLock) diff --git a/src/RynthCore.Engine/Compatibility/AccountHooks.cs b/src/RynthCore.Engine/Compatibility/AccountHooks.cs index 6736281..293a316 100644 --- a/src/RynthCore.Engine/Compatibility/AccountHooks.cs +++ b/src/RynthCore.Engine/Compatibility/AccountHooks.cs @@ -75,6 +75,7 @@ internal static class AccountHooks private static SendNoticeWorldNameDelegate? _sendNoticeWorldNameDetour; private static string? _cachedAccountName; private static string? _cachedWorldName; + private static volatile string? _announcedWorldName; public static bool IsInitialized { get; private set; } public static bool WorldHookInstalled { get; private set; } @@ -153,6 +154,7 @@ internal static class AccountHooks if (!string.IsNullOrEmpty(name)) { _cachedWorldName = name; + _announcedWorldName = name; RynthLog.Verbose($"Compat: world name captured - \"{name}\"."); } } @@ -161,9 +163,21 @@ internal static class AccountHooks } catch { } + // The account id is set by now (login): warm the account-name cache here + // on the main thread so off-thread readers find it filled. + try { WarmFromMainThread(); } + catch { } + return result; } + /// <summary> + /// The world name the server itself announced at login (the SendNotice_WorldName hook), + /// or null. Unlike TryGetWorldName it never falls back to the launcher's profile name, + /// which the player chose (ServerInfo's detection wants what the server said). Any thread. + /// </summary> + public static string? AnnouncedWorldName => _announcedWorldName; + /// <summary> /// Returns the current account name. Result is cached after the first successful read. /// </summary> @@ -171,12 +185,50 @@ internal static class AccountHooks { name = string.Empty; - if (_cachedAccountName != null) + string? cached = Volatile.Read(ref _cachedAccountName); + if (cached != null) { - name = _cachedAccountName; + name = cached; return true; } + // Cold cache off AC's main thread (host GetAccountNameFn on the plugin pump: + // RynthNet identity push, meta expressions, RynthLua): report "not yet". + // Client::GetInstance / Client::GetAccountName and the PSRefBuffer read run + // on the main thread only (WarmFromMainThread), which fills the cache + // during login, normally before any plugin asks. + if (!MainThreadGuard.IsOnMainThread()) + return false; + + return TryReadAccountNameNative(out name); + } + + private static long _nextAccountNameWarmMs; + + /// <summary> + /// Main thread only (MainThreadSnapshots.Tick, and the end of the + /// SendNotice_WorldName detour). Fills the account-name cache while it is cold, + /// at most every 500 ms; a single null check once it is warm. + /// </summary> + internal static void WarmFromMainThread() + { + if (Volatile.Read(ref _cachedAccountName) != null || !MainThreadGuard.IsOnMainThread()) + return; + long now = Environment.TickCount64; + if (now < _nextAccountNameWarmMs) + return; + _nextAccountNameWarmMs = now + 500; + TryReadAccountNameNative(out _); + } + + // The native read (body unchanged). MAIN THREAD ONLY. + private static bool TryReadAccountNameNative(out string name) + { + name = string.Empty; + + if (!MainThreadGuard.IsOnMainThread()) + return false; + if (_getClientInstance == null || _getAccountName == null) return false; @@ -205,7 +257,7 @@ internal static class AccountHooks if (string.IsNullOrEmpty(str)) return false; - _cachedAccountName = str; + Volatile.Write(ref _cachedAccountName, str); name = str; return true; } diff --git a/src/RynthCore.Engine/Compatibility/AelrynthWire.cs b/src/RynthCore.Engine/Compatibility/AelrynthWire.cs new file mode 100644 index 0000000..0f9b726 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AelrynthWire.cs @@ -0,0 +1,403 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/AelrynthWire.cs +// +// Pure parsing for the Aelrynth-only features: no AC, no engine state, so the +// offline tests (tools/AelrynthTests) compile this file as is. +// +// ServerDetect which server the client is on, from the launch command line +// (-h host[:port] -p port), the world name the server announced +// at login, and the Bank mod's custom player properties. +// MasteryWire the SkillMastery mod's /mastery-data reply: ONE chat line, +// "~ael1 " + a JSON object (Mods/src/Aeshnidae.SkillMastery, +// DataCommand.cs + CompanionFeed.cs), and ACE's "Unknown +// command: <name>" refusal. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.Json; + +namespace RynthCore.Engine.Compatibility; + +/// <summary>Where the launch command line says the client connects.</summary> +internal enum ServerHostKind +{ + /// <summary>No -h on the command line (or it couldn't be read).</summary> + Unknown, + /// <summary>aelrynth.com (or a subdomain) / 144.217.84.148, any port.</summary> + Aelrynth, + /// <summary>Loopback or a private LAN address: a developer's own server.</summary> + Local, + /// <summary>Any other host: somebody else's server.</summary> + Other, +} + +/// <summary>One detection result. Immutable.</summary> +internal sealed class ServerVerdict +{ + public bool IsAelrynth { get; init; } + public bool IsStaging { get; init; } + /// <summary>Plain-English why, for /rc server and the log.</summary> + public string Reason { get; init; } = ""; + + public static readonly ServerVerdict Unknown = new() { Reason = "nothing known yet" }; +} + +internal static class ServerDetect +{ + public const string AelrynthDomain = "aelrynth.com"; + public const string AelrynthIp = "144.217.84.148"; + /// <summary>The live world (9020, 9021 the second socket ACE opens).</summary> + public const int LivePortLow = 9020, LivePortHigh = 9021; + /// <summary>The staging world on the same VPS (ops/staging.sh).</summary> + public const int StagingPort = 9030; + + /// <summary>The Bank mod's custom PropertyInt64 ids (Aeshnidae.Bank ClientTotals): Radiance earned, Luminance banked, Luminance drawn this session.</summary> + public const uint RadianceEarnedProperty = 9101, LuminanceBankedProperty = 9102, LuminanceDrawnProperty = 9103; + + /// <summary> + /// The host and port from acclient's command line: "-h host:port" (the RynthCore + /// launcher's ACE form) or "-h host -p port" (GDLE form, other launchers). Only + /// -h and -p are read; the rest (account, password) is never kept. + /// </summary> + public static bool TryParseLaunchHost(string? commandLine, out string host, out int port) + { + host = ""; + port = 0; + if (string.IsNullOrEmpty(commandLine)) + return false; + List<string> args = SplitArgs(commandLine); + for (int i = 0; i + 1 < args.Count; i++) + { + if (string.Equals(args[i], "-h", StringComparison.OrdinalIgnoreCase)) + { + string v = args[i + 1].Trim(); + int colon = v.LastIndexOf(':'); + if (colon > 0 && v.IndexOf(':') == colon + && int.TryParse(v.AsSpan(colon + 1), NumberStyles.None, CultureInfo.InvariantCulture, out int p)) + { + host = v.Substring(0, colon); + if (port == 0) port = p; + } + else + { + host = v; + } + } + else if (string.Equals(args[i], "-p", StringComparison.OrdinalIgnoreCase) + && int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out int p)) + { + port = p; + } + } + host = host.Trim().TrimEnd('.').ToLowerInvariant(); + return host.Length > 0; + } + + /// <summary>Windows command-line splitting, enough for the launchers' quoting (quotes group, \" is a quote).</summary> + private static List<string> SplitArgs(string s) + { + var list = new List<string>(); + var cur = new System.Text.StringBuilder(); + bool inQuotes = false, any = false; + for (int i = 0; i < s.Length; i++) + { + char c = s[i]; + if (c == '\\' && i + 1 < s.Length && s[i + 1] == '"') { cur.Append('"'); i++; any = true; continue; } + if (c == '"') { inQuotes = !inQuotes; any = true; continue; } + if (!inQuotes && char.IsWhiteSpace(c)) + { + if (any) { list.Add(cur.ToString()); cur.Clear(); any = false; } + continue; + } + cur.Append(c); + any = true; + } + if (any) list.Add(cur.ToString()); + return list; + } + + public static ServerHostKind ClassifyHost(string? host) + { + if (string.IsNullOrWhiteSpace(host)) + return ServerHostKind.Unknown; + string h = host.Trim().TrimEnd('.').ToLowerInvariant(); + if (h == AelrynthDomain || h.EndsWith("." + AelrynthDomain, StringComparison.Ordinal) || h == AelrynthIp) + return ServerHostKind.Aelrynth; + if (h == "localhost" || h == "::1" || h == "[::1]" || h.StartsWith("127.", StringComparison.Ordinal) + || h.StartsWith("10.", StringComparison.Ordinal) || h.StartsWith("192.168.", StringComparison.Ordinal) + || IsPrivate172(h)) + return ServerHostKind.Local; + return ServerHostKind.Other; + } + + private static bool IsPrivate172(string h) + { + if (!h.StartsWith("172.", StringComparison.Ordinal)) return false; + int dot = h.IndexOf('.', 4); + return dot > 4 && int.TryParse(h.AsSpan(4, dot - 4), NumberStyles.None, CultureInfo.InvariantCulture, out int b) + && b >= 16 && b <= 31; + } + + /// <summary>The server's own name for the world: Aelrynth, or Aeshnidae (its earlier name, still in the live config).</summary> + public static bool IsAelrynthWorldName(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return false; + string n = name.Trim(); + return n.StartsWith("Aelrynth", StringComparison.OrdinalIgnoreCase) + || n.StartsWith("Aeshnidae", StringComparison.OrdinalIgnoreCase); + } + + /// <summary> + /// Combines the signals. Unknown means not Aelrynth. + /// - Aelrynth's host (domain or IP, any port): yes. Port 9030 or a world name + /// with "Staging" in it is the staging world (same mods, IsStaging). + /// - Somebody else's public host: no, unless BOTH server-sent signals agree + /// (the announced world name and the Bank mod's properties) - Aelrynth on a + /// new address before this list knows it. + /// - A local/LAN host or no host at all: yes when the server announced an + /// Aelrynth world name or sends the Bank mod's properties (a dev copy). + /// </summary> + public static ServerVerdict Decide(ServerHostKind hostKind, string? host, int port, string? announcedWorld, bool bankProperties) + { + bool worldMatch = IsAelrynthWorldName(announcedWorld); + bool stagingName = announcedWorld != null && announcedWorld.IndexOf("staging", StringComparison.OrdinalIgnoreCase) >= 0; + string where = host is { Length: > 0 } ? (port > 0 ? $"{host}:{port}" : host) : "no host on the command line"; + string world = announcedWorld is { Length: > 0 } ? $"world \"{announcedWorld}\"" : "no world name yet"; + string bank = bankProperties ? "Bank properties seen" : "no Bank properties"; + + switch (hostKind) + { + case ServerHostKind.Aelrynth: + { + bool staging = port == StagingPort || stagingName; + return new ServerVerdict + { + IsAelrynth = true, + IsStaging = staging, + Reason = $"Aelrynth{(staging ? " staging" : "")}: connected to {where} ({world}, {bank})", + }; + } + case ServerHostKind.Other: + if (worldMatch && bankProperties) + return new ServerVerdict + { + IsAelrynth = true, + IsStaging = stagingName, + Reason = $"Aelrynth: {where} is not a known Aelrynth address, but the server says {world} and sends Bank properties", + }; + return new ServerVerdict { Reason = $"not Aelrynth: connected to {where} ({world}, {bank})" }; + default: + if (worldMatch || bankProperties) + return new ServerVerdict + { + IsAelrynth = true, + IsStaging = stagingName, + Reason = $"Aelrynth (local copy): {where}, {world}, {bank}", + }; + return new ServerVerdict { Reason = $"not Aelrynth: {where}, {world}, {bank}" }; + } + } +} + +/// <summary>One trained skill's mastery, as /mastery-data sends it.</summary> +internal sealed class MasterySkill +{ + public int Id; // STypeSkill + public string Key = ""; // Skill enum name, lower case: what /raise takes + public string Name = ""; + public bool Specialized; + public long Base, Current; // the server's, mastery bonus included + public int Ranks; // mastery ranks bought (RanksPerSkillPoint of them make a point) + public string Points = ""; // ranks as points, "3.7" + public int Bonus; // whole points on the skill now + public long Next; // Radiance for the next raise; 0 at the ceiling + public int Afford; // raises in a row the banked Radiance pays for (capped at 999) + public bool Ceiling; // at the server's mastery ceiling + public bool Locked; // the server wants the retail maximum first +} + +/// <summary>One /mastery-data reply. Immutable once parsed.</summary> +internal sealed class MasteryData +{ + public bool Ok; + public string Why = ""; + public bool Enabled; + public long Radiance; // banked Radiance on the account: what a raise spends + public int PerPoint = 1; // raises per skill point + public int CeilingPoints; // 0 = no ceiling + public bool RequireCap; + public Dictionary<int, MasterySkill> Skills = new(); +} + +internal static class MasteryWire +{ + /// <summary>The Companion wire prefix (CompanionFeed.Prefix in the server mods).</summary> + public const string Prefix = "~ael1 "; + public const string DataCommand = "mastery-data"; + + /// <summary> + /// The prefix within the line's first 32 characters (in case the client puts + /// something in front), with no quote before it: a player who SAYS "~ael1 {...}" + /// arrives as Name says, "~ael1 ..." and is not a server line. + /// </summary> + public static bool IsDataLine(string? line) => PrefixAt(line) >= 0; + + private static int PrefixAt(string? line) + { + if (line == null || line.Length < Prefix.Length) return -1; + int at = line.IndexOf(Prefix, StringComparison.Ordinal); + return at >= 0 && at <= 32 && line.LastIndexOf('"', at) < 0 ? at : -1; + } + + /// <summary>The data line's "t" (what it is), or "" when it isn't one or can't be read.</summary> + public static string TypeOf(string? line) + { + int at = PrefixAt(line); + if (at < 0) return ""; + try + { + using JsonDocument doc = JsonDocument.Parse(Body(line!, at)); + return doc.RootElement.ValueKind == JsonValueKind.Object ? Str(doc.RootElement, "t") : ""; + } + catch { return ""; } + } + + private static string Body(string line, int at) + { + string body = line.Substring(at + Prefix.Length); + int end = body.LastIndexOf('}'); + return end >= 0 ? body.Substring(0, end + 1) : body; + } + + /// <summary> + /// Parses a /mastery-data line ("t":"mastery"). False for any other line, another + /// "t", or JSON that can't be read. Fields the server adds later are ignored; + /// missing ones keep their defaults. + /// </summary> + public static bool TryParse(string? line, out MasteryData? data) + { + data = null; + int at = PrefixAt(line); + if (at < 0) return false; + try + { + using JsonDocument doc = JsonDocument.Parse(Body(line!, at)); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object || Str(root, "t") != "mastery") + return false; + var d = new MasteryData + { + Ok = Bool(root, "ok"), + Why = Str(root, "why"), + Enabled = Bool(root, "enabled"), + Radiance = Math.Max(0, Long(root, "radiance")), + PerPoint = (int)Math.Clamp(Long(root, "perPoint", 1), 1, 1_000_000), + CeilingPoints = (int)Math.Clamp(Long(root, "ceiling"), 0, int.MaxValue), + RequireCap = Bool(root, "requireCap"), + }; + if (root.TryGetProperty("skills", out JsonElement skills) && skills.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement s in skills.EnumerateArray()) + { + if (s.ValueKind != JsonValueKind.Object) continue; + int id = (int)Math.Clamp(Long(s, "id"), 0, int.MaxValue); + string key = Str(s, "k"); + if (id <= 0 || !IsSkillKey(key)) continue; + d.Skills[id] = new MasterySkill + { + Id = id, + Key = key, + Name = Str(s, "name"), + Specialized = Str(s, "adv") == "spec", + Base = Long(s, "base"), + Current = Long(s, "cur"), + Ranks = (int)Math.Clamp(Long(s, "ranks"), 0, int.MaxValue), + Points = Str(s, "points"), + Bonus = (int)Math.Clamp(Long(s, "bonus"), 0, int.MaxValue), + Next = Math.Max(0, Long(s, "next")), + Afford = (int)Math.Clamp(Long(s, "afford"), 0, int.MaxValue), + Ceiling = Bool(s, "ceiling"), + Locked = Bool(s, "locked"), + }; + } + } + data = d; + return true; + } + catch + { + return false; + } + } + + /// <summary> + /// ACE's refusal of a command it doesn't have: "Unknown command: <name>" + /// (GameActionTalk). True when <paramref name="line"/> is that for <paramref name="command"/>. + /// </summary> + public static bool IsUnknownCommand(string? line, string command) + { + const string marker = "Unknown command: "; + if (line == null) return false; + int at = line.IndexOf(marker, StringComparison.Ordinal); + if (at < 0 || at > 32 || (at > 0 && line.LastIndexOf('"', at - 1) >= 0)) return false; + return string.Equals(line.Substring(at + marker.Length).Trim(), command, StringComparison.OrdinalIgnoreCase); + } + + /// <summary>A Skill enum name in lower case ("meleedefense"): what the mod's /raise matches.</summary> + public static bool IsSkillKey(string? key) + { + if (string.IsNullOrEmpty(key) || key.Length > 40) return false; + foreach (char c in key) + if (c < 'a' || c > 'z') return false; + return true; + } + + /// <summary> + /// The server command text for a raise, as the client sends a typed "/raise ..." + /// (ACE runs Talk text that starts with '@' as a command): "@raise meleedefense 1". + /// Null when the key or count isn't one the mod's parser reads unambiguously. + /// </summary> + public static string? RaiseCommand(string? key, int count) + { + if (!IsSkillKey(key) || count < 1 || count > 999) return null; + return "@raise " + key + " " + count.ToString(CultureInfo.InvariantCulture); + } + + /// <summary>The server command text that asks for the data line.</summary> + public const string DataRequest = "@" + DataCommand; + + // ── JSON helpers: tolerant of type drift (a number sent as a string, and the reverse) ── + + private static string Str(JsonElement o, string name) + { + if (!o.TryGetProperty(name, out JsonElement v)) return ""; + return v.ValueKind switch + { + JsonValueKind.String => v.GetString() ?? "", + JsonValueKind.Number => v.GetRawText(), + JsonValueKind.True => "true", + JsonValueKind.False => "false", + _ => "", + }; + } + + private static long Long(JsonElement o, string name, long fallback = 0) + { + if (!o.TryGetProperty(name, out JsonElement v)) return fallback; + if (v.ValueKind == JsonValueKind.Number) + { + if (v.TryGetInt64(out long l)) return l; + if (v.TryGetDouble(out double d)) return d >= long.MaxValue ? long.MaxValue : d <= long.MinValue ? long.MinValue : (long)d; + return fallback; + } + if (v.ValueKind == JsonValueKind.String + && long.TryParse(v.GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out long s)) + return s; + return fallback; + } + + private static bool Bool(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True; +} diff --git a/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs index ac3daf0..2334a06 100644 --- a/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs +++ b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs @@ -1,10 +1,13 @@ // ============================================================================ // RynthCore.Engine - Compatibility/AppraisalHooks.cs // -// Hooks CM_Examine::SendNotice_SetAppraiseInfo to cache appraisal bool -// properties for inventory items whose m_pQualities is null. -// CBaseQualities::InqBool returns 0 for such items because the property -// setter skips CBaseQualities storage when m_pQualities is null. +// Caches what the last identify of each object carried, for objects whose +// m_pQualities is null (CBaseQualities::Inq* return 0 for them) and for every +// read off AC's main thread (where no Inq* may run). Two feeds: the identify +// message itself (OnIdentifyWire, from SmartBoxHooks.ParseGameEvent: all six +// tables plus the armour/weapon/hook profiles, see PropertyWire) and, merged +// over it, AC's parsed AppraisalProfile via a hook on +// CM_Examine::SendNotice_SetAppraiseInfo (int, bool, string, spells, vitals). // // VA derivation (map_offset + 0x00401000 = live VA): // 002AF5B0 CM_Examine::SendNotice_SetAppraiseInfo → 0x006B05B0 @@ -57,12 +60,23 @@ internal static class AppraisalHooks private static readonly HashSet<uint> _appraisedGuids = new(); // Unix timestamp (seconds) of last appraisal receipt per guid private static readonly Dictionary<uint, long> _lastIdTime = new(); - // Int property cache: guid → (stype → value) - private static readonly Dictionary<uint, Dictionary<uint, int>> _intCache = new(); - // Bool property cache: guid → (stype → value) - private static readonly Dictionary<uint, Dictionary<uint, bool>> _boolCache = new(); - // String property cache: guid → (stype → value) - private static readonly Dictionary<uint, Dictionary<uint, string>> _stringCache = new(); + // Every property the last identify of an object carried: guid → bag (2026-09-30). + // Two sources, both on AC's main thread inside UIQueueManager::ProcessNetBlobData: + // - the identify message itself (SmartBoxHooks.ParseGameEvent → OnIdentifyWire, before + // AC handles it): all six tables (int, int64, bool, float, string, data id) plus the + // armour/weapon/hook profile values filed under their property ids (PropertyWire); + // - AC's parsed AppraisalProfile (SendNoticeDetour, after): int, bool and string, the + // long-proven path, merged over the wire values. + // Before, only the second existed, so int64, float and data id properties never answered + // off the main thread (the float capture of 2026-09-30 sat in a parser nothing called). + private static readonly Dictionary<uint, PropertyBag> _bags = new(); + // The guid whose wire record ParseGameEvent stored in the current dispatch (main thread only): + // SendNoticeDetour then merges AC's tables into it instead of replacing them. + private static uint _wireGuidThisDispatch; + private static int _wireLogCount, _wireMissLogCount; + // Hard cap on identified objects kept (they are also evicted on delete and cleared on + // logout). Past it the oldest identify is dropped. + private const int MaxAppraisedObjects = 4096; // Spell book cache: guid → spell ID array (from AppraisalProfile._spellBook PSmartArray<UInt32> at +0x30) private static readonly Dictionary<uint, uint[]> _spellIdCache = new(); private static readonly object _cacheLock = new(); @@ -97,14 +111,138 @@ internal static class AppraisalHooks { _appraisedGuids.Clear(); _lastIdTime.Clear(); - _intCache.Clear(); - _boolCache.Clear(); - _stringCache.Clear(); + _bags.Clear(); _spellIdCache.Clear(); _failedRollLogged.Clear(); } } + /// <summary>Drops everything cached for an object AC deleted (PropertyUpdateHooks' BeingDeleted hook).</summary> + public static void EvictObject(uint guid) + { + lock (_cacheLock) + { + _appraisedGuids.Remove(guid); + _lastIdTime.Remove(guid); + _bags.Remove(guid); + _spellIdCache.Remove(guid); + _failedRollLogged.Remove(guid); + } + } + + public static int CachedObjectCount + { + get { lock (_cacheLock) return _bags.Count; } + } + + // Caller holds _cacheLock. Keeps the bag count under MaxAppraisedObjects by dropping the + // object identified longest ago (a scan, only when the cap is hit). + private static void EnforceCapLocked(uint keep) + { + while (_bags.Count >= MaxAppraisedObjects) + { + uint oldest = 0; + long oldestTime = long.MaxValue; + foreach (uint g in _bags.Keys) + { + if (g == keep) continue; + long t = _lastIdTime.TryGetValue(g, out long v) ? v : 0; + if (t < oldestTime) { oldestTime = t; oldest = g; } + } + if (oldest == 0) return; + _bags.Remove(oldest); + _appraisedGuids.Remove(oldest); + _lastIdTime.Remove(oldest); + _spellIdCache.Remove(oldest); + } + } + + // Caller holds _cacheLock. + private static PropertyBag GetOrAddBagLocked(uint guid) + { + if (!_bags.TryGetValue(guid, out PropertyBag? bag)) + { + EnforceCapLocked(guid); + _bags[guid] = bag = new PropertyBag(); + } + return bag; + } + + /// <summary> + /// Stores what an identify message carried (PropertyWire.TryParseIdentify), replacing the + /// object's previous identify. AC's main thread, from SmartBoxHooks.ParseGameEvent, just + /// before AC handles the message; SendNoticeDetour then merges AC's own tables in. + /// </summary> + internal static void StoreIdentify(IdentifyRecord rec) + { + lock (_cacheLock) + { + if (!_bags.ContainsKey(rec.ObjectId)) + EnforceCapLocked(rec.ObjectId); + _bags[rec.ObjectId] = rec.Properties; + } + _wireGuidThisDispatch = rec.ObjectId; + + if (_wireLogCount < 20) + { + _wireLogCount++; + PropertyBag b = rec.Properties; + RynthLog.Compat($"Compat: identify wire obj=0x{rec.ObjectId:X8} flags=0x{rec.Flags:X4} ok={rec.Success} " + + $"int={b.Ints.Count} int64={b.Int64s.Count} bool={b.Bools.Count} float={b.Floats.Count} " + + $"string={b.Strings.Count} did={b.DataIds.Count} armor={rec.HasArmorProfile} weapon={rec.HasWeaponProfile} " + + $"hook={rec.HasHookProfile} creature={rec.HasCreatureProfile}{(rec.Truncated ? " TRUNCATED" : "")}"); + } + } + + /// <summary> + /// The identify message (game event 0xC9) as UIQueueManager::ProcessNetBlobData received it, + /// from its event type on. AC's main thread, before AC handles it. Never touches AC state. + /// </summary> + internal static unsafe void OnIdentifyWire(IntPtr data, int size) + { + _wireGuidThisDispatch = 0; + if (data == IntPtr.Zero || size < 16) + return; + if (PropertyWire.TryParseIdentify(new ReadOnlySpan<byte>((void*)data, size), out IdentifyRecord rec)) + StoreIdentify(rec); + } + + /// <summary> + /// Folds a property update into an already-identified object so the cache doesn't keep + /// serving the value from the last identify (a used pet essence's Structure, a changed + /// float or string). Objects never identified are left alone; PropertyUpdateHooks keeps + /// their updates. + /// </summary> + internal static void ApplyUpdate(uint guid, in PropertyUpdate u) + { + lock (_cacheLock) + { + if (_bags.TryGetValue(guid, out PropertyBag? bag)) + bag.Apply(u); + } + } + + public static bool TryGetCachedInt64Property(uint guid, uint stype, out long value) + { + value = 0; + lock (_cacheLock) + return _bags.TryGetValue(guid, out PropertyBag? b) && b.Int64s.TryGetValue(stype, out value); + } + + public static bool TryGetCachedDataIdProperty(uint guid, uint stype, out uint value) + { + value = 0; + lock (_cacheLock) + return _bags.TryGetValue(guid, out PropertyBag? b) && b.DataIds.TryGetValue(stype, out value); + } + + public static bool TryGetCachedInstanceIdProperty(uint guid, uint stype, out uint value) + { + value = 0; + lock (_cacheLock) + return _bags.TryGetValue(guid, out PropertyBag? b) && b.InstanceIds.TryGetValue(stype, out value); + } + /// <summary> /// Returns the Unix timestamp (seconds) of when appraisal data was last received for this guid, or 0 if never. /// </summary> @@ -122,35 +260,7 @@ internal static class AppraisalHooks { value = 0; lock (_cacheLock) - { - if (!_intCache.TryGetValue(guid, out Dictionary<uint, int>? props)) - return false; - return props.TryGetValue(stype, out value); - } - } - - /// <summary> - /// Applies a later server property update to an already-appraised object so the cache - /// doesn't keep serving the value from the last ID. Objects never appraised are left - /// alone (the update cache covers them). - /// </summary> - public static void PatchCachedInt(uint guid, uint stype, int value) - { - lock (_cacheLock) - { - if (_intCache.TryGetValue(guid, out Dictionary<uint, int>? props)) - props[stype] = value; - } - } - - /// <summary>Bool counterpart of <see cref="PatchCachedInt"/>.</summary> - public static void PatchCachedBool(uint guid, uint stype, bool value) - { - lock (_cacheLock) - { - if (_boolCache.TryGetValue(guid, out Dictionary<uint, bool>? props)) - props[stype] = value; - } + return _bags.TryGetValue(guid, out PropertyBag? b) && b.Ints.TryGetValue(stype, out value); } /// <summary> @@ -161,11 +271,15 @@ internal static class AppraisalHooks { value = false; lock (_cacheLock) - { - if (!_boolCache.TryGetValue(guid, out Dictionary<uint, bool>? props)) - return false; - return props.TryGetValue(stype, out value); - } + return _bags.TryGetValue(guid, out PropertyBag? b) && b.Bools.TryGetValue(stype, out value); + } + + /// <summary>A float (double) property from the last server appraisal of this object.</summary> + public static bool TryGetCachedDoubleProperty(uint guid, uint stype, out double value) + { + value = 0; + lock (_cacheLock) + return _bags.TryGetValue(guid, out PropertyBag? b) && b.Floats.TryGetValue(stype, out value); } /// <summary> @@ -177,9 +291,27 @@ internal static class AppraisalHooks value = string.Empty; lock (_cacheLock) { - if (!_stringCache.TryGetValue(guid, out Dictionary<uint, string>? props)) - return false; - return props.TryGetValue(stype, out value!); + if (_bags.TryGetValue(guid, out PropertyBag? b) && b.Strings.TryGetValue(stype, out string? s)) + { + value = s; + return true; + } + return false; + } + } + + // SendNoticeDetour's tables from AC's AppraisalProfile. When this dispatch's wire record is + // in place they are merged over it (same keys win, the profile-derived values stay); when + // the wire parse didn't run, they replace the table as they always did. + private static void StoreProfileTable<T>(uint guid, Dictionary<uint, T> props, Func<PropertyBag, Dictionary<uint, T>> table) + { + lock (_cacheLock) + { + PropertyBag bag = GetOrAddBagLocked(guid); + Dictionary<uint, T> dst = table(bag); + if (_wireGuidThisDispatch != guid) + dst.Clear(); + foreach (var kv in props) dst[kv.Key] = kv.Value; } } @@ -242,6 +374,14 @@ internal static class AppraisalHooks _lastIdTime[guid] = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); } + if (_wireGuidThisDispatch != guid && _wireMissLogCount < 5 && SmartBoxHooks.IsGameEventHookInstalled) + { + // The identify reached AC's handler without its wire record: int64, float and data + // id properties (and the profile values) are missing for it. Seen once per few ids. + _wireMissLogCount++; + RynthLog.Compat($"Compat: identify 0x{guid:X8} reached SetAppraiseInfo without its wire record - only int/bool/string cached."); + } + try { CacheIntProps(guid, profilePtr); @@ -287,6 +427,7 @@ internal static class AppraisalHooks try { RynthLog.Compat($"Compat: appraisal creature-vitals error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { } } + _wireGuidThisDispatch = 0; return result; } @@ -339,10 +480,7 @@ internal static class AppraisalHooks if (props.Count == 0) return; - lock (_cacheLock) - { - _intCache[guid] = props; - } + StoreProfileTable(guid, props, b => b.Ints); RynthLog.Verbose($"Compat: cached {props.Count} int prop(s) for guid=0x{guid:X8}"); } @@ -396,10 +534,7 @@ internal static class AppraisalHooks if (props.Count == 0) return; - lock (_cacheLock) - { - _boolCache[guid] = props; - } + StoreProfileTable(guid, props, b => b.Bools); RynthLog.Verbose($"Compat: cached {props.Count} bool prop(s) for guid=0x{guid:X8}"); } @@ -471,10 +606,7 @@ internal static class AppraisalHooks if (props.Count == 0) return; - lock (_cacheLock) - { - _stringCache[guid] = props; - } + StoreProfileTable(guid, props, b => b.Strings); RynthLog.Verbose($"Compat: cached {props.Count} string prop(s) for guid=0x{guid:X8}"); } @@ -588,6 +720,10 @@ internal static class AppraisalHooks } else { + // CreatureAppraisalProfile.enchantment_bitfield (+0x34): low 9 bits = attribute / vital + // modified, bits 16..24 = modified upward. The nameplates' "debuffed by others" marker. + ImGuiBackend.Hud.HudFeed.OnAppraisal(guid, unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x34))); + int log = Interlocked.Increment(ref _creatureVitalsLogCount); if (log <= 50) RynthLog.Compat($"Compat: appraisal creature vitals guid=0x{guid:X8} hp={health}/{maxHealth} stam={stamina}/{maxStamina} mana={mana}/{maxMana}"); diff --git a/src/RynthCore.Engine/Compatibility/AutoIdService.cs b/src/RynthCore.Engine/Compatibility/AutoIdService.cs index 1412784..6421c20 100644 --- a/src/RynthCore.Engine/Compatibility/AutoIdService.cs +++ b/src/RynthCore.Engine/Compatibility/AutoIdService.cs @@ -113,6 +113,13 @@ internal static class AutoIdService // Object may have been destroyed between enqueue and drain if (objectId == 0) continue; + // Deleted since it was queued: Evict took it out of _sent. Skip it without + // spending one of the 3 requests per tick. After a big landblock change (the + // 585 deletes of 2026-10-02) the queue otherwise kept asking the server to + // appraise gone objects at 30 a second for half a minute, and live ones waited. + // A delete-then-recreate is queued again by Enqueue, so nothing live is lost. + if (!_sent.ContainsKey(objectId)) + continue; // Marshal onto AC's main thread (EndScene drain) — the Timer thread must // not call the native 0xC8 send directly (off-thread heap alloc + non-atomic diff --git a/src/RynthCore.Engine/Compatibility/BusyCountHooks.cs b/src/RynthCore.Engine/Compatibility/BusyCountHooks.cs index 80913fe..6c3f8eb 100644 --- a/src/RynthCore.Engine/Compatibility/BusyCountHooks.cs +++ b/src/RynthCore.Engine/Compatibility/BusyCountHooks.cs @@ -132,10 +132,17 @@ internal static class BusyCountHooks int was = _netBusyCount; - if (_originalDecrementBusyCount != null) + // Decrement exactly what the REAL field holds, never past zero. This used + // to call the original decrement max(shadow, 3) times: with the real field + // already 0 (AC's UseDone decrements it inline, which the shadow never + // sees) that walked it to -1..-3 before the write below put it back. + // m_cBusy only drives the cursor (UpdateCursorState: != 0 = busy cursor), + // so this was never the item-action lock, but there is no reason to + // write below zero. See ClientActionGates for the gates AC really checks. + int real = Marshal.ReadInt32(_lastThisPtr + OffsetMCBusy); + if (_originalDecrementBusyCount != null && real > 0) { - int calls = Math.Max(was, 3); - for (int i = 0; i < calls && i < 20; i++) + for (int i = 0; i < real && i < 20; i++) _originalDecrementBusyCount(_lastThisPtr); } @@ -171,11 +178,72 @@ internal static class BusyCountHooks catch { /* non-fatal */ } } - RynthLog.Verbose($"Compat: force-reset busy count (was {was})"); + RynthLog.Verbose($"Compat: force-reset busy count (was real {real}, shadow {was})"); + } + + // ── Negative m_cBusy repair ───────────────────────────────────────────── + // AC never takes m_cBusy below what it added; only a zeroing of ours can: + // a force-clear (or the direct-action reconciler) zeroes a count whose + // action is still in flight, then the server's UseDone decrements it + // inline (Handle_Item::UseDone, not through DecrementBusyCount) to -1. + // The real-field watchdog only looks at > 0, so the negative value stayed + // for the session: a permanent busy cursor. Repair it after a short grace. + private static long _realBusyNegativeSince; + private static long _negativeRepairCount; + private const long NegativeBusyRepairMs = 2_000; + public static long NegativeRepairCount => Interlocked.Read(ref _negativeRepairCount); + public static int ShadowBusyCount => Volatile.Read(ref _netBusyCount); + public static int PendingReconcileDelta => _pendingCastBusyDelta; + + /// <summary>Read AC's real m_cBusy. False when the ClientUISystem isn't known/readable.</summary> + public static bool TryReadRealBusy(out int value) + { + value = 0; + IntPtr p = _lastThisPtr; + if (p == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(p + OffsetMCBusy)) + return false; + try { value = Marshal.ReadInt32(p + OffsetMCBusy); return true; } + catch { return false; } + } + + /// <summary> + /// If AC's m_cBusy is negative, set it to 0 and refresh the cursor. Main + /// thread only (returns false elsewhere). <paramref name="was"/> is the + /// value found. + /// </summary> + public static bool RepairNegativeBusy(out int was) + { + was = 0; + if (!MainThreadGuard.IsOnMainThread()) + return false; + IntPtr p = _lastThisPtr; + if (!TryReadRealBusy(out was) || was >= 0) + return false; + if (!ClientObjectHooks.IsWritablePointer(p + OffsetMCBusy)) + return false; + + Marshal.WriteInt32(p + OffsetMCBusy, 0); + Interlocked.Exchange(ref _netBusyCount, 0); + Interlocked.Increment(ref _negativeRepairCount); + if (_updateCursorStateAddress != IntPtr.Zero) + { + try + { + var updateCursor = Marshal.GetDelegateForFunctionPointer<UpdateCursorStateDelegate>(_updateCursorStateAddress); + updateCursor(p); + } + catch { /* non-fatal */ } + } + return true; } public static void Initialize() { + // The item-action gates (pending request / attacking flag) resolve on + // their own; they don't need the busy-count hooks below. + try { ClientActionGates.Initialize(); } + catch (Exception ex) { RynthLog.Compat($"ClientActionGates: init threw {ex.GetType().Name}: {ex.Message}"); } + if (IsInstalled) return; @@ -290,8 +358,10 @@ internal static class BusyCountHooks { _lastThisPtr = IntPtr.Zero; Volatile.Write(ref _realBusyPositiveTickMs, 0); + _realBusyNegativeSince = 0; _pendingCastBusyDelta = 0; _pendingCastGestureSeen = false; + try { ClientActionGates.ResetTracking(); } catch { } } // ── Direct-action busy reconciliation (source fix for the per-action leak) ── @@ -398,6 +468,29 @@ internal static class BusyCountHooks { long now = Environment.TickCount64; + // The gates AC actually checks before an item use/move/equip (pending + // inventory request, attacking flag). Runs on every call — before each + // inbound game event and after each tick — so the attacking flag's + // zero window between AttackDone and the next CommenceAttack is seen. + if (MainThreadGuard.IsOnMainThread()) + { + try { ClientActionGates.Tick(now, PlayerLifecycleLog.InWorldTransition); } + catch { } + } + + // Dead or portaling (and just after): the busy count moves on its own + // while AC rebuilds the world, and force-clearing it then writes into + // AC mid-transition — every death today crashed inside AC during the + // death portal (2026-09-28). Restart the timers so a genuinely stuck + // count is judged afresh once the world has settled. + if (PlayerLifecycleLog.InWorldTransition) + { + Volatile.Write(ref _realBusyPositiveTickMs, 0); + if (Volatile.Read(ref _busyBecamePositiveTickMs) != 0) + Volatile.Write(ref _busyBecamePositiveTickMs, now); + return; + } + // ── Real-field watchdog (catches counter desync) ───────────────────── // Trust AC's REAL m_cBusy over our shadow counter: when they diverge a // pinned real field is what actually wedges the client (mode-change / @@ -445,6 +538,40 @@ internal static class BusyCountHooks // (e.g. first beat after the next login). Volatile.Write(ref _realBusyPositiveTickMs, 0); } + + // Negative real field (ReadRealBusy folds every negative into its -1 + // "unreadable" sentinel, so read it directly). See RepairNegativeBusy. + bool haveReal = TryReadRealBusy(out int signedBusy); + if (haveReal && signedBusy < 0) + { + if (_realBusyNegativeSince == 0) + _realBusyNegativeSince = now; + else if (now - _realBusyNegativeSince >= NegativeBusyRepairMs && RepairNegativeBusy(out int neg)) + { + _realBusyNegativeSince = 0; + RynthLog.Compat($"BusyCountHooks: REAL m_cBusy was negative ({neg}) — reset to 0 (a zeroed count's own UseDone arrived later)."); + } + } + else + { + _realBusyNegativeSince = 0; + } + + // Counter-based watchdog below: the shadow counter never sees AC's + // inline UseDone decrement, so it reads "stuck" after nearly every use + // and cast even though the real field is back at 0. When the real + // field is readable and idle, just resync the shadow — force-clearing + // there only zeroed the next in-flight action (thousands of needless + // force-clears a session). A real field > 0 is the real-field + // watchdog's job above. + long shadowSince = Volatile.Read(ref _busyBecamePositiveTickMs); + if (shadowSince != 0 && haveReal && signedBusy <= 0 + && now - shadowSince >= BusyWatchdogTimeoutMs) + { + Interlocked.Exchange(ref _netBusyCount, 0); + Volatile.Write(ref _busyBecamePositiveTickMs, 0); + return; + } } // ── Counter-based watchdog (original) ──────────────────────────────── diff --git a/src/RynthCore.Engine/Compatibility/CObjectMaintHooks.cs b/src/RynthCore.Engine/Compatibility/CObjectMaintHooks.cs index 290ffc8..b9d0a45 100644 --- a/src/RynthCore.Engine/Compatibility/CObjectMaintHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CObjectMaintHooks.cs @@ -89,29 +89,7 @@ internal static class CObjectMaintHooks int count = 0; try { - for (uint i = 0; i < tableSize; i++) - { - IntPtr bucketSlot = buckets + (int)(i * 4); - if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4)) - break; - IntPtr node = Marshal.ReadIntPtr(bucketSlot); - - int chainGuard = 0; - while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket) - { - if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4)) - break; - uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET); - if (id != 0) - { - visit(id); - count++; - } - if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4)) - break; - node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET); - } - } + WalkBuckets(buckets, tableSize, visit, ref count); } catch (Exception ex) { @@ -122,6 +100,44 @@ internal static class CObjectMaintHooks return count; } + /// <summary> + /// The bucket/chain walk both enumerators share. One probe covers the whole bucket array + /// and one covers each node's hash_next + id (adjacent, +4..+12), where the walk used to + /// probe every bucket slot and each node twice: a table of 4096 buckets cost 4096+ probes + /// per walk, ten walks a second (2026-10-02 flood fix; see MemoryProbe). When a combined + /// probe fails it falls back to the old per-slot / per-field probes, so the walk stops at + /// exactly the same place as before on bad memory. <paramref name="count"/> is by ref so a + /// visitor that throws still leaves the partial count (the callers' old behaviour). + /// </summary> + private static void WalkBuckets(IntPtr buckets, uint tableSize, Action<uint> visit, ref int count) + { + bool arrayReadable = SmartBoxLocator.IsMemoryReadable(buckets, (int)(tableSize * 4)); + for (uint i = 0; i < tableSize; i++) + { + IntPtr bucketSlot = buckets + (int)(i * 4); + if (!arrayReadable && !SmartBoxLocator.IsMemoryReadable(bucketSlot, 4)) + break; + IntPtr node = Marshal.ReadIntPtr(bucketSlot); + + int chainGuard = 0; + while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket) + { + bool nodeReadable = SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 8); + if (!nodeReadable && !SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4)) + break; + uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET); + if (id != 0) + { + visit(id); + count++; + } + if (!nodeReadable && !SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4)) + break; + node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET); + } + } + } + // DIAGNOSTIC (temporary): same walk as EnumerateLiveWeenieObjectIds but over // an arbitrary CObjectMaint table (object_table +0x84 / null_object_table // +0x9C / weenie_object_table +0xB4). Duplicated rather than refactoring the @@ -151,29 +167,7 @@ internal static class CObjectMaintHooks int count = 0; try { - for (uint i = 0; i < tableSize; i++) - { - IntPtr bucketSlot = buckets + (int)(i * 4); - if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4)) - break; - IntPtr node = Marshal.ReadIntPtr(bucketSlot); - - int chainGuard = 0; - while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket) - { - if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4)) - break; - uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET); - if (id != 0) - { - visit(id); - count++; - } - if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4)) - break; - node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET); - } - } + WalkBuckets(buckets, tableSize, visit, ref count); } catch (Exception ex) { diff --git a/src/RynthCore.Engine/Compatibility/CastGate.cs b/src/RynthCore.Engine/Compatibility/CastGate.cs index c9db560..680a093 100644 --- a/src/RynthCore.Engine/Compatibility/CastGate.cs +++ b/src/RynthCore.Engine/Compatibility/CastGate.cs @@ -19,9 +19,10 @@ namespace RynthCore.Engine.Compatibility; /// <see cref="PlayerPhysicsHooks.TryGetCastGestureInProgress"/>). /// /// This is a SAMPLED gate — no acclient.exe hook is installed. <see cref="Sample"/> -/// runs on the existing 30 Hz NormalPluginPump heartbeat (PluginManager.TickAll) -/// and reads a single CMotionInterp scalar through the already-proven -/// PlayerPhysicsHooks accessor. No new detour, no pattern-scan-and-call (the +/// runs on AC's main thread (MainThreadSnapshots.Tick, from the Client::UseTime +/// drain and EndScene; it ran on the 30 Hz plugin pump until 2026-09-30, which +/// walked the player's MovementManager chain off-thread) and reads a single +/// CMotionInterp scalar through the already-proven PlayerPhysicsHooks accessor. No new detour, no pattern-scan-and-call (the /// ACE crash class), no list walk (UAF-safe). The consumer polls the gate at /// the same tick rate, so the busy→idle edge is observed without any new /// engine→plugin callback (avoids the NativeAOT reverse-P/Invoke crash class). @@ -46,7 +47,7 @@ internal static class CastGate public static int GetCastBusyState() => Volatile.Read(ref _castBusy); /// <summary> - /// Sampled from the 30 Hz plugin pump (PluginManager.TickAll). Cheap, fully + /// Sampled on AC's main thread (MainThreadSnapshots.Tick). Cheap, fully /// guarded, never throws. If CMotionInterp isn't reachable (pre-login / /// between worlds) the gate reports "clear to cast" so the consumer falls /// back to its own throttle/park, which is the hard anti-spam guarantee. diff --git a/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs b/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs index 90fc472..d4541ef 100644 --- a/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs @@ -122,12 +122,7 @@ internal static class CharacterCaptureHooks if (Interlocked.Exchange(ref _autoLoginPollStarted, 1) != 0) return; - var thread = new Thread(AutoLoginPollLoop) - { - Name = "RynthCore.AutoLoginPoll", - IsBackground = true - }; - thread.Start(); + EngineThreads.Start("RynthCore.AutoLoginPoll", AutoLoginPollLoop); RynthLog.Info($"CharacterCapture: Poll-driven auto-login armed for '{targetCharacter}'."); } @@ -139,6 +134,10 @@ internal static class CharacterCaptureHooks /// Hard-stops the instant mode==GamePlayUI or LoginComplete is observed: /// poking LogOn pointers while in-game has been correlated with AC self- /// exiting (see ScheduleAutoLoginIfRequested's notes). + /// Thread note (2026-09-30): this thread never touches AC itself any more. + /// CharacterManagementHooks serves the mode and the character list from its + /// main-thread snapshot, and TryLogOnCharacter hands the real LogOnCharacter + /// to AC's main thread and waits at most ~1.5 s for the result. /// </summary> private static void AutoLoginPollLoop() { @@ -152,9 +151,8 @@ internal static class CharacterCaptureHooks try { - while (true) + while (EngineThreads.Sleep(AutoLoginPollIntervalMs)) { - Thread.Sleep(AutoLoginPollIntervalMs); if (LoginLifecycleHooks.HasObservedLoginComplete) { @@ -254,21 +252,15 @@ internal static class CharacterCaptureHooks if (Interlocked.Exchange(ref _characterListCapturePollStarted, 1) != 0) return; - var thread = new Thread(CharacterListCapturePollLoop) - { - Name = "RynthCore.CharacterListCapture", - IsBackground = true - }; - thread.Start(); + EngineThreads.Start("RynthCore.CharacterListCapture", CharacterListCapturePollLoop); } private static void CharacterListCapturePollLoop() { try { - while (!EngineLifecycle.IsShuttingDown) + while (!EngineLifecycle.IsShuttingDown && EngineThreads.Sleep(CharacterListCapturePollIntervalMs)) { - Thread.Sleep(CharacterListCapturePollIntervalMs); // In the world: no native reads at all. if (LoginLifecycleHooks.HasObservedLoginComplete) @@ -529,7 +521,16 @@ internal static class CharacterCaptureHooks return (sessionHint.AccountName, sessionHint.ServerName, sessionHint.TargetCharacter); } - return ReadLaunchContextFile(Path.Combine(rootDir, "launch_context.json")); + // The shared launch_context.json names whatever the launcher last started. + // Only trust it for a client started at about that moment (an old launcher + // that wrote no per-process file). A client the launcher didn't start - one + // from ThwargLauncher that "watch for AC start" injected into - otherwise + // auto-logged into the launcher's last character and was knocked back to + // the desktop (2026-09-30, a player's Thwarg main closing seconds after login). + string sharedPath = Path.Combine(rootDir, "launch_context.json"); + if (!SharedContextIsForThisLaunch(sharedPath)) + return (string.Empty, string.Empty, string.Empty); + return ReadLaunchContextFile(sharedPath); } catch { @@ -537,6 +538,29 @@ internal static class CharacterCaptureHooks } } + private static int _sharedContextLogged; + + /// <summary>True when the shared launch_context.json was written within two minutes of this process starting.</summary> + private static bool SharedContextIsForThisLaunch(string sharedPath) + { + if (!File.Exists(sharedPath)) return false; + DateTime? created = null; + try + { + using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(sharedPath)); + if (doc.RootElement.TryGetProperty("CreatedAtUtc", out JsonElement c) && c.TryGetDateTime(out DateTime t)) + created = t.ToUniversalTime(); + } + catch { } + DateTime started = System.Diagnostics.Process.GetCurrentProcess().StartTime.ToUniversalTime(); + bool ours = created.HasValue && created.Value >= started.AddMinutes(-2) && created.Value <= started.AddSeconds(30); + if (Interlocked.Exchange(ref _sharedContextLogged, 1) == 0) + RynthLog.Info(ours + ? $"CharacterCapture: no per-process launch context; using the shared one (written {created:HH:mm:ss}Z, this client started {started:HH:mm:ss}Z)." + : $"CharacterCapture: no launch context for this client (not started by the RynthCore launcher; shared one from {(created.HasValue ? created.Value.ToString("HH:mm:ss") + "Z" : "?")} is another launch) - no auto-login."); + return ours; + } + private static (string accountName, string serverName, string targetCharacter) ReadLaunchContextFile(string filePath) { if (!File.Exists(filePath)) @@ -623,8 +647,8 @@ internal static class CharacterCaptureHooks { try { - Thread.Sleep(scheduledDelayMs); - PerformAutoLogin(fallbackCharacters, finalSlots, targetCharacter); + if (EngineThreads.Sleep(scheduledDelayMs)) + PerformAutoLogin(fallbackCharacters, finalSlots, targetCharacter); } finally { @@ -635,6 +659,7 @@ internal static class CharacterCaptureHooks Name = "RynthCore.AutoLogin", IsBackground = true }; + EngineThreads.Track(thread); thread.Start(); RynthLog.Verbose( diff --git a/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs b/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs index 7e3f451..0ecb841 100644 --- a/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Threading; namespace RynthCore.Engine.Compatibility; @@ -77,8 +78,226 @@ internal static class CharacterManagementHooks public static string StatusMessage => _statusMessage; + // ── Main-thread char-select service (2026-09-30 main-thread audit) ───────── + // The two char-select poll threads (RynthCore.AutoLoginPoll and + // RynthCore.CharacterListCapture, plus the dormant RynthCore.AutoLogin) used to + // call UIFlow::GetPersistantData, the CharacterSet GetIdentity/GetName/GetGid + // accessors and CPlayerSystem::LogOnCharacter straight from their own threads, + // and PtrToStringAnsi'd name buffers AC frees when char-select rebuilds the + // set (create / delete / reconnect). A freed buffer there is an uncatchable + // AV. Now: + // * MainThreadTick (AcMainThreadQueue.Drain, AC's main thread; pre-login it + // runs from the Client::UseTime drain) publishes the UIFlow mode every call + // and, at char-select, an immutable name/slot-count snapshot every 250 ms. + // * Off-thread TryReadCharacterNames / GetNativeCharacterSetSlotCount serve + // that snapshot; off-thread TryGetCurrentMode serves the published mode. + // * Off-thread TryLogOnCharacter parks the target in a one-request slot and + // waits a bounded time for the main thread to run the real call; on a + // timeout it withdraws the request (it can never fire late) and reports + // failure, which the poll loops already retry. + // The main thread never waits on anyone: it only consumes what is there. + private sealed class CharSelectSnapshot + { + public static readonly CharSelectSnapshot Empty = new(Array.Empty<string>(), 0); + public readonly string[] Names; + public readonly int SlotCount; + public CharSelectSnapshot(string[] names, int slotCount) { Names = names; SlotCount = slotCount; } + } + + private sealed class LogOnResult + { + public bool Ok; + public string Matched = string.Empty; + public uint AvatarId; + public int SlotIndex = -1; + public string Status = string.Empty; + } + + private const int CharSelectSnapshotIntervalMs = 250; + private const int LogOnRequestWaitMs = 500; // one frame at char-select is ~16-50 ms + private const int LogOnRunningGraceMs = 1000; // extra wait once the main thread has taken it + + private static volatile CharSelectSnapshot _charSelectSnapshot = CharSelectSnapshot.Empty; + private static long _nextCharSelectSnapshotMs; + private static int _publishedMode; + private static int _modePublished; // 1 once MainThreadTick has read the mode + + // Login request slot: 0 idle, 1 pending (off-thread caller armed it), + // 2 running (main thread took it), 3 done (result published). + private static int _logOnState; + private static string _logOnTarget = string.Empty; + private static LogOnResult? _logOnResult; + private static readonly object LogOnCallerLock = new(); // serialises OFF-thread callers only + private static int _loggedNoMainThreadService; + + /// <summary> + /// Main thread only (AcMainThreadQueue.Drain). Publishes the UIFlow mode, runs a + /// pending login request, and refreshes the char-select snapshot (throttled). + /// Idle in the world: a flag check and one aligned read. + /// </summary> + public static void MainThreadTick() + { + if (!MainThreadGuard.IsOnMainThread()) + return; + + if (TryReadModeRaw(out int mode)) + { + Volatile.Write(ref _publishedMode, mode); + Volatile.Write(ref _modePublished, 1); + } + else + { + Volatile.Write(ref _modePublished, 0); + } + + // A pending login request is serviced on the next drain, not throttled. + if (Volatile.Read(ref _logOnState) == 1) + RunPendingLogOn(); + + if (LoginLifecycleHooks.HasObservedLoginComplete) + { + if (_charSelectSnapshot.Names.Length != 0) + _charSelectSnapshot = CharSelectSnapshot.Empty; + return; + } + + long now = Environment.TickCount64; + if (now < Volatile.Read(ref _nextCharSelectSnapshotMs)) + return; + Volatile.Write(ref _nextCharSelectSnapshotMs, now + CharSelectSnapshotIntervalMs); + + // Never bind here: EnsureBound pattern-scans .text under a lock the poll + // threads also take. They bind on their first pass; until then, skip. + if (!Volatile.Read(ref _bound) || mode != CharacterManagementUI) + { + if (_charSelectSnapshot.Names.Length != 0 || _charSelectSnapshot.SlotCount != 0) + _charSelectSnapshot = CharSelectSnapshot.Empty; + return; + } + + try + { + var names = new List<string>(); + ReadCharacterNamesCore(names); + int slotCount = SlotCountCore(); + _charSelectSnapshot = new CharSelectSnapshot(names.ToArray(), slotCount); + } + catch + { + _charSelectSnapshot = CharSelectSnapshot.Empty; + } + } + + // Main thread: take the request (1 -> 2), run the real call, publish (-> 3). + private static void RunPendingLogOn() + { + if (Interlocked.CompareExchange(ref _logOnState, 2, 1) != 1) + return; // withdrawn by its caller in the meantime + var result = new LogOnResult(); + try + { + string target = Volatile.Read(ref _logOnTarget); + result.Ok = TryLogOnCharacterCore(target, out result.Matched, out result.AvatarId, out result.SlotIndex, out result.Status); + } + catch (Exception ex) + { + result.Ok = false; + result.Status = $"LogOnCharacter threw {ex.GetType().Name}: {ex.Message}"; + } + Volatile.Write(ref _logOnResult, result); + Volatile.Write(ref _logOnState, 3); + } + + // Off-thread: arm the slot and wait (bounded) for the main thread's result. + private static bool RequestLogOnFromMainThread(string targetCharacter, out string matchedCharacter, out uint avatarId, out int slotIndex, out string status) + { + matchedCharacter = string.Empty; + avatarId = 0; + slotIndex = -1; + + lock (LogOnCallerLock) + { + // A result a previous caller gave up on: discard it, the slot is ours. + if (Volatile.Read(ref _logOnState) == 3) + Volatile.Write(ref _logOnState, 0); + if (Volatile.Read(ref _logOnState) != 0) + { + status = "Main thread is still running the previous LogOnCharacter request."; + return false; + } + + Volatile.Write(ref _logOnResult, null); + Volatile.Write(ref _logOnTarget, targetCharacter); + Volatile.Write(ref _logOnState, 1); + + long start = Environment.TickCount64; + while (true) + { + int state = Volatile.Read(ref _logOnState); + if (state == 3) + { + LogOnResult? r = Volatile.Read(ref _logOnResult); + Volatile.Write(ref _logOnState, 0); + if (r == null) { status = "LogOnCharacter produced no result."; return false; } + matchedCharacter = r.Matched; + avatarId = r.AvatarId; + slotIndex = r.SlotIndex; + status = r.Status; + return r.Ok; + } + + long waited = Environment.TickCount64 - start; + if (state == 1 && waited >= LogOnRequestWaitMs) + { + // Not taken yet: withdraw it so it can never run late. + if (Interlocked.CompareExchange(ref _logOnState, 0, 1) == 1) + { + if (Interlocked.Exchange(ref _loggedNoMainThreadService, 1) == 0) + RynthLog.Compat("CharacterManagement: LogOnCharacter request not serviced by AC's main thread within 500 ms (is the Client::UseTime drain hooked?); retrying on the next poll."); + status = "AC's main thread did not service the LogOnCharacter request in time."; + return false; + } + continue; // taken just now; wait for it + } + if (state == 2 && waited >= LogOnRequestWaitMs + LogOnRunningGraceMs) + { + // Running on the main thread; its result is picked up (and + // discarded) by the next caller. Never blocks longer than this. + status = "LogOnCharacter still running on AC's main thread."; + return false; + } + if (!EngineThreads.Sleep(10)) + { + Interlocked.CompareExchange(ref _logOnState, 0, 1); + status = "Engine shutting down."; + return false; + } + } + } + } + + private static bool TryReadModeRaw(out int mode) + { + mode = 0; + IntPtr uiFlowPtr = GetUiFlowPointer(); + if (uiFlowPtr == IntPtr.Zero) + return false; + + mode = Marshal.ReadInt32(IntPtr.Add(uiFlowPtr, UIFlowCurModeOffset)); + return true; + } + public static bool TryGetCurrentMode(out int mode) { + // Off the main thread, serve the mode MainThreadTick published (at most a + // frame old). Before the first tick has run, fall back to the raw read: + // one aligned 4-byte load from the long-lived UIFlow singleton. + if (!MainThreadGuard.IsOnMainThread() && Volatile.Read(ref _modePublished) != 0) + { + mode = Volatile.Read(ref _publishedMode); + return true; + } + mode = 0; IntPtr uiFlowPtr = GetUiFlowPointer(); if (uiFlowPtr == IntPtr.Zero) @@ -109,12 +328,49 @@ internal static class CharacterManagementHooks return false; } + // Bind here, on the caller's thread: pattern resolve reads only acclient's + // .text, and doing it off-thread keeps the scan off AC's main thread. if (!EnsureBound()) { status = _statusMessage; return false; } + // Off AC's main thread (the auto-login poll threads): the CharacterSet reads + // and CPlayerSystem::LogOnCharacter run on the main thread via the request + // slot; this thread waits a bounded time for the result. + if (!MainThreadGuard.IsOnMainThread()) + return RequestLogOnFromMainThread(targetCharacter, out matchedCharacter, out avatarId, out slotIndex, out status); + + return TryLogOnCharacterCore(targetCharacter, out matchedCharacter, out avatarId, out slotIndex, out status); + } + + // The real lookup + LogOnCharacter. MAIN THREAD ONLY (MainThreadTick's request + // slot, or a caller already on AC's main thread). + private static bool TryLogOnCharacterCore(string targetCharacter, out string matchedCharacter, out uint avatarId, out int slotIndex, out string status) + { + matchedCharacter = string.Empty; + avatarId = 0; + slotIndex = -1; + + if (!MainThreadGuard.IsOnMainThread()) + { + status = "Off AC's main thread."; + return false; + } + + if (string.IsNullOrWhiteSpace(targetCharacter)) + { + status = "No target character requested."; + return false; + } + + if (!Volatile.Read(ref _bound)) + { + status = _statusMessage; + return false; + } + bool hasMode = TryGetCurrentMode(out int mode); if (hasMode && mode == GamePlayUI) { @@ -198,12 +454,35 @@ internal static class CharacterManagementHooks if (!EnsureBound()) return false; + // Off AC's main thread (the capture/auto-login polls): the main-thread + // snapshot, taken only while CharacterManagementUI was up (<= 250 ms old). + if (!MainThreadGuard.IsOnMainThread()) + { + CharSelectSnapshot snap = _charSelectSnapshot; + if (snap.Names.Length == 0) + return false; + if (!TryGetCurrentMode(out int offMode) || offMode != CharacterManagementUI) + return false; + names.AddRange(snap.Names); + return true; + } + if (!TryGetCurrentMode(out int mode) || mode != CharacterManagementUI) return false; + ReadCharacterNamesCore(names); + return names.Count > 0; + } + + // MAIN THREAD ONLY. Appends the native set's names in slot order. + private static void ReadCharacterNamesCore(List<string> names) + { + if (!MainThreadGuard.IsOnMainThread()) + return; + IntPtr charSetPtr = GetCharacterSetPointer(); if (charSetPtr == IntPtr.Zero) - return false; + return; for (int index = 0; index < MaxCharacterSlots; index++) { @@ -218,8 +497,6 @@ internal static class CharacterManagementHooks names.Add(name.Trim()); } - - return names.Count > 0; } /// <summary> @@ -234,6 +511,19 @@ internal static class CharacterManagementHooks if (!EnsureBound()) return 0; + // Off AC's main thread: the slot count from the main-thread snapshot. + if (!MainThreadGuard.IsOnMainThread()) + return _charSelectSnapshot.SlotCount; + + return SlotCountCore(); + } + + // MAIN THREAD ONLY. + private static int SlotCountCore() + { + if (!MainThreadGuard.IsOnMainThread()) + return 0; + IntPtr charSetPtr = GetCharacterSetPointer(); if (charSetPtr == IntPtr.Zero) return 0; @@ -289,8 +579,10 @@ internal static class CharacterManagementHooks _uiFlowAddr = HookResolver.ResolveData(text, "CharMgmt.UIFlow", PatXrefUIFlow, 2, UIFlowInstanceVa).Address.ToInt32(); _playerSystemAddr = HookResolver.ResolveData(text, "CharMgmt.CPlayerSystem", PatXrefCPlayerSystem, 2, PlayerSystemVa).Address.ToInt32(); - _bound = _uiFlowGetPersistantData != null && _getPlayerSystem != null && _logOnCharacter != null - && _characterSetGetIdentity != null && _characterSetGetName != null && _characterSetGetGid != null; + // Published last (volatile): MainThreadTick reads _bound without the + // lock and then uses the delegates, so they must be visible first. + Volatile.Write(ref _bound, _uiFlowGetPersistantData != null && _getPlayerSystem != null && _logOnCharacter != null + && _characterSetGetIdentity != null && _characterSetGetName != null && _characterSetGetGid != null); _statusMessage = _bound ? "Bound." : "One or more character-management addresses failed to resolve."; if (_bound) RynthLog.Verbose("CharacterManagement: Bound UIFlow and direct LogOnCharacter entry points."); @@ -322,6 +614,11 @@ internal static class CharacterManagementHooks private static IntPtr GetCharacterSetPointer() { + // Calls UIFlow::GetPersistantData; the set it returns is rebuilt by the + // main thread. Main thread only (every caller is a *Core method). + if (!MainThreadGuard.IsOnMainThread()) + return IntPtr.Zero; + IntPtr uiFlowPtr = GetUiFlowPointer(); if (uiFlowPtr == IntPtr.Zero) return IntPtr.Zero; @@ -355,6 +652,9 @@ internal static class CharacterManagementHooks private static IntPtr GetPlayerSystemPointer() { + if (!MainThreadGuard.IsOnMainThread()) + return IntPtr.Zero; + try { IntPtr playerSystemPtr = _getPlayerSystem!(); diff --git a/src/RynthCore.Engine/Compatibility/CharacterTitles.cs b/src/RynthCore.Engine/Compatibility/CharacterTitles.cs new file mode 100644 index 0000000..9e6c53a --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/CharacterTitles.cs @@ -0,0 +1,192 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/CharacterTitles.cs +// +// The titles the character holds, for plugins (API v75 GetCharacterTitles). +// The server sends them only in game events, never as properties: +// 0x0029 CharacterTitle at login (ACE GameEventCharacterTitle): +// [u32 1][u32 current title][u32 count][count x u32 title id] +// 0x002B UpdateTitle for each new or newly displayed title (GameEventUpdateTitle): +// [u32 title id][u32 set as display title] +// Both reach SmartBoxHooks.ParseGameEvent ([event type][payload]) on AC's main +// thread, or the Decal bridge's copy on the pump. Parsing only: nothing here +// touches AC. +// +// Owner: a 0x0029 is sent once per login, so it belongs to whoever is logging +// in; the player id is noted when known and adopted at the first read when it +// wasn't yet. A list for another character is never served. +// +// Survives a hot reload: the list is mirrored into this process's environment +// (RYNTHCORE_CHAR_TITLES), as VTankWatch does, because the server won't send +// it again until the next login. +// ============================================================================ + +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal static class CharacterTitles +{ + public const uint EventCharacterTitle = 0x0029; + public const uint EventUpdateTitle = 0x002B; + private const int MaxTitles = 4096; + private const string EnvName = "RYNTHCORE_CHAR_TITLES"; + + private static readonly object Lock = new(); + private static uint _owner; + private static uint _current; + private static List<uint>? _titles; // null = nothing received for this process yet + private static int _seq; + private static bool _restored; + + public static bool IsTitleEvent(uint eventType) => eventType is EventCharacterTitle or EventUpdateTitle; + + /// <summary>A title game event: <paramref name="data"/> is [event type][payload], <paramref name="size"/> bytes.</summary> + public static unsafe void OnGameEvent(uint eventType, IntPtr data, uint size, uint playerId) + { + if (data == IntPtr.Zero || size < 4 || size > 0x10000) return; + var span = new ReadOnlySpan<byte>((void*)data, (int)size); + lock (Lock) + { + RestoreOnce(); + if (eventType == EventCharacterTitle) + { + if (!TryParseTitleList(span, out uint current, out List<uint> titles)) return; + _owner = playerId; + _current = current; + _titles = titles; + } + else + { + if (!TryParseUpdate(span, out uint title, out bool display)) return; + if (_titles == null || (_owner != 0 && playerId != 0 && _owner != playerId)) return; + if (!_titles.Contains(title) && _titles.Count < MaxTitles) _titles.Add(title); + if (display) _current = title; + } + _seq++; + Persist(); + } + } + + /// <summary> + /// For the plugin API: copies up to <paramref name="max"/> title ids and returns how many + /// the character holds (which may be more than were copied), or -1 when the list for this + /// character isn't known (not received since the client started, or another character's). + /// </summary> + public static unsafe int Copy(uint playerId, uint* ids, int max, uint* current) + { + lock (Lock) + { + RestoreOnce(); + if (_titles == null || playerId == 0) return -1; + if (_owner == 0) _owner = playerId; // received before the id was known + else if (_owner != playerId) return -1; + if (current != null) *current = _current; + if (ids != null) + for (int i = 0; i < _titles.Count && i < max; i++) ids[i] = _titles[i]; + return _titles.Count; + } + } + + public static int Sequence => Volatile.Read(ref _seq); + + /// <summary>For /rc: what the engine holds.</summary> + public static string Describe() + { + lock (Lock) + { + RestoreOnce(); + return _titles == null + ? "no title list received since this client started" + : $"{_titles.Count} titles for 0x{_owner:X8}, current {_current}"; + } + } + + // ── Wire (pure) ───────────────────────────────────────────────────────── + + /// <summary>0x0029: [type][u32 1][u32 current][u32 count][count x u32]. False when it doesn't fit.</summary> + internal static bool TryParseTitleList(ReadOnlySpan<byte> msg, out uint current, out List<uint> titles) + { + current = 0; + titles = new List<uint>(); + if (msg.Length < 16) return false; + current = BinaryPrimitives.ReadUInt32LittleEndian(msg[8..]); + uint count = BinaryPrimitives.ReadUInt32LittleEndian(msg[12..]); + if (count > MaxTitles || 16 + (long)count * 4 > msg.Length) return false; + for (int i = 0; i < (int)count; i++) + { + uint id = BinaryPrimitives.ReadUInt32LittleEndian(msg[(16 + i * 4)..]); + if (!titles.Contains(id)) titles.Add(id); + } + return true; + } + + /// <summary>0x002B: [type][u32 title][u32 set as display title].</summary> + internal static bool TryParseUpdate(ReadOnlySpan<byte> msg, out uint title, out bool display) + { + title = 0; + display = false; + if (msg.Length < 12) return false; + title = BinaryPrimitives.ReadUInt32LittleEndian(msg[4..]); + display = BinaryPrimitives.ReadUInt32LittleEndian(msg[8..]) != 0; + return true; + } + + // ── Hot-reload mirror: "owner;current;id,id,..." (hex owner, decimal ids) ── + + private static void Persist() + { + try + { + var sb = new StringBuilder(); + sb.Append(_owner.ToString("X8", CultureInfo.InvariantCulture)).Append(';') + .Append(_current.ToString(CultureInfo.InvariantCulture)).Append(';'); + for (int i = 0; i < _titles!.Count; i++) + { + if (i > 0) sb.Append(','); + sb.Append(_titles[i].ToString(CultureInfo.InvariantCulture)); + } + Environment.SetEnvironmentVariable(EnvName, sb.ToString()); + } + catch { } + } + + private static void RestoreOnce() + { + if (_restored) return; + _restored = true; + try + { + if (TryParseMirror(Environment.GetEnvironmentVariable(EnvName), out uint owner, out uint current, out List<uint> titles)) + { + _owner = owner; + _current = current; + _titles = titles; + _seq++; + } + } + catch { } + } + + internal static bool TryParseMirror(string? s, out uint owner, out uint current, out List<uint> titles) + { + owner = 0; + current = 0; + titles = new List<uint>(); + if (string.IsNullOrEmpty(s)) return false; + string[] parts = s.Split(';'); + if (parts.Length != 3) return false; + if (!uint.TryParse(parts[0], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out owner)) return false; + if (!uint.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out current)) return false; + foreach (string p in parts[2].Split(',', StringSplitOptions.RemoveEmptyEntries)) + { + if (!uint.TryParse(p, NumberStyles.None, CultureInfo.InvariantCulture, out uint id)) return false; + if (titles.Count < MaxTitles && !titles.Contains(id)) titles.Add(id); + } + return true; + } +} diff --git a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs index d59efc8..1ecbbb3 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs @@ -18,6 +18,7 @@ internal static class ChatCallbackHooks private const int PsRefBufferWideDataOffset = 20; private const int MaxIncomingChatChars = 1024; + private const int MaxDataLineChars = 65536; private const int IncomingChatAddTextToScrollVa = 0x005649F0; private const int IncomingChatWrapperVa = 0x0058A000; private const int OutgoingChatVa = 0x005821A0; @@ -70,6 +71,19 @@ internal static class ChatCallbackHooks private static int _incomingChatSuppressionEnabled; private static int _incomingCallCount; + // ── Held incoming chat (IncomingChatHold.cs) ───────────────────────────── + // AddTextToScroll lines wait for the plugins' verdict before AC prints them, so a + // line a plugin eats never reaches AC's chat window. Main-thread only, except the + // beats and the switch. + private static readonly HeldChatQueue _held = new(); + private static readonly Action<HeldChatLine> _printHeld = PrintHeldLine; + private static bool _incomingByPattern; // AddTextToScroll itself was found by its pattern + private static bool _replayReady; // PStringBase<wchar_t> ctor/dtor/null buffer found by pattern + private static int _holdSwitch = 1; // /rc chathold on|off (not saved; on at every start) + private static long _drainBeatMs; // last AcMainThreadQueue.Drain on AC's main thread + private static int _eatLogCount; + [ThreadStatic] private static int _replayDepth; // inside our own print of a held line + // Captured live from the outgoing-chat detour so we can re-invoke AC's outgoing // chat function DIRECTLY (deterministic) instead of simulating keystrokes into // the native chat bar. Keystroke simulation depends on the bar's open/closed @@ -116,6 +130,9 @@ internal static class ChatCallbackHooks { incomingVerified = true; incomingStatus = $"0x{_incomingAddress.ToInt32():X8} ({incomingMode})"; + if (_originalIncomingChatAddTextPtr != IntPtr.Zero) + _replayReady = _incomingByPattern && TryPrepareReplay(textSection); + RynthLog.Compat($"Compat: incoming chat hold {(_replayReady ? "ready" : "unavailable (lines print before plugins hear them, as before)")}."); } if (EnableOutgoingHook && !OutgoingInstalled) @@ -237,6 +254,7 @@ internal static class ChatCallbackHooks unsafe { _incomingAddress = resolved.Address; + _incomingByPattern = resolved.Source == HookResolver.ResolveSource.PatternScan; delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int> pDetour = &IncomingChatAddTextDetour; MinHook.Hook(_incomingAddress, (IntPtr)pDetour, out _originalIncomingChatAddTextPtr); } @@ -277,23 +295,199 @@ internal static class ChatCallbackHooks private static unsafe int IncomingChatAddTextDetour(IntPtr thisPtr, IntPtr text, uint chatType, uint unknown, IntPtr stringInfo) { RecursionGuard.Tick("ChatCallbackHooks.IncomingChatAddText"); - // 1. Read string BEFORE original — buffer may be freed after - string? line = (text != IntPtr.Zero) ? ReadIncomingChatLine(text, chatType) : null; - - // 2. Call original var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int>)_originalIncomingChatAddTextPtr; + + // 1. Read string BEFORE original — buffer may be freed after + bool truncated = false; + string? raw = (text != IntPtr.Zero) ? ReadIncomingChatRaw(text, chatType, out truncated) : null; + string? line = raw?.TrimEnd('\r', '\n'); + + // 1b. The engine's own server-data replies (Aelrynth /mastery-data it asked for): + // not drawn, not held and not passed on. Every caller of AddTextToScroll ignores its + // return value (all 394 call sites in the retail client, checked 2026-10-01). + // Not inside our own reprint of a held line: that line was already offered here when + // it first arrived (and wasn't ours, or it wouldn't have been held), so offering it + // again could take a stale line for the answer to a request sent since. + if (line != null && _replayDepth == 0 && EatOwnReply(line)) + return 0; + + // 2. Hold the line until the plugins have heard it (IncomingChatHold.cs): AC prints it + // from the next main-thread drain unless a plugin eats it. Anything unexpected here + // falls through to the old path: print now, plugins hear it afterwards. + ChatHoldDecision decision = ChatHoldDecision.PassThrough; + bool handedOver = false; // QueueChatWindowText already saw the line (engine HUD feed and plugins) + try + { + decision = DecideHold(raw, truncated, stringInfo); + if (decision == ChatHoldDecision.Hold) + { + var held = new HeldChatLine(raw!, chatType, unknown, thisPtr, Environment.TickCount64); + handedOver = true; + if (PluginManager.QueueChatWindowText(line, chatType, held)) + { + _held.Add(held); + return 1; // what AddTextToScroll returns for a line it handled + } + decision = ChatHoldDecision.FlushThenPassThrough; // plugins aren't taking chat right now + } + if (decision == ChatHoldDecision.FlushThenPassThrough) + ReleaseHeld(flushAll: true); + } + catch + { + // Fall through and print. (If the line was handed over, it isn't handed over twice.) + } + + // 3. Call original int result = pOriginal(thisPtr, text, chatType, unknown, stringInfo); - // 3. Queue AFTER original returns — game state is consistent - if (line != null) + // 4. Queue AFTER original returns — game state is consistent + if (line != null && !handedOver) QueueIncomingChatLine(line, chatType); return result; } [MethodImpl(MethodImplOptions.NoInlining)] - private static string? ReadIncomingChatLine(IntPtr pStringBase, uint chatType) + private static bool EatOwnReply(string line) { + try { return MasteryFeed.OnIncomingLine(line); } + catch { return false; } + } + + /// <summary>Hold this line, print it now, or print everything held and then it. AC's main thread or not.</summary> + private static ChatHoldDecision DecideHold(string? raw, bool truncated, IntPtr stringInfo) + { + bool onMain = MainThreadGuard.IsOnMainThread(); + bool replaying = _replayDepth > 0; + + // Lines whose verdict is in print first, so a line printed now keeps its place after them. + if (onMain && !replaying && _held.Count > 0) + ReleaseHeld(flushAll: false); + + var inputs = new ChatHoldInputs( + Enabled: HoldActive, + Disarmed: AcMainThreadQueue.IsDisarmed, + OnMainThread: onMain, + Replaying: replaying, + HasText: !string.IsNullOrEmpty(raw), + Truncated: truncated, + HasStringInfo: stringInfo != IntPtr.Zero, + NowMs: Environment.TickCount64, + PumpBeatMs: PluginManager.ChatPumpBeatMs, + DrainBeatMs: Volatile.Read(ref _drainBeatMs), + HeldCount: _held.Count); + return HeldChatQueue.Decide(inputs); + } + + private static bool HoldActive => _replayReady && Volatile.Read(ref _holdSwitch) != 0; + + /// <summary> + /// Called by AcMainThreadQueue.Drain (Client::UseTime and EndScene, AC's main thread): the + /// beat that says held lines will be printed, then prints the ones that may print now. + /// After teardown starts it prints everything still held. + /// </summary> + internal static void OnMainThreadDrain(bool disarmed) + { + if (!MainThreadGuard.IsOnMainThread()) + return; + if (!disarmed) + Volatile.Write(ref _drainBeatMs, Environment.TickCount64); + if (_held.Count == 0 || _replayDepth > 0) + return; + try { ReleaseHeld(flushAll: disarmed || !HoldActive); } + catch { } + } + + /// <summary>Prints held lines that may print now (AC's main thread, never inside our own print).</summary> + private static void ReleaseHeld(bool flushAll) + { + long eatenBefore = _held.EatenTotal; + long lateBefore = _held.TimedOutTotal; + _held.Release(Environment.TickCount64, flushAll, _printHeld); + + if (_held.EatenTotal != eatenBefore && _eatLogCount < 5) + { + _eatLogCount++; + RynthLog.Compat($"Compat: chat hold kept {_held.EatenTotal - eatenBefore} line(s) a plugin ate out of AC's chat window (total {_held.EatenTotal})."); + } + if (_held.TimedOutTotal != lateBefore && _held.TimedOutTotal <= 5) + RynthLog.Compat($"Compat: chat hold printed {_held.TimedOutTotal - lateBefore} line(s) without a plugin verdict after {HeldChatQueue.HoldTimeoutMs} ms (plugin pump slow; total {_held.TimedOutTotal})."); + } + + /// <summary>Prints one held line through AC's own AddTextToScroll, exactly as it came in.</summary> + private static unsafe void PrintHeldLine(HeldChatLine h) + { + var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int>)_originalIncomingChatAddTextPtr; + _replayDepth++; + try + { + fixed (char* chars = h.Raw) // .NET strings end in a NUL, as the PStringBase ctor needs + { + var wide = OutgoingWidePString.Create((ushort*)chars); + try + { + // StringInfo is always null here: lines that came with one are never held. + pOriginal(h.This, (IntPtr)(&wide), h.ChatType, h.Unknown, IntPtr.Zero); + } + finally { wide.Dispose(); } + } + } + finally { _replayDepth--; } + } + + /// <summary> + /// Holding needs to build AC strings itself to print a held line: the PStringBase<wchar_t> + /// ctor, dtor and empty buffer, all found by pattern (never a guessed address). + /// </summary> + private static bool TryPrepareReplay(AcClientTextSection textSection) + { + try + { + var ctor = HookResolver.Resolve(textSection, "ChatCallback.PStringW_ctor", PatWidePStringCtor, 0x00402730); + var dtor = HookResolver.Resolve(textSection, "ChatCallback.PStringW_dtor", PatWidePStringDtor, 0x004011B0); + var nul = HookResolver.ResolveData(textSection, "ChatCallback.PStringW_NullBuffer", PatXrefWideNullBuffer, 2, 0x00818340); + if (ctor.Source != HookResolver.ResolveSource.PatternScan + || dtor.Source != HookResolver.ResolveSource.PatternScan + || nul.Source != HookResolver.ResolveSource.PatternScan) + return false; + // Resolve OutgoingWidePString's statics now, not on AC's thread at the first held line. + return OutgoingWidePString.Warm(); + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: chat hold setup failed - {ex.GetType().Name}: {ex.Message}"); + return false; + } + } + + /// <summary>/rc chathold on|off.</summary> + internal static void SetHoldEnabled(bool on) => Volatile.Write(ref _holdSwitch, on ? 1 : 0); + + internal static bool HoldSwitchOn => Volatile.Read(ref _holdSwitch) != 0; + + /// <summary>One line for /rc chathold status.</summary> + internal static string HoldStatusText() + { + string state = !IncomingInstalled ? "unavailable (incoming chat isn't hooked; in Decal bridge mode Decal owns it)" + : !_replayReady ? "unavailable (the client's string functions weren't found, or another hook sits on AddTextToScroll)" + : HoldSwitchOn ? "ON" : "OFF"; + return $"Chat hold is {state}. Since start: {_held.HeldTotal} held, {_held.ShownTotal} shown, " + + $"{_held.EatenTotal} eaten by plugins, {_held.TimedOutTotal} shown late (no verdict in {HeldChatQueue.HoldTimeoutMs} ms), " + + $"{_held.PrintFailedTotal} print errors; {_held.Count} waiting now."; + } + + /// <summary> + /// Reads the line exactly as AC got it (line breaks kept). <paramref name="truncated"/> is + /// true when it is longer than <see cref="MaxIncomingChatChars"/>: plugins get the first + /// part, as before, but such a line is never held (it couldn't be printed back whole). + /// A server data line ("~ael1 ...") is read in full instead (up to + /// <see cref="MaxDataLineChars"/>) but still reports truncated, so it is never held either. + /// </summary> + [MethodImpl(MethodImplOptions.NoInlining)] + private static string? ReadIncomingChatRaw(IntPtr pStringBase, uint chatType, out bool truncated) + { + truncated = false; try { // PStringBase<ushort> is a 4-byte struct: a single pointer to @@ -311,16 +505,32 @@ internal static class ChatCallbackHooks break; length++; } + // Lines this long are never held (chat-eat's limit, unchanged): they print at once + // and plugins hear them afterwards, as before. Set from the usual cap BEFORE the + // data-line read below, so a long data line read in full still counts as too long. + truncated = length >= MaxIncomingChatChars; - string? line = length > 0 - ? Marshal.PtrToStringUni(charData, length)?.TrimEnd('\r', '\n') - : null; + // A server data line ("~ael1 {json}", one line for every skill) runs past the + // usual cap: read it to its terminator, up to 64K characters. + if (length == MaxIncomingChatChars + && MasteryWire.IsDataLine(Marshal.PtrToStringUni(charData, 40))) + { + while (length < MaxDataLineChars) + { + short ch = Marshal.ReadInt16(charData, length * 2); + if (ch == 0) + break; + length++; + } + } + + string? raw = length > 0 ? Marshal.PtrToStringUni(charData, length) : null; int count = Interlocked.Increment(ref _incomingCallCount); if (count <= 0) RynthLog.Verbose($"Compat: incoming chat #{count} type={chatType} len={length}"); - return line; + return raw; } catch { return null; } } @@ -642,6 +852,17 @@ internal static class ChatCallbackHooks return value; } + /// <summary>From a NUL-terminated buffer the caller keeps pinned for the call.</summary> + public static OutgoingWidePString Create(ushort* chars) + { + var value = new OutgoingWidePString { CharBuffer = Marshal.ReadIntPtr(NullWideBufferVa) }; + Ctor(&value, chars); + return value; + } + + /// <summary>Runs the static resolution now; true when all three addresses are set.</summary> + public static bool Warm() => NullWideBufferVa != IntPtr.Zero && Ctor != null && Dtor != null; + public void Dispose() { fixed (OutgoingWidePString* ptr = &this) diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs b/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs index 924662e..62f8313 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs @@ -211,6 +211,35 @@ internal static unsafe class ChatCommandDispatcher } } + /// <summary> + /// Sends a server command quietly: Talk text that starts with '@', which ACE runs as + /// a command (GameActionTalk) exactly as it runs a typed "/command" the client + /// forwards. Straight to CM_Communication::Event_Talk: no plugin pre-dispatch, no + /// chat-bar keystrokes, nothing said aloud. Printable ASCII only. AC's main thread + /// only (the Aelrynth mastery feed calls it from MainThreadSnapshots.Tick); refuses + /// anywhere else rather than queueing. + /// </summary> + public static bool SendServerCommand(string atCommand) + { + if (!MainThreadGuard.IsOnMainThread()) + return false; + if (string.IsNullOrEmpty(atCommand) || atCommand.Length < 2 || atCommand[0] != '@' || atCommand.Length > 200) + return false; + foreach (char c in atCommand) + if (c < 0x20 || c > 0x7E) + return false; + try + { + LogoffOriginProbe.RecordChat("ServerCommand", atCommand); + return DispatchSay(atCommand); + } + catch (Exception ex) + { + RynthLog.Compat($"ChatDispatch: server command '{atCommand}' failed - {ex.GetType().Name}: {ex.Message}"); + return false; + } + } + private static string ExpandShorthand(string text) { if (StartsWithCmd(text, "/s ")) return "/say " + text.Substring(3); @@ -310,6 +339,11 @@ internal static unsafe class ChatCommandDispatcher /// </summary> private static bool DispatchRaw(string command) { + // Decal bridge mode: AC's outgoing-chat function belongs to Decal (our hook is not + // installed) and there is no window subclass for keystrokes, so the line goes to + // Decal's InvokeChatParser, which the bridge runs on AC's main thread. + if (DecalBridgeHost.Active) + return DecalBridgeHost.TryInvokeChatParser(command); if (ChatCallbackHooks.TryDispatchDirect(command)) return true; return SimulateChatInput(command); diff --git a/src/RynthCore.Engine/Compatibility/ChatFileDispatcher.cs b/src/RynthCore.Engine/Compatibility/ChatFileDispatcher.cs index ae64c57..022e4ca 100644 --- a/src/RynthCore.Engine/Compatibility/ChatFileDispatcher.cs +++ b/src/RynthCore.Engine/Compatibility/ChatFileDispatcher.cs @@ -41,10 +41,15 @@ internal static class ChatFileDispatcher private const int DebounceMs = 200; - public static string FilePath => Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "RynthCore", - "dispatch.txt"); + // RYNTHCORE_DISPATCH_FILE gives a test client its own file: the default one is + // watched by every running client. + public static string FilePath => + Environment.GetEnvironmentVariable("RYNTHCORE_DISPATCH_FILE") is { Length: > 0 } overridePath + ? overridePath + : Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "RynthCore", + "dispatch.txt"); public static void Start() { diff --git a/src/RynthCore.Engine/Compatibility/ChatHooks.cs b/src/RynthCore.Engine/Compatibility/ChatHooks.cs index aff1674..c55347e 100644 --- a/src/RynthCore.Engine/Compatibility/ChatHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatHooks.cs @@ -52,6 +52,11 @@ internal static class ChatHooks private static ListenToElementMessageDelegate? _listenDetour; private static IntPtr _gmMainChatInstance; + private static IntPtr _gmMainChatVtable; // the instance's vtable when captured + // Set when a logoff is requested, cleared when the logout completes: AC frees + // the chatbox during the logoff, and ListenToElementMessage can still fire on + // the dying one, so it is not captured again in between. + private static volatile bool _logoffInProgress; private static IntPtr _uiElementSetVisibleAddress; private static bool _hookInstalled; private static string _statusMessage = "Not initialized."; @@ -123,8 +128,11 @@ internal static class ChatHooks private static void ListenDetour(IntPtr thisPtr, IntPtr msgInfo) { RecursionGuard.Tick("ChatHooks.Listen"); - if (thisPtr != IntPtr.Zero) + if (thisPtr != IntPtr.Zero && !_logoffInProgress && thisPtr != _gmMainChatInstance) + { + _gmMainChatVtable = ClientObjectHooks.IsReadablePointer(thisPtr) ? Marshal.ReadIntPtr(thisPtr) : IntPtr.Zero; _gmMainChatInstance = thisPtr; + } if (++_listenFires <= 3) RynthLog.Compat($"ChatHooks: Listen fired #{_listenFires} this=0x{thisPtr.ToInt32():X8}"); try { _originalListen!(thisPtr, msgInfo); } @@ -145,6 +153,12 @@ internal static class ChatHooks IntPtr inst = _gmMainChatInstance; if (inst == IntPtr.Zero) return; if (_uiElementSetVisibleAddress == IntPtr.Zero) return; + if (!StillAlive(inst)) + { + RynthLog.Compat($"ChatHooks: chatbox 0x{inst.ToInt32():X8} is gone (freed); dropped until it is captured again."); + _gmMainChatInstance = IntPtr.Zero; + return; + } if (RynthChatOwnsChat) { @@ -168,9 +182,40 @@ internal static class ChatHooks } } + /// <summary> + /// Second guard against a freed chatbox: its memory must still be readable + /// and still start with the vtable it had when captured. (A freed object's + /// first bytes are overwritten by the heap; the 2026-09-28 14:41 crash called + /// SetVisible on one and jumped to 0x0000FFFF.) + /// </summary> + private static bool StillAlive(IntPtr inst) + { + if (!ClientObjectHooks.IsReadablePointer(inst)) return false; + IntPtr vtable = Marshal.ReadIntPtr(inst); + if (_gmMainChatVtable == IntPtr.Zero) _gmMainChatVtable = vtable; + return vtable == _gmMainChatVtable; + } + + /// <summary> + /// A logoff was requested (LogoffOriginProbe): drop the chatbox now. The logout + /// notice (ResetCachedInstance) comes after AC has already freed it, and the + /// per-frame SetVisible in between crashed on the freed object (2026-09-28). + /// AC's main thread. + /// </summary> + public static void OnLogoffRequested() + { + _logoffInProgress = true; + _gmMainChatInstance = IntPtr.Zero; + _gmMainChatVtable = IntPtr.Zero; + _isHiddenAsserted = true; + } + + /// <summary>The logout completed (PluginManager's logout dispatch): the next chatbox is a new one.</summary> public static void ResetCachedInstance() { _gmMainChatInstance = IntPtr.Zero; + _gmMainChatVtable = IntPtr.Zero; + _logoffInProgress = false; _isHiddenAsserted = true; // re-assert on the next instance, as at start-up } } diff --git a/src/RynthCore.Engine/Compatibility/ClientActionGates.cs b/src/RynthCore.Engine/Compatibility/ClientActionGates.cs new file mode 100644 index 0000000..9665c94 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ClientActionGates.cs @@ -0,0 +1,572 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ClientActionGates.cs +// +// The acclient's own item-action gates, which lock the player out of using, +// equipping and moving items while chat, clicks and the inventory still work. +// +// Every item action the client makes (double-click use, equip, drag to a pack, +// pick up, drop, give, split, merge, vendor buy/sell) first asks +// ACCWeenieObject::IsPlayerReadyToMakeInventoryRequest. That refuses when +// either of two globals is set, and prints a line in chat: +// +// 1. The PENDING INVENTORY REQUEST slot (4 dwords in .data, 0x00871ED0..DC on +// the 4,841,472-byte client): request type, object id and the time it was +// sent. ACCWeenieObject::RecordRequest (and the UIAttempt* callers, inline) +// fill it when the client sends an inventory request. Only the server's +// answer ABOUT THAT SAME OBJECT empties it: ServerSaysMoveItem, +// ServerSaysSetStackSize, ServerSaysAttemptFailed (0x00A0), the ground +// container view/close (RecordResponse) or the vendor list re-send. Those +// are ACCWeenieObject methods, so when the object is no longer in the +// client's object table (the corpse decayed, a later corpse open queued the +// previous corpse's contents for destruction, a stack merged away) the +// answer finds nothing and the slot is never emptied. The time field is +// written and never read: there is no timeout. Logging off does not empty +// it either, and CPlayerSystem::LogOffCharacter/UseTime wait for it, so the +// logoff sits at "Logging off..." forever. Refusal text: +// "You can only move or use one item at a time". +// +// 2. The ATTACKING flag (0x00871EE0): set by +// ClientCombatSystem::HandleCommenceAttackEvent (0x01B8), cleared only by +// HandleAttackDoneEvent (0x01A7). A lost AttackDone leaves it set for the +// rest of the process. Refusal text: +// "You cannot move or use an item while attacking". +// +// Neither is the busy count (ClientUISystem m_cBusy): AC only reads m_cBusy to +// pick the cursor (UpdateCursorState: != 0 shows the busy cursor), so a zeroed +// or negative count changes the cursor and nothing else. That is why every +// busy-count reset (/ra clearbusy, /ra panic, the watchdogs) left this lock +// in place. +// +// This file: +// * resolves both gates by pattern (two independent code sites each, which +// must agree, or the gate is left alone); +// * reads them for /rc actionstate and the heartbeat (read-only, any thread); +// * on AC's main thread, empties a pending request whose object has been +// gone from the client for MissingObjectGraceMs, or that has had no answer +// for PendingTimeoutMs, and clears an attacking flag that has stayed set +// with no AttackDone for AttackStaleMs. Emptying the slot is exactly what +// AC's own RecordResponse does when an answer arrives; a late real answer +// after that finds nothing pending and changes nothing; +// * does the same on demand for /rc unlockactions (latched when off-thread). +// ============================================================================ +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal static class ClientActionGates +{ + // ACCWeenieObject::RecordRequest(objectId, type) — the whole function: + // mov eax,[esp+4]; mov ecx,[esp+8]; mov edx,[TimerCurTime]; mov [reqObj],eax; + // mov eax,[TimerCurTime+4]; mov [reqType],ecx; mov [reqTime],edx; mov [reqTime+4],eax; ret + private static readonly byte?[] RecordRequestPattern = + [ + 0x8B, 0x44, 0x24, 0x04, + 0x8B, 0x4C, 0x24, 0x08, + 0x8B, 0x15, null, null, null, null, // +10 TimerCurTime (low dword) + 0xA3, null, null, null, null, // +15 reqObj + 0xA1, null, null, null, null, // +20 TimerCurTime (high dword) + 0x89, 0x0D, null, null, null, null, // +26 reqType + 0x89, 0x15, null, null, null, null, // +32 reqTime (low) + 0xA3, null, null, null, null, // +37 reqTime (high) + 0xC3 + ]; + + // ACCWeenieObject::RecordResponse(objectId) — clears the slot when the id matches: + // mov eax,[esp+4]; cmp eax,[reqObj]; jne +16h; xor eax,eax; + // mov [reqObj],eax; mov [reqType],eax; mov [reqTime],eax; mov [reqTime+4],eax; ret + private static readonly byte?[] RecordResponsePattern = + [ + 0x8B, 0x44, 0x24, 0x04, + 0x3B, 0x05, null, null, null, null, // +6 reqObj + 0x75, 0x16, + 0x33, 0xC0, + 0xA3, null, null, null, null, // +15 reqObj + 0xA3, null, null, null, null, // +20 reqType + 0xA3, null, null, null, null, // +25 reqTime (low) + 0xA3, null, null, null, null, // +30 reqTime (high) + 0xC3 + ]; + + // ClientCombatSystem::HandleAttackDoneEvent: mov [esi+3C],bl; cmp [esp+0C],ebx; + // mov [esi+3D],bl; mov [attacking],ebx + private static readonly byte?[] AttackDonePattern = + [ + 0x88, 0x5E, 0x3C, 0x39, 0x5C, 0x24, 0x0C, 0x88, 0x5E, 0x3D, + 0x89, 0x1D, null, null, null, null // +12 attacking + ]; + + // ClientCombatSystem::HandleCommenceAttackEvent tail: mov [attacking],1; + // call GetUISystem; mov ecx,eax; pop esi; add esp,4; jmp IncrementBusyCount + private static readonly byte?[] CommenceAttackPattern = + [ + 0xC7, 0x05, null, null, null, null, // +2 attacking + 0x01, 0x00, 0x00, 0x00, + 0xE8, null, null, null, null, + 0x8B, 0xC8, 0x5E, 0x83, 0xC4, 0x04, 0xE9 + ]; + + // Resolved addresses (0 = not resolved; the gate is then read-only-unavailable). + private static int _reqTypeVa, _reqObjVa, _reqTimeVa, _timerVa, _attackVa; + private static bool _requestReady, _attackReady, _initialized; + private static string _status = "Not initialized."; + + // Repair policy. A normal request is answered within a network round trip + // (a ground pickup adds the walk to the item); a single attack swing lasts a + // few seconds and every AttackDone empties the flag between swings. CheckWatchdog + // runs before every inbound game event and after every game tick, so the + // flag's zero window between AttackDone and the next CommenceAttack is always + // sampled at least once. + // 10 s (was 60): a real answer comes within about a second, and with healing interrupting + // melee/looting (2026.10.4.2) a lost answer locked every item action for a full minute. + private const long PendingTimeoutMs = 10_000; + private const long MissingObjectGraceMs = 5_000; + // 12 s in melee/missile (was 30); outside them no attack can be running, so 1.5 s. + private const long AttackStaleMs = 12_000; + private const long AttackStaleOutOfStanceMs = 1_500; + private const long PendingCheckIntervalMs = 500; + private const long ChatNoticeCooldownMs = 10 * 60_000; + + // Main-thread tracking state. + private static long _trackedKey; + private static long _pendingSeenAt; + private static long _objectMissingSince; + private static long _lastPendingCheck; + private static long _attackSetSince; + private static long _lastChatNoticeAt = long.MinValue / 2; + + private static long _pendingClears; + private static long _attackClears; + private static int _unlockRequested; + + public static bool IsRequestGateAvailable => _requestReady; + public static bool IsAttackGateAvailable => _attackReady; + public static string StatusMessage => _status; + public static long PendingClearCount => Interlocked.Read(ref _pendingClears); + public static long AttackClearCount => Interlocked.Read(ref _attackClears); + + public static void Initialize() + { + if (_initialized) + return; + _initialized = true; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + _status = "acclient .text not readable."; + RynthLog.Compat($"ClientActionGates: {_status}"); + return; + } + + string req = ResolveRequestSlot(text); + string atk = ResolveAttackFlag(text); + _status = $"request slot: {req}; attack flag: {atk}."; + RynthLog.Compat($"ClientActionGates: {_status}"); + } + + private static string ResolveRequestSlot(AcClientTextSection text) + { + if (!TryFindUnique(text, RecordRequestPattern, out int a)) + return "RecordRequest pattern not found (unique)"; + if (!TryFindUnique(text, RecordResponsePattern, out int b)) + return "RecordResponse pattern not found (unique)"; + + byte[] t = text.Bytes; + int obj = BitConverter.ToInt32(t, a + 15); + int type = BitConverter.ToInt32(t, a + 26); + int time = BitConverter.ToInt32(t, a + 32); + int timeHi = BitConverter.ToInt32(t, a + 37); + int timerLo = BitConverter.ToInt32(t, a + 10); + int timerHi = BitConverter.ToInt32(t, a + 20); + + bool consistent = + type == obj - 4 && time == obj + 4 && timeHi == obj + 8 && timerHi == timerLo + 4 + && BitConverter.ToInt32(t, b + 6) == obj && BitConverter.ToInt32(t, b + 15) == obj + && BitConverter.ToInt32(t, b + 20) == type && BitConverter.ToInt32(t, b + 25) == time + && BitConverter.ToInt32(t, b + 30) == timeHi; + if (!consistent) + return $"code sites disagree (obj=0x{obj:X8} type=0x{type:X8})"; + if (!ClientObjectHooks.IsWritablePointer(new IntPtr(type)) + || !ClientObjectHooks.IsWritablePointer(new IntPtr(timeHi)) + || !ClientObjectHooks.IsReadablePointer(new IntPtr(timerLo))) + return $"globals not mapped (type=0x{type:X8})"; + + _reqTypeVa = type; + _reqObjVa = obj; + _reqTimeVa = time; + _timerVa = timerLo; + _requestReady = true; + return $"0x{type:X8} (type) / 0x{obj:X8} (object)"; + } + + private static string ResolveAttackFlag(AcClientTextSection text) + { + if (!TryFindUnique(text, AttackDonePattern, out int a)) + return "HandleAttackDoneEvent pattern not found (unique)"; + if (!TryFindUnique(text, CommenceAttackPattern, out int b)) + return "HandleCommenceAttackEvent pattern not found (unique)"; + int flagA = BitConverter.ToInt32(text.Bytes, a + 12); + int flagB = BitConverter.ToInt32(text.Bytes, b + 2); + if (flagA != flagB) + return $"code sites disagree (0x{flagA:X8} vs 0x{flagB:X8})"; + if (!ClientObjectHooks.IsWritablePointer(new IntPtr(flagA))) + return $"global 0x{flagA:X8} not mapped"; + _attackVa = flagA; + _attackReady = true; + return $"0x{flagA:X8}"; + } + + private static bool TryFindUnique(AcClientTextSection text, byte?[] pattern, out int offset) + { + offset = PatternScanner.FindPattern(text.Bytes, pattern); + if (offset < 0) + return false; + return PatternScanner.FindPatternInRegion(text.Bytes, pattern, offset + 1, text.Bytes.Length) < 0; + } + + // ── Reads (any thread: plain loads from acclient .data, which never unmaps) ── + + public static bool TryReadPending(out uint type, out uint objectId, out double ageSeconds) + { + type = 0; + objectId = 0; + ageSeconds = -1; + if (!_requestReady) + return false; + type = unchecked((uint)Marshal.ReadInt32(new IntPtr(_reqTypeVa))); + objectId = unchecked((uint)Marshal.ReadInt32(new IntPtr(_reqObjVa))); + double issued = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(new IntPtr(_reqTimeVa))); + double now = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(new IntPtr(_timerVa))); + if (type != 0 && issued > 0 && now >= issued && now - issued < 1e7) + ageSeconds = now - issued; + return true; + } + + public static bool TryReadAttacking(out bool attacking) + { + attacking = false; + if (!_attackReady) + return false; + attacking = Marshal.ReadInt32(new IntPtr(_attackVa)) != 0; + return true; + } + + public static string RequestTypeName(uint type) => type switch + { + 0 => "none", + 1 => "merge", + 2 => "split", + 3 => "move", + 4 => "pick up", + 5 => "put in container", + 6 => "drop", + 7 => "wield", + 9 => "give", + 10 => "vendor buy/sell", + _ => $"request {type}", + }; + + /// <summary>Short heartbeat field, empty when both gates are open.</summary> + public static string HeartbeatField() + { + try + { + string s = string.Empty; + if (TryReadPending(out uint type, out _, out double age) && type != 0) + s = age >= 0 ? $" req={type}/{age:0}s" : $" req={type}"; + if (TryReadAttacking(out bool attacking) && attacking) + s += " atk=1"; + return s; + } + catch { return string.Empty; } + } + + // ── Main-thread watchdog ───────────────────────────────────────────────── + + /// <summary>Drop the tracking state at logout / client close (the slot itself is AC's).</summary> + public static void ResetTracking() + { + _trackedKey = 0; + _pendingSeenAt = 0; + _objectMissingSince = 0; + _attackSetSince = 0; + } + + /// <summary> + /// Called from BusyCountHooks.CheckWatchdog on every game tick and before every + /// inbound game event. Main thread only; any other thread returns at once. + /// </summary> + public static void Tick(long now, bool inWorldTransition) + { + if (!MainThreadGuard.IsOnMainThread()) + return; + + if (Interlocked.Exchange(ref _unlockRequested, 0) == 1) + { + foreach (string line in UnlockNow("manual (/rc unlockactions)")) + RynthLog.Compat($"ClientActionGates: {line}"); + } + + TickAttackFlag(now, inWorldTransition); + + if (now - _lastPendingCheck < PendingCheckIntervalMs) + return; + _lastPendingCheck = now; + TickPendingRequest(now, inWorldTransition); + } + + private static void TickAttackFlag(long now, bool inWorldTransition) + { + if (!_attackReady) + return; + bool attacking = Marshal.ReadInt32(new IntPtr(_attackVa)) != 0; + if (!attacking || inWorldTransition) + { + _attackSetSince = 0; + return; + } + if (_attackSetSince == 0) + { + _attackSetSince = now; + return; + } + // Peace or Magic mode (kits, looting, casting happen here): no melee/missile attack + // can be in progress, so a set flag is a lost AttackDone. Clear it quickly. + int mode = CombatModeHooks.ReadCurrentCombatMode(); + bool attackStance = mode == CombatActionHooks.CombatModeMelee || mode == CombatActionHooks.CombatModeMissile; + if (now - _attackSetSince < (attackStance ? AttackStaleMs : AttackStaleOutOfStanceMs)) + return; + + long heldMs = now - _attackSetSince; + _attackSetSince = 0; + if (ClearAttackFlag()) + { + RynthLog.Compat($"ClientActionGates: attacking flag held {heldMs / 1000}s with no AttackDone — cleared. AC was refusing every item use/move ('while attacking')."); + NotifyChat("Item actions were locked (the client never got the end of an attack). Unlocked."); + } + } + + private static void TickPendingRequest(long now, bool inWorldTransition) + { + if (!_requestReady) + return; + TryReadPending(out uint type, out uint objectId, out double acAge); + if (type == 0) + { + _trackedKey = 0; + _objectMissingSince = 0; + return; + } + + long issuedBits = Marshal.ReadInt64(new IntPtr(_reqTimeVa)); + long key = unchecked(((long)type << 56) ^ ((long)objectId << 24) ^ issuedBits); + if (key != _trackedKey || _pendingSeenAt == 0) + { + _trackedKey = key; + _pendingSeenAt = now; + _objectMissingSince = 0; + } + + // Portal / death: objects leave and re-enter the client wholesale and + // answers can arrive after the world settles. Judge afresh afterwards. + if (inWorldTransition) + { + _pendingSeenAt = now; + _objectMissingSince = 0; + return; + } + + string? reason = null; + if (LoginLifecycleHooks.HasObservedLoginComplete) + { + bool exists = objectId != 0 && ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out _); + if (exists) + _objectMissingSince = 0; + else if (_objectMissingSince == 0) + _objectMissingSince = now; + else if (now - _objectMissingSince >= MissingObjectGraceMs) + reason = "its object is no longer in the client, so no answer can clear it"; + } + + if (reason == null && now - _pendingSeenAt >= PendingTimeoutMs) + reason = $"no answer for {(now - _pendingSeenAt) / 1000}s"; + + if (reason == null) + return; + + if (ClearPendingRequest()) + { + RynthLog.Compat( + $"ClientActionGates: cleared a stuck item request — {RequestTypeName(type)} (type {type}) on 0x{objectId:X8}" + + $"{(acAge >= 0 ? $", sent {acAge:0}s ago" : string.Empty)}: {reason}. AC was refusing every item use/move/equip ('one item at a time')."); + NotifyChat("Item actions were locked (the client was still waiting on an old item request). Unlocked."); + } + _trackedKey = 0; + _objectMissingSince = 0; + } + + private static void NotifyChat(string text) + { + // Called from the main-thread watchdog only; the chat line itself is + // written by the queue's drain. + if (!MainThreadGuard.IsOnMainThread()) + return; + long now = Environment.TickCount64; + if (now - _lastChatNoticeAt < ChatNoticeCooldownMs) + return; + _lastChatNoticeAt = now; + AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, 1); + } + + /// <summary> + /// Empty AC's pending-inventory-request slot, the same four stores + /// RecordResponse makes when the server answers. Main thread only. + /// </summary> + private static bool ClearPendingRequest() + { + if (!MainThreadGuard.IsOnMainThread() || !_requestReady) + return false; + Marshal.WriteInt32(new IntPtr(_reqObjVa), 0); + Marshal.WriteInt32(new IntPtr(_reqTypeVa), 0); + Marshal.WriteInt32(new IntPtr(_reqTimeVa), 0); + Marshal.WriteInt32(new IntPtr(_reqTimeVa + 4), 0); + Interlocked.Increment(ref _pendingClears); + return true; + } + + /// <summary>Clear AC's attacking flag, as HandleAttackDoneEvent does. Main thread only.</summary> + private static bool ClearAttackFlag() + { + if (!MainThreadGuard.IsOnMainThread() || !_attackReady) + return false; + Marshal.WriteInt32(new IntPtr(_attackVa), 0); + Interlocked.Increment(ref _attackClears); + return true; + } + + /// <summary> + /// /rc unlockactions: open both gates now and repair a negative busy count. + /// On AC's main thread it runs at once and returns what it did; elsewhere it + /// latches for the next watchdog tick and says so. + /// </summary> + public static string[] RequestUnlock() + { + if (!MainThreadGuard.IsOnMainThread()) + { + Interlocked.Exchange(ref _unlockRequested, 1); + return ["Unlock queued for the next game tick."]; + } + return UnlockNow("manual (/rc unlockactions)"); + } + + private static string[] UnlockNow(string why) + { + if (!MainThreadGuard.IsOnMainThread()) + return ["Unlock skipped: not on the game thread."]; + + var done = new System.Collections.Generic.List<string>(); + if (TryReadPending(out uint type, out uint objectId, out double age) && type != 0) + { + if (ClearPendingRequest()) + done.Add($"cleared the pending item request ({RequestTypeName(type)} on 0x{objectId:X8}{(age >= 0 ? $", {age:0}s old" : string.Empty)})"); + } + if (TryReadAttacking(out bool attacking) && attacking) + { + if (ClearAttackFlag()) + done.Add("cleared the attacking flag"); + } + if (BusyCountHooks.RepairNegativeBusy(out int was)) + done.Add($"reset a negative busy count ({was} -> 0)"); + + ResetTracking(); + string summary = done.Count == 0 + ? "Nothing to unlock: no pending item request, no attacking flag, busy count not negative." + : "Unlocked: " + string.Join("; ", done) + "."; + RynthLog.Compat($"ClientActionGates: {why}: {summary}"); + return [summary]; + } + + // ── /rc actionstate ───────────────────────────────────────────────────── + + public static string[] DescribeLines() + { + var lines = new System.Collections.Generic.List<string>(); + lines.Add("Action state (what the client checks before a use, equip or move):"); + + // 1. Pending inventory request. + if (!_requestReady) + { + lines.Add($" Item request: unavailable ({_status})"); + } + else + { + TryReadPending(out uint type, out uint objectId, out double age); + if (type == 0) + { + lines.Add(" Item request: none (open)"); + } + else + { + string name = string.Empty; + bool exists = false; + if (MainThreadGuard.IsOnMainThread() && objectId != 0) + { + exists = ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out _); + if (exists) ClientObjectHooks.TryGetObjectName(objectId, out name); + } + lines.Add($" Item request: WAITING - {RequestTypeName(type)} (type {type}) on 0x{objectId:X8}" + + $"{(name.Length > 0 ? $" '{name}'" : string.Empty)}" + + $"{(age >= 0 ? $", sent {age:0.0}s ago" : string.Empty)}, object {(exists ? "still in client" : "GONE from client")}."); + lines.Add(" While this is set the client refuses every use/equip/move ('You can only move or use one item at a time') and a logoff waits forever."); + } + } + + // 2. Attacking flag. + if (!_attackReady) + lines.Add(" Attacking flag: unavailable"); + else + { + TryReadAttacking(out bool attacking); + long held = _attackSetSince == 0 ? 0 : (Environment.TickCount64 - _attackSetSince) / 1000; + lines.Add(attacking + ? $" Attacking flag: SET{(held > 0 ? $" ({held}s)" : string.Empty)} - item use/move refused ('while attacking') until the server's AttackDone." + : " Attacking flag: clear"); + } + + // 3. Busy count (cursor only). + string busy = BusyCountHooks.TryReadRealBusy(out int real) ? real.ToString() : "unreadable"; + lines.Add($" Busy count m_cBusy: {busy} (engine shadow {BusyCountHooks.ShadowBusyCount}, pending reconcile {BusyCountHooks.PendingReconcileDelta}, force-clears {BusyCountHooks.ForceClearCount}, reconciles {BusyCountHooks.ReconcileCount}, negative repairs {BusyCountHooks.NegativeRepairCount}). Non-zero only shows the busy cursor."); + + // 4. ClientUISystem: target mode / open container / vendor. + IntPtr ui = ClientHelperHooks.ReadUiSystemPtr(); + if (ui != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(ui, 0x40)) + { + uint ground = unchecked((uint)Marshal.ReadInt32(ui + 0x18)); + uint vendor = unchecked((uint)Marshal.ReadInt32(ui + 0x20)); + int targetMode = Marshal.ReadInt32(ui + 0x2C); + string tm = targetMode switch { 0 => "none", 1 => "1 (use: pick an object)", 3 => "3 (choose a target for an item: next click is the target, Esc cancels)", _ => targetMode.ToString() }; + lines.Add($" Target mode: {tm}; open container 0x{ground:X8}; vendor 0x{vendor:X8}"); + } + else + { + lines.Add(" UI system: not available"); + } + + // 5. Combat system. + IntPtr combat = CombatModeHooks.ReadCombatSystemPtr(); + if (combat != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(combat, 0x48)) + { + int mode = Marshal.ReadInt32(combat + 0x1C); + string modeName = mode switch { 1 => "NonCombat", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => mode.ToString() }; + byte busyHeld = Marshal.ReadByte(combat + 0x3C); + byte inAttack = Marshal.ReadByte(combat + 0x3D); + byte autoRepeat = Marshal.ReadByte(combat + 0x44); + lines.Add($" Combat: mode {modeName}; attack holds busy {busyHeld}; attack in progress {inAttack}; auto-repeat {autoRepeat}"); + } + + lines.Add($" World transition (portal/death): {(PlayerLifecycleLog.InWorldTransition ? "yes" : "no")}; logged in: {(LoginLifecycleHooks.HasObservedLoginComplete ? "yes" : "no")}"); + lines.Add($" Auto-unlocks this session: item request {PendingClearCount}, attacking flag {AttackClearCount}. Unlock now: /rc unlockactions"); + return lines.ToArray(); + } +} diff --git a/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs b/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs index e79042d..e8d2546 100644 --- a/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs @@ -165,6 +165,9 @@ internal static class ClientActionHooks { // Direct quaternion write — instant snap, most reliable (uses proven SmartBox offsets). // Equivalent to old Decal Actions.Heading = value. + // Off AC's main thread (plugin pump) SetPlayerHeadingDirect only parks the + // heading in AcMainThreadQueue's coalesced slot and returns true; the snap + // (and the no-player CommandInterpreter fallback below) run in Drain. if (PlayerPhysicsHooks.SetPlayerHeadingDirect(headingDegrees)) return true; diff --git a/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs b/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs index ae644c8..a26f98e 100644 --- a/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.InteropServices; +using System.Threading; namespace RynthCore.Engine.Compatibility; @@ -212,10 +213,53 @@ internal static class ClientCombatHooks if (_playerInReadyPosition == null || _getCombatSystem == null) return false; + // Off AC's main thread (host IsPlayerReadyFn: RynthNet's login probe polls it + // every 2 s from the plugin pump): the value sampled on the main thread + // (<= ~200 ms old). ClientCombatSystem::PlayerInReadyPosition walks the + // player's motion state and the combat singleton, both freed and rebuilt + // around login / logout, exactly when this is polled. + if (!MainThreadGuard.IsOnMainThread()) + return Volatile.Read(ref _readySnapshot) != 0; + + bool ready = ReadPlayerReadyLive(); + Volatile.Write(ref _readySnapshot, ready ? 1 : 0); + return ready; + } + + // 1 = the main thread last saw the player in a ready position. + private static int _readySnapshot; + private static long _nextReadySampleMs; + private const int ReadySampleIntervalMs = 200; + + /// <summary> + /// Main thread only (MainThreadSnapshots.Tick). Samples PlayerInReadyPosition for + /// off-thread IsPlayerReady callers, about five times a second. With no player + /// object (char-select, portal teardown) it publishes "not ready" without + /// calling into the combat system. + /// </summary> + internal static void SampleReady() + { + if (!MainThreadGuard.IsOnMainThread() || _playerInReadyPosition == null || _getCombatSystem == null) + return; + long now = Environment.TickCount64; + if (now < _nextReadySampleMs) + return; + _nextReadySampleMs = now + ReadySampleIntervalMs; + + bool ready = ClientHelperHooks.GetPlayerId() != 0 && ReadPlayerReadyLive(); + Volatile.Write(ref _readySnapshot, ready ? 1 : 0); + } + + // MAIN THREAD ONLY. + private static bool ReadPlayerReadyLive() + { + if (!MainThreadGuard.IsOnMainThread() || _playerInReadyPosition == null || _getCombatSystem == null) + return false; try { IntPtr cs = _getCombatSystem(); if (cs == IntPtr.Zero) return false; + if (!ClientObjectHooks.IsReadablePointer(cs)) return false; return _playerInReadyPosition(cs, 1) != 0; } catch { return false; } @@ -257,5 +301,6 @@ internal static class ClientCombatHooks _autoTarget = null; _sendAttackHeightChanged = null; _initialized = false; + Volatile.Write(ref _readySnapshot, 0); } } diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index 2000daa..a147ff2 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -66,10 +66,47 @@ internal static class ClientHelperHooks // Byte-identical sibling of Event_StackableMerge (differs only in the action // opcode immediate: give writes 0xCD, merge 0x54). Cdecl, returns bool. // Chorizite map: 002ACA60 -> live VA 0x006ACA60. Sends the F7B1 give - // GameAction. amount = stack count to give (0 = whole object). - // Args (live-disasm + call-site UIAttemptGive confirmed): item, targetNpc, amount. + // GameAction. amount = stack count to give (ACE refuses amount <= 0). + // Args: TARGET FIRST, then the item, then amount. The function writes 0xCD, then + // [esp+0x1C], [esp+0x20], [esp+0x24] in that order, and ACE's GiveObjectRequest reads + // targetGuid, objectGuid, amount. Its one caller, ACCWeenieObject::UIAttemptGive + // (call at 0x0058E46F), pushes amount, this->id (the item, [esi+8]), then the target. + // (Re-checked 2026-10-01; the old delegate had the two ids swapped.) [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate byte EventGiveObjectRequestDelegate(uint objectId, uint targetId, int amount); + private delegate byte EventGiveObjectRequestDelegate(uint targetId, uint objectId, int amount); + + // CM_Inventory::Event_GetAndWieldItem(ulong itemId, ulong equipMask) — the 0x001A + // GetAndWieldItem game action ("wield this item at these locations"). Same generated + // shape as its two siblings above (cdecl, returns bool), opcode immediate 0x1A. + // Chorizite map: 002AB950 -> live VA 0x006AC950 (the "FUN_006AC950" once mistaken for + // the merge helper, which is why that attempt tried to equip Pyreals). Arg order from + // the disassembly (itemId at [esp+0x1C], mask at [esp+0x20] after the prologue) and the + // one caller, ACCWeenieObject::UIAttemptWield @0x0058E3C0: push mask; push this->id. + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate byte EventGetAndWieldItemDelegate(uint objectId, uint equipMask); + + // CM_Inventory::Event_DropItem(ulong itemId) — the 0x001B DropItem game action (put the + // item on the ground at the player's feet). Same generated shape as the three above + // (cdecl, returns bool) with one argument, so +0x08 after the first inner call and the + // 0x1B opcode as the last pattern byte. Chorizite map entrypoint 0x006AC880; its caller + // is ACCWeenieObject::UIAttemptPutIn3D (call at 0x0058E545). Arg: itemId at [esp+0x1C] + // after the prologue (sub esp,0Ch + three pushes). + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate byte EventDropItemDelegate(uint objectId); + + // CM_Inventory::Event_NoLongerViewingContents(ulong containerId) - the 0x0195 + // NoLongerViewingContents game action, the packet the client sends to close an external + // container (corpse, chest). Same generated shape as Event_DropItem (cdecl, returns bool, + // one argument) with opcode 0x0195. Entry 0x006ACBB0. Its one caller is + // ClientUISystem::SetGroundContainer(newId, notifyServer) @0x005652B0, which sends it for + // the old ground container when notifyServer is set: the container window's close and + // opening a second container both go through there. ACE (Player.HandleActionNoLongerViewingContents) + // closes the container if this player is its viewer and answers with CloseGroundContainer + // (0x0052); the client's own handler for that tears the window down + // (SetGroundContainer(0, false)), clears the pending-request slot for that container + // (ACCWeenieObject::RecordResponse) and runs ACCObjectMaint::StopViewingObjectContents. + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate byte EventNoLongerViewingContentsDelegate(uint containerId); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void UseObjectDelegate(IntPtr clientUiSystem, uint objectId); @@ -105,6 +142,12 @@ internal static class ClientHelperHooks private const int EventStackableMergeVa = 0x006ACDD0; // CM_Inventory::Event_GiveObjectRequest — public give-to-NPC API (FALLBACK only; pattern-scanned). private const int EventGiveObjectRequestVa = 0x006ACA60; + // CM_Inventory::Event_GetAndWieldItem — wield into a chosen slot (FALLBACK only; pattern-scanned). + private const int EventGetAndWieldItemVa = 0x006AC950; + // CM_Inventory::Event_DropItem — drop an item on the ground (FALLBACK only; pattern-scanned). + private const int EventDropItemVa = 0x006AC880; + // CM_Inventory::Event_NoLongerViewingContents - close an external container (FALLBACK only; pattern-scanned). + private const int EventNoLongerViewingContentsVa = 0x006ACBB0; private const int UseObjectVa = 0x00565750; private const int PlayerSystemVa = 0x0087119C; private const int InqPlayerCoordsVa = 0x00560E00; @@ -126,6 +169,9 @@ internal static class ClientHelperHooks private static MoveItemInternalDelegate? _moveItemInternal; private static EventStackableMergeDelegate? _eventStackableMerge; private static EventGiveObjectRequestDelegate? _eventGiveObjectRequest; + private static EventGetAndWieldItemDelegate? _eventGetAndWieldItem; + private static EventDropItemDelegate? _eventDropItem; + private static EventNoLongerViewingContentsDelegate? _eventNoLongerViewingContents; private static InqPlayerCoordsDelegate? _inqPlayerCoords; private static GetPlayerIdDelegate? _getPlayerId; private static AddTextToScrollDelegate? _addTextToScroll; @@ -151,6 +197,9 @@ internal static class ClientHelperHooks public static bool HasSplitStackInternal => _moveItemInternal != null; public static bool HasMergeStackInternal => _eventStackableMerge != null; public static bool HasGiveObjectTo => _eventGiveObjectRequest != null; + public static bool HasWieldItem => _eventGetAndWieldItem != null; + public static bool HasDropItem => _eventDropItem != null; + public static bool HasCloseContainer => _eventNoLongerViewingContents != null; public static bool HasGetCurCoords => _inqPlayerCoords != null; public static bool HasGetPlayerId => _getPlayerId != null; public static bool HasGetGroundContainerId => true; @@ -178,7 +227,22 @@ internal static class ClientHelperHooks // so do NOT trim it. Generated + verified unique (1 match @0x006ACA60) via // pe_pattern.py GEN against both acclient copies. private static readonly byte?[] PatEventGiveObjectRequest = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x10, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0xCD ]; - private static readonly byte?[] PatInqPlayerCoords = [ 0x83, 0xEC, 0x10, 0x53, 0x8B, 0x5C, 0x24, 0x1C, 0x55, 0x56 ]; + // CM_Inventory::Event_GetAndWieldItem @0x006AC950. Same template as the two above but with + // one fewer argument (so +0x0C, not +0x10, after the first inner call) and the 0x1A opcode + // as the last byte. Generated + verified unique (1 match @0x006AC950) via pe_pattern.py GEN + // against both acclient copies (C:\Turbine and C:\Games\RynthCore\AcClient). + private static readonly byte?[] PatEventGetAndWieldItem = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x1A ]; + // CM_Inventory::Event_DropItem @0x006AC880. The same template again with one argument + // (+0x08 after the first inner call) and the 0x1B opcode as the last byte. Verified + // unique (1 match @0x006AC880) over the engine's scan window against both acclient + // copies (C:\Turbine and C:\Games\RynthCore\AcClient), 2026-09-30. + private static readonly byte?[] PatEventDropItem = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x1B ]; + // CM_Inventory::Event_NoLongerViewingContents @0x006ACBB0. Byte-identical to Event_DropItem + // except the opcode immediate (0x0195, so the last two bytes are 0x95 0x01 where DropItem has + // 0x1B). Verified unique (1 match @0x006ACBB0) over the engine's scan window against + // C:\Games\RynthCore\AcClient\acclient.exe, 2026-10-04. + private static readonly byte?[] PatEventNoLongerViewingContents = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x95, 0x01 ]; + private static readonly byte?[] PatInqPlayerCoords =[ 0x83, 0xEC, 0x10, 0x53, 0x8B, 0x5C, 0x24, 0x1C, 0x55, 0x56 ]; private static readonly byte?[] PatGetPlayerId = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x85, 0xC0, 0x74, 0x07 ]; private static readonly byte?[] PatAddTextToScroll = [ 0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84 ]; private static readonly byte?[] PatUseWithTargetEvent = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x35 ]; @@ -238,6 +302,9 @@ internal static class ClientHelperHooks _moveItemInternal = Bind<MoveItemInternalDelegate>(text, "ClientHelper.MoveItemInternal", PatMoveItemInternal, MoveItemInternalVa); _eventStackableMerge = Bind<EventStackableMergeDelegate>(text, "ClientHelper.Event_StackableMerge", PatEventStackableMerge, EventStackableMergeVa); _eventGiveObjectRequest = Bind<EventGiveObjectRequestDelegate>(text, "ClientHelper.Event_GiveObjectRequest", PatEventGiveObjectRequest, EventGiveObjectRequestVa); + _eventGetAndWieldItem = Bind<EventGetAndWieldItemDelegate>(text, "ClientHelper.Event_GetAndWieldItem", PatEventGetAndWieldItem, EventGetAndWieldItemVa); + _eventDropItem = Bind<EventDropItemDelegate>(text, "ClientHelper.Event_DropItem", PatEventDropItem, EventDropItemVa); + _eventNoLongerViewingContents = Bind<EventNoLongerViewingContentsDelegate>(text, "ClientHelper.Event_NoLongerViewingContents", PatEventNoLongerViewingContents, EventNoLongerViewingContentsVa); _inqPlayerCoords = Bind<InqPlayerCoordsDelegate>(text, "ClientHelper.InqPlayerCoords", PatInqPlayerCoords, InqPlayerCoordsVa); _getPlayerId = Bind<GetPlayerIdDelegate>(text, "ClientHelper.GetPlayerId", PatGetPlayerId, GetPlayerIdVa); _addTextToScroll = Bind<AddTextToScrollDelegate>(text, "ClientHelper.AddTextToScroll", PatAddTextToScroll, AddTextToScrollVa); @@ -252,6 +319,12 @@ internal static class ClientHelperHooks _totalStackAddr = HookResolver.ResolveData(text, "ClientHelper.total_stack", PatXrefTotalStack, 2, TotalStackVa).Address.ToInt32(); _playerSystemAddr = HookResolver.ResolveData(text, "ClientHelper.CPlayerSystem", PatXrefPlayerSystem, 2, PlayerSystemVa).Address.ToInt32(); _commSystemAddr = HookResolver.ResolveData(text, "ClientHelper.CommunicationSystem", PatXrefCommunicationSystem, 2, CommunicationSystemVa).Address.ToInt32(); + // v72 player-to-player trade actions (CM_Trade / ClientTradeSystem). + try { PlayerTrade.Probe(text); } + catch (Exception ex) { RynthLog.Compat($"Compat: player trade binding failed - {ex.Message}"); } + // Skills panel raises (CM_Train senders). + try { PlayerTraining.Probe(text); } + catch (Exception ex) { RynthLog.Compat($"Compat: raise senders binding failed - {ex.Message}"); } _initialized = true; _statusMessage = "Ready."; RynthLog.Verbose("Compat: helper hooks ready - validated select/state/chat helpers plus mapped interaction and inventory helpers."); @@ -300,6 +373,35 @@ internal static class ClientHelperHooks } } + /// <summary> + /// Click-to-select from an ImGui overlay (a Radar dot, a monster nameplate): + /// selects <paramref name="objectId"/> the way a click on it in the 3D world + /// does. The faces park the id with AcMainThreadQueue.EnqueueOverlaySelect; + /// its drain lands here on AC's main thread, where the checks run right + /// before the select: the client is in the world (logged in, no logout or + /// DB-cache teardown under way, not portaling) and the object still exists + /// (the client still resolves its weenie). Off-thread it marshals like + /// every other mutator. False when nothing was selected. + /// </summary> + public static bool SelectFromOverlay(uint objectId) + { + if (!MainThreadGuard.IsOnMainThread()) + return AcMainThreadQueue.EnqueueOverlaySelect(objectId); + + if (objectId == 0 || _setSelectedObject == null) + return false; + if (!LoginLifecycleHooks.HasObservedLoginComplete || LogoutLifecycleHooks.HasObservedLogout + || DbCacheTeardownHooks.TeardownActive || TeleportStateHooks.IsPortaling || GetPlayerId() == 0) + return false; + if (!ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out _)) + return false; // despawned / died / left range since the click + if (GetSelectedItemId() == objectId) + return true; // already the selection: nothing to redo + + AcActionTrace.Record("OverlaySelect", objectId); + return SetSelectedObjectId(objectId); + } + public static uint GetSelectedItemId() { return ReadUInt32(_selectedIdAddr); @@ -610,7 +712,9 @@ internal static class ClientHelperHooks /// CM_Inventory::Event_GiveObjectRequest (cdecl) at 0x006ACA60 — the F7B1 give /// GameAction, the same path the drag-onto-NPC UI uses. This is the CORRECT /// give-to-NPC primitive; MoveItemExternal is move-to-container and does not - /// give. amount=0 gives the whole object; positive = partial stack. + /// give. amount=0 gives the whole object; positive = partial stack. The wire needs a + /// real count (ACE answers "Give amount not valid!" to 0), so 0 is turned into the + /// item's stack size here (1 for a single item). /// </summary> public static bool GiveObjectTo(uint objectId, uint targetId, int amount = 0) { @@ -627,7 +731,9 @@ internal static class ClientHelperHooks try { - byte rv = _eventGiveObjectRequest(objectId, targetId, amount); + if (amount == 0) + amount = WholeStackAmount(objectId); + byte rv = _eventGiveObjectRequest(targetId, objectId, amount); RynthLog.Verbose($"Compat: Event_GiveObjectRequest item=0x{objectId:X8} -> target=0x{targetId:X8} amount={amount} rv={rv}"); return rv != 0; } @@ -638,6 +744,113 @@ internal static class ClientHelperHooks } } + /// <summary> + /// The count that gives a whole object: its stack size, or 1 for a single item (or + /// when the item can't be read). Main thread (TryReadItemFields is false off it). + /// </summary> + internal static int WholeStackAmount(uint objectId) => + ClientObjectHooks.TryReadItemFields(objectId, out ClientObjectHooks.ItemPwdFields f) && f.StackSize > 1 + ? (int)Math.Min(f.StackSize, int.MaxValue) + : 1; + + /// <summary> + /// Wield an item into the given equip slot(s) through CM_Inventory::Event_GetAndWieldItem + /// (cdecl) at 0x006AC950 — the 0x001A GetAndWieldItem game action, the packet the + /// paperdoll drag sends (ACCWeenieObject::UIAttemptWield calls it). equipMask is an + /// EquipMask / INVENTORY_LOC value (e.g. 0x00100000 MeleeWeapon, 0x00200000 Shield, + /// 0x00400000 MissileWeapon, 0x01000000 Held, 0x02000000 TwoHanded; rings/bracelets + /// have a left and a right bit). The server checks the slot against the item's + /// ValidLocations and answers with the wield, or InventoryServerSaveFailed (0x00A0) plus + /// a WeenieError. Unlike UIAttemptWield this sends the packet only: no client busy count, + /// no pending-wield UI state — the same raw-send contract as GiveObjectTo. + /// </summary> + public static bool WieldItem(uint objectId, uint equipMask) + { + // Inventory sends run on AC's main thread, like MoveItemExternal / GiveObjectTo. + if (!MainThreadGuard.IsOnMainThread()) + return _eventGetAndWieldItem != null && IsValidObjectId(objectId) && equipMask != 0 + && AcMainThreadQueue.EnqueueWieldItem(objectId, equipMask); + + if (_eventGetAndWieldItem == null) return false; + if (!IsValidObjectId(objectId) || equipMask == 0) return false; + + try + { + byte rv = _eventGetAndWieldItem(objectId, equipMask); + RynthLog.Verbose($"Compat: Event_GetAndWieldItem item=0x{objectId:X8} mask=0x{equipMask:X8} rv={rv}"); + return rv != 0; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: Event_GetAndWieldItem threw - {ex.Message}"); + return false; + } + } + + /// <summary> + /// Drop an item on the ground through CM_Inventory::Event_DropItem (cdecl) at 0x006AC880, + /// the 0x001B DropItem game action that ACCWeenieObject::UIAttemptPutIn3D sends. The + /// server walks nothing (it drops at the player's feet) and answers with the item's new + /// place, or InventoryServerSaveFailed (0x00A0). Packet only, like WieldItem: no client + /// busy count, no pending-request UI state. Used by the Inventory panel. + /// </summary> + public static bool DropItem(uint objectId) + { + // Inventory sends run on AC's main thread, like WieldItem / GiveObjectTo. + if (!MainThreadGuard.IsOnMainThread()) + return _eventDropItem != null && IsValidObjectId(objectId) + && AcMainThreadQueue.EnqueueDropItem(objectId); + + if (_eventDropItem == null) return false; + if (!IsValidObjectId(objectId)) return false; + + try + { + byte rv = _eventDropItem(objectId); + RynthLog.Verbose($"Compat: Event_DropItem item=0x{objectId:X8} rv={rv}"); + return rv != 0; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: Event_DropItem threw - {ex.Message}"); + return false; + } + } + + /// <summary> + /// Close an external container (a corpse, a chest) the way the client does when its window + /// is closed: CM_Inventory::Event_NoLongerViewingContents (cdecl) at 0x006ACBB0, the 0x0195 + /// NoLongerViewingContents game action. Packet only, like DropItem: no busy count (m_cBusy), + /// no pending-request slot (it is not an inventory request; RecordRequest is not called). + /// The server closes the container if this player is viewing it and answers with + /// CloseGroundContainer (0x0052), whose client handler closes the window and raises + /// StopViewingObjectContents to the plugins. A container this player isn't viewing is + /// ignored by the server (no answer). Runs on AC's main thread, in the action ring, so a + /// close queued just before the next UseObject goes out first, in the same frame. + /// </summary> + public static bool CloseContainer(uint containerId) + { + // An inventory game-action send, like DropItem / WieldItem: main thread only. + if (!MainThreadGuard.IsOnMainThread()) + return _eventNoLongerViewingContents != null && IsValidObjectId(containerId) + && AcMainThreadQueue.EnqueueCloseContainer(containerId); + + if (_eventNoLongerViewingContents == null) return false; + if (!IsValidObjectId(containerId)) return false; + + try + { + byte rv = _eventNoLongerViewingContents(containerId); + RynthLog.Verbose($"Compat: Event_NoLongerViewingContents container=0x{containerId:X8} rv={rv}"); + return rv != 0; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: Event_NoLongerViewingContents threw - {ex.Message}"); + return false; + } + } + public static bool TryGetCurCoords(out double northSouth, out double eastWest) { northSouth = 0; @@ -646,6 +859,15 @@ internal static class ClientHelperHooks if (_inqPlayerCoords == null) return false; + // Off AC's main thread: no coords. The only caller (PluginManager.GetCurCoords, + // on the plugin pump) reaches this as the fallback when the raw SmartBox pose + // read fails, i.e. during login/portal/logout while AC's player state is + // changing. Calling CPlayerSystem::InqPlayerCoords there runs AC code + // off-thread and try/catch cannot stop a native AV. Plugins already handle + // "no coords", and InqPlayerCoords only returns cached data anyway. + if (!MainThreadGuard.IsOnMainThread()) + return false; + try { IntPtr playerSystem = ReadPointer(_playerSystemAddr); @@ -670,14 +892,29 @@ internal static class ClientHelperHooks } } + // Last player id read on AC's main thread. The native leaf (0x0048E5F0) reads + // the SmartBox global and then a field of it; off-thread that dereferences an + // AC object the main thread can free during logout/teardown, and try/catch + // cannot stop a native AV. Off-thread callers (host GetPlayerIdFn on the pump, + // snapshot owner checks, HUDs) get this value instead: at most one frame old, + // refreshed every EndScene by EngineFrameController, 0 = no player / not ready. + private static int _cachedPlayerId; + public static uint GetPlayerId() { if (_getPlayerId == null) return 0; + // Main-thread callers (PrefetchPlayerStats, IsFullOwnedContainer, the EndScene + // prefetches) keep the live native read exactly as before, and publish it. + if (!MainThreadGuard.IsOnMainThread()) + return unchecked((uint)Volatile.Read(ref _cachedPlayerId)); + try { - return _getPlayerId(); + uint id = _getPlayerId(); + Volatile.Write(ref _cachedPlayerId, unchecked((int)id)); + return id; } catch { @@ -733,6 +970,12 @@ internal static class ClientHelperHooks // MoveItemInternal/External early-return-enqueue off-thread), so the PWD ownership // read, ITEMS_CAPACITY read, and GetNumContainedItems walk are all authoritative // and the off-thread read-AV class does not apply. + /// <summary> + /// The full-pack guard MoveItemInternal / MoveItemExternal apply, for callers that send + /// through another path (the Inventory panel's split). Main thread. + /// </summary> + internal static bool IsOwnedContainerFull(uint target) => IsFullOwnedContainer(target); + private static bool IsFullOwnedContainer(uint target) { uint player = GetPlayerId(); @@ -871,6 +1114,15 @@ internal static class ClientHelperHooks if (_sendNoticeOpenSalvagePanel == null || toolId == 0) return false; + // Off AC's main thread (RynthAi SalvageManager / Meta tick on the plugin + // pump): marshal. The salvage trio posts a UI notice and mutates the live + // gmSalvageUI UIElement tree; off-thread it races AC's own UI walk, the + // same class as the SetSelectedObject 0x60D1D AV. The ring is FIFO with + // one consumer, so open -> add -> execute keep their order. Drain calls + // back into this method on the main thread, where the gate is satisfied. + if (!MainThreadGuard.IsOnMainThread()) + return AcMainThreadQueue.EnqueueSalvageOpen(toolId); + try { _sendNoticeOpenSalvagePanel(toolId); @@ -891,6 +1143,10 @@ internal static class ClientHelperHooks /// </summary> public static bool SalvagePanelAddItem(uint itemId) { + // Decal bridge mode: salvage is left to Decal (our OpenSalvagePanel hook isn't + // installed, so the instance is never captured) - Decal's SalvagePanelAdd instead. + if (DecalBridgeHost.Active && !SalvageHooks.IsInstalled) + return DecalBridgeHost.TrySalvagePanelAdd(itemId); if (_gmSalvageUIAddNewItem == null || itemId == 0) return false; @@ -901,6 +1157,14 @@ internal static class ClientHelperHooks return false; } + // Off-thread: enqueue AFTER the instance pre-check, so a false still means + // "panel not captured" (SalvageManager re-queues the item on it). The + // queued entry carries only the item id: on the main thread this method + // runs again and re-reads the instance, since the panel may have closed + // or been rebuilt in between. + if (!MainThreadGuard.IsOnMainThread()) + return AcMainThreadQueue.EnqueueSalvageAddItem(itemId); + try { _gmSalvageUIAddNewItem(inst, itemId); @@ -919,6 +1183,8 @@ internal static class ClientHelperHooks /// </summary> public static bool SalvagePanelExecute() { + if (DecalBridgeHost.Active && !SalvageHooks.IsInstalled) + return DecalBridgeHost.TrySalvagePanelSalvage(); // bridge mode: Decal's SalvagePanelSalvage if (_gmSalvageUISalvage == null) return false; @@ -929,6 +1195,11 @@ internal static class ClientHelperHooks return false; } + // Off-thread: same shape as SalvagePanelAddItem (instance re-read on the + // main thread when the entry drains). + if (!MainThreadGuard.IsOnMainThread()) + return AcMainThreadQueue.EnqueueSalvageExecute(); + try { _gmSalvageUISalvage(inst); @@ -974,8 +1245,12 @@ internal static class ClientHelperHooks _moveItemInternal = null; _eventStackableMerge = null; _eventGiveObjectRequest = null; + _eventGetAndWieldItem = null; + _eventDropItem = null; + _eventNoLongerViewingContents = null; _inqPlayerCoords = null; _getPlayerId = null; + Volatile.Write(ref _cachedPlayerId, 0); _addTextToScroll = null; _useWithTargetEvent = null; _sendNoticeOpenSalvagePanel = null; @@ -1018,6 +1293,13 @@ internal static class ClientHelperHooks return Marshal.ReadIntPtr(new IntPtr(address)); } + /// <summary>The ClientUISystem singleton, or Zero before the UI exists. Read-only (diagnostics).</summary> + internal static IntPtr ReadUiSystemPtr() + { + IntPtr slot = new IntPtr(_uiSystemAddr); + return ClientObjectHooks.IsReadablePointer(slot) ? Marshal.ReadIntPtr(slot) : IntPtr.Zero; + } + // WidePString (AC1Legacy::PStringBase<ushort>) helper fns — pattern-resolved (1a, 2026-06-05). private static readonly byte?[] PatWidePStringCtor = [ 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x85, 0xFF, 0x8B, 0xF1, 0x74, 0x2C ]; private static readonly byte?[] PatWidePStringDtor = [ 0x56, 0x8B, 0x31, 0x83, 0xEE, 0x14, 0x8D, 0x46 ]; diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index a04659a..f3f8cca 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -161,6 +161,24 @@ internal static class ClientObjectHooks private static uint _cachedLandcell; // player cell id (landblock = cell >> 16) private static float _cachedPx, _cachedPy, _cachedPz; // [status-export] player cell-local position (for the live map dot) private static uint _playerStatsCacheOwner; + // Primary attributes 1..6 (index = stype), buffed and raw, and the int64 properties plugins + // ask about (TotalExperience 1, AvailableExperience 2, AvailableLuminance 6, MaximumLuminance 7): + // main-thread-only Inq* reads, served to the off-thread plugin pump from this snapshot. + private static readonly uint[] _cachedAttrBuffed = new uint[7]; + private static readonly uint[] _cachedAttrRaw = new uint[7]; + // 1 TotalExperience, 2 AvailableExperience, 6 AvailableLuminance, 7 MaximumLuminance, then + // Aelrynth's Bank session totals (custom ids, absent on other servers): 9101 Radiance earned, + // 9102 Luminance auto-banked, 9103 Luminance drawn from the bank. RynthTracker reads them. + private static readonly uint[] PlayerQuadStypes = { 1u, 2u, 6u, 7u, 9101u, 9102u, 9103u }; + private static readonly Dictionary<uint, long> _cachedPlayerQuad = new(); + // Secondary attributes (vitals) by stype 1..6 from InqAttribute2ndBaseLevel: the buffed + // maximums RynthAi's getcharvital_buffedmax and RynthLua read. + private static readonly uint[] _cachedAttr2nd = new uint[7]; + // Skill levels by stype 1..54 (InqSkillLevel), buffed and raw. + private const int MaxSkillStype = 54; + private static readonly int[] _cachedSkillLevelBuffed = new int[MaxSkillStype + 1]; + private static readonly int[] _cachedSkillLevelRaw = new int[MaxSkillStype + 1]; + private static readonly bool[] _cachedSkillLevelKnown = new bool[MaxSkillStype + 1]; private static DateTime _lastPlayerStatsPrefetchUtc = DateTime.MinValue; private const int PlayerStatsPrefetchThrottleMs = 1000; @@ -213,6 +231,13 @@ internal static class ClientObjectHooks private static readonly object _objectIdentityCacheLock = new(); private static readonly Dictionary<uint, string> _objectNameCache = new(); private static readonly Dictionary<uint, uint> _objectTypeCache = new(); + // Live PublicWeenieDesc _location (CURRENT_WIELDED_LOCATION) per object, so the + // off-thread pump reads where an item is wielded from the client, not from an + // appraisal/update cache that can be stale after an equip swap. + private static readonly Dictionary<uint, int> _objectLocationCache = new(); + // Live PublicWeenieDesc _stackSize per object: the caches only know a stack the + // server sent an update or appraisal for, so an unappraised stack read as 1. + private static readonly Dictionary<uint, int> _objectStackCache = new(); private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue; private static bool _loggedObjectIdentityServe; private const int ObjectIdentityPrefetchThrottleMs = 500; @@ -229,8 +254,8 @@ internal static class ClientObjectHooks private const int CreateSeedCap = 16384; // PublicWeenieDesc field offsets (Chorizite Weenie.cs; same layout the PWD-direct // fallbacks in TryGetObjectName / TryGetItemType read from the embedded copy). + // PwdTypeOffset is declared with the other PublicWeenieDesc offsets further down. private const int PwdNameOffset = 4; - private const int PwdTypeOffset = 56; private static int _createSeedCount; private static bool _loggedCreateSeedServe; @@ -243,6 +268,71 @@ internal static class ClientObjectHooks /// </summary> public static uint[] LiveObjectIds => _liveObjectIds; + // ── Snapshot-only reads (monster nameplates) ──────────────────────────── + // The same main-thread snapshots the off-thread pump is served, readable + // from ANY thread without resolving the object: a dictionary lookup, never + // an AC call. Used where a few hundred ids are scanned several times a + // second (ImGui/MonsterHud), so the live paths' per-id native calls stay out. + + /// <summary>The attackable snapshot's value (main-thread ObjectIsAttackable, ~0.5 s old). False when not sampled.</summary> + public static bool TryGetSnapshotAttackable(uint objectId, out bool attackable) + { + lock (_attackableCacheLock) + return _attackableCache.TryGetValue(objectId, out attackable); + } + + /// <summary>The identity snapshot's name (~0.5 s old).</summary> + public static bool TryGetSnapshotName(uint objectId, out string name) + { + lock (_objectIdentityCacheLock) + { + if (_objectNameCache.TryGetValue(objectId, out string? n)) { name = n; return true; } + } + name = string.Empty; + return false; + } + + /// <summary>The identity snapshot's ITEM_TYPE flags (~0.5 s old).</summary> + public static bool TryGetSnapshotItemType(uint objectId, out uint typeFlags) + { + lock (_objectIdentityCacheLock) + return _objectTypeCache.TryGetValue(objectId, out typeFlags); + } + + /// <summary>The position snapshot's cell + landblock-local origin (~0.1 s old).</summary> + public static bool TryGetSnapshotPosition(uint objectId, out uint objCellId, out float x, out float y, out float z) + { + lock (_positionCacheLock) + { + if (_positionCache.TryGetValue(objectId, out PosEntry p)) + { + objCellId = p.Cell; x = p.X; y = p.Y; z = p.Z; + return true; + } + } + objCellId = 0; x = y = z = 0; + return false; + } + + /// <summary> + /// The PWD snapshot's ObjectDescriptionFlags bitfield (BF_PLAYER 0x8, BF_CORPSE + /// 0x2000, BF_PORTAL 0x40000, ...), container and wielder (~0.1 s old). Any + /// thread: on the main thread too it reads the snapshot, never AC memory + /// (the Sense scan, 2026-09-30). + /// </summary> + public static bool TryGetSnapshotPwdInfo(uint objectId, out uint bitfield, out uint containerId, out uint wielderId) + { + if (TryGetPwdSnapshot(objectId, out PwdEntry e)) + { + bitfield = e.Bitfield; + containerId = e.Container; + wielderId = e.Wielder; + return true; + } + bitfield = containerId = wielderId = 0; + return false; + } + // Position snapshot — mirrors the attackable/identity snapshots, but sampled // EVERY EndScene (no throttle) because positions change per-frame. The // off-thread plugin pump reads position from here instead of resolving @@ -252,9 +342,52 @@ internal static class ClientObjectHooks // delegate, struct values) so per-frame capture in the EndScene reverse- // P/Invoke can't trigger a GC → NativeAOT fail-fast (the same hazard that // moved TickAll off this thread; see EngineFrameController.OnEndScene). - private struct PosEntry { public uint Cell; public float X, Y, Z; } + // Qw/Qz and State (CPhysicsObj m_state) ride along since 2026-09-30 so the + // off-thread TryGetObjectHeading / TryGetObjectPhysicsState are served from + // this snapshot too, instead of dereferencing a cached weenie pointer. + private struct PosEntry { public uint Cell; public float X, Y, Z, Qw, Qz; public uint State; public bool HasState; } + + // PublicWeenieDesc field snapshot (2026-09-30 main-thread audit). The off-thread + // wcid / bitfield / icon / ownership readers used to take a raw weenie pointer + // from _weeniePtrFront (up to ~100 ms old) and read the PWD fields live; a + // weenie freed and reused in that window passes the page probe and hands the bot + // garbage (a wrong door bit, container or wcid), and a decommit between probe and + // read is an uncatchable AV. The same 10 Hz main-thread walk now copies the + // fields for EVERY id that resolves a weenie (pack items have no position), into + // a back/front pair swapped with the pointer maps under _weeniePtrSwapLock. + // Struct values in reused dictionaries: zero-alloc in the EndScene walk. + // IconOverlay / IconUnderlay ride along since 2026-09-30 (script window item icons). + // Since the property-coverage work (2026-09-30) the whole PublicWeenieDesc is copied + // (PwdLayout.Size bytes): every CreateObject field (value, burden, useability, radar, + // monarch, pet owner, ...) answers off the main thread as the property it came from. + [System.Runtime.CompilerServices.InlineArray(PwdLayout.Size)] + private struct PwdBytes { private byte _first; } + private struct PwdEntry + { + public PwdBytes Bytes; + public readonly uint Wcid => U32(in this, PwdLayout.Wcid); + public readonly uint Icon => U32(in this, PwdLayout.Icon); + public readonly uint IconOverlay => U32(in this, PwdLayout.IconOverlay); + public readonly uint IconUnderlay => U32(in this, PwdLayout.IconUnderlay); + public readonly uint Container => U32(in this, PwdLayout.Container); + public readonly uint Wielder => U32(in this, PwdLayout.Wielder); + public readonly uint Location => U32(in this, PwdLayout.Location); + public readonly uint Bitfield => U32(in this, PwdLayout.Bitfield); + private static uint U32(in PwdEntry e, int offset) + => System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(((ReadOnlySpan<byte>)e.Bytes).Slice(offset)); + } + private static Dictionary<uint, PwdEntry> _pwdFront = new(512); + private static Dictionary<uint, PwdEntry> _pwdBack = new(512); + private const int PwdWcidOffset = PwdLayout.Wcid, PwdIconOffset = PwdLayout.Icon, PwdIconOverlayOffset = PwdLayout.IconOverlay, + PwdIconUnderlayOffset = PwdLayout.IconUnderlay, PwdContainerOffset = PwdLayout.Container, + PwdWielderOffset = PwdLayout.Wielder, PwdLocationOffset = PwdLayout.Location, PwdBitfieldOffset = PwdLayout.Bitfield; private static readonly object _positionCacheLock = new(); - private static readonly Dictionary<uint, PosEntry> _positionCache = new(512); + // Double-buffered (2026-10-02): the walk fills _positionBack with no lock held, then the + // two swap under _positionCacheLock. Off-thread readers lock only to look up the front. + // The walk used to fill the front under the lock, so every plugin position read waited + // for the whole walk, and a slow walk (MemoryProbe) held the plugin tick to 4-9 a second. + private static Dictionary<uint, PosEntry> _positionCache = new(512); + private static Dictionary<uint, PosEntry> _positionBack = new(512); private static bool _loggedPositionServe; private static readonly Action<uint> _capturePositionDelegate = CapturePositionForId; private static DateTime _lastPositionPrefetchUtc = DateTime.MinValue; @@ -270,38 +403,37 @@ internal static class ClientObjectHooks // CObjectMaint READ-AV). The pump must NEVER call _getWeenieObject live; the // main-thread position walk records every live id->weeniePtr into // _weeniePtrBack, then publishes it to _weeniePtrFront via an atomic swap. - // GetWeenieObjectResolve serves _weeniePtrFront off-thread. Double-buffered + // (Since 2026-09-30 GetWeenieObjectResolve returns Zero off-thread instead of + // serving this map: off-thread readers use value snapshots. The map is kept + // for the snapshot diagnostics and swaps with _pwdFront.) Double-buffered // so off-thread reads take only the brief swap lock and never block on the // walk (the per-frame single-lock walk previously stalled the render thread). private static readonly object _weeniePtrSwapLock = new(); private static Dictionary<uint, IntPtr> _weeniePtrFront = new(512); private static Dictionary<uint, IntPtr> _weeniePtrBack = new(512); - // PublicWeenieDesc int-field snapshot (stack size, max stack, container, wielder, - // locations, capacities, material). Deep-audit finding #24 made the PWD reads main- - // thread-only, which left the off-thread plugin pump with NO source for these: every - // stack read as unknown (treated as 1) — AutoStack's 1,500 failed merges, AutoCram - // amounts, missile-crafting counts and meta item-count expressions. The main-thread - // position walk now copies these fields for every live object (pack items included) - // into _pwdBack and publishes it with the weenie-pointer swap, so off-thread readers - // get values at most ~100 ms old without touching AC memory. Struct values + reused - // dictionaries keep the walk zero-alloc (same constraint as _positionCache). - private struct PwdIntEntry - { - public int ContainerId, WielderId, ValidLocations, Location; - public int ItemsCapacity, ContainersCapacity, StackSize, MaxStackSize, MaterialType; - } - private static Dictionary<uint, PwdIntEntry> _pwdFront = new(512); - private static Dictionary<uint, PwdIntEntry> _pwdBack = new(512); - private static bool _loggedPwdServe; - // PWD field offsets (Chorizite Weenie.cs; same layout as the PWD fast paths below). - private const int PwdContainerIdOffset = 28, PwdWielderIdOffset = 32, PwdValidLocationsOffset = 40; - private const int PwdLocationOffset = 44, PwdItemsCapacityOffset = 48, PwdContainersCapacityOffset = 52; - private const int PwdStackSizeOffset = 96, PwdMaxStackSizeOffset = 100, PwdMaterialTypeOffset = 148; // Diagnostic (temporary): periodic snapshot-size log + live-read probe of // objects with a position but no cached name. Remove once the missing- // monsters cause is pinned. _diagSampleBuf preallocated to stay low-alloc. private static DateTime _lastSnapshotDiagUtc = DateTime.MinValue; + + // Time AC's main thread spends in each snapshot walk, reported (and reset) by the + // [SnapshotDiag] line every 10 s. The 2026-10-02 frame-rate collapse was these walks + // growing with AC's heap; this line is how a log shows whether they stay small. + private struct WalkStat + { + public int Count; + public long Ticks, MaxTicks; + public void Add(long ticks) { Count++; Ticks += ticks; if (ticks > MaxTicks) MaxTicks = ticks; } + public string TakeText() + { + double toMs = 1000.0 / System.Diagnostics.Stopwatch.Frequency; + string text = Count == 0 ? "-" : $"{Count}x avg {Ticks * toMs / Count:0.00} max {MaxTicks * toMs:0.00} ms"; + this = default; + return text; + } + } + private static WalkStat _walkPositions, _walkIdentity, _walkAttackable; private const int SnapshotDiagThrottleMs = 10000; private static readonly uint[] _diagSampleBuf = new uint[16]; // object_table id collection buffer for the table-comparison diagnostic. @@ -445,21 +577,28 @@ internal static class ClientObjectHooks private const uint PAGE_GUARD = 0x100; /// <summary> - /// Checks if a pointer's memory page is committed and readable via VirtualQuery. + /// Checks if a pointer's memory page is committed and not NOACCESS/GUARD. /// Critical for NativeAOT where try/catch does NOT catch access violations. + /// Answered by <see cref="MemoryProbe"/> (was a VirtualQuery per call, whose cost grows + /// with AC's heap under WOW64 - the 2026-10-02 frame-rate collapse; same answer). /// </summary> - internal static bool IsReadablePointer(IntPtr ptr) - { - if (ptr == IntPtr.Zero) - return false; - if (VirtualQuery(ptr, out var mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0) - return false; - if (mbi.State != MEM_COMMIT) - return false; - if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) - return false; - return true; - } + internal static bool IsReadablePointer(IntPtr ptr) => MemoryProbe.IsAccessible(ptr); + + /// <summary> + /// Like <see cref="IsReadablePointer"/> for a whole span: every page of the span must + /// pass (<see cref="MemoryProbe"/>; a span reaching into an uncommitted page fails closed). + /// </summary> + internal static bool IsReadableSpan(IntPtr ptr, int length) => MemoryProbe.IsAccessible(ptr, length); + + private const uint PAGE_WRITABLE_MASK = 0x04 /*READWRITE*/ | 0x08 /*WRITECOPY*/ + | 0x40 /*EXECUTE_READWRITE*/ | 0x80 /*EXECUTE_WRITECOPY*/; + + /// <summary> + /// Like <see cref="IsReadablePointer"/> but also requires a writable page. + /// Probe before a raw store into AC memory: under NativeAOT a write AV is not + /// catchable, so a freed or read-only target must fail closed instead. + /// </summary> + internal static bool IsWritablePointer(IntPtr ptr) => MemoryProbe.IsWritable(ptr); /// <summary> /// Stronger check than <see cref="IsReadablePointer"/>: confirms the pointer @@ -778,9 +917,19 @@ internal static class ClientObjectHooks public static bool TryGetVitae(uint playerId, out float value) { value = 1.0f; - // Off-thread: refuse — _getVitaeValue is an AC native call (Class A guard). + // Off-thread: _getVitaeValue is an AC native call (Class A guard). The player's vitae + // comes from the main-thread snapshot (PrefetchPlayerStats); others refuse. if (!MainThreadGuard.IsOnMainThread()) - return false; + { + if (playerId == 0 || playerId != ClientHelperHooks.GetPlayerId()) + return false; + lock (_playerStatsCacheLock) + { + if (_playerStatsCacheOwner != playerId) return false; + value = _cachedVitae; + return true; + } + } if (_getVitaeValue == null || _getWeenieObject == null) { if (!Probe() || _getVitaeValue == null || _getWeenieObject == null) @@ -951,7 +1100,10 @@ internal static class ClientObjectHooks { buffed = 0; training = 0; - if (_getWeenieObject == null) + // Lazy probe only on AC's main thread: a probe re-binds delegates the main + // thread uses and resets SmartBoxLocator's shared candidate list. Off-thread + // callers skip it and fall through to the cached-skill serve below. + if (_getWeenieObject == null && MainThreadGuard.IsOnMainThread()) { if (!Probe() || _getWeenieObject == null) return false; @@ -1204,13 +1356,48 @@ internal static class ClientObjectHooks if (TryGetObjectPosition(playerId, out uint c, out float fx, out float fy, out float fz) && c != 0) { cell = c; px = fx; py = fy; pz = fz; } // [status-export] cell-local position for the live map dot + var attrBuffed = new uint[7]; + var attrRaw = new uint[7]; + for (uint a = 1; a <= 6; a++) + { + if (TryGetObjectAttribute(playerId, a, 0, out uint ab)) attrBuffed[a] = ab; + if (TryGetObjectAttribute(playerId, a, 1, out uint ar)) attrRaw[a] = ar; + } + var attr2nd = new uint[7]; + for (uint a2 = 1; a2 <= 6; a2++) + if (TryGetObjectAttribute2ndBaseLevel(playerId, a2, out uint v2)) attr2nd[a2] = v2; + var skB = new int[MaxSkillStype + 1]; + var skR = new int[MaxSkillStype + 1]; + var skK = new bool[MaxSkillStype + 1]; + for (uint sk = 1; sk <= MaxSkillStype; sk++) + { + bool b = TryGetObjectSkillLevel(playerId, sk, 0, out int lb); + bool r = TryGetObjectSkillLevel(playerId, sk, 1, out int lr); + if (b) skB[sk] = lb; + if (r) skR[sk] = lr; + skK[sk] = b || r; + } + var quad = new Dictionary<uint, long>(); + foreach (uint q in PlayerQuadStypes) + if (TryGetObjectQuadProperty(playerId, q, out long qv)) quad[q] = qv; + lock (_playerStatsCacheLock) { + Array.Copy(attrBuffed, _cachedAttrBuffed, 7); + Array.Copy(attrRaw, _cachedAttrRaw, 7); + Array.Copy(attr2nd, _cachedAttr2nd, 7); + Array.Copy(skB, _cachedSkillLevelBuffed, skB.Length); + Array.Copy(skR, _cachedSkillLevelRaw, skR.Length); + Array.Copy(skK, _cachedSkillLevelKnown, skK.Length); + _cachedPlayerQuad.Clear(); + foreach (var kv in quad) _cachedPlayerQuad[kv.Key] = kv.Value; _cachedTotalXp = xp; _cachedLuminance = lum; _cachedDeaths = deaths; _cachedVitae = vitae; _cachedEncVal = encVal; _cachedEncCap = encCap; _cachedLandcell = cell; _cachedPx = px; _cachedPy = py; _cachedPz = pz; _playerStatsCacheOwner = playerId; } + + SnapshotPlayerQualities(playerId); } catch (Exception ex) { @@ -1218,6 +1405,124 @@ internal static class ClientObjectHooks } } + // ── The player's own qualities tables (2026-09-30) ───────────────────── + // Every property the client holds for the player, copied from its CBaseQualities hash + // tables once a second on AC's main thread (PrefetchPlayerStats): memory reads, no calls + // except a one-time layout check through InqInt64/InqFloat. PropertyCaches serves it after + // the PlayerDescription record, so the player answers in full even when the engine + // started after login (an injected or hot-reloaded engine never saw PlayerDescription). + // Raw values, as the server sent them (what UtilityBelt shows), not enchanted. + // CBaseQualities (Chorizite Weenie.cs; offsets match the InqInt/InqInt64/InqBool/ + // InqFloat/InqString patterns): +0x08 int, +0x0C int64, +0x10 bool, +0x14 float, + // +0x18 string, +0x1C data id, +0x20 instance id tables. + // PackableHashTable: +0x08 buckets, +0x0C bucket count. PackableHashData<K,V>: + // { K key; V data; next; hashVal }, so 4-byte data at +4 / next +8, 8-byte data + // (int64, double) at +8 / next +16 (MSVC aligns them to 8), a string's buffer at +4. + private sealed record OwnedBag(uint Owner, PropertyBag Bag); + private static volatile OwnedBag? _playerQualities; + private static int _qualitiesInt64Layout, _qualitiesFloatLayout; // 0 unchecked, 1 verified, -1 refused + + /// <summary>The player's qualities snapshot (~1 s old), or null. Any thread; never touches AC.</summary> + internal static PropertyBag? PlayerQualitiesSnapshot(uint playerId) + { + OwnedBag? b = _playerQualities; + return b != null && playerId != 0 && b.Owner == playerId ? b.Bag : null; + } + + /// <summary>Logout: the snapshot belongs to the character that left.</summary> + internal static void ClearPlayerQualitiesSnapshot() => _playerQualities = null; + + // MAIN THREAD ONLY (PrefetchPlayerStats). + private static unsafe void SnapshotPlayerQualities(uint playerId) + { + if (!TryGetPlayerQualitiesPtr(out IntPtr qualities) || qualities == IntPtr.Zero) + return; + IntPtr bq = qualities + CBaseQualitiesOffset; + if (!IsReadableSpan(bq, 0x24)) + return; + + var bag = new PropertyBag(); + WalkQualitiesTable(Marshal.ReadIntPtr(bq + 0x08), 8, (k, n) => bag.Ints[k] = Marshal.ReadInt32(n + 4)); + WalkQualitiesTable(Marshal.ReadIntPtr(bq + 0x10), 8, (k, n) => bag.Bools[k] = Marshal.ReadInt32(n + 4) != 0); + WalkQualitiesTable(Marshal.ReadIntPtr(bq + 0x1C), 8, (k, n) => bag.DataIds[k] = unchecked((uint)Marshal.ReadInt32(n + 4))); + WalkQualitiesTable(Marshal.ReadIntPtr(bq + 0x20), 8, (k, n) => bag.InstanceIds[k] = unchecked((uint)Marshal.ReadInt32(n + 4))); + WalkQualitiesTable(Marshal.ReadIntPtr(bq + 0x18), 8, (k, n) => + { + IntPtr buf = Marshal.ReadIntPtr(n + 4); // PStringBase -> PSRefBuffer: +8 length (with NUL), +20 chars + if (buf == IntPtr.Zero || !IsReadableSpan(buf, 20)) return; + int len = Marshal.ReadInt32(buf + 8); + if (len > 1 && len < 4096 && IsReadableSpan(buf + 20, len - 1)) + bag.Strings[k] = Marshal.PtrToStringAnsi(buf + 20, len - 1) ?? string.Empty; + }); + if (_qualitiesInt64Layout >= 0) + WalkQualitiesTable(Marshal.ReadIntPtr(bq + 0x0C), 16, (k, n) => bag.Int64s[k] = Marshal.ReadInt64(n + 8)); + if (_qualitiesFloatLayout >= 0) + WalkQualitiesTable(Marshal.ReadIntPtr(bq + 0x14), 16, (k, n) => + { + double v = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(n + 8)); + if (double.IsFinite(v)) bag.Floats[k] = v; + }); + + VerifyQualitiesLayout(bq, bag); + if (_qualitiesInt64Layout < 0) bag.Int64s.Clear(); + if (_qualitiesFloatLayout < 0) bag.Floats.Clear(); + _playerQualities = new OwnedBag(playerId, bag); + } + + // The 8-byte node layout is checked once against AC's own readers: a walked value must + // equal InqInt64 / InqFloat for the same key (raw or enchanted). A mismatch on every key + // refuses that table for the session instead of serving garbage. + private static unsafe void VerifyQualitiesLayout(IntPtr bq, PropertyBag bag) + { + if (_qualitiesInt64Layout == 0 && _inqInt64 != null && bag.Int64s.Count > 0) + { + bool match = false; + foreach (var kv in bag.Int64s) + { + long v = 0; + if (_inqInt64(bq, kv.Key, &v) != 0 && v == kv.Value) { match = true; break; } + } + _qualitiesInt64Layout = match ? 1 : -1; + RynthLog.Compat($"Compat: player qualities int64 layout {(match ? "verified" : "REFUSED (no key matched InqInt64)")} ({bag.Int64s.Count} keys)"); + } + if (_qualitiesFloatLayout == 0 && _inqFloat != null && bag.Floats.Count > 0) + { + bool match = false; + foreach (var kv in bag.Floats) + { + double raw = 0, enchanted = 0; + bool okRaw = _inqFloat(bq, kv.Key, &raw, 1) != 0; + bool okEnch = _inqFloat(bq, kv.Key, &enchanted, 0) != 0; + if ((okRaw && raw == kv.Value) || (okEnch && enchanted == kv.Value)) { match = true; break; } + } + _qualitiesFloatLayout = match ? 1 : -1; + RynthLog.Compat($"Compat: player qualities float layout {(match ? "verified" : "REFUSED (no key matched InqFloat)")} ({bag.Floats.Count} keys)"); + } + } + + // Walks one PackableHashTable (MAIN THREAD ONLY), bounded like AppraisalHooks' walkers. + private static void WalkQualitiesTable(IntPtr table, int nextOffset, Action<uint, IntPtr> onNode) + { + if (table == IntPtr.Zero || !IsReadableSpan(table, 0x10)) + return; + IntPtr buckets = Marshal.ReadIntPtr(table + 0x08); + int bucketCount = Marshal.ReadInt32(table + 0x0C); + if (buckets == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536 || !IsReadableSpan(buckets, bucketCount * 4)) + return; + int total = 0; + for (int i = 0; i < bucketCount; i++) + { + IntPtr node = Marshal.ReadIntPtr(buckets + i * 4); + int chain = 0; + while (node != IntPtr.Zero && chain++ < 4096 && total++ < 65536) + { + if (!IsReadableSpan(node, nextOffset + 4)) break; + onNode(unchecked((uint)Marshal.ReadInt32(node)), node); + node = Marshal.ReadIntPtr(node + nextOffset); + } + } + } + /// <summary> /// Off-thread-safe: serve the cached player-stats snapshot (XP / luminance / deaths / /// vitae multiplier, 1.0 = no penalty). Returns false until the cache is populated. @@ -1235,6 +1540,175 @@ internal static class ClientObjectHooks } } + // CACQualities::_attribCache (the Chorizite layout: SerializeUsingPackDBObj 0x38 + + // CBaseQualities 0x28), just before _skillStatsTable. AttributeCache: vtable, then six + // Attribute* (strength .. self) and three SecondaryAttribute* (health, stamina, mana). + // Attribute: vtable, _level_from_cp +4, _init_level +8, _cp_spent +12 (16 bytes); + // SecondaryAttribute adds _current_level +16. InqAttribute2nd (0x00592D20) reads the + // same [this+0x60] cache. + private const int AttributeCacheOffset = 0x60; + private const int QualitiesEnchantmentRegistryOffset = 0x70; + + /// <summary> + /// The Skills panel's reads (PlayerProgressHooks.Prefetch): the player's skill table + /// rows, the attribute cache (ranks, innate level, XP spent), buffed and base skills, + /// attributes and vital maximums, level, skill credits, XP, luminance and vitae, into + /// <paramref name="dst"/>. MAIN THREAD ONLY; every pointer is checked before it is read. + /// False (and <paramref name="dst"/> cleared) when the player or its qualities aren't there. + /// </summary> + internal static unsafe bool ReadPlayerProgressLive(PlayerProgress dst) + { + if (!MainThreadGuard.IsOnMainThread()) + return false; + dst.Clear(); + uint playerId = ClientHelperHooks.GetPlayerId(); + if (playerId == 0) + return false; + if (_getWeenieObject == null && (!Probe() || _getWeenieObject == null)) + return false; + + try + { + if (!TryGetObjectQualitiesPtr(playerId, out IntPtr q)) + return false; + // InqSkill / InqAttribute / InqAttribute2nd with raw 0 read the enchantment + // registry at [q+0x70] without a null check (early login): wait for it. + if (!IsReadableSpan(q, QualitiesEnchantmentRegistryOffset + 4) + || Marshal.ReadIntPtr(q + QualitiesEnchantmentRegistryOffset) == IntPtr.Zero) + return false; + dst.PlayerId = playerId; + + dst.SkillTableRead = ReadSkillRowsLive(q, dst); + dst.AttributeCacheRead = ReadAttributeCacheLive(q, dst); + + if (_inqSkillLevel != null) + { + for (uint sk = 1; sk <= PlayerProgress.MaxSkill; sk++) + { + int buffed = 0, raw = 0; + bool b = _inqSkillLevel(q, sk, &buffed, 0) != 0; + bool r = _inqSkillLevel(q, sk, &raw, 1) != 0; + dst.SkillLevelKnown[sk] = b || r; + dst.SkillBuffed[sk] = b ? buffed : raw; + dst.SkillBase[sk] = r ? raw : buffed; + } + } + if (_inqAttribute != null) + { + for (uint a = 1; a <= 6; a++) + { + uint v = 0; + if (_inqAttribute(q, a, &v, 0) != 0) dst.AttrBuffed[a] = v; + v = 0; + if (_inqAttribute(q, a, &v, 1) != 0) dst.AttrBase[a] = v; + } + } + if (_inqAttribute2ndBaseLevel != null) + { + // STypeAttribute2nd maximums: 1 health, 3 stamina, 5 mana. raw 0 applies + // EnchantAttribute2nd (decompile of 0x00592D20); raw 1 is the base maximum. + for (uint i = 1; i <= 3; i++) + { + uint stype = i * 2 - 1, v = 0; + if (_inqAttribute2ndBaseLevel(q, stype, &v, 0) != 0) dst.VitalBuffed[i] = v; + v = 0; + if (_inqAttribute2ndBaseLevel(q, stype, &v, 1) != 0) dst.VitalBase[i] = v; + } + } + + if (TryGetObjectIntProperty(playerId, 25u, out int level)) dst.Level = level; // PropertyInt.Level + if (TryGetObjectIntProperty(playerId, 24u, out int credits)) dst.SkillCredits = credits; // AvailableSkillCredits + if (TryGetObjectQuadProperty(playerId, 1u, out long total)) dst.TotalXp = total; // TotalExperience + if (TryGetObjectQuadProperty(playerId, 2u, out long avail)) dst.UnassignedXp = avail; // AvailableExperience + if (TryGetObjectQuadProperty(playerId, 6u, out long lum)) dst.Luminance = lum; // AvailableLuminance + if (TryGetObjectQuadProperty(playerId, 7u, out long maxLum)) dst.MaxLuminance = maxLum; // MaximumLuminance + if (TryGetVitae(playerId, out float vitae)) dst.Vitae = vitae; + return true; + } + catch (Exception ex) + { + RynthLog.Compat($"ReadPlayerProgressLive exception: {ex.Message}"); + dst.Clear(); + return false; + } + } + + /// <summary>The skill table at [q+0x64] into dst's skill rows (class, XP spent, ranks, innate). Main thread.</summary> + private static bool ReadSkillRowsLive(IntPtr q, PlayerProgress dst) + { + IntPtr tableFieldPtr = q + SkillStatsTableOffset; + if (!IsReadablePointer(tableFieldPtr)) + return false; + IntPtr skillTablePtr = Marshal.ReadIntPtr(tableFieldPtr); + // Marshal's layout, as PrefetchPlayerSkills reads it (the proven path). + if (skillTablePtr == IntPtr.Zero || !IsReadableSpan(skillTablePtr, Marshal.SizeOf<PackableHashTableUInt32SkillNative>())) + return false; + PackableHashTableUInt32SkillNative table = Marshal.PtrToStructure<PackableHashTableUInt32SkillNative>(skillTablePtr); + if (table.TableSize == 0 || table.TableSize > 4096 || table.Buckets == IntPtr.Zero + || !IsReadableSpan(table.Buckets, (int)table.TableSize * IntPtr.Size)) + return false; + + int nodeSize = Marshal.SizeOf<PackableHashDataUInt32SkillNative>(); + int total = 0; + for (uint b = 0; b < table.TableSize; b++) + { + IntPtr nodePtr = Marshal.ReadIntPtr(table.Buckets + unchecked((int)(b * (uint)IntPtr.Size))); + int guard = 0; + while (nodePtr != IntPtr.Zero && guard++ < 512 && total++ < 4096) + { + if (!IsReadableSpan(nodePtr, nodeSize)) + break; + PackableHashDataUInt32SkillNative node = Marshal.PtrToStructure<PackableHashDataUInt32SkillNative>(nodePtr); + if (node.Key >= 1 && node.Key <= PlayerProgress.MaxSkill) + { + dst.SkillInTable[node.Key] = true; + dst.SkillClass[node.Key] = node.Data.AdvancementClass; + dst.SkillXpSpent[node.Key] = node.Data.PracticePoints; + dst.SkillRanks[node.Key] = node.Data.LevelFromPracticePoints; + dst.SkillInit[node.Key] = node.Data.InitialLevel; + } + nodePtr = node.Next; + } + } + return true; + } + + /// <summary>The attribute cache at [q+0x60] into dst's attribute and vital rows. Main thread.</summary> + private static bool ReadAttributeCacheLive(IntPtr q, PlayerProgress dst) + { + IntPtr cacheFieldPtr = q + AttributeCacheOffset; + if (!IsReadablePointer(cacheFieldPtr)) + return false; + IntPtr cache = Marshal.ReadIntPtr(cacheFieldPtr); + if (cache == IntPtr.Zero || !IsReadableSpan(cache, 40)) + return false; + bool any = false; + for (int i = 0; i < 9; i++) + { + IntPtr a = Marshal.ReadIntPtr(cache + 4 + i * 4); + int size = i < 6 ? 16 : 20; + if (a == IntPtr.Zero || !IsReadableSpan(a, size) || !SmartBoxLocator.IsPointerInModule(Marshal.ReadIntPtr(a))) + continue; + uint ranks = unchecked((uint)Marshal.ReadInt32(a + 4)); + uint init = unchecked((uint)Marshal.ReadInt32(a + 8)); + uint spent = unchecked((uint)Marshal.ReadInt32(a + 12)); + if (i < 6) + { + dst.AttrRanks[i + 1] = ranks; + dst.AttrInit[i + 1] = init; + dst.AttrXpSpent[i + 1] = spent; + } + else + { + dst.VitalRanks[i - 5] = ranks; + dst.VitalInit[i - 5] = init; + dst.VitalXpSpent[i - 5] = spent; + } + any = true; + } + return any; + } + /// <summary> /// Refreshes the known-spell (spellbook) snapshot from AC. MUST run on AC's /// main thread — driven from the same EndScene path as PrefetchPlayerSkills. @@ -1360,9 +1834,19 @@ internal static class ClientObjectHooks public static unsafe bool TryGetObjectSkillLevel(uint objectId, uint skillStype, int raw, out int level) { level = 0; - // Off-thread: refuse — _inqSkillLevel is an AC native call (Class A guard). + // Off-thread: _inqSkillLevel is an AC native call (Class A guard). The player's own + // skill levels come from the main-thread snapshot (PrefetchPlayerStats); others refuse. if (!MainThreadGuard.IsOnMainThread()) - return false; + { + if (skillStype < 1 || skillStype > MaxSkillStype || objectId == 0 || objectId != ClientHelperHooks.GetPlayerId()) + return false; + lock (_playerStatsCacheLock) + { + if (_playerStatsCacheOwner != objectId || !_cachedSkillLevelKnown[skillStype]) return false; + level = raw != 0 ? _cachedSkillLevelRaw[skillStype] : _cachedSkillLevelBuffed[skillStype]; + return true; + } + } if (_inqSkillLevel == null || _getWeenieObject == null) { if (!Probe() || _inqSkillLevel == null || _getWeenieObject == null) @@ -1389,9 +1873,19 @@ internal static class ClientObjectHooks public static unsafe bool TryGetObjectAttribute(uint objectId, uint stype, int raw, out uint value) { value = 0; - // Off-thread: refuse — _inqAttribute is an AC native call (Class A guard). + // Off-thread: _inqAttribute is an AC native call (Class A guard). The player's own + // attributes come from the main-thread snapshot (PrefetchPlayerStats); others refuse. if (!MainThreadGuard.IsOnMainThread()) - return false; + { + if (stype < 1 || stype > 6 || objectId == 0 || objectId != ClientHelperHooks.GetPlayerId()) + return false; + lock (_playerStatsCacheLock) + { + if (_playerStatsCacheOwner != objectId) return false; + value = raw != 0 ? _cachedAttrRaw[stype] : _cachedAttrBuffed[stype]; + return value != 0; + } + } if (_inqAttribute == null || _getWeenieObject == null) { if (!Probe() || _inqAttribute == null || _getWeenieObject == null) @@ -1417,6 +1911,13 @@ internal static class ClientObjectHooks public static bool TryGetPlayerQualitiesPtr(out IntPtr qualitiesPtr) { qualitiesPtr = IntPtr.Zero; + // Main thread only. The hot-reload / Decal-coexistence init threads call this + // through PlayerVitalsHooks.TryReseedFromCurrentPlayer (EntryPoint); off the + // main thread TryGetQualitiesPtr refused anyway, so they always got false. + // Returning first skips the pointless lookup; the real reseed happens on the + // main thread in TryGetObjectQualitiesPtr's lazy path. + if (!MainThreadGuard.IsOnMainThread()) + return false; if (_getWeenieObject == null) { if (!Probe() || _getWeenieObject == null) @@ -1445,6 +1946,10 @@ internal static class ClientObjectHooks public static bool TryGetWeenieObjectPtr(uint objectId, out IntPtr ptr) { ptr = IntPtr.Zero; + // A raw weenie pointer is only meaningful on AC's main thread (off-thread the + // resolver returns Zero); refusing here also keeps the lazy Probe on-thread. + if (!MainThreadGuard.IsOnMainThread()) + return false; if (_getWeenieObject == null) { if (!Probe() || _getWeenieObject == null) @@ -1474,23 +1979,19 @@ internal static class ClientObjectHooks containerID = 0; wielderID = 0; location = 0; - - // Off-thread: serve from the main-thread PWD snapshot instead of dereferencing a - // cached (possibly freed and reused) weenie pointer — the finding #24 TOCTOU class. + // Off AC's main thread (plugin pump: RynthAi WorldObjectCache / loot / wield, + // RynthLua, GetContainerContents): the PWD snapshot from the 10 Hz main-thread + // walk. A miss (not walked yet, or gone) is false, as a cache miss in the + // weenie-pointer map was before. Never reads AC memory off-thread. if (!MainThreadGuard.IsOnMainThread()) { - PwdIntEntry e; - lock (_weeniePtrSwapLock) - { - if (!_pwdFront.TryGetValue(objectId, out e)) - return false; - } - containerID = unchecked((uint)e.ContainerId); - wielderID = unchecked((uint)e.WielderId); - location = unchecked((uint)e.Location); + if (!TryGetPwdSnapshot(objectId, out PwdEntry e)) + return false; + containerID = e.Container; + wielderID = e.Wielder; + location = e.Location; return true; } - if (_getWeenieObject == null) { if (!Probe() || _getWeenieObject == null) @@ -1537,9 +2038,9 @@ internal static class ClientObjectHooks value = 0; if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0) return false; - // Off-thread: only the fields the main-thread PWD snapshot carries are available. + // Off-thread: served from the main-thread PWD byte snapshot, never from AC memory. if (!MainThreadGuard.IsOnMainThread()) - return TryGetPwdSnapshotInt(objectId, pwdFieldOffset, out value); + return TryGetPwdSnapshotRawInt32(objectId, pwdFieldOffset, out value); if (_getWeenieObject == null) { if (!Probe() || _getWeenieObject == null) @@ -1564,6 +2065,74 @@ internal static class ClientObjectHooks } } + /// <summary>An item's PublicWeenieDesc fields, as the Inventory panel shows them.</summary> + internal struct ItemPwdFields + { + public uint Wcid, Icon, Container, Wielder, ValidLocations, Location, Type, Value, Useability, + StackSize, MaxStackSize, Bitfield, SpellId; + public int ItemsCapacity, Burden, MaterialType; + public float Workmanship; + } + + // PublicWeenieDesc offsets (Chorizite Weenie.cs:1734; the same base as TryReadPwdInt32). + private const int PwdItemsCapacityOffset = 48, PwdTypeOffset = 56, PwdValueOffset = 60, PwdUseabilityOffset = 64, + PwdValidLocationsOffset = 40, PwdStackSizeOffset = 96, PwdMaxStackSizeOffset = 100, PwdBurdenOffset = 116, + PwdSpellIdOffset = 120, PwdMaterialTypeOffset = 148, PwdWorkmanshipOffset = 152; + + /// <summary> + /// Reads every field the Inventory panel needs from an object's PublicWeenieDesc in one + /// go: the weenie is resolved once and PWD+12..+155 (wcid through workmanship) is + /// page-probed as one span, then plain reads. MAIN THREAD ONLY: off it this returns false + /// without touching AC memory. An object that is gone (or not a weenie) is false, never + /// a fault, so a caller holding an old id just finds nothing. + /// </summary> + internal static bool TryReadItemFields(uint objectId, out ItemPwdFields f) + { + f = default; + if (objectId == 0 || !MainThreadGuard.IsOnMainThread()) + return false; + if (_getWeenieObject == null) + { + if (!Probe() || _getWeenieObject == null) + return false; + } + if (_weeniePhysicsObjOffset < 0) + return false; + try + { + IntPtr weeniePtr = _getWeenieObject(objectId); + if (weeniePtr == IntPtr.Zero) + return false; + IntPtr pwd = weeniePtr + _weeniePhysicsObjOffset + 4; + if (!IsReadableSpan(pwd + PwdWcidOffset, PwdWorkmanshipOffset + 4 - PwdWcidOffset)) + return false; + f.Wcid = (uint)Marshal.ReadInt32(pwd + PwdWcidOffset); + f.Icon = (uint)Marshal.ReadInt32(pwd + PwdIconOffset); + f.Container = (uint)Marshal.ReadInt32(pwd + PwdContainerOffset); + f.Wielder = (uint)Marshal.ReadInt32(pwd + PwdWielderOffset); + f.ValidLocations = (uint)Marshal.ReadInt32(pwd + PwdValidLocationsOffset); + f.Location = (uint)Marshal.ReadInt32(pwd + PwdLocationOffset); + f.ItemsCapacity = Marshal.ReadInt32(pwd + PwdItemsCapacityOffset); + f.Type = (uint)Marshal.ReadInt32(pwd + PwdTypeOffset); + f.Value = (uint)Marshal.ReadInt32(pwd + PwdValueOffset); + f.Useability = (uint)Marshal.ReadInt32(pwd + PwdUseabilityOffset); + f.StackSize = (uint)Marshal.ReadInt32(pwd + PwdStackSizeOffset); + f.MaxStackSize = (uint)Marshal.ReadInt32(pwd + PwdMaxStackSizeOffset); + f.Bitfield = (uint)Marshal.ReadInt32(pwd + PwdBitfieldOffset); + f.Burden = Marshal.ReadInt32(pwd + PwdBurdenOffset); + f.SpellId = (uint)Marshal.ReadInt32(pwd + PwdSpellIdOffset); + f.MaterialType = Marshal.ReadInt32(pwd + PwdMaterialTypeOffset); + f.Workmanship = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(pwd + PwdWorkmanshipOffset)); + if (float.IsNaN(f.Workmanship) || f.Workmanship < 0 || f.Workmanship > 100) f.Workmanship = 0; + return true; + } + catch + { + f = default; + return false; + } + } + /// <summary> /// Reads PublicWeenieDesc._wcid directly from the weenie struct. /// Returns the Weenie Class ID (WCID) for the given object. @@ -1573,6 +2142,15 @@ internal static class ClientObjectHooks public static bool TryGetObjectWcid(uint objectId, out uint wcid) { wcid = 0; + // Off-thread (RynthAi ExpressionEngine / WorldObjectCache, RynthLua): the PWD + // snapshot (<= ~100 ms old; a wcid never changes for an object). + if (!MainThreadGuard.IsOnMainThread()) + { + if (!TryGetPwdSnapshot(objectId, out PwdEntry e)) + return false; + wcid = e.Wcid; + return true; + } if (_getWeenieObject == null) { if (!Probe() || _getWeenieObject == null) @@ -1606,6 +2184,16 @@ internal static class ClientObjectHooks public static bool TryGetObjectBitfield(uint objectId, out uint bitfield) { bitfield = 0; + // Off-thread (RynthAi DoorInteractionController's BF_DOOR check, player + // filters): the PWD snapshot (<= ~100 ms old). MonsterHud (main thread) + // keeps the live read below. + if (!MainThreadGuard.IsOnMainThread()) + { + if (!TryGetPwdSnapshot(objectId, out PwdEntry e)) + return false; + bitfield = e.Bitfield; + return true; + } if (_getWeenieObject == null) { if (!Probe() || _getWeenieObject == null) @@ -1851,6 +2439,7 @@ internal static class ClientObjectHooks if (!Probe() || _inqType == null || _getWeenieObject == null) return false; } + bool inqOk = false; try { IntPtr weeniePtr; @@ -1893,7 +2482,12 @@ internal static class ClientObjectHooks { typeFlags = _inqType(weeniePtr); } - return true; + // Qualities of a never-appraised world object (a portal) can hold type 0; + // the type the server sent in CreateObject is in the PWD below. Portals + // were missing from the radar and /ub usel until clicked (2026-09-29). + if (typeFlags != 0) + return true; + inqOk = true; } // PWD.type is set up by network packets independently of qualities. @@ -1909,7 +2503,9 @@ internal static class ClientObjectHooks if (IsReadablePointer(typeAddr)) { typeFlags = (uint)Marshal.ReadInt32(typeAddr); - return true; + if (typeFlags != 0) + return true; + inqOk = true; } } } @@ -1919,12 +2515,13 @@ internal static class ClientObjectHooks } // Last resort: appraisal cache from IdentifyObject responses. - if (AppraisalHooks.TryGetCachedIntProperty(objectId, 1 /* STypeInt.ItemType */, out int cachedType)) + if (AppraisalHooks.TryGetCachedIntProperty(objectId, 1 /* STypeInt.ItemType */, out int cachedType) && cachedType != 0) { typeFlags = unchecked((uint)cachedType); return true; } - return false; + typeFlags = 0; + return inqOk; // read fine, the type just isn't known yet } /// <summary> @@ -1935,52 +2532,39 @@ internal static class ClientObjectHooks /// All other stypes fall through to CBaseQualities::InqInt. /// Common stypes: LOCATIONS=9, CURRENT_WIELDED_LOCATION=10, STACK_SIZE=12, DAMAGE_TYPE=45. /// </summary> - /// <summary>PWD offset for STypeInt properties stored in PublicWeenieDesc, or -1.</summary> - private static int PwdOffsetForIntStype(uint stype) => stype switch - { - 6 => PwdItemsCapacityOffset, // ITEMS_CAPACITY → _itemsCapacity - 7 => PwdContainersCapacityOffset, // CONTAINERS_CAPACITY → _containersCapacity - 9 => PwdValidLocationsOffset, // LOCATIONS → _valid_locations - 10 => PwdLocationOffset, // CURRENT_WIELDED_LOCATION → _location - 11 => PwdMaxStackSizeOffset, // MAX_STACK_SIZE → _maxStackSize - 12 => PwdStackSizeOffset, // STACK_SIZE → _stackSize - 131 => PwdMaterialTypeOffset, // MATERIAL_TYPE → _material_type - _ => -1, - }; - public static unsafe bool TryGetObjectIntProperty(uint objectId, uint stype, out int value) { value = 0; - // Stypes whose values live in PublicWeenieDesc are served from the PWD first: it is - // network-populated and current, while the appraisal cache can be stale (a stack - // size cached before a merge). On AC's main thread the PWD is read live; off-thread - // it comes from the main-thread PWD snapshot (finding #24 forbids live reads there). - int pwdOffset = PwdOffsetForIntStype(stype); - if (pwdOffset >= 0) + // STACK_SIZE: the client's own copy is the truth (it follows every split, + // merge and use); the caches below only know stacks the server sent a + // property update or appraisal for. Live on the main thread, snapshot off it. + if (stype == 12) { - bool gotPwd = MainThreadGuard.IsOnMainThread() - ? TryReadPwdInt32(objectId, pwdOffset, out int pwdValue) - : TryGetPwdSnapshotInt(objectId, pwdOffset, out pwdValue); - // A zero stack field means "not sent" — let a cached appraisal value fill it in. - bool isStackField = stype is 11 or 12; - if (gotPwd && (!isStackField || pwdValue > 0)) + if (TryReadPwdInt32(objectId, 96, out value) && value > 0) return true; + lock (_objectIdentityCacheLock) { - value = pwdValue; - return true; + if (_objectStackCache.TryGetValue(objectId, out value)) return true; } - if (AppraisalHooks.TryGetCachedIntProperty(objectId, stype, out value)) - return true; - if (gotPwd) - { - value = pwdValue; - return true; - } - return false; + value = 0; } - // Appraisal cache covers objects where m_pQualities is null (doors, inventory items, etc.) - if (AppraisalHooks.TryGetCachedIntProperty(objectId, stype, out value)) + + // The player's current burden off the main thread: the PrefetchPlayerStats snapshot. + if (stype == 5 && !MainThreadGuard.IsOnMainThread() && objectId != 0 && objectId == ClientHelperHooks.GetPlayerId()) + { + lock (_playerStatsCacheLock) + { + if (_playerStatsCacheOwner == objectId) { value = _cachedEncVal; return true; } + } + } + + // The property caches (PropertyCaches: the player's PlayerDescription + private + // updates, else the last identify, then public updates). They cover objects whose + // m_pQualities is null (doors, inventory items), and server updates for + // never-appraised objects (an essence's uses after a use or refill) are newer than + // the PublicWeenieDesc copy read below. + if (PropertyCaches.TryGetInt(objectId, stype, out value)) return true; if (_getWeenieObject == null) @@ -1989,12 +2573,57 @@ internal static class ClientObjectHooks return false; } - // Deep-audit finding #24 (2026-06-18): never touch AC memory off-thread here. PWD-backed - // stypes were handled above (live on the main thread, snapshot off-thread); InqInt - // walks qualities and stays main-thread-only. Off-thread, the network update cache - // (a managed ConcurrentDictionary) still answers for never-appraised objects. + // Fast path: stypes whose values live in PublicWeenieDesc. + // PWD starts at weenie + _phys_obj_offset + 4. Layout (Chorizite Weenie.cs:1734): + // +28 _containerID, +32 _wielderID, +40 _valid_locations, +44 _location, + // +48 _itemsCapacity, +52 _containersCapacity, +76 _effects, +88 _structure, +92 _maxStructure, + // +96 _stackSize, +100 _maxStackSize, + // +148 _material_type + // CBaseQualities::InqInt fails for inventory/corpse items (m_pQualities is null on pack wienies). + // Any stype whose value lives in PWD must be served from here instead. + int pwdFieldOffset = stype switch + { + 6 => 48, // ITEMS_CAPACITY → _itemsCapacity + 7 => 52, // CONTAINERS_CAPACITY → _containersCapacity + 9 => 40, // LOCATIONS → _valid_locations + 10 => 44, // CURRENT_WIELDED_LOCATION → _location + 11 => 100, // MAX_STACK_SIZE → _maxStackSize + 12 => 96, // STACK_SIZE → _stackSize + 18 => 76, // UI_EFFECTS → _effects (a pet essence's element) + 91 => 92, // MAX_STRUCTURE → _maxStructure + 92 => 88, // STRUCTURE → _structure (uses left on kits, essences) + 131 => 148, // MATERIAL_TYPE → _material_type (4 bytes, int) + _ => -1, + }; + + // Deep-audit finding #24 (2026-06-18): this PWD fast path used to run + // BEFORE the IsOnMainThread check below, dereferencing a weenie + // pointer captured on a <=100ms-stale main-thread walk with raw + // Marshal.ReadInt32. IsReadablePointer catches an unmapped page but + // not a freed-then-reallocated one (TOCTOU) — off-thread that risks + // feeding a garbage property value into loot/salvage logic. Hoisted + // the gate up here (same place the InqInt fallback already gates) so + // the fast path only ever runs on the main thread; off-thread + // callers fall through to the appraisal cache only (already checked + // above) rather than touching AC memory directly. if (!MainThreadGuard.IsOnMainThread()) - return PropertyUpdateHooks.TryGetCachedIntProperty(objectId, stype, out value); + { + // Off the main thread the PWD copy of CURRENT_WIELDED_LOCATION comes from the + // identity snapshot. Only after the caches above: the PWD _location can stay 0 + // for an item wielded after it was created (a Longbow in hand read 0). + if (stype == 10) + { + lock (_objectIdentityCacheLock) + { + if (_objectLocationCache.TryGetValue(objectId, out value)) + return true; + } + value = 0; + } + // Every other CreateObject field (value, burden, capacity, useability, ...) from the + // PWD snapshot, the way an unidentified object's properties reach UtilityBelt. + return TryGetPwdSnapshotInt(objectId, stype, out value); + } // CBaseQualities::InqInt for stypes not in PWD. if (_inqInt == null) @@ -2008,28 +2637,24 @@ internal static class ClientObjectHooks if (weeniePtr == IntPtr.Zero) return false; - if (!TryGetQualitiesPtr(weeniePtr, out IntPtr qualitiesPtr)) - return false; - - IntPtr baseQualitiesPtr = qualitiesPtr + CBaseQualitiesOffset; - if (!IsReadablePointer(baseQualitiesPtr)) - return false; - - int retval = 0; - int result = _inqInt(baseQualitiesPtr, stype, &retval, 0, 1); - - if (result != 0) + if (TryGetQualitiesPtr(weeniePtr, out IntPtr qualitiesPtr)) { - value = retval; - return true; + IntPtr baseQualitiesPtr = qualitiesPtr + CBaseQualitiesOffset; + if (IsReadablePointer(baseQualitiesPtr)) + { + int retval = 0; + int result = _inqInt(baseQualitiesPtr, stype, &retval, 0, 1); + if (result != 0) + { + value = retval; + return true; + } + } } - // Fallback: network property cache (covers static world objects like doors - // where m_pQualities is null and InqInt returns 0). - if (PropertyUpdateHooks.TryGetCachedIntProperty(objectId, stype, out value)) - return true; - - return false; + // Fallback (no qualities, or InqInt doesn't know it): the rest of the + // PublicWeenieDesc, as off the main thread (the caches were read above). + return TryGetPwdSnapshotInt(objectId, stype, out value); } catch { @@ -2043,26 +2668,79 @@ internal static class ClientObjectHooks /// fast-path. DataID properties otherwise go through a qualities table that is /// null for inventory/pack items (InqDataID would fail), so we bypass it. PWD is /// network-populated, so this works on UNequipped items with no qualities pointer - /// and no appraisal — no main-thread native call (the weenie ptr is served from - /// the off-thread double-buffered snapshot when not on AC's main thread). - /// Supported stypes: Icon=8, IconOverlay=50, IconUnderlay=52. Layout per the _type - /// reader above: WeenieDesc(4) + _name(4) + _plural_name(4) + _wcid(4) = 16 → _iconID, - /// then _iconOverlayID(+20) and _iconUnderlayID(+24). + /// and no appraisal — no native call. Off AC's main thread the value comes from + /// the PWD field snapshot the 10 Hz main-thread walk takes (since 2026-09-30). + /// Supported stypes: Icon=8 (PWD._iconID at +16), IconOverlay=50 (_iconOverlayID + /// at +20) and IconUnderlay=52 (_iconUnderlayID at +24; both since 2026-09-30). + /// Layout per the _type reader above: WeenieDesc(4) + _name(4) + _plural_name(4) + + /// _wcid(4) = 16 → _iconID. 0 in the overlay/underlay fields means "none". /// </summary> public static bool TryGetObjectDataIdProperty(uint objectId, uint stype, out uint dataId) + { + if (TryGetPwdIconDataId(objectId, stype, out dataId)) + return true; + // Every other data id (2026-09-30): the property caches (identify DID table, + // PlayerDescription, UpdatePropertyDataID), then the rest of the PWD (Spell 28). + if (PropertyCaches.TryGetDataId(objectId, stype, out dataId)) + return true; + return TryGetPwdSnapshotDataId(objectId, stype, out dataId); + } + + /// <summary> + /// v73: a STypeIID (PropertyInstanceId) property - another object's id. Any thread; never + /// touches AC memory off the main thread. Container (2) and Wielder (3) come from the + /// client's own PublicWeenieDesc first (the client moves items itself; the snapshot follows + /// it), then the property caches (the player's PlayerDescription and private updates: + /// allegiance, monarch, patron, ...; public UpdatePropertyInstanceID), then the rest of the + /// PWD (Monarch 26, HouseOwner 32, PetOwner 44). A zero id answers nothing. + /// </summary> + public static bool TryGetObjectInstanceIdProperty(uint objectId, uint stype, out uint value) + { + value = 0; + if (objectId == 0 || stype == 0) + return false; + if (stype is 2 or 3 && TryGetObjectOwnershipInfo(objectId, out uint container, out uint wielder, out _)) + { + value = stype == 2 ? container : wielder; + if (value != 0) return true; + } + if (PropertyCaches.TryGetInstanceId(objectId, stype, out value) && value != 0) + return true; + return TryGetPwdSnapshotInstanceId(objectId, stype, out value); + } + + private static bool TryGetPwdIconDataId(uint objectId, uint stype, out uint dataId) { dataId = 0; int pwdFieldOffset = stype switch { - 8 => 16, // PropertyDataId.Icon → _iconID - 50 => 20, // PropertyDataId.IconOverlay → _iconOverlayID - 52 => 24, // PropertyDataId.IconUnderlay → _iconUnderlayID - _ => -1, + 8 => PwdIconOffset, // PropertyDataId.Icon → _iconID + 50 => PwdIconOverlayOffset, // PropertyDataId.IconOverlay → _iconOverlayID + 52 => PwdIconUnderlayOffset, // PropertyDataId.IconUnderlay → _iconUnderlayID + _ => -1, }; if (pwdFieldOffset < 0) return false; + // Off AC's main thread (RynthAi icons, AutoVendorManager): the PWD snapshot + // from the 10 Hz main-thread walk. Reading PWD through the cached weenie + // pointer here was the deep-audit #24 TOCTOU (a freed, reused weenie still + // passes the page probe). Blank icons are worse than a 100 ms old one, so + // serve the copy rather than refusing. + if (!MainThreadGuard.IsOnMainThread()) + { + if (!TryGetPwdSnapshot(objectId, out PwdEntry e)) + return false; + dataId = pwdFieldOffset switch + { + PwdIconOffset => e.Icon, + PwdIconOverlayOffset => e.IconOverlay, + _ => e.IconUnderlay, + }; + return true; + } + if (_getWeenieObject == null) { if (!Probe() || _getWeenieObject == null) @@ -2105,11 +2783,6 @@ internal static class ClientObjectHooks public static unsafe bool TryGetObjectDoubleProperty(uint objectId, uint stype, out double value) { value = 0; - if (_getWeenieObject == null) - { - if (!Probe() || _getWeenieObject == null) - return false; - } // Deep-audit finding #24 (2026-06-18): same TOCTOU class as // TryGetObjectIntProperty above — this PWD fast path used to run @@ -2117,9 +2790,24 @@ internal static class ClientObjectHooks // possibly-stale weenie pointer off-thread. Hoisted the gate up // before the fast path; no appraisal-cache fallback exists for this // stype today, so off-thread callers now just get false instead of - // an unguarded read. + // an unguarded read. (2026-09-30: also ahead of the lazy Probe, which + // must not run off-thread.) + // + // 2026-09-30: the property caches hold float properties too (the identify message's + // float table and armour/weapon profiles, PlayerDescription, UpdatePropertyFloat), so + // objects answer off-thread like their int, bool and string properties do. Before, + // every off-thread double read failed. UseRadius / CooldownDuration / workmanship of + // an unidentified object come from the PWD snapshot. + if (PropertyCaches.TryGetFloat(objectId, stype, out value)) + return true; if (!MainThreadGuard.IsOnMainThread()) - return false; + return TryGetPwdSnapshotFloat(objectId, stype, out value); + + if (_getWeenieObject == null) + { + if (!Probe() || _getWeenieObject == null) + return false; + } // Fast path: ITEM_WORKMANSHIP (STypeFloat=280) → PublicWeenieDesc._workmanship (Single at PWD+152) if (stype == 280u && _weeniePhysicsObjOffset >= 0) @@ -2155,20 +2843,21 @@ internal static class ClientObjectHooks if (weeniePtr == IntPtr.Zero) return false; - if (!TryGetQualitiesPtr(weeniePtr, out IntPtr qualitiesPtr)) - return false; - - IntPtr baseQualitiesPtr = qualitiesPtr + CBaseQualitiesOffset; - if (!IsReadablePointer(baseQualitiesPtr)) - return false; - - double retval = 0; - int result = _inqFloat(baseQualitiesPtr, stype, &retval, 0); - if (result == 0) - return false; - - value = retval; - return true; + if (TryGetQualitiesPtr(weeniePtr, out IntPtr qualitiesPtr)) + { + IntPtr baseQualitiesPtr = qualitiesPtr + CBaseQualitiesOffset; + if (IsReadablePointer(baseQualitiesPtr)) + { + double retval = 0; + int result = _inqFloat(baseQualitiesPtr, stype, &retval, 0); + if (result != 0) + { + value = retval; + return true; + } + } + } + return TryGetPwdSnapshotFloat(objectId, stype, out value); } catch { @@ -2183,9 +2872,19 @@ internal static class ClientObjectHooks public static unsafe bool TryGetObjectQuadProperty(uint objectId, uint stype, out long value) { value = 0; - // Off-thread: refuse — _inqInt64 is an AC native call (Class A guard). + // The property caches first (2026-09-30): the player's PlayerDescription + private + // updates, an identified object's int64 table, public UpdatePropertyInt64. + if (PropertyCaches.TryGetInt64(objectId, stype, out value)) + return true; + // Off-thread: _inqInt64 is an AC native call (Class A guard). The player's experience and + // luminance come from the main-thread snapshot (PrefetchPlayerStats); others refuse. if (!MainThreadGuard.IsOnMainThread()) - return false; + { + if (objectId == 0 || objectId != ClientHelperHooks.GetPlayerId()) + return false; + lock (_playerStatsCacheLock) + return _playerStatsCacheOwner == objectId && _cachedPlayerQuad.TryGetValue(stype, out value); + } if (_inqInt64 == null) { if (!Probe() || _inqInt64 == null) @@ -2227,9 +2926,19 @@ internal static class ClientObjectHooks public static unsafe bool TryGetObjectAttribute2ndBaseLevel(uint objectId, uint stype, out uint value) { value = 0; - // Off-thread: refuse — _inqAttribute2ndBaseLevel is an AC native call (Class A guard). + // Off-thread: _inqAttribute2ndBaseLevel is an AC native call (Class A guard). The player's + // own values come from the main-thread snapshot (PrefetchPlayerStats); others refuse. if (!MainThreadGuard.IsOnMainThread()) - return false; + { + if (stype < 1 || stype > 6 || objectId == 0 || objectId != ClientHelperHooks.GetPlayerId()) + return false; + lock (_playerStatsCacheLock) + { + if (_playerStatsCacheOwner != objectId) return false; + value = _cachedAttr2nd[stype]; + return value != 0; + } + } if (_inqAttribute2ndBaseLevel == null) { if (!Probe() || _inqAttribute2ndBaseLevel == null) @@ -2266,21 +2975,15 @@ internal static class ClientObjectHooks { value = false; - // Appraisal cache covers inventory items where m_pQualities is null - // (CBaseQualities::InqBool always returns 0 for such objects). - if (AppraisalHooks.TryGetCachedBoolProperty(objectId, stype, out value)) + // The property caches cover inventory items where m_pQualities is null + // (CBaseQualities::InqBool always returns 0 for such objects), the player's own + // record and public updates (PropertyCaches; pure dictionary reads). + if (PropertyCaches.TryGetBool(objectId, stype, out value)) return true; // Off-thread: refuse — _inqBool is an AC native call (Class A guard). - // PropertyUpdateHooks cache fallback also gated below — only the - // safe network-cache lookup is allowed off-thread there. if (!MainThreadGuard.IsOnMainThread()) - { - // Allow the network-property cache to serve off-thread (pure dict read). - if (PropertyUpdateHooks.TryGetCachedBoolProperty(objectId, stype, out value)) - return true; return false; - } if (_inqBool == null || _getWeenieObject == null) { if (!Probe() || _inqBool == null || _getWeenieObject == null) @@ -2328,14 +3031,16 @@ internal static class ClientObjectHooks { value = string.Empty; - // Appraisal cache covers inventory items where m_pQualities is null - // (CBaseQualities::InqString always returns 0 for such objects). - if (AppraisalHooks.TryGetCachedStringProperty(objectId, stype, out value)) + // The property caches cover inventory items where m_pQualities is null + // (CBaseQualities::InqString always returns 0 for such objects), the player's own + // record (PlayerDescription) and UpdatePropertyString (PropertyCaches). + if (PropertyCaches.TryGetString(objectId, stype, out value)) return true; - // Off-thread: refuse — _inqString is an AC native call (Class A guard). + // Off-thread: refuse — _inqString is an AC native call (Class A guard). The name + // (PropertyString.Name, 1) of any object comes from the identity snapshot. if (!MainThreadGuard.IsOnMainThread()) - return false; + return stype == 1 && TryGetSnapshotName(objectId, out value) && value.Length > 0; if (_inqString == null || _getWeenieObject == null) { if (!Probe() || _inqString == null || _getWeenieObject == null) @@ -2518,14 +3223,16 @@ internal static class ClientObjectHooks if ((DateTime.UtcNow - _lastAttackablePrefetchUtc).TotalMilliseconds < AttackablePrefetchThrottleMs) return; _lastAttackablePrefetchUtc = DateTime.UtcNow; + long walkT0 = System.Diagnostics.Stopwatch.GetTimestamp(); + using var probeScope = MemoryProbe.BeginWalk(); // one page query per page per walk (MemoryProbe) try { - var snapshot = new Dictionary<uint, bool>(); - int n = CObjectMaintHooks.EnumerateLiveWeenieObjectIds(id => - { - snapshot[id] = ComputeAttackableOnMainThread(id); - }); + // Scratch reused across walks (main thread only): the walk used to allocate a new + // dictionary and closure every 500 ms on AC's thread, growing with the object count. + var snapshot = _attackableScratch; + snapshot.Clear(); + int n = CObjectMaintHooks.EnumerateLiveWeenieObjectIds(_captureAttackableDelegate); if (n <= 0) return; // walk failed/empty — keep the last good snapshot @@ -2549,6 +3256,35 @@ internal static class ClientObjectHooks { RynthLog.Compat($"PrefetchAttackable exception: {ex.Message}"); } + finally + { + _walkAttackable.Add(System.Diagnostics.Stopwatch.GetTimestamp() - walkT0); + } + } + + // Main-thread scratch for the attackable / identity walks (see PrefetchAttackable). + private static readonly Dictionary<uint, bool> _attackableScratch = new(1024); + private static readonly Dictionary<uint, string> _identityNameScratch = new(1024); + private static readonly Dictionary<uint, uint> _identityTypeScratch = new(1024); + private static readonly Dictionary<uint, int> _identityLocScratch = new(1024); + private static readonly Dictionary<uint, int> _identityStackScratch = new(1024); + private static readonly List<uint> _identityIdScratch = new(1024); + private static readonly Action<uint> _captureAttackableDelegate = CaptureAttackableForId; + private static readonly Action<uint> _captureIdentityDelegate = CaptureIdentityForId; + + private static void CaptureAttackableForId(uint id) => _attackableScratch[id] = ComputeAttackableOnMainThread(id); + + private static void CaptureIdentityForId(uint id) + { + _identityIdScratch.Add(id); + if (TryGetObjectName(id, out string nm) && nm.Length > 0) + _identityNameScratch[id] = nm; + if (TryGetItemType(id, out uint typeFlags)) + _identityTypeScratch[id] = typeFlags; + if (TryReadPwdInt32(id, 44, out int loc)) + _identityLocScratch[id] = loc; + if (TryReadPwdInt32(id, 96, out int stack) && stack > 0) + _identityStackScratch[id] = stack; } public static void PrefetchObjectIdentity() @@ -2558,21 +3294,20 @@ internal static class ClientObjectHooks if ((DateTime.UtcNow - _lastObjectIdentityPrefetchUtc).TotalMilliseconds < ObjectIdentityPrefetchThrottleMs) return; _lastObjectIdentityPrefetchUtc = DateTime.UtcNow; + long walkT0 = System.Diagnostics.Stopwatch.GetTimestamp(); + using var probeScope = MemoryProbe.BeginWalk(); // one page query per page per walk (MemoryProbe) try { - var nameSnap = new Dictionary<uint, string>(); - var typeSnap = new Dictionary<uint, uint>(); - var idSnap = new List<uint>(); + // Scratch reused across walks (main thread only), as PrefetchAttackable. + var nameSnap = _identityNameScratch; + var typeSnap = _identityTypeScratch; + var locSnap = _identityLocScratch; + var stackSnap = _identityStackScratch; + var idSnap = _identityIdScratch; + nameSnap.Clear(); typeSnap.Clear(); locSnap.Clear(); stackSnap.Clear(); idSnap.Clear(); - int n = CObjectMaintHooks.EnumerateLiveWeenieObjectIds(id => - { - idSnap.Add(id); - if (TryGetObjectName(id, out string nm) && nm.Length > 0) - nameSnap[id] = nm; - if (TryGetItemType(id, out uint typeFlags)) - typeSnap[id] = typeFlags; - }); + int n = CObjectMaintHooks.EnumerateLiveWeenieObjectIds(_captureIdentityDelegate); if (n <= 0) return; // walk failed/empty — keep the last good snapshot @@ -2585,6 +3320,12 @@ internal static class ClientObjectHooks _objectTypeCache.Clear(); foreach (var kv in typeSnap) _objectTypeCache[kv.Key] = kv.Value; + _objectLocationCache.Clear(); + foreach (var kv in locSnap) + _objectLocationCache[kv.Key] = kv.Value; + _objectStackCache.Clear(); + foreach (var kv in stackSnap) + _objectStackCache[kv.Key] = kv.Value; } _liveObjectIds = idSnap.ToArray(); @@ -2598,6 +3339,10 @@ internal static class ClientObjectHooks { RynthLog.Compat($"PrefetchObjectIdentity exception: {ex.Message}"); } + finally + { + _walkIdentity.Add(System.Diagnostics.Stopwatch.GetTimestamp() - walkT0); + } } /// <summary> @@ -2891,6 +3636,36 @@ internal static class ClientObjectHooks if (!TryGetWeenieObjectPtr(objectId, out IntPtr weeniePtr)) return false; + return ReadPhysicsFromWeenie(objectId, weeniePtr, out objCellId, out x, out y, out z, out _, out _, out _, out _); + } + + /// <summary> + /// Reads cell/origin plus the heading quaternion's qw/qz and CPhysicsObj m_state + /// from a weenie pointer resolved on the main thread. MAIN THREAD ONLY (callers: + /// <see cref="ReadObjectPositionLive"/> and the <see cref="PrefetchPositions"/> walk). + /// </summary> + private static bool ReadPhysicsFromWeenie( + uint objectId, + IntPtr weeniePtr, + out uint objCellId, + out float x, + out float y, + out float z, + out float qw, + out float qz, + out uint state, + out bool hasState) + { + objCellId = 0; + x = y = z = 0; + qw = 1f; + qz = 0; + state = 0; + hasState = false; + + if (weeniePtr == IntPtr.Zero || _weeniePhysicsObjOffset < 0) + return false; + try { IntPtr physicsObj = Marshal.ReadIntPtr(weeniePtr + _weeniePhysicsObjOffset); @@ -2903,7 +3678,11 @@ internal static class ClientObjectHooks // read below would AV in NativeAOT, bypassing try/catch. IsReadablePointer // catches the unmapped-page case; the vtable module check catches any // garbage-but-mapped value. - if (!IsReadablePointer(physicsObj)) + // One VirtualQuery covers the object head through m_state (+0xA8); if the + // span happens to straddle two regions, fall back to the old head-only + // probe and leave m_state unknown for this pass. + bool spanOk = IsReadableSpan(physicsObj, PhysicsStateOffset + 4); + if (!spanOk && !IsReadablePointer(physicsObj)) return false; IntPtr vtable = Marshal.ReadIntPtr(physicsObj); @@ -2915,6 +3694,13 @@ internal static class ClientObjectHooks x = ReadFloat(pos + PositionOriginXOffset); y = ReadFloat(pos + PositionOriginYOffset); z = ReadFloat(pos + PositionOriginZOffset); + qw = ReadFloat(pos + PositionQwOffset); + qz = ReadFloat(pos + PositionQzOffset); + if (spanOk) + { + state = unchecked((uint)Marshal.ReadInt32(physicsObj + PhysicsStateOffset)); + hasState = true; + } return true; } catch (Exception ex) @@ -2924,6 +3710,14 @@ internal static class ClientObjectHooks } } + // Heading (0–360°, clockwise, 0 = North) from a yaw quaternion's qw/qz. Same + // formula as NavigationEngine / CorpseOpenController. + private static float HeadingFromQuaternion(float qw, float qz) + { + double physYawDeg = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + return (float)(((-physYawDeg) % 360.0 + 720.0) % 360.0); + } + /// <summary> /// Samples every live object's position on AC's main thread (EndScene path) /// into <see cref="_positionCache"/>, which the off-thread plugin pump reads @@ -2931,9 +3725,9 @@ internal static class ClientObjectHooks /// volatile) and ZERO-ALLOC: the dict is reused (Clear + re-add of struct /// values) and the per-id callback is a cached delegate, so this never /// allocates inside the EndScene reverse-P/Invoke (which would risk the - /// NativeAOT GC fail-fast that moved TickAll off this thread). The lock is - /// held across the walk to stay zero-alloc; the pump's per-id read contends - /// only briefly. Walk runs every frame, so a transient empty (walk failure) + /// NativeAOT GC fail-fast that moved TickAll off this thread). Two reused + /// dictionaries swap after the walk (still zero-alloc), so the pump's per-id + /// read never waits for the walk. Walk runs every frame, so a transient empty (walk failure) /// self-heals next frame — no last-good retention needed (unlike the /// throttled attackable/identity snapshots). /// </summary> @@ -2944,6 +3738,8 @@ internal static class ClientObjectHooks if ((DateTime.UtcNow - _lastPositionPrefetchUtc).TotalMilliseconds < PositionPrefetchThrottleMs) return; _lastPositionPrefetchUtc = DateTime.UtcNow; + long walkT0 = System.Diagnostics.Stopwatch.GetTimestamp(); + using var probeScope = MemoryProbe.BeginWalk(); // one page query per page per walk (MemoryProbe) if (_weeniePhysicsObjOffset < 0) { ProbePhysObjOffset(); @@ -2953,29 +3749,24 @@ internal static class ClientObjectHooks try { - lock (_positionCacheLock) - { - _positionCache.Clear(); - _weeniePtrBack.Clear(); - _pwdBack.Clear(); - CObjectMaintHooks.EnumerateLiveWeenieObjectIds(_capturePositionDelegate); - } + // Back buffers are main-thread only: fill them with no lock held. + _positionBack.Clear(); + _weeniePtrBack.Clear(); + _pwdBack.Clear(); + CObjectMaintHooks.EnumerateLiveWeenieObjectIds(_capturePositionDelegate); - // Publish the freshly-walked id->weeniePtr map (GetWeenieObjectResolve) and the - // PWD int snapshot (TryGetPwdSnapshotInt) to off-thread readers together. The - // swap is brief and is NOT held during the walk, so pump reads never stall on it. + lock (_positionCacheLock) + (_positionCache, _positionBack) = (_positionBack, _positionCache); + + // Publish the freshly-walked id->weeniePtr map and the PWD field copy + // to off-thread readers together. The swap is brief and is NOT held + // during the walk, so the pump's reads never stall on the walk. lock (_weeniePtrSwapLock) { (_weeniePtrFront, _weeniePtrBack) = (_weeniePtrBack, _weeniePtrFront); (_pwdFront, _pwdBack) = (_pwdBack, _pwdFront); } - if (!_loggedPwdServe && _pwdFront.Count > 0) - { - _loggedPwdServe = true; - RynthLog.Compat($"ClientObjectHooks: PWD int snapshot warm — {_pwdFront.Count} objects (stack size / max stack / container / location served off-thread)."); - } - if (!_loggedPositionServe && _positionCache.Count > 0) { _loggedPositionServe = true; @@ -2988,6 +3779,10 @@ internal static class ClientObjectHooks { RynthLog.Compat($"PrefetchPositions exception: {ex.Message}"); } + finally + { + _walkPositions.Add(System.Diagnostics.Stopwatch.GetTimestamp() - walkT0); + } } // ── DIAGNOSTIC (logging only, temporary) ──────────────────────────────── @@ -3013,6 +3808,8 @@ internal static class ClientObjectHooks lock (_objectIdentityCacheLock) { nameN = _objectNameCache.Count; typeN = _objectTypeCache.Count; } lock (_weeniePtrSwapLock) ptrN = _weeniePtrFront.Count; RynthLog.Compat($"[SnapshotDiag] pos={posN} attackable={atkN}({atkTrue} atk) names={nameN} types={typeN} ptr={ptrN}"); + var (fastPages, slowCalls, slowMs) = MemoryProbe.TakeStats(); + RynthLog.Compat($"[SnapshotDiag] walks (main thread, last 10 s): positions {_walkPositions.TakeText()}; identity {_walkIdentity.TakeText()}; attackable {_walkAttackable.TakeText()}; memory probes {fastPages} pages fast, {slowCalls} VirtualQuery ({slowMs:0.0} ms){(MemoryProbe.FastPathActive ? "" : " FAST PATH OFF")}"); // Compare CObjectMaint's physics tables — object_table (+0x84) and // null_object_table (+0x9C, objects with pending/null weenie) — @@ -3057,98 +3854,119 @@ internal static class ClientObjectHooks } // Cached delegate target for PrefetchPositions' enumerate. Runs on the main - // thread under _positionCacheLock; reads the live position and stores it. + // thread (no lock: it fills the back buffer); reads the live position and stores it. // Method group is cached in _capturePositionDelegate so the enumerate call // allocates no closure per frame. - /// <summary> - /// Copies the PublicWeenieDesc int fields of a freshly resolved (main-thread, live) - /// weenie into <see cref="_pwdBack"/>. One VirtualQuery covers the whole +28..+151 - /// span when it sits in a single region (the normal case), so the 10 Hz walk stays - /// cheap; a span crossing a region boundary is probed at both ends. Zero-alloc. - /// </summary> - private static void CapturePwdInts(uint id, IntPtr weeniePtr) - { - if (_weeniePhysicsObjOffset < 0) - return; - try - { - IntPtr pwd = weeniePtr + _weeniePhysicsObjOffset + 4; - IntPtr first = pwd + PwdContainerIdOffset; - IntPtr last = pwd + PwdMaterialTypeOffset + 3; - if (!IsReadableRange(first, last)) - return; - - _pwdBack[id] = new PwdIntEntry - { - ContainerId = Marshal.ReadInt32(pwd + PwdContainerIdOffset), - WielderId = Marshal.ReadInt32(pwd + PwdWielderIdOffset), - ValidLocations = Marshal.ReadInt32(pwd + PwdValidLocationsOffset), - Location = Marshal.ReadInt32(pwd + PwdLocationOffset), - ItemsCapacity = Marshal.ReadInt32(pwd + PwdItemsCapacityOffset), - ContainersCapacity = Marshal.ReadInt32(pwd + PwdContainersCapacityOffset), - StackSize = Marshal.ReadInt32(pwd + PwdStackSizeOffset), - MaxStackSize = Marshal.ReadInt32(pwd + PwdMaxStackSizeOffset), - MaterialType = Marshal.ReadInt32(pwd + PwdMaterialTypeOffset), - }; - } - catch - { - // Unreadable descriptor: leave the id out of the snapshot (readers fail closed). - } - } - - /// <summary>True when every byte in [first, last] is committed, readable memory.</summary> - private static bool IsReadableRange(IntPtr first, IntPtr last) - { - if (VirtualQuery(first, out var mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0) - return false; - if (mbi.State != MEM_COMMIT || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) - return false; - long regionEnd = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64(); - return last.ToInt64() < regionEnd || IsReadablePointer(last); - } - - /// <summary> - /// Off-thread read of a PWD int field from the main-thread snapshot. Returns false for - /// offsets the snapshot doesn't carry or objects not seen by the last walk. - /// </summary> - private static bool TryGetPwdSnapshotInt(uint objectId, int pwdFieldOffset, out int value) - { - value = 0; - PwdIntEntry e; - lock (_weeniePtrSwapLock) - { - if (!_pwdFront.TryGetValue(objectId, out e)) - return false; - } - switch (pwdFieldOffset) - { - case PwdContainerIdOffset: value = e.ContainerId; return true; - case PwdWielderIdOffset: value = e.WielderId; return true; - case PwdValidLocationsOffset: value = e.ValidLocations; return true; - case PwdLocationOffset: value = e.Location; return true; - case PwdItemsCapacityOffset: value = e.ItemsCapacity; return true; - case PwdContainersCapacityOffset: value = e.ContainersCapacity; return true; - case PwdStackSizeOffset: value = e.StackSize; return true; - case PwdMaxStackSizeOffset: value = e.MaxStackSize; return true; - case PwdMaterialTypeOffset: value = e.MaterialType; return true; - default: return false; - } - } - private static void CapturePositionForId(uint id) { // Resolve natively here (we are on AC's main thread, so the CObjectMaint - // walk is safe) and stash the ptr so the off-thread pump can resolve it - // via GetWeenieObjectResolve without walking AC's table itself. + // walk is safe). The pointer map only feeds the snapshot diagnostics now; + // the pump reads the VALUES copied below (PWD fields, position, state). IntPtr weeniePtr = _getWeenieObjectNative != null ? _getWeenieObjectNative(id) : IntPtr.Zero; - if (weeniePtr != IntPtr.Zero) + if (weeniePtr == IntPtr.Zero) + return; + _weeniePtrBack[id] = weeniePtr; + // PWD fields for every weenie (pack items included: they have no position). + if (TryReadPwdFieldsLive(weeniePtr, out PwdEntry pwd)) + _pwdBack[id] = pwd; + // Reuses the pointer resolved above (the old path resolved it a second time + // through TryGetWeenieObjectPtr, which on this thread is the same native call). + if (ReadPhysicsFromWeenie(id, weeniePtr, out uint cell, out float x, out float y, out float z, + out float qw, out float qz, out uint state, out bool hasState)) + _positionBack[id] = new PosEntry { Cell = cell, X = x, Y = y, Z = z, Qw = qw, Qz = qz, State = state, HasState = hasState }; + } + + // One probe over the whole PublicWeenieDesc (PwdLayout.Size bytes), then one copy. + // MAIN THREAD ONLY (the PrefetchPositions walk, with a freshly resolved pointer). + private static unsafe bool TryReadPwdFieldsLive(IntPtr weeniePtr, out PwdEntry entry) + { + entry = default; + if (weeniePtr == IntPtr.Zero || _weeniePhysicsObjOffset < 0) + return false; + try { - _weeniePtrBack[id] = weeniePtr; - CapturePwdInts(id, weeniePtr); + IntPtr pwd = weeniePtr + _weeniePhysicsObjOffset + 4; + if (!IsReadableSpan(pwd, PwdLayout.Size)) + return false; + new ReadOnlySpan<byte>((void*)pwd, PwdLayout.Size).CopyTo(entry.Bytes); + return true; } - if (ReadObjectPositionLive(id, out uint cell, out float x, out float y, out float z)) - _positionCache[id] = new PosEntry { Cell = cell, X = x, Y = y, Z = z }; + catch + { + return false; + } + } + + // Off-thread PWD lookup (brief swap lock, no AC memory). + private static bool TryGetPwdSnapshot(uint objectId, out PwdEntry entry) + { + lock (_weeniePtrSwapLock) + return _pwdFront.TryGetValue(objectId, out entry); + } + + // The snapshot's CreateObject fields as properties (PwdLayout: a zero field answers nothing). + private static bool TryGetPwdSnapshotInt(uint objectId, uint stype, out int value) + { + value = 0; + return PwdLayout.IntOffset(stype) >= 0 && TryGetPwdSnapshot(objectId, out PwdEntry e) + && PwdLayout.TryGetInt(e.Bytes, stype, out value); + } + + /// <summary> + /// Off-thread read of one 4-byte PWD field by raw offset (the <see cref="TryReadPwdInt32"/> + /// contract) from the main-thread snapshot. False for objects the last walk didn't see. + /// </summary> + private static bool TryGetPwdSnapshotRawInt32(uint objectId, int pwdFieldOffset, out int value) + { + value = 0; + if (pwdFieldOffset < 0 || pwdFieldOffset + 4 > PwdLayout.Size) + return false; + if (!TryGetPwdSnapshot(objectId, out PwdEntry e)) + return false; + value = System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(((ReadOnlySpan<byte>)e.Bytes).Slice(pwdFieldOffset)); + return true; + } + + private static bool TryGetPwdSnapshotFloat(uint objectId, uint stype, out double value) + { + value = 0; + return stype is 54 or 167 or 280 && TryGetPwdSnapshot(objectId, out PwdEntry e) + && PwdLayout.TryGetFloat(e.Bytes, stype, out value); + } + + private static bool TryGetPwdSnapshotDataId(uint objectId, uint stype, out uint value) + { + value = 0; + return PwdLayout.DataIdOffset(stype) >= 0 && TryGetPwdSnapshot(objectId, out PwdEntry e) + && PwdLayout.TryGetDataId(e.Bytes, stype, out value); + } + + private static bool TryGetPwdSnapshotInstanceId(uint objectId, uint stype, out uint value) + { + value = 0; + return PwdLayout.InstanceIdOffset(stype) >= 0 && TryGetPwdSnapshot(objectId, out PwdEntry e) + && PwdLayout.TryGetInstanceId(e.Bytes, stype, out value); + } + + /// <summary> + /// Off-thread helper for UpdateObjectInventoryHooks: writes the ids whose PWD + /// container or wielder is <paramref name="containerId"/> from the main-thread + /// snapshot, under one lock, with no AC access. Returns the count written. + /// </summary> + internal static int CollectOwnedIdsFromSnapshot(uint containerId, Span<uint> dest) + { + int found = 0; + lock (_weeniePtrSwapLock) + { + foreach (KeyValuePair<uint, PwdEntry> kv in _pwdFront) + { + if (found >= dest.Length) break; + if (kv.Key == containerId) continue; + if (kv.Value.Container == containerId || kv.Value.Wielder == containerId) + dest[found++] = kv.Key; + } + } + return found; } /// <summary> @@ -3163,8 +3981,15 @@ internal static class ClientObjectHooks { if (MainThreadGuard.IsOnMainThread()) return _getWeenieObjectNative != null ? _getWeenieObjectNative(objectId) : IntPtr.Zero; - lock (_weeniePtrSwapLock) - return _weeniePtrFront.TryGetValue(objectId, out IntPtr p) ? p : IntPtr.Zero; + // Off the main thread: never hand out a raw AC object pointer (2026-09-30). + // It used to serve _weeniePtrFront, but a pointer up to ~100 ms old can be + // freed and reused before the caller dereferences it (the use-after-free + // class behind the old PWD / physics / enchantment reads). Every off-thread + // reader is now served from a value snapshot (identity, position, PWD + // fields, enchantments) before it gets here, so Zero only makes any + // remaining or future caller fail closed. _weeniePtrFront stays for the + // snapshot diagnostics. + return IntPtr.Zero; } // CPhysicsObj::m_state offset — confirmed from Ghidra set_state disasm: MOV [ESI+0xa8], EAX @@ -3178,6 +4003,23 @@ internal static class ClientObjectHooks { state = 0; + // Off AC's main thread (RynthAi DoorInteractionController's ETHEREAL check, + // meta expressions): m_state from the position snapshot (<= ~100 ms old). + // The live path below dereferenced a cached, possibly freed weenie and its + // CPhysicsObj from the pump. A miss is false, as before. + if (!MainThreadGuard.IsOnMainThread()) + { + lock (_positionCacheLock) + { + if (_positionCache.TryGetValue(objectId, out PosEntry p) && p.HasState) + { + state = p.State; + return true; + } + } + return false; + } + if (_weeniePhysicsObjOffset < 0) { ProbePhysObjOffset(); @@ -3218,6 +4060,22 @@ internal static class ClientObjectHooks { headingDegrees = 0; + // Off AC's main thread (meta getheading, CorpseOpenController): the heading + // from the position snapshot's quaternion (<= ~100 ms old). The live path + // below read a cached weenie's CPhysicsObj vtable with no probe at all. + if (!MainThreadGuard.IsOnMainThread()) + { + lock (_positionCacheLock) + { + if (_positionCache.TryGetValue(objectId, out PosEntry p)) + { + headingDegrees = HeadingFromQuaternion(p.Qw, p.Qz); + return true; + } + } + return false; + } + if (_weeniePhysicsObjOffset < 0) { ProbePhysObjOffset(); @@ -3234,6 +4092,10 @@ internal static class ClientObjectHooks if (physicsObj == IntPtr.Zero) return false; + // Same guard as TryGetObjectPhysicsState / ReadPhysicsFromWeenie. + if (!IsReadablePointer(physicsObj)) + return false; + IntPtr vtable = Marshal.ReadIntPtr(physicsObj); if (!SmartBoxLocator.IsPointerInModule(vtable)) return false; @@ -3242,9 +4104,7 @@ internal static class ClientObjectHooks float qw = ReadFloat(pos + PositionQwOffset); float qz = ReadFloat(pos + PositionQzOffset); - // Same formula as NavigationEngine / CorpseOpenController - double physYawDeg = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); - headingDegrees = (float)(((-physYawDeg) % 360.0 + 720.0) % 360.0); + headingDegrees = HeadingFromQuaternion(qw, qz); return true; } catch @@ -3266,6 +4126,11 @@ internal static class ClientObjectHooks /// </summary> private static void ProbePhysObjOffset() { + // Main thread only: it walks the SmartBox player and scans 0x200 bytes of + // the player weenie. PrefetchPositions (main thread) runs it anyway. + if (!MainThreadGuard.IsOnMainThread()) + return; + if (!SmartBoxLocator.TryGetPlayer(out IntPtr playerPhysObj, out uint playerId, out _)) return; diff --git a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs index 45fe3c0..dcd1c07 100644 --- a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; @@ -407,6 +408,13 @@ internal static class CombatActionHooks if (_cancelAttack == null) return false; + // 0x1B7 CM_Combat::Event_CancelAttack: same sender class as MeleeAttack, so the + // same gate. Queued in the action ring so it keeps FIFO order after an attack + // that is already queued (it used to run at once and could overtake it). The + // drain re-enters here on the main thread, where the gate passes. + if (!MainThreadGuard.IsOnMainThread()) + return AcMainThreadQueue.EnqueueCancelAttack(); + try { return _cancelAttack(); @@ -422,6 +430,14 @@ internal static class CombatActionHooks if (_queryHealth == null) return false; + // 0x1BF CM_Combat::Event_QueryHealth is a game-action send (AC blob alloc + + // send queue): main thread only. The plugin QueryHealthFn arrives on the pump, + // so off-thread calls go to the non-gesture QueryHealth queue and the drain + // re-enters here on the main thread. Callers ignore the result and read the + // async 0x01C0 reply, so "queued" is enough. + if (!MainThreadGuard.IsOnMainThread()) + return targetId != 0 && AcMainThreadQueue.EnqueueQueryHealth(targetId); + try { return _queryHealth(targetId); @@ -437,6 +453,17 @@ internal static class CombatActionHooks if (_requestId == null || objectId == 0) return false; + // The 0xC8 IdentifyObject send allocates on AC's heap and bumps the + // ClientUISystem busy count (non-atomic, via BusyCountHooks) - main thread + // only. Plugin RequestIdFn calls and the PluginManager.TickAll login + // self-identify arrive on the plugin pump, so off-thread callers go through + // the same non-gesture queue AutoIdService uses. DrainRequestIds re-enters + // here on the main thread, where this gate passes and the packet is sent. + // Fire-and-forget: the appraisal reply is async anyway, so "queued" keeps + // the bool's meaning ("requested"). + if (!MainThreadGuard.IsOnMainThread()) + return AcMainThreadQueue.EnqueueRequestId(objectId); + try { return _requestId(objectId); @@ -451,6 +478,8 @@ internal static class CombatActionHooks { if (spellId <= 0) return false; if (_castSpellClient == null) return false; + // Nameplate debuffs: pairs "You cast <spell> on <name>" with this target id. + ImGuiBackend.Hud.HudFeed.OnCast(targetId, spellId); // P2 cast marshalling — drain-BEFORE-tick variant (2026-06-03, attempt 2). // Off the main thread, enqueue the cast; GameTickHooks drains it on AC's @@ -615,8 +644,13 @@ internal static class CombatActionHooks _castSpellClientPtr = IntPtr.Zero; _getMagicSystemPtr = IntPtr.Zero; _freeHandsCastPtr = IntPtr.Zero; - _queryHealthResponseDetour = null; - _originalQueryHealthResponse = null; + // _queryHealthResponseDetour / _originalQueryHealthResponse are deliberately + // NOT cleared (2026-09-30): the MinHook detour on Handle_Combat__QueryHealthResponse + // stays enabled across a re-probe, so clearing them unrooted the detour + // delegate while AC could still jump to it, made a detour call in that + // window skip AC's original handler, and let InstallQueryHealthResponseHook + // re-run HookCreate on a live target (the remove-and-retry path, safe only + // after shutdown joined every caller). Kept, the install guard is a no-op. _identifyObjectDetour = null; _originalIdentifyObject = null; IsInitialized = false; @@ -757,10 +791,6 @@ internal static class CombatActionHooks if (success == 0 || objectId == 0) return; - const uint CreatureProfile = 0x0100; - if ((flags & CreatureProfile) == 0) - return; - int offset = 16; // Past the header int iSize = (int)size; @@ -773,6 +803,13 @@ internal static class CombatActionHooks return; // BoolStatsTable if ((flags & 0x0004) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 12)) return; // FloatStatsTable + + // The identify's properties (every table and profile) are cached from the live + // seam, SmartBoxHooks.ParseGameEvent -> PropertyWire (2026-09-30); this parser only + // runs from the disabled inner-dispatcher hook and reads the creature vitals. + const uint CreatureProfile = 0x0100; + if ((flags & CreatureProfile) == 0) + return; if ((flags & 0x0008) != 0 && !SkipStringHashTable(buffer, iSize, ref offset)) return; // StringStatsTable if ((flags & 0x1000) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8)) diff --git a/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs b/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs index d94925c..ecd7efc 100644 --- a/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs @@ -49,6 +49,13 @@ internal static class CombatModeHooks public static bool IsInstalled { get; private set; } public static string StatusMessage => _statusMessage; + /// <summary>The ClientCombatSystem singleton, or Zero. Read-only (diagnostics).</summary> + internal static IntPtr ReadCombatSystemPtr() + { + IntPtr slot = (IntPtr)_combatSystemPtrAddr; + return ClientObjectHooks.IsReadablePointer(slot) ? Marshal.ReadIntPtr(slot) : IntPtr.Zero; + } + // Deep-audit finding #4 (2026-06-18): this used to raw-dereference the // ClientCombatSystem singleton unconditionally, including off AC's main // thread — a teardown-window read (relog/portal, singleton being torn diff --git a/src/RynthCore.Engine/Compatibility/DecalBridgeHost.cs b/src/RynthCore.Engine/Compatibility/DecalBridgeHost.cs new file mode 100644 index 0000000..edef128 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/DecalBridgeHost.cs @@ -0,0 +1,570 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/DecalBridgeHost.cs +// +// "Bridge mode" (docs/DECAL_BRIDGE_PLAN.md): when Decal runs in the same acclient.exe +// AND the RynthCore Decal bridge (src/RynthCore.DecalBridge, a Decal network filter) +// is loaded, the engine leaves the AC functions Decal itself patches to Decal and +// gets what it needed from them through the bridge instead: +// +// AC function (Decal patches it too) bridge mode +// ClientSystem::AddTextToScroll 0x005649F0 chat lines <- Decal ChatBoxMessage +// OutgoingChat 0x005821A0 chat-bar lines <- Decal CommandLineText +// sending lines -> Decal InvokeChatParser +// gmSalvageUI::OpenSalvagePanel 0x004CBF70 salvage add/go -> Decal SalvagePanelAdd/Salvage +// +// Every other hook stays native: Decal doesn't patch those functions (measured patch +// map, 2026-09-29), and the native hooks run on AC's main thread with the live reads +// the bridge can't do. RYNTHCORE_DECAL_BRIDGE_STREAMS=all brings back the spike's +// routing (object create/delete/change and game events from Decal too) for A/B tests. +// +// Transport: BridgeProtocol.cs (byte rings in a named mapping). Events are drained on +// the plugin pump thread, before ProcessPendingActions, into the same queues the hooks +// feed. Commands are queued here and run by the bridge on AC's main thread. No thread, +// timer or callback the bridge could hold: Shutdown just unmaps the view. +// +// Cost without Decal: Initialize makes two GetModuleHandle calls and returns; nothing +// else here runs (every other entry point checks Active first). +// ============================================================================ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using RynthCore.DecalBridge; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class DecalBridgeHost +{ + // Chat-bar prefixes the bridge eats for us. NOT /vt, /ub, /mt: RynthAi answers those + // as compat commands, but with Decal loaded they belong to the real VTank/UB/MagTools. + private const string EatPrefixes = "/rc;/ra;/rv;/rn;/rnav;/lua"; + // Same id DecalBridgeRegistration writes (RynthCore.App). + private const string FilterKey = @"SOFTWARE\Decal\NetworkFilters\{5B3E0D57-2C41-4F8A-9D6E-8C1B70DECA11}"; + private const int HelloWaitMs = 20000; + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr GetModuleHandleW(string name); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern uint GetModuleFileNameW(IntPtr module, char* buffer, uint size); + + private static readonly object Sync = new(); + private static readonly object CommandSync = new(); + private static BridgeChannel? _ch; + private static DecalBridgeMode _mode; + private static bool _allStreams; + private static long _lastSummaryTick; + private static readonly long[] _kindCounts = new long[16]; + private static readonly Dictionary<uint, long> _opcodeCounts = new(); + private static readonly Dictionary<uint, long> _gameEventCounts = new(); + private static long _serverBytes; + private static int _logged; + private static bool _sawHello; + private static int _salvageLogged; + private static int _commandDropLogged; + + /// <summary>Bridge mode is on for this generation (decided at init; false without Decal).</summary> + public static bool Active { get; private set; } + + /// <summary> + /// Init steps bridge mode leaves to Decal: the two whose AC functions Decal patches. + /// With RYNTHCORE_DECAL_BRIDGE_STREAMS=all, also the spike's create/delete/game-event/raw sources. + /// </summary> + public static bool SkipsInitStep(string step) => Active && (step switch + { + "chat callback hooks" => true, // AddTextToScroll + OutgoingChat: Decal patches both entries + "salvage hooks" => true, // gmSalvageUI::OpenSalvagePanel: Decal patches it + "create-object hooks" or "delete-object hooks" or "smartbox hooks" or "raw packet hooks" => _allStreams, + _ => false, + }); + + /// <summary>Decides bridge mode. Top of InitWorker, before any hook step.</summary> + public static void Initialize() + { + Active = false; + InactiveReason = null; + string? decal = FindDecalModule(); + if (decal == null) + return; // no Decal: nothing below ever runs + + _mode = ModeFromEnvironment() ?? EngineSettings.DecalBridgeMode; + if (_mode == DecalBridgeMode.Off) + { + RynthLog.Info($"DecalBridge: Decal in the process ({decal}) and DecalBridge=Off - old coexistence mode (every hook installs)."); + NoteInactive("DecalBridge=Off (engine.json or RYNTHCORE_DECAL_BRIDGE=0)", + "RynthCore: the Decal bridge is switched off (DecalBridge Off in engine.json), so RynthCore's overlay is off in this Decal client."); + return; + } + + int pid = Environment.ProcessId; + bool mappingExists = BridgeChannel.Exists(pid); + bool registered = IsBridgeRegistered(out string registration); + if (_mode == DecalBridgeMode.Auto && !registered && !mappingExists) + { + RynthLog.Info($"DecalBridge: Decal in the process ({decal}) but the RynthCore Decal bridge isn't registered ({registration}) - old coexistence mode. " + + "Set the account to \"Decal + RynthCore\" in the launcher to use bridge mode."); + NoteInactive($"Decal won't load the bridge in this client (its entry, read as this client sees the registry: {registration})", NotLoadedChat); + return; + } + + _allStreams = string.Equals(Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_BRIDGE_STREAMS"), "all", StringComparison.OrdinalIgnoreCase); + try + { + var ch = BridgeChannel.OpenOrCreate(pid); + if (!ch.Valid) + { + RynthLog.Warn($"DecalBridge: the bridge mapping has another protocol version ({ch.ReadInt(BridgeLayout.OffVersion)}, engine {BridgeLayout.Version}) - " + + "the bridge and the engine are from different builds; old coexistence mode."); + ch.Dispose(); + NoteInactive("the Decal bridge and the engine are from different builds (protocol version)", + "RynthCore: the Decal bridge and the engine are from different builds - restart the client once the update has finished, or reinstall RynthCore."); + return; + } + uint want = BridgeLayout.Bit(BridgeRecordKind.ChatText) | BridgeLayout.Bit(BridgeRecordKind.ChatBarEnter) | + BridgeLayout.Bit(BridgeRecordKind.LoginComplete) | BridgeLayout.Bit(BridgeRecordKind.Logoff) | + BridgeLayout.Bit(BridgeRecordKind.CommandResult); + if (_allStreams) + want |= BridgeLayout.Bit(BridgeRecordKind.CreateObject) | BridgeLayout.Bit(BridgeRecordKind.ReleaseObject) | + BridgeLayout.Bit(BridgeRecordKind.ChangeObject) | BridgeLayout.Bit(BridgeRecordKind.ServerMessage); + ch.WriteInt(BridgeLayout.OffWantMask, unchecked((int)want)); + WritePrefixes(ch, EatPrefixes); + ch.WriteInt(BridgeLayout.OffEngineGeneration, EntryPoint.InitCount); + ch.WriteInt(BridgeLayout.OffEngineAttached, 1); + if (_allStreams) + { + // A new generation has no objects (a hot reload, or an engine injected late): + // ask the bridge to replay Decal's WorldFilter. Duplicates are harmless. + ch.WriteInt(BridgeLayout.OffReplayRequest, ch.ReadInt(BridgeLayout.OffReplayRequest) + 1); + } + lock (Sync) _ch = ch; + Active = true; + RynthLog.Info($"DecalBridge: BRIDGE MODE ({_mode}; Decal: {decal}; bridge {registration}; gen {EntryPoint.InitCount}). " + + $"Bridge state={ch.ReadInt(BridgeLayout.OffBridgeState)}, records so far={ch.ReadLong(BridgeLayout.OffRecords)}. " + + (_allStreams + ? "Streams=all: chat, salvage, create/delete, game-event and raw-packet hooks are left to Decal." + : "The chat and salvage hooks are left to Decal; every other hook installs as usual.")); + } + catch (Exception ex) + { + RynthLog.Warn($"DecalBridge: could not open the bridge mapping ({ex.GetType().Name}: {ex.Message}) - old coexistence mode."); + NoteInactive($"could not open the bridge mapping ({ex.GetType().Name})", NotLoadedChat); + } + } + + /// <summary> + /// After the hook steps: waits (bounded) for the bridge to say hello. True = bridge mode + /// stands. False = it fell back (Auto only) and the caller installs the skipped steps. + /// </summary> + public static bool WaitForBridge(Func<bool> aborted) + { + BridgeChannel? ch; + lock (Sync) ch = _ch; + if (!Active || ch == null) + return true; + long start = Environment.TickCount64; + while (ch.ReadInt(BridgeLayout.OffBridgeState) != 1) + { + if (aborted() || Environment.TickCount64 - start >= HelloWaitMs) + break; + Thread.Sleep(100); + } + long waited = Environment.TickCount64 - start; + if (ch.ReadInt(BridgeLayout.OffBridgeState) == 1) + { + RynthLog.Info($"DecalBridge: bridge is up (bridge pid {ch.ReadInt(BridgeLayout.OffBridgePid)}, waited {waited} ms)."); + return true; + } + if (_mode == DecalBridgeMode.On) + { + RynthLog.Warn($"DecalBridge: no hello from the bridge after {waited} ms and DecalBridge=On - staying in bridge mode; " + + "chat, chat commands and salvage stay dark until the bridge loads."); + NoteInactive($"registered, but Decal didn't load the bridge (no hello after {waited} ms; DecalBridge=On keeps bridge mode)", NotLoadedChat); + return true; + } + RynthLog.Warn($"DecalBridge: no hello from the bridge after {waited} ms - falling back to the old coexistence mode " + + "(the chat and salvage hooks install now). Check Logs\\DecalBridge.<pid>.log and the registration (RynthCore.Injector --decal-bridge status)."); + Detach(logSummary: false); + NoteInactive($"registered, but Decal didn't load the bridge (no hello after {waited} ms) - see Logs\\DecalBridge.<pid>.log", NotLoadedChat); + return false; + } + + /// <summary> + /// The IDirect3DDevice9* Decal renders with, as the bridge read it from Decal's public + /// IDecalCore.GetD3DDevice on its first frame. Zero when not in bridge mode or not yet + /// known. Never waits (read on AC's thread at login). + /// </summary> + public static IntPtr DecalDevice + { + get + { + BridgeChannel? ch; + lock (Sync) ch = _ch; + return ch == null ? IntPtr.Zero : new IntPtr(ch.ReadInt(BridgeLayout.OffD3DDevice)); + } + } + + /// <summary>Feeds everything the bridge wrote since the last call into the plugin queues. Pump thread.</summary> + public static int Drain() + { + BridgeChannel? ch; + lock (Sync) ch = _ch; + if (ch == null) + return 0; + int n = 0; + try + { + n = ch.Drain(Handle, 20000); + } + catch (Exception ex) + { + RynthLog.Warn($"DecalBridge: drain threw {ex.GetType().Name}: {ex.Message}"); + } + long now = Environment.TickCount64; + if (now - _lastSummaryTick >= 60000) + { + _lastSummaryTick = now; + LogSummary(ch); + } + return n; + } + + public static void Shutdown() => Detach(logSummary: true); + + private static void Detach(bool logSummary) + { + BridgeChannel? ch; + lock (Sync) { ch = _ch; _ch = null; } + Active = false; + if (ch == null) + return; + try + { + if (logSummary) LogSummary(ch); + ch.WriteInt(BridgeLayout.OffEngineAttached, 0); + ch.WriteInt(BridgeLayout.OffWantMask, 0); + } + catch { } + lock (CommandSync) ch.Dispose(); + if (logSummary) + RynthLog.Info("DecalBridge: detached (mapping view released; the bridge keeps the rings for the next generation)."); + } + + // ── "Decal is here but the bridge isn't" (2026-10-03) ──────────────────────── + // + // Without the bridge a Decal client takes the old coexistence path (no overlay; it has + // ended in crashes). The launcher's pre-launch check blocks that, but a client started + // another way (an older launcher, the injector, a registration Decal doesn't read) still + // gets here, so say it once: one clear log line, and one chat line after login. + + private const string NotLoadedChat = + "RynthCore: the Decal bridge isn't loaded - open the launcher's Decal check (Recovery Actions > Check Decal bridge). RynthCore's overlay is off in this client."; + private const string NoticeShownVar = "RYNTHCORE_DECAL_BRIDGE_NOTICE_SHOWN"; // once per client, across hot reloads + private static int _noticeScheduled; + private static string? _noticeText; + + /// <summary> + /// Why bridge mode is off although Decal is in this client (null: bridge mode, or no + /// Decal). Set at init by <see cref="Initialize"/> or the <see cref="WaitForBridge"/> fallback. + /// </summary> + public static string? InactiveReason { get; private set; } + + /// <summary> + /// The engine should stand down in this client (EntryPoint.InitWorker): Decal is here, the + /// bridge isn't active, the mode isn't an explicit DecalBridge=Off (engine.json or + /// RYNTHCORE_DECAL_BRIDGE=0 - the old coexistence path, for tests), and engine.json + /// DecalStandDown isn't false. Never true without Decal. + /// </summary> + public static bool ShouldStandDown => + InactiveReason != null && !Active && _mode != DecalBridgeMode.Off && EngineSettings.DecalStandDown; + + private static void NoteInactive(string reason, string chatLine) + { + InactiveReason = reason; + RynthLog.Warn($"DecalBridge: NOT ACTIVE in this Decal client - {reason}. No RynthCore overlay here: the old coexistence path runs " + + "(known to end in a crash). Fix: the launcher's Recovery Actions > Check Decal bridge (or RynthCore.Injector --decal-bridge check)."); + if (Environment.GetEnvironmentVariable(NoticeShownVar) == "1") + return; + if (Interlocked.Exchange(ref _noticeScheduled, 1) != 0) + return; + _noticeText = chatLine; + if (LoginLifecycleHooks.HasObservedLoginComplete) + PostNotice(); + else + LoginLifecycleHooks.LoginComplete += OnLoginForNotice; + } + + private static void OnLoginForNotice() + { + LoginLifecycleHooks.LoginComplete -= OnLoginForNotice; + PostNotice(); + } + + // Queued for AC's main thread (drained from Client::UseTime); never calls AC from here. + private static void PostNotice() + { + string? text = _noticeText; + if (text == null) return; + try + { + if (AcMainThreadQueue.EnqueueWriteToChat(text, 2)) + Environment.SetEnvironmentVariable(NoticeShownVar, "1"); + } + catch { } + } + + // ── commands (engine -> bridge -> Decal's public API on AC's main thread) ───── + + /// <summary>Sends a chat line as if typed, through Decal's InvokeChatParser. Any thread.</summary> + public static bool TryInvokeChatParser(string line) + { + if (!Active || string.IsNullOrEmpty(line)) + return false; + bool sent = SendCommand(BridgeRecordKind.CmdInvokeChatParser, 0, line); + // The bridge doesn't echo our own lines back as ChatBarEnter, so a /vt start|stop + // the engine or a plugin sends is noted here. + if (sent) + VTankWatch.ObserveSentLine(line); + return sent; + } + + /// <summary>Salvage panel add, left to Decal in bridge mode (SalvagePanelAdd). Any thread.</summary> + public static bool TrySalvagePanelAdd(uint itemId) + { + if (!Active || itemId == 0) + return false; + NoteSalvage(); + return SendCommand(BridgeRecordKind.CmdSalvagePanelAdd, itemId, null); + } + + /// <summary>Salvage button, left to Decal in bridge mode (SalvagePanelSalvage). Any thread.</summary> + public static bool TrySalvagePanelSalvage() + { + if (!Active) + return false; + NoteSalvage(); + return SendCommand(BridgeRecordKind.CmdSalvagePanelSalvage, 0, null); + } + + private static void NoteSalvage() + { + if (Interlocked.Exchange(ref _salvageLogged, 1) == 0) + RynthLog.Info("DecalBridge: salvage is left to Decal in bridge mode (our OpenSalvagePanel hook is not installed): " + + "adding items and pressing Salvage go through Decal's SalvagePanelAdd/SalvagePanelSalvage. The panel must be open (use an Ust)."); + } + + private static bool SendCommand(BridgeRecordKind kind, uint arg0, string? text) + { + lock (CommandSync) + { + BridgeChannel? ch; + lock (Sync) ch = _ch; + if (ch == null) + return false; + bool ok = ch.WriteCommand(kind, arg0, 0, text); + if (!ok && Interlocked.Exchange(ref _commandDropLogged, 1) == 0) + RynthLog.Warn($"DecalBridge: command ring full - {kind} dropped (is the bridge running? it drains once per frame)."); + return ok; + } + } + + // ── record handling ────────────────────────────────────────────────────── + private static void Handle(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int len) + { + int k = (int)kind; + if (k >= 0 && k < _kindCounts.Length) _kindCounts[k]++; + switch (kind) + { + case BridgeRecordKind.Hello: + _sawHello = true; + RynthLog.Info($"DecalBridge: hello from bridge v{arg0}: {Utf16(payload, len)}"); + break; + + case BridgeRecordKind.ChatText: + { + string text = Utf16(payload, len); + FirstFew($"chat type={arg0} target={arg1} '{Trim(text)}'"); + VTankWatch.ObserveChatText(text); // diagnostic log only + PluginManager.QueueChatWindowText(text, arg0); + break; + } + + case BridgeRecordKind.ChatBarEnter: + { + // Runs on the pump thread (the hook ran it on AC's thread, synchronously, + // so it could eat the line; the bridge now does the eating by prefix). + string text = Utf16(payload, len); + FirstFew($"chat-bar '{Trim(text)}' eatenByBridge={arg0 != 0}"); + // Every parser line, eaten or not: /vt start|stop went on to VTank, and is + // how RynthAi learns that VTank's macro runs (one bot per client). + VTankWatch.ObserveParserLine(text); + // Only the lines the bridge ate (our prefixes) are ours to run. Every other + // line already went on to Decal and AC: handing it to the plugins too would + // run it twice (RynthAi answers /vt, /ub and /mt as compat commands, and + // VTank, UB and MagTools already ran them). + if (arg0 == 0) + break; + if (RynthCoreChatCommands.TryHandle(text)) + break; + PluginManager.DispatchChatBarEnter(text); + break; + } + + case BridgeRecordKind.CommandResult: + RynthLog.Warn($"DecalBridge: command {(BridgeRecordKind)arg0} failed in the bridge: {Utf16(payload, len)}"); + break; + + // Streams=all only (the spike's routing). Same side effects as CreateObjectHooks / + // DeleteObjectHooks: the auto-appraisal queue is what gives RynthAi its creature + // classification (measured in world 2026-09-29). + case BridgeRecordKind.CreateObject: + PluginManager.QueueCreateObject(arg0); + AutoIdService.Enqueue(arg0); + break; + + case BridgeRecordKind.ReleaseObject: + PaletteCache.Remove(arg0); + PluginManager.QueueDeleteObject(arg0); + AutoIdService.Evict(arg0); + break; + + case BridgeRecordKind.ChangeObject: + PluginManager.QueueUpdateObject(arg0); + break; + + case BridgeRecordKind.ServerMessage: + { + _serverBytes += len; + _opcodeCounts[arg0] = _opcodeCounts.TryGetValue(arg0, out long c) ? c + 1 : 1; + // Decal's Message.RawData for a game event: [F7B0][objectId][sequence][eventType][payload]. + if (arg0 == 0xF7B0 && len >= 16 && *(uint*)payload == 0xF7B0) + { + uint ev = *(uint*)(payload + 12); + _gameEventCounts[ev] = _gameEventCounts.TryGetValue(ev, out long g) ? g + 1 : 1; + SmartBoxHooks.ProcessBridgeGameEvent(payload + 12, len - 12); + } + break; + } + + case BridgeRecordKind.LoginComplete: + RynthLog.Info($"DecalBridge: Decal LoginComplete (character 0x{arg0:X8}); engine login seen={LoginLifecycleHooks.HasObservedLoginComplete}."); + break; + + case BridgeRecordKind.Logoff: + RynthLog.Info($"DecalBridge: Decal Logoff type={arg0}."); + VTankWatch.OnLogoff(); + break; + } + } + + private static void LogSummary(BridgeChannel ch) + { + var sb = new StringBuilder(); + sb.Append($"DecalBridge: summary - hello={_sawHello} records={ch.ReadLong(BridgeLayout.OffRecords)} dropped={ch.ReadLong(BridgeLayout.OffDropped)} "); + sb.Append($"chat={_kindCounts[2]} chatBar={_kindCounts[3]} commands sent={ch.ReadLong(BridgeLayout.OffCmdWritePos) > 0} run={ch.ReadLong(BridgeLayout.OffCmdDone)} dropped={ch.ReadLong(BridgeLayout.OffCmdDropped)}"); + if (_allStreams) + { + sb.Append($" create={_kindCounts[4]} release={_kindCounts[5]} change={_kindCounts[6]} server={_kindCounts[7]} ({_serverBytes / 1024} KB); top opcodes:"); + foreach (var kv in Top(_opcodeCounts, 8)) sb.Append($" {kv.Key:X4}x{kv.Value}"); + sb.Append("; game events:"); + foreach (var kv in Top(_gameEventCounts, 12)) sb.Append($" {kv.Key:X4}x{kv.Value}"); + } + sb.Append($"; plugins live objects={PluginManager.LiveObjectCount}"); + RynthLog.Info(sb.ToString()); + } + + private static IEnumerable<KeyValuePair<uint, long>> Top(Dictionary<uint, long> d, int n) + { + var list = new List<KeyValuePair<uint, long>>(d); + list.Sort((a, b) => b.Value.CompareTo(a.Value)); + return list.Count > n ? list.GetRange(0, n) : list; + } + + private static void FirstFew(string line) + { + if (_logged >= 20) return; + _logged++; + RynthLog.Info("DecalBridge: " + line); + } + + private static string Trim(string s) => s.Length > 80 ? s.Substring(0, 80) + "..." : s.TrimEnd('\n', '\r'); + + private static string Utf16(byte* p, int len) => len >= 2 ? new string((char*)p, 0, len / 2) : string.Empty; + + private static void WritePrefixes(BridgeChannel ch, string prefixes) + { + char* dst = (char*)(ch.Header + BridgeLayout.OffPrefixes); + int n = Math.Min(prefixes.Length, BridgeLayout.PrefixChars - 1); + for (int i = 0; i < n; i++) dst[i] = prefixes[i]; + dst[n] = '\0'; + } + + // ── decisions ──────────────────────────────────────────────────────────── + + /// <summary>RYNTHCORE_DECAL_BRIDGE (test override): 1/on, 0/off, auto.</summary> + private static DecalBridgeMode? ModeFromEnvironment() + { + string? v = Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_BRIDGE"); + if (string.IsNullOrWhiteSpace(v)) return null; + v = v.Trim(); + if (v == "1" || v.Equals("on", StringComparison.OrdinalIgnoreCase)) return DecalBridgeMode.On; + if (v == "0" || v.Equals("off", StringComparison.OrdinalIgnoreCase)) return DecalBridgeMode.Off; + if (v.Equals("auto", StringComparison.OrdinalIgnoreCase)) return DecalBridgeMode.Auto; + return null; + } + + /// <summary> + /// Whether Decal will load the bridge in this client: its filter entry, read through + /// this (virtualized, 32-bit) process's own view of HKLM - the view Decal reads, which + /// includes the per-user copy the launcher writes. + /// </summary> + private static bool IsBridgeRegistered(out string detail) + { + try + { + using Microsoft.Win32.RegistryKey? k = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(FilterKey); + if (k == null) { detail = "not registered"; return false; } + bool enabled = k.GetValue("Enabled") is int e && e != 0; + string? dir = k.GetValue("Path") as string; + string? file = k.GetValue("Assembly") as string; + bool present = dir != null && file != null && File.Exists(Path.Combine(dir, file)); + detail = $"registered, {(enabled ? "enabled" : "DISABLED")}, {(present ? dir : $"DLL missing at {dir}")}"; + return enabled && present; + } + catch (Exception ex) + { + detail = $"registry read failed: {ex.GetType().Name}"; + return false; + } + } + + /// <summary> + /// Decal in this process? Two GetModuleHandle calls (no module walk). decal.dll, or + /// Decal's Inject.dll (the first thing a Decal launch loads) next to Decal.Adapter.dll. + /// Deliberately not DecalDetection: that caches its first answer, and asking it this + /// early (before decal.dll loads) would cache "no Decal" for the post-login check. + /// </summary> + private static string? FindDecalModule() + { + try + { + IntPtr m = GetModuleHandleW("decal.dll"); + if (m == IntPtr.Zero) + { + m = GetModuleHandleW("Inject.dll"); + if (m == IntPtr.Zero) + return null; + } + char* buf = stackalloc char[520]; + uint n = GetModuleFileNameW(m, buf, 520); + string path = new string(buf, 0, (int)n); + string? dir = Path.GetDirectoryName(path); + return dir != null && File.Exists(Path.Combine(dir, "Decal.Adapter.dll")) ? path : null; + } + catch + { + return null; + } + } +} diff --git a/src/RynthCore.Engine/Compatibility/DragDropHooks.cs b/src/RynthCore.Engine/Compatibility/DragDropHooks.cs new file mode 100644 index 0000000..6b221bc --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/DragDropHooks.cs @@ -0,0 +1,110 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/DragDropHooks.cs +// Hooks UIElementManager::StartDragandDrop so the engine knows which item AC +// is actually dragging. AC does not change the selected object when a drag +// starts, so the selection is the previously clicked item, not the dragged one. +// +// The dragged UI element is resolved to an object id with AC's own +// UIElement_ItemList::InqDropIconInfo (the same call AC makes when the drop +// lands), then handed to ItemDragBridge, which republishes it to ImGui. +// +// Threads: AC's main thread (AC's input / UI processing). +// ============================================================================ + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Engine.Hooking; +using RynthCore.Engine.ImGuiBackend; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class DragDropHooks +{ + // bool __thiscall UIElementManager::StartDragandDrop(UIElementManager*, UIElement* elem, int clickX, int clickY) + private const int StartDragandDropVa = 0x0045E120; + // void __cdecl UIElement_ItemList::InqDropIconInfo(const UIElement* icon, uint& itemId, uint& spellId, DropItemFlags& flags) + private const int InqDropIconInfoVa = 0x004E3380; + + // Both verified unique in the shipped client (sub esp,34h / mov edi,[esp+48h] / mov esi,ecx prologue; + // InqDropIconInfo zeroes its out-params up front). + private static readonly byte?[] StartDragandDropPattern = + [ + 0x83, 0xEC, 0x34, 0x53, 0x55, 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x48, 0x85, 0xFF, 0x8B, 0xF1, 0x0F, 0x84, + null, null, null, null, 0xA1, null, null, null, null, 0x85, 0xC0 + ]; + private static readonly byte?[] InqDropIconInfoPattern = + [ + 0x8B, 0x44, 0x24, 0x10, 0x83, 0xEC, 0x3C, 0x53, 0x55, 0x8B, 0x6C, 0x24, 0x50, 0x56, 0x8B, 0x74, 0x24, 0x4C, + 0x33, 0xDB, 0x3B, 0xF3, 0x57, 0x8B, 0x7C, 0x24, 0x54, 0x89, 0x1F + ]; + + private static IntPtr _originalStartDrag; + private static delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void> _inqDropIconInfo; + private static int _logCount; + + /// <summary>The drag-start hook is live, so ItemDragBridge gets the real dragged item.</summary> + public static bool IsInstalled { get; private set; } + public static string StatusMessage { get; private set; } = "Not probed yet."; + + public static void Initialize() + { + if (IsInstalled) return; + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + StatusMessage = "acclient.exe not available."; + return; + } + + var inq = HookResolver.Resolve(text, "DragDrop.InqDropIconInfo", InqDropIconInfoPattern, InqDropIconInfoVa); + var start = HookResolver.Resolve(text, "DragDrop.StartDragandDrop", StartDragandDropPattern, StartDragandDropVa); + // A guessed address for either would mean calling or patching the wrong code: pattern hits only. + if (inq.Source != HookResolver.ResolveSource.PatternScan || start.Source != HookResolver.ResolveSource.PatternScan) + { + StatusMessage = $"drag-start hook skipped (InqDropIconInfo {inq.Detail}, StartDragandDrop {start.Detail})."; + RynthLog.Compat($"Compat: {StatusMessage}"); + return; + } + + try + { + _inqDropIconInfo = (delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void>)inq.Address; + delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte> detour = &StartDragandDropDetour; + MinHook.Hook(start.Address, (IntPtr)detour, out _originalStartDrag); + IsInstalled = true; + StatusMessage = $"Hooked UIElementManager::StartDragandDrop @ 0x{start.Address.ToInt32():X8}."; + RynthLog.Info($"Compat: drag-start hook ready - StartDragandDrop=0x{start.Address.ToInt32():X8}, InqDropIconInfo=0x{inq.Address.ToInt32():X8}"); + } + catch (Exception ex) + { + StatusMessage = ex.Message; + RynthLog.Compat($"Compat: drag-start hook failed - {ex.Message}"); + } + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])] + private static byte StartDragandDropDetour(IntPtr manager, IntPtr element, int clickX, int clickY) + { + try + { + if (element != IntPtr.Zero && _inqDropIconInfo != null) + { + uint itemId = 0, spellId = 0, flags = 0; + _inqDropIconInfo(element, &itemId, &spellId, &flags); + // Spell-bar drags carry a spell id and no item. + if (itemId != 0) + { + if (_logCount < 20) { _logCount++; RynthLog.UI($"DragDropHooks: AC drag start item=0x{itemId:X8} flags=0x{flags:X}"); } + ItemDragBridge.OnNativeDragStart(itemId); + } + } + } + catch (Exception ex) + { + try { RynthLog.Compat($"Compat: drag-start detour error - {ex.GetType().Name}: {ex.Message}"); } catch { } + } + + var original = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte>)_originalStartDrag; + return original(manager, element, clickX, clickY); + } +} diff --git a/src/RynthCore.Engine/Compatibility/EnchantmentHooks.cs b/src/RynthCore.Engine/Compatibility/EnchantmentHooks.cs index 6f9c806..72f9688 100644 --- a/src/RynthCore.Engine/Compatibility/EnchantmentHooks.cs +++ b/src/RynthCore.Engine/Compatibility/EnchantmentHooks.cs @@ -1,5 +1,7 @@ using System; +using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Threading; namespace RynthCore.Engine.Compatibility; @@ -80,7 +82,14 @@ internal static class EnchantmentHooks IntPtr qualPtr = PlayerVitalsHooks.KnownPlayerQualitiesPtr; if (qualPtr == IntPtr.Zero) return -1; - int count = ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount); + // Off AC's main thread (plugin pump: RynthAi BuffManager, meta expressions, + // RynthLua): copy the main-thread snapshot. Walking the registry's linked + // lists here raced AC adding/removing/expiring buffs on its own thread (a + // freed node on a still-committed page passes every probe), which the + // double walk only detected, never prevented. + int count = MainThreadGuard.IsOnMainThread() + ? ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount) + : CopyPlayerSnapshot(qualPtr, spellIds, expiryTimes, maxCount); if (_enchReadLogCount < 8) { @@ -92,6 +101,262 @@ internal static class EnchantmentHooks } private static int _enchReadLogCount; + // ── Main-thread enchantment snapshots (2026-09-30 main-thread audit) ───────── + // Player: MainThreadSnapshots.Tick walks the player's registry every 250 ms (at + // once after an enchantment game event marks it dirty) into preallocated + // back buffers, then swaps them in under _playerEnchLock. Zero-alloc. + private const int MaxSnapshotEnchantments = 1024; + private const int PlayerEnchRefreshMs = 250; + private static readonly object _playerEnchLock = new(); + private static uint[] _pEnchIdsFront = new uint[MaxSnapshotEnchantments]; + private static double[] _pEnchExpFront = new double[MaxSnapshotEnchantments]; + private static uint[] _pEnchIdsBack = new uint[MaxSnapshotEnchantments]; + private static double[] _pEnchExpBack = new double[MaxSnapshotEnchantments]; + // The same entries' StatMod (type, key, value) and spell category, for the Skills + // panel's per-stat buff lists (CopyPlayerStatMods). Swapped with the arrays above. + private static uint[] _pEnchTypeFront = new uint[MaxSnapshotEnchantments]; + private static uint[] _pEnchKeyFront = new uint[MaxSnapshotEnchantments]; + private static float[] _pEnchValFront = new float[MaxSnapshotEnchantments]; + private static uint[] _pEnchCatFront = new uint[MaxSnapshotEnchantments]; + private static uint[] _pEnchTypeBack = new uint[MaxSnapshotEnchantments]; + private static uint[] _pEnchKeyBack = new uint[MaxSnapshotEnchantments]; + private static float[] _pEnchValBack = new float[MaxSnapshotEnchantments]; + private static uint[] _pEnchCatBack = new uint[MaxSnapshotEnchantments]; + private static int _pEnchCountFront = -1; // -1 = nothing valid published + private static IntPtr _pEnchOwnerFront; + private static long _nextPlayerEnchRefreshMs; + private static int _playerEnchDirty; + + /// <summary> + /// Main thread only: an enchantment game event was just applied by AC. Refresh + /// the player snapshot immediately (SmartBoxHooks calls this before it queues + /// the event to plugins, so their re-read sees the change). + /// </summary> + internal static void RefreshPlayerSnapshotNow() + { + Volatile.Write(ref _playerEnchDirty, 1); + PrefetchPlayerEnchantments(allowWalk: !LogoutLifecycleHooks.HasObservedLogout); + } + + // Off-thread copy of the player snapshot; -1 when it is missing, belongs to + // another qualities object, or a DB-cache teardown is running. + private static unsafe int CopyPlayerSnapshot(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount) + { + if (DbCacheTeardownHooks.TeardownActive) + return -1; + lock (_playerEnchLock) + { + int n = _pEnchCountFront; + if (n < 0 || _pEnchOwnerFront != qualPtr) + return -1; + if (n > maxCount) n = maxCount; + for (int i = 0; i < n; i++) + { + spellIds[i] = _pEnchIdsFront[i]; + expiryTimes[i] = _pEnchExpFront[i]; + } + return n; + } + } + + /// <summary> + /// The player snapshot with each entry's StatMod and spell category (the Skills + /// panel). Fills up to the arrays' length; returns the count, or -1 when nothing + /// valid is published (no player, another qualities object, a teardown). Any thread. + /// </summary> + internal static int CopyPlayerStatMods(uint[] spellIds, double[] expiryTimes, uint[] modTypes, uint[] modKeys, + float[] modVals, uint[] categories) + { + if (DbCacheTeardownHooks.TeardownActive) + return -1; + IntPtr qualPtr = PlayerVitalsHooks.KnownPlayerQualitiesPtr; + lock (_playerEnchLock) + { + int n = _pEnchCountFront; + if (n < 0 || qualPtr == IntPtr.Zero || _pEnchOwnerFront != qualPtr) + return -1; + n = Math.Min(n, Math.Min(Math.Min(spellIds.Length, expiryTimes.Length), Math.Min(modTypes.Length, + Math.Min(modKeys.Length, Math.Min(modVals.Length, categories.Length))))); + Array.Copy(_pEnchIdsFront, spellIds, n); + Array.Copy(_pEnchExpFront, expiryTimes, n); + Array.Copy(_pEnchTypeFront, modTypes, n); + Array.Copy(_pEnchKeyFront, modKeys, n); + Array.Copy(_pEnchValFront, modVals, n); + Array.Copy(_pEnchCatFront, categories, n); + return n; + } + } + + /// <summary> + /// Main thread only (MainThreadSnapshots.Tick). Refreshes the player snapshot + /// every 250 ms, or on the next tick after an enchantment event. With + /// <paramref name="allowWalk"/> false (no live player: logout window, teardown) + /// it publishes "nothing valid" instead of walking the cached qualities pointer. + /// </summary> + internal static unsafe void PrefetchPlayerEnchantments(bool allowWalk) + { + if (!MainThreadGuard.IsOnMainThread()) + return; + long now = Environment.TickCount64; + bool dirty = Volatile.Read(ref _playerEnchDirty) != 0; + if (!dirty && now < _nextPlayerEnchRefreshMs) + return; + Volatile.Write(ref _playerEnchDirty, 0); + _nextPlayerEnchRefreshMs = now + PlayerEnchRefreshMs; + + IntPtr qualPtr = PlayerVitalsHooks.KnownPlayerQualitiesPtr; + int count = -1; + if (qualPtr != IntPtr.Zero && allowWalk) + { + fixed (uint* ids = _pEnchIdsBack) + fixed (double* exp = _pEnchExpBack) + fixed (uint* types = _pEnchTypeBack) + fixed (uint* keys = _pEnchKeyBack) + fixed (float* vals = _pEnchValBack) + fixed (uint* cats = _pEnchCatBack) + count = ReadEnchantmentsFromQualities(qualPtr, ids, exp, MaxSnapshotEnchantments, types, keys, vals, cats); + } + + lock (_playerEnchLock) + { + (_pEnchIdsFront, _pEnchIdsBack) = (_pEnchIdsBack, _pEnchIdsFront); + (_pEnchExpFront, _pEnchExpBack) = (_pEnchExpBack, _pEnchExpFront); + (_pEnchTypeFront, _pEnchTypeBack) = (_pEnchTypeBack, _pEnchTypeFront); + (_pEnchKeyFront, _pEnchKeyBack) = (_pEnchKeyBack, _pEnchKeyFront); + (_pEnchValFront, _pEnchValBack) = (_pEnchValBack, _pEnchValFront); + (_pEnchCatFront, _pEnchCatBack) = (_pEnchCatBack, _pEnchCatFront); + _pEnchCountFront = count; + _pEnchOwnerFront = qualPtr; + } + } + + // Objects: request-driven. An off-thread ReadObjectEnchantments registers the + // id and gets -1 (every caller already treats -1 as "skip this tick") until the + // main thread has walked it; after that it gets the last main-thread result, + // refreshed every 500 ms while it keeps being asked for. Ids not asked for in + // 5 s are dropped. At most 64 watched ids. + private sealed class ObjEnchEntry + { + public uint[] Ids = Array.Empty<uint>(); + public double[] Exp = Array.Empty<double>(); + public int Count = -1; // -1 = not walked yet / unreadable + public long LastRequestMs; + } + private const int MaxWatchedObjects = 64; + private const int ObjectEnchRefreshMs = 500; + private const int ObjectEnchIdleDropMs = 5000; + private static readonly object _objEnchLock = new(); + private static readonly Dictionary<uint, ObjEnchEntry> _objEnch = new(MaxWatchedObjects); + private static readonly uint[] _objEnchWork = new uint[MaxWatchedObjects]; + private static readonly uint[] _objEnchScratchIds = new uint[MaxSnapshotEnchantments]; + private static readonly double[] _objEnchScratchExp = new double[MaxSnapshotEnchantments]; + private static long _nextObjectEnchRefreshMs; + private static IntPtr _objEnchSessionOwner; + + private static unsafe int CopyObjectSnapshot(uint objectId, uint* spellIds, double* expiryTimes, int maxCount) + { + if (DbCacheTeardownHooks.TeardownActive) + return -1; + long now = Environment.TickCount64; + lock (_objEnchLock) + { + if (!_objEnch.TryGetValue(objectId, out ObjEnchEntry? e)) + { + if (_objEnch.Count >= MaxWatchedObjects) + { + // Full: evict the id asked for least recently. + uint oldest = 0; long oldestMs = long.MaxValue; + foreach (KeyValuePair<uint, ObjEnchEntry> kv in _objEnch) + if (kv.Value.LastRequestMs < oldestMs) { oldestMs = kv.Value.LastRequestMs; oldest = kv.Key; } + _objEnch.Remove(oldest); + } + _objEnch[objectId] = new ObjEnchEntry { LastRequestMs = now }; + return -1; + } + e.LastRequestMs = now; + int n = e.Count; + if (n < 0) + return -1; + if (n > maxCount) n = maxCount; + for (int i = 0; i < n; i++) + { + spellIds[i] = e.Ids[i]; + expiryTimes[i] = e.Exp[i]; + } + return n; + } + } + + /// <summary> + /// Main thread only (MainThreadSnapshots.Tick). Walks the watched objects' + /// registries every 500 ms. Idle (one lock, empty dictionary) when nothing asks. + /// </summary> + internal static unsafe void PrefetchWatchedObjectEnchantments() + { + if (!MainThreadGuard.IsOnMainThread()) + return; + long now = Environment.TickCount64; + if (now < _nextObjectEnchRefreshMs) + return; + _nextObjectEnchRefreshMs = now + ObjectEnchRefreshMs; + + int n = 0; + lock (_objEnchLock) + { + // A new character (or none): nothing watched belongs to it. + IntPtr owner = PlayerVitalsHooks.KnownPlayerQualitiesPtr; + if (owner != _objEnchSessionOwner) + { + _objEnch.Clear(); + _objEnchSessionOwner = owner; + } + if (_objEnch.Count == 0) + return; + // Live ids fill the work buffer from the front, idle ones from the back + // (Count <= MaxWatchedObjects, so the two never meet); then drop the idle. + int drop = 0; + foreach (KeyValuePair<uint, ObjEnchEntry> kv in _objEnch) + { + if (now - kv.Value.LastRequestMs <= ObjectEnchIdleDropMs) + _objEnchWork[n++] = kv.Key; + else + _objEnchWork[_objEnchWork.Length - 1 - drop++] = kv.Key; + } + for (int i = 0; i < drop; i++) + _objEnch.Remove(_objEnchWork[_objEnchWork.Length - 1 - i]); + } + + if (DbCacheTeardownHooks.TeardownActive) + return; + + for (int i = 0; i < n; i++) + { + uint id = _objEnchWork[i]; + int count; + fixed (uint* ids = _objEnchScratchIds) + fixed (double* exp = _objEnchScratchExp) + count = ReadObjectEnchantmentsLive(id, ids, exp, MaxSnapshotEnchantments); + + lock (_objEnchLock) + { + if (!_objEnch.TryGetValue(id, out ObjEnchEntry? e)) + continue; // dropped meanwhile + if (count > 0 && e.Ids.Length < count) + { + // Grow once per object (rare: only when its buff count rises). + e.Ids = new uint[Math.Max(count, 16)]; + e.Exp = new double[e.Ids.Length]; + } + for (int k = 0; k < count; k++) + { + e.Ids[k] = _objEnchScratchIds[k]; + e.Exp[k] = _objEnchScratchExp[k]; + } + e.Count = count; + } + } + } + /// <summary> /// Reads active enchantments from any game object's CEnchantmentRegistry. /// Path: GetWeenieObject(objectId) → weenie+qualitiesOffset → CACQualities+0x70. @@ -104,6 +369,22 @@ internal static class EnchantmentHooks { if (maxCount <= 0) return 0; + // Off AC's main thread (host ReadObjectEnchantmentsFn: RynthAi's opt-in + // registry diagnostic, RynthLua): the request-driven main-thread snapshot. + // The live walk below started from a cached, possibly freed weenie pointer. + if (!MainThreadGuard.IsOnMainThread()) + return CopyObjectSnapshot(objectId, spellIds, expiryTimes, maxCount); + + return ReadObjectEnchantmentsLive(objectId, spellIds, expiryTimes, maxCount); + } + + // MAIN THREAD ONLY: resolve the weenie natively and walk its registry. + private static unsafe int ReadObjectEnchantmentsLive(uint objectId, uint* spellIds, double* expiryTimes, int maxCount) + { + if (maxCount <= 0) return 0; + if (!MainThreadGuard.IsOnMainThread()) + return -1; + if (!ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out IntPtr weeniePtr)) return -1; @@ -141,8 +422,13 @@ internal static class EnchantmentHooks /// <summary> /// Core: reads enchantments from a CACQualities pointer's enchantment registry. /// </summary> - private static unsafe int ReadEnchantmentsFromQualities(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount) + private static unsafe int ReadEnchantmentsFromQualities(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount, + uint* modTypes = null, uint* modKeys = null, float* modVals = null, uint* categories = null) { + // MAIN THREAD ONLY: see the note at the end of this method. + if (!MainThreadGuard.IsOnMainThread()) + return -1; + // While AC is inside a DB object-cache teardown (DbCacheTeardownHooks sets this // on AC's main thread for the duration of DestroyObjectCaches — which fires at // world-load, zone change, logout, AND final close), refuse to walk the @@ -180,43 +466,36 @@ internal static class EnchantmentHooks if (!SmartBoxLocator.IsPointerInModule(registryVtable)) return -1; - // Stability check (2026-09-02 "infinite buffing loop" bug): AC's own - // main thread mutates these linked lists as buffs land/expire, and in - // Decal-coexistence mode this reader runs off-thread on the 30Hz - // plugin pump (no EndScene-driven main-thread tick exists there) — a - // walk here can race that mutation. A torn/truncated walk silently - // under-reports the active buff set; BuffManager.RefreshFromLiveMemory - // treats a short read as "buffs expired" and clears its timers, - // making a just-completed rebuff pass look like nothing landed and - // instantly restarting it. Walk twice and only trust an exact match; - // on a mismatch, skip this tick (return -1, already a safe no-op for - // every caller) rather than report a truncated set. - int countA = WalkAllLists(registryPtr, spellIds, expiryTimes, maxCount); - - uint* idsB = stackalloc uint[maxCount]; - double* expB = stackalloc double[maxCount]; - int countB = WalkAllLists(registryPtr, idsB, expB, maxCount); - - if (countA != countB) - return -1; - for (int i = 0; i < countA; i++) - { - if (spellIds[i] != idsB[i] || expiryTimes[i] != expB[i]) - return -1; - } - return countA; + // Stability check history (2026-09-02 "infinite buffing loop" bug): when this + // walk ran off-thread on the plugin pump it could race AC mutating these + // lists as buffs landed/expired, so it walked twice and trusted only an + // exact match. Since 2026-09-30 it only runs on AC's main thread (the + // snapshot prefetches and main-thread callers), where nothing mutates the + // lists during the walk, so one walk is exact. + return WalkAllLists(registryPtr, spellIds, expiryTimes, maxCount, modTypes, modKeys, modVals, categories); } - private static unsafe int WalkAllLists(IntPtr registryPtr, uint* spellIds, double* expiryTimes, int maxCount) + private static unsafe int WalkAllLists(IntPtr registryPtr, uint* spellIds, double* expiryTimes, int maxCount, + uint* modTypes, uint* modKeys, float* modVals, uint* categories) { int count = 0; - count = WalkEnchantList(registryPtr + RegistryMultListOffset, spellIds, expiryTimes, maxCount, count); - count = WalkEnchantList(registryPtr + RegistryAddListOffset, spellIds, expiryTimes, maxCount, count); - count = WalkEnchantList(registryPtr + RegistryCooldownListOffset, spellIds, expiryTimes, maxCount, count); + count = WalkEnchantList(registryPtr + RegistryMultListOffset, spellIds, expiryTimes, maxCount, count, modTypes, modKeys, modVals, categories); + count = WalkEnchantList(registryPtr + RegistryAddListOffset, spellIds, expiryTimes, maxCount, count, modTypes, modKeys, modVals, categories); + count = WalkEnchantList(registryPtr + RegistryCooldownListOffset, spellIds, expiryTimes, maxCount, count, modTypes, modKeys, modVals, categories); return count; } - private static unsafe int WalkEnchantList(IntPtr listPtrAddress, uint* spellIds, double* expiryTimes, int maxCount, int count) + // Optional per-enchantment detail (the Skills panel's buffs): the spell category and + // the StatMod. With the pack(8) padding after _power_level and after _degrade_limit, + // _last_time_degraded sits at +56 and the StatMod at +64: vtable, type +68, key +72, + // val +76 (float); sizeof 80 = NodeNextOffset. All inside the node span checked below. + private const int EnchantmentCategoryOffset = 12; + private const int EnchantmentStatModTypeOffset = 68; + private const int EnchantmentStatModKeyOffset = 72; + private const int EnchantmentStatModValOffset = 76; + + private static unsafe int WalkEnchantList(IntPtr listPtrAddress, uint* spellIds, double* expiryTimes, int maxCount, int count, + uint* modTypes, uint* modKeys, float* modVals, uint* categories) { if (!SmartBoxLocator.IsMemoryReadable(listPtrAddress, 4)) return count; @@ -245,6 +524,13 @@ internal static class EnchantmentHooks { spellIds[count] = spellId; expiryTimes[count] = duration > 0 ? start + duration : double.MaxValue; + if (modTypes != null) + { + modTypes[count] = unchecked((uint)Marshal.ReadInt32(nodePtr + EnchantmentStatModTypeOffset)); + modKeys[count] = unchecked((uint)Marshal.ReadInt32(nodePtr + EnchantmentStatModKeyOffset)); + modVals[count] = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(nodePtr + EnchantmentStatModValOffset)); + categories[count] = unchecked((uint)Marshal.ReadInt32(nodePtr + EnchantmentCategoryOffset)); + } count++; } diff --git a/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs b/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs index 5562391..6befe71 100644 --- a/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs +++ b/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs @@ -87,6 +87,10 @@ internal static class EngineStatusMetrics w.WriteString("ts", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'")); w.WriteString("host", SafeMachineName()); w.WriteNumber("pid", Environment.ProcessId); + // The engine's build ("2026.9.26.3 (8ca322f)", "dev (...)") and plugin API version, so a + // plugin can say which engine it runs on (RynthAi /ra version). Additive fields. + w.WriteString("engineVersion", EntryPoint.BuildStamp); + w.WriteNumber("apiVersion", Plugins.PluginContractVersion.Current); w.WriteString("account", SessionStateRegistry.LastAccountName ?? string.Empty); w.WriteString("character", SessionStateRegistry.LastCharacterName ?? string.Empty); diff --git a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs index 7b4d7c1..d3a8734 100644 --- a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs +++ b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs @@ -30,6 +30,11 @@ namespace RynthCore.Engine.Compatibility; /// </summary> internal static class GameTickHooks { + /// <summary>Set once the Decal-coexistence plugin pump starts (no EndScene hook in that + /// client): the UseTime detour then also runs EngineFrameController.RunHeadlessPrefetch. + /// Never set in a client without Decal.</summary> + internal static volatile bool HeadlessPrefetch; + private const int UseTimeVa = 0x00411FA0; // Client::UseTime — thiscall, returns bool in AL // Client::UseTime returns a bool (AL): AC's main loop drives it as @@ -118,7 +123,12 @@ internal static class GameTickHooks // off-thread callers of IsPortaling in coexistence mode would see a // perpetually stale cache since nothing else ever reads it on-thread. // The getter itself does the guarded read + cache write; discard the value. - try { _ = TeleportStateHooks.IsPortaling; } + bool portaling = false; + try { portaling = TeleportStateHooks.IsPortaling; } + catch { } + // Death / portal space / teleport lines, for lining crashes up with what + // the character was doing (PlayerLifecycleLog). + try { PlayerLifecycleLog.SampleOnGameThread(portaling); } catch { } // Run AC's own game-logic + physics + animation pass. @@ -174,6 +184,17 @@ internal static class GameTickHooks // requirement, and they go through the separate cast slot.) try { AcMainThreadQueue.Drain(); } catch { } + // Main-thread snapshots the pump reads instead of AC memory (player id, + // cast gate, pose, ...). Post-tick, so they reflect this tick's physics. + try { MainThreadSnapshots.Tick(); } + catch { } + // Decal clients only (no EndScene hook): the prefetches EngineFrameController + // runs per frame. False for every other client - one flag check. + if (HeadlessPrefetch) + { + try { ImGuiBackend.EngineFrameController.RunHeadlessPrefetch(); } + catch { } + } // Busy watchdog: also post-tick now. Its decrement / cursor-refresh // touch m_cBusy, not the motion sequence, so order is immaterial here; // keeping all engine-issued mutations after AC's pass is the invariant. diff --git a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index 7d5f9b1..5a37c15 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.InteropServices; using System.Threading; namespace RynthCore.Engine.Compatibility; @@ -22,10 +23,40 @@ internal static class HeartbeatLogger private static int _exited; private static Thread? _thread; + [StructLayout(LayoutKind.Sequential)] + private struct MEMORYSTATUSEX + { + public uint dwLength, dwMemoryLoad; + public ulong ullTotalPhys, ullAvailPhys, ullTotalPageFile, ullAvailPageFile, + ullTotalVirtual, ullAvailVirtual, ullAvailExtendedVirtual; + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer); + + /// <summary> + /// Free and total user address space of this (32-bit) process, in MB, or + /// (-1, -1). Every reload leaks the old engine and plugin copies, each a + /// NativeAOT runtime with its own reservations, so this only goes down; + /// 2026-09-28 13:57 a client vanished while its 5th engine loaded plugins. + /// </summary> + public static (long FreeMb, long TotalMb) AddressSpaceMb() + { + var m = new MEMORYSTATUSEX { dwLength = (uint)Marshal.SizeOf<MEMORYSTATUSEX>() }; + if (!GlobalMemoryStatusEx(ref m)) return (-1, -1); + return ((long)(m.ullAvailVirtual >> 20), (long)(m.ullTotalVirtual >> 20)); + } + public static void Start() { if (Interlocked.CompareExchange(ref _started, 1, 0) != 0) return; + try + { + var (free, total) = AddressSpaceMb(); + RynthLog.Info($"HeartbeatLogger: address space at engine start: {free} MB free of {total} MB (initCount={EntryPoint.InitCount})."); + } + catch { } _thread = new Thread(Run) { @@ -62,6 +93,7 @@ internal static class HeartbeatLogger { long tick = 0; int lastFrames = 0; + int lastDrawn = 0; int lastPlugTicks = 0; long lastMs = Environment.TickCount64; long startMs = lastMs; @@ -83,15 +115,24 @@ internal static class HeartbeatLogger int fps = (int)((frames - lastFrames) * 1000L / dtMs); int pps = (int)((plug - lastPlugTicks) * 1000L / dtMs); lastFrames = frames; lastPlugTicks = plug; lastMs = nowMs; + // fps counts every EndScene, including the offscreen passes Decal's views, + // VVS and UB render each frame (2-3 per frame in bridge mode), so it read + // 40-130 while the game drew 19-42 (2026-10-03). draw= is frames on screen. + int drawn = D3D9.EndSceneHook.BackBufferFrames; + int draw = drawn >= lastDrawn ? (int)((drawn - lastDrawn) * 1000L / dtMs) : 0; + lastDrawn = drawn; long wsMb = 0; try { wsMb = Environment.WorkingSet / (1024 * 1024); } catch { } int login = 0; try { login = LoginLifecycleHooks.HasObservedLoginComplete ? 1 : 0; } catch { } - // qd = marshalled actions silently dropped (ring full). A - // climbing qd with healthy fps means the consumer phase is - // dead — exactly the silent blackhole class the review found. + // qdrop = marshalled actions dropped (ring full) since start: a running + // TOTAL, not a queue depth. Named qdrop, not qd, since 2026-10-01: launchers + // read "qd" as a depth and killed healthy 60 fps clients once the total + // passed 2000 (a loot loop had flooded the ring), and an old launcher + // doesn't parse qdrop. A total climbing with healthy fps = a producer + // flooding the ring; flat = fine. long dropped = 0; try { dropped = AcMainThreadQueue.DroppedCount; } catch { } // rec = busy reconciles (cast/item-action), fcl = force-clears. @@ -103,7 +144,38 @@ internal static class HeartbeatLogger int idle = -1; try { idle = LogoffOriginProbe.IdleSecondsForHeartbeat; } catch { } string idleField = idle >= 0 ? $" idle={idle}s" : ""; - RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} plug={pps}/s ws={wsMb}MB login={login} qd={dropped} rec={rec} fcl={fcl}{idleField}"); + // ui = ImGui cost on AC's render thread per frame, p95/max over the + // last second (docs/IMGUI_PARITY_PLAN.md §4.5). Only while ImGui is on. + string uiField = ""; + try + { + if (Plugins.EngineSettings.EnableImGuiBackend) + uiField = $" ui={ImGuiBackend.UiFrameStats.P95Ms:0.0}/{ImGuiBackend.UiFrameStats.MaxMs:0.0}ms"; + } + catch { } + // vafree = free address space (MB): reloads leak engine/plugin copies, + // so a client that dies mid-reload can be checked for running out. + string vaField = ""; + try { long free = AddressSpaceMb().FreeMb; if (free >= 0) vaField = $" vafree={free}MB"; } + catch { } + // req=<type>/<age>s = the client is waiting on an item request (it refuses + // every use/move/equip meanwhile); atk=1 = its attacking flag is set. Both + // omitted while open, so a long run of req= in a log is the item-action lock. + string gateField = ClientActionGates.HeartbeatField(); + RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}"); + + // Every 60 s: garbage collections and the time they paused the process. + // Under the CoreCLR host the engine and managed plugins share one GC, so a + // blocking gen2 stalls AC's main thread whenever it is in managed code. + if (tick % 60 == 0) + LogGcStats(); + + // Every 5 s: hide and destroy any panel window no live panel owns + // (the "double UI" orphans). + if (tick % 5 == 0) + { + try { RynthCore.Engine.UI.LayeredWindow.SweepOrphans(); } catch { } + } // Cache this client's live metrics so the GetEngineStatusJson host bridge can serve // them to a plugin (the RynthRemote status export). No file write, no networking. @@ -140,4 +212,22 @@ internal static class HeartbeatLogger Interlocked.Exchange(ref _exited, 1); } } + + private static int _gc0, _gc1, _gc2; + private static TimeSpan _gcPause; + + private static void LogGcStats() + { + try + { + int g0 = GC.CollectionCount(0), g1 = GC.CollectionCount(1), g2 = GC.CollectionCount(2); + TimeSpan pause = GC.GetTotalPauseDuration(); + GCMemoryInfo info = GC.GetGCMemoryInfo(GCKind.Any); + RynthLog.Info($"gc: last 60s g0={g0 - _gc0} g1={g1 - _gc1} g2={g2 - _gc2} paused={(pause - _gcPause).TotalMilliseconds:0}ms " + + $"(last GC gen{info.Generation}{(info.Concurrent ? " background" : "")} {info.PauseDurations[0].TotalMilliseconds:0}ms) " + + $"heap={GC.GetTotalMemory(false) / 1048576}MB concurrent={System.Runtime.GCSettings.LatencyMode != System.Runtime.GCLatencyMode.Batch}"); + _gc0 = g0; _gc1 = g1; _gc2 = g2; _gcPause = pause; + } + catch { } + } } diff --git a/src/RynthCore.Engine/Compatibility/IncomingChatHold.cs b/src/RynthCore.Engine/Compatibility/IncomingChatHold.cs new file mode 100644 index 0000000..effcfcc --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/IncomingChatHold.cs @@ -0,0 +1,196 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/IncomingChatHold.cs +// +// Lets a plugin's "eat" (the eatFlag of OnChatWindowText) keep a line out of +// AC's own chat window, not just out of RynthChat. +// +// AC prints chat on its main thread (ClientCommunicationSystem::AddTextToScroll, +// hooked in ChatCallbackHooks). Plugins hear chat on the plugin pump thread, and +// their handlers touch plugin state that only the pump may touch, so they can't +// be called inline from AC's thread. Instead the AddTextToScroll detour HOLDS +// the line (AC doesn't print it yet), the pump hands it to the plugins as +// before, the plugins' verdict is stored on the held line, and AC's main thread +// prints the lines nobody ate, in arrival order, from the next main-thread +// drain (Client::UseTime / EndScene) or the next incoming line, whichever is +// first. A line still waiting after HoldTimeoutMs prints anyway, so a stalled +// pump can delay chat by at most that long and never loses it. +// +// This file is the pure part (no AC, no native calls) so tools\ChatHoldTests can +// compile it in and test the decisions offline. The native part (reading the +// line, calling AC's original to print it) is in ChatCallbackHooks. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +/// <summary>One incoming chat line AC has not printed yet, waiting for the plugins' verdict.</summary> +internal sealed class HeldChatLine +{ + public const int Pending = 0; + public const int Show = 1; + public const int Eat = 2; + + public HeldChatLine(string raw, uint chatType, uint unknown, IntPtr thisPtr, long heldAtMs) + { + Raw = raw; + ChatType = chatType; + Unknown = unknown; + This = thisPtr; + HeldAtMs = heldAtMs; + } + + /// <summary>The text exactly as AC was given it (line breaks included); printed as is.</summary> + public string Raw { get; } + public uint ChatType { get; } + /// <summary>AddTextToScroll's third argument (the client's "offer to the plugin API" flag), passed back unchanged.</summary> + public uint Unknown { get; } + /// <summary>AddTextToScroll's this (the communication system).</summary> + public IntPtr This { get; } + public long HeldAtMs { get; } + + private int _verdict; + + /// <summary>Pending, Show or Eat. Written once by the pump, read by AC's main thread.</summary> + public int Verdict => Volatile.Read(ref _verdict); + + /// <summary>The plugins' verdict (pump thread). The first verdict wins; later ones are ignored.</summary> + public void Decide(bool eat) => Interlocked.CompareExchange(ref _verdict, eat ? Eat : Show, Pending); +} + +/// <summary>What the AddTextToScroll detour does with one line.</summary> +internal enum ChatHoldDecision +{ + /// <summary>Hold it: AC prints it after the plugins' verdict (unless a plugin eats it).</summary> + Hold, + /// <summary>Print it now, plugins hear it afterwards (the old behaviour). Lines already held stay held.</summary> + PassThrough, + /// <summary>Print every held line now (no verdict needed), then print this one: holding is off or unsafe.</summary> + FlushThenPassThrough, +} + +/// <summary>Everything the hold decision looks at, so it can be tested without AC.</summary> +internal readonly record struct ChatHoldInputs( + bool Enabled, // the /rc chathold switch, and the replay path resolved at install + bool Disarmed, // engine teardown has begun + bool OnMainThread, // the detour runs on AC's main thread (the held list is main-thread only) + bool Replaying, // we are inside our own print of a held line (AC re-entered AddTextToScroll) + bool HasText, // the line was read and is not empty + bool Truncated, // the line is longer than we read, so it can't be printed back exactly + bool HasStringInfo, // the caller passed a StringInfo pointer, which won't outlive the call + long NowMs, + long PumpBeatMs, // last time the plugin pump looked at the chat queue (0 = never) + long DrainBeatMs, // last main-thread drain (0 = never) + int HeldCount); + +/// <summary> +/// The held lines, oldest first. Only AC's main thread adds to or releases from it; the pump +/// only writes verdicts on the lines themselves, so no lock is needed here. +/// </summary> +internal sealed class HeldChatQueue +{ + /// <summary>A line still waiting this long prints anyway.</summary> + public const long HoldTimeoutMs = 400; + /// <summary>Hold only while the plugin pump has looked at the chat queue this recently.</summary> + public const long PumpStaleMs = 250; + /// <summary>Hold only while the main-thread drain (which prints held lines) ran this recently.</summary> + public const long DrainStaleMs = 500; + /// <summary>Never hold more than this many lines; past it, everything prints at once.</summary> + public const int MaxHeld = 256; + + private readonly Queue<HeldChatLine> _lines = new(); + + public int Count => _lines.Count; + + // Counters for /rc chathold status. Written on AC's main thread only. + public long HeldTotal { get; private set; } + public long ShownTotal { get; private set; } + public long EatenTotal { get; private set; } + public long TimedOutTotal { get; private set; } + public long PrintFailedTotal { get; private set; } + + public static ChatHoldDecision Decide(in ChatHoldInputs i) + { + // Inside our own print (AC calls AddTextToScroll again from inside it): print in place, + // and never touch the held list while a release is walking it. + if (i.Replaying) + return ChatHoldDecision.PassThrough; + + // The held list belongs to AC's main thread. A line from any other thread prints as before. + if (!i.OnMainThread) + return ChatHoldDecision.PassThrough; + + // Holding is off, the engine is going away, or nobody would answer or print the line in + // time: print what is held (keeps the order) and stop holding. + if (!i.Enabled || i.Disarmed) + return ChatHoldDecision.FlushThenPassThrough; + if (i.PumpBeatMs == 0 || i.NowMs - i.PumpBeatMs > PumpStaleMs) + return ChatHoldDecision.FlushThenPassThrough; + if (i.DrainBeatMs == 0 || i.NowMs - i.DrainBeatMs > DrainStaleMs) + return ChatHoldDecision.FlushThenPassThrough; + if (i.HeldCount >= MaxHeld) + return ChatHoldDecision.FlushThenPassThrough; + + // A line we couldn't print back exactly prints now. Lines still waiting for a verdict + // stay held (they print a frame later), so a line a plugin eats stays hidden. + if (!i.HasText || i.Truncated || i.HasStringInfo) + return ChatHoldDecision.PassThrough; + + return ChatHoldDecision.Hold; + } + + /// <summary> + /// The plugins' verdict on one line: eaten when any plugin set the eat flag and none of + /// them threw on it. A plugin that throws can't be trusted to have meant it, so the line shows. + /// </summary> + public static bool PluginsAteIt(int eatFlag, bool anyPluginThrew) => eatFlag != 0 && !anyPluginThrew; + + public void Add(HeldChatLine line) + { + _lines.Enqueue(line); + HeldTotal++; + } + + /// <summary> + /// Prints the lines that may print now, oldest first: shown lines, and lines that waited + /// longer than <see cref="HoldTimeoutMs"/> (all of them when <paramref name="flushAll"/>). + /// Eaten lines are dropped. Stops at the first line still waiting, so the order never + /// changes. A print that throws is counted and skipped. Returns how many lines printed. + /// </summary> + public int Release(long nowMs, bool flushAll, Action<HeldChatLine> print) + { + int printed = 0; + while (_lines.Count > 0) + { + HeldChatLine line = _lines.Peek(); + int verdict = line.Verdict; + if (verdict == HeldChatLine.Pending && !flushAll && nowMs - line.HeldAtMs < HoldTimeoutMs) + break; + + _lines.Dequeue(); + if (verdict == HeldChatLine.Eat) + { + EatenTotal++; + continue; + } + + if (verdict == HeldChatLine.Pending) + TimedOutTotal++; + else + ShownTotal++; + + try + { + print(line); + printed++; + } + catch + { + PrintFailedTotal++; + } + } + return printed; + } +} diff --git a/src/RynthCore.Engine/Compatibility/InventoryModel.cs b/src/RynthCore.Engine/Compatibility/InventoryModel.cs new file mode 100644 index 0000000..3930e57 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/InventoryModel.cs @@ -0,0 +1,1155 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/InventoryModel.cs +// The data and the item actions behind the ImGui Inventory panel +// (docs/IMGUI_INVENTORY.md). Engine only; no plugin involved. +// +// Threads: +// MainThreadTick AC's main thread only (MainThreadSnapshots.Tick, from +// Client::UseTime and EndScene). Every AC read and every item +// action happens here. Idle cost when the panel is closed and +// nothing is in flight: one volatile read. +// Subscribe / Unsubscribe / Hover / Request / Current / Tooltip / Pending / +// LastResult / Target +// any thread (the panel calls them from its Draw). They only +// swap references or small values; the published objects are +// immutable. +// +// One item action at a time: AC keeps one pending inventory request and refuses +// a second ("You can only move or use one item at a time"; ClientActionGates). +// Request() refuses while an action is waiting; nothing is ever queued behind it. +// +// The client's own gate (ClientActionGates, read on the main thread here): +// Before the send while AC's pending-request slot holds anyone's request (the +// bot looting, a retail drag), or (use/move/split, which AC +// gates itself) the attacking flag is set, the action is held: +// "Waiting for the game", sent the first tick the gate is open, +// dropped after GateWaitTicks. +// After the send move and split go through ItemHolder::AttemptToPlaceInContainer +// -> UIAttemptPutInContainer / SplitToContainer, which record the +// request in that slot. "Slot set for our object, then emptied" is +// the server's answer (ServerSaysMoveItem / SetStackSize / +// AttemptFailed all empty it), so the result is decided right +// then from the effect checks and any refusal since the send. A +// move/split that left the slot empty was not sent by AC (it +// refused locally and said why in chat). +// Use, wield, drop and give don't touch the slot (use is a UseEvent; the others +// are raw CM_Inventory sends), so they end as before: the effect is seen, the +// server refuses it (InventoryServerSaveFailed for the item, or a use's +// WeenieError / UseDone), the item is gone, or ActionTimeoutTicks pass. +// Without the gate (its patterns unresolved) every action behaves that way and +// nothing is held. +// +// Vanishing items: every read resolves the object again on the main thread and +// fails closed (ClientObjectHooks.TryReadItemFields), and the item and target are +// re-checked in the same tick, right before the send. An item that disappears +// (corpse decay, stack merge) is just absent from the next view; an action on it +// ends as "gone". +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text; +using System.Threading; +using RynthCore.Engine.ImGuiBackend.Hud; + +namespace RynthCore.Engine.Compatibility; + +/// <summary>Filter groups for the panel.</summary> +internal enum InventoryCategory : byte { Misc, Weapons, Armor, Jewelry, Usable, Components, Salvage } + +/// <summary>One item as the panel shows it. Immutable; shared between views while unchanged.</summary> +internal sealed class InventoryItem +{ + public uint Id, Container, Wielder, Location, ValidLocations, Type, Value, Icon, Wcid, SpellId, Useability; + /// <summary>The PublicWeenieDesc's object-description flags (ObjectDescriptionFlag).</summary> + public uint Bitfield; + public int Burden, Stack, MaxStack, ItemsCapacity, MaterialType; + public float Workmanship; + public string Name = string.Empty; + /// <summary>Lower-case name, for the search box.</summary> + public string SearchName = string.Empty; + /// <summary>The count drawn on the icon ("" for a single item).</summary> + public string StackText = string.Empty; + public InventoryCategory Category; + public bool IsPack => ItemsCapacity > 0; + + /// <summary>ObjectDescriptionFlag.RequiresPackSlot: the item takes one of the main pack's pack slots.</summary> + public const uint RequiresPackSlotFlag = 0x00800000u; + + /// <summary> + /// A foci-style item (Foci of Enchantment and the like, ACE's ContainerType.Foci): it + /// sits in one of the main pack's pack slots (the side column) next to the side packs, + /// and doesn't count against the main pack's 102 item slots. The server keeps it in the + /// main pack only (a side pack has no pack slots). + /// </summary> + public bool RequiresPackSlot => (Bitfield & RequiresPackSlotFlag) != 0 && !IsPack; + + public bool SameFields(in ClientObjectHooks.ItemPwdFields f) => + Container == f.Container && Wielder == f.Wielder && Location == f.Location && ValidLocations == f.ValidLocations + && Type == f.Type && Value == f.Value && Icon == f.Icon && Wcid == f.Wcid && SpellId == f.SpellId + && Useability == f.Useability && Burden == f.Burden && Stack == (int)f.StackSize && MaxStack == (int)f.MaxStackSize + && ItemsCapacity == f.ItemsCapacity && MaterialType == f.MaterialType && Workmanship == f.Workmanship + && Bitfield == f.Bitfield; +} + +/// <summary>The main pack or one side pack.</summary> +internal sealed class InventoryPack +{ + public uint Id; + public string Name = string.Empty; + public int Capacity; + public bool IsMain; + /// <summary>Everything in the pack, pack-slot items (foci) included, in captured order.</summary> + public InventoryItem[] Items = Array.Empty<InventoryItem>(); + /// <summary>Items that count against <see cref="Capacity"/>: pack-slot items don't (ACE's CountPackItems).</summary> + public int Used; + /// <summary>"12/24" (items that count / capacity).</summary> + public string FillText = string.Empty; +} + +/// <summary>Everything the panel draws, captured at once. Immutable.</summary> +internal sealed class InventoryView +{ + public static readonly InventoryView Empty = new(); + + public uint PlayerId; + public InventoryPack[] Packs = Array.Empty<InventoryPack>(); + /// <summary> + /// The main pack's pack-slot items (foci), in captured order: retail's side column shows + /// the side packs first, then these. They are also in Packs[0].Items. + /// </summary> + public InventoryItem[] SlotItems = Array.Empty<InventoryItem>(); + /// <summary>The main pack's pack slots (side packs + pack-slot items): 7, +1 with the extra-pack-slot augmentation.</summary> + public int ContainerSlots = 7; + public InventoryItem[] Worn = Array.Empty<InventoryItem>(); + public int ItemCount; + public int Burden, BurdenCapacity; + public long Pyreals; + public string BurdenText = string.Empty; + public string BurdenTip = string.Empty; + public string PyrealText = string.Empty; + /// <summary>ItemCount and Worn.Length as text (the pack column).</summary> + public string ItemCountText = "0", WornCountText = "0"; + /// <summary>OR of the worn items' locations (which slots are taken).</summary> + public uint WornMask; + /// <summary>The character's name ("" until known): the Classic view's "Inventory of Name".</summary> + public string PlayerName = string.Empty; + /// <summary>Aetheria sigil slots unlocked (PropertyInt 322: 1 blue, 2 yellow, 4 red).</summary> + public uint AetheriaMask; + + public bool Owns(uint containerId) + { + foreach (InventoryPack p in Packs) + if (p.Id == containerId) return true; + return false; + } + + public InventoryPack? PackOf(uint containerId) + { + foreach (InventoryPack p in Packs) + if (p.Id == containerId) return p; + return null; + } +} + +/// <summary>The hovered item's extra tooltip lines (appraisal, spells). Immutable.</summary> +internal sealed class InventoryTooltip +{ + public uint Id; + public string[] Lines = Array.Empty<string>(); + public bool Identifying; +} + +/// <summary>The creature or player selected in the game (the Give target). Immutable.</summary> +internal sealed class InventoryTarget +{ + public uint Id; + public string Name = string.Empty; + /// <summary>"Give: Name", "Give to Name", and the Give zone's tooltip, built once.</summary> + public string ZoneLabel = string.Empty, MenuLabel = string.Empty, ZoneTip = string.Empty; +} + +internal enum InventoryActionKind : byte { Use, Move, Split, Wield, Drop, Give } + +/// <summary>An item action the panel asks for.</summary> +internal sealed class InventoryRequest +{ + public InventoryActionKind Kind; + public uint ItemId; + /// <summary> + /// Move/Split: the pack (player id = main pack). Give: the creature. Wield: the + /// paperdoll slot it was dropped on (an equip mask; 0 = pick one). Else 0. + /// </summary> + public uint TargetId; + /// <summary>Split: how many to split off. Give: 0 = the whole stack.</summary> + public int Amount; + public string ItemName = string.Empty; + public string TargetName = string.Empty; +} + +/// <summary>The action in flight, or held until the game is free, for the status row. Immutable.</summary> +internal sealed class InventoryPending +{ + public InventoryActionKind Kind; + public uint ItemId; + public string Label = string.Empty; + public long StartedTicks; + /// <summary>Not sent yet: the client is busy with another item action (or an attack).</summary> + public bool WaitingForGame; + /// <summary>While <see cref="WaitingForGame"/>: what the client is busy with ("pick up of Pyreal").</summary> + public string BusyWith = string.Empty; +} + +/// <summary>How the last action ended. Immutable.</summary> +internal sealed class InventoryResult +{ + public string Text = string.Empty; + public bool Ok; + public long AtTicks; +} + +internal static class InventoryModel +{ + // ── Cadence ───────────────────────────────────────────────────────── + private static readonly long Freq = Stopwatch.Frequency; + private static readonly long CaptureIdleTicks = Freq; // 1 s while open + private static readonly long CaptureMinTicks = Freq * 15 / 100; // at most ~6/s after changes + private static readonly long WatchTicks = Freq / 10; // action watch: 10 Hz + private static readonly long ActionTimeoutTicks = Freq * 6; // no effect seen: stop waiting + private static readonly long GateWaitTicks = Freq * 10; // held for the game's gate at most this long + private static readonly long SlotTimeoutTicks = Freq * 15; // our request still in AC's slot: stop waiting + private static readonly long AnsweredGraceTicks = Freq / 2; // slot emptied, no effect, no refusal yet + private static readonly long NotSentGraceTicks = Freq * 3 / 2; // move/split that AC didn't record + private static readonly long TargetTicks = Freq / 4; // selection check: 4 Hz + private static readonly long TooltipRefreshTicks = Freq; // tooltip rebuild while hovered + private static readonly long IdentifyHoverTicks = Freq * 3 / 10; // hover this long before an ID + private static readonly long IdentifyGapTicks = Freq; // at most one ID a second + private static readonly long IdentifyRepeatTicks = Freq * 60; // never the same item within a minute + + private const uint PyrealWcid = 273; + private const uint StypeEncumbVal = 5, StypeCoinValue = 20, StypeItemCurMana = 107, StypeItemMaxMana = 108, + StypeAugCarry = 230, StypeAetheriaBitfield = 322, AttrStrength = 1, + StypeContainersCapacity = 7, StypeAugExtraPackSlot = 229; + private const int MaxIds = 1024; + + // ── Published (any thread reads) ──────────────────────────────────── + private static InventoryView _current = InventoryView.Empty; + private static long _version; + private static InventoryTooltip? _tooltip; + private static InventoryPending? _pending; + private static InventoryResult? _result; + private static InventoryTarget? _target; + + public static InventoryView Current => Volatile.Read(ref _current); + /// <summary>Changes whenever a new view is published.</summary> + public static long Version => Interlocked.Read(ref _version); + public static InventoryTooltip? Tooltip => Volatile.Read(ref _tooltip); + public static InventoryPending? Pending => Volatile.Read(ref _pending); + public static InventoryResult? LastResult => Volatile.Read(ref _result); + public static InventoryTarget? Target => Volatile.Read(ref _target); + public static bool DropAvailable => ClientHelperHooks.HasDropItem; + public static bool GiveAvailable => ClientHelperHooks.HasGiveObjectTo; + public static bool WieldAvailable => ClientHelperHooks.HasWieldItem; + + // ── Inputs (any thread) ───────────────────────────────────────────── + private static int _subscribers; + private static int _dirty = 1; + private static InventoryRequest? _requested; + private static uint _hoverId; + private static long _hoverSince; + + public static void Subscribe() + { + Interlocked.Increment(ref _subscribers); + MarkDirty(); + } + + public static void Unsubscribe() + { + if (Interlocked.Decrement(ref _subscribers) < 0) + Interlocked.Exchange(ref _subscribers, 0); + } + + /// <summary>Something in the inventory changed: capture again soon. Any thread; cheap.</summary> + public static void MarkDirty() => Volatile.Write(ref _dirty, 1); + + /// <summary>The item under the mouse (0 = none). Any thread.</summary> + public static void Hover(uint itemId) + { + if (Volatile.Read(ref _hoverId) == itemId) return; + Volatile.Write(ref _hoverSince, Stopwatch.GetTimestamp()); + Volatile.Write(ref _hoverId, itemId); + } + + /// <summary> + /// Asks for one item action. Refused (false, with the reason) while another one is + /// waiting for the server or already requested: nothing is queued. It is sent on AC's + /// main thread at its next tick, after the item and target are checked again. Any thread. + /// </summary> + public static bool Request(InventoryRequest request, out string why) + { + InventoryPending? busy = Pending; + if (busy != null) + { + why = (busy.WaitingForGame ? "Still waiting for the game: " : "Still waiting for the server: ") + busy.Label; + return false; + } + if (Interlocked.CompareExchange(ref _requested, request, null) != null) + { + why = "Another item action is about to be sent."; + return false; + } + why = string.Empty; + return true; + } + + // ── Main-thread state ─────────────────────────────────────────────── + private static readonly uint[] _ids = new uint[MaxIds]; + private static readonly uint[] _packIds = new uint[64]; + private static readonly Dictionary<uint, InventoryItem> _items = new(512); + private static readonly List<InventoryItem> _scratchItems = new(512); + private static readonly HashSet<uint> _seen = new(); + private static readonly HashSet<uint> _kept = new(); + private static readonly List<uint> _gone = new(); + private static long _lastCapture, _lastWatch, _lastTarget, _lastTooltip, _lastIdentify; + private static ulong _lastSignature; + private static uint _lastPlayer; + private static string _playerName = string.Empty; + private static readonly Dictionary<uint, long> _identified = new(); + private static readonly uint[] _spellBuf = new uint[64]; + + // The action in flight (main thread only). + private sealed class InFlight + { + public InventoryRequest Request = null!; + public long Started; + public int UseDoneSeq, ErrorSeq; + public uint Container, Wielder; + public int Stack; + public uint Player; + /// <summary>AC recorded this send in its pending-request slot (type, object).</summary> + public bool SlotTracked; + public uint SlotType, SlotObject; + /// <summary>A move/split: AC records it in the slot when it actually sends it.</summary> + public bool ExpectSlot; + /// <summary>When the slot stopped holding our request (the server answered); 0 = not yet.</summary> + public long AnsweredAt; + } + private static InFlight? _inFlight; + + // The action held until the client's gate opens (main thread only). + private static InventoryRequest? _held; + private static long _heldSince; + private static long _heldBusyKey; + + /// <summary> + /// AC's main thread (MainThreadSnapshots.Tick). Sends a requested action, watches the + /// one in flight, captures the inventory and builds the hovered item's tooltip, each + /// throttled. Returns at once while the panel is closed and nothing is in flight. + /// </summary> + public static void MainThreadTick() + { + bool open = Volatile.Read(ref _subscribers) > 0; + if (!open && _inFlight == null && _held == null && Volatile.Read(ref _requested) == null) + return; + if (!MainThreadGuard.IsOnMainThread()) + return; + + long now = Stopwatch.GetTimestamp(); + try + { + InventoryRequest? req = Interlocked.Exchange(ref _requested, null); + if (req != null) Begin(req, now); + // Every tick, unthrottled: the gate's open moments between the bot's + // requests can be short. + if (_held != null) TryReleaseHeld(now); + if (_inFlight != null && now - _lastWatch >= WatchTicks) + { + _lastWatch = now; + Watch(now); + } + if (!open) return; + + bool dirty = Volatile.Read(ref _dirty) != 0; + long since = now - _lastCapture; + if ((dirty && since >= CaptureMinTicks) || since >= CaptureIdleTicks + || (_inFlight != null && since >= CaptureMinTicks * 2)) + { + Volatile.Write(ref _dirty, 0); + _lastCapture = now; + Capture(); + } + if (now - _lastTarget >= TargetTicks) + { + _lastTarget = now; + SampleTarget(); + } + HoverTick(now); + } + catch (Exception ex) + { + // Never into AC: a managed failure here only costs this tick. + RynthLog.Compat($"InventoryModel: tick failed - {ex.GetType().Name}: {ex.Message}"); + } + } + + // ── Capture ───────────────────────────────────────────────────────── + + private static void Capture() + { + uint player = ClientHelperHooks.GetPlayerId(); + if (player == 0) + { + if (_lastPlayer != 0 || !ReferenceEquals(Current, InventoryView.Empty)) + { + _lastPlayer = 0; + _items.Clear(); + _lastSignature = 0; + Publish(InventoryView.Empty); + } + return; + } + if (player != _lastPlayer) + { + _items.Clear(); // another character: nothing carries over + _identified.Clear(); + _lastPlayer = player; + _lastSignature = 0; + _playerName = string.Empty; + } + + // Candidates: the PWD snapshot's children of the player and of each of its packs + // (<= ~100 ms old); every candidate's container and wielder are then read live, + // and an item is placed by its live container. + int n = ClientObjectHooks.CollectOwnedIdsFromSnapshot(player, _ids); + int packCount = 0; + for (int i = 0; i < n && packCount < _packIds.Length; i++) + { + if (ClientObjectHooks.TryReadItemFields(_ids[i], out ClientObjectHooks.ItemPwdFields pf) + && pf.Container == player && pf.Wielder == 0 && pf.ItemsCapacity > 0) + _packIds[packCount++] = _ids[i]; + } + Array.Sort(_packIds, 0, packCount); + for (int p = 0; p < packCount && n < MaxIds; p++) + n += ClientObjectHooks.CollectOwnedIdsFromSnapshot(_packIds[p], _ids.AsSpan(n)); + Array.Sort(_ids, 0, n); + + _seen.Clear(); + _kept.Clear(); + _scratchItems.Clear(); + ulong sig = 1469598103934665603UL ^ player; + for (int i = 0; i < n; i++) + { + uint id = _ids[i]; + if (!_seen.Add(id)) continue; + if (!ClientObjectHooks.TryReadItemFields(id, out ClientObjectHooks.ItemPwdFields f)) continue; + bool worn = f.Wielder == player; + bool inMain = f.Container == player && f.Wielder == 0; + bool inPack = !worn && !inMain && f.Wielder == 0 && Array.BinarySearch(_packIds, 0, packCount, f.Container) >= 0; + if (!worn && !inMain && !inPack) continue; // moved away since the snapshot + + if (!_items.TryGetValue(id, out InventoryItem? item) || !item.SameFields(f)) + { + item = MakeItem(id, f, item); + _items[id] = item; + } + _scratchItems.Add(item); + _kept.Add(id); + sig = Mix(sig, id, f.Container, f.Wielder, f.Location, f.StackSize, f.Value, (uint)f.Burden, f.Icon, + (uint)item.Name.Length ^ (f.Bitfield & InventoryItem.RequiresPackSlotFlag)); + } + + // Forget items no longer carried. + if (_items.Count > _kept.Count) + { + _gone.Clear(); + foreach (uint id in _items.Keys) + if (!_kept.Contains(id)) _gone.Add(id); + foreach (uint id in _gone) _items.Remove(id); + } + + // Player totals. + int burden = ClientObjectHooks.TryGetObjectIntProperty(player, StypeEncumbVal, out int b) ? b : -1; + long pyreals = ClientObjectHooks.TryGetObjectIntProperty(player, StypeCoinValue, out int coins) ? coins : -1; + int capacity = 0; + if (ClientObjectHooks.TryGetObjectAttribute(player, AttrStrength, 0, out uint strength) && strength > 0) + { + int augs = ClientObjectHooks.TryGetObjectIntProperty(player, StypeAugCarry, out int a) ? Math.Max(0, a) : 0; + int bonus = Math.Min(150, 30 * augs); + capacity = (int)(150 * strength + strength * bonus); + } + uint aetheria = ClientObjectHooks.TryGetObjectIntProperty(player, StypeAetheriaBitfield, out int ae) ? (uint)ae & 7u : 0u; + // The main pack's pack slots: the player's ContainersCapacity when the client has it, + // else ACE's rule (Player.cs: 7 + AugmentationExtraPackSlot). + int containerSlots = ClientObjectHooks.TryGetObjectIntProperty(player, StypeContainersCapacity, out int cc) && cc > 0 + ? cc + : 7 + (ClientObjectHooks.TryGetObjectIntProperty(player, StypeAugExtraPackSlot, out int xp) ? Math.Clamp(xp, 0, 1) : 0); + containerSlots = Math.Clamp(containerSlots, 1, 32); + // The name is read once per character (it doesn't change), then kept. + if (_playerName.Length == 0) + { + if (!ClientObjectHooks.TryGetSnapshotName(player, out string name) || name.Length == 0) + ClientObjectHooks.TryGetObjectName(player, out name); + _playerName = name ?? string.Empty; + } + sig = Mix(sig, (uint)burden, (uint)pyreals, (uint)capacity, (uint)(pyreals >> 32), (uint)_scratchItems.Count, + aetheria, (uint)_playerName.Length, (uint)containerSlots, 0); + + if (sig == _lastSignature && _current.PlayerId == player) return; + _lastSignature = sig; + Publish(BuildView(player, packCount, burden, pyreals, capacity, aetheria, containerSlots)); + } + + private static InventoryView BuildView(uint player, int packCount, int burden, long pyreals, int capacity, uint aetheria, + int containerSlots) + { + var view = new InventoryView + { + PlayerId = player, Burden = burden, BurdenCapacity = capacity, PlayerName = _playerName, AetheriaMask = aetheria, + ContainerSlots = containerSlots, + }; + + // Main pack first, then the side packs in id order. The main pack's pack-slot items + // (foci) are also listed on their own, for the Classic side column (after the packs). + var main = new List<InventoryItem>(); + var slotItems = new List<InventoryItem>(); + var packLists = new List<InventoryItem>[packCount]; + for (int p = 0; p < packCount; p++) packLists[p] = new List<InventoryItem>(); + var worn = new List<InventoryItem>(); + long pyrealStacks = 0; + int count = 0; + foreach (InventoryItem it in _scratchItems) + { + if (it.Wielder == player) { worn.Add(it); view.WornMask |= it.Location; continue; } + if (it.Wcid == PyrealWcid) pyrealStacks += Math.Max(1, it.Stack); + if (it.Container == player) + { + if (!it.IsPack) + { + main.Add(it); + if (it.RequiresPackSlot) slotItems.Add(it); + count++; + } + continue; + } + int idx = Array.BinarySearch(_packIds, 0, packCount, it.Container); + if (idx >= 0) { packLists[idx].Add(it); count++; } + } + + var packs = new InventoryPack[packCount + 1]; + packs[0] = new InventoryPack + { + Id = player, Name = "Main pack", Capacity = 102, IsMain = true, Items = Ordered(main), + }; + packs[0].Used = CountTowardCapacity(packs[0].Items); + packs[0].FillText = Fill(packs[0].Used, 102); + for (int p = 0; p < packCount; p++) + { + _items.TryGetValue(_packIds[p], out InventoryItem? packItem); + int cap = packItem?.ItemsCapacity ?? 24; + packs[p + 1] = new InventoryPack + { + Id = _packIds[p], + Name = packItem?.Name ?? "Pack", + Capacity = cap, + Items = Ordered(packLists[p]), + }; + packs[p + 1].Used = CountTowardCapacity(packs[p + 1].Items); + packs[p + 1].FillText = Fill(packs[p + 1].Used, cap); + } + view.Packs = packs; + view.SlotItems = slotItems.ToArray(); + view.Worn = worn.ToArray(); + view.ItemCount = count; + view.Pyreals = pyreals >= 0 ? pyreals : pyrealStacks; + + view.PyrealText = view.Pyreals.ToString("N0", CultureInfo.InvariantCulture); + view.ItemCountText = count.ToString(CultureInfo.InvariantCulture); + view.WornCountText = view.Worn.Length.ToString(CultureInfo.InvariantCulture); + if (burden < 0) { view.BurdenText = "?"; view.BurdenTip = "Burden not known yet."; } + else if (capacity > 0) + { + int pct = (int)Math.Round(100.0 * burden / capacity); + view.BurdenText = pct.ToString(CultureInfo.InvariantCulture) + "%"; + view.BurdenTip = $"Burden {burden:N0} of {capacity:N0} ({pct}%). Over 100% you move slower; 300% is the limit."; + } + else + { + view.BurdenText = burden.ToString("N0", CultureInfo.InvariantCulture); + view.BurdenTip = $"Burden {burden:N0}."; + } + return view; + } + + // Already in ascending id order (the capture sorts ids): that is "pack order". + private static InventoryItem[] Ordered(List<InventoryItem> list) => list.ToArray(); + + /// <summary>ACE's Container.CountPackItems: everything but packs and pack-slot items.</summary> + private static int CountTowardCapacity(InventoryItem[] items) + { + int n = 0; + foreach (InventoryItem it in items) + if (!it.RequiresPackSlot) n++; + return n; + } + + private static string Fill(int items, int capacity) => + items.ToString(CultureInfo.InvariantCulture) + "/" + capacity.ToString(CultureInfo.InvariantCulture); + + private static InventoryItem MakeItem(uint id, in ClientObjectHooks.ItemPwdFields f, InventoryItem? old) + { + string name = old?.Name ?? string.Empty; + if (name.Length == 0 || old!.Wcid != f.Wcid || old.Stack != (int)f.StackSize) + { + if (!ClientObjectHooks.TryGetSnapshotName(id, out name) || name.Length == 0) + if (!ClientObjectHooks.TryGetObjectName(id, out name) || name.Length == 0) + name = old?.Name is { Length: > 0 } prev ? prev : "(unknown item)"; + } + int stack = (int)f.StackSize; + return new InventoryItem + { + Id = id, Container = f.Container, Wielder = f.Wielder, Location = f.Location, ValidLocations = f.ValidLocations, + Type = f.Type, Value = f.Value, Icon = f.Icon, Wcid = f.Wcid, SpellId = f.SpellId, Useability = f.Useability, + Bitfield = f.Bitfield, + Burden = f.Burden, Stack = stack, MaxStack = (int)f.MaxStackSize, ItemsCapacity = f.ItemsCapacity, + MaterialType = f.MaterialType, Workmanship = f.Workmanship, + Name = name, + SearchName = name.ToLowerInvariant(), + StackText = stack > 1 ? ShortCount(stack) : string.Empty, + Category = CategoryOf(f.Type), + }; + } + + /// <summary>"25", "1.2k", "25k".</summary> + internal static string ShortCount(int n) + { + if (n < 1000) return n.ToString(CultureInfo.InvariantCulture); + if (n < 10000) return (n / 1000.0).ToString("0.#", CultureInfo.InvariantCulture) + "k"; + if (n < 1000000) return (n / 1000).ToString(CultureInfo.InvariantCulture) + "k"; + return (n / 1000000.0).ToString("0.#", CultureInfo.InvariantCulture) + "M"; + } + + internal static InventoryCategory CategoryOf(uint type) + { + if ((type & (0x1u | 0x100u | 0x8000u)) != 0) return InventoryCategory.Weapons; // melee, missile, caster + if ((type & (0x2u | 0x4u)) != 0) return InventoryCategory.Armor; // armor, clothing + if ((type & 0x8u) != 0) return InventoryCategory.Jewelry; + if ((type & 0x1000u) != 0) return InventoryCategory.Components; + if ((type & (0x20000000u | 0x40000000u)) != 0) return InventoryCategory.Salvage; // tinkering tool / material + if ((type & (0x20u | 0x800u | 0x80000u | 0x4000u | 0x2000u)) != 0) return InventoryCategory.Usable; // food, gem, mana stone, key, writable + return InventoryCategory.Misc; + } + + private static ulong Mix(ulong h, uint a, uint b, uint c, uint d, uint e, uint f, uint g, uint i, uint j) + { + const ulong P = 1099511628211UL; + h = (h ^ a) * P; h = (h ^ b) * P; h = (h ^ c) * P; h = (h ^ d) * P; h = (h ^ e) * P; + h = (h ^ f) * P; h = (h ^ g) * P; h = (h ^ i) * P; h = (h ^ j) * P; + return h; + } + + private static void Publish(InventoryView view) + { + Volatile.Write(ref _current, view); + Interlocked.Increment(ref _version); + } + + // ── Give target ───────────────────────────────────────────────────── + + private static void SampleTarget() + { + uint sel = ClientHelperHooks.GetSelectedItemId(); + uint player = ClientHelperHooks.GetPlayerId(); + InventoryTarget? cur = _target; + if (sel == 0 || sel == player || _items.ContainsKey(sel) + || !ClientObjectHooks.TryGetItemType(sel, out uint type) || (type & 0x10u) == 0) // creatures and players only + { + if (cur != null) Volatile.Write(ref _target, null); + return; + } + if (cur != null && cur.Id == sel) return; + if (!ClientObjectHooks.TryGetSnapshotName(sel, out string name) || name.Length == 0) + if (!ClientObjectHooks.TryGetObjectName(sel, out name) || name.Length == 0) name = "the selected creature"; + Volatile.Write(ref _target, new InventoryTarget + { + Id = sel, Name = name, ZoneLabel = "Give: " + name, MenuLabel = "Give to " + name, + ZoneTip = "Give to " + name + ": drag an item here, or click to give the selected item.", + }); + } + + // ── Actions ───────────────────────────────────────────────────────── + + /// <summary>What the status row says for an action ("Moving X to Y").</summary> + private static string ActionLabel(InventoryRequest r) => r.Kind switch + { + InventoryActionKind.Use => "Using " + r.ItemName, + InventoryActionKind.Move => $"Moving {r.ItemName} to {r.TargetName}", + InventoryActionKind.Split => $"Splitting {r.Amount} {r.ItemName} into {r.TargetName}", + InventoryActionKind.Wield => "Equipping " + r.ItemName, + InventoryActionKind.Drop => "Dropping " + r.ItemName, + InventoryActionKind.Give => $"Giving {r.ItemName} to {r.TargetName}", + _ => r.ItemName, + }; + + /// <summary> + /// Use, move and split go through ACCWeenieObject::IsPlayerReadyToMakeInventoryRequest, + /// which AC refuses while attacking as well as while a request is pending. Wield, drop + /// and give are raw CM_Inventory sends that AC doesn't gate. + /// </summary> + private static bool ClientGated(InventoryActionKind kind) => + kind is InventoryActionKind.Use or InventoryActionKind.Move or InventoryActionKind.Split; + + /// <summary>Move and split: AC records them in its pending-request slot when it sends them.</summary> + private static bool RecordsSlot(InventoryActionKind kind) => + kind is InventoryActionKind.Move or InventoryActionKind.Split; + + /// <summary> + /// Is the client's item-action gate closed for this kind? Key 0 = open (or the gate + /// isn't available: today's behaviour). Main thread (called from MainThreadTick only). + /// </summary> + private static long GateBusyKey(InventoryActionKind kind) + { + if (!ClientActionGates.IsRequestGateAvailable) + return 0; + if (ClientActionGates.TryReadPending(out uint type, out uint obj, out _) && type != 0) + return ((long)type << 32) | obj; + if (ClientGated(kind) && ClientActionGates.TryReadAttacking(out bool attacking) && attacking) + return -1; + return 0; + } + + private static string BusyText(long key) + { + if (key == -1) return "an attack"; + uint type = (uint)(key >> 32), obj = (uint)key; + string what = ClientActionGates.RequestTypeName(type); + if (obj != 0 && (ClientObjectHooks.TryGetSnapshotName(obj, out string name) && name.Length > 0 + || ClientObjectHooks.TryGetObjectName(obj, out name) && name.Length > 0)) + return what + " of " + name; + return "another item action (" + what + ")"; + } + + /// <summary>Send now if the client's gate is open, else hold the action until it is. Main thread.</summary> + private static void Begin(InventoryRequest r, long now) + { + if (_inFlight != null || _held != null) { Finish("Still waiting for the server.", false, now); return; } + long key = GateBusyKey(r.Kind); + if (key == 0) + { + Send(r, now); + return; + } + _held = r; + _heldSince = now; + _heldBusyKey = key; + PublishHeld(r, key); + } + + private static void PublishHeld(InventoryRequest r, long key) => + Volatile.Write(ref _pending, new InventoryPending + { + Kind = r.Kind, ItemId = r.ItemId, Label = ActionLabel(r), StartedTicks = _heldSince, + WaitingForGame = true, BusyWith = BusyText(key), + }); + + /// <summary>The held action: sent the first tick the gate is open, or dropped after GateWaitTicks. Main thread.</summary> + private static void TryReleaseHeld(long now) + { + InventoryRequest r = _held!; + long key = GateBusyKey(r.Kind); + if (key == 0) + { + _held = null; + Volatile.Write(ref _pending, null); + Send(r, now); + return; + } + if (now - _heldSince >= GateWaitTicks) + { + _held = null; + Volatile.Write(ref _pending, null); + string busy = BusyText(key); + Finish($"Not sent: the game stayed busy with {busy}. Try again.", false, now); + RynthLog.Compat($"InventoryModel: {ActionLabel(r)} not sent - the client's item gate stayed closed {GateWaitTicks / Freq}s ({busy})."); + return; + } + if (key != _heldBusyKey) + { + _heldBusyKey = key; + PublishHeld(r, key); + } + } + + private static void Send(InventoryRequest r, long now) + { + if (_inFlight != null) { Finish("Still waiting for the server.", false, now); return; } + uint player = ClientHelperHooks.GetPlayerId(); + if (player == 0) { Finish("Not in the world.", false, now); return; } + if (!ClientObjectHooks.TryReadItemFields(r.ItemId, out ClientObjectHooks.ItemPwdFields f)) + { + Finish($"{r.ItemName} is gone.", false, now); + MarkDirty(); + return; + } + bool worn = f.Wielder == player; + bool carried = worn || (f.Wielder == 0 && (f.Container == player || OwnedPack(f.Container, player))); + if (!carried) + { + Finish($"{r.ItemName} is no longer in your packs.", false, now); + MarkDirty(); + return; + } + + bool ok; + string label = ActionLabel(r); + switch (r.Kind) + { + case InventoryActionKind.Use: + ok = ClientHelperHooks.UseObject(r.ItemId); + break; + + case InventoryActionKind.Move: + { + if (r.TargetId != player && !OwnedPack(r.TargetId, player)) + { + Finish("That pack is gone.", false, now); + return; + } + if (f.Container == r.TargetId && !worn) { Finish($"{r.ItemName} is already there.", true, now); return; } + int amount = Math.Max(1, (int)f.StackSize); + // The helper refuses (false) a full pack of the player's own before sending. + ok = ClientHelperHooks.MoveItemInternal(r.ItemId, r.TargetId, 0, amount); + if (!ok) { Finish($"{r.TargetName} is full, or the move isn't possible.", false, now); return; } + break; + } + + case InventoryActionKind.Split: + { + int stack = (int)f.StackSize; + if (stack < 2 || r.Amount < 1 || r.Amount >= stack) + { + Finish($"Can't split {r.Amount} from a stack of {stack}.", false, now); + return; + } + if (r.TargetId != player && !OwnedPack(r.TargetId, player)) + { + Finish("That pack is gone.", false, now); + return; + } + // The new stack needs a free slot. SplitStackInternal goes through the same + // native slot-table walk as a move (FUN_00588f70) but, unlike MoveItemInternal, + // has no full-pack guard of its own, so apply it here before sending. + if (ClientHelperHooks.IsOwnedContainerFull(r.TargetId)) + { + Finish($"{r.TargetName} is full, or the split isn't possible.", false, now); + return; + } + ok = ClientHelperHooks.SplitStackInternal(r.ItemId, r.TargetId, 0, r.Amount); + break; + } + + case InventoryActionKind.Wield: + { + if (worn) { Finish($"{r.ItemName} is already worn.", true, now); return; } + uint mask = r.TargetId != 0 + ? SlotWieldMask(f.ValidLocations, r.TargetId) + : WieldMask(f.ValidLocations, Current.WornMask); + if (mask == 0) + { + Finish(r.TargetId != 0 && f.ValidLocations != 0 + ? $"{r.ItemName} doesn't go in that slot." + : $"{r.ItemName} can't be worn or wielded.", false, now); + return; + } + ok = ClientHelperHooks.WieldItem(r.ItemId, mask); + break; + } + + case InventoryActionKind.Drop: + if (worn) { Finish($"Take {r.ItemName} off before dropping it.", false, now); return; } + ok = ClientHelperHooks.DropItem(r.ItemId); + break; + + case InventoryActionKind.Give: + { + if (worn) { Finish($"Take {r.ItemName} off before giving it.", false, now); return; } + if (r.TargetId == 0 || r.TargetId == player || !ClientObjectHooks.TryGetItemType(r.TargetId, out _)) + { + Finish("The give target is gone.", false, now); + return; + } + ok = ClientHelperHooks.GiveObjectTo(r.ItemId, r.TargetId, Math.Max(0, r.Amount)); + break; + } + + default: + return; + } + + if (!ok) + { + Finish($"Couldn't send: {label}.", false, now); + return; + } + + SmartBoxHooks.TryGetLastWeenieError(out int errSeq, out _, out _, out _); + _inFlight = new InFlight + { + Request = r, Started = now, UseDoneSeq = SmartBoxHooks.GetUseDoneSeq(), ErrorSeq = errSeq, + Container = f.Container, Wielder = f.Wielder, Stack = (int)f.StackSize, Player = player, + }; + + // The send ran synchronously on this thread and the slot was empty just before it + // (Begin/TryReleaseHeld only send with the gate open), so a request in the slot now + // is ours: whatever object AC recorded (the item; an auto-merge may record another). + if (ClientActionGates.IsRequestGateAvailable && RecordsSlot(r.Kind)) + { + _inFlight.ExpectSlot = true; + if (ClientActionGates.TryReadPending(out uint slotType, out uint slotObj, out _) && slotType != 0) + { + _inFlight.SlotTracked = true; + _inFlight.SlotType = slotType; + _inFlight.SlotObject = slotObj; + } + } + Volatile.Write(ref _pending, new InventoryPending { Kind = r.Kind, ItemId = r.ItemId, Label = label, StartedTicks = now }); + _lastWatch = now; + MarkDirty(); + } + + /// <summary>Looks at the item again: done, refused, gone, or still waiting. Main thread.</summary> + private static void Watch(long now) + { + InFlight a = _inFlight!; + InventoryRequest r = a.Request; + bool exists = ClientObjectHooks.TryReadItemFields(r.ItemId, out ClientObjectHooks.ItemPwdFields f); + + // The server refused it: InventoryServerSaveFailed (0x00A0) for this item, or (a use) + // any refusal / an error UseDone. + SmartBoxHooks.TryGetLastWeenieError(out int errSeq, out uint err, out uint evt, out uint errObj); + bool refused = errSeq != a.ErrorSeq && (evt == 0x00A0 ? errObj == r.ItemId : r.Kind == InventoryActionKind.Use); + bool useDone = SmartBoxHooks.GetUseDoneSeq() != a.UseDoneSeq; + uint useErr = 0; + if (useDone) SmartBoxHooks.TryGetLastUseDone(out _, out useErr); + + // AC's slot no longer holds our request: the server has answered (or the client + // dropped it). Read on this (main) thread, like every other read here. + if (a.SlotTracked && a.AnsweredAt == 0) + { + ClientActionGates.TryReadPending(out uint slotType, out uint slotObj, out _); + if (slotType != a.SlotType || slotObj != a.SlotObject) + a.AnsweredAt = now; + } + + string? done = null; + bool ok = true; + if (refused) + { + done = $"Refused: {PendingLabel(r)} (error 0x{err:X})."; + ok = false; + } + else if (!exists) + { + done = r.Kind switch + { + InventoryActionKind.Drop => $"Dropped {r.ItemName}.", + InventoryActionKind.Give => $"Gave {r.ItemName} to {r.TargetName}.", + InventoryActionKind.Use => $"Used {r.ItemName}.", + _ => $"{r.ItemName} is gone (merged or removed).", + }; + } + else + { + switch (r.Kind) + { + case InventoryActionKind.Use: + if (useDone) + { + ok = useErr == 0; + done = ok ? $"Used {r.ItemName}." : $"Couldn't use {r.ItemName} (error 0x{useErr:X})."; + } + else if (f.Wielder != a.Wielder || f.Container != a.Container || (int)f.StackSize != a.Stack) + done = $"Used {r.ItemName}."; + break; + case InventoryActionKind.Move: + if (f.Container == r.TargetId && f.Wielder == 0) done = $"Moved {r.ItemName} to {r.TargetName}."; + else if (a.AnsweredAt != 0 && (int)f.StackSize < a.Stack) // part merged into a stack there + done = $"Moved {a.Stack - (int)f.StackSize} {r.ItemName} to {r.TargetName}."; + break; + case InventoryActionKind.Split: + if ((int)f.StackSize < a.Stack) done = $"Split {r.Amount} {r.ItemName} into {r.TargetName}."; + break; + case InventoryActionKind.Wield: + if (f.Wielder == a.Player) done = $"Equipped {r.ItemName}."; + break; + case InventoryActionKind.Drop: + if (f.Wielder != a.Player && f.Container != a.Player && !OwnedPack(f.Container, a.Player)) + done = $"Dropped {r.ItemName}."; + break; + case InventoryActionKind.Give: + if ((int)f.StackSize < a.Stack + || (f.Wielder != a.Player && f.Container != a.Player && !OwnedPack(f.Container, a.Player))) + done = $"Gave {r.ItemName} to {r.TargetName}."; + break; + } + } + + if (done == null && a.AnsweredAt != 0) + { + // The server answered and nothing we watch for happened: a refusal. Any + // WeenieError since the send is its reason (the last one kept). + if (errSeq != a.ErrorSeq) + { + done = $"Refused: {PendingLabel(r)} (error 0x{err:X})."; + ok = false; + } + else if (now - a.AnsweredAt >= AnsweredGraceTicks) + { + done = $"Refused: {PendingLabel(r)} (the server answered; nothing changed)."; + ok = false; + } + } + else if (done == null && a.ExpectSlot && !a.SlotTracked && now - a.Started >= NotSentGraceTicks) + { + // AC didn't record a move/split: it refused it before sending (it says why in chat). + done = $"The game didn't send: {PendingLabel(r)} (see chat for why)."; + ok = false; + } + else if (done == null && now - a.Started >= (a.SlotTracked ? SlotTimeoutTicks : ActionTimeoutTicks)) + { + // Slot-tracked: AC is still holding our request, so it will refuse other item + // actions until the server answers (or ClientActionGates frees a stuck one). + done = a.SlotTracked + ? $"No answer from the server yet for: {PendingLabel(r)}. The game is still waiting on it (/rc actionstate)." + : $"No answer seen for: {PendingLabel(r)}. You can act again."; + ok = false; + } + if (done == null) return; + _inFlight = null; + Volatile.Write(ref _pending, null); + Finish(done, ok, now); + MarkDirty(); + } + + private static string PendingLabel(InventoryRequest r) => Pending?.Label ?? r.ItemName; + + private static void Finish(string text, bool ok, long now) => + Volatile.Write(ref _result, new InventoryResult { Text = text, Ok = ok, AtTicks = now }); + + /// <summary>A side pack the player carries (its container is the player). Main thread.</summary> + private static bool OwnedPack(uint containerId, uint player) + { + if (containerId == 0 || containerId == player) return false; + return ClientObjectHooks.TryReadItemFields(containerId, out ClientObjectHooks.ItemPwdFields p) + && p.Container == player && p.Wielder == 0 && p.ItemsCapacity > 0; + } + + /// <summary> + /// The slot(s) to wield into. Armour and clothing: their whole coverage (the server + /// uses that anyway). Anything else (weapons, shields, rings, bracelets, trinkets, + /// sigils): the first slot it fits that nothing is in, else its first slot. + /// </summary> + internal static uint WieldMask(uint valid, uint occupied) + { + const uint ClothingAndArmor = 0x7FFF; + if (valid == 0) return 0; + if ((valid & ClothingAndArmor) != 0) return valid; + uint first = 0; + for (int bit = 0; bit < 32; bit++) + { + uint m = 1u << bit; + if ((valid & m) == 0) continue; + if (first == 0) first = m; + if ((occupied & m) == 0) return m; + } + return first; + } + + /// <summary> + /// The slot(s) to wield into when the item was dropped on one paperdoll slot + /// (<paramref name="slot"/>, an equip mask), or 0 when it can't go there. Armour, + /// clothing and cloaks keep their whole coverage (the server puts them there anyway); + /// anything else goes in that slot only (a ring on the chosen hand, a weapon in the + /// weapon slot). Ported from OpenAC's ItemEquipRules.ResolvePaperdollDropWieldMask + /// (Tom's OpenAC client, src/AcDream.Runtime/Gameplay/ItemEquipRules.cs). + /// </summary> + internal static uint SlotWieldMask(uint valid, uint slot) + { + const uint AutoWear = 0x7FFFu | 0x08000000u; // clothing and armour (head..lower legs), cloak + if ((valid & slot) == 0) return 0; + return (valid & AutoWear) != 0 ? valid : valid & slot; + } + + // ── Tooltip and identify ──────────────────────────────────────────── + + private static void HoverTick(long now) + { + uint id = Volatile.Read(ref _hoverId); + InventoryTooltip? tip = _tooltip; + if (id == 0) + { + if (tip != null) Volatile.Write(ref _tooltip, null); + return; + } + + bool appraised = AppraisalHooks.HasAppraisalData(id); + bool sentRecently = _identified.TryGetValue(id, out long sentAt) && now - sentAt < IdentifyRepeatTicks; + if (!appraised && !sentRecently && now - Volatile.Read(ref _hoverSince) >= IdentifyHoverTicks + && now - _lastIdentify >= IdentifyGapTicks && _items.ContainsKey(id)) + { + if (_identified.Count > 512) _identified.Clear(); + _identified[id] = now; + _lastIdentify = now; + sentRecently = true; + ClientActionHooks.RequestId(id); // main thread: the 0xC8 is sent now + tip = null; // rebuild below with "identifying" + } + + if (tip != null && tip.Id == id && now - _lastTooltip < TooltipRefreshTicks) return; + _lastTooltip = now; + Volatile.Write(ref _tooltip, BuildTooltip(id, appraised, !appraised && sentRecently)); + } + + private static InventoryTooltip BuildTooltip(uint id, bool appraised, bool identifying) + { + var lines = new List<string>(8); + _items.TryGetValue(id, out InventoryItem? item); + if (appraised) + { + bool hasCur = ClientObjectHooks.TryGetObjectIntProperty(id, StypeItemCurMana, out int cur); + bool hasMax = ClientObjectHooks.TryGetObjectIntProperty(id, StypeItemMaxMana, out int max); + if (hasMax && max > 0) + lines.Add($"Mana {(hasCur ? cur : 0):N0} / {max:N0}"); + int n = AppraisalHooks.GetObjectSpellIds(id, _spellBuf, _spellBuf.Length); + if (n > 0) + { + if (!PortalSpellTable.Ready) PortalSpellTable.EnsureLoadQueued(); + var sb = new StringBuilder("Spells: "); + int shown = Math.Min(n, _spellBuf.Length); + for (int i = 0; i < shown; i++) + { + if (i > 0) sb.Append(", "); + sb.Append(SpellName(_spellBuf[i])); + } + lines.Add(sb.ToString()); + } + } + if (item != null && item.SpellId != 0 && (lines.Count == 0 || !appraised)) + { + if (!PortalSpellTable.Ready) PortalSpellTable.EnsureLoadQueued(); + lines.Add("Casts " + SpellName(item.SpellId)); + } + if (identifying) lines.Add("Identifying..."); + else if (!appraised) lines.Add("Not identified yet."); + return new InventoryTooltip { Id = id, Lines = lines.ToArray(), Identifying = identifying }; + } + + private static string SpellName(uint spellId) + { + // Spell ids in an appraisal can carry the layer in the high word. + uint sid = spellId & 0xFFFF; + return PortalSpellTable.TryGetName(sid, out string name) ? name : "spell " + sid.ToString(CultureInfo.InvariantCulture); + } +} diff --git a/src/RynthCore.Engine/Compatibility/LogoBypassHooks.cs b/src/RynthCore.Engine/Compatibility/LogoBypassHooks.cs index 97940bc..dee5ce1 100644 --- a/src/RynthCore.Engine/Compatibility/LogoBypassHooks.cs +++ b/src/RynthCore.Engine/Compatibility/LogoBypassHooks.cs @@ -82,6 +82,23 @@ internal static class LogoBypassHooks return; } + // An engine hot reload (gen 2+) runs this step long before the reload marks the login + // complete, while the character stands in the world. The early burst then clicked + // (350, 100) up to 12 times, 400 ms apart, into the 3D view: AC reads two clicks that + // close together as a double-click and USES whatever is under that spot, so a door or a + // corpse there opened, closed, opened... "before the bot is on" (2026-10-04). The logo + // screens only exist when the client starts, so a reload never needs a dismiss click. + if (EntryPoint.InitCount >= 2) + { + RynthLog.Compat($"LogoBypass: engine hot reload (initCount={EntryPoint.InitCount}) - the client is past the logo screens, no dismiss clicks."); + return; + } + if (IsInGameWorld(out string where)) + { + RynthLog.Compat($"LogoBypass: the client is already in the game world ({where}) - no dismiss clicks."); + return; + } + _started = true; lock (StateLock) { @@ -90,12 +107,7 @@ internal static class LogoBypassHooks _recommendedAutoLoginTick = 0; } - var thread = new Thread(BypassThread) - { - Name = "RynthCore.LogoBypass", - IsBackground = true - }; - thread.Start(); + EngineThreads.Start("RynthCore.LogoBypass", BypassThread); RynthLog.Compat("LogoBypass: Started - waiting for post-connect or character-list signal before dismiss clicks."); } @@ -151,7 +163,8 @@ internal static class LogoBypassHooks if (LoginLifecycleHooks.HasObservedLoginComplete) return; SendDismissInput(hwnd); - Thread.Sleep(EarlyBurstIntervalMs); + if (!EngineThreads.Sleep(EarlyBurstIntervalMs)) + return; } } @@ -204,7 +217,8 @@ internal static class LogoBypassHooks if (found != IntPtr.Zero) return found; - Thread.Sleep(HwndPollMs); + if (!EngineThreads.Sleep(HwndPollMs)) + return IntPtr.Zero; elapsed += HwndPollMs; } @@ -221,13 +235,14 @@ internal static class LogoBypassHooks { if (TryTakeDueDismissClick()) SendDismissInput(hwnd); - else - Thread.Sleep(IdlePollMs); + else if (!EngineThreads.Sleep(IdlePollMs)) + break; } } finally { - string reason = LoginLifecycleHooks.HasObservedLoginComplete ? "login complete" : "timeout"; + string reason = LoginLifecycleHooks.HasObservedLoginComplete ? "login complete" + : EngineThreads.Stopping ? "engine shutdown" : "timeout"; RynthLog.Verbose($"LogoBypass: Stopped ({reason})."); } } @@ -249,8 +264,40 @@ internal static class LogoBypassHooks } } + private static int _withheldClicks; + + /// <summary> + /// True when the character is in the game world: AC's UI flow is in GamePlayUI, or the + /// login has completed. A click there lands in the 3D view, where two of them make a + /// double-click that uses the object under the cursor. + /// </summary> + private static bool IsInGameWorld(out string where) + { + where = ""; + if (LoginLifecycleHooks.HasObservedLoginComplete) { where = "login complete"; return true; } + try + { + if (CharacterManagementHooks.TryGetCurrentMode(out int mode) && mode == GamePlayUIMode) + { + where = $"UI mode 0x{mode:X8} (GamePlayUI)"; + return true; + } + } + catch { } + return false; + } + + private const int GamePlayUIMode = 0x10000008; // same value CharacterCaptureHooks checks + private static void SendDismissInput(IntPtr hwnd) { + // Last guard before every click: never into the game world (see Start). + if (IsInGameWorld(out string where)) + { + if (Interlocked.Increment(ref _withheldClicks) == 1) + RynthLog.Compat($"LogoBypass: dismiss click withheld - the client is in the game world ({where})."); + return; + } IntPtr lParam = MakeLParam(DismissClickX, DismissClickY); PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam); PostMessage(hwnd, WM_LBUTTONDOWN, (IntPtr)0x0001, lParam); diff --git a/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs b/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs index 610f10b..3d6dd86 100644 --- a/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs +++ b/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs @@ -230,6 +230,10 @@ internal static unsafe class LogoffOriginProbe private static void OnRequest(string fn, string args) { + // First, before any logging: AC frees UI objects during the logoff. + ChatHooks.OnLogoffRequested(); + RadarHooks.OnLogoffRequested(); + RetailVitalsHooks.OnLogoffRequested(); long now = Environment.TickCount64; IntPtr caller = LogoutLifecycleHooks.LogCaller(fn, "LogoffProbe"); string callerText = DescribeAcclientAddress(caller); diff --git a/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs b/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs new file mode 100644 index 0000000..c994566 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs @@ -0,0 +1,119 @@ +namespace RynthCore.Engine.Compatibility; + +/// <summary> +/// One main-thread refresh point for the small per-frame snapshots that the +/// plugin pump (and other engine threads) read instead of touching AC. +/// +/// AC's client is single-threaded. The plugin pump ("RynthCore.NormalPluginPump") +/// and the helper threads must not call AC functions or read AC memory that the +/// main thread mutates or frees; they read values sampled here instead. Called +/// from two places that both run on AC's main thread: +/// * GameTickHooks.UseTimeDetour, after AC's own tick and the queue drain. It +/// fires in every mode, before login too. +/// * EngineFrameController.OnEndScene, next to the other prefetches (EndScene +/// is only hooked after login). +/// Each step throttles itself, so running from both is cheap. Nothing here may +/// allocate per call or wait on another thread. +/// </summary> +internal static class MainThreadSnapshots +{ + // Host ProbeClientHooksFn from the plugin pump: re-probe on the main thread. + private static int _clientHookProbeRequested; + private static long _nextSmartBoxProbeMs; + + public static void RequestClientHookProbe() => + System.Threading.Volatile.Write(ref _clientHookProbeRequested, 1); + + public static void Tick() + { + // Both call sites are AC's main thread by construction (same reasoning as + // AcMainThreadQueue.Drain, which latches here too). + MainThreadGuard.RecordIfFirst(); + if (!MainThreadGuard.IsOnMainThread()) + return; + // Teardown: the detours stay live until MH_DisableHook(ALL) and Shutdown is + // resetting hook state; nobody reads these snapshots any more (the pump is + // stopped first), so stop touching AC here, like AcMainThreadQueue.Disarm. + if (EngineLifecycle.IsShuttingDown) + return; + + if (System.Threading.Volatile.Read(ref _clientHookProbeRequested) != 0 + && System.Threading.Interlocked.Exchange(ref _clientHookProbeRequested, 0) != 0) + { + try + { + ClientActionHooks.Probe(); + RynthLog.Compat("ProbeClientHooks: re-probed on AC's main thread (plugin request)."); + } + catch { } + } + + // Player id cache (off-thread GetPlayerId callers). Two loads, unthrottled. + try { ClientHelperHooks.GetPlayerId(); } catch { } + + // The two SmartBox-based samples below must not trigger SmartBoxLocator's + // lazy re-probe (a .text pattern scan) on every frame if the bootstrap probe + // failed: retry it here at most every 10 s instead. + bool smartBoxReady = SmartBoxLocator.IsInitialized; + if (!smartBoxReady) + { + long now = System.Environment.TickCount64; + if (now >= _nextSmartBoxProbeMs) + { + _nextSmartBoxProbeMs = now + 10_000; + try { smartBoxReady = SmartBoxLocator.Probe(); } catch { } + } + } + + // Cast gate: CMotionInterp's pending-motion head, read here instead of on + // the pump (the SmartBox player -> MovementManager -> CMotionInterp chain + // dies with the player's physics object at logout / char switch). + if (smartBoxReady) + { + try { CastGate.Sample(); } catch { } + } + + // Player pose + heading (seqlock copy): nav, radar, Jumper, Nav3D, GetCurCoords. + // Publishes "no pose" while SmartBox is not located. + try { PlayerPhysicsHooks.PublishPoseSnapshot(smartBoxReady); } catch { } + + // The qualities walks below (base vitals, enchantment registries) need a + // live player object. Between gmGamePlayUI::RecvNotice_Logoff and the pump's + // logout dispatch (which zeroes KnownPlayerQualitiesPtr) the cached pointer + // can outlive the object, and during a DB-cache teardown AC is freeing them. + bool playerLive = !LogoutLifecycleHooks.HasObservedLogout + && !DbCacheTeardownHooks.TeardownActive + && ClientHelperHooks.GetPlayerId() != 0; + + // Base (unbuffed) max vitals for host GetPlayerBaseVitalsFn (~1 Hz). + if (playerLive) + { + try { PlayerVitalsHooks.PrefetchBaseVitals(); } catch { } + } + + // PlayerInReadyPosition for host IsPlayerReadyFn (~5 Hz). + try { ClientCombatHooks.SampleReady(); } catch { } + + // Account name cache (host GetAccountNameFn): only while still cold. + try { AccountHooks.WarmFromMainThread(); } catch { } + + // Enchantment registries: the player's (250 ms, or next tick after an + // enchantment event) and any objects plugins asked about (500 ms). + try { EnchantmentHooks.PrefetchPlayerEnchantments(playerLive); } catch { } + if (playerLive) + { + try { EnchantmentHooks.PrefetchWatchedObjectEnchantments(); } catch { } + // Inventory panel: sends the one requested item action, watches it, and + // captures the packs (throttled; returns at once while the panel is closed + // and nothing is in flight). Only while the player object is live. + try { InventoryModel.MainThreadTick(); } catch { } + // Skills panel: ranks, XP spent and buffs (500 ms, only while the panel is open). + // After the enchantment snapshot so its buffs are this tick's. + try { PlayerProgressHooks.Prefetch(); } catch { } + } + + // Aelrynth skill mastery: the /mastery-data request after login, on panel open + // and after a raise (only on Aelrynth; a few compares when nothing is wanted). + try { MasteryFeed.MainThreadTick(playerLive); } catch { } + } +} diff --git a/src/RynthCore.Engine/Compatibility/MasteryFeed.cs b/src/RynthCore.Engine/Compatibility/MasteryFeed.cs new file mode 100644 index 0000000..bff8111 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/MasteryFeed.cs @@ -0,0 +1,340 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/MasteryFeed.cs +// +// Aelrynth skill mastery for the Skills panel. The numbers exist only on the +// server: the SkillMastery mod answers "/mastery-data" with ONE chat line, +// "~ael1 " + JSON (AelrynthWire.cs parses it). This feed asks for that line, +// reads it, and hides it from chat. +// +// Only ever on Aelrynth (ServerInfo.IsAelrynth): anywhere else nothing is sent, +// because another server would answer "Unknown command". If an Aelrynth server +// answers that anyway (the mod switched off), the feed stops asking until the +// next login. +// +// When it asks (each rate limited: one request in flight, 4 s apart at least): +// - once, 4 s after login (waits up to a minute for detection to settle); +// - when the Skills panel opens and the last reply is over 30 s old; +// - 2 s after a mastery raise this feed sent; +// - "/rc mastery". +// +// Hiding: the incoming-chat hook (ChatCallbackHooks.IncomingChatAddTextDetour) +// offers every line to OnIncomingLine first. A data line that answers OUR +// request (sent in the last 15 s), and ACE's "Unknown command: mastery-data" +// for it, are eaten: not drawn, not passed on. A line the player asked for by +// typing /mastery-data is read but left in chat. +// +// Threads: MainThreadTick and OnIncomingLine run on AC's main thread (the only +// place a command is sent). The panel's calls (PanelOpened, RequestRefresh, +// QueueRaise, Snapshot) are any-thread: they set fields under a small lock and +// the main thread does the sending. +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +/// <summary>One published reply with what the panel needs beside it. Immutable.</summary> +internal sealed class MasterySnapshot +{ + public required MasteryData Data { get; init; } + public required int Version { get; init; } + public required long ReceivedMs { get; init; } + /// <summary>The Bank mod's Radiance-earned property (9101) when the reply arrived; -1 when the server doesn't send it.</summary> + public required long EarnedAtReceipt { get; init; } +} + +internal static class MasteryFeed +{ + private const int LoginDelayMs = 4000; + private const int LoginGiveUpMs = 60_000; + private const int MinIntervalMs = 4000; + private const int ReplyWindowMs = 15_000; + private const int StaleMs = 30_000; + private const int AfterRaiseMs = 2000; + private const int MinRaiseIntervalMs = 1500; + private const int MaxSendFailures = 3; + + private static readonly object Gate = new(); + + // Any thread, under Gate. + private static long _wantAtMs; // 0 = no request wanted + private static string? _raiseCommand; + private static string _raiseLabel = ""; + + // Main thread only. + private static uint _playerId; + private static long _loginAtMs; + private static bool _loginPending; + private static long _lastDataSendMs = -MinIntervalMs; + private static long _lastRaiseMs = -MinRaiseIntervalMs; + private static int _sendFailures; + private static int _version; + + // Read anywhere. + private static volatile MasterySnapshot? _snapshot; + private static long _awaitingUntilMs; // our request's reply window (Volatile) + private static volatile bool _unsupported; + private static volatile string _status = "not asked yet"; + + /// <summary>The last reply, or null (none this login). Any thread.</summary> + public static MasterySnapshot? Snapshot => _snapshot; + + /// <summary>This login's Aelrynth server answered "Unknown command": nothing more is asked until the next login.</summary> + public static bool Unsupported => _unsupported; + + /// <summary> + /// Our incoming-chat hook isn't installed (Decal bridge mode leaves AddTextToScroll to + /// Decal), so a reply could be neither read nor hidden: nothing is asked or raised, and + /// the server's JSON line never lands in the player's chat. Any thread. + /// </summary> + public static bool NoChatHook => !ChatCallbackHooks.IncomingInstalled; + + /// <summary>A request is out and its reply not in yet.</summary> + public static bool Awaiting => Environment.TickCount64 < Volatile.Read(ref _awaitingUntilMs); + + /// <summary>What the feed did last, for /rc mastery and the panel.</summary> + public static string Status => _status; + + // ── Any thread: the panel and /rc ─────────────────────────────────── + + /// <summary>The Skills panel opened: ask unless the last reply is fresh. Does nothing off Aelrynth.</summary> + public static void PanelOpened() + { + if (!ServerInfo.IsAelrynth || _unsupported) return; + MasterySnapshot? s = _snapshot; + if (s == null || Environment.TickCount64 - s.ReceivedMs > StaleMs) + RequestAt(Environment.TickCount64); + } + + /// <summary>Ask now (still rate limited). Does nothing off Aelrynth.</summary> + public static void RequestRefresh() + { + if (!ServerInfo.IsAelrynth || _unsupported) return; + RequestAt(Environment.TickCount64); + } + + private static void RequestAt(long atMs) + { + lock (Gate) + { + if (_wantAtMs == 0 || atMs < _wantAtMs) + _wantAtMs = Math.Max(1, atMs); + } + } + + /// <summary> + /// Queues one "/raise <skill> <count>" for the main thread (the caller has + /// confirmed with the player). False with the reason when it can't be sent. + /// </summary> + public static bool QueueRaise(MasterySkill skill, int count, out string why) + { + if (!ServerInfo.IsAelrynth) { why = "Not on Aelrynth."; return false; } + if (_unsupported) { why = "This server has no mastery commands."; return false; } + if (NoChatHook) { why = "Not available under Decal (Decal owns incoming chat, so the reply can't be read)."; return false; } + string? cmd = MasteryWire.RaiseCommand(skill.Key, count); + if (cmd == null) { why = "That skill's name can't be sent to the server."; return false; } + lock (Gate) + { + if (_raiseCommand != null) { why = "A raise is already on its way."; return false; } + _raiseCommand = cmd; + _raiseLabel = $"{skill.Name} +{count}"; + } + why = ""; + return true; + } + + /// <summary> + /// The Radiance a raise can spend now, as near as the client knows: the balance in + /// the last reply plus what the Bank mod says was earned since (property 9101 rising). + /// Earnings from the last few seconds may not be banked yet, so the server can still + /// refuse a raise this says fits. Any thread (dictionary reads); call it about once a second. + /// </summary> + public static long EstimateRadiance(MasterySnapshot s) + { + long r = s.Data.Radiance; + if (s.EarnedAtReceipt >= 0 && ServerInfo.TryGetRadianceEarned(out long earned) && earned > s.EarnedAtReceipt) + r += earned - s.EarnedAtReceipt; + return r; + } + + // ── AC's main thread ──────────────────────────────────────────────── + + /// <summary> + /// MainThreadSnapshots.Tick, every tick. <paramref name="playerLive"/>: the player + /// object is usable (commands are only sent then); a logout (or no player) ends the + /// login, so the next one asks again even on the same character. A few compares when + /// nothing is wanted; sends at most one command per call. + /// </summary> + internal static void MainThreadTick(bool playerLive) + { + if (!MainThreadGuard.IsOnMainThread()) + return; + long now = Environment.TickCount64; + uint me = LogoutLifecycleHooks.HasObservedLogout ? 0 : ClientHelperHooks.GetPlayerId(); + if (me != _playerId) + NewLogin(me, now); + if (me == 0 || !playerLive) + return; + // Idle: two volatile loads, no lock. + if (!_loginPending && Volatile.Read(ref _wantAtMs) == 0 && Volatile.Read(ref _raiseCommand) == null) + return; + + string? raise; + long wantAt; + lock (Gate) + { + raise = _raiseCommand; + wantAt = _wantAtMs; + } + if (!_loginPending && wantAt == 0 && raise == null) + return; + + if (NoChatHook) + { + // Decal bridge mode: the reply would show in chat and never reach us. + _loginPending = false; + if (wantAt != 0 || raise != null) + lock (Gate) { _wantAtMs = 0; _raiseCommand = null; } + _status = "not asked: Decal owns incoming chat (bridge mode), so the reply can't be read or hidden"; + return; + } + + if (!ServerInfo.IsAelrynth || _unsupported) + { + // Detection can settle a few seconds into the login (the Bank properties, the + // world name): the login request waits for it, up to a minute. + if (_loginPending && now - _loginAtMs > LoginGiveUpMs) + _loginPending = false; + if (wantAt != 0 || raise != null) + { + lock (Gate) { _wantAtMs = 0; _raiseCommand = null; } + if (raise != null) + _status = _unsupported ? "raise not sent: this server has no mastery commands" : "raise not sent: not on Aelrynth"; + } + return; + } + + if (raise != null && now - _lastRaiseMs >= MinRaiseIntervalMs) + { + string label; + lock (Gate) { _raiseCommand = null; label = _raiseLabel; } + _lastRaiseMs = now; + if (ChatCommandDispatcher.SendServerCommand(raise)) + { + _status = $"sent: raise {label}"; + RynthLog.Compat($"MasteryFeed: sent {raise}"); + RequestAt(now + AfterRaiseMs); + } + else + { + _status = $"raise {label} could not be sent"; + } + return; // one command per tick + } + + if (_loginPending && now - _loginAtMs >= LoginDelayMs) + { + _loginPending = false; + RequestAt(now); + wantAt = now; + } + + if (wantAt != 0 && now >= wantAt && now - _lastDataSendMs >= MinIntervalMs && !Awaiting) + { + lock (Gate) { _wantAtMs = 0; } + _lastDataSendMs = now; + _loginPending = false; // the panel asked first: that covers the login request + if (ChatCommandDispatcher.SendServerCommand(MasteryWire.DataRequest)) + { + Volatile.Write(ref _awaitingUntilMs, now + ReplyWindowMs); + _sendFailures = 0; + _status = "asked the server"; + } + else if (++_sendFailures < MaxSendFailures) + { + RequestAt(now + 10_000); + _status = "could not send the request; trying again shortly"; + } + else + { + _status = "could not send the request (the client's talk function isn't bound)"; + } + } + } + + private static void NewLogin(uint me, long now) + { + _playerId = me; + _loginAtMs = now; + _loginPending = me != 0; + _snapshot = null; + _unsupported = false; + _sendFailures = 0; + Volatile.Write(ref _awaitingUntilMs, 0); + lock (Gate) { _wantAtMs = 0; _raiseCommand = null; } + _status = me != 0 ? "waiting to ask after login" : "logged out"; + } + + /// <summary> + /// Every incoming chat line, from the chat hook (AC's main thread), before AC draws + /// it. True = eat it (our own request's reply). Never throws. + /// </summary> + internal static bool OnIncomingLine(string line) + { + try + { + if (line.Length < 8) + return false; + bool awaiting = Awaiting; + if (MasteryWire.IsDataLine(line)) + { + if (!ServerInfo.IsAelrynth) + return false; + if (MasteryWire.TryParse(line, out MasteryData? data) && data != null) + { + Publish(data); + Volatile.Write(ref _awaitingUntilMs, 0); + return awaiting; + } + // Not a mastery line (another mod's data line), or one too damaged to read. + if (awaiting && line.Contains("\"t\":\"mastery\"", StringComparison.Ordinal)) + { + Volatile.Write(ref _awaitingUntilMs, 0); + _status = "the server's reply could not be read"; + RynthLog.Compat($"MasteryFeed: unreadable reply ({line.Length} chars)"); + return true; + } + return false; + } + if (awaiting && MasteryWire.IsUnknownCommand(line, MasteryWire.DataCommand)) + { + _unsupported = true; + Volatile.Write(ref _awaitingUntilMs, 0); + _status = "this server has no mastery commands (asked once; not again until the next login)"; + RynthLog.Compat("MasteryFeed: the server answered Unknown command: mastery-data - not asking again this login."); + return true; + } + return false; + } + catch + { + return false; + } + } + + private static void Publish(MasteryData data) + { + long earned = ServerInfo.TryGetRadianceEarned(out long e) ? e : -1; + _snapshot = new MasterySnapshot + { + Data = data, + Version = ++_version, + ReceivedMs = Environment.TickCount64, + EarnedAtReceipt = earned, + }; + _status = data.Ok + ? $"{data.Skills.Count} skills, {data.Radiance:N0} Radiance banked" + : "the server could not read your mastery" + (data.Why.Length > 0 ? $" ({data.Why})" : ""); + } +} diff --git a/src/RynthCore.Engine/Compatibility/MemoryProbe.cs b/src/RynthCore.Engine/Compatibility/MemoryProbe.cs new file mode 100644 index 0000000..17681d5 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/MemoryProbe.cs @@ -0,0 +1,294 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +/// <summary> +/// "Can I read (or write) this AC memory without an access violation?" for NativeAOT, where an +/// AV cannot be caught. Every IsReadablePointer / IsReadableSpan / IsMemoryReadable / +/// IsWritablePointer in the engine answers through here. +/// +/// WHY NOT JUST VirtualQuery (what they all used until 2026-10-02): in a 32-bit process on +/// 64-bit Windows, VirtualQuery's cost grows with the size of the committed region AFTER the +/// address asked about - the kernel walks the page tables to work out RegionSize. Measured on +/// the i7-4770K (tools/FloodProbeBench): 10 us on a small heap block, 0.35 ms 16 MB from the end +/// of a committed run, 2.6 ms at 64 MB, 11 ms at 256 MB, 19 ms at 512 MB. AC's heap reaches +/// 1.0-1.4 GB in a crowded dungeon, and the main-thread snapshot walks probed every hash bucket +/// and 3-4 spots of every object 10 times a second (identity/attackable walks 2 more times), +/// so a big heap turned each walk into tens to hundreds of milliseconds on AC's thread: the +/// 3-10 fps collapse in Matron Hive South (Lucy, 2026-10-02), still there after logout because +/// the heap stays committed. +/// +/// HOW: QueryWorkingSetEx answers per PAGE (about 2 us for one call, under 0.1 us per extra +/// page in the same call) no matter how big the region is. A page that is resident ("Valid") +/// is committed, and the call returns its protection, so the old rule is checked exactly: +/// committed, not NOACCESS, not GUARD, plus readable/writable where the caller asked. Only when +/// a page is NOT resident (trimmed to the standby list, never touched, reserved, free) does it +/// fall back to the old VirtualQuery test, which then decides exactly as before. A span is +/// accepted when every page in it passes (VirtualQuery additionally insisted on one region; +/// two adjacent readable regions read just as safely). +/// +/// Thread-safe and allocation-free (stackalloc). Counters are for the [SnapshotDiag] line. +/// The snapshot walks open a <see cref="BeginWalk"/> scope so each page is queried once per +/// walk rather than once per probe. +/// </summary> +internal static unsafe class MemoryProbe +{ + private const uint MEM_COMMIT = 0x1000; + private const uint PAGE_NOACCESS = 0x01; + private const uint PAGE_GUARD = 0x100; + + /// <summary>Any page protection that can be read (READONLY, READWRITE, WRITECOPY, EXECUTE_READ, ...).</summary> + internal const uint ReadableMask = 0x02 | 0x04 | 0x08 | 0x20 | 0x40 | 0x80; + /// <summary>Any page protection that can be written (READWRITE, WRITECOPY, EXECUTE_READWRITE, EXECUTE_WRITECOPY).</summary> + internal const uint WritableMask = 0x04 | 0x08 | 0x40 | 0x80; + + private const int PageShift = 12; + private const long PageSize = 1L << PageShift; + /// <summary>Spans longer than this many pages go straight to VirtualQuery. 80 pages = 320 KB covers the + /// largest CObjectMaint bucket array the walk accepts (65536 buckets x 4 bytes = 64 pages).</summary> + private const int MaxFastPages = 80; + + private static readonly IntPtr CurrentProcess = new(-1); + + // 1 = QueryWorkingSetEx unavailable or failing: every probe uses VirtualQuery (old behaviour). + private static int _fastDisabled; + + private static long _fastPages; + private static long _slowCalls; + private static long _slowTicks; + + [StructLayout(LayoutKind.Sequential)] + private struct WorkingSetExInfo + { + public IntPtr VirtualAddress; + public UIntPtr Flags; + } + + [StructLayout(LayoutKind.Sequential)] + private struct MemoryBasicInformation + { + public IntPtr BaseAddress; + public IntPtr AllocationBase; + public uint AllocationProtect; + public IntPtr RegionSize; + public uint State; + public uint Protect; + public uint Type; + } + + [DllImport("kernel32.dll", EntryPoint = "K32QueryWorkingSetEx")] + private static extern int QueryWorkingSetEx(IntPtr process, WorkingSetExInfo* info, uint size); + + [DllImport("kernel32.dll")] + private static extern int VirtualQuery(IntPtr address, MemoryBasicInformation* info, int length); + + /// <summary>Committed, not NOACCESS/GUARD (the old IsReadablePointer / IsReadableSpan rule).</summary> + public static bool IsAccessible(IntPtr ptr, int length = 1) => Check(ptr, length, 0); + + /// <summary>Committed, not NOACCESS/GUARD, and a readable protection (the old SmartBoxLocator rule).</summary> + public static bool IsReadable(IntPtr ptr, int length = 1) => Check(ptr, length, ReadableMask); + + /// <summary>Committed, not NOACCESS/GUARD, and a writable protection (the old IsWritablePointer rule).</summary> + public static bool IsWritable(IntPtr ptr, int length = 1) => Check(ptr, length, WritableMask); + + /// <summary> + /// Probe counters since the last call: pages answered by QueryWorkingSetEx, and the + /// VirtualQuery fallbacks with their total time. Resets them. + /// </summary> + public static (long FastPages, long SlowCalls, double SlowMs) TakeStats() + { + long fast = Interlocked.Exchange(ref _fastPages, 0); + long slow = Interlocked.Exchange(ref _slowCalls, 0); + long ticks = Interlocked.Exchange(ref _slowTicks, 0); + return (fast, slow, ticks * 1000.0 / System.Diagnostics.Stopwatch.Frequency); + } + + /// <summary>True while the QueryWorkingSetEx path is in use (false = every probe is a VirtualQuery).</summary> + public static bool FastPathActive => Volatile.Read(ref _fastDisabled) == 0; + + // ── Walk scope: remember resident pages for the length of one snapshot walk ────────── + // A walk over every object probes 3-10 spots per object, almost all on one or two pages. + // Inside a scope (AC's main thread, inside one walk, AC itself not running) a page found + // resident keeps its answer until the scope ends, so a page costs one query per walk + // instead of one per probe. Only the thread that opened the scope uses the cache; a probe + // from any other thread asks the system as usual. Plain statics with an owner thread, not + // [ThreadStatic]: the engine can live in a collectible context (CoreCLR host). + private const int CacheSlots = 1024; + private static readonly uint[] _cachePage = new uint[CacheSlots]; // page number + 1 (0 = empty slot) + private static readonly ushort[] _cacheProt = new ushort[CacheSlots]; // that page's Win32Protection + private static int _scopeOwner; // managed thread id that holds the scope (0 = none) + private static int _scopeDepth; // nesting on the owner thread + + /// <summary> + /// Opens a page cache for one main-thread snapshot walk (dispose to close; nests). Only + /// for code that reads AC memory while AC is not running (the EndScene / UseTime walks). + /// A second thread asking while another holds the scope just gets no cache. + /// </summary> + public static WalkScope BeginWalk() + { + int me = Environment.CurrentManagedThreadId; + if (Volatile.Read(ref _scopeOwner) == me) + { + _scopeDepth++; + return new WalkScope(true); + } + if (Interlocked.CompareExchange(ref _scopeOwner, me, 0) != 0) + return new WalkScope(false); + _scopeDepth = 1; + Array.Clear(_cachePage); + return new WalkScope(true); + } + + internal readonly struct WalkScope : IDisposable + { + private readonly bool _open; + public WalkScope(bool open) => _open = open; + public void Dispose() + { + if (!_open || Volatile.Read(ref _scopeOwner) != Environment.CurrentManagedThreadId) + return; + if (--_scopeDepth <= 0) + { + _scopeDepth = 0; + Volatile.Write(ref _scopeOwner, 0); + } + } + } + + private static bool InScope => _scopeDepth > 0 && Volatile.Read(ref _scopeOwner) == Environment.CurrentManagedThreadId; + + // Protection of a resident page from the walk cache, or 0 when not cached. + private static uint CachedProtection(ulong page) + { + int slot = (int)(page & (CacheSlots - 1)); + return _cachePage[slot] == (uint)page + 1 ? _cacheProt[slot] : 0u; + } + + private static void RememberProtection(ulong page, uint protect) + { + int slot = (int)(page & (CacheSlots - 1)); + _cachePage[slot] = (uint)page + 1; + _cacheProt[slot] = (ushort)protect; + } + + private static int Judge(uint protect, uint requiredMask) + { + if ((protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) + return 0; + if (requiredMask != 0 && (protect & requiredMask) == 0) + return 0; + return 1; + } + + private static bool Check(IntPtr ptr, int length, uint requiredMask) + { + if (ptr == IntPtr.Zero || length <= 0) + return false; + + if (Volatile.Read(ref _fastDisabled) == 0) + { + int verdict = TryFast(ptr, length, requiredMask); + if (verdict >= 0) + return verdict == 1; + } + return Slow(ptr, length, requiredMask); + } + + // 1 = every page resident and acceptable, 0 = a resident page is refused, + // -1 = can't tell here (a page is not resident, span too long, or the call failed). + private static int TryFast(IntPtr ptr, int length, uint requiredMask) + { + ulong start = unchecked((ulong)(nuint)ptr); + ulong last = start + (ulong)(length - 1); + if (last > uint.MaxValue) + return 0; // runs past the 32-bit address space: never readable + ulong firstPage = start >> PageShift; + ulong lastPage = last >> PageShift; + ulong pageCount = lastPage - firstPage + 1; + if (pageCount > MaxFastPages) + return -1; + + int n = (int)pageCount; + + // Inside a walk scope: answer from the pages already seen in this walk. + bool inScope = InScope; + if (inScope) + { + bool allCached = true; + for (int i = 0; i < n && allCached; i++) + { + uint cached = CachedProtection(firstPage + (ulong)i); + if (cached == 0) allCached = false; + else if (Judge(cached, requiredMask) == 0) return 0; + } + if (allCached) + return 1; + } + + WorkingSetExInfo* info = stackalloc WorkingSetExInfo[n]; + for (int i = 0; i < n; i++) + { + info[i].VirtualAddress = (IntPtr)(nint)(long)((firstPage + (ulong)i) << PageShift); + info[i].Flags = UIntPtr.Zero; + } + + int ok; + try + { + ok = QueryWorkingSetEx(CurrentProcess, info, (uint)(n * sizeof(WorkingSetExInfo))); + } + catch + { + // Entry point missing (pre-Windows 7 kernel32) or the call itself failed: VirtualQuery from now on. + Interlocked.Exchange(ref _fastDisabled, 1); + return -1; + } + if (ok == 0) + return -1; + + Interlocked.Add(ref _fastPages, n); + for (int i = 0; i < n; i++) + { + ulong flags = (ulong)(nuint)info[i].Flags; + if ((flags & 1) == 0) + return -1; // not resident: committed-but-trimmed, untouched, reserved or free - ask VirtualQuery + uint protect = (uint)((flags >> 4) & 0x7FF); // PSAPI_WORKING_SET_EX_BLOCK.Win32Protection + if (protect == 0) + return -1; // resident but no protection reported: let VirtualQuery decide + if (inScope) RememberProtection(firstPage + (ulong)i, protect); + if (Judge(protect, requiredMask) == 0) + return 0; + } + return 1; + } + + // The pre-2026-10-02 rule, unchanged: one VirtualQuery, the span inside that one region. + private static bool Slow(IntPtr ptr, int length, uint requiredMask) + { + long t0 = System.Diagnostics.Stopwatch.GetTimestamp(); + try + { + MemoryBasicInformation mbi; + if (VirtualQuery(ptr, &mbi, sizeof(MemoryBasicInformation)) == 0) + return false; + if (mbi.State != MEM_COMMIT) + return false; + if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) + return false; + if (requiredMask != 0 && (mbi.Protect & requiredMask) == 0) + return false; + if (length <= 1) + return true; + ulong regionEnd = unchecked((ulong)(nuint)mbi.BaseAddress + (ulong)(nuint)mbi.RegionSize); + ulong spanEnd = unchecked((ulong)(nuint)ptr + (ulong)length); + return spanEnd <= regionEnd; + } + finally + { + Interlocked.Increment(ref _slowCalls); + Interlocked.Add(ref _slowTicks, System.Diagnostics.Stopwatch.GetTimestamp() - t0); + } + } +} diff --git a/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs b/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs new file mode 100644 index 0000000..cf264b6 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs @@ -0,0 +1,177 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/MessageBoxHooks.cs +// Logs every message box shown in this process (user32!MessageBoxW / A): +// caption, text, style and the calling module, when it opens and when it +// closes. +// +// Why: AC reports some errors in a modal MessageBox on its main thread +// (acclient+0x3CE80, formatted by the caller at acclient+0x1558B5). The main +// thread then waits on the dialog, MainThreadHangWatchdog reports a wedge, +// and the launcher kills and relaunches the client - with the dialog's text +// lost (the 2026-09-28 Drakkon6 close: heap isn't in the hang minidump). +// Now the text is in the log, and the watchdog names the open dialog in its +// hang report (see Describe). +// +// The detour only observes: it always calls the original and returns its +// result. Installed per engine generation; EngineLifecycle's +// MH_DisableHook(ALL) removes it on reload. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +internal static class MessageBoxHooks +{ + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int MessageBoxDelegate(IntPtr hWnd, IntPtr text, IntPtr caption, uint type); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr GetModuleHandleW(string? lpModuleName); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr LoadLibraryW(string lpLibFileName); + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)] + private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); + + [DllImport("kernel32.dll")] + private static extern ushort RtlCaptureStackBackTrace(uint framesToSkip, uint framesToCapture, IntPtr[] backTrace, out uint hash); + + [DllImport("kernel32.dll")] + private static extern uint GetCurrentThreadId(); + + private static MessageBoxDelegate? _detourW, _detourA, _originalW, _originalA; + private static int _installed; + + // The dialog currently open (last one wins if several nest). Read by the + // hang watchdog's thread; written on the thread showing the dialog. + private static volatile string? _openDescription; + private static long _openedAtTicks; + private static int _openCount; + + public static void Initialize() + { + if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0) return; + try + { + IntPtr user32 = GetModuleHandleW("user32.dll"); + if (user32 == IntPtr.Zero) user32 = LoadLibraryW("user32.dll"); + if (user32 == IntPtr.Zero) + { + RynthLog.Compat("MessageBoxHooks: user32 not found."); + return; + } + _detourW = MessageBoxWDetour; + _detourA = MessageBoxADetour; + _originalW = Hook(user32, "MessageBoxW", _detourW); + _originalA = Hook(user32, "MessageBoxA", _detourA); + } + catch (Exception ex) + { + RynthLog.Compat($"MessageBoxHooks: install failed - {ex.GetType().Name}: {ex.Message}"); + } + } + + private static MessageBoxDelegate? Hook(IntPtr user32, string name, MessageBoxDelegate detour) + { + IntPtr target = GetProcAddress(user32, name); + if (target == IntPtr.Zero) + { + RynthLog.Compat($"MessageBoxHooks: GetProcAddress({name}) failed."); + return null; + } + IntPtr trampoline = MinHook.HookCreate(target, Marshal.GetFunctionPointerForDelegate(detour)); + var original = Marshal.GetDelegateForFunctionPointer<MessageBoxDelegate>(trampoline); + Thread.MemoryBarrier(); + MinHook.Enable(target); + RynthLog.Info($"MessageBoxHooks: hooked user32!{name} @ 0x{target.ToInt32():X8}."); + return original; + } + + /// <summary> + /// The message box open right now, e.g. "AC message box open 12s on the + /// main thread: 'Asheron's Call' - '…'", or null. Any thread. + /// </summary> + public static string? Describe() + { + string? open = _openDescription; + if (open == null) return null; + long secs = (Environment.TickCount64 - Interlocked.Read(ref _openedAtTicks)) / 1000; + return $"message box open {secs}s: {open}"; + } + + private static int MessageBoxWDetour(IntPtr hWnd, IntPtr text, IntPtr caption, uint type) => + Show(hWnd, text, caption, type, wide: true); + + private static int MessageBoxADetour(IntPtr hWnd, IntPtr text, IntPtr caption, uint type) => + Show(hWnd, text, caption, type, wide: false); + + private static int Show(IntPtr hWnd, IntPtr text, IntPtr caption, uint type, bool wide) + { + MessageBoxDelegate? original = wide ? _originalW : _originalA; + string? description = null; + long opened = Environment.TickCount64; + try + { + description = Opened(text, caption, type, wide); + } + catch { /* observation only: never block the dialog */ } + + int result = original != null ? original(hWnd, text, caption, type) : 0; + + try + { + long secs = (Environment.TickCount64 - opened) / 1000; + RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}"); + if (Interlocked.Decrement(ref _openCount) <= 0) + { + Interlocked.Exchange(ref _openCount, 0); + _openDescription = null; + } + } + catch { } + return result; + } + + private static string Opened(IntPtr text, IntPtr caption, uint type, bool wide) + { + string body = Read(text, wide); + string title = Read(caption, wide); + bool mainThread = MainThreadGuard.IsOnMainThread(); + + // The first frame outside user32 and this file: who asked for the dialog. + string caller = "?"; + var frames = new IntPtr[8]; + int n = RtlCaptureStackBackTrace(1, (uint)frames.Length, frames, out _); + for (int i = 0; i < n; i++) + { + string module = ProcessExitHooks.ResolveModule(frames[i], out int rva); + if (module.Contains("RynthCore.Engine", StringComparison.OrdinalIgnoreCase) + || module.Contains("user32", StringComparison.OrdinalIgnoreCase)) + continue; + caller = $"{module}+0x{rva:X}"; + break; + } + + string description = $"'{title}' - '{Flatten(body)}' (style=0x{type:X}, {(mainThread ? "AC main thread" : $"thread {GetCurrentThreadId()}")}, caller {caller})"; + Interlocked.Exchange(ref _openedAtTicks, Environment.TickCount64); + Interlocked.Increment(ref _openCount); + _openDescription = description; + RynthLog.Error($"MessageBoxHooks: MESSAGE BOX OPENED {description}"); + return description; + } + + private static string Read(IntPtr p, bool wide) + { + if (p == IntPtr.Zero) return ""; + string? s = wide ? Marshal.PtrToStringUni(p) : Marshal.PtrToStringAnsi(p); + if (s == null) return ""; + return s.Length > 2000 ? s.Substring(0, 2000) + "…" : s; + } + + private static string Flatten(string s) => s.Replace("\r\n", " | ").Replace('\n', ' ').Replace('\r', ' '); +} diff --git a/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs b/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs index 518fb59..13617dd 100644 --- a/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs @@ -225,9 +225,15 @@ internal static class MovementActionHooks public static bool SetAutonomyLevel(uint level) { + // A missing delegate stays a false return on every thread (it would only + // no-op in the drain), then off-thread callers queue the 0xF752 send like + // StopMovement/Jump do; true there means "queued". if (_autonomyLevel == null) return false; + if (!MainThreadGuard.IsOnMainThread()) + return AcMainThreadQueue.EnqueueSetAutonomyLevel(level); + try { return _autonomyLevel(level); diff --git a/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs b/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs new file mode 100644 index 0000000..a21bd1c --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs @@ -0,0 +1,104 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/PlayerLifecycleLog.cs +// One log line per player lifecycle edge: death (health reaches 0), revival, +// portal space entered/exited, and landblock jumps (a teleport, not walking +// into the next landblock), each with the landblock. +// +// Why: 2026-09-28 a client crashed in AC's own teardown code +// (acclient+0x18712F, null read in a hash-table clear) during the death +// portal to the lifestone, and nothing in the log recorded the death or the +// teleport. With these lines a crash can be lined up with what the character +// was doing. +// +// Sampled from GameTickHooks.UseTimeDetour on AC's main thread, before AC's +// tick, so the reads see a consistent world. Alloc-free except on an edge. +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal static class PlayerLifecycleLog +{ + private static bool _init; + private static volatile bool _portaling, _dead; + private static long _transitionUntil; + private const long TransitionSettleMs = 5_000; + + /// <summary> + /// Dead, in portal space, or within 5 s after either: AC is tearing down and + /// loading the world, so nothing should poke at its state (BusyCountHooks' + /// force-clear). As of the last game tick; any thread. + /// </summary> + public static bool InWorldTransition => + _dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _transitionUntil); + private static uint _landblock; + private static long _portalEnteredAt, _diedAt; + + /// <summary>AC main thread, once per game tick.</summary> + public static void SampleOnGameThread(bool portaling) + { + bool dead = false; + uint health = 0, maxHealth = 0; + if (PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot v)) + { + health = v.Health; + maxHealth = v.MaxHealth; + dead = v.MaxHealth > 0 && v.Health == 0; + } + uint cell = 0; + if (PlayerPhysicsHooks.TryGetPlayerPose(out uint c, out _, out _, out _, out _, out _, out _, out _)) + cell = c; + uint landblock = cell >> 16; + + if (!_init) + { + _init = true; + _portaling = portaling; + _dead = dead; + _landblock = landblock; + return; + } + + long now = Environment.TickCount64; + if (dead || portaling || _dead || _portaling) + Interlocked.Exchange(ref _transitionUntil, now + TransitionSettleMs); + if (dead != _dead) + { + if (dead) + { + _diedAt = now; + RynthLog.Info($"[Lifecycle] player DIED (health 0/{maxHealth}) in landblock 0x{landblock:X4} (cell 0x{cell:X8})."); + } + else + RynthLog.Info($"[Lifecycle] player alive again (health {health}/{maxHealth}) {Ago(_diedAt, now)} after death, landblock 0x{landblock:X4}."); + _dead = dead; + } + + if (portaling != _portaling) + { + if (portaling) + { + _portalEnteredAt = now; + string why = _diedAt != 0 && now - _diedAt < 30_000 ? " (death portal)" : ""; + RynthLog.Info($"[Lifecycle] portal space ENTERED{why} from landblock 0x{landblock:X4} (cell 0x{cell:X8})."); + } + else + RynthLog.Info($"[Lifecycle] portal space EXITED into landblock 0x{landblock:X4} (cell 0x{cell:X8}) after {Ago(_portalEnteredAt, now)}."); + _portaling = portaling; + } + + if (landblock != 0 && _landblock != 0 && landblock != _landblock) + { + int dx = (int)((landblock >> 8) & 0xFF) - (int)((_landblock >> 8) & 0xFF); + int dy = (int)(landblock & 0xFF) - (int)(_landblock & 0xFF); + if (Math.Abs(dx) > 1 || Math.Abs(dy) > 1) + RynthLog.Info($"[Lifecycle] landblock jump 0x{_landblock:X4} -> 0x{landblock:X4}{(portaling ? " (in portal space)" : "")}."); + } + if (landblock != 0) _landblock = landblock; + } + + private static string Ago(long since, long now) => + since == 0 ? "?" : $"{(now - since) / 1000.0:0.0}s"; +} diff --git a/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs b/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs index 4a42691..8f60197 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs @@ -87,6 +87,118 @@ internal static class PlayerPhysicsHooks return ready; } + // ── Player pose snapshot (2026-09-30 main-thread audit) ───────────────────── + // The plugin pump (RynthAi nav / radar / Jumper / meta, RynthLua), Nav3DRenderer's + // Clear/CommitFrame and UI threads read the player's pose and heading many times + // a second. Read live off-thread that walked the SmartBox player (unprobed vtable + // read), read cell and origin as separate loads (a landblock crossing could pair + // the new cell with the old x/y, ~192 m off for a tick) and called AC's + // CPhysicsObj::get_heading off-thread. The main thread now publishes one + // consistent copy per frame (MainThreadSnapshots.Tick) under a seqlock: the + // writer never waits and never allocates; readers retry a few times and fail + // closed. Main-thread callers (GameMatrixCapture, MonsterHud, PlateDebuffs, + // PlayerLifecycleLog) keep the live read. + private static int _poseSeq; // odd while the main thread is writing + private static bool _poseValid; + private static bool _poseHeadingValid; + private static uint _poseCell; + private static float _poseX, _poseY, _poseZ, _poseQw, _poseQx, _poseQy, _poseQz, _poseHeading; + private static long _lastPosePublishTs; + private static long _nextHeadingBindAttemptMs; + private static readonly long PosePublishMinTicks = System.Diagnostics.Stopwatch.Frequency / 250; // <= 250 Hz + + /// <summary> + /// Main thread only (MainThreadSnapshots.Tick). Reads the live pose and heading + /// once and publishes them together. An unreadable player (portal, logout, + /// char-select) publishes "invalid", so off-thread readers fail closed as the + /// live read did. + /// </summary> + internal static void PublishPoseSnapshot(bool smartBoxReady) + { + if (!MainThreadGuard.IsOnMainThread()) + return; + long ts = System.Diagnostics.Stopwatch.GetTimestamp(); + if (ts - _lastPosePublishTs < PosePublishMinTicks) + return; // UseTime and EndScene both call in; once per few ms is plenty + _lastPosePublishTs = ts; + + uint cell = 0; + float x = 0, y = 0, z = 0, qw = 1f, qx = 0, qy = 0, qz = 0; + // Not located: publish "no pose" without TryGetPlayer (which would re-run + // the SmartBox probe's pattern scan on every call). + bool ok = smartBoxReady && + TryGetPlayerPoseLive(out cell, out x, out y, out z, out qw, out qx, out qy, out qz); + float heading = 0f; + bool headingOk = false; + if (ok) + { + // Bind the heading thunk at most every 5 s while it is missing: the bind + // runs a SmartBox probe + pattern resolve, far too heavy for every frame. + if (_getHeading == null) + { + long now = Environment.TickCount64; + if (now >= _nextHeadingBindAttemptMs) + { + _nextHeadingBindAttemptMs = now + 5000; + EnsurePhysicsDelegates(); + } + } + if (_getHeading != null) + headingOk = TryGetPlayerHeadingLive(out heading); + } + + System.Threading.Interlocked.Increment(ref _poseSeq); // odd: writing + _poseValid = ok; + _poseHeadingValid = headingOk; + _poseCell = cell; + _poseX = x; _poseY = y; _poseZ = z; + _poseQw = qw; _poseQx = qx; _poseQy = qy; _poseQz = qz; + _poseHeading = heading; + System.Threading.Interlocked.Increment(ref _poseSeq); // even: published + } + + // Seqlock read. False when nothing valid is published, or (vanishingly rarely) + // when the writer kept the lock for every retry. + private static bool TryReadPoseSnapshot(out uint cell, out float x, out float y, out float z, + out float qw, out float qx, out float qy, out float qz, + out bool headingValid, out float heading) + { + for (int attempt = 0; attempt < 8; attempt++) + { + int s1 = System.Threading.Volatile.Read(ref _poseSeq); + if ((s1 & 1) != 0) + { + System.Threading.Thread.SpinWait(8); + continue; + } + bool valid = _poseValid; + headingValid = _poseHeadingValid; + cell = _poseCell; + x = _poseX; y = _poseY; z = _poseZ; + qw = _poseQw; qx = _poseQx; qy = _poseQy; qz = _poseQz; + heading = _poseHeading; + System.Threading.Interlocked.MemoryBarrier(); + if (System.Threading.Volatile.Read(ref _poseSeq) != s1) + continue; + if (!valid) + break; + return true; + } + cell = 0; x = y = z = 0; qw = 1f; qx = qy = qz = 0; + headingValid = false; heading = 0; + return false; + } + + /// <summary> + /// The per-frame main-thread pose copy (cell, cell-local origin, yaw quaternion + /// qw/qz and AC's heading, 0 = North, clockwise), read from any thread without + /// calling into AC. headingValid is false while AC's get_heading isn't bound; + /// derive the heading from qw/qz then. False when nothing valid is published. + /// </summary> + public static bool TryGetPlayerPoseSnapshot(out uint objCellId, out float x, out float y, out float z, + out float qw, out float qz, out bool headingValid, out float heading) + => TryReadPoseSnapshot(out objCellId, out x, out y, out z, out qw, out _, out _, out qz, out headingValid, out heading); + public static bool TryGetPlayerPose( out uint objCellId, out float x, @@ -96,6 +208,26 @@ internal static class PlayerPhysicsHooks out float qx, out float qy, out float qz) + { + // Off AC's main thread: the per-frame main-thread copy (one consistent + // cell/origin/quaternion set, at most a frame old). + if (!MainThreadGuard.IsOnMainThread()) + return TryReadPoseSnapshot(out objCellId, out x, out y, out z, out qw, out qx, out qy, out qz, out _, out _); + + return TryGetPlayerPoseLive(out objCellId, out x, out y, out z, out qw, out qx, out qy, out qz); + } + + // Live pose read. Page-probes every field. Called on the main thread (the + // snapshot publisher and main-thread callers of TryGetPlayerPose). + private static bool TryGetPlayerPoseLive( + out uint objCellId, + out float x, + out float y, + out float z, + out float qw, + out float qx, + out float qy, + out float qz) { objCellId = 0; x = y = z = 0; @@ -152,9 +284,32 @@ internal static class PlayerPhysicsHooks } public static bool TryGetPlayerHeading(out float headingDegrees) + { + // Off AC's main thread (host GetPlayerHeadingFn on the pump: Jumper, radar, + // dungeon map, AutoVendor): the heading the main thread read with AC's own + // get_heading this frame. Never calls into AC from here. + if (!MainThreadGuard.IsOnMainThread()) + { + if (TryReadPoseSnapshot(out _, out _, out _, out _, out _, out _, out _, out _, out bool hv, out float h) && hv) + { + headingDegrees = h; + return true; + } + headingDegrees = 0; + return false; + } + + return TryGetPlayerHeadingLive(out headingDegrees); + } + + // Main thread only: AC's CPhysicsObj::get_heading on the SmartBox player. + private static bool TryGetPlayerHeadingLive(out float headingDegrees) { headingDegrees = 0; + if (!MainThreadGuard.IsOnMainThread()) + return false; + if (!EnsurePhysicsDelegates()) return false; @@ -180,6 +335,12 @@ internal static class PlayerPhysicsHooks public static bool SetPlayerHeading(float headingDegrees) { + // CPhysicsObj::set_heading (with sendEvent) writes the live physics object + // and can send a movement event: main thread only. No callers today; an + // off-thread caller gets false (use TurnToHeading, which marshals). + if (!MainThreadGuard.IsOnMainThread()) + return false; + if (!EnsurePhysicsDelegates() || _setHeading == null) return false; @@ -217,6 +378,16 @@ internal static class PlayerPhysicsHooks public static bool SetPlayerHeadingDirect(float decalHeadingDeg) { + // Plugins reach this from the pump thread on every nav tick + // (Host.TurnToHeading -> ClientActionHooks.TurnToHeading). Two raw stores + // into the live quaternion there raced AC's physics integration (torn, + // non-unit orientation), and the SmartBox player walk ran off-thread too. + // Park the heading in the coalesced slot instead; AcMainThreadQueue.Drain + // calls back in here on the main thread (and falls back to the + // CommandInterpreter turn there when there is no player, as before). + if (!MainThreadGuard.IsOnMainThread()) + return AcMainThreadQueue.EnqueueDirectHeading(decalHeadingDeg); + int n = System.Threading.Interlocked.Increment(ref _setHeadingCalls); if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure)) { @@ -237,6 +408,17 @@ internal static class PlayerPhysicsHooks float newQz = (float)Math.Sin(physYawRad * 0.5); IntPtr pos = player + PhysicsPositionOffset; + // Probe both stores (they can straddle a page) so a player pointer that + // went stale between the SmartBox lookup and here fails closed rather + // than taking an uncatchable NativeAOT write AV. + if (!ClientObjectHooks.IsWritablePointer(pos + PositionQwOffset) || + !ClientObjectHooks.IsWritablePointer(pos + PositionQzOffset)) + { + _statusMessage = "Player position struct not writable."; + if (ShouldLogHeading(n)) + RynthLog.Compat($"Move: SetPlayerHeadingDirect({decalHeadingDeg:0.0}) #{n} — position not writable (player=0x{player.ToInt32():X8})"); + return false; + } WriteFloat(pos + PositionQwOffset, newQw); WriteFloat(pos + PositionQzOffset, newQz); @@ -363,6 +545,13 @@ internal static class PlayerPhysicsHooks { inProgress = false; + // Main thread only: the SmartBox player -> MovementManager -> CMotionInterp + // hops are unprobed reads through objects AC frees at logout / char switch. + // Every caller (queue drain, busy watchdog, CastGate.Sample) is on the main + // thread; an off-thread caller gets "couldn't read" (no opinion) instead. + if (!MainThreadGuard.IsOnMainThread()) + return false; + if (!TryGetCMotionInterp(out IntPtr cmi) || cmi == IntPtr.Zero) return false; diff --git a/src/RynthCore.Engine/Compatibility/PlayerProgressHooks.cs b/src/RynthCore.Engine/Compatibility/PlayerProgressHooks.cs new file mode 100644 index 0000000..f12edb9 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/PlayerProgressHooks.cs @@ -0,0 +1,252 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/PlayerProgressHooks.cs +// +// The Skills panel's data (docs/IMGUI_SKILLS.md): the player's skills, +// attributes and vitals with the numbers a raise needs (ranks, XP spent, +// innate level, buffed and base values), level, XP, skill credits, and the +// buffs on each stat (the enchantment snapshot's StatMods). +// +// Threads: +// Prefetch AC's main thread (MainThreadSnapshots.Tick, player live). All the +// AC reads are in ClientObjectHooks.ReadPlayerProgressLive. +// Want / Current / RefreshSoon any thread (the panel: AC's render thread). +// +// Demand-driven: nothing is read unless a reader called Want in the last 2 s, +// then at most every 500 ms. Reads go into one preallocated work buffer; a new +// snapshot object is published (and allocated) only when something changed, +// so an idle open panel costs a compare every half second. +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +/// <summary> +/// One read of the player's progress. Published copies are never written again +/// (readers may keep them); the work buffer is private to the prefetch. +/// Index conventions: skills by STypeSkill (1..MaxSkill), attributes by +/// STypeAttribute (1..6), vitals 1 = health, 2 = stamina, 3 = mana. +/// </summary> +internal sealed class PlayerProgress +{ + public const int MaxSkill = 54; + public const int MaxBuffs = 256; + + public int Version; + public uint PlayerId; + + // Skills: the qualities' skill table (class 0 when the skill isn't in it) and InqSkill. + public bool SkillTableRead; + public readonly bool[] SkillInTable = new bool[MaxSkill + 1]; + public readonly uint[] SkillClass = new uint[MaxSkill + 1]; // 1 untrained, 2 trained, 3 specialized + public readonly uint[] SkillXpSpent = new uint[MaxSkill + 1]; + public readonly uint[] SkillRanks = new uint[MaxSkill + 1]; + public readonly uint[] SkillInit = new uint[MaxSkill + 1]; + public readonly bool[] SkillLevelKnown = new bool[MaxSkill + 1]; + public readonly int[] SkillBuffed = new int[MaxSkill + 1]; + public readonly int[] SkillBase = new int[MaxSkill + 1]; + + // Attributes 1..6 and vitals 1..3 (health, stamina, mana): the AttributeCache and Inq*. + public bool AttributeCacheRead; + public readonly uint[] AttrRanks = new uint[7]; + public readonly uint[] AttrInit = new uint[7]; + public readonly uint[] AttrXpSpent = new uint[7]; + public readonly uint[] AttrBuffed = new uint[7]; + public readonly uint[] AttrBase = new uint[7]; + public readonly uint[] VitalRanks = new uint[4]; + public readonly uint[] VitalInit = new uint[4]; + public readonly uint[] VitalXpSpent = new uint[4]; + public readonly uint[] VitalBuffed = new uint[4]; + public readonly uint[] VitalBase = new uint[4]; + + public int Level; + public int SkillCredits; + public long TotalXp; + public long UnassignedXp; + public long Luminance; + public long MaxLuminance; + public float Vitae = 1f; + + // Buffs that change a skill, attribute or vital (StatMod type has 0x1, 0x2 or 0x10). + public int BuffCount; + public readonly uint[] BuffSpell = new uint[MaxBuffs]; + public readonly double[] BuffExpiry = new double[MaxBuffs]; // server time; double.MaxValue = no end + public readonly uint[] BuffType = new uint[MaxBuffs]; + public readonly uint[] BuffKey = new uint[MaxBuffs]; + public readonly float[] BuffVal = new float[MaxBuffs]; + public readonly uint[] BuffCategory = new uint[MaxBuffs]; + + public void Clear() + { + PlayerId = 0; + SkillTableRead = false; + Array.Clear(SkillInTable); + Array.Clear(SkillClass); + Array.Clear(SkillXpSpent); + Array.Clear(SkillRanks); + Array.Clear(SkillInit); + Array.Clear(SkillLevelKnown); + Array.Clear(SkillBuffed); + Array.Clear(SkillBase); + AttributeCacheRead = false; + Array.Clear(AttrRanks); + Array.Clear(AttrInit); + Array.Clear(AttrXpSpent); + Array.Clear(AttrBuffed); + Array.Clear(AttrBase); + Array.Clear(VitalRanks); + Array.Clear(VitalInit); + Array.Clear(VitalXpSpent); + Array.Clear(VitalBuffed); + Array.Clear(VitalBase); + Level = SkillCredits = 0; + TotalXp = UnassignedXp = Luminance = MaxLuminance = 0; + Vitae = 1f; + BuffCount = 0; + } + + public void CopyFrom(PlayerProgress o) + { + PlayerId = o.PlayerId; + SkillTableRead = o.SkillTableRead; + o.SkillInTable.CopyTo(SkillInTable, 0); + o.SkillClass.CopyTo(SkillClass, 0); + o.SkillXpSpent.CopyTo(SkillXpSpent, 0); + o.SkillRanks.CopyTo(SkillRanks, 0); + o.SkillInit.CopyTo(SkillInit, 0); + o.SkillLevelKnown.CopyTo(SkillLevelKnown, 0); + o.SkillBuffed.CopyTo(SkillBuffed, 0); + o.SkillBase.CopyTo(SkillBase, 0); + AttributeCacheRead = o.AttributeCacheRead; + o.AttrRanks.CopyTo(AttrRanks, 0); + o.AttrInit.CopyTo(AttrInit, 0); + o.AttrXpSpent.CopyTo(AttrXpSpent, 0); + o.AttrBuffed.CopyTo(AttrBuffed, 0); + o.AttrBase.CopyTo(AttrBase, 0); + o.VitalRanks.CopyTo(VitalRanks, 0); + o.VitalInit.CopyTo(VitalInit, 0); + o.VitalXpSpent.CopyTo(VitalXpSpent, 0); + o.VitalBuffed.CopyTo(VitalBuffed, 0); + o.VitalBase.CopyTo(VitalBase, 0); + Level = o.Level; + SkillCredits = o.SkillCredits; + TotalXp = o.TotalXp; + UnassignedXp = o.UnassignedXp; + Luminance = o.Luminance; + MaxLuminance = o.MaxLuminance; + Vitae = o.Vitae; + BuffCount = o.BuffCount; + Array.Copy(o.BuffSpell, BuffSpell, o.BuffCount); + Array.Copy(o.BuffExpiry, BuffExpiry, o.BuffCount); + Array.Copy(o.BuffType, BuffType, o.BuffCount); + Array.Copy(o.BuffKey, BuffKey, o.BuffCount); + Array.Copy(o.BuffVal, BuffVal, o.BuffCount); + Array.Copy(o.BuffCategory, BuffCategory, o.BuffCount); + } + + /// <summary>True when every value equals <paramref name="o"/>'s (Version aside). No allocation.</summary> + public bool SameAs(PlayerProgress o) + { + if (PlayerId != o.PlayerId || SkillTableRead != o.SkillTableRead || AttributeCacheRead != o.AttributeCacheRead + || Level != o.Level || SkillCredits != o.SkillCredits || TotalXp != o.TotalXp || UnassignedXp != o.UnassignedXp + || Luminance != o.Luminance || MaxLuminance != o.MaxLuminance || Vitae != o.Vitae || BuffCount != o.BuffCount) + return false; + return Eq(SkillInTable, o.SkillInTable) && Eq(SkillClass, o.SkillClass) && Eq(SkillXpSpent, o.SkillXpSpent) + && Eq(SkillRanks, o.SkillRanks) && Eq(SkillInit, o.SkillInit) && Eq(SkillLevelKnown, o.SkillLevelKnown) + && Eq(SkillBuffed, o.SkillBuffed) && Eq(SkillBase, o.SkillBase) + && Eq(AttrRanks, o.AttrRanks) && Eq(AttrInit, o.AttrInit) && Eq(AttrXpSpent, o.AttrXpSpent) + && Eq(AttrBuffed, o.AttrBuffed) && Eq(AttrBase, o.AttrBase) + && Eq(VitalRanks, o.VitalRanks) && Eq(VitalInit, o.VitalInit) && Eq(VitalXpSpent, o.VitalXpSpent) + && Eq(VitalBuffed, o.VitalBuffed) && Eq(VitalBase, o.VitalBase) + && EqN(BuffSpell, o.BuffSpell, BuffCount) && EqN(BuffExpiry, o.BuffExpiry, BuffCount) + && EqN(BuffType, o.BuffType, BuffCount) && EqN(BuffKey, o.BuffKey, BuffCount) + && EqN(BuffVal, o.BuffVal, BuffCount) && EqN(BuffCategory, o.BuffCategory, BuffCount); + } + + private static bool Eq<T>(T[] a, T[] b) where T : IEquatable<T> => a.AsSpan().SequenceEqual(b); + + private static bool EqN<T>(T[] a, T[] b, int n) where T : IEquatable<T> => a.AsSpan(0, n).SequenceEqual(b.AsSpan(0, n)); +} + +internal static class PlayerProgressHooks +{ + private const int RefreshMs = 500; + private const int WantWindowMs = 2000; + + // StatMod type flags (ACE EnchantmentTypeFlags) that mark a buff on a stat. + internal const uint ModAttribute = 0x1, ModSecondAttribute = 0x2, ModSkill = 0x10; + internal const uint ModMultiplicative = 0x4000, ModAdditive = 0x8000, ModVitae = 0x800000; + private const uint ModAnyStat = ModAttribute | ModSecondAttribute | ModSkill; + + private static long _wantedUntilMs; + private static long _nextReadMs; + private static int _version; + private static PlayerProgress? _published; + + // Main thread only: the work buffer and the enchantment copy's scratch. + private static readonly PlayerProgress Work = new(); + private const int EnchScratch = 1024; + private static readonly uint[] ScratchSpell = new uint[EnchScratch]; + private static readonly double[] ScratchExpiry = new double[EnchScratch]; + private static readonly uint[] ScratchType = new uint[EnchScratch]; + private static readonly uint[] ScratchKey = new uint[EnchScratch]; + private static readonly float[] ScratchVal = new float[EnchScratch]; + private static readonly uint[] ScratchCategory = new uint[EnchScratch]; + + /// <summary>A reader wants fresh data for the next 2 s. Any thread; call it each frame the panel draws.</summary> + public static void Want() => + Volatile.Write(ref _wantedUntilMs, Environment.TickCount64 + WantWindowMs); + + /// <summary>Read again at the next main-thread tick (after a raise). Any thread.</summary> + public static void RefreshSoon() => Volatile.Write(ref _nextReadMs, 0); + + /// <summary>The last published read, or null. Never written again once published. Any thread.</summary> + public static PlayerProgress? Current => Volatile.Read(ref _published); + + /// <summary> + /// AC's main thread (MainThreadSnapshots.Tick, only while the player is live). + /// Reads when wanted and due; publishes only a changed result. + /// </summary> + internal static void Prefetch() + { + if (!MainThreadGuard.IsOnMainThread()) + return; + long now = Environment.TickCount64; + if (now > Volatile.Read(ref _wantedUntilMs) || now < Volatile.Read(ref _nextReadMs)) + return; + Volatile.Write(ref _nextReadMs, now + RefreshMs); + + if (!ClientObjectHooks.ReadPlayerProgressLive(Work)) + return; + CopyStatBuffs(Work); + + PlayerProgress? current = Volatile.Read(ref _published); + if (current != null && current.SameAs(Work)) + return; + var snapshot = new PlayerProgress(); + snapshot.CopyFrom(Work); + snapshot.Version = ++_version; + Volatile.Write(ref _published, snapshot); + } + + /// <summary>The player's enchantments that change a skill, attribute or vital (not vitae).</summary> + private static void CopyStatBuffs(PlayerProgress dst) + { + dst.BuffCount = 0; + int n = EnchantmentHooks.CopyPlayerStatMods(ScratchSpell, ScratchExpiry, ScratchType, ScratchKey, ScratchVal, ScratchCategory); + for (int i = 0; i < n && dst.BuffCount < PlayerProgress.MaxBuffs; i++) + { + uint type = ScratchType[i]; + if ((type & ModAnyStat) == 0 || (type & ModVitae) != 0) + continue; + int k = dst.BuffCount++; + dst.BuffSpell[k] = ScratchSpell[i]; + dst.BuffExpiry[k] = ScratchExpiry[i]; + dst.BuffType[k] = type; + dst.BuffKey[k] = ScratchKey[i]; + dst.BuffVal[k] = ScratchVal[i]; + dst.BuffCategory[k] = ScratchCategory[i]; + } + } +} diff --git a/src/RynthCore.Engine/Compatibility/PlayerTrade.cs b/src/RynthCore.Engine/Compatibility/PlayerTrade.cs new file mode 100644 index 0000000..ac7f2e6 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/PlayerTrade.cs @@ -0,0 +1,480 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/PlayerTrade.cs +// +// Player-to-player trade (plugin API v72): the state of the trade window, read +// from the server's trade GameEvents, and the trade actions, sent through the +// retail client's own CM_Trade / ClientTradeSystem functions. +// +// STATE UIQueueManager::ProcessNetBlobData (SmartBoxHooks' existing game-event +// detour, AC's main thread) hands every trade GameEvent to OnGameEvent +// before AC handles it. No new hook. Payloads (event type at +0, payload +// from +4), checked against ACE's writers (GameEvent*Trade.cs) and the +// client's CM_Trade::DispatchUI_Recv_* readers: +// 0x01FD RegisterTrade u32 initiator, u32 partner, f64 stamp +// 0x01FE OpenTrade u32 objectId (ACE never sends it) +// 0x01FF CloseTrade u32 EndTradeReason (1 normal, 2 combat, 0x51 cancelled) +// 0x0200 AddToTrade u32 item, u32 side (1 you, 2 partner), u32 slot +// 0x0201 RemoveFromTrade u32 item, u32 side (ACE never sends it) +// 0x0202 AcceptTrade u32 who accepted +// 0x0203 DeclineTrade u32 who declined +// 0x0205 ResetTrade u32 who reset (both windows empty; also sent +// to both sides after a completed trade) +// 0x0207 TradeFailure u32 item, u32 WeenieError +// 0x0208 ClearTradeAcceptance (none) +// plus WeenieError 0x0529 TradeComplete (counted). ACE sends the second +// party RegisterTrade(initiator, initiator), so the partner is "the +// initiator unless that's you, else the partner field". +// +// The state lives in fixed arrays under one lock: the detour never +// allocates and never calls a plugin. Plugins read a copy on their pump +// (GetTradeState / GetTradeItems) and compare Generation / Sequence / +// counters between reads; nothing is queued for them. +// +// ACTIONS Bound by byte pattern (tools/pe_pattern.py CHECK), VAs from the +// Chorizite acclient map (+0x401000), verified on both acclient copies: +// CM_Trade::Event_OpenTradeNegotiations(ulong) 0x006AE260 0x01F6 +// CM_Trade::Event_AddToTrade(ulong item, ulong loc) 0x006AE030 0x01F8 +// CM_Trade::Event_ResetTrade() 0x006AE330 0x0204 +// CM_Trade::Event_CloseTradeNegotiations() 0x006AE140 0x01F7 +// ClientTradeSystem::AcceptTrade() (thiscall) 0x0056E7A0 0x01FA +// ClientTradeSystem::DeclineTrade() (thiscall) 0x0056E7C0 0x01FB +// The Event_* functions are cdecl, return bool, and only build and send +// the game action (the same generated shape as Event_GetAndWieldItem). +// Accept goes through ClientTradeSystem because CM_Trade::Event_AcceptTrade +// packs the client's own Trade object (ClientTradeSystem+0x10); the wrapper +// also sets that object's accepted flag (+0x38) the way the trade window's +// Accept button does. Decline clears it the same way. The ClientTradeSystem +// instance is the global ClientTradeSystem::GetTradeSystem returns +// (0x0087174C), resolved by code xref. +// +// Every action runs on AC's main thread: from any other thread it is queued +// on AcMainThreadQueue (ActionKind.Trade) and the drain calls back in here. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; + +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class PlayerTrade +{ + // ── Actions ───────────────────────────────────────────────────────────── + + internal enum TradeOp : uint + { + Open = 1, + Add = 2, + Reset = 3, + Accept = 4, + Decline = 5, + Close = 6, + } + + private const int EventOpenTradeNegotiationsVa = 0x006AE260; + private const int EventAddToTradeVa = 0x006AE030; + private const int EventResetTradeVa = 0x006AE330; + private const int EventCloseTradeNegotiationsVa = 0x006AE140; + private const int TradeSystemAcceptTradeVa = 0x0056E7A0; + private const int TradeSystemDeclineTradeVa = 0x0056E7C0; + private const int TradeSystemGlobalVa = 0x0087174C; + + // The four CM_Trade events share one generated template (see Event_GiveObjectRequest in + // ClientHelperHooks); what tells them apart is the arg-block size after the first inner + // call (+0x08 one arg, +0x0C two, +0x04 none) and the opcode immediate at the end, so the + // patterns run to that byte. Generated + verified unique via pe_pattern.py GEN against both + // acclient copies (C:\Turbine and C:\Games\RynthCore\AcClient). + private static readonly byte?[] PatEventOpenTradeNegotiations = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0xF6 ]; + private static readonly byte?[] PatEventAddToTrade = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0xF8 ]; + private static readonly byte?[] PatEventResetTrade = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0xC7, 0x02, 0x04 ]; + private static readonly byte?[] PatEventCloseTradeNegotiations = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0xC7, 0x02, 0xF7 ]; + // ClientTradeSystem::AcceptTrade: mov eax,[ecx+10h]; mov dword [eax+38h],1; mov ecx,[ecx+10h]; + // push ecx; call Event_AcceptTrade; pop ecx; ret. DeclineTrade: the same flag write with 0, + // then jmp Event_DeclineTrade. Unique at 8 bytes; run on to the call/jmp for margin. + private static readonly byte?[] PatTradeSystemAcceptTrade = [ 0x8B, 0x41, 0x10, 0xC7, 0x40, 0x38, 0x01, 0x00, 0x00, 0x00, 0x8B, 0x49, 0x10, 0x51, 0xE8, null, null, null, null, 0x59, 0xC3 ]; + private static readonly byte?[] PatTradeSystemDeclineTrade = [ 0x8B, 0x41, 0x10, 0xC7, 0x40, 0x38, 0x00, 0x00, 0x00, 0x00, 0xE9 ]; + // mov [ClientTradeSystem::s_pTradeSystem], esi; call [import]; xor edi, edi (operand at +2). + private static readonly byte?[] PatXrefTradeSystem = [ 0x89, 0x35, null, null, null, null, 0xFF, 0x15, 0xFC, 0x31, 0x79, 0x00, 0x33, 0xFF ]; + + private static delegate* unmanaged[Cdecl]<uint, byte> _eventOpenTradeNegotiations; + private static delegate* unmanaged[Cdecl]<uint, uint, byte> _eventAddToTrade; + private static delegate* unmanaged[Cdecl]<byte> _eventResetTrade; + private static delegate* unmanaged[Cdecl]<byte> _eventCloseTradeNegotiations; + private static delegate* unmanaged[Thiscall]<IntPtr, void> _tradeSystemAcceptTrade; + private static delegate* unmanaged[Thiscall]<IntPtr, void> _tradeSystemDeclineTrade; + private static int _tradeSystemAddr; + + public static bool HasOpen => _eventOpenTradeNegotiations != null; + public static bool HasAdd => _eventAddToTrade != null; + public static bool HasReset => _eventResetTrade != null; + public static bool HasClose => _eventCloseTradeNegotiations != null; + public static bool HasAccept => _tradeSystemAcceptTrade != null; + public static bool HasDecline => _tradeSystemDeclineTrade != null; + public static bool ActionsAvailable => HasOpen && HasAdd && HasReset && HasClose && HasAccept && HasDecline; + + /// <summary>Bind the trade functions. Called from ClientHelperHooks.Probe (engine init).</summary> + public static void Probe(AcClientTextSection text) + { + _eventOpenTradeNegotiations = (delegate* unmanaged[Cdecl]<uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.Event_OpenTradeNegotiations", PatEventOpenTradeNegotiations, EventOpenTradeNegotiationsVa)); + _eventAddToTrade = (delegate* unmanaged[Cdecl]<uint, uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.Event_AddToTrade", PatEventAddToTrade, EventAddToTradeVa)); + _eventResetTrade = (delegate* unmanaged[Cdecl]<byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.Event_ResetTrade", PatEventResetTrade, EventResetTradeVa)); + _eventCloseTradeNegotiations = (delegate* unmanaged[Cdecl]<byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.Event_CloseTradeNegotiations", PatEventCloseTradeNegotiations, EventCloseTradeNegotiationsVa)); + _tradeSystemAcceptTrade = (delegate* unmanaged[Thiscall]<IntPtr, void>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.ClientTradeSystem_AcceptTrade", PatTradeSystemAcceptTrade, TradeSystemAcceptTradeVa)); + _tradeSystemDeclineTrade = (delegate* unmanaged[Thiscall]<IntPtr, void>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.ClientTradeSystem_DeclineTrade", PatTradeSystemDeclineTrade, TradeSystemDeclineTradeVa)); + HookResolver.ResolveResult system = HookResolver.ResolveData(text, "PlayerTrade.ClientTradeSystem", PatXrefTradeSystem, 2, TradeSystemGlobalVa); + _tradeSystemAddr = system.Source == HookResolver.ResolveSource.PatternScan ? system.Address.ToInt32() : 0; + if (_tradeSystemAddr == 0) + { + // Without the instance Accept / Decline can't run; don't offer them. + _tradeSystemAcceptTrade = null; + _tradeSystemDeclineTrade = null; + } + RynthLog.Verbose($"Compat: player trade {(ActionsAvailable ? "ready" : "partly bound")} (open={HasOpen} add={HasAdd} reset={HasReset} close={HasClose} accept={HasAccept} decline={HasDecline})."); + } + + // Fail closed: these send game actions, so only a unique pattern match binds. The resolver's + // fixed-VA fallback (a pattern miss on some other client build) leaves the action unavailable. + private static void* ResolveFn(HookResolver.ResolveResult r) => + r.Success && r.Source == HookResolver.ResolveSource.PatternScan ? (void*)r.Address : null; + + /// <summary>Ask <paramref name="targetId"/> to trade (0x01F6 OpenTradeNegotiations).</summary> + public static bool Open(uint targetId) + { + if (!MainThreadGuard.IsOnMainThread()) + return _eventOpenTradeNegotiations != null && targetId != 0 + && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Open, targetId, 0); + if (_eventOpenTradeNegotiations == null || targetId == 0) return false; + byte rv = _eventOpenTradeNegotiations(targetId); + LogAction($"Event_OpenTradeNegotiations target=0x{targetId:X8} rv={rv}"); + return rv != 0; + } + + /// <summary>Put one of your items in the trade window (0x01F8 AddToTrade). slot 0 = next free.</summary> + public static bool Add(uint itemId, uint slot) + { + if (!MainThreadGuard.IsOnMainThread()) + return _eventAddToTrade != null && itemId != 0 + && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Add, itemId, slot); + if (_eventAddToTrade == null || itemId == 0) return false; + byte rv = _eventAddToTrade(itemId, slot); + LogAction($"Event_AddToTrade item=0x{itemId:X8} slot={slot} rv={rv}"); + return rv != 0; + } + + /// <summary>Empty both sides of the window (0x0204 ResetTrade).</summary> + public static bool Reset() + { + if (!MainThreadGuard.IsOnMainThread()) + return _eventResetTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Reset, 0, 0); + if (_eventResetTrade == null) return false; + byte rv = _eventResetTrade(); + LogAction($"Event_ResetTrade rv={rv}"); + return rv != 0; + } + + /// <summary>Close the trade (0x01F7 CloseTradeNegotiations).</summary> + public static bool Close() + { + if (!MainThreadGuard.IsOnMainThread()) + return _eventCloseTradeNegotiations != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Close, 0, 0); + if (_eventCloseTradeNegotiations == null) return false; + byte rv = _eventCloseTradeNegotiations(); + LogAction($"Event_CloseTradeNegotiations rv={rv}"); + return rv != 0; + } + + /// <summary>Accept the trade as it stands (the window's Accept button, 0x01FA AcceptTrade).</summary> + public static bool Accept() + { + if (!MainThreadGuard.IsOnMainThread()) + return _tradeSystemAcceptTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Accept, 0, 0); + if (_tradeSystemAcceptTrade == null) return false; + IntPtr system = TradeSystemWithTrade(); + if (system == IntPtr.Zero) { LogAction("AcceptTrade skipped: no ClientTradeSystem / Trade object"); return false; } + _tradeSystemAcceptTrade(system); + LogAction($"ClientTradeSystem::AcceptTrade this=0x{system.ToInt32():X8}"); + return true; + } + + /// <summary>Withdraw your acceptance (the window's Decline button, 0x01FB DeclineTrade).</summary> + public static bool Decline() + { + if (!MainThreadGuard.IsOnMainThread()) + return _tradeSystemDeclineTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Decline, 0, 0); + if (_tradeSystemDeclineTrade == null) return false; + IntPtr system = TradeSystemWithTrade(); + if (system == IntPtr.Zero) { LogAction("DeclineTrade skipped: no ClientTradeSystem / Trade object"); return false; } + _tradeSystemDeclineTrade(system); + LogAction($"ClientTradeSystem::DeclineTrade this=0x{system.ToInt32():X8}"); + return true; + } + + /// <summary>AcMainThreadQueue drain (main thread): run a queued trade action.</summary> + public static void RunQueued(uint op, uint a, uint b) + { + switch ((TradeOp)op) + { + case TradeOp.Open: Open(a); break; + case TradeOp.Add: Add(a, b); break; + case TradeOp.Reset: Reset(); break; + case TradeOp.Accept: Accept(); break; + case TradeOp.Decline: Decline(); break; + case TradeOp.Close: Close(); break; + } + } + + /// <summary>The ClientTradeSystem, when it and its Trade object (+0x10) exist; else zero.</summary> + private static IntPtr TradeSystemWithTrade() + { + if (_tradeSystemAddr == 0) return IntPtr.Zero; + IntPtr system = Marshal.ReadIntPtr(new IntPtr(_tradeSystemAddr)); + if (system == IntPtr.Zero) return IntPtr.Zero; + IntPtr trade = Marshal.ReadIntPtr(IntPtr.Add(system, 0x10)); + return trade == IntPtr.Zero ? IntPtr.Zero : system; + } + + private static int _actionLogCount; + + private static void LogAction(string message) + { + if (_actionLogCount >= 200) return; + _actionLogCount++; + RynthLog.Compat($"Trade: {message}"); + } + + // ── State ─────────────────────────────────────────────────────────────── + + private const int MaxItemsPerSide = 256; + private const uint TradeSideSelf = 1; + private const uint TradeSidePartner = 2; + + private static readonly object _lock = new(); + private static readonly uint[] _selfItems = new uint[MaxItemsPerSide]; + private static readonly uint[] _partnerItems = new uint[MaxItemsPerSide]; + private static int _selfCount, _partnerCount; + private static bool _open, _selfAccepted, _partnerAccepted; + private static uint _generation, _sequence, _partnerId, _initiatorId, _lastEventType; + private static uint _failureCount, _failureItem, _failureReason; + private static uint _closeReason, _acceptedBy, _declinedBy, _resetBy; + private static uint _completedCount, _partnerAcceptCount; + private static int _eventLogCount; + + /// <summary>True for the GameEvent types this file tracks.</summary> + public static bool IsTradeEvent(uint eventType) => eventType >= 0x01FD && eventType <= 0x0208; + + /// <summary> + /// A trade GameEvent (SmartBoxHooks.ParseGameEvent, AC's main thread, before AC handles it). + /// <paramref name="size"/> counts the 4-byte event type. No allocation on the state path. + /// </summary> + public static void OnGameEvent(uint eventType, IntPtr data, uint size) + { + uint a = size >= 8 ? Rd(data, 4) : 0; + uint b = size >= 12 ? Rd(data, 8) : 0; + uint self = ClientHelperHooks.GetPlayerId(); + + lock (_lock) + { + switch (eventType) + { + case 0x01FD: // RegisterTrade: initiator, partner, stamp + if (size < 12) return; + _open = true; + _generation++; + _initiatorId = a; + _partnerId = a != 0 && a != self ? a : b; + ClearWindow(); + _closeReason = 0; + break; + + case 0x01FE: // OpenTrade: objectId + if (!_open) + { + _open = true; + _generation++; + ClearWindow(); + _closeReason = 0; + } + if (_partnerId == 0 && a != 0 && a != self) + _partnerId = a; + break; + + case 0x01FF: // CloseTrade: EndTradeReason + _open = false; + _closeReason = a; + _partnerId = 0; + _initiatorId = 0; + ClearWindow(); + break; + + case 0x0200: // AddToTrade: item, side, slot + if (size < 12 || a == 0) return; + if (b == TradeSidePartner) AddUnique(_partnerItems, ref _partnerCount, a); + else AddUnique(_selfItems, ref _selfCount, a); + // The server clears both acceptances whenever the window changes. + _selfAccepted = _partnerAccepted = false; + break; + + case 0x0201: // RemoveFromTrade: item, side + if (a == 0) return; + if (b != TradeSideSelf) RemoveItem(_partnerItems, ref _partnerCount, a); + if (b != TradeSidePartner) RemoveItem(_selfItems, ref _selfCount, a); + _selfAccepted = _partnerAccepted = false; + break; + + case 0x0202: // AcceptTrade: who + _acceptedBy = a; + // Who is "you": the player id when known, else "not the partner". + if (self != 0 ? a != self : (a != 0 && a == _partnerId)) + { + _partnerAccepted = true; + _partnerAcceptCount++; + } + else + { + _selfAccepted = true; + } + break; + + case 0x0203: // DeclineTrade: who + _declinedBy = a; + _selfAccepted = _partnerAccepted = false; + break; + + case 0x0205: // ResetTrade: who + _resetBy = a; + ClearWindow(); + break; + + case 0x0207: // TradeFailure: item, WeenieError + _failureCount++; + _failureItem = a; + _failureReason = b; + if (a != 0) RemoveItem(_selfItems, ref _selfCount, a); + break; + + case 0x0208: // ClearTradeAcceptance + _selfAccepted = _partnerAccepted = false; + break; + + default: + return; + } + _sequence++; + _lastEventType = eventType; + } + + if (_eventLogCount < 200) + { + _eventLogCount++; + RynthLog.Compat($"Trade: evt=0x{eventType:X4} a=0x{a:X8} b=0x{b:X8} len={size} partner=0x{_partnerId:X8} you={_selfCount} them={_partnerCount}"); + } + } + + /// <summary>WeenieError 0x0529 TradeComplete (AC's main thread).</summary> + public static void OnTradeComplete() + { + lock (_lock) + { + _completedCount++; + _sequence++; + } + if (_eventLogCount < 200) + { + _eventLogCount++; + RynthLog.Compat("Trade: complete (WeenieError 0x0529)"); + } + } + + private static void ClearWindow() + { + _selfCount = 0; + _partnerCount = 0; + _selfAccepted = false; + _partnerAccepted = false; + } + + private static void AddUnique(uint[] list, ref int count, uint id) + { + for (int i = 0; i < count; i++) + if (list[i] == id) return; + if (count < list.Length) list[count++] = id; + } + + private static void RemoveItem(uint[] list, ref int count, uint id) + { + for (int i = 0; i < count; i++) + { + if (list[i] != id) continue; + for (int j = i + 1; j < count; j++) list[j - 1] = list[j]; + count--; + return; + } + } + + private static uint Rd(IntPtr data, int offset) => unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, offset))); + + /// <summary> + /// v72 GetTradeState: copy the state into <paramref name="state"/> (up to state->Size bytes). + /// Returns the bytes written, 0 on a bad argument. Any thread. + /// </summary> + public static int GetState(TradeStateNative* state) + { + if (state == null) return 0; + uint want = state->Size; + if (want < 8) return 0; + + TradeStateNative s = default; + lock (_lock) + { + uint flags = 0; + if (_open) flags |= TradeStateFlags.Open; + if (_selfAccepted) flags |= TradeStateFlags.YouAccepted; + if (_partnerAccepted) flags |= TradeStateFlags.PartnerAccepted; + s.Flags = flags; + s.Generation = _generation; + s.Sequence = _sequence; + s.PartnerId = _partnerId; + s.InitiatorId = _initiatorId; + s.SelfItemCount = _selfCount; + s.PartnerItemCount = _partnerCount; + s.LastEventType = _lastEventType; + s.FailureCount = _failureCount; + s.LastFailureItemId = _failureItem; + s.LastFailureReason = _failureReason; + s.LastCloseReason = _closeReason; + s.LastAcceptedBy = _acceptedBy; + s.LastDeclinedBy = _declinedBy; + s.LastResetBy = _resetBy; + s.CompletedCount = _completedCount; + s.PartnerAcceptCount = _partnerAcceptCount; + } + if (SmartBoxHooks.IsGameEventHookInstalled) s.Flags |= TradeStateFlags.Watching; + if (ActionsAvailable) s.Flags |= TradeStateFlags.ActionsAvailable; + + uint n = Math.Min(want, (uint)sizeof(TradeStateNative)); + s.Size = n; + Buffer.MemoryCopy(&s, state, want, n); + return (int)n; + } + + /// <summary> + /// v72 GetTradeItems: copy up to <paramref name="capacity"/> item ids from one side + /// (1 = yours, 2 = the partner's) and return that side's total count; -1 for a bad side. + /// </summary> + public static int GetItems(int side, uint* buffer, int capacity) + { + if (side != (int)TradeSideSelf && side != (int)TradeSidePartner) return -1; + lock (_lock) + { + uint[] list = side == (int)TradeSideSelf ? _selfItems : _partnerItems; + int count = side == (int)TradeSideSelf ? _selfCount : _partnerCount; + if (buffer != null && capacity > 0) + { + int n = Math.Min(capacity, count); + for (int i = 0; i < n; i++) buffer[i] = list[i]; + } + return count; + } + } +} diff --git a/src/RynthCore.Engine/Compatibility/PlayerTraining.cs b/src/RynthCore.Engine/Compatibility/PlayerTraining.cs new file mode 100644 index 0000000..947c260 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/PlayerTraining.cs @@ -0,0 +1,145 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/PlayerTraining.cs +// +// Spending unassigned XP on an attribute, a vital or a skill (the Skills panel, +// docs/IMGUI_SKILLS.md), through the retail client's own senders, bound the +// way PlayerTrade binds CM_Trade: +// +// CM_Train::Event_TrainAttribute(atype, xp) 0x006A8E90 0x0045 RaiseAttribute +// CM_Train::Event_TrainAttribute2nd(vtype, xp) 0x006A8FA0 0x0044 RaiseVital +// CM_Train::Event_TrainSkill(stype, xp) 0x006A90B0 0x0046 RaiseSkill +// CM_Train::Event_TrainSkillAdvancementClass(stype, credits) +// 0x006A91C0 0x0047 TrainSkill +// +// The last is what the retail skills window's train dialog sends +// (gmSkillUI::TrainSkillDialogCallback 0x0049C480 calls it with the skill and +// the credits). ACE's handler (Player.HandleActionTrainSkill) only trains an +// untrained skill, and only when the credits sent equal the portal SkillTable's +// TrainedCost and you have them. Specializing has no game action on ACE: it +// takes the skill's Gem of Enlightenment (SkillAlterationDevice). +// +// bool __cdecl (Chorizite acclient map); each only builds and sends the game +// action, in the generated CM_* sender shape Event_AddToTrade has (two +// arguments: arg block +0x0C), so the patterns run to the opcode immediate. +// Cut with tools/pe_pattern.py GEN and unique on both acclient copies +// (C:\Turbine and C:\Games\RynthCore\AcClient). Bound only by a unique pattern +// match: a miss leaves raising unavailable, never a fixed-VA call. +// +// The server (ACE Player.HandleActionRaise*) checks the XP against unassigned XP +// and the XP left to the top rank, and raises as many ranks as it covers. +// Vitals are addressed by their maximum: 1 health, 3 stamina, 5 mana. +// +// Every call runs on AC's main thread: off it (or with defer) the request goes +// through AcMainThreadQueue (ActionKind.Train) and the drain calls back in. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class PlayerTraining +{ + internal enum TrainKind : uint + { + Attribute = 1, + Vital = 2, + Skill = 3, + // Untrained -> trained with skill credits (the amount is credits, not XP). + TrainWithCredits = 4, + } + + private const int EventTrainAttributeVa = 0x006A8E90; + private const int EventTrainAttribute2ndVa = 0x006A8FA0; + private const int EventTrainSkillVa = 0x006A90B0; + private const int EventTrainSkillAdvancementClassVa = 0x006A91C0; + + // The CM_* generated sender template (see PlayerTrade); the last byte is the opcode. + private static readonly byte?[] PatEventTrainAttribute = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x45 ]; + private static readonly byte?[] PatEventTrainAttribute2nd = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x44 ]; + private static readonly byte?[] PatEventTrainSkill = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x46 ]; + private static readonly byte?[] PatEventTrainSkillAdvancementClass = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x47 ]; + + private static delegate* unmanaged[Cdecl]<uint, uint, byte> _eventTrainAttribute; + private static delegate* unmanaged[Cdecl]<uint, uint, byte> _eventTrainAttribute2nd; + private static delegate* unmanaged[Cdecl]<uint, uint, byte> _eventTrainSkill; + private static delegate* unmanaged[Cdecl]<uint, uint, byte> _eventTrainSkillAdvancementClass; + + /// <summary>True when all three raise senders are bound. Any thread.</summary> + public static bool Available => _eventTrainAttribute != null && _eventTrainAttribute2nd != null && _eventTrainSkill != null; + + /// <summary>True when the train-with-credits sender is bound. Any thread.</summary> + public static bool TrainAvailable => _eventTrainSkillAdvancementClass != null; + + /// <summary>Bind the senders. Called from ClientHelperHooks.Probe (engine init).</summary> + public static void Probe(AcClientTextSection text) + { + _eventTrainAttribute = (delegate* unmanaged[Cdecl]<uint, uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTraining.Event_TrainAttribute", PatEventTrainAttribute, EventTrainAttributeVa)); + _eventTrainAttribute2nd = (delegate* unmanaged[Cdecl]<uint, uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTraining.Event_TrainAttribute2nd", PatEventTrainAttribute2nd, EventTrainAttribute2ndVa)); + _eventTrainSkill = (delegate* unmanaged[Cdecl]<uint, uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTraining.Event_TrainSkill", PatEventTrainSkill, EventTrainSkillVa)); + _eventTrainSkillAdvancementClass = (delegate* unmanaged[Cdecl]<uint, uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTraining.Event_TrainSkillAdvancementClass", PatEventTrainSkillAdvancementClass, EventTrainSkillAdvancementClassVa)); + RynthLog.Verbose($"Compat: raise senders {(Available ? "ready" : "partly bound")} (attribute={_eventTrainAttribute != null} vital={_eventTrainAttribute2nd != null} skill={_eventTrainSkill != null} train={_eventTrainSkillAdvancementClass != null})."); + } + + // Fail closed: these send game actions, so only a unique pattern match binds. + private static void* ResolveFn(HookResolver.ResolveResult r) => + r.Success && r.Source == HookResolver.ResolveSource.PatternScan ? (void*)r.Address : null; + + private static bool Bound(TrainKind kind) => kind switch + { + TrainKind.Attribute => _eventTrainAttribute != null, + TrainKind.Vital => _eventTrainAttribute2nd != null, + TrainKind.Skill => _eventTrainSkill != null, + TrainKind.TrainWithCredits => _eventTrainSkillAdvancementClass != null, + _ => false, + }; + + private static bool ValidTarget(TrainKind kind, uint stype) => kind switch + { + TrainKind.Attribute => stype >= 1 && stype <= 6, + TrainKind.Vital => stype is 1 or 3 or 5, + TrainKind.Skill or TrainKind.TrainWithCredits => stype >= 1 && stype <= 54, + _ => false, + }; + + /// <summary> + /// Spend <paramref name="xp"/> unassigned XP on one attribute (1..6), vital maximum + /// (1 health, 3 stamina, 5 mana) or skill. Off AC's main thread, or with + /// <paramref name="defer"/> (a UI click inside the ImGui frame), it is queued and sent + /// from the drain. Returns false when unbound, the target is invalid or the queue is full. + /// With TrainKind.TrainWithCredits the amount is skill credits (see <see cref="TrainSkill"/>). + /// </summary> + public static bool Raise(TrainKind kind, uint stype, uint xp, bool defer = false) + { + if (!Bound(kind) || !ValidTarget(kind, stype) || xp == 0) + return false; + if (defer || !MainThreadGuard.IsOnMainThread()) + return AcMainThreadQueue.EnqueueTrain((uint)kind, stype, xp); + + byte rv = kind switch + { + TrainKind.Attribute => _eventTrainAttribute(stype, xp), + TrainKind.Vital => _eventTrainAttribute2nd(stype, xp), + TrainKind.TrainWithCredits => _eventTrainSkillAdvancementClass(stype, xp), + _ => _eventTrainSkill(stype, xp), + }; + RynthLog.Compat(kind == TrainKind.TrainWithCredits + ? $"PlayerTraining: train skill {stype} with {xp} credits rv={rv}" + : $"PlayerTraining: raise {kind} {stype} with {xp:N0} XP rv={rv}"); + PlayerProgressHooks.RefreshSoon(); + return rv != 0; + } + + /// <summary> + /// Train an untrained skill with <paramref name="credits"/> skill credits (0x0047 TrainSkill). + /// The server wants exactly the portal SkillTable's TrainedCost. Same threading as Raise. + /// </summary> + public static bool TrainSkill(uint stype, uint credits, bool defer = false) => + Raise(TrainKind.TrainWithCredits, stype, credits, defer); + + /// <summary>AcMainThreadQueue drain (AC's main thread): A = TrainKind, B = stype, C = XP.</summary> + internal static void RunQueued(uint kind, uint stype, uint xp) + { + try { Raise((TrainKind)kind, stype, xp); } + catch (Exception ex) { RynthLog.Compat($"PlayerTraining: queued raise failed - {ex.Message}"); } + } +} diff --git a/src/RynthCore.Engine/Compatibility/PlayerVitalsHooks.cs b/src/RynthCore.Engine/Compatibility/PlayerVitalsHooks.cs index a958d49..0a764fa 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerVitalsHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerVitalsHooks.cs @@ -40,6 +40,16 @@ internal static class PlayerVitalsHooks internal static void ResetSession() { KnownPlayerQualitiesPtr = IntPtr.Zero; + // The off-thread base-vitals copy belongs to the old character. + lock (CacheLock) + { + _baseVitalsHp = _baseVitalsStam = _baseVitalsMana = 0; + _baseVitalsOwner = IntPtr.Zero; + // The vitals snapshot is the old character's too. Kept, the next character showed + // its health until a vital changed, and the login seed's "highest max seen" rule + // kept the old character's larger maximums for good (2026-10-01). + _snapshot = default; + } // Creature health is keyed by object id — ids don't survive the // session, and without this clear the 1024-entry cap filled over a // long session and every NEW creature was silently never tracked. @@ -326,6 +336,80 @@ internal static class PlayerVitalsHooks if (ptr == IntPtr.Zero) return false; + // Off AC's main thread (host GetPlayerBaseVitalsFn on the pump: RynthAi meta + // getcharvital_base, RynthLua): serve the main-thread copy. Calling + // CACQualities::InqAttribute2nd here walked the player's attribute table + // while the main thread can rebuild it (the 0x00416C86 class). Base max only + // changes when XP is spent or gear/augs change, so ~1 s old is fine. The + // copy must belong to the current qualities object (a relog swaps it). + if (!MainThreadGuard.IsOnMainThread()) + { + lock (CacheLock) + { + if (_baseVitalsOwner != ptr) + return false; + baseMaxHp = _baseVitalsHp; + baseMaxStam = _baseVitalsStam; + baseMaxMana = _baseVitalsMana; + } + return baseMaxHp > 0 || baseMaxStam > 0 || baseMaxMana > 0; + } + + return TryReadPlayerBaseVitalsLive(ptr, out baseMaxHp, out baseMaxStam, out baseMaxMana); + } + + // Main-thread base-vitals copy for the off-thread path above. Separate from the + // vital snapshot and from ClientObjectHooks.PrefetchPlayerStats on purpose: it + // must not change either one's semantics. + private static uint _baseVitalsHp, _baseVitalsStam, _baseVitalsMana; + private static IntPtr _baseVitalsOwner; + private static long _nextBaseVitalsPrefetchMs; + private const int BaseVitalsPrefetchIntervalMs = 1000; + + /// <summary> + /// Main thread only (MainThreadSnapshots.Tick). Refreshes the base-vitals copy + /// about once a second from the live qualities table. + /// </summary> + internal static void PrefetchBaseVitals() + { + if (!MainThreadGuard.IsOnMainThread() || _inqAttribute2ndStruct == null) + return; + IntPtr ptr = KnownPlayerQualitiesPtr; + if (ptr == IntPtr.Zero) + return; + + // A new qualities object (login / relog / reseed) is read within ~250 ms + // rather than waiting out the 1 s refresh, so off-thread callers see values + // about as soon as they did when the read was live. + long now = Environment.TickCount64; + if (now < _nextBaseVitalsPrefetchMs) + return; + bool ownerCurrent; + lock (CacheLock) ownerCurrent = _baseVitalsOwner == ptr; + _nextBaseVitalsPrefetchMs = now + (ownerCurrent ? BaseVitalsPrefetchIntervalMs : 250); + + if (!ClientObjectHooks.IsCacQualitiesObject(ptr)) + return; + + if (TryReadPlayerBaseVitalsLive(ptr, out uint hp, out uint stam, out uint mana)) + { + lock (CacheLock) + { + _baseVitalsHp = hp; + _baseVitalsStam = stam; + _baseVitalsMana = mana; + _baseVitalsOwner = ptr; + } + } + } + + // The live read (unchanged from the pre-2026-09-30 body). MAIN THREAD ONLY. + private static unsafe bool TryReadPlayerBaseVitalsLive(IntPtr ptr, out uint baseMaxHp, out uint baseMaxStam, out uint baseMaxMana) + { + baseMaxHp = baseMaxStam = baseMaxMana = 0; + if (!MainThreadGuard.IsOnMainThread() || _inqAttribute2ndStruct == null || ptr == IntPtr.Zero) + return false; + try { SecondaryAttributeNative v = default; diff --git a/src/RynthCore.Engine/Compatibility/PowerbarHooks.cs b/src/RynthCore.Engine/Compatibility/PowerbarHooks.cs index cf5e019..4780641 100644 --- a/src/RynthCore.Engine/Compatibility/PowerbarHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PowerbarHooks.cs @@ -115,6 +115,11 @@ internal static class PowerbarHooks public static void Initialize() { + // "Hide retail vitals" rides this init step (EntryPoint's list of steps is + // not edited for it); it resolves and hooks on its own and never throws. + try { RetailVitalsHooks.Initialize(); } + catch (Exception ex) { RynthLog.Compat($"PowerbarHooks: RetailVitalsHooks.Initialize threw {ex.GetType().Name}: {ex.Message}"); } + if (_hookInstalled) return; diff --git a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs index cd8647f..a537b87 100644 --- a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs @@ -290,11 +290,31 @@ internal static class ProcessExitHooks // hProcess == -1 (pseudo-handle for current process) or == GetCurrentProcess() handle. bool selfKill = hProcess == new IntPtr(-1) || hProcess == GetCurrentProcessHandle(); if (selfKill) + { LogTermination("TerminateProcess", hProcess, exitCode); + DumpCrashOnce("TerminateProcess", exitCode); + } try { return _terminateOriginal!(hProcess, exitCode); } catch { return false; } } + // A crash exit (an NTSTATUS error code, 0xC0000000 and up: 0xC0000005 is an access + // violation) on the way out: write a minidump once, while the faulting frames are still on + // the stack. The runtime ends the process with TerminateProcess after a native AV under one + // of our detours, so no unhandled exception ever reaches a crash watcher (procdump -e saw + // nothing for Lucy's Town Network crashes, 10-01 19:46 and 10-02 15:55). + private static int _crashDumped; + private static void DumpCrashOnce(string via, uint code) + { + if (code < 0xC0000000u || System.Threading.Interlocked.Exchange(ref _crashDumped, 1) != 0) return; + try + { + if (CrashDump.WriteSelfDump($"{via} 0x{code:X8}", out string path, "crash")) + RynthLog.Info($"ProcessExit: crash dump written {path} ({via} 0x{code:X8})"); + } + catch { } + } + [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess(); private static IntPtr GetCurrentProcessHandle() => GetCurrentProcess(); @@ -312,7 +332,10 @@ internal static class ProcessExitHooks { bool selfKill = processHandle == new IntPtr(-1) || processHandle == GetCurrentProcessHandle(); if (selfKill) + { LogTermination("NtTerminateProcess", processHandle, exitStatus); + DumpCrashOnce("NtTerminateProcess", exitStatus); + } try { return _ntTermOriginal!(processHandle, exitStatus); } catch { return 0xC0000001; /* STATUS_UNSUCCESSFUL */ } } @@ -361,6 +384,9 @@ internal static class ProcessExitHooks HardTerminateNoReentry(code); } + /// <summary>ExitProcess/TerminateProcess was called: the process is closing.</summary> + public static bool TerminationIntercepted => Volatile.Read(ref _logged) != 0; + private static void LogTermination(string func, IntPtr hProcess, uint exitCode) { if (Interlocked.Exchange(ref _logged, 1) != 0) diff --git a/src/RynthCore.Engine/Compatibility/PropertyCaches.cs b/src/RynthCore.Engine/Compatibility/PropertyCaches.cs new file mode 100644 index 0000000..415cc46 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/PropertyCaches.cs @@ -0,0 +1,120 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/PropertyCaches.cs +// +// One lookup over the engine's property caches, in the order every +// TryGetObject*Property uses them (2026-09-30). Pure dictionary reads under +// their owners' locks: safe on any thread, never touches AC. +// +// the player: PlayerDescription + private updates (PropertyUpdateHooks self +// record), then public updates about the player, then the +// client's own qualities tables (ClientObjectHooks' 1 s +// main-thread snapshot), then the player's last identify; +// any other: its last identify (with later updates folded in), then the +// public updates the server sent for it. +// +// What the client knows beyond these (PublicWeenieDesc fields, AC's live +// qualities on the main thread) stays with ClientObjectHooks. +// ============================================================================ + +namespace RynthCore.Engine.Compatibility; + +internal static class PropertyCaches +{ + private static bool IsPlayer(uint objectId) + { + if (objectId == 0) return false; + uint me = ClientHelperHooks.GetPlayerId(); + return me != 0 && me == objectId; + } + + public static bool TryGetInt(uint objectId, uint stype, out int value) + { + if (IsPlayer(objectId)) + { + if (PropertyUpdateHooks.TryGetSelfInt(stype, out value)) return true; + if (PropertyUpdateHooks.TryGetCachedIntProperty(objectId, stype, out value)) return true; + if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.Ints.TryGetValue(stype, out value) == true) return true; + return AppraisalHooks.TryGetCachedIntProperty(objectId, stype, out value); + } + return AppraisalHooks.TryGetCachedIntProperty(objectId, stype, out value) + || PropertyUpdateHooks.TryGetCachedIntProperty(objectId, stype, out value); + } + + public static bool TryGetInt64(uint objectId, uint stype, out long value) + { + if (IsPlayer(objectId)) + { + if (PropertyUpdateHooks.TryGetSelfInt64(stype, out value)) return true; + if (PropertyUpdateHooks.TryGetCachedInt64Property(objectId, stype, out value)) return true; + if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.Int64s.TryGetValue(stype, out value) == true) return true; + return AppraisalHooks.TryGetCachedInt64Property(objectId, stype, out value); + } + return AppraisalHooks.TryGetCachedInt64Property(objectId, stype, out value) + || PropertyUpdateHooks.TryGetCachedInt64Property(objectId, stype, out value); + } + + public static bool TryGetBool(uint objectId, uint stype, out bool value) + { + if (IsPlayer(objectId)) + { + if (PropertyUpdateHooks.TryGetSelfBool(stype, out value)) return true; + if (PropertyUpdateHooks.TryGetCachedBoolProperty(objectId, stype, out value)) return true; + if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.Bools.TryGetValue(stype, out value) == true) return true; + return AppraisalHooks.TryGetCachedBoolProperty(objectId, stype, out value); + } + return AppraisalHooks.TryGetCachedBoolProperty(objectId, stype, out value) + || PropertyUpdateHooks.TryGetCachedBoolProperty(objectId, stype, out value); + } + + public static bool TryGetFloat(uint objectId, uint stype, out double value) + { + if (IsPlayer(objectId)) + { + if (PropertyUpdateHooks.TryGetSelfFloat(stype, out value)) return true; + if (PropertyUpdateHooks.TryGetCachedDoubleProperty(objectId, stype, out value)) return true; + if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.Floats.TryGetValue(stype, out value) == true) return true; + return AppraisalHooks.TryGetCachedDoubleProperty(objectId, stype, out value); + } + return AppraisalHooks.TryGetCachedDoubleProperty(objectId, stype, out value) + || PropertyUpdateHooks.TryGetCachedDoubleProperty(objectId, stype, out value); + } + + public static bool TryGetString(uint objectId, uint stype, out string value) + { + if (IsPlayer(objectId)) + { + if (PropertyUpdateHooks.TryGetSelfString(stype, out value)) return true; + if (PropertyUpdateHooks.TryGetCachedStringProperty(objectId, stype, out value)) return true; + if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId) is { } q && q.Strings.TryGetValue(stype, out string? qs)) { value = qs; return true; } + return AppraisalHooks.TryGetCachedStringProperty(objectId, stype, out value); + } + return AppraisalHooks.TryGetCachedStringProperty(objectId, stype, out value) + || PropertyUpdateHooks.TryGetCachedStringProperty(objectId, stype, out value); + } + + public static bool TryGetDataId(uint objectId, uint stype, out uint value) + { + if (IsPlayer(objectId)) + { + if (PropertyUpdateHooks.TryGetSelfDataId(stype, out value)) return true; + if (PropertyUpdateHooks.TryGetCachedDataIdProperty(objectId, stype, out value)) return true; + if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.DataIds.TryGetValue(stype, out value) == true) return true; + return AppraisalHooks.TryGetCachedDataIdProperty(objectId, stype, out value); + } + return AppraisalHooks.TryGetCachedDataIdProperty(objectId, stype, out value) + || PropertyUpdateHooks.TryGetCachedDataIdProperty(objectId, stype, out value); + } + + public static bool TryGetInstanceId(uint objectId, uint stype, out uint value) + { + if (IsPlayer(objectId)) + { + if (PropertyUpdateHooks.TryGetSelfInstanceId(stype, out value)) return true; + if (PropertyUpdateHooks.TryGetCachedInstanceIdProperty(objectId, stype, out value)) return true; + if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.InstanceIds.TryGetValue(stype, out value) == true) return true; + return AppraisalHooks.TryGetCachedInstanceIdProperty(objectId, stype, out value); + } + return PropertyUpdateHooks.TryGetCachedInstanceIdProperty(objectId, stype, out value) + || AppraisalHooks.TryGetCachedInstanceIdProperty(objectId, stype, out value); + } +} diff --git a/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs b/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs index 9452629..2407ccc 100644 --- a/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs @@ -1,36 +1,34 @@ // ============================================================================ // RynthCore.Engine - Compatibility/PropertyUpdateHooks.cs // -// Hooks CM_Qualities network message dispatchers to cache property updates -// broadcast by the server. This solves the problem where -// CBaseQualities::InqInt/InqBool fail for static world objects (doors, signs, -// etc.) because m_pQualities is null — those objects never get a qualities -// block allocated in client memory, but the server still sends property -// update messages that are processed and discarded. +// Caches the property update messages the server sends (UpdateProperty*, +// public and private, every type) and the player's own properties from +// PlayerDescription. This solves the problem where CBaseQualities::Inq* fail +// for objects whose m_pQualities is null (doors, signs, pack items), and where +// off AC's main thread no Inq* may run at all: plugins, metas and Lua read +// from these caches instead. // -// Hooked functions (all cdecl, from Chorizite CM.cs): -// CM_Qualities::DispatchUI_UpdateInt @ 0x006B0000 -// CM_Qualities::DispatchUI_UpdateBool @ 0x006AFF00 -// CM_Qualities::DispatchUI_PrivateUpdateInt @ 0x006AF960 -// CM_Qualities::DispatchUI_PrivateUpdateBool@ 0x006AF880 +// Sources (all on AC's main thread): +// - SmartBoxHooks.ParseGameEvent (UIQueueManager::ProcessNetBlobData) hands +// every UpdateProperty* message (0x02CD-0x02DA) to OnUpdateWire and the +// PlayerDescription (game event 0x13) to OnPlayerDescriptionWire, parsed by +// PropertyWire in ACE's exact formats. This is the one path for int64, +// float, string, data id and instance id updates (2026-09-30). +// - The older CM_Qualities::DispatchUI_Update{Int,Bool} hooks (from Chorizite +// CM.cs) stay installed: they cache int/bool updates only when the +// game-event hook is missing, so nothing is lost if it fails to install. +// CM_Qualities::DispatchUI_UpdateInt @ 0x006B0000 +// CM_Qualities::DispatchUI_UpdateBool @ 0x006AFF00 +// CM_Qualities::DispatchUI_PrivateUpdateInt @ 0x006AF960 +// CM_Qualities::DispatchUI_PrivateUpdateBool@ 0x006AF880 // -// Eviction via: -// ECM_Physics::SendNotice_BeingDeleted @ 0x00693960 -// -// Public message buffer layout: -// [0..3] sequence (uint) -// [4..7] objectGUID (uint) -// [8..11] stype (uint) -// [12..15] value (int / int-as-bool) -// -// Private message buffer layout (player implied): -// [0..3] sequence (uint) -// [4..7] stype (uint) -// [8..11] value (int / int-as-bool) +// Bounds: evicted on ECM_Physics::SendNotice_BeingDeleted @ 0x00693960, +// cleared on logout (PluginManager.DispatchPendingLogout), and pruned to the +// live objects when more than MaxObjects are cached. // ============================================================================ using System; -using System.Collections.Concurrent; +using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; using RynthCore.Engine.Hooking; @@ -76,43 +74,226 @@ internal static class PropertyUpdateHooks private static string _statusMessage = "Not initialized."; private static int _hookCount; // how many of the 5 hooks succeeded - // --- Property caches --- - // guid → (stype → value) - private static readonly ConcurrentDictionary<uint, ConcurrentDictionary<uint, int>> _intCache = new(); - private static readonly ConcurrentDictionary<uint, ConcurrentDictionary<uint, int>> _boolCache = new(); + // --- Property caches (all under _lock) --- + // Public updates: guid → every property the server updated for it this session. + private static readonly Dictionary<uint, PropertyBag> _bags = new(); + // The player: PlayerDescription's tables, then every private update (they carry no guid). + private static PropertyBag _self = new(); + private static bool _selfDescribed; + private static readonly object _lock = new(); + private const int MaxObjects = 4096; + private static int _updateLogCount; public static bool IsInstalled => _hookInstalled; public static string StatusMessage => _statusMessage; - // --- Public query API --- + // --- Public query API (any thread: dictionary reads under _lock) --- public static bool TryGetCachedIntProperty(uint objectId, uint stype, out int value) { value = 0; - if (_intCache.TryGetValue(objectId, out var props)) - return props.TryGetValue(stype, out value); - return false; + lock (_lock) + return _bags.TryGetValue(objectId, out PropertyBag? b) && b.Ints.TryGetValue(stype, out value); } public static bool TryGetCachedBoolProperty(uint objectId, uint stype, out bool value) { value = false; - if (_boolCache.TryGetValue(objectId, out var props)) + lock (_lock) + return _bags.TryGetValue(objectId, out PropertyBag? b) && b.Bools.TryGetValue(stype, out value); + } + + public static bool TryGetCachedInt64Property(uint objectId, uint stype, out long value) + { + value = 0; + lock (_lock) + return _bags.TryGetValue(objectId, out PropertyBag? b) && b.Int64s.TryGetValue(stype, out value); + } + + public static bool TryGetCachedDoubleProperty(uint objectId, uint stype, out double value) + { + value = 0; + lock (_lock) + return _bags.TryGetValue(objectId, out PropertyBag? b) && b.Floats.TryGetValue(stype, out value); + } + + public static bool TryGetCachedStringProperty(uint objectId, uint stype, out string value) + { + value = string.Empty; + lock (_lock) { - if (props.TryGetValue(stype, out int raw)) + if (_bags.TryGetValue(objectId, out PropertyBag? b) && b.Strings.TryGetValue(stype, out string? s)) { - value = raw != 0; + value = s; return true; } + return false; } - return false; + } + + public static bool TryGetCachedDataIdProperty(uint objectId, uint stype, out uint value) + { + value = 0; + lock (_lock) + return _bags.TryGetValue(objectId, out PropertyBag? b) && b.DataIds.TryGetValue(stype, out value); + } + + public static bool TryGetCachedInstanceIdProperty(uint objectId, uint stype, out uint value) + { + value = 0; + lock (_lock) + return _bags.TryGetValue(objectId, out PropertyBag? b) && b.InstanceIds.TryGetValue(stype, out value); + } + + // The player's own record (PlayerDescription + private updates). + public static bool TryGetSelfInt(uint stype, out int value) { lock (_lock) return _self.Ints.TryGetValue(stype, out value); } + public static bool TryGetSelfInt64(uint stype, out long value) { lock (_lock) return _self.Int64s.TryGetValue(stype, out value); } + public static bool TryGetSelfBool(uint stype, out bool value) { lock (_lock) return _self.Bools.TryGetValue(stype, out value); } + public static bool TryGetSelfFloat(uint stype, out double value) { lock (_lock) return _self.Floats.TryGetValue(stype, out value); } + public static bool TryGetSelfDataId(uint stype, out uint value) { lock (_lock) return _self.DataIds.TryGetValue(stype, out value); } + public static bool TryGetSelfInstanceId(uint stype, out uint value) { lock (_lock) return _self.InstanceIds.TryGetValue(stype, out value); } + public static bool TryGetSelfString(uint stype, out string value) + { + value = string.Empty; + lock (_lock) + { + if (!_self.Strings.TryGetValue(stype, out string? s)) return false; + value = s; + return true; + } + } + + /// <summary>True once this session's PlayerDescription was read.</summary> + public static bool HasPlayerDescription + { + get { lock (_lock) return _selfDescribed; } + } + + public static int CachedObjectCount + { + get { lock (_lock) return _bags.Count; } + } + + public static int SelfPropertyCount + { + get { lock (_lock) return _self.Count; } } /// <summary>Evict all cached properties for an object (e.g. when it is destroyed).</summary> public static void EvictObject(uint objectId) { - _intCache.TryRemove(objectId, out _); - _boolCache.TryRemove(objectId, out _); + lock (_lock) + _bags.Remove(objectId); + } + + /// <summary>Logout: nothing here survives the session (guids and the player change).</summary> + public static void ClearSession() + { + lock (_lock) + { + _bags.Clear(); + _self = new PropertyBag(); + _selfDescribed = false; + } + ClientObjectHooks.ClearPlayerQualitiesSnapshot(); + } + + // --- Wire entry points (AC's main thread, SmartBoxHooks.ParseGameEvent) --- + + /// <summary>One UpdateProperty* message (0x02CD-0x02DA), from its opcode on.</summary> + internal static unsafe void OnUpdateWire(IntPtr data, int size) + { + if (data == IntPtr.Zero || size < 9) + return; + if (PropertyWire.TryParsePropertyUpdate(new ReadOnlySpan<byte>((void*)data, size), out PropertyUpdate u)) + Apply(u); + } + + /// <summary>The player's PlayerDescription (game event 0x13), from its event type on.</summary> + internal static unsafe void OnPlayerDescriptionWire(IntPtr data, int size) + { + if (data == IntPtr.Zero || size < 12) + return; + if (!PropertyWire.TryParsePlayerDescription(new ReadOnlySpan<byte>((void*)data, size), out PropertyBag bag, out bool truncated)) + return; + lock (_lock) + { + // Private updates that raced ahead of the description are newer: keep them on top. + bag.MergeFrom(_self); + _self = bag; + _selfDescribed = true; + } + RynthLog.Compat($"Compat: PlayerDescription properties int={bag.Ints.Count} int64={bag.Int64s.Count} bool={bag.Bools.Count} " + + $"float={bag.Floats.Count} string={bag.Strings.Count} did={bag.DataIds.Count} iid={bag.InstanceIds.Count}{(truncated ? " TRUNCATED" : "")}"); + } + + /// <summary> + /// Files one update: a private one into the player's record, a public one under its object; + /// either way it is also folded into that object's identify record so the appraisal cache + /// (read first) doesn't serve a stale value. + /// </summary> + internal static void Apply(in PropertyUpdate u) + { + uint target; + if (u.IsPrivate) + { + lock (_lock) + _self.Apply(u); + target = ClientHelperHooks.GetPlayerId(); + } + else + { + if (u.ObjectId == 0) + return; + lock (_lock) + { + if (!_bags.TryGetValue(u.ObjectId, out PropertyBag? bag)) + { + if (_bags.Count >= MaxObjects) + PruneToLiveLocked(); + _bags[u.ObjectId] = bag = new PropertyBag(); + } + bag.Apply(u); + } + target = u.ObjectId; + } + if (target != 0) + AppraisalHooks.ApplyUpdate(target, u); + + if (_updateLogCount < 8) + { + _updateLogCount++; + RynthLog.Info($"[PropUpd] {(u.IsPrivate ? "private" : "public")} {u.Kind} obj=0x{target:X8} key={u.Key} " + + $"value={(u.Kind == PropertyKind.Float ? u.Real.ToString(System.Globalization.CultureInfo.InvariantCulture) : u.Kind == PropertyKind.String ? u.Text : u.Integer.ToString(System.Globalization.CultureInfo.InvariantCulture))}"); + } + } + + // Caller holds _lock. Drops objects the client no longer knows (the identity walk's id list), + // or everything if that list is empty; the player's own public updates are kept. + private static void PruneToLiveLocked() + { + uint[] live = ClientObjectHooks.LiveObjectIds; + uint me = ClientHelperHooks.GetPlayerId(); + if (live.Length == 0) + { + PropertyBag? mine = me != 0 && _bags.TryGetValue(me, out PropertyBag? m) ? m : null; + _bags.Clear(); + if (mine != null) _bags[me] = mine; + return; + } + var keep = new HashSet<uint>(live); + var drop = new List<uint>(); + foreach (uint id in _bags.Keys) + if (id != me && !keep.Contains(id)) + drop.Add(id); + foreach (uint id in drop) + _bags.Remove(id); + if (_bags.Count >= MaxObjects) // everything is live: make room anyway + { + PropertyBag? mine = me != 0 && _bags.TryGetValue(me, out PropertyBag? m) ? m : null; + _bags.Clear(); + if (mine != null) _bags[me] = mine; + } } // --- Initialization --- @@ -226,77 +407,39 @@ internal static class PropertyUpdateHooks // --- Detour implementations --- + // The CM_Qualities dispatchers receive the message from its opcode on (acclient.exe: + // each begins `mov edx,[buf]; add buf,4; cmp edx,<its opcode>`), the same bytes + // ProcessNetBlobData hands SmartBoxHooks.ParseGameEvent - which caches every update type + // when the game-event hook is installed. These detours are the fallback for when it isn't. + private static unsafe void ApplyFromDispatcher(IntPtr buf, uint size) + { + if (SmartBoxHooks.IsGameEventHookInstalled || buf == IntPtr.Zero || size < 9 || size > 0x1000) + return; + if (PropertyWire.TryParsePropertyUpdate(new ReadOnlySpan<byte>((void*)buf, (int)size), out PropertyUpdate u)) + Apply(u); + } + private static uint DetourUpdateInt(IntPtr uiPtr, IntPtr bufPtr, uint size) { - try - { - // Public: seq(4) + guid(4) + stype(4) + value(4) = 16 bytes minimum - if (bufPtr != IntPtr.Zero && size >= 16) - { - uint guid = (uint)Marshal.ReadInt32(bufPtr + 4); - uint stype = (uint)Marshal.ReadInt32(bufPtr + 8); - int val = Marshal.ReadInt32(bufPtr + 12); - CacheInt(guid, stype, val); - } - } - catch { } + try { ApplyFromDispatcher(bufPtr, size); } catch { } return _origUpdateInt!(uiPtr, bufPtr, size); } private static uint DetourUpdateBool(IntPtr uiPtr, IntPtr bufPtr, uint size) { - try - { - // Public: seq(4) + guid(4) + stype(4) + value(4) = 16 bytes minimum - if (bufPtr != IntPtr.Zero && size >= 16) - { - uint guid = (uint)Marshal.ReadInt32(bufPtr + 4); - uint stype = (uint)Marshal.ReadInt32(bufPtr + 8); - int val = Marshal.ReadInt32(bufPtr + 12); - CacheBool(guid, stype, val); - } - } - catch { } + try { ApplyFromDispatcher(bufPtr, size); } catch { } return _origUpdateBool!(uiPtr, bufPtr, size); } private static uint DetourPrivateUpdateInt(IntPtr uiPtr, IntPtr bufPtr, uint size) { - try - { - // Private: seq(4) + stype(4) + value(4) = 12 bytes minimum - if (bufPtr != IntPtr.Zero && size >= 12) - { - uint playerId = ClientHelperHooks.GetPlayerId(); - if (playerId != 0) - { - uint stype = (uint)Marshal.ReadInt32(bufPtr + 4); - int val = Marshal.ReadInt32(bufPtr + 8); - CacheInt(playerId, stype, val); - } - } - } - catch { } + try { ApplyFromDispatcher(bufPtr, size); } catch { } return _origPrivateUpdateInt!(uiPtr, bufPtr, size); } private static uint DetourPrivateUpdateBool(IntPtr uiPtr, IntPtr bufPtr, uint size) { - try - { - // Private: seq(4) + stype(4) + value(4) = 12 bytes minimum - if (bufPtr != IntPtr.Zero && size >= 12) - { - uint playerId = ClientHelperHooks.GetPlayerId(); - if (playerId != 0) - { - uint stype = (uint)Marshal.ReadInt32(bufPtr + 4); - int val = Marshal.ReadInt32(bufPtr + 8); - CacheBool(playerId, stype, val); - } - } - } - catch { } + try { ApplyFromDispatcher(bufPtr, size); } catch { } return _origPrivateUpdateBool!(uiPtr, bufPtr, size); } @@ -311,29 +454,14 @@ internal static class PropertyUpdateHooks { uint objectId = (uint)Marshal.ReadInt32(idAddr); if (objectId != 0) + { EvictObject(objectId); + AppraisalHooks.EvictObject(objectId); + } } } } catch { } return _origBeingDeleted!(weenieObjPtr); } - - // --- Cache helpers --- - - private static void CacheInt(uint guid, uint stype, int value) - { - var props = _intCache.GetOrAdd(guid, _ => new ConcurrentDictionary<uint, int>()); - props[stype] = value; - // The appraisal snapshot is read first off-thread; keep it current (e.g. an essence's - // Structure after a refill or summon) instead of serving the value from the last ID. - AppraisalHooks.PatchCachedInt(guid, stype, value); - } - - private static void CacheBool(uint guid, uint stype, int value) - { - var props = _boolCache.GetOrAdd(guid, _ => new ConcurrentDictionary<uint, int>()); - props[stype] = value; - AppraisalHooks.PatchCachedBool(guid, stype, value != 0); - } } diff --git a/src/RynthCore.Engine/Compatibility/PropertyWire.cs b/src/RynthCore.Engine/Compatibility/PropertyWire.cs new file mode 100644 index 0000000..4574c6c --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/PropertyWire.cs @@ -0,0 +1,629 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/PropertyWire.cs +// +// Pure parsers for every message that carries an object's properties to the +// client, in ACE's exact wire formats (ACE.Server: AppraiseInfo.cs and the +// Armor/Creature/Weapon/HookProfile writers, GameEventPlayerDescription.cs, +// GameMessagePrivate/PublicUpdateProperty*.cs, WorldObject_Networking.cs for +// the PublicWeenieDesc fields). No AC memory, no engine state: the engine feeds +// them from UIQueueManager::ProcessNetBlobData (SmartBoxHooks.ParseGameEvent), +// and the offline tests (tools\PropertyWireTests) compile +// this file in and feed them hand-built messages. +// +// ProcessNetBlobData hands its handlers the message from its type on: a game +// event (0xF7B0) arrives as [event type][payload], a top-level message as +// [opcode][body]. Verified against acclient.exe: the function compares [data] +// with 0x2D5/0x2D6 (string updates, @0x55CD72) and calls +// CM_Examine::SendNotice_SetAppraiseInfo (@0x55C862) and +// CPlayerSystem::Handle_PlayerDescription (@0x55BE35); the CM_Qualities +// DispatchUI_* handlers it calls read the opcode at buf+0. +// ============================================================================ + +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Engine.Compatibility; + +/// <summary>The seven AC property types (STypeInt, STypeInt64, ...).</summary> +internal enum PropertyKind : byte +{ + Int, + Int64, + Bool, + Float, + String, + DataId, + InstanceId, +} + +/// <summary>One property update message (UpdateProperty* public or private).</summary> +internal readonly struct PropertyUpdate +{ + public PropertyUpdate(PropertyKind kind, bool isPrivate, uint objectId, uint key, long integer, double real, string? text) + { + Kind = kind; + IsPrivate = isPrivate; + ObjectId = objectId; + Key = key; + Integer = integer; + Real = real; + Text = text; + } + + public PropertyKind Kind { get; } + /// <summary>A private update is about the player and carries no object id.</summary> + public bool IsPrivate { get; } + /// <summary>The object a public update is about; 0 for a private one.</summary> + public uint ObjectId { get; } + public uint Key { get; } + /// <summary>Int, Int64, Bool (0/1), DataId and InstanceId values.</summary> + public long Integer { get; } + /// <summary>Float values.</summary> + public double Real { get; } + /// <summary>String values.</summary> + public string? Text { get; } +} + +/// <summary> +/// An object's properties, one table per type. Not thread-safe: the engine's caches +/// guard every bag with their own lock. +/// </summary> +internal sealed class PropertyBag +{ + public readonly Dictionary<uint, int> Ints = new(); + public readonly Dictionary<uint, long> Int64s = new(); + public readonly Dictionary<uint, bool> Bools = new(); + public readonly Dictionary<uint, double> Floats = new(); + public readonly Dictionary<uint, string> Strings = new(); + public readonly Dictionary<uint, uint> DataIds = new(); + public readonly Dictionary<uint, uint> InstanceIds = new(); + + public int Count => Ints.Count + Int64s.Count + Bools.Count + Floats.Count + Strings.Count + DataIds.Count + InstanceIds.Count; + + public void Apply(in PropertyUpdate u) + { + switch (u.Kind) + { + case PropertyKind.Int: Ints[u.Key] = unchecked((int)u.Integer); break; + case PropertyKind.Int64: Int64s[u.Key] = u.Integer; break; + case PropertyKind.Bool: Bools[u.Key] = u.Integer != 0; break; + case PropertyKind.Float: Floats[u.Key] = u.Real; break; + case PropertyKind.String: Strings[u.Key] = u.Text ?? string.Empty; break; + case PropertyKind.DataId: DataIds[u.Key] = unchecked((uint)u.Integer); break; + case PropertyKind.InstanceId: InstanceIds[u.Key] = unchecked((uint)u.Integer); break; + } + } + + /// <summary>Copies every value of <paramref name="other"/> in, replacing same-key values.</summary> + public void MergeFrom(PropertyBag other) + { + foreach (var kv in other.Ints) Ints[kv.Key] = kv.Value; + foreach (var kv in other.Int64s) Int64s[kv.Key] = kv.Value; + foreach (var kv in other.Bools) Bools[kv.Key] = kv.Value; + foreach (var kv in other.Floats) Floats[kv.Key] = kv.Value; + foreach (var kv in other.Strings) Strings[kv.Key] = kv.Value; + foreach (var kv in other.DataIds) DataIds[kv.Key] = kv.Value; + foreach (var kv in other.InstanceIds) InstanceIds[kv.Key] = kv.Value; + } +} + +/// <summary>What one identify reply (game event 0xC9, SetAppraiseInfo) told the client.</summary> +internal sealed class IdentifyRecord +{ + public uint ObjectId; + public uint Flags; + public bool Success; + /// <summary>The six tables, plus the armour/weapon/hook profile values filed under their property ids.</summary> + public readonly PropertyBag Properties = new(); + public int SpellCount; + public bool HasArmorProfile, HasCreatureProfile, HasWeaponProfile, HasHookProfile; + public uint CreatureHealth, CreatureHealthMax; + /// <summary>A flagged section ran past the end of the message; everything before it was kept.</summary> + public bool Truncated; +} + +internal static class PropertyWire +{ + // Game events (ProcessNetBlobData: [event type][payload]). + public const uint EventPlayerDescription = 0x0013; + public const uint EventIdentifyObjectResponse = 0x00C9; + + // Top-level messages (ACE GameMessageOpcode). + public const uint OpPrivateUpdateInt = 0x02CD, OpPublicUpdateInt = 0x02CE; + public const uint OpPrivateUpdateInt64 = 0x02CF, OpPublicUpdateInt64 = 0x02D0; + public const uint OpPrivateUpdateBool = 0x02D1, OpPublicUpdateBool = 0x02D2; + public const uint OpPrivateUpdateFloat = 0x02D3, OpPublicUpdateFloat = 0x02D4; + public const uint OpPrivateUpdateString = 0x02D5, OpPublicUpdateString = 0x02D6; + public const uint OpPrivateUpdateDataId = 0x02D7, OpPublicUpdateDataId = 0x02D8; + public const uint OpPrivateUpdateInstanceId = 0x02D9, OpPublicUpdateInstanceId = 0x02DA; + + // IdentifyResponseFlags (ACE.Entity.Enum.IdentifyResponseFlags). + public const uint IdIntStats = 0x0001, IdBoolStats = 0x0002, IdFloatStats = 0x0004, IdStringStats = 0x0008, + IdSpellBook = 0x0010, IdWeaponProfile = 0x0020, IdHookProfile = 0x0040, IdArmorProfile = 0x0080, + IdCreatureProfile = 0x0100, IdDidStats = 0x1000, IdInt64Stats = 0x2000; + + // PlayerDescription DescriptionPropertyFlag. + public const uint PdInt = 0x0001, PdBool = 0x0002, PdDouble = 0x0004, PdDid = 0x0008, PdString = 0x0010, + PdIid = 0x0040, PdInt64 = 0x0080; + + // Property ids the profiles are filed under (ACE PropertyInt / PropertyFloat / PropertyBool). + public const uint IntValidLocations = 9, IntDamage = 44, IntDamageType = 45, IntWeaponSkill = 48, IntWeaponTime = 49, IntAmmoType = 50; + public const uint FloatWeaponLength = 21, FloatDamageVariance = 22, FloatMaximumVelocity = 26, FloatWeaponOffense = 62, FloatDamageMod = 63; + public const uint BoolInscribable = 22; + + /// <summary> + /// ArmorProfile floats in wire order (ACE ArmorProfile.Write: slash, pierce, bludgeon, cold, + /// fire, acid, nether, lightning) and the PropertyFloat ids they are filed under + /// (ArmorModVsSlash 13 .. ArmorModVsAcid 18, ArmorModVsNether 165, ArmorModVsElectric 19). + /// </summary> + public static readonly uint[] ArmorProfileFloatIds = { 13, 14, 15, 16, 17, 18, 165, 19 }; + + public static bool IsPropertyUpdateOpcode(uint opcode) => opcode >= OpPrivateUpdateInt && opcode <= OpPublicUpdateInstanceId; + + /// <summary> + /// Parses one UpdateProperty* message, starting at its opcode. Layouts (ACE): + /// private: [op][seq u8][key u32][value] + /// public: [op][seq u8][guid u32][key u32][value] + /// strings: private [op][seq][key][align 4][str16L], public [op][seq][key][guid][align 4][str16L] + /// (the public string update has the key BEFORE the guid, unlike every other type). + /// Values: int i32, int64 i64, bool u32, float f64, data id u32, instance id u32. + /// </summary> + public static bool TryParsePropertyUpdate(ReadOnlySpan<byte> msg, out PropertyUpdate update) + { + update = default; + var r = new WireReader(msg); + if (!r.U32(out uint op) || !IsPropertyUpdateOpcode(op) || !r.Skip(1)) // sequence byte + return false; + + bool isPrivate = (op & 1) != 0; // every private opcode is odd, every public one even + uint guid = 0, key; + switch (op) + { + case OpPrivateUpdateString: + case OpPublicUpdateString: + { + if (!r.U32(out key)) return false; + if (!isPrivate && !r.U32(out guid)) return false; + if (!r.Align4() || !r.String16L(out string text)) return false; + update = new PropertyUpdate(PropertyKind.String, isPrivate, guid, key, 0, 0, text); + return true; + } + } + + if (!isPrivate && !r.U32(out guid)) return false; + if (!r.U32(out key)) return false; + switch (op) + { + case OpPrivateUpdateInt: + case OpPublicUpdateInt: + if (!r.I32(out int i)) return false; + update = new PropertyUpdate(PropertyKind.Int, isPrivate, guid, key, i, 0, null); + return true; + case OpPrivateUpdateInt64: + case OpPublicUpdateInt64: + if (!r.I64(out long q)) return false; + update = new PropertyUpdate(PropertyKind.Int64, isPrivate, guid, key, q, 0, null); + return true; + case OpPrivateUpdateBool: + case OpPublicUpdateBool: + if (!r.U32(out uint b)) return false; + update = new PropertyUpdate(PropertyKind.Bool, isPrivate, guid, key, b != 0 ? 1 : 0, 0, null); + return true; + case OpPrivateUpdateFloat: + case OpPublicUpdateFloat: + if (!r.F64(out double d) || !double.IsFinite(d)) return false; + update = new PropertyUpdate(PropertyKind.Float, isPrivate, guid, key, 0, d, null); + return true; + case OpPrivateUpdateDataId: + case OpPublicUpdateDataId: + if (!r.U32(out uint did)) return false; + update = new PropertyUpdate(PropertyKind.DataId, isPrivate, guid, key, did, 0, null); + return true; + case OpPrivateUpdateInstanceId: + case OpPublicUpdateInstanceId: + if (!r.U32(out uint iid)) return false; + update = new PropertyUpdate(PropertyKind.InstanceId, isPrivate, guid, key, iid, 0, null); + return true; + } + return false; + } + + /// <summary> + /// Parses an identify reply, starting at its event type (0xC9): [type][guid][flags][success], + /// then in ACE's write order the int, int64, bool, float, string and data id tables, the + /// spell book, the armour, creature, weapon and hook profiles. The tables are kept as sent; + /// the armour profile's ratings, the weapon profile's numbers and the hook profile's + /// locations/ammo/inscribable are added under their property ids, where the tables don't + /// already hold them (as the retail client's appraisal panel reads them, and UtilityBelt + /// exposes them). A section that runs past the end stops the parse; what came before is kept. + /// </summary> + public static bool TryParseIdentify(ReadOnlySpan<byte> msg, out IdentifyRecord record) + { + record = new IdentifyRecord(); + var r = new WireReader(msg); + if (!r.U32(out uint type) || type != EventIdentifyObjectResponse) + return false; + if (!r.U32(out record.ObjectId) || !r.U32(out record.Flags) || !r.U32(out uint success) || record.ObjectId == 0) + return false; + record.Success = success != 0; + uint f = record.Flags; + PropertyBag bag = record.Properties; + + if (!ReadSections(ref r, record, bag, f)) + record.Truncated = true; + return true; + } + + private static bool ReadSections(ref WireReader r, IdentifyRecord rec, PropertyBag bag, uint f) + { + if ((f & IdIntStats) != 0 && !ReadIntTable(ref r, bag.Ints)) return false; + if ((f & IdInt64Stats) != 0 && !ReadInt64Table(ref r, bag.Int64s)) return false; + if ((f & IdBoolStats) != 0 && !ReadBoolTable(ref r, bag.Bools)) return false; + if ((f & IdFloatStats) != 0 && !ReadFloatTable(ref r, bag.Floats)) return false; + if ((f & IdStringStats) != 0 && !ReadStringTable(ref r, bag.Strings)) return false; + if ((f & IdDidStats) != 0 && !ReadUIntTable(ref r, bag.DataIds)) return false; + + if ((f & IdSpellBook) != 0) + { + if (!r.I32(out int n) || n < 0 || n > 100_000 || !r.Skip(n * 4)) return false; + rec.SpellCount = n; + } + + if ((f & IdArmorProfile) != 0) + { + Span<float> prot = stackalloc float[8]; + for (int i = 0; i < 8; i++) + if (!r.F32(out prot[i])) return false; + rec.HasArmorProfile = true; + for (int i = 0; i < 8; i++) + if (float.IsFinite(prot[i])) bag.Floats.TryAdd(ArmorProfileFloatIds[i], prot[i]); + } + + if ((f & IdCreatureProfile) != 0) + { + // cpFlags, Health, HealthMax; ShowAttributes(0x8): Str, End, Quick, Coord, Focus, Self, + // Stamina, Mana, StaminaMax, ManaMax; HasBuffsDebuffs(0x1): u16 highlights, u16 colors. + if (!r.U32(out uint cp) || !r.U32(out rec.CreatureHealth) || !r.U32(out rec.CreatureHealthMax)) return false; + if ((cp & 0x8) != 0 && !r.Skip(40)) return false; + if ((cp & 0x1) != 0 && !r.Skip(4)) return false; + rec.HasCreatureProfile = true; + } + + if ((f & IdWeaponProfile) != 0) + { + // ACE WeaponProfile.Write: DamageType, WeaponTime, WeaponSkill, Damage (u32 each), + // DamageVariance, DamageMod, WeaponLength, MaxVelocity, WeaponOffense (f64 each), + // MaxVelocityEstimated (u32; no property of its own). + if (!r.U32(out uint dmgType) || !r.U32(out uint time) || !r.U32(out uint skill) || !r.U32(out uint dmg)) return false; + if (!r.F64(out double variance) || !r.F64(out double dmgMod) || !r.F64(out double length) + || !r.F64(out double maxVel) || !r.F64(out double offense) || !r.Skip(4)) return false; + rec.HasWeaponProfile = true; + bag.Ints.TryAdd(IntDamageType, unchecked((int)dmgType)); + bag.Ints.TryAdd(IntWeaponTime, unchecked((int)time)); + bag.Ints.TryAdd(IntWeaponSkill, unchecked((int)skill)); + bag.Ints.TryAdd(IntDamage, unchecked((int)dmg)); + AddFinite(bag.Floats, FloatDamageVariance, variance); + AddFinite(bag.Floats, FloatDamageMod, dmgMod); + AddFinite(bag.Floats, FloatWeaponLength, length); + AddFinite(bag.Floats, FloatMaximumVelocity, maxVel); + AddFinite(bag.Floats, FloatWeaponOffense, offense); + } + + if ((f & IdHookProfile) != 0) + { + // ACE HookProfile.Write: Flags (Inscribable 1, IsHealer 2, IsFood 4, IsLockpick 8), + // ValidLocations, AmmoType. Sent when a house hook holds an item: the tables above + // are that item's. + if (!r.U32(out uint hookFlags) || !r.U32(out uint locations) || !r.U32(out uint ammo)) return false; + rec.HasHookProfile = true; + if (locations != 0) bag.Ints.TryAdd(IntValidLocations, unchecked((int)locations)); + if (ammo != 0) bag.Ints.TryAdd(IntAmmoType, unchecked((int)ammo)); + if ((hookFlags & 0x1) != 0) bag.Bools.TryAdd(BoolInscribable, true); + } + // The enchantment bitfields and armour levels that may follow carry no properties. + return true; + } + + /// <summary> + /// Parses the property tables at the start of the player's PlayerDescription (game event + /// 0x13), starting at its event type: [type][property flags][weenie type], then the int, + /// int64, bool, double, string, data id and instance id tables (ACE + /// GameEventPlayerDescription.WriteEventBody order). Everything after them (positions, + /// attributes, skills, spells, options, inventory) is ignored. A table that runs past the + /// end stops the parse; the tables before it are kept (<paramref name="truncated"/>). + /// </summary> + public static bool TryParsePlayerDescription(ReadOnlySpan<byte> msg, out PropertyBag bag, out bool truncated) + { + bag = new PropertyBag(); + truncated = false; + var r = new WireReader(msg); + if (!r.U32(out uint type) || type != EventPlayerDescription || !r.U32(out uint f) || !r.Skip(4)) + return false; + bool ok = ((f & PdInt) == 0 || ReadIntTable(ref r, bag.Ints)) + && ((f & PdInt64) == 0 || ReadInt64Table(ref r, bag.Int64s)) + && ((f & PdBool) == 0 || ReadBoolTable(ref r, bag.Bools)) + && ((f & PdDouble) == 0 || ReadFloatTable(ref r, bag.Floats)) + && ((f & PdString) == 0 || ReadStringTable(ref r, bag.Strings)) + && ((f & PdDid) == 0 || ReadUIntTable(ref r, bag.DataIds)) + && ((f & PdIid) == 0 || ReadUIntTable(ref r, bag.InstanceIds)); + truncated = !ok; + return true; + } + + private static void AddFinite(Dictionary<uint, double> d, uint key, double v) + { + if (double.IsFinite(v)) d.TryAdd(key, v); + } + + // PackableHashTable on the wire: u16 count, u16 bucket count, then count entries. + private static bool ReadHeader(ref WireReader r, out int count) + { + count = 0; + if (!r.U16(out ushort n) || !r.Skip(2)) return false; + count = n; + return true; + } + + private static bool ReadIntTable(ref WireReader r, Dictionary<uint, int> d) + { + if (!ReadHeader(ref r, out int n) || !r.Has(n * 8)) return false; + for (int i = 0; i < n; i++) { r.U32(out uint k); r.I32(out int v); d[k] = v; } + return true; + } + + private static bool ReadUIntTable(ref WireReader r, Dictionary<uint, uint> d) + { + if (!ReadHeader(ref r, out int n) || !r.Has(n * 8)) return false; + for (int i = 0; i < n; i++) { r.U32(out uint k); r.U32(out uint v); d[k] = v; } + return true; + } + + private static bool ReadBoolTable(ref WireReader r, Dictionary<uint, bool> d) + { + if (!ReadHeader(ref r, out int n) || !r.Has(n * 8)) return false; + for (int i = 0; i < n; i++) { r.U32(out uint k); r.U32(out uint v); d[k] = v != 0; } + return true; + } + + private static bool ReadInt64Table(ref WireReader r, Dictionary<uint, long> d) + { + if (!ReadHeader(ref r, out int n) || !r.Has(n * 12)) return false; + for (int i = 0; i < n; i++) { r.U32(out uint k); r.I64(out long v); d[k] = v; } + return true; + } + + private static bool ReadFloatTable(ref WireReader r, Dictionary<uint, double> d) + { + if (!ReadHeader(ref r, out int n) || !r.Has(n * 12)) return false; + for (int i = 0; i < n; i++) + { + r.U32(out uint k); + r.F64(out double v); + if (double.IsFinite(v)) d[k] = v; + } + return true; + } + + private static bool ReadStringTable(ref WireReader r, Dictionary<uint, string> d) + { + if (!ReadHeader(ref r, out int n)) return false; + for (int i = 0; i < n; i++) + { + if (!r.U32(out uint k) || !r.String16L(out string v)) return false; + d[k] = v; + } + return true; + } + + /// <summary>Bounds-checked little-endian reader over one message.</summary> + private ref struct WireReader + { + private readonly ReadOnlySpan<byte> _s; + private int _pos; + + public WireReader(ReadOnlySpan<byte> s) { _s = s; _pos = 0; } + + public bool Has(int n) => n >= 0 && _pos + n <= _s.Length && _pos + n >= _pos; + + public bool Skip(int n) + { + if (!Has(n)) return false; + _pos += n; + return true; + } + + public bool U16(out ushort v) + { + v = 0; + if (!Has(2)) return false; + v = BinaryPrimitives.ReadUInt16LittleEndian(_s.Slice(_pos)); + _pos += 2; + return true; + } + + public bool U32(out uint v) + { + v = 0; + if (!Has(4)) return false; + v = BinaryPrimitives.ReadUInt32LittleEndian(_s.Slice(_pos)); + _pos += 4; + return true; + } + + public bool I32(out int v) + { + v = 0; + if (!Has(4)) return false; + v = BinaryPrimitives.ReadInt32LittleEndian(_s.Slice(_pos)); + _pos += 4; + return true; + } + + public bool I64(out long v) + { + v = 0; + if (!Has(8)) return false; + v = BinaryPrimitives.ReadInt64LittleEndian(_s.Slice(_pos)); + _pos += 8; + return true; + } + + public bool F32(out float v) + { + v = 0; + if (!Has(4)) return false; + v = BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(_s.Slice(_pos))); + _pos += 4; + return true; + } + + public bool F64(out double v) + { + v = 0; + if (!Has(8)) return false; + v = BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(_s.Slice(_pos))); + _pos += 8; + return true; + } + + /// <summary>Pads to a 4-byte boundary from the message start (ACE Writer.Align()).</summary> + public bool Align4() => Skip((4 - (_pos & 3)) & 3); + + /// <summary> + /// ACE WriteString16L: u16 length, the bytes (code page 1252), then zero padding so + /// that 2 + length is a multiple of 4. + /// </summary> + public bool String16L(out string v) + { + v = string.Empty; + if (!U16(out ushort len) || !Has(len)) return false; + v = Encoding.Latin1.GetString(_s.Slice(_pos, len)); + _pos += len; + return Skip((4 - ((2 + len) & 3)) & 3); + } + } +} + +/// <summary> +/// The PublicWeenieDesc fields every object carries from its CreateObject, filed under the +/// property ids they come from on the server (ACE WorldObject_Networking.SerializeCreateObject) +/// - the only properties the client holds for an object that was never identified. Offsets are +/// from the start of the client's PublicWeenieDesc (Chorizite Weenie.cs PublicWeenieDesc; the +/// engine copies the first <see cref="Size"/> bytes of it in its 10 Hz main-thread walk). +/// A zero field is "not sent" (the header flag was clear), so it answers nothing. +/// </summary> +internal static class PwdLayout +{ + public const int Size = 176; + + public const int Wcid = 12, Icon = 16, IconOverlay = 20, IconUnderlay = 24, Container = 28, Wielder = 32, + Priority = 36, ValidLocations = 40, Location = 44, ItemsCapacity = 48, ContainersCapacity = 52, + Type = 56, Value = 60, Useability = 64, UseRadius = 68, TargetType = 72, Effects = 76, + AmmoType = 80, CombatUse = 84, Structure = 88, MaxStructure = 92, StackSize = 96, + MaxStackSize = 100, Bitfield = 104, BlipColor = 108, RadarEnum = 112, Burden = 116, + SpellId = 120, HouseOwner = 124, HookType = 136, HookItemTypes = 140, Monarch = 144, + MaterialType = 148, Workmanship = 152, CooldownId = 156, CooldownDuration = 160, PetOwner = 168; + + public static int IntOffset(uint stype) => stype switch + { + 1 => Type, // ItemType + 4 => Priority, // ClothingPriority + 5 => Burden, // EncumbranceVal + 6 => ItemsCapacity, + 7 => ContainersCapacity, + 9 => ValidLocations, + 10 => Location, // CurrentWieldedLocation + 11 => MaxStackSize, + 12 => StackSize, + 16 => Useability, // ItemUseable + 18 => Effects, // UiEffects + 19 => Value, + 50 => AmmoType, + 51 => CombatUse, + 91 => MaxStructure, + 92 => Structure, + 94 => TargetType, + 95 => BlipColor, // RadarBlipColor + 131 => MaterialType, + 133 => RadarEnum, // ShowableOnRadar + 151 => HookType, + 152 => HookItemTypes, // HookItemType + 280 => CooldownId, // SharedCooldown + _ => -1, + }; + + public static int DataIdOffset(uint stype) => stype switch + { + 8 => Icon, + 28 => SpellId, // Spell + 50 => IconOverlay, + 52 => IconUnderlay, + _ => -1, + }; + + public static int InstanceIdOffset(uint stype) => stype switch + { + 2 => Container, + 3 => Wielder, + 26 => Monarch, + 32 => HouseOwner, + 44 => PetOwner, + _ => -1, + }; + + public static bool TryGetInt(ReadOnlySpan<byte> pwd, uint stype, out int value) + { + value = 0; + int off = IntOffset(stype); + if (off < 0 || off + 4 > pwd.Length) return false; + value = BinaryPrimitives.ReadInt32LittleEndian(pwd.Slice(off)); + return value != 0; + } + + public static bool TryGetDataId(ReadOnlySpan<byte> pwd, uint stype, out uint value) + { + value = 0; + int off = DataIdOffset(stype); + if (off < 0 || off + 4 > pwd.Length) return false; + value = BinaryPrimitives.ReadUInt32LittleEndian(pwd.Slice(off)); + return value != 0; + } + + public static bool TryGetInstanceId(ReadOnlySpan<byte> pwd, uint stype, out uint value) + { + value = 0; + int off = InstanceIdOffset(stype); + if (off < 0 || off + 4 > pwd.Length) return false; + value = BinaryPrimitives.ReadUInt32LittleEndian(pwd.Slice(off)); + return value != 0; + } + + /// <summary> + /// UseRadius (54, f32), CooldownDuration (167, f64), and 280, the engine's long-standing + /// read of the item's workmanship (f32; UtilityBelt's SalvageWorkmanship 0xA000009 maps to it). + /// </summary> + public static bool TryGetFloat(ReadOnlySpan<byte> pwd, uint stype, out double value) + { + value = 0; + switch (stype) + { + case 54: + if (UseRadius + 4 > pwd.Length) return false; + value = BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(pwd.Slice(UseRadius))); + break; + case 167: + if (CooldownDuration + 8 > pwd.Length) return false; + value = BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(pwd.Slice(CooldownDuration))); + break; + case 280: + if (Workmanship + 4 > pwd.Length) return false; + value = BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(pwd.Slice(Workmanship))); + break; + default: + return false; + } + return value != 0 && double.IsFinite(value); + } +} diff --git a/src/RynthCore.Engine/Compatibility/RadarHooks.cs b/src/RynthCore.Engine/Compatibility/RadarHooks.cs index c0ef66d..33cc458 100644 --- a/src/RynthCore.Engine/Compatibility/RadarHooks.cs +++ b/src/RynthCore.Engine/Compatibility/RadarHooks.cs @@ -85,6 +85,8 @@ internal static class RadarHooks private static GmRadarUIDrawChildrenDelegate? _drawChildrenDetour; private static IntPtr _gmRadarUIInstance; + // Logoff requested, logout not yet complete: the radar is being freed (see ChatHooks). + private static volatile bool _logoffInProgress; private static IntPtr _uiElementSetVisibleAddress; private static IntPtr _uiElementGetSurfaceBoxAddress; private static bool _hookInstalled; @@ -205,7 +207,7 @@ internal static class RadarHooks private static void DrawObjectsDetour(IntPtr thisPtr, IntPtr uiSurface) { RecursionGuard.Tick("RadarHooks.DrawObjects"); - if (thisPtr != IntPtr.Zero) + if (thisPtr != IntPtr.Zero && !_logoffInProgress) _gmRadarUIInstance = thisPtr; int hit = Interlocked.Increment(ref _drawObjectsHits); @@ -231,7 +233,7 @@ internal static class RadarHooks private static void DrawChildrenDetour(IntPtr thisPtr, IntPtr clipRect, IntPtr clipInside, IntPtr boxArray, IntPtr uiSurface) { RecursionGuard.Tick("RadarHooks.DrawChildren"); - if (thisPtr != IntPtr.Zero) + if (thisPtr != IntPtr.Zero && !_logoffInProgress) _gmRadarUIInstance = thisPtr; int hit = Interlocked.Increment(ref _drawChildrenHits); @@ -292,9 +294,17 @@ internal static class RadarHooks } } + /// <summary>A logoff was requested: drop the radar before AC frees it (see ChatHooks.OnLogoffRequested).</summary> + public static void OnLogoffRequested() + { + _logoffInProgress = true; + _gmRadarUIInstance = IntPtr.Zero; + } + public static void ResetCachedInstance() { _gmRadarUIInstance = IntPtr.Zero; + _logoffInProgress = false; _isHiddenAsserted = false; } diff --git a/src/RynthCore.Engine/Compatibility/RetailVitalsHooks.cs b/src/RynthCore.Engine/Compatibility/RetailVitalsHooks.cs new file mode 100644 index 0000000..d9f95e3 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/RetailVitalsHooks.cs @@ -0,0 +1,451 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/RetailVitalsHooks.cs +// +// "Hide retail vitals": hides AC's own health/stamina/mana bars, now that the +// RynthVision player plate and the RynthAi dashboard bars replace them. Same +// shape as ChatHooks / RadarHooks: capture the UIElement, then EndSceneHook +// calls TickHide every frame, which calls UIElement::SetVisible on it. +// +// What the bars are (Ghidra symbols + disassembly of the 4,841,472-byte client): +// gmVitalsUI (element class 0x10000009, 0x618 bytes) derives from +// UIElement_Field, so the UIElement is at offset 0; NoticeHandler sits at +// +0x5F8 and the QualityChangeHandler at +0x5FC. Two subclasses carry the +// bars on screen: gmFloatyVitalsUI (0x1000004D, stacked) and +// gmFloatySideVitalsUI (0x10000056, side by side). Both exist at once and AC +// shows one and hides the other with UIElement::SetVisible (vtable slot 0x18), +// per the "Side by side vitals" option (gmGamePlayUI:: +// RecvNotice_PlayerOptionChanged, 0x004EAA30). +// +// Capture: gmVitalsUI::Update (0x004C0AB0), thiscall with no arguments. It is +// only reached through two thunks, OnQualityChanged (add ecx,-0x5FC) and +// RecvNotice_PlayerDescReceived (add ecx,-0x5F8), so its 'this' is always the +// primary (UIElement) pointer - unlike gmPowerbarUI's RecvNotice_* hooks, whose +// 'this' was the NoticeHandler sub-object and crashed SetVisible +// (PowerbarHooks.TickHide). It runs at login (player description) and on every +// health/stamina/mana change, for every gmVitalsUI-family instance. +// As a second check, an instance is only kept if its vtable's slot 0x18 is +// UIElement::SetVisible (directly or through a one-jmp thunk): exactly the +// function TickHide calls, and the one AC itself calls on these objects. +// +// Restore: TickHide hides only instances whose own visible flag is set, and +// remembers which ones it hid; with the option off it shows exactly those +// again, once. The hidden sibling (stacked vs side by side) is never shown. +// +// Freed instances: dropped when a logoff is requested (LogoffOriginProbe) and +// when the logout completes (PluginManager), as the chat and radar are; and +// every tick checks the object is still readable and still has the vtable it +// had when captured (MSVC destructors reset the vtable to the base class's, +// so a destroyed gmFloaty*VitalsUI fails the check). +// +// Installed from PowerbarHooks.Initialize (the "powerbar hooks" init step) +// because EntryPoint.cs is not edited for this. Both addresses go through +// HookResolver: pattern first, fallback VA second. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class RetailVitalsHooks +{ + // Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth. + private const int GmVitalsUIUpdateFallbackVa = 0x004C0AB0; + private const int UIElementSetVisibleFallbackVa = 0x00462390; + + // gmVitalsUI::Update() - 0xA4-byte frame, then InterfaceSystem::GetInstance for + // the PlayerDesc (push imm32 = its interface id). Unique in the text window + // (checked with tools\pe_pattern.py; the first 11 bytes alone are unique). + private static readonly byte?[] UpdatePattern = + [ + 0x81, 0xEC, 0xA4, 0x00, 0x00, 0x00, // sub esp, 0xA4 + 0x53, 0x55, 0x56, 0x57, // push ebx/ebp/esi/edi + 0x8D, 0x44, 0x24, 0x10, 0x50, // lea eax,[esp+10h]; push eax + 0x8B, 0xF1, // mov esi, ecx + 0x8D, 0x4C, 0x24, 0x18, // lea ecx,[esp+18h] + 0x68, null, null, null, null, // push imm32 (interface id) + 0x33, 0xFF, 0x51, // xor edi,edi; push ecx + 0x89, 0x7C, 0x24, 0x1C, // mov [esp+1Ch], edi + 0xE8, null, null, null, null, // call rel32 (InterfaceSystem::GetInstance) + 0x8B, 0xC8, // mov ecx, eax + 0xE8, null, null, null, null // call rel32 (InterfaceSystem::GetClass) + ]; + + // UIElement::SetVisible(bool) - the same pattern ChatHooks / RadarHooks / + // PowerbarHooks resolve; each consumer resolves it independently. + private static readonly byte?[] UIElementSetVisiblePattern = + [ + 0x51, 0x53, 0x56, 0x57, + 0x8B, 0x3D, null, null, null, null, // mov edi, ds:[imm32] + 0x8B, 0xF1, + 0xE8, null, null, null, null, // call rel32 + 0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00, + 0x88, 0x44, 0x24, 0x0F + ]; + + // UIRegion's own "visible" flag: bit 1 of the dword at +0xA4. UIRegion::SetVisible + // writes it and UIElement::SetVisible reads it before and after; reading it here + // has no side effects (UIElement::IsVisible walks the parents and calls virtuals). + private const int RegionFlagsOffset = 0xA4; + private const int RegionVisibleBit = 0x2; + private const int SetVisibleVtableSlot = 0x18; + + // Up to four gmVitalsUI-family objects at once (AC builds two: stacked + side by side). + private const int MaxInstances = 4; + + private struct Slot + { + public IntPtr Instance; + public IntPtr Vtable; // the instance's vtable when captured + public bool HiddenByUs; // TickHide turned it off; show it again when the option goes off + } + + // Written by UpdateDetour and read by TickHide, both on AC's main thread only. + private static readonly Slot[] Slots = new Slot[MaxInstances]; + + // Set when a logoff is requested, cleared when the logout completes: AC frees the + // vitals UI during the logoff and Update can still fire on a dying one, so nothing + // is captured in between (as ChatHooks). + private static volatile bool _logoffInProgress; + + private static IntPtr _uiElementSetVisibleAddress; + private static IntPtr _originalUpdate; + private static bool _hookInstalled; + private static string _statusMessage = "Not initialized."; + private static int _updateFires; + private static int _rejectLogs; + + public static bool IsInstalled => _hookInstalled; + public static string StatusMessage => _statusMessage; + + // ── The setting ─────────────────────────────────────────────────────────── + + private static readonly object SettingSync = new(); + private static volatile bool _hide; + private static bool _settingLoaded; + + private static string SettingPath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "retail_ui.txt"); + private const string HideVitalsKey = "HideRetailVitals"; + + /// <summary> + /// The "Hide retail vitals" option. Stored for the whole PC in + /// %LOCALAPPDATA%\RynthCore\retail_ui.txt ("HideRetailVitals=1"), beside the + /// engine's other in-client UI settings (panel_text_size.txt, + /// nameplate_settings.txt). Set from Settings > UI or /rc ui retailvitals. + /// Any thread: it only flips a flag and writes the file; TickHide applies it + /// on AC's main thread. + /// </summary> + public static bool HideRetailVitals + { + get { EnsureSettingLoaded(); return _hide; } + set + { + EnsureSettingLoaded(); + lock (SettingSync) + { + if (_hide == value) return; + _hide = value; + SaveSetting(); + } + RynthLog.Compat($"RetailVitalsHooks: Hide retail vitals -> {value} (installed={_hookInstalled}, captured={CountCaptured()})."); + } + } + + public static void EnsureSettingLoaded() + { + if (_settingLoaded) return; + lock (SettingSync) + { + if (_settingLoaded) return; + _settingLoaded = true; + try + { + string path = SettingPath; + if (!File.Exists(path)) return; + foreach (string line in File.ReadAllLines(path)) + { + int eq = line.IndexOf('='); + if (eq <= 0 || !line[..eq].Trim().Equals(HideVitalsKey, StringComparison.OrdinalIgnoreCase)) continue; + if (int.TryParse(line.AsSpan(eq + 1).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int v)) + _hide = v != 0; + } + } + catch (Exception ex) + { + RynthLog.Compat($"RetailVitalsHooks: could not read {SettingPath}: {ex.GetType().Name}: {ex.Message}"); + } + } + } + + // Caller holds SettingSync. Keeps any other key=value lines in the file. + private static void SaveSetting() + { + try + { + string path = SettingPath; + var lines = new List<string>(); + if (File.Exists(path)) + { + foreach (string line in File.ReadAllLines(path)) + { + int eq = line.IndexOf('='); + if (eq > 0 && line[..eq].Trim().Equals(HideVitalsKey, StringComparison.OrdinalIgnoreCase)) continue; + if (line.Trim().Length > 0) lines.Add(line); + } + } + lines.Add($"{HideVitalsKey}={(_hide ? 1 : 0)}"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllLines(path, lines); + } + catch (Exception ex) + { + RynthLog.Compat($"RetailVitalsHooks: could not save {SettingPath}: {ex.GetType().Name}: {ex.Message}"); + } + } + + // ── Install ─────────────────────────────────────────────────────────────── + + public static void Initialize() + { + EnsureSettingLoaded(); + if (_hookInstalled) + return; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection)) + { + _statusMessage = "acclient.exe not available."; + return; + } + + var setVisible = HookResolver.Resolve(textSection, "RetailVitalsHooks.UIElement::SetVisible", + UIElementSetVisiblePattern, UIElementSetVisibleFallbackVa); + if (!setVisible.Success) + { + _statusMessage = $"UIElement::SetVisible resolve failed ({setVisible.Detail})."; + RynthLog.Compat($"RetailVitalsHooks: {_statusMessage} Not hooked."); + return; + } + + var update = HookResolver.Resolve(textSection, "RetailVitalsHooks.gmVitalsUI::Update", + UpdatePattern, GmVitalsUIUpdateFallbackVa); + if (!update.Success) + { + _statusMessage = $"gmVitalsUI::Update resolve failed ({update.Detail})."; + RynthLog.Compat($"RetailVitalsHooks: {_statusMessage} Not hooked."); + return; + } + + // Only hook through a pattern match: a guessed address for a hook target is + // worse than no "Hide retail vitals" (the fallback VA is logged as RISKY and + // refused here; the option then does nothing). + if (update.Source != HookResolver.ResolveSource.PatternScan) + { + _statusMessage = $"gmVitalsUI::Update only resolved by fallback VA ({update.Detail}); not hooked."; + RynthLog.Compat($"RetailVitalsHooks: {_statusMessage}"); + return; + } + + try + { + _uiElementSetVisibleAddress = setVisible.Address; + delegate* unmanaged[Thiscall]<IntPtr, void> detour = &UpdateDetour; + MinHook.Hook(update.Address, (IntPtr)detour, out _originalUpdate); + _hookInstalled = true; + _statusMessage = $"Hooked gmVitalsUI::Update @ 0x{update.Address.ToInt32():X8} ({update.Detail}); SetVisible @ 0x{setVisible.Address.ToInt32():X8}."; + RynthLog.Compat($"RetailVitalsHooks: {_statusMessage} Hide retail vitals={_hide}."); + } + catch (Exception ex) + { + _originalUpdate = IntPtr.Zero; + _statusMessage = ex.Message; + RynthLog.Compat($"RetailVitalsHooks: install threw {ex.GetType().Name}: {ex.Message}"); + } + } + + // ── Capture (AC's main thread; must never throw into AC) ───────────────── + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })] + private static void UpdateDetour(IntPtr thisPtr) + { + try + { + RecursionGuard.Tick("RetailVitalsHooks.Update"); + if (thisPtr != IntPtr.Zero && !_logoffInProgress && MainThreadGuard.IsOnMainThread()) + Capture(thisPtr); + } + catch { } + ((delegate* unmanaged[Thiscall]<IntPtr, void>)_originalUpdate)(thisPtr); + } + + private static void Capture(IntPtr inst) + { + int free = -1; + for (int i = 0; i < Slots.Length; i++) + { + if (Slots[i].Instance == inst) return; // already have it + if (free < 0 && Slots[i].Instance == IntPtr.Zero) free = i; + } + + if (++_updateFires <= 6) + RynthLog.Compat($"RetailVitalsHooks: Update fired on new instance 0x{inst.ToInt32():X8}."); + + if (!ClientObjectHooks.IsReadableSpan(inst, RegionFlagsOffset + 4)) + { + Reject(inst, "object not readable"); + return; + } + IntPtr vtable = Marshal.ReadIntPtr(inst); + if (!IsSetVisibleSlot(vtable)) + { + Reject(inst, $"vtable 0x{vtable.ToInt32():X8} slot 0x{SetVisibleVtableSlot:X} is not UIElement::SetVisible"); + return; + } + + if (free < 0) + { + // Full: reuse a slot whose object is gone. With none, keep the ones we have. + for (int i = 0; i < Slots.Length; i++) + { + if (!StillAlive(Slots[i])) { free = i; break; } + } + if (free < 0) + { + Reject(inst, "all slots hold live instances"); + return; + } + } + + Slots[free] = new Slot { Instance = inst, Vtable = vtable, HiddenByUs = false }; + RynthLog.Compat($"RetailVitalsHooks: captured vitals element 0x{inst.ToInt32():X8} (vtable 0x{vtable.ToInt32():X8}, visible={IsOwnVisible(inst)})."); + } + + private static void Reject(IntPtr inst, string why) + { + if (++_rejectLogs <= 8) + RynthLog.Compat($"RetailVitalsHooks: not capturing 0x{inst.ToInt32():X8}: {why}."); + } + + /// <summary> + /// The vtable's SetVisible slot must be UIElement::SetVisible itself, or a + /// one-instruction "jmp rel32" thunk to it (incremental-link thunks: the + /// floaty classes' slot is 0x004CF950: jmp 0x00462390). + /// </summary> + private static bool IsSetVisibleSlot(IntPtr vtable) + { + IntPtr setVisible = _uiElementSetVisibleAddress; + if (setVisible == IntPtr.Zero) return false; + if (!ClientObjectHooks.IsReadableSpan(vtable, SetVisibleVtableSlot + 4)) return false; + IntPtr fn = Marshal.ReadIntPtr(vtable, SetVisibleVtableSlot); + if (fn == setVisible) return true; + if (!ClientObjectHooks.IsReadableSpan(fn, 5)) return false; + if (Marshal.ReadByte(fn) != 0xE9) return false; + int rel = Marshal.ReadInt32(fn, 1); + return unchecked(fn.ToInt32() + 5 + rel) == setVisible.ToInt32(); + } + + // ── Per-frame visibility (EndSceneHook, AC's main thread) ───────────────── + + public static void TickHide() + { + if (!_hookInstalled) return; + if (!LoginLifecycleHooks.HasObservedLoginComplete) return; + if (_logoffInProgress) return; + if (!MainThreadGuard.IsOnMainThread()) return; + IntPtr setVisible = _uiElementSetVisibleAddress; + if (setVisible == IntPtr.Zero) return; + + bool hide = _hide; + for (int i = 0; i < Slots.Length; i++) + { + IntPtr inst = Slots[i].Instance; + if (inst == IntPtr.Zero) continue; + if (!StillAlive(Slots[i])) + { + RynthLog.Compat($"RetailVitalsHooks: vitals element 0x{inst.ToInt32():X8} is gone (freed); dropped until it is captured again."); + Slots[i] = default; + continue; + } + + bool visible = IsOwnVisible(inst); + if (hide) + { + // Only the one AC is showing; its hidden sibling stays AC's business. + if (visible) + { + try { ((delegate* unmanaged[Thiscall]<IntPtr, int, void>)setVisible)(inst, 0); } + catch { /* best-effort */ } + Slots[i].HiddenByUs = true; + } + } + else if (Slots[i].HiddenByUs) + { + if (!visible) + { + try { ((delegate* unmanaged[Thiscall]<IntPtr, int, void>)setVisible)(inst, 1); } + catch { /* best-effort */ } + } + Slots[i].HiddenByUs = false; + } + } + } + + private static bool IsOwnVisible(IntPtr inst) => + (Marshal.ReadInt32(inst, RegionFlagsOffset) & RegionVisibleBit) != 0; + + /// <summary> + /// The object is still readable and still starts with the vtable it had when + /// captured. A destroyed gmVitalsUI-family object has had its vtable reset to + /// a base class's by the destructor chain (or its memory reused/decommitted). + /// </summary> + private static bool StillAlive(in Slot s) + { + if (s.Instance == IntPtr.Zero) return false; + if (!ClientObjectHooks.IsReadableSpan(s.Instance, RegionFlagsOffset + 4)) return false; + return Marshal.ReadIntPtr(s.Instance) == s.Vtable; + } + + private static int CountCaptured() + { + int n = 0; + for (int i = 0; i < Slots.Length; i++) + if (Slots[i].Instance != IntPtr.Zero) n++; + return n; + } + + /// <summary>One line for /rc ui retailvitals.</summary> + public static string Describe() + { + int hidden = 0; + for (int i = 0; i < Slots.Length; i++) + if (Slots[i].Instance != IntPtr.Zero && Slots[i].HiddenByUs) hidden++; + string state = !_hookInstalled + ? $"not available ({_statusMessage})" + : $"{CountCaptured()} vitals element(s) captured, {hidden} hidden by RynthCore"; + return $"Hide retail vitals is {(HideRetailVitals ? "ON" : "OFF")} - {state}."; + } + + // ── Logout / relog ──────────────────────────────────────────────────────── + + /// <summary> + /// A logoff was requested (LogoffOriginProbe): drop the vitals elements now, + /// before AC frees them (see ChatHooks.OnLogoffRequested). AC's main thread. + /// </summary> + public static void OnLogoffRequested() + { + _logoffInProgress = true; + for (int i = 0; i < Slots.Length; i++) Slots[i] = default; + } + + /// <summary>The logout completed (PluginManager's logout dispatch): the next login builds new ones.</summary> + public static void ResetCachedInstance() + { + for (int i = 0; i < Slots.Length; i++) Slots[i] = default; + _logoffInProgress = false; + } +} diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 3706a56..125d05f 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -1,4 +1,5 @@ using System; +using S = RynthCore.Engine.ImGuiBackend.Hud.MonsterHudSettings; namespace RynthCore.Engine.Compatibility; @@ -17,12 +18,37 @@ namespace RynthCore.Engine.Compatibility; /// button rides the bar itself, so it's unreachable once the bar is). /// The launcher button writes this to dispatch.txt as the out-of-band /// recovery.</item> +/// <item><c>/rc actionstate</c> (alias <c>/rc actions</c>) — read-only: the client's +/// item-action gates (pending item request, attacking flag, busy count, +/// target mode, combat state), see <see cref="ClientActionGates"/>. +/// <c>/rc unlockactions</c> (alias <c>/rc unlock</c>) opens those gates now.</item> /// <item><c>/rc vitals</c> (alias <c>/rc hud</c>) — toggle the custom D3D9 /// Health/Stamina/Mana HUD on/off (persisted to engine.json).</item> +/// <item><c>/rc ui retailvitals [on|off|status]</c> — hide AC's own +/// health/stamina/mana bars (<see cref="RetailVitalsHooks"/>; saved for the +/// PC, also in Settings > UI). Alone it reports the state.</item> /// <item><c>/rc vendor [list|info|status|buy <id|sel> [n]|sell <id|sel> [id ...]]</c> /// — read / trade with the open vendor through the engine's vendor /// primitives (<see cref="VendorTrade"/>); a manual test hook for the /// plugin API. Replies go to chat from the main-thread drain and to the log.</item> +/// <item><c>/rc chathold [on|off|status]</c> — incoming chat waits for the plugins' +/// verdict before AC prints it, so a line a plugin eats is kept out of AC's chat +/// window too (<see cref="ChatCallbackHooks"/>). On at every start; not saved.</item> +/// <item><c>/rv plates</c> (aliases <c>/rv nameplates</c>, <c>/rc plates</c>) — the +/// RynthVision nameplates and combat text: monster plates on|off, self, debuffs, +/// numbers, gains [on|off] (with their sub-switches), all on|off, all|engaged, +/// dist/max/scale/opacity/lift <n>, field toggles, reset, status +/// (<see cref="ImGuiBackend.Hud.MonsterHud"/>). "/rv plates" is caught here, +/// before plugin pre-dispatch, so the RynthVision plugin's own "/rv" handler +/// never sees it; every other "/rv" line still goes to the plugin.</item> +/// <item><c>/rc server [auto|aelrynth|other]</c> — which server the engine detects +/// (<see cref="ServerInfo"/>) and why; aelrynth/other force it for this session.</item> +/// <item><c>/rc mastery</c> — the Aelrynth mastery feed's state (<see cref="MasteryFeed"/>), +/// and ask the server for /mastery-data again.</item> +/// <item><c>/rc worldlayer [auto|uipass|transition|endscene]</c> — where the world overlays +/// (nameplates, combat text, Nav3D markers) draw in AC's frame +/// (<see cref="D3D9.Nav3DRenderInjector"/>): alone it reports the path and counters; +/// a mode forces it for this session (A/B checks). Auto at every start; not saved.</item> /// </list> /// </summary> internal static class RynthCoreChatCommands @@ -40,6 +66,21 @@ internal static class RynthCoreChatCommands return false; string trimmed = line.Trim(); + + // /rv plates ... : the RynthVision overlays live engine-side, so the engine answers + // before the plugin's "/rv" prefix handler would (it runs after this, on pre-dispatch). + if (trimmed.StartsWith("/rv ", StringComparison.OrdinalIgnoreCase)) + { + string rv = trimmed.Substring(4).Trim(); + if (IsVerb(rv, "plates", out string rvArgs) || IsVerb(rv, "nameplates", out rvArgs)) + { + try { HandlePlatesCommand(rvArgs); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rv plates failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + return false; + } + if (!trimmed.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase)) return false; @@ -54,23 +95,136 @@ internal static class RynthCoreChatCommands return true; } + // /rc imgui [on|off|fonttest] + if (sub.Equals("imgui", StringComparison.OrdinalIgnoreCase) + || sub.StartsWith("imgui ", StringComparison.OrdinalIgnoreCase)) + { + try { HandleImGuiCommand(sub.Length > 5 ? sub.Substring(6).Trim() : string.Empty); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc imgui failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + + // /rc ui list | /rc ui <Panel> avalonia|imgui|both + if (sub.Equals("ui", StringComparison.OrdinalIgnoreCase) + || sub.StartsWith("ui ", StringComparison.OrdinalIgnoreCase)) + { + try { HandleUiCommand(sub.Length > 2 ? sub.Substring(3).Trim() : string.Empty); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc ui failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + + // /rc chathold [on|off|status]: lines a plugin eats stay out of AC's chat window too + if (IsVerb(sub, "chathold", out string holdArgs)) + { + try { HandleChatHoldCommand(holdArgs); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc chathold failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + + // /rc plates [on|off|all|engaged|dist N|max N|scale X|opacity X|lift X|names|hp|level|weak|distance|fade|reset|status] + if (IsVerb(sub, "plates", out string platesArgs) || IsVerb(sub, "nameplates", out platesArgs)) + { + try { HandlePlatesCommand(platesArgs); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc plates failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + + // /rc server [auto|aelrynth|other] : which server the engine thinks this is (testing override) + if (IsVerb(sub, "server", out string serverArgs)) + { + try { HandleServerCommand(serverArgs); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc server failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + + // /rc mastery : the Aelrynth mastery feed's state, and ask the server again + if (IsVerb(sub, "mastery", out _)) + { + try { HandleMasteryCommand(); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc mastery failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + + // /rc worldlayer [auto|uipass|transition|endscene] : where the world overlays draw + if (IsVerb(sub, "worldlayer", out string worldArgs)) + { + try { HandleWorldLayerCommand(worldArgs); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc worldlayer failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + + // /rc vtank [clear] : what the engine knows about VTank's macro (Decal bridge only); + // clear = VTank was stopped with its own button, which the engine can't see. + if (IsVerb(sub, "vtank", out string vtankArgs)) + { + if (vtankArgs.Equals("clear", StringComparison.OrdinalIgnoreCase)) + Reply(VTankWatch.Clear() ? "VTank marked as not running; RynthAi's macro can start again." : "VTank was already marked as not running."); + Reply(VTankWatch.Describe()); + return true; + } + switch (sub.ToLowerInvariant()) { + case "rl": + case "reload": + // Same as the bar's RL button. Signalled from a pool thread: the + // loader's reload shuts this engine down, and this handler runs + // inside AC's outgoing-chat hook. + RynthLog.Compat("RynthCoreChatCommands: /rc rl — engine reload requested."); + System.Threading.ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null); + return true; + + case "inv": + case "inventory": + // The ImGui Inventory panel (open/close), like its bar button. + if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.InventoryFace.Title)) + Reply("The Inventory panel isn't available (the ImGui layer is off?)."); + else + UI.PanelRouter.Toggle(ImGuiBackend.Panels.InventoryFace.Title); + return true; + + case "sense": + // The ImGui Sense panel (open/close), like its bar button. + if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SenseFace.Title)) + Reply("The Sense panel isn't available (the ImGui layer is off?)."); + else + UI.PanelRouter.Toggle(ImGuiBackend.Panels.SenseFace.Title); + return true; + case "resetbar": case "barreset": RynthLog.Compat("RynthCoreChatCommands: /rc resetbar — resetting overlay bar position."); ImGuiBackend.RynthCoreShell.RequestExternalReset(); return true; + case "actionstate": + case "actions": + // Read-only: every client-side gate on item use/equip/move + // (ClientActionGates). Works while those are locked — chat still does. + try + { + foreach (string stateLine in ClientActionGates.DescribeLines()) + Reply(stateLine); + } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc actionstate failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + + case "unlockactions": + case "unlock": + try + { + foreach (string unlockLine in ClientActionGates.RequestUnlock()) + Reply(unlockLine); + } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc unlockactions failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + case "vitals": case "hud": { - // Toggle the custom D3D9 vital HUD. Setter persists to engine.json - // so it survives relaunch. (No AC-chat echo — the AddTextToScroll - // path has a known AV risk; the HUD appearing/vanishing confirms.) - bool now = !Plugins.EngineSettings.DrawCustomVitalBars; - Plugins.EngineSettings.DrawCustomVitalBars = now; - RynthLog.Compat($"RynthCoreChatCommands: /rc vitals — custom vital HUD {(now ? "ON" : "OFF")}."); + // The old D3D9 vitals HUD is gone (2026-09-29): your vitals are the + // RynthVision player plate now. + Reply("The old vitals HUD was removed. Your health/stamina/mana bars are the RynthVision player plate: /rv plates self [on|off]."); return true; } @@ -81,4 +235,438 @@ internal static class RynthCoreChatCommands return true; } } + + /// <summary> + /// /rc ui list, or /rc ui <Panel> avalonia|imgui|both: which face shows a + /// panel while it is docked in the client (UI.PanelRouter). Replies are + /// queued to chat, not written from inside this outgoing-chat hook. + /// </summary> + private static void HandleUiCommand(string args) + { + string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0 || parts[0].Equals("list", StringComparison.OrdinalIgnoreCase)) + { + foreach (string line in UI.PanelRouter.Describe()) + Reply(line); + return; + } + + // /rc ui retailvitals [on|off]: hide AC's own health/stamina/mana bars + // (RetailVitalsHooks). Alone it reports; anything but on/off toggles. + if (parts[0].Equals("retailvitals", StringComparison.OrdinalIgnoreCase)) + { + if (parts.Length >= 2 && parts[1].Equals("status", StringComparison.OrdinalIgnoreCase)) + { + Reply(RetailVitalsHooks.Describe()); + return; + } + if (parts.Length >= 2) + RetailVitalsHooks.HideRetailVitals = Flag(parts[1], RetailVitalsHooks.HideRetailVitals); + Reply(RetailVitalsHooks.Describe()); + return; + } + + // /rc ui open|close|popout|redock|snap <Panel>: drive a panel by name (tests, + // dispatch.txt). Names may have spaces ("Monster Detail"). + string verb = parts[0].ToLowerInvariant(); + if (verb is "open" or "close" or "popout" or "redock" or "snap" && parts.Length >= 2) + { + // "Monsters" (the retired basic panel) is the Damage panel now. + string title = UI.PanelRouter.Canonical(string.Join(' ', parts, 1, parts.Length - 1)); + if (title.Equals("bar", StringComparison.OrdinalIgnoreCase) && verb is "popout" or "redock") + { + ImGuiBackend.ImGuiBar.SetPoppedOut(verb == "popout"); + Reply($"/rc ui {verb} bar: requested."); + return; + } + if (title.Equals("bar", StringComparison.OrdinalIgnoreCase) && verb == "snap") title = "__bar"; + else if (!ImGuiBackend.ImGuiPanelHost.HasFace(title)) { Reply($"No ImGui panel named '{title}'."); return; } + switch (verb) + { + case "open": ImGuiBackend.ImGuiPanelHost.Open(title); break; + case "close": ImGuiBackend.ImGuiPanelHost.Close(title); break; + case "popout": ImGuiBackend.ImGuiPanelHost.PopOut(title); break; + case "redock": ImGuiBackend.ImGuiPanelHost.Redock(title); break; + case "snap": + ImGuiBackend.Win32Backend.PostToGameThread(() => + RynthLog.UI($"/rc ui snap {title}: " + (ImGuiBackend.ImGuiPopOuts.RequestSnapshot(title) ?? "not popped out"))); + break; + } + Reply($"/rc ui {verb} {title}: requested."); + return; + } + + if (parts.Length != 2 || !UI.PanelFaceStore.TryParseFace(parts[1], out UI.PanelFace face)) + { + Reply("Usage: /rc ui list | /rc ui <Panel|bar> avalonia|imgui|both | /rc ui open|close|popout|redock|snap <Panel> | /rc ui retailvitals [on|off]"); + return; + } + + Reply(UI.PanelRouter.SetDockedFace(parts[0], face)); + } + + /// <summary> + /// /rc imgui on|off switches the engine's in-client ImGui layer live and + /// saves it to engine.json; /rc imgui fonttest toggles the font/theme test + /// window; /rc imgui alone reports the state. + /// </summary> + private static void HandleImGuiCommand(string arg) + { + switch (arg.ToLowerInvariant()) + { + case "on": + Plugins.EngineSettings.EnableImGuiBackend = true; + ImGuiBackend.ImGuiBar.ApplyFace(); + Reply("ImGui layer ON (saved). The self-test result is in the log (ImGuiSelfTest:). Panels: /rc ui list."); + return; + case "off": + Plugins.EngineSettings.EnableImGuiBackend = false; + ImGuiBackend.Win32Backend.ClearCaptureFlags(); + ImGuiBackend.Win32Backend.DiscardQueuedInput(); + ImGuiBackend.ImGuiBar.ApplyFace(); // the Avalonia bar comes back + Reply("ImGui layer OFF (saved)."); + return; + case "fonttest": + ImGuiBackend.ImGuiFontTest.Enabled = !ImGuiBackend.ImGuiFontTest.Enabled; + Reply($"ImGui font test window {(ImGuiBackend.ImGuiFontTest.Enabled ? "shown" : "hidden")}" + + (Plugins.EngineSettings.EnableImGuiBackend ? "." : " (the ImGui layer is off: /rc imgui on).")); + return; + case "diag": + foreach (string line in ImGuiBackend.EngineFrameController.DescribeState()) + RynthLog.Info("ImGuiDiag: " + line); + foreach (string line in ImGuiBackend.ImGuiPanelHost.DescribeFaces()) + RynthLog.Info("ImGuiDiag: " + line); + foreach (string line in UI.ScriptWindows.ScriptWindowRegistry.Describe()) + RynthLog.Info("ImGuiDiag: " + line); + RynthLog.Info($"ImGuiDiag: bar visible={ImGuiBackend.ImGuiBar.Visible} face={UI.PanelFaceStore.FaceName(ImGuiBackend.ImGuiBar.ResolveFace())} avaloniaBarSuppressed={UI.AvaloniaOverlay.DockedBarSuppressed}"); + Reply("ImGui diagnostics written to the RynthCore log (ImGuiDiag:)."); + return; + case "": + Reply($"ImGui layer is {(Plugins.EngineSettings.EnableImGuiBackend ? "ON" : "OFF")}. Usage: /rc imgui on|off|fonttest|diag"); + return; + default: + Reply("Usage: /rc imgui on|off|fonttest|diag"); + return; + } + } + + /// <summary> + /// /rc chathold on|off|status: incoming chat waits for the plugins before AC prints it, + /// so a line a plugin eats (RynthAi's Meta Manager eats the reply to its own /myquests) + /// is not shown in AC's chat window either (ChatCallbackHooks, IncomingChatHold.cs). + /// On at every start; off prints every line at once, as before, and plugins can then + /// only keep a line out of RynthChat. + /// </summary> + private static void HandleChatHoldCommand(string arg) + { + switch (arg.ToLowerInvariant()) + { + case "on": + ChatCallbackHooks.SetHoldEnabled(true); + break; + case "off": + ChatCallbackHooks.SetHoldEnabled(false); + break; + case "": + case "status": + break; + default: + Reply("Usage: /rc chathold [on|off|status]"); + return; + } + Reply(ChatCallbackHooks.HoldStatusText()); + } + + /// <summary>"verb" or "verb args..." (case-insensitive); args trimmed.</summary> + /// <summary> + /// /rc server: the detection verdict and its signals. "aelrynth" / "other" force it + /// for this session (to test the Aelrynth-only features anywhere, or to see a + /// non-Aelrynth client on Aelrynth); "auto" goes back to detecting. Never saved. + /// </summary> + private static void HandleServerCommand(string args) + { + switch (args.Trim().ToLowerInvariant()) + { + case "aelrynth": case "on": ServerInfo.Override = ServerInfo.Mode.ForceAelrynth; break; + case "other": case "off": ServerInfo.Override = ServerInfo.Mode.ForceOther; break; + case "auto": ServerInfo.Override = ServerInfo.Mode.Auto; break; + case "": break; + default: + Reply("Usage: /rc server [auto|aelrynth|other]"); + return; + } + ServerVerdict v = ServerInfo.Current; + Reply($"Server: {(v.IsAelrynth ? (v.IsStaging ? "Aelrynth (staging)" : "Aelrynth") : "not Aelrynth")} - {v.Reason}."); + Reply($"Signals: host {ServerInfo.HostDescription}; world name {AccountHooks.AnnouncedWorldName ?? "(not announced)"}; " + + $"override {ServerInfo.Override}."); + Reply($"Titles (plugin API v75): {CharacterTitles.Describe()}."); + } + + private static void HandleMasteryCommand() + { + if (!ServerInfo.IsAelrynth) + { + Reply("Mastery: not on Aelrynth, so nothing is asked (/rc server for why)."); + return; + } + MasterySnapshot? s = MasteryFeed.Snapshot; + Reply($"Mastery: {MasteryFeed.Status}" + + (s != null ? $"; last reply {(Environment.TickCount64 - s.ReceivedMs) / 1000}s ago" : "; no reply this login") + + (MasteryFeed.Unsupported ? "" : ". Asking again.")); + MasteryFeed.RequestRefresh(); + } + + /// <summary> + /// /rc worldlayer: report (no argument / status) or force (auto, uipass, transition, + /// endscene) where the world overlays draw. The render thread picks the mode up next + /// frame; the DIP hook is switched at the next frame boundary. + /// </summary> + private static void HandleWorldLayerCommand(string arg) + { + D3D9.WorldLayerMode? mode = arg.ToLowerInvariant() switch + { + "auto" => D3D9.WorldLayerMode.Auto, + "uipass" or "ui" => D3D9.WorldLayerMode.UiPass, + "transition" or "zenable" => D3D9.WorldLayerMode.Transition, + "endscene" => D3D9.WorldLayerMode.EndScene, + _ => null, + }; + if (mode is { } m) + { + D3D9.Nav3DRenderInjector.Mode = m; + Reply($"World overlays now: {D3D9.Nav3DRenderInjector.DescribePath()} (this session only)."); + return; + } + if (arg.Length > 0 && !arg.Equals("status", StringComparison.OrdinalIgnoreCase)) + Reply("Usage: /rc worldlayer [auto|uipass|transition|endscene]"); + Reply(D3D9.Nav3DRenderInjector.Describe()); + Reply(ImGuiBackend.UnderUiLayer.Describe()); + } + + private static bool IsVerb(string sub, string verb, out string args) + { + args = string.Empty; + if (sub.Equals(verb, StringComparison.OrdinalIgnoreCase)) return true; + if (!sub.StartsWith(verb + " ", StringComparison.OrdinalIgnoreCase)) return false; + args = sub.Substring(verb.Length + 1).Trim(); + return true; + } + + /// <summary> + /// /rv plates (alias /rc plates): the RynthVision nameplates and combat text + /// (ImGui/MonsterHud). Alone it toggles the monster plates; on|off, all on|off, + /// self|debuffs|others|numbers|gains [sub] [on|off], all|engaged, dist|max|scale| + /// opacity|lift <n>, names|hp|level|weak|distance|fade|click [on|off], reset, status. + /// Every change is saved. + /// </summary> + private static void HandlePlatesCommand(string args) + { + const string usage = "Usage: /rv plates [on|off] | all on|off | self [numbers|name|firstperson|lock] [on|off] | " + + "self fixed|follow|unlock|reset | " + + "debuffs [on|off] | others [on|off] | numbers [dealt|taken|heals|kills] [on|off] | " + + "gains [xp|lum|radiance] [on|off] | npcs [on|off] | npcs dist <yd>|max <n> | players [on|off] | all|engaged |dist <yd>|max <n>|scale <x>|opacity <x>|lift <m> | " + + "names|hp|level|weak|distance|fade|click [on|off] | reset | status | test"; + if (!ImGuiBackend.Hud.HudFeed.VisionInstalled) + { + Reply("RynthVision isn't in the plugin list (launcher, Plugins tab), so its nameplates and combat text are off."); + return; + } + if (!ImGuiBackend.Hud.MonsterHudSettings.Loaded) + { + ImGuiBackend.Hud.MonsterHudSettings.EnsureLoadQueued(); + Reply("Nameplate settings are still loading - try again in a moment."); + return; + } + + string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries); + string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : ""; + string? value = parts.Length > 1 ? parts[1] : null; + string? sub = value != null && !IsOnOff(value) ? value.ToLowerInvariant() : null; + string? subValue = sub != null ? (parts.Length > 2 ? parts[2] : null) : value; + bool save = true; + + switch (verb) + { + case "": + S.Enabled = !S.Enabled; + break; + case "on": S.Enabled = true; break; + case "off": S.Enabled = false; break; + case "all": + // "all on|off": every overlay; "all" alone: plates for all monsters (the filter). + if (value != null && IsOnOff(value)) S.SetAll(Flag(value, true)); + else S.Filter = ImGuiBackend.Hud.PlateFilter.All; + break; + case "engaged": + case "combat": + case "target": + S.Filter = ImGuiBackend.Hud.PlateFilter.Engaged; break; + case "self": + case "me": + switch (sub) + { + case null: S.SelfPlate = Flag(subValue, S.SelfPlate); break; + case "numbers": case "text": S.SelfNumbers = Flag(subValue, S.SelfNumbers); break; + case "name": S.SelfName = Flag(subValue, S.SelfName); break; + case "firstperson": case "fp": S.SelfHideFirstPerson = Flag(subValue, S.SelfHideFirstPerson); break; + // Placement: fixed on screen (drag it while unlocked) or following the character. + case "fixed": case "screen": S.SelfPlacement = ImGuiBackend.Hud.SelfPlacement.Fixed; break; + case "follow": case "world": S.SelfPlacement = ImGuiBackend.Hud.SelfPlacement.Follow; break; + case "lock": S.SelfLocked = subValue == null || Flag(subValue, S.SelfLocked); break; + case "unlock": S.SelfLocked = false; break; + case "reset": S.SelfFixedX = S.DefaultSelfFixedX; S.SelfFixedY = S.DefaultSelfFixedY; break; + case "position": case "pos": + { + string? w = subValue?.ToLowerInvariant(); + ImGuiBackend.Hud.SelfPlatePosition? p = w switch + { + "above" or "over" or "top" or "head" => ImGuiBackend.Hud.SelfPlatePosition.Above, + "below" or "under" or "feet" or "bottom" => ImGuiBackend.Hud.SelfPlatePosition.Below, + "left" => ImGuiBackend.Hud.SelfPlatePosition.Left, + "right" => ImGuiBackend.Hud.SelfPlatePosition.Right, + _ => null, + }; + if (p == null) { Reply("usage: /rv plates self position above|below|left|right"); return; } + S.SelfPosition = p.Value; + break; + } + default: Reply(usage); return; + } + break; + case "click": + case "clickselect": + S.ClickToSelect = Flag(value, S.ClickToSelect); break; + case "onscreen": + case "keeponscreen": + S.KeepOnScreen = Flag(value, S.KeepOnScreen); break; + case "debuffs": + case "debuff": + S.ShowDebuffs = Flag(value, S.ShowDebuffs); break; + case "others": + S.ShowOthersDebuff = Flag(value, S.ShowOthersDebuff); break; + case "numbers": + case "juice": + switch (sub) + { + case null: S.Numbers = Flag(subValue, S.Numbers); break; + case "dealt": case "damage": S.NumDealt = Flag(subValue, S.NumDealt); break; + case "taken": S.NumTaken = Flag(subValue, S.NumTaken); break; + case "heals": case "heal": S.NumHeals = Flag(subValue, S.NumHeals); break; + case "kills": case "kill": case "burst": S.NumKills = Flag(subValue, S.NumKills); break; + case "restores": case "stamina": case "mana": S.NumRestores = Flag(subValue, S.NumRestores); break; + case "size": + if (!TryNum(subValue, out float nsz)) { Reply("usage: /rv plates numbers size 0.5-2.5"); return; } + S.NumSize = Math.Clamp(nsz, S.MinNumSize, S.MaxNumSize); break; + case "time": case "duration": + if (!TryNum(subValue, out float ntm)) { Reply("usage: /rv plates numbers time 0.5-3"); return; } + S.NumTime = Math.Clamp(ntm, S.MinNumTime, S.MaxNumTime); break; + default: Reply(usage); return; + } + break; + case "gains": + case "gain": + switch (sub) + { + case "size": + if (!TryNum(subValue, out float gsz)) { Reply("usage: /rv plates gains size 0.5-2.5"); return; } + S.GainSize = Math.Clamp(gsz, S.MinNumSize, S.MaxNumSize); break; + case "time": case "duration": + if (!TryNum(subValue, out float gtm)) { Reply("usage: /rv plates gains time 0.5-3"); return; } + S.GainTime = Math.Clamp(gtm, S.MinNumTime, S.MaxNumTime); break; + case null: S.Gains = Flag(subValue, S.Gains); break; + case "xp": S.GainXp = Flag(subValue, S.GainXp); break; + case "lum": case "luminance": S.GainLum = Flag(subValue, S.GainLum); break; + case "radiance": S.GainRadiance = Flag(subValue, S.GainRadiance); break; + default: Reply(usage); return; + } + break; + case "dist": + case "range": + if (!TryNum(value, out float d)) { Reply(usage); return; } + S.MaxDistance = Math.Clamp(d, S.MinDistance, S.MaxDistanceLimit); + break; + case "max": + if (!TryNum(value, out float n)) { Reply(usage); return; } + S.MaxPlates = Math.Clamp((int)Math.Round(n), S.MinPlates, S.MaxPlatesLimit); + break; + case "scale": + if (!TryNum(value, out float sc)) { Reply(usage); return; } + S.Scale = Math.Clamp(sc, S.MinScale, S.MaxScale); + break; + case "opacity": + case "alpha": + if (!TryNum(value, out float o)) { Reply(usage); return; } + if (o > 1f) o /= 100f; // "opacity 80" means 80 % + S.Opacity = Math.Clamp(o, S.MinOpacity, S.MaxOpacity); + break; + case "lift": + case "height": + if (!TryNum(value, out float h)) { Reply(usage); return; } + S.HeightLift = Math.Clamp(h, S.MinLift, S.MaxLift); + break; + case "npcs": + case "npc": + switch (sub) + { + case null: S.NpcNames = Flag(subValue, S.NpcNames); break; + case "dist": case "range": + if (!TryNum(subValue, out float nd)) { Reply("usage: /rv plates npcs dist 5-80"); return; } + S.NpcMaxDistance = Math.Clamp(nd, S.MinNpcDistance, S.MaxNpcDistanceLimit); break; + case "max": + if (!TryNum(subValue, out float nm)) { Reply("usage: /rv plates npcs max 1-40"); return; } + S.MaxNpcLabels = Math.Clamp((int)Math.Round(nm), S.MinNpcLabels, S.MaxNpcLabelsLimit); break; + default: Reply(usage); return; + } + break; + case "players": + S.PlayerNames = Flag(value, S.PlayerNames); break; + case "names": S.ShowNames = Flag(value, S.ShowNames); break; + case "hp": S.ShowHpNumbers = Flag(value, S.ShowHpNumbers); break; + case "level": S.ShowLevel = Flag(value, S.ShowLevel); break; + case "weak": S.ShowWeakness = Flag(value, S.ShowWeakness); break; + case "distance": S.ShowDistance = Flag(value, S.ShowDistance); break; + case "fade": S.FadeWithDistance = Flag(value, S.FadeWithDistance); break; + case "reset": + S.ResetToDefaults(); + save = false; + break; + case "status": + case "diag": + foreach (string line in ImGuiBackend.Hud.MonsterHud.DescribeLines()) + Reply(line); + return; + case "test": + ImGuiBackend.Hud.CombatText.SpawnTest(); + Reply("Sample combat numbers, a kill burst and gains spawned around you."); + return; + default: + Reply(usage); + return; + } + + if (save) S.Save(); + Reply(S.Describe() + + (Plugins.EngineSettings.EnableImGuiBackend ? "" : " (The ImGui layer is off, so nothing draws: /rc imgui on.)")); + } + + private static bool IsOnOff(string v) => + v.Equals("on", StringComparison.OrdinalIgnoreCase) || v.Equals("off", StringComparison.OrdinalIgnoreCase) || + v == "1" || v == "0" || v.Equals("true", StringComparison.OrdinalIgnoreCase) || v.Equals("false", StringComparison.OrdinalIgnoreCase) || + v.Equals("toggle", StringComparison.OrdinalIgnoreCase); + + private static bool TryNum(string? s, out float v) + { + v = 0; + return s != null && float.TryParse(s, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out v); + } + + /// <summary>"on"/"off" sets; anything else (or nothing) toggles.</summary> + private static bool Flag(string? value, bool current) => + value?.ToLowerInvariant() switch { "on" or "1" or "true" => true, "off" or "0" or "false" => false, _ => !current }; + + private static void Reply(string text) + { + RynthLog.Compat($"RynthCoreChatCommands: {text}"); + AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, 1); + } } diff --git a/src/RynthCore.Engine/Compatibility/ServerInfo.cs b/src/RynthCore.Engine/Compatibility/ServerInfo.cs new file mode 100644 index 0000000..2217c18 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ServerInfo.cs @@ -0,0 +1,163 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ServerInfo.cs +// +// Which server this client is on: ServerInfo.IsAelrynth is the one flag the +// Aelrynth-only features (the Skills panel's mastery) check before they show +// anything or send a server command another server wouldn't know. +// +// Signals (combined by ServerDetect.Decide, AelrynthWire.cs): +// - the launch command line's -h host[:port] / -p port (read once); +// - the world name the server announced at login (AccountHooks, the +// SendNotice_WorldName hook; not the launcher's own profile name); +// - the Bank mod's custom player properties 9101-9103 (PropertyCaches). +// Unknown means not Aelrynth. "/rc server aelrynth|other|auto" overrides it +// for this session (testing), never saved. +// +// Threads: any. Re-evaluated at most once a second; each read in between is a +// volatile load and a compare. Never touches AC (dictionary reads only). +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal static class ServerInfo +{ + public enum Mode { Auto, ForceAelrynth, ForceOther } + + private const int RefreshMs = 1000; + + private static volatile ServerVerdict _verdict = ServerVerdict.Unknown; + private static long _nextRefreshMs; + private static int _mode; // Mode + private static int _hostRead; + private static readonly object HostLock = new(); + private static string _host = ""; + private static int _port; + private static ServerHostKind _hostKind = ServerHostKind.Unknown; + private static volatile bool _bankSeen; // sticky: the properties only ever appear on Aelrynth + private static volatile bool _lastAelrynth; + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr GetCommandLineW(); + + /// <summary>True when the client is on Aelrynth (live, staging or a dev copy) - or the override says so. Any thread.</summary> + public static bool IsAelrynth => Current.IsAelrynth; + + /// <summary>Aelrynth's staging world (port 9030 / "Staging" world name). Any thread.</summary> + public static bool IsStaging => Current.IsStaging; + + public static Mode Override + { + get => (Mode)Volatile.Read(ref _mode); + set + { + Volatile.Write(ref _mode, (int)value); + Volatile.Write(ref _nextRefreshMs, 0); + } + } + + /// <summary>The current verdict (re-evaluated at most once a second). Any thread.</summary> + public static ServerVerdict Current + { + get + { + long now = Environment.TickCount64; + if (now >= Volatile.Read(ref _nextRefreshMs)) + { + Volatile.Write(ref _nextRefreshMs, now + RefreshMs); + Refresh(); + } + return _verdict; + } + } + + /// <summary>The connect host and port from the command line, for /rc server. Any thread.</summary> + public static string HostDescription + { + get + { + ReadHostOnce(); + return _host.Length == 0 ? "(none)" : _port > 0 ? $"{_host}:{_port}" : _host; + } + } + + private static void Refresh() + { + try + { + ReadHostOnce(); + if (!_bankSeen) + _bankSeen = HasBankProperties(); + + ServerVerdict v = Override switch + { + Mode.ForceAelrynth => new ServerVerdict { IsAelrynth = true, Reason = "forced on with /rc server aelrynth (testing)" }, + Mode.ForceOther => new ServerVerdict { Reason = "forced off with /rc server other (testing)" }, + _ => ServerDetect.Decide(_hostKind, _host, _port, AccountHooks.AnnouncedWorldName, _bankSeen), + }; + _verdict = v; + if (v.IsAelrynth != _lastAelrynth) + { + _lastAelrynth = v.IsAelrynth; + RynthLog.Compat($"ServerInfo: {v.Reason}"); + } + } + catch (Exception ex) + { + RynthLog.Compat($"ServerInfo: refresh failed - {ex.GetType().Name}: {ex.Message}"); + } + } + + private static void ReadHostOnce() + { + if (Volatile.Read(ref _hostRead) != 0) + return; + lock (HostLock) + { + if (_hostRead != 0) + return; + ReadHost(); + Volatile.Write(ref _hostRead, 1); + } + } + + private static void ReadHost() + { + try + { + IntPtr p = GetCommandLineW(); + string? cmd = p == IntPtr.Zero ? null : Marshal.PtrToStringUni(p); + // Only -h / -p are kept: the command line also carries the account password. + if (ServerDetect.TryParseLaunchHost(cmd, out string host, out int port)) + { + _host = host; + _port = port; + } + _hostKind = ServerDetect.ClassifyHost(_host); + } + catch + { + _hostKind = ServerHostKind.Unknown; + } + } + + private static bool HasBankProperties() + { + uint me = ClientHelperHooks.GetPlayerId(); + if (me == 0) return false; + return PropertyCaches.TryGetInt64(me, ServerDetect.RadianceEarnedProperty, out _) + || PropertyCaches.TryGetInt64(me, ServerDetect.LuminanceBankedProperty, out _) + || PropertyCaches.TryGetInt64(me, ServerDetect.LuminanceDrawnProperty, out _); + } + + /// <summary>The Bank mod's "Radiance earned this session" (9101), when the server sends it. Any thread.</summary> + public static bool TryGetRadianceEarned(out long value) + { + value = 0; + uint me = ClientHelperHooks.GetPlayerId(); + return me != 0 && PropertyCaches.TryGetInt64(me, ServerDetect.RadianceEarnedProperty, out value); + } +} diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs index 0a713a7..210d35f 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs @@ -93,6 +93,7 @@ internal static class SmartBoxHooks { delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, uint> pGeDetour = &DispatchGameEventDetour; MinHook.Hook(geAddr, (IntPtr)pGeDetour, out _originalDispatchGameEventPtr); + _gameEventHookInstalled = true; RynthLog.Verbose($"Compat: game-event hook ready @ 0x{geAddr.ToInt32():X8}"); } else RynthLog.Compat("Compat: game-event pattern matched already-hooked address."); @@ -164,6 +165,7 @@ internal static class SmartBoxHooks RecursionGuard.Tick("SmartBoxHooks.DispatchGameEvent"); var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, uint>)_originalDispatchGameEventPtr; + EnchantmentChange? enchantment = null; try { // Reject undersized payloads instead of clamping up: an inflated @@ -173,17 +175,84 @@ internal static class SmartBoxHooks { uint eventType = unchecked((uint)Marshal.ReadInt32(data)); int len = size > 0x4000 ? 0x4000 : size; + // Property messages (2026-09-30): the identify reply, PlayerDescription and every + // UpdateProperty* message pass through here, from their type on. `size` is the + // real length (the function bounds itself with data+size), so the two large ones + // get all of it (PlayerDescription runs to ~29 KB) instead of the 16 KB clamp. + ParsePropertyMessage(eventType, data, size > 0x10000 ? 0x10000 : size); ParseGameEvent(eventType, data, (uint)len); + if ((eventType >= 0x02C2 && eventType <= 0x02C8) || eventType == 0x0312) + enchantment = CaptureEnchantmentEvent(eventType, data, (uint)len); } } catch { } - return pOriginal(thisPtr, data, size); + uint status = pOriginal(thisPtr, data, size); + + // Enchantment events are queued AFTER the original ran: by then AC's + // CEnchantmentRegistry holds the change (ClientMagicSystem::Handle_Magic__* + // update it synchronously), so a plugin that re-reads the registry when the + // event reaches it on the pump sees the new state. Queue only, never call + // plugins from here (AC's main thread). + if (enchantment != null) + { + try { FlushEnchantmentEvent(enchantment); } catch { } + } + + return status; + } + + // spike/decal-bridge: set while a game event from the Decal bridge is parsed on the + // plugin pump thread, where the main-thread-only live reads must not run. + [ThreadStatic] private static bool _fromBridge; + + /// <summary> + /// spike/decal-bridge: a game event taken from Decal's raw server message instead of + /// the ProcessNetBlobData hook. <paramref name="data"/> is [eventType][payload], as the + /// hook sees it. Runs on the pump thread after AC has already applied the event, so an + /// enchantment is queued at once, and a purge (no ids on the wire) can't be diffed. + /// </summary> + internal static unsafe void ProcessBridgeGameEvent(byte* data, int size) + { + if (data == null || size < 4) + return; + uint eventType = *(uint*)data; + int len = size > 0x4000 ? 0x4000 : size; + _fromBridge = true; + try + { + ParseGameEvent(eventType, (IntPtr)data, (uint)len); + if ((eventType >= 0x02C2 && eventType <= 0x02C8) && eventType != 0x02C6) + { + EnchantmentChange? c = CaptureEnchantmentEvent(eventType, (IntPtr)data, (uint)len); + if (c != null) + FlushEnchantmentEvent(c); + } + } + catch { } + finally { _fromBridge = false; } } private static int _geEventLogCount; private static int _hpReadLogCount; + // Feeds the property caches (AppraisalHooks, PropertyUpdateHooks) from the messages that + // carry properties. Parsing only: nothing here touches AC state. Each parser is + // bounds-checked against `size` and ignores a message it can't read. + private static void ParsePropertyMessage(uint eventType, IntPtr data, int size) + { + try + { + if (eventType == PropertyWire.EventIdentifyObjectResponse) + AppraisalHooks.OnIdentifyWire(data, size); + else if (eventType == PropertyWire.EventPlayerDescription) + PropertyUpdateHooks.OnPlayerDescriptionWire(data, size); + else if (PropertyWire.IsPropertyUpdateOpcode(eventType)) + PropertyUpdateHooks.OnUpdateWire(data, size); + } + catch { } + } + // Parse an inbound GameEvent for the events combat cares about. `data` points // at the event blob: inner type @ +0, payload @ +4. `size` bounds reads. private static void ParseGameEvent(uint eventType, IntPtr data, uint size) @@ -199,6 +268,20 @@ internal static class SmartBoxHooks RynthLog.Compat($"GE evt=0x{eventType:X4} len={size} p=[{d1:X8} {d2:X8} {d3:X8}]"); } + // v75: the character's titles (0x0029 at login, 0x002B per new title; see CharacterTitles). + if (CharacterTitles.IsTitleEvent(eventType)) + { + try { CharacterTitles.OnGameEvent(eventType, data, size, ClientHelperHooks.GetPlayerId()); } catch { } + return; + } + + // v72: the player-to-player trade events (0x01FD-0x0208; see PlayerTrade). + if (PlayerTrade.IsTradeEvent(eventType)) + { + PlayerTrade.OnGameEvent(eventType, data, size); + return; + } + switch (eventType) { case 0x01C0: // UpdateHealth: [targetId u32][ratio f32] @@ -213,7 +296,8 @@ internal static class SmartBoxHooks // The plugin QueryHealth()s its combat target on lock, which is // what makes this fire for the mobs it's actually fighting. // Falls back to the wire-parsed appraisal cache if the read fails. - bool gotReal = ClientObjectHooks.TryReadCreatureMaxHealth(targetId, out uint realMax) && realMax > 0; + uint realMax = 0; + bool gotReal = !_fromBridge && ClientObjectHooks.TryReadCreatureMaxHealth(targetId, out realMax) && realMax > 0; if (gotReal) maxHealth = realMax; else if (ObjectQualityCache.TryGetCreatureVitals(targetId, out CreatureVitals exact) && exact.MaxHealth > 0) @@ -245,6 +329,7 @@ internal static class SmartBoxHooks RynthLog.Compat($"Combat: kill notify '{msg}'"); } PluginManager.QueueKillNotification(msg); + ImGuiBackend.Hud.HudFeed.OnKillMessage(msg); // kill burst } break; } @@ -259,6 +344,9 @@ internal static class SmartBoxHooks { uint err = size >= 8 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))) : 0; int seq = System.Threading.Interlocked.Increment(ref _useDoneSeq); + // v70: the sequence and its error code as one 64-bit value, so a reader + // on the plugin pump never pairs one UseDone's number with another's code. + System.Threading.Interlocked.Exchange(ref _useDoneLast, ((long)(uint)seq << 32) | err); if (_useDoneLogCount < 25) { _useDoneLogCount++; @@ -266,6 +354,33 @@ internal static class SmartBoxHooks } break; } + + case 0x028A: // WeenieError: [errorType u32]. "Your spell fizzled", + // "You don't know that spell", ... — AC's own refusal lines. + // A cast that fizzles ends with this AND a UseDone(None). + if (size >= 8) + { + uint code = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))); + RecordWeenieError(eventType, code, 0); + if (code == 0x0529) // TradeComplete (v72 trade state) + PlayerTrade.OnTradeComplete(); + } + break; + + case 0x028B: // WeenieErrorWithString: [errorType u32][string16 text] + if (size >= 8) + RecordWeenieError(eventType, unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))), 0); + break; + + case 0x00A0: // InventoryServerSaveFailed: [objectId u32][errorType u32] — + // the server refused an inventory change (wield, move, ...). + // Layout from UIQueueManager::ProcessNetBlobData's inline case + // @0x0055C012 (edx=[p], esi=[p+4]) and ACE's writer. + if (size >= 12) + RecordWeenieError(eventType, + unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 8))), + unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4)))); + break; } } @@ -273,8 +388,225 @@ internal static class SmartBoxHooks // at cast time and re-reads it to detect the server finishing the cast. private static int _useDoneSeq; private static int _useDoneLogCount; + // (seq << 32) | errorType of the most recent UseDone; 0 until the first one. + private static long _useDoneLast; + private static bool _gameEventHookInstalled; + /// <summary>True once the game-event detour (UIQueueManager::ProcessNetBlobData) is installed.</summary> + public static bool IsGameEventHookInstalled => _gameEventHookInstalled; public static int GetUseDoneSeq() => System.Threading.Volatile.Read(ref _useDoneSeq); + /// <summary> + /// v70: the most recent UseDone's sequence number (as GetUseDoneSeq counts them) and its + /// WeenieError code (0 = the action completed). Any thread. False when the game-event + /// hook isn't installed; seq 0 = no UseDone yet this session. + /// </summary> + public static bool TryGetLastUseDone(out int seq, out uint error) + { + long v = System.Threading.Interlocked.Read(ref _useDoneLast); + seq = unchecked((int)(v >> 32)); + error = unchecked((uint)v); + return _gameEventHookInstalled; + } + + // ── Weenie errors (v70) ───────────────────────────────────────────── + // The last refusal the server sent: WeenieError (0x028A), WeenieErrorWithString + // (0x028B) or InventoryServerSaveFailed (0x00A0, with the item id). Written on AC's + // main thread, read from the plugin pump: four fields, so a lock (never contended). + private static readonly object _weenieErrorLock = new(); + private static int _weenieErrorSeq; + private static uint _weenieErrorCode, _weenieErrorEvent, _weenieErrorObject; + private static int _weenieErrorLogCount; + + private static void RecordWeenieError(uint eventType, uint code, uint objectId) + { + int seq; + lock (_weenieErrorLock) + { + seq = ++_weenieErrorSeq; + _weenieErrorCode = code; + _weenieErrorEvent = eventType; + _weenieErrorObject = objectId; + } + if (_weenieErrorLogCount < 25) + { + _weenieErrorLogCount++; + RynthLog.Compat($"WeenieError seq={seq} evt=0x{eventType:X3} err=0x{code:X4} obj=0x{objectId:X8}"); + } + } + + /// <summary> + /// v70: the most recent server refusal (see RecordWeenieError). seq counts them (0 = none + /// yet); eventType says which message carried it; objectId is the item for 0x00A0, else 0. + /// Any thread. False when the game-event hook isn't installed. + /// </summary> + public static bool TryGetLastWeenieError(out int seq, out uint error, out uint eventType, out uint objectId) + { + lock (_weenieErrorLock) + { + seq = _weenieErrorSeq; + error = _weenieErrorCode; + eventType = _weenieErrorEvent; + objectId = _weenieErrorObject; + } + return _gameEventHookInstalled; + } + + // ── Enchantment events (v70) ──────────────────────────────────────── + // The player's enchantment changes arrive as these GameEvents (all dispatched by + // UIQueueManager::ProcessNetBlobData, the function this file hooks; the case targets + // were traced to CM_Magic::DispatchUI_* in the Chorizite map): + // 0x02C2 UpdateEnchantment Enchantment + // 0x02C4 UpdateMultipleEnchantments u32 count + Enchantment[] + // 0x02C3 RemoveEnchantment LayeredSpellId (u16 spell, u16 layer) + // 0x02C5 RemoveMultipleEnchantments u32 count + LayeredSpellId[] + // 0x02C7 DispelEnchantment LayeredSpellId (silent removal) + // 0x02C8 DispelMultipleEnchantments u32 count + LayeredSpellId[] + // 0x02C6 PurgeEnchantments (none: all but vitae go, e.g. on death) + // 0x0312 PurgeBadEnchantments (none: the harmful ones go) + // The purges carry no ids, so the player's registry is read just before and just after + // AC applies them and the spells that disappeared are reported. Removals report the spell + // id (layer stripped), which is what OnEnchantmentRemoved's plugins key on. + // + // Enchantment on the wire (ACE's writer, 60 bytes, +4 when HasSpellSetId != 0): + // +0 u16 spellId +2 u16 layer +4 u16 category +6 u16 hasSpellSetId +8 u32 power + // +12 f64 startTime +20 f64 duration +28 u32 caster +32 f32 degradeMod + // +36 f32 degradeLimit +40 f64 lastDegraded +48 u32 statModType +52 u32 key + // +56 f32 value [+60 u32 spellSetId] + private const int EnchantmentWireSize = 60; + private const int MaxEnchantmentsPerEvent = 256; + private static int _enchantmentEventLogCount; + + private sealed class EnchantmentChange + { + public uint EventType; + public bool Added; + public int Count; + public uint[] SpellIds = Array.Empty<uint>(); + public double[] Durations = Array.Empty<double>(); + /// <summary>Purges: the player's spell ids before AC applied it (null = unreadable).</summary> + public uint[]? Before; + } + + private static EnchantmentChange? CaptureEnchantmentEvent(uint eventType, IntPtr data, uint size) + { + // Payload starts at data+4; `size` counts the 4-byte event type too. + switch (eventType) + { + case 0x02C2: // UpdateEnchantment + { + if (size < 4 + EnchantmentWireSize) return null; + var c = new EnchantmentChange { EventType = eventType, Added = true, Count = 1, SpellIds = new uint[1], Durations = new double[1] }; + ReadWireEnchantment(data, 4, out c.SpellIds[0], out c.Durations[0]); + return c.SpellIds[0] != 0 ? c : null; + } + + case 0x02C4: // UpdateMultipleEnchantments + { + if (size < 8) return null; + uint count = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))); + if (count == 0 || count > MaxEnchantmentsPerEvent) return null; + var c = new EnchantmentChange { EventType = eventType, Added = true, SpellIds = new uint[count], Durations = new double[count] }; + uint off = 8; + for (uint i = 0; i < count; i++) + { + if (off + EnchantmentWireSize > size) break; + ushort hasSet = unchecked((ushort)Marshal.ReadInt16(IntPtr.Add(data, (int)off + 6))); + ReadWireEnchantment(data, (int)off, out uint spellId, out double duration); + off += EnchantmentWireSize + (hasSet != 0 ? 4u : 0u); + if (spellId == 0) continue; + c.SpellIds[c.Count] = spellId; + c.Durations[c.Count] = duration; + c.Count++; + } + return c.Count > 0 ? c : null; + } + + case 0x02C3: // RemoveEnchantment + case 0x02C7: // DispelEnchantment + { + if (size < 8) return null; + uint spellId = (uint)(ushort)Marshal.ReadInt16(IntPtr.Add(data, 4)); + if (spellId == 0) return null; + return new EnchantmentChange { EventType = eventType, Count = 1, SpellIds = new[] { spellId } }; + } + + case 0x02C5: // RemoveMultipleEnchantments + case 0x02C8: // DispelMultipleEnchantments + { + if (size < 8) return null; + uint count = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))); + if (count == 0 || count > MaxEnchantmentsPerEvent) return null; + var c = new EnchantmentChange { EventType = eventType, SpellIds = new uint[count] }; + for (uint i = 0; i < count && 8 + i * 4 + 4 <= size; i++) + { + uint spellId = (uint)(ushort)Marshal.ReadInt16(IntPtr.Add(data, (int)(8 + i * 4))); + if (spellId != 0) c.SpellIds[c.Count++] = spellId; + } + return c.Count > 0 ? c : null; + } + + case 0x02C6: // PurgeEnchantments + case 0x0312: // PurgeBadEnchantments + return new EnchantmentChange { EventType = eventType, Before = SnapshotPlayerSpellIds() }; + } + return null; + } + + private static void ReadWireEnchantment(IntPtr data, int off, out uint spellId, out double duration) + { + spellId = (uint)(ushort)Marshal.ReadInt16(IntPtr.Add(data, off)); + duration = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(IntPtr.Add(data, off + 20))); + } + + private static void FlushEnchantmentEvent(EnchantmentChange c) + { + // The registry just changed: refresh the off-thread player snapshot NOW (we + // are on the main thread, after AC applied the change), before the event is + // queued, so a plugin re-reading on the event sees the new state as before. + EnchantmentHooks.RefreshPlayerSnapshotNow(); + + if (c.Before != null) + { + // A purge: whatever left the registry. + uint[]? after = SnapshotPlayerSpellIds(); + if (after == null) return; + var remaining = new HashSet<uint>(after); + var reported = new HashSet<uint>(); + foreach (uint id in c.Before) + if (!remaining.Contains(id) && reported.Add(id)) + PluginManager.QueueEnchantmentRemoved(id); + LogEnchantmentEvent(c.EventType, reported.Count, 0); + return; + } + + for (int i = 0; i < c.Count; i++) + { + if (c.Added) PluginManager.QueueEnchantmentAdded(c.SpellIds[i], c.Durations[i]); + else PluginManager.QueueEnchantmentRemoved(c.SpellIds[i]); + } + LogEnchantmentEvent(c.EventType, c.Count, c.SpellIds[0]); + } + + private static void LogEnchantmentEvent(uint eventType, int count, uint firstSpellId) + { + if (_enchantmentEventLogCount >= 25) return; + _enchantmentEventLogCount++; + RynthLog.Compat($"Enchantment evt=0x{eventType:X3} count={count} first={firstSpellId}"); + } + + /// <summary>The player's enchantment spell ids (main thread here), or null when unreadable.</summary> + private static unsafe uint[]? SnapshotPlayerSpellIds() + { + const int Max = 512; + uint* ids = stackalloc uint[Max]; + double* expiry = stackalloc double[Max]; + int n = EnchantmentHooks.ReadPlayerEnchantments(ids, expiry, Max); + if (n < 0) return null; + var result = new uint[n]; + for (int i = 0; i < n; i++) result[i] = ids[i]; + return result; + } + // AttackerNotification (0x01B1) / DefenderNotification (0x01B2). Payload at // data+4: string16 name, u32 damageType, f64 percent, u32 damage, // [u32 damageLocation (defender only),] u32 crit, …. Read-only byte math. @@ -282,6 +614,9 @@ internal static class SmartBoxHooks { if (size < 24) return; bool attacker = eventType == 0x01B1; + // "X hits you": the nameplates' engaged filter keys attackers by name (no id on the wire). + if (!attacker) + ImGuiBackend.Hud.MonsterHudData.RecordAttacker(ReadString16Latin1(data, 4, size)); int nameLen = (ushort)Marshal.ReadInt16(IntPtr.Add(data, 4)); int strBlock = ((2 + nameLen + 3) / 4) * 4; // u16 len + chars, padded to a multiple of 4 @@ -300,6 +635,8 @@ internal static class SmartBoxHooks RynthLog.Compat($"Combat: damage evt 0x{eventType:X3} dmg={damage} crit={crit} atk={attacker} len={size}"); } PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker); + // RynthVision combat text: the attacker event names the monster hit. + ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(data, 4, size) : null, damage, crit != 0); } private static SmartBoxEventInfo ReadSmartBoxEventInfo(IntPtr blob) @@ -417,6 +754,7 @@ internal static class SmartBoxHooks } PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker); + ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(payloadPtr, nameOff, info.BlobSize) : null, damage, crit != 0); } catch { diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxLocator.cs b/src/RynthCore.Engine/Compatibility/SmartBoxLocator.cs index daaab9f..7eac2a9 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxLocator.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxLocator.cs @@ -42,34 +42,10 @@ internal static class SmartBoxLocator /// Uses VirtualQuery — safe to call on any address including unmapped pages. /// Critical for NativeAOT where AccessViolationException cannot be caught. /// </summary> - public static bool IsMemoryReadable(IntPtr address, int size) - { - if (address == IntPtr.Zero || size <= 0) - return false; - - if (VirtualQuery(address, out MEMORY_BASIC_INFORMATION mbi, - Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0) - return false; - - if (mbi.State != MEM_COMMIT) - return false; - if ((mbi.Protect & PAGE_NOACCESS) != 0) - return false; - if ((mbi.Protect & PAGE_GUARD) != 0) - return false; - if ((mbi.Protect & READABLE_MASK) == 0) - return false; - - // Ensure the committed region covers the full requested range. - // Deep-audit finding #32 (2026-06-18): this used signed 32-bit - // arithmetic (ToInt32()) — acclient.exe is LARGE_ADDRESS_AWARE so - // addresses above 0x7FFFFFFF are reachable, and ToInt32() on those - // can wrap. Do the comparison in 64-bit (every caller passes a small - // compile-time size, so no overflow risk on that side). - long regionEnd = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64(); - long requestEnd = address.ToInt64() + size; - return requestEnd <= regionEnd; - } + public static bool IsMemoryReadable(IntPtr address, int size) => MemoryProbe.IsReadable(address, size); + // Was a VirtualQuery per call (one per CObjectMaint hash bucket and two per node in the + // snapshot walks); see MemoryProbe for why that collapsed the frame rate once AC's heap grew. + // Same rule: committed, not NOACCESS/GUARD, readable, the whole span (64-bit arithmetic). public static bool IsInitialized { get; private set; } public static int CandidateCount => _smartboxStaticCandidates.Count; diff --git a/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs b/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs index f03e5d0..fe5ca50 100644 --- a/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs +++ b/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs @@ -102,6 +102,7 @@ internal static class UpdateObjectInventoryHooks { if (objectId != 0) PluginManager.QueueUpdateObjectInventory(objectId); + InventoryModel.MarkDirty(); // Inventory panel: capture again soon (one volatile write) } catch { } } @@ -188,6 +189,18 @@ internal static class UpdateObjectInventoryHooks /// </summary> private static int ScanByContainerId(uint containerId, Span<uint> itemIds) { + // Off AC's main thread (host GetContainerContentsFn on the plugin pump): one + // pass over the main-thread PWD snapshot under a single lock, no AC memory. + // Per-id TryGetObjectOwnershipInfo would serve the same snapshot but take the + // lock once per id; the fixed-range fallback below (65k ids) is pointless + // off-thread, so an empty snapshot just means "nothing yet". + if (!MainThreadGuard.IsOnMainThread()) + { + int n = ClientObjectHooks.CollectOwnedIdsFromSnapshot(containerId, itemIds); + itemIds[..n].Sort(); // same ascending order as below + return n; + } + // Check every object the client knows, from the identity snapshot. The old fixed // range stopped at 0x8000FFFF, but a server hands out ids well past that once it // has run a while, so newer items (and packs, with everything in them) were @@ -264,17 +277,5 @@ internal static class UpdateObjectInventoryHooks private const uint PageNoAccess = 0x01; private const uint PageGuard = 0x100; - private static bool IsReadablePointer(IntPtr ptr) - { - if (ptr == IntPtr.Zero) - return false; - - if (VirtualQuery(ptr, out MEMORY_BASIC_INFORMATION mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0) - return false; - - if (mbi.State != MemCommit) - return false; - - return (mbi.Protect & (PageNoAccess | PageGuard)) == 0; - } + private static bool IsReadablePointer(IntPtr ptr) => MemoryProbe.IsAccessible(ptr); } diff --git a/src/RynthCore.Engine/Compatibility/VTankSignal.cs b/src/RynthCore.Engine/Compatibility/VTankSignal.cs new file mode 100644 index 0000000..e56a4e0 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/VTankSignal.cs @@ -0,0 +1,73 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/VTankSignal.cs +// +// Pure parsing for VTankWatch (no engine state, no AC, no Decal), so the offline +// tests in tools\VTankWatchTests compile this file directly. +// +// The signal is VTank's own DOCUMENTED chat commands, as they go through Decal's +// chat parser (typed in the chat bar, sent by a meta's Chat Command action, by a +// login command, or by another plugin through InvokeChatParser): +// /vt start - "Turns the macro on" +// /vt stop - "Turns the macro off" +// (VirindiPlugins wiki, "Virindi Tank Commands", /vt commands - Actions.) +// Nothing here reads, loads or inspects VTank itself (its licence forbids reverse +// engineering; docs/LEGAL_COMPATIBILITY.md). +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +internal static class VTankSignal +{ + /// <summary>The line turns VTank's macro on.</summary> + public const int Start = 1; + /// <summary>The line turns VTank's macro off.</summary> + public const int Stop = -1; + /// <summary>Not a VTank start/stop command.</summary> + public const int None = 0; + + /// <summary> + /// <see cref="Start"/> for "/vt start", <see cref="Stop"/> for "/vt stop" (any case, + /// any spacing, leading/trailing blanks ignored); <see cref="None"/> for anything else, + /// including other /vt commands ("/vt startx", "/vt opt set ...") and lines that only + /// mention the words ("tell X /vt start"). + /// </summary> + public static int ParseCommand(string? line) + { + if (string.IsNullOrEmpty(line)) + return None; + ReadOnlySpan<char> s = line.AsSpan().Trim(); + if (s.Length < 4 || s[0] != '/' || !s.Slice(1, 2).Equals("vt", StringComparison.OrdinalIgnoreCase)) + return None; + s = s.Slice(3); + // "/vt" must be a whole word: "/vtank start" is not VTank's command. + if (s.Length == 0 || !char.IsWhiteSpace(s[0])) + return None; + s = s.TrimStart(); + int end = 0; + while (end < s.Length && !char.IsWhiteSpace(s[end])) end++; + ReadOnlySpan<char> verb = s.Slice(0, end); + // The documented forms take no argument; tolerate trailing words anyway (VTank's own + // parser decides), but the verb itself must match exactly. + if (verb.Equals("start", StringComparison.OrdinalIgnoreCase)) return Start; + if (verb.Equals("stop", StringComparison.OrdinalIgnoreCase)) return Stop; + return None; + } + + /// <summary> + /// A chat-window line that looks like VTank's own output (for the diagnostic log only: + /// it is never used to decide anything, because VTank documents no on/off chat line). + /// Lines other players send ("X tells you, ...", channel chat) are excluded. + /// </summary> + public static bool LooksLikeVTankChat(string? text) + { + if (string.IsNullOrEmpty(text)) + return false; + if (text.Contains(" tells you, ", StringComparison.Ordinal) || text.Contains(" says, ", StringComparison.Ordinal)) + return false; + return text.Contains("VTank", StringComparison.OrdinalIgnoreCase) + || text.Contains("Virindi Tank", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[VT]", StringComparison.OrdinalIgnoreCase); + } +} diff --git a/src/RynthCore.Engine/Compatibility/VTankWatch.cs b/src/RynthCore.Engine/Compatibility/VTankWatch.cs new file mode 100644 index 0000000..c6ff037 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/VTankWatch.cs @@ -0,0 +1,123 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/VTankWatch.cs +// +// "Is VTank's macro running in this client?" for the Decal bridge, so RynthAi can +// follow the one-bot-per-client rule (docs/DECAL_BRIDGE_PLAN.md, "What's lost or +// different under Decal"): when VTank starts, RynthAi's macro stops. +// +// Signal (VTankSignal.cs): VTank's documented /vt start and /vt stop commands, seen +// - in every line Decal's chat parser hands the bridge (CommandLineText -> +// ChatBarEnter record, eaten or not): typed lines, VTank meta Chat Command +// actions and other plugins' InvokeChatParser calls; +// - in the lines the engine itself sends through Decal (TryInvokeChatParser), which +// the bridge doesn't echo back (RynthAi metas, on-login commands, plugins). +// Cleared at Decal's Logoff (Decal plugins, VTank included, end with the session). +// NOT seen: VTank's own "Run Macro" button and its own stops (death with +// StopMacroOnDeath, a meta that stops it internally). VTank documents no chat line +// for those, so there is nothing legal to read; see the report for options. +// +// Survives a hot reload: the state is mirrored into this process's environment +// (RYNTHCORE_VTANK_MACRO), which outlives an engine generation. +// +// Without Decal nothing here runs: every entry point is called from DecalBridgeHost +// after its Active check, and GetPluginState answers 0 ("not watching"). +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal static class VTankWatch +{ + /// <summary>Plugin API v74 GetVTankState flags.</summary> + public const uint FlagWatching = 1u << 0; + public const uint FlagRunning = 1u << 1; + + private const string EnvName = "RYNTHCORE_VTANK_MACRO"; + private const int MaxChatLogLines = 30; + + private static int _running = ReadEnv(); + private static int _seq = _running; // a restored "running" is a change the plugins haven't seen + private static string _lastChange = _running != 0 ? "restored after a reload" : "none yet"; + private static int _chatLogged; + + /// <summary>True while VTank's macro was last seen turned on (bridge mode only).</summary> + public static bool Running => DecalBridgeHost.Active && Volatile.Read(ref _running) != 0; + + /// <summary>Bumped on every change of <see cref="Running"/>.</summary> + public static int Sequence => Volatile.Read(ref _seq); + + /// <summary> + /// Plugin API v74: bit0 = the engine watches VTank (Decal bridge mode), bit1 = VTank's + /// macro is running as far as the engine saw. 0 without Decal. Any thread. + /// </summary> + public static uint GetPluginState(out int sequence) + { + sequence = Volatile.Read(ref _seq); + if (!DecalBridgeHost.Active) + return 0; + return FlagWatching | (Volatile.Read(ref _running) != 0 ? FlagRunning : 0); + } + + /// <summary>A line Decal's chat parser saw (typed, meta, plugin). Pump thread.</summary> + public static void ObserveParserLine(string text) => Observe(text, "Decal's chat parser"); + + /// <summary>A line the engine sent through Decal's InvokeChatParser. Any thread.</summary> + public static void ObserveSentLine(string text) => Observe(text, "sent by RynthCore"); + + /// <summary>Decal ended the session: VTank (a Decal plugin) ends with it.</summary> + public static void OnLogoff() + { + if (Set(false, "logoff")) + RynthLog.Info("VTankWatch: logoff - VTank's macro counts as stopped."); + } + + /// <summary>Diagnostic only: log the first VTank-looking chat lines, so a test shows what VTank prints.</summary> + public static void ObserveChatText(string text) + { + if (Volatile.Read(ref _chatLogged) >= MaxChatLogLines || !VTankSignal.LooksLikeVTankChat(text)) + return; + if (Interlocked.Increment(ref _chatLogged) > MaxChatLogLines) + return; + string t = text.TrimEnd('\r', '\n'); + if (t.Length > 160) t = t.Substring(0, 160) + "..."; + RynthLog.Info($"VTankWatch: chat line '{t}' (logged for reference; not used as a signal)"); + } + + /// <summary>/rc vtank clear: the player says VTank isn't running (it was stopped with its own button).</summary> + public static bool Clear() => Set(false, "/rc vtank clear"); + + public static string Describe() => + !DecalBridgeHost.Active + ? "VTank watch: off (no Decal bridge in this client; RynthAi is never stopped for VTank)." + : $"VTank watch: on. VTank macro {(Volatile.Read(ref _running) != 0 ? "RUNNING" : "not running")} (last change: {Volatile.Read(ref _lastChange)}). " + + "Signal: /vt start and /vt stop through Decal's chat parser; VTank's own button is not seen."; + + private static void Observe(string text, string source) + { + int verb = VTankSignal.ParseCommand(text); + if (verb == VTankSignal.None) + return; + bool on = verb == VTankSignal.Start; + if (Set(on, $"'{text.Trim()}' ({source})")) + RynthLog.Info($"VTankWatch: VTank macro {(on ? "STARTED" : "STOPPED")} - '{text.Trim()}' ({source})."); + } + + private static bool Set(bool on, string why) + { + int v = on ? 1 : 0; + if (Interlocked.Exchange(ref _running, v) == v) + return false; + Volatile.Write(ref _lastChange, $"{(on ? "started" : "stopped")} by {why} at {DateTime.Now:HH:mm:ss}"); + Interlocked.Increment(ref _seq); + try { Environment.SetEnvironmentVariable(EnvName, on ? "1" : null); } catch { } + return true; + } + + private static int ReadEnv() + { + try { return Environment.GetEnvironmentVariable(EnvName) == "1" ? 1 : 0; } + catch { return 0; } + } +} diff --git a/src/RynthCore.Engine/CrashDump.cs b/src/RynthCore.Engine/CrashDump.cs index b1226cb..ab5f143 100644 --- a/src/RynthCore.Engine/CrashDump.cs +++ b/src/RynthCore.Engine/CrashDump.cs @@ -50,7 +50,7 @@ internal static class CrashDump /// Write a minidump of the current process to Logs\dumps\. Best-effort; /// never throws. Returns true on success and sets <paramref name="dumpPath"/>. /// </summary> - internal static bool WriteSelfDump(string reason, out string dumpPath) + internal static bool WriteSelfDump(string reason, out string dumpPath, string prefix = "hang") { dumpPath = string.Empty; try @@ -59,7 +59,7 @@ internal static class CrashDump Directory.CreateDirectory(dir); string stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); - dumpPath = Path.Combine(dir, $"hang_{Environment.ProcessId}_{stamp}.dmp"); + dumpPath = Path.Combine(dir, $"{prefix}_{Environment.ProcessId}_{stamp}.dmp"); using var fs = new FileStream(dumpPath, FileMode.Create, FileAccess.Write, FileShare.None); bool ok = MiniDumpWriteDump( diff --git a/src/RynthCore.Engine/D3D9/AcUiPassHook.cs b/src/RynthCore.Engine/D3D9/AcUiPassHook.cs new file mode 100644 index 0000000..5fffa56 --- /dev/null +++ b/src/RynthCore.Engine/D3D9/AcUiPassHook.cs @@ -0,0 +1,156 @@ +// ============================================================================ +// RynthCore.Engine - D3D9/AcUiPassHook.cs +// Hooks AC's RenderUI::RenderObjects, the call that draws AC's 2D UI, so the +// world overlays (Nav3D markers, nameplates, combat text) draw right before +// it: after ALL of AC's 3D (alpha-sorted foliage and effects included) and +// under every AC window. +// +// Why a function hook and not a D3D state signal (2026-10-04, plates drew +// behind foliage): AC's frame is Client::UseTime -> SceneTool::StartFrame -> +// SmartBox::Draw (the whole 3D scene) -> SceneTool::EndFrame, and EndFrame +// sets a full-screen viewport, calls RenderUI::RenderObjects (each UI +// element's surface, in z-order), KeyStone::Update, the debug HUDs, restores +// the viewport and ends the scene. Inside SmartBox::Draw, ZENABLE goes 1->0 +// more than once before the UI: the outdoor sky pass after the landblocks +// (LScape -> sky pass 1, depth mode ALWAYS/no-write, DrawObjCellForDummies) +// draws with Z off, and only AFTER it does SmartBox::RenderNormalMode flush +// the deferred alpha list (D3DPolyRender::FlushAlphaList(0)) - where the +// alpha-sorted foliage and effects draw. The old "first ZENABLE 1->0" signal +// fired at that sky pass, so the alpha list covered the plates. The entry of +// RenderUI::RenderObjects is exactly "3D done, 2D UI begins", costs one call +// per frame instead of work on every draw, and needs no prediction. +// Evidence and addresses: ops/overnight/2026-10-04-plates-foliage.md (Aeshnidae). +// +// The function takes no arguments and returns nothing (it loads ecx itself; +// its caller doesn't use eax/ecx/edx after it), so a cdecl void() detour is +// exact. AC's main thread only (the render thread). A frame where AC draws no +// UI never calls it; the overlays then draw at EndScene (the existing +// fallback), which is also "after all 3D". +// +// Teardown: EngineLifecycle calls Uninstall before EndSceneHook.Uninstall, so +// the detour stops entering the overlay code before UnderUiLayer/DX9Backend +// are torn down (EndSceneHook.Uninstall then waits 80 ms for a call in flight). +// The hook is only disabled, like every Compatibility hook at MH_DisableHook(ALL); +// the next generation's HookCreate reclaims the target (reload recovery / the +// loader facade). +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.D3D9; + +internal static class AcUiPassHook +{ + // RenderUI::RenderObjects on the 4,841,472-byte client. Pattern is the source of truth. + private const int RenderObjectsFallbackVa = 0x004488A0; + + // mov eax,[list count]; sub esp,8; push esi; xor esi,esi; test eax,eax; + // mov byte [in-render flag],1; mov dword [..],0; mov ecx,imm; jbe +10; + // mov eax,[list head]; test eax,eax; je +5; lea esi,[eax-8]; jmp +2; xor esi,esi; + // test esi,esi; mov [esp+8],ecx; je +20. Unique in .text (checked 2026-10-04 on + // both C:\Turbine and C:\Games\RynthCore\AcClient copies); absolute addresses wildcarded. + private static readonly byte?[] RenderObjectsPattern = + [ + 0xA1, null, null, null, null, + 0x83, 0xEC, 0x08, + 0x56, + 0x33, 0xF6, + 0x85, 0xC0, + 0xC6, 0x05, null, null, null, null, 0x01, + 0xC7, 0x05, null, null, null, null, 0x00, 0x00, 0x00, 0x00, + 0xB9, null, null, null, null, + 0x76, 0x10, + 0xA1, null, null, null, null, + 0x85, 0xC0, + 0x74, 0x05, + 0x8D, 0x70, 0xF8, + 0xEB, 0x02, + 0x33, 0xF6, + 0x85, 0xF6, + 0x89, 0x4C, 0x24, 0x08, + 0x74, 0x20, + ]; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void RenderObjectsD(); + + private static RenderObjectsD? _original; + private static RenderObjectsD? _detour; + private static IntPtr _target; + private static long _calls; + + /// <summary>True once the hook is live. Read on AC's render thread every frame.</summary> + public static volatile bool IsInstalled; + + public static string Status { get; private set; } = "not installed"; + + /// <summary>AC UI passes seen since install (diagnostics).</summary> + public static long Calls => Interlocked.Read(ref _calls); + + /// <summary>InitWorker step. Resolves and hooks RenderUI::RenderObjects. Idempotent.</summary> + public static void Initialize() + { + if (IsInstalled) return; + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + Status = "acclient.exe not available"; + return; + } + + var r = HookResolver.Resolve(text, "AcUiPassHook.RenderUI::RenderObjects", + RenderObjectsPattern, RenderObjectsFallbackVa); + if (!r.Success) + { + Status = $"not resolved ({r.Detail}); overlays use the ZENABLE transition"; + RynthLog.Compat($"AcUiPassHook: {Status}"); + return; + } + + try + { + _target = r.Address; + _detour = Detour; + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_detour); + _original = Marshal.GetDelegateForFunctionPointer<RenderObjectsD>(MinHook.HookCreate(_target, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(_target); + IsInstalled = true; + Status = $"hooked RenderUI::RenderObjects @ 0x{_target.ToInt32():X8} ({r.Detail})"; + RynthLog.Compat($"AcUiPassHook: {Status}"); + } + catch (Exception ex) + { + Status = $"install failed: {ex.Message}"; + RynthLog.Compat($"AcUiPassHook: install threw {ex.GetType().Name}: {ex.Message}"); + } + } + + /// <summary> + /// Engine shutdown / hot reload (lifecycle thread), before the render-side teardown: + /// stops the detour drawing at once, then disables the hook. Idempotent. + /// </summary> + public static void Uninstall() + { + if (!IsInstalled) return; + IsInstalled = false; // the detour checks this first: no overlay draw from here on + Thread.MemoryBarrier(); + int status = MinHook.MH_DisableHook(_target); + Status = $"uninstalled (disable = {MinHook.StatusString(status)})"; + RynthLog.Compat($"AcUiPassHook: {Status}"); + } + + private static void Detour() + { + Interlocked.Increment(ref _calls); + if (IsInstalled && !EngineLifecycle.IsShuttingDown) + { + try { Nav3DRenderInjector.OnAcUiPass(); } + catch { /* never let an overlay problem take AC's UI pass down */ } + } + _original!(); + } +} diff --git a/src/RynthCore.Engine/D3D9/BitmapFont.cs b/src/RynthCore.Engine/D3D9/BitmapFont.cs deleted file mode 100644 index 360f4bb..0000000 --- a/src/RynthCore.Engine/D3D9/BitmapFont.cs +++ /dev/null @@ -1,168 +0,0 @@ -// ═══════════════════════════════════════════════════════════════════════════ -// RynthCore.Engine — D3D9/BitmapFont.cs -// Dependency-free 5x7 bitmap font, ported from RynthCore2's bitmap_font.cpp. -// -// Standard 5x7 glyph cells. Each glyph is 7 rows; the low 5 bits of each row -// are the columns, bit 4 = leftmost. A set bit is a lit pixel cell. Lit cells -// are emitted as rectangles through a caller-supplied sink so the renderer -// (VitalHud) can turn each into a colored quad. No allocation, no texture. -// ═══════════════════════════════════════════════════════════════════════════ - -using System; - -namespace RynthCore.Engine.D3D9; - -internal static class BitmapFont -{ - /// <summary>Receives one lit pixel cell as an inclusive-exclusive rect.</summary> - internal delegate void CellSink(int x0, int y0, int x1, int y1); - - public const int GlyphW = 5; - public const int GlyphH = 7; - private const int Advance = GlyphW + 1; // one-cell gap between glyphs - - // Glyph table row, in a fixed order; IndexOf maps a character to a row. - // 0 = space - // 1..10 = '0'..'9' - // 11..36 = 'A'..'Z' - // 37..45 = '/' ':' '.' ',' '-' '+' '%' '(' ')' - private const int GSpace = 0; - private const int GDigit0 = 1; - private const int GLetterA = 11; - private const int GSlash = 37; - private const int GColon = 38; - private const int GDot = 39; - private const int GComma = 40; - private const int GDash = 41; - private const int GPlus = 42; - private const int GPercent = 43; - private const int GLParen = 44; - private const int GRParen = 45; - - // 5x7 cells, bit 4 leftmost — transcribed verbatim from bitmap_font.cpp. - private static readonly byte[][] Glyphs = - [ - /* space */ [0, 0, 0, 0, 0, 0, 0], - /* 0 */ [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110], - /* 1 */ [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110], - /* 2 */ [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111], - /* 3 */ [0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110], - /* 4 */ [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010], - /* 5 */ [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110], - /* 6 */ [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110], - /* 7 */ [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000], - /* 8 */ [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110], - /* 9 */ [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100], - /* A */ [0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001], - /* B */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110], - /* C */ [0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110], - /* D */ [0b11100, 0b10010, 0b10001, 0b10001, 0b10001, 0b10010, 0b11100], - /* E */ [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111], - /* F */ [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000], - /* G */ [0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01111], - /* H */ [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001], - /* I */ [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110], - /* J */ [0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100], - /* K */ [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001], - /* L */ [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111], - /* M */ [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001], - /* N */ [0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001], - /* O */ [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110], - /* P */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000], - /* Q */ [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101], - /* R */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001], - /* S */ [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110], - /* T */ [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100], - /* U */ [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110], - /* V */ [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100], - /* W */ [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b10101, 0b01010], - /* X */ [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001], - /* Y */ [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100], - /* Z */ [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111], - /* / */ [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000], - /* : */ [0b00000, 0b00100, 0b00100, 0b00000, 0b00100, 0b00100, 0b00000], - /* . */ [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b01100], - /* , */ [0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b00100, 0b01000], - /* - */ [0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000], - /* + */ [0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000], - /* % */ [0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011], - /* ( */ [0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010], - /* ) */ [0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000], - ]; - - // Maps an ASCII character to a glyph row, or -1 if unsupported (advance blank). - private static int IndexOf(char c) - { - if (c >= '0' && c <= '9') return GDigit0 + (c - '0'); - if (c >= 'A' && c <= 'Z') return GLetterA + (c - 'A'); - if (c >= 'a' && c <= 'z') return GLetterA + (c - 'a'); // fold to uppercase - return c switch - { - ' ' => GSpace, - '/' => GSlash, - ':' => GColon, - '.' => GDot, - ',' => GComma, - '-' => GDash, - '+' => GPlus, - '%' => GPercent, - '(' => GLParen, - ')' => GRParen, - _ => -1, - }; - } - - /// <summary>Pixel height of a glyph at the given cell size.</summary> - public static int Height(int cellPx) - { - if (cellPx < 1) cellPx = 1; - return GlyphH * cellPx; - } - - /// <summary>Pixel width of a rendered string at the given cell size. Takes a - /// span so callers can measure stack-formatted text without allocating.</summary> - public static int MeasureWidth(ReadOnlySpan<char> s, int cellPx) - { - if (s.IsEmpty) return 0; - if (cellPx < 1) cellPx = 1; - int n = s.Length; - // n glyphs, each GlyphW wide, with (n-1) single-cell gaps between them. - return (n * GlyphW + (n - 1)) * cellPx; - } - - /// <summary> - /// Emits the lit cells of <paramref name="s"/> at (x, y) at the given cell - /// size by invoking <paramref name="sink"/> once per lit cell. Takes a span - /// (string literals convert implicitly) so it stays allocation-free; the sink - /// is a cached delegate on the caller side. - /// </summary> - public static void Emit(ReadOnlySpan<char> s, int x, int y, int cellPx, CellSink sink) - { - if (s.IsEmpty || sink == null) return; - if (cellPx < 1) cellPx = 1; - - int penX = x; - foreach (char ch in s) - { - int gi = IndexOf(ch); - if (gi >= 0 && gi != GSpace) - { - byte[] rows = Glyphs[gi]; - for (int r = 0; r < GlyphH; r++) - { - int bits = rows[r]; - for (int c = 0; c < GlyphW; c++) - { - if (((bits >> (GlyphW - 1 - c)) & 1) != 0) - { - int x0 = penX + c * cellPx; - int y0 = y + r * cellPx; - sink(x0, y0, x0 + cellPx, y0 + cellPx); - } - } - } - } - penX += Advance * cellPx; - } - } -} diff --git a/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs b/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs index bdbc2db..7b2b5a0 100644 --- a/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs +++ b/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs @@ -30,6 +30,15 @@ internal static class D3D9Bootstrapper [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)] private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); + /// <summary> + /// Decal is in this client and the in-game renderer was asked for (EntryPoint, + /// DecalInGameImGui). Decal detours Direct3DCreate9 and IDirect3D9::CreateDevice, so the + /// throwaway-device discovery would hand a second device to Decal: the EndScene address + /// comes from AC's live device (heap scan) or d3d9.dll's image instead. Never set + /// without Decal. + /// </summary> + internal static volatile bool DecalInProcess; + private static int _started; private static bool _d3dCreateHookInstalled; private static bool _createDeviceHookInstalled; @@ -46,18 +55,23 @@ internal static class D3D9Bootstrapper if (Interlocked.CompareExchange(ref _started, 1, 0) != 0) return; - var thread = new Thread(BootstrapWorker) - { - Name = "RynthCore.D3D9Bootstrap", - IsBackground = true - }; - thread.Start(); + EngineThreads.Start("RynthCore.D3D9Bootstrap", BootstrapWorker); } private static void BootstrapWorker() { try { + if (DecalInProcess) + { + while (GetModuleHandleA("d3d9.dll") == IntPtr.Zero) + if (!EngineThreads.Sleep(PollIntervalMs)) + return; + RynthLog.D3D9("D3D9Bootstrapper: Decal in the process - discovering EndScene without creating a device."); + EndSceneHook.InstallWithoutDevice("decal-live-device"); + return; + } + // This runs after character login, so d3d9.dll and the game's // device are fully initialized. Use the NULLREF throwaway device // for vtable discovery — it's safe post-login because the @@ -91,7 +105,8 @@ internal static class D3D9Bootstrapper return; } - Thread.Sleep(PollIntervalMs); + if (!EngineThreads.Sleep(PollIntervalMs)) + return; // engine shutting down: don't install hooks for a dying generation } } catch (Exception ex) diff --git a/src/RynthCore.Engine/D3D9/D3D9VTable.cs b/src/RynthCore.Engine/D3D9/D3D9VTable.cs index 6c07019..c8e422b 100644 --- a/src/RynthCore.Engine/D3D9/D3D9VTable.cs +++ b/src/RynthCore.Engine/D3D9/D3D9VTable.cs @@ -421,6 +421,68 @@ internal static unsafe class D3D9VTable return null; } + /// <summary> + /// Decal clients: Decal gives AC's device its own copy of the vtable (EndScene and Reset + /// point into Inject.dll, the rest still into d3d9.dll). This finds the d3d9.dll vtable the + /// copy was made from - the vtable in d3d9's image that agrees with the copy in the most + /// slots - so the engine can hook d3d9's own functions and never Decal's. Read-only. + /// Returns null when no candidate agrees in at least 100 slots. + /// </summary> + public static IntPtr[]? MatchOriginalDeviceVTable(IntPtr copiedVTable, int numEntries = 119) + { + IntPtr hModule = GetModuleHandleA("d3d9.dll"); + if (hModule == IntPtr.Zero || copiedVTable == IntPtr.Zero) + return null; + if (!TryReadModuleImageSize(hModule, out int imageSize) || imageSize < 0x2000 || imageSize > 50 * 1024 * 1024) + return null; + var copy = new int[numEntries]; + for (int i = 0; i < numEntries; i++) + copy[i] = Marshal.ReadInt32(copiedVTable, i * 4); + + byte[] image = new byte[imageSize]; + const int PageSize = 0x1000; + for (int off = 0; off < imageSize; off += PageSize) + { + int chunk = Math.Min(PageSize, imageSize - off); + IntPtr addr = IntPtr.Add(hModule, off); + if (SmartBoxLocator.IsMemoryReadable(addr, chunk)) + Marshal.Copy(addr, image, off, chunk); + } + + int bestOff = -1, bestMatches = 0; + for (int off = 0x1000; off <= imageSize - numEntries * 4; off += 4) + { + // Cheap reject: QueryInterface and AddRef of the copy must match. + if (BitConverter.ToInt32(image, off) != copy[0] || BitConverter.ToInt32(image, off + 4) != copy[1]) + continue; + int matches = 0; + for (int i = 0; i < numEntries; i++) + if (BitConverter.ToInt32(image, off + i * 4) == copy[i]) + matches++; + if (matches > bestMatches) + { + bestMatches = matches; + bestOff = off; + } + } + if (bestOff < 0 || bestMatches < 100) + { + RynthLog.D3D9($"D3D9VTable: no d3d9.dll vtable matches the copied one (best {bestMatches}/{numEntries})."); + return null; + } + var vtable = new IntPtr[numEntries]; + var differs = new System.Text.StringBuilder(); + for (int i = 0; i < numEntries; i++) + { + vtable[i] = new IntPtr(BitConverter.ToInt32(image, bestOff + i * 4)); + if (vtable[i].ToInt32() != copy[i]) + differs.Append(' ').Append(i); + } + RynthLog.D3D9($"D3D9VTable: the copied device vtable came from d3d9+0x{bestOff:X} ({bestMatches}/{numEntries} slots equal; replaced slots:{differs}). " + + $"d3d9's EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8}."); + return vtable; + } + private static bool IsRecognizedPrologue(byte[] image, int offset) { byte b = image[offset]; diff --git a/src/RynthCore.Engine/D3D9/DecalD3D9.cs b/src/RynthCore.Engine/D3D9/DecalD3D9.cs new file mode 100644 index 0000000..76433b3 --- /dev/null +++ b/src/RynthCore.Engine/D3D9/DecalD3D9.cs @@ -0,0 +1,129 @@ +// ============================================================================ +// RynthCore.Engine - D3D9/DecalD3D9.cs +// +// Decal clients with the in-game renderer only (DecalInGameImGui, docs/DECAL_BRIDGE_PLAN.md). +// Decal gives AC's device its own copy of the vtable, with Reset, BeginScene, EndScene and a +// few more slots pointing into Inject.dll (measured 2026-09-30). The engine hooks d3d9.dll's +// own functions (which Decal's wrappers call) and never Decal's code: HookTarget resolves a +// device slot through d3d9's original vtable. Without Decal, Enabled stays false and +// HookTarget is the plain vtable read it always was. +// ============================================================================ +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Engine.D3D9; + +internal static unsafe class DecalD3D9 +{ + /// <summary>Set by EndSceneHook.InstallWithoutDevice (Decal clients only).</summary> + internal static bool Enabled; + + /// <summary>d3d9.dll's own EndScene for AC's device, from <see cref="TryResolve"/>.</summary> + internal static IntPtr ResolvedEndScene; + + /// <summary> + /// Decides, before any hook goes in, whether the in-game renderer can run in this Decal + /// client: AC's device from the bridge (Decal's public IDecalCore.GetD3DDevice; read + /// without waiting), and d3d9.dll's EndScene for it - directly when its vtable is d3d9's, + /// or through the d3d9 vtable Decal's per-device copy was made from. Read-only. False = + /// stay on the Decal-coexistence path (no D3D9). Called once per generation. + /// </summary> + internal static bool TryResolve() + { + if (ResolvedEndScene != IntPtr.Zero) + return true; + IntPtr device = Compatibility.DecalBridgeHost.DecalDevice; + if (device == IntPtr.Zero) + { + RynthLog.D3D9("DecalD3D9: the bridge hasn't reported Decal's device - staying on the coexistence path."); + return false; + } + IntPtr es = DescribeDevice(device, "Decal's device (GetD3DDevice)", out bool inD3d9); + if (inD3d9 && es != IntPtr.Zero) + { + ResolvedEndScene = es; + return true; + } + // Decal swapped the device's vtable for its own copy: find d3d9's original. + IntPtr[]? original = D3D9VTable.MatchOriginalDeviceVTable(Marshal.ReadIntPtr(device)); + if (original == null) + { + RynthLog.D3D9("DecalD3D9: d3d9.dll's original device vtable wasn't found - staying on the coexistence path."); + return false; + } + OriginalVTable = original; + ResolvedEndScene = original[DeviceVTableIndex.EndScene]; + RynthLog.D3D9($"DecalD3D9: Decal wraps EndScene; d3d9's own EndScene is {Describe(ResolvedEndScene)} (Decal's wrapper calls it)."); + return true; + } + + /// <summary>Decal clients: d3d9.dll's own device vtable (the one Decal's per-device copy + /// was made from), when found. Hooks on device methods resolve through it.</summary> + internal static IntPtr[]? OriginalVTable; + private static int _refusedLogged; + + /// <summary> + /// The address to hook for a device method. Without Decal: the device's vtable slot, as + /// always. With Decal: d3d9.dll's own function for that slot, and zero (do not hook) if + /// it isn't in d3d9.dll - the engine never hooks Decal's code. + /// </summary> + internal static IntPtr HookTarget(IntPtr device, int index) + { + IntPtr fn = Marshal.ReadIntPtr(Marshal.ReadIntPtr(device), index * IntPtr.Size); + if (!Enabled) + return fn; + if (OriginalVTable != null && index < OriginalVTable.Length) + fn = OriginalVTable[index]; + string where = Describe(fn); + if (where.StartsWith("d3d9.dll+", StringComparison.OrdinalIgnoreCase)) + return fn; + if (Interlocked.Increment(ref _refusedLogged) <= 8) + RynthLog.D3D9($"DecalD3D9: device slot {index} resolves to {where}, not d3d9.dll - not hooked (Decal's code is never patched)."); + return IntPtr.Zero; + } + + [DllImport("kernel32.dll")] + private static extern bool GetModuleHandleExW(uint flags, IntPtr address, out IntPtr module); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern uint GetModuleFileNameW(IntPtr module, char* buffer, uint size); + + /// <summary>"module+0xRVA" for a code or data address.</summary> + internal static string Describe(IntPtr address) + { + const uint FROM_ADDRESS = 0x4, UNCHANGED_REFCOUNT = 0x2; + if (address == IntPtr.Zero) + return "null"; + if (!GetModuleHandleExW(FROM_ADDRESS | UNCHANGED_REFCOUNT, address, out IntPtr module) || module == IntPtr.Zero) + return $"0x{address.ToInt32():X8} (no module)"; + char* buf = stackalloc char[260]; + uint n = GetModuleFileNameW(module, buf, 260); + return $"{System.IO.Path.GetFileName(new string(buf, 0, (int)n))}+0x{address.ToInt32() - module.ToInt32():X}"; + } + + /// <summary>Logs a device's vtable owner and EndScene/Reset/Present slots; returns its EndScene.</summary> + internal static IntPtr DescribeDevice(IntPtr device, string what, out bool endSceneInD3d9) + { + endSceneInD3d9 = false; + try + { + IntPtr vtable = Marshal.ReadIntPtr(device); + IntPtr endScene = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.EndScene * IntPtr.Size); + IntPtr reset = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.Reset * IntPtr.Size); + IntPtr present = Marshal.ReadIntPtr(vtable, 17 * IntPtr.Size); + string es = Describe(endScene); + endSceneInD3d9 = es.StartsWith("d3d9.dll+", StringComparison.OrdinalIgnoreCase); + RynthLog.D3D9($"DecalD3D9: {what} 0x{device.ToInt32():X8}: vtable {Describe(vtable)}, EndScene {es}, Reset {Describe(reset)}, Present {Describe(present)}."); + return endScene; + } + catch (Exception ex) + { + RynthLog.D3D9($"DecalD3D9: reading {what} threw {ex.GetType().Name}: {ex.Message}"); + return IntPtr.Zero; + } + } + + /// <summary>First backbuffer frame in our EndScene detour (AC's thread): which device our + /// d3d9 hook is called with, and whose code its vtable points at.</summary> + internal static void FirstFrame(IntPtr device) => DescribeDevice(device, "EndScene called with device", out _); +} diff --git a/src/RynthCore.Engine/D3D9/DeviceResetHook.cs b/src/RynthCore.Engine/D3D9/DeviceResetHook.cs new file mode 100644 index 0000000..ea4183c --- /dev/null +++ b/src/RynthCore.Engine/D3D9/DeviceResetHook.cs @@ -0,0 +1,88 @@ +// ============================================================================ +// RynthCore.Engine - D3D9/DeviceResetHook.cs +// IDirect3DDevice9::Reset: release the engine's D3DPOOL_DEFAULT resources +// (the pop-outs' render targets) just before AC resets a lost device. +// +// A plain D3D9 device can't be Reset while any default-pool resource is +// alive: Reset fails, and AC shows "Could not initialize Direct3D" and stops +// (2026-09-30 15:06, Lucy, PID 9384: the ImGui bar was popped out when the +// device was lost — screen lock / display change). The resources are +// recreated on the next frame, so nothing else changes. +// +// AC's main thread (Reset is called where EndScene is). Installed from the +// device when the frame controller first sees it; removed at shutdown. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Hooking; +using RynthCore.Engine.ImGuiBackend; + +namespace RynthCore.Engine.D3D9; + +internal static class DeviceResetHook +{ + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int ResetDelegate(IntPtr device, IntPtr presentationParameters); + + private static ResetDelegate? _original; + private static ResetDelegate? _detour; + private static IntPtr _address; + private static bool _installed; + private static int _resets; + + public static void InstallFromDevice(IntPtr device) + { + if (_installed || device == IntPtr.Zero) return; + try + { + // Without Decal: the device's vtable slot, as before. With Decal: d3d9's own Reset + // (Decal wraps Reset; its code is never hooked) - zero means not hooked. + _address = DecalD3D9.HookTarget(device, DeviceVTableIndex.Reset); + if (_address == IntPtr.Zero) return; + _detour = ResetDetour; + _original = Marshal.GetDelegateForFunctionPointer<ResetDelegate>( + MinHook.HookCreate(_address, Marshal.GetFunctionPointerForDelegate(_detour))); + Thread.MemoryBarrier(); + MinHook.Enable(_address); + _installed = true; + RynthLog.D3D9($"DeviceResetHook: installed at 0x{_address.ToInt32():X8}."); + } + catch (Exception ex) + { + RynthLog.D3D9($"DeviceResetHook: install failed - {ex.Message}"); + } + } + + public static void Uninstall() + { + if (!_installed) return; + RynthLog.D3D9($"DeviceResetHook: disable = {MinHook.StatusString(MinHook.MH_DisableHook(_address))}, remove = {MinHook.StatusString(MinHook.MH_RemoveHook(_address))}."); + _installed = false; + _original = null; + _detour = null; + } + + private static int ResetDetour(IntPtr device, IntPtr presentationParameters) + { + int n = Interlocked.Increment(ref _resets); + try + { + int released = ImGuiPopOuts.ReleaseDeviceResources(); + if (n <= 20) + RynthLog.D3D9($"DeviceResetHook: device Reset #{n}: released {released} pop-out surface set(s) first."); + } + catch (Exception ex) + { + try { RynthLog.D3D9($"DeviceResetHook: releasing before Reset threw {ex.GetType().Name}: {ex.Message}"); } catch { } + } + + int hr = _original!(device, presentationParameters); + if (n <= 20 || hr < 0) + { + try { RynthLog.D3D9($"DeviceResetHook: Reset #{n} returned 0x{hr:X8}."); } catch { } + } + return hr; + } +} diff --git a/src/RynthCore.Engine/D3D9/EndSceneHook.cs b/src/RynthCore.Engine/D3D9/EndSceneHook.cs index 2a811e4..4f40c7a 100644 --- a/src/RynthCore.Engine/D3D9/EndSceneHook.cs +++ b/src/RynthCore.Engine/D3D9/EndSceneHook.cs @@ -14,6 +14,10 @@ internal static class EndSceneHook private const int MaxOffscreenSkipsBeforeFallback = 120; private const int OffscreenFallbackDelayMs = 3000; private const int UiInitWarmupFrames = 180; + // After a hot reload the device and the game have been running all along: a few + // frames is enough (180 was ~1 s more of no overlay on every reload). + private const int UiInitWarmupFramesReload = 5; + private static int WarmupFrames => EntryPoint.InitCount >= 2 ? UiInitWarmupFramesReload : UiInitWarmupFrames; // ── FPS Governor — set by plugins via API ─────────────────────── internal static bool FpsLimitEnabled; @@ -46,6 +50,62 @@ internal static class EndSceneHook [DllImport("kernel32.dll")] private static extern uint GetCurrentProcessId(); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr CreateWaitableTimerExW(IntPtr attributes, string? name, uint flags, uint access); + + [DllImport("kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetWaitableTimer(IntPtr timer, ref long dueTime, int period, IntPtr completion, IntPtr arg, [MarshalAs(UnmanagedType.Bool)] bool resume); + + [DllImport("kernel32.dll")] + private static extern uint WaitForSingleObject(IntPtr handle, uint ms); + + [DllImport("winmm.dll")] + private static extern uint timeBeginPeriod(uint ms); + + private const uint CREATE_WAITABLE_TIMER_HIGH_RESOLUTION = 0x2; + private const uint TIMER_ALL_ACCESS = 0x1F0003; + private static IntPtr _frameTimer; + private static bool _frameTimerTried; + + /// <summary> + /// Waits <paramref name="ms"/> without burning the CPU. The governor used to wait with + /// Sleep(0) in a loop when focused (Sleep(0) returns at once when nothing else is ready, + /// so a "capped" focused client spun a whole core) and Sleep(1) in the background (15.6 ms + /// timer steps, so a 30 fps cap gave 19 fps, 2026-10-03). A high-resolution waitable timer + /// (Windows 10 1803+) wakes within about half a millisecond; without one, timeBeginPeriod(1) + /// makes Sleep(1) a 1 ms sleep. The last 0.3 ms is a yield loop for accuracy. + /// </summary> + private static void WaitFrame(double ms) + { + if (!_frameTimerTried) + { + _frameTimerTried = true; + try { _frameTimer = CreateWaitableTimerExW(IntPtr.Zero, null, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); } catch { } + if (_frameTimer == IntPtr.Zero) { try { timeBeginPeriod(1); } catch { } } + RynthLog.D3D9($"EndSceneHook: FPS governor waits with {(_frameTimer != IntPtr.Zero ? "a high-resolution timer" : "1 ms sleeps")}."); + } + + long start = Stopwatch.GetTimestamp(); + double waitMs = ms - 0.3; + if (waitMs > 0.5) + { + if (_frameTimer != IntPtr.Zero) + { + long due = -(long)(waitMs * 10_000); // negative = relative, in 100 ns units + if (SetWaitableTimer(_frameTimer, ref due, 0, IntPtr.Zero, IntPtr.Zero, false)) + WaitForSingleObject(_frameTimer, (uint)Math.Ceiling(waitMs) + 50); + } + else + { + while ((Stopwatch.GetTimestamp() - start) * 1000.0 / Stopwatch.Frequency < waitMs - 1.0) + Thread.Sleep(1); + } + } + while ((Stopwatch.GetTimestamp() - start) * 1000.0 / Stopwatch.Frequency < ms) + Thread.Yield(); + } + [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int EndSceneDelegate(IntPtr pDevice); @@ -54,6 +114,8 @@ internal static class EndSceneHook private static IntPtr _endSceneAddr; private static bool _installed; private static int _frameCount; + /// <summary>Back-buffer frames drawn (offscreen passes - Decal views, VVS, UB - not counted). Resets on reinstall.</summary> + internal static int BackBufferFrames => Volatile.Read(ref _frameCount); private static int _renderCount; private static int _skipCount; private static int _uiFrameCount; @@ -101,6 +163,30 @@ internal static class EndSceneHook RynthLog.D3D9("EndSceneHook: FAILED - could not discover vtable after all attempts."); } + /// <summary> + /// Decal clients (D3D9Bootstrapper.DecalInProcess): no D3D9 object is created (Decal + /// detours Direct3DCreate9 and CreateDevice). AC's device comes from the Decal bridge + /// (Decal's public IDecalCore.GetD3DDevice); Decal has swapped its vtable for a copy, so + /// d3d9.dll's original vtable is found by matching and d3d9's own EndScene is hooked + /// (DecalD3D9.TryResolve). A heap or image scan is not used: it can't tell AC's device + /// from the ones Decal plugins create (measured: it picked another device). + /// </summary> + public static void InstallWithoutDevice(string installSource) + { + if (_installed) + return; + ResetInstallState(installSource); + DecalD3D9.Enabled = true; + // Resolved (read-only) by EntryPoint before it chose this path; never Decal's code. + if (!DecalD3D9.TryResolve()) + { + RynthLog.D3D9("EndSceneHook: FAILED - AC's device couldn't be identified through the Decal bridge; no in-game UI in this client."); + return; + } + RynthLog.D3D9($"EndSceneHook: hooking d3d9's own EndScene @ 0x{DecalD3D9.ResolvedEndScene.ToInt32():X8} ({DecalD3D9.Describe(DecalD3D9.ResolvedEndScene)})."); + InstallFromEndSceneAddress(DecalD3D9.ResolvedEndScene); + } + public static void InstallFromDevice(IntPtr pDevice) { if (_installed) @@ -161,6 +247,7 @@ internal static class EndSceneHook // Let the render thread return through the trampoline. Thread.Sleep(80); + DeviceResetHook.Uninstall(); EngineFrameController.Shutdown(); status = MinHook.MH_RemoveHook(_endSceneAddr); @@ -225,7 +312,12 @@ internal static class EndSceneHook _skipCount++; long offscreenElapsedMs = Environment.TickCount64 - _firstOffscreenTick; - if (_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs) + // Decal clients: Decal's views, VVS and UB render into their own targets every + // frame, so an offscreen EndScene is normal there and the fallback below would + // draw our UI (and nav rings) into their textures (measured 2026-09-30). Never + // fall back with Decal; without Decal nothing changes. + if (DecalD3D9.Enabled || + (_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs)) return _originalEndScene!(pDevice); _offscreenFilterDisabled = true; @@ -241,6 +333,8 @@ internal static class EndSceneHook try { RadarHooks.TickHide(); } catch { /* never let this bring down EndScene */ } // Per-frame retail-powerbar visibility assertion (no-op unless plugin enables suppression). try { PowerbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ } + // Per-frame retail health/stamina/mana bars visibility ("Hide retail vitals"). + try { RetailVitalsHooks.TickHide(); } catch { /* never let this bring down EndScene */ } if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0) { @@ -260,8 +354,16 @@ internal static class EndSceneHook IntPtr actualEndScene = Marshal.ReadIntPtr(deviceVtable, DeviceVTableIndex.EndScene * IntPtr.Size); bool match = actualEndScene == _endSceneAddr; RynthLog.D3D9($"EndSceneHook: Device vtable EndScene=0x{actualEndScene:X8}, hooked=0x{_endSceneAddr:X8} — {(match ? "MATCH" : "MISMATCH")}"); + if (DecalD3D9.Enabled) + DecalD3D9.FirstFrame(pDevice); - if (!match && actualEndScene != IntPtr.Zero) + if (!match && DecalD3D9.Enabled) + { + // Decal client: the device's slot is Decal's wrapper (we hooked d3d9's own + // EndScene, which that wrapper calls). Never rehook onto Decal's code. + RynthLog.D3D9($"EndSceneHook: mismatch expected with Decal (slot is {DecalD3D9.Describe(actualEndScene)}) - keeping the d3d9 hook."); + } + else if (!match && actualEndScene != IntPtr.Zero) { // Deep-audit finding #8 (2026-06-18): the old sequence // disabled+REMOVED the old hook (freeing the trampoline @@ -303,11 +405,11 @@ internal static class EndSceneHook { if (!_warmupLogged) { - RynthLog.D3D9($"EndSceneHook: Backbuffer detected. Warming up {UiInitWarmupFrames} frame(s) before UI init."); + RynthLog.D3D9($"EndSceneHook: Backbuffer detected. Warming up {WarmupFrames} frame(s) before UI init."); _warmupLogged = true; } - if (_renderCount < UiInitWarmupFrames) + if (_renderCount < WarmupFrames) return _originalEndScene!(pDevice); _uiActivated = true; @@ -324,7 +426,7 @@ internal static class EndSceneHook if (_uiFrameCount == 60 && RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend) RynthLog.D3D9("EndSceneHook: 60 UI frames - ImGui is stable."); - if (_renderCount == UiInitWarmupFrames && !RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend) + if (_renderCount == WarmupFrames && !RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend) RynthLog.D3D9("EndSceneHook: ImGui backend disabled via engine.json (EnableImGuiBackend=false). Always-on engine work still runs; only ImGui draw calls are skipped."); // Avalonia compositor: independent of ImGui. Reads the latest @@ -348,9 +450,9 @@ internal static class EndSceneHook RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}"); } - // ImGui draw data (plugin overlay windows, shell) is submitted LAST so it - // sits on top of the Avalonia layer. Built earlier in OnEndScene; guarded - // internally, so an ImGui draw failure can't skip the original EndScene. + // ImGui draw data (in-client panels, plugin overlay windows such as the ILT Hub) + // is submitted LAST so it sits on top of the Avalonia layer. Built in OnEndScene; + // guarded internally, so an ImGui draw failure can't skip the original EndScene. EngineFrameController.RenderDeferredImGui(); } catch (Exception ex) @@ -388,8 +490,8 @@ internal static class EndSceneHook int targetFps = isFocused ? FpsTargetFocused : FpsTargetBackground; double minFrameMs = 1000.0 / Math.Max(targetFps, 1); - while (_fpsTimer.Elapsed.TotalMilliseconds < minFrameMs) - Thread.Sleep(isFocused ? 0 : 1); + double leftMs = minFrameMs - _fpsTimer.Elapsed.TotalMilliseconds; + if (leftMs > 0) WaitFrame(leftMs); _fpsTimer.Restart(); if (!_fpsLimiterLoggedOnce) diff --git a/src/RynthCore.Engine/D3D9/GameMatrixCapture.cs b/src/RynthCore.Engine/D3D9/GameMatrixCapture.cs index 625ccf4..4e2ea30 100644 --- a/src/RynthCore.Engine/D3D9/GameMatrixCapture.cs +++ b/src/RynthCore.Engine/D3D9/GameMatrixCapture.cs @@ -70,6 +70,33 @@ internal static unsafe class GameMatrixCapture private static bool _loggedFirstCapture; public static bool HasCapturedFrame => _hasValidViewProj; + + // Landblock whose local frame the current view matrix is built in: the + // anchor (submission / player) landblock when the camera was shifted into + // it, else the viewer's own. Anything projecting a world point must first + // move that point into this landblock's frame (192 m per landblock step). + private static uint _frameLandblock; + + /// <summary> + /// Landblock (cellId >> 16) whose local coordinates WorldToScreen expects, + /// as of the last CaptureFrame; 0 when unknown. AC's render thread. + /// </summary> + public static uint FrameLandblock => _frameLandblock; + + // Camera position in the same frame as the view matrix (D3D axes: x = east, + // y = up, z = north, FrameLandblock-local), as of the last CaptureFrame. + private static float _camX, _camY, _camZ; + + /// <summary> + /// The camera's position in WorldToScreen's frame (D3D axes, FrameLandblock-local). + /// False before the first capture. AC's render thread. + /// </summary> + public static bool TryGetCameraPosition(out float x, out float y, out float z) + { + x = _camX; y = _camY; z = _camZ; + return _hasValidViewProj; + } + public static uint ViewportWidth => _vpWidth; public static uint ViewportHeight => _vpHeight; @@ -100,6 +127,10 @@ internal static unsafe class GameMatrixCapture if (pMatrix != null && state == D3DTS_PROJECTION) { bool isPerspective = Math.Abs(pMatrix[11]) > 0.01f; + // Decal clients: a Virindi/Decal/UB 3D pass into its own render target must not + // replace AC's projection. Projection sets are rare; only checked with Decal. + if (isPerspective && DecalD3D9.Enabled && !ImGuiBackend.DX9Backend.IsRenderingToBackBuffer(dev)) + isPerspective = false; if (isPerspective) { for (int i = 0; i < 16; i++) @@ -198,6 +229,7 @@ internal static unsafe class GameMatrixCapture uint viewerCellId = unchecked((uint)Marshal.ReadInt32(camFrame + CamCellIdOffset)); uint viewerLandblock = viewerCellId >> 16; viewerLbForLog = viewerLandblock; + uint frameLandblock = viewerLandblock; // replaced by the anchor when the shift applies // Prefer the landblock the plugin tick LOCKED IN when it submitted // its Nav3D geometry (see Nav3DRenderer.ClearFrame). If we use the @@ -235,6 +267,7 @@ internal static unsafe class GameMatrixCapture cx += dXBlocks * 192f; // EW shift back into player-landblock frame cy += dYBlocks * 192f; // NS shiftApplied = (dXBlocks != 0 || dYBlocks != 0); + frameLandblock = playerLandblock; } else { @@ -299,6 +332,8 @@ internal static unsafe class GameMatrixCapture RynthLog.D3D9($"GameMatrixCapture: viewport={_vpWidth}x{_vpHeight}"); } + _camX = px; _camY = py; _camZ = pz; + _frameLandblock = frameLandblock; _hasValidViewProj = true; } @@ -354,8 +389,8 @@ internal static unsafe class GameMatrixCapture { try { - IntPtr vtable = Marshal.ReadIntPtr(pDevice); - IntPtr setTransformAddr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.SetTransform * IntPtr.Size); + IntPtr setTransformAddr = DecalD3D9.HookTarget(pDevice, DeviceVTableIndex.SetTransform); + if (setTransformAddr == IntPtr.Zero) return; // Decal client and the slot isn't d3d9's: not hooked _hookDelegate = new SetTransformD(SetTransformDetour); IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate); diff --git a/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs b/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs index 71bb505..a64fc9c 100644 --- a/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs +++ b/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs @@ -1,8 +1,22 @@ // ═══════════════════════════════════════════════════════════════════════════ // RynthCore.Engine — D3D9/Nav3DRenderInjector.cs -// Hooks DrawIndexedPrimitive to inject nav marker rendering at the -// 3D→UI boundary. When ZENABLE transitions from 1→0, renders markers -// so they appear after the 3D world but before the game's UI pass. +// Where the world overlays (Nav3D markers, then UnderUiLayer's nameplates and +// combat text) draw in AC's frame: after AC's 3D world, before AC's 2D UI. +// At most once per frame (one flag for every path). +// +// Paths, in order of preference (WorldLayerMode.Auto): +// UI pass AcUiPassHook: the entry of AC's RenderUI::RenderObjects, after +// all 3D including the alpha-sorted foliage/effects list. One +// call per frame; the DrawIndexedPrimitive hook below is then +// switched OFF (no per-draw cost). +// Transition only when the UI-pass hook isn't installed: the DIP hook spots +// ZENABLE going 1->0 after 3D draws. Known to fire too early +// outdoors (AC's sky pass after the landblocks draws with Z off, +// before the alpha list), so foliage can cover the overlays. +// EndScene the fallback (EngineFrameController): a frame where neither +// fired (no AC UI this frame, portal space, a loading screen). +// "/rc worldlayer" reports the path and counters, and "/rc worldlayer +// auto|uipass|transition|endscene" forces a path for the session (A/B checks). // ═══════════════════════════════════════════════════════════════════════════ using System; @@ -12,6 +26,19 @@ using RynthCore.Engine.Hooking; namespace RynthCore.Engine.D3D9; +/// <summary>Where the world overlays draw. Session only (/rc worldlayer); Auto at every start.</summary> +internal enum WorldLayerMode +{ + /// <summary>UI pass when the hook is installed, else the ZENABLE transition.</summary> + Auto, + /// <summary>Only at AC's UI pass (EndScene fallback otherwise).</summary> + UiPass, + /// <summary>Only at the first ZENABLE 1->0 transition (the pre-2026-10-04 behaviour).</summary> + Transition, + /// <summary>Always at EndScene (over AC's UI): for comparison only.</summary> + EndScene, +} + internal static class Nav3DRenderInjector { private const uint D3DRS_ZENABLE = 7; @@ -23,7 +50,9 @@ internal static class Nav3DRenderInjector private static DrawIndexedPrimitiveD? _originalDIP; private static DrawIndexedPrimitiveD? _hookDelegate; + private static IntPtr _dipTarget; private static bool _hookInstalled; + private static bool _dipEnabled; private static bool _inRender; // Per-frame transition detection @@ -31,8 +60,24 @@ internal static class Nav3DRenderInjector private static bool _markersRenderedThisFrame; private static bool _seen3D; + // Frames whose overlays drew at each place (diagnostics; AC's render thread). + private static long _atUiPass, _atTransition, _atEndScene; + + /// <summary>Session override, set by /rc worldlayer (any thread; read on AC's render thread).</summary> + public static volatile WorldLayerMode Mode = WorldLayerMode.Auto; + + /// <summary>The world overlays already drew this frame (any path).</summary> public static bool RenderedThisFrame => _markersRenderedThisFrame; + /// <summary>True while the overlays themselves are drawing (the draw hooks ignore those draws).</summary> + internal static bool InOverlayRender => _inRender; + + private static bool UseUiPass => + Mode == WorldLayerMode.UiPass || (Mode == WorldLayerMode.Auto && AcUiPassHook.IsInstalled); + + private static bool UseTransition => + Mode == WorldLayerMode.Transition || (Mode == WorldLayerMode.Auto && !AcUiPassHook.IsInstalled); + public static void ResetFrame() { _markersRenderedThisFrame = false; @@ -46,8 +91,8 @@ internal static class Nav3DRenderInjector try { - IntPtr vtable = Marshal.ReadIntPtr(pDevice); - IntPtr addr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.DrawIndexedPrimitive * IntPtr.Size); + IntPtr addr = DecalD3D9.HookTarget(pDevice, DeviceVTableIndex.DrawIndexedPrimitive); + if (addr == IntPtr.Zero) return; // Decal client and the slot isn't d3d9's: not hooked _hookDelegate = new DrawIndexedPrimitiveD(Detour); IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate); @@ -55,6 +100,8 @@ internal static class Nav3DRenderInjector MinHook.HookCreate(addr, hookPtr)); Thread.MemoryBarrier(); MinHook.Enable(addr); + _dipTarget = addr; + _dipEnabled = true; _hookInstalled = true; RynthLog.D3D9("Nav3DRenderInjector: DrawIndexedPrimitive hook installed."); @@ -65,6 +112,97 @@ internal static class Nav3DRenderInjector } } + /// <summary> + /// Frame boundary (end of EndScene, AC's render thread): the DIP hook runs only + /// when the transition path needs it. With the UI-pass hook live it is switched + /// off, so AC's draws pay nothing. + /// </summary> + public static void SyncHookState() + { + // Teardown: AcUiPassHook.Uninstall flips Auto to "transition"; don't re-patch then. + if (!_hookInstalled || EngineLifecycle.IsShuttingDown) return; + bool want = UseTransition; + if (want == _dipEnabled) return; + int status = want ? MinHook.MH_EnableHook(_dipTarget) : MinHook.MH_DisableHook(_dipTarget); + if (status == MinHook.MH_OK || status == MinHook.MH_ERROR_ENABLED || status == MinHook.MH_ERROR_DISABLED) + { + _dipEnabled = want; + RynthLog.D3D9($"Nav3DRenderInjector: DrawIndexedPrimitive hook {(want ? "enabled" : "disabled")} " + + $"(world overlays: {DescribePath()})."); + } + else if (want) + { + RynthLog.D3D9($"Nav3DRenderInjector: re-enabling the DrawIndexedPrimitive hook failed ({MinHook.StatusString(status)})."); + } + else + { + // Couldn't switch it off: harmless, the detour returns early when not needed. + _dipEnabled = true; + } + } + + /// <summary>AcUiPassHook: AC's RenderUI::RenderObjects is about to draw AC's 2D UI.</summary> + public static void OnAcUiPass() + { + if (!UseUiPass) return; + IntPtr dev = ImGuiBackend.EngineFrameController.CachedDevice; + if (dev == IntPtr.Zero) return; + if (PresentWorldOverlays(dev, sceneViewport: true)) + _atUiPass++; + } + + /// <summary> + /// EngineFrameController, EndScene, before the ImGui panels: draws the overlays + /// when no earlier path did this frame, then closes the frame for them (the ImGui + /// panels' own draws can't trigger the transition path afterwards). + /// </summary> + public static void PresentAtEndScene(IntPtr dev) + { + if (_markersRenderedThisFrame || dev == IntPtr.Zero) return; + _markersRenderedThisFrame = true; + _inRender = true; + try { ImGuiBackend.DX9Backend.RenderNav3D(dev); } + catch { } + try { ImGuiBackend.UnderUiLayer.PresentFallback(dev); } + catch { } + _inRender = false; + _atEndScene++; + } + + /// <summary>Draws the Nav3D markers, then the world overlays, once per frame. False: not drawn here.</summary> + private static bool PresentWorldOverlays(IntPtr dev, bool sceneViewport) + { + if (_markersRenderedThisFrame) return false; + // Decal clients: VVS/Decal/UB draw 3D into their own render targets too; only AC's + // back buffer gets the markers and nameplates (measured 2026-09-30: without this they + // showed up inside a Virindi window). Checked once per frame, only with Decal. + if (DecalD3D9.Enabled && !ImGuiBackend.DX9Backend.IsRenderingToBackBuffer(dev)) return false; + + _markersRenderedThisFrame = true; + _inRender = true; + try + { + // At the UI pass AC has set a full-screen viewport; the markers project + // with the 3D view's (captured at the last EndScene). + ImGuiBackend.DX9Backend.RenderNav3D(dev, sceneViewport); + } + catch + { + } + // The world overlays (nameplates, combat text) go here too, over the + // markers and under AC's UI. UnderUiLayer presents a list at most once. + try + { + if (sceneViewport) ImGuiBackend.UnderUiLayer.PresentAtUiPass(dev); + else ImGuiBackend.UnderUiLayer.PresentAtTransition(dev); + } + catch + { + } + _inRender = false; + return true; + } + private static int Detour(IntPtr dev, uint primitiveType, int baseVertexIndex, uint minVertexIndex, uint numVertices, uint startIndex, uint primCount) @@ -73,6 +211,10 @@ internal static class Nav3DRenderInjector return _originalDIP!(dev, primitiveType, baseVertexIndex, minVertexIndex, numVertices, startIndex, primCount); + if (!UseTransition) + return _originalDIP!(dev, primitiveType, baseVertexIndex, + minVertexIndex, numVertices, startIndex, primCount); + ImGuiBackend.DX9Backend.DeviceGetRenderState(dev, D3DRS_ZENABLE, out uint zEnable); if (zEnable != 0) @@ -81,16 +223,8 @@ internal static class Nav3DRenderInjector // Detect 3D→UI transition: ZENABLE goes from 1→0 after 3D draws if (!_markersRenderedThisFrame && _seen3D && _lastZEnable != 0 && zEnable == 0) { - _markersRenderedThisFrame = true; - _inRender = true; - try - { - ImGuiBackend.DX9Backend.RenderNav3D(dev); - } - catch - { - } - _inRender = false; + if (PresentWorldOverlays(dev, sceneViewport: false)) + _atTransition++; } _lastZEnable = zEnable; @@ -98,4 +232,19 @@ internal static class Nav3DRenderInjector return _originalDIP!(dev, primitiveType, baseVertexIndex, minVertexIndex, numVertices, startIndex, primCount); } + + /// <summary>The path the overlays use now, for status lines.</summary> + public static string DescribePath() => Mode switch + { + WorldLayerMode.UiPass => AcUiPassHook.IsInstalled ? "AC UI pass (forced)" : "AC UI pass (forced, hook missing: EndScene)", + WorldLayerMode.Transition => _hookInstalled ? "ZENABLE 1->0 transition (forced)" : "ZENABLE transition (forced, DIP hook missing: EndScene)", + WorldLayerMode.EndScene => "EndScene (forced, over AC's UI)", + _ => AcUiPassHook.IsInstalled ? "AC UI pass (auto)" : "ZENABLE 1->0 transition (auto: UI-pass hook not installed)", + }; + + /// <summary>One line for /rc worldlayer status and /rc imgui diag.</summary> + public static string Describe() => + $"world overlays: {DescribePath()}; frames drawn at UI pass {_atUiPass}, at transition {_atTransition}, " + + $"at EndScene {_atEndScene}; DIP hook {(_hookInstalled ? (_dipEnabled ? "on" : "off") : "not installed")}; " + + $"UI-pass hook: {AcUiPassHook.Status}, {AcUiPassHook.Calls} calls"; } diff --git a/src/RynthCore.Engine/D3D9/Nav3DRenderer.cs b/src/RynthCore.Engine/D3D9/Nav3DRenderer.cs index 6ea9296..f5db00d 100644 --- a/src/RynthCore.Engine/D3D9/Nav3DRenderer.cs +++ b/src/RynthCore.Engine/D3D9/Nav3DRenderer.cs @@ -13,9 +13,11 @@ // invisible). // // Pattern: -// pump: BeginFrame() → AddX(...) × N → CommitFrame() -// render: reads from the "ready" buffer only; never touches "pending" -// CommitFrame atomically swaps the index reads see. +// pump: ClearFrame() → AddX(...) × N → CommitFrame() +// render: Ready once per draw, then reads only that buffer; never +// touches "pending" +// CommitFrame atomically swaps the buffer reads see. A tick during which the +// player crossed a landblock boundary is dropped (see CommitFrame). // ═══════════════════════════════════════════════════════════════════════════ using System.Threading; @@ -34,7 +36,8 @@ internal static class Nav3DRenderer private const float DefaultRingHeight = 0.5f; // back-compat default for AddRing - private sealed class NavBuffer + /// <summary>One tick's submissions. Render side: read-only.</summary> + internal sealed class NavBuffer { public readonly float[] RingX = new float[MaxRings]; public readonly float[] RingY = new float[MaxRings]; @@ -99,38 +102,14 @@ internal static class Nav3DRenderer // ── Render-side reads ──────────────────────────────────────────────────── - public static int RingCount => _ready.RingCount; - public static int LineCount => _ready.LineCount; - public static int TriangleCount => _ready.TriCount; - - public static void GetRing(int i, out float x, out float y, out float z, - out float radius, out float thickness, out float height, out uint color) - { - var r = _ready; - x = r.RingX[i]; y = r.RingY[i]; z = r.RingZ[i]; - radius = r.RingRadius[i]; thickness = r.RingThick[i]; - height = r.RingHeight[i]; color = r.RingColor[i]; - } - - public static void GetLine(int i, out float x1, out float y1, out float z1, - out float x2, out float y2, out float z2, out float thickness, out uint color) - { - var r = _ready; - x1 = r.LineX1[i]; y1 = r.LineY1[i]; z1 = r.LineZ1[i]; - x2 = r.LineX2[i]; y2 = r.LineY2[i]; z2 = r.LineZ2[i]; - thickness = r.LineThick[i]; color = r.LineColor[i]; - } - - public static void GetTriangle(int i, out float x1, out float y1, out float z1, - out float x2, out float y2, out float z2, - out float x3, out float y3, out float z3, out uint color) - { - var r = _ready; - x1 = r.TriX1[i]; y1 = r.TriY1[i]; z1 = r.TriZ1[i]; - x2 = r.TriX2[i]; y2 = r.TriY2[i]; z2 = r.TriZ2[i]; - x3 = r.TriX3[i]; y3 = r.TriY3[i]; z3 = r.TriZ3[i]; - color = r.TriColor[i]; - } + /// <summary> + /// The latest committed frame. Take it once per draw and read everything + /// from it: re-reading this (volatile) property per item would mix two + /// ticks if a commit landed mid-draw (a count from one, contents from the + /// other). The triple buffer keeps a taken frame untouched for a full + /// tick after it stops being ready. + /// </summary> + public static NavBuffer Ready => _ready; // The landblock the plugin tick that produced the ready buffer was using. // Render thread uses this for view-matrix shifting so geometry stays @@ -197,9 +176,26 @@ internal static class Nav3DRenderer /// spare becomes the next pending. Render reads of the new ready buffer /// become visible across cores via the volatile field. Called by /// PluginManager.TickAll AFTER all plugins have submitted. + /// + /// The pump runs off AC's thread, so the player can cross a landblock + /// boundary between ClearFrame and here. Plugins sample the pose during + /// their tick, so some of this tick's geometry may then be in the old + /// landblock's frame and some in the new one, while the frame is anchored + /// to the old — whatever was sampled after the crossing would draw 192 m + /// off for a tick. Such a tick is dropped: the previous frame stays ready + /// (one tick stale, consistent) and the next tick is anchored correctly. /// </summary> public static void CommitFrame() { + uint anchored = _pending.SubmissionPlayerLandblock; + if (anchored != 0 && + PlayerPhysicsHooks.TryGetPlayerPose(out uint cellId, out _, out _, out _, out _, out _, out _, out _) && + (cellId >> 16) != 0 && (cellId >> 16) != anchored) + { + _pending.Reset(); + return; + } + NavBuffer newReady = _pending; NavBuffer newSpare = _ready; NavBuffer newPending = _spare; diff --git a/src/RynthCore.Engine/D3D9/VitalHud.cs b/src/RynthCore.Engine/D3D9/VitalHud.cs deleted file mode 100644 index 26de74d..0000000 --- a/src/RynthCore.Engine/D3D9/VitalHud.cs +++ /dev/null @@ -1,706 +0,0 @@ -// ═══════════════════════════════════════════════════════════════════════════ -// RynthCore.Engine — D3D9/VitalHud.cs -// -// "Hot HUD" — draws player Health / Stamina / Mana bars directly in the D3D9 -// EndScene path, on AC's render thread, every frame. Ported from RynthCore2's -// overlay/hud_overlay.cpp; the D3D9 plumbing mirrors TestRenderer.cs (cached -// vtable delegates + full render-state save/restore). -// -// Visuals: a translucent panel with a drop shadow, three gradient-filled bars -// (track + fill + gloss + border) with an HP/STAM/MANA label and a right- -// aligned "cur/max" number drawn from the dependency-free BitmapFont. -// Everything is colored 2D quads (D3DFVF_XYZRHW | D3DFVF_DIFFUSE, no texture) -// accumulated into one static vertex batch flushed with a single -// DrawPrimitiveUP — no per-frame heap allocation (avoids the LFH per-frame- -// alloc AV class). -// -// Interactive: drag the panel to move it, drag the bottom-right grip to resize. -// Win32Backend routes mouse messages to TryHandleMouse, which consumes the ones -// that land on the HUD so they never reach AC (no stray camera spin). Position + -// scale persist to %APPDATA%\RynthCore\vitalhud.cfg. -// -// Data source: Compatibility.PlayerVitalsHooks.TryGetSnapshot — the same -// buffed-effective values AC's own bars render, maintained on AC's main thread. -// Draw and TryHandleMouse both run on that thread (EndScene / WndProc), so the -// shared geometry state needs no cross-thread synchronization. -// ═══════════════════════════════════════════════════════════════════════════ - -using System; -using System.Globalization; -using System.IO; -using System.Runtime.InteropServices; -using RynthCore.Engine.Compatibility; -using RynthCore.Engine.Plugins; - -namespace RynthCore.Engine.D3D9; - -internal static unsafe class VitalHud -{ - // ─── D3D9 constants ─────────────────────────────────────────────── - private const uint D3DFVF_XYZRHW = 0x0004; - private const uint D3DFVF_DIFFUSE = 0x0040; - private const uint HudFvf = D3DFVF_XYZRHW | D3DFVF_DIFFUSE; - - private const uint D3DPT_TRIANGLELIST = 4; - - // D3DRENDERSTATETYPE - private const uint D3DRS_ZENABLE = 7; - private const uint D3DRS_ZWRITEENABLE = 14; - private const uint D3DRS_ALPHATESTENABLE = 15; - private const uint D3DRS_SRCBLEND = 19; - private const uint D3DRS_DESTBLEND = 20; - private const uint D3DRS_CULLMODE = 22; - private const uint D3DRS_ALPHABLENDENABLE = 27; - private const uint D3DRS_FOGENABLE = 28; - private const uint D3DRS_STENCILENABLE = 52; - private const uint D3DRS_LIGHTING = 137; - private const uint D3DRS_COLORWRITEENABLE = 168; - private const uint D3DRS_BLENDOP = 171; - private const uint D3DRS_SCISSORTESTENABLE = 174; - - // D3DTEXTURESTAGESTATETYPE - private const uint D3DTSS_COLOROP = 1; - private const uint D3DTSS_COLORARG1 = 2; - private const uint D3DTSS_ALPHAOP = 4; - private const uint D3DTSS_ALPHAARG1 = 6; - - // values - private const uint D3DBLEND_SRCALPHA = 5; - private const uint D3DBLEND_INVSRCALPHA = 6; - private const uint D3DBLENDOP_ADD = 1; - private const uint D3DCULL_NONE = 1; - private const uint D3DTOP_DISABLE = 1; - private const uint D3DTOP_SELECTARG1 = 2; - private const uint D3DTA_DIFFUSE = 0; - - // ─── Win32 messages + capture P/Invoke ──────────────────────────── - private const uint WM_LBUTTONDOWN = 0x0201; - private const uint WM_LBUTTONUP = 0x0202; - private const uint WM_MOUSEMOVE = 0x0200; - - [DllImport("user32.dll")] - private static extern IntPtr SetCapture(IntPtr hWnd); - - [DllImport("user32.dll")] - private static extern bool ReleaseCapture(); - - // ─── Vertex ─────────────────────────────────────────────────────── - [StructLayout(LayoutKind.Sequential)] - private struct Vertex - { - public float X, Y, Z, Rhw; - public uint Color; // ARGB - } - - [StructLayout(LayoutKind.Sequential)] - private struct D3DVIEWPORT9 - { - public uint X, Y, Width, Height; - public float MinZ, MaxZ; - } - - // ─── Device method delegates (COM/stdcall) ──────────────────────── - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int SetRenderStateDelegate(IntPtr dev, uint state, uint value); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int GetRenderStateDelegate(IntPtr dev, uint state, out uint pValue); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int SetTextureStageStateDelegate(IntPtr dev, uint stage, uint type, uint value); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int GetTextureStageStateDelegate(IntPtr dev, uint stage, uint type, out uint pValue); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int SetTextureDelegate(IntPtr dev, uint stage, IntPtr pTexture); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int GetTextureDelegate(IntPtr dev, uint stage, out IntPtr ppTexture); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int SetFVFDelegate(IntPtr dev, uint fvf); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int GetFVFDelegate(IntPtr dev, out uint fvf); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int SetVertexShaderDelegate(IntPtr dev, IntPtr pShader); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int GetVertexShaderDelegate(IntPtr dev, out IntPtr ppShader); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int SetPixelShaderDelegate(IntPtr dev, IntPtr pShader); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int GetPixelShaderDelegate(IntPtr dev, out IntPtr ppShader); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int DrawPrimitiveUPDelegate(IntPtr dev, uint primitiveType, uint primitiveCount, IntPtr pData, uint stride); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int GetViewportDelegate(IntPtr dev, out D3DVIEWPORT9 vp); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate uint ReleaseComDelegate(IntPtr pUnk); - - private static SetRenderStateDelegate? _setRenderState; - private static GetRenderStateDelegate? _getRenderState; - private static SetTextureStageStateDelegate? _setTextureStageState; - private static GetTextureStageStateDelegate? _getTextureStageState; - private static SetTextureDelegate? _setTexture; - private static GetTextureDelegate? _getTexture; - private static SetFVFDelegate? _setFVF; - private static GetFVFDelegate? _getFVF; - private static SetVertexShaderDelegate? _setVertexShader; - private static GetVertexShaderDelegate? _getVertexShader; - private static SetPixelShaderDelegate? _setPixelShader; - private static GetPixelShaderDelegate? _getPixelShader; - private static DrawPrimitiveUPDelegate? _drawPrimitiveUP; - private static GetViewportDelegate? _getViewport; - private static bool _delegatesCached; - - // ─── Geometry / interaction state (AC main thread only) ─────────── - private const float MinScale = 0.6f; - private const float MaxScale = 2.5f; - - private static float _hudX = 16f, _hudY = 16f, _scale = 1f; - private static float _vpW, _vpH; // last viewport, for input clamp - private static bool _geomInit; - private static bool _firstDrawLogged; - - private static int _dragMode; // 0 none, 1 move, 2 resize - private static float _grabDX, _grabDY; - private static float _resizeStartScale = 1f, _resizeStartDist = 1f; - - /// <summary>True while the user is dragging or resizing the HUD. Win32Backend - /// keeps routing mouse messages to <see cref="TryHandleMouse"/> while set.</summary> - public static bool IsDragging => _dragMode != 0; - - // ─── Vertex batch (single static buffer; no per-frame heap alloc) ── - // Text is the big consumer — the outline pass below draws each number 9×. - private const int MaxVerts = 48000; - private static readonly Vertex[] _batch = new Vertex[MaxVerts]; - private static int _batchCount; - - // Cached text sink + color so BitmapFont.Emit allocates nothing per call. - private static readonly BitmapFont.CellSink _cellSink = TextCell; - private static uint _textColor; - - // ─── Layout derived from the uniform scale ──────────────────────── - private struct Metrics - { - public float Scale, Pad, BarW, BarH, Gap, PanelW, PanelH, Grip; - } - - private static Metrics Metric(float s) - { - if (s < MinScale) s = MinScale; - if (s > MaxScale) s = MaxScale; - Metrics m; - m.Scale = s; - m.Pad = 8f * s; - m.BarW = 228f * s; // wide enough for a big "cur/max" number - m.BarH = 26f * s; // taller bars → bigger, retail-legible numbers - m.Gap = 6f * s; - m.PanelW = m.Pad * 2f + m.BarW; - m.PanelH = m.Pad * 2f + m.BarH * 3f + m.Gap * 2f; - m.Grip = 16f * s; - return m; - } - - // ─── Color helpers ──────────────────────────────────────────────── - private static uint Argb(int a, int r, int g, int b) - => ((uint)a << 24) | ((uint)r << 16) | ((uint)g << 8) | (uint)b; - - private static uint Lighten(uint c, int add) - { - static int Cl(int v) => v < 0 ? 0 : (v > 255 ? 255 : v); - int a = (int)((c >> 24) & 0xFF); - int r = (int)((c >> 16) & 0xFF); - int g = (int)((c >> 8) & 0xFF); - int b = (int)(c & 0xFF); - return Argb(a, Cl(r + add), Cl(g + add), Cl(b + add)); - } - - // ─── Batch builders ─────────────────────────────────────────────── - private static void BatchReset() => _batchCount = 0; - - private static void PushQuad(float x0, float y0, float x1, float y1, - uint cTL, uint cTR, uint cBR, uint cBL) - { - if (_batchCount + 6 > MaxVerts) return; - Set(ref _batch[_batchCount + 0], x0, y0, cTL); - Set(ref _batch[_batchCount + 1], x1, y0, cTR); - Set(ref _batch[_batchCount + 2], x1, y1, cBR); - Set(ref _batch[_batchCount + 3], x0, y0, cTL); - Set(ref _batch[_batchCount + 4], x1, y1, cBR); - Set(ref _batch[_batchCount + 5], x0, y1, cBL); - _batchCount += 6; - - static void Set(ref Vertex v, float x, float y, uint c) - { - v.X = x; v.Y = y; v.Z = 0f; v.Rhw = 1f; v.Color = c; - } - } - - private static void PushRect(float x0, float y0, float x1, float y1, uint c) - => PushQuad(x0, y0, x1, y1, c, c, c, c); - - private static void PushVGrad(float x0, float y0, float x1, float y1, uint top, uint bot) - => PushQuad(x0, y0, x1, y1, top, top, bot, bot); - - // ─── Text → batched quads via the bitmap font ───────────────────── - private static void TextCell(int x0, int y0, int x1, int y1) - => PushRect(x0, y0, x1, y1, _textColor); - - // Draws text with a full dark outline (all 8 neighbour offsets) then the - // foreground on top, so it stays legible over any bar fill color — the - // single drop-shadow was washed out on the light (yellow) bar. - private static void DrawText(ReadOnlySpan<char> s, int x, int y, int cellPx, uint color) - { - int o = cellPx >= 4 ? 2 : 1; // outline thickness in px - _textColor = Argb(235, 0, 0, 0); - BitmapFont.Emit(s, x - o, y - o, cellPx, _cellSink); - BitmapFont.Emit(s, x, y - o, cellPx, _cellSink); - BitmapFont.Emit(s, x + o, y - o, cellPx, _cellSink); - BitmapFont.Emit(s, x - o, y, cellPx, _cellSink); - BitmapFont.Emit(s, x + o, y, cellPx, _cellSink); - BitmapFont.Emit(s, x - o, y + o, cellPx, _cellSink); - BitmapFont.Emit(s, x, y + o, cellPx, _cellSink); - BitmapFont.Emit(s, x + o, y + o, cellPx, _cellSink); - _textColor = color; - BitmapFont.Emit(s, x, y, cellPx, _cellSink); - } - - // "cur/max" formatted into the caller's buffer without allocating; returns - // the number of chars written (≤ buf.Length). - private static int FormatVital(uint cur, uint mx, Span<char> buf) - { - int len = 0; - if (cur.TryFormat(buf, out int w1)) len += w1; - if (len < buf.Length) buf[len++] = '/'; - if (mx.TryFormat(buf.Slice(len), out int w2)) len += w2; - return len; - } - - private static void EmitBar(float x, float y, in Metrics m, - uint cur, uint mx, uint baseColor) - { - float w = m.BarW, h = m.BarH; - - PushRect(x, y, x + w, y + h, Argb(205, 18, 20, 26)); // track - - if (mx > 0) - { - float ratio = (float)cur / mx; - if (ratio < 0f) ratio = 0f; - if (ratio > 1f) ratio = 1f; - float fw = w * ratio; - PushVGrad(x, y, x + fw, y + h, Lighten(baseColor, 55), baseColor); // fill - PushRect(x, y, x + fw, y + h * 0.32f, Argb(60, 255, 255, 255)); // gloss - } - - float bw = m.Scale >= 1.5f ? 2f : 1f; // border - uint bc = Argb(180, 90, 100, 120); - PushRect(x, y, x + w, y + bw, bc); - PushRect(x, y + h - bw, x + w, y + h, bc); - PushRect(x, y, x + bw, y + h, bc); - PushRect(x + w - bw, y, x + w, y + h, bc); - - // Number only (no label — the red/yellow/blue color identifies the bar). - // Sized as large as fits the bar, centered, with a dark outline so it - // reads clearly over any fill color (especially white-on-yellow). - Span<char> numBuf = stackalloc char[24]; - ReadOnlySpan<char> num = numBuf[..FormatVital(cur, mx, numBuf)]; - - int innerPad = (int)(m.Pad * 0.4f); - if (innerPad < 2) innerPad = 2; - int availW = (int)w - 2 * innerPad; - - int cellPx = (int)(h * 0.82f / BitmapFont.GlyphH); // tallest that fits the bar - if (cellPx < 1) cellPx = 1; - while (cellPx > 1 && BitmapFont.MeasureWidth(num, cellPx) > availW) cellPx--; - - int tw = BitmapFont.MeasureWidth(num, cellPx); - int th = BitmapFont.Height(cellPx); - int tx = (int)(x + (w - tw) * 0.5f); // center horizontally - int ty = (int)(y + (h - th) * 0.5f); // center vertically - DrawText(num, tx, ty, cellPx, Argb(255, 245, 250, 255)); - } - - // ─── Public API ─────────────────────────────────────────────────── - public static void Draw(IntPtr pDevice) - { - if (pDevice == IntPtr.Zero) return; - if (!PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot snap)) return; - - if (!_delegatesCached) - CacheDelegates(pDevice); - if (_drawPrimitiveUP == null) return; // delegate cache failed - - if (_getViewport!(pDevice, out D3DVIEWPORT9 vp) < 0) return; - float wF = vp.Width; - float hF = vp.Height; - if (wF < 1f || hF < 1f) return; - - if (!_firstDrawLogged) - { - _firstDrawLogged = true; - RynthLog.D3D9("VitalHud: first draw."); - } - - // First-draw placement: prefer the saved config, else default top-right. - if (!_geomInit) - { - _geomInit = true; - if (LoadCfg(out float lx, out float ly, out float ls)) - { - _scale = ls; _hudX = lx; _hudY = ly; - } - else - { - _scale = 1f; - Metrics dm = Metric(1f); - _hudX = wF - dm.PanelW - 16f; - _hudY = 16f; - } - } - - // ── Save the device state we are about to clobber ────────────── - _getRenderState!(pDevice, D3DRS_ZENABLE, out uint svZE); - _getRenderState(pDevice, D3DRS_ZWRITEENABLE, out uint svZWE); - _getRenderState(pDevice, D3DRS_ALPHATESTENABLE, out uint svATE); - _getRenderState(pDevice, D3DRS_ALPHABLENDENABLE, out uint svABE); - _getRenderState(pDevice, D3DRS_SRCBLEND, out uint svSB); - _getRenderState(pDevice, D3DRS_DESTBLEND, out uint svDB); - _getRenderState(pDevice, D3DRS_BLENDOP, out uint svBO); - _getRenderState(pDevice, D3DRS_CULLMODE, out uint svCull); - _getRenderState(pDevice, D3DRS_LIGHTING, out uint svLit); - _getRenderState(pDevice, D3DRS_FOGENABLE, out uint svFog); - _getRenderState(pDevice, D3DRS_STENCILENABLE, out uint svSte); - _getRenderState(pDevice, D3DRS_SCISSORTESTENABLE, out uint svSci); - _getRenderState(pDevice, D3DRS_COLORWRITEENABLE, out uint svCW); - _getFVF!(pDevice, out uint svFvf); - - _getTextureStageState!(pDevice, 0, D3DTSS_COLOROP, out uint svT0CO); - _getTextureStageState(pDevice, 0, D3DTSS_COLORARG1, out uint svT0CA1); - _getTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, out uint svT0AO); - _getTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, out uint svT0AA1); - _getTextureStageState(pDevice, 1, D3DTSS_COLOROP, out uint svT1CO); - - _getVertexShader!(pDevice, out IntPtr svVS); - _getPixelShader!(pDevice, out IntPtr svPS); - _getTexture!(pDevice, 0, out IntPtr svTex0); - - try - { - // ── Set HUD state: 2D, alpha-blended, colored verts, no tex/shaders ── - _setRenderState!(pDevice, D3DRS_ZENABLE, 0); - _setRenderState(pDevice, D3DRS_ZWRITEENABLE, 0); - _setRenderState(pDevice, D3DRS_ALPHATESTENABLE, 0); - _setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, 1); - _setRenderState(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); - _setRenderState(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); - _setRenderState(pDevice, D3DRS_BLENDOP, D3DBLENDOP_ADD); - _setRenderState(pDevice, D3DRS_CULLMODE, D3DCULL_NONE); - _setRenderState(pDevice, D3DRS_LIGHTING, 0); - _setRenderState(pDevice, D3DRS_FOGENABLE, 0); - _setRenderState(pDevice, D3DRS_STENCILENABLE, 0); - _setRenderState(pDevice, D3DRS_SCISSORTESTENABLE, 0); - _setRenderState(pDevice, D3DRS_COLORWRITEENABLE, 0xF); - - _setTextureStageState!(pDevice, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); - _setTextureStageState(pDevice, 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE); - _setTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); - _setTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE); - _setTextureStageState(pDevice, 1, D3DTSS_COLOROP, D3DTOP_DISABLE); - - _setTexture!(pDevice, 0, IntPtr.Zero); - _setVertexShader!(pDevice, IntPtr.Zero); - _setPixelShader!(pDevice, IntPtr.Zero); - _setFVF!(pDevice, HudFvf); - - BuildBatch(in snap, wF, hF); - - if (_batchCount >= 3) - { - fixed (Vertex* p = _batch) - { - _drawPrimitiveUP(pDevice, D3DPT_TRIANGLELIST, - (uint)(_batchCount / 3), (IntPtr)p, (uint)sizeof(Vertex)); - } - } - - _vpW = wF; // for input hit-test clamping - _vpH = hF; - } - finally - { - // ── Restore the saved state ──────────────────────────────── - _setRenderState!(pDevice, D3DRS_ZENABLE, svZE); - _setRenderState(pDevice, D3DRS_ZWRITEENABLE, svZWE); - _setRenderState(pDevice, D3DRS_ALPHATESTENABLE, svATE); - _setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, svABE); - _setRenderState(pDevice, D3DRS_SRCBLEND, svSB); - _setRenderState(pDevice, D3DRS_DESTBLEND, svDB); - _setRenderState(pDevice, D3DRS_BLENDOP, svBO); - _setRenderState(pDevice, D3DRS_CULLMODE, svCull); - _setRenderState(pDevice, D3DRS_LIGHTING, svLit); - _setRenderState(pDevice, D3DRS_FOGENABLE, svFog); - _setRenderState(pDevice, D3DRS_STENCILENABLE, svSte); - _setRenderState(pDevice, D3DRS_SCISSORTESTENABLE, svSci); - _setRenderState(pDevice, D3DRS_COLORWRITEENABLE, svCW); - - _setTextureStageState!(pDevice, 0, D3DTSS_COLOROP, svT0CO); - _setTextureStageState(pDevice, 0, D3DTSS_COLORARG1, svT0CA1); - _setTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, svT0AO); - _setTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, svT0AA1); - _setTextureStageState(pDevice, 1, D3DTSS_COLOROP, svT1CO); - - _setFVF!(pDevice, svFvf); - _setVertexShader!(pDevice, svVS); - _setPixelShader!(pDevice, svPS); - _setTexture!(pDevice, 0, svTex0); - - // GetVertexShader / GetPixelShader / GetTexture each AddRef — release. - ReleaseCom(svVS); - ReleaseCom(svPS); - ReleaseCom(svTex0); - } - } - - private static void BuildBatch(in PlayerVitalsSnapshot snap, float wF, float hF) - { - Metrics m = Metric(_scale); - float px = _hudX; - float py = _hudY; - if (px > wF - m.PanelW) px = wF - m.PanelW; // keep on-screen (draw-only) - if (py > hF - m.PanelH) py = hF - m.PanelH; - if (px < 0f) px = 0f; - if (py < 0f) py = 0f; - - BatchReset(); - - float so = 5f * m.Scale; // shadow - PushRect(px + so, py + so, px + m.PanelW + so, py + m.PanelH + so, Argb(110, 0, 0, 0)); - PushVGrad(px, py, px + m.PanelW, py + m.PanelH, // backing - Argb(205, 28, 30, 38), Argb(205, 16, 17, 22)); - PushRect(px, py, px + m.PanelW, py + m.Pad * 0.6f, Argb(45, 255, 255, 255)); // header hint - - float pbw = m.Scale >= 1.5f ? 2f : 1f; // panel border - uint pbc = Argb(200, 120, 130, 150); - PushRect(px, py, px + m.PanelW, py + pbw, pbc); - PushRect(px, py + m.PanelH - pbw, px + m.PanelW, py + m.PanelH, pbc); - PushRect(px, py, px + pbw, py + m.PanelH, pbc); - PushRect(px + m.PanelW - pbw, py, px + m.PanelW, py + m.PanelH, pbc); - - float bx = px + m.Pad; - float by = py + m.Pad; - EmitBar(bx, by, in m, snap.Health, snap.MaxHealth, Argb(235, 200, 45, 45)); - by += m.BarH + m.Gap; - EmitBar(bx, by, in m, snap.Stamina, snap.MaxStamina, Argb(235, 205, 170, 45)); - by += m.BarH + m.Gap; - EmitBar(bx, by, in m, snap.Mana, snap.MaxMana, Argb(235, 55, 115, 235)); - - // resize grip (three dots) bottom-right - float d = 3f * m.Scale; - if (d < 2f) d = 2f; - float gx = px + m.PanelW - m.Pad * 0.5f; - float gy = py + m.PanelH - m.Pad * 0.5f; - uint gc = Argb(200, 200, 205, 215); - for (int i = 1; i <= 3; i++) - { - float ox = gx - i * (d + 1f); - float oy = gy - i * (d + 1f); - PushRect(ox, oy, ox + d, oy + d, gc); - } - } - - // ─── Input ──────────────────────────────────────────────────────── - - /// <summary> - /// Handles left-button drag (anywhere on the panel) + grip resize. Returns - /// true when the message landed on the HUD and should be swallowed so it - /// never reaches AC. Called from Win32Backend.WndProcHook on AC's main - /// thread, before the Avalonia forward. No-op (returns false) when the HUD - /// is not being drawn. - /// </summary> - public static bool TryHandleMouse(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) - { - if (!_geomInit || !EngineSettings.DrawCustomVitalBars) - return false; - - switch (msg) - { - case WM_LBUTTONDOWN: - { - float mxf = (short)((long)lParam & 0xFFFF); - float myf = (short)(((long)lParam >> 16) & 0xFFFF); - Metrics m = Metric(_scale); - - // Clamp the same way Draw does so the hit-test matches the pixels. - float px = _hudX, py = _hudY; - if (_vpW > 0f && px > _vpW - m.PanelW) px = _vpW - m.PanelW; - if (_vpH > 0f && py > _vpH - m.PanelH) py = _vpH - m.PanelH; - if (px < 0f) px = 0f; - if (py < 0f) py = 0f; - - bool inPanel = mxf >= px && mxf <= px + m.PanelW && - myf >= py && myf <= py + m.PanelH; - if (!inPanel) return false; - - // Pin the (clamped) top-left so move/resize anchor to the pixels. - _hudX = px; _hudY = py; - - bool inGrip = mxf >= px + m.PanelW - m.Grip && myf >= py + m.PanelH - m.Grip; - if (inGrip) - { - float dx = mxf - px, dy = myf - py; - float dist = MathF.Sqrt(dx * dx + dy * dy); - if (dist < 8f) dist = 8f; - _resizeStartDist = dist; - _resizeStartScale = m.Scale; - _dragMode = 2; - } - else - { - _grabDX = mxf - px; - _grabDY = myf - py; - _dragMode = 1; - } - SetCapture(hWnd); - return true; - } - - case WM_MOUSEMOVE: - { - if (_dragMode == 0) return false; - // Left button no longer held (we missed the UP — e.g. capture - // stolen by alt-tab): end the drag and let the move through so the - // HUD can't get stuck following the cursor. - if (((long)wParam & 0x0001 /* MK_LBUTTON */) == 0) - { - _dragMode = 0; - ReleaseCapture(); - SaveCfg(); - return false; - } - float mxf = (short)((long)lParam & 0xFFFF); - float myf = (short)(((long)lParam >> 16) & 0xFFFF); - - if (_dragMode == 1) // move - { - float nx = mxf - _grabDX; - float ny = myf - _grabDY; - Metrics m = Metric(_scale); - if (_vpW > 0f && nx > _vpW - m.PanelW) nx = _vpW - m.PanelW; - if (_vpH > 0f && ny > _vpH - m.PanelH) ny = _vpH - m.PanelH; - if (nx < 0f) nx = 0f; - if (ny < 0f) ny = 0f; - _hudX = nx; _hudY = ny; - } - else // resize - { - float dx = mxf - _hudX, dy = myf - _hudY; - float dist = MathF.Sqrt(dx * dx + dy * dy); - float s = _resizeStartScale * dist / _resizeStartDist; - if (s < MinScale) s = MinScale; - if (s > MaxScale) s = MaxScale; - _scale = s; - } - return true; - } - - case WM_LBUTTONUP: - { - if (_dragMode == 0) return false; - _dragMode = 0; - ReleaseCapture(); - SaveCfg(); - return true; - } - - default: - return false; - } - } - - // ─── Persistence: %APPDATA%\RynthCore\vitalhud.cfg ("x y scale") ── - private static string? CfgPath() - { - string? appData = Environment.GetEnvironmentVariable("APPDATA"); - if (string.IsNullOrEmpty(appData)) return null; - return Path.Combine(appData, "RynthCore", "vitalhud.cfg"); - } - - private static bool LoadCfg(out float x, out float y, out float s) - { - x = 0f; y = 0f; s = 1f; - try - { - string? path = CfgPath(); - if (path == null || !File.Exists(path)) return false; - string[] parts = File.ReadAllText(path) - .Split([' ', '\t', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries); - if (parts.Length < 3) return false; - if (!float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out float fx) || - !float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float fy) || - !float.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out float fs)) - return false; - if (fs < MinScale) fs = MinScale; - if (fs > MaxScale) fs = MaxScale; - if (fx < 0f) fx = 0f; - if (fy < 0f) fy = 0f; - x = fx; y = fy; s = fs; - return true; - } - catch (Exception ex) - { - RynthLog.D3D9($"VitalHud: LoadCfg failed - {ex.Message}"); - return false; - } - } - - private static void SaveCfg() - { - try - { - string? path = CfgPath(); - if (path == null) return; - Directory.CreateDirectory(Path.GetDirectoryName(path)!); - string body = string.Format(CultureInfo.InvariantCulture, "{0:F1} {1:F1} {2:F4}", _hudX, _hudY, _scale); - File.WriteAllText(path, body); - } - catch (Exception ex) - { - RynthLog.D3D9($"VitalHud: SaveCfg failed - {ex.Message}"); - } - } - - // ─── Internals ──────────────────────────────────────────────────── - private static void CacheDelegates(IntPtr pDevice) - { - IntPtr vtable = Marshal.ReadIntPtr(pDevice); - - _setRenderState = Get<SetRenderStateDelegate>(vtable, DeviceVTableIndex.SetRenderState); - _getRenderState = Get<GetRenderStateDelegate>(vtable, DeviceVTableIndex.GetRenderState); - _setTextureStageState = Get<SetTextureStageStateDelegate>(vtable, DeviceVTableIndex.SetTextureStageState); - _getTextureStageState = Get<GetTextureStageStateDelegate>(vtable, DeviceVTableIndex.GetTextureStageState); - _setTexture = Get<SetTextureDelegate>(vtable, DeviceVTableIndex.SetTexture); - _getTexture = Get<GetTextureDelegate>(vtable, DeviceVTableIndex.GetTexture); - _setFVF = Get<SetFVFDelegate>(vtable, DeviceVTableIndex.SetFVF); - _getFVF = Get<GetFVFDelegate>(vtable, DeviceVTableIndex.GetFVF); - _setVertexShader = Get<SetVertexShaderDelegate>(vtable, DeviceVTableIndex.SetVertexShader); - _getVertexShader = Get<GetVertexShaderDelegate>(vtable, DeviceVTableIndex.GetVertexShader); - _setPixelShader = Get<SetPixelShaderDelegate>(vtable, DeviceVTableIndex.SetPixelShader); - _getPixelShader = Get<GetPixelShaderDelegate>(vtable, DeviceVTableIndex.GetPixelShader); - _drawPrimitiveUP = Get<DrawPrimitiveUPDelegate>(vtable, DeviceVTableIndex.DrawPrimitiveUP); - _getViewport = Get<GetViewportDelegate>(vtable, DeviceVTableIndex.GetViewport); - - _delegatesCached = true; - RynthLog.D3D9("VitalHud: D3D9 delegates cached."); - } - - private static T Get<T>(IntPtr vtable, int index) where T : Delegate - { - IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size); - return Marshal.GetDelegateForFunctionPointer<T>(addr); - } - - private static void ReleaseCom(IntPtr pUnk) - { - if (pUnk == IntPtr.Zero) return; - IntPtr vtbl = Marshal.ReadIntPtr(pUnk); - IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size); // IUnknown::Release - var release = Marshal.GetDelegateForFunctionPointer<ReleaseComDelegate>(releaseAddr); - release(pUnk); - } -} diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs index 3ff3fc6..0d1ac0d 100644 --- a/src/RynthCore.Engine/EngineLifecycle.cs +++ b/src/RynthCore.Engine/EngineLifecycle.cs @@ -7,8 +7,7 @@ // // 1. EndSceneHook.Uninstall — chains into EngineFrameController.Shutdown which // tears down PluginManager (RynthPluginShutdown + FreeLibrary plugins), -// OverlayTextureRenderer, ViewportRendererBackend, ViewportPlatformBackend, -// DX9Backend, Win32Backend (restores WndProc), and destroys ImGui context. +// OverlayTextureRenderer, DX9Backend, and destroys the ImGui context. // 2. Drain — sleep so any in-flight EndScene call has returned through the // trampoline before we tear down anything else. // 3. AvaloniaOverlay.Stop — Dispatcher shutdown, join STA thread. @@ -106,6 +105,15 @@ internal static class EngineLifecycle RynthLog.Info("EngineLifecycle: Shutdown beginning."); + // A reload can come while this generation is still initializing (two RL clicks, + // or a file-watcher reload during login). Let InitWorker reach its next step and + // stop before tearing anything down under it. + Step("InitWorker join", () => + { + if (!EntryPoint.WaitForInitWorker(15000)) + RynthLog.Info("EngineLifecycle: InitWorker still running after 15 s; tearing down anyway."); + }); + // Stop the hang watchdog BEFORE its beat source (the EndScene detour) // is uninstalled. A still-running old-generation watchdog sees the beat // go silent, declares a false hang ~4s later, suspends AC's healthy main @@ -121,6 +129,13 @@ internal static class EngineLifecycle // 2026-06-11 DINPUT8 reload wedge. Step("AcMainThreadQueue.Disarm", () => Compatibility.AcMainThreadQueue.Disarm()); + // Same for queued panel commands (UI.Data.UiDataHub): never run a + // plugin-mutating UI command while the plugins are shutting down. + Step("UiDataHub.Disarm", () => UI.Data.UiDataHub.Disarm()); + + // AC's UI-pass hook draws the world overlays mid-frame from the same render-side + // state EndSceneHook.Uninstall tears down: stop it first (its 80 ms drain covers both). + Step("AcUiPassHook.Uninstall", () => AcUiPassHook.Uninstall()); Step("EndSceneHook.Uninstall", () => EndSceneHook.Uninstall()); // Give in-flight EndScene calls a chance to drain. AC's render thread @@ -152,6 +167,12 @@ internal static class EngineLifecycle // Otherwise the pump's TickAll/ProcessPendingActions can be mid-call // into a plugin whose code pages we're about to unmap → AV. Step("TickPump.StopAndJoin", () => EntryPoint.StopTickPumpAndJoin()); + // spike/decal-bridge: after the pump (its only reader) has stopped. + Step("DecalBridgeHost.Shutdown", () => Compatibility.DecalBridgeHost.Shutdown()); + + // The chat log is written on the tick pump (UiDataHub), now stopped. Left open, + // it outlived this generation and locked the next one out of the file. + Step("ChatModel.CloseLog", () => UI.Data.ChatModel.CloseLog()); Step("PluginManager.ShutdownAll (defensive)", () => PluginManager.ShutdownAll()); @@ -162,6 +183,14 @@ internal static class EngineLifecycle // module's code at the moment of FreeLibrary. Step("HeartbeatLogger.StopAndJoin", () => Compatibility.HeartbeatLogger.StopAndJoin()); + // Every other engine thread (init, pumps, login helpers, D3D9 bootstrap...). + // Their sleeps wake at once; a thread still running engine code afterwards + // keeps this generation from unloading under the CoreCLR host. + Step("EngineThreads.StopAndJoinAll", () => EngineThreads.StopAndJoinAll(3000)); + + // Process-wide events: under CoreCLR they would hold this generation. + Step("EntryPoint.UninstallManagedExceptionHandlers", EntryPoint.UninstallManagedExceptionHandlers); + Step("MH_DisableHook(ALL)", () => { // DisableHook restores the original code at every hooked function — that's @@ -176,6 +205,10 @@ internal static class EngineLifecycle RynthLog.Info($"MH_DisableHook(ALL) = {MinHook.StatusString(disable)}"); }); + // Managed plugins' contexts go last: nothing in the engine may call into them + // after this (every thread is joined, the hooks are off). + Step("ManagedPlugins.UnloadRetired", ManagedPlugins.UnloadRetired); + Volatile.Write(ref _hasShutDown, 1); RynthLog.Info("EngineLifecycle: Shutdown complete."); } diff --git a/src/RynthCore.Engine/EngineThreads.cs b/src/RynthCore.Engine/EngineThreads.cs new file mode 100644 index 0000000..a0acbeb --- /dev/null +++ b/src/RynthCore.Engine/EngineThreads.cs @@ -0,0 +1,78 @@ +// ============================================================================ +// RynthCore.Engine - EngineThreads.cs +// +// Every long-lived thread the engine starts goes through here, so shutdown can wake +// them and join them. Under the CoreCLR host (docs/UNLOADABLE_ENGINE_PLAN.md) a +// thread with a frame in engine code keeps the whole engine generation from +// unloading; under NativeAOT it keeps running old code after a reload. Either way +// EngineLifecycle.Shutdown must leave none behind. +// +// Loops sleep with EngineThreads.Sleep(ms), which returns false (at once) when the +// engine is shutting down: `if (!EngineThreads.Sleep(250)) return;`. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Threading; + +namespace RynthCore.Engine; + +internal static class EngineThreads +{ + private static readonly object Sync = new(); + private static readonly List<Thread> Threads = new(); + private static readonly ManualResetEvent StopEvent = new(false); + + /// <summary>True once shutdown has asked every engine thread to stop.</summary> + public static bool Stopping => StopEvent.WaitOne(0); + + /// <summary>Starts a background thread the engine's shutdown will wait for.</summary> + public static Thread Start(string name, ThreadStart body, ApartmentState apartment = ApartmentState.Unknown) + { + var thread = new Thread(body) { Name = name, IsBackground = true }; + if (apartment != ApartmentState.Unknown) + thread.SetApartmentState(apartment); + Track(thread); + thread.Start(); + return thread; + } + + /// <summary>Registers a thread created elsewhere (call before Start).</summary> + public static void Track(Thread thread) + { + lock (Sync) + { + Threads.RemoveAll(t => t.ThreadState.HasFlag(ThreadState.Stopped)); + Threads.Add(thread); + } + } + + /// <summary>Sleeps; false (immediately) once the engine is shutting down.</summary> + public static bool Sleep(int milliseconds) => !StopEvent.WaitOne(Math.Max(0, milliseconds)); + + public static bool Sleep(TimeSpan duration) => Sleep((int)Math.Min(int.MaxValue, duration.TotalMilliseconds)); + + /// <summary> + /// Wakes every tracked thread and waits up to <paramref name="budgetMs"/> in total for + /// them to finish. Logs the ones still running: each keeps its engine generation alive. + /// </summary> + public static void StopAndJoinAll(int budgetMs) + { + StopEvent.Set(); + List<Thread> threads; + lock (Sync) threads = new List<Thread>(Threads); + + long deadline = Environment.TickCount64 + budgetMs; + var stuck = new List<string>(); + foreach (Thread t in threads) + { + if (t == Thread.CurrentThread) continue; + int remaining = (int)Math.Max(0, deadline - Environment.TickCount64); + if (!t.Join(remaining)) + stuck.Add(t.Name ?? $"#{t.ManagedThreadId}"); + } + RynthLog.Info(stuck.Count == 0 + ? $"EngineThreads: all {threads.Count} engine thread(s) finished." + : $"EngineThreads: {stuck.Count} of {threads.Count} thread(s) still running after {budgetMs} ms: {string.Join(", ", stuck)}"); + } +} diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index ba3cce7..1939e93 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -40,12 +40,11 @@ public static class EntryPoint private static int _initCount; private static bool _imGuiResolverConfigured; private static IntPtr _imGuiNativeHandle; - - /// <summary>Module handle of the loaded cimgui DLL (zero until the ImGui resolver is configured).</summary> + /// <summary>Module handle of the loaded cimgui.dll (zero until preloaded).</summary> internal static IntPtr ImGuiNativeHandle => _imGuiNativeHandle; - private static readonly object LogLock = new(); private static readonly Queue<string> RecentLogLines = new(); + private static long _recentLogSeq; internal enum EngineLogLevel { @@ -82,6 +81,24 @@ public static class EntryPoint /// from inside an EndScene detour — the caller should run on a background /// thread so the render thread's call into our hook can return cleanly. /// </summary> + /// <summary> + /// The loader refused a hot-reload because this client is short of address + /// space (each reload keeps the old engine and plugins mapped). Says so in + /// chat. Loader thread. + /// </summary> + [UnmanagedCallersOnly(EntryPoint = "RynthCoreReloadRefused")] + public static uint ReloadRefused(int freeMb) + { + try + { + RynthLog.Warn($"Hot-reload refused by the loader: {freeMb} MB of address space free."); + Compatibility.AcMainThreadQueue.EnqueueWriteToChat( + $"[RynthCore] A new RynthCore build is ready but wasn't loaded: this client has only {freeMb} MB of memory address space left, and reloading could crash it. Restart the client to use the new build.", 2); + } + catch { } + return 0; + } + [UnmanagedCallersOnly(EntryPoint = "RynthCoreShutdown")] public static uint Shutdown(IntPtr lpParam) { @@ -137,11 +154,14 @@ public static class EntryPoint InstallManagedExceptionHandlers(); - RynthLog.Info("================================================================"); - RynthLog.Info($"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}"); - RynthLog.Info($" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}"); - RynthLog.Info($" logging {logSummary}"); - RynthLog.Info("================================================================"); + // The banner bypasses the category levels: it must be in every log, whatever engine.json says. + LogTagged("engine", "================================================================", "INF"); + LogTagged("engine", $"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}", "INF"); + LogTagged("engine", $" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}", "INF"); + LogTagged("engine", $" logging {logSummary}", "INF"); + LogTagged("engine", "================================================================", "INF"); + string hiddenCategories = LogSettings.HiddenCategoriesWarning(); + if (hiddenCategories.Length > 0) RynthLog.Warn(hiddenCategories); // Live logging config: launcher edits to engine.json apply without a client restart. // Stopped in EngineLifecycle.Shutdown before the module can be unloaded. @@ -171,18 +191,16 @@ public static class EntryPoint // and our VEH (NativeAOT __fastfail, AC self-exit on disconnect, // etc.). Install early so we catch even very-early-startup kills. RunInitStep("early process-exit hooks", ProcessExitHooks.Initialize); + // Logs the text of any message box (AC shows some errors in one on + // its main thread, which then looks like a wedge to the watchdog). + RunInitStep("message-box hooks", MessageBoxHooks.Initialize); // Heartbeat: one log line per second so we have a hard upper-bound // timestamp for when AC went silent if it dies via a path our // termination hooks don't catch (kernel-level kill, int 0x29 not // routed through RtlFailFast, hardware fault, etc.). RunInitStep("heartbeat logger", HeartbeatLogger.Start); - var thread = new Thread(InitWorker) - { - Name = "RynthCore.Init", - IsBackground = true - }; - thread.Start(); + _initThread = EngineThreads.Start("RynthCore.Init", InitWorker); return 0; } @@ -226,6 +244,13 @@ public static class EntryPoint // GetModuleHandleA("RynthCore.Engine.dll") fails when the loader has // staged us under a unique filename (RynthCore.Engine.gen2.dll etc.) // for hot-reload, so this is the path that always works. +#if ENGINE_CORECLR + // A managed engine is an assembly, not a module: the loader staged it and the + // Shim loaded it from that path. + string location = typeof(EntryPoint).Assembly.Location; + if (!string.IsNullOrEmpty(location)) + return location; +#endif IntPtr hEngine = IntPtr.Zero; try { @@ -548,6 +573,14 @@ public static class EntryPoint RynthLog.Info("WARNING: cimgui runtime not found - ImGui will not be available."); RynthLog.Info(" Ship RynthCore.cimgui.dll (or cimgui.dll) alongside RynthCore.Engine.dll"); } + else if (Plugins.EngineSettings.EnableImGuiBackend) + { + // Read the ImGui font files and the panel state here, off AC's + // render thread (the ImGui faces read both from memory). + ImGuiBackend.ImGuiFonts.Preload(); + UI.PanelStateStore.TryGetPanel("", out _); + UI.PanelFaceStore.TryGet("", out _); + } if (!Plugins.EngineSettings.EnableEngine) { @@ -559,13 +592,44 @@ public static class EntryPoint // user has dropped a candidate-string list at // %APPDATA%\RynthCore\string_anchors.txt — otherwise no-ops. // No hooks installed, no AC code modified; pure pattern read. - StringAnchorDiagnostic.RunIfConfigured(); + // A diagnostic (runs when its config file exists); ~0.8 s of scanning, so the + // first load does it and a hot reload skips it. + if (_initCount < 2) + StringAnchorDiagnostic.RunIfConfigured(); int hookBudget = Plugins.EngineSettings.EngineHookCount; int hookIndex = 0; + // Decal bridge mode (docs/DECAL_BRIDGE_PLAN.md) is decided before any hook goes + // in. Without Decal in the process this is two GetModuleHandle calls, Active + // stays false and no step is skipped. + DecalBridgeHost.Initialize(); + // Decal stand-down (2026-10-03, docs/DECAL_BRIDGE_PLAN.md "Where Decal reads its + // filters"): Decal is in this client but the bridge isn't (not registered as this + // client sees the registry, protocol mismatch, mapping failure). The old coexistence + // path that used to run here never worked - no overlay, then a crash. Stand down + // instead: install only what DecalBridgeHost's "the Decal bridge isn't loaded" chat + // line needs - the login event, AddTextToScroll's address (a probe, no hook) and the + // Client::UseTime drain that runs queued chat writes on AC's main thread - and load + // no plugins. None of those is a function Decal patches. The client then runs as a + // plain Decal client. DecalBridge=Off (tests) and engine.json "DecalStandDown": false + // keep the old path. Without Decal this is false (InactiveReason stays null). + bool decalStandDown = DecalBridgeHost.ShouldStandDown; + if (decalStandDown) + RynthLog.Warn($"InitWorker: Decal without the bridge ({DecalBridgeHost.InactiveReason}) - standing down: " + + "only the login, chat-address and UseTime-drain steps install; no plugins, no overlay."); + List<(string Name, Action Action)>? bridgeSkipped = null; RynthLog.Info($"InitWorker: starting hook init steps (budget={hookBudget})"); void Step(string name, Action action) { + if (InitAborted()) return; + if (decalStandDown && name is not ("client helper hooks" or "login lifecycle hooks" or "game-tick cast drain hook")) + return; // stand-down (above): logged once there + if (DecalBridgeHost.SkipsInitStep(name)) + { + RynthLog.Info($"InitWorker: '{name}' skipped - bridge mode leaves this to Decal."); + (bridgeSkipped ??= new()).Add((name, action)); + return; + } int idx = hookIndex++; if (idx >= hookBudget) { @@ -603,6 +667,8 @@ public static class EntryPoint Step("account hooks", AccountHooks.Initialize); Step("client combat hooks", () => ClientCombatHooks.Probe()); Step("selected-target hooks", SelectedTargetHooks.Initialize); + // Which item AC is dragging (AC keeps the old selection during a drag). + Step("drag-start hook", DragDropHooks.Initialize); Step("smartbox hooks", SmartBoxHooks.Initialize); Step("player vitals hooks", PlayerVitalsHooks.Initialize); Step("enchantment hooks", () => EnchantmentHooks.Initialize()); @@ -642,11 +708,42 @@ public static class EntryPoint Step("vector-update hooks", VectorUpdateServerDispatchHooks.Initialize); Step("update-object-inventory hooks", UpdateObjectInventoryHooks.Initialize); Step("view-object-contents hooks", ViewObjectContentsHooks.Initialize); + // RenderUI::RenderObjects: the world overlays (nameplates, Nav3D markers) draw at + // the start of AC's 2D UI pass, after all 3D incl. foliage (2026-10-04). + Step("UI-pass overlay hook", AcUiPassHook.Initialize); Step("vendor hooks", VendorHooks.Initialize); Step("chat callback hooks", ChatCallbackHooks.Initialize); Step("raw packet hooks", RawPacketHooks.Initialize); Step("property-update hooks", PropertyUpdateHooks.Initialize); Step("auto-id service", AutoIdService.Start); + // Bridge mode: wait (bounded) for the bridge's hello. In Auto mode a bridge that + // never shows up means the old coexistence mode: install what was skipped. + if (bridgeSkipped != null && !DecalBridgeHost.WaitForBridge(InitAborted)) + { + // No hello: Decal didn't load the bridge. Stand down (see above) rather than + // install the chat/salvage hooks over Decal's own patches. The other native + // hooks went in during the 20 s wait and stay; nothing loads plugins to use them. + if (DecalBridgeHost.ShouldStandDown) + { + decalStandDown = true; + RynthLog.Warn($"InitWorker: Decal without the bridge ({DecalBridgeHost.InactiveReason}) - standing down: " + + "the chat and salvage hooks stay out; no plugins, no overlay."); + } + else + { + foreach ((string name, Action action) in bridgeSkipped) + RunInitStep(name + " (bridge fallback)", action); + } + } + if (InitAborted()) return; + if (decalStandDown) + { + // No LoadPlugins, no RunPostLoginBootstrap (EndScene hook, plugin pump), and no + // hot-reload bootstrap below: a reload of this client stands down again (the + // registry hasn't changed). DecalBridgeHost posts the chat line at login. + RynthLog.Info("InitWorker: stand-down complete - this client runs as a Decal client; RynthCore stays idle."); + return; + } if (Plugins.EngineSettings.EnablePlugins) { RynthLog.Info("InitWorker DIAG — calling PluginManager.LoadPlugins."); @@ -670,6 +767,7 @@ public static class EntryPoint // viewport platform/renderer. Avalonia floating panels still // work because they ride a separate LayeredWindow (GDI), not // the D3D9 swap chain. + if (InitAborted()) return; LoginLifecycleHooks.LoginComplete += RunPostLoginBootstrap; // ── Fast-login race guard (first launch, initCount==1) ─────────── @@ -692,6 +790,7 @@ public static class EntryPoint } RynthLog.Info($"InitWorker: post-init checkpoint, _initCount={_initCount}"); + if (InitAborted()) return; // On a hot reload (initCount >= 2) the game's already past the // login gate, so SendLoginCompleteNotification won't fire again. @@ -699,7 +798,7 @@ public static class EntryPoint // protects against can't happen post-login. if (_initCount >= 2) { - if (DecalDetection.IsDecalLoaded) + if (UseDecalCoexistencePath()) { RynthLog.Info( $"D3D9: Hot reload (initCount={_initCount}) — Decal coexistence " + @@ -742,7 +841,13 @@ public static class EntryPoint RynthLog.Info("PlayerVitals: hot reload — could not derive qualities ptr (will fall back to event-driven path)."); } - if (Plugins.EngineSettings.EnableAvaloniaOverlay) + // Avalonia (the older panel UI, now only a fallback) and the ImGui faces are + // set up separately: the ImGui faces, the chat settings and the dashboard state + // don't depend on Avalonia, and the CoreCLR engine runs without it (Avalonia + // can't be unloaded; docs/UNLOADABLE_ENGINE_PLAN.md). + bool avalonia = Plugins.EngineSettings.EnableAvaloniaOverlay; + bool dcompTest = avalonia && UI.Dcomp.DcompOverlayBootstrap.IsEnabled; + if (avalonia) { PreloadNativeDll(engineDir, "libSkiaSharp.dll"); PreloadNativeDll(engineDir, "libHarfBuzzSharp.dll"); @@ -752,88 +857,133 @@ public static class EntryPoint // skip the production AvaloniaOverlay and start the DComp test // path instead. Both paths cannot coexist in one process (Avalonia // is single-app-per-process). Default behavior is unchanged. - if (UI.Dcomp.DcompOverlayBootstrap.IsEnabled) + if (dcompTest) { RynthLog.Info("InitWorker: RYNTHCORE_DCOMP_OVERLAY=1 — starting DComp test overlay instead of production AvaloniaOverlay."); UI.Dcomp.DcompOverlayBootstrap.Start(); } - else - { - // Engine-builtin panels (no plugin DLL pairing) — always register. - OverlayHost.RegisterPanel("Status", StatusPanel.Create); - OverlayHost.RegisterPanel("Log", LogPanel.Create); - OverlayHost.RegisterPanel("Monsters", MonstersPanel.Create); - OverlayHost.RegisterPanel("Items", ItemsPanel.Create); - OverlayHost.RegisterPanel("Settings", SettingsPanel.Create); - OverlayHost.RegisterPanel("Nav", NavPanel.Create); - OverlayHost.RegisterPanel("Meta", MetaPanel.Create); - OverlayHost.RegisterPanel("Radar", RadarPanel.Create); - - // Plugin-paired panels: register only if the matching plugin DLL is - // listed in engine.json PluginPaths (controlled by the launcher Plugins - // tab). The panel UI is engine-side per the Avalonia-overlay design - // (plugin DLLs feed data via C exports) — unchecking a plugin in the - // launcher must take its entire surface area out of process so the - // diagnostic "is plugin X the off-thread caller?" question is testable. - if (HasPluginDll("RynthCore.Plugin.RynthAi.dll")) - { - OverlayHost.RegisterPanel("RynthAi", RynthAiPanel.Create); - OverlayHost.RegisterPanel("Damage", MonsterDamagePanel.Create); - } - else - RynthLog.Info("InitWorker: RynthAi panel skipped — DLL not in engine.json PluginPaths."); - - if (HasPluginDll("RynthCore.Plugin.RynthChat.dll")) - { - OverlayHost.RegisterPanel("Chat", RynthChatPanel.Create); - // Regex filter-rule editor — its own panel (opened from - // the chat panel's Filters button or the bar). - OverlayHost.RegisterPanel("ChatFilters", RynthChatFiltersPanel.Create); - // Apply persisted RynthChat settings (incl. "Hide retail chat" -> - // ChatHooks.SuppressOriginalChat) at init so suppression takes effect - // on login without the user having to open the Chat panel first. - // - // ⚠ INVARIANT: this is the ONLY place that invokes a panel's static - // method BEFORE AvaloniaOverlay.Start() (below) sets up the Win32 - // platform. Doing so runs that panel's static ctor on THIS (InitWorker) - // thread. A panel whose static ctor eagerly constructs Avalonia objects - // (SolidColorBrush etc.) would then create Dispatcher.UIThread with the - // wrong (non-controlled) impl → the overlay thread's Dispatcher.MainLoop - // throws PlatformNotSupportedException → the ENTIRE overlay dies and no - // RynthCore/plugin UI renders (game + plugin pump still run). This bit us - // 2026-06-30; fixed by making RynthChatPanel's brush statics LAZY. - // Before adding any EnsureSettingsLoaded-style early call for another - // panel, confirm that panel's static ctor constructs NO Avalonia objects - // (make its brushes lazy), OR move the settings-load off the panel class. - // OverlayHost.RegisterPanel above is safe: a method-group does NOT trigger - // the static ctor. See rynthcore memory "overlay no-UI = dispatcher poison". - RynthChatPanel.EnsureSettingsLoaded(); - } - else - RynthLog.Info("InitWorker: RynthChat panel skipped — DLL not in engine.json PluginPaths."); - - if (HasPluginDll("RynthCore.Plugin.RynthVision.dll")) - OverlayHost.RegisterPanel("Vision", RynthVisionPanel.Create); - else - RynthLog.Info("InitWorker: RynthVision panel skipped — DLL not in engine.json PluginPaths."); - - if (HasPluginDll("RynthCore.Plugin.RynthTracker.dll")) - OverlayHost.RegisterPanel("Tracker", RynthTrackerPanel.Create); - else - RynthLog.Info("InitWorker: RynthTracker panel skipped — DLL not in engine.json PluginPaths."); - - if (HasPluginDll("RynthCore.Plugin.RynthNav.dll")) - OverlayHost.RegisterPanel("RynthNav", RynthNavPanel.Create); - else - RynthLog.Info("InitWorker: RynthNav panel skipped — DLL not in engine.json PluginPaths."); - - AvaloniaOverlay.Start(); - } } else { - RynthLog.Info("InitWorker: AvaloniaOverlay disabled via engine.json (EnableAvaloniaOverlay=false). No panels, no Skia, no offscreen window."); + RynthLog.Info("InitWorker: AvaloniaOverlay disabled (engine.json EnableAvaloniaOverlay=false, or the CoreCLR engine). ImGui faces only; no Skia, no offscreen window."); } + + if (!dcompTest) + { + // The panel list (titles + Avalonia view factories). Registering creates no + // Avalonia object and starts nothing; the ImGui bar builds its buttons from it + // and PanelRouter resolves titles with it, Avalonia on or off. + // Engine-builtin panels (no plugin DLL pairing) — always register. + OverlayHost.RegisterPanel("Status", StatusPanel.Create); + OverlayHost.RegisterPanel("Log", LogPanel.Create); + OverlayHost.RegisterPanel("Monsters", MonstersPanel.Create); + OverlayHost.RegisterPanel("Items", ItemsPanel.Create); + OverlayHost.RegisterPanel("Settings", SettingsPanel.Create); + OverlayHost.RegisterPanel("Nav", NavPanel.Create); + OverlayHost.RegisterPanel("Meta", MetaPanel.Create); + OverlayHost.RegisterPanel("Radar", RadarPanel.Create); + + // Plugin-paired panels: register only if the matching plugin DLL is + // listed in engine.json PluginPaths (controlled by the launcher Plugins + // tab). The panel UI is engine-side per the Avalonia-overlay design + // (plugin DLLs feed data via C exports) — unchecking a plugin in the + // launcher must take its entire surface area out of process so the + // diagnostic "is plugin X the off-thread caller?" question is testable. + if (HasPluginDll("RynthCore.Plugin.RynthAi.dll")) + { + OverlayHost.RegisterPanel("RynthAi", RynthAiPanel.Create); + OverlayHost.RegisterPanel("Damage", MonsterDamagePanel.Create); + } + // Lua: the RynthLua plugin (or an older RynthAi that still carries it). + if (HasPluginDll("RynthCore.Plugin.RynthLua.dll") || HasPluginDll("RynthCore.Plugin.RynthAi.dll")) + OverlayHost.RegisterPanel("Lua", LuaPanel.Create); + else + RynthLog.Info("InitWorker: RynthAi panel skipped — DLL not in engine.json PluginPaths."); + + if (HasPluginDll("RynthCore.Plugin.RynthChat.dll")) + { + OverlayHost.RegisterPanel("Chat", RynthChatPanel.Create); + // Regex filter-rule editor — its own panel (opened from + // the chat panel's Filters button or the bar). + OverlayHost.RegisterPanel("ChatFilters", RynthChatFiltersPanel.Create); + } + else + RynthLog.Info("InitWorker: RynthChat panel skipped — DLL not in engine.json PluginPaths."); + + if (HasPluginDll("RynthCore.Plugin.RynthVision.dll")) + OverlayHost.RegisterPanel("Vision", RynthVisionPanel.Create); + else + RynthLog.Info("InitWorker: RynthVision panel skipped — DLL not in engine.json PluginPaths."); + + if (HasPluginDll("RynthCore.Plugin.RynthTracker.dll")) + OverlayHost.RegisterPanel("Tracker", RynthTrackerPanel.Create); + else + RynthLog.Info("InitWorker: RynthTracker panel skipped — DLL not in engine.json PluginPaths."); + + if (HasPluginDll("RynthCore.Plugin.RynthNav.dll")) + OverlayHost.RegisterPanel("RynthNav", RynthNavPanel.Create); + else + RynthLog.Info("InitWorker: RynthNav panel skipped — DLL not in engine.json PluginPaths."); + + // Apply persisted RynthChat settings (incl. "Hide retail chat" -> + // ChatHooks.SuppressOriginalChat) at init so suppression takes effect + // on login without the user having to open the Chat panel first; the + // chat keys feed ChatModel's input line whichever chat face is up. + // + // ⚠ INVARIANT: this runs BEFORE AvaloniaOverlay.Start() (below) sets up + // the Win32 platform, on THIS (InitWorker) thread. Nothing here may run a + // panel's static ctor that constructs Avalonia objects (SolidColorBrush + // etc.): that creates Dispatcher.UIThread with the wrong impl → the + // overlay thread's Dispatcher.MainLoop throws PlatformNotSupportedException + // → the ENTIRE overlay dies (bit us 2026-06-30). Hence ChatModel + // (UI/Data/ChatData.cs), which touches no Avalonia type, not the panel + // class. OverlayHost.RegisterPanel above is safe: a method group does NOT + // trigger the static ctor. See rynthcore memory "overlay no-UI = dispatcher poison". + if (HasPluginDll("RynthCore.Plugin.RynthChat.dll")) + { + UI.Data.ChatModel.EnsureSettingsLoaded(); + UI.Data.ChatModel.InstallInput(); + } + // ImGui faces for panels docked in the client (UI.PanelRouter + // picks the face). Registered even while the ImGui layer is off, + // so /rc imgui on can use them without a reload. + bool trackerPresent = HasPluginDll("RynthCore.Plugin.RynthTracker.dll"); + ImGuiBackend.Panels.P1Faces.Register(trackerPresent); + if (HasPluginDll("RynthCore.Plugin.RynthVision.dll")) + ImGuiBackend.Panels.VisionFace.Register(); + if (HasPluginDll("RynthCore.Plugin.RynthNav.dll")) + ImGuiBackend.Panels.RynthNavFace.Register(); + if (HasPluginDll("RynthCore.Plugin.RynthChat.dll")) + { + ImGuiBackend.Panels.ChatFace.Register(); + ImGuiBackend.Panels.ChatFiltersFace.Register(); + } + ImGuiBackend.Panels.RadarFace.Register(); + ImGuiBackend.Panels.SettingsFace.Register(); + ImGuiBackend.Panels.MetaFace.Register(); + RadarSettingsStore.Load(); // file read here, not on AC's thread + if (HasPluginDll("RynthCore.Plugin.RynthLua.dll") || HasPluginDll("RynthCore.Plugin.RynthAi.dll")) + ImGuiBackend.Panels.LuaFace.Register(); + if (HasPluginDll("RynthCore.Plugin.RynthAi.dll")) + { + ImGuiBackend.Panels.RynthAiFace.Register(); + ImGuiBackend.Panels.DamageFace.Register(); + ImGuiBackend.Panels.DamageDetailFace.Register(); + ImGuiBackend.Panels.MonstersFace.Register(); + ImGuiBackend.Panels.NavFace.Register(); + ImGuiBackend.Panels.ItemsFace.Register(); + // Load the dashboard state file here, not on AC's thread. NOT through + // RynthAiPanel: see the dispatcher invariant above ChatModel.EnsureSettingsLoaded. + RynthAiDashboardState.EnsureLoaded(); + } + if (trackerPresent) + TrackerSettings.EnsureLoaded(); + // Hide the docked Avalonia bar before it is built if the ImGui bar stands in. + ImGuiBackend.ImGuiBar.ApplyFace(); + } + + if (avalonia && !dcompTest) + AvaloniaOverlay.Start(); RynthLog.Info("RynthCore bootstrap initialized."); } catch (Exception ex) @@ -874,8 +1024,20 @@ public static class EntryPoint /// that need them already null-check, and headless plugins (Avalonia- /// rendered like RynthAi) work fine without them. /// </summary> + private static int _decalCoexistenceStarted; + private static void InitPluginsForDecalCoexistence() { + // Once per generation. A hot reload reaches this twice - from the initCount>=2 + // branch in InitWorker and again from RunPostLoginBootstrap via + // MarkAlreadyComplete - and used to start TWO tick pumps (two concurrent + // PluginManager.TickAll drivers; _tickPumpThread only remembered the second). + // Measured on a Decal test client 2026-09-29 (spike/decal-bridge). + if (Interlocked.CompareExchange(ref _decalCoexistenceStarted, 1, 0) != 0) + { + RynthLog.Info("DecalCoexistence: plugin init/pump already started in this generation - not starting a second pump."); + return; + } IntPtr hwnd = global::RynthCore.Engine.ImGuiBackend.EngineFrameController.FindGameWindow(); if (hwnd != IntPtr.Zero) { @@ -894,7 +1056,8 @@ public static class EntryPoint { try { - Thread.Sleep(DecalCoexistencePluginInitDelay); + if (!EngineThreads.Sleep(DecalCoexistencePluginInitDelay)) + return; // Reseed the qualities pointer from the live player object // before plugins look at vitals. Auto-inject lands AFTER AC @@ -919,6 +1082,17 @@ public static class EntryPoint $"dispatchCount={Compatibility.CreateObjectHooks.DispatchCount}, " + $"liveObjects={Plugins.PluginManager.LiveObjectCount}"); + // Bridge mode: queue what the bridge buffered before InitPlugins, so its + // replay includes it. + if (DecalBridgeHost.Active) + RynthLog.Info($"DecalBridge: drained {DecalBridgeHost.Drain()} buffered record(s) before plugin init."); + + // No EndScene hook in this mode, so the per-frame main-thread prefetches the + // pump reads (skills, spells, attackable, names/types, positions, stats, the + // cold-login object seed) run from the Client::UseTime detour instead. + Compatibility.GameTickHooks.HeadlessPrefetch = true; + RynthLog.Info("DecalCoexistence: main-thread prefetches now run from Client::UseTime (no EndScene hook)."); + Plugins.PluginManager.InitPlugins(IntPtr.Zero, IntPtr.Zero, hwnd); // Drive the plugin tick loop. Without this, the macro @@ -929,7 +1103,8 @@ public static class EntryPoint int consecutiveFailures = 0; while (Volatile.Read(ref _tickPumpStopRequested) == 0) { - Thread.Sleep(DecalCoexistenceTickInterval); + if (!EngineThreads.Sleep(DecalCoexistenceTickInterval)) + break; if (Volatile.Read(ref _tickPumpStopRequested) != 0) break; try @@ -941,8 +1116,15 @@ public static class EntryPoint // NO TARGET, BuffManager never sees enchantments land, combat // events evaporate. Historically driven from EngineFrameController's // per-frame loop; this is the headless equivalent. + if (DecalBridgeHost.Active) + DecalBridgeHost.Drain(); // bridge events into the same queues Plugins.PluginManager.ProcessPendingActions(IntPtr.Zero, IntPtr.Zero, hwnd); + Plugins.PluginManager.FlushPendingDeletes(); // as PumpPluginFrame: closes the create->delete race Plugins.PluginManager.TickAll(); + // Panel data (UiDataHub): published on the plugin-tick thread, as + // PumpPluginFrame does in the normal pump. Without it the panels' + // snapshots never refreshed with Decal loaded. + UI.Data.UiDataHub.Step(); consecutiveFailures = 0; } catch (Exception tickEx) @@ -977,6 +1159,7 @@ public static class EntryPoint IsBackground = true, }; _tickPumpThread = worker; + EngineThreads.Track(worker); worker.Start(); } @@ -1020,8 +1203,10 @@ public static class EntryPoint { if (Interlocked.CompareExchange(ref _postLoginBootstrapStarted, 1, 0) != 0) return; + if (EngineLifecycle.IsShuttingDown) + return; // no EndScene hook / plugin pump for a generation being torn down - if (DecalDetection.IsDecalLoaded) + if (UseDecalCoexistencePath()) { RynthLog.Info( $"D3D9: Decal coexistence — '{DecalDetection.DetectedModule}' loaded, " + @@ -1060,6 +1245,37 @@ public static class EntryPoint RynthLog.Info("NormalPluginPump: disabled via engine.json (EnablePlugins=false)."); } + private static int _decalInGameLogged; + + /// <summary> + /// True: Decal is in this client and the old coexistence path runs (no EndScene hook, no + /// ImGui, the 30 Hz Decal pump). False without Decal, and with Decal when engine.json + /// DecalInGameImGui (or RYNTHCORE_DECAL_IMGUI=1) asks for the normal EndScene hook and + /// ImGui renderer there (docs/DECAL_BRIDGE_PLAN.md, step 3): the bootstrapper then finds + /// AC's device without creating one (Decal detours Direct3DCreate9 and CreateDevice). + /// Without Decal the setting is never read. + /// </summary> + private static bool UseDecalCoexistencePath() + { + if (!DecalDetection.IsDecalLoaded && !DecalBridgeHost.Active) + return false; + if (!Plugins.EngineSettings.DecalInGameImGui) + return true; + // AC's device must be known through the bridge first (bridge mode only); otherwise + // the old coexistence path, so plugins still get their pump. + if (!DecalBridgeHost.Active || !D3D9.DecalD3D9.TryResolve()) + { + if (Interlocked.Exchange(ref _decalInGameLogged, 1) == 0) + RynthLog.Info($"D3D9: DecalInGameImGui is on, but AC's device isn't known through the Decal bridge (bridge mode={DecalBridgeHost.Active}) - Decal coexistence path instead."); + return true; + } + D3D9Bootstrapper.DecalInProcess = true; + if (Interlocked.Exchange(ref _decalInGameLogged, 1) == 0) + RynthLog.Info($"D3D9: Decal in the process ('{DecalDetection.DetectedModule ?? "Decal"}', bridge mode={DecalBridgeHost.Active}) and DecalInGameImGui is on - " + + "installing the normal EndScene hook and ImGui renderer (device found without creating one)."); + return false; + } + private static void StartNormalPluginPump() { if (Interlocked.CompareExchange(ref _normalPumpStarted, 1, 0) != 0) @@ -1073,7 +1289,8 @@ public static class EntryPoint int consecutiveFailures = 0; while (Volatile.Read(ref _tickPumpStopRequested) == 0) { - Thread.Sleep(NormalPluginPumpInterval); + if (!EngineThreads.Sleep(NormalPluginPumpInterval)) + break; if (Volatile.Read(ref _tickPumpStopRequested) != 0) break; try @@ -1109,6 +1326,7 @@ public static class EntryPoint IsBackground = true, }; _tickPumpThread = worker; + EngineThreads.Track(worker); worker.Start(); } @@ -1126,6 +1344,7 @@ public static class EntryPoint /// </summary> internal static bool StopTickPumpAndJoin(int timeoutMs = 2000) { + Compatibility.GameTickHooks.HeadlessPrefetch = false; // no more prefetch work once teardown starts if (_tickPumpThread == null) return true; @@ -1155,8 +1374,34 @@ public static class EntryPoint Interlocked.Exchange(ref _tickPumpStopRequested, 1); } + private static Thread? _initThread; + private static int _initAbortLogged; + + /// <summary> + /// Waits for InitWorker to finish. A reload can arrive while it is still installing + /// hooks and loading plugins; teardown must not run under it (it would keep + /// installing hooks and starting the D3D9 bootstrap for a generation being torn + /// down). InitWorker stops at its next step once shutdown has begun. + /// </summary> + internal static bool WaitForInitWorker(int timeoutMs) + { + Thread? t = _initThread; + if (t == null || t == Thread.CurrentThread) return true; + return t.Join(timeoutMs); + } + + /// <summary>True (and logged once) when shutdown began while InitWorker was running.</summary> + private static bool InitAborted() + { + if (!EngineLifecycle.IsShuttingDown) return false; + if (Interlocked.Exchange(ref _initAbortLogged, 1) == 0) + RynthLog.Info("InitWorker: engine shutting down — stopping init here."); + return true; + } + private static void RunInitStep(string name, Action action) { + if (InitAborted()) return; try { action(); @@ -1217,6 +1462,20 @@ public static class EntryPoint } } + /// <summary> + /// Removes the handlers above. They are process-wide events, so under the CoreCLR + /// host they would keep this engine generation alive after a reload (and keep its + /// handlers running next to the new generation's). + /// </summary> + internal static void UninstallManagedExceptionHandlers() + { + if (Interlocked.CompareExchange(ref _managedHandlersInstalled, 0, 1) != 1) + return; + AppDomain.CurrentDomain.UnhandledException -= OnUnhandledException; + System.Threading.Tasks.TaskScheduler.UnobservedTaskException -= OnUnobservedTaskException; + AppDomain.CurrentDomain.FirstChanceException -= OnFirstChanceException; + } + [ThreadStatic] private static bool _inFirstChanceHandler; /// <summary> @@ -1334,6 +1593,7 @@ public static class EntryPoint lock (LogLock) { RecentLogLines.Enqueue(line); + System.Threading.Interlocked.Increment(ref _recentLogSeq); // 64-bit: atomic for the lock-free RecentLogSeq read while (RecentLogLines.Count > MaxRecentLogLines) RecentLogLines.Dequeue(); @@ -1414,4 +1674,21 @@ public static class EntryPoint lock (LogLock) return RecentLogLines.ToArray(); } + + /// <summary> + /// The recent-log ring plus the sequence number of its last line (lines are + /// numbered from 1 since load). Lets a viewer "clear" by remembering a + /// sequence number, which keeps working after the ring wraps. + /// </summary> + internal static string[] GetRecentLogLines(out long lastSeq) + { + lock (LogLock) + { + lastSeq = _recentLogSeq; + return RecentLogLines.ToArray(); + } + } + + /// <summary>Sequence number of the newest log line (0 before any). Lock-free read.</summary> + internal static long RecentLogSeq => System.Threading.Interlocked.Read(ref _recentLogSeq); } diff --git a/src/RynthCore.Engine/Hooking/LoaderServices.cs b/src/RynthCore.Engine/Hooking/LoaderServices.cs new file mode 100644 index 0000000..6df446b --- /dev/null +++ b/src/RynthCore.Engine/Hooking/LoaderServices.cs @@ -0,0 +1,58 @@ +// ============================================================================ +// RynthCore.Engine - Hooking/LoaderServices.cs +// +// The native loader (native/Loader/Services.c, loader 2.0+) owns the permanent native +// entry points the engine used to hand out itself: the game window's subclass proc and +// the plugin API table's function pointers. With them, nothing native ever points into +// an engine generation after its shutdown, so the CoreCLR host can unload it +// (docs/UNLOADABLE_ENGINE_PLAN.md). Under an older loader (or none) Available is false +// and callers keep their old behaviour. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.Hooking; + +internal static unsafe class LoaderServices +{ + private static readonly delegate* unmanaged[Stdcall]<IntPtr, IntPtr, IntPtr*, int> s_subclassInstall; + private static readonly delegate* unmanaged[Stdcall]<IntPtr, int> s_subclassRelease; + private static readonly delegate* unmanaged[Stdcall]<int, IntPtr, IntPtr> s_apiStub; + + static LoaderServices() + { + IntPtr loader = GetModuleHandleW("RynthCore.Loader.dll"); + if (loader == IntPtr.Zero || GetProcAddress(loader, "RcServices_Version") == IntPtr.Zero) + return; + s_subclassInstall = (delegate* unmanaged[Stdcall]<IntPtr, IntPtr, IntPtr*, int>)GetProcAddress(loader, "RcSubclass_Install"); + s_subclassRelease = (delegate* unmanaged[Stdcall]<IntPtr, int>)GetProcAddress(loader, "RcSubclass_Release"); + s_apiStub = (delegate* unmanaged[Stdcall]<int, IntPtr, IntPtr>)GetProcAddress(loader, "RcApiStub"); + } + + public static bool Available => s_subclassInstall != null && s_subclassRelease != null && s_apiStub != null; + + /// <summary> + /// Routes <paramref name="hwnd"/>'s messages to <paramref name="handler"/> through the + /// loader's permanent subclass. <paramref name="previous"/> is the proc to forward to. + /// </summary> + public static bool SubclassInstall(IntPtr hwnd, IntPtr handler, out IntPtr previous) + { + IntPtr prev = IntPtr.Zero; + bool ok = s_subclassInstall(hwnd, handler, &prev) != 0; + previous = prev; + return ok; + } + + /// <summary>The loader's subclass passes everything straight to the previous proc again.</summary> + public static void SubclassRelease(IntPtr hwnd) => s_subclassRelease(hwnd); + + /// <summary>A permanent stub for plugin API slot <paramref name="index"/> that calls <paramref name="fn"/>.</summary> + public static IntPtr ApiStub(int index, IntPtr fn) => s_apiStub(index, fn); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr GetModuleHandleW(string lpModuleName); + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] + private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); +} diff --git a/src/RynthCore.Engine/Hooking/MinHook.cs b/src/RynthCore.Engine/Hooking/MinHook.cs index 03db9ea..bf0f758 100644 --- a/src/RynthCore.Engine/Hooking/MinHook.cs +++ b/src/RynthCore.Engine/Hooking/MinHook.cs @@ -13,9 +13,10 @@ using System.Threading; namespace RynthCore.Engine.Hooking; -internal static class MinHook +internal static unsafe class MinHook { private const string DLL = "minhook.x86.dll"; + private const string LoaderDll = "RynthCore.Loader.dll"; // ─── Status codes (must match MinHook's MH_STATUS enum) ──────────── public const int MH_OK = 0; @@ -23,37 +24,90 @@ internal static class MinHook public const int MH_ERROR_NOT_INITIALIZED = 2; public const int MH_ERROR_ALREADY_CREATED = 3; public const int MH_ERROR_NOT_CREATED = 4; + public const int MH_ERROR_ENABLED = 5; + public const int MH_ERROR_DISABLED = 6; // ─── Core API ───────────────────────────────────────────────────── + // + // The native loader (native/Loader, 2.0+) exports MinHook's API itself: every + // target gets a permanent stub and a reload only re-points it, so no hook ever + // points into an unloaded engine (docs/UNLOADABLE_ENGINE_PLAN.md). The engine uses + // that facade when the loader has it (RcHooks_Version), else minhook.x86.dll as + // before (the NativeAOT loader, or the engine loaded directly). - [DllImport(DLL, CallingConvention = CallingConvention.StdCall)] - public static extern int MH_Initialize(); + private static readonly Api s_api = ResolveApi(); - [DllImport(DLL, CallingConvention = CallingConvention.StdCall)] - public static extern int MH_Uninitialize(); + /// <summary>True when hooks go through the native loader's facade.</summary> + public static bool UsesLoaderFacade => s_api.IsFacade; - [DllImport(DLL, CallingConvention = CallingConvention.StdCall)] - public static extern int MH_CreateHook( - IntPtr pTarget, - IntPtr pDetour, - out IntPtr ppOriginal); + public static int MH_Initialize() => s_api.Initialize(); - [DllImport(DLL, CallingConvention = CallingConvention.StdCall)] - public static extern int MH_RemoveHook(IntPtr pTarget); + public static int MH_Uninitialize() => s_api.Uninitialize(); - [DllImport(DLL, CallingConvention = CallingConvention.StdCall)] - public static extern int MH_EnableHook(IntPtr pTarget); + public static int MH_CreateHook(IntPtr pTarget, IntPtr pDetour, out IntPtr ppOriginal) + { + IntPtr original = IntPtr.Zero; + int status = s_api.Create(pTarget, pDetour, &original); + ppOriginal = original; + return status; + } - [DllImport(DLL, CallingConvention = CallingConvention.StdCall)] - public static extern int MH_DisableHook(IntPtr pTarget); + public static int MH_RemoveHook(IntPtr pTarget) => s_api.Remove(pTarget); + + public static int MH_EnableHook(IntPtr pTarget) => s_api.Enable(pTarget); + + public static int MH_DisableHook(IntPtr pTarget) => s_api.Disable(pTarget); /// <summary>Enable/disable all hooks at once.</summary> public static readonly IntPtr MH_ALL_HOOKS = IntPtr.Zero; - // ─── Status to string ───────────────────────────────────────────── + private static IntPtr MH_StatusToString(int status) => s_api.StatusToString(status); - [DllImport(DLL, CallingConvention = CallingConvention.StdCall)] - private static extern IntPtr MH_StatusToString(int status); + private sealed class Api + { + public bool IsFacade; + public delegate* unmanaged[Stdcall]<int> Initialize; + public delegate* unmanaged[Stdcall]<int> Uninitialize; + public delegate* unmanaged[Stdcall]<IntPtr, IntPtr, IntPtr*, int> Create; + public delegate* unmanaged[Stdcall]<IntPtr, int> Remove; + public delegate* unmanaged[Stdcall]<IntPtr, int> Enable; + public delegate* unmanaged[Stdcall]<IntPtr, int> Disable; + public delegate* unmanaged[Stdcall]<int, IntPtr> StatusToString; + } + + private static Api ResolveApi() + { + IntPtr module = GetModuleHandleW(LoaderDll); + bool facade = module != IntPtr.Zero && GetProcAddress(module, "RcHooks_Version") != IntPtr.Zero; + if (!facade) + module = NativeLibrary.Load(DLL, typeof(MinHook).Assembly, null); + + IntPtr Get(string name) + { + IntPtr fn = GetProcAddress(module, name); + if (fn == IntPtr.Zero) + throw new EntryPointNotFoundException($"{(facade ? LoaderDll : DLL)} has no export {name}"); + return fn; + } + + return new Api + { + IsFacade = facade, + Initialize = (delegate* unmanaged[Stdcall]<int>)Get("MH_Initialize"), + Uninitialize = (delegate* unmanaged[Stdcall]<int>)Get("MH_Uninitialize"), + Create = (delegate* unmanaged[Stdcall]<IntPtr, IntPtr, IntPtr*, int>)Get("MH_CreateHook"), + Remove = (delegate* unmanaged[Stdcall]<IntPtr, int>)Get("MH_RemoveHook"), + Enable = (delegate* unmanaged[Stdcall]<IntPtr, int>)Get("MH_EnableHook"), + Disable = (delegate* unmanaged[Stdcall]<IntPtr, int>)Get("MH_DisableHook"), + StatusToString = (delegate* unmanaged[Stdcall]<int, IntPtr>)Get("MH_StatusToString"), + }; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr GetModuleHandleW(string lpModuleName); + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] + private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); public static string StatusString(int status) { diff --git a/src/RynthCore.Engine/ImGui/CodeEditor.cs b/src/RynthCore.Engine/ImGui/CodeEditor.cs new file mode 100644 index 0000000..8dabf7b --- /dev/null +++ b/src/RynthCore.Engine/ImGui/CodeEditor.cs @@ -0,0 +1,296 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/CodeEditor.cs +// A syntax-coloured source editor for ImGui faces: ImGuiColorTextEdit +// compiled into our cimgui.dll (native/cimgui/rynth_textedit_ext.cpp), +// called through function pointers resolved from that module. +// +// AC's render thread only, inside the ImGui frame. The native editor is +// created on the first Render (it reads the ImGui style) and destroyed by +// Dispose. Text crosses the boundary only on SetText/GetText, never per +// frame: IsDirty compares the editor's change counter, so a 50 KB meta costs +// nothing while it is being typed in. +// ============================================================================ + +using System; +using System.Numerics; +using System.Runtime.InteropServices; +using System.Text; + +namespace RynthCore.Engine.ImGuiBackend; + +internal enum CodeLanguage { None = 0, Meta = 1, Lua = 2 } + +internal sealed unsafe class CodeEditor : IDisposable +{ + // ── Exports ──────────────────────────────────────────────────────────── + private static bool _resolved, _available; + private static delegate* unmanaged[Cdecl]<IntPtr> _create; + private static delegate* unmanaged[Cdecl]<IntPtr, void> _destroy; + private static delegate* unmanaged[Cdecl]<byte*, byte*, byte*, void> _setMetaVocabulary; + private static delegate* unmanaged[Cdecl]<IntPtr, int, void> _setLanguage; + private static delegate* unmanaged[Cdecl]<IntPtr, uint*, int, void> _setPalette; + private static delegate* unmanaged[Cdecl]<IntPtr, int, int, int, int, void> _setOptions; + private static delegate* unmanaged[Cdecl]<IntPtr, byte*, void> _setText; + private static delegate* unmanaged[Cdecl]<IntPtr, int*, byte*> _getText; + private static delegate* unmanaged[Cdecl]<IntPtr, uint> _getChangeCount; + private static delegate* unmanaged[Cdecl]<IntPtr, byte*, float, float, int, int> _render; + private static delegate* unmanaged[Cdecl]<IntPtr, int*, int*, void> _getCursor; + private static delegate* unmanaged[Cdecl]<IntPtr, int, int, void> _setCursor; + private static delegate* unmanaged[Cdecl]<IntPtr, float*, float*, void> _getCursorScreenPos; + private static delegate* unmanaged[Cdecl]<IntPtr, int*, byte*> _getLinePrefix; + private static delegate* unmanaged[Cdecl]<IntPtr, int, byte*, void> _replaceBeforeCursor; + private static delegate* unmanaged[Cdecl]<IntPtr, int, void> _setCompletionKeysHeld; + private static delegate* unmanaged[Cdecl]<IntPtr, void> _requestFocus; + + /// <summary>False when the loaded cimgui.dll was built without the editor.</summary> + public static bool Available + { + get + { + if (!_resolved) Resolve(); + return _available; + } + } + + private static void Resolve() + { + _resolved = true; + IntPtr module = EntryPoint.ImGuiNativeHandle; + if (module == IntPtr.Zero) return; + IntPtr Get(string name) => NativeLibrary.TryGetExport(module, name, out IntPtr p) ? p : IntPtr.Zero; + + _create = (delegate* unmanaged[Cdecl]<IntPtr>)Get("RynthTE_Create"); + _destroy = (delegate* unmanaged[Cdecl]<IntPtr, void>)Get("RynthTE_Destroy"); + _setMetaVocabulary = (delegate* unmanaged[Cdecl]<byte*, byte*, byte*, void>)Get("RynthTE_SetMetaVocabulary"); + _setLanguage = (delegate* unmanaged[Cdecl]<IntPtr, int, void>)Get("RynthTE_SetLanguage"); + _setPalette = (delegate* unmanaged[Cdecl]<IntPtr, uint*, int, void>)Get("RynthTE_SetPalette"); + _setOptions = (delegate* unmanaged[Cdecl]<IntPtr, int, int, int, int, void>)Get("RynthTE_SetOptions"); + _setText = (delegate* unmanaged[Cdecl]<IntPtr, byte*, void>)Get("RynthTE_SetText"); + _getText = (delegate* unmanaged[Cdecl]<IntPtr, int*, byte*>)Get("RynthTE_GetText"); + _getChangeCount = (delegate* unmanaged[Cdecl]<IntPtr, uint>)Get("RynthTE_GetChangeCount"); + _render = (delegate* unmanaged[Cdecl]<IntPtr, byte*, float, float, int, int>)Get("RynthTE_Render"); + _getCursor = (delegate* unmanaged[Cdecl]<IntPtr, int*, int*, void>)Get("RynthTE_GetCursor"); + _setCursor = (delegate* unmanaged[Cdecl]<IntPtr, int, int, void>)Get("RynthTE_SetCursor"); + _getCursorScreenPos = (delegate* unmanaged[Cdecl]<IntPtr, float*, float*, void>)Get("RynthTE_GetCursorScreenPos"); + _getLinePrefix = (delegate* unmanaged[Cdecl]<IntPtr, int*, byte*>)Get("RynthTE_GetLinePrefix"); + _replaceBeforeCursor = (delegate* unmanaged[Cdecl]<IntPtr, int, byte*, void>)Get("RynthTE_ReplaceBeforeCursor"); + _setCompletionKeysHeld = (delegate* unmanaged[Cdecl]<IntPtr, int, void>)Get("RynthTE_SetCompletionKeysHeld"); + _requestFocus = (delegate* unmanaged[Cdecl]<IntPtr, void>)Get("RynthTE_RequestFocus"); + + _available = _create != null && _destroy != null && _setMetaVocabulary != null && _setLanguage != null + && _setPalette != null && _setOptions != null && _setText != null && _getText != null + && _getChangeCount != null && _render != null && _getCursor != null && _setCursor != null + && _getCursorScreenPos != null && _getLinePrefix != null && _replaceBeforeCursor != null + && _setCompletionKeysHeld != null && _requestFocus != null; + if (!_available) + RynthLog.UI("CodeEditor: this cimgui.dll has no RynthTE_* exports; ImGui source editors are unavailable."); + } + + private static bool _vocabularySet; + + /// <summary>The Meta language's keywords (all Meta editors share them). Set once.</summary> + public static void SetMetaVocabulary(string[] structWords, string[] conditionWords, string[] actionWords) + { + if (_vocabularySet || !Available) return; + _vocabularySet = true; + byte[] s = Utf8Z(string.Join('\n', structWords)); + byte[] c = Utf8Z(string.Join('\n', conditionWords)); + byte[] a = Utf8Z(string.Join('\n', actionWords)); + fixed (byte* ps = s, pc = c, pa = a) + _setMetaVocabulary(ps, pc, pa); + } + + // ── Instance ─────────────────────────────────────────────────────────── + private IntPtr _handle; + private readonly byte[] _id; + private readonly CodeLanguage _language; + private readonly uint[] _palette; + private string? _pendingText; + private uint _cleanCount; + private bool _held; + + /// <param name="palette">ImGui colours (ABGR) in ImGuiColorTextEdit's PaletteIndex order.</param> + public CodeEditor(string id, CodeLanguage language, uint[] palette) + { + _id = Utf8Z(id); + _language = language; + _palette = palette; + } + + public bool Created => _handle != IntPtr.Zero; + + private bool Ensure() + { + if (_handle != IntPtr.Zero) return true; + if (!Available) return false; + _handle = _create(); + if (_handle == IntPtr.Zero) return false; + _setLanguage(_handle, (int)_language); + fixed (uint* p = _palette) + _setPalette(_handle, p, _palette.Length); + _setOptions(_handle, 0, 0, 1, 4); + SetTextNow(_pendingText ?? string.Empty); + _pendingText = null; + return true; + } + + /// <summary>Replaces the text (and the undo history); the editor is clean afterwards.</summary> + public void SetText(string text) + { + if (_handle == IntPtr.Zero) { _pendingText = text; return; } + SetTextNow(text); + } + + private void SetTextNow(string text) + { + byte[] bytes = Utf8Z(text); + fixed (byte* p = bytes) + _setText(_handle, p); + _cleanCount = _getChangeCount(_handle); + } + + public string GetText() + { + if (_handle == IntPtr.Zero) return _pendingText ?? string.Empty; + int len; + byte* p = _getText(_handle, &len); + return len <= 0 ? string.Empty : Encoding.UTF8.GetString(p, len); + } + + /// <summary>Counts text changes (edits, undo, redo, SetText).</summary> + public uint ChangeCount => _handle == IntPtr.Zero ? 0 : _getChangeCount(_handle); + + /// <summary>Edited since the last SetText or MarkClean.</summary> + public bool IsDirty => _handle != IntPtr.Zero && _getChangeCount(_handle) != _cleanCount; + + public void MarkClean() + { + if (_handle != IntPtr.Zero) _cleanCount = _getChangeCount(_handle); + } + + /// <summary>Draws the editor as a child window of <paramref name="size"/>; returns whether it has keyboard focus.</summary> + public bool Render(Vector2 size) + { + if (!Ensure()) return false; + fixed (byte* id = _id) + return _render(_handle, id, size.X, size.Y, 1) != 0; + } + + /// <summary>Zero-based line and (tab-expanded) column of the cursor.</summary> + public (int Line, int Column) Cursor + { + get + { + if (_handle == IntPtr.Zero) return (0, 0); + int line, column; + _getCursor(_handle, &line, &column); + return (line, column); + } + } + + public void SetCursor(int line, int charIndex) + { + if (_handle != IntPtr.Zero) _setCursor(_handle, line, charIndex); + } + + /// <summary>Screen position of the bottom-left corner of the cursor's cell (after Render).</summary> + public Vector2 CursorScreenPos + { + get + { + if (_handle == IntPtr.Zero) return Vector2.Zero; + float x, y; + _getCursorScreenPos(_handle, &x, &y); + return new Vector2(x, y); + } + } + + /// <summary>The cursor's line up to the cursor.</summary> + public string LinePrefix() + { + if (_handle == IntPtr.Zero) return string.Empty; + int len; + byte* p = _getLinePrefix(_handle, &len); + return len <= 0 ? string.Empty : Encoding.UTF8.GetString(p, len); + } + + /// <summary>Replaces the <paramref name="bytes"/> UTF-8 bytes before the cursor with <paramref name="text"/> (one undo step).</summary> + public void ReplaceBeforeCursor(int bytes, string text) + { + if (_handle == IntPtr.Zero) return; + byte[] t = Utf8Z(text); + fixed (byte* p = t) + _replaceBeforeCursor(_handle, bytes, p); + } + + /// <summary>While true the editor leaves Up/Down/PageUp/PageDown/Enter/Tab/Escape to a completion list.</summary> + public bool CompletionKeysHeld + { + get => _held; + set + { + if (_held == value || _handle == IntPtr.Zero) return; + _held = value; + _setCompletionKeysHeld(_handle, value ? 1 : 0); + } + } + + public void RequestFocus() + { + if (_handle != IntPtr.Zero) _requestFocus(_handle); + } + + public void Dispose() + { + if (_handle == IntPtr.Zero) return; + _pendingText = GetText(); + _destroy(_handle); + _handle = IntPtr.Zero; + _held = false; + } + + private static byte[] Utf8Z(string s) + { + byte[] bytes = new byte[Encoding.UTF8.GetByteCount(s) + 1]; + Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0); + return bytes; + } + + // ── Palettes ─────────────────────────────────────────────────────────── + + /// <summary> + /// The Meta editor's colours (MetaSourceEditor's): STATE:/IF:/DO:/NAV: teal + /// (Keyword), conditions amber (KnownIdentifier), actions blue + /// (PreprocIdentifier), braces violet, numbers green, "~~" comments grey. + /// Lua uses the same slots (keywords teal, built-ins amber). + /// </summary> + public static uint[] RynthPalette() + { + static uint C(uint argb) => RynthTheme.Argb(argb); + return new[] + { + C(0xFFD9E6F2), // Default + C(0xFF26D9E6), // Keyword + C(0xFF99E699), // Number + C(0xFFE6C07B), // String + C(0xFFE6C07B), // CharLiteral + C(0xFFCC88CC), // Punctuation + C(0xFF8CA6BF), // Preprocessor + C(0xFFD9E6F2), // Identifier + C(0xFFE8B333), // KnownIdentifier + C(0xFF7BB8FF), // PreprocIdentifier + C(0xFF6A7A8A), // Comment + C(0xFF6A7A8A), // MultiLineComment + C(0xFF141F29), // Background + C(0xFFE6F2FF), // Cursor + C(0x80305A80), // Selection + C(0x80B02020), // ErrorMarker + C(0xFF3A4A5A), // ControlCharacter + C(0x40F08000), // Breakpoint + C(0xFF4F6478), // LineNumber + C(0x40263A50), // CurrentLineFill + C(0x20263A50), // CurrentLineFillInactive + C(0x40264059), // CurrentLineEdge + }; + } +} diff --git a/src/RynthCore.Engine/ImGui/DX9Backend.cs b/src/RynthCore.Engine/ImGui/DX9Backend.cs index 30a0851..1fa9201 100644 --- a/src/RynthCore.Engine/ImGui/DX9Backend.cs +++ b/src/RynthCore.Engine/ImGui/DX9Backend.cs @@ -6,7 +6,6 @@ using System; using System.Numerics; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ImGuiNET; using RynthCore.Engine.D3D9; @@ -17,30 +16,36 @@ internal static unsafe class DX9Backend { private static readonly Guid IID_IUnknown = new("00000000-0000-0000-C000-000000000046"); - // ─── Native ImDrawData layout (pre-1.90 cimgui, x86) ───────────── - // Our cimgui.dll uses the old layout where CmdLists is a raw pointer (4 bytes) - // rather than ImVector (12 bytes). All offsets confirmed by memory dump. - private static Vector2 GetDisplayPos(IntPtr drawDataNative) + // Draw data is read through ImGui.NET's native structs (ImDrawData, + // ImDrawList, ImDrawCmd). That is only valid because Native\cimgui.dll is + // the exact 1.91.6 build ImGui.NET 1.91.6.1 was generated against; + // ImGuiSelfTest refuses to start ImGui if the loaded DLL is anything else. + + // Converted-vertex scratch buffer, grown on demand and reused every frame + // (no per-frame native allocation on AC's thread). Freed in Shutdown. + private static CustomVertex* _vtxScratch; + private static int _vtxScratchCapacity; + + private static CustomVertex* EnsureVertexScratch(int needed) { - float x = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 20)); - float y = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 24)); - return new Vector2(x, y); - } - private static Vector2 GetDisplaySize(IntPtr drawDataNative) - { - float x = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 28)); - float y = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 32)); - return new Vector2(x, y); - } - private static int GetCmdListsCount(IntPtr drawDataNative) - { - return Marshal.ReadInt32(drawDataNative, 4); - } - private static IntPtr GetCmdListsArray(IntPtr drawDataNative) - { - return Marshal.ReadIntPtr(drawDataNative, 16); + if (needed > _vtxScratchCapacity) + { + int cap = _vtxScratchCapacity == 0 ? 8192 : _vtxScratchCapacity; + while (cap < needed) cap *= 2; + if (_vtxScratch != null) NativeMemory.Free(_vtxScratch); + _vtxScratch = (CustomVertex*)NativeMemory.Alloc((nuint)cap, (nuint)sizeof(CustomVertex)); + _vtxScratchCapacity = cap; + } + return _vtxScratch; } + // ── Diagnostics (/rc imgui diag): what the last RenderDrawData did ── + private static int _diagLists, _diagVtx, _diagCmds, _diagDraws, _diagSkipped, _diagFailed, _diagLastHr; + private static long _diagFrames; + + public static string DescribeLastFrame() => + $"render: initialized={_initialized} frames={_diagFrames} lastFrame lists={_diagLists} vtx={_diagVtx} cmds={_diagCmds} draws={_diagDraws} skipped={_diagSkipped} failedDraws={_diagFailed} lastFailHr=0x{_diagLastHr:X8} fontTex=0x{_fontTexture:X8}"; + // ─── D3D9 constants ─────────────────────────────────────────────── private const uint D3DPT_TRIANGLELIST = 4; private const uint D3DFMT_INDEX16 = 101; @@ -125,6 +130,12 @@ internal static unsafe class DX9Backend // D3DSAMPLERSTATETYPE private const uint D3DSAMP_MINFILTER = 5; private const uint D3DSAMP_MAGFILTER = 6; + private const uint D3DSAMP_ADDRESSU = 1; + private const uint D3DSAMP_ADDRESSV = 2; + private const uint D3DSAMP_MIPFILTER = 7; + private const uint D3DTADDRESS_CLAMP = 3; + private const uint D3DTEXF_NONE = 0; + private const uint D3DRS_WRAP0 = 128; // D3DTEXTUREFILTERTYPE private const uint D3DTEXF_LINEAR = 2; @@ -133,16 +144,24 @@ internal static unsafe class DX9Backend private const uint D3DFVF_XYZ = 0x002; private const uint D3DFVF_DIFFUSE = 0x040; private const uint D3DFVF_TEX1 = 0x100; - private const uint D3DFVF_CUSTOM = D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1; + private const uint D3DFVF_XYZRHW = 0x004; + private const uint D3DFVF_CUSTOM = D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1; + private const uint D3DRS_VERTEXBLEND = 151; + private const uint D3DRS_CLIPPLANEENABLE = 152; // D3DBLENDOP private const uint D3DBLENDOP_ADD = 1; // ─── Vertex structure (D3D9 layout) ─────────────────────────────── [StructLayout(LayoutKind.Sequential)] + // Pre-transformed (screen-space) vertices, like VitalHud and the Avalonia + // quad. The first in-game test drew ImGui with XYZ vertices through the + // fixed-function transform stage and nothing appeared, although every + // draw call succeeded: state AC leaves in that stage (user clip planes, + // vertex blending) can discard the geometry. XYZRHW skips it entirely. private struct CustomVertex { - public float X, Y, Z; + public float X, Y, Z, Rhw; public uint Col; // ARGB public float U, V; } @@ -358,6 +377,11 @@ internal static unsafe class DX9Backend if (!CreateFontTexture(pDevice)) return false; + // Draw lists may exceed 64K vertices (radar walls); with this flag ImGui + // splits them into commands that carry a VtxOffset, which + // RenderDrawData applies, so 16-bit indices stay valid. + ImGuiNET.ImGui.GetIO().BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset; + _initialized = true; RynthLog.Render("DX9Backend: ImGui resources initialized."); return true; @@ -372,12 +396,19 @@ internal static unsafe class DX9Backend public static void Shutdown() { + ReleaseRetiredFontTexture(); if (_fontTexture != IntPtr.Zero) { var release = GetTexMethod<ReleaseD>(_fontTexture, TextureVTableIndex.Release); release(_fontTexture); _fontTexture = IntPtr.Zero; } + if (_vtxScratch != null) + { + NativeMemory.Free(_vtxScratch); + _vtxScratch = null; + _vtxScratchCapacity = 0; + } _initialized = false; _coreInitialized = false; } @@ -466,21 +497,54 @@ internal static unsafe class DX9Backend public static void RenderDrawData(ImDrawDataPtr drawData, IntPtr pDevice) { if (!_initialized) return; - if (drawData.NativePtr == null) return; + ImDrawData* dd = drawData.NativePtr; + if (dd == null) return; + RenderLists((ImDrawList**)dd->CmdLists.Data, dd->CmdListsCount, dd->TotalVtxCount, dd->DisplayPos, dd->DisplaySize, + pDevice, midFrame: false); + } - IntPtr ddNative = (IntPtr)drawData.NativePtr; - int cmdListsCount = GetCmdListsCount(ddNative); - Vector2 displaySize = GetDisplaySize(ddNative); - Vector2 displayPos = GetDisplayPos(ddNative); + /// <summary> + /// Renders one draw list built outside ImGui's draw data (UnderUiLayer: the + /// world overlays drawn at AC's 3D→UI transition, in the middle of AC's frame). + /// Same state save/restore as <see cref="RenderDrawData"/>, plus the few + /// states a 3D pass can leave that the UI pass at EndScene never does. + /// Doesn't count in /rc imgui diag. AC's render thread. + /// </summary> + public static void RenderDrawList(ImDrawList* list, Vector2 displaySize, IntPtr pDevice) + { + if (!_initialized || list == null || pDevice == IntPtr.Zero) return; + RenderLists(&list, 1, -1, Vector2.Zero, displaySize, pDevice, midFrame: true); + } + /// <param name="totalVtx">For the diagnostics; -1: not a frame of ImGui's own (not counted).</param> + private static void RenderLists(ImDrawList** cmdLists, int cmdListsCount, int totalVtx, Vector2 displayPos, Vector2 displaySize, + IntPtr pDevice, bool midFrame) + { if (cmdListsCount == 0) return; if (displaySize.X <= 0 || displaySize.Y <= 0) return; + if (cmdLists == null) return; - IntPtr cmdListsArray = GetCmdListsArray(ddNative); - if (cmdListsArray == IntPtr.Zero) return; + if (totalVtx >= 0) + { + _diagFrames++; + _diagLists = cmdListsCount; _diagVtx = totalVtx; + _diagCmds = 0; _diagDraws = 0; _diagSkipped = 0; _diagFailed = 0; + } - if (false && _logCount < 3) - RynthLog.Render($"DX9: Rendering {cmdListsCount} lists, display={displaySize.X}x{displaySize.Y}"); + // Mid-frame only (the 3D pass's leftovers): texture-coordinate wrapping, + // and sampler 0's addressing and mip filter. + uint oldWrap0 = 0, oldSamp0AddrU = 0, oldSamp0AddrV = 0, oldSamp0Mip = 0; + if (midFrame) + { + _getRenderState!(pDevice, D3DRS_WRAP0, out oldWrap0); + _getSamplerState!(pDevice, 0, D3DSAMP_ADDRESSU, out oldSamp0AddrU); + _getSamplerState!(pDevice, 0, D3DSAMP_ADDRESSV, out oldSamp0AddrV); + _getSamplerState!(pDevice, 0, D3DSAMP_MIPFILTER, out oldSamp0Mip); + _setRenderState!(pDevice, D3DRS_WRAP0, 0); + _setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); + _setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); + _setSamplerState!(pDevice, 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE); + } // ── Manual state save ──────────────────────────────────────── D3DVIEWPORT9 oldVp = default; @@ -500,6 +564,7 @@ internal static unsafe class DX9Backend uint oldFillMode = 0, oldZWriteEnable = 0, oldAlphaTestEnable = 0; uint oldClipping = 0, oldRangeFog = 0, oldSpecular = 0; uint oldSrcBlendAlpha = 0, oldDestBlendAlpha = 0; + uint oldVertexBlend = 0, oldClipPlanes = 0; uint oldTss0TexCoordIdx = 0, oldTss0TexTransFlags = 0; // Stream source and index buffer — DrawIndexedPrimitiveUP sets these to NULL internally IntPtr oldStreamData = IntPtr.Zero; @@ -548,6 +613,8 @@ internal static unsafe class DX9Backend _getRenderState!(pDevice, D3DRS_SPECULARENABLE, out oldSpecular); _getRenderState!(pDevice, D3DRS_SRCBLENDALPHA, out oldSrcBlendAlpha); _getRenderState!(pDevice, D3DRS_DESTBLENDALPHA, out oldDestBlendAlpha); + _getRenderState!(pDevice, D3DRS_VERTEXBLEND, out oldVertexBlend); + _getRenderState!(pDevice, D3DRS_CLIPPLANEENABLE, out oldClipPlanes); _getTexStageState!(pDevice, 0, D3DTSS_TEXCOORDINDEX, out oldTss0TexCoordIdx); _getTexStageState!(pDevice, 0, D3DTSS_TEXTURETRANSFORMFLAGS, out oldTss0TexTransFlags); _getStreamSource!(pDevice, 0, out oldStreamData, out oldStreamOffset, out oldStreamStride); @@ -555,153 +622,89 @@ internal static unsafe class DX9Backend try { - // Set up render state with correct display size - if (false && _logCount < 3) RynthLog.Render("DX9: step SetupRenderState"); SetupRenderStateNative(pDevice, displayPos, displaySize); - if (false && _logCount < 3) RynthLog.Render("DX9: step SetupRenderState done"); - // ── Native ImDrawCmd offsets (imgui.h 1.91.6, x86) ────────── - // +0 ClipRect (4 floats, 16 bytes) - // +16 TextureId (ptr, 4 bytes) - // +20 VtxOffset (uint32) - // +24 IdxOffset (uint32) - // +28 ElemCount (uint32) - // +32 UserCallback (ptr, 4 bytes) - // +36 UserCallbackData (ptr, 4 bytes) - // Total = 40 bytes. The C# ImDrawCmd wrapper adds UserCallbackDataSize - // and UserCallbackDataOffset (8 more bytes = 48), but the native cimgui.dll - // does NOT have those fields. We read at stride 40 to match the native layout. - const int CmdStride = 40; const int ResetRenderStateSentinel = -8; // ImDrawCallback_ResetRenderState for (int n = 0; n < cmdListsCount; n++) { - IntPtr listPtr = Marshal.ReadIntPtr(cmdListsArray, n * IntPtr.Size); - if (listPtr == IntPtr.Zero) continue; + ImDrawList* list = cmdLists[n]; + if (list == null) continue; - // Read ImDrawList fields directly from native memory. - // ImDrawList starts with three ImVectors (each 12 bytes: Size/Capacity/Data). - // [0] CmdBuffer — ImVector<ImDrawCmd> - // [12] IdxBuffer — ImVector<ImDrawIdx> - // [24] VtxBuffer — ImVector<ImDrawVert> - int cmdCount = Marshal.ReadInt32(listPtr, 0); // CmdBuffer.Size - IntPtr cmdData = Marshal.ReadIntPtr(listPtr, 8); // CmdBuffer.Data - int idxCount = Marshal.ReadInt32(listPtr, 12); // IdxBuffer.Size - IntPtr idxBase = Marshal.ReadIntPtr(listPtr, 20); // IdxBuffer.Data - int vtxCount = Marshal.ReadInt32(listPtr, 24); // VtxBuffer.Size - IntPtr vtxBase = Marshal.ReadIntPtr(listPtr, 32); // VtxBuffer.Data - - if (false && _logCount < 3) - RynthLog.Render($"DX9: list[{n}] vtx={vtxCount} idx={idxCount} cmds={cmdCount}"); + int vtxCount = list->VtxBuffer.Size; + int cmdCount = list->CmdBuffer.Size; if (vtxCount == 0 || cmdCount == 0) continue; - // One-time stride diagnostic — log what each cmd stride gives for cmd[1] - if (false && _logCount == 0 && n == 0 && cmdCount >= 2) - { - RynthLog.Render($"DX9: C# ImDrawCmd size = {Unsafe.SizeOf<ImDrawCmd>()}"); - for (int ts = 32; ts <= 64; ts += 4) - { - IntPtr tp = cmdData + ts; - uint te = (uint)Marshal.ReadInt32(tp, 28); - float tx = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(tp, 0)); - float tz = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(tp, 8)); - uint tcb = (uint)Marshal.ReadInt32(tp, 32); - RynthLog.Render($"DX9: stride={ts}: elems={te} clipX={tx} clipZ={tz} cb=0x{tcb:X8}"); - } - } - - // One-time vertex diagnostic — verify ImDrawVert layout - if (false && _logCount == 0 && n == 0) - { - RynthLog.Render($"DX9: C# ImDrawVert size = {Unsafe.SizeOf<ImDrawVert>()}"); - // Read first 3 vertices as raw bytes to verify layout - for (int vi = 0; vi < Math.Min(3, vtxCount); vi++) - { - IntPtr vp = vtxBase + vi * Unsafe.SizeOf<ImDrawVert>(); - float px = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 0)); - float py = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 4)); - float ux = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 8)); - float uy = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 12)); - uint col = (uint)Marshal.ReadInt32(vp, 16); - RynthLog.Render($"DX9: vtx[{vi}] pos=({px},{py}) uv=({ux},{uy}) col=0x{col:X8}"); - } - } - - CustomVertex* vtxBuf = (CustomVertex*)NativeMemory.Alloc((nuint)(vtxCount * sizeof(CustomVertex))); - ImDrawVert* srcVtx = (ImDrawVert*)vtxBase; + ImDrawVert* srcVtx = (ImDrawVert*)list->VtxBuffer.Data; + ushort* idxBase = (ushort*)list->IdxBuffer.Data; + ImDrawCmd* cmds = (ImDrawCmd*)list->CmdBuffer.Data; + // ImGui vertices are pos/uv/RGBA; D3D9's FVF wants xyz/ARGB/uv. + CustomVertex* vtxBuf = EnsureVertexScratch(vtxCount); for (int i = 0; i < vtxCount; i++) { - vtxBuf[i].X = srcVtx[i].pos.X; - vtxBuf[i].Y = srcVtx[i].pos.Y; + // Screen pixels relative to the viewport; -0.5 is D3D9's + // half-pixel offset (the XYZ path put it in the projection). + vtxBuf[i].X = srcVtx[i].pos.X - displayPos.X - 0.5f; + vtxBuf[i].Y = srcVtx[i].pos.Y - displayPos.Y - 0.5f; vtxBuf[i].Z = 0f; + vtxBuf[i].Rhw = 1f; uint c = srcVtx[i].col; vtxBuf[i].Col = (c & 0xFF00FF00) | ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16); vtxBuf[i].U = srcVtx[i].uv.X; vtxBuf[i].V = srcVtx[i].uv.Y; } - if (false && _logCount < 3) RynthLog.Render($"DX9: list[{n}] vertex copy done"); - for (int cmdI = 0; cmdI < cmdCount; cmdI++) { - IntPtr cmdPtr = cmdData + cmdI * CmdStride; + ImDrawCmd* cmd = &cmds[cmdI]; - // Read fields at known native offsets - float clipX = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 0)); - float clipY = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 4)); - float clipZ = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 8)); - float clipW = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 12)); - IntPtr textureId = Marshal.ReadIntPtr(cmdPtr, 16); - uint nativeIdxOff = (uint)Marshal.ReadInt32(cmdPtr, 24); - uint elemCount = (uint)Marshal.ReadInt32(cmdPtr, 28); - IntPtr userCallback = Marshal.ReadIntPtr(cmdPtr, 32); - - if (userCallback != IntPtr.Zero) + if (cmd->UserCallback != IntPtr.Zero) { - if (false && _logCount < 3) - RynthLog.Render($"DX9: cmd[{cmdI}] CALLBACK elems={elemCount} cb=0x{userCallback:X}"); - if ((int)userCallback == ResetRenderStateSentinel) + if ((int)cmd->UserCallback == ResetRenderStateSentinel) SetupRenderStateNative(pDevice, displayPos, displaySize); - // Non-sentinel callbacks: skip (no draw data, ElemCount expected 0) + // Other callbacks are not supported (no managed callbacks + // from inside the render path); they carry no geometry. continue; } - if (elemCount == 0) - { - if (false && _logCount < 3) - RynthLog.Render($"DX9: cmd[{cmdI}] ZERO-ELEM skip tex=0x{textureId:X}"); - continue; - } - - if (false && _logCount < 3) - RynthLog.Render($"DX9: cmd[{cmdI}] tex=0x{textureId:X} elems={elemCount} clip={clipX},{clipY},{clipZ},{clipW}"); + uint elemCount = cmd->ElemCount; + _diagCmds++; + if (elemCount == 0) continue; + Vector4 clip = cmd->ClipRect; RECT sr; - sr.Left = (int)(clipX - displayPos.X); - sr.Top = (int)(clipY - displayPos.Y); - sr.Right = (int)(clipZ - displayPos.X); - sr.Bottom = (int)(clipW - displayPos.Y); + sr.Left = (int)(clip.X - displayPos.X); + sr.Top = (int)(clip.Y - displayPos.Y); + sr.Right = (int)(clip.Z - displayPos.X); + sr.Bottom = (int)(clip.W - displayPos.Y); + // Inside the viewport (0,0,displaySize; set above): a pop-out's picture is + // only part of its ImGui display, so a full-display clip rect reaches past + // it on every side. Nothing outside the viewport is drawn anyway. + if (sr.Left < 0) sr.Left = 0; + if (sr.Top < 0) sr.Top = 0; + if (sr.Right > (int)displaySize.X) sr.Right = (int)displaySize.X; + if (sr.Bottom > (int)displaySize.Y) sr.Bottom = (int)displaySize.Y; + if (sr.Right <= sr.Left || sr.Bottom <= sr.Top) { _diagSkipped++; continue; } _setScissorRect!(pDevice, &sr); - _setTexture!(pDevice, 0, textureId); + _setTexture!(pDevice, 0, cmd->TextureId); - ushort* pIdxData = (ushort*)idxBase + nativeIdxOff; - if (false && _logCount < 3) - RynthLog.Render($"DX9: cmd[{cmdI}] DrawIndexedPrimUP primCount={elemCount / 3}"); - _drawIndexedPrimUP!(pDevice, - D3DPT_TRIANGLELIST, 0, (uint)vtxCount, + // DrawIndexedPrimitiveUP has no base-vertex argument, so the + // command's VtxOffset is applied by offsetting the vertex pointer. + uint vtxOffset = cmd->VtxOffset; + if (vtxOffset >= (uint)vtxCount) { _diagSkipped++; continue; } + int hr = _drawIndexedPrimUP!(pDevice, + D3DPT_TRIANGLELIST, 0, (uint)vtxCount - vtxOffset, elemCount / 3, - (IntPtr)pIdxData, D3DFMT_INDEX16, - (IntPtr)vtxBuf, (uint)sizeof(CustomVertex)); - if (false && _logCount < 3) RynthLog.Render($"DX9: cmd[{cmdI}] draw done"); + (IntPtr)(idxBase + cmd->IdxOffset), D3DFMT_INDEX16, + (IntPtr)(vtxBuf + vtxOffset), (uint)sizeof(CustomVertex)); + _diagDraws++; + if (hr < 0) { _diagFailed++; _diagLastHr = hr; } } - - NativeMemory.Free(vtxBuf); } } finally { - _logCount++; // ── Manual state restore ───────────────────────────────── _setRenderState!(pDevice, D3DRS_CULLMODE, oldCull); _setRenderState!(pDevice, D3DRS_LIGHTING, oldLighting); @@ -745,10 +748,19 @@ internal static unsafe class DX9Backend _setRenderState!(pDevice, D3DRS_SPECULARENABLE, oldSpecular); _setRenderState!(pDevice, D3DRS_SRCBLENDALPHA, oldSrcBlendAlpha); _setRenderState!(pDevice, D3DRS_DESTBLENDALPHA, oldDestBlendAlpha); + _setRenderState!(pDevice, D3DRS_VERTEXBLEND, oldVertexBlend); + _setRenderState!(pDevice, D3DRS_CLIPPLANEENABLE, oldClipPlanes); _setTexStageState!(pDevice, 0, D3DTSS_TEXCOORDINDEX, oldTss0TexCoordIdx); _setTexStageState!(pDevice, 0, D3DTSS_TEXTURETRANSFORMFLAGS, oldTss0TexTransFlags); _setStreamSource!(pDevice, 0, oldStreamData, oldStreamOffset, oldStreamStride); _setIndices!(pDevice, oldIndexBuffer); + if (midFrame) + { + _setRenderState!(pDevice, D3DRS_WRAP0, oldWrap0); + _setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSU, oldSamp0AddrU); + _setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSV, oldSamp0AddrV); + _setSamplerState!(pDevice, 0, D3DSAMP_MIPFILTER, oldSamp0Mip); + } // Release COM refs we obtained if (oldTexture != IntPtr.Zero) @@ -842,28 +854,35 @@ internal static unsafe class DX9Backend // FVF — SetStreamSource is NOT called here; DrawIndexedPrimitiveUP uses user-memory // pointers directly and does not require a bound vertex stream. _setFVF!(dev, D3DFVF_CUSTOM); + _setRenderState!(dev, D3DRS_VERTEXBLEND, 0); // D3DVBF_DISABLE + _setRenderState!(dev, D3DRS_CLIPPLANEENABLE, 0); // no user clip planes - // Orthographic projection — D3D9 pixel centers are at +0.5 (not +0.0 like D3D10+) - float L = displayPos.X + 0.5f; - float R = displayPos.X + displaySize.X + 0.5f; - float T = displayPos.Y + 0.5f; - float B = displayPos.Y + displaySize.Y + 0.5f; + // No transforms: XYZRHW vertices are already in viewport pixels (see CustomVertex). + } - D3DMATRIX identity; - identity.M11 = 1; identity.M12 = 0; identity.M13 = 0; identity.M14 = 0; - identity.M21 = 0; identity.M22 = 1; identity.M23 = 0; identity.M24 = 0; - identity.M31 = 0; identity.M32 = 0; identity.M33 = 1; identity.M34 = 0; - identity.M41 = 0; identity.M42 = 0; identity.M43 = 0; identity.M44 = 1; + /// <summary> + /// After the font atlas was rebuilt: replace the font texture. Render thread. + /// The old texture is kept one more frame: UnderUiLayer's list from the frame + /// before may still be drawn by this frame's fallback, and it names the old one. + /// </summary> + public static bool RebuildFontTexture(IntPtr pDevice) + { + ReleaseRetiredFontTexture(); + _retiredFontTexture = _fontTexture; + _fontTexture = IntPtr.Zero; + return CreateFontTexture(pDevice); + } - D3DMATRIX projection; - projection.M11 = 2f / (R - L); projection.M12 = 0f; projection.M13 = 0f; projection.M14 = 0f; - projection.M21 = 0f; projection.M22 = 2f / (T - B); projection.M23 = 0f; projection.M24 = 0f; - projection.M31 = 0f; projection.M32 = 0f; projection.M33 = 0.5f; projection.M34 = 0f; - projection.M41 = (L + R) / (L - R); projection.M42 = (T + B) / (B - T); projection.M43 = 0.5f; projection.M44 = 1f; + // The font texture a rebuild replaced; released at the next frame's build. + private static IntPtr _retiredFontTexture; - _setTransform!(dev, D3DTS_WORLD, &identity); - _setTransform!(dev, D3DTS_VIEW, &identity); - _setTransform!(dev, D3DTS_PROJECTION, &projection); + /// <summary>Releases the texture the last rebuild replaced. Render thread, at the start of a frame's build.</summary> + public static void ReleaseRetiredFontTexture() + { + if (_retiredFontTexture == IntPtr.Zero) return; + var release = GetTexMethod<ReleaseD>(_retiredFontTexture, TextureVTableIndex.Release); + release(_retiredFontTexture); + _retiredFontTexture = IntPtr.Zero; } private static bool CreateFontTexture(IntPtr pDevice) @@ -921,27 +940,52 @@ internal static unsafe class DX9Backend // Store texture ID for ImGui io.Fonts.SetTexID(_fontTexture); - - // Force native TexID write — managed wrapper can mismatch on x86 - nint texId = io.Fonts.TexID; - unsafe - { - byte* ioPtr = (byte*)ImGuiNET.ImGui.GetIO().NativePtr; - IntPtr fontsPtr = *(IntPtr*)(ioPtr + 36); - *(IntPtr*)(fontsPtr + 4) = _fontTexture; - } - if (texId == 0) - { - unsafe - { - byte* ioPtr = (byte*)ImGuiNET.ImGui.GetIO().NativePtr; - IntPtr fontsPtr = *(IntPtr*)(ioPtr + 36); - *(IntPtr*)(fontsPtr + 4) = _fontTexture; - } - } return true; } + /// <summary> + /// A managed-pool A8R8G8B8 texture (it survives a device reset) holding RGBA pixels + /// (script window icons). Zero on failure. AC's render thread, after <see cref="InitCore"/>. + /// </summary> + public static IntPtr CreateTextureRgba(IntPtr pDevice, int width, int height, ReadOnlySpan<byte> rgba) + { + if (_createTexture == null || pDevice == IntPtr.Zero || width <= 0 || height <= 0 + || rgba.Length < width * height * 4) + return IntPtr.Zero; + int hr = _createTexture(pDevice, (uint)width, (uint)height, 1, 0, + D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out IntPtr tex, IntPtr.Zero); + if (hr < 0 || tex == IntPtr.Zero) + return IntPtr.Zero; + + var lockRect = GetTexMethod<TexLockRectD>(tex, TextureVTableIndex.LockRect); + var unlockRect = GetTexMethod<TexUnlockRectD>(tex, TextureVTableIndex.UnlockRect); + D3DLOCKED_RECT locked; + if (lockRect(tex, 0, &locked, IntPtr.Zero, 0) < 0 || locked.pBits == IntPtr.Zero) + { + ReleaseComObject(tex); + return IntPtr.Zero; + } + byte* dst = (byte*)locked.pBits; + for (int y = 0; y < height; y++) + { + ReadOnlySpan<byte> srcRow = rgba.Slice(y * width * 4, width * 4); + byte* dstRow = dst + y * locked.Pitch; + for (int x = 0; x < width; x++) + { + int i = x * 4; + dstRow[i + 0] = srcRow[i + 2]; // B + dstRow[i + 1] = srcRow[i + 1]; // G + dstRow[i + 2] = srcRow[i + 0]; // R + dstRow[i + 3] = srcRow[i + 3]; // A + } + } + unlockRect(tex, 0); + return tex; + } + + /// <summary>Releases a texture made by <see cref="CreateTextureRgba"/>. AC's render thread.</summary> + public static void ReleaseTexture(IntPtr tex) => ReleaseComObject(tex); + private static void CacheDelegates(IntPtr pDevice) { IntPtr vtable = Marshal.ReadIntPtr(pDevice); @@ -1060,6 +1104,59 @@ internal static unsafe class DX9Backend _navTrigReady = true; } + // AC's 3D view viewport, read at EndScene (AC has put it back by then; the EndScene + // fallback has always drawn the markers with it). AC's render thread only. + private static D3DVIEWPORT9 _sceneViewport; + private static bool _hasSceneViewport; + + /// <summary> + /// EndScene, before anything of ours touches the viewport: remembers AC's 3D view + /// viewport for <see cref="RenderNav3D(IntPtr, bool)"/> at the UI pass, where AC has + /// set a full-screen one. AC's render thread. + /// </summary> + public static void CaptureSceneViewport(IntPtr pDevice) + { + if (!_coreInitialized || _getViewport == null || pDevice == IntPtr.Zero) return; + D3DVIEWPORT9 vp; + if (_getViewport(pDevice, &vp) >= 0 && vp.Width > 0 && vp.Height > 0) + { + _sceneViewport = vp; + _hasSceneViewport = true; + } + } + + /// <summary> + /// <see cref="RenderNav3D(IntPtr)"/>; with <paramref name="sceneViewport"/> (AC's UI + /// pass) the markers draw in AC's 3D view viewport (from the last EndScene) when the + /// current one differs, and the current one is put back afterwards. + /// </summary> + public static void RenderNav3D(IntPtr pDevice, bool sceneViewport) + { + if (!sceneViewport || !_hasSceneViewport || !_coreInitialized || pDevice == IntPtr.Zero || + _getViewport == null || _setViewport == null) + { + RenderNav3D(pDevice); + return; + } + D3DVIEWPORT9 current; + if (_getViewport(pDevice, ¤t) < 0) + { + RenderNav3D(pDevice); + return; + } + D3DVIEWPORT9 scene = _sceneViewport; + bool same = current.X == scene.X && current.Y == scene.Y && current.Width == scene.Width && + current.Height == scene.Height && current.MinZ == scene.MinZ && current.MaxZ == scene.MaxZ; + if (same) + { + RenderNav3D(pDevice); + return; + } + _setViewport(pDevice, &scene); + try { RenderNav3D(pDevice); } + finally { _setViewport(pDevice, ¤t); } + } + public static void RenderNav3D(IntPtr pDevice) { // Nav3D only needs the cached function pointers + nav trig + GameMatrixCapture; @@ -1067,7 +1164,11 @@ internal static unsafe class DX9Backend // core init flag so this path runs even when EnableImGuiBackend=false. if (!_coreInitialized || pDevice == IntPtr.Zero) return; if (!D3D9.GameMatrixCapture.HasCapturedFrame) return; - if (D3D9.Nav3DRenderer.RingCount == 0 && D3D9.Nav3DRenderer.LineCount == 0 && D3D9.Nav3DRenderer.TriangleCount == 0) return; + // One snapshot of the committed frame for the whole draw (the pump may + // commit a new one meanwhile; this one stays intact for a tick). + D3D9.Nav3DRenderer.NavBuffer frame = D3D9.Nav3DRenderer.Ready; + int triCount = frame.TriCount, lineCount = frame.LineCount, ringCount = frame.RingCount; + if (ringCount == 0 && lineCount == 0 && triCount == 0) return; EnsureNavTrig(); @@ -1163,39 +1264,33 @@ internal static unsafe class DX9Backend // vertex buffer and submitted in a single DrawPrimitiveUP — at // high slope-radius settings we can have 4000+ triangles per // frame, and one DP-UP per triangle was visibly frame-dropping. - int triCount = D3D9.Nav3DRenderer.TriangleCount; if (triCount > 0) { EnsureNavTriBatch(triCount * 3); NavVertex* batch = (NavVertex*)_navTriBatch; for (int i = 0; i < triCount; i++) { - D3D9.Nav3DRenderer.GetTriangle(i, - out float x1, out float y1, out float z1, - out float x2, out float y2, out float z2, - out float x3, out float y3, out float z3, out uint color); + uint color = frame.TriColor[i]; int b = i * 3; - batch[b ].X = x1; batch[b ].Y = y1; batch[b ].Z = z1; batch[b ].Col = color; - batch[b + 1].X = x2; batch[b + 1].Y = y2; batch[b + 1].Z = z2; batch[b + 1].Col = color; - batch[b + 2].X = x3; batch[b + 2].Y = y3; batch[b + 2].Z = z3; batch[b + 2].Col = color; + batch[b ].X = frame.TriX1[i]; batch[b ].Y = frame.TriY1[i]; batch[b ].Z = frame.TriZ1[i]; batch[b ].Col = color; + batch[b + 1].X = frame.TriX2[i]; batch[b + 1].Y = frame.TriY2[i]; batch[b + 1].Z = frame.TriZ2[i]; batch[b + 1].Col = color; + batch[b + 2].X = frame.TriX3[i]; batch[b + 2].Y = frame.TriY3[i]; batch[b + 2].Z = frame.TriZ3[i]; batch[b + 2].Col = color; } _drawPrimUP!(pDevice, D3DPT_TRIANGLELIST, (uint)triCount, (IntPtr)batch, (uint)sizeof(NavVertex)); } // Draw lines (extruded XZ-plane quads — for edges/strips) - for (int i = 0; i < D3D9.Nav3DRenderer.LineCount; i++) + for (int i = 0; i < lineCount; i++) { - D3D9.Nav3DRenderer.GetLine(i, out float x1, out float y1, out float z1, - out float x2, out float y2, out float z2, out float thick, out uint color); - DrawNavLine(pDevice, x1, y1, z1, x2, y2, z2, thick, color); + DrawNavLine(pDevice, frame.LineX1[i], frame.LineY1[i], frame.LineZ1[i], + frame.LineX2[i], frame.LineY2[i], frame.LineZ2[i], frame.LineThick[i], frame.LineColor[i]); } // Draw rings - for (int i = 0; i < D3D9.Nav3DRenderer.RingCount; i++) + for (int i = 0; i < ringCount; i++) { - D3D9.Nav3DRenderer.GetRing(i, out float x, out float y, out float z, - out float radius, out float thick, out float height, out uint color); - DrawNavRing(pDevice, x, y, z, radius, thick, height, color); + DrawNavRing(pDevice, frame.RingX[i], frame.RingY[i], frame.RingZ[i], + frame.RingRadius[i], frame.RingThick[i], frame.RingHeight[i], frame.RingColor[i]); } if (_nav3DLogCount == 0) diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 01c5638..9461e55 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -11,7 +11,7 @@ // * ImGui-gated (only when EngineSettings.EnableImGuiBackend is true): // Win32Backend.NewFrame / DX9Backend.NewFrame, ImGui.NewFrame/EndFrame/ // Render, RynthCoreShell + plugin RenderAll, DX9Backend.RenderDrawData, -// mouse/keyboard capture flag updates, multi-viewport platform pump. +// mouse/keyboard capture flag updates. // // Renamed 2026-05-10 from ImGuiController — the type now owns more than // ImGui's frame; the ImGui block is just one branch of its work. @@ -43,23 +43,15 @@ internal static class EngineFrameController [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsWindowVisible(IntPtr hWnd); - [DllImport("user32.dll")] - private static extern bool GetClientRect(IntPtr hWnd, out ClientRect lpRect); - - [DllImport("user32.dll")] - private static extern bool ClientToScreen(IntPtr hWnd, ref ClientPoint lpPoint); - - [StructLayout(LayoutKind.Sequential)] - private struct ClientRect { public int Left, Top, Right, Bottom; } - [StructLayout(LayoutKind.Sequential)] - private struct ClientPoint { public int X, Y; } - private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); private static bool _imguiInitialized; private static bool _imguiInitFailed; private static bool _coreResolved; private static bool _pluginsInitialized; + // Pump frames plugin init has waited for the ImGui context (PumpPluginFrame; ~16 ms each). + private static int _pluginInitContextWaits; + private const int PluginInitContextMaxWaits = 300; private static IntPtr _context; private static IntPtr _gameHwnd; @@ -74,28 +66,24 @@ internal static class EngineFrameController internal static volatile IntPtr CachedDevice; private static int _pluginPumpInFrame; // re-entrancy guard for the pump - // ImGui draw data built by RunImGuiFrame, submitted later by RenderDeferredImGui - // (after the Avalonia blit). Render thread only. Device == 0 means nothing pending. - private static ImDrawDataPtr _deferredDrawData; - private static IntPtr _deferredDrawDevice; - // ImGui pipeline diagnostics (render thread only): one-time lines plus a 30 s heartbeat so a // log shows whether frames start, which branch runs and whether draw data is submitted. private const long HeartbeatIntervalMs = 30_000; - private static bool _loggedImGuiGate; private static long _engineErrorCount; - private static long _imguiErrorCount; - private static long _nextImGuiErrorLogAt; private static long _nextEngineErrorLogAt; - private static bool _loggedInitFailedSkip; - private static bool _loggedFirstFrame; private static bool _loggedFirstSubmit; private static int _loggedBranch = -1; private static string _initFailStep = "unknown"; - private static long _framesCompleted; private static long _drawSubmits; private static long _nextHeartbeatAt; + // Device for this frame's built ImGui draw data, submitted by RenderDeferredImGui after the + // Avalonia blit. Render thread only; Zero = nothing pending. The draw data stays valid until + // the next NewFrame on the main context. + private static IntPtr _deferredSubmitDevice; + // Build + pop-out time of the frame waiting in _deferredSubmitDevice (UiFrameStats adds the submit). + private static long _deferredUiTicks; + private static long _lastFrameTicks; private static int _frameCount; @@ -127,6 +115,8 @@ internal static class EngineFrameController RynthLog.Render($"EngineFrameController: Game HWND = 0x{_gameHwnd:X8}"); EntryPoint.GameHwnd = _gameHwnd; _coreResolved = true; + // Pop-outs hold D3DPOOL_DEFAULT render targets: release them before AC resets a lost device. + D3D9.DeviceResetHook.InstallFromDevice(pDevice); return true; } @@ -141,6 +131,11 @@ internal static class EngineFrameController return false; } + // Before any context exists: the loaded cimgui.dll must be the exact + // build ImGui.NET wraps, or every struct read below is at wrong offsets. + if (!ImGuiSelfTest.Run(EntryPoint.ImGuiNativeHandle)) + return false; + IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext(); if (previousContext != IntPtr.Zero) RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context."); @@ -170,23 +165,20 @@ internal static class EngineFrameController } io.ConfigFlags |= ImGuiConfigFlags.DockingEnable; - // ViewportsEnable was enabling ImGui multi-viewport platform/renderer - // callbacks against a cimgui.dll that is NOT built with - // IMGUI_ENABLE_VIEWPORTS. The platform/renderer callback chain then - // recursed (Platform → Renderer → Platform → ...) on AC's render - // thread, eating the 1MB stack in ~17s and AV'ing in ntdll mid-push. - // CLAUDE.md flags this: Multi-viewport "requires cimgui built with - // IMGUI_ENABLE_VIEWPORTS" — flag re-introduced this in the engine - // and triggered the silent stack-overflow on every login. - // io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable; - // Popped-out plugin windows use WS_EX_TOOLWINDOW so they don't show - // up as extra "Asheron's Call" entries in the taskbar — critical for - // users running many clients side by side. - io.ConfigViewportsNoTaskBarIcon = true; - ImGuiNET.ImGui.StyleColorsDark(); + // Multi-viewport (ViewportsEnable) is deliberately never enabled: it + // runs many native->managed platform/renderer callbacks per frame on + // AC's thread and creates HWNDs from inside EndScene. Pop-out panels, + // if built, are driven explicitly by the engine instead + // (docs/IMGUI_PARITY_PLAN.md section 4.2). - // One-shot offset probe for diagnostics — safe to keep installed. - ViewportProbe.Run(); + // DPI scale for fonts and style metrics. Logged next to Avalonia's + // scale: docked positions are stored in Avalonia logical units, so + // the two must agree for a panel to land in the same place in + // either face (plan section 4.4). + _uiScale = UiScale.ForWindow(_gameHwnd); + RynthLog.UI($"EngineFrameController: ImGui scale {_uiScale:0.##} (Avalonia input scale {UI.AvaloniaOverlay.InputScale:0.##})."); + RynthTheme.Apply(ImGuiNET.ImGui.GetStyle(), _uiScale); + ImGuiFonts.Build(io, _uiScale); if (!Win32Backend.Init(_gameHwnd)) { @@ -200,26 +192,11 @@ internal static class EngineFrameController return false; } - // Viewport backends only run when ViewportsEnable is on. Installing - // their callbacks on PlatformIO without the flag has no upside and - // just expands the crash surface. - if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0) - { - bool platformOk = ViewportPlatformBackend.Init(_gameHwnd); - bool rendererOk = platformOk && ViewportRendererBackend.Init(pDevice); - if (!platformOk || !rendererOk) - { - RynthLog.Render($"EngineFrameController: viewport init failed (platform={platformOk}, renderer={rendererOk}) — disabling ViewportsEnable."); - io.ConfigFlags &= ~ImGuiConfigFlags.ViewportsEnable; - } - ViewportPlatformBackend.ImGuiContext = _context; - } - _lastFrameTicks = Stopwatch.GetTimestamp(); _imguiInitialized = true; initSucceeded = true; - RynthLog.Info("EngineFrameController: ImGui fully initialized."); + RynthLog.UI("EngineFrameController: ImGui initialized."); return true; } finally @@ -246,14 +223,16 @@ internal static class EngineFrameController { ImGuiNET.ImGui.SetCurrentContext(contextToDestroy); - // Zero the WndProc context guard BEFORE DestroyContext so any - // deferred OS messages that arrive at viewport HWNDs during or - // after teardown don't try to call into freed ImGui memory. - ViewportPlatformBackend.ImGuiContext = IntPtr.Zero; PluginManager.ShutdownAll(); + // No context may be destroyed while a font worker runs (ImGuiFonts, re-bake note). + ImGuiFonts.WaitForWorkers(); + // Pop-outs share the main font atlas: their contexts go before the main one. + ImGuiPopOuts.Shutdown(); OverlayTextureRenderer.Shutdown(); - ViewportRendererBackend.Shutdown(); - ViewportPlatformBackend.Shutdown(); + // Its lists are drawn by DX9Backend from the DIP hook, which is still live. + UnderUiLayer.Shutdown(); + ScriptIcons.Shutdown(); // script window icon textures, before the backend goes + RetailSprites.Shutdown(); // retail UI pictures (Inventory Classic view), likewise DX9Backend.Shutdown(); // Do NOT call Win32Backend.Shutdown() here. EngineLifecycle.Shutdown // owns that step explicitly, AFTER AvaloniaOverlay.Stop — floating @@ -263,6 +242,7 @@ internal static class EngineFrameController // those destroys to AC's proc, which ignores them, and the orphaned // panel HWND outlives the engine load. ImGuiNET.ImGui.DestroyContext(contextToDestroy); + ImGuiFonts.Free(); // the atlas referenced these buffers; the context is gone now _imguiInitialized = false; _coreResolved = false; @@ -281,6 +261,8 @@ internal static class EngineFrameController // EngineSettings.EnableImGuiBackend, so world→screen capture, nav- // marker rendering, and plugin lifecycle stay alive when the ImGui // surface is disabled. + // A frame that throws before its build must not resubmit last frame's draw data. + _deferredSubmitDevice = IntPtr.Zero; try { // Resolve game HWND and seed EntryPoint.GameHwnd. Required even @@ -299,10 +281,16 @@ internal static class EngineFrameController // accumulates, RenderedThisFrame stays false on every frame, and the // end-of-frame fallback below paints markers OVER the UI. This call was // dropped in the v0.19 Nav3D double-buffer refactor — restored here. + // Since 2026-10-04 this is the second choice: with AcUiPassHook live the + // overlays draw at AC's UI pass and SyncHookState (end of frame) switches + // this hook off; it comes back for /rc worldlayer transition or without it. D3D9.Nav3DRenderInjector.Install(pDevice); // Capture the game's View/Projection matrices before ImGui touches them GameMatrixCapture.CaptureFrame(pDevice); + // ...and AC's 3D view viewport: at AC's UI pass (AcUiPassHook) the viewport is + // full-screen, and the Nav3D markers draw in this one there. + DX9Backend.CaptureSceneViewport(pDevice); // Refresh the player-skill snapshot on AC's main thread (this // EndScene runs on it). The plugin tick is pumped off-thread and @@ -332,6 +320,11 @@ internal static class EngineFrameController // is the dump-verified 0x0067E779 READ-AV when done on the pump thread. // Sampled every frame (positions are volatile), zero-alloc. Compatibility.ClientObjectHooks.PrefetchPositions(); + // Refresh the cached player id every frame (unthrottled: the native leaf is + // two loads) and the other small main-thread snapshots (cast gate, pose, + // ...). Off-thread callers are served from these instead of reading AC + // memory from the pump thread. Also runs from the Client::UseTime drain. + Compatibility.MainThreadSnapshots.Tick(); // Same main-thread guard: snapshot XP/luminance/deaths/vitae (main-thread-only // Inq* reads) so the GetEngineStatusJson host bridge can serve them off-thread (throttled). Compatibility.ClientObjectHooks.PrefetchPlayerStats(); @@ -357,24 +350,13 @@ internal static class EngineFrameController try { Compatibility.AcMainThreadQueue.Drain(); } catch (Exception ex) { RynthLog.Plugin($"AcMainThreadQueue.Drain threw {ex.GetType().Name}: {ex.Message}"); } - // Nav3DRenderInjector fires mid-frame at the 3D→UI ZENABLE - // transition — that's the only pipeline position where markers - // can render BEHIND AC's UI (the UI pass draws after ZENABLE - // turns off, and the end-of-frame fallback is past it entirely). - // - // The injector accumulates state per-frame via DrawIndexedPrimitive - // callbacks during AC's draws (which fire before this EndScene), - // so by the time we check RenderedThisFrame here, its decision - // for the current frame is final. ResetFrame at the END of - // OnEndScene primes it for the next frame's accumulation. - // - // Historically the engine forced the end-of-frame fallback ONLY - // because the injector's hit-rate varied across motion, producing - // flicker when some frames painted at the 3D→UI boundary and - // others at end-of-frame. We accept that risk here: the user - // wants markers behind the UI, and a frame the injector misses - // simply doesn't render markers (less jarring than a Z-order flip). - bool nav3DAlreadyRendered = D3D9.Nav3DRenderInjector.RenderedThisFrame; + // The world overlays (Nav3D markers, nameplates, combat text) normally drew + // mid-frame, before this EndScene: at the start of AC's 2D UI pass + // (AcUiPassHook), or without that hook at the 3D->UI ZENABLE transition + // (Nav3DRenderInjector's DIP hook). A frame where neither fired (portal space, + // a loading screen, no AC UI) draws them at EndScene instead - see + // Nav3DRenderInjector.PresentAtEndScene below. ResetFrame at the END of + // OnEndScene primes the next frame. // Publish the live device pointer for the off-render-thread plugin // pump (see PumpPluginFrame). The D3D9 device is a stable COM @@ -396,28 +378,46 @@ internal static class EngineFrameController // calls it at all. // ── ImGui-gated work ───────────────────────────────────────── - if (!_loggedImGuiGate) + // The frame is BUILT here and SUBMITTED by RenderDeferredImGui, which + // EndSceneHook calls after the Avalonia quad, so ImGui windows sit above + // the Nav3D fallback, the vital HUD and the Avalonia panels. Input order + // matches: Win32Backend gives ImGui the mouse while it wants it. + bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend; + bool imguiBuilt = false; + long uiTicks = 0; + if (!imguiEnabled) + _imguiIdle = true; // switched off in game: input state resets when it comes back + else { - // Reaching here proves the always-on steps above aren't throwing every frame. - _loggedImGuiGate = true; - RynthLog.Info($"EngineFrameController: reached ImGui gate (EnableImGuiBackend={Plugins.EngineSettings.EnableImGuiBackend}, EnableImGuiShell={Plugins.EngineSettings.EnableImGuiShell}, EnablePluginOverlayWindows={Plugins.EngineSettings.EnablePluginOverlayWindows})."); + long t0 = Stopwatch.GetTimestamp(); + imguiBuilt = BuildImGuiFrame(pDevice); + uiTicks = Stopwatch.GetTimestamp() - t0; } - if (Plugins.EngineSettings.EnableImGuiBackend) - RunImGuiFrame(pDevice); - // Fallback render — only fires when the injector missed this - // frame's 3D→UI transition. _coreInitialized is enough — this - // does not touch font / vertex buffer state. - if (!nav3DAlreadyRendered) - DX9Backend.RenderNav3D(pDevice); + // Fallback: the Nav3D markers and the world overlays built last frame + // (nameplates, combat text), when neither the UI pass nor the transition + // drew them this frame - still under the ImGui panels. No-op when they + // already drew (one per-frame flag for every path; UnderUiLayer presents + // a list once). _coreInitialized is enough for the markers. + D3D9.Nav3DRenderInjector.PresentAtEndScene(pDevice); - // Custom D3D9 vital HUD (Health/Stamina/Mana). Always-on (independent - // of EnableImGuiBackend) so it shows even in Avalonia-only mode; drawn - // last so it sits on top of the world + AC UI. Reads the vitals - // snapshot maintained on this same (AC main) thread and does its own - // device state save/restore. No-op until vitals are seeded. - if (Plugins.EngineSettings.DrawCustomVitalBars) - D3D9.VitalHud.Draw(pDevice); + if (imguiEnabled) + { + long t0 = Stopwatch.GetTimestamp(); + // Popped-out panels: their own contexts, windows and render targets. + if (_imguiInitialized) + ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive); + long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0); + if (imguiBuilt) + { + _deferredUiTicks = ticks; + _deferredSubmitDevice = pDevice; + } + else + { + UiFrameStats.Record(ticks); + } + } } catch (Exception ex) { @@ -440,9 +440,34 @@ internal static class EngineFrameController // never fires again — every subsequent frame falls back to the // end-of-frame draw (which paints over the UI). D3D9.Nav3DRenderInjector.ResetFrame(); + // The DIP hook only runs while the transition path is in use (no UI-pass + // hook, or /rc worldlayer transition); switched here, between frames. + try { D3D9.Nav3DRenderInjector.SyncHookState(); } + catch (Exception ex) { RynthLog.D3D9($"Nav3DRenderInjector.SyncHookState threw {ex.GetType().Name}: {ex.Message}"); } + // What this frame built for the world overlays is presented next frame. + UnderUiLayer.EndFrame(); } } + /// <summary> + /// The main-thread prefetches of the always-on pipeline above, for a client without + /// the EndScene hook (Decal in the process): called from the Client::UseTime detour + /// (AC's main thread) once GameTickHooks.HeadlessPrefetch is set. Same calls, same + /// order, each throttled and main-thread-gated internally. The EndScene path doesn't + /// use this (it runs the calls inline, unchanged). + /// </summary> + internal static void RunHeadlessPrefetch() + { + Compatibility.ClientObjectHooks.PrefetchPlayerSkills(); + Compatibility.ClientObjectHooks.PrefetchKnownSpells(); + Compatibility.ClientObjectHooks.PrefetchAttackable(); + Compatibility.ClientObjectHooks.PrefetchObjectIdentity(); + Compatibility.ClientObjectHooks.PrefetchPositions(); + Compatibility.ClientObjectHooks.PrefetchPlayerStats(); + try { Plugins.PluginManager.TrySeedLiveObjectsFromCObjectMaintOnce(); } + catch (Exception ex) { RynthLog.Plugin($"CObjectMaint seed threw {ex.GetType().Name}: {ex.Message}"); } + } + /// <summary> /// The plugin lifecycle/tick work that used to run inline in /// <see cref="OnEndScene"/>. Driven by the dedicated managed plugin pump @@ -467,15 +492,40 @@ internal static class EngineFrameController return; // never re-enter PluginManager from two stacks try { + // Plugins only get the ImGui context when they may draw with it: the + // ImGui shell (EnableImGuiShell, FORCE-gated) or their own overlay + // windows (EnablePluginOverlayWindows: RynthAi's ILT Hub, HUDs, Item + // Info; RynthPluginRenderOverlay). RynthAi only reads the context for + // those windows, so this does not switch it into a legacy-ImGui setup. + bool pluginsDraw = Plugins.EngineSettings.EnableImGuiShell + || (Plugins.EngineSettings.EnablePluginOverlayWindows && Plugins.EngineSettings.EnableImGuiBackend); + // _context is written by the render thread (Init); this is the pump thread. + IntPtr pluginContext = pluginsDraw ? System.Threading.Volatile.Read(ref _context) : IntPtr.Zero; if (!_pluginsInitialized) { + // The plugin host copies the context once at init, so wait for the + // render path's ImGui init (first ImGui frame) rather than hand over + // zero for the whole session. Bounded: a failed or stalled ImGui init + // must not hold plugins (and the bot) back. + if (pluginsDraw && pluginContext == IntPtr.Zero && !_imguiInitFailed + && ++_pluginInitContextWaits <= PluginInitContextMaxWaits) + return; + if (pluginsDraw && pluginContext == IntPtr.Zero) + RynthLog.Warn($"EngineFrameController: plugins initialised without an ImGui context (imguiInitFailed={_imguiInitFailed}, waits={_pluginInitContextWaits}) - plugin overlay windows will not draw this session."); _pluginsInitialized = true; - PluginManager.InitPlugins(_context, device, _gameHwnd); + PluginManager.InitPlugins(pluginContext, device, _gameHwnd); } - PluginManager.ProcessPendingActions(_context, device, _gameHwnd); + // Decal bridge mode with the in-game renderer (DecalInGameImGui): chat and + // chat-bar lines come from the bridge. One flag check in every other client. + if (Compatibility.DecalBridgeHost.Active) + Compatibility.DecalBridgeHost.Drain(); + PluginManager.ProcessPendingActions(pluginContext, device, _gameHwnd); PluginManager.FlushPendingDeletes(); // closes the create→delete race window PluginManager.TickAll(); + // Panel data: plugin exports for the UI are called here, on the same + // thread as the plugin tick, and published as immutable snapshots. + UI.Data.UiDataHub.Step(); } catch (Exception ex) { @@ -487,50 +537,145 @@ internal static class EngineFrameController } } - /// <summary> - /// Runs the ImGui-specific portion of the per-frame pipeline: - /// backend NewFrame plumbing, ImGui frame open/close, RynthCore shell + - /// plugin RenderAll, draw-data submission, capture flag update, and the - /// multi-viewport platform pump. Bypassed entirely when - /// EngineSettings.EnableImGuiBackend is false. - /// </summary> - private static void RunImGuiFrame(IntPtr pDevice) + /// <summary>True when anything ImGui should be drawn this frame.</summary> + private static bool HasImGuiContent() { - if (_imguiInitFailed) + if (Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled) return true; + if (!PanelsLive) return false; + ImGuiPanelHost.RestoreOnce(); + return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame + || PluginOverlayWindowsLive; + } + + /// <summary> + /// In the world, with the shell off, and some loaded plugin exports + /// RynthPluginRenderOverlay: its windows need a frame every frame. + /// </summary> + private static bool PluginOverlayWindowsLive => + PanelsLive && Plugins.EngineSettings.EnablePluginOverlayWindows && PluginManager.HasOverlayPlugins; + + /// <summary> + /// Panel faces show only in the world, like the Avalonia overlay (hidden + /// between characters, not closed). + /// </summary> + private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete; + + /// <summary>DPI scale the fonts and style were built for (see Init).</summary> + private static float _uiScale = 1f; + + /// <summary>The scale the fonts and style were built for.</summary> + internal static float FontScale => _uiScale; + + /// <summary>A popped-out panel was clicked: the main context's text edit ends next frame. AC thread.</summary> + internal static void DropMainTextFocus() => _dropImGuiTextFocus = true; + + // ── Diagnostics (/rc imgui diag) ───────────────────────────────── + private static long _framesBuilt; + private static System.Numerics.Vector2 _lastDisplaySize; + + /// <summary>One line per fact about the ImGui layer's state. Game thread (reads plain fields).</summary> + internal static System.Collections.Generic.List<string> DescribeState() + { + var lines = new System.Collections.Generic.List<string> { - if (!_loggedInitFailedSkip) - { - _loggedInitFailedSkip = true; - RynthLog.Error("EngineFrameController: ImGui init failed earlier - RunImGuiFrame is a no-op for this session (no plugin overlay windows)."); - } - return; - } + $"layer={(Plugins.EngineSettings.EnableImGuiBackend ? "on" : "off")} initialized={_imguiInitialized} initFailed={_imguiInitFailed} selfTest={ImGuiSelfTest.LastResult}", + $"inWorld={PanelsLive} content={HasImGuiContentNoRestore()} idle={_imguiIdle} framesBuilt={_framesBuilt} uiScale={_uiScale:0.##} avaloniaScale={UI.AvaloniaOverlay.InputScale:0.##} display={_lastDisplaySize.X:0}x{_lastDisplaySize.Y:0}", + DX9Backend.DescribeLastFrame(), + UnderUiLayer.Describe(), + D3D9.Nav3DRenderInjector.Describe(), + $"capture: {Win32Backend.DescribeCapture()}", + }; + lines.AddRange(ImGuiPopOuts.Describe()); + return lines; + } + + private static bool HasImGuiContentNoRestore() => + Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame)) + || PluginOverlayWindowsLive; + + // Keyboard owner between the stacks (plan §3.2 d): whichever side started + // text entry most recently keeps the keyboard. + private static bool _prevImGuiText, _prevAvaloniaText, _dropImGuiTextFocus; + + /// <summary>True while frames are being skipped because nothing ImGui is open.</summary> + private static bool _imguiIdle = true; + + /// <summary> + /// Builds the ImGui frame (NewFrame ... Render) and publishes the capture + /// flags. Returns true when there is draw data for <see cref="SubmitImGuiFrame"/>. + /// Only called while EngineSettings.EnableImGuiBackend is true. + /// + /// Early-out: with no ImGui content there is no ImGui frame at all. Queued + /// input is dropped (nothing would drain it) and capture flags are cleared, + /// so the idle cost is one GetClientRect. + /// </summary> + private static bool BuildImGuiFrame(IntPtr pDevice) + { + if (_imguiInitFailed) return false; if (!_imguiInitialized) { + // Initialised as soon as the backend is enabled (not lazily on first + // content), so the cimgui self-test result is in the log at startup. if (!Init(pDevice)) { _imguiInitFailed = true; RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session."); - return; + return false; } } + Win32Backend.UpdateClientMetrics(out int clientW, out int clientH); + + // Monster nameplates: pick the monsters (throttled) before deciding + // whether there is a frame to build, so plates alone can ask for one. + Hud.MonsterHud.Update(PanelsLive); + + if (!HasImGuiContent()) + { + _imguiIdle = true; + Win32Backend.DiscardQueuedInput(); + Win32Backend.ClearCaptureFlags(); + ImGuiTextFocus.ClearMain(); + return false; + } + IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext(); ImGuiNET.ImGui.SetCurrentContext(_context); bool frameStarted = false; bool frameEnded = false; - - // A frame that throws before Render must not resubmit last frame's draw data. - _deferredDrawDevice = IntPtr.Zero; - try { - _frameCount++; - DX9Backend.NewFrame(); - Win32Backend.NewFrame(); - ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + long now = Stopwatch.GetTimestamp(); + if (_imguiIdle) + { + // Resuming: keys/buttons released while idle must not read as held, + // and the idle gap must not become one huge DeltaTime. + _imguiIdle = false; + Win32Backend.ResetImGuiInputState(io); + _lastFrameTicks = now; + } + + _frameCount++; + // A panel's text size changed: re-bake the fonts (only the sizes in + // use) and replace the font texture, between frames. + // The new atlas is baked on a worker (ImGuiFonts.PumpRebuild), once per run of + // changes (RequestRebuild debounces); here it is swapped in and its texture made. + DX9Backend.ReleaseRetiredFontTexture(); // the texture a rebuild replaced last frame + long rebuildStart = Stopwatch.GetTimestamp(); + if (ImGuiFonts.PumpRebuild(io, _uiScale, out string rebuilt)) + { + DX9Backend.RebuildFontTexture(pDevice); + double rebuildMs = (Stopwatch.GetTimestamp() - rebuildStart) * 1000.0 / Stopwatch.Frequency; + RynthLog.UI($"ImGuiFonts: text size change: {rebuilt}; render thread {rebuildMs:0.0} ms (swap + texture)."); + } + // Script window icons decoded since the last frame become textures, and the least + // recently drawn go, before anything draws (no draw list points at them any more). + ScriptIcons.BeginFrame(pDevice); + RetailSprites.BeginFrame(pDevice); // retail UI pictures decoded since the last frame (kept, never evicted) + DX9Backend.NewFrame(); + Win32Backend.NewFrame(clientW, clientH); // Fallback: if Win32Backend could not determine display size, read from the D3D9 viewport. if (io.DisplaySize.X <= 1 || io.DisplaySize.Y <= 1) @@ -540,43 +685,24 @@ internal static class EngineFrameController io.DisplaySize = new System.Numerics.Vector2(vpW, vpH); } - long now = Stopwatch.GetTimestamp(); float dt = (float)(now - _lastFrameTicks) / Stopwatch.Frequency; _lastFrameTicks = now; io.DeltaTime = dt > 0f ? dt : 1f / 60f; - // With ViewportsEnable on, ImGui routes mouse and window positions in - // absolute screen coords. The main viewport's Pos must equal the game - // client's screen origin so clicks over the main viewport map to the - // correct windows, and popped-out viewports share a coord system with - // the main one. - if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0) - { - int screenX = 0, screenY = 0; - if (_gameHwnd != IntPtr.Zero) - { - ClientPoint p = new ClientPoint { X = 0, Y = 0 }; - if (ClientToScreen(_gameHwnd, ref p)) { screenX = p.X; screenY = p.Y; } - } - ImGuiViewportPtr mainVp = ImGuiNET.ImGui.GetMainViewport(); - mainVp.Pos = new System.Numerics.Vector2(screenX, screenY); - mainVp.Size = io.DisplaySize; - mainVp.WorkPos = new System.Numerics.Vector2(screenX, screenY); - mainVp.WorkSize = io.DisplaySize; - } - ImGuiNET.ImGui.NewFrame(); frameStarted = true; - if (!_loggedFirstFrame) + // Before any window: a drag from a popped-out Inventory or AC's inventory becomes + // a payload the client's drop targets (Mini Remote slots) see this frame. + ItemDragBridge.SubmitMainFrame(io); + ImGuiTextFocus.BeginFrame(); + if (_dropImGuiTextFocus) { - _loggedFirstFrame = true; - RynthLog.Info($"EngineFrameController: first ImGui frame started (frame={_frameCount}, display={io.DisplaySize.X:0}x{io.DisplaySize.Y:0})."); + // An Avalonia TextBox took the keyboard: end ImGui's text edit. + _dropImGuiTextFocus = false; + ImGuiNET.ImGui.SetWindowFocus(null); } - - // EnableImGuiShell gates the in-AC ImGui surface as a whole: both the - // RynthCore overlay bar and any plugin-drawn ImGui windows. Plugins - // still load, init, and tick when this is off — they just don't - // draw, so Avalonia panels can drive them via the plugin's C exports. + // EnableImGuiShell gates the old diagnostic shell and plugin-drawn + // ImGui windows (plugin code on AC's thread: FORCE-gated, stays off). int branch; if (Plugins.EngineSettings.EnableImGuiShell) { @@ -584,11 +710,11 @@ internal static class EngineFrameController RynthCoreShell.Render(_frameCount); PluginManager.RenderAll(); } - else if (Plugins.EngineSettings.EnablePluginOverlayWindows) + else if (PluginOverlayWindowsLive) { branch = 2; - // Avalonia mode: only the opt-in extra windows (RynthPluginRenderOverlay), - // never the plugins' full ImGui UIs that Avalonia panels already cover. + // Only the opt-in extra windows (RynthPluginRenderOverlay), never the + // plugins' full ImGui UIs. PluginManager.RenderOverlayAll(); } else @@ -598,39 +724,45 @@ internal static class EngineFrameController if (branch != _loggedBranch) { _loggedBranch = branch; - RynthLog.Info($"EngineFrameController: ImGui branch = {(branch == 1 ? "shell (RenderAll)" : branch == 2 ? "overlay windows (RenderOverlayAll)" : "none (shell and overlay windows both off)")}."); + RynthLog.Info($"EngineFrameController: ImGui plugin branch = {(branch == 1 ? "shell (RenderAll)" : branch == 2 ? "overlay windows (RenderOverlayAll)" : "none")}."); } - - // A plugin that threw mid-window leaves scopes open; EndFrame would assert - // with a modal dialog on AC's main thread. - if (branch != 0) ImGuiStackRecovery.RecoverBeforeEndFrame(); - - bool captureMouse = - ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow) || - ImGuiNET.ImGui.IsAnyItemActive(); - bool captureKeyboard = ImGuiNET.ImGui.IsAnyItemActive(); + if (PanelsLive) + { + // World overlays: built into UnderUiLayer's list, drawn next frame at + // AC's 3D->UI transition (under AC's UI and every panel), no input. + Hud.MonsterHud.Draw(_uiScale); + if (ImGuiBar.Visible) + ImGuiBar.Draw(_uiScale); + ImGuiPanelHost.DrawAll(_uiScale); + ImGuiBar.SyncPopOut(_uiScale); + } + if (ImGuiFontTest.Enabled) + ImGuiFontTest.Draw(_uiScale); ImGuiNET.ImGui.EndFrame(); frameEnded = true; ImGuiNET.ImGui.Render(); - Win32Backend.UpdateCaptureFlags(captureMouse, captureKeyboard); + ImGuiAssertLog.Poll(); + _framesBuilt++; + _lastDisplaySize = io.DisplaySize; - ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData(); - - // Submission is deferred to RenderDeferredImGui, which EndSceneHook calls - // AFTER OverlayTextureRenderer has blitted the Avalonia layer, so ImGui - // windows (plugin overlay windows such as the ILT Hub) sit on top of the - // Avalonia panels. The draw data stays valid until the next NewFrame. - _deferredDrawData = drawData; - _deferredDrawDevice = pDevice; - _framesCompleted++; - LogHeartbeatIfDue(drawData); - - if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0) - { - ImGuiNET.ImGui.UpdatePlatformWindows(); - ImGuiNET.ImGui.RenderPlatformWindowsDefault(); - } + // io.WantCaptureMouse already applies ImGui's own button-ownership + // rule; io.WantTextInput is true only while a text field is edited. + // MonsterHud.WantsMouse: the cursor is on a clickable nameplate (or a + // press that began on one is held), so that click is the plate's. + // Keyboard: io.WantTextInput lags the box by a frame (ImGui publishes it from + // the previous frame's widgets), so a box that went active this frame counts + // too (ImGuiTextFocus): the keys typed right after the click stay out of AC. + ImGuiTextFocus.EndMainFrame(io.WantTextInput); + bool typing = io.WantTextInput || ImGuiTextFocus.MainBoxActive; + Win32Backend.UpdateCaptureFlags(io.WantCaptureMouse || Hud.MonsterHud.WantsMouse, typing); + // The UI is released (Insert): no text box keeps the keyboard. Keys are not + // gated by the toggle any more (Win32Backend.UpdateCaptureFlags), so the edit + // ends instead and the next keys go to the game. + if (typing && !Win32Backend.UiCaptureEnabled) + _dropImGuiTextFocus = true; + ArbitrateTextFocus(io.WantTextInput); + return true; } catch (Exception ex) { @@ -644,14 +776,10 @@ internal static class EngineFrameController { } - _imguiErrorCount++; - long errNow = Environment.TickCount64; - if (_imguiErrorCount == 1) - RynthLog.Error($"EngineFrameController: ImGui frame error at frame {_frameCount} (frameStarted={frameStarted}): {ex}"); - else if (errNow >= _nextImGuiErrorLogAt) - RynthLog.Error($"EngineFrameController: ImGui frame errors so far={_imguiErrorCount}, latest {ex.GetType().Name}: {ex.Message}"); - if (errNow >= _nextImGuiErrorLogAt) - _nextImGuiErrorLogAt = errNow + HeartbeatIntervalMs; + Win32Backend.ClearCaptureFlags(); + ImGuiTextFocus.ClearMain(); + RynthLog.Info($"EngineFrameController: frame {_frameCount} ImGui error: {ex.GetType().Name}: {ex.Message}"); + return false; } finally { @@ -659,34 +787,62 @@ internal static class EngineFrameController } } + private static void ArbitrateTextFocus(bool imguiText) + { + bool avaloniaText = Win32Backend.AvaloniaTextInputActive; + if (imguiText && !_prevImGuiText && avaloniaText) + { + // An ImGui field just started typing: Avalonia gives up the keyboard. + Win32Backend.AvaloniaTextInputActive = false; + UI.AvaloniaOverlay.ClearTextFocus(); + avaloniaText = false; + } + else if (avaloniaText && !_prevAvaloniaText && imguiText) + { + _dropImGuiTextFocus = true; + } + _prevImGuiText = imguiText; + _prevAvaloniaText = avaloniaText; + } + /// <summary> /// Submits this frame's ImGui draw data. EndSceneHook calls it after - /// OverlayTextureRenderer.Render so ImGui windows draw on top of the Avalonia - /// layer. Runs whether or not the Avalonia blit ran (character select, Avalonia - /// off), and is a no-op when RunImGuiFrame produced nothing this frame. + /// OverlayTextureRenderer.Render so ImGui windows draw on top of the Avalonia layer. + /// Runs whether or not the Avalonia blit ran (character select, Avalonia off), and is + /// a no-op when <see cref="OnEndScene"/> built nothing this frame. Never throws. /// </summary> public static void RenderDeferredImGui() { - IntPtr device = _deferredDrawDevice; + IntPtr device = _deferredSubmitDevice; if (device == IntPtr.Zero) return; - _deferredDrawDevice = IntPtr.Zero; // one submission per frame, even if it throws + _deferredSubmitDevice = IntPtr.Zero; // one submission per frame, even if it throws + long t0 = Stopwatch.GetTimestamp(); + SubmitImGuiFrame(device); + UiFrameStats.Record(_deferredUiTicks + (Stopwatch.GetTimestamp() - t0)); + } + + /// <summary>Draws the frame <see cref="BuildImGuiFrame"/> produced.</summary> + private static void SubmitImGuiFrame(IntPtr pDevice) + { IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext(); ImGuiNET.ImGui.SetCurrentContext(_context); try { - DX9Backend.RenderDrawData(_deferredDrawData, device); + ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData(); + DX9Backend.RenderDrawData(drawData, pDevice); _drawSubmits++; if (!_loggedFirstSubmit) { _loggedFirstSubmit = true; - RynthLog.Info("EngineFrameController: first deferred ImGui draw submitted (after the Avalonia layer)."); + RynthLog.Info("EngineFrameController: first ImGui draw submitted."); } + LogHeartbeatIfDue(drawData); } catch (Exception ex) { - RynthLog.Info($"EngineFrameController: frame {_frameCount} deferred ImGui draw error: {ex.GetType().Name}: {ex.Message}"); + RynthLog.Info($"EngineFrameController: frame {_frameCount} ImGui submit error: {ex.GetType().Name}: {ex.Message}"); } finally { @@ -695,7 +851,7 @@ internal static class EngineFrameController } /// <summary> - /// Every 30 s: completed ImGui frames, deferred submits, draw list / vertex counts of the + /// Every 30 s: built ImGui frames, submits, draw list / vertex counts of the /// latest frame and the overlay-window stats from PluginManager. Zero draw lists means no /// ImGui window was drawn that frame. One string per interval; no per-frame allocation. /// </summary> @@ -714,7 +870,7 @@ internal static class EngineFrameController byte* p = (byte*)drawData.NativePtr; if (p != null) { lists = *(int*)(p + 4); vertices = *(int*)(p + 12); } } - RynthLog.Info($"EngineFrameController: ImGui heartbeat frames={_framesCompleted} submits={_drawSubmits} lastFrame drawLists={lists} vertices={vertices} {PluginManager.DescribeOverlayState()}."); + RynthLog.Info($"EngineFrameController: ImGui heartbeat frames={_framesBuilt} submits={_drawSubmits} lastFrame drawLists={lists} vertices={vertices} {PluginManager.DescribeOverlayState()}."); } internal static IntPtr FindGameWindow() diff --git a/src/RynthCore.Engine/ImGui/ImGuiAssertLog.cs b/src/RynthCore.Engine/ImGui/ImGuiAssertLog.cs new file mode 100644 index 0000000..ae4b6d5 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ImGuiAssertLog.cs @@ -0,0 +1,74 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ImGuiAssertLog.cs +// Surfaces Dear ImGui's soft asserts in the engine log. +// +// Our cimgui build routes IM_ASSERT into a native ring buffer instead of +// aborting (native/cimgui/rynth_imconfig.h). Poll() runs on AC's thread after +// each ImGui frame: it reads one int, and only formats and logs when new +// failures appeared. The first MaxLoggedInFull are logged individually; after +// that a count is logged at most once a minute so a per-frame assert can't +// flood the log. +// ============================================================================ + +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static unsafe class ImGuiAssertLog +{ + private const int MaxLoggedInFull = 50; + private const int RingSlots = 16; // kAssertSlots in rynth_cimgui_ext.cpp + + private static delegate* unmanaged[Cdecl]<int> _getCount; + private static delegate* unmanaged[Cdecl]<int, byte*, int, int> _getText; + private static int _seen; + private static int _loggedInFull; + private static int _suppressed; + private static long _lastSummaryTicks; + + /// <summary>Resolves the ring-buffer exports. Called by ImGuiSelfTest once the build is verified.</summary> + public static void Bind(IntPtr cimguiModule) + { + if (NativeLibrary.TryGetExport(cimguiModule, "RynthImGui_GetAssertCount", out IntPtr count) && + NativeLibrary.TryGetExport(cimguiModule, "RynthImGui_GetAssertText", out IntPtr text)) + { + _getCount = (delegate* unmanaged[Cdecl]<int>)count; + _getText = (delegate* unmanaged[Cdecl]<int, byte*, int, int>)text; + // Asserts from an earlier engine generation (the DLL outlives RL) are not ours to report. + _seen = _getCount(); + } + } + + public static void Poll() + { + if (_getCount == null) return; + int count = _getCount(); + if (count == _seen) return; + + int first = Math.Max(_seen, count - RingSlots); + _suppressed += first - _seen; // overwritten before we could read them + byte* buf = stackalloc byte[256]; + for (int i = first; i < count; i++) + { + if (_loggedInFull >= MaxLoggedInFull) { _suppressed++; continue; } + int len = _getText(i, buf, 256); + if (len < 0) { _suppressed++; continue; } + _loggedInFull++; + RynthLog.UI($"ImGui assert #{i + 1}: {Marshal.PtrToStringAnsi((IntPtr)buf, len)}"); + } + _seen = count; + + if (_suppressed > 0) + { + long now = Stopwatch.GetTimestamp(); + if (now - _lastSummaryTicks >= Stopwatch.Frequency * 60) + { + RynthLog.UI($"ImGui asserts: {_suppressed} more not logged individually ({count} total this load)."); + _suppressed = 0; + _lastSummaryTicks = now; + } + } + } +} diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs new file mode 100644 index 0000000..b4da640 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -0,0 +1,448 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ImGuiBar.cs +// The overlay bar's ImGui face (docs/IMGUI_PARITY_PLAN.md §2.0). +// +// Same content as the Avalonia bar, as square Phosphor icon buttons with +// the names in tooltips: the grip (RC: build stamp tooltip), one button per +// registered panel except the ones the RynthAi launcher opens (PanelIcons; +// an unknown panel shows its first letter), reload (RL) and pop out. +// Dragging the grip moves the bar; the position is the shared bar= row in +// panel_state.txt. Right-click a panel button (or the grip for the bar +// itself) to choose which face shows it docked. Pop out moves the ImGui bar +// into its own window (ImGuiPopOuts, sized to its content; dock back +// returns it); a bar whose face is Avalonia/Both still pops out as the +// Avalonia bar. +// +// Face key "__bar" in panel_faces.txt; code default Avalonia. While the ImGui +// bar shows, the docked Avalonia bar is hidden and takes no clicks +// (AvaloniaOverlay.DockedBarSuppressed). AC thread except where noted. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Threading; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.ScriptWindows; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class ImGuiBar +{ + public const string FaceKey = "__bar"; + + // Opened from the RynthAi launcher, not the bar (AvaloniaOverlay.BuildRoot). Lua has + // its own bar button since it became the RynthLua plugin. "Monsters" (retired 2026-10-01, + // still registered by EntryPoint) must never get a button: PanelRouter sends it to Damage. + private static readonly HashSet<string> LauncherOnly = new(StringComparer.OrdinalIgnoreCase) + { "Monsters", "Damage", "Settings", "Nav", "Meta", "Items" }; + + private static readonly PanelFace[] Faces = { PanelFace.Avalonia, PanelFace.ImGui, PanelFace.Both }; + private static readonly string[] FaceNames = { "Avalonia", "ImGui", "Both (side by side)" }; + + private sealed record ButtonInfo(string Title, string Id, string PopupId, string Icon, bool Letter, string Tooltip, + bool ImGuiOnly = false); + + // Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button. + private static readonly string[] ImGuiOnlyBarPanels = { Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title }; + + // Known panels' icons (DrakBot's where the same window exists); others show their first letter. + private static readonly Dictionary<string, string> PanelIcons = new(StringComparer.OrdinalIgnoreCase) + { + ["RynthAi"] = PhosphorIcons.Robot, + ["Chat"] = PhosphorIcons.ChatCircleText, + ["ChatFilters"] = PhosphorIcons.Funnel, + ["Radar"] = PhosphorIcons.Compass, + ["Vision"] = PhosphorIcons.Eye, + ["Nav"] = PhosphorIcons.MapTrifold, + ["RynthNav"] = PhosphorIcons.NavigationArrow, + ["Tracker"] = PhosphorIcons.ChartLineUp, + ["Lua"] = PhosphorIcons.FileCode, + ["Settings"] = PhosphorIcons.Gear, + ["Damage"] = PhosphorIcons.ChartBar, + ["Meta"] = PhosphorIcons.ListChecks, + ["Items"] = PhosphorIcons.Backpack, + ["Loot Editor"] = PhosphorIcons.TreasureChest, + ["Skills"] = PhosphorIcons.GraduationCap, + ["Sense"] = PhosphorIcons.Binoculars, + ["Status"] = PhosphorIcons.Info, + ["Inventory"] = PhosphorIcons.Package, // not Backpack: the dashboard's Items launcher has that + ["Log"] = PhosphorIcons.TerminalWindow, + }; + + /// <summary>A panel's bar icon: its Phosphor icon, else its first letter (letter = true).</summary> + internal static string IconFor(string title, out bool letter) + { + letter = !PanelIcons.TryGetValue(title, out string? icon); + if (!letter) return icon!; + foreach (char c in title) + if (char.IsLetterOrDigit(c)) return char.ToUpperInvariant(c).ToString(); + return "?"; + } + + // Square buttons, logical px (x the DPI scale). + private const float ButtonSize = 20f, ButtonGap = 3f; + + private static ButtonInfo[]? _buttons; + private static string _tooltip = ""; + private static bool _placed; + private static Vector2 _pos, _persistedPos; + + private const string PopOutTitle = "__bar"; + // Popped out (the ImGui bar in its own window). Read from panel_state once, + // then kept here so a switch shows at once (the file is written in the background). + private static bool? _floating; + private static bool Floating => _floating ??= PanelStateStore.BarFloating; + + /// <summary>True when the ImGui bar is popped out into its own window.</summary> + public static bool PoppedOut => ResolveFace() == PanelFace.ImGui && Floating; + + /// <summary>The bar's docked face. Any thread.</summary> + public static PanelFace ResolveFace() + { + if (!Plugins.EngineSettings.EnableImGuiBackend) return PanelFace.Avalonia; + if (!Plugins.EngineSettings.EnableAvaloniaOverlay) return PanelFace.ImGui; + return PanelFaceStore.TryGet(FaceKey, out PanelFace f) ? f : PanelFace.ImGui; + } + + /// <summary> + /// Shows/hides the docked Avalonia bar to match the bar's face. Call at + /// init and whenever the face or the ImGui layer changes. Any thread. + /// </summary> + public static void ApplyFace() + { + AvaloniaOverlay.SetDockedBarSuppressed(ResolveFace() == PanelFace.ImGui); + _placed = false; // re-read the shared position next frame + } + + /// <summary>True when the ImGui bar should draw (docked face ImGui/Both, not popped out).</summary> + public static bool Visible => ResolveFace() != PanelFace.Avalonia && !Floating; + + /// <summary> + /// Opens or closes the bar's own window to match <see cref="PoppedOut"/>. AC + /// thread, in the world, with the main context current (after the panels). + /// </summary> + public static void SyncPopOut(float s) + { + bool have = ImGuiPopOuts.IsPopped(PopOutTitle); + if (PoppedOut && !have) + { + EnsureButtons(); + var saved = PanelStateStore.BarFloatingPosition; + Vector2 at = saved.HasValue + ? new Vector2((float)saved.Value.Left, (float)saved.Value.Top) + : ImGuiPopOuts.ClientOriginOnScreen() + _pos; + ImGuiPopOuts.Open(PopOutTitle, (int)at.X, (int)at.Y, (int)(400 * s), (int)(28 * s), 0, 0, s, + draw: DrawPopped, + onMoved: static (x, y) => UiBackgroundWriter.Enqueue("persist bar", () => PanelStateStore.SetBarFloatingState(true, x, y)), + sizeToContent: true); + } + else if (!PoppedOut && have) + { + ImGuiPopOuts.Close(PopOutTitle); + } + } + + /// <summary> + /// Pops the ImGui bar out into its own window (at the docked bar's screen + /// spot) or docks it back where it was docked. The window opens/closes on + /// the next frame (SyncPopOut). Any thread. + /// </summary> + public static void SetPoppedOut(bool popped) + { + if (popped == Floating) return; + _floating = popped; + if (popped) + { + Vector2 screen = ImGuiPopOuts.ClientOriginOnScreen() + _pos; + UiBackgroundWriter.Enqueue("pop out bar", () => PanelStateStore.SetBarFloatingState(true, screen.X, screen.Y)); + } + else + { + _placed = false; // back where it was docked (bar= row); the popped-out spot is kept + var at = PanelStateStore.BarFloatingPosition ?? (0, 0); + UiBackgroundWriter.Enqueue("dock bar", () => PanelStateStore.SetBarFloatingState(false, at.Item1, at.Item2)); + } + } + + /// <summary>The bar in its own window: the same content at the pop-out's panel origin, sized to fit. AC thread.</summary> + private static void DrawPopped(float s, Vector2 display) + { + EnsureButtons(); + float place = AvaloniaOverlay.InputScale > 0 ? AvaloniaOverlay.InputScale : 1f; + ImGuiNET.ImGui.SetNextWindowPos(ImGuiPopOuts.PanelOrigin, ImGuiCond.Always); + PushBarWindowStyle(s); + ImGuiNET.ImGui.Begin("##rc_bar", BarFlags); + try + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + DrawContent(s, place, popped: true); + ImGuiNET.ImGui.PopFont(); + // Not on its first frame: an auto-resizing window has no content size yet + // and reports just its padding (8x6), which would shrink the window to it. + if (!ImGuiNET.ImGui.IsWindowAppearing()) + ImGuiPopOuts.ReportContentSize(ImGuiNET.ImGui.GetWindowSize()); + } + finally + { + ImGuiNET.ImGui.End(); + PopBarWindowStyle(); + } + } + + private const ImGuiWindowFlags BarFlags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize + | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoMove + | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoFocusOnAppearing + | ImGuiWindowFlags.NoBringToFrontOnFocus | ImGuiWindowFlags.NoNav; + + private static void PushBarWindowStyle(float s) + { + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 3) * s); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(ButtonGap, ButtonGap) * s); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, RynthTheme.BarRounding); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowMinSize, Vector2.One); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, RynthTheme.BarBackground); + } + + private static void PopBarWindowStyle() + { + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopStyleVar(5); + } + + public static void Draw(float s) + { + EnsureButtons(); + float place = AvaloniaOverlay.InputScale > 0 ? AvaloniaOverlay.InputScale : 1f; + bool both = ResolveFace() == PanelFace.Both; + + if (!_placed) + { + var saved = PanelStateStore.BarPosition; + Vector2 logical = saved.HasValue ? new Vector2((float)saved.Value.Left, (float)saved.Value.Top) : new Vector2(50, 5); + if (both) logical += new Vector2(24, 24); + _pos = _persistedPos = logical * place; + ImGuiNET.ImGui.SetNextWindowPos(_pos, ImGuiCond.Always); + _placed = true; + } + + PushBarWindowStyle(s); + ImGuiNET.ImGui.Begin("##rc_bar", BarFlags); + try + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + DrawContent(s, place, popped: false); + ImGuiNET.ImGui.PopFont(); + } + finally + { + _pos = ImGuiNET.ImGui.GetWindowPos(); + ImGuiNET.ImGui.End(); + PopBarWindowStyle(); + } + + if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && _pos != _persistedPos) + { + _persistedPos = _pos; + Vector2 logical = _pos / place - (both ? new Vector2(24, 24) : Vector2.Zero); + double left = logical.X, top = logical.Y; + UiBackgroundWriter.Enqueue("persist bar", () => PanelStateStore.SetBarPosition(left, top)); + if (!both) AvaloniaOverlay.SyncDockedBarPosition(left, top); + } + } + + private static void DrawContent(float s, float place, bool popped) + { + var square = new Vector2(ButtonSize, ButtonSize) * s; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Ui14); + + // Grip (the RC label's place, in its light green): the bar's drag handle + // (the Avalonia bar drags from its left edge, over the same spot). + Vector2 rcPos = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.InvisibleButton("##bardrag", new Vector2(square.X * 0.8f, square.Y)); + if (popped) + { + // Popped out, the window itself moves (it follows the cursor from here on). + if (ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 2f)) + ImGuiPopOuts.BeginMoveCurrent(); + } + else if (ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 0f)) + { + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + Vector2 size = ImGuiNET.ImGui.GetWindowSize(); + Vector2 next = ImGuiNET.ImGui.GetWindowPos() + ImGuiNET.ImGui.GetIO().MouseDelta; + if (display.X > 1) + next = Vector2.Clamp(next, Vector2.Zero, Vector2.Max(Vector2.Zero, display - size)); + ImGuiNET.ImGui.SetWindowPos(next); + } + ImGuiNET.ImGui.SetItemTooltip(_tooltip); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ImGuiNET.ImGui.OpenPopup("##face_bar"); + PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.DotsSixVertical, rcPos, new Vector2(square.X * 0.8f, square.Y), RynthTheme.RcLabel); + FacePopup("##face_bar", FaceKey, hasImGuiFace: true); + + // Collapse: the bar folds to its grip and this caret. + bool collapsed = RynthAiDashboardState.BarCollapsed; + ImGuiNET.ImGui.SameLine(0, 0); + Vector2 cPos = ImGuiNET.ImGui.GetCursorScreenPos(); + var caretSize = new Vector2(square.X * 0.6f, square.Y); + if (ImGuiNET.ImGui.InvisibleButton("##barcollapse", caretSize)) + RynthAiDashboardState.SetBarCollapsed(!collapsed); + bool caretHot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.SetItemTooltip(collapsed ? "Show the bar" : "Fold the bar to this button"); + PhosphorIcons.DrawCentered(dl, iconFont, collapsed ? PhosphorIcons.CaretRight : PhosphorIcons.CaretLeft, cPos, caretSize, + caretHot ? RynthTheme.RcLabel : 0xFF9A9A9Au); + if (collapsed) return; + + PushBarButtonStyle(s); + ImFontPtr letterFont = ImGuiFonts.Get(UiFont.UiBold11); + foreach (ButtonInfo b in _buttons!) + { + ImGuiNET.ImGui.SameLine(); + if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText)) + PanelRouter.Toggle(b.Title); + ImGuiNET.ImGui.SetItemTooltip(b.Tooltip); + if (b.ImGuiOnly) continue; // no Avalonia face: no face to choose + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ImGuiNET.ImGui.OpenPopup(b.PopupId); + FacePopup(b.PopupId, b.Title, ImGuiPanelHost.HasFace(b.Title)); + } + + // Script windows (decision 2): one button with a menu, only while a ShowInBar + // script window exists. They never get buttons of their own (EnsureButtons + // lists OverlayHost's engine panels only; script windows are dynamic entries). + ScriptBarItem[] scripts = ScriptWindowRegistry.BarItems; + if (scripts.Length > 0) + { + ImGuiNET.ImGui.SameLine(); + if (IconButton("##scripts", iconFont, PhosphorIcons.AppWindow, square, RynthTheme.BarText)) + ImGuiNET.ImGui.OpenPopup("##scripts_menu"); + ImGuiNET.ImGui.SetItemTooltip("Script windows"); + } + + ImGuiNET.ImGui.SameLine(0, 6 * s); + if (IconButton("##reload", iconFont, PhosphorIcons.ArrowsClockwise, square, RynthTheme.ReloadLabel)) + ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null); + ImGuiNET.ImGui.SetItemTooltip("Engine reload (RL) — shut down, FreeLibrary, reload from disk, re-init."); + + if (ResolveFace() == PanelFace.ImGui) + { + ImGuiNET.ImGui.SameLine(); + if (IconButton("##popout", iconFont, popped ? PhosphorIcons.ArrowSquareIn : PhosphorIcons.ArrowSquareOut, square, RynthTheme.PopOutLabel)) + SetPoppedOut(!popped); + ImGuiNET.ImGui.SetItemTooltip(popped ? "Dock the bar back into the game window." : "Pop the bar out into its own floating window."); + } + else if (Plugins.EngineSettings.EnableAvaloniaOverlay) // Avalonia/Both bar: pops out as the Avalonia bar + { + ImGuiNET.ImGui.SameLine(); + if (IconButton("##popout", iconFont, PhosphorIcons.ArrowSquareOut, square, RynthTheme.PopOutLabel)) + { + Vector2 logical = ImGuiNET.ImGui.GetWindowPos() / place; + AvaloniaOverlay.PopOutBarFrom(logical.X, logical.Y); + } + ImGuiNET.ImGui.SetItemTooltip("Pop the bar out into its own floating window."); + } + PopBarButtonStyle(); + + // Drawn after the bar buttons' style is popped, so the menu has the normal look. + ScriptsMenu(scripts); + } + + /// <summary> + /// The Scripts button's popup: the ShowInBar script windows grouped by script, a + /// checkbox item each for open. Toggling tells the owner (Visibility, reason 2). + /// </summary> + private static void ScriptsMenu(ScriptBarItem[] items) + { + if (!ImGuiNET.ImGui.BeginPopup("##scripts_menu")) return; + try + { + if (items.Length == 0) ImGuiNET.ImGui.CloseCurrentPopup(); + uint disabled = ImGuiNET.ImGui.GetColorU32(ImGuiCol.TextDisabled); + foreach (ScriptBarItem item in items) + { + if (item.GroupStart) + { + // A script's own text: never a format string. + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, disabled); + ImGuiNET.ImGui.TextUnformatted(item.Group); + ImGuiNET.ImGui.PopStyleColor(); + } + bool open = ImGuiPanelHost.IsOpen(item.PanelKey); + if (ImGuiNET.ImGui.MenuItem(item.MenuLabel, "", open)) + ScriptWindowRegistry.PlayerSetVisible(item.Window, !open); + } + } + finally + { + ImGuiNET.ImGui.EndPopup(); + } + } + + /// <summary>A square bar button (the bar's button style) with an icon, or a letter, centred on it.</summary> + private static bool IconButton(string id, ImFontPtr font, string icon, Vector2 size, uint color) + { + Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos(); + bool clicked = ImGuiNET.ImGui.Button(id, size); + PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), font, icon, at, size, color); + return clicked; + } + + private static void FacePopup(string popupId, string title, bool hasImGuiFace) + { + if (!ImGuiNET.ImGui.BeginPopup(popupId)) return; + ImGuiNET.ImGui.TextDisabled(title == FaceKey ? "Bar, docked, shows as" : "Docked, shows as"); + PanelFace current = title == FaceKey ? ResolveFace() : PanelRouter.ResolveDockedFace(title); + for (int i = 0; i < Faces.Length; i++) + { + bool enabled = Faces[i] == PanelFace.Avalonia || hasImGuiFace; + if (ImGuiNET.ImGui.MenuItem(FaceNames[i], "", current == Faces[i], enabled)) + PanelRouter.SetDockedFace(title, Faces[i]); + } + if (!hasImGuiFace) + ImGuiNET.ImGui.TextDisabled("(no ImGui version yet)"); + ImGuiNET.ImGui.EndPopup(); + } + + private static void PushBarButtonStyle(float s) + { + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 2f); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, RynthTheme.BarButton); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, RynthTheme.Argb(0xFF2A3850)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonActive, RynthTheme.Argb(0xFF34466A)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, RynthTheme.BarButtonBorder); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, RynthTheme.BarText); + } + + private static void PopBarButtonStyle() + { + ImGuiNET.ImGui.PopStyleColor(5); + ImGuiNET.ImGui.PopStyleVar(3); + } + + private static void EnsureButtons() + { + if (_buttons != null) return; + var list = new List<ButtonInfo>(); + foreach (var (title, _) in OverlayHost.GetPanels()) + if (!LauncherOnly.Contains(title)) + { + string icon = IconFor(title, out bool letter); + list.Add(new ButtonInfo(title, "##bar_" + title, "##face_" + title, icon, letter, + title + "\nRight-click: which face shows it docked.")); + } + foreach (string title in ImGuiOnlyBarPanels) + if (ImGuiPanelHost.HasFace(title) && !LauncherOnly.Contains(title)) + { + string icon = IconFor(title, out bool letter); + list.Add(new ButtonInfo(title, "##bar_" + title, "##face_" + title, icon, letter, title, ImGuiOnly: true)); + } + _buttons = list.ToArray(); + _tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar face."; + } +} diff --git a/src/RynthCore.Engine/ImGui/ImGuiController.cs b/src/RynthCore.Engine/ImGui/ImGuiController.cs deleted file mode 100644 index 8e62807..0000000 --- a/src/RynthCore.Engine/ImGui/ImGuiController.cs +++ /dev/null @@ -1,343 +0,0 @@ -// ============================================================================ -// RynthCore.Engine - ImGui/ImGuiController.cs -// Top-level orchestrator: creates context, initializes backends, -// and drives the NewFrame -> UI -> Render cycle from EndScene. -// ============================================================================ - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using ImGuiNET; -using RynthCore.Engine.D3D9; -using RynthCore.Engine.Plugins; -using RynthCore.Install; - -namespace RynthCore.Engine.ImGuiBackend; - -internal static class ImGuiController -{ - [DllImport("kernel32.dll")] - private static extern uint GetCurrentProcessId(); - - [DllImport("user32.dll")] - private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); - - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); - - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool IsWindowVisible(IntPtr hWnd); - - [DllImport("user32.dll")] - private static extern bool GetClientRect(IntPtr hWnd, out ClientRect lpRect); - - [DllImport("user32.dll")] - private static extern bool ClientToScreen(IntPtr hWnd, ref ClientPoint lpPoint); - - [StructLayout(LayoutKind.Sequential)] - private struct ClientRect { public int Left, Top, Right, Bottom; } - [StructLayout(LayoutKind.Sequential)] - private struct ClientPoint { public int X, Y; } - - private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); - - private static bool _initialized; - private static bool _initFailed; - private static bool _pluginsInitialized; - private static IntPtr _context; - private static IntPtr _gameHwnd; - private static long _lastFrameTicks; - private static int _frameCount; - - public static bool Init(IntPtr pDevice) - { - if (_initialized) - return true; - - // Prefer the actual D3D device window so startup does not latch onto a splash/loading HWND. - _gameHwnd = DX9Backend.GetDeviceWindow(pDevice); - if (_gameHwnd == IntPtr.Zero) - { - RynthLog.Render("ImGuiController: D3D device window unavailable, falling back to EnumWindows."); - _gameHwnd = FindGameWindow(); - } - - if (_gameHwnd == IntPtr.Zero) - { - RynthLog.Render("ImGuiController: Could not find game window."); - return false; - } - - RynthLog.Render($"ImGuiController: Game HWND = 0x{_gameHwnd:X8}"); - EntryPoint.GameHwnd = _gameHwnd; - - IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext(); - if (previousContext != IntPtr.Zero) - RynthLog.Render($"ImGuiController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context."); - - _context = ImGuiNET.ImGui.CreateContext(); - bool initSucceeded = false; - try - { - ImGuiNET.ImGui.SetCurrentContext(_context); - ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); - - // Pin imgui.ini to a stable absolute path so window positions/sizes - // persist across plugin reloads (RL) and AC restarts. The default - // ImGui behavior writes to the working directory which can differ - // between launches. Allocated once, kept alive for the process lifetime. - try - { - string iniPath = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, "imgui.ini"); - System.IO.Directory.CreateDirectory(RynthInstallPaths.RynthAiDir); - IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath); - unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; } - RynthLog.Render($"ImGuiController: imgui.ini pinned to {iniPath}"); - } - catch (Exception ex) - { - RynthLog.Render($"ImGuiController: failed to pin imgui.ini path - {ex.Message}"); - } - - io.ConfigFlags |= ImGuiConfigFlags.DockingEnable; - io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable; - // Popped-out plugin windows use WS_EX_TOOLWINDOW so they don't show - // up as extra "Asheron's Call" entries in the taskbar — critical for - // users running many clients side by side. - io.ConfigViewportsNoTaskBarIcon = true; - ImGuiNET.ImGui.StyleColorsDark(); - - // One-shot offset probe for diagnostics — safe to keep installed. - ViewportProbe.Run(); - - if (!Win32Backend.Init(_gameHwnd)) - return false; - - if (!DX9Backend.Init(pDevice)) - return false; - - // Viewport backends only run when ViewportsEnable is on. Installing - // their callbacks on PlatformIO without the flag has no upside and - // just expands the crash surface. - if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0) - { - bool platformOk = ViewportPlatformBackend.Init(_gameHwnd); - bool rendererOk = platformOk && ViewportRendererBackend.Init(pDevice); - if (!platformOk || !rendererOk) - { - RynthLog.Render($"ImGuiController: viewport init failed (platform={platformOk}, renderer={rendererOk}) — disabling ViewportsEnable."); - io.ConfigFlags &= ~ImGuiConfigFlags.ViewportsEnable; - } - ViewportPlatformBackend.ImGuiContext = _context; - } - - _lastFrameTicks = Stopwatch.GetTimestamp(); - _initialized = true; - initSucceeded = true; - - RynthLog.Render("ImGuiController: Fully initialized - RynthCore shell active."); - return true; - } - finally - { - if (!initSucceeded && _context != IntPtr.Zero) - { - ImGuiNET.ImGui.DestroyContext(_context); - _context = IntPtr.Zero; - } - - ImGuiNET.ImGui.SetCurrentContext(previousContext); - } - } - - public static void Shutdown() - { - if (!_initialized) - return; - - IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext(); - IntPtr contextToDestroy = _context; - - try - { - ImGuiNET.ImGui.SetCurrentContext(contextToDestroy); - - PluginManager.ShutdownAll(); - OverlayTextureRenderer.Shutdown(); - ViewportRendererBackend.Shutdown(); - ViewportPlatformBackend.Shutdown(); - DX9Backend.Shutdown(); - Win32Backend.Shutdown(); - ImGuiNET.ImGui.DestroyContext(contextToDestroy); - - _initialized = false; - _context = IntPtr.Zero; - } - finally - { - ImGuiNET.ImGui.SetCurrentContext(previousContext == contextToDestroy ? IntPtr.Zero : previousContext); - } - } - - public static void OnEndScene(IntPtr pDevice) - { - if (_initFailed) - return; - - if (!_initialized) - { - if (!Init(pDevice)) - { - _initFailed = true; - return; - } - } - - IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext(); - ImGuiNET.ImGui.SetCurrentContext(_context); - bool frameStarted = false; - bool frameEnded = false; - - try - { - // Capture the game's View/Projection matrices before ImGui touches them - GameMatrixCapture.CaptureFrame(pDevice); - - // Install the SetRenderState hook that injects Nav3D rendering - // before the game's 2D UI pass (once, after DX9Backend is ready) - Nav3DRenderInjector.Install(pDevice); - bool nav3DAlreadyRendered = Nav3DRenderInjector.RenderedThisFrame; - Nav3DRenderInjector.ResetFrame(); - - // Initialize plugins once ImGui is fully ready - if (!_pluginsInitialized) - { - _pluginsInitialized = true; - PluginManager.InitPlugins(_context, pDevice, _gameHwnd); - } - - _frameCount++; - DX9Backend.NewFrame(); - Win32Backend.NewFrame(); - - ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); - - // Fallback: if Win32Backend could not determine display size, read from the D3D9 viewport. - if (io.DisplaySize.X <= 1 || io.DisplaySize.Y <= 1) - { - DX9Backend.GetViewportSize(pDevice, out int vpW, out int vpH); - if (vpW > 1 && vpH > 1) - io.DisplaySize = new System.Numerics.Vector2(vpW, vpH); - } - - long now = Stopwatch.GetTimestamp(); - float dt = (float)(now - _lastFrameTicks) / Stopwatch.Frequency; - _lastFrameTicks = now; - io.DeltaTime = dt > 0f ? dt : 1f / 60f; - - // Drain queued host/plugin callbacks before opening the Dear ImGui frame. - // This keeps heavy world-update bursts from stretching an already-active frame. - // Drain queued host/plugin callbacks before opening the Dear ImGui frame. - // This keeps heavy world-update bursts from stretching an already-active frame. - PluginManager.ProcessPendingActions(_context, pDevice, _gameHwnd); - - // Plugin tick (per-frame logic, before ImGui drawing) - PluginManager.TickAll(); - - // With ViewportsEnable on, ImGui routes mouse and window positions in - // absolute screen coords. The main viewport's Pos must equal the game - // client's screen origin so clicks over the main viewport map to the - // correct windows, and popped-out viewports share a coord system with - // the main one. - if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0) - { - int screenX = 0, screenY = 0; - if (_gameHwnd != IntPtr.Zero) - { - ClientPoint p = new ClientPoint { X = 0, Y = 0 }; - if (ClientToScreen(_gameHwnd, ref p)) { screenX = p.X; screenY = p.Y; } - } - ImGuiViewportPtr mainVp = ImGuiNET.ImGui.GetMainViewport(); - mainVp.Pos = new System.Numerics.Vector2(screenX, screenY); - mainVp.Size = io.DisplaySize; - mainVp.WorkPos = new System.Numerics.Vector2(screenX, screenY); - mainVp.WorkSize = io.DisplaySize; - } - - ImGuiNET.ImGui.NewFrame(); - frameStarted = true; - RynthCoreShell.Render(_frameCount); - - // Plugin render (ImGui draw calls) - PluginManager.RenderAll(); - - // A plugin that threw mid-window leaves scopes open; EndFrame would assert - // with a modal dialog on AC's main thread. - ImGuiStackRecovery.RecoverBeforeEndFrame(); - - bool captureMouse = - ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow) || - ImGuiNET.ImGui.IsAnyItemActive(); - bool captureKeyboard = ImGuiNET.ImGui.IsAnyItemActive(); - - ImGuiNET.ImGui.EndFrame(); - frameEnded = true; - ImGuiNET.ImGui.Render(); - Win32Backend.UpdateCaptureFlags(captureMouse, captureKeyboard); - - ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData(); - - if (!nav3DAlreadyRendered) - DX9Backend.RenderNav3D(pDevice); - - DX9Backend.RenderDrawData(drawData, pDevice); - OverlayTextureRenderer.Render(pDevice); - - if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0) - { - ImGuiNET.ImGui.UpdatePlatformWindows(); - ImGuiNET.ImGui.RenderPlatformWindowsDefault(); - } - } - catch (Exception ex) - { - try - { - // Keep Dear ImGui's frame state balanced so the next frame does not assert. - if (frameStarted && !frameEnded && ImGuiNET.ImGui.GetCurrentContext() == _context) - ImGuiNET.ImGui.EndFrame(); - } - catch - { - } - - RynthLog.Info($"ImGuiController: frame {_frameCount} error: {ex.GetType().Name}: {ex.Message}"); - } - finally - { - ImGuiNET.ImGui.SetCurrentContext(previousContext); - } - } - - private static IntPtr FindGameWindow() - { - uint pid = GetCurrentProcessId(); - IntPtr found = IntPtr.Zero; - - EnumWindows((hWnd, _) => - { - GetWindowThreadProcessId(hWnd, out uint windowPid); - if (windowPid == pid && IsWindowVisible(hWnd)) - { - found = hWnd; - return false; - } - - return true; - }, IntPtr.Zero); - - return found; - } -} diff --git a/src/RynthCore.Engine/ImGui/ImGuiFontTest.cs b/src/RynthCore.Engine/ImGui/ImGuiFontTest.cs new file mode 100644 index 0000000..0c3c8fb --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ImGuiFontTest.cs @@ -0,0 +1,72 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ImGuiFontTest.cs +// Developer check for the atlas and theme (docs/IMGUI_PARITY_PLAN.md P0 +// acceptance): every baked font with sample text, every merged symbol and +// icons inline with text (to judge their size and baseline), then every +// baked Phosphor icon, plus the theme swatches. Only with RYNTHCORE_IMGUI_FONTTEST=1 in the +// client's environment or after /rc imgui fonttest; never shown otherwise. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class ImGuiFontTest +{ + /// <summary>Shown when RYNTHCORE_IMGUI_FONTTEST=1, or toggled with /rc imgui fonttest.</summary> + public static volatile bool Enabled = + Environment.GetEnvironmentVariable("RYNTHCORE_IMGUI_FONTTEST") == "1"; + + private const string Sample = "The quick brown fox 0123456789 — …"; + private const string Symbols = "● • → ←"; + private const string Icons = PhosphorIcons.Gear + " Settings " + PhosphorIcons.Play + " Run " + PhosphorIcons.Trash + + " Delete " + PhosphorIcons.Sword + PhosphorIcons.Sparkle + PhosphorIcons.SneakerMove + PhosphorIcons.Bag + " Hxg"; + + public static void Draw(float scale) + { + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(560, 520) * scale, ImGuiCond.FirstUseEver); + if (ImGuiNET.ImGui.Begin("RynthCore font test##fonttest")) + { + ImGuiNET.ImGui.TextDisabled($"scale {scale:0.##} atlas {ImGuiNET.ImGui.GetIO().Fonts.TexWidth}x{ImGuiNET.ImGui.GetIO().Fonts.TexHeight}"); + for (UiFont f = 0; f < UiFont.Count; f++) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(f)); + ImGuiNET.ImGui.TextUnformatted($"{f,-9} {Sample} {Symbols} {Icons}"); + ImGuiNET.ImGui.PopFont(); + } + + ImGuiNET.ImGui.Separator(); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui14)); + ImGuiNET.ImGui.PushTextWrapPos(0); + ImGuiNET.ImGui.TextUnformatted(PhosphorIcons.Baked); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopFont(); + + ImGuiNET.ImGui.Separator(); + Swatch("bar", RynthTheme.BarBackground); Swatch("button", RynthTheme.BarButton); + Swatch("glass", RynthTheme.PanelGlass); Swatch("teal", RynthTheme.PanelBorder); + Swatch("header", RynthTheme.PanelHeader); Swatch("rynthai", RynthTheme.RynthAiBackground); + Swatch("gold", RynthTheme.RadarGold); + ImGuiNET.ImGui.NewLine(); + ImGuiNET.ImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.RcLabel), "RC"); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.ReloadLabel), "RL"); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.PopOutLabel), PhosphorIcons.ArrowSquareOut); + } + ImGuiNET.ImGui.End(); + } + + private static void Swatch(string label, uint color) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float h = ImGuiNET.ImGui.GetTextLineHeight(); + ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(p, p + new Vector2(h * 2, h), color); + ImGuiNET.ImGui.Dummy(new Vector2(h * 2, h)); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextUnformatted(label); + ImGuiNET.ImGui.SameLine(); + } +} diff --git a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs new file mode 100644 index 0000000..c75324c --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs @@ -0,0 +1,627 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ImGuiFonts.cs +// The ImGui font atlas (docs/IMGUI_PARITY_PLAN.md §4.4). +// +// ImGui 1.91 has no dynamic font sizes, so every size a panel face uses is +// baked once, at the DPI scale the context is created with: +// Segoe UI 9/10/11/14 and Bold 11/14 (panel text, headers, radar compass), +// Consolas 9/10/12 (Tracker, Log, Meta rows), Cascadia Mono 12 (Meta +// source; Consolas if missing), and the chat monospace at 8-18 in steps +// of 2 (the chat font slider snaps to the nearest). +// The few symbol glyphs still drawn as text (SymbolCodepoints) are merged in +// from Segoe UI Symbol wherever the main font lacks them. +// +// Icons: the Phosphor icon font (MIT, Assets/Fonts/Phosphor.ttf, embedded in +// this assembly) is merged into every baked font, the scaled sets included, +// at the web font's code points (U+E000 up), so an icon is text +// (PhosphorIcons). Only PhosphorIcons.Baked is merged, not the whole set. +// Each font gets the icons at about 1.2x its em (Phosphor's em is its pixel +// size; Segoe UI's is 0.75 of it), shifted down so the icon's centre sits on +// the text's cap-height centre, on a fixed advance so icon columns line up. +// +// Font files are read by Preload() on the engine's init worker, so AC's +// render thread only copies bytes into the atlas. The native TTF buffers and +// glyph ranges stay alive until Free() (after the context is destroyed). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Numerics; +using System.Runtime.InteropServices; +using ImGuiNET; + +namespace RynthCore.Engine.ImGuiBackend; + +internal enum UiFont +{ + Ui10, Ui11, Ui14, + UiBold11, UiBold14, + Mono9, Mono10, Mono12, + Code12, + Chat8, Chat10, Chat12, Chat14, Chat16, Chat18, + Ui9, + // RynthAi dashboard: Cascadia Mono (Consolas if missing), like the Avalonia face. + Dash9, Dash10, Dash11, Dash14, + // RynthVision combat numbers: baked big so they stay sharp. + NumBold24, + // Scaled-up nameplate text and big combat numbers: picked by Sharp() so text is + // shrunk from a bigger bake, never stretched from a smaller one. + Ui18, NumBold48, + Count, +} + +internal static unsafe class ImGuiFonts +{ + private static readonly string FontsDir = Environment.GetFolderPath(Environment.SpecialFolder.Fonts); + + // Main text: Basic Latin + Latin-1, general punctuation (— – … • ‘ ’ “ ”), arrows. + private static readonly ushort[] MainRanges = { 0x0020, 0x00FF, 0x2010, 0x2027, 0x2190, 0x21FF, 0 }; + + // Symbols still drawn as text, merged from Segoe UI Symbol where the main font + // lacks them. The panels' other symbols (⚔ ✦ ➤ ◫ ♥ ◆ ⚙ ▾ ▴ ↗ ↙ ◢ ✕ ☑ ☐ ▶ ▼ ▲ ◀ ■ + // ❏ ↺ ✎ − ⬡ ◎ ⚒ ...) are Phosphor icons now (PhosphorIcons). Arrows, bullets and + // dashes are in MainRanges. + private static readonly ushort[] SymbolCodepoints = + { + 0x25CF, // ● (Meta source: unapplied edits) + }; + + private static byte[]? _segoe, _segoeBold, _consolas, _cascadia, _symbol, _phosphor; + + private const string PhosphorResource = "RynthCore.Engine.Assets.Fonts.Phosphor.ttf"; + // Icon size relative to the text's em, capped at the line height (x0.95) for + // fonts whose em fills the line (Consolas): bigger icons climb out of the line. + private const float IconScale = 1.2f, IconMaxOfLine = 0.95f; + // Where a Phosphor icon's box centre sits above the baseline, in its em + // (the 1024-unit box runs from -64 to 960). + private const float IconCentreEm = 448f / 1024f; + // Phosphor's regular strokes are 1/16 em: at 9-13 px they rasterize thin and grey. + private const float IconRasterizerMultiply = 1.2f; + private static volatile bool _preloaded; + private static readonly List<IntPtr> NativeBuffers = new(); + private static readonly ImFontPtr[] Fonts = new ImFontPtr[(int)UiFont.Count]; + + // Per-panel text size (UI.PanelTextScale): the same fonts baked bigger, one + // set per size in use. Get() returns the set for CurrentStep, which the panel + // host sets while it draws a panel, so every face's text grows without any + // face code changing. Baked (not stretched), so the big text stays sharp. + private static readonly Dictionary<int, ImFontPtr[]> ScaledFonts = new(); + + /// <summary>Text size step of the panel being drawn (0 = normal). Render thread.</summary> + public static int CurrentStep; + + // Stopwatch timestamp the requested rebuild is due at; 0 = none requested. + private static long _rebuildDue; + + /// <summary> + /// A panel's text size changed: rebuild the font atlas before a frame at least + /// <paramref name="delayMs"/> from now. Each request moves the time out, so a run + /// of changes (clicks, wheel notches) re-bakes once, after the last. Any thread. + /// </summary> + public static void RequestRebuild(int delayMs = 0) + { + long due = Stopwatch.GetTimestamp() + Math.Max(0, delayMs) * Stopwatch.Frequency / 1000; + if (due == 0) due = 1; + System.Threading.Volatile.Write(ref _rebuildDue, due); + } + + /// <summary>True once per request, when it is due. Render thread, before NewFrame.</summary> + public static bool TakeRebuildRequest() + { + long due = System.Threading.Volatile.Read(ref _rebuildDue); + if (due == 0 || Stopwatch.GetTimestamp() < due) return false; + // A newer request made meanwhile keeps its own (later) time. + return System.Threading.Interlocked.CompareExchange(ref _rebuildDue, 0, due) == due; + } + + /// <summary> + /// The baked size step closest to <paramref name="step"/> (0 = normal): the step + /// itself once baked. Between a size change and the re-bake it lands on, a panel + /// keeps drawing at a nearby baked size instead of dropping to normal. Render thread. + /// </summary> + public static int BakedStepNear(int step) + { + if (step <= 0 || ScaledFonts.ContainsKey(step)) return Math.Max(0, step); + int best = 0; + foreach (int baked in ScaledFonts.Keys) + if (Math.Abs(baked - step) < Math.Abs(best - step)) best = baked; + return best; + } + + // Native copies of the font files and glyph ranges, made once: rebuilds reuse them. + private static IntPtr _nSegoe, _nSegoeBold, _nMono, _nCode, _nSymbol, _nPhosphor; + private static ushort* _mainRanges, _symbolRanges, _iconRanges; + + /// <summary>Reads the font files. Engine init worker thread; safe to skip (Build reads them itself).</summary> + public static void Preload() + { + if (_preloaded) return; + _segoe = TryRead("segoeui.ttf"); + _segoeBold = TryRead("segoeuib.ttf"); + _consolas = TryRead("consola.ttf"); + _cascadia = TryRead("CascadiaMono.ttf"); + _symbol = TryRead("seguisym.ttf"); + _phosphor = TryReadResource(PhosphorResource); + _preloaded = true; + } + + /// <summary>A baked font. Before Build (or if it failed) this is ImGui's default font.</summary> + public static ImFontPtr Get(UiFont font) + { + if (CurrentStep > 0 && ScaledFonts.TryGetValue(CurrentStep, out ImFontPtr[]? set)) + { + ImFontPtr s = set[(int)font]; + if (s.NativePtr != null) return s; + } + ImFontPtr f = Fonts[(int)font]; + return f.NativePtr != null ? f : ImGuiNET.ImGui.GetIO().FontDefault; + } + + private static readonly UiFont[] SharpRegular = { UiFont.Ui9, UiFont.Ui10, UiFont.Ui11, UiFont.Ui14, UiFont.Ui18 }; + private static readonly UiFont[] SharpBold = { UiFont.UiBold11, UiFont.UiBold14, UiFont.NumBold24, UiFont.NumBold48 }; + + /// <summary> + /// The smallest baked font at least <paramref name="px"/> tall (else the biggest), for text + /// drawn at a scaled size: shrinking a bigger bake stays sharp, stretching a smaller one blurs. + /// Draw with the returned font at <paramref name="px"/>. + /// </summary> + public static ImFontPtr Sharp(float px, bool bold) + { + UiFont[] set = bold ? SharpBold : SharpRegular; + ImFontPtr best = Get(set[0]); + for (int i = 0; i < set.Length; i++) + { + ImFontPtr f = Fonts[(int)set[i]]; + if (f.NativePtr == null) continue; + best = f; + if (f.FontSize >= px - 0.5f) break; + } + return best; + } + + /// <summary>The baked chat font nearest to <paramref name="points"/> (8-18).</summary> + public static ImFontPtr Chat(float points) + { + int step = Math.Clamp((int)MathF.Round((points - 8f) / 2f), 0, 5); + return Get(UiFont.Chat8 + step); + } + + /// <summary> + /// Adds every font to the current context's atlas at <paramref name="scale"/> + /// (DPI / 96). AC thread, before the atlas texture is first built. + /// </summary> + public static void Build(ImGuiIOPtr io, float scale) + { + long t0 = Stopwatch.GetTimestamp(); + PrepareNativeData(); + + ScaledFonts.Clear(); + AddAll(io.Fonts, scale, RynthCore.Engine.UI.PanelTextScale.StepsInUse(), Fonts, ScaledFonts); + + if (Fonts[(int)UiFont.Ui11].NativePtr != null) + io.NativePtr->FontDefault = Fonts[(int)UiFont.Ui11].NativePtr; + else + io.Fonts.AddFontDefault(); // no Segoe UI: ImGui's built-in font keeps text readable + + double ms = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency; + RynthLog.UI($"ImGuiFonts: {CountBaked()} fonts queued at scale {scale:0.##} in {ms:0.0} ms " + + $"(Cascadia Mono {(_cascadia != null ? "found" : "missing, using Consolas")}, symbols {(_symbol != null ? "merged" : "missing")}, " + + $"icons {(_phosphor != null ? $"{IconCount()} merged" : "missing")})."); + } + + /// <summary>The font files and glyph ranges as native memory, made once (rebuilds reuse them). AC thread.</summary> + private static void PrepareNativeData() + { + if (!_preloaded) Preload(); + if (_mainRanges != null) return; + byte[]? mono = _consolas; + byte[]? code = _cascadia ?? _consolas; + _mainRanges = PinRanges(MainRanges); + _symbolRanges = PinRanges(SymbolRanges()); + _iconRanges = PinRanges(IconRanges()); + _nSegoe = ToNative(_segoe); _nSegoeBold = ToNative(_segoeBold); _nMono = ToNative(mono); + _nCode = ToNative(code); _nSymbol = ToNative(_symbol); _nPhosphor = ToNative(_phosphor); + } + + /// <summary> + /// Queues every font into <paramref name="atlas"/>: the normal set into + /// <paramref name="baseSet"/>, a bigger copy per text size step into + /// <paramref name="scaled"/>. Touches no ImGui context and no static font + /// table, so the off-thread re-bake runs it too (after PrepareNativeData). + /// </summary> + private static void AddAll(ImFontAtlasPtr atlas, float scale, List<int> steps, ImFontPtr[] baseSet, + Dictionary<int, ImFontPtr[]> scaled) + { + byte[]? mono = _consolas; + byte[]? code = _cascadia ?? _consolas; + ushort* mainRanges = _mainRanges; + ushort* symbolRanges = _symbolRanges; + ushort* iconRanges = _iconRanges; + IntPtr segoe = _nSegoe, segoeBold = _nSegoeBold, consolas = _nMono, codeFont = _nCode, symbol = _nSymbol, + phosphor = _nPhosphor; + + // Each base font's em and cap height, to size and place the icons merged into it. + FaceMetrics mSegoe = FaceMetrics.Read(_segoe), mSegoeBold = FaceMetrics.Read(_segoeBold), + mMono = FaceMetrics.Read(mono), mCode = FaceMetrics.Read(code); + + ImFontPtr[] target = baseSet; + float factor = 1f; + + void Add(UiFont id, IntPtr data, byte[]? bytes, FaceMetrics metrics, float px) + { + if (data == IntPtr.Zero || bytes == null) return; + float size = MathF.Round(px * scale * factor); + ImFontConfigPtr cfg = ImGuiNative.ImFontConfig_ImFontConfig(); + try + { + cfg.FontDataOwnedByAtlas = false; + target[(int)id] = atlas.AddFontFromMemoryTTF(data, bytes.Length, size, cfg, (IntPtr)mainRanges); + if (symbol != IntPtr.Zero && _symbol != null) + { + cfg.MergeMode = true; + cfg.GlyphMinAdvanceX = 0; + atlas.AddFontFromMemoryTTF(symbol, _symbol.Length, size, cfg, (IntPtr)symbolRanges); + } + if (phosphor != IntPtr.Zero && _phosphor != null) + { + // Phosphor's em is its pixel size (ascent + descent = 1 em). + float em = size * metrics.EmPerPx; + float iconPx = MathF.Max(1f, MathF.Round(MathF.Min(em * IconScale, size * IconMaxOfLine))); + cfg.MergeMode = true; + // Whole-pixel advances, so horizontal oversampling buys nothing: 1 halves the icons' atlas space. + cfg.PixelSnapH = true; + cfg.OversampleH = 1; + cfg.GlyphMinAdvanceX = iconPx; + // Down (+y) from the shared baseline: the icon's centre onto the cap-height centre. + cfg.GlyphOffset = new Vector2(0, MathF.Round(IconCentreEm * iconPx - metrics.CapHalfEm * em)); + cfg.RasterizerMultiply = IconRasterizerMultiply; + atlas.AddFontFromMemoryTTF(phosphor, _phosphor.Length, iconPx, cfg, (IntPtr)iconRanges); + } + } + finally + { + ImGuiNative.ImFontConfig_destroy(cfg.NativePtr); + } + } + + Add(UiFont.Ui11, segoe, _segoe, mSegoe, 11); // first added = io.FontDefault unless set below + Add(UiFont.Ui10, segoe, _segoe, mSegoe, 10); + Add(UiFont.Ui14, segoe, _segoe, mSegoe, 14); + Add(UiFont.Ui9, segoe, _segoe, mSegoe, 9); + Add(UiFont.UiBold11, segoeBold, _segoeBold, mSegoeBold, 11); + Add(UiFont.UiBold14, segoeBold, _segoeBold, mSegoeBold, 14); + Add(UiFont.Mono9, consolas, mono, mMono, 9); + Add(UiFont.Mono10, consolas, mono, mMono, 10); + Add(UiFont.Mono12, consolas, mono, mMono, 12); + Add(UiFont.Code12, codeFont, code, mCode, 12); + Add(UiFont.Dash9, codeFont, code, mCode, 9); + Add(UiFont.Dash10, codeFont, code, mCode, 10); + Add(UiFont.Dash11, codeFont, code, mCode, 11); + Add(UiFont.Dash14, codeFont, code, mCode, 14); + Add(UiFont.NumBold24, segoeBold, _segoeBold, mSegoeBold, 24); + Add(UiFont.Ui18, segoe, _segoe, mSegoe, 18); + Add(UiFont.NumBold48, segoeBold, _segoeBold, mSegoeBold, 48); + for (int i = 0; i < 6; i++) + Add(UiFont.Chat8 + i, consolas, mono, mMono, 8 + i * 2); + + // Bigger copies for each panel text size in use (chat keeps its own size setting). + foreach (int step in steps) + { + target = new ImFontPtr[(int)UiFont.Count]; + factor = RynthCore.Engine.UI.PanelTextScale.Factor(step); + Add(UiFont.Ui11, segoe, _segoe, mSegoe, 11); + Add(UiFont.Ui10, segoe, _segoe, mSegoe, 10); + Add(UiFont.Ui14, segoe, _segoe, mSegoe, 14); + Add(UiFont.Ui9, segoe, _segoe, mSegoe, 9); + Add(UiFont.UiBold11, segoeBold, _segoeBold, mSegoeBold, 11); + Add(UiFont.UiBold14, segoeBold, _segoeBold, mSegoeBold, 14); + Add(UiFont.Mono9, consolas, mono, mMono, 9); + Add(UiFont.Mono10, consolas, mono, mMono, 10); + Add(UiFont.Mono12, consolas, mono, mMono, 12); + Add(UiFont.Code12, codeFont, code, mCode, 12); + Add(UiFont.Dash9, codeFont, code, mCode, 9); + Add(UiFont.Dash10, codeFont, code, mCode, 10); + Add(UiFont.Dash11, codeFont, code, mCode, 11); + Add(UiFont.Dash14, codeFont, code, mCode, 14); + scaled[step] = target; + } + } + + // ── Re-bake off AC's thread ───────────────────────────────────────── + // A text size change needs a new atlas. Rasterizing it took 180-300 ms with one + // or two enlarged sizes (about 1 s with all ten), which froze the game for that + // long when it ran on the render thread. Instead a worker queues and builds a + // NEW atlas (no ImGui context involved) while frames go on with the old one; + // then, between frames, the main context and every pop-out are pointed at the + // new atlas, its texture is made, and the old atlas is destroyed on another + // worker. AC's thread only pays for the swap and the texture upload. + // + // ImGui's allocator hook writes to the current context's debug counters from + // any thread, so no context may be destroyed while a worker allocates or frees: + // WaitForWorkers() runs first (ImGuiPopOuts.Close, EngineFrameController.Shutdown). + + private sealed class Bake + { + public IntPtr Atlas; // ImFontAtlas*, in no context yet; 0 = the bake failed + public readonly ImFontPtr[] Base = new ImFontPtr[(int)UiFont.Count]; + public readonly Dictionary<int, ImFontPtr[]> Scaled = new(); + public int Steps; + public double Ms; + public string? Error; + } + + private static System.Threading.Thread? _bakeThread; + private static Bake? _bakeDone; // set by the worker as it ends + private static readonly List<System.Threading.Thread> FreeThreads = new(); + + /// <summary> + /// Render thread, before NewFrame, with the main context current. Starts a re-bake + /// when one is due, and swaps a finished one in. True when <paramref name="io"/>'s + /// atlas changed: the caller makes its texture. <paramref name="what"/> says what happened. + /// </summary> + public static bool PumpRebuild(ImGuiIOPtr io, float scale, out string what) + { + what = ""; + if (_bakeThread != null) + { + Bake? done = System.Threading.Volatile.Read(ref _bakeDone); + if (done == null) return false; // still baking: frames go on with the old atlas + _bakeThread.Join(); + _bakeThread = null; + _bakeDone = null; + if (done.Atlas == IntPtr.Zero) + { + // Failed off-thread: the old way, here. + io.Fonts.Clear(); + Build(io, scale); + what = $"off-thread bake failed ({done.Error}); re-baked on the render thread"; + return true; + } + SwapIn(io, done); + what = $"baked off-thread in {done.Ms:0.0} ms ({done.Steps} enlarged size(s) in use)"; + return true; + } + + if (!TakeRebuildRequest()) return false; + PrepareNativeData(); + List<int> steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse(); + try + { + _bakeDone = null; + _bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps)); + return false; + } + catch (Exception ex) + { + _bakeThread = null; + io.Fonts.Clear(); + Build(io, scale); + what = $"no bake thread ({ex.GetType().Name}); re-baked on the render thread"; + return true; + } + } + + private static void BakeWorker(float scale, List<int> steps) + { + var bake = new Bake { Steps = steps.Count }; + long t0 = Stopwatch.GetTimestamp(); + ImFontAtlas* atlas = null; + try + { + atlas = ImGuiNative.ImFontAtlas_ImFontAtlas(); + var ptr = new ImFontAtlasPtr(atlas); + AddAll(ptr, scale, steps, bake.Base, bake.Scaled); + if (bake.Base[(int)UiFont.Ui11].NativePtr == null) + ptr.AddFontDefault(); // no Segoe UI: ImGui's built-in font keeps text readable + ptr.Build(); + // The RGBA copy the texture is made from, here too: the swap then only uploads it. + ptr.GetTexDataAsRGBA32(out IntPtr _, out int _, out int _); + bake.Atlas = (IntPtr)atlas; + atlas = null; + } + catch (Exception ex) + { + bake.Error = $"{ex.GetType().Name}: {ex.Message}"; + } + finally + { + if (atlas != null) ImGuiNative.ImFontAtlas_destroy(atlas); + bake.Ms = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency; + System.Threading.Volatile.Write(ref _bakeDone, bake); + } + } + + /// <summary>Points the main context and every pop-out at the baked atlas; the old one is freed off-thread.</summary> + private static void SwapIn(ImGuiIOPtr io, Bake bake) + { + ImFontAtlas* old = io.NativePtr->Fonts; + ImFontAtlas* fresh = (ImFontAtlas*)bake.Atlas; + io.NativePtr->Fonts = fresh; // the main context owns (and at shutdown deletes) whatever atlas it holds + io.NativePtr->FontDefault = bake.Base[(int)UiFont.Ui11].NativePtr; // null: the atlas's first font + Array.Copy(bake.Base, Fonts, Fonts.Length); + ScaledFonts.Clear(); + foreach (KeyValuePair<int, ImFontPtr[]> kv in bake.Scaled) ScaledFonts[kv.Key] = kv.Value; + ImGuiPopOuts.ReplaceFontAtlas((IntPtr)old, (IntPtr)fresh); + if (old == null || old == fresh) return; + IntPtr oldPtr = (IntPtr)old; + try + { + lock (FreeThreads) + { + FreeThreads.RemoveAll(t => !t.IsAlive); + FreeThreads.Add(EngineThreads.Start("ImGuiFonts.Free", + () => ImGuiNative.ImFontAtlas_destroy((ImFontAtlas*)oldPtr))); + } + } + catch + { + ImGuiNative.ImFontAtlas_destroy(old); // no thread: free it here + } + } + + /// <summary> + /// Waits for a running re-bake and atlas frees. Before destroying any ImGui + /// context (see the note above). AC thread. A finished bake stays to be swapped in. + /// </summary> + public static void WaitForWorkers() + { + _bakeThread?.Join(); + System.Threading.Thread[] frees; + lock (FreeThreads) { frees = FreeThreads.ToArray(); FreeThreads.Clear(); } + foreach (System.Threading.Thread t in frees) t.Join(); + } + + /// <summary>Frees the native font buffers. Only after the ImGui context is destroyed.</summary> + public static void Free() + { + // A worker may still read the buffers below (a bake) or free an atlas. + WaitForWorkers(); + if (_bakeThread != null || _bakeDone != null) + { + _bakeThread = null; + Bake? pending = _bakeDone; + _bakeDone = null; + if (pending != null && pending.Atlas != IntPtr.Zero) + ImGuiNative.ImFontAtlas_destroy((ImFontAtlas*)pending.Atlas); // baked, never swapped in + } + foreach (IntPtr p in NativeBuffers) + NativeMemory.Free((void*)p); + NativeBuffers.Clear(); + Array.Clear(Fonts); + ScaledFonts.Clear(); + _mainRanges = _symbolRanges = _iconRanges = null; + _nSegoe = _nSegoeBold = _nMono = _nCode = _nSymbol = _nPhosphor = IntPtr.Zero; + } + + private static int CountBaked() + { + int n = 0; + foreach (ImFontPtr f in Fonts) if (f.NativePtr != null) n++; + return n; + } + + private static ushort[] SymbolRanges() + { + var ranges = new ushort[SymbolCodepoints.Length * 2 + 1]; + for (int i = 0; i < SymbolCodepoints.Length; i++) + { + ranges[i * 2] = SymbolCodepoints[i]; + ranges[i * 2 + 1] = SymbolCodepoints[i]; + } + return ranges; // trailing 0 terminator + } + + /// <summary>PhosphorIcons.Baked as glyph ranges: sorted, runs of neighbours joined, 0-terminated.</summary> + private static ushort[] IconRanges() + { + var points = new SortedSet<ushort>(); + foreach (char c in PhosphorIcons.Baked) points.Add(c); + var ranges = new List<ushort>(); + int start = -1, prev = -1; + foreach (ushort cp in points) + { + if (start < 0) start = cp; + else if (cp != prev + 1) { ranges.Add((ushort)start); ranges.Add((ushort)prev); start = cp; } + prev = cp; + } + if (start >= 0) { ranges.Add((ushort)start); ranges.Add((ushort)prev); } + ranges.Add(0); + return ranges.ToArray(); + } + + private static int IconCount() => new HashSet<char>(PhosphorIcons.Baked).Count; + + /// <summary> + /// A TrueType font's em as a fraction of the ImGui pixel size (ImGui sizes a + /// font so hhea ascent - descent = the size) and half its cap height in em. + /// Read from the head, hhea and OS/2 tables; Segoe UI's values when unreadable. + /// </summary> + private readonly record struct FaceMetrics(float EmPerPx, float CapHalfEm) + { + private static readonly FaceMetrics Fallback = new(2048f / 2724f, 1434f / 2048f * 0.5f); + + public static FaceMetrics Read(byte[]? ttf) + { + if (ttf == null || ttf.Length < 12) return Fallback; + try + { + int upm = 0, ascent = 0, descent = 0, cap = 0; + int tables = U16(ttf, 4); + for (int i = 0; i < tables; i++) + { + int rec = 12 + i * 16; + uint tag = (uint)(ttf[rec] << 24 | ttf[rec + 1] << 16 | ttf[rec + 2] << 8 | ttf[rec + 3]); + int off = ttf[rec + 8] << 24 | ttf[rec + 9] << 16 | ttf[rec + 10] << 8 | ttf[rec + 11]; + if (tag == 0x68656164) upm = U16(ttf, off + 18); // head + else if (tag == 0x68686561) { ascent = S16(ttf, off + 4); descent = S16(ttf, off + 6); } // hhea + else if (tag == 0x4F532F32 && U16(ttf, off) >= 2) cap = S16(ttf, off + 88); // OS/2 + } + if (upm <= 0 || ascent - descent <= 0) return Fallback; + if (cap <= 0) cap = (int)(upm * 0.7f); + return new FaceMetrics((float)upm / (ascent - descent), cap * 0.5f / upm); + } + catch (IndexOutOfRangeException) + { + return Fallback; + } + } + + private static int U16(byte[] b, int at) => b[at] << 8 | b[at + 1]; + private static int S16(byte[] b, int at) => (short)(b[at] << 8 | b[at + 1]); + } + + private static ushort* PinRanges(ushort[] ranges) + { + var p = (ushort*)NativeMemory.Alloc((nuint)ranges.Length, sizeof(ushort)); + ranges.AsSpan().CopyTo(new Span<ushort>(p, ranges.Length)); + NativeBuffers.Add((IntPtr)p); + return p; + } + + private static IntPtr ToNative(byte[]? bytes) + { + if (bytes == null || bytes.Length == 0) return IntPtr.Zero; + void* p = NativeMemory.Alloc((nuint)bytes.Length); + bytes.AsSpan().CopyTo(new Span<byte>(p, bytes.Length)); + NativeBuffers.Add((IntPtr)p); + return (IntPtr)p; + } + + /// <summary>A font embedded in this assembly (the Phosphor icons); null when missing.</summary> + private static byte[]? TryReadResource(string name) + { + try + { + using Stream? stream = typeof(ImGuiFonts).Assembly.GetManifestResourceStream(name); + if (stream == null) + { + RynthLog.UI($"ImGuiFonts: embedded font {name} missing; icons will not draw."); + return null; + } + var bytes = new byte[stream.Length]; + stream.ReadExactly(bytes); + return bytes; + } + catch (Exception ex) + { + RynthLog.UI($"ImGuiFonts: could not read {name} - {ex.GetType().Name}: {ex.Message}"); + return null; + } + } + + private static byte[]? TryRead(string file) + { + try + { + string path = Path.Combine(FontsDir, file); + return File.Exists(path) ? File.ReadAllBytes(path) : null; + } + catch (Exception ex) + { + RynthLog.UI($"ImGuiFonts: could not read {file} - {ex.GetType().Name}: {ex.Message}"); + return null; + } + } +} diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs new file mode 100644 index 0000000..f55b35d --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -0,0 +1,1350 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ImGuiPanelHost.cs +// Engine-side ImGui panel faces (docs/IMGUI_PARITY_PLAN.md §4.1). +// +// A panel docked in the client is drawn here. Popped out, the same face +// is drawn into its own window by ImGuiPopOuts (Tom, 2026-09-29: pop-outs are +// ImGui too; Avalonia is being retired). The host owns each face's window: the +// Avalonia-matching frame (24 px header with DRAG, title, text size, pop-out +// and close; 16 px resize grip, all Phosphor icons), placement restore/persistence shared +// with the Avalonia face through PanelStateStore, and per-panel error isolation. +// +// Threads: +// Register engine init. +// RegisterDynamic / Unregister / RequestSize / RequestPos +// any thread (script windows, from the plugin pump thread); +// DrawOrder is copy-on-write, removal finishes in DrawAll; +// requests are applied in DrawPanel. +// Open / Close any thread (router: game thread / Avalonia UI thread). +// Applied on AC's render thread at the next DrawAll. +// DrawAll AC's render thread, inside the ImGui frame. +// IsOpen/AnyOpen any thread; a copy-on-write set, so frame reads never lock. +// Panel Draw code runs on AC's thread: it reads hub snapshots and posts +// commands only (no plugin calls, no AC reads, no locks, no file I/O). +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.ImGuiBackend; + +internal enum PanelChrome +{ + /// <summary>DRAG + title + pop-out + close header, resize grip.</summary> + Standard, + /// <summary>No header or grip: the panel draws its own drag surface (RynthAi, Radar).</summary> + None, +} + +/// <summary>How a face's window looks and sizes, in Avalonia logical units.</summary> +internal sealed record PanelSpec( + Vector2 DefaultSize, + Vector2 MinSize, + PanelChrome Chrome = PanelChrome.Standard, + uint? Background = null, // null: panel glass; 0: transparent (the panel paints its own) + uint? BorderColor = null, // null: teal + float Rounding = RynthTheme.PanelRounding, + // A face is registered only once it's finished, so finished panels open in + // ImGui unless the player picked another face (/rc ui). Popped out is Avalonia. + PanelFace CodeDefault = PanelFace.ImGui, + bool EdgeToEdge = false, // body has no padding and never scrolls (Radar) + bool GoldGrip = false, // the Radar's 14 px gold grip, inset 4 px + bool NoPopOut = false, // no pop-out button + // Standard chrome without the 18 px strip under the body for the grip: the + // grip sits over the body's bottom-right corner and the face keeps that + // corner free (ImGuiPanelHost.BodyGripReserve wide) - Chat puts it on its + // input row, beside Tell; Tracker, Status, Log, Monsters, Meta, Lua, + // ChatFilters and RynthNav keep their bottom rows short of it. A body that + // scrolls ends above the grip instead (the reserve is then 0). + bool GripInBody = false, + // OR'd into the body child's window flags (script windows: NoScrollbar, + // NoScrollWithMouse). 0 = no change. + ImGuiWindowFlags BodyFlags = ImGuiWindowFlags.None, + // Where the panel first opens (logical units) when nothing is saved for its + // key; null = the cascade. (Script windows: a FirstUseEver position.) + Vector2? DefaultPos = null, + // With nothing saved and no DefaultPos: open centred in the game view rather + // than in the top-left cascade, where popped-out panels (separate windows + // above the game frame) usually sit and would hide it. + bool OpenCentered = false); + +/// <summary>An ImGui panel face. One instance per open; dropped on close.</summary> +internal interface IImGuiPanel +{ + /// <summary>Opened: subscribe to hub sources. AC thread.</summary> + void OnShown() { } + + /// <summary>Closed: unsubscribe. AC thread.</summary> + void OnHidden() { } + + /// <summary>Draws the body (below the header). AC thread, inside the panel's child region.</summary> + void Draw(); + + /// <summary>Minimum size (logical units) when it depends on the panel's state; null = the spec's.</summary> + Vector2? MinSize => null; + + /// <summary> + /// True while the panel should let clicks through to the game (e.g. the + /// radar's "hold Ctrl to interact" option): the window takes no input. + /// </summary> + bool ClickThrough => false; + + /// <summary> + /// Popped out and not hovered or in use: how often the face is redrawn (Hz). + /// Its pictures are only pushed when they change; this bounds the cost of + /// building the frame. Hovered or just used, a pop-out runs at 30 Hz. + /// </summary> + int PopOutIdleHz => 10; + + /// <summary> + /// True while the face has nothing to show docked (the Dungeon Map outdoors): it + /// stays open and subscribed, but the host draws no window for it until this is + /// false again. Popped out it is drawn as usual. AC thread; keep it cheap. + /// </summary> + bool HiddenWhileDocked => false; +} + +internal static class ImGuiPanelHost +{ + private sealed class Entry + { + /// <summary>The key: PanelStateStore row, router and command name.</summary> + public required string Title; + /// <summary>What the header shows (the key for engine panels; a script window's own title).</summary> + public required string DisplayTitle; + /// <summary>Registered at run time (script windows, RegisterDynamic); never restored by RestoreOnce.</summary> + public bool Dynamic; + /// <summary>Unregistered: removed once it has closed (AC thread, DrawAll).</summary> + public bool PendingRemoval; + public required PanelSpec Spec; + public required Func<IImGuiPanel> Factory; + public required string WindowId; // built once: no per-frame string work + public required string BothTitle; + public IImGuiPanel? Instance; + public bool Shown; + public bool Popped; // drawn in its own window (ImGuiPopOuts), not in the client + public bool BodyScrolls; // last frame the body had a vertical scrollbar + public float LastGripRoom; // body height kept free for the grip (held during a resize) + public bool NeedsPlacement; + public Vector2 Pos, Size; // client pixels, as last drawn + public Vector2 PersistedPos, PersistedSize; + // The saved spot when the client was too small for it at placement (AC's 800x600 + // character select): re-applied as the display grows, dropped once it fits or the + // player moves the panel. Without this a panel saved near the right or bottom edge + // came back pulled inwards on every restart. + public Vector2? DesiredPos; + public Vector2 DesiredForDisplay; + public Vector2? RequestedSize; // logical units, applied next frame (under Sync) + public Vector2? RequestedPos; // logical units, applied next frame (under Sync) + public volatile bool HasRequest; // RequestedSize or RequestedPos is set + public int Failures; + public string? Error; + } + + private static readonly object Sync = new(); + private static readonly Dictionary<string, Entry> Entries = new(StringComparer.OrdinalIgnoreCase); + // Copy-on-write under Sync: DrawAll iterates the list it read without holding the lock, + // and dynamic entries are added and removed from the plugin pump thread. + private static List<Entry> DrawOrder = new(); + private static volatile bool _removalPending; + private enum RequestKind { Open, Close, PopOut, Redock, ToAvaloniaDocked } + + private static readonly ConcurrentQueue<(string Title, RequestKind Kind)> Requests = new(); + private static HashSet<string> _open = new(StringComparer.OrdinalIgnoreCase); + private static bool _restored; + private const int MaxFailures = 3; + + // ── Registry ─────────────────────────────────────────────────────── + + /// <summary> + /// Declares an ImGui face for <paramref name="title"/> (the same title the + /// Avalonia face registers with OverlayHost). Engine init. + /// </summary> + public static void Register(string title, PanelSpec spec, Func<IImGuiPanel> factory) + { + lock (Sync) + { + if (Entries.ContainsKey(title)) return; + var entry = new Entry + { + Title = title, DisplayTitle = title, Spec = spec, Factory = factory, + WindowId = title + "##rc_panel", BothTitle = title + " · ImGui", + }; + Entries[title] = entry; + DrawOrder = new List<Entry>(DrawOrder) { entry }; + } + } + + /// <summary> + /// Declares (or updates) a face registered at run time: a script window + /// (UI/ScriptWindows). <paramref name="key"/> is the panel key (saved + /// placement, commands); <paramref name="displayTitle"/> is what the header + /// shows and may change on every call. An entry being removed is revived. + /// Opening and closing stay separate (Open / Close). Any thread. + /// </summary> + public static void RegisterDynamic(string key, string displayTitle, PanelSpec spec, Func<IImGuiPanel> factory) + { + lock (Sync) + { + if (Entries.TryGetValue(key, out Entry? existing)) + { + if (!existing.Dynamic) return; // never replaces an engine panel + existing.DisplayTitle = displayTitle; + existing.Spec = spec; + existing.Factory = factory; + existing.PendingRemoval = false; + return; + } + var entry = new Entry + { + Title = key, DisplayTitle = displayTitle, Spec = spec, Factory = factory, Dynamic = true, + WindowId = key + "##rc_panel", BothTitle = displayTitle, + }; + Entries[key] = entry; + DrawOrder = new List<Entry>(DrawOrder) { entry }; + } + } + + /// <summary>Changes a dynamic face's header text. Any thread.</summary> + public static void SetDisplayTitle(string key, string displayTitle) + { + lock (Sync) + if (Entries.TryGetValue(key, out Entry? e) && e.Dynamic) e.DisplayTitle = displayTitle; + } + + /// <summary> + /// Removes a face added with <see cref="RegisterDynamic"/>: it closes (its + /// placement is saved as usual) and the entry goes once it has closed. Any thread. + /// </summary> + public static void Unregister(string key) + { + lock (Sync) + { + if (!Entries.TryGetValue(key, out Entry? e) || !e.Dynamic) return; + e.PendingRemoval = true; + } + Close(key); + _removalPending = true; + } + + /// <summary>Drops unregistered entries that have closed. AC thread, after the requests are applied.</summary> + private static void RemoveUnregistered() + { + if (!_removalPending) return; + _removalPending = false; + lock (Sync) + { + List<Entry>? next = null; + foreach (Entry e in DrawOrder) + { + if (e.PendingRemoval && !e.Shown && !IsOpen(e.Title)) + { + next ??= new List<Entry>(DrawOrder); + next.Remove(e); + Entries.Remove(e.Title); + } + else if (e.PendingRemoval) + { + _removalPending = true; // still closing: look again next frame + } + } + if (next != null) DrawOrder = next; + } + } + + public static bool HasFace(string title) + { + lock (Sync) return Entries.ContainsKey(title); + } + + public static PanelFace CodeDefault(string title) + { + lock (Sync) return Entries.TryGetValue(title, out Entry? e) ? e.Spec.CodeDefault : PanelFace.Avalonia; + } + + // ── Open state (any thread) ──────────────────────────────────────── + + public static bool IsOpen(string title) => System.Threading.Volatile.Read(ref _open).Contains(title); + + /// <summary>True when any ImGui panel face is open.</summary> + public static bool AnyOpen => System.Threading.Volatile.Read(ref _open).Count > 0; + + /// <summary> + /// True while the host needs ImGui frames: a face is open, one is still + /// shown, or a request is queued. Requests (close, pop out, hand off) are + /// applied inside DrawAll, so frames must keep running until the last one + /// is processed - otherwise closing or popping out the last open face left + /// it unapplied (nothing saved, Avalonia never opened, still subscribed). + /// </summary> + public static bool NeedsFrame => AnyOpen || !Requests.IsEmpty || System.Threading.Volatile.Read(ref _shownCount) > 0; + + private static int _shownCount; + + public static void Open(string title) => Request(title, RequestKind.Open); + + public static void Close(string title) => Request(title, RequestKind.Close); + + /// <summary>Moves an open panel out of the client into its own window (ImGuiPopOuts).</summary> + public static void PopOut(string title) => Request(title, RequestKind.PopOut); + + /// <summary>Moves a popped-out panel back into the client, where it was docked.</summary> + public static void Redock(string title) => Request(title, RequestKind.Redock); + + /// <summary>The face's idle redraw rate while popped out (IImGuiPanel.PopOutIdleHz). AC thread.</summary> + public static int PopOutIdleHz(string title) + { + Entry? entry; + lock (Sync) Entries.TryGetValue(title, out entry); + try { return Math.Clamp(entry?.Instance?.PopOutIdleHz ?? 10, 1, 30); } catch { return 10; } + } + + /// <summary>For a face's own pop-out button: dock back (arrow in) while it is drawn in its own window, else pop out.</summary> + public static string PopOutGlyph => ImGuiPopOuts.InPopOutFrame ? PhosphorIcons.ArrowSquareIn : PhosphorIcons.ArrowSquareOut; + + /// <summary>The pop-out button's tooltip, matching <see cref="PopOutGlyph"/>.</summary> + public static string PopOutTooltip => ImGuiPopOuts.InPopOutFrame + ? "Dock back into the game window" : "Pop out into a floating window"; + + /// <summary>A face's own pop-out button: pops out, or docks back while popped out. AC thread, in Draw.</summary> + public static void TogglePopOut(string title) + { + if (ImGuiPopOuts.InPopOutFrame) Redock(title); + else PopOut(title); + } + + /// <summary>True when the panel is open in its own window. Any thread (racy read).</summary> + public static bool IsPopped(string title) + { + Entry? entry; + lock (Sync) Entries.TryGetValue(title, out entry); + return entry != null && entry.Popped; + } + + /// <summary> + /// The docked face switched from ImGui to Avalonia while open: close the + /// ImGui face, save "docked, open" at its placement, then open the Avalonia + /// face there. One ordered step, like PopOut. + /// </summary> + public static void HandOffToAvalonia(string title) => Request(title, RequestKind.ToAvaloniaDocked); + + private static void Request(string title, RequestKind kind) + { + lock (Sync) + { + if (!Entries.ContainsKey(title)) return; + if (kind is RequestKind.PopOut or RequestKind.Redock) + { + // Moves an open panel between the client and its own window. + if (!_open.Contains(title)) return; + } + else + { + bool open = kind == RequestKind.Open; + var next = new HashSet<string>(_open, StringComparer.OrdinalIgnoreCase); + if (!(open ? next.Add(title) : next.Remove(title))) return; + System.Threading.Volatile.Write(ref _open, next); + } + } + Requests.Enqueue((title, kind)); + } + + /// <summary>One line per face that is requested open or shown. Diagnostics; any thread (racy reads).</summary> + public static List<string> DescribeFaces() + { + var lines = new List<string>(); + List<Entry> order; + lock (Sync) order = DrawOrder; + foreach (Entry e in order) + { + if (!e.Shown && !IsOpen(e.Title)) continue; + lines.Add($"face {e.Title}: requested={IsOpen(e.Title)} shown={e.Shown} pos=({e.Pos.X:0},{e.Pos.Y:0}) size=({e.Size.X:0}x{e.Size.Y:0}) failures={e.Failures}{(e.Error != null ? " error=" + e.Error : "")}"); + } + if (lines.Count == 0) lines.Add("faces: none open"); + return lines; + } + + // ── Helpers for panel faces (AC thread, inside the panel's Draw) ───── + + /// <summary> + /// Makes the last item a drag handle for its panel window (chromeless + /// panels drag from their own title row, like the Avalonia face's + /// AttachDragHandle). Clamped to the client area. + /// </summary> + public static void DragWindowWithLastItem() + { + if (ImGuiPopOuts.InPopOutFrame) + { + // Popped out: the OS window moves (it follows the cursor from here on). + if (ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 2f)) + ImGuiPopOuts.BeginMoveCurrent(); + return; + } + if (!ImGuiNET.ImGui.IsItemActive() || !ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 0f)) return; + // The panel body is a child window; move its parent (the panel window). + _pendingDragDelta += ImGuiNET.ImGui.GetIO().MouseDelta; + } + + /// <summary>Asks for a new window size (logical units), applied on the next frame it draws. Any thread.</summary> + public static void RequestSize(string title, Vector2 logicalSize) + { + lock (Sync) + { + if (!Entries.TryGetValue(title, out Entry? entry)) return; + entry.RequestedSize = logicalSize; + entry.HasRequest = true; + } + } + + /// <summary> + /// Asks for a new window position (logical units), applied on the next frame it + /// draws docked, clamped to the client area. It is not saved as a move by the + /// player. A request queued with an Open survives the open's placement. Any thread. + /// </summary> + public static void RequestPos(string title, Vector2 logicalPos) + { + lock (Sync) + { + if (!Entries.TryGetValue(title, out Entry? entry)) return; + entry.RequestedPos = logicalPos; + entry.HasRequest = true; + } + } + + /// <summary> + /// True while an Open or Close for <paramref name="title"/> is queued but not yet + /// applied on AC's thread (the requested state differs from what is drawn). Any thread (racy). + /// </summary> + public static bool IsTransitioning(string title) + { + Entry? entry; + lock (Sync) Entries.TryGetValue(title, out entry); + return entry != null && entry.Shown != IsOpen(title); + } + + private static Vector2 _pendingDragDelta; + + // Chromeless-panel corner resize in progress: which panel, and where it began. + private static string? _resizeTitle; + private static Vector2 _resizeStartSize, _resizeStartMouse; + + /// <summary> + /// While a GripInBody face draws: the width (px) at the body's right edge, + /// across the bottom <see cref="BodyGripReserve"/> px, that the grip covers + /// and the face must leave free. 0 for every other face. AC thread. + /// </summary> + public static float BodyGripReserve { get; private set; } + + // ── Frame (AC thread) ────────────────────────────────────────────── + + /// <summary> + /// Draws every open face. <paramref name="uiScale"/> is the scale fonts + /// were built for; placement uses the Avalonia overlay's scale so a panel + /// lands where its Avalonia face would. + /// </summary> + public static void DrawAll(float uiScale) + { + float placeScale = PlacementScale(); + while (Requests.TryDequeue(out var req)) + Apply(req.Title, req.Kind, placeScale); + RemoveUnregistered(); + + List<Entry> order; + lock (Sync) order = DrawOrder; + foreach (Entry entry in order) + { + if (!entry.Shown || entry.Popped) continue; + if (HiddenWhileDocked(entry)) + { + if (_resizeTitle == entry.Title) _resizeTitle = null; // hid mid-resize: free the grip + continue; + } + DrawPanel(entry, uiScale, placeScale, null); + } + } + + private static bool HiddenWhileDocked(Entry entry) + { + if (entry.Error != null) return false; // an error line is always shown + try { return entry.Instance?.HiddenWhileDocked ?? false; } + catch { return false; } + } + + /// <summary> + /// Draws a popped-out panel filling its own window (<paramref name="display"/> + /// px). AC thread, called by ImGuiPopOuts with the pop-out's context current. + /// </summary> + public static void DrawPopped(string title, float uiScale, Vector2 display) + { + Entry? entry; + lock (Sync) Entries.TryGetValue(title, out entry); + if (entry == null || !entry.Shown || !entry.Popped) return; + DrawPanel(entry, uiScale, PlacementScale(), display); + } + + /// <summary>A pop-out window was moved or resized by the user: save it. Game thread.</summary> + public static void OnPopOutGeometry(string title, int left, int top, int width, int height) + { + Entry? entry; + lock (Sync) Entries.TryGetValue(title, out entry); + if (entry == null || !entry.Popped) return; + PersistPopped(entry, open: true, left, top, width, height, PlacementScale()); + } + + /// <summary> + /// Once per engine load, in the world: docked panels that were open and + /// whose docked face is ImGui (or Both) reopen here. (The Avalonia overlay + /// skips those in its own restore.) AC thread. + /// </summary> + public static void RestoreOnce() + { + if (_restored) return; + _restored = true; + List<string> titles = new(); + // Script windows (dynamic) open when their owner says so, not from the saved state. + lock (Sync) + foreach (Entry e in Entries.Values) + if (!e.Dynamic) titles.Add(e.Title); + foreach (string title in titles) + { + if (!PanelStateStore.TryGetPanel(title, out PanelStateStore.PanelEntry saved)) continue; + if (!saved.Open) continue; + PanelFace face = PanelRouter.ResolveDockedFace(title); + if (face is not (PanelFace.ImGui or PanelFace.Both)) continue; + // Saved popped out: it reopens popped out (Apply reads the saved entry). + Open(title); + } + } + + /// <summary>Client pixels per logical unit (the unit PanelSpec sizes, MinSize and RequestSize use).</summary> + internal static float PlacementScale() + { + // Saved positions are in Avalonia logical units. Without the Avalonia overlay + // (off, or the CoreCLR engine) the ImGui DPI scale is the same conversion. + float s = AvaloniaOverlay.IsRunning ? AvaloniaOverlay.InputScale : EngineFrameController.FontScale; + return s > 0f ? s : 1f; + } + + private static void Apply(string title, RequestKind kind, float placeScale) + { + Entry? entry; + lock (Sync) Entries.TryGetValue(title, out entry); + if (entry == null) return; + + if (kind == RequestKind.PopOut) + { + if (entry.Shown && !entry.Popped) StartPopOut(entry, placeScale, fromSaved: false); + return; + } + if (kind == RequestKind.Redock) + { + if (!entry.Shown || !entry.Popped) return; + ImGuiPopOuts.Close(title); + entry.Popped = false; + entry.NeedsPlacement = true; // back where it was docked + Persist(entry, open: true, placeScale); + return; + } + + bool open = kind == RequestKind.Open; + if (entry.Shown == open) return; + + if (open) + { + PlaceFromSavedState(entry, placeScale); + entry.Failures = 0; + entry.Error = null; + try + { + entry.Instance = entry.Factory(); + entry.Instance.OnShown(); + } + catch (Exception ex) + { + entry.Error = $"{title} failed to open: {ex.Message}"; + RynthLog.UI($"ImGuiPanelHost: {title} factory/OnShown threw {ex.GetType().Name}: {ex.Message}"); + } + entry.Shown = true; + System.Threading.Interlocked.Increment(ref _shownCount); + // One panel on screen once: close any Avalonia copy of it (script windows have none). + if (!entry.Dynamic) AvaloniaOverlay.CloseAvaloniaCopy(title); + // Last left popped out: it opens popped out again, where it was. + if (PanelRouter.CanPopOut && !entry.Spec.NoPopOut + && PanelStateStore.TryGetPanel(title, out PanelStateStore.PanelEntry saved) && saved.Floating) + StartPopOut(entry, placeScale, fromSaved: true); + else + Persist(entry, open: true, placeScale); // reopen here after a restart + } + else + { + bool wasPopped = entry.Popped; + if (wasPopped) + { + ImGuiPopOuts.Close(title); + entry.Popped = false; + } + try { entry.Instance?.OnHidden(); } + catch (Exception ex) { RynthLog.UI($"ImGuiPanelHost: {title}.OnHidden threw {ex.GetType().Name}: {ex.Message}"); } + entry.Instance = null; + entry.Shown = false; + System.Threading.Interlocked.Decrement(ref _shownCount); + if (kind is RequestKind.PopOut or RequestKind.ToAvaloniaDocked) + { + // Save the placement as open (popped out or docked), then let the + // Avalonia face open: its toggle reads that entry, so a popped-out + // one opens at its saved screen position. + Persist(entry, open: true, placeScale, floating: kind == RequestKind.PopOut); + UiBackgroundWriter.Enqueue($"hand off {title}", () => AvaloniaOverlay.ActivateBarButton(title)); + } + else if (wasPopped) + { + // Closed while popped out: it reopens popped out, where it was. + PanelStateStore.TryGetPanel(title, out PanelStateStore.PanelEntry prior); + PersistPopped(entry, open: false, (int)prior.FloatingLeft, (int)prior.FloatingTop, + (int)(entry.Size.X), (int)(entry.Size.Y), placeScale, keepSize: true); + } + else + { + Persist(entry, open: false, placeScale); + } + } + } + + /// <summary> + /// Opens <paramref name="entry"/>'s own window: at its saved popped-out + /// position, or where it sits in the client. AC thread, main context current. + /// </summary> + private static void StartPopOut(Entry entry, float placeScale, bool fromSaved) + { + float s = UiScaleForChrome(); + Vector2 size = entry.Size; + Vector2 origin = ImGuiPopOuts.ClientOriginOnScreen(); + int left = (int)(origin.X + entry.Pos.X), top = (int)(origin.Y + entry.Pos.Y); + if (PanelStateStore.TryGetPanel(entry.Title, out PanelStateStore.PanelEntry saved) + && (saved.FloatingLeft != 0 || saved.FloatingTop != 0) && (fromSaved || saved.Floating)) + { + left = (int)Math.Round(saved.FloatingLeft); + top = (int)Math.Round(saved.FloatingTop); + } + bool standard = entry.Spec.Chrome == PanelChrome.Standard; + int caption = standard ? (int)(RynthTheme.HeaderHeight * s) : 0; + int buttons = standard ? (int)HeaderButtonsWidth(entry, s, popped: true) : 0; + ImGuiPopOuts.Open(entry.Title, left, top, (int)size.X, (int)size.Y, caption, buttons, s); + entry.Popped = true; + PersistPopped(entry, open: true, left, top, (int)size.X, (int)size.Y, placeScale); + } + + private static float UiScaleForChrome() => EngineFrameController.FontScale; + + private static void PlaceFromSavedState(Entry entry, float placeScale) + { + Vector2 size = entry.Spec.DefaultSize; + Vector2 pos; + if (PanelStateStore.TryGetPanel(entry.Title, out PanelStateStore.PanelEntry saved) && (saved.Width > 0 || saved.Left != 0 || saved.Top != 0)) + { + pos = new Vector2((float)saved.Left, (float)saved.Top); + if (saved.Width > 0 && saved.Height > 0) size = new Vector2((float)saved.Width, (float)saved.Height); + } + else if (entry.Spec.DefaultPos is Vector2 defaultPos) + { + pos = defaultPos; // the face's own first spot (a script window's FirstUseEver position) + } + else if (entry.Spec.OpenCentered && CenteredLogicalPos(size, placeScale) is Vector2 centered) + { + pos = centered; + } + else + { + int shown = 0; + lock (Sync) foreach (Entry e in DrawOrder) if (e.Shown) shown++; + pos = new Vector2(100 + shown * 20, 100 + shown * 20); // Avalonia's cascade + } + + size = Vector2.Max(size, entry.Spec.MinSize); + // Side-by-side check: the ImGui copy sits offset from the Avalonia one. + if (PanelRouter.ResolveDockedFace(entry.Title) == PanelFace.Both) + pos += new Vector2(24, 24); + + entry.Pos = ClampToDisplay(pos * placeScale, size * placeScale); + entry.Size = size * placeScale; + entry.PersistedPos = entry.Pos; + entry.PersistedSize = entry.Size; + entry.NeedsPlacement = true; + entry.DesiredPos = entry.Pos != pos * placeScale ? pos * placeScale : null; + entry.DesiredForDisplay = ImGuiNET.ImGui.GetIO().DisplaySize; + + // Popped-out windows sit above the game frame, so a docked panel opening under + // one would be invisible. The new spot is saved by the open's Persist, so the + // panel comes back where it could be seen. + if (ClearOfPopOuts(entry.Pos, entry.Size) is Vector2 clear) + { + RynthLog.UI($"ImGuiPanelHost: {entry.Title} would open under a popped-out window; " + + $"moved from ({entry.Pos.X:0},{entry.Pos.Y:0}) to ({clear.X:0},{clear.Y:0})."); + entry.Pos = clear; + entry.PersistedPos = clear; + entry.DesiredPos = null; // don't pull it back under the pop-out as the display grows + } + } + + /// <summary>Above this share of a docked panel hidden by popped-out windows, it opens elsewhere.</summary> + private const float MaxCoveredFraction = 0.5f; + /// <summary>Candidate spots per axis when looking for a clear place (a grid over the game view).</summary> + private const int ClearSpotSteps = 8; + + /// <summary> + /// A spot (client px) for a docked window of <paramref name="size"/> at <paramref name="pos"/> + /// that popped-out windows hide less, nearest the original among the least-covered; null when + /// at most half of it is covered or no spot is better. + /// </summary> + private static Vector2? ClearOfPopOuts(Vector2 pos, Vector2 size) + { + float area = size.X * size.Y; + if (area <= 0) return null; + List<(Vector2 Min, Vector2 Max)> covers = PopOutRectsInClient(); + if (covers.Count == 0) return null; + float covered = CoveredArea(pos, size, covers); + if (covered <= area * MaxCoveredFraction) return null; + + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + if (display.X <= 1 || display.Y <= 1) return null; + Vector2 room = Vector2.Max(Vector2.Zero, display - size); + + // Pass 1: the least coverage any grid spot reaches. Pass 2: the nearest spot within + // 2% of the panel's area of that, so a nearly-as-clear nearby spot beats a far one. + float least = float.MaxValue; + for (int i = 0; i <= ClearSpotSteps; i++) + for (int j = 0; j <= ClearSpotSteps; j++) + least = Math.Min(least, CoveredArea(GridSpot(room, i, j), size, covers)); + if (least >= covered) return null; + + float tolerance = least + area * 0.02f; + Vector2? best = null; + float bestDist = float.MaxValue; + for (int i = 0; i <= ClearSpotSteps; i++) + for (int j = 0; j <= ClearSpotSteps; j++) + { + Vector2 spot = GridSpot(room, i, j); + if (CoveredArea(spot, size, covers) > tolerance) continue; + float dist = Vector2.DistanceSquared(spot, pos); + if (dist < bestDist) { bestDist = dist; best = spot; } + } + return best; + } + + private static Vector2 GridSpot(Vector2 room, int i, int j) => + new(MathF.Round(room.X * i / ClearSpotSteps), MathF.Round(room.Y * j / ClearSpotSteps)); + + /// <summary>Visible popped-out windows' rects in the game window's client px (ImGui coordinates).</summary> + private static List<(Vector2 Min, Vector2 Max)> PopOutRectsInClient() + { + Vector2 origin = ImGuiPopOuts.ClientOriginOnScreen(); + var rects = new List<(Vector2, Vector2)>(); + foreach (var (left, top, width, height) in UI.LayeredWindow.VisibleContentRects()) + { + var min = new Vector2(left, top) - origin; + rects.Add((min, min + new Vector2(width, height))); + } + return rects; + } + + /// <summary>Area of the window hidden by <paramref name="covers"/> (overlaps between covers count twice).</summary> + private static float CoveredArea(Vector2 pos, Vector2 size, List<(Vector2 Min, Vector2 Max)> covers) + { + Vector2 max = pos + size; + float total = 0; + foreach (var (cMin, cMax) in covers) + { + float w = MathF.Min(max.X, cMax.X) - MathF.Max(pos.X, cMin.X); + float h = MathF.Min(max.Y, cMax.Y) - MathF.Max(pos.Y, cMin.Y); + if (w > 0 && h > 0) total += w * h; + } + return total; + } + + /// <summary> + /// Top-left (logical units) that centres a window of logical <paramref name="size"/> in the + /// game view; null while the display size isn't known yet. + /// </summary> + private static Vector2? CenteredLogicalPos(Vector2 size, float placeScale) + { + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + if (display.X <= 1 || display.Y <= 1 || placeScale <= 0) return null; + return Vector2.Max(Vector2.Zero, (display / placeScale - size) * 0.5f); + } + + private static Vector2 ClampToDisplay(Vector2 pos, Vector2 size) + { + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + if (display.X <= 1 || display.Y <= 1) return pos; + return new Vector2( + Math.Clamp(pos.X, 0, Math.Max(0, display.X - size.X)), + Math.Clamp(pos.Y, 0, Math.Max(0, display.Y - size.Y))); + } + + /// <param name="popDisplay">The pop-out window's size when drawing popped out; null in the client.</param> + private static void DrawPanel(Entry entry, float uiScale, float placeScale, Vector2? popDisplay) + { + PanelSpec spec = entry.Spec; + bool popped = popDisplay.HasValue; + bool standard = spec.Chrome == PanelChrome.Standard; + bool both = PanelRouter.ResolveDockedFace(entry.Title) == PanelFace.Both; + + Vector2 minSize = (entry.Instance?.MinSize ?? spec.MinSize) * placeScale; + if (popped) + { + // The panel fills its window; moving and resizing are the window's. + // (At the pop-out's panel origin: its display is the work area around it.) + ImGuiNET.ImGui.SetNextWindowPos(ImGuiPopOuts.PanelOrigin, ImGuiCond.Always); + ImGuiNET.ImGui.SetNextWindowSize(popDisplay!.Value, ImGuiCond.Always); + minSize = Vector2.Zero; + } + else + { + if (entry.HasRequest) + { + Vector2? reqSize, reqPos; + lock (Sync) + { + reqSize = entry.RequestedSize; + reqPos = entry.RequestedPos; + entry.RequestedSize = null; + entry.RequestedPos = null; + entry.HasRequest = false; + } + if (reqSize is Vector2 requested) + { + entry.Size = Vector2.Max(requested * placeScale, minSize); + entry.NeedsPlacement = true; + // A script's size request is its own, not the player's: not saved. + if (entry.Dynamic) entry.PersistedSize = entry.Size; + } + if (reqPos is Vector2 requestedPos) + { + entry.Pos = ClampToDisplay(requestedPos * placeScale, entry.Size); + entry.PersistedPos = entry.Pos; // not a move by the player: nothing to save + entry.DesiredPos = null; + entry.NeedsPlacement = true; + } + } + if (entry.DesiredPos is Vector2 want) + { + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + if (display != entry.DesiredForDisplay) + { + entry.DesiredForDisplay = display; + Vector2 p = ClampToDisplay(want, entry.Size); + if (p != entry.Pos) + { + entry.Pos = p; + entry.PersistedPos = p; // not a move by the player: nothing to save + entry.NeedsPlacement = true; + } + if (p == want) entry.DesiredPos = null; // back where it was saved + } + } + if (entry.NeedsPlacement) + { + ImGuiNET.ImGui.SetNextWindowPos(entry.Pos, ImGuiCond.Always); + ImGuiNET.ImGui.SetNextWindowSize(entry.Size, ImGuiCond.Always); + entry.NeedsPlacement = false; + } + ImGuiNET.ImGui.SetNextWindowSizeConstraints(minSize, new Vector2(float.MaxValue, float.MaxValue)); + } + + uint background = spec.Background ?? RynthTheme.PanelGlass; + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, spec.Rounding); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, spec.Chrome == PanelChrome.None ? 0f : 1f); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, background); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, spec.BorderColor ?? RynthTheme.PanelBorder); + + ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoCollapse + | ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse + | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoMove; + bool clickThrough = false; + // Popped out, a panel is always interactive (like the Avalonia pop-out was). + if (!popped) try { clickThrough = entry.Instance?.ClickThrough ?? false; } catch { } + if (clickThrough) flags |= ImGuiWindowFlags.NoInputs; + + bool childOpen = false; + ImGuiNET.ImGui.Begin(entry.WindowId, flags); + try + { + ImGuiNET.ImGui.PopStyleVar(3); // the frame's own vars; the body gets normal padding + float header = standard ? RynthTheme.HeaderHeight * uiScale : 0f; + float grip = standard ? 18f * uiScale : 0f; + + if (standard && DrawHeader(entry, uiScale, both, popped)) + return; // closed, popped out or docked back this frame + + ImGuiNET.ImGui.SetCursorPos(new Vector2(0, header)); + // Per-panel text size (Settings > Display): the face's fonts come from the + // set baked at that size (ImGuiFonts.Get); the header above keeps its size. + // (Until a size change has been re-baked, the nearest size that is.) + ImGuiFonts.CurrentStep = ImGuiFonts.BakedStepNear(PanelTextScale.Get(entry.Title)); + // Chromeless panels (the dashboard) have no frame to hold the grip, so it + // sits over the body's bottom-right corner. It is handled by hand instead + // of as an ImGui item: an item there competed with the face's own items + // (the drag-anywhere surface) and with the body's scrollbar, so resizing + // worked only sometimes. The mouse is tested against the corner directly, + // the resize follows the mouse from where the drag began (no per-frame + // drift), and the face's window-drag is ignored while resizing. + // A GripInBody face (standard chrome, no strip under the body) is handled + // the same way, over the corner the face leaves free. + bool inlineGrip = standard && spec.GripInBody; + bool manualGrip = (!standard || inlineGrip) && !clickThrough && !popped; // popped: the window resizes itself + Vector2 outerPos = ImGuiNET.ImGui.GetWindowPos(), outerSize = ImGuiNET.ImGui.GetWindowSize(); + float gSize = GripSize(entry, uiScale); + Vector2 gMin = GripMin(entry, uiScale, outerPos + outerSize); + bool resizing = false, gHot = false; + if (manualGrip) + { + Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); + bool over = ImGuiNET.ImGui.IsMouseHoveringRect(gMin, gMin + new Vector2(gSize, gSize), false) + && ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem); + if (over && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left) && _resizeTitle == null) + { + _resizeTitle = entry.Title; + _resizeStartSize = outerSize; + _resizeStartMouse = mouse; + } + resizing = _resizeTitle == entry.Title; + if (resizing && !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) + { + _resizeTitle = null; + resizing = false; + } + if (resizing) + { + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + Vector2 maxSize = display.X > 1 ? display - outerPos : new Vector2(float.MaxValue, float.MaxValue); + Vector2 next = Vector2.Clamp(_resizeStartSize + (mouse - _resizeStartMouse), minSize, Vector2.Max(minSize, maxSize)); + if (next != outerSize) ImGuiNET.ImGui.SetWindowSize(next); + } + gHot = over || resizing; + if (gHot) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.ResizeNWSE); + } + + // While the body scrolls, end it above the corner so its scrollbar can't + // take the grip's clicks. Held for the length of a resize so the body + // doesn't flip between the two heights mid-drag. + // (A popped GripInBody face too: its window's own corner grip sits there.) + bool gripOverBody = manualGrip || (popped && inlineGrip); + float gripRoom = standard && !inlineGrip ? grip + : resizing ? entry.LastGripRoom + : (entry.BodyScrolls && gripOverBody ? (gSize + (spec.GoldGrip ? 4f : 1f) * uiScale) : 0f); + entry.LastGripRoom = gripRoom; + Vector2 bodySize = ImGuiNET.ImGui.GetWindowSize() - new Vector2(0, header + gripRoom); + if (bodySize.Y < 1) bodySize.Y = 1; + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, spec.EdgeToEdge ? Vector2.Zero : new Vector2(6, 4) * uiScale); + ImGuiWindowFlags bodyFlags = ImGuiWindowFlags.NoBackground; + if (spec.EdgeToEdge) bodyFlags |= ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse; + bodyFlags |= spec.BodyFlags; + if (clickThrough) bodyFlags |= ImGuiWindowFlags.NoInputs; + childOpen = ImGuiNET.ImGui.BeginChild("##body", bodySize, ImGuiChildFlags.AlwaysUseWindowPadding, bodyFlags); + ImGuiNET.ImGui.PopStyleVar(); + + if (childOpen) + { + if (entry.Error != null) + { + // Never a format string: the error names the panel key (a script window's + // key is script text, e.g. a hud called "50%s") and an exception message. + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1f, 0.4f, 0.3f, 1f)); + ImGuiNET.ImGui.PushTextWrapPos(0f); + ImGuiNET.ImGui.TextUnformatted(entry.Error); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + } + else if (entry.Instance != null) + { + // Only while the body covers the corner (not when it scrolls and ends above it). + BodyGripReserve = inlineGrip && gripRoom == 0f ? gSize + 1f * uiScale : 0f; + try { DrawBody(entry); } + finally { BodyGripReserve = 0f; } + } + // Grip painted on top of the face when the body covers the corner + // (a GripInBody face's even while it lets clicks through: its slot stays). + if ((manualGrip || inlineGrip || (popped && !standard)) && gripRoom == 0f) + GripPaint(entry, uiScale, gMin, gHot, ImGuiNET.ImGui.GetWindowDrawList()); + entry.BodyScrolls = ImGuiNET.ImGui.GetScrollMaxY() > 0f; + } + ImGuiNET.ImGui.EndChild(); + childOpen = false; + + if (gripOverBody && gripRoom > 0f) + GripPaint(entry, uiScale, gMin, gHot, ImGuiNET.ImGui.GetWindowDrawList()); + // Framed panels: the grip is an ordinary item in the frame's corner. + // Popped out it's only painted: the window's own corner resizes it. + if (standard && !inlineGrip && popped) + GripPaint(entry, uiScale, GripMin(entry, uiScale, outerPos + outerSize), false, ImGuiNET.ImGui.GetWindowDrawList()); + else if (standard && !inlineGrip && !clickThrough) + DrawGrip(entry, uiScale, minSize); + if (resizing) _pendingDragDelta = Vector2.Zero; // the face's window-drag doesn't also move it + + // A drag started from the panel's own surface (DragWindowWithLastItem). + if (popped) _pendingDragDelta = Vector2.Zero; + if (_pendingDragDelta != Vector2.Zero) + { + ImGuiNET.ImGui.SetWindowPos(ClampToDisplay(ImGuiNET.ImGui.GetWindowPos() + _pendingDragDelta, ImGuiNET.ImGui.GetWindowSize())); + _pendingDragDelta = Vector2.Zero; + } + } + finally + { + ImGuiFonts.CurrentStep = 0; + if (childOpen) ImGuiNET.ImGui.EndChild(); + if (!popped) + { + // Popped out, Pos/Size keep the docked placement to return to. + entry.Pos = ImGuiNET.ImGui.GetWindowPos(); + entry.Size = ImGuiNET.ImGui.GetWindowSize(); + } + ImGuiNET.ImGui.End(); + ImGuiNET.ImGui.PopStyleColor(2); + } + + // Persist once a move/resize has finished (not every frame of a drag). + if (!popped && !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) + && (entry.Pos != entry.PersistedPos || entry.Size != entry.PersistedSize)) + { + entry.PersistedPos = entry.Pos; + entry.PersistedSize = entry.Size; + entry.DesiredPos = null; // the player placed it: that is the spot now + Persist(entry, open: true, placeScale); + } + } + + /// <summary>The panel whose face is drawing right now (names a text box's owner in the input log). AC thread.</summary> + internal static string? DrawingTitle { get; private set; } + + private static void DrawBody(Entry entry) + { + DrawingTitle = entry.Title; + try + { + entry.Instance!.Draw(); + } + catch (Exception ex) + { + entry.Failures++; + RynthLog.UI($"ImGuiPanelHost: {entry.Title}.Draw threw {ex.GetType().Name}: {ex.Message} ({entry.Failures}/{MaxFailures})"); + if (entry.Failures >= MaxFailures) + entry.Error = $"{entry.Title} stopped drawing after repeated errors: {ex.Message}"; + } + finally + { + DrawingTitle = null; + } + } + + private static float HeaderButtonsWidth(Entry entry, float s, bool popped) + { + float btn = 20f * s; + bool second = popped || (PanelRouter.CanPopOut && !entry.Spec.NoPopOut); + // close, [pop-out / dock back], text size + return btn + 2 * s + (second ? btn + 2 * s : 0) + btn + 4 * s; + } + + /// <summary>The standard header. Returns true when the panel was closed, popped out or docked back.</summary> + private static bool DrawHeader(Entry entry, float s, bool bothTag, bool popped) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 winPos = ImGuiNET.ImGui.GetWindowPos(); + float width = ImGuiNET.ImGui.GetWindowWidth(); + float h = RynthTheme.HeaderHeight * s; + float r = entry.Spec.Rounding; + dl.AddRectFilled(winPos, winPos + new Vector2(width, h), RynthTheme.PanelHeader, r, ImDrawFlags.RoundCornersTop); + + float btn = 20f * s; + // In Both (side-by-side) the Avalonia copy owns pop-out. + bool canPopOut = popped || (PanelRouter.CanPopOut && !bothTag && !entry.Spec.NoPopOut); + float buttonsWidth = HeaderButtonsWidth(entry, s, popped); + + // Drag surface: the header minus the buttons. Popped out, the window drags + // itself from this band (LayeredWindow.CaptionHeight) and never shows it to ImGui. + ImGuiNET.ImGui.SetCursorPos(Vector2.Zero); + ImGuiNET.ImGui.InvisibleButton("##drag", new Vector2(Math.Max(1, width - buttonsWidth), h)); + if (!popped && ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 0f)) + { + Vector2 next = ClampToDisplay(winPos + ImGuiNET.ImGui.GetIO().MouseDelta, ImGuiNET.ImGui.GetWindowSize()); + ImGuiNET.ImGui.SetWindowPos(next); + } + + // Grip dots + DRAG (teal, 9) + title (10), vertically centred. + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + float dragY = (h - ImGuiNET.ImGui.GetTextLineHeight()) * 0.5f; + dl.AddText(winPos + new Vector2(6 * s, dragY), RynthTheme.DragLabel, DragLabel); + float dragW = ImGuiNET.ImGui.CalcTextSize(DragLabel).X - 2 * s; + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + float titleY = (h - ImGuiNET.ImGui.GetTextLineHeight()) * 0.5f; + string title = bothTag ? entry.BothTitle : entry.DisplayTitle; + dl.AddText(winPos + new Vector2(8 * s + dragW + 6 * s, titleY), ImGuiNET.ImGui.GetColorU32(ImGuiCol.Text), title); + + bool gone = false; + float y = (h - btn) * 0.5f; + float x = width - 4 * s - btn; + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero); + ImGuiNET.ImGui.SetCursorPos(new Vector2(x, y)); + if (HeaderIconButton("##close", PhosphorIcons.X, btn)) + { + Close(entry.Title); + gone = true; + } + ImGuiNET.ImGui.SetItemTooltip("Close"); + if (canPopOut) + { + ImGuiNET.ImGui.SetCursorPos(new Vector2(x - 2 * s - btn, y)); + if (popped) + { + if (HeaderIconButton("##redock", PhosphorIcons.ArrowSquareIn, btn)) + { + Redock(entry.Title); + gone = true; + } + ImGuiNET.ImGui.SetItemTooltip("Dock back into the game window"); + } + else + { + if (HeaderIconButton("##popout", PhosphorIcons.ArrowSquareOut, btn)) + { + PopOut(entry.Title); + gone = true; + } + ImGuiNET.ImGui.SetItemTooltip("Pop out into a floating window"); + } + } + + // Text size (the same per-panel setting as Settings > Display). + float tsX = x - (canPopOut ? btn + 2 * s : 0) - 2 * s - btn; + ImGuiNET.ImGui.SetCursorPos(new Vector2(tsX, y)); + int step = PanelTextScale.Get(entry.Title); + if (HeaderIconButton("##textsize", PhosphorIcons.TextAa, btn, step != 0 ? RynthTheme.DragLabel : (uint?)null)) + ImGuiNET.ImGui.OpenPopup(TextSizePopupId); + if (ImGuiNET.ImGui.BeginItemTooltip()) + { + ImGuiNET.ImGui.TextUnformatted("Text size: " + PanelTextScale.Describe(step)); + ImGuiNET.ImGui.TextDisabled("Click to change. Ctrl+wheel on the title bar steps it."); + ImGuiNET.ImGui.EndTooltip(); + } + ImGuiNET.ImGui.PopStyleVar(); + + // Ctrl+wheel anywhere on the title bar steps this window's size. Only the + // header: the body's wheel belongs to the face (lists, chat, radar zoom). + // Popped out, the drag band is the window's own caption and never reaches + // ImGui, so there it works over the buttons. + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + if (!gone && io.KeyCtrl && io.MouseWheel != 0f + && ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) + && ImGuiNET.ImGui.IsMouseHoveringRect(winPos, winPos + new Vector2(width, h), false)) + { + PanelTextScale.SetForWindow(entry.Title, step + (io.MouseWheel > 0f ? 1 : -1)); + } + + // Under the header, right-aligned to the button: never over a pop-out's drag band. + ImGuiNET.ImGui.SetNextWindowPos(winPos + new Vector2(tsX + btn, h), ImGuiCond.Appearing, new Vector2(1, 0)); + DrawTextSizePopup(entry.Title, s); + + ImGuiNET.ImGui.PopFont(); + return gone; + } + + private const string TextSizePopupId = "##textsize_pop"; + + private static string[]? _textSizeMenuLabels; + + /// <summary> + /// A "Text size" submenu for a chromeless panel's own menu (it has no title bar + /// to hold the button): the steps, then "Use for all windows". AC thread. + /// </summary> + public static void TextSizeMenu(string title) + { + if (!ImGuiNET.ImGui.BeginMenu("Text size")) return; + try + { + string[] labels = _textSizeMenuLabels ??= BuildTextSizeMenuLabels(); + int step = PanelTextScale.Get(title); + for (int i = 0; i < labels.Length; i++) + if (ImGuiNET.ImGui.MenuItem(labels[i], "", i == step) && i != step) + PanelTextScale.SetForWindow(title, i); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Use for all windows")) + PanelTextScale.UseForAll(step); + } + finally + { + ImGuiNET.ImGui.EndMenu(); + } + } + + private static string[] BuildTextSizeMenuLabels() + { + var labels = new string[PanelTextScale.SizeNames.Length]; + for (int i = 0; i < labels.Length; i++) + labels[i] = i == 0 ? "Normal" : PanelTextScale.Describe(i); + return labels; + } + + /// <summary>The title bar's text size popup: smaller / bigger, a slider over the steps, reset, use everywhere.</summary> + private static void DrawTextSizePopup(string title, float s) + { + if (!ImGuiNET.ImGui.BeginPopup(TextSizePopupId)) return; + try + { + int step = PanelTextScale.Get(title); + int max = PanelTextScale.SizeNames.Length - 1; + int all = PanelTextScale.GetAll(); + float btn = 20f * s; + + ImGuiNET.ImGui.TextUnformatted("Text size"); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero); + ImGuiNET.ImGui.BeginDisabled(step <= 0); + if (HeaderIconButton("##ts_smaller", PhosphorIcons.Minus, btn)) + PanelTextScale.SetForWindow(title, step - 1); + ImGuiNET.ImGui.EndDisabled(); + ImGuiNET.ImGui.SetItemTooltip("Smaller"); + ImGuiNET.ImGui.SameLine(0, 4 * s); + ImGuiNET.ImGui.BeginDisabled(step >= max); + if (HeaderIconButton("##ts_bigger", PhosphorIcons.Plus, btn)) + PanelTextScale.SetForWindow(title, step + 1); + ImGuiNET.ImGui.EndDisabled(); + ImGuiNET.ImGui.SetItemTooltip("Bigger"); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.SameLine(0, 8 * s); + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextUnformatted(PanelTextScale.Describe(step)); + + int pick = step; + ImGuiNET.ImGui.SetNextItemWidth(btn * 2 + 4 * s + 8 * s + 110 * s); + if (ImGuiNET.ImGui.SliderInt("##ts_step", ref pick, 0, max, "%d", ImGuiSliderFlags.AlwaysClamp) && pick != step) + PanelTextScale.SetForWindow(title, pick); + + ImGuiNET.ImGui.BeginDisabled(step == all); + if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + " Reset")) + PanelTextScale.ResetWindow(title); + ImGuiNET.ImGui.EndDisabled(); + ImGuiNET.ImGui.SetItemTooltip(all == 0 ? "Back to normal size" : "Back to the All Panels size (Settings > Display)"); + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.Button("Use for all windows")) + PanelTextScale.UseForAll(step); + ImGuiNET.ImGui.SetItemTooltip("Every in-game window at this size (Settings > Display > All Panels)"); + } + finally + { + ImGuiNET.ImGui.EndPopup(); + } + } + + private const string DragLabel = PhosphorIcons.DotsSixVertical + "DRAG"; + + /// <summary>A header button (the theme's button look) with an icon centred on it.</summary> + private static bool HeaderIconButton(string id, string icon, float size, uint? color = null) + { + Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos(); + bool clicked = ImGuiNET.ImGui.Button(id, new Vector2(size, size)); + PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(UiFont.Ui14), icon, at, + new Vector2(size, size), color ?? ImGuiNET.ImGui.GetColorU32(ImGuiCol.Text)); + return clicked; + } + + /// <summary>The resize grip at the bottom-right (16 px, teal, rounded outer corner).</summary> + private static float GripSize(Entry entry, float s) => (entry.Spec.GoldGrip ? 14f : 16f) * s; + + /// <summary>Top-left of the grip for a corner (bottom-right point).</summary> + private static Vector2 GripMin(Entry entry, float s, Vector2 corner) + { + float size = GripSize(entry, s); + float inset = (entry.Spec.GoldGrip ? 4f : 1f) * s; + return corner - new Vector2(size + inset, size + inset); + } + + private static bool DrawGrip(Entry entry, float s, Vector2 minSize) + { + Vector2 winPos = ImGuiNET.ImGui.GetWindowPos(); + Vector2 winSize = ImGuiNET.ImGui.GetWindowSize(); + Vector2 min = GripMin(entry, s, winPos + winSize); + bool hot = GripInteract(entry, s, minSize, min, winPos, winSize, null); + GripPaint(entry, s, min, hot, ImGuiNET.ImGui.GetWindowDrawList()); + return hot; + } + + /// <summary> + /// The grip's hit area at <paramref name="min"/>; dragging it resizes the panel + /// window (<paramref name="windowName"/>, or the current window when null). + /// Returns true while hovered or dragged. + /// </summary> + private static bool GripInteract(Entry entry, float s, Vector2 minSize, Vector2 min, Vector2 winPos, Vector2 winSize, + string? windowName) + { + float size = GripSize(entry, s); + ImGuiNET.ImGui.SetCursorScreenPos(min); + ImGuiNET.ImGui.InvisibleButton("##grip", new Vector2(size, size)); + bool hot = ImGuiNET.ImGui.IsItemHovered() || ImGuiNET.ImGui.IsItemActive(); + if (hot) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.ResizeNWSE); + if (ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 0f)) + { + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + Vector2 maxSize = display.X > 1 ? display - winPos : new Vector2(float.MaxValue, float.MaxValue); + Vector2 next = Vector2.Clamp(winSize + ImGuiNET.ImGui.GetIO().MouseDelta, minSize, Vector2.Max(minSize, maxSize)); + if (windowName != null) ImGuiNET.ImGui.SetWindowSize(windowName, next); + else ImGuiNET.ImGui.SetWindowSize(next); + } + return hot; + } + + private static void GripPaint(Entry entry, float s, Vector2 min, bool hot, ImDrawListPtr dl) + { + bool gold = entry.Spec.GoldGrip; + float size = GripSize(entry, s); + Vector2 max = min + new Vector2(size, size); + uint accent = gold ? RynthTheme.RadarGold : RynthTheme.GripGlyph; + uint fill = gold ? (hot ? RynthTheme.RadarGripHover : RynthTheme.RadarGripIdle) : (hot ? RynthTheme.GripHover : RynthTheme.GripIdle); + dl.AddRectFilled(min, max, fill, gold ? 0f : 4f * s, ImDrawFlags.RoundCornersBottomRight); + dl.AddLine(min, new Vector2(max.X, min.Y), accent); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Resize, min, new Vector2(size, size), accent); + } + + /// <summary> + /// Saves open state and docked placement (converted back to Avalonia + /// logical units), keeping the popped-out screen position. Written off + /// AC's thread, in order with the router's own writes. + /// </summary> + /// <summary> + /// Saves a popped-out panel: open state, its window's screen position and size + /// (the size in Avalonia logical units, like the docked size), and the docked + /// position it returns to. Written off AC's thread, in order. + /// </summary> + private static void PersistPopped(Entry entry, bool open, int left, int top, int width, int height, float placeScale, bool keepSize = false) + { + string title = entry.Title; + Vector2 docked = entry.Pos / placeScale; + Vector2 size = new Vector2(width, height) / placeScale; + UiBackgroundWriter.Enqueue($"persist {title}", () => + { + PanelStateStore.TryGetPanel(title, out PanelStateStore.PanelEntry prior); + double w = keepSize && prior.Width > 0 ? prior.Width : size.X; + double h = keepSize && prior.Height > 0 ? prior.Height : size.Y; + PanelStateStore.SetPanel(title, new PanelStateStore.PanelEntry( + open, docked.X, docked.Y, w, h, true, left, top)); + }); + } + + private static void Persist(Entry entry, bool open, float placeScale, bool floating = false) + { + string title = entry.Title; + Vector2 pos = entry.Pos / placeScale; + Vector2 size = entry.Size / placeScale; + if (PanelRouter.ResolveDockedFace(title) == PanelFace.Both) + pos -= new Vector2(24, 24); // don't let the side-by-side offset drift the Avalonia face + UiBackgroundWriter.Enqueue($"persist {title}", () => + { + PanelStateStore.TryGetPanel(title, out PanelStateStore.PanelEntry prior); + PanelStateStore.SetPanel(title, new PanelStateStore.PanelEntry( + open, pos.X, pos.Y, size.X, size.Y, floating, prior.FloatingLeft, prior.FloatingTop)); + }); + } +} diff --git a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs new file mode 100644 index 0000000..feceed4 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs @@ -0,0 +1,715 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ImGuiPopOuts.cs +// Popped-out ImGui panels (docs/IMGUI_PARITY_PLAN.md §4.2, P5): a panel +// popped out of the client is still its ImGui face, drawn by the engine into +// its own window. No ImGui multi-viewport. +// +// Per pop-out: +// • a LayeredWindow owned by AC's window (non-activating, hidden from +// Alt-Tab, moves and resizes without the OS modal loop), created on the +// game thread by a posted message, never inline in EndScene; +// • a secondary ImGui context sharing the main font atlas, fed from that +// window's mouse messages, plus keys and the wheel routed from the game +// window (the pop-out never takes focus, so AC keeps rendering); +// • a PopOutSurface: render target → readback → UpdateLayeredWindow. +// A pop-out renders at up to 30 Hz, and on every frame for a few frames after +// input so clicks and typing feel immediate. +// +// Tooltips and popups: the context's display is the monitor's work area, with +// the panel drawn where it really is on it, so ImGui places a tooltip or menu +// as it would in the client (flipping at the screen's edges). The picture is +// the panel plus a transparent margin holding whatever reaches past it; with +// nothing out there the margin is 0 and the picture is just the panel. The +// window grows by the margin and moves so the panel stays put (LayeredWindow +// .Present). Before this, the window was the panel and a tooltip below the +// one-button-high popped-out bar was cut off at its edge. +// +// Threads: everything here runs on AC's main thread, which both renders +// (EndScene) and dispatches the game and pop-out WndProcs. No locks. +// Shutdown releases every window, context and D3D surface; nothing survives +// an engine reload. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Numerics; +using System.Runtime.InteropServices; +using ImGuiNET; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static unsafe class ImGuiPopOuts +{ + private const uint WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105; + private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_RBUTTONDOWN = 0x0204, + WM_RBUTTONUP = 0x0205, WM_MBUTTONDOWN = 0x0207, WM_MBUTTONUP = 0x0208, WM_MOUSEWHEEL = 0x020A, WM_MOUSEHWHEEL = 0x020E; + private const int VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12; + private const int HotFramesAfterInput = 4; + private const int MaxContentSide = 4096; // a size-to-content pop-out's largest size (px) + private const int MarginStep = 32; // margins grow in steps, so a tooltip that follows the mouse doesn't resize the window every frame + private const float OverflowSlack = 2f; // anti-aliased edges reach ~1 px past the panel: not a tooltip + // A margin's largest size (px). Room for any tooltip or menu; it bounds the readback + // if something follows the mouse far off the panel (the inventory's drag ghost). + private const int MaxMargin = 640; + private static readonly long FrameInterval = Stopwatch.Frequency / 30; // hovered or just used + // Otherwise the face's own idle rate (IImGuiPanel.PopOutIdleHz, default 10 Hz). + + [StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; } + [DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT p); + [DllImport("user32.dll")] private static extern IntPtr WindowFromPoint(POINT p); + [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr hWnd, ref POINT p); + [DllImport("user32.dll")] private static extern short GetKeyState(int vk); + [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + + private readonly record struct InputMessage(uint Msg, IntPtr WParam, IntPtr LParam); + + private sealed class PopOut + { + public required string Title; + public required IntPtr Context; + public int Left, Top, Width, Height; // requested geometry (screen px) + public int CaptionHeight, CaptionRightInset; // native drag band (px) + public LayeredWindow? Window; + public bool Visible; + public readonly PopOutSurface Surface = new(); + public readonly List<InputMessage> Input = new(32); + public readonly bool[] Buttons = new bool[3]; + public long LastFrameTicks; + public int HotFrames = HotFramesAfterInput; + public bool WantTextInput, DropTextFocus; + public bool Hovered; + // A pop-out that isn't a panel (the bar): its own draw, sized to its content. + public Action<float, Vector2>? Draw; + public Action<int, int>? OnMoved; + public bool SizeToContent, ResizeGrip = true; + public Vector2 ContentSize; + public int ShownWidth, ShownHeight; // the picture size last pushed + public long IdleInterval = Stopwatch.Frequency / 10; + public ulong LastHash; + // The context's display (the work area around the panel) and the panel's place on it. + public int OriginX, OriginY, DisplayW, DisplayH; + // The picture's margins around the panel (px): room for tooltips and popups. + public int MarginL, MarginT, MarginR, MarginB; + // Cost, for /rc imgui diag: frames built / pictures pushed, and the time spent. + public long Built, Pushed, BuildTicks, PushTicks; + } + + private static readonly Dictionary<string, PopOut> Pops = new(StringComparer.OrdinalIgnoreCase); + private static readonly List<PopOut> Order = new(); + private static PopOut? _current; // the pop-out whose frame is being built + private static PopOut? _keyboard; // the pop-out typing into a text box + private static int _loggedErrors; + + /// <summary>True while a pop-out's ImGui frame is being built (inside a face's Draw). AC thread.</summary> + public static bool InPopOutFrame => _current != null; + + /// <summary> + /// Where a popped-out face puts its window (its top-left in the pop-out's ImGui + /// coordinates): the panel's place on the work area. (0,0) outside a pop-out frame. + /// AC thread, in the draw. + /// </summary> + public static Vector2 PanelOrigin => _current is { } pop ? new Vector2(pop.OriginX, pop.OriginY) : Vector2.Zero; + + public static bool IsPopped(string title) => Pops.ContainsKey(title); + + /// <summary> + /// A pop-out's text box holds the keyboard: the game WndProc routes keys to it + /// (RouteInput) and lets none of them reach AC. AC thread. + /// </summary> + public static bool HasTextFocus => _keyboard is { WantTextInput: true }; + + /// <summary>The pop-out typing into a text box, or null (for the input log). AC thread.</summary> + public static string? TextFocusTitle => _keyboard is { WantTextInput: true } k ? k.Title : null; + + /// <summary>The screen position of the game window's client origin (to place a pop-out where the docked panel was).</summary> + public static Vector2 ClientOriginOnScreen() + { + var p = new POINT(); + IntPtr game = Win32Backend.GameHwnd; + if (game != IntPtr.Zero) ClientToScreen(game, ref p); + return new Vector2(p.X, p.Y); + } + + /// <summary> + /// Pops a panel out at the given screen geometry. Call with the main context + /// current (its font atlas is shared). AC thread. + /// </summary> + public static void Open(string title, int left, int top, int width, int height, int captionHeight, int captionRightInset, float uiScale, + Action<float, Vector2>? draw = null, Action<int, int>? onMoved = null, bool sizeToContent = false) + { + if (Pops.ContainsKey(title)) return; + IntPtr main = ImGuiNET.ImGui.GetCurrentContext(); + if (main == IntPtr.Zero) return; + + IntPtr ctx = ImGuiNET.ImGui.CreateContext(ImGuiNET.ImGui.GetIO().Fonts); + ImGuiNET.ImGui.SetCurrentContext(ctx); + try + { + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + io.NativePtr->IniFilename = null; + io.BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset; + RynthTheme.Apply(ImGuiNET.ImGui.GetStyle(), uiScale); + } + finally + { + ImGuiNET.ImGui.SetCurrentContext(main); + } + + var pop = new PopOut + { + Title = title, Context = ctx, + Left = left, Top = top, Width = Math.Max(80, width), Height = Math.Max(40, height), + CaptionHeight = captionHeight, CaptionRightInset = captionRightInset, + Draw = draw, OnMoved = onMoved, SizeToContent = sizeToContent, ResizeGrip = !sizeToContent, + }; + Pops[title] = pop; + Order.Add(pop); + // Creating an HWND from inside EndScene isn't safe: the game WndProc does it. + if (!Win32Backend.PostToGameThread(() => CreateWindow(pop))) + RynthLog.UI($"ImGuiPopOuts: {title}: no game window to create the pop-out from."); + } + + private static void CreateWindow(PopOut pop) + { + if (!Pops.TryGetValue(pop.Title, out PopOut? live) || live != pop || pop.Window != null) return; + try + { + // A saved spot off the screen (a monitor since unplugged, a bad save) comes back on it. + if (LayeredWindow.ClampToWorkArea(ref pop.Left, ref pop.Top, pop.Width, pop.Height)) + RynthLog.UI($"ImGuiPopOuts: {pop.Title}: saved spot was off the screen; moved to ({pop.Left},{pop.Top})."); + var window = new LayeredWindow(pop.Width, pop.Height, pop.Left, pop.Top, Win32Backend.GameHwnd) + { + CaptionHeight = pop.CaptionHeight, + CaptionRightInset = pop.CaptionRightInset, + ResizeGripEnabled = pop.ResizeGrip, + }; + window.OnInput = (msg, wParam, lParam, _, _) => OnWindowInput(pop, msg, wParam, lParam); + window.OnResized = (_, _) => pop.HotFrames = Math.Max(pop.HotFrames, 2); + window.OnMoved = (x, y) => NotifyMoved(pop, window, x, y); + window.OnResizeEnd = (w, h) => ImGuiPanelHost.OnPopOutGeometry(pop.Title, window.ScreenLeft, window.ScreenTop, w, h); + LayeredWindow.ClaimTitle(pop.Title, window.Hwnd); + pop.Window = window; + pop.HotFrames = HotFramesAfterInput; + RynthLog.UI($"ImGuiPopOuts: {pop.Title} popped out at ({pop.Left},{pop.Top}) {pop.Width}x{pop.Height}."); + } + catch (Exception ex) + { + RynthLog.UI($"ImGuiPopOuts: {pop.Title}: window creation failed ({ex.GetType().Name}: {ex.Message})."); + } + } + + /// <summary>The window moved (a drag ended, or it was pulled back onto the screen): save the spot. AC thread.</summary> + private static void NotifyMoved(PopOut pop, LayeredWindow window, int x, int y) + { + if (pop.OnMoved != null) pop.OnMoved(x, y); + else ImGuiPanelHost.OnPopOutGeometry(pop.Title, x, y, window.Width, window.Height); + } + + /// <summary>Closes a pop-out: its window, surfaces and context. AC thread.</summary> + public static void Close(string title) + { + if (!Pops.Remove(title, out PopOut? pop)) return; + Order.Remove(pop); + if (_keyboard == pop) _keyboard = null; + ImGuiTextFocus.ForgetPopOut(title); + try { pop.Window?.Dispose(); } catch (Exception ex) { RynthLog.UI($"ImGuiPopOuts: {title} window dispose threw {ex.Message}"); } + pop.Window = null; + pop.Surface.Dispose(); + ImGuiFonts.WaitForWorkers(); // no context goes while a font worker runs (ImGuiFonts, re-bake note) + ImGuiNET.ImGui.DestroyContext(pop.Context); // restores the current context + RynthLog.UI($"ImGuiPopOuts: {title} closed."); + } + + /// <summary> + /// The main context's font atlas was replaced (ImGuiFonts re-bake): every pop-out + /// shares it, so each one's context is pointed at the new atlas too. AC thread, + /// between frames. + /// </summary> + public static void ReplaceFontAtlas(IntPtr oldAtlas, IntPtr newAtlas) + { + if (Order.Count == 0) return; + IntPtr previous = ImGuiNET.ImGui.GetCurrentContext(); + try + { + foreach (PopOut pop in Order) + { + ImGuiNET.ImGui.SetCurrentContext(pop.Context); + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + if ((IntPtr)io.NativePtr->Fonts == oldAtlas) + io.NativePtr->Fonts = (ImFontAtlas*)newAtlas; + pop.LastHash = 0; // redraw with the new glyphs even if the lists hash the same + } + } + finally + { + ImGuiNET.ImGui.SetCurrentContext(previous); + } + } + + /// <summary>Engine shutdown / reload: every pop-out goes. Any thread that may touch the device.</summary> + /// <summary> + /// The device is about to be Reset (D3D9.DeviceResetHook): release every + /// pop-out's D3DPOOL_DEFAULT surfaces, or the Reset fails and AC stops with + /// "Could not initialize Direct3D". They are recreated on the next frame; + /// the windows keep their last picture meanwhile. AC thread. Returns the + /// number of pop-outs released. + /// </summary> + public static int ReleaseDeviceResources() + { + int released = 0; + foreach (PopOut pop in Order) + { + pop.Surface.Dispose(); + pop.LastHash = 0; // draw the next frame even if nothing changed + released++; + } + return released; + } + + public static void Shutdown() + { + var titles = new List<string>(Pops.Keys); + foreach (string title in titles) Close(title); + } + + /// <summary> + /// A size-to-content pop-out's draw reports how big its content came out; + /// the window takes that size on the next frame. AC thread, in the draw. + /// </summary> + public static void ReportContentSize(Vector2 size) + { + PopOut? pop = _current; + if (pop == null || !pop.SizeToContent || size == pop.ContentSize) return; + pop.ContentSize = size; + pop.HotFrames = Math.Max(pop.HotFrames, 2); + } + + /// <summary>Starts moving the current pop-out's window (a chromeless face dragged by its own surface). AC thread, in a face's Draw.</summary> + public static void BeginMoveCurrent() => _current?.Window?.BeginContentMove(); + + // ── Input ────────────────────────────────────────────────────────── + + private static void OnWindowInput(PopOut pop, uint msg, IntPtr wParam, IntPtr lParam) + { + pop.Input.Add(new InputMessage(msg, wParam, lParam)); + pop.HotFrames = HotFramesAfterInput; + if (msg is WM_LBUTTONDOWN or WM_RBUTTONDOWN or WM_MBUTTONDOWN) + { + // A click in this pop-out ends text entry everywhere else. + EngineFrameController.DropMainTextFocus(); + foreach (PopOut other in Order) + if (other != pop && other.WantTextInput) { other.DropTextFocus = true; other.HotFrames = 2; } + } + } + + /// <summary> + /// Called by the game WndProc for every message. True when a pop-out took it: + /// keys while a pop-out's text box is being edited, and the wheel over a + /// pop-out. A click on the game ends a pop-out's text edit. AC thread. + /// </summary> + public static bool RouteInput(uint msg, IntPtr wParam, IntPtr lParam) + { + if (Order.Count == 0) return false; + switch (msg) + { + case WM_LBUTTONDOWN or WM_RBUTTONDOWN or WM_MBUTTONDOWN: + foreach (PopOut pop in Order) + if (pop.WantTextInput) { pop.DropTextFocus = true; pop.HotFrames = 2; } + return false; + + case WM_MOUSEWHEEL or WM_MOUSEHWHEEL: + { + var p = new POINT { X = (short)((long)lParam & 0xFFFF), Y = (short)(((long)lParam >> 16) & 0xFFFF) }; + IntPtr under = WindowFromPoint(p); + foreach (PopOut pop in Order) + { + if (pop.Window == null || pop.Window.Hwnd != under) continue; + OnWindowInput(pop, msg, wParam, lParam); + return true; + } + return false; + } + + case WM_KEYDOWN or WM_KEYUP or WM_CHAR or WM_SYSKEYDOWN or WM_SYSKEYUP: + { + PopOut? sink = _keyboard; + if (sink == null || !sink.WantTextInput) return false; + sink.Input.Add(new InputMessage(msg, wParam, lParam)); + sink.HotFrames = HotFramesAfterInput; + return true; + } + } + return false; + } + + /// <param name="offsetX">Added to a message's client x to make it ImGui's (the window's origin in ImGui coordinates).</param> + private static void FeedInput(PopOut pop, ImGuiIOPtr io, int offsetX, int offsetY) + { + foreach (InputMessage m in pop.Input) + { + // Mouse messages from the window carry the position (client coords). It has to + // reach ImGui before the button: a press is applied where ImGui last saw the + // mouse, and an idle pop-out may last have seen it outside the window, so a + // quick grab of a drag surface pressed nothing (Tom, 2026-09-29: the popped-out + // dashboard wouldn't move). Wheel lParams are screen coordinates: skipped. + if (m.Msg is WM_MOUSEMOVE or WM_LBUTTONDOWN or WM_LBUTTONUP or WM_RBUTTONDOWN or WM_RBUTTONUP or WM_MBUTTONDOWN or WM_MBUTTONUP) + io.AddMousePosEvent((short)((long)m.LParam & 0xFFFF) + offsetX, (short)(((long)m.LParam >> 16) & 0xFFFF) + offsetY); + switch (m.Msg) + { + case WM_LBUTTONDOWN: SetButton(pop, io, 0, true); break; + case WM_LBUTTONUP: SetButton(pop, io, 0, false); break; + case WM_RBUTTONDOWN: SetButton(pop, io, 1, true); break; + case WM_RBUTTONUP: SetButton(pop, io, 1, false); break; + case WM_MBUTTONDOWN: SetButton(pop, io, 2, true); break; + case WM_MBUTTONUP: SetButton(pop, io, 2, false); break; + case WM_MOUSEWHEEL: io.AddMouseWheelEvent(0f, (short)((long)m.WParam >> 16) / 120f); break; + case WM_MOUSEHWHEEL: io.AddMouseWheelEvent((short)((long)m.WParam >> 16) / 120f, 0f); break; + case WM_KEYDOWN or WM_SYSKEYDOWN or WM_KEYUP or WM_SYSKEYUP: + { + ImGuiKey key = Win32Backend.VkToImGuiKey((int)(long)m.WParam); + if (key != ImGuiKey.None) io.AddKeyEvent(key, m.Msg is WM_KEYDOWN or WM_SYSKEYDOWN); + break; + } + case WM_CHAR: + { + uint ch = (uint)(long)m.WParam; + if (ch > 0 && ch < 0x10000) io.AddInputCharacter(ch); + break; + } + } + } + pop.Input.Clear(); + } + + private static void SetButton(PopOut pop, ImGuiIOPtr io, int button, bool down) + { + if (pop.Buttons[button] == down) return; + pop.Buttons[button] = down; + io.AddMouseButtonEvent(button, down); + } + + // ── Frames ───────────────────────────────────────────────────────── + + /// <summary> + /// Draws and presents every pop-out that is due. <paramref name="live"/> is + /// false between characters: pop-outs hide, like the in-client panels. + /// AC thread, inside EndScene, after the main frame. + /// </summary> + public static void RenderAll(IntPtr device, float uiScale, bool live) + { + if (Order.Count == 0) return; + if (!live) + { + foreach (PopOut pop in Order) + if (pop.Visible) { pop.Window?.Hide(); pop.Visible = false; } + return; + } + + IntPtr previous = ImGuiNET.ImGui.GetCurrentContext(); + long now = Stopwatch.GetTimestamp(); + try + { + for (int i = 0; i < Order.Count; i++) + { + PopOut pop = Order[i]; + if (pop.Window == null || pop.Window.Hwnd == IntPtr.Zero) continue; + long interval = pop.HotFrames > 0 || pop.Hovered || pop.WantTextInput ? 0 : pop.IdleInterval; + if (pop.HotFrames <= 0 && now - pop.LastFrameTicks < Math.Max(interval, FrameInterval)) continue; + RenderOne(device, pop, uiScale, now); + } + } + finally + { + _current = null; + ImGuiNET.ImGui.SetCurrentContext(previous); + } + } + + private static void RenderOne(IntPtr device, PopOut pop, float uiScale, long now) + { + LayeredWindow window = pop.Window!; + int w = Math.Max(1, window.Width), h = Math.Max(1, window.Height); + if (pop.SizeToContent && pop.ContentSize.X >= 1 && pop.ContentSize.Y >= 1) + { + // The window follows the content (Present resizes it to the picture). + w = Math.Min(MaxContentSide, (int)MathF.Ceiling(pop.ContentSize.X)); + h = Math.Min(MaxContentSide, (int)MathF.Ceiling(pop.ContentSize.Y)); + } + PlaceOnDisplay(pop, window, w, h); + // The screen spot of ImGui's (0,0). + int anchorX = window.ScreenLeft - pop.OriginX, anchorY = window.ScreenTop - pop.OriginY; + ImGuiNET.ImGui.SetCurrentContext(pop.Context); + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + bool started = false; + try + { + // The display is the work area, not the window: a size-to-content face must + // lay out against a large display (ImGui clamps an auto-resizing window to the + // display; when the display was the window, each shrank the other, 400x40 -> + // 8x6 -> 4x4, and the popped-out bar was a 4 px speck), and tooltips and + // popups get room around the panel. + io.DisplaySize = new Vector2(pop.DisplayW, pop.DisplayH); + float dt = pop.LastFrameTicks == 0 ? 1f / 30f : (float)(now - pop.LastFrameTicks) / Stopwatch.Frequency; + io.DeltaTime = Math.Clamp(dt, 1f / 240f, 0.5f); + pop.LastFrameTicks = now; + + FeedInput(pop, io, window.SurfaceLeft - anchorX, window.SurfaceTop - anchorY); + // The cursor, from the screen: over this window (or dragging from it) it's in + // ImGui's coordinates, otherwise nowhere, so hover highlights clear. + GetCursorPos(out POINT cursor); + bool held = pop.Buttons[0] || pop.Buttons[1] || pop.Buttons[2]; + pop.Hovered = WindowFromPoint(cursor) == window.Hwnd; + if (held || pop.Hovered) + io.AddMousePosEvent(cursor.X - anchorX, cursor.Y - anchorY); + else + io.AddMousePosEvent(-float.MaxValue, -float.MaxValue); + bool gameFocused = GetForegroundWindow() == Win32Backend.GameHwnd; + io.AddFocusEvent(gameFocused || held); + io.AddKeyEvent(ImGuiKey.ModCtrl, (GetKeyState(VK_CONTROL) & 0x8000) != 0); + io.AddKeyEvent(ImGuiKey.ModShift, (GetKeyState(VK_SHIFT) & 0x8000) != 0); + io.AddKeyEvent(ImGuiKey.ModAlt, (GetKeyState(VK_MENU) & 0x8000) != 0); + + _current = pop; + ImGuiTextFocus.BeginFrame(); + ImGuiNET.ImGui.NewFrame(); + started = true; + if (pop.DropTextFocus) + { + pop.DropTextFocus = false; + ImGuiNET.ImGui.SetWindowFocus(null); + } + if (pop.Draw != null) pop.Draw(uiScale, new Vector2(w, h)); + else ImGuiPanelHost.DrawPopped(pop.Title, uiScale, new Vector2(w, h)); + ImGuiNET.ImGui.EndFrame(); + started = false; + ImGuiNET.ImGui.Render(); + _current = null; + long built = Stopwatch.GetTimestamp(); + pop.Built++; + pop.BuildTicks += built - now; + + // The picture: the panel, plus a margin for anything drawn past it (a tooltip, + // a menu). Only a menu there takes clicks; a tooltip lets them through. + ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData(); + UpdateMargins(pop, drawData.NativePtr, w, h); + window.MarginsClickThrough = !ImGuiNET.ImGui.IsPopupOpen("", ImGuiPopupFlags.AnyPopupId | ImGuiPopupFlags.AnyPopupLevel); + int sx = pop.OriginX - pop.MarginL, sy = pop.OriginY - pop.MarginT; + int sw = w + pop.MarginL + pop.MarginR, sh = h + pop.MarginT + pop.MarginB; + if (drawData.NativePtr != null) + { + drawData.NativePtr->DisplayPos = new Vector2(sx, sy); // render into the sw x sh picture + drawData.NativePtr->DisplaySize = new Vector2(sw, sh); + } + + // Nothing changed since the last picture: skip the render, readback and + // window update (most panels are still most of the time). + ulong hash = HashDrawData(drawData, sw, sh) ^ Mix(sx, sy, w, h); + if (hash == pop.LastHash && pop.Visible && pop.Surface.SnapshotPath == null) + { + pop.Surface.Flush(device, window); + } + else + { + pop.LastHash = hash; + if (pop.Surface.Render(device, drawData, sw, sh, new PopOutSurface.Placement(pop.MarginL, pop.MarginT, w, h), window)) + { + // Shown, or its picture changed size (the bar grows to its content): + // none of it may hang off the screen. + if ((!pop.Visible || w != pop.ShownWidth || h != pop.ShownHeight) && window.EnsureOnScreen()) + NotifyMoved(pop, window, window.ScreenLeft, window.ScreenTop); + pop.ShownWidth = w; + pop.ShownHeight = h; + if (!pop.Visible) + { + window.Show(); + pop.Visible = true; + } + } + pop.Pushed++; + pop.PushTicks += Stopwatch.GetTimestamp() - built; + } + + // io.WantTextInput lags a frame behind the box (ImGui publishes it from the + // previous frame's widgets); a box that went active this frame counts too, so + // the keys typed right after the click already come here, not to AC. + pop.WantTextInput = ImGuiTextFocus.EndPopOutFrame(pop.Title, io.WantTextInput); + pop.IdleInterval = Stopwatch.Frequency / ImGuiPanelHost.PopOutIdleHz(pop.Title); + if (pop.WantTextInput) _keyboard = pop; + else if (_keyboard == pop) _keyboard = null; + if (pop.HotFrames > 0) pop.HotFrames--; + } + catch (Exception ex) + { + try { if (started) ImGuiNET.ImGui.EndFrame(); } catch { } + _current = null; + pop.HotFrames = 0; + if (_loggedErrors++ < 10) + RynthLog.UI($"ImGuiPopOuts: {pop.Title} frame threw {ex.GetType().Name}: {ex.Message}"); + } + } + + // ── Tooltips and popups: the display and the margins ─────────────── + + /// <summary> + /// Sets the context's display to the work area of the panel's monitor (and the + /// panel, where it hangs off it), and the panel's place on it. ImGui then keeps + /// tooltips and popups on the screen and flips them at its edges, as in the client. + /// </summary> + private static void PlaceOnDisplay(PopOut pop, LayeredWindow window, int w, int h) + { + if (window.IsDragging && pop.DisplayW > 0) + { + // Mid-drag the display travels with the panel: the panel keeps its ImGui + // position, so a moved picture is the same picture (not redrawn every step). + // It is placed afresh once the drag ends. + pop.DisplayW = Math.Max(pop.DisplayW, pop.OriginX + w); + pop.DisplayH = Math.Max(pop.DisplayH, pop.OriginY + h); + return; + } + int left = window.ScreenLeft, top = window.ScreenTop; + int l = left, t = top, r = left + w, b = top + h; + if (LayeredWindow.TryGetWorkArea(left, top, w, h, out int wl, out int wt, out int wr, out int wb)) + { + l = Math.Min(l, wl); t = Math.Min(t, wt); + r = Math.Max(r, wr); b = Math.Max(b, wb); + } + pop.OriginX = left - l; + pop.OriginY = top - t; + pop.DisplayW = r - l; + pop.DisplayH = b - t; + } + + /// <summary> + /// The picture's margins: room for everything drawn past the panel, in steps, held + /// while something is out there (a tooltip following the mouse doesn't resize the + /// window on every frame) and dropped to 0 when nothing is. Never past the display. + /// </summary> + private static void UpdateMargins(PopOut pop, ImDrawData* dd, int w, int h) + { + float px0 = pop.OriginX, py0 = pop.OriginY, px1 = px0 + w, py1 = py0 + h; + if (!OverflowBounds(dd, px0, py0, px1, py1, pop.DisplayW, pop.DisplayH, out float x0, out float y0, out float x1, out float y1)) + { + pop.MarginL = pop.MarginT = pop.MarginR = pop.MarginB = 0; + return; + } + pop.MarginL = Math.Clamp(Math.Max(Step(px0 - x0), pop.MarginL), 0, pop.OriginX); + pop.MarginT = Math.Clamp(Math.Max(Step(py0 - y0), pop.MarginT), 0, pop.OriginY); + pop.MarginR = Math.Clamp(Math.Max(Step(x1 - px1), pop.MarginR), 0, Math.Max(0, pop.DisplayW - pop.OriginX - w)); + pop.MarginB = Math.Clamp(Math.Max(Step(y1 - py1), pop.MarginB), 0, Math.Max(0, pop.DisplayH - pop.OriginY - h)); + } + + private static int Step(float overflow) + => overflow <= OverflowSlack ? 0 : Math.Min(MaxMargin, ((int)MathF.Ceiling(overflow) + MarginStep - 1) / MarginStep * MarginStep); + + /// <summary> + /// The bounds of what is drawn outside the panel rect (tooltips, popups), as it will + /// show: each draw command's triangles, cut to its clip rect and the display. False + /// when nothing reaches more than <see cref="OverflowSlack"/> px past the panel. + /// Only commands whose clip rect reaches past the panel are walked (a window's + /// background, tooltips and popups); the panel's own content is clipped inside it. + /// </summary> + private static bool OverflowBounds(ImDrawData* dd, float px0, float py0, float px1, float py1, float displayW, float displayH, + out float x0, out float y0, out float x1, out float y1) + { + x0 = px0; y0 = py0; x1 = px1; y1 = py1; + if (dd == null) return false; + ImDrawList** lists = (ImDrawList**)dd->CmdLists.Data; + for (int n = 0; n < dd->CmdListsCount; n++) + { + ImDrawList* list = lists[n]; + if (list == null) continue; + int vtxCount = list->VtxBuffer.Size, idxCount = list->IdxBuffer.Size; + ImDrawVert* vtx = (ImDrawVert*)list->VtxBuffer.Data; + ushort* idx = (ushort*)list->IdxBuffer.Data; + ImDrawCmd* cmds = (ImDrawCmd*)list->CmdBuffer.Data; + for (int c = 0; c < list->CmdBuffer.Size; c++) + { + ImDrawCmd* cmd = &cmds[c]; + if (cmd->UserCallback != IntPtr.Zero || cmd->ElemCount == 0) continue; + float cx0 = Math.Max(cmd->ClipRect.X, 0f), cy0 = Math.Max(cmd->ClipRect.Y, 0f); + float cx1 = Math.Min(cmd->ClipRect.Z, displayW), cy1 = Math.Min(cmd->ClipRect.W, displayH); + if (cx1 <= cx0 || cy1 <= cy0) continue; + if (cx0 >= px0 && cy0 >= py0 && cx1 <= px1 && cy1 <= py1) continue; // can't draw outside the panel + + float vx0 = float.MaxValue, vy0 = float.MaxValue, vx1 = float.MinValue, vy1 = float.MinValue; + long start = cmd->IdxOffset, end = Math.Min((long)idxCount, start + cmd->ElemCount); + long vbase = cmd->VtxOffset; + for (long i = start; i < end; i++) + { + long v = vbase + idx[i]; + if (v >= vtxCount) continue; + Vector2 pos = vtx[v].pos; + if (pos.X < vx0) vx0 = pos.X; + if (pos.Y < vy0) vy0 = pos.Y; + if (pos.X > vx1) vx1 = pos.X; + if (pos.Y > vy1) vy1 = pos.Y; + } + vx0 = Math.Max(vx0, cx0); vy0 = Math.Max(vy0, cy0); + vx1 = Math.Min(vx1, cx1); vy1 = Math.Min(vy1, cy1); + if (vx1 <= vx0 || vy1 <= vy0) continue; + x0 = Math.Min(x0, vx0); y0 = Math.Min(y0, vy0); + x1 = Math.Max(x1, vx1); y1 = Math.Max(y1, vy1); + } + } + return px0 - x0 > OverflowSlack || py0 - y0 > OverflowSlack || x1 - px1 > OverflowSlack || y1 - py1 > OverflowSlack; + } + + /// <summary>Folds the picture's placement into the draw-data hash.</summary> + private static ulong Mix(int a, int b, int c, int d) + => ((ulong)(uint)a * 0x9E3779B97F4A7C15UL) ^ ((ulong)(uint)b * 0xC2B2AE3D27D4EB4FUL) + ^ ((ulong)(uint)c * 0x165667B19E3779F9UL) ^ ((ulong)(uint)d * 0x27D4EB2F165667C5UL); + + /// <summary>Diagnostics: the pop-out's next frame is also saved as a BMP in the log folder. AC thread.</summary> + public static string? RequestSnapshot(string title) + { + if (!Pops.TryGetValue(title, out PopOut? pop)) return null; + string path = System.IO.Path.Combine(@"C:\Games\RynthCore\Logs", $"popout_{title.Replace(' ', '_')}.bmp"); + pop.Surface.SnapshotPath = path; + pop.HotFrames = Math.Max(pop.HotFrames, 2); + return path; + } + + /// <summary>One line per pop-out for /rc imgui diag.</summary> + public static List<string> Describe() + { + var lines = new List<string>(); + double ms = 1000.0 / Stopwatch.Frequency; + foreach (PopOut pop in Order) + lines.Add($"popout {pop.Title}: window={(pop.Window == null ? "pending" : $"0x{pop.Window.Hwnd.ToInt64():X} at ({pop.Window.ScreenLeft},{pop.Window.ScreenTop}) {pop.Window.Width}x{pop.Window.Height}")} visible={pop.Visible} text={pop.WantTextInput}" + + $" margins=({pop.MarginL},{pop.MarginT},{pop.MarginR},{pop.MarginB}) display={pop.DisplayW}x{pop.DisplayH}" + + $" built={pop.Built} ({(pop.Built > 0 ? pop.BuildTicks * ms / pop.Built : 0):0.00} ms) pushed={pop.Pushed} ({(pop.Pushed > 0 ? pop.PushTicks * ms / pop.Pushed : 0):0.00} ms)"); + return lines; + } + + /// <summary>A 64-bit hash of everything that affects the picture: vertices, indices, commands and the size.</summary> + private static ulong HashDrawData(ImDrawDataPtr drawData, int w, int h) + { + ImDrawData* dd = drawData.NativePtr; + ulong hash = 0xcbf29ce484222325UL ^ (ulong)(uint)w ^ ((ulong)(uint)h << 32); + if (dd == null) return hash; + ImDrawList** lists = (ImDrawList**)dd->CmdLists.Data; + for (int n = 0; n < dd->CmdListsCount; n++) + { + ImDrawList* list = lists[n]; + if (list == null) continue; + hash = HashBytes(hash, (byte*)list->VtxBuffer.Data, list->VtxBuffer.Size * sizeof(ImDrawVert)); + hash = HashBytes(hash, (byte*)list->IdxBuffer.Data, list->IdxBuffer.Size * sizeof(ushort)); + hash = HashBytes(hash, (byte*)list->CmdBuffer.Data, list->CmdBuffer.Size * sizeof(ImDrawCmd)); + } + return hash; + } + + private static ulong HashBytes(ulong hash, byte* data, int length) + { + if (data == null || length <= 0) return hash; + ulong* p = (ulong*)data; + int words = length >> 3; + for (int i = 0; i < words; i++) + hash = (hash ^ p[i]) * 0x100000001B3UL + (hash >> 29); + for (int i = words << 3; i < length; i++) + hash = (hash ^ data[i]) * 0x100000001B3UL; + return hash ^ (ulong)length; + } +} diff --git a/src/RynthCore.Engine/ImGui/ImGuiSelfTest.cs b/src/RynthCore.Engine/ImGui/ImGuiSelfTest.cs new file mode 100644 index 0000000..a128e37 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ImGuiSelfTest.cs @@ -0,0 +1,166 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ImGuiSelfTest.cs +// Refuses to start ImGui unless the loaded cimgui.dll is RynthCore's own +// build (native/cimgui, scripts/Build-Cimgui.ps1) and its struct layout +// matches ImGui.NET 1.91.6.1. +// +// Every managed ImGui struct accessor (ImDrawData, ImGuiIO, ImFontAtlas, ...) +// reads native memory at ImGui.NET's compiled offsets, and every enum value +// is passed straight through. A different native build silently shifts both: +// the DLL bundled until 2026-09 was 1.89.7, and even the stock NuGet 1.91.6 +// x86 DLL disagrees with its own wrapper (64-bit ImTextureID). This check +// turns a mismatch into a logged refusal instead of memory corruption on +// AC's thread. +// ============================================================================ + +using System; +using System.Numerics; +using System.Runtime.InteropServices; +using ImGuiNET; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static unsafe class ImGuiSelfTest +{ + /// <summary>IMGUI_VERSION of the native build ImGui.NET 1.91.6.1 wraps.</summary> + internal const string ExpectedVersion = "1.91.6"; + + /// <summary>Must equal RynthImGui_BuildTag() in native/cimgui/rynth_cimgui_ext.cpp.</summary> + /// <summary>Outcome of the last Run, for /rc imgui diag ("not run" before the first).</summary> + public static string LastResult { get; private set; } = "not run"; + + internal const string ExpectedBuildTag = "rynth-cimgui 1.91.6dock ImTextureID=void* soft-assert layout-1 textedit-264bee4"; + + /// <summary> + /// True when <paramref name="cimguiModule"/> is our cimgui build and its + /// layout matches the managed wrapper. Safe to call before any context + /// exists. On a mismatch it logs why and returns false; the caller must + /// not create an ImGui context. + /// </summary> + public static bool Run(IntPtr cimguiModule) + { + try + { + // igGetVersion exists in every cimgui and has no side effects, so + // it goes first: older builds compile IM_ASSERT in as a hard abort, + // and the layout calls below would trip it on a mismatch. + string version = ImGuiNET.ImGui.GetVersion() ?? ""; + if (version != ExpectedVersion) + return Fail($"cimgui.dll reports ImGui {version}, ImGui.NET expects {ExpectedVersion}"); + + if (cimguiModule == IntPtr.Zero + || !NativeLibrary.TryGetExport(cimguiModule, "RynthImGui_BuildTag", out IntPtr buildTagFn) + || !NativeLibrary.TryGetExport(cimguiModule, "RynthImGui_GetLayout", out IntPtr getLayoutFn)) + return Fail("cimgui.dll is not the RynthCore build (no RynthImGui_* exports); rebuild with scripts/Build-Cimgui.ps1"); + + string tag = Marshal.PtrToStringAnsi(((delegate* unmanaged[Cdecl]<IntPtr>)buildTagFn)()) ?? ""; + if (tag != ExpectedBuildTag) + return Fail($"cimgui build tag '{tag}', expected '{ExpectedBuildTag}'"); + + (string Name, int Value)[] expected = ExpectedLayout(); + var getLayout = (delegate* unmanaged[Cdecl]<int*, int, int>)getLayoutFn; + int nativeCount = getLayout(null, 0); + if (nativeCount < expected.Length) + return Fail($"layout table has {nativeCount} entries, expected {expected.Length}"); + + int* native = stackalloc int[nativeCount]; + getLayout(native, nativeCount); + int mismatches = 0; + for (int i = 0; i < expected.Length; i++) + { + if (native[i] == expected[i].Value) continue; + mismatches++; + RynthLog.UI($"ImGuiSelfTest: layout[{i}] {expected[i].Name}: native={native[i]} managed={expected[i].Value}"); + } + if (mismatches > 0) + return Fail($"{mismatches} layout mismatch(es) between cimgui.dll and ImGui.NET"); + + // Dear ImGui's own check (asserts are soft in our build). + if (!ImGuiNET.ImGui.DebugCheckVersionAndDataLayout(ExpectedVersion, + (uint)sizeof(ImGuiIO), (uint)sizeof(ImGuiStyle), (uint)sizeof(Vector2), + (uint)sizeof(Vector4), (uint)sizeof(ImDrawVert), sizeof(ushort))) + return Fail("DebugCheckVersionAndDataLayout reported a mismatch"); + + ImGuiAssertLog.Bind(cimguiModule); + LastResult = $"OK - {tag}"; + RynthLog.UI($"ImGuiSelfTest: OK - {tag}, {expected.Length} layout checks passed."); + return true; + } + catch (Exception ex) + { + return Fail($"{ex.GetType().Name}: {ex.Message}"); + } + } + + private static bool Fail(string why) + { + LastResult = "FAILED - " + why; + RynthLog.UI($"ImGuiSelfTest: FAILED - {why}. ImGui disabled."); + return false; + } + + private static int Off(void* structBase, void* field) => (int)((byte*)field - (byte*)structBase); + + /// <summary> + /// The managed side of the layout table, in the index order of + /// RynthImGui_GetLayout (native/cimgui/rynth_cimgui_ext.cpp). Append only. + /// </summary> + internal static (string Name, int Value)[] ExpectedLayout() + { + // Offsets are taken from zeroed stack locals (&((T*)null)->Field + // null-checks in .NET). + ImDrawCmd cmd = default; + ImDrawList list = default; + ImDrawData data = default; + ImFontAtlas atlas = default; + ImGuiIO io = default; + return new (string, int)[] + { + ("table version", 1), + ("sizeof(ImTextureID)", sizeof(IntPtr)), + ("sizeof(ImWchar)", sizeof(ushort)), + ("sizeof(ImDrawIdx)", sizeof(ushort)), + ("sizeof(ImDrawVert)", sizeof(ImDrawVert)), + ("sizeof(ImDrawCmd)", sizeof(ImDrawCmd)), + ("ImDrawCmd.TextureId", Off(&cmd, &cmd.TextureId)), + ("ImDrawCmd.VtxOffset", Off(&cmd, &cmd.VtxOffset)), + ("ImDrawCmd.IdxOffset", Off(&cmd, &cmd.IdxOffset)), + ("ImDrawCmd.ElemCount", Off(&cmd, &cmd.ElemCount)), + ("ImDrawCmd.UserCallback", Off(&cmd, &cmd.UserCallback)), + ("sizeof(ImDrawList)", sizeof(ImDrawList)), + ("ImDrawList.VtxBuffer", Off(&list, &list.VtxBuffer)), + ("sizeof(ImDrawData)", sizeof(ImDrawData)), + ("ImDrawData.CmdLists", Off(&data, &data.CmdLists)), + ("ImDrawData.DisplayPos", Off(&data, &data.DisplayPos)), + ("ImDrawData.DisplaySize", Off(&data, &data.DisplaySize)), + ("sizeof(ImFontAtlas)", sizeof(ImFontAtlas)), + ("ImFontAtlas.TexID", Off(&atlas, &atlas.TexID)), + ("sizeof(ImFont)", sizeof(ImFont)), + // Pinned to the native size: ImGui.NET's generator expands the + // Colored:1/Visible:1/Codepoint:30 bitfield into three uints, so + // its ImFontGlyph is 48 bytes and wrong under ANY native build. + // Never read glyphs through ImGui.NET's ImFontGlyph/ImFontGlyphPtr. + ("sizeof(ImFontGlyph) [native]", 40), + ("sizeof(ImFontConfig)", sizeof(ImFontConfig)), + ("sizeof(ImGuiIO)", sizeof(ImGuiIO)), + ("ImGuiIO.Fonts", Off(&io, &io.Fonts)), + ("ImGuiIO.WantCaptureMouse", Off(&io, &io.WantCaptureMouse)), + ("ImGuiIO.WantTextInput", Off(&io, &io.WantTextInput)), + ("sizeof(ImGuiStyle)", sizeof(ImGuiStyle)), + ("sizeof(ImGuiViewport)", sizeof(ImGuiViewport)), + ("sizeof(ImGuiPlatformIO)", sizeof(ImGuiPlatformIO)), + ("sizeof(ImGuiInputTextCallbackData)", sizeof(ImGuiInputTextCallbackData)), + ("sizeof(ImGuiListClipper)", sizeof(ImGuiListClipper)), + ("sizeof(ImGuiPayload)", sizeof(ImGuiPayload)), + ("sizeof(ImGuiTableSortSpecs)", sizeof(ImGuiTableSortSpecs)), + ("sizeof(ImGuiTableColumnSortSpecs)", sizeof(ImGuiTableColumnSortSpecs)), + ("sizeof(ImGuiStorage)", sizeof(ImGuiStorage)), + ("sizeof(ImGuiWindowClass)", sizeof(ImGuiWindowClass)), + ("sizeof(ImGuiSizeCallbackData)", sizeof(ImGuiSizeCallbackData)), + ("ImGuiCol.COUNT", (int)ImGuiCol.COUNT), + ("ImGuiKey.NamedKey_END", (int)ImGuiKey.NamedKey_END), + ("ImGuiStyleVar.COUNT", (int)ImGuiStyleVar.COUNT), + ("ImGuiMouseCursor.COUNT", (int)ImGuiMouseCursor.COUNT), + }; + } +} diff --git a/src/RynthCore.Engine/ImGui/ImGuiStackRecovery.cs b/src/RynthCore.Engine/ImGui/ImGuiStackRecovery.cs deleted file mode 100644 index 41a6ff3..0000000 --- a/src/RynthCore.Engine/ImGui/ImGuiStackRecovery.cs +++ /dev/null @@ -1,99 +0,0 @@ -// ============================================================================ -// RynthCore.Engine - ImGuiStackRecovery.cs -// -// Closes ImGui scopes a plugin left open when it threw mid-frame (Begin without -// End, BeginTable without EndTable, unpopped IDs / style vars, ...). -// -// The shipped cimgui (Dear ImGui 1.89.7, static CRT, asserts on) reports a -// mismatched stack at EndFrame through IM_ASSERT, which shows a modal -// MessageBoxA on AC's main thread. The client then freezes until the hang -// watchdog kills it. ImGui's own recovery routine, -// ErrorCheckEndFrameRecover, unwinds everything down to the implicit fallback -// window; it is documented as safe to call right before EndFrame. -// -// 1.89.7 has no io.ConfigErrorRecovery* fields, so ImGui.NET's 1.91 IO layout -// must not be used to switch the assert off; the export is called directly. -// ============================================================================ - -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace RynthCore.Engine.ImGuiBackend; - -internal static unsafe class ImGuiStackRecovery -{ - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); - - // void igErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data) - private static delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void> _recover; - private static bool _resolved; - private static bool _loggedUnavailable; - - private static int _recoveredThisFrame; - private static long _totalRecovered; - private static long _nextLogAtMs; - private static string _lastMessage = string.Empty; - - /// <summary>Scopes closed since the engine started.</summary> - internal static long TotalRecovered => _totalRecovered; - - /// <summary> - /// Unwinds any ImGui scope still open at the end of plugin rendering. Must be - /// called on the render thread, with the engine's context current, outside - /// every Begin the caller itself opened (i.e. right before EndFrame). - /// </summary> - internal static void RecoverBeforeEndFrame() - { - if (!_resolved) Resolve(); - if (_recover == null) return; - - _recoveredThisFrame = 0; - _recover((IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, byte*, byte*, void>)&OnRecovered, IntPtr.Zero); - if (_recoveredThisFrame == 0) return; - - _totalRecovered += _recoveredThisFrame; - long now = Environment.TickCount64; - if (now < _nextLogAtMs) return; - _nextLogAtMs = now + 10_000; - RynthLog.Warn($"ImGuiStackRecovery: closed {_recoveredThisFrame} ImGui scope(s) a plugin left open " - + $"(total {_totalRecovered}); last: {_lastMessage}"); - } - - private static void Resolve() - { - _resolved = true; - IntPtr module = EntryPoint.ImGuiNativeHandle; - IntPtr fn = module != IntPtr.Zero ? GetProcAddress(module, "igErrorCheckEndFrameRecover") : IntPtr.Zero; - _recover = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)fn; - if (fn == IntPtr.Zero && !_loggedUnavailable) - { - _loggedUnavailable = true; - RynthLog.Warn("ImGuiStackRecovery: igErrorCheckEndFrameRecover not exported by cimgui; plugin frame errors can still assert."); - } - else if (fn != IntPtr.Zero) - { - RynthLog.Info($"ImGuiStackRecovery: armed (igErrorCheckEndFrameRecover @ 0x{fn:X8})."); - } - } - - // ImGuiErrorLogCallback is variadic cdecl (caller cleans the stack). Every recovery - // message in 1.89.7 carries exactly one %s (the window name), so the first variadic - // argument is read as a third fixed parameter. - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static void OnRecovered(IntPtr userData, byte* fmt, byte* arg) - { - try - { - _recoveredThisFrame++; - string format = fmt != null ? Marshal.PtrToStringAnsi((IntPtr)fmt) ?? string.Empty : string.Empty; - string name = arg != null ? Marshal.PtrToStringAnsi((IntPtr)arg) ?? string.Empty : string.Empty; - _lastMessage = format.Replace("%s", name); - } - catch - { - // Never let a managed exception unwind into native ImGui. - } - } -} diff --git a/src/RynthCore.Engine/ImGui/ImGuiTextFocus.cs b/src/RynthCore.Engine/ImGui/ImGuiTextFocus.cs new file mode 100644 index 0000000..dc800a9 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ImGuiTextFocus.cs @@ -0,0 +1,81 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ImGuiTextFocus.cs +// Which RynthCore ImGui text box holds the keyboard, per ImGui context (the +// main frame and each pop-out), seen from the box itself: FaceKit.TextBox and +// the script-window replay call NoteActive while their InputText is the +// active item. That is the same frame the click lands, one frame ahead of +// io.WantTextInput (which ImGui publishes from the previous frame's widgets). +// +// Used two ways by Win32Backend's WndProc: +// * keyboard capture: a box active in the last frame keeps keys from AC +// even before io.WantTextInput catches up (the click-then-type frame); +// * the leak diagnostic: a key-down or char that is about to reach AC while +// a box was active logs one "[Input] key reached AC ..." line per burst. +// +// Threads: AC's main thread only (ImGui frames and the game WndProc both run +// there). No locks. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class ImGuiTextFocus +{ + private static string? _frameOwner; // the frame being built + private static string? _mainOwner; // the last main frame's + private static readonly Dictionary<string, string> PopOwners = new(StringComparer.OrdinalIgnoreCase); + + /// <summary>A text box is the active item in the frame being built. AC thread, in the draw.</summary> + public static void NoteActive(string id) + { + if (_frameOwner != null) return; + string? panel = ImGuiPanelHost.DrawingTitle; + _frameOwner = string.IsNullOrEmpty(panel) ? id : panel + " " + id; + if (ImGuiPopOuts.InPopOutFrame) _frameOwner += " (popped out)"; + } + + /// <summary>A frame (main or pop-out) is about to be built.</summary> + public static void BeginFrame() => _frameOwner = null; + + /// <summary>The main frame was built. <paramref name="wantTextInput"/> is its io.WantTextInput.</summary> + public static void EndMainFrame(bool wantTextInput) + { + _mainOwner = _frameOwner ?? (wantTextInput ? "a text field in the client" : null); + _frameOwner = null; + } + + /// <summary>No main frame this tick (nothing ImGui open, or the frame failed): no box.</summary> + public static void ClearMain() + { + _mainOwner = null; + _frameOwner = null; + } + + /// <summary>A box was active in the last main frame (FaceKit / script windows only).</summary> + public static bool MainBoxActive => _mainOwner != null; + + /// <summary>A pop-out's frame was built. Returns true when one of its boxes was active.</summary> + public static bool EndPopOutFrame(string title, bool wantTextInput) + { + string? owner = _frameOwner ?? (wantTextInput ? title + " (popped out)" : null); + _frameOwner = null; + if (owner != null) PopOwners[title] = owner; + else PopOwners.Remove(title); + return owner != null; + } + + public static void ForgetPopOut(string title) => PopOwners.Remove(title); + + /// <summary>The box holding the keyboard (main frame first), or null.</summary> + public static string? ActiveOwner + { + get + { + if (_mainOwner != null) return _mainOwner; + foreach (string owner in PopOwners.Values) return owner; + return null; + } + } +} diff --git a/src/RynthCore.Engine/ImGui/ItemDragBridge.cs b/src/RynthCore.Engine/ImGui/ItemDragBridge.cs new file mode 100644 index 0000000..6cbd4e8 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ItemDragBridge.cs @@ -0,0 +1,251 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ItemDragBridge.cs +// Carries an item drag into the MAIN ImGui context when it didn't start there, +// so drop targets in the client (RynthAi's Mini Remote slots) can take it: +// +// • A popped-out Inventory: the pop-out has its own ImGui context and holds +// mouse capture for the whole drag, so the main context never sees it. +// The pop-out face reports the dragged item (NotePopOutDrag); the main +// frame republishes it as an extern payload. The main context sees no +// button press, so the payload uses PayloadAutoExpire: it is delivered to +// the hovered target on the first frame it is no longer submitted. +// • AC's own inventory: a press that began on the game belongs to the game, +// and ImGui ignores hovering for it. DragDropHooks reports the item AC +// starts dragging (OnNativeDragStart); a carried one is republished the +// same way, under PayloadType, and delivered when ImGui sees the button go +// up. AC does not select the dragged item, so without that hook the bridge +// can only guess from the selection: the guess goes out under +// NativePayloadType, which targets treat as unreliable. +// +// A native drag released over an ImGui window would otherwise complete in AC +// as a drop on the 3D view (the item lands on the ground). TryRedirectNativeDrop +// moves that button-up back to where the drag began, which AC treats as +// putting the item back. +// +// Threads: AC's main thread only (game WndProc, EndScene, pop-out frames). +// ============================================================================ + +using System; +using System.Diagnostics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static unsafe class ItemDragBridge +{ + /// <summary>Payload type for one item (uint object id). Must match RynthAi's MiniRemoteHud.ItemPayloadType.</summary> + public const string PayloadType = "RYNTH_INV_ITEM"; + + /// <summary> + /// Payload type for a game drag whose item was guessed from the selection (DragDropHooks not + /// installed). Any game left-drag with a carried item selected looks like this (moving an AC + /// panel too), so targets should take it only where a wrong item does no harm (RynthAi: empty + /// slots). Must match MiniRemoteHud.GameItemPayloadType. + /// </summary> + public const string NativePayloadType = "RYNTH_GAME_ITEM"; + + private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202; + private const int MK_LBUTTON = 0x0001, MK_OTHER = 0x0002 | 0x0010 | 0x0020 | 0x0040; + /// <summary>Movement (px, squared) before a game press counts as a drag.</summary> + private const int DragThresholdSq = 5 * 5; + /// <summary>AC may select the pressed item a few messages after the press: keep re-reading it this long.</summary> + private static readonly long SelectionSettleTicks = Stopwatch.Frequency / 2; + /// <summary>A pop-out drag with no report for this long is over (the pop-out closed mid-drag).</summary> + private static readonly long PopOutStaleTicks = Stopwatch.Frequency; + + // Popped-out Inventory drag. + private static uint _popOutItem; + private static long _popOutSeenAt; + + // Native (AC inventory) drag. + private static bool _pressPending; + private static IntPtr _pressLParam; + private static int _pressX, _pressY; + private static long _pressAt; + private static uint _nativeItem; + /// <summary>_nativeItem came from AC's drag start (DragDropHooks), not from the selection.</summary> + private static bool _nativeFromHook; + /// <summary>The left button is down on a press that belongs to the game.</summary> + private static bool _gamePressHeld; + private static bool _nativeReleased; + /// <summary>The cursor was over an ImGui window in the last main frame (only tracked during a native drag).</summary> + private static bool _overImGui; + + // ── Popped-out Inventory ──────────────────────────────────────────────── + + /// <summary>A popped-out Inventory is dragging <paramref name="itemId"/> (call every pop-out frame of the drag).</summary> + public static void NotePopOutDrag(uint itemId) + { + if (itemId == 0) return; + if (_popOutItem != itemId) + RynthLog.UI($"ItemDragBridge: pop-out drag 0x{itemId:X8} published to the client."); + _popOutItem = itemId; + _popOutSeenAt = Stopwatch.GetTimestamp(); + } + + /// <summary>The popped-out Inventory's drag ended (dropped or cancelled).</summary> + public static void EndPopOutDrag() => _popOutItem = 0; + + // ── Native drag (game WndProc) ────────────────────────────────────────── + + /// <summary> + /// Every game-window mouse message, after the backend decided who owns the held buttons. + /// <paramref name="gameOwned"/>: the current press began on the game, not on ImGui. + /// </summary> + public static void OnGameMouse(uint msg, IntPtr wParam, IntPtr lParam, bool gameOwned) + { + int keys = (int)((long)wParam & 0xFFFF); + switch (msg) + { + case WM_LBUTTONDOWN: + // Only a plain left press that belongs to the game can be an inventory drag. + _pressPending = gameOwned && (keys & MK_OTHER) == 0; + _pressLParam = lParam; + _pressX = LoWord(lParam); + _pressY = HiWord(lParam); + _pressAt = Stopwatch.GetTimestamp(); + _gamePressHeld = _pressPending; + if (_pressPending) { _nativeItem = 0; _nativeFromHook = false; _nativeReleased = false; } + break; + + case WM_MOUSEMOVE: + if ((keys & MK_LBUTTON) == 0) + { + // A release we never saw (outside the window): finish the drag. + _pressPending = false; + _gamePressHeld = false; + if (_nativeItem != 0) _nativeReleased = true; + break; + } + if (_pressPending) + { + int dx = LoWord(lParam) - _pressX, dy = HiWord(lParam) - _pressY; + if (dx * dx + dy * dy >= DragThresholdSq) + { + _pressPending = false; + // With the drag-start hook the real item arrives through OnNativeDragStart. + if (_nativeItem == 0 && !DragDropHooks.IsInstalled) + { + _nativeItem = CarriedSelection(); + if (_nativeItem != 0) + RynthLog.UI($"ItemDragBridge: native inventory drag 0x{_nativeItem:X8} (from the selection) published to ImGui."); + } + } + } + else if (_nativeItem != 0 && !_nativeFromHook && !_nativeReleased && Stopwatch.GetTimestamp() - _pressAt < SelectionSettleTicks) + { + // The selection can trail the press by a few messages: follow it while it settles. + uint sel = CarriedSelection(); + if (sel != 0) _nativeItem = sel; + } + break; + + case WM_LBUTTONUP: + _pressPending = false; + _gamePressHeld = false; + if (_nativeItem != 0) _nativeReleased = true; + break; + } + } + + /// <summary> + /// AC started dragging <paramref name="itemId"/> (DragDropHooks, AC's main thread). Taken while + /// a game-owned left press is held and only for items the player carries. + /// </summary> + public static void OnNativeDragStart(uint itemId) + { + if (!_gamePressHeld || itemId == 0 || !IsCarried(itemId)) return; + _pressPending = false; + _nativeItem = itemId; + _nativeFromHook = true; + _nativeReleased = false; + RynthLog.UI($"ItemDragBridge: native inventory drag 0x{itemId:X8} published to ImGui."); + } + + /// <summary> + /// A native item drag is being released over an ImGui window: returns the press position + /// to send AC instead, so AC puts the item back rather than dropping it on the ground. + /// </summary> + public static bool TryRedirectNativeDrop(uint msg, out IntPtr pressLParam) + { + pressLParam = _pressLParam; + if (msg != WM_LBUTTONUP || _nativeItem == 0 || !_overImGui) return false; + RynthLog.UI($"ItemDragBridge: native drag 0x{_nativeItem:X8} released over an ImGui window; AC gets the drop back at its start ({_pressX},{_pressY})."); + return true; + } + + // ── Main frame (after ImGui.NewFrame, before any window) ──────────────── + + /// <summary>Republishes a pop-out or native drag in the main context for this frame.</summary> + public static void SubmitMainFrame(ImGuiIOPtr io) + { + uint id = 0; + string type = PayloadType; + if (_popOutItem != 0) + { + if (Stopwatch.GetTimestamp() - _popOutSeenAt > PopOutStaleTicks) _popOutItem = 0; + else id = _popOutItem; + } + + if (id == 0 && _nativeItem != 0) + { + type = _nativeFromHook ? PayloadType : NativePayloadType; + // After the button-up, stop once ImGui itself sees the button up: that frame + // delivers the drop (the payload outlives its last submission by one frame). + if (_nativeReleased && !io.MouseDown[0]) + { + _nativeItem = 0; + _nativeFromHook = false; + _nativeReleased = false; + _overImGui = false; + return; + } + id = _nativeItem; + _overImGui = ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem); + } + + if (id == 0) return; + const ImGuiDragDropFlags flags = ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip + | ImGuiDragDropFlags.PayloadAutoExpire; + if (ImGuiNET.ImGui.BeginDragDropSource(flags)) + { + ImGuiNET.ImGui.SetDragDropPayload(type, (IntPtr)(&id), sizeof(uint)); + ImGuiNET.ImGui.EndDragDropSource(); + } + } + + /// <summary>Forget every drag (focus lost, logout, engine shutdown).</summary> + public static void Reset() + { + _popOutItem = 0; + _pressPending = false; + _gamePressHeld = false; + _nativeItem = 0; + _nativeFromHook = false; + _nativeReleased = false; + _overImGui = false; + } + + /// <summary>The game's selected object when the player carries it, else 0.</summary> + private static uint CarriedSelection() + { + uint id = ClientHelperHooks.GetSelectedItemId(); + return IsCarried(id) ? id : 0; + } + + /// <summary><paramref name="id"/> is in the player's pack, a side pack, or worn.</summary> + private static bool IsCarried(uint id) + { + if (id == 0 || !ClientHelperHooks.HasGetPlayerId) return false; + uint player = ClientHelperHooks.GetPlayerId(); + if (player == 0 || id == player) return false; + if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _)) return false; + if (wielder == player || container == player) return true; + // Side pack in the main pack. + return container != 0 && ClientObjectHooks.TryGetObjectOwnershipInfo(container, out uint outer, out _, out _) && outer == player; + } + + private static int LoWord(IntPtr l) => unchecked((short)((long)l & 0xFFFF)); + private static int HiWord(IntPtr l) => unchecked((short)(((long)l >> 16) & 0xFFFF)); +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/CombatText.cs b/src/RynthCore.Engine/ImGui/MonsterHud/CombatText.cs new file mode 100644 index 0000000..a226cea --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/CombatText.cs @@ -0,0 +1,832 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/CombatText.cs +// RynthVision combat text, the ImGui port of the RynthJuice plugin (so it +// also works in dungeons), plus the gain text: +// - damage you deal: a number over the monster, white -> yellow -> orange +// -> red by size, GOLD, bigger and with "!" on a crit; +// - damage you take: red numbers over your head; +// - heals: green "+N" over you or a monster; +// - kill burst: expanding rings where a monster you damaged dies; +// - gains: "+12,345 XP", "+500 Lum", "+10 Radiance" rising over your head. +// Numbers pop from the head with a little sideways jitter, drift up and fade +// (~1.2 s; crits pop larger). At most MaxNumbers live at once. +// +// Sources (engine-side events, no polling of monsters): +// AttackerNotification / DefenderNotification (SmartBoxHooks, exact melee +// and missile damage + crit; the target is named, not id'd); +// ACE's spell lines "[Critical hit! ]You <verb> <target> for N points +// with <spell>." and "<source> <verbs> you for N points with <spell>.", +// and damage over time ("You <verb> <target> for N points of periodic +// ... damage!", "You receive N points of periodic harm."); +// health observations (MonsterHudData): a monster reaching 0 (kill) or +// rising (heal); the player's own vitals snapshot for heals; +// KillerNotification (the death message names the victim) and object +// deletes after a recent hit (kill fallback); +// XP / Luminance: TotalExperience (Int64 1) and AvailableLuminance +// (Int64 6) read at 4 Hz on AC's thread, rises only (spending never +// shows); Radiance (Aelrynth): "You gain N Radiance." in chat. +// ACE sends no damage notification for a killing blow, so the last hit's +// number is estimated from the last health ratio x max HP when the max is +// known (appraised), else only the burst shows. +// +// Hooks run on AC's main thread and only queue (a lock, a struct); the +// render thread resolves names to monsters and draws. Engine-owned statics. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +internal static class CombatText +{ + private const int MaxNumbers = 30; + private const int MaxBursts = 8; + private const int MaxGains = 6; + private const int MaxEvents = 64; + // Base lifetimes; MonsterHudSettings.NumTime scales them. + private const float NumberLife = 2.0f, CritLife = 2.5f, HealLife = 1.8f; + private const float GainLife = 1.8f, GainMergeSec = 0.3f; + private const float BurstLife = 1.1f; + private const double KillAfterHitSec = 10.0; // a death counts as "yours" this long after your last hit + private const double DeleteKillSec = 8.0; // a delete counts as a death this soon after your last hit + + private static uint C(uint argb) => MonsterHud.C(argb); + private static readonly uint StaminaAmber = C(0xFFFFC040), ManaBlue = C(0xFF5AA8FF); + private static readonly uint Gold = C(0xFFFFD700), HealGreen = C(0xFF50FF50), TakenRed = C(0xFFFF2828), + White = C(0xFFFFFFFF), PaleYellow = C(0xFFFFF080), Orange = C(0xFFFFA030), Red = C(0xFFFF3828), + BurstCyan = C(0xFF60FFFF), BurstGold = C(0xFFFFD24A), + XpGold = C(0xFFFFC83C), LumViolet = C(0xFFC08CFF), RadianceTeal = C(0xFF7FF0E0); + + // ── Events (AC's main thread -> render thread) ────────────────────── + private enum EvKind : byte { Dealt, Taken, Health, KillMsg, Deleted, Radiance, Test, ChatXp, ChatLum } + private readonly record struct Ev(EvKind Kind, uint Id, string? Text, int Amount, bool Crit, float Prev, float Ratio, uint Max); + + private static readonly object Sync = new(); + private static readonly List<Ev> Pending = new(MaxEvents); + private static readonly List<Ev> Work = new(MaxEvents); + + // ── Live effects (render thread) ──────────────────────────────────── + private enum NumKind : byte { Dealt, Taken, Heal, Stamina, Mana } + + private sealed class Number + { + public bool Active; + public NumKind Kind; + public string Text = ""; + public uint Color; + public bool Crit; + public long Born; + public float Life; + public bool OnPlayer; + public uint Cell; + public float X, Y, Z; + public float Jitter; + public uint Target; + } + + private sealed class Burst + { + public bool Active; + public bool Crit; + public long Born; + public uint Cell; + public float X, Y, Z; // feet + } + + private enum GainKind : byte { Xp, Lum, Radiance } + + private sealed class Gain + { + public GainKind Kind; + public long Amount; + public long Born; + public long Merged; + public string Text = ""; + } + + private sealed class Hit + { + public long Ticks; + public uint Cell; + public float X, Y, Z; // head + public float FeetZ; + public long BurstAt; + } + + private static readonly Number[] Numbers = CreatePool<Number>(MaxNumbers); + private static readonly Burst[] Bursts = CreatePool<Burst>(MaxBursts); + private static readonly List<Gain> Gains = new(MaxGains); + private static readonly Dictionary<uint, Hit> Hits = new(64); + private static readonly List<uint> HitEvict = new(16); + private static int _liveNumbers, _liveBursts; + private static uint _rng = 0x9E3779B9u; + private static long _nextHitPrune; + + // Player vitals (heals) and the gain baselines. + private static uint _prevHealth, _prevMaxHealth, _prevStamina, _prevMaxStamina, _prevMana, _prevMaxMana; + private static uint _gainOwner; + private static long _xpBase = -1, _lumBase = -1; + // A chat line already showed this rise (Aelrynth's kill summary): the property poll skips it. + private static long _chatXpUntil, _chatLumUntil; + private static string _lastRadianceLine = ""; + private static long _lastRadianceTicks; + private static int _statNumbers, _statBursts, _statGains; + + private static T[] CreatePool<T>(int n) where T : new() + { + var a = new T[n]; + for (int i = 0; i < n; i++) a[i] = new T(); + return a; + } + + /// <summary>True while anything is on screen or waiting to be drawn.</summary> + public static bool HasContent + { + get + { + if (_liveNumbers > 0 || _liveBursts > 0 || Gains.Count > 0) return true; + lock (Sync) return Pending.Count > 0; + } + } + + public static void Clear() + { + lock (Sync) Pending.Clear(); + foreach (Number n in Numbers) n.Active = false; + foreach (Burst b in Bursts) b.Active = false; + Gains.Clear(); + Hits.Clear(); + _liveNumbers = _liveBursts = 0; + _prevHealth = _prevMaxHealth = 0; + _gainOwner = 0; + _xpBase = _lumBase = -1; + } + + /// <summary>When the player last hit this monster (Stopwatch ticks), long.MinValue if never. Render thread.</summary> + public static long LastHitTicks(uint id) => Hits.TryGetValue(id, out Hit? h) ? h.Ticks : long.MinValue; + + // ════════════════════════════════════════════════════════════════════ + // Feeds (AC's main thread; queue only) + // ════════════════════════════════════════════════════════════════════ + + private static void Push(in Ev e) + { + lock (Sync) + { + if (Pending.Count >= MaxEvents) Pending.RemoveAt(0); + Pending.Add(e); + } + } + + private static bool NumbersOn => MonsterHudSettings.Numbers; + + private static long _lastDamageKey, _lastDamageTicks; + private static string? _lastDamageName; + + /// <summary>AttackerNotification (you hit <paramref name="name"/>) / DefenderNotification (you were hit).</summary> + public static void OnDamageEvent(bool attacker, string? name, uint damage, bool crit) + { + if (!NumbersOn || damage == 0) return; + // The same event seen by both of SmartBoxHooks' paths within 50 ms is one hit. + long key = ((long)damage << 2) | (attacker ? 2L : 0L) | (crit ? 1L : 0L); + long now = Stopwatch.GetTimestamp(); + if (key == _lastDamageKey && name == _lastDamageName && now - _lastDamageTicks < Stopwatch.Frequency / 20) return; + _lastDamageKey = key; _lastDamageName = name; _lastDamageTicks = now; + if (attacker) + { + if (!string.IsNullOrEmpty(name)) Push(new Ev(EvKind.Dealt, 0, name, (int)damage, crit, 0, 0, 0)); + } + else if (MonsterHudSettings.NumTaken) + { + Push(new Ev(EvKind.Taken, 0, null, (int)damage, crit, 0, 0, 0)); + } + } + + /// <summary>A health observation for a creature (not the player): kills and heals.</summary> + public static void OnHealth(uint id, float prev, float ratio, uint max) + { + if (!NumbersOn || prev < 0f) return; + if (ratio <= 0.001f && prev > 0.001f) + Push(new Ev(EvKind.Health, id, null, 0, false, prev, ratio, max)); + else if (ratio > prev + 0.001f && MonsterHudSettings.NumHeals) + Push(new Ev(EvKind.Health, id, null, 0, false, prev, ratio, max)); + } + + /// <summary>KillerNotification: the player killed something; the message names it.</summary> + public static void OnKillMessage(string? message) + { + if (!NumbersOn || string.IsNullOrEmpty(message)) return; + Push(new Ev(EvKind.KillMsg, 0, message, 0, false, 0, 0, 0)); + } + + /// <summary>"/rv plates test": a spread of sample numbers, a burst and gains around the player.</summary> + public static void SpawnTest() => Push(new Ev(EvKind.Test, 0, null, 0, false, 0, 0, 0)); + + public static void OnDeleted(uint id) + { + if (!NumbersOn || !MonsterHudSettings.NumKills) return; + // Only creatures can be kill-burst candidates; items and corpses come and go all the time. + if (!ClientObjectHooks.TryGetSnapshotItemType(id, out uint type) || (type & 0x10) == 0) return; + Push(new Ev(EvKind.Deleted, id, null, 0, false, 0, 0, 0)); + } + + private static int _radianceDiag, _gainDiag; + + private static readonly string[] AttackPrefixes = { "Critical hit! ", "Overpower! ", "Sneak Attack! " }; + + /// <summary>A chat line: spell damage (dealt / taken) and Radiance gains. Cheap for anything else.</summary> + public static void OnChat(string line) + { + if (line.Length < 14) return; + + // Diagnostics: the first lines mentioning Radiance (every kill line), and whether they parse. + if (_radianceDiag < 60 && line.Contains("Radiance", StringComparison.Ordinal)) + { + _radianceDiag++; + bool shape = line.StartsWith("You gain ", StringComparison.Ordinal) && line.EndsWith(" Radiance.", StringComparison.Ordinal); + RynthLog.Compat($"Nameplates: radiance line '{line}' (len {line.Length}, matches {shape}, gains {MonsterHudSettings.Gains}/{MonsterHudSettings.GainRadiance})"); + } + + // Aelrynth's kill summary: "Kill: +5,000 experience, +50 Radiance." (parts optional, + // "Luminance" too). It reports XP even at max level, where TotalExperience no longer rises. + if (line.StartsWith("Kill: +", StringComparison.Ordinal)) + { + if (!MonsterHudSettings.Gains) return; + long now = Stopwatch.GetTimestamp(); + if (line == _lastRadianceLine && now - _lastRadianceTicks < Stopwatch.Frequency / 10) return; + _lastRadianceLine = line; + _lastRadianceTicks = now; + // Parts are separated by ", "; a bare ',' is a thousands separator ("+10,500 experience"), + // which the old Split(',') cut in two, dropping every XP amount of 1,000 or more. + foreach (string raw in line.Substring(6).TrimEnd('.').Split(", ")) + { + string part = raw.Trim(); + if (part.Length < 3 || part[0] != '+') continue; + int sp = part.IndexOf(' '); + if (sp < 2 || !TryParseNumber(part.AsSpan(1, sp - 1), out long amount) || amount <= 0) continue; + string what = part.Substring(sp + 1); + int amt = (int)Math.Min(amount, int.MaxValue); + if (what.StartsWith("experience", StringComparison.OrdinalIgnoreCase)) + { + if (!MonsterHudSettings.GainXp) continue; + _chatXpUntil = now + Stopwatch.Frequency * 2; // the property poll skips this rise + Push(new Ev(EvKind.ChatXp, 0, null, amt, false, 0, 0, 0)); + } + else if (what.StartsWith("Luminance", StringComparison.OrdinalIgnoreCase)) + { + if (!MonsterHudSettings.GainLum) continue; + _chatLumUntil = now + Stopwatch.Frequency * 2; + Push(new Ev(EvKind.ChatLum, 0, null, amt, false, 0, 0, 0)); + } + else if (what.StartsWith("Radiance", StringComparison.OrdinalIgnoreCase)) + { + if (MonsterHudSettings.GainRadiance) Push(new Ev(EvKind.Radiance, 0, null, amt, false, 0, 0, 0)); + } + } + return; + } + + // "You gain 1,234 Radiance." (Aelrynth; may be batched) + if (line.StartsWith("You gain ", StringComparison.Ordinal) && line.EndsWith(" Radiance.", StringComparison.Ordinal)) + { + if (!MonsterHudSettings.Gains || !MonsterHudSettings.GainRadiance) return; + long now = Stopwatch.GetTimestamp(); + // The same line twice within 100 ms is one line seen by two chat paths. + if (line == _lastRadianceLine && now - _lastRadianceTicks < Stopwatch.Frequency / 10) return; + _lastRadianceLine = line; + _lastRadianceTicks = now; + if (TryParseNumber(line.AsSpan(9, line.Length - 9 - " Radiance.".Length), out long amount) && amount > 0) + Push(new Ev(EvKind.Radiance, 0, null, (int)Math.Min(amount, int.MaxValue), false, 0, 0, 0)); + return; + } + + if (!NumbersOn) return; + + // Damage over time on you: "You receive N points of periodic harm." + if (line.StartsWith("You receive ", StringComparison.Ordinal) && line.EndsWith(" points of periodic harm.", StringComparison.Ordinal)) + { + if (MonsterHudSettings.NumTaken && + TryParseNumber(line.AsSpan(12, line.Length - 12 - " points of periodic harm.".Length), out long harm) && harm > 0 && harm < 1_000_000) + Push(new Ev(EvKind.Taken, 0, null, (int)harm, false, 0, 0, 0)); + return; + } + + // Spells: "... for N points with <spell>."; your damage over time: "You <verb> <target> for N points of periodic <type> damage!" + int ptsWith = line.IndexOf(" points with ", StringComparison.Ordinal); + if (ptsWith < 0) ptsWith = line.IndexOf(" points of periodic ", StringComparison.Ordinal); + if (ptsWith < 0) return; + + bool crit = false; + int start = 0; + for (bool again = true; again;) + { + again = false; + foreach (string pre in AttackPrefixes) + if (string.CompareOrdinal(line, start, pre, 0, pre.Length) == 0) + { + if (pre[0] == 'C') crit = true; + start += pre.Length; + again = true; + } + } + + int forAt = line.LastIndexOf(" for ", ptsWith, StringComparison.Ordinal); + if (forAt <= start || !TryParseNumber(line.AsSpan(forAt + 5, ptsWith - forAt - 5), out long n) || n <= 0 || n > 1_000_000) + return; + + if (string.CompareOrdinal(line, start, "You ", 0, 4) == 0) + { + // "You <verb> <target> for N points with <spell>." + int verbEnd = line.IndexOf(' ', start + 4); + if (verbEnd < 0 || verbEnd >= forAt) return; + string target = line[(verbEnd + 1)..forAt]; + if (target.Length > 0) Push(new Ev(EvKind.Dealt, 0, target, (int)n, crit, 0, 0, 0)); + } + else if (MonsterHudSettings.NumTaken && forAt >= 4 && string.CompareOrdinal(line, forAt - 4, " you", 0, 4) == 0) + { + // "<source> <verbs> you for N points with <spell>." + Push(new Ev(EvKind.Taken, 0, null, (int)n, crit, 0, 0, 0)); + } + } + + /// <summary>Digits with thousands separators ("12,345").</summary> + private static bool TryParseNumber(ReadOnlySpan<char> s, out long value) + { + value = 0; + bool any = false; + foreach (char ch in s) + { + if (ch == ',' || ch == '.' || ch == ' ') continue; + if (ch < '0' || ch > '9') return false; + value = value * 10 + (ch - '0'); + any = true; + if (value > 1_000_000_000_000L) return false; + } + return any; + } + + /// <summary>XP / Luminance rises since the last poll (4 Hz, AC's thread, from MonsterHud.Update).</summary> + public static void PollGains(uint playerId) + { + if (playerId == 0) return; + if (playerId != _gainOwner) { _gainOwner = playerId; _xpBase = _lumBase = -1; } + bool gains = MonsterHudSettings.Gains; + if (!ClientObjectHooks.TryGetObjectQuadProperty(playerId, 1u, out long xp) || xp <= 0) return; // TotalExperience + long nowTicks = Stopwatch.GetTimestamp(); + if (_xpBase >= 0 && xp > _xpBase && gains && MonsterHudSettings.GainXp && nowTicks > _chatXpUntil) AddGain(GainKind.Xp, xp - _xpBase); + _xpBase = xp; + // AvailableLuminance: absent means 0 once the player's qualities are readable (the XP read was). + long lum = ClientObjectHooks.TryGetObjectQuadProperty(playerId, 6u, out long l) ? l : 0; + if (_lumBase >= 0 && lum > _lumBase && gains && MonsterHudSettings.GainLum && nowTicks > _chatLumUntil) AddGain(GainKind.Lum, lum - _lumBase); + _lumBase = lum; + } + + // ════════════════════════════════════════════════════════════════════ + // Draw (render thread, inside the ImGui frame) + // ════════════════════════════════════════════════════════════════════ + + public static void Draw(ref MonsterHud.Frame f) + { + ProcessEvents(ref f); + if (NumbersOn && MonsterHudSettings.NumHeals) WatchPlayerHeals(); + PruneHits(f.Now); + + float k = MonsterHudSettings.Scale * f.UiScale; + if (_liveBursts > 0) DrawBursts(ref f, k); + if (_liveNumbers > 0) DrawNumbers(ref f, k); + if (Gains.Count > 0) DrawGains(ref f, k); + } + + private static void ProcessEvents(ref MonsterHud.Frame f) + { + Work.Clear(); + lock (Sync) + { + if (Pending.Count == 0) return; + Work.AddRange(Pending); + Pending.Clear(); + } + uint player = ClientHelperHooks.GetPlayerId(); + foreach (Ev e in Work) + { + switch (e.Kind) + { + case EvKind.Dealt: + { + uint id = MonsterHud.FindPlateByName(e.Text!); + if (id == 0) id = PlateDebuffs.UniqueNearby(e.Text!); + if (id == 0 || !NoteHit(id, f.Now, out Hit h)) break; + if (MonsterHudSettings.NumDealt) + SpawnNumber(NumKind.Dealt, e.Amount, e.Crit, false, h.Cell, h.X, h.Y, h.Z, id, f.Now); + break; + } + case EvKind.Taken: + SpawnNumber(NumKind.Taken, e.Amount, e.Crit, true, 0, 0, 0, 0, 0, f.Now); + break; + case EvKind.Health: + if (e.Id == player) break; + if (e.Ratio <= 0.001f) + { + Kill(e.Id, e.Prev, e.Max, f.Now, requireHit: true); + } + else + { + uint max = e.Max; + if (max == 0 && ObjectQualityCache.TryGetCreatureVitals(e.Id, out CreatureVitals v)) max = v.MaxHealth; + int delta = max > 0 ? (int)MathF.Round((e.Ratio - e.Prev) * max) : 0; + if (delta >= Math.Max(8, (int)(max * 0.05f)) && MonsterHud.TryGetHead(e.Id, out uint c, out float x, out float y, out float z, out _)) + SpawnNumber(NumKind.Heal, delta, false, false, c, x, y, z, e.Id, f.Now); + } + break; + case EvKind.KillMsg: + { + uint id = MonsterHud.FindPlateNamedIn(e.Text!); + if (id == 0) break; + float prev = MonsterHudData.TryGetHealth(id, out HealthObservation ho) ? ho.Ratio : 0f; + uint max = ho.Max; + Kill(id, prev, max, f.Now, requireHit: false); + break; + } + case EvKind.Deleted: + if (Hits.TryGetValue(e.Id, out Hit? dh)) + { + if (dh.BurstAt == 0 && f.Now - dh.Ticks < (long)(DeleteKillSec * Stopwatch.Frequency) && + MonsterHudSettings.NumKills) + SpawnBurst(dh.Cell, dh.X, dh.Y, dh.FeetZ, false, f.Now); + Hits.Remove(e.Id); + } + break; + // Chat-reported gains show one-for-one with the chat line: merging two kills + // inside GainMergeSec showed a sum that matched no line in chat (2026-09-30). + case EvKind.Radiance: + AddGain(GainKind.Radiance, e.Amount, merge: false); + break; + case EvKind.ChatXp: + AddGain(GainKind.Xp, e.Amount, merge: false); + break; + case EvKind.ChatLum: + AddGain(GainKind.Lum, e.Amount, merge: false); + break; + case EvKind.Test: + { + uint c = f.PlayerCell; + float x = f.Px, y = f.Py, z = f.Pz + 2f; + SpawnNumber(NumKind.Dealt, 18, false, false, c, x + 2f, y + 2f, z, 0, f.Now); + SpawnNumber(NumKind.Dealt, 73, false, false, c, x - 2f, y + 1f, z, 0, f.Now); + SpawnNumber(NumKind.Dealt, 142, false, false, c, x + 1f, y - 2f, z, 0, f.Now); + SpawnNumber(NumKind.Dealt, 891, true, false, c, x - 1f, y - 1f, z, 0, f.Now); + SpawnNumber(NumKind.Heal, 64, false, false, c, x + 3f, y, z, 0, f.Now); + SpawnNumber(NumKind.Taken, 37, false, true, 0, 0, 0, 0, 0, f.Now); + SpawnBurst(c, x, y + 3f, f.Pz, false, f.Now); + AddGain(GainKind.Xp, 12345); + AddGain(GainKind.Lum, 500); + AddGain(GainKind.Radiance, 10); + break; + } + } + } + Work.Clear(); + } + + /// <summary>Records a hit on a monster (for kill attribution) with its head position. False without a position.</summary> + private static bool NoteHit(uint id, long now, out Hit hit) + { + if (!Hits.TryGetValue(id, out Hit? h)) + { + if (Hits.Count >= 128) Hits.Clear(); + h = new Hit(); + Hits[id] = h; + } + hit = h; + h.Ticks = now; + if (MonsterHud.TryGetHead(id, out uint cell, out float x, out float y, out float z, out float feet)) + { + h.Cell = cell; h.X = x; h.Y = y; h.Z = z; h.FeetZ = feet; + } + return h.Cell != 0; + } + + /// <summary>A monster died: the burst, the estimated killing blow, and its debuffs go.</summary> + private static void Kill(uint id, float prevRatio, uint max, long now, bool requireHit) + { + PlateDebuffs.Remove(id); + Hits.TryGetValue(id, out Hit? h); + bool recent = h != null && now - h.Ticks < (long)(KillAfterHitSec * Stopwatch.Frequency); + if (requireHit && !recent) return; + if (h != null && h.BurstAt != 0 && now - h.BurstAt < 5 * Stopwatch.Frequency) return; // already shown + + if (!MonsterHud.TryGetHead(id, out uint cell, out float x, out float y, out float z, out float feet)) + { + if (h == null || h.Cell == 0) return; + cell = h.Cell; x = h.X; y = h.Y; z = h.Z; feet = h.FeetZ; + } + if (h == null) + { + if (Hits.Count >= 128) Hits.Clear(); + h = new Hit { Ticks = long.MinValue / 2, Cell = cell, X = x, Y = y, Z = z, FeetZ = feet }; + Hits[id] = h; + } + h.BurstAt = now; + + // ACE sends no notification for the killing blow: estimate it from the last health seen. + if (MonsterHudSettings.NumDealt && recent) + { + if (max == 0 && ObjectQualityCache.TryGetCreatureVitals(id, out CreatureVitals v)) max = v.MaxHealth; + int est = max > 0 ? (int)MathF.Round(Math.Clamp(prevRatio, 0f, 1f) * max) : 0; + if (est > 0 && !RecentNumberOn(id, now)) SpawnNumber(NumKind.Dealt, est, false, false, cell, x, y, z, id, now); + } + if (MonsterHudSettings.NumKills) + SpawnBurst(cell, x, y, feet, false, now); + } + + private static bool RecentNumberOn(uint id, long now) + { + foreach (Number n in Numbers) + if (n.Active && n.Target == id && now - n.Born < Stopwatch.Frequency * 3 / 10) return true; + return false; + } + + private static void PruneHits(long now) + { + if (now < _nextHitPrune) return; + _nextHitPrune = now + Stopwatch.Frequency * 5; + HitEvict.Clear(); + foreach (KeyValuePair<uint, Hit> kv in Hits) + if (now - kv.Value.Ticks > 60 * Stopwatch.Frequency && (kv.Value.BurstAt == 0 || now - kv.Value.BurstAt > 60 * Stopwatch.Frequency)) + HitEvict.Add(kv.Key); + foreach (uint id in HitEvict) Hits.Remove(id); + } + + /// <summary>The player's health rising past regen size: a green number over the head.</summary> + private static void WatchPlayerHeals() + { + if (!PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot v) || v.MaxHealth == 0) return; + long now = Stopwatch.GetTimestamp(); + Restore(NumKind.Heal, v.Health, v.MaxHealth, ref _prevHealth, ref _prevMaxHealth, now); + if (MonsterHudSettings.NumRestores) + { + Restore(NumKind.Stamina, v.Stamina, v.MaxStamina, ref _prevStamina, ref _prevMaxStamina, now); + Restore(NumKind.Mana, v.Mana, v.MaxMana, ref _prevMana, ref _prevMaxMana, now); + } + } + + /// <summary>A rise bigger than a regen tick (spells, potions, kits): a number over the player.</summary> + private static void Restore(NumKind kind, uint cur, uint max, ref uint prevCur, ref uint prevMax, long now) + { + uint prev = prevCur, pm = prevMax; + prevCur = cur; + prevMax = max; + if (max == 0 || prev == 0 || pm != max || cur <= prev) return; + int delta = (int)(cur - prev); + if (delta >= Math.Max(10, (int)(max * 0.05f))) + SpawnNumber(kind, delta, false, true, 0, 0, 0, 0, 0, now); + } + + // ── Spawning ───────────────────────────────────────────────────────── + + private static void SpawnNumber(NumKind kind, int amount, bool crit, bool onPlayer, uint cell, float x, float y, float z, uint target, long now) + { + if (amount <= 0) return; + Number? n = null; + foreach (Number c in Numbers) + if (!c.Active) { n = c; break; } + if (n == null) + { + // Full: reuse the oldest. + n = Numbers[0]; + foreach (Number c in Numbers) if (c.Born < n.Born) n = c; + _liveNumbers--; + } + n.Active = true; + n.Kind = kind; + n.Crit = crit; + n.Born = now; + n.OnPlayer = onPlayer; + n.Cell = cell; n.X = x; n.Y = y; n.Z = z; + n.Target = target; + n.Jitter = (NextRandom() * 2f - 1f) * 14f; + string s = amount.ToString(CultureInfo.InvariantCulture); + switch (kind) + { + case NumKind.Heal: + n.Text = "+" + s; n.Color = HealGreen; n.Life = HealLife; + break; + case NumKind.Stamina: + n.Text = "+" + s + " stam"; n.Color = StaminaAmber; n.Life = HealLife; + break; + case NumKind.Mana: + n.Text = "+" + s + " mana"; n.Color = ManaBlue; n.Life = HealLife; + break; + case NumKind.Taken: + n.Text = crit ? s + "!" : s; n.Color = crit ? Gold : TakenRed; n.Life = crit ? CritLife : NumberLife; + break; + default: + n.Text = crit ? s + "!" : s; n.Color = crit ? Gold : DamageColor(amount); n.Life = crit ? CritLife : NumberLife; + break; + } + _liveNumbers++; + _statNumbers++; + } + + private static void SpawnBurst(uint cell, float x, float y, float z, bool crit, long now) + { + Burst? b = null; + foreach (Burst c in Bursts) + if (!c.Active) { b = c; break; } + if (b == null) + { + b = Bursts[0]; + foreach (Burst c in Bursts) if (c.Born < b.Born) b = c; + _liveBursts--; + } + b.Active = true; + b.Crit = crit; + b.Born = now; + b.Cell = cell; b.X = x; b.Y = y; b.Z = z; + _liveBursts++; + _statBursts++; + } + + /// <summary>A gain; with <paramref name="merge"/>, the same kind within GainMergeSec adds to the newest one.</summary> + private static void AddGain(GainKind kind, long amount, bool merge = true) + { + if (amount <= 0) return; + // Diagnostics (2026-09-30: popups read half the chat's "Kill:" XP): the first 60 gains + // with their source, beside the kill lines logged in OnChat. + if (_gainDiag < 60) + { + _gainDiag++; + RynthLog.Compat($"Nameplates: gain {kind} +{amount} ({(merge ? "property rise" : "chat line")})"); + } + long now = Stopwatch.GetTimestamp(); + for (int i = merge ? Gains.Count - 1 : -1; i >= 0; i--) + { + Gain g = Gains[i]; + if (g.Kind != kind) continue; + if (now - g.Born < (long)(GainMergeSec * Stopwatch.Frequency)) + { + g.Amount += amount; + g.Merged = now; + g.Text = GainText(kind, g.Amount); + return; + } + break; + } + if (Gains.Count >= MaxGains) Gains.RemoveAt(0); + Gains.Add(new Gain { Kind = kind, Amount = amount, Born = now, Merged = now, Text = GainText(kind, amount) }); + _statGains++; + } + + private static string GainText(GainKind kind, long amount) + { + string n = amount.ToString("N0", CultureInfo.InvariantCulture); + return kind switch + { + GainKind.Xp => "+" + n + " XP", + GainKind.Lum => "+" + n + " Lum", + _ => "+" + n + " Radiance", + }; + } + + private static float NextRandom() + { + _rng ^= _rng << 13; _rng ^= _rng >> 17; _rng ^= _rng << 5; + return (_rng & 0xFFFFFF) / (float)0x1000000; + } + + private static uint DamageColor(int amount) => + amount < 25 ? White : amount < 60 ? PaleYellow : amount < 120 ? Orange : Red; + + // ── Painting ───────────────────────────────────────────────────────── + + private static float EaseOut(float t) => 1f - (1f - t) * (1f - t); + + /// <summary>Where "over the player" is on screen: the head, or the upper middle in first person.</summary> + private static Vector2 PlayerAnchor(ref MonsterHud.Frame f, bool aboveplate, float k) + { + if (PlayerPlate.HeadOnScreen && !PlayerPlate.FirstPerson) + return new Vector2(PlayerPlate.HeadScreen.X, (aboveplate ? PlayerPlate.PlateTop : PlayerPlate.HeadScreen.Y) - 6f * k); + return new Vector2(MathF.Round(f.Display.X * 0.5f), MathF.Round(f.Display.Y * (aboveplate ? 0.28f : 0.42f))); + } + + private static void DrawNumbers(ref MonsterHud.Frame f, float k) + { + float baseSize = ImGuiFonts.Get(UiFont.NumBold24).FontSize * MonsterHudSettings.NumSize * MonsterHudSettings.Scale; + float timeScale = MonsterHudSettings.NumTime; + Vector2 playerAt = PlayerAnchor(ref f, false, k); + int live = 0; + foreach (Number n in Numbers) + { + if (!n.Active) continue; + float age = (f.Now - n.Born) / (float)Stopwatch.Frequency / timeScale; + if (age >= n.Life) { n.Active = false; continue; } + live++; + + Vector2 at; + if (n.OnPlayer) at = playerAt; + else if (!MonsterHud.Project(ref f, n.Cell, n.X, n.Y, n.Z, out at, keepOnScreen: true)) continue; + + float t = age / n.Life; + float rise = 70f * k * MonsterHudSettings.NumSize * EaseOut(t); + float pop = 1f + (n.Crit ? 0.7f : 0.35f) * MathF.Max(0f, 1f - age / (n.Crit ? 0.16f : 0.12f)); + float size = MathF.Round(baseSize * pop * (n.Crit ? 1.35f : 1f) * (n.Kind == NumKind.Taken ? 1.1f : 1f)); + ImFontPtr font = ImGuiFonts.Sharp(size, bold: true); // shrink a bigger bake, never stretch + float alpha = MathF.Min(1f, age / 0.06f); + float fadeStart = 0.55f * n.Life; + if (age > fadeStart) alpha *= MathF.Max(0f, 1f - (age - fadeStart) / (n.Life - fadeStart)); + + float w = MonsterHud.TextWidth(font, size, n.Text); + var pos = new Vector2(MathF.Round(at.X + n.Jitter * k - w * 0.5f), MathF.Round(at.Y - 10f * k - rise - size)); + MonsterHud.OutlinedText(f.Dl, font, size, pos, alpha, n.Text); + if (n.Crit) MonsterHud.OutlinedText(f.Dl, font, size, pos + new Vector2(1, 0), alpha * 0.6f, n.Text); + f.Dl.AddText(font, size, pos, MonsterHud.Mul(n.Color, alpha), n.Text); + } + _liveNumbers = live; + } + + private static void DrawGains(ref MonsterHud.Frame f, float k) + { + // 24 px bake at GainSize 1 would be big; 0.75 keeps the old look at the default. + float baseSize = MathF.Round(ImGuiFonts.Get(UiFont.NumBold24).FontSize * 0.75f * MonsterHudSettings.GainSize * MonsterHudSettings.Scale); + float life = GainLife * MonsterHudSettings.GainTime; + Vector2 at = PlayerAnchor(ref f, true, k); + float lineH = baseSize + 3f * k; + int slot = 0; + for (int i = Gains.Count - 1; i >= 0; i--) + { + Gain g = Gains[i]; + float age = (f.Now - g.Born) / (float)Stopwatch.Frequency; + if (age >= life) { Gains.RemoveAt(i); continue; } + float t = age / life; + float drift = 34f * k * MonsterHudSettings.GainSize * EaseOut(t); + float sinceMerge = (f.Now - g.Merged) / (float)Stopwatch.Frequency; + float pop = 1f + 0.25f * MathF.Max(0f, 1f - sinceMerge / 0.15f); + float size = MathF.Round(baseSize * pop); + ImFontPtr font = ImGuiFonts.Sharp(size, bold: true); + float alpha = MathF.Min(1f, age / 0.08f); + if (t > 0.6f) alpha *= MathF.Max(0f, 1f - (t - 0.6f) / 0.4f); + uint col = g.Kind == GainKind.Xp ? XpGold : g.Kind == GainKind.Lum ? LumViolet : RadianceTeal; + + float w = MonsterHud.TextWidth(font, size, g.Text); + // Newest at the bottom; each older line sits one line higher. + var pos = new Vector2(MathF.Round(at.X - w * 0.5f), MathF.Round(at.Y - size - drift - slot * lineH)); + MonsterHud.OutlinedText(f.Dl, font, size, pos, alpha, g.Text); + f.Dl.AddText(font, size, pos, MonsterHud.Mul(col, alpha), g.Text); + slot++; + } + } + + /// <summary>Expanding ground rings plus a short fading pillar of rings where the monster fell.</summary> + private static void DrawBursts(ref MonsterHud.Frame f, float k) + { + int live = 0; + foreach (Burst b in Bursts) + { + if (!b.Active) continue; + float age = (f.Now - b.Born) / (float)Stopwatch.Frequency; + if (age >= BurstLife) { b.Active = false; continue; } + live++; + float t = age / BurstLife; + float fade = 1f - t; + uint main = b.Crit ? BurstGold : BurstCyan; + float thick = MathF.Max(1f, 3f * k * fade + 1f); + + Ring(ref f, b, 0.5f + 5.5f * EaseOut(t), 0.15f, MonsterHud.Mul(main, fade), thick); + float t2 = Math.Clamp((age - 0.12f) / (BurstLife - 0.12f), 0f, 1f); + if (t2 > 0f) Ring(ref f, b, 0.3f + 3.2f * EaseOut(t2), 0.15f, MonsterHud.Mul(White, (1f - t2) * 0.8f), MathF.Max(1f, thick * 0.7f)); + for (int i = 0; i < 4; i++) + { + float h = 0.6f + i * 0.7f + 1.2f * t; + float r = (1.3f - i * 0.22f) * (0.6f + 0.6f * EaseOut(t)); + Ring(ref f, b, r, h, MonsterHud.Mul(main, fade * (0.75f - i * 0.12f)), MathF.Max(1f, thick * 0.6f)); + } + } + _liveBursts = live; + } + + private static void Ring(ref MonsterHud.Frame f, Burst b, float radius, float height, uint col, float thick) + { + const int Segs = 28; + bool havePrev = false; + Vector2 prev = default; + for (int i = 0; i <= Segs; i++) + { + float ang = i * (MathF.PI * 2f / Segs); + bool ok = MonsterHud.Project(ref f, b.Cell, b.X + radius * MathF.Cos(ang), b.Y + radius * MathF.Sin(ang), b.Z + height, out Vector2 p); + if (ok && havePrev) f.Dl.AddLine(prev, p, col, thick); + havePrev = ok; + prev = p; + } + } + + public static string Describe() => + $"Combat text {(MonsterHudSettings.Numbers ? "on" : "off")}, gains {(MonsterHudSettings.Gains ? "on" : "off")}: " + + $"{_liveNumbers} number(s), {_liveBursts} burst(s), {Gains.Count} gain(s) live; " + + $"{_statNumbers} numbers, {_statBursts} kill bursts, {_statGains} gains this session."; +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/HudFeed.cs b/src/RynthCore.Engine/ImGui/MonsterHud/HudFeed.cs new file mode 100644 index 0000000..def11c9 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/HudFeed.cs @@ -0,0 +1,145 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/HudFeed.cs +// The one-line entry points the engine's existing hooks call for the +// RynthVision overlays (nameplates, debuffs, self plate, combat text), and +// the gate that keeps them off unless RynthVision is installed. +// +// Callers (all existing chokepoints, no new hooks): +// PluginManager.QueueChatWindowText -> OnChat +// PluginManager.QueueSelectedTargetChange -> OnSelection +// PluginManager.QueueDeleteObject -> OnDeleted +// CombatActionHooks.CastSpell -> OnCast +// SmartBoxHooks (0x01B1 / 0x01B2 / 0x01AD) -> OnDamageEvent, OnKillMessage +// AppraisalHooks (0xC9 CreatureProfile) -> OnAppraisal +// MonsterHudData.RecordHealth -> OnHealth +// All on AC's main thread; each call is a few compares when the line or +// event isn't one of ours, and never throws into the hook. +// +// Gate: the overlays belong to RynthVision, so they run only when +// RynthCore.Plugin.RynthVision.dll is in engine.json's PluginPaths (the list +// EntryPoint gates the Vision panel on), re-read every few seconds. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Threading; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +internal static class HudFeed +{ + private const string VisionDll = "RynthCore.Plugin.RynthVision.dll"; + private static volatile bool _visionInstalled; + private static long _nextGateCheck; + + /// <summary>True when the RynthVision plugin is in the plugin list. Any thread; re-checked every 5 s.</summary> + public static bool VisionInstalled + { + get + { + long now = Stopwatch.GetTimestamp(); + if (now >= Volatile.Read(ref _nextGateCheck)) + { + Volatile.Write(ref _nextGateCheck, now + Stopwatch.Frequency * 5); + _visionInstalled = HasVision(); + } + return _visionInstalled; + } + } + + private static bool HasVision() + { + try + { + IReadOnlyList<string> paths = Plugins.EngineSettings.PluginPaths; + for (int i = 0; i < paths.Count; i++) + if (string.Equals(Path.GetFileName(paths[i]), VisionDll, StringComparison.OrdinalIgnoreCase)) + return true; + } + catch { } + return false; + } + + /// <summary>Cheap gate for the feeds: the cached flag only (Update refreshes it).</summary> + private static bool On => _visionInstalled && MonsterHudSettings.Loaded; + + public static void OnChat(string? line) + { + if (!On || string.IsNullOrEmpty(line)) return; + try + { + line = line.TrimEnd('\r', '\n'); // same instance when there is nothing to trim + if (MonsterHudSettings.Enabled && MonsterHudSettings.ShowDebuffs) PlateDebuffs.OnChat(line); + CombatText.OnChat(line); + } + catch (Exception ex) { Log("chat", ex); } + } + + public static void OnCast(uint targetId, int spellId) + { + if (!On || !MonsterHudSettings.ShowDebuffs) return; + try { PlateDebuffs.NoteCast(targetId, spellId); } + catch (Exception ex) { Log("cast", ex); } + } + + public static void OnSelection(uint id) + { + if (!On) return; + try { PlateDebuffs.NoteSelection(id); } + catch (Exception ex) { Log("selection", ex); } + } + + public static void OnDeleted(uint id) + { + if (!On) return; + try + { + PlateDebuffs.Remove(id); + CombatText.OnDeleted(id); + } + catch (Exception ex) { Log("delete", ex); } + } + + public static void OnDamageEvent(bool attacker, string? name, uint damage, bool crit) + { + if (!On) return; + try { CombatText.OnDamageEvent(attacker, name, damage, crit); } + catch (Exception ex) { Log("damage", ex); } + } + + public static void OnKillMessage(string? message) + { + if (!On) return; + try { CombatText.OnKillMessage(message); } + catch (Exception ex) { Log("kill", ex); } + } + + public static void OnAppraisal(uint id, uint enchantmentBitfield) + { + if (!On || !MonsterHudSettings.ShowDebuffs) return; + try { PlateDebuffs.OnAppraisal(id, enchantmentBitfield); } + catch (Exception ex) { Log("appraisal", ex); } + } + + /// <summary><paramref name="prev"/> is -1 when this is the first observation.</summary> + public static void OnHealth(uint id, float prev, float ratio, uint max) + { + if (!On) return; + try + { + if (ratio <= 0.001f && prev > 0.001f) PlateDebuffs.Remove(id); // died + CombatText.OnHealth(id, prev, ratio, max); + } + catch (Exception ex) { Log("health", ex); } + } + + private static int _errors; + + private static void Log(string what, Exception ex) + { + if (++_errors <= 10) + RynthLog.UI($"Nameplates: {what} feed failed - {ex.GetType().Name}: {ex.Message}"); + } +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs new file mode 100644 index 0000000..5a077ee --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs @@ -0,0 +1,1568 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/MonsterHud.cs +// RynthVision nameplates: MMO-style plates over monsters in the 3D world +// (name, level badge, health bar with absolute HP when a max is known, "weak +// to" pill, distance, a row of debuff icons); the selected target gets a gold +// frame, a glow and a pointer. Also the host of the other world overlays: +// the player's own plate (PlayerPlate) and the combat text (CombatText: +// damage / heal numbers, kill bursts, XP / Luminance / Radiance gains). +// +// Part of RynthVision: everything here is off unless the RynthVision plugin +// is in the plugin list (HudFeed.VisionInstalled), and each part has its own +// switch (MonsterHudSettings). +// +// Drawn into UnderUiLayer's draw list, which renders at AC's 3D->UI +// transition: after the world, under AC's own windows (chat, radar, +// inventory) and every ImGui panel. The only input it takes is a left-click +// on a monster plate (MonsterHudSettings.ClickToSelect): while the cursor is +// on a plate and no ImGui panel is under it, WantsMouse asks the game window +// to keep that click from AC (EngineFrameController ORs it into the capture +// flags), and the press selects the plate's monster through the main-thread +// overlay-select slot. Every other click still goes to the game. +// +// Two rates: +// Update (AC's render thread, before the ImGui frame): at most 4x a second +// it picks which monsters get a plate - attackable creatures from the +// engine's main-thread snapshots (ClientObjectHooks.TryGetSnapshot*, a +// dictionary lookup each, no AC calls), within range, nearest first, +// capped at MaxPlates, the target always kept. Players are skipped. The +// same scan picks the name-only labels: non-attackable creatures (NPCs, +// vendors; summoned pets skipped) within NpcMaxDistance, nearest first, +// capped at MaxNpcLabels apart from the plates (and players, if "Player +// names" is on). Each object is classified once (Classes). The same tick +// polls the player's XP / Luminance for the gain text. +// Draw (inside the ImGui frame): every frame each chosen monster's LIVE +// position is read (main thread, a handful of objects) and projected with +// the engine's camera capture (GameMatrixCapture), so plates stick to +// moving monsters without the 10 Hz snapshot's stepping. +// +// World -> screen: AC transforms geometry on the CPU; GameMatrixCapture +// rebuilds the view from SmartBox's camera frame and hooks SetTransform for +// the projection. Positions are landblock-local; the view is built in +// GameMatrixCapture.FrameLandblock's frame, so a monster in a neighbouring +// landblock is shifted 192 m per landblock step before projecting (D3D axes: +// x = east, y = up, z = north). Viewport pixels are mapped to ImGui's +// display size in case the backbuffer and the client differ. +// +// Unload-safe: no threads, timers, hooks or process-wide subscriptions; all +// state is engine-owned statics that die with the generation. Nothing here +// blocks: settings I/O and the spell-table read are queued, data locks are brief. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Numerics; +using System.Runtime.InteropServices; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.D3D9; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +internal static class MonsterHud +{ + // ── Tunables ───────────────────────────────────────────────────────── + private const int SnapshotPeriodMs = 250; // monster list refresh (4 Hz) + private const double AttackerMemorySec = 20; // "hit you recently" + private const double HurtMemorySec = 60; // "hurt recently" (engaged filter) + private const uint TypeCreature = 0x10; // ITEM_TYPE TYPE_CREATURE + private const uint BfPlayer = 0x8; // PublicWeenieDesc BF_PLAYER + private const uint BfVendor = 0x200; // PublicWeenieDesc BF_VENDOR + private const uint PetOwnerIid = 44; // PropertyInstanceId PetOwner (summoned pets) + internal const float LandblockSize = 192f; + private const int MaxIcons = 5; // debuff icons per plate; more shows "+N" + private const float BlinkSec = 5f; // icons blink in their last seconds + + // ── Palette (ARGB literals -> ImGui ABGR) ──────────────────────────── + private static readonly uint BarBack = C(0xE00C1118), BarEdge = C(0xFF000000), Tick = C(0x70000000), + Shine = C(0x38FFFFFF), Trail = C(0xFFF3E2A8), Gold = C(0xFFE6C766), GoldBright = C(0xFFFFD966), + GoldGlow = C(0x55E6C766), NameText = C(0xFFF2E8DC), AttackerText = C(0xFFFF8A7A), Outline = C(0xE6000000), + HpText = C(0xFFFFFFFF), DimText = C(0xFFB8C4D0), BadgeBack = C(0xD0101820), BadgeEdge = C(0xFF34587A), + Leader = C(0x60FFFFFF), HoverEdge = C(0xC0FFFFFF), UnknownFill = C(0xFF5E8A6A), IconBack = C(0xD80B1219), OthersTint = C(0xFFFF8A7A); + private static readonly Vector3 HpHigh = new(0x3F, 0xD0, 0x6A), HpMid = new(0xE8, 0xB3, 0x33), HpLow = new(0xE0, 0x4A, 0x4A); + + // Element colours, shared by the "weak to" pill and the vulnerability icons. + private static readonly uint ElemSlash = C(0xFFC9D1DB), ElemPierce = C(0xFFD9C19A), ElemBludgeon = C(0xFFB59A7E), + ElemFire = C(0xFFFF7A3D), ElemCold = C(0xFF7FD3FF), ElemLightning = C(0xFFC89BFF), ElemAcid = C(0xFF8FE36A), + ElemNether = C(0xFFB06BE0); + + // One glyph and tint per DebuffKind (index = kind). + private static readonly string[] KindGlyph = + { + PhosphorIcons.Fire, PhosphorIcons.Snowflake, PhosphorIcons.Lightning, PhosphorIcons.Flask, + PhosphorIcons.Sword, PhosphorIcons.Knife, PhosphorIcons.Hammer, + PhosphorIcons.ShieldSlash, PhosphorIcons.MagicWand, PhosphorIcons.ShieldWarning, + PhosphorIcons.ArrowFatLinesDown, PhosphorIcons.HeartBreak, PhosphorIcons.Footprints, + PhosphorIcons.TrendDown, PhosphorIcons.Skull, PhosphorIcons.ArrowFatDown, + }; + private static readonly uint[] KindTint = + { + ElemFire, ElemCold, ElemLightning, ElemAcid, ElemSlash, ElemPierce, ElemBludgeon, + C(0xFF9FB4C8), // Imperil: steel + C(0xFFB98CFF), // Magic Yield: violet + C(0xFFFFB347), // melee / missile defense: orange + C(0xFFF2D24B), // attributes: yellow + C(0xFFFF6B8A), // vitals / regen: pink-red + C(0xFFA8C66C), // movement: moss + C(0xFF8FB8DE), // skills: blue-grey + C(0xFF7CE08A), // damage over time: green + C(0xFFC8C8C8), // other + }; + private static readonly string[] StackDigits = { "", "", "2", "3", "4", "5", "6", "7", "8", "9" }; + + internal static uint C(uint argb) => RynthTheme.Argb(argb); + + // ── Per-monster state ──────────────────────────────────────────────── + private sealed class Plate + { + public uint Id; + public string Name = ""; + /// <summary>RadarKind.Monster: a full monster plate. Npc / Vendor / Player: a name-only label.</summary> + public byte Kind = RadarKind.Monster; + public bool IsLabel => Kind != RadarKind.Monster; + public int Level; // 0 = unknown + public string LevelText = ""; + public float HeadHeight = DefaultHeadHeight; + public WeakTag? Weak; + public uint Wcid; + + public bool Chosen; // in the latest snapshot + public bool Gone; // live position read failed (despawned / died) + public bool OnScreen; + public bool Appeared; // became visible this frame: layout snaps instead of easing + public float Alpha; // smoothed, 0..1 + public float Scale = 1f; // smoothed + public float Nudge; // smoothed crowd offset (px, upward) + public float NudgeTarget; + public float ShownRatio = 1f; // smoothed bar + public float TrailRatio = 1f; // "chip" behind the bar after a hit + public long TrailHoldUntil; + public bool HpKnown; + public float Ratio = 1f; + public uint HpCur, HpMax; + public float Distance; + public bool IsTarget, IsAttacker; + public Vector2 Anchor; // screen point above the head + public float LastWx, LastWy, LastWz; + public bool HasWorld; + public uint LastCell; // last live position, AC landblock-local (feet) + public float LastX, LastY, LastZ; + + // Debuff icons (this frame) + public readonly DebuffIcon[] Icons = new DebuffIcon[MaxIcons]; + public int IconCount; // may exceed MaxIcons (overflow) + public bool Others; // "debuffed by others" marker + + // Layout (this frame) + public float Width, Height, BarW, BarH, NameSize, SmallSize, BelowBar, IconSize; + public ImFontPtr NameFont, SmallFont; + public float NameW, BadgeW; + + // Cached strings (rebuilt only when the value changes) + public string HpString = ""; + public long HpKey = long.MinValue; + public string DistString = ""; + public int DistKey = int.MinValue; + public string OverflowString = ""; + public int OverflowKey = -1; + } + + private sealed record WeakTag(string Label, uint Color); + + private const float DefaultHeadHeight = 2.0f; + private static readonly Dictionary<uint, Plate> Plates = new(64); + private static readonly List<Plate> DrawOrder = new(64); + private static readonly List<Plate> Placed = new(64); + private static readonly List<(uint Id, float D2)> Candidates = new(128); + private static readonly List<(uint Id, float D2)> LabelCandidates = new(64); + private static readonly List<uint> Evict = new(16); + + // What each live object is, worked out once per id (item type, BF_PLAYER, BF_VENDOR and + // PetOwner never change), so the 4 Hz scan skips non-creatures with one lookup and the + // monster pick no longer reads the bitfield live. Attackable is NOT cached: it is read + // from the snapshot every scan, as before. Entries not seen for a while are pruned. + private const byte ClsUnknown = 0, ClsOther = 1, ClsCreature = 2, ClsVendor = 3, ClsPlayer = 4, ClsPet = 5; + private const byte ClsCreatureNoPwd = 6; // a creature whose PWD isn't in the snapshot yet: never cached + private struct ObjClass { public byte Cls; public int Seen; } + private static readonly Dictionary<uint, ObjClass> Classes = new(512); + private static readonly List<uint> ClassEvict = new(64); + private static int _classPass; + private static readonly Comparison<(uint Id, float D2)> ByD2 = static (a, b) => a.D2.CompareTo(b.D2); + private static readonly Comparison<Plate> NearFirst = static (a, b) => + a.IsTarget != b.IsTarget ? (a.IsTarget ? -1 : 1) : a.Distance.CompareTo(b.Distance); + + private static long _nextSnapshotTicks; + private static bool _wasInWorld; + private static volatile bool _hasContent; + private static uint _playerId; + private static int _playerLevel; + private static long _nextPlayerLevelTicks; + + // Weakness ("Weak to") from RynthAi's learned damage data (UiSources.Damage). + private static bool _damageSubscribed; + private static long _weakVersion = -1; + private static Dictionary<uint, WeakTag> _weakByWcid = new(); + private static Dictionary<string, WeakTag> _weakByName = new(StringComparer.OrdinalIgnoreCase); + + /// <summary>True while there is anything to draw (fading plates, the self plate, combat text). Any thread.</summary> + public static bool WantsFrame => _hasContent; + + // Click-to-select (AC's render thread only). + private static bool _wantsMouse; + private static uint _hoverId; // plate under the cursor this frame (0: none) + private static uint _pressId; // plate the held left press began on (0: none) + + /// <summary> + /// True when this frame's plates want the mouse: the cursor is on a clickable + /// plate, or a press that began on one is still held. Read after the frame is + /// built, on AC's render thread. + /// </summary> + public static bool WantsMouse => _wantsMouse || PlayerPlate.WantsMouse; + + /// <summary>Plates being tracked (diagnostics).</summary> + public static int PlateCount => Plates.Count; + + // ════════════════════════════════════════════════════════════════════ + // Update: which monsters get a plate (throttled) + // ════════════════════════════════════════════════════════════════════ + + /// <summary> + /// AC's render thread, every frame the ImGui layer is on, BEFORE the frame + /// is built (so <see cref="WantsFrame"/> can ask for one). Cheap when throttled. + /// </summary> + public static void Update(bool inWorld) + { + // Draw recomputes it; a frame that doesn't draw the plates never wants the mouse. + _wantsMouse = false; + PlayerPlate.ClearMouse(); + try + { + if (!MonsterHudSettings.Loaded) + { + MonsterHudSettings.EnsureLoadQueued(); + _hasContent = false; + return; + } + + if (!inWorld || !HudFeed.VisionInstalled) + { + if (_wasInWorld) + { + // Logout / character switch (or RynthVision removed): object ids don't carry over. + _wasInWorld = false; + ClearAll(); + } + SetDamageSubscription(false); + _hasContent = false; + return; + } + _wasInWorld = true; + + // Monsters are tracked for the plates, and also for the combat text (it finds + // "the Drudge you hit" among them) when the plates themselves are off. + bool monsters = MonsterHudSettings.Enabled; + bool trackMonsters = monsters || MonsterHudSettings.Numbers; + // Name-only labels over NPCs (and, if asked, players): their own switches and cap. + bool track = trackMonsters || MonsterHudSettings.NpcNames || MonsterHudSettings.PlayerNames; + if (!track) ClearPlates(); + SetDamageSubscription(monsters && MonsterHudSettings.ShowWeakness); + if (monsters && MonsterHudSettings.ShowDebuffs) PortalSpellTable.EnsureLoadQueued(); + + long now = Stopwatch.GetTimestamp(); + if (now >= _nextSnapshotTicks) + { + _nextSnapshotTicks = now + Stopwatch.Frequency * SnapshotPeriodMs / 1000; + RefreshPlayer(now); + CombatText.PollGains(_playerId); + if (track) Snapshot(now, trackMonsters); + } + + _hasContent = Plates.Count > 0 || MonsterHudSettings.SelfPlate || CombatText.HasContent; + } + catch (Exception ex) + { + _hasContent = false; + RynthLog.UI($"MonsterHud: update failed - {ex.GetType().Name}: {ex.Message}"); + } + } + + private static void ClearPlates() + { + Plates.Clear(); + DrawOrder.Clear(); + ResetClick(); + } + + private static void ResetClick() + { + _wantsMouse = false; + _hoverId = 0; + _pressId = 0; + } + + private static void ClearAll() + { + ClearPlates(); + MonsterHudData.Clear(); + PlateDebuffs.Clear(); + CombatText.Clear(); + PlayerPlate.Reset(); + Classes.Clear(); + _playerId = 0; + } + + /// <summary>The player's id, level (con colours) and spell-duration augmentations, every 5 s.</summary> + private static void RefreshPlayer(long now) + { + uint playerId = ClientHelperHooks.GetPlayerId(); + if (playerId == 0) return; + if (playerId == _playerId && now < _nextPlayerLevelTicks) return; + if (playerId != _playerId) CombatText.Clear(); // a new character: no gains from the old baseline + _playerId = playerId; + _nextPlayerLevelTicks = now + Stopwatch.Frequency * 5; + _playerLevel = ClientObjectHooks.TryGetObjectIntProperty(playerId, 25, out int lvl) ? lvl : 0; + // PropertyInt.AugmentationIncreasedSpellDuration: +20 % debuff duration each. + PlateDebuffs.SetDurationAugmentation(ClientObjectHooks.TryGetObjectIntProperty(playerId, 238, out int aug) ? aug : 0); + } + + private static void SetDamageSubscription(bool want) + { + if (want == _damageSubscribed) return; + _damageSubscribed = want; + if (want) + { + UiSources.Damage.Subscribe(); + UiSources.Damage.RequestRefresh(); + } + else + { + UiSources.Damage.Unsubscribe(); + } + } + + private static void Snapshot(long now, bool trackMonsters) + { + uint playerId = _playerId; + if (playerId == 0 || !GameMatrixCapture.HasCapturedFrame || TeleportStateHooks.IsPortaling || + !PlayerPhysicsHooks.TryGetPlayerPose(out uint pCell, out float px, out float py, out float pz, out _, out _, out _, out _) || + (pCell >> 16) == 0) + { + // Portal space, no camera yet, or the player isn't placed: nothing to label. + ClearPlates(); + return; + } + + RefreshWeakMaps(); + + uint target = ClientHelperHooks.GetSelectedItemId(); + float maxD = MonsterHudSettings.MaxDistance; + float maxD2 = maxD * maxD; + float targetD2 = MathF.Max(maxD2, 100f * 100f); // the target keeps its plate a bit further out + bool engagedOnly = MonsterHudSettings.Filter == PlateFilter.Engaged && MonsterHudSettings.Enabled; + bool npcNames = MonsterHudSettings.NpcNames, playerNames = MonsterHudSettings.PlayerNames; + float npcD = MonsterHudSettings.NpcMaxDistance; + float npcD2 = npcD * npcD; + float npcTargetD2 = MathF.Max(npcD2, 100f * 100f); // a selected NPC keeps its name further out too + bool targetIsLabel = false; + + int pass = ++_classPass; + Candidates.Clear(); + LabelCandidates.Clear(); + uint[] ids = ClientObjectHooks.LiveObjectIds; + for (int i = 0; i < ids.Length; i++) + { + uint id = ids[i]; + if (id == playerId) continue; + + // Classified once per id; a cached non-creature costs this one lookup. + ref ObjClass oc = ref CollectionsMarshal.GetValueRefOrAddDefault(Classes, id, out _); + oc.Seen = pass; + byte cls = oc.Cls; + if (cls == ClsUnknown) + { + cls = Classify(id); + if (cls != ClsCreatureNoPwd) oc.Cls = cls; + } + if (cls == ClsOther || cls == ClsUnknown) continue; + + // Monster plate (attackable creature) or name label (NPC / vendor, player)? + bool label; + if (cls == ClsPlayer) + { + // Players never get a monster plate (attackable in PK or not). + if (!playerNames) continue; + label = true; + } + else + { + if (!ClientObjectHooks.TryGetSnapshotAttackable(id, out bool attackable)) continue; + if (attackable) + { + if (!trackMonsters) continue; + label = false; + } + else + { + // Non-attackable: an NPC (vendors included). Pets and creatures not yet + // classified (no PWD) get nothing. + if (!npcNames || (cls != ClsCreature && cls != ClsVendor)) continue; + label = true; + } + } + + if (!ClientObjectHooks.TryGetSnapshotPosition(id, out uint cell, out float x, out float y, out float z)) continue; + if (!TryOffset(pCell, cell, out float ox, out float oy)) continue; + float dx = x + ox - px, dy = y + oy - py, dz = z - pz; + float d2 = dx * dx + dy * dy + dz * dz; + if (label) + { + if (d2 > (id == target ? npcTargetD2 : npcD2)) continue; + LabelCandidates.Add((id, d2)); + if (id == target) targetIsLabel = true; + } + else + { + if (d2 > (id == target ? targetD2 : maxD2)) continue; + Candidates.Add((id, d2)); + } + } + Candidates.Sort(ByD2); + LabelCandidates.Sort(ByD2); + if ((pass & 63) == 0) PruneClasses(pass); + + foreach (Plate p in Plates.Values) p.Chosen = false; + + int cap = MonsterHudSettings.MaxPlates; + int chosen = 0; + bool targetChosen = false; + for (int i = 0; i < Candidates.Count; i++) + { + uint id = Candidates[i].Id; + bool isTarget = id == target; + if (chosen >= cap && !isTarget) + { + if (targetChosen || target == 0) break; + continue; // keep scanning only to find the target + } + + // Players are creatures too (attackable in PK): no plates for them. Classified + // ids were sorted out in the scan; one whose PWD wasn't snapshotted yet is read live. + if ((!Classes.TryGetValue(id, out ObjClass oc) || oc.Cls == ClsUnknown) && + ClientObjectHooks.TryGetObjectBitfield(id, out uint bf) && (bf & BfPlayer) != 0) continue; + + ClientObjectHooks.TryGetSnapshotName(id, out string name); + if (engagedOnly && !isTarget && !IsEngaged(id, name, now)) continue; + + Plate plate = GetPlate(id, RadarKind.Monster); + if (name.Length > 0 && name != plate.Name) plate.Name = name; + RefreshIdentity(plate); + chosen++; + if (isTarget) targetChosen = true; + } + + // ── Name labels: NPCs (vendors in their own colour) and players, capped apart from the plates ── + int labelCap = MonsterHudSettings.MaxNpcLabels; + int labels = 0; + for (int i = 0; i < LabelCandidates.Count; i++) + { + uint id = LabelCandidates[i].Id; + bool isTarget = id == target; + if (labels >= labelCap && !isTarget) + { + if (!targetIsLabel) break; + continue; // keep scanning only to find the target + } + if (!ClientObjectHooks.TryGetSnapshotName(id, out string name) || name.Length == 0) continue; + + byte cls = Classes.TryGetValue(id, out ObjClass oc) ? oc.Cls : ClsCreature; + byte kind = cls == ClsPlayer ? RadarKind.Player : cls == ClsVendor ? RadarKind.Vendor : RadarKind.Npc; + Plate plate = GetPlate(id, kind); + // Head height once per name; again while selected (selecting appraises: CreatureType may arrive). + if (name != plate.Name || isTarget) + { + plate.Name = name; + plate.HeadHeight = EstimateHeadHeight(id, name); + } + labels++; + if (isTarget) targetIsLabel = false; // found: the cap applies again + } + + // Plates no longer chosen fade out in Draw and are evicted at zero alpha. + } + + /// <summary>The plate for <paramref name="id"/> (made on first sight), marked chosen this snapshot.</summary> + private static Plate GetPlate(uint id, byte kind) + { + if (!Plates.TryGetValue(id, out Plate? plate)) + { + plate = new Plate { Id = id, Alpha = 0f }; + Plates[id] = plate; + } + plate.Kind = kind; + plate.Chosen = true; + plate.Gone = false; + return plate; + } + + /// <summary> + /// What an object is, from the main-thread snapshots only (no AC call): not a creature, + /// a player, a summoned pet, a vendor or another creature. ClsUnknown / ClsCreatureNoPwd + /// when the snapshots don't have it yet (asked again next scan). + /// </summary> + private static byte Classify(uint id) + { + if (!ClientObjectHooks.TryGetSnapshotItemType(id, out uint type)) return ClsUnknown; + if ((type & TypeCreature) == 0) return ClsOther; + if (!ClientObjectHooks.TryGetSnapshotPwdInfo(id, out uint bf, out _, out _)) return ClsCreatureNoPwd; + if ((bf & BfPlayer) != 0) return ClsPlayer; + if (ClientObjectHooks.TryGetObjectInstanceIdProperty(id, PetOwnerIid, out uint owner) && owner != 0) return ClsPet; + return (bf & BfVendor) != 0 ? ClsVendor : ClsCreature; + } + + /// <summary>Drops class entries for ids the last scan didn't see (despawned / out of range). Every 64 scans (~16 s).</summary> + private static void PruneClasses(int pass) + { + ClassEvict.Clear(); + foreach (KeyValuePair<uint, ObjClass> kv in Classes) + if (kv.Value.Seen != pass) ClassEvict.Add(kv.Key); + foreach (uint id in ClassEvict) Classes.Remove(id); + } + + private static bool IsEngaged(uint id, string name, long now) + { + if (MonsterHudData.AttackedRecently(name, AttackerMemorySec)) return true; + return MonsterHudData.TryGetHealth(id, out HealthObservation h) && h.Ratio < 0.999f && + (now - h.Ticks) < (long)(HurtMemorySec * Stopwatch.Frequency); + } + + /// <summary>Level, creature type (appraisal) and weakness (RynthAi): all can arrive after the plate appears.</summary> + private static void RefreshIdentity(Plate p) + { + p.HeadHeight = EstimateHeadHeight(p.Id, p.Name); + if (AppraisalHooks.TryGetCachedIntProperty(p.Id, 25, out int lvl) && lvl > 0 && lvl != p.Level) + { + p.Level = lvl; + p.LevelText = lvl.ToString(CultureInfo.InvariantCulture); + } + + if (!MonsterHudSettings.ShowWeakness) { p.Weak = null; return; } + if (p.Wcid == 0) ClientObjectHooks.TryGetObjectWcid(p.Id, out p.Wcid); + if (p.Wcid != 0 && _weakByWcid.TryGetValue(p.Wcid, out WeakTag? w)) p.Weak = w; + else if (p.Name.Length > 0 && _weakByName.TryGetValue(p.Name, out w)) p.Weak = w; + else p.Weak = null; + } + + /// <summary> + /// Metres from the landblock-local frame of <paramref name="fromCell"/> to that of + /// <paramref name="toCell"/> (192 m per landblock step). False for far-apart + /// landblocks (another dungeon, a bogus cell). + /// </summary> + internal static bool TryOffset(uint fromCell, uint toCell, out float ox, out float oy) + { + int fx = (int)((fromCell >> 24) & 0xFF), fy = (int)((fromCell >> 16) & 0xFF); + int tx = (int)((toCell >> 24) & 0xFF), ty = (int)((toCell >> 16) & 0xFF); + int dx = tx - fx, dy = ty - fy; + ox = dx * LandblockSize; + oy = dy * LandblockSize; + return (toCell >> 16) != 0 && Math.Abs(dx) <= 2 && Math.Abs(dy) <= 2; + } + + // ── Head height ────────────────────────────────────────────────────── + + /// <summary> + /// Metres from the feet to just above the head. The client's own model + /// height isn't read (its CPartArray/CSetup layout isn't mapped here), so + /// this goes by CreatureType from the appraisal cache, then by name, then + /// a humanoid default; "Height lift" in the settings corrects the rest. + /// </summary> + internal static float EstimateHeadHeight(uint id, string name) + { + if (AppraisalHooks.TryGetCachedIntProperty(id, 2, out int ct) && ct > 0 && ct < CreatureTypeHeights.Length && + CreatureTypeHeights[ct] > 0) + return CreatureTypeHeights[ct]; + + foreach ((string key, float h) in NameHeights) + if (name.Contains(key, StringComparison.OrdinalIgnoreCase)) + return h; + return DefaultHeadHeight; + } + + // Indexed by AC CreatureType (PropertyInt 2); 0 = use the default. + private static readonly float[] CreatureTypeHeights = + { + 0, + 2.3f, // 1 Olthoi + 2.4f, // 2 Banderling + 1.7f, // 3 Drudge + 2.0f, // 4 Mosswart + 3.3f, // 5 Lugian + 2.1f, // 6 Tumerok + 1.0f, // 7 Mite + 3.2f, // 8 Tusker + 1.6f, // 9 Phyntos Wasp + 0.8f, // 10 Rat + 2.2f, // 11 Auroch + 2.0f, // 12 Cow + 3.4f, // 13 Golem + 2.1f, // 14 Undead + 1.4f, // 15 Gromnie + 1.4f, // 16 Reedshark + 1.2f, // 17 Armoredillo + 2.0f, // 18 Fae + 2.3f, // 19 Virindi + 1.8f, // 20 Wisp + 2.2f, // 21 Knathtead + 2.3f, // 22 Shadow + 2.0f, // 23 Mattekar + 2.1f, // 24 Mumiyah + 0.8f, // 25 Rabbit + 2.0f, // 26 Sclavus + 1.4f, // 27 Shallows Shark + 2.8f, // 28 Monouga + 2.1f, // 29 Zombie + 2.1f, // 30 Skeleton + 2.1f, // 31 Human + 2.2f, // 32 Shreth + 1.4f, // 33 Chittick + 2.2f, // 34 Moarsman + 1.0f, // 35 Olthoi Larvae + 1.8f, // 36 Slithis + 2.0f, // 37 Deru + 2.6f, // 38 Fire Elemental + 2.4f, // 39 Snowman + 0, // 40 Unknown + 0.8f, // 41 Bunny + 2.6f, // 42 Lightning Elemental + 2.6f, // 43 Rockslide + 2.7f, // 44 Grievver + 1.8f, // 45 Niffis + 2.8f, // 46 Ursuin + 2.6f, // 47 Crystal + 2.1f, // 48 Hollow Minion + 2.4f, // 49 Scarecrow + 2.8f, // 50 Idol + }; + + private static readonly (string Key, float Height)[] NameHeights = + { + ("Golem", 3.4f), ("Tusker", 3.2f), ("Lugian", 3.3f), ("Ursuin", 2.8f), ("Monouga", 2.8f), + ("Grievver", 2.7f), ("Banderling", 2.4f), ("Olthoi", 2.3f), ("Mite", 1.0f), ("Rat", 0.8f), + ("Rabbit", 0.8f), ("Bunny", 0.8f), ("Gromnie", 1.4f), ("Drudge", 1.7f), ("Wasp", 1.6f), + ("Armoredillo", 1.2f), ("Chittick", 1.4f), ("Reedshark", 1.4f), ("Chicken", 0.9f), + }; + + // ── Weakness ───────────────────────────────────────────────────────── + + private static void RefreshWeakMaps() + { + if (!MonsterHudSettings.ShowWeakness) return; + var snap = UiSources.Damage.Current; + if (snap == null || snap.Version == _weakVersion) return; + _weakVersion = snap.Version; + var byWcid = new Dictionary<uint, WeakTag>(); + var byName = new Dictionary<string, WeakTag>(StringComparer.OrdinalIgnoreCase); + foreach (DamageRow r in snap.Value.Rows) + { + if (r.IsDefault || string.IsNullOrEmpty(r.Weak)) continue; + WeakTag? tag = ParseWeak(r.Weak); + if (tag == null) continue; + if (r.Wcid != 0) byWcid.TryAdd(r.Wcid, tag); + if (r.Name.Length > 0) byName.TryAdd(r.Name, tag); + } + _weakByWcid = byWcid; + _weakByName = byName; + } + + /// <summary>"Bludgeon 1.0, Pierce 0.86" -> the first (most damage taken) element.</summary> + private static WeakTag? ParseWeak(string weak) + { + int comma = weak.IndexOf(','); + string first = (comma > 0 ? weak[..comma] : weak).Trim(); + int sp = first.IndexOf(' '); + string elem = sp > 0 ? first[..sp] : first; + return elem.ToLowerInvariant() switch + { + "slash" or "slashing" => new WeakTag("SL", ElemSlash), + "pierce" or "piercing" => new WeakTag("PI", ElemPierce), + "bludgeon" or "bludgeoning" => new WeakTag("BL", ElemBludgeon), + "fire" => new WeakTag("FI", ElemFire), + "cold" => new WeakTag("CO", ElemCold), + "lightning" or "electric" => new WeakTag("LI", ElemLightning), + "acid" => new WeakTag("AC", ElemAcid), + "nether" => new WeakTag("NE", ElemNether), + _ => null, + }; + } + + // ════════════════════════════════════════════════════════════════════ + // Draw: project and paint (every frame, inside the ImGui frame) + // ════════════════════════════════════════════════════════════════════ + + /// <summary>What every overlay needs to project a world point this frame.</summary> + internal struct Frame + { + public uint FrameCell, PlayerCell; + public float Px, Py, Pz; // player, AC landblock-local (feet) + public float MapX, MapY; // viewport px -> ImGui display px + public Vector2 Display; + public float Dt; + public long Now; + public float UiScale; + public ImDrawListPtr Dl; + } + + /// <summary>AC's render thread, inside the ImGui frame (between NewFrame and Render).</summary> + public static void Draw(float uiScale) + { + if (!_hasContent) { ResetClick(); PlayerPlate.DropDrag(); return; } + try + { + if (!TryBeginFrame(uiScale, out Frame f)) { ResetClick(); PlayerPlate.DropDrag(); return; } + DrawPlates(ref f, MonsterHudSettings.Enabled); + PlayerPlate.Draw(ref f); + CombatText.Draw(ref f); + // The player plate fixed on screen: ImGui's background list (the normal UI pass), not the layer above. + PlayerPlate.DrawScreen(ref f); + } + catch (Exception ex) + { + RynthLog.UI($"MonsterHud: draw failed - {ex.GetType().Name}: {ex.Message}"); + ClearPlates(); + CombatText.Clear(); + _hasContent = false; + } + } + + private static bool TryBeginFrame(float uiScale, out Frame f) + { + f = default; + if (!GameMatrixCapture.HasCapturedFrame) return false; + uint vpW = GameMatrixCapture.ViewportWidth, vpH = GameMatrixCapture.ViewportHeight; + if (vpW == 0 || vpH == 0) return false; + if (!PlayerPhysicsHooks.TryGetPlayerPose(out uint pCell, out float px, out float py, out float pz, out _, out _, out _, out _) || + (pCell >> 16) == 0 || TeleportStateHooks.IsPortaling) + return false; + + uint frameCell = GameMatrixCapture.FrameLandblock << 16; + if (frameCell == 0) frameCell = pCell; + + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + Vector2 display = io.DisplaySize; + if (display.X <= 1 || display.Y <= 1) return false; + f.FrameCell = frameCell; + f.PlayerCell = pCell; + f.Px = px; f.Py = py; f.Pz = pz; + f.MapX = display.X / vpW; + f.MapY = display.Y / vpH; + f.Display = display; + f.Dt = Math.Clamp(io.DeltaTime, 0.001f, 0.1f); + f.Now = Stopwatch.GetTimestamp(); + f.UiScale = uiScale; + // Our own list, drawn at AC's 3D->UI transition so AC's windows cover the + // plates (UnderUiLayer). The background list (over AC's UI) only if the + // layer isn't available. + f.Dl = UnderUiLayer.BeginBuild(display); + if (!UnderUiLayer.IsBuilding) f.Dl = ImGuiNET.ImGui.GetBackgroundDrawList(); + return true; + } + + /// <summary> + /// An AC landblock-local point (x east, y north, z up) to ImGui screen pixels, + /// rounded. False when it is behind the camera or far outside the screen. + /// </summary> + internal static bool Project(ref Frame f, uint cell, float x, float y, float z, out Vector2 screen, bool keepOnScreen = false) + { + screen = default; + if (!TryOffset(f.FrameCell, cell, out float fx, out float fy)) return false; + if (!GameMatrixCapture.WorldToScreen(x + fx, z, y + fy, out float sx, out float sy)) return false; + sx *= f.MapX; sy *= f.MapY; + if (keepOnScreen && MonsterHudSettings.KeepOnScreen) + { + // In front of the camera but past an edge (the camera closes in near walls): pin to the edge. + Vector2 c = ClampToScreen(ref f, sx, sy, 24f * f.UiScale, 30f * f.UiScale); + screen = new Vector2(MathF.Round(c.X), MathF.Round(c.Y)); + return true; + } + const float margin = 200f; + if (sx < -margin || sx > f.Display.X + margin || sy < -margin || sy > f.Display.Y + margin) return false; + screen = new Vector2(MathF.Round(sx), MathF.Round(sy)); + return true; + } + + /// <summary>A screen point pulled inside the display, <paramref name="side"/> px from the left/right/bottom + /// edges and <paramref name="top"/> px from the top (room for what is drawn above the point).</summary> + internal static Vector2 ClampToScreen(ref Frame f, float sx, float sy, float side, float top) => + new(Math.Clamp(sx, side, MathF.Max(side, f.Display.X - side)), + Math.Clamp(sy, top, MathF.Max(top, f.Display.Y - side))); + + /// <summary> + /// Live positions for every tracked monster and name label; the monster plates themselves + /// only when <paramref name="paint"/> (labels exist only while their own switch is on). + /// </summary> + private static void DrawPlates(ref Frame f, bool paint) + { + float monsterMaxD = MonsterHudSettings.MaxDistance; + float labelMaxD = MonsterHudSettings.NpcMaxDistance; + float opacity = MonsterHudSettings.Opacity; + float userScale = MonsterHudSettings.Scale; + float lift = MonsterHudSettings.HeightLift; + bool fade = MonsterHudSettings.FadeWithDistance; + bool debuffs = MonsterHudSettings.ShowDebuffs; + bool others = debuffs && MonsterHudSettings.ShowOthersDebuff; + float dt = f.Dt; + float kAlpha = 1f - MathF.Exp(-dt * 12f); + float kScale = 1f - MathF.Exp(-dt * 10f); + float kBar = 1f - MathF.Exp(-dt * 14f); + uint target = ClientHelperHooks.GetSelectedItemId(); + + DrawOrder.Clear(); + Evict.Clear(); + foreach (Plate p in Plates.Values) + { + // ── Live position (main thread; ~MaxPlates reads) ── + if (!p.Gone && ClientObjectHooks.TryGetObjectPosition(p.Id, out uint cell, out float x, out float y, out float z) && + TryOffset(f.FrameCell, cell, out float fx, out float fy) && TryOffset(f.PlayerCell, cell, out float ox, out float oy)) + { + float dx = x + ox - f.Px, dy = y + oy - f.Py, dz = z - f.Pz; + p.Distance = MathF.Sqrt(dx * dx + dy * dy + dz * dz); + p.LastWx = x + fx; // D3D x = east + p.LastWy = z + p.HeadHeight + lift; // D3D y = up + p.LastWz = y + fy; // D3D z = north + p.LastCell = cell; p.LastX = x; p.LastY = y; p.LastZ = z; + p.HasWorld = true; + } + else + { + p.Gone = true; // despawned / died / out of reach: fade where it was + } + + bool label = p.IsLabel; + if (!paint && !label) + { + // Tracked for the combat text only: no plate, no fade. + p.Alpha = 0f; + if (!p.Chosen || p.Gone) Evict.Add(p.Id); + continue; + } + + p.IsTarget = p.Id == target && target != 0; + p.IsAttacker = !label && MonsterHudData.AttackedRecently(p.Name, AttackerMemorySec); + + p.OnScreen = false; + if (p.HasWorld && GameMatrixCapture.WorldToScreen(p.LastWx, p.LastWy, p.LastWz, out float sx, out float sy)) + { + sx *= f.MapX; sy *= f.MapY; + const float margin = 60f; + if (MonsterHudSettings.KeepOnScreen) + { + // Pinned to the edge: room above the anchor for the name, bar and debuff row (a label: the name). + Vector2 c = ClampToScreen(ref f, sx, sy, (label ? 50f : 70f) * f.UiScale * userScale, + (label ? 22f : 56f) * f.UiScale * userScale); + p.Anchor = new Vector2(MathF.Round(c.X), MathF.Round(c.Y)); + p.OnScreen = true; + } + else if (sx > -margin && sx < f.Display.X + margin && sy > -margin && sy < f.Display.Y + margin) + { + // Whole pixels: text and 1 px lines stay crisp and a still monster never shimmers. + p.Anchor = new Vector2(MathF.Round(sx), MathF.Round(sy)); + p.OnScreen = true; + } + } + + // ── Alpha / scale targets ── + float maxD = label ? labelMaxD : monsterMaxD; + float t = maxD > 1f ? Math.Clamp(p.Distance / maxD, 0f, 1f) : 0f; + float distFade = fade ? 1f - 0.55f * SmoothStep(0.45f, 1f, t) : 1f; + bool show = p.OnScreen && (p.Chosen || p.IsTarget) && !p.Gone; + float alphaTarget = show ? opacity * (p.IsTarget ? 1f : distFade) : 0f; + bool wasVisible = p.Alpha > 0.01f; + p.Appeared = !wasVisible; + if (!p.OnScreen) + p.Alpha = 0f; // behind the camera / off screen: no stale position, pop back in with a fade + else + p.Alpha += (alphaTarget - p.Alpha) * kAlpha; + + float distScale = fade ? 1f - 0.28f * SmoothStep(0.15f, 1f, t) : 1f; + float scaleTarget = userScale * distScale * (p.IsTarget ? 1.12f : 1f); + // Appearing: start at the right size; visible: ease (target pop, distance). + p.Scale = wasVisible ? p.Scale + (scaleTarget - p.Scale) * kScale : scaleTarget; + + // ── Health (monster plates only) ── + if (!label) UpdateHealth(p, f.Now, kBar, dt); + + if (!show && p.Alpha < 0.01f) + { + if (!p.Chosen || p.Gone) Evict.Add(p.Id); + continue; + } + if (p.OnScreen && p.Alpha >= 0.01f) + { + // ── Debuffs (only for plates that draw) ── + p.Others = false; + p.IconCount = debuffs && !label ? PlateDebuffs.GetIcons(p.Id, p.Icons, out p.Others) : 0; + if (!others) p.Others = false; + DrawOrder.Add(p); + } + } + foreach (uint id in Evict) Plates.Remove(id); + if (DrawOrder.Count == 0) { ResetClick(); return; } + + // ── Layout: nearest (and the target) claim their spot; others step up ── + DrawOrder.Sort(NearFirst); + Placed.Clear(); + foreach (Plate p in DrawOrder) + { + Measure(p, f.UiScale); + ResolveOverlap(p, f.UiScale); + p.Nudge = p.Appeared ? p.NudgeTarget : p.Nudge + (p.NudgeTarget - p.Nudge) * (1f - MathF.Exp(-dt * 10f)); + Placed.Add(p); + } + + // ── Click-to-select: which plate is under the cursor, and a press on it ── + PlateClick(f.UiScale); + + // ── Paint: farthest first, nearest (and the target) on top ── + for (int i = DrawOrder.Count - 1; i >= 0; i--) + { + Plate p = DrawOrder[i]; + if (p.IsLabel) PaintLabel(f.Dl, p, f.UiScale); + else Paint(f.Dl, p, f.UiScale, f.Now); + } + } + + internal static float SmoothStep(float e0, float e1, float x) + { + float t = Math.Clamp((x - e0) / (e1 - e0), 0f, 1f); + return t * t * (3f - 2f * t); + } + + private static void UpdateHealth(Plate p, long now, float kBar, float dt) + { + if (MonsterHudData.TryGetHealth(p.Id, out HealthObservation h)) + { + p.HpKnown = true; + p.Ratio = h.Ratio; + uint max = h.Max; + if (ObjectQualityCache.TryGetCreatureVitals(p.Id, out CreatureVitals v) && v.MaxHealth > 0) + max = v.MaxHealth; // the appraisal CreatureProfile's absolute max wins + p.HpMax = max; + p.HpCur = max > 0 ? (uint)MathF.Round(max * h.Ratio) : 0; + } + else + { + // Never observed: an untouched monster is at full health in practice. + p.HpKnown = false; + p.Ratio = 1f; + p.HpMax = ObjectQualityCache.TryGetCreatureVitals(p.Id, out CreatureVitals v) ? v.MaxHealth : 0; + p.HpCur = p.HpMax; + } + + if (p.Alpha <= 0.01f) + { + // Not visible: snap, so a plate never appears mid-animation. + p.ShownRatio = p.TrailRatio = p.Ratio; + p.TrailHoldUntil = 0; + return; + } + StepBar(ref p.ShownRatio, ref p.TrailRatio, ref p.TrailHoldUntil, p.Ratio, now, kBar, dt); + } + + /// <summary> + /// Eases a bar toward <paramref name="ratio"/> and runs its "chip": after a + /// drop the chip holds 0.45 s, then drains at 80 % of the bar per second; + /// a rise pulls it up at once. Shared with the player plate. + /// </summary> + internal static void StepBar(ref float shown, ref float trail, ref long holdUntil, float ratio, long now, float kBar, float dt) + { + shown += (ratio - shown) * kBar; + if (ratio > trail) + { + trail = ratio; // healed: the chip follows up at once + } + else if (ratio < trail - 0.001f) + { + if (holdUntil == 0) holdUntil = now + Stopwatch.Frequency * 45 / 100; + if (now >= holdUntil) + trail = MathF.Max(ratio, trail - 0.8f * dt); + } + else + { + holdUntil = 0; + } + } + + // ── Layout ─────────────────────────────────────────────────────────── + + private static void Measure(Plate p, float uiScale) + { + float s = MathF.Max(0.3f, p.Scale); + float k = s * uiScale; + + if (p.IsLabel) + { + // Name only: the same bold bake as a monster's name, no bar, badge or icons. + p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s); + p.NameFont = ImGuiFonts.Sharp(p.NameSize, bold: true); + p.NameW = TextWidth(p.NameFont, p.NameSize, p.Name); + p.BadgeW = 0f; + p.BarW = p.BarH = 0f; + p.IconSize = 0f; + p.BelowBar = p.IsTarget ? 9f * k : 3f * k; // the target pointer hangs under the name + p.Width = p.NameW + 8f * k; + p.Height = p.NameSize + 2f * k + p.BelowBar; + return; + } + + p.BarW = MathF.Round(112f * k); + p.BarH = MathF.Round((MonsterHudSettings.ShowHpNumbers ? 12f : 7f) * k); + + // Sizes follow the 11 px bold / 9 px regular bakes; the font drawn is the smallest bake at + // least that big, so a scaled-up plate shrinks a bigger bake instead of stretching (blur). + p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s); + p.NameFont = ImGuiFonts.Sharp(p.NameSize, bold: true); + p.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.Ui9).FontSize * s); + p.SmallFont = ImGuiFonts.Sharp(p.SmallSize, bold: false); + + p.NameW = MonsterHudSettings.ShowNames && p.Name.Length > 0 ? TextWidth(p.NameFont, p.NameSize, p.Name) : 0f; + p.BadgeW = MonsterHudSettings.ShowLevel && p.LevelText.Length > 0 + ? TextWidth(p.SmallFont, p.SmallSize, p.LevelText) + 8f * k : 0f; + + // Debuff row under the bar: icon + countdown line. + p.IconSize = MathF.Round(13f * k); + float iconRow = p.IconCount > 0 || p.Others ? p.IconSize + MathF.Round(3f * k) + 3f : 0f; + p.BelowBar = iconRow + (p.IsTarget ? 9f * k : 3f * k); + + float nameLine = p.NameW + (p.BadgeW > 0 ? p.BadgeW + 4f * k : 0f); + float nameH = (p.NameW > 0 || p.BadgeW > 0) ? p.NameSize + 2f * k : 0f; + // The weak pill (left) and distance (right) hang off the bar's ends: keep them + // inside the crowd-avoidance box, symmetric so the plate stays centred. + float side = (p.Weak != null || MonsterHudSettings.ShowDistance) ? 2f * 30f * k : 0f; + p.Width = MathF.Max(p.BarW + side, nameLine) + 8f * k; + p.Height = nameH + p.BarH + p.BelowBar; + } + + /// <summary>Screen rect of a plate at a given upward nudge: (x0, y0, x1, y1).</summary> + private static Vector4 RectAt(Plate p, float nudge, float uiScale) + { + float k = p.Scale * uiScale; + float bottom = p.Anchor.Y - 4f * k - nudge + p.BelowBar; + return new Vector4(p.Anchor.X - p.Width * 0.5f, bottom - p.Height, p.Anchor.X + p.Width * 0.5f, bottom); + } + + private static void ResolveOverlap(Plate p, float uiScale) + { + float gap = 2f * uiScale; + float nudge = 0f; + float maxNudge = 160f * uiScale; + for (int pass = 0; pass < 8; pass++) + { + Vector4 r = RectAt(p, nudge, uiScale); + bool moved = false; + foreach (Plate q in Placed) + { + Vector4 o = RectAt(q, q.NudgeTarget, uiScale); + if (r.X >= o.Z || r.Z <= o.X || r.Y >= o.W || r.W <= o.Y) continue; + // Step above the plate it hits. + float need = nudge + (r.W - o.Y) + gap; + if (need > nudge) { nudge = need; moved = true; r = RectAt(p, nudge, uiScale); } + } + if (!moved || nudge >= maxNudge) break; + } + p.NudgeTarget = MathF.Min(nudge, maxNudge); + } + + // ── Click-to-select ────────────────────────────────────────────────── + + /// <summary> + /// Finds the plate under the cursor (the topmost: DrawOrder[0] paints last) and + /// turns a left press on it into a select. A plate only counts when click-to-select + /// is on, the Insert UI toggle is on and no ImGui panel or popup is under the + /// cursor (or holding the mouse). The press must already be the plate's when it + /// arrives: the game window ate it because the previous frame's capture flags + /// (Win32Backend.MouseCaptured) were up, so AC never saw it. The press selects at + /// once (as a click in the 3D world does) and the capture stays until the button + /// is released, so the release never reaches AC either. One select per press. + /// </summary> + private static void PlateClick(float uiScale) + { + uint prevHover = _hoverId; // the plate whose hover put the capture up for this frame's input + _hoverId = 0; + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + bool usable = MonsterHudSettings.ClickToSelect && Win32Backend.IsUiCaptureEnabled() && !io.WantCaptureMouse; + if (usable) + { + Vector2 m = io.MousePos; + foreach (Plate p in DrawOrder) + { + if (p.Gone || p.Alpha < 0.25f) continue; // fading in or out: not a target yet + Vector4 r = RectAt(p, p.Nudge, uiScale); + if (m.X < r.X || m.X > r.Z || m.Y < r.Y || m.Y > r.W) continue; + _hoverId = p.Id; + break; + } + } + + if (_pressId == 0) + { + // The press went where last frame's hover sent it: if the cursor slipped off + // that plate as it pressed, the click was still eaten for it, so it still selects it. + uint target = _hoverId != 0 ? _hoverId : prevHover; + // Another button held (e.g. the game's right-drag camera) keeps the press with the game. + if (usable && target != 0 && Win32Backend.MouseCaptured && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left) + && !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Right) && !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Middle)) + { + _pressId = target; + AcMainThreadQueue.EnqueueOverlaySelect(target); + } + } + else if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) + { + _pressId = 0; // released: the capture can drop + } + + _wantsMouse = _hoverId != 0 || _pressId != 0; + } + + /// <summary>Text width at <paramref name="size"/> px. No font push: this runs outside any window.</summary> + internal static float TextWidth(ImFontPtr font, float size, string text) => + font.CalcTextSizeA(size, float.MaxValue, 0f, text).X; + + // ── Paint ──────────────────────────────────────────────────────────── + + private static void Paint(ImDrawListPtr dl, Plate p, float uiScale, long now) + { + float a = Math.Clamp(p.Alpha, 0f, 1f); + float k = MathF.Max(0.3f, p.Scale) * uiScale; + float cx = p.Anchor.X; + float barBottom = MathF.Round(p.Anchor.Y - 4f * k - p.Nudge); + float barTop = barBottom - p.BarH; + float barL = MathF.Round(cx - p.BarW * 0.5f), barR = barL + p.BarW; + var b0 = new Vector2(barL, barTop); + var b1 = new Vector2(barR, barBottom); + float round = MathF.Max(1f, 2f * k); + bool icons = p.IconCount > 0 || p.Others; + float iconTop = barBottom + MathF.Round(3f * k); + float pointerTop = icons ? iconTop + p.IconSize + 3f + 2f * k : barBottom + 2f * k; + + // Crowd leader: a plate pushed up keeps a faint line down to its monster. + if (p.Nudge > 10f * uiScale) + dl.AddLine(new Vector2(cx, pointerTop - 1), new Vector2(cx, p.Anchor.Y - 2f * k), Mul(Leader, a), 1f); + + // ── Target: glow + gold frame + pointer ── + if (p.IsTarget) + { + float g = 3f * k; + dl.AddRectFilled(b0 - new Vector2(g, g), b1 + new Vector2(g, g), Mul(GoldGlow, a), round + g); + float tri = MathF.Round(5f * k); + var t0 = new Vector2(cx - tri, pointerTop); + var t1 = new Vector2(cx + tri, pointerTop); + var t2 = new Vector2(cx, pointerTop + tri); + dl.AddTriangleFilled(t0 - new Vector2(1, 1), t1 + new Vector2(1, -1), t2 + new Vector2(0, 1.5f), Mul(Outline, a)); + dl.AddTriangleFilled(t0, t1, t2, Mul(GoldBright, a)); + } + + // ── Bar ── + PaintBar(dl, b0, b1, round, a, p.ShownRatio, p.TrailRatio, p.HpKnown ? HealthColor(p.Ratio) : UnknownFill, p.BarW >= 60f); + + if (p.IsTarget) + dl.AddRect(b0 - new Vector2(1.5f, 1.5f), b1 + new Vector2(1.5f, 1.5f), Mul(Gold, a), round + 1.5f, ImDrawFlags.None, 1.5f); + else if (p.Id == _hoverId) + dl.AddRect(b0 - new Vector2(1.5f, 1.5f), b1 + new Vector2(1.5f, 1.5f), Mul(HoverEdge, a), round + 1.5f, ImDrawFlags.None, 1f); // click-to-select hover + + // HP numbers inside the bar. + if (MonsterHudSettings.ShowHpNumbers && p.HpKnown && p.BarH >= 9f) + { + string hp = HpString(p); + if (hp.Length > 0) + { + float w = TextWidth(p.SmallFont, p.SmallSize, hp); + var pos = new Vector2(MathF.Round(cx - w * 0.5f), MathF.Round(barTop + (p.BarH - p.SmallSize) * 0.5f)); + OutlinedText(dl, p.SmallFont, p.SmallSize, pos, a, hp); + dl.AddText(p.SmallFont, p.SmallSize, pos, Mul(HpText, a), hp); + } + } + + // Left of the bar: the "weak to" element pill. + if (p.Weak != null) + { + float pw = TextWidth(p.SmallFont, p.SmallSize, p.Weak.Label) + 6f * k; + float ph = MathF.Max(p.BarH + 2f, p.SmallSize + 2f); + var q0 = new Vector2(MathF.Round(barL - 4f * k - pw), MathF.Round(barTop + (p.BarH - ph) * 0.5f)); + var q1 = q0 + new Vector2(pw, ph); + dl.AddRectFilled(q0, q1, Mul(BadgeBack, a), 3f * k); + dl.AddRect(q0, q1, Mul(p.Weak.Color, a * 0.9f), 3f * k, ImDrawFlags.None, 1f); + var tp = new Vector2(MathF.Round(q0.X + 3f * k), MathF.Round(q0.Y + (ph - p.SmallSize) * 0.5f)); + dl.AddText(p.SmallFont, p.SmallSize, tp, Mul(p.Weak.Color, a), p.Weak.Label); + } + + // Distance, right of the bar. + if (MonsterHudSettings.ShowDistance) + { + string d = DistString(p); + var pos = new Vector2(MathF.Round(barR + 4f * k), MathF.Round(barTop + (p.BarH - p.SmallSize) * 0.5f)); + OutlinedText(dl, p.SmallFont, p.SmallSize, pos, a, d); + dl.AddText(p.SmallFont, p.SmallSize, pos, Mul(DimText, a), d); + } + + // Under the bar: the debuff icons. + if (icons) + PaintIcons(dl, p, cx, iconTop, k, a, now); + + // ── Name line: [level badge] Name ── + if (p.NameW > 0 || p.BadgeW > 0) + { + float lineW = p.NameW + (p.BadgeW > 0 ? p.BadgeW + (p.NameW > 0 ? 4f * k : 0f) : 0f); + float x = MathF.Round(cx - lineW * 0.5f); + float nameTop = MathF.Round(barTop - 2f * k - p.NameSize); + + if (p.BadgeW > 0) + { + float bh = p.SmallSize + 2f * k; + var c0 = new Vector2(x, MathF.Round(nameTop + (p.NameSize - bh) * 0.5f + 1f)); + var c1 = c0 + new Vector2(p.BadgeW, bh); + uint con = ConColor(p.Level); + dl.AddRectFilled(c0, c1, Mul(BadgeBack, a), 3f * k); + dl.AddRect(c0, c1, Mul(p.IsTarget ? Gold : BadgeEdge, a), 3f * k, ImDrawFlags.None, 1f); + var lp = new Vector2(MathF.Round(c0.X + 4f * k), MathF.Round(c0.Y + (bh - p.SmallSize) * 0.5f)); + dl.AddText(p.SmallFont, p.SmallSize, lp, Mul(con, a), p.LevelText); + x += p.BadgeW + 4f * k; + } + + if (p.NameW > 0) + { + uint col = p.IsTarget ? GoldBright : p.IsAttacker ? AttackerText : NameText; + var pos = new Vector2(x, nameTop); + OutlinedText(dl, p.NameFont, p.NameSize, pos, a, p.Name); + dl.AddText(p.NameFont, p.NameSize, pos, Mul(col, a), p.Name); + } + } + } + + /// <summary> + /// A name-only label (NPC, vendor, player): the name in the radar's colour for that + /// kind (NPC yellow, vendor gold, player blue; the radar's colour picks apply), the + /// crowd leader line, the gold pointer when selected and an underline on hover. + /// </summary> + private static void PaintLabel(ImDrawListPtr dl, Plate p, float uiScale) + { + if (p.NameW <= 0f) return; + float a = Math.Clamp(p.Alpha, 0f, 1f); + float k = MathF.Max(0.3f, p.Scale) * uiScale; + float cx = p.Anchor.X; + float baseY = MathF.Round(p.Anchor.Y - 4f * k - p.Nudge); // the name's bottom + float nameTop = MathF.Round(baseY - p.NameSize); + float x = MathF.Round(cx - p.NameW * 0.5f); + float pointerTop = baseY + 2f * k; + + if (p.Nudge > 10f * uiScale) + dl.AddLine(new Vector2(cx, pointerTop - 1), new Vector2(cx, p.Anchor.Y - 2f * k), Mul(Leader, a), 1f); + + if (p.IsTarget) + { + float tri = MathF.Round(5f * k); + var t0 = new Vector2(cx - tri, pointerTop); + var t1 = new Vector2(cx + tri, pointerTop); + var t2 = new Vector2(cx, pointerTop + tri); + dl.AddTriangleFilled(t0 - new Vector2(1, 1), t1 + new Vector2(1, -1), t2 + new Vector2(0, 1.5f), Mul(Outline, a)); + dl.AddTriangleFilled(t0, t1, t2, Mul(GoldBright, a)); + } + else if (p.Id == _hoverId) + { + dl.AddLine(new Vector2(x, baseY + 1f), new Vector2(x + p.NameW, baseY + 1f), Mul(HoverEdge, a), 1f); // click-to-select hover + } + + uint col = C(UI.Panels.RadarSettingsStore.KindColor(p.Kind)); + var pos = new Vector2(x, nameTop); + OutlinedText(dl, p.NameFont, p.NameSize, pos, a, p.Name); + dl.AddText(p.NameFont, p.NameSize, pos, Mul(col, a), p.Name); + } + + /// <summary> + /// A bar: black edge, dark track, the chip (what the last drop took), the + /// gradient fill with a shine line, and optional quarter ticks. Shared with + /// the player plate. + /// </summary> + internal static void PaintBar(ImDrawListPtr dl, Vector2 b0, Vector2 b1, float round, float a, + float shownRatio, float trailRatio, uint baseCol, bool ticks) + { + dl.AddRectFilled(b0 - Vector2.One, b1 + Vector2.One, Mul(BarEdge, a * 0.9f), round + 1); + dl.AddRectFilled(b0, b1, Mul(BarBack, a), round); + + float innerW = b1.X - b0.X - 2f; + var i0 = new Vector2(b0.X + 1, b0.Y + 1); + float innerBottom = b1.Y - 1; + if (innerBottom <= i0.Y) innerBottom = i0.Y + 1; + float shown = Math.Clamp(shownRatio, 0f, 1f); + float trail = Math.Clamp(trailRatio, 0f, 1f); + + if (trail > shown + 0.002f) + dl.AddRectFilled(new Vector2(i0.X + innerW * shown, i0.Y), new Vector2(i0.X + innerW * trail, innerBottom), Mul(Trail, a * 0.85f)); + + if (shown > 0.001f) + { + uint top = Mul(Shade(baseCol, 1.18f), a), bottom = Mul(Shade(baseCol, 0.72f), a); + var f1 = new Vector2(i0.X + MathF.Max(1f, innerW * shown), innerBottom); + dl.AddRectFilledMultiColor(i0, f1, top, top, bottom, bottom); + dl.AddLine(i0 + new Vector2(0, 0.5f), new Vector2(f1.X, i0.Y + 0.5f), Mul(Shine, a), 1f); + } + + if (ticks && innerBottom - i0.Y >= 3f) + for (int q = 1; q <= 3; q++) + { + float tx = MathF.Round(i0.X + innerW * q * 0.25f); + dl.AddLine(new Vector2(tx, i0.Y + 1), new Vector2(tx, innerBottom - 1), Mul(Tick, a), 1f); + } + } + + /// <summary> + /// The debuff row, centred under the bar: one icon per kind with a shrinking + /// countdown line, blinking in its last seconds; "+N" when more than fit; + /// then the "debuffed by others" marker. + /// </summary> + private static void PaintIcons(ImDrawListPtr dl, Plate p, float cx, float top, float k, float a, long now) + { + float sz = p.IconSize; + float gap = MathF.Max(2f, MathF.Round(2f * k)); + int count = p.IconCount; + int shown = count > MaxIcons ? MaxIcons - 1 : count; + int overflow = count - shown; + string more = ""; + float moreW = 0f; + if (overflow > 0) + { + if (overflow != p.OverflowKey) + { + p.OverflowKey = overflow; + p.OverflowString = "+" + overflow.ToString(CultureInfo.InvariantCulture); + } + more = p.OverflowString; + moreW = TextWidth(p.SmallFont, p.SmallSize, more) + 4f * k; + } + int slots = shown + (p.Others ? 1 : 0); + float rowW = slots * sz + Math.Max(0, slots - 1) * gap + (overflow > 0 ? gap + moreW : 0f); + float x = MathF.Round(cx - rowW * 0.5f); + float glyphPx = MathF.Round(sz * 0.8f); + ImFontPtr iconFont = ImGuiFonts.Sharp(glyphPx, bold: false); // the icons are merged into every bake + float lineH = MathF.Max(1f, MathF.Round(1.5f * k)); + + for (int i = 0; i < shown; i++) + { + DebuffIcon ic = p.Icons[i]; + int kind = (int)ic.Kind; + uint tint = kind < KindTint.Length ? KindTint[kind] : KindTint[^1]; + float remaining = (ic.Expiry - now) / (float)Stopwatch.Frequency; + float frac = ic.Duration > 0 ? Math.Clamp(remaining / ic.Duration, 0f, 1f) : 0f; + float blink = remaining < BlinkSec ? 0.45f + 0.55f * MathF.Abs(MathF.Cos(remaining * MathF.PI * 2f)) : 1f; + + var i0 = new Vector2(x, top); + var i1 = i0 + new Vector2(sz, sz); + dl.AddRectFilled(i0, i1, Mul(IconBack, a), 2f * k); + dl.AddRect(i0, i1, Mul(tint, a * 0.55f * blink), 2f * k, ImDrawFlags.None, 1f); + PhosphorIcons.DrawCentered(dl, iconFont, glyphPx, KindGlyph[kind < KindGlyph.Length ? kind : KindGlyph.Length - 1], + i0, new Vector2(sz, sz), Mul(tint, a * blink)); + if (ic.Stack > 1 && ic.Stack < StackDigits.Length) + { + string digit = StackDigits[ic.Stack]; + float ds = MathF.Round(p.SmallSize * 0.85f); + var dp = new Vector2(i1.X - TextWidth(p.SmallFont, ds, digit) + 1f, i0.Y - 2f); + OutlinedText(dl, p.SmallFont, ds, dp, a, digit); + dl.AddText(p.SmallFont, ds, dp, Mul(HpText, a), digit); + } + // Countdown: a line under the icon that shrinks to nothing at expiry. + float ly = i1.Y + 1f; + dl.AddRectFilled(new Vector2(i0.X, ly), new Vector2(i1.X, ly + lineH), Mul(Outline, a * 0.8f)); + if (frac > 0f) + dl.AddRectFilled(new Vector2(i0.X, ly), new Vector2(i0.X + MathF.Max(1f, sz * frac), ly + lineH), Mul(tint, a * blink)); + x += sz + gap; + } + + if (overflow > 0) + { + var mp = new Vector2(x, MathF.Round(top + (sz - p.SmallSize) * 0.5f)); + OutlinedText(dl, p.SmallFont, p.SmallSize, mp, a, more); + dl.AddText(p.SmallFont, p.SmallSize, mp, Mul(DimText, a), more); + x += moreW + gap; + } + + if (p.Others) + { + var i0 = new Vector2(x, top); + dl.AddRectFilled(i0, i0 + new Vector2(sz, sz), Mul(IconBack, a * 0.8f), 2f * k); + PhosphorIcons.DrawCentered(dl, iconFont, glyphPx, PhosphorIcons.UsersThree, i0, new Vector2(sz, sz), Mul(OthersTint, a * 0.8f)); + } + } + + /// <summary>A soft 1 px outline under text (the text itself is drawn by the caller).</summary> + internal static void OutlinedText(ImDrawListPtr dl, ImFontPtr font, float size, Vector2 pos, float a, string text) + { + uint o = Mul(Outline, a); + dl.AddText(font, size, pos + new Vector2(-1, 0), o, text); + dl.AddText(font, size, pos + new Vector2(1, 0), o, text); + dl.AddText(font, size, pos + new Vector2(0, -1), o, text); + dl.AddText(font, size, pos + new Vector2(0, 1), o, text); + dl.AddText(font, size, pos + new Vector2(1, 1), o, text); + } + + private static string HpString(Plate p) + { + long key = p.HpMax > 0 ? ((long)p.HpMax << 32) | p.HpCur : -1 - (long)MathF.Round(p.Ratio * 100f); + if (key == p.HpKey) return p.HpString; + p.HpKey = key; + p.HpString = p.HpMax > 0 + ? p.HpCur.ToString(CultureInfo.InvariantCulture) + " / " + p.HpMax.ToString(CultureInfo.InvariantCulture) + : ((int)MathF.Round(p.Ratio * 100f)).ToString(CultureInfo.InvariantCulture) + "%"; + return p.HpString; + } + + private static string DistString(Plate p) + { + int d = (int)MathF.Round(p.Distance); + if (d == p.DistKey) return p.DistString; + p.DistKey = d; + p.DistString = d.ToString(CultureInfo.InvariantCulture) + "yd"; + return p.DistString; + } + + // ── Lookups for the other overlays (render thread) ────────────────── + + /// <summary> + /// A monster's head point (AC landblock-local, z = feet + head height + lift) and its feet height: + /// live position when the client still has it, else its plate's last one. + /// </summary> + internal static bool TryGetHead(uint id, out uint cell, out float x, out float y, out float z, out float feetZ) + { + Plates.TryGetValue(id, out Plate? p); + float head = p?.HeadHeight ?? EstimateHeadHeight(id, ClientObjectHooks.TryGetSnapshotName(id, out string n) ? n : ""); + if (ClientObjectHooks.TryGetObjectPosition(id, out cell, out x, out y, out feetZ) && (cell >> 16) != 0) + { + z = feetZ + head + MonsterHudSettings.HeightLift; + return true; + } + if (p != null && p.LastCell != 0) + { + cell = p.LastCell; x = p.LastX; y = p.LastY; feetZ = p.LastZ; + z = feetZ + head + MonsterHudSettings.HeightLift; + return true; + } + z = 0; + return false; + } + + /// <summary> + /// The plate whose monster has <paramref name="name"/>: the selected one first, + /// then the one the player hit most recently, then the nearest. 0 if none. + /// </summary> + internal static uint FindPlateByName(string name) + { + uint target = ClientHelperHooks.GetSelectedItemId(); + uint best = 0; + long bestHit = long.MinValue; + float bestD = float.MaxValue; + foreach (Plate p in Plates.Values) + { + if (p.Gone || p.IsLabel || !p.Name.Equals(name, StringComparison.Ordinal)) continue; + if (p.Id == target) return p.Id; + long hit = CombatText.LastHitTicks(p.Id); + if (hit > bestHit || (hit == bestHit && p.Distance < bestD)) + { + best = p.Id; bestHit = hit; bestD = p.Distance; + } + } + return best; + } + + /// <summary> + /// The plate whose monster's name appears in a death message (the longest + /// such name; ties: the one hit most recently, then the target). 0 if none. + /// </summary> + internal static uint FindPlateNamedIn(string message) + { + uint target = ClientHelperHooks.GetSelectedItemId(); + uint best = 0; + int bestLen = 0; + long bestHit = long.MinValue; + foreach (Plate p in Plates.Values) + { + if (p.IsLabel || p.Name.Length == 0 || p.Name.Length < bestLen) continue; + if (!message.Contains(p.Name, StringComparison.Ordinal)) continue; + long hit = CombatText.LastHitTicks(p.Id); + if (p.Id == target) hit = Math.Max(hit, long.MinValue + 1); + if (p.Name.Length > bestLen || hit > bestHit) + { + best = p.Id; bestLen = p.Name.Length; bestHit = hit; + } + } + return best; + } + + // ── Colours ────────────────────────────────────────────────────────── + + /// <summary>Green above 60 %, amber through the middle, red below 30 %; blended.</summary> + private static uint HealthColor(float ratio) + { + Vector3 c = ratio >= 0.6f ? Vector3.Lerp(HpMid, HpHigh, Math.Clamp((ratio - 0.6f) / 0.25f, 0f, 1f)) + : ratio >= 0.3f ? Vector3.Lerp(HpLow, HpMid, (ratio - 0.3f) / 0.3f) + : HpLow; + return 0xFF000000u | ((uint)c.Z << 16) | ((uint)c.Y << 8) | (uint)c.X; // ABGR + } + + /// <summary>Level badge text by the monster's level against the player's ("con" colours).</summary> + private static uint ConColor(int level) + { + if (_playerLevel <= 0 || level <= 0) return C(0xFFE6E6E6); + float r = (float)level / _playerLevel; + return r < 0.6f ? C(0xFF9AA3AD) // trivial: grey + : r < 0.9f ? C(0xFF7BE08F) // easy: green + : r < 1.1f ? C(0xFFF2F2F2) // even: white + : r < 1.3f ? C(0xFFFFB347) // tough: orange + : C(0xFFFF6B6B); // dangerous: red + } + + /// <summary>Scales an ABGR colour's alpha by <paramref name="a"/>.</summary> + internal static uint Mul(uint abgr, float a) + { + uint alpha = (uint)Math.Clamp((int)MathF.Round((abgr >> 24) * a), 0, 255); + return (abgr & 0x00FFFFFF) | (alpha << 24); + } + + /// <summary>Scales an ABGR colour's RGB by <paramref name="k"/> (alpha kept).</summary> + internal static uint Shade(uint abgr, float k) + { + uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k)); + uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k)); + uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k)); + return (abgr & 0xFF000000) | (b << 16) | (g << 8) | r; + } + + // ── Diagnostics ────────────────────────────────────────────────────── + + /// <summary>Chat lines for "/rv plates status": what the overlays see right now. AC's thread.</summary> + public static string[] DescribeLines() + { + int onScreen = 0, known = 0, labels = 0, labelsOnScreen = 0; + foreach (Plate p in Plates.Values) + { + if (p.IsLabel) + { + labels++; + if (p.OnScreen && p.Alpha > 0.01f) labelsOnScreen++; + continue; + } + if (p.OnScreen && p.Alpha > 0.01f) onScreen++; + if (p.HpKnown) known++; + } + return new[] + { + $"Nameplates: {Plates.Count - labels} tracked, {onScreen} on screen, {known} with health seen; " + + $"name labels {labels} ({labelsOnScreen} on screen), {Classes.Count} objects classified; " + + $"camera {(GameMatrixCapture.HasCapturedFrame ? "captured" : "not captured")} " + + $"(frame lb 0x{GameMatrixCapture.FrameLandblock:X4}, viewport {GameMatrixCapture.ViewportWidth}x{GameMatrixCapture.ViewportHeight}); " + + $"weakness data {(_weakByWcid.Count + _weakByName.Count > 0 ? "loaded" : "none")}.", + PlateDebuffs.Describe(), + PlayerPlate.Describe() + " " + CombatText.Describe(), + }; + } +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudData.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudData.cs new file mode 100644 index 0000000..bb77d4c --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudData.cs @@ -0,0 +1,102 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/MonsterHudData.cs +// What the nameplates know about a monster beyond the client's object +// tables: its last health ratio (and absolute HP when a max is known) and +// whether it hit the player recently. +// +// Fed by two existing chokepoints (one line each, no new hooks); each health +// change is passed on to HudFeed (combat text kills / heals): +// PluginManager.QueueUpdateHealth - every health observation the engine +// makes (0x01C0 UpdateHealth, QueryHealthResponse, 0xC9 appraisal +// CreatureProfile, player vitals); runs whether or not plugins load. +// SmartBoxHooks.ParseGameEventDamage - DefenderNotification (0x01B2, +// "X hits you"), which names the attacker (no id on the wire). +// Both run on AC's main thread today; the lock keeps them safe if a caller +// ever moves. Bounded: a full table is cleared wholesale (advisory data). +// Engine-owned statics only (collectible with the engine generation). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +/// <summary>Last health observation for one object.</summary> +internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks); + +internal static class MonsterHudData +{ + private static readonly object Sync = new(); + private static readonly Dictionary<uint, HealthObservation> Health = new(256); + private static readonly Dictionary<string, long> Attackers = new(StringComparer.OrdinalIgnoreCase); + private const int MaxHealthEntries = 2048; + private const int MaxAttackerEntries = 64; + + /// <summary> + /// A health update for <paramref name="id"/>. A max of 0 (ratio-only update) + /// keeps the last known max. Any thread; never blocks for long. + /// </summary> + public static void RecordHealth(uint id, float ratio, uint current, uint max) + { + if (id == 0 || float.IsNaN(ratio)) return; + ratio = Math.Clamp(ratio, 0f, 1f); + long now = Stopwatch.GetTimestamp(); + float before = -1f; + lock (Sync) + { + bool had = Health.TryGetValue(id, out HealthObservation prev); + if (had) before = prev.Ratio; + if (max == 0 && had && prev.Max > 0) + { + max = prev.Max; + current = (uint)Math.Round(max * ratio); + } + if (Health.Count >= MaxHealthEntries && !Health.ContainsKey(id)) + Health.Clear(); + Health[id] = new HealthObservation(ratio, current, max, now); + } + // Kills and heals for the combat text; a death also drops the monster's debuffs. + HudFeed.OnHealth(id, before, ratio, max); + } + + public static bool TryGetHealth(uint id, out HealthObservation h) + { + lock (Sync) + return Health.TryGetValue(id, out h); + } + + /// <summary>A monster named <paramref name="name"/> hit the player. Any thread.</summary> + public static void RecordAttacker(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return; + long now = Stopwatch.GetTimestamp(); + lock (Sync) + { + if (Attackers.Count >= MaxAttackerEntries && !Attackers.ContainsKey(name)) + Attackers.Clear(); + Attackers[name] = now; + } + } + + /// <summary>True when a monster with this name hit the player within <paramref name="seconds"/>.</summary> + public static bool AttackedRecently(string name, double seconds) + { + if (name.Length == 0) return false; + lock (Sync) + { + if (!Attackers.TryGetValue(name, out long t)) return false; + return (Stopwatch.GetTimestamp() - t) < (long)(seconds * Stopwatch.Frequency); + } + } + + /// <summary>Logout / character switch: ids don't survive the session.</summary> + public static void Clear() + { + lock (Sync) + { + Health.Clear(); + Attackers.Clear(); + } + } +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs new file mode 100644 index 0000000..0777b5e --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs @@ -0,0 +1,326 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/MonsterHudSettings.cs +// Persisted settings of the monster nameplates (MonsterHud.cs), in the same +// hand-editable key=value style as RadarSettingsStore: +// %LocalAppData%\RynthCore\nameplate_settings.txt. +// +// Threads: fields are read on AC's render thread every frame and written by +// the Settings face (render thread) and /rc plates (AC's chat hook, the same +// thread). File I/O never runs on the render thread: Load and Save both go +// through UiBackgroundWriter, and the HUD draws nothing until Loaded is set, +// so a player who turned it off never sees a frame of plates at startup. +// ============================================================================ + +using System; +using System.Globalization; +using System.IO; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +/// <summary>Which monsters get a plate.</summary> +internal enum PlateFilter +{ + /// <summary>Every attackable monster in range (nearest first, up to MaxPlates).</summary> + All = 0, + /// <summary>The selected target, monsters that hit you recently, and monsters that are hurt.</summary> + Engaged = 1, +} + +internal static class MonsterHudSettings +{ + private static readonly object Sync = new(); + private static volatile bool _loaded; + private static bool _loadQueued; + + // ── Values (conservative defaults) ────────────────────────────────── + public static bool Enabled = true; + public static float MaxDistance = 35f; // yards (AC units) + public static int MaxPlates = 20; + public static PlateFilter Filter = PlateFilter.All; + public static bool ShowNames = true; + public static bool ShowHpNumbers = true; + public static bool ShowDistance = false; + public static bool ShowLevel = true; + public static bool ShowWeakness = true; // "Weak to" pill (RynthAi's learned damage data) + public static bool FadeWithDistance = true; + public static float Scale = 1.0f; + public static float Opacity = 0.9f; + public static float HeightLift = 0.0f; // extra metres above the estimated head height + /// <summary>A left-click on a monster plate selects that monster in game.</summary> + public static bool ClickToSelect = true; + + // Name-only labels over NPCs (vendors in gold) and, optionally, other players. + // Counted apart from MaxPlates so they never push a monster plate out. + public static bool NpcNames = true; + public static float NpcMaxDistance = 30f; // yards; short so a town isn't a wall of text + public static int MaxNpcLabels = 15; + public static bool PlayerNames = false; + + // Debuff icons on the monster plates (PlateDebuffs). + public static bool ShowDebuffs = true; + public static bool ShowOthersDebuff = true; // "debuffed by others" marker (appraisal highlights) + + // The player's own plate (PlayerPlate): health / stamina / mana over your head. + public static bool SelfPlate = true; + public static bool SelfNumbers = false; // "cur/max" beside each bar + public static bool SelfName = false; + public static bool SelfHideFirstPerson = true; + /// <summary> + /// Fixed on screen (default since 2026-10-05: a plate tied to the head jitters while you move) or + /// following the character (SelfPosition, SelfHideFirstPerson). Fixed draws with the normal UI. + /// </summary> + public static SelfPlacement SelfPlacement = SelfPlacement.Fixed; + /// <summary>Fixed mode: the plate can't be dragged (and never takes a click). Unlock to move it.</summary> + public static bool SelfLocked = true; + /// <summary>Fixed mode: where the bars' centre sits, as a fraction of the screen (kept on screen when drawn).</summary> + public static float SelfFixedX = DefaultSelfFixedX, SelfFixedY = DefaultSelfFixedY; + /// <summary>Just under a third-person character, clear of the chat in the bottom-left corner.</summary> + public const float DefaultSelfFixedX = 0.5f, DefaultSelfFixedY = 0.68f; + + // Combat text (CombatText): floating numbers and the kill burst. + public static bool Numbers = true; + public static bool NumDealt = true; + public static bool NumTaken = true; + public static bool NumHeals = true; + public static bool NumKills = true; + /// <summary>Plates, numbers and your plate stay inside the screen when the camera closes in (walls).</summary> + public static bool KeepOnScreen = true; + /// <summary>"+N stam" / "+N mana" over you when a spell, potion or kit restores them.</summary> + public static bool NumRestores = true; + /// <summary>Combat number size (1 = the 24 px bake) and how long they stay (1 = default).</summary> + public static float NumSize = 1.0f, NumTime = 1.0f; + /// <summary>XP / Lum / Radiance gain text: size and how long it stays (1 = default).</summary> + public static float GainSize = 1.0f, GainTime = 1.0f; + /// <summary>Where the player plate sits relative to the character.</summary> + public static SelfPlatePosition SelfPosition = SelfPlatePosition.Above; + public const float MinNumSize = 0.5f, MaxNumSize = 2.5f, MinNumTime = 0.5f, MaxNumTime = 3.0f; + + // Gain text over the player: XP, Luminance, Radiance. + public static bool Gains = true; + public static bool GainXp = true; + public static bool GainLum = true; + public static bool GainRadiance = true; + + // ── Ranges (shared by the Settings face, the command and Load) ────── + public const float MinDistance = 5f, MaxDistanceLimit = 120f; + public const int MinPlates = 1, MaxPlatesLimit = 60; + public const float MinNpcDistance = 5f, MaxNpcDistanceLimit = 80f; + public const int MinNpcLabels = 1, MaxNpcLabelsLimit = 40; + public const float MinScale = 0.6f, MaxScale = 2.0f; + public const float MinOpacity = 0.2f, MaxOpacity = 1.0f; + public const float MinLift = -1.5f, MaxLift = 3.0f; + + /// <summary>True once the file has been read (or found missing). Any thread.</summary> + public static bool Loaded => _loaded; + + private static string FilePath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "nameplate_settings.txt"); + + /// <summary>Queues the one-time read off the calling thread. Any thread; cheap after the first call.</summary> + public static void EnsureLoadQueued() + { + if (_loaded) return; + lock (Sync) + { + if (_loadQueued) return; + _loadQueued = true; + } + UiBackgroundWriter.Enqueue("nameplate settings (load)", LoadNow); + } + + private static void LoadNow() + { + lock (Sync) + { + try + { + string path = FilePath; + if (!File.Exists(path)) return; + foreach (string raw in File.ReadAllLines(path)) + { + string line = raw.Trim(); + if (line.Length == 0 || line.StartsWith('#')) continue; + int eq = line.IndexOf('='); + if (eq <= 0) continue; + string key = line[..eq].Trim(); + string val = line[(eq + 1)..].Trim(); + switch (key) + { + case "enabled": Enabled = val == "1"; break; + case "maxDistance": if (TryF(val, out float d)) MaxDistance = Math.Clamp(d, MinDistance, MaxDistanceLimit); break; + case "maxPlates": + if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) + MaxPlates = Math.Clamp(n, MinPlates, MaxPlatesLimit); + break; + case "filter": Filter = val.Equals("engaged", StringComparison.OrdinalIgnoreCase) ? PlateFilter.Engaged : PlateFilter.All; break; + case "showNames": ShowNames = val == "1"; break; + case "showHp": ShowHpNumbers = val == "1"; break; + case "showDistance": ShowDistance = val == "1"; break; + case "showLevel": ShowLevel = val == "1"; break; + case "showWeakness": ShowWeakness = val == "1"; break; + case "fade": FadeWithDistance = val == "1"; break; + case "scale": if (TryF(val, out float s)) Scale = Math.Clamp(s, MinScale, MaxScale); break; + case "opacity": if (TryF(val, out float o)) Opacity = Math.Clamp(o, MinOpacity, MaxOpacity); break; + case "clickSelect": ClickToSelect = val == "1"; break; + case "heightLift": if (TryF(val, out float h)) HeightLift = Math.Clamp(h, MinLift, MaxLift); break; + case "npcNames": NpcNames = val == "1"; break; + case "npcDistance": if (TryF(val, out float nd)) NpcMaxDistance = Math.Clamp(nd, MinNpcDistance, MaxNpcDistanceLimit); break; + case "npcMax": + if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int nm)) + MaxNpcLabels = Math.Clamp(nm, MinNpcLabels, MaxNpcLabelsLimit); + break; + case "playerNames": PlayerNames = val == "1"; break; + case "showDebuffs": ShowDebuffs = val == "1"; break; + case "showOthersDebuff": ShowOthersDebuff = val == "1"; break; + case "selfPlate": SelfPlate = val == "1"; break; + case "selfNumbers": SelfNumbers = val == "1"; break; + case "selfName": SelfName = val == "1"; break; + case "selfHideFirstPerson": SelfHideFirstPerson = val == "1"; break; + case "selfPlacement": SelfPlacement = val.Equals("follow", StringComparison.OrdinalIgnoreCase) ? SelfPlacement.Follow : SelfPlacement.Fixed; break; + case "selfLocked": SelfLocked = val == "1"; break; + case "selfFixedX": if (TryF(val, out float fx)) SelfFixedX = Math.Clamp(fx, 0f, 1f); break; + case "selfFixedY": if (TryF(val, out float fy)) SelfFixedY = Math.Clamp(fy, 0f, 1f); break; + case "numbers": Numbers = val == "1"; break; + case "numDealt": NumDealt = val == "1"; break; + case "numTaken": NumTaken = val == "1"; break; + case "numHeals": NumHeals = val == "1"; break; + case "numKills": NumKills = val == "1"; break; + case "keepOnScreen": KeepOnScreen = val == "1"; break; + case "numRestores": NumRestores = val == "1"; break; + case "numSize": if (TryF(val, out float ns)) NumSize = Math.Clamp(ns, MinNumSize, MaxNumSize); break; + case "numTime": if (TryF(val, out float nt)) NumTime = Math.Clamp(nt, MinNumTime, MaxNumTime); break; + case "selfPosition": if (Enum.TryParse(val, true, out SelfPlatePosition sp)) SelfPosition = sp; break; + case "gainSize": if (TryF(val, out float gs)) GainSize = Math.Clamp(gs, MinNumSize, MaxNumSize); break; + case "gainTime": if (TryF(val, out float gt)) GainTime = Math.Clamp(gt, MinNumTime, MaxNumTime); break; + case "gains": Gains = val == "1"; break; + case "gainXp": GainXp = val == "1"; break; + case "gainLum": GainLum = val == "1"; break; + case "gainRadiance": GainRadiance = val == "1"; break; + } + } + } + catch { /* best-effort: defaults stay */ } + finally { _loaded = true; } + } + } + + private static bool TryF(string s, out float v) => float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out v); + + /// <summary>Writes the settings in the background. Any thread.</summary> + public static void Save() => UiBackgroundWriter.Enqueue("nameplate settings", SaveNow); + + private static void SaveNow() + { + lock (Sync) + { + try + { + string path = FilePath; + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + using var sw = new StreamWriter(path, append: false); + sw.WriteLine("# RynthCore monster nameplates - auto-generated, hand-edits OK. /rc plates in game."); + sw.WriteLine($"enabled={B(Enabled)}"); + sw.WriteLine(FormattableString.Invariant($"maxDistance={MaxDistance:0.#}")); + sw.WriteLine(FormattableString.Invariant($"maxPlates={MaxPlates}")); + sw.WriteLine($"filter={(Filter == PlateFilter.Engaged ? "engaged" : "all")}"); + sw.WriteLine($"showNames={B(ShowNames)}"); + sw.WriteLine($"showHp={B(ShowHpNumbers)}"); + sw.WriteLine($"showDistance={B(ShowDistance)}"); + sw.WriteLine($"showLevel={B(ShowLevel)}"); + sw.WriteLine($"showWeakness={B(ShowWeakness)}"); + sw.WriteLine($"fade={B(FadeWithDistance)}"); + sw.WriteLine(FormattableString.Invariant($"scale={Scale:0.##}")); + sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}")); + sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}")); + sw.WriteLine($"clickSelect={B(ClickToSelect)}"); + sw.WriteLine($"npcNames={B(NpcNames)}"); + sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}")); + sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}")); + sw.WriteLine($"playerNames={B(PlayerNames)}"); + sw.WriteLine($"showDebuffs={B(ShowDebuffs)}"); + sw.WriteLine($"showOthersDebuff={B(ShowOthersDebuff)}"); + sw.WriteLine($"selfPlate={B(SelfPlate)}"); + sw.WriteLine($"selfNumbers={B(SelfNumbers)}"); + sw.WriteLine($"selfName={B(SelfName)}"); + sw.WriteLine($"selfHideFirstPerson={B(SelfHideFirstPerson)}"); + sw.WriteLine($"selfPlacement={(SelfPlacement == SelfPlacement.Follow ? "follow" : "fixed")}"); + sw.WriteLine($"selfLocked={B(SelfLocked)}"); + sw.WriteLine(FormattableString.Invariant($"selfFixedX={SelfFixedX:0.####}")); + sw.WriteLine(FormattableString.Invariant($"selfFixedY={SelfFixedY:0.####}")); + sw.WriteLine($"numbers={B(Numbers)}"); + sw.WriteLine($"numDealt={B(NumDealt)}"); + sw.WriteLine($"numTaken={B(NumTaken)}"); + sw.WriteLine($"numHeals={B(NumHeals)}"); + sw.WriteLine($"numKills={B(NumKills)}"); + sw.WriteLine($"keepOnScreen={B(KeepOnScreen)}"); + sw.WriteLine($"numRestores={B(NumRestores)}"); + sw.WriteLine(FormattableString.Invariant($"numSize={NumSize:0.##}")); + sw.WriteLine(FormattableString.Invariant($"numTime={NumTime:0.##}")); + sw.WriteLine(FormattableString.Invariant($"gainSize={GainSize:0.##}")); + sw.WriteLine($"selfPosition={SelfPosition}"); + sw.WriteLine(FormattableString.Invariant($"gainTime={GainTime:0.##}")); + sw.WriteLine($"gains={B(Gains)}"); + sw.WriteLine($"gainXp={B(GainXp)}"); + sw.WriteLine($"gainLum={B(GainLum)}"); + sw.WriteLine($"gainRadiance={B(GainRadiance)}"); + } + catch { /* non-fatal */ } + } + } + + private static string B(bool v) => v ? "1" : "0"; + + /// <summary>Back to the defaults (and saved). Render / chat thread.</summary> + public static void ResetToDefaults() + { + Enabled = true; MaxDistance = 35f; MaxPlates = 20; Filter = PlateFilter.All; + ShowNames = true; ShowHpNumbers = true; ShowDistance = false; ShowLevel = true; ShowWeakness = true; + FadeWithDistance = true; Scale = 1.0f; Opacity = 0.9f; HeightLift = 0f; ClickToSelect = true; + ShowDebuffs = true; ShowOthersDebuff = true; + NpcNames = true; NpcMaxDistance = 30f; MaxNpcLabels = 15; PlayerNames = false; + SelfPlate = true; SelfNumbers = false; SelfName = false; SelfHideFirstPerson = true; + SelfPlacement = SelfPlacement.Fixed; SelfLocked = true; SelfFixedX = DefaultSelfFixedX; SelfFixedY = DefaultSelfFixedY; + Numbers = true; NumDealt = true; NumTaken = true; NumHeals = true; NumKills = true; + NumSize = 1.0f; NumTime = 1.0f; NumRestores = true; KeepOnScreen = true; + GainSize = 1.0f; GainTime = 1.0f; SelfPosition = SelfPlatePosition.Above; + Gains = true; GainXp = true; GainLum = true; GainRadiance = true; + Save(); + } + + /// <summary>The fixed plate back to its default spot (and saved). Render / chat thread.</summary> + public static void ResetSelfPosition() + { + SelfFixedX = DefaultSelfFixedX; + SelfFixedY = DefaultSelfFixedY; + Save(); + } + + /// <summary>Every master switch at once ("/rv plates all on|off").</summary> + public static void SetAll(bool on) + { + Enabled = on; ShowDebuffs = on; SelfPlate = on; Numbers = on; Gains = on; NpcNames = on; + if (!on) PlayerNames = false; // "all on" leaves player names as chosen (off by default) + } + + /// <summary>One line for chat: the current state.</summary> + public static string Describe() => string.Create(CultureInfo.InvariantCulture, + $"RynthVision nameplates: monsters {(Enabled ? "ON" : "OFF")} ({(Filter == PlateFilter.Engaged ? "engaged only" : "all monsters")}, " + + $"{MaxDistance:0}yd, max {MaxPlates}, scale {Scale:0.##}, opacity {Opacity:0.##}, lift {HeightLift:0.#}m; " + + $"names {OnOff(ShowNames)}, hp {OnOff(ShowHpNumbers)}, level {OnOff(ShowLevel)}, weak {OnOff(ShowWeakness)}, " + + $"distance {OnOff(ShowDistance)}, fade {OnOff(FadeWithDistance)}, click to select {OnOff(ClickToSelect)}), debuffs {OnOff(ShowDebuffs)} (others {OnOff(ShowOthersDebuff)}); " + + $"NPC names {OnOff(NpcNames)} ({NpcMaxDistance:0}yd, max {MaxNpcLabels}), player names {OnOff(PlayerNames)}; " + + $"self {OnOff(SelfPlate)} ({(SelfPlacement == SelfPlacement.Fixed ? "fixed on screen, " + (SelfLocked ? "locked" : "unlocked") : "follows you, " + SelfPosition.ToString().ToLowerInvariant())}, " + + $"numbers {OnOff(SelfNumbers)}, name {OnOff(SelfName)}, hide in first person {OnOff(SelfHideFirstPerson)}); " + + $"combat text {OnOff(Numbers)} (dealt {OnOff(NumDealt)}, taken {OnOff(NumTaken)}, heals {OnOff(NumHeals)}, kills {OnOff(NumKills)}); " + + $"gains {OnOff(Gains)} (xp {OnOff(GainXp)}, lum {OnOff(GainLum)}, radiance {OnOff(GainRadiance)})."); + + private static string OnOff(bool v) => v ? "on" : "off"; +} + +/// <summary>Player plate placement: over the head, under the feet, or beside the character.</summary> +internal enum SelfPlatePosition { Above, Below, Left, Right } + +/// <summary>Player plate: fixed at a saved screen spot (draggable when unlocked), or following the character.</summary> +internal enum SelfPlacement { Fixed, Follow } diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs new file mode 100644 index 0000000..01e3023 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs @@ -0,0 +1,308 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/MonsterHudSettingsUi.cs +// The RynthVision overlay settings, drawn as two tabs of the Vision panel +// (Panels/VisionFace.cs): "Nameplates" (monster plates, NPC / player names, +// debuff icons, your plate, look) and "Combat text" (numbers, kill burst, gains). Square toggle +// dots and amber section headers; sliders save when the drag ends. Values +// live engine-side in MonsterHudSettings. AC's render thread, inside the +// face's content child. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +internal static class MonsterHudSettingsUi +{ + private static readonly uint Amber = C(0xFFE8B333), TextDim = C(0xFFF2F7FC), Mute = C(0xFFB8C8D8), + ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455), BtnBord = C(0xFF34587A), BtnFill = C(0xFF16283A); + private static uint C(uint argb) => RynthTheme.Argb(argb); + + private static bool Loading(float w) + { + if (MonsterHudSettings.Loaded) return false; + MonsterHudSettings.EnsureLoadQueued(); + Note("Loading...", w); + return true; + } + + /// <summary>The "Nameplates" tab body at the cursor, <paramref name="w"/> wide.</summary> + public static void DrawNameplates(float w) + { + if (Loading(w)) return; + bool changed = false; + + Section("Monster plates", w); + changed |= Toggle("Show monster nameplates", ref MonsterHudSettings.Enabled, + "Health bars and names over monsters in the world. Chat: /rv plates on|off."); + changed |= Toggle("Click a plate to select", ref MonsterHudSettings.ClickToSelect, + "Left-click a monster's plate (name or health bar) to select that monster, as clicking it in the world does. " + + "Off: plates never take a click. Chat: /rv plates click.", sub: true); + Note("Plates sit under every panel; a click on a plate selects its monster, every other click goes to the game.", w); + bool all = MonsterHudSettings.Filter == PlateFilter.All; + if (Toggle("All monsters in range", ref all, "Every attackable monster within the distance, nearest first.", radio: true)) + { + MonsterHudSettings.Filter = PlateFilter.All; + changed = true; + } + bool engaged = MonsterHudSettings.Filter == PlateFilter.Engaged; + if (Toggle("Only target + attackers", ref engaged, + "Your selected target, monsters that hit you in the last 20 s, and monsters that are hurt.", radio: true)) + { + MonsterHudSettings.Filter = PlateFilter.Engaged; + changed = true; + } + changed |= SliderF("Max distance (yd)", ref MonsterHudSettings.MaxDistance, + MonsterHudSettings.MinDistance, MonsterHudSettings.MaxDistanceLimit, "%.0f", w); + changed |= SliderI("Max plates", ref MonsterHudSettings.MaxPlates, + MonsterHudSettings.MinPlates, MonsterHudSettings.MaxPlatesLimit, w); + + Section("On the plate", w); + changed |= Toggle("Name", ref MonsterHudSettings.ShowNames, null); + changed |= Toggle("HP numbers", ref MonsterHudSettings.ShowHpNumbers, + "\"142 / 190\" when the monster's max HP is known (appraised), else a percentage. Hidden until its health has been seen."); + changed |= Toggle("Level badge", ref MonsterHudSettings.ShowLevel, + "Coloured against your level: grey, green, white, orange, red. Needs an appraisal."); + changed |= Toggle("Weak-to element", ref MonsterHudSettings.ShowWeakness, + "What the monster takes most damage from, from RynthAi's Damage data (needs RynthAi)."); + changed |= Toggle("Distance", ref MonsterHudSettings.ShowDistance, null); + + Section("Names over NPCs and players", w); + changed |= Toggle("NPC names", ref MonsterHudSettings.NpcNames, + "The name over vendors, quest givers, town criers and other NPCs: yellow, vendors gold (the radar's colours). " + + "Name only, no health bar; click one to select it. Chat: /rv plates npcs."); + changed |= SliderF("NPC name distance (yd)", ref MonsterHudSettings.NpcMaxDistance, + MonsterHudSettings.MinNpcDistance, MonsterHudSettings.MaxNpcDistanceLimit, "%.0f", w); + changed |= SliderI("Max names", ref MonsterHudSettings.MaxNpcLabels, + MonsterHudSettings.MinNpcLabels, MonsterHudSettings.MaxNpcLabelsLimit, w); + changed |= Toggle("Player names", ref MonsterHudSettings.PlayerNames, + "The name over other players too (blue), within the same distance and count. Chat: /rv plates players."); + Note("Names count apart from the monster plates, so they never push one out; the nearest win.", w); + + Section("Debuffs", w); + changed |= Toggle("Debuff icons", ref MonsterHudSettings.ShowDebuffs, + "Your own debuffs on each monster (vulnerabilities, Imperil, Magic Yield, attribute and skill debuffs...), " + + "one icon per kind with a line that runs out with the spell. From your \"You cast ... on ...\" lines. Chat: /rv plates debuffs."); + changed |= Toggle("Debuffed by others", ref MonsterHudSettings.ShowOthersDebuff, + "A small marker when an appraisal shows a lowered attribute or vital that none of your own debuffs explains. " + + "It only updates when the monster is appraised (your combat target is appraised often).", sub: true); + + Section("Your plate", w); + changed |= Toggle("Show your plate", ref MonsterHudSettings.SelfPlate, + "Your own health, stamina and mana bars: fixed on screen, or following your character. Chat: /rv plates self."); + changed |= Toggle("Numbers on your bars", ref MonsterHudSettings.SelfNumbers, "\"cur / max\" inside each bar (taller bars).", sub: true); + changed |= Toggle("Your name", ref MonsterHudSettings.SelfName, null, sub: true); + + bool fixedOn = MonsterHudSettings.SelfPlacement == SelfPlacement.Fixed; + if (Toggle("Fixed on screen", ref fixedOn, + "The bars stay where you put them on the screen, so they don't move with your character. " + + "Unlock to drag them. Chat: /rv plates self fixed.", radio: true, sub: true)) + { + MonsterHudSettings.SelfPlacement = SelfPlacement.Fixed; + changed = true; + } + if (fixedOn) + { + bool unlocked = !MonsterHudSettings.SelfLocked; + bool locked = MonsterHudSettings.SelfLocked; + if (Toggle("Lock position", ref locked, + "Locked, the plate can't be grabbed or clicked, so play never moves it. " + + "Untick it, then drag the plate (it shows a frame) and tick it again. Chat: /rv plates self lock on|off.", indent: 32)) + { + MonsterHudSettings.SelfLocked = locked; + changed = true; + } + if (unlocked) + Note("Unlocked: drag your plate anywhere on the screen, then lock it again.", w, indent: 32); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.SetCursorScreenPos(ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(32, 0)); + if (SmallButton("Reset position")) + MonsterHudSettings.ResetSelfPosition(); // saves + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("Back to the default spot, just under your character. Chat: /rv plates self reset."); + } + + bool follow = MonsterHudSettings.SelfPlacement == SelfPlacement.Follow; + if (Toggle("Follow your character", ref follow, + "The bars ride along with your character in the world (they move as it moves). Chat: /rv plates self follow.", + radio: true, sub: true)) + { + MonsterHudSettings.SelfPlacement = SelfPlacement.Follow; + changed = true; + } + if (follow) + { + changed |= SelfPositionPick("Over your head", SelfPlatePosition.Above); + changed |= SelfPositionPick("Under your feet", SelfPlatePosition.Below); + changed |= SelfPositionPick("Beside you, left", SelfPlatePosition.Left); + changed |= SelfPositionPick("Beside you, right", SelfPlatePosition.Right); + changed |= Toggle("Hide in first person", ref MonsterHudSettings.SelfHideFirstPerson, + "When the camera is at your head the plate would sit mid-screen; hide it then.", indent: 32); + } + + Section("Look", w); + changed |= SliderF("Scale", ref MonsterHudSettings.Scale, MonsterHudSettings.MinScale, MonsterHudSettings.MaxScale, "%.2f", w); + changed |= Toggle("Keep on screen", ref MonsterHudSettings.KeepOnScreen, + "When the camera closes in (walls), plates and numbers stay pinned to the screen edge instead of leaving it. Chat: /rv plates onscreen."); + changed |= SliderF("Opacity", ref MonsterHudSettings.Opacity, MonsterHudSettings.MinOpacity, MonsterHudSettings.MaxOpacity, "%.2f", w); + changed |= SliderF("Height lift (m)", ref MonsterHudSettings.HeightLift, MonsterHudSettings.MinLift, MonsterHudSettings.MaxLift, "%.1f", w); + changed |= Toggle("Fade and shrink with distance", ref MonsterHudSettings.FadeWithDistance, null); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 8)); + if (SmallButton("Reset all to defaults")) + { + MonsterHudSettings.ResetToDefaults(); + changed = false; // ResetToDefaults saved already + } + + if (changed) + MonsterHudSettings.Save(); + } + + /// <summary>The "Combat text" tab body at the cursor, <paramref name="w"/> wide.</summary> + public static void DrawCombatText(float w) + { + if (Loading(w)) return; + bool changed = false; + + Section("Combat numbers", w); + changed |= Toggle("Show combat numbers", ref MonsterHudSettings.Numbers, + "Floating numbers over monsters and over you. Chat: /rv plates numbers."); + changed |= Toggle("Damage you deal", ref MonsterHudSettings.NumDealt, + "White to red by size; gold and bigger with \"!\" on a crit. A killing blow is estimated from the last health seen.", sub: true); + changed |= Toggle("Damage you take", ref MonsterHudSettings.NumTaken, "Red numbers over your head.", sub: true); + changed |= Toggle("Heals", ref MonsterHudSettings.NumHeals, + "Green \"+N\" when you or a monster gains more health than a regen tick.", sub: true); + changed |= Toggle("Kill burst", ref MonsterHudSettings.NumKills, "Expanding rings where a monster you damaged dies.", sub: true); + changed |= Toggle("Stamina and mana restores", ref MonsterHudSettings.NumRestores, + "\"+N stam\" (amber) and \"+N mana\" (blue) over you when a spell, potion or kit restores more than a regen tick.", sub: true); + changed |= SliderF("Number size", ref MonsterHudSettings.NumSize, MonsterHudSettings.MinNumSize, MonsterHudSettings.MaxNumSize, "%.2f", w); + changed |= SliderF("Number duration", ref MonsterHudSettings.NumTime, MonsterHudSettings.MinNumTime, MonsterHudSettings.MaxNumTime, "%.2fx", w); + + Section("Gains", w); + changed |= Toggle("Show gains", ref MonsterHudSettings.Gains, + "Rising text over your head when you earn. Chat: /rv plates gains."); + changed |= Toggle("Experience", ref MonsterHudSettings.GainXp, "\"+12,345 XP\"", sub: true); + changed |= Toggle("Luminance", ref MonsterHudSettings.GainLum, "\"+500 Lum\"", sub: true); + changed |= Toggle("Radiance", ref MonsterHudSettings.GainRadiance, + "\"+10 Radiance\", from Aelrynth's \"You gain N Radiance.\" lines.", sub: true); + changed |= SliderF("Gain text size", ref MonsterHudSettings.GainSize, MonsterHudSettings.MinNumSize, MonsterHudSettings.MaxNumSize, "%.2f", w); + changed |= SliderF("Gain text duration", ref MonsterHudSettings.GainTime, MonsterHudSettings.MinNumTime, MonsterHudSettings.MaxNumTime, "%.2fx", w); + Note("Spending experience or luminance never shows.", w); + + if (changed) + MonsterHudSettings.Save(); + } + + // ── Rows ───────────────────────────────────────────────────────────── + + /// <summary>A square dot + label; the row toggles (a radio row only ever turns on; a sub row is indented).</summary> + private static bool SelfPositionPick(string label, SelfPlatePosition pos) + { + bool on = MonsterHudSettings.SelfPosition == pos; + if (!Toggle(label, ref on, "Where your plate sits. Chat: /rv plates self position above|below|left|right.", radio: true, indent: 32)) + return false; + MonsterHudSettings.SelfPosition = pos; + return true; + } + + private static bool Toggle(string label, ref bool value, string? tip, bool radio = false, bool sub = false, float indent = 0) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + if (sub && indent <= 0) indent = 16; + if (indent > 0) ImGuiNET.ImGui.SetCursorScreenPos(ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(indent, 0)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float labelW = ImGuiNET.ImGui.CalcTextSize(label).X; + ImGuiNET.ImGui.PushID(label); + bool clicked = ImGuiNET.ImGui.InvisibleButton("##t", new Vector2(18 + labelW, 16)); + ImGuiNET.ImGui.PopID(); + if (ImGuiNET.ImGui.IsItemHovered()) + { + ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + if (tip != null) ImGuiNET.ImGui.SetTooltip(tip); + } + if (clicked) value = radio || !value; + dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), value ? ToggleOn : ToggleOff, 2); + dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + return clicked; + } + + private static bool SliderF(string label, ref float value, float min, float max, string fmt, float w) + { + BeginSliderRow(label, w); + bool changed = ImGuiNET.ImGui.SliderFloat("##v", ref value, min, max, fmt, ImGuiSliderFlags.AlwaysClamp); + return EndSliderRow(changed); + } + + private static bool SliderI(string label, ref int value, int min, int max, float w) + { + BeginSliderRow(label, w); + bool changed = ImGuiNET.ImGui.SliderInt("##v", ref value, min, max, "%d", ImGuiSliderFlags.AlwaysClamp); + return EndSliderRow(changed); + } + + private static void BeginSliderRow(string label, float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.GetWindowDrawList().AddText(p + new Vector2(0, 2), TextDim, label); + float labelCol = Math.Min(130, w * 0.45f); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + labelCol, p.Y)); + ImGuiNET.ImGui.SetNextItemWidth(Math.Max(60, w - labelCol)); + ImGuiNET.ImGui.PushID(label); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + } + + /// <summary>True once the edit is finished (drag released or value typed), so saves aren't per-step.</summary> + private static bool EndSliderRow(bool changed) + { + bool done = changed && !ImGuiNET.ImGui.IsItemActive() || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + ImGuiNET.ImGui.PopID(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + return done; + } + + private static void Section(string text, float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.GetWindowDrawList().AddText(p, Amber, text); + ImGuiNET.ImGui.Dummy(new Vector2(w, ImGuiNET.ImGui.GetFontSize() + 2)); + ImGuiNET.ImGui.PopFont(); + } + + private static void Note(string text, float w, float indent = 0) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + if (indent > 0) + { + ImGuiNET.ImGui.SetCursorPosX(ImGuiNET.ImGui.GetCursorPosX() + indent); + w -= indent; + } + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(text); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + } + + private static bool SmallButton(string label) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(8, 3)); + bool clicked = ImGuiNET.ImGui.Button(label); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + return clicked; + } +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlateDebuffs.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlateDebuffs.cs new file mode 100644 index 0000000..0b953ea --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlateDebuffs.cs @@ -0,0 +1,519 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/PlateDebuffs.cs +// Which debuffs are on which monster, for the icon row on each nameplate. +// +// Source 1, the player's own casts (primary). ACE tells the caster +// "You cast {spell} on {target}{suffix}" (ChatMessageType.Magic) +// with suffix ", surpassing X" | ", refreshing X" | ", but it is surpassed by X" +// (WorldObject_Magic.cs, from AddEnchantmentResult.StackType), and +// "{target} resists your spell", "You fail to affect {target} with {spell}". +// The line names the target, not its id, and several monsters share names, +// so the line is matched to an object id: +// 1. a pending engine cast (CombatActionHooks.CastSpell: RynthAi and every +// other engine-issued cast) of the same spell on a monster of that name, +// within PendingCastSec; +// 2. else the selected target, or a target selected within PendingCastSec, +// with that name (manual casts go at the selection); +// 3. else the only creature of that name within FallbackRangeM; +// 4. else nothing is recorded (ambiguous). +// The spell name gives id / category / power / duration through the client's +// spell table (PortalSpellTable). Stacking follows AC: one entry per spell +// category; a surpassing or refreshing cast replaces it; a surpassed cast +// leaves the stronger one and at least extends how long the category lasts. +// Duration: the table's, times 1 + 0.2 x the player's +// AugmentationIncreasedSpellDuration (PropertyInt 238), not for DoTs (ACE +// EnchantmentManager.BuildEntry). +// +// Source 2, appraisal highlights (secondary, generic). The 0xC9 appraisal's +// CreatureAppraisalProfile keeps enchantment_bitfield: low 9 bits = attribute +// or vital modified, bits 16..24 = modified upward (green). Red bits that none +// of the player's own debuffs explained at that moment raise one "debuffed by +// others" marker, kept for OthersMemorySec or until the next appraisal. It +// only refreshes on appraisal (the combat target is re-appraised often). +// +// Entries drop at expiry, when the monster dies or is released (delete), and +// on logout. Fed on AC's main thread (chat, cast, selection, appraisal, +// delete hooks); read by the plates on the render thread. A lock keeps it +// safe if a caller moves. Bounded. Engine-owned statics only. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +/// <summary>What an icon on the plate stands for (one icon per kind).</summary> +internal enum DebuffKind : byte +{ + VulnFire, VulnCold, VulnLightning, VulnAcid, VulnSlash, VulnPierce, VulnBludgeon, + Imperil, MagicYield, Defense, Attributes, Vitals, Movement, Skills, Dot, Other, +} + +/// <summary>One icon: the kind, when its soonest entry expires, that entry's full length, and how many categories it merges.</summary> +internal struct DebuffIcon +{ + public DebuffKind Kind; + public long Expiry; // Stopwatch ticks + public float Duration; // seconds, of the entry expiring first + public int Stack; +} + +internal static class PlateDebuffs +{ + private const double PendingCastSec = 8.0; + private const float FallbackRangeM = 60f; + private const double OthersMemorySec = 180.0; + private const int MaxMonsters = 512; + private const int MaxPending = 16; + private const uint TypeCreature = 0x10; + + private sealed class Entry + { + public uint Category; + public DebuffKind Kind; + public uint SpellId; + public uint Power; + public long Expiry; + public float Duration; + } + + private readonly record struct PendingCast(uint Target, uint SpellId, long Ticks); + private readonly record struct Selection(uint Id, long Ticks); + private readonly record struct OthersMark(ushort Mask, long Ticks); + + private static readonly object Sync = new(); + private static readonly Dictionary<uint, List<Entry>> ByMonster = new(64); + private static readonly Dictionary<uint, OthersMark> Others = new(64); + private static readonly List<PendingCast> Pending = new(MaxPending); + private static readonly List<Selection> Selections = new(8); + private static float _durationMult = 1f; + private static int _recorded, _ambiguous, _resisted; + private static string _lastEvent = "none yet"; + + /// <summary>Caster duration multiplier from AugmentationIncreasedSpellDuration (MonsterHud refreshes it).</summary> + public static void SetDurationAugmentation(int augs) => + _durationMult = 1f + Math.Clamp(augs, 0, 5) * 0.2f; + + // ── Feeds (AC's main thread) ───────────────────────────────────────── + + /// <summary> + /// An engine-issued cast (targetId 0 = self: ignored). A repeat of the same + /// spell on the same target (a retry, or the off-thread enqueue and its + /// main-thread run) refreshes the one entry instead of adding another. + /// </summary> + public static void NoteCast(uint targetId, int spellId) + { + if (targetId == 0 || spellId <= 0) return; + long now = Stopwatch.GetTimestamp(); + lock (Sync) + { + for (int i = 0; i < Pending.Count; i++) + if (Pending[i].Target == targetId && Pending[i].SpellId == (uint)spellId) + { + Pending.RemoveAt(i); + break; + } + if (Pending.Count >= MaxPending) Pending.RemoveAt(0); + Pending.Add(new PendingCast(targetId, (uint)spellId, now)); + } + } + + /// <summary>The client's selection changed.</summary> + public static void NoteSelection(uint id) + { + if (id == 0) return; + long now = Stopwatch.GetTimestamp(); + lock (Sync) + { + if (Selections.Count >= 8) Selections.RemoveAt(0); + Selections.Add(new Selection(id, now)); + } + } + + /// <summary>A monster left the client (died, despawned, out of range): its debuffs go with it.</summary> + public static void Remove(uint id) + { + lock (Sync) + { + ByMonster.Remove(id); + Others.Remove(id); + } + } + + public static void Clear() + { + lock (Sync) + { + ByMonster.Clear(); + Others.Clear(); + Pending.Clear(); + Selections.Clear(); + } + } + + /// <summary> + /// The appraisal's enchantment bitfield for a creature (successful roll only). + /// Keeps the red bits that the player's own tracked debuffs don't explain. + /// </summary> + public static void OnAppraisal(uint id, uint bitfield) + { + if (id == 0 || (bitfield & 0xFE00FE00u) != 0) return; // bits outside the 9 + 9 known: not trusted + ushort red = (ushort)((bitfield & 0x1FF) & ~((bitfield >> 16) & 0x1FF)); + long now = Stopwatch.GetTimestamp(); + lock (Sync) + { + ushort explained = 0; + if (ByMonster.TryGetValue(id, out List<Entry>? list)) + foreach (Entry e in list) + if (e.Expiry > now) explained |= ExplainedBits(e.Category); + ushort unexplained = (ushort)(red & ~explained); + if (unexplained == 0) { Others.Remove(id); return; } + if (Others.Count >= MaxMonsters && !Others.ContainsKey(id)) Others.Clear(); + Others[id] = new OthersMark(unexplained, now); + } + } + + /// <summary> + /// A chat line. Cheap unless it is one of the caster's magic lines. Needs + /// the spell table; before it has loaded, cast lines are ignored. + /// </summary> + public static void OnChat(string line) + { + if (line.Length < 12) return; + if (line.StartsWith("You cast ", StringComparison.Ordinal)) + { + if (!PortalSpellTable.Ready) { PortalSpellTable.EnsureLoadQueued(); return; } + OnYouCast(line); + return; + } + if (line.EndsWith(" resists your spell", StringComparison.Ordinal)) + { + string name = line[..^" resists your spell".Length]; + Consume(name, 0); + lock (Sync) { _resisted++; _lastEvent = $"{name} resisted"; } + return; + } + if (line.StartsWith("You fail to affect ", StringComparison.Ordinal)) + { + int with = line.LastIndexOf(" with ", StringComparison.Ordinal); + if (with > 19) Consume(line[19..with], 0); + return; + } + if (line.StartsWith("Your spell fizzled", StringComparison.Ordinal)) + { + lock (Sync) if (Pending.Count > 0) Pending.RemoveAt(Pending.Count - 1); + } + } + + private static readonly string[] SuffixMarks = { ", surpassing ", ", refreshing ", ", but it is surpassed by " }; + + private static void OnYouCast(string line) + { + // "You cast <spell> on <target>[<suffix>]" + string body = line[9..].TrimEnd('.', ' ', '\r', '\n'); + int suffixAt = -1, suffixKind = -1; + for (int k = 0; k < SuffixMarks.Length; k++) + { + int i = body.IndexOf(SuffixMarks[k], StringComparison.Ordinal); + if (i > 0 && (suffixAt < 0 || i < suffixAt)) { suffixAt = i; suffixKind = k; } + } + string surpassedBy = suffixKind == 2 ? body[(suffixAt + SuffixMarks[2].Length)..] : ""; + if (suffixAt > 0) body = body[..suffixAt]; + + // The spell name may itself contain " on ": try each split, left to right. + DebuffSpell? spell = null; + string target = ""; + for (int at = body.IndexOf(" on ", StringComparison.Ordinal); at > 0; at = body.IndexOf(" on ", at + 1, StringComparison.Ordinal)) + { + if (PortalSpellTable.TryGetByName(body[..at], out DebuffSpell s)) + { + spell = s; + target = body[(at + 4)..]; + break; + } + } + if (spell == null || target.Length == 0 || target == "yourself" || target == "you") return; // a buff, or not ours + + long now = Stopwatch.GetTimestamp(); + uint id = ResolveTarget(spell, target, now, out string how); + lock (Sync) + { + if (id == 0) + { + _ambiguous++; + _lastEvent = $"{spell.Name} on {target}: target ambiguous, not shown"; + return; + } + Apply(id, spell, suffixKind, surpassedBy, now); + _recorded++; + _lastEvent = $"{spell.Name} on {target} (0x{id:X8}, {how})"; + } + } + + /// <summary>Pending engine cast, then the selection, then a unique name nearby; 0 if ambiguous.</summary> + private static uint ResolveTarget(DebuffSpell spell, string name, long now, out string how) + { + long window = (long)(PendingCastSec * Stopwatch.Frequency); + lock (Sync) + { + // 1. The newest engine cast of this spell on a monster so named. + int best = -1; + for (int i = Pending.Count - 1; i >= 0; i--) + { + PendingCast p = Pending[i]; + if (now - p.Ticks > window) continue; + if (p.SpellId != spell.Id && !SameName(p.SpellId, spell.Name)) continue; + if (!NameIs(p.Target, name)) continue; + best = i; + break; + } + if (best >= 0) + { + uint t = Pending[best].Target; + Pending.RemoveAt(best); + how = "engine cast"; + return t; + } + } + + // 2. The selection (manual casts go at the selected target). + uint sel = ClientHelperHooks.GetSelectedItemId(); + if (sel != 0 && NameIs(sel, name)) { how = "selected"; return sel; } + lock (Sync) + { + for (int i = Selections.Count - 1; i >= 0; i--) + { + Selection s = Selections[i]; + if (now - s.Ticks > window) break; + if (NameIs(s.Id, name)) { how = "recent selection"; return s.Id; } + } + } + + // 3. The only creature of that name nearby. + uint only = UniqueNearby(name); + how = only != 0 ? "unique name" : "ambiguous"; + return only; + } + + private static bool SameName(uint spellId, string name) => + PortalSpellTable.TryGetById(spellId, out DebuffSpell s) && s.Name.Equals(name, StringComparison.OrdinalIgnoreCase); + + private static bool NameIs(uint id, string name) => + ClientObjectHooks.TryGetSnapshotName(id, out string n) && n.Equals(name, StringComparison.Ordinal); + + /// <summary>The only creature so named within FallbackRangeM of the player; 0 when none or several.</summary> + internal static uint UniqueNearby(string name) + { + if (!PlayerPhysicsHooks.TryGetPlayerPose(out uint pCell, out float px, out float py, out float pz, out _, out _, out _, out _)) + return 0; + uint found = 0; + uint[] ids = ClientObjectHooks.LiveObjectIds; + for (int i = 0; i < ids.Length; i++) + { + uint id = ids[i]; + if (!NameIs(id, name)) continue; + if (!ClientObjectHooks.TryGetSnapshotItemType(id, out uint type) || (type & TypeCreature) == 0) continue; + if (!ClientObjectHooks.TryGetSnapshotPosition(id, out uint cell, out float x, out float y, out float z)) continue; + int dx = (int)((cell >> 24) & 0xFF) - (int)((pCell >> 24) & 0xFF); + int dy = (int)((cell >> 16) & 0xFF) - (int)((pCell >> 16) & 0xFF); + if (Math.Abs(dx) > 1 || Math.Abs(dy) > 1) continue; + float ex = x + dx * 192f - px, ey = y + dy * 192f - py, ez = z - pz; + if (ex * ex + ey * ey + ez * ez > FallbackRangeM * FallbackRangeM) continue; + if (found != 0) return 0; // two of them: ambiguous + found = id; + } + return found; + } + + /// <summary>A resist or failure: drop the newest pending cast on a monster so named.</summary> + private static void Consume(string name, uint spellId) + { + lock (Sync) + { + for (int i = Pending.Count - 1; i >= 0; i--) + { + if ((spellId == 0 || Pending[i].SpellId == spellId) && NameIs(Pending[i].Target, name)) + { + Pending.RemoveAt(i); + return; + } + } + } + } + + /// <summary>AC-style stacking, one entry per category. Caller holds Sync.</summary> + private static void Apply(uint id, DebuffSpell spell, int suffixKind, string surpassedBy, long now) + { + float dur = (float)spell.Duration * (spell.IsDot ? 1f : _durationMult); + if (dur <= 0) return; + long expiry = now + (long)(dur * Stopwatch.Frequency); + + if (!ByMonster.TryGetValue(id, out List<Entry>? list)) + { + if (ByMonster.Count >= MaxMonsters) ByMonster.Clear(); + list = new List<Entry>(4); + ByMonster[id] = list; + } + Entry? e = null; + foreach (Entry x in list) + if (x.Category == spell.Category) { e = x; break; } + + if (suffixKind == 2) + { + // Surpassed: the stronger spell stays; ours sits under it, so the category lasts at least as long as ours. + if (e != null) + { + if (expiry > e.Expiry) { e.Expiry = expiry; e.Duration = dur; } + return; + } + DebuffSpell shown = PortalSpellTable.TryGetByName(surpassedBy, out DebuffSpell y) && y.Category == spell.Category ? y : spell; + list.Add(new Entry { Category = spell.Category, Kind = KindOf(shown), SpellId = shown.Id, Power = shown.Power, Expiry = expiry, Duration = dur }); + return; + } + + // Initial, surpassing, refreshing: this spell now heads the category. + if (e == null) + { + e = new Entry { Category = spell.Category }; + list.Add(e); + } + e.Kind = KindOf(spell); + e.SpellId = spell.Id; + e.Power = spell.Power; + e.Expiry = expiry; + e.Duration = dur; + } + + // ── Read (render thread) ───────────────────────────────────────────── + + /// <summary> + /// The icons for one monster, merged by kind, soonest expiry first within a + /// kind; expired entries are dropped here. Returns the icon count (may + /// exceed dst.Length: the rest are the overflow). + /// </summary> + public static int GetIcons(uint id, DebuffIcon[] dst, out bool others) + { + others = false; + long now = Stopwatch.GetTimestamp(); + lock (Sync) + { + if (Others.TryGetValue(id, out OthersMark m)) + { + if (now - m.Ticks < (long)(OthersMemorySec * Stopwatch.Frequency)) others = true; + else Others.Remove(id); + } + if (!ByMonster.TryGetValue(id, out List<Entry>? list)) return 0; + for (int i = list.Count - 1; i >= 0; i--) + if (list[i].Expiry <= now) list.RemoveAt(i); + if (list.Count == 0) { ByMonster.Remove(id); return 0; } + + int n = 0; + ulong seen = 0; + foreach (Entry e in list) + { + int k = (int)e.Kind; + if ((seen & (1UL << k)) != 0) + { + for (int i = 0; i < Math.Min(n, dst.Length); i++) + { + if (dst[i].Kind != e.Kind) continue; + dst[i].Stack++; + if (e.Expiry < dst[i].Expiry) { dst[i].Expiry = e.Expiry; dst[i].Duration = e.Duration; } + break; + } + continue; + } + seen |= 1UL << k; + if (n < dst.Length) + dst[n] = new DebuffIcon { Kind = e.Kind, Expiry = e.Expiry, Duration = e.Duration, Stack = 1 }; + n++; + } + // Stable order on the plate: by kind. + int shown = Math.Min(n, dst.Length); + for (int i = 1; i < shown; i++) + { + DebuffIcon t = dst[i]; + int j = i - 1; + while (j >= 0 && dst[j].Kind > t.Kind) { dst[j + 1] = dst[j]; j--; } + dst[j + 1] = t; + } + return n; + } + } + + /// <summary>Tracked debuff entries (all monsters) and monsters carrying the "others" marker.</summary> + public static void Count(out int entries, out int monsters, out int othersMarked) + { + long now = Stopwatch.GetTimestamp(); + entries = monsters = 0; + lock (Sync) + { + foreach (List<Entry> list in ByMonster.Values) + { + int live = 0; + foreach (Entry e in list) if (e.Expiry > now) live++; + entries += live; + if (live > 0) monsters++; + } + othersMarked = Others.Count; + } + } + + public static string Describe() + { + Count(out int entries, out int monsters, out int others); + lock (Sync) + return $"Debuffs: {entries} tracked on {monsters} monster(s), {others} with others' marker; " + + $"{_recorded} recorded, {_resisted} resisted, {_ambiguous} ambiguous this session; last: {_lastEvent}. " + + $"Spell table: {PortalSpellTable.Status}."; + } + + // ── Categories ─────────────────────────────────────────────────────── + + /// <summary>AC spell category (ACE SpellCategory) to the icon it shows.</summary> + internal static DebuffKind KindOf(DebuffSpell s) + { + switch (s.Category) + { + case 110: return DebuffKind.VulnFire; + case 106: return DebuffKind.VulnCold; + case 108: return DebuffKind.VulnLightning; + case 102: return DebuffKind.VulnAcid; + case 114: return DebuffKind.VulnSlash; + case 112: return DebuffKind.VulnPierce; + case 104: return DebuffKind.VulnBludgeon; + case 116: return DebuffKind.Imperil; // ArmorLowering (Imperil) + case 42: return DebuffKind.MagicYield; // MagicDefenseLowering (Magic Yield) + case 38: case 40: return DebuffKind.Defense; // Melee / Missile defense (Vulnerability, Defenselessness) + case 2: case 4: case 6: case 8: case 10: case 12: return DebuffKind.Attributes; + case 80: case 82: case 84: case 94: case 96: case 98: return DebuffKind.Vitals; // max vitals, regen (Fester...) + case 78: return DebuffKind.Movement; // RunLowering (Leaden Feet) + } + if (s.IsDot) return DebuffKind.Dot; + uint c = s.Category; + bool skill = (c >= 18 && c <= 76 && (c & 1) == 0) || c == 206 || c == 217 || c == 219 || c == 220 || c == 594 || + c == 644 || c == 664 || c == 667 || c == 670 || c == 673 || c == 676 || c == 697; + if (skill) return DebuffKind.Skills; + if (c == 636 || c == 637 || c == 642 || c == 643 || (c >= 410 && c <= 412) || c == 530 || c == 536 || c == 537 || + c == 618 || c == 619 || c == 631 || (c >= 684 && c <= 687)) + return DebuffKind.Dot; + return DebuffKind.Other; + } + + /// <summary>Appraisal bits (attribute / vital highlight) a category of the player's own would turn red.</summary> + private static ushort ExplainedBits(uint category) => category switch + { + 2 => 0x001, // Strength + 4 => 0x002 | 0x040 | 0x080, // Endurance (and the max health / stamina it feeds) + 6 => 0x004, // Quickness + 8 => 0x008, // Coordination + 10 => 0x010, // Focus + 12 => 0x020 | 0x100, // Self (and max mana) + 80 => 0x040, + 82 => 0x080, + 84 => 0x100, + _ => 0, + }; +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs new file mode 100644 index 0000000..c1779e5 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs @@ -0,0 +1,385 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/PlayerPlate.cs +// The player's own plate: three thin stacked bars over your head (health red, +// stamina amber, mana blue) in the monster plates' style (edge, shine, the +// chip that drains after a drop); optional "cur/max" in each bar and the +// name above. No name and no numbers by default, to stay compact. +// +// Data: PlayerVitalsHooks.TryGetSnapshot, the buffed values AC's own vital +// bars show, kept on AC's main thread (a lock and a struct copy per frame). +// +// Two placements (MonsterHudSettings.SelfPlacement): +// Fixed on screen (default since 2026-10-05: tied to the head the plate +// jittered while the character moved). The bars sit at a saved screen +// spot (fractions of the screen, so a resize keeps it in place, then +// clamped inside the screen). Drawn by DrawScreen into ImGui's +// background list, i.e. with the normal UI (over AC's windows, under +// every ImGui panel), not through the under-UI 3D layer: a screen HUD +// element doesn't belong to the world. "Lock position" (on by default) +// makes it untouchable; unlocked, a frame shows and a left-drag anywhere +// on the plate moves it (WantsMouse keeps that press from AC), saved on +// release. Reset puts it back at the default spot. +// Follow character: the player's live pose, projected like the monster +// plates (MonsterHud.Project handles the landblock frame), above the +// head, under the feet or beside the character; drawn by Draw into the +// monster plates' list (UnderUiLayer). +// +// First person (follow mode): when the camera is inside or right at the +// head, the plate would sit in the middle of the screen, so it hides +// (setting; on by default). The head point is published either way, for the +// gain text. +// +// Render thread only. Engine-owned statics. +// ============================================================================ + +using System; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.D3D9; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +internal static class PlayerPlate +{ + private const float HeadHeight = 2.05f; // metres above the feet (human-sized characters) + private const float FirstPersonDistance = 1.3f; // camera this close to the head = first person + + private static readonly uint HealthCol = MonsterHud.C(0xFFE04A4A), StaminaCol = MonsterHud.C(0xFFE8B333), + ManaCol = MonsterHud.C(0xFF3F8FE8), NameCol = MonsterHud.C(0xFFF2E8DC), NumCol = MonsterHud.C(0xFFFFFFFF); + + private struct BarState + { + public float Shown, Trail; + public long Hold; + public bool Init; + public uint Cur, Max; + public string? Text; + public long TextKey; + } + + private static BarState _hp, _st, _mn; + private static float _alpha; + + // Fixed mode: dragging (unlocked only). + private static bool _hover, _dragging, _wantsMouse; + private static Vector2 _grab; // cursor minus the bars' centre when the drag began + + /// <summary> + /// Fixed mode, unlocked: the cursor is on the plate (or a drag is held), so the click is the plate's. + /// MonsterHud.WantsMouse includes it. Render thread. + /// </summary> + public static bool WantsMouse => _wantsMouse; + + /// <summary>Where the head is on screen this frame (valid when <see cref="HeadOnScreen"/>).</summary> + public static Vector2 HeadScreen { get; private set; } + public static bool HeadOnScreen { get; private set; } + /// <summary>Top of the drawn plate (or the head point when it isn't drawn): where the gain text starts.</summary> + public static float PlateTop { get; private set; } + /// <summary>The camera is at the head (first person) this frame.</summary> + public static bool FirstPerson { get; private set; } + + public static void Reset() + { + _hp = default; _st = default; _mn = default; + _alpha = 0f; + HeadOnScreen = false; + FirstPerson = false; + DropDrag(); + } + + /// <summary>No fixed plate this frame: no hover, no drag, no capture.</summary> + public static void DropDrag() + { + _hover = _dragging = _wantsMouse = false; + } + + /// <summary>Clears last frame's capture before a frame (Update); DrawScreen sets it again.</summary> + public static void ClearMouse() => _wantsMouse = false; + + public static void Draw(ref MonsterHud.Frame f) + { + // Head point (AC landblock-local), used by the gain text even when the plate is off. + float hz = f.Pz + HeadHeight + MonsterHudSettings.HeightLift; + FirstPerson = IsFirstPerson(ref f); + HeadOnScreen = MonsterHud.Project(ref f, f.PlayerCell, f.Px, f.Py, hz, out Vector2 head, keepOnScreen: true) && + head.X > -40 && head.X < f.Display.X + 40 && head.Y > -40 && head.Y < f.Display.Y + 40; + HeadScreen = head; + PlateTop = head.Y; + // Fixed on screen: DrawScreen paints it with the normal UI (gain text stays over the head). + if (MonsterHudSettings.SelfPlacement == SelfPlacement.Fixed) return; + + bool show = MonsterHudSettings.SelfPlate && HeadOnScreen && !(FirstPerson && MonsterHudSettings.SelfHideFirstPerson) && + PlayerVitalsHooks.TryGetSnapshot(out _); + if (!Advance(ref f, show)) return; + Layout l = Measure(f.UiScale); + float k = l.K, barW = l.BarW, blockH = l.BlockH, nameH = l.NameH; + + // Where the block goes: above the head (default), under the feet, or beside the character. + float left, y; + SelfPlatePosition where = MonsterHudSettings.SelfPosition; + if (where == SelfPlatePosition.Above) + { + left = head.X - barW * 0.5f; + y = head.Y - 4f * k - blockH; + } + else + { + bool feetOk = MonsterHud.Project(ref f, f.PlayerCell, f.Px, f.Py, f.Pz, out Vector2 feet, keepOnScreen: true); + if (!feetOk) feet = new Vector2(head.X, head.Y + 90f * k); + float charH = MathF.Max(20f * k, feet.Y - head.Y); + float midY = head.Y + charH * 0.5f; + float side = MathF.Max(22f * k, charH * 0.28f); + switch (where) + { + case SelfPlatePosition.Below: + left = feet.X - barW * 0.5f; + y = feet.Y + 6f * k + nameH; + break; + case SelfPlatePosition.Left: + left = head.X - side - barW; + y = midY - blockH * 0.5f; + break; + default: // Right + left = head.X + side; + y = midY - blockH * 0.5f; + break; + } + } + if (MonsterHudSettings.KeepOnScreen) + { + left = Math.Clamp(left, 4f, MathF.Max(4f, f.Display.X - barW - 4f)); + y = Math.Clamp(y, 4f + nameH, MathF.Max(4f + nameH, f.Display.Y - blockH - 4f)); + } + float top = Paint(f.Dl, ref l, MathF.Round(left), MathF.Round(y)); + // Gain text floats above the plate when it's over the head, else above the head itself. + PlateTop = where == SelfPlatePosition.Above ? top : head.Y; + } + + /// <summary> + /// Fixed on screen: the plate at its saved spot, into ImGui's background list (the normal UI pass: + /// over AC's windows, under every panel), and the drag while unlocked. After <see cref="Draw"/>, + /// inside the ImGui frame. Render thread. + /// </summary> + public static void DrawScreen(ref MonsterHud.Frame f) + { + if (MonsterHudSettings.SelfPlacement != SelfPlacement.Fixed) { DropDrag(); return; } + bool show = MonsterHudSettings.SelfPlate && PlayerVitalsHooks.TryGetSnapshot(out _); + if (!Advance(ref f, show)) { DropDrag(); return; } + Layout l = Measure(f.UiScale); + + // The bars' centre from the saved fractions, then the block kept inside the screen. + Vector2 display = f.Display; + float cx = MonsterHudSettings.SelfFixedX * display.X, cy = MonsterHudSettings.SelfFixedY * display.Y; + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + bool unlocked = !MonsterHudSettings.SelfLocked; + if (_dragging) + { + if (unlocked && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) + { + cx = io.MousePos.X - _grab.X; + cy = io.MousePos.Y - _grab.Y; + } + else + { + // Let go (or locked mid-drag): keep where it is, saved. + _dragging = false; + MonsterHudSettings.Save(); + } + } + float left = Math.Clamp(cx - l.BarW * 0.5f, 4f, MathF.Max(4f, display.X - l.BarW - 4f)); + float y = Math.Clamp(cy - l.BlockH * 0.5f, 4f + l.NameH, MathF.Max(4f + l.NameH, display.Y - l.BlockH - 4f)); + left = MathF.Round(left); + y = MathF.Round(y); + if (_dragging && display.X > 1 && display.Y > 1) + { + // The spot as fractions (clamped, so letting go off screen keeps it reachable). + MonsterHudSettings.SelfFixedX = Math.Clamp((left + l.BarW * 0.5f) / display.X, 0f, 1f); + MonsterHudSettings.SelfFixedY = Math.Clamp((y + l.BlockH * 0.5f) / display.Y, 0f, 1f); + } + + // The plate's rect (name included), a little padded: the drag surface. + float pad = MathF.Round(4f * l.K); + var r0 = new Vector2(left - pad, y - l.NameH - pad); + var r1 = new Vector2(left + l.BarW + pad, y + l.BlockH + pad); + Drag(unlocked, r0, r1, new Vector2(left + l.BarW * 0.5f, y + l.BlockH * 0.5f)); + + ImDrawListPtr dl = ImGuiNET.ImGui.GetBackgroundDrawList(); + if (unlocked) + { + // Unlocked: a frame says it can be moved (brighter while hovered or dragged). + float a = Math.Clamp(_alpha, 0.35f, 1f); + bool hot = _hover || _dragging; + dl.AddRectFilled(r0, r1, MonsterHud.Mul(hot ? 0x40000000u : 0x28000000u, a), 3f); + dl.AddRect(r0, r1, MonsterHud.Mul(hot ? FrameHot : FrameCol, a), 3f, ImDrawFlags.None, hot ? 1.5f : 1f); + } + Paint(dl, ref l, left, y); + } + + private static readonly uint FrameCol = MonsterHud.C(0xB026D9E6), FrameHot = MonsterHud.C(0xFF26D9E6); + + /// <summary>Hover and a left-drag on the unlocked plate (the MonsterHud plate-click pattern).</summary> + private static void Drag(bool unlocked, Vector2 r0, Vector2 r1, Vector2 centre) + { + bool prevHover = _hover; + _hover = false; + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + bool usable = unlocked && Win32Backend.IsUiCaptureEnabled() && (!io.WantCaptureMouse || _dragging); + if (usable) + { + Vector2 m = io.MousePos; + _hover = m.X >= r0.X && m.X <= r1.X && m.Y >= r0.Y && m.Y <= r1.Y; + } + if (!_dragging && usable && (_hover || prevHover) && Win32Backend.MouseCaptured && + ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left) && + !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Right) && !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Middle)) + { + // The press went where last frame's hover put the capture: the drag starts. + _dragging = true; + _grab = io.MousePos - centre; + } + if (_hover || _dragging) + { + ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.ResizeAll); + if (_hover && !_dragging) + ImGuiNET.ImGui.SetTooltip(DragTip); + } + _wantsMouse = _hover || _dragging; + } + + private const string DragTip = "Drag to move your plate.\nLock it again in Vision > Nameplates > Your plate (or /rv plates self lock)."; + + /// <summary>Fades the plate in / out and steps the bars; false when nothing should be painted.</summary> + private static bool Advance(ref MonsterHud.Frame f, bool show) + { + float kAlpha = 1f - MathF.Exp(-f.Dt * 12f); + _alpha += ((show ? MonsterHudSettings.Opacity : 0f) - _alpha) * kAlpha; + if (!show) { if (_alpha < 0.02f) _alpha = 0f; return false; } + if (_alpha < 0.01f) return false; + + PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot v); + float kBar = 1f - MathF.Exp(-f.Dt * 14f); + Step(ref _hp, v.Health, v.MaxHealth, f.Now, kBar, f.Dt); + Step(ref _st, v.Stamina, v.MaxStamina, f.Now, kBar, f.Dt); + Step(ref _mn, v.Mana, v.MaxMana, f.Now, kBar, f.Dt); + return true; + } + + /// <summary>The plate's sizes and fonts this frame.</summary> + private struct Layout + { + public float K, BarW, BarH, Gap, Round, BlockH, NameH, SmallSize, NameSize; + public bool Numbers; + public ImFontPtr Small, NameFont; + } + + private static Layout Measure(float uiScale) + { + Layout l = default; + float k = l.K = MonsterHudSettings.Scale * uiScale; + bool numbers = l.Numbers = MonsterHudSettings.SelfNumbers; + // With numbers on, the bars grow to fit bold, outlined text that reads over any fill. + l.BarW = MathF.Round((numbers ? 124f : 96f) * k); + l.BarH = MathF.Round((numbers ? 15f : 5f) * k); + l.Gap = MathF.Max(2f, MathF.Round(2f * k)); + l.Round = MathF.Max(1f, 1.5f * k); + // Sized from the 11 px bold bake, drawn from the smallest bake at least that big (no blur when scaled up). + l.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale); + l.Small = ImGuiFonts.Sharp(l.SmallSize, bold: true); + l.BlockH = 3 * l.BarH + 2 * l.Gap; + l.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale); + l.NameFont = ImGuiFonts.Sharp(l.NameSize, bold: true); + l.NameH = MonsterHudSettings.SelfName ? l.NameSize + 3f * k : 0f; + return l; + } + + /// <summary>Paints the three bars (and the name over them) with their top-left at (left, y); returns the plate's top.</summary> + private static float Paint(ImDrawListPtr dl, ref Layout l, float left, float y) + { + float a = Math.Clamp(_alpha, 0f, 1f); + PaintOne(dl, ref _hp, left, y, l.BarW, l.BarH, l.Round, a, HealthCol, l.Numbers, l.Small, l.SmallSize); + PaintOne(dl, ref _st, left, y + l.BarH + l.Gap, l.BarW, l.BarH, l.Round, a, StaminaCol, l.Numbers, l.Small, l.SmallSize); + PaintOne(dl, ref _mn, left, y + 2 * (l.BarH + l.Gap), l.BarW, l.BarH, l.Round, a, ManaCol, l.Numbers, l.Small, l.SmallSize); + float top = y - 1f; + if (MonsterHudSettings.SelfName) + { + string name = PlayerName(); + if (name.Length > 0) + { + float w = MonsterHud.TextWidth(l.NameFont, l.NameSize, name); + var pos = new Vector2(MathF.Round(left + (l.BarW - w) * 0.5f), MathF.Round(y - 3f * l.K - l.NameSize)); + MonsterHud.OutlinedText(dl, l.NameFont, l.NameSize, pos, a, name); + dl.AddText(l.NameFont, l.NameSize, pos, MonsterHud.Mul(NameCol, a), name); + top = pos.Y; + } + } + return top; + } + + /// <summary>The camera at (or inside) the head: AC's first-person view.</summary> + private static bool IsFirstPerson(ref MonsterHud.Frame f) + { + if (!GameMatrixCapture.TryGetCameraPosition(out float cx, out float cy, out float cz)) return false; + if (!MonsterHud.TryOffset(f.FrameCell, f.PlayerCell, out float ox, out float oy)) return false; + // Camera is in D3D axes (x east, y up, z north); the eyes sit about 1.6 m up. + float dx = cx - (f.Px + ox), dy = cy - (f.Pz + 1.6f), dz = cz - (f.Py + oy); + return dx * dx + dy * dy + dz * dz < FirstPersonDistance * FirstPersonDistance; + } + + private static void Step(ref BarState b, uint cur, uint max, long now, float kBar, float dt) + { + float ratio = max > 0 ? Math.Clamp((float)cur / max, 0f, 1f) : 0f; + b.Cur = cur; b.Max = max; + if (!b.Init || _alpha <= 0.02f) + { + b.Shown = b.Trail = ratio; + b.Hold = 0; + b.Init = true; + return; + } + MonsterHud.StepBar(ref b.Shown, ref b.Trail, ref b.Hold, ratio, now, kBar, dt); + } + + private static void PaintOne(ImDrawListPtr dl, ref BarState b, float left, float top, float w, float h, float round, float a, + uint col, bool numbers, ImFontPtr font, float size) + { + var b0 = new Vector2(left, top); + var b1 = new Vector2(left + w, top + h); + MonsterHud.PaintBar(dl, b0, b1, round, a, b.Shown, b.Trail, col, ticks: false); + if (!numbers || h < 8f || b.Max == 0) return; + long key = ((long)b.Max << 32) | b.Cur; + string? text = b.Text; + if (key != b.TextKey || text == null) + { + b.TextKey = key; + text = b.Text = b.Cur.ToString(CultureInfo.InvariantCulture) + " / " + b.Max.ToString(CultureInfo.InvariantCulture); + } + float tw = MonsterHud.TextWidth(font, size, text); + var pos = new Vector2(MathF.Round(left + (w - tw) * 0.5f), MathF.Round(top + (h - size) * 0.5f)); + // A dark band behind the text, then an outline, so it reads over bright and dark fills alike. + dl.AddRectFilled(new Vector2(pos.X - 3f, top + 1f), new Vector2(pos.X + tw + 3f, top + h - 1f), MonsterHud.Mul(0x70000000u, a), 2f); + MonsterHud.OutlinedText(dl, font, size, pos, a, text); + dl.AddText(font, size, pos, MonsterHud.Mul(NumCol, a), text); + } + + private static string _name = ""; + private static uint _nameOwner; + + private static string PlayerName() + { + uint id = ClientHelperHooks.GetPlayerId(); + if (id != _nameOwner && ClientObjectHooks.TryGetSnapshotName(id, out string n) && n.Length > 0) + { + _nameOwner = id; + _name = n; + } + return _name; + } + + public static string Describe() => + $"Self plate {(MonsterHudSettings.SelfPlate ? "on" : "off")}" + + (MonsterHudSettings.SelfPlacement == SelfPlacement.Fixed + ? (MonsterHudSettings.SelfLocked ? ", fixed on screen (locked)." : ", fixed on screen (unlocked: drag it).") + : FirstPerson ? ", follows you (first person" + (MonsterHudSettings.SelfHideFirstPerson ? ", hidden)." : ").") : ", follows you."); +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PortalSpellTable.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PortalSpellTable.cs new file mode 100644 index 0000000..b8466c0 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PortalSpellTable.cs @@ -0,0 +1,348 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/PortalSpellTable.cs +// The client's spell table (portal dat file 0x0E00000E), read once in the +// background so the nameplates can turn "You cast <spell> on <monster>" into +// a spell id, category, power and duration. +// +// Layout (ACE.DatLoader SpellTable / SpellBase): file id u32, then a +// PackedHashTable (u16 count, u16 buckets) of u32 spell id + SpellBase: +// name, desc: u16 length + nibble-swapped bytes, each padded to 4 +// school, icon, category, bitfield, baseMana u32; rangeConst, rangeMod f32; +// power u32; economyMod f32; formulaVersion u32; componentLoss f32; +// metaSpellType u32, metaSpellId u32; +// Enchantment (1) / FellowEnchantment (12): duration f64, degradeMod f32, +// degradeLimit f32; PortalSummon (7): portalLifetime f64; +// 8 x u32 components, casterEffect, targetEffect, fizzleEffect u32, +// recoveryInterval f64, recoveryAmount f32, displayOrder, +// nonComponentTargetType, manaMod u32. +// Bitfield 0x4 = Beneficial, 0x10000 = DamageOverTime (ACE SpellFlags). +// +// Only debuffs are kept (non-beneficial enchantments, ~1,500 of ~6,300), +// plus every spell's icon id (script windows draw spell icons) and name +// (the Inventory panel's item tooltips and the Skills panel's buff lists). +// The dat reader is a minimal port of the on-demand reader in +// RynthSuite/Shared/RynthCore.TerrainData/DatDatabase.cs (header at 0x140, +// B-tree search by id, block chain whose first dword is the next block). +// +// Threads: the load runs on UiBackgroundWriter (never AC's thread); readers +// take a published immutable snapshot. Engine-owned statics only. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +/// <summary>One debuff spell from the client's spell table.</summary> +internal sealed class DebuffSpell +{ + public uint Id; + public string Name = ""; + public uint Category; + public uint Power; + public uint Flags; + public double Duration; // seconds, before caster augmentations + public bool IsDot => (Flags & 0x10000) != 0; +} + +internal static class PortalSpellTable +{ + private const uint SpellTableFileId = 0x0E00000E; + private const uint FlagBeneficial = 0x4; + private const uint MetaEnchantment = 1, MetaPortalSummon = 7, MetaFellowEnchantment = 12; + + private sealed class Table + { + public readonly Dictionary<uint, DebuffSpell> ById = new(); + public readonly Dictionary<string, DebuffSpell> ByName = new(StringComparer.OrdinalIgnoreCase); + /// <summary>Every spell's icon (0x06 texture id), for script windows' spell icons.</summary> + public readonly Dictionary<uint, uint> IconById = new(); + /// <summary>Every spell's name, for item tooltips (Inventory panel) and buff lists (Skills panel).</summary> + public readonly Dictionary<uint, string> NameById = new(); + } + + private static readonly object Sync = new(); + private static volatile Table? _table; + private static bool _queued; + private static volatile string _status = "not loaded"; + + /// <summary>True once the table is readable.</summary> + public static bool Ready => _table != null; + + public static int Count => _table?.ById.Count ?? 0; + + /// <summary>"1,512 debuffs from client_portal.dat" or why not. Any thread.</summary> + public static string Status => _status; + + /// <summary>Queues the one-time read off the calling thread. Cheap after the first call.</summary> + public static void EnsureLoadQueued() + { + if (_table != null) return; + lock (Sync) + { + if (_queued) return; + _queued = true; + } + _status = "loading"; + UiBackgroundWriter.Enqueue("portal spell table", LoadNow); + } + + public static bool TryGetById(uint id, out DebuffSpell spell) + { + Table? t = _table; + if (t != null && t.ById.TryGetValue(id, out DebuffSpell? s)) { spell = s; return true; } + spell = null!; + return false; + } + + /// <summary>Any spell's icon (0x06 texture id) once the table is loaded. Any thread.</summary> + public static bool TryGetIcon(uint spellId, out uint icon) + { + Table? t = _table; + if (t != null && t.IconById.TryGetValue(spellId, out icon)) return true; + icon = 0; + return false; + } + + /// <summary>Any spell's name once the table is loaded. Any thread.</summary> + public static bool TryGetName(uint spellId, out string name) + { + Table? t = _table; + if (t != null && t.NameById.TryGetValue(spellId, out string? n)) { name = n; return true; } + name = string.Empty; + return false; + } + + /// <summary> + /// A debuff by its exact name. Several spells can share a name (monster + /// versions of "Poison", "Slowness"...): the strongest non-self one wins. + /// </summary> + public static bool TryGetByName(string name, out DebuffSpell spell) + { + Table? t = _table; + if (t != null && t.ByName.TryGetValue(name, out DebuffSpell? s)) { spell = s; return true; } + spell = null!; + return false; + } + + // ── Load (background) ──────────────────────────────────────────────── + + private static void LoadNow() + { + try + { + string? path = FindPortalDat(); + if (path == null) { _status = "client_portal.dat not found next to acclient.exe"; return; } + byte[]? raw = DatReader.ReadFile(path, SpellTableFileId, out string why); + if (raw == null) { _status = $"{Path.GetFileName(path)}: {why}"; return; } + Table t = Parse(raw, out int total); + _table = t; + _status = $"{t.ById.Count:N0} debuffs of {total:N0} spells from {Path.GetFileName(path)}"; + RynthLog.UI($"Nameplates: spell table - {_status}"); + } + catch (Exception ex) + { + _status = $"spell table read failed: {ex.GetType().Name}: {ex.Message}"; + RynthLog.UI($"Nameplates: {_status}"); + } + } + + private static string? FindPortalDat() + { + var dirs = new List<string>(2); + try + { + string? exe = Environment.ProcessPath; + string? dir = string.IsNullOrEmpty(exe) ? null : Path.GetDirectoryName(exe); + if (!string.IsNullOrEmpty(dir)) dirs.Add(dir); + } + catch { } + try { dirs.Add(Environment.CurrentDirectory); } catch { } + foreach (string dir in dirs) + foreach (string name in new[] { "client_portal.dat", "portal.dat" }) + { + string full = Path.Combine(dir, name); + if (File.Exists(full)) return full; + } + return null; + } + + private static Table Parse(byte[] raw, out int total) + { + var t = new Table(); + var r = new SpanReader(raw); + r.U32(); // file id + total = r.U16(); + r.U16(); // bucket count + for (int i = 0; i < total && r.Ok; i++) + { + uint id = r.U32(); + string name = r.ObfuscatedString(); + r.ObfuscatedString(); // description + r.U32(); // school + uint icon = r.U32(); + uint category = r.U32(); + uint flags = r.U32(); + r.U32(); // base mana + r.Skip(8); // range constant, range mod + uint power = r.U32(); + r.Skip(12); // economy mod, formula version, component loss + uint meta = r.U32(); + r.U32(); // meta spell id + double duration = 0; + if (meta == MetaEnchantment || meta == MetaFellowEnchantment) + { + duration = r.F64(); + r.Skip(8); // degrade modifier, degrade limit + } + else if (meta == MetaPortalSummon) + { + r.Skip(8); + } + r.Skip(8 * 4 + 12 + 8 + 4 + 12); // components, effects, recovery, display order, target type, mana mod + if (!r.Ok) break; + + if (icon != 0) t.IconById[id] = icon; + if (name.Length > 0) t.NameById[id] = name; + if (meta != MetaEnchantment || (flags & FlagBeneficial) != 0 || name.Length == 0) continue; + var s = new DebuffSpell { Id = id, Name = name, Category = category, Power = power, Flags = flags, Duration = duration }; + t.ById[id] = s; + if (!t.ByName.TryGetValue(name, out DebuffSpell? prev) || Better(s, prev)) + t.ByName[name] = s; + } + return t; + } + + /// <summary>Name collisions: prefer a spell cast on others (not SelfTargeted 0x8), then the stronger.</summary> + private static bool Better(DebuffSpell a, DebuffSpell b) + { + bool aSelf = (a.Flags & 0x8) != 0, bSelf = (b.Flags & 0x8) != 0; + if (aSelf != bSelf) return !aSelf; + return a.Power > b.Power; + } + + /// <summary>Bounds-checked little-endian reader; Ok turns false on overrun.</summary> + private ref struct SpanReader + { + private readonly ReadOnlySpan<byte> _b; + private int _p; + public bool Ok; + + public SpanReader(byte[] b) { _b = b; _p = 0; Ok = true; } + + private bool Has(int n) + { + if (Ok && _p + n <= _b.Length) return true; + Ok = false; + return false; + } + + public uint U32() { if (!Has(4)) return 0; uint v = BitConverter.ToUInt32(_b.Slice(_p, 4)); _p += 4; return v; } + public ushort U16() { if (!Has(2)) return 0; ushort v = BitConverter.ToUInt16(_b.Slice(_p, 2)); _p += 2; return v; } + public double F64() { if (!Has(8)) return 0; double v = BitConverter.ToDouble(_b.Slice(_p, 8)); _p += 8; return v; } + public void Skip(int n) { if (Has(n)) _p += n; } + + /// <summary>u16 length + bytes with nibbles swapped, then aligned to 4 (from the file start, as ACE does).</summary> + public string ObfuscatedString() + { + int n = U16(); + if (!Has(n)) return ""; + Span<char> chars = n <= 256 ? stackalloc char[n] : new char[n]; + for (int i = 0; i < n; i++) + { + byte x = _b[_p + i]; + chars[i] = (char)(byte)((x >> 4) | (x << 4)); // Latin-1: byte == code point + } + _p += n; + _p = (_p + 3) & ~3; + return new string(chars); + } + } + + /// <summary>Just enough of the dat format to read one file by id.</summary> + private static class DatReader + { + private const int HeaderOffset = 0x140; + private const int Branches = 62, MaxEntries = 61, EntrySize = 24; + private const int NodeSize = 4 * Branches + 4 + EntrySize * MaxEntries; // 1716 + private const int MaxDepth = 16; + + public static byte[]? ReadFile(string path, uint fileId, out string why) + { + // Read-only, and share everything: AC holds its own handles on the dats. + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, + FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess); + Span<byte> hdr = stackalloc byte[36]; + fs.Seek(HeaderOffset, SeekOrigin.Begin); + if (!ReadFully(fs, hdr)) { why = "short header"; return null; } + uint blockSize = BitConverter.ToUInt32(hdr.Slice(4, 4)); + uint root = BitConverter.ToUInt32(hdr.Slice(32, 4)); + if (blockSize <= 4 || blockSize > 65536 || root == 0 || root >= fs.Length) { why = "bad header"; return null; } + + uint offset = root; + for (int depth = 0; depth < MaxDepth && offset != 0; depth++) + { + byte[]? node = ReadChain(fs, blockSize, offset, NodeSize); + if (node == null) { why = "unreadable B-tree node"; return null; } + uint count = BitConverter.ToUInt32(node, 4 * Branches); + if (count > MaxEntries) { why = "corrupt B-tree node"; return null; } + int i = 0; + while (i < count && BitConverter.ToUInt32(node, 4 * Branches + 4 + i * EntrySize + 4) < fileId) i++; + if (i < count && BitConverter.ToUInt32(node, 4 * Branches + 4 + i * EntrySize + 4) == fileId) + { + int e = 4 * Branches + 4 + i * EntrySize; + uint fileOffset = BitConverter.ToUInt32(node, e + 8); + uint fileSize = BitConverter.ToUInt32(node, e + 12); + if (fileSize == 0 || fileSize > 64 * 1024 * 1024) { why = "implausible file size"; return null; } + byte[]? data = ReadChain(fs, blockSize, fileOffset, (int)fileSize); + why = data == null ? "unreadable file blocks" : ""; + return data; + } + bool leaf = BitConverter.ToUInt32(node, 0) == 0; + if (leaf || i >= Branches) break; + offset = BitConverter.ToUInt32(node, i * 4); + } + why = $"file 0x{fileId:X8} not in the dat"; + return null; + } + + /// <summary>A block chain: each block starts with the next block's offset (0 = last).</summary> + private static byte[]? ReadChain(FileStream fs, uint blockSize, uint offset, int size) + { + if ((long)offset + 4 > fs.Length) return null; + var buffer = new byte[size]; + Span<byte> next = stackalloc byte[4]; + fs.Seek(offset, SeekOrigin.Begin); + if (!ReadFully(fs, next)) return null; + uint nextAddr = BitConverter.ToUInt32(next); + int done = 0; + int guard = 0; + while (done < size) + { + int take = Math.Min((int)blockSize - 4, size - done); + if (!ReadFully(fs, buffer.AsSpan(done, take))) return null; + done += take; + if (done >= size) break; + if (nextAddr == 0 || nextAddr >= fs.Length || ++guard > 1_000_000) return null; + fs.Seek(nextAddr, SeekOrigin.Begin); + if (!ReadFully(fs, next)) return null; + nextAddr = BitConverter.ToUInt32(next); + } + return buffer; + } + + private static bool ReadFully(FileStream fs, Span<byte> dest) + { + while (dest.Length > 0) + { + int n = fs.Read(dest); + if (n <= 0) return false; + dest = dest.Slice(n); + } + return true; + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs new file mode 100644 index 0000000..6e0d542 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -0,0 +1,951 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ChatFace.cs +// ImGui face of RynthChat (docked or popped out; the old Avalonia face is +// UI/Panels/RynthChatPanel.cs): channel and custom tabs with unread counts +// (right-click a tab: mark read, rename, delete), Filters (the ChatFilters +// rule editor), the settings gear, search, the coloured scrollback, and the +// input line with Tell and the panel's resize grip beside it. +// +// Scrollback: wrapped lines, heights cached per wrap width and font; only +// the lines in view are drawn. The timestamp is dimmed and the text wraps +// under itself. Lines keep the colour and highlights the rules gave them +// (ChatLine.Route, worked out on the pump - no regex runs here); a line with +// highlights is laid out by hand (LayoutSpans) so each run can take its own +// colour. Drag across lines to copy them (the keyboard stays with the game, +// so copy is mouse-driven). Right-click a line to copy it or to make a rule +// from it: move / copy lines like it to a tab, hide them, colour them. A line +// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go +// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them). +// Follows the newest line until you scroll up. +// +// The input line belongs to ChatModel (UI/Data/ChatData.cs): Win32Backend +// turns the chat keys into ChatModel edits on AC's thread, which is also +// this face's thread. Clicking the box starts typing, like Enter. +// +// The panel has no strip under the body for the resize grip (PanelSpec. +// GripInBody): the input row stops short of the bottom-right corner by +// ImGuiPanelHost.BodyGripReserve and the host draws the grip there. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class ChatFace : IImGuiPanel +{ + public const string Title = "Chat"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(460, 300), new Vector2(260, 140), Background: 0, EdgeToEdge: true, GripInBody: true), + () => new ChatFace()); + + private static readonly uint TabActive = RynthTheme.Argb(0xFF264C59), TabAdd = RynthTheme.Argb(0xFF7AE09A), + InputBg = RynthTheme.Argb(0xFF0A121A), InputBorder = RynthTheme.Argb(0xFF264C59), InputActive = RynthTheme.Argb(0xFFFFD700), + SelBg = RynthTheme.Argb(0x663A6EA5), FlashBg = RynthTheme.Argb(0xE0264C59), TellBg = RynthTheme.Argb(0xFF0E2E3A), + TsColor = RynthTheme.Argb(0xFF6F8397), MentionBg = RynthTheme.Argb(0x33FFC857), + BadgeBg = RynthTheme.Argb(0xFF1F6F7A), BadgeMention = RynthTheme.Argb(0xFFB8860B); + private const float StickThreshold = 24f; + + // Visible lines for the current tab + search, with wrapped heights; _lay + // holds the hand layout of lines with highlights (null for plain lines). + private readonly List<ChatLine> _vis = new(512); + private readonly List<float> _h = new(512); + private readonly List<SpanLayout?> _lay = new(512); + private float[] _tops = new float[1]; + private int _heightsFrom; // first line whose height needs measuring + private bool _topsDirty = true; + private long _seenLinesVersion = -1, _seenRoutes = -1, _lastId; + private string _seenTab = "", _seenSearch = ""; + private float _seenWrap = -1, _seenFont = -1; + private bool _seenTs; + + private readonly byte[] _search = new byte[128], _newTab = new byte[64], _mentionWords = new byte[256]; + private bool _stick = true; + private float _lastScrollY; + // Height of lines dropped off the top (the buffer is full) while not following the + // tail: the view is moved up by as much, so the lines being read stay put instead of + // sliding away. + private float _droppedAbove; + private float _inputScroll; + + // Selection: indices into _vis. + private int _selAnchor = -1, _selEnd = -1; + private bool _selDragging, _selMoved; + private Vector2 _selDown; + private string? _flash; + private double _flashUntil; + + // Unread lines per tab since it was last on screen (Id of the newest line seen there). + private readonly Dictionary<string, long> _seenId = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary<string, (int Count, bool Mention)> _unread = new(StringComparer.OrdinalIgnoreCase); + private long _unreadLines = -1, _unreadRoutes = -1, _unreadTabsVersion = -1; + private string _unreadTab = ""; + + private bool _openSettings, _openNewTab, _focusNewTab, _openTabMenu, _openLineMenu, _openRename; + private string? _ctxTab, _renameFrom; + private ChatLine? _ctxLine; + private string _ctxPattern = ""; + // Map coordinates in the right-clicked line (ChatCoords, found when the menu opens): + // its menu offers "Arrow to" / "Go to" them, through RynthNav. + private List<ChatCoord> _ctxCoords = new(); + /// <summary>A Move/Copy rule waiting for the New tab popup to name its tab.</summary> + private ChatFilterRule? _pendingRule; + + public bool ClickThrough => ChatModel.CtrlGatedClickThrough && !ImGuiNET.ImGui.GetIO().KeyCtrl; + + /// <summary>New lines arrive a few times a second at most; popped out and idle, 5 Hz is plenty.</summary> + public int PopOutIdleHz => 5; + + public void OnShown() + { + ChatModel.EnsureSettingsLoaded(); + UiSources.Chat.Subscribe(); + UiSources.Chat.RequestRefresh(); + ChatModel.SetShown(true); + _stick = true; + _seenRoutes = -1; // full rebuild on the first frame + _seenId.Clear(); // every tab starts read + _unreadLines = -1; + } + + public void OnHidden() + { + ChatModel.SetShown(false); + UiSources.Chat.Unsubscribe(); + } + + public void Draw() + { + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + uint bg = RynthTheme.Argb(((uint)Math.Clamp(ChatModel.BackgroundAlpha, 0, 255) << 24) | 0x0A121A); + dl.AddRectFilled(origin, origin + size, bg, 4); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4)); + float x0 = origin.X + 4, w = size.X - 8; + + var snap = UiSources.Chat.Current; + ChatLine[] lines = snap?.Value ?? Array.Empty<ChatLine>(); + string tab = ChatModel.CurrentTab(); + UpdateUnread(lines, snap?.Version ?? -1, tab); + + float y = DrawTabStrip(new Vector2(x0, origin.Y + 4), w); + + DrawSearch(new Vector2(x0, y), w); + y += 26; + + SyncLines(snap, lines, tab); + + // Scrollback, then the input row along the bottom; the grip takes its + // bottom-right corner (ImGuiPanelHost.BodyGripReserve). + const float inputH = 22, bottomPad = 2; + float reserve = ImGuiPanelHost.BodyGripReserve; + float inputY = origin.Y + size.Y - bottomPad - inputH; + float listH = Math.Max(20, inputY - 4 - y); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y)); + DrawLines(new Vector2(w, listH)); + float inputRight = reserve > 0 ? origin.X + size.X - reserve - 3 : x0 + w; + DrawInput(new Vector2(x0, inputY), inputRight - x0, inputH); + + ImGuiNET.ImGui.PopStyleVar(); + DrawPopups(); + ImGuiNET.ImGui.PopFont(); + } + + // ── Tabs ───────────────────────────────────────────────────────────── + + private const string SearchHint = PhosphorIcons.MagnifyingGlass + " Search…"; + private const string FiltersLabel = PhosphorIcons.Funnel + " Filters"; + + /// <summary>Tabs wrap left of Filters and the settings gear. Returns the y below the strip.</summary> + private float DrawTabStrip(Vector2 start, float w) + { + const float h = 20; + float gearW = 22, filtW = ButtonWidth(FiltersLabel) - 4; + float right = start.X + w; + if (IconButton("##chat_gear", PhosphorIcons.Gear, new Vector2(right - gearW, start.Y), new Vector2(gearW, h), Text, BtnFill)) + _openSettings = true; + ImGuiNET.ImGui.SetItemTooltip("Chat settings"); + if (Button("##chat_filters", FiltersLabel, new Vector2(right - gearW - 3 - filtW, start.Y), new Vector2(filtW, h), Text, BtnFill)) + PanelRouter.Toggle("ChatFilters"); + ImGuiNET.ImGui.SetItemTooltip("Rules: move, copy or hide lines by regex, and colour them"); + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float stripRight = right - gearW - filtW - 8; + float x = start.X, y = start.Y; + string current = ChatModel.CurrentTab(); + foreach (string tab in ChatModel.AllTabs()) + { + bool custom = !ChatModel.IsBaseTab(tab); + bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase); + _unread.TryGetValue(tab, out var unread); + string? badge = !active && unread.Count > 0 ? (unread.Count > 99 ? "99+" : unread.Count.ToString()) : null; + float badgeW = 0; + if (badge != null) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + badgeW = ImGuiNET.ImGui.CalcTextSize(badge).X + 8; + ImGuiNET.ImGui.PopFont(); + } + float textW = ImGuiNET.ImGui.CalcTextSize(tab).X; + // No inline delete button on custom tabs: right-click → Delete tab does it and + // the red X cost a tab's worth of strip width (2026-09-30). + float bw = textW + 12 + (badge != null ? badgeW + 3 : 0), extra = 0; + if (x > start.X && x + bw + extra > stripRight) { x = start.X; y += h + 2; } + ImGuiNET.ImGui.PushID(tab); + var p = new Vector2(x, y); + if (Button("##tab", "", p, new Vector2(bw, h), Text, active ? TabActive : BtnFill)) + ChatModel.SelectTab(tab); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _ctxTab = tab; _openTabMenu = true; } + if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here"); + else if (custom) ImGuiNET.ImGui.SetItemTooltip("Right-click to rename or delete this tab"); + float ty = y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.AddText(new Vector2(x + 6, ty), Text, tab); + if (badge != null) + { + var b0 = new Vector2(x + 6 + textW + 3, y + 4); + dl.AddRectFilled(b0, b0 + new Vector2(badgeW, h - 8), unread.Mention ? BadgeMention : BadgeBg, (h - 8) * 0.5f); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + dl.AddText(b0 + new Vector2(4, (h - 8 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, badge); + ImGuiNET.ImGui.PopFont(); + } + ImGuiNET.ImGui.PopID(); + x += bw + extra + 2; + } + if (x > start.X && x + 18 > stripRight) { x = start.X; y += h + 2; } + if (IconButton("##chat_addtab", PhosphorIcons.Plus, new Vector2(x, y), new Vector2(18, h), TabAdd, BtnFill, font: UiFont.Ui11)) + { + _pendingRule = null; + WriteUtf8(_newTab, ""); + _openNewTab = _focusNewTab = true; + } + ImGuiNET.ImGui.SetItemTooltip("New tab (fill it with a rule: right-click a line, or Filters)"); + return y + h + 4; + } + + /// <summary> + /// Unread counts per tab: lines shown there that arrived after it was last on + /// screen. Recounted only when the lines, the routes or the tabs change. + /// </summary> + private void UpdateUnread(ChatLine[] lines, long linesVersion, string current) + { + long newest = lines.Length > 0 ? lines[^1].Id : 0; + _seenId[current] = newest; + long routes = ChatModel.RoutesVersion, tabsVersion = ChatModel.FiltersVersion; + if (linesVersion == _unreadLines && routes == _unreadRoutes && tabsVersion == _unreadTabsVersion + && string.Equals(current, _unreadTab, StringComparison.Ordinal)) return; + _unreadLines = linesVersion; + _unreadRoutes = routes; + _unreadTabsVersion = tabsVersion; + _unreadTab = current; + _unread.Clear(); + foreach (string tab in ChatModel.AllTabs()) + { + if (!_seenId.TryGetValue(tab, out long seen)) { _seenId[tab] = newest; continue; } // a new tab starts read + int count = 0; + bool mention = false; + for (int i = lines.Length - 1; i >= 0 && lines[i].Id > seen; i--) + if (ChatModel.LineInTab(lines[i], tab)) { count++; mention |= lines[i].Route.Mention; } + if (count > 0) _unread[tab] = (count, mention); + } + } + + private void DrawSearch(Vector2 p, float w) + { + bool hasText = _search[0] != 0; + TextBox("##chat_search", _search, p, hasText ? w - 24 : w, SearchHint, out _); + if (hasText) + { + if (IconButton("##chat_search_x", PhosphorIcons.X, new Vector2(p.X + w - 22, p.Y), new Vector2(22, 22), Mute, BtnFill, font: UiFont.Ui10)) + WriteUtf8(_search, ""); + ImGuiNET.ImGui.SetItemTooltip("Clear the search"); + } + } + + // ── Lines ──────────────────────────────────────────────────────────── + + /// <summary>Brings _vis up to date with the snapshot, tab, search and routes.</summary> + private void SyncLines(UiSnapshot<ChatLine[]>? snap, ChatLine[] lines, string tab) + { + string search = Utf8(_search); + long routes = ChatModel.RoutesVersion; + + if (routes != _seenRoutes || tab != _seenTab || search != _seenSearch) + { + _seenRoutes = routes; + _seenTab = tab; + _seenSearch = search; + _seenLinesVersion = snap?.Version ?? -1; + _vis.Clear(); + _h.Clear(); + _lay.Clear(); + foreach (ChatLine line in lines) + if (ChatModel.LineVisible(line, tab, search)) { _vis.Add(line); _h.Add(0); _lay.Add(null); } + _lastId = lines.Length > 0 ? lines[^1].Id : _lastId; + _heightsFrom = 0; + _topsDirty = true; + ClearSelection(); + _stick = true; // a rebuild re-pins to the newest line + _droppedAbove = 0f; + return; + } + if (snap == null || snap.Version == _seenLinesVersion) return; + _seenLinesVersion = snap.Version; + + // Drop lines the source no longer keeps, then add the new ones. + long oldest = lines.Length > 0 ? lines[0].Id : long.MaxValue; + int drop = 0; + while (drop < _vis.Count && _vis[drop].Id < oldest) drop++; + if (drop > 0 && !_selDragging) + { + if (!Following) + for (int i = 0; i < drop; i++) _droppedAbove += _h[i]; + _vis.RemoveRange(0, drop); + _h.RemoveRange(0, drop); + _lay.RemoveRange(0, drop); + _heightsFrom = Math.Max(0, _heightsFrom - drop); + if (_selAnchor >= 0) { _selAnchor -= drop; _selEnd -= drop; if (_selAnchor < 0 || _selEnd < 0) ClearSelection(); } + _topsDirty = true; + } + foreach (ChatLine line in lines) + { + if (line.Id <= _lastId) continue; + _lastId = line.Id; + if (!ChatModel.LineVisible(line, tab, search)) continue; + if (_heightsFrom > _vis.Count) _heightsFrom = _vis.Count; + _vis.Add(line); + _h.Add(0); + _lay.Add(null); + _topsDirty = true; + } + } + + /// <summary>The view follows the newest line (auto-scroll on and not scrolled away).</summary> + private bool Following => ChatModel.AutoScroll && _stick; + + private void DrawLines(Vector2 size) + { + // Lines left the top of a full buffer while not following: scroll up by as much + // in THIS frame's BeginChild. (SetScrollY only lands in the next frame's Begin, + // after this frame has drawn the shortened list at the old scroll - the text + // jumped up for a frame and a strip at the bottom went blank, several times a + // second in busy chat.) A frame with wheel input waits a frame: this would + // override the wheel's own scroll. + bool compensated = false; + if (_droppedAbove > 0f) + { + if (Following) _droppedAbove = 0f; + else if (ImGuiNET.ImGui.GetIO().MouseWheel == 0f) + { + ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, Math.Max(0f, _lastScrollY - _droppedAbove))); + _droppedAbove = 0f; + compensated = true; + } + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ScrollbarBg, 0u); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0, 0)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, 10f); + bool open = ImGuiNET.ImGui.BeginChild("##chat_lines", size, ImGuiChildFlags.None, ImGuiWindowFlags.AlwaysVerticalScrollbar); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) { ImGuiNET.ImGui.EndChild(); return; } + + float fontSize = ChatModel.FontSize; + ImFontPtr font = ImGuiFonts.Chat(fontSize); + ImGuiNET.ImGui.PushFont(font); + bool showTs = ChatModel.ShowTimestamps; + float wrapW = Math.Max(20, ImGuiNET.ImGui.GetContentRegionAvail().X - 6); + // The text starts after the timestamp and wraps under itself. + float tsW = showTs ? ImGuiNET.ImGui.CalcTextSize("00:00:00 ").X : 0; + float textW = Math.Max(20, wrapW - tsW); + if (wrapW != _seenWrap || fontSize != _seenFont || showTs != _seenTs) + { + _seenWrap = wrapW; + _seenFont = fontSize; + _seenTs = showTs; + _heightsFrom = 0; + } + if (_heightsFrom < _vis.Count) + { + for (int i = _heightsFrom; i < _vis.Count; i++) + { + ChatLine line = _vis[i]; + ChatSpan[]? spans = line.Route.Spans; + if (spans != null) + { + SpanLayout lay = LayoutSpans(font, line.Text, spans, textW); + _lay[i] = lay; + _h[i] = lay.Height; + } + else + { + _lay[i] = null; + _h[i] = ImGuiNET.ImGui.CalcTextSize(line.Text, false, textW).Y; + } + } + _heightsFrom = _vis.Count; + _topsDirty = true; + } + if (_topsDirty) + { + if (_tops.Length < _vis.Count + 1) _tops = new float[Math.Max(_vis.Count + 1, _tops.Length * 2)]; + _tops[0] = 0; + for (int i = 0; i < _vis.Count; i++) _tops[i + 1] = _tops[i] + _h[i]; + _topsDirty = false; + } + int n = _vis.Count; + float total = _tops[n]; + + // Following the tail until the user scrolls away from it. + float scrollY = ImGuiNET.ImGui.GetScrollY(), maxY = ImGuiNET.ImGui.GetScrollMaxY(); + if (compensated) _lastScrollY = scrollY; // our move, not the user's + // Wheel up over the chat stops following at once; reaching the bottom again resumes it. + // Not while it has nothing to scroll: no scroll change would ever turn following back on. + if (maxY > 0f && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.GetIO().MouseWheel > 0f) + _stick = false; + else if (Math.Abs(scrollY - _lastScrollY) > 0.5f) + _stick = scrollY >= maxY - StickThreshold; + + Vector2 basePos = ImGuiNET.ImGui.GetCursorScreenPos(); + float viewH = ImGuiNET.ImGui.GetWindowHeight(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + int first = FirstAtOrBelow(scrollY, n); + int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd); + for (int i = first; i < n && _tops[i] < scrollY + viewH; i++) + { + Vector2 p = basePos + new Vector2(0, _tops[i]); + ChatLine line = _vis[i]; + ChatRoute route = line.Route; + if (route.Mention) + dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), MentionBg); + if (lo >= 0 && i >= lo && i <= hi) + dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), SelBg); + uint col = RynthTheme.Argb(ChatModel.LineArgb(line)); + if (showTs) dl.AddText(font, font.FontSize, p + new Vector2(3, 0), TsColor, line.Timestamp); + Vector2 tp = p + new Vector2(3 + tsW, 0); + SpanLayout? lay = _lay[i]; + if (lay == null) + dl.AddText(font, font.FontSize, tp, col, line.Text, textW); + else + foreach (Seg seg in lay.Segs) + dl.AddText(font, font.FontSize, tp + seg.Offset, seg.Argb == 0 ? col : RynthTheme.Argb(seg.Argb), seg.Text); + } + ImGuiNET.ImGui.Dummy(new Vector2(wrapW, Math.Max(1, total))); + HandleSelection(basePos, wrapW, scrollY, viewH, n); + HandleLineMenu(basePos, wrapW, n); + + _lastScrollY = scrollY; + if (ChatModel.AutoScroll && _stick && !_selDragging && total > viewH) + ImGuiNET.ImGui.SetScrollHereY(1f); + + // "Copied N lines" / "Rule added", top-right, for a moment. + if (_flash != null) + { + if (ImGuiNET.ImGui.GetTime() > _flashUntil) _flash = null; + else + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_flash); + Vector2 wp = ImGuiNET.ImGui.GetWindowPos(); + Vector2 fp = new(Math.Max(wp.X + 2, wp.X + wrapW - ts.X - 12), wp.Y + 4); + dl.AddRectFilled(fp, fp + ts + new Vector2(12, 4), FlashBg, 3); + dl.AddText(fp + new Vector2(6, 2), Text, _flash); + ImGuiNET.ImGui.PopFont(); + } + } + + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.EndChild(); + } + + private void Flash(string message, double seconds = 2.0) + { + _flash = message; + _flashUntil = ImGuiNET.ImGui.GetTime() + seconds; + } + + // ── Highlighted lines: hand layout ─────────────────────────────────── + + private readonly record struct Seg(string Text, Vector2 Offset, uint Argb); // Argb 0 = the line's colour + + private sealed class SpanLayout + { + public required float Height; + public required Seg[] Segs; + } + + /// <summary> + /// Word-wraps <paramref name="text"/> to <paramref name="wrapW"/> and cuts each + /// row where a highlight starts or ends, so every run is drawn in its own + /// colour. Called when a line is measured, never per frame. + /// </summary> + private static SpanLayout LayoutSpans(ImFontPtr font, string text, ChatSpan[] spans, float wrapW) + { + float size = font.FontSize; + float Width(int start, int end) => end <= start ? 0 : font.CalcTextSizeA(size, float.MaxValue, 0f, text[start..end]).X; + + // Rows as [start, end) character ranges. + var rows = new List<(int Start, int End)>(); + int rowStart = 0; + float x = 0; + int i = 0; + while (i < text.Length) + { + if (text[i] == '\n') { rows.Add((rowStart, i)); rowStart = i + 1; x = 0; i++; continue; } + // A word and the spaces after it. + int j = i; + while (j < text.Length && text[j] != ' ' && text[j] != '\n') j++; + while (j < text.Length && text[j] == ' ') j++; + float ww = Width(i, j); + int wordEnd = j; + while (wordEnd > i && text[wordEnd - 1] == ' ') wordEnd--; + float inkW = Width(i, wordEnd); + if (x > 0 && x + inkW > wrapW) + { + rows.Add((rowStart, i)); + rowStart = i; + x = 0; + } + if (x == 0 && inkW > wrapW) + { + // A word wider than the row: break it by characters. + int k = i; + while (k < wordEnd) + { + int m = k + 1; + while (m < wordEnd && Width(k, m + 1) <= wrapW) m++; + if (m < wordEnd) { rows.Add((rowStart, m)); rowStart = m; } + else x = Width(k, j); + k = m; + } + i = j; + continue; + } + x += ww; + i = j; + } + rows.Add((rowStart, text.Length)); + + var segs = new List<Seg>(); + for (int r = 0; r < rows.Count; r++) + { + (int a, int b) = rows[r]; + float y = r * size, sx = 0; + int c = a; + foreach (ChatSpan span in spans) + { + int s0 = Math.Max(span.Start, a), s1 = Math.Min(span.Start + span.Length, b); + if (s1 <= s0) continue; + if (s0 > c) { segs.Add(new Seg(text[c..s0], new Vector2(sx, y), 0)); sx += Width(c, s0); } + segs.Add(new Seg(text[s0..s1], new Vector2(sx, y), span.Argb)); + sx += Width(s0, s1); + c = s1; + } + if (c < b) segs.Add(new Seg(text[c..b], new Vector2(sx, y), 0)); + } + return new SpanLayout { Height = Math.Max(1, rows.Count) * size, Segs = segs.ToArray() }; + } + + /// <summary>Index of the line containing content y (clamped to the list).</summary> + private int FirstAtOrBelow(float y, int n) + { + int lo = 0, hi = n; // first i with _tops[i + 1] > y + while (lo < hi) + { + int mid = (lo + hi) >> 1; + if (_tops[mid + 1] > y) hi = mid; else lo = mid + 1; + } + return Math.Min(lo, Math.Max(0, n - 1)); + } + + private void HandleSelection(Vector2 basePos, float wrapW, float scrollY, float viewH, int n) + { + if (n == 0) { ClearSelection(); return; } + Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); + float contentY = mouse.Y - basePos.Y; + if (!_selDragging) + { + if (!ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left) + || !ImGuiNET.ImGui.IsWindowHovered() + || mouse.X > basePos.X + wrapW + 6) // the scrollbar + return; + ClearSelection(); + if (contentY < 0 || contentY >= _tops[n]) return; + _selAnchor = _selEnd = FirstAtOrBelow(contentY, n); + _selDragging = true; + _selMoved = false; + _selDown = mouse; + return; + } + + if (Math.Abs(mouse.X - _selDown.X) > 3 || Math.Abs(mouse.Y - _selDown.Y) > 3) _selMoved = true; + _selEnd = FirstAtOrBelow(Math.Clamp(contentY, 0, _tops[n] - 1), n); + + // Dragging past the edges scrolls. + Vector2 wp = ImGuiNET.ImGui.GetWindowPos(); + if (mouse.Y < wp.Y) ImGuiNET.ImGui.SetScrollY(Math.Max(0, scrollY - 12)); + else if (mouse.Y > wp.Y + viewH) ImGuiNET.ImGui.SetScrollY(scrollY + 12); + + if (ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) return; + _selDragging = false; + // A drag (even within one line) copies; a plain click just clears. + if (!_selMoved && _selEnd == _selAnchor) { ClearSelection(); return; } + int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd); + var parts = new List<string>(hi - lo + 1); + for (int i = lo; i <= hi && i < _vis.Count; i++) parts.Add(CopyText(_vis[i])); + Flash(ChatModel.CopyLines(parts), 1.5); + } + + private static string CopyText(ChatLine line) => ChatModel.ShowTimestamps ? line.FormattedText : line.Text; + + /// <summary>Right-click on a line: its menu (drawn in DrawPopups).</summary> + private void HandleLineMenu(Vector2 basePos, float wrapW, int n) + { + if (n == 0 || _selDragging || !ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right) || !ImGuiNET.ImGui.IsWindowHovered()) + return; + Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); + float contentY = mouse.Y - basePos.Y; + if (mouse.X > basePos.X + wrapW + 6 || contentY < 0 || contentY >= _tops[n]) return; + _ctxLine = _vis[FirstAtOrBelow(contentY, n)]; + _ctxPattern = ChatModel.PatternFor(_ctxLine); + _ctxCoords = ImGuiPanelHost.HasFace(RynthNavFace.Title) ? ChatCoords.Find(_ctxLine.Text) : new List<ChatCoord>(); + _openLineMenu = true; + } + + private void ClearSelection() + { + _selAnchor = _selEnd = -1; + _selDragging = _selMoved = false; + } + + // ── Input ──────────────────────────────────────────────────────────── + + private void DrawInput(Vector2 p, float w, float h) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float tellW = ButtonWidth("Tell"); + float boxW = Math.Max(20, w - tellW - 4); + bool typing = Win32Backend.ChatCaptureActive; + + ImGuiNET.ImGui.SetCursorScreenPos(p); + if (ImGuiNET.ImGui.InvisibleButton("##chat_input", new Vector2(boxW, h))) + ChatModel.BeginTyping(); + if (!typing && ChatHooks.RynthChatOwnsChat) ImGuiNET.ImGui.SetItemTooltip("Click or press Enter to chat"); + dl.AddRectFilled(p, p + new Vector2(boxW, h), InputBg, 3); + dl.AddRect(p, p + new Vector2(boxW, h), typing ? InputActive : InputBorder, 3); + + string text = ChatModel.InputText; + float fh = ImGuiNET.ImGui.GetFontSize(); + float ty = p.Y + (h - fh) * 0.5f; + dl.PushClipRect(p + new Vector2(2, 1), p + new Vector2(boxW - 2, h - 1), true); + if (text.Length == 0 && !typing) + { + _inputScroll = 0; + dl.AddText(new Vector2(p.X + 5, ty), Faded(Mute), ChatModel.InputHint ?? "Press Enter to chat…"); + } + else + { + int cursor = Math.Clamp(ChatModel.InputCursor, 0, text.Length); + float caretX = cursor == 0 ? 0 : ImGuiNET.ImGui.CalcTextSize(text[..cursor]).X; + float room = boxW - 12; + if (caretX - _inputScroll > room) _inputScroll = caretX - room; + if (caretX < _inputScroll) _inputScroll = caretX; + float tx = p.X + 5 - _inputScroll; + dl.AddText(new Vector2(tx, ty), Text, text); + if (typing && ImGuiNET.ImGui.GetTime() % 1.0 < 0.6) + dl.AddLine(new Vector2(tx + caretX, ty), new Vector2(tx + caretX, ty + fh), Text); + } + dl.PopClipRect(); + + if (Button("##chat_tell", "Tell", new Vector2(p.X + boxW + 4, p.Y), new Vector2(tellW, h), Text, TellBg)) + Win32Backend.RequestTellSelected(); + ImGuiNET.ImGui.SetItemTooltip("Select an NPC or player in the game, then click to start /tell <name>, — or type /tell and press Enter."); + } + + // ── Rules from a line ──────────────────────────────────────────────── + + private void RuleFromLine(ChatRuleAction action, string? tab) + { + var rule = new ChatFilterRule { Pattern = _ctxPattern, Action = action, Tab = tab ?? "" }; + if (action == ChatRuleAction.Color) + { + rule.ColorMode = ChatColorMode.Line; + ChatModel.AddRule(rule); + if (!ImGuiPanelHost.IsOpen("ChatFilters")) PanelRouter.Toggle("ChatFilters"); + Flash("Rule added - pick its colour in Filters"); + return; + } + ChatModel.AddRule(rule); + Flash(action switch + { + ChatRuleAction.Move => $"Rule added: lines like this move to {tab}", + ChatRuleAction.Copy => $"Rule added: lines like this also show in {tab}", + _ => "Rule added: lines like this are hidden (undo in Filters)", + }, 3); + } + + private void TabMenu(string id, ChatRuleAction action) + { + if (!ImGuiNET.ImGui.BeginMenu(id)) return; + foreach (string t in ChatModel.TargetTabs()) + if (ImGuiNET.ImGui.MenuItem(t)) RuleFromLine(action, t); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("New tab…")) + { + _pendingRule = new ChatFilterRule { Pattern = _ctxPattern, Action = action }; + WriteUtf8(_newTab, ""); + _openNewTab = _focusNewTab = true; + } + ImGuiNET.ImGui.EndMenu(); + } + + // ── Popups ─────────────────────────────────────────────────────────── + + private void DrawPopups() + { + if (_openSettings) + { + _openSettings = false; + WriteUtf8(_mentionWords, ChatModel.MentionWords); + ImGuiNET.ImGui.OpenPopup("##chat_settings"); + } + if (_openNewTab) { _openNewTab = false; ImGuiNET.ImGui.OpenPopup("##chat_newtab"); } + if (_openTabMenu) { _openTabMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_tabmenu"); } + if (_openLineMenu) { _openLineMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_linemenu"); } + if (_openRename) { _openRename = false; ImGuiNET.ImGui.OpenPopup("##chat_rename"); } + + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, RynthTheme.Argb(0xF2060C14)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, TabActive); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrabActive, Amber); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, TabActive); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8)); + + DrawSettingsPopup(); + DrawNewTabPopup(); + DrawTabMenu(); + DrawRenamePopup(); + DrawLineMenu(); + + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(8); + } + + private void DrawSettingsPopup() + { + if (!ImGuiNET.ImGui.BeginPopup("##chat_settings")) return; + ImGuiNET.ImGui.PushItemWidth(150); + int font = (int)MathF.Round(ChatModel.FontSize); + if (ImGuiNET.ImGui.SliderInt("Font size", ref font, 8, 18)) ChatModel.FontSize = font; + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatModel.SaveSettings(); + int pct = (int)MathF.Round(ChatModel.BackgroundAlpha / 2.55f); + if (ImGuiNET.ImGui.SliderInt("Background", ref pct, 0, 100, "%d%%")) + ChatModel.BackgroundAlpha = (int)MathF.Round(pct * 2.55f); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatModel.SaveSettings(); + ImGuiNET.ImGui.PopItemWidth(); + + bool ts = ChatModel.ShowTimestamps; + if (ImGuiNET.ImGui.Checkbox("Timestamps", ref ts)) + { + ChatModel.ShowTimestamps = ts; + ChatModel.SaveSettings(); + } + bool auto = ChatModel.AutoScroll; + if (ImGuiNET.ImGui.Checkbox("Auto-scroll", ref auto)) + { + ChatModel.AutoScroll = auto; + if (auto) _stick = true; + ChatModel.SaveSettings(); + } + bool hide = ChatHooks.SuppressOriginalChat; + if (ImGuiNET.ImGui.Checkbox("Hide retail chat (Enter types here)", ref hide)) + { + ChatHooks.SuppressOriginalChat = hide; + ChatModel.SaveSettings(); + } + ImGuiNET.ImGui.SetItemTooltip("On: the retail chatbox is hidden and Enter types in RynthChat.\n" + + "Off: the retail chatbox is shown and Enter types there; RynthChat keeps showing lines and its Tell button still works."); + bool log = ChatModel.LogEnabled; + if (ImGuiNET.ImGui.Checkbox("Log to file", ref log)) + { + ChatModel.LogEnabled = log; + ChatModel.SaveSettings(); + } + ImGuiNET.ImGui.SetItemTooltip("%AppData%\\RynthCore\\ChatLogs\\<character>.log"); + bool through = ChatModel.CtrlGatedClickThrough; + if (ImGuiNET.ImGui.Checkbox("Click-through (hold Ctrl to interact)", ref through)) + ChatModel.SetCtrlGatedClickThrough(through); + ImGuiNET.ImGui.SetItemTooltip("Docked chat only; popped out it's always interactive.\n" + + "On: clicks pass through to the game; hold Ctrl to use the chat."); + + ImGuiNET.ImGui.Separator(); + bool mention = ChatModel.MentionHighlight; + if (ImGuiNET.ImGui.Checkbox("Highlight my name", ref mention)) + { + ChatModel.MentionHighlight = mention; + ChatModel.FiltersChanged(); // re-highlights the kept lines + } + ImGuiNET.ImGui.SetItemTooltip("When another player's chat or channel line says your character's name\n" + + "(or a word below), the name is highlighted, the line tinted and the tab's count turns gold."); + if (mention) + { + Label("Also highlight (comma-separated):", Mute); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + TextBox("##mention_words", _mentionWords, p, 230, "e.g. Drak, buffs", out _); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + ChatModel.MentionWords = Utf8(_mentionWords).Trim(); + ChatModel.FiltersChanged(); + } + NextLine(p, 26); + bool sound = ChatModel.MentionSound; + if (ImGuiNET.ImGui.Checkbox("Beep when mentioned", ref sound)) + { + ChatModel.MentionSound = sound; + ChatModel.SaveSettings(); + } + } + if (!ChatModel.PluginBound) Label("Plugin not bound", Mute); + ImGuiNET.ImGui.EndPopup(); + } + + private void DrawNewTabPopup() + { + if (!ImGuiNET.ImGui.BeginPopup("##chat_newtab")) + { + _pendingRule = null; + return; + } + if (_pendingRule != null) + Label(_pendingRule.Action == ChatRuleAction.Copy ? "New tab for a copy of lines like this:" : "New tab for lines like this:", Mute); + if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; } + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool enter = TextBox("##newtab_name", _newTab, p, 120, "tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20); + bool add = Button("##newtab_add", "Add", new Vector2(p.X + 124, p.Y), new Vector2(ButtonWidth("Add"), 20), Text, TabActive); + bool cancel = Button("##newtab_cancel", "Cancel", new Vector2(p.X + 128 + ButtonWidth("Add"), p.Y), new Vector2(ButtonWidth("Cancel"), 20), Text, BtnFill); + NextLine(p, 20); + if (enter || add) + { + ChatFilterRule? pending = _pendingRule; + string? name = ChatModel.AddCustomTab(Utf8(_newTab), select: pending == null); + if (name != null && pending != null) + { + pending.Tab = name; + ChatModel.AddRule(pending); + Flash(pending.Action == ChatRuleAction.Copy + ? $"Rule added: lines like this also show in {name}" + : $"Rule added: lines like this move to {name}", 3); + } + _pendingRule = null; + ImGuiNET.ImGui.CloseCurrentPopup(); + } + else if (cancel || ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape)) + { + _pendingRule = null; + ImGuiNET.ImGui.CloseCurrentPopup(); + } + ImGuiNET.ImGui.EndPopup(); + } + + private void DrawTabMenu() + { + if (!ImGuiNET.ImGui.BeginPopup("##chat_tabmenu")) return; + string tab = _ctxTab ?? ""; + Label(tab, Teal); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Mark as read")) + { + var lines = UiSources.Chat.Current?.Value; + _seenId[tab] = lines is { Length: > 0 } ? lines[^1].Id : 0; + _unread.Remove(tab); + } + if (ImGuiNET.ImGui.MenuItem("Mark all tabs read")) + { + var lines = UiSources.Chat.Current?.Value; + long newest = lines is { Length: > 0 } ? lines[^1].Id : 0; + foreach (string t in ChatModel.AllTabs()) _seenId[t] = newest; + _unread.Clear(); + } + if (!ChatModel.IsBaseTab(tab)) + { + if (ImGuiNET.ImGui.MenuItem("Rename…")) + { + _renameFrom = tab; + WriteUtf8(_newTab, tab); + _openRename = _focusNewTab = true; + } + if (ImGuiNET.ImGui.MenuItem("Delete tab")) ChatModel.DeleteCustomTab(tab); + } + if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters")) + PanelRouter.Toggle("ChatFilters"); + ImGuiNET.ImGui.EndPopup(); + } + + private void DrawRenamePopup() + { + if (!ImGuiNET.ImGui.BeginPopup("##chat_rename")) return; + Label($"Rename \"{_renameFrom}\" (its rules follow):", Mute); + if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; } + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool enter = TextBox("##rename_name", _newTab, p, 140, "tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20); + bool ok = Button("##rename_ok", "Rename", new Vector2(p.X + 144, p.Y), new Vector2(ButtonWidth("Rename"), 20), Text, TabActive); + NextLine(p, 20); + if (enter || ok) + { + if (_renameFrom != null && !ChatModel.RenameCustomTab(_renameFrom, Utf8(_newTab))) + Flash("That name is taken (or blank)"); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + else if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape)) + ImGuiNET.ImGui.CloseCurrentPopup(); + ImGuiNET.ImGui.EndPopup(); + } + + private void DrawLineMenu() + { + ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(200, 0), new Vector2(420, float.MaxValue)); + if (!ImGuiNET.ImGui.BeginPopup("##chat_linemenu")) return; + ChatLine? line = _ctxLine; + if (line == null) { ImGuiNET.ImGui.EndPopup(); return; } + // Coordinates in the line: point RynthNav's arrow there, or walk there (left-click + // selects lines, so this lives in the right-click menu). + for (int i = 0; i < _ctxCoords.Count && i < 3; i++) + { + ChatCoord c = _ctxCoords[i]; + ImGuiNET.ImGui.PushID(i); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.NavigationArrow + " Arrow to " + c.Text)) + RynthNavCommands.Arrow(c.Text, c.Ns, c.Ew); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Play + " Go to " + c.Text)) + RynthNavCommands.Go(c.Text, c.Ns, c.Ew); + ImGuiNET.ImGui.PopID(); + } + if (_ctxCoords.Count > 0) ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Copy line")) Flash(ChatModel.CopyLines(new[] { CopyText(line) }), 1.5); + ImGuiNET.ImGui.Separator(); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 400); + ImGuiNET.ImGui.TextUnformatted("Lines like this: " + _ctxPattern); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + TabMenu("Move them to", ChatRuleAction.Move); + TabMenu("Also show them in", ChatRuleAction.Copy); + if (ImGuiNET.ImGui.MenuItem("Hide them")) RuleFromLine(ChatRuleAction.Hide, null); + if (ImGuiNET.ImGui.MenuItem("Colour them…")) RuleFromLine(ChatRuleAction.Color, null); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters")) + PanelRouter.Toggle("ChatFilters"); + ImGuiNET.ImGui.EndPopup(); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs new file mode 100644 index 0000000..e07110c --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -0,0 +1,599 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ChatFiltersFace.cs +// ImGui face of the RynthChat rule editor (the old Avalonia face is +// UI/Panels/RynthChatFiltersPanel.cs). One card per rule: +// +// [#] [on] [regex ..........................] [up] [down] [delete] +// When [Any line v] [Move to v] [Junk v] [Colour line v] [swatch] +// (a regex error, a timed-out rule, a missing tab, or its hit count) +// +// The order and what each action does are spelled out in the header lines +// (and in UI/Data/ChatData.cs). Below the rules: Add, Import / Export (the +// clipboard, JSON), and a test box - paste a line, pick where it came from, +// and see which rules match and where it ends up. The test runs on an edit, +// never per frame; the chat itself is routed on the pump. +// +// The rules live in ChatModel. Each edit applies (the pump re-routes the +// kept lines within 100 ms) and saves at once. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class ChatFiltersFace : IImGuiPanel +{ + public const string Title = "ChatFilters"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(600, 460), new Vector2(440, 260), EdgeToEdge: true, GripInBody: true), + () => new ChatFiltersFace()); + + private static readonly uint AddBg = RynthTheme.Argb(0xFF264C59), CardBg = RynthTheme.Argb(0xFF0E1822), + FocusBorder = RynthTheme.Argb(0xFFFFD700); + + private sealed class Buffers + { + public readonly byte[] Pattern = new byte[1024]; + public bool Active; + } + + private readonly Dictionary<ChatFilterRule, Buffers> _bufs = new(); + private long _seenVersion = -1; + private readonly Picker _picker = new("##chatrule_pick"); + private string? _flash; + private double _flashUntil; + private ChatFilterRule? _focus; + private double _focusUntil; + private bool _scrollToFocus; + private ChatFilterRule? _newTabFor; + private bool _openNewTab, _focusNewTab; + private readonly byte[] _newTab = new byte[64]; + + // Test box: re-evaluated when the text, its source or the rules change. + private readonly byte[] _test = new byte[512]; + private int _testSource = 1; // index into ChatModel.Conditions (not 0, "any") + private string _testSeen = ""; + private int _testSourceSeen = -1; + private long _testVersion = -1; + private readonly List<(string Text, uint Color)> _testResult = new(); + + public void OnShown() => ChatModel.EnsureSettingsLoaded(); + + private const string AddLabel = PhosphorIcons.Plus + " Add rule"; + private const string ImportLabel = PhosphorIcons.ClipboardText + " Import"; + private const string ExportLabel = PhosphorIcons.Copy + " Export"; + private const string Caret = " " + PhosphorIcons.CaretDown; + + private static readonly string[] ActionLabels = { "Move to", "Copy to", "Hide", "Colour only" }; + private static readonly string[] ActionHelp = + { + "Move: the line shows ONLY in the chosen tab (it leaves All and its channel tab).", + "Copy: the line also shows in the chosen tab (it stays where it was).", + "Hide: the line is not shown anywhere (the chat log still has it).", + "Colour only: no routing; the rule just colours.", + }; + private static readonly string[] ColorLabels = { "No colour", "Colour line", "Colour match" }; + /// <summary>Indexed by <see cref="ChatMatchMode"/>.</summary> + private static readonly string[] ModeLabels = { "Regex", "Contains", "Starts with", "Ends with" }; + + public void Draw() + { + float w = Begin(out Vector2 origin, out Vector2 size); + ChatFilterRule[] rules = ChatModel.Filters; + SyncBuffers(rules); + if (ChatModel.FocusRule is { } focus) + { + ChatModel.FocusRule = null; + _focus = focus; + _focusUntil = ImGuiNET.ImGui.GetTime() + 2.5; + _scrollToFocus = true; + } + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + Label("Rules run top to bottom (" + PhosphorIcons.ArrowUp + PhosphorIcons.ArrowDown + " to reorder) on each line's text, as a case-insensitive regex.", Mute); + Label("Where it shows: Copy rules add a tab and go on; the first Move or Hide that matches decides.", Mute); + Label("Colour: the first \"Colour line\" wins; \"Colour match\" colours every match (a higher rule wins an overlap).", Mute); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); + + float testH = TestAreaHeight(); + Action? edit = null; + float listH = Math.Max(60, Remaining(origin, size) - 30 - testH); + ImGuiNET.ImGui.BeginChild("##filter_rows", new Vector2(w, listH)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal); + float rowW = ImGuiNET.ImGui.GetContentRegionAvail().X - 2; + for (int i = 0; i < rules.Length; i++) + { + ImGuiNET.ImGui.PushID(i); + DrawRule(rules, i, rowW, ref edit); + ImGuiNET.ImGui.PopID(); + } + if (rules.Length == 0) + { + Label("No rules yet. Click \"Add rule\", or right-click a line in the chat", Mute); + Label("and pick \"Move them to\", \"Hide them\" or \"Colour them\".", Mute); + } + DrawStandardFilters(rowW); + ImGuiNET.ImGui.PopStyleColor(2); + ImGuiNET.ImGui.EndChild(); + + // Add / Import / Export + Vector2 ap = ImGuiNET.ImGui.GetCursorScreenPos(); + float bx = ap.X; + if (Button("##add", AddLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(AddLabel) + 4, 24), Text, AddBg)) + { + // An empty pattern matches nothing until typed; saved now so the row survives a relaunch mid-edit. + var rule = new ChatFilterRule(); + edit = () => ChatModel.AddRule(rule); + } + bx += ButtonWidth(AddLabel) + 8; + if (Button("##import", ImportLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(ImportLabel), 24), Text, BtnFill)) + Flash(ChatModel.ImportRules(ChatModel.GetClipboardText())); + ImGuiNET.ImGui.SetItemTooltip("Add the rules on the clipboard (an Export, or a rynthchat_settings.json) after these."); + bx += ButtonWidth(ImportLabel) + 4; + if (Button("##export", ExportLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(ExportLabel), 24), Text, BtnFill, rules.Length > 0)) + Flash(ChatModel.SetClipboardText(ChatModel.ExportRules()) + ? $"Copied {rules.Length} rule{(rules.Length == 1 ? "" : "s")} to the clipboard" + : "Clipboard busy - try again"); + ImGuiNET.ImGui.SetItemTooltip("Copy every rule and your tabs to the clipboard as JSON, to share or keep."); + bx += ButtonWidth(ExportLabel) + 8; + if (_flash != null) + { + if (ImGuiNET.ImGui.GetTime() > _flashUntil) _flash = null; + else ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(bx, ap.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Amber, _flash); + } + NextLine(ap, 28); + + DrawTest(w); + + End(origin, size); + _picker.Draw(); + DrawNewTabPopup(); + edit?.Invoke(); // after drawing: the rows above drew from the old list + } + + // ── Standard filters (RynthChatPresets) ────────────────────────────── + + /// <summary> + /// The canned filters, by group: tick to hide, or pick a tab to move the lines there. + /// The router checks them after the rules, for lines no rule moved or hid. + /// </summary> + private void DrawStandardFilters(float rowW) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + if (!ImGuiNET.ImGui.CollapsingHeader("Standard filters##std")) return; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + Label("Checked after the rules above, only for lines no rule moved or hid.", Mute); + Label("Tick to hide the lines; pick a tab to move them there instead.", Mute); + ImGuiNET.ImGui.PopFont(); + foreach (string group in UI.Panels.RynthChatPresets.Groups) + { + int on = 0, total = 0; + foreach (var p in UI.Panels.RynthChatPresets.All) + if (p.Group == group) { total++; if (p.Enabled) on++; } + if (!ImGuiNET.ImGui.TreeNode($"{group} ({on}/{total})###grp_{group}")) continue; + foreach (var p in UI.Panels.RynthChatPresets.All) + { + if (p.Group != group) continue; + ImGuiNET.ImGui.PushID(p.Id); + bool enabled = p.Enabled; + if (ImGuiNET.ImGui.Checkbox(p.Label, ref enabled)) { p.Enabled = enabled; ChatModel.FiltersChanged(); } + ImGuiNET.ImGui.SetItemTooltip(p.Description + "\nExample: " + p.Example); + ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, rowW * 0.6f)); + string tabText = (p.Tab.Length == 0 ? "hide" : "to " + p.Tab) + Caret; + if (ImGuiNET.ImGui.SmallButton(tabText)) + OpenPresetTabPicker(p, new Vector2(ImGuiNET.ImGui.GetItemRectMin().X, ImGuiNET.ImGui.GetItemRectMax().Y + 2)); + ImGuiNET.ImGui.SetItemTooltip("Where its lines go: hidden, or moved to a tab"); + ImGuiNET.ImGui.PopID(); + } + ImGuiNET.ImGui.TreePop(); + } + } + + private void OpenPresetTabPicker(UI.Panels.RynthChatPresets.Preset preset, Vector2 below) + { + string[] tabs = ChatModel.TargetTabs(); + var items = new string[tabs.Length + 1]; + items[0] = "Hide"; + Array.Copy(tabs, 0, items, 1, tabs.Length); + int selected = preset.Tab.Length == 0 ? 0 : Math.Max(0, Array.FindIndex(tabs, t => string.Equals(t, preset.Tab, StringComparison.OrdinalIgnoreCase)) + 1); + _picker.Open(below, items, selected, k => + { + preset.Tab = k <= 0 ? "" : items[k]; + ChatModel.FiltersChanged(); + }, 160); + } + + private void Flash(string message) + { + _flash = message; + _flashUntil = ImGuiNET.ImGui.GetTime() + 3; + } + + // ── One rule ───────────────────────────────────────────────────────── + + private void DrawRule(ChatFilterRule[] rules, int i, float rowW, ref Action? edit) + { + ChatFilterRule r = rules[i]; + Buffers b = _bufs[r]; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 card = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.ChannelsSplit(2); + dl.ChannelsSetCurrent(1); + const float rowH = 22; + + // Row 1: number, on, pattern, up, down, delete. + Vector2 p = card + new Vector2(4, 4); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + dl.AddText(new Vector2(p.X, p.Y + 5), Faded(Mute), (i + 1).ToString()); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 16, p.Y + 1)); + bool on = r.Enabled; + if (ImGuiNET.ImGui.Checkbox("##on", ref on)) { r.Enabled = on; ChatModel.FiltersChanged(); } + ImGuiNET.ImGui.SetItemTooltip(on ? "Rule on (click to turn off)" : "Rule off (click to turn on)"); + + const float btn = 22; + float x = p.X + 42; + float patW = Math.Max(80, card.X + rowW - 4 - 3 * (btn + 2) - 4 - x); + if (TextBox("##pat", b.Pattern, new Vector2(x, p.Y), patW, "regex, e.g. ^You have been healed", out bool patActive)) + { + r.Pattern = Utf8(b.Pattern); + r.Recompile(); + ChatModel.FiltersChanged(); + } + b.Active = patActive; + if (r.Invalid && r.Pattern.Length > 0) + dl.AddRect(new Vector2(x, p.Y), new Vector2(x + patW, p.Y + rowH), Red, 3); + else if (r.Slow) + dl.AddRect(new Vector2(x, p.Y), new Vector2(x + patW, p.Y + rowH), Amber, 3); + x += patW + 4; + ChatFilterRule rule = r; + if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x, p.Y), new Vector2(btn, rowH), Text, BtnFill, i > 0)) + edit = () => ChatModel.MoveFilter(rule, -1); + ImGuiNET.ImGui.SetItemTooltip("Move up (runs earlier)"); + x += btn + 2; + if (IconButton("##down", PhosphorIcons.ArrowDown, new Vector2(x, p.Y), new Vector2(btn, rowH), Text, BtnFill, i < rules.Length - 1)) + edit = () => ChatModel.MoveFilter(rule, +1); + ImGuiNET.ImGui.SetItemTooltip("Move down (runs later)"); + x += btn + 2; + if (IconButton("##del", PhosphorIcons.Trash, new Vector2(x, p.Y), new Vector2(btn, rowH), Red, BtnFill)) + edit = () => ChatModel.EditFilters(list => list.Remove(rule)); + ImGuiNET.ImGui.SetItemTooltip("Delete this rule"); + + // Row 2 (wraps when narrow): When, action, tab, colour mode, swatch. + float left = p.X + 42, right = card.X + rowW - 4; + var flow = new Flow(left, p.Y + rowH + 4, right, rowH); + + int matchMode = (int)r.Mode; + string modeText = ModeLabels[matchMode] + Caret; + Vector2 mPos = flow.Place(ButtonWidth(modeText)); + if (Button("##mode", modeText, mPos, new Vector2(ButtonWidth(modeText), rowH), Text, BtnFill)) + _picker.Open(mPos + new Vector2(0, rowH + 2), ModeLabels, matchMode, k => + { + rule.Mode = (ChatMatchMode)k; + rule.Recompile(); + ChatModel.FiltersChanged(); + }, 120); + ImGuiNET.ImGui.SetItemTooltip("How the pattern matches: a regex, or plain text anywhere / at the start / at the end of the line."); + + string whenText = "When: " + ChatModel.ConditionLabel(r.When) + Caret; + Vector2 wp = flow.Place(Math.Min(ButtonWidth(whenText), 240)); + if (Button("##when", whenText, wp, new Vector2(Math.Min(ButtonWidth(whenText), 240), rowH), Text, BtnFill, leftAlign: true)) + OpenWhenPicker(rule, wp); + ImGuiNET.ImGui.SetItemTooltip("Only lines from this channel or chat type (Any line: every line)"); + + int action = (int)r.Action; + string actText = ActionLabels[action] + Caret; + Vector2 aPos = flow.Place(ButtonWidth(actText)); + if (Button("##act", actText, aPos, new Vector2(ButtonWidth(actText), rowH), Text, BtnFill)) + _picker.Open(aPos + new Vector2(0, rowH + 2), ActionLabels, action, k => + { + rule.Action = (ChatRuleAction)k; + if (rule.Action == ChatRuleAction.Color && rule.ColorMode == ChatColorMode.None) rule.ColorMode = ChatColorMode.Line; + ChatModel.FiltersChanged(); + }, 140); + ImGuiNET.ImGui.SetItemTooltip(ActionHelp[action]); + + if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy) + { + bool noTab = r.Tab.Length == 0; + string tabText = (noTab ? "pick a tab" : r.Tab) + Caret; + Vector2 tPos = flow.Place(ButtonWidth(tabText)); + if (Button("##tab", tabText, tPos, new Vector2(ButtonWidth(tabText), rowH), noTab ? Amber : Teal, BtnFill)) + OpenTabPicker(rule, tPos); + ImGuiNET.ImGui.SetItemTooltip("The tab it goes to (pick \"New tab…\" to make one)"); + } + + if (r.Action != ChatRuleAction.Hide) + { + int mode = (int)r.ColorMode; + string colText = ColorLabels[mode] + Caret; + Vector2 cPos = flow.Place(ButtonWidth(colText)); + if (Button("##colmode", colText, cPos, new Vector2(ButtonWidth(colText), rowH), Text, BtnFill)) + _picker.Open(cPos + new Vector2(0, rowH + 2), ColorLabels, mode, k => + { + rule.ColorMode = (ChatColorMode)k; + ChatModel.FiltersChanged(); + }, 130); + ImGuiNET.ImGui.SetItemTooltip("Colour line: the whole line. Colour match: just the text the regex matched."); + if (r.ColorMode != ChatColorMode.None) + { + Vector2 sPos = flow.Place(rowH); + ImGuiNET.ImGui.SetCursorScreenPos(sPos + new Vector2(2, 2)); + Vector4 v = RynthTheme.Vec(r.ColorArgb); + var rgb = new Vector3(v.X, v.Y, v.Z); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 3)); + if (ImGuiNET.ImGui.ColorEdit3("##col", ref rgb, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) + { + r.ColorArgb = 0xFF000000 + | ((uint)Math.Clamp((int)MathF.Round(rgb.X * 255), 0, 255) << 16) + | ((uint)Math.Clamp((int)MathF.Round(rgb.Y * 255), 0, 255) << 8) + | (uint)Math.Clamp((int)MathF.Round(rgb.Z * 255), 0, 255); + ChatModel.FiltersChanged(); + } + ImGuiNET.ImGui.PopStyleVar(); + } + } + + // Row 3: what's wrong, or what it's doing. + float y = flow.Bottom + 3; + (string? note, uint noteColor) = RuleNote(r); + if (note != null) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + ImGuiNET.ImGui.PushClipRect(new Vector2(left, y), new Vector2(right, y + 40), true); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(left, y)); + ImGuiNET.ImGui.PushTextWrapPos(right - ImGuiNET.ImGui.GetWindowPos().X + ImGuiNET.ImGui.GetScrollX()); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, noteColor); + ImGuiNET.ImGui.TextUnformatted(note); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopTextWrapPos(); + y = ImGuiNET.ImGui.GetCursorScreenPos().Y; + ImGuiNET.ImGui.PopClipRect(); + ImGuiNET.ImGui.PopFont(); + } + float bottom = Math.Max(y, flow.Bottom + 2) + 4; + + // Card background under everything (channel 0), dimmed while off. + dl.ChannelsSetCurrent(0); + bool focused = ReferenceEquals(r, _focus) && ImGuiNET.ImGui.GetTime() < _focusUntil; + dl.AddRectFilled(card, new Vector2(card.X + rowW, bottom), r.Enabled ? CardBg : RowAlt, 4); + dl.AddRect(card, new Vector2(card.X + rowW, bottom), focused ? FocusBorder : BtnBord, 4); + dl.ChannelsMerge(); + if (!r.Enabled) + dl.AddRectFilled(card, new Vector2(card.X + rowW, bottom), RynthTheme.Argb(0x55000000), 4); + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(card.X, bottom)); + ImGuiNET.ImGui.Dummy(new Vector2(rowW, 4)); + if (_scrollToFocus && ReferenceEquals(r, _focus)) + { + _scrollToFocus = false; + ImGuiNET.ImGui.SetScrollHereY(1f); // bring the new rule into view + } + } + + private static (string? Note, uint Color) RuleNote(ChatFilterRule r) + { + if (r.Pattern.Length == 0) return ("Type a pattern: the rule matches nothing until then.", Faded(Mute)); + if (r.Invalid) return ("Regex error: " + (r.Error ?? "doesn't compile"), Red); + if (r.Slow) return ("Too slow: matching it took too long (see the RynthCore log), so the rule is skipped. Edit the pattern to try again.", Amber); + if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy && r.Tab.Length == 0) + return ("Pick a tab: until then it only colours.", Amber); + if (!r.Enabled) return ("Off.", Faded(Mute)); + int hits = System.Threading.Volatile.Read(ref r.Hits); + return (hits == 0 ? "No recent line matches." : $"Matches {hits} recent line{(hits == 1 ? "" : "s")}.", Faded(Mute)); + } + + /// <summary>Left-to-right placement that wraps to a new row when the next item doesn't fit.</summary> + private struct Flow + { + private readonly float _left, _right, _h; + private float _x, _y; + public Flow(float left, float top, float right, float h) { _left = _x = left; _right = right; _y = top; _h = h; } + public float Bottom => _y + _h; + + public Vector2 Place(float w) + { + if (_x > _left && _x + w > _right) { _x = _left; _y += _h + 3; } + var at = new Vector2(_x, _y); + _x += w + 4; + return at; + } + } + + private void OpenWhenPicker(ChatFilterRule rule, Vector2 at) + { + var labels = new string[ChatModel.Conditions.Length]; + int sel = 0; + for (int k = 0; k < labels.Length; k++) + { + labels[k] = ChatModel.Conditions[k].Label; + if (string.Equals(ChatModel.Conditions[k].Value, rule.When, StringComparison.OrdinalIgnoreCase)) sel = k; + } + _picker.Open(at + new Vector2(0, 24), labels, sel, k => + { + rule.When = ChatModel.Conditions[k].Value; + ChatModel.FiltersChanged(); + }, 260); + } + + private void OpenTabPicker(ChatFilterRule rule, Vector2 at) + { + string[] tabs = ChatModel.TargetTabs(); + var items = new string[tabs.Length + 1]; + Array.Copy(tabs, items, tabs.Length); + items[^1] = PhosphorIcons.Plus + " New tab…"; + int sel = Array.FindIndex(tabs, t => string.Equals(t, rule.Tab, StringComparison.OrdinalIgnoreCase)); + _picker.Open(at + new Vector2(0, 24), items, sel, k => + { + if (k == tabs.Length) + { + _newTabFor = rule; + WriteUtf8(_newTab, ""); + _openNewTab = _focusNewTab = true; + return; + } + rule.Tab = tabs[k]; + ChatModel.FiltersChanged(); + }, 180); + } + + private void DrawNewTabPopup() + { + if (_openNewTab) { _openNewTab = false; ImGuiNET.ImGui.OpenPopup("##chatrule_newtab"); } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 6)); + bool open = ImGuiNET.ImGui.BeginPopup("##chatrule_newtab"); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) return; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; } + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool enter = TextBox("##ruletab_name", _newTab, p, 140, "new tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20); + bool add = Button("##ruletab_add", "Add", new Vector2(p.X + 144, p.Y), new Vector2(ButtonWidth("Add"), 20), Text, AddBg); + NextLine(p, 20); + if (enter || add) + { + string? name = ChatModel.AddCustomTab(Utf8(_newTab), select: false); + if (name != null && _newTabFor != null) + { + _newTabFor.Tab = name; + ChatModel.FiltersChanged(); + } + _newTabFor = null; + ImGuiNET.ImGui.CloseCurrentPopup(); + } + else if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape)) + ImGuiNET.ImGui.CloseCurrentPopup(); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.EndPopup(); + } + + // ── Test box ───────────────────────────────────────────────────────── + + private float TestAreaHeight() + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + float lh = ImGuiNET.ImGui.GetTextLineHeightWithSpacing(); + ImGuiNET.ImGui.PopFont(); + return 16 + 26 + Math.Max(1, _testResult.Count) * lh + 4; + } + + private void DrawTest(float w) + { + Label("Test a line - paste one from the chat (right-click it, Copy line):", Mute); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + string srcLabel = "from: " + ChatModel.Conditions[_testSource].Label + Caret; + float srcW = Math.Min(ButtonWidth(srcLabel), 230); + TextBox("##test", _test, p, Math.Max(80, w - srcW - 4), "e.g. Bob tells you, \"hi\"", out _); + var sp = new Vector2(p.X + w - srcW, p.Y); + if (Button("##testsrc", srcLabel, sp, new Vector2(srcW, 22), Text, BtnFill, leftAlign: true)) + { + var labels = new string[ChatModel.Conditions.Length - 1]; + for (int k = 1; k < ChatModel.Conditions.Length; k++) labels[k - 1] = ChatModel.Conditions[k].Label; + _picker.Open(sp + new Vector2(0, 24), labels, _testSource - 1, k => _testSource = k + 1, 260); + } + ImGuiNET.ImGui.SetItemTooltip("Where the test line came from (for rules with a When)"); + NextLine(p, 26); + + string text = Utf8(_test); + long version = ChatModel.FiltersVersion; + if (text != _testSeen || _testSource != _testSourceSeen || version != _testVersion) + { + _testSeen = text; + _testSourceSeen = _testSource; + _testVersion = version; + RunTest(text); + } + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + // The result lines reach the body's bottom edge: a long one is cut short of + // the resize grip (GripInBody) instead of running under it. + float grip = ImGuiPanelHost.BodyGripReserve; + if (grip > 0) + { + Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.PushClipRect(at, new Vector2(at.X + w - grip, at.Y + 4096), true); + } + foreach ((string line, uint color) in _testResult) Label(line, color); + if (grip > 0) ImGuiNET.ImGui.PopClipRect(); + ImGuiNET.ImGui.PopFont(); + } + + /// <summary>Runs the rules over the test line. On an edit only (UI thread; each regex has its timeout).</summary> + private void RunTest(string text) + { + _testResult.Clear(); + text = text.Trim(); + // A line copied from the chat starts with its timestamp; the rules never see that. + if (text.Length > 9 && text[2] == ':' && text[5] == ':' && text[8] == ' ' && char.IsDigit(text[0])) text = text[9..]; + if (text.Length == 0) { _testResult.Add(("Paste a line to see which rules match and where it goes.", Faded(Mute))); return; } + + string when = ChatModel.Conditions[_testSource].Value; + string channel = "Chat"; + int type = -1; + if (when.StartsWith("chan:", StringComparison.Ordinal)) channel = when[5..]; + else if (when.StartsWith("type:", StringComparison.Ordinal) && int.TryParse(when[5..], out int t)) + { + type = t; + channel = ChatModel.ChannelForType(t); + } + if (text.StartsWith("[Rynth", StringComparison.OrdinalIgnoreCase)) channel = "Rynth"; + + var trace = new List<ChatRouter.Step>(); + ChatRoute route = ChatModel.TestRouter().Evaluate(text, channel, type, trace); + foreach (ChatRouter.Step step in trace) + _testResult.Add((step.Rule switch + { + ChatRouter.StandardFilterStep => "Standard", + < 0 => "Your name", + _ => $"Rule {step.Rule + 1}", + } + ": " + step.What, Text)); + if (trace.Count == 0) _testResult.Add(("No rule matches.", Faded(Mute))); + + string where; + if (route.Hidden) where = "Hidden: shown nowhere."; + else + { + var tabs = new List<string>(); + if (route.InHome) { tabs.Add("All"); tabs.Add(channel); } + if (route.Tabs != null) tabs.AddRange(route.Tabs); + where = tabs.Count == 0 ? "Shown nowhere." : "Shows in: " + string.Join(", ", tabs) + "."; + } + uint color = RynthTheme.Argb(route.LineArgb ?? ChatModel.ChannelArgb(channel)); + _testResult.Add((where + (route.LineArgb != null ? " (this is its colour)" : ""), route.Hidden ? Faded(Mute) : color)); + } + + /// <summary>Buffers for each rule; refilled from the rules when another face changed them, + /// except the row being typed in.</summary> + private void SyncBuffers(ChatFilterRule[] rules) + { + long version = ChatModel.FiltersVersion; + bool changed = version != _seenVersion; + _seenVersion = version; + foreach (ChatFilterRule r in rules) + { + if (!_bufs.TryGetValue(r, out Buffers? b)) + { + _bufs[r] = b = new Buffers(); + WriteUtf8(b.Pattern, r.Pattern); + } + else if (changed && !b.Active) + WriteUtf8(b.Pattern, r.Pattern); + } + if (_bufs.Count > rules.Length) + { + var live = new HashSet<ChatFilterRule>(rules); + foreach (ChatFilterRule gone in new List<ChatFilterRule>(_bufs.Keys)) + if (!live.Contains(gone)) _bufs.Remove(gone); + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs new file mode 100644 index 0000000..6c41020 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs @@ -0,0 +1,563 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/DamageDetailFace.cs +// "Monster Detail": everything the Damage panel knows about one monster, +// opened by clicking its name there. The Damage panel keeps only what you +// set and sort by; the numbers behind it live here: +// header HP (and where it came from), seconds per kill, hit rate +// Weak to all eight elements as damage taken (1.0 = full) + source +// Accuracy per weapon: hits, misses, hit %, seconds per kill +// Damage per weapon / element / spell tier: avg, crit, non-crit, +// crit rate, casts per kill, kills +// Summons kills and seconds per kill per summon element (and none) +// Damage taken per element: hits, average, biggest +// Rule priority, damage type, extra vuln, match expression, spell +// shapes (debuffs: the Damage panel's caret) +// "Default" shows only Rule: the settings every monster on Default uses. +// A name rule (wcid 0 + a rule name, from the Damage panel's Name rules, +// e.g. "Olthoi") shows only Rule, plus its debuffs, off hand, pet, rename +// and delete: it has no row in the Damage panel to hold them. +// +// Data: UiSources.MonsterDetail (the selected wcid) and MonsterRules; edits +// go through DamageCommands on the pump thread. No Avalonia twin; pops out as ImGui. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using System.Text; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using Rule = RynthCore.Engine.UI.Panels.MonstersPanel.Rule; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class DamageDetailFace : IImGuiPanel +{ + public const string Title = "Monster Detail"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(560, 620), new Vector2(360, 240)), + () => new DamageDetailFace()); + + private static string _selectedName = ""; + + /// <summary> + /// Shows <paramref name="wcid"/> in the Monster Detail panel, opening it. wcid 0 shows a + /// rule only: <paramref name="name"/>'s (a name rule, or a monster not met yet), or the + /// Default settings when the name is empty or "Default". + /// </summary> + public static void Show(uint wcid, string name) + { + _selectedName = wcid == 0 && (string.IsNullOrWhiteSpace(name) || IsDefaultName(name)) ? "Default" : name; + MonsterDetailSource.SelectedWcid = wcid; + _showCount++; + UiSources.MonsterDetail.RequestRefresh(); + ImGuiPanelHost.Open(Title); + } + + private static uint C(uint argb) => RynthTheme.Argb(argb); + private static readonly uint Teal = C(0xFF26D9E6), Gold = C(0xFFFFD16A), Dim = C(0xFFC8D4E0), White = C(0xFFF2F7FC), + EntryBg = C(0xFF16283A), EntryBorder = C(0xFF34587A), ToggleOn = C(0xFF33CC66), ToggleOff = C(0xFF4D4D4D), + BarBg = C(0xFF16222E), Good = C(0xFF33CC66), Mid = C(0xFFE8B333), Bad = C(0xFFE05A5A), DeleteBg = C(0xFF6E1E1E), + DeleteBorder = C(0xFFFF8A8A); + + private MonsterDetail? _detail; + private long _seenVersion = -1, _seenRulesVersion = -1; + private MonsterRulesSnapshot? _rules; + private bool _confirmRemove; + private static int _showCount; + private int _seenShow = -1; + + // The Rule section's edit boxes: whose rule they hold, the saved values they were + // last loaded from, and whether one is being typed in. + private string _bufFor = ""; + private int _prioSeen = int.MinValue; + private string? _exprSeen; + private bool _prioActive, _exprActive; + private readonly byte[] _prioBuf = new byte[12], _exprBuf = new byte[512], _renameBuf = new byte[128]; + private string? _renaming; // a rename just sent: "Loading…" until the rule comes back under it + + public void OnShown() + { + UiSources.MonsterDetail.Subscribe(); + UiSources.MonsterRules.Subscribe(); + UiSources.MonsterDetail.RequestRefresh(); + UiSources.MonsterRules.RequestRefresh(); + } + + public void OnHidden() + { + UiSources.MonsterDetail.Unsubscribe(); + UiSources.MonsterRules.Unsubscribe(); + } + + public void Draw() + { + var snap = UiSources.MonsterDetail.Current; + if (snap != null && snap.Version != _seenVersion) { _seenVersion = snap.Version; _detail = snap.Value; } + var rules = UiSources.MonsterRules.Current; + if (rules != null && rules.Version != _seenRulesVersion) { _seenRulesVersion = rules.Version; _rules = rules.Value; } + + if (_seenShow != _showCount) { _seenShow = _showCount; _confirmRemove = false; } // another monster: no stale confirm + uint wcid = MonsterDetailSource.SelectedWcid; + bool isDefault = wcid == 0 && IsDefaultName(_selectedName); + bool nameRule = wcid == 0 && !isDefault; + MonsterDetail? d = _detail != null && _detail.Wcid == wcid && wcid != 0 ? _detail : null; + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4)); + + // ── Header ─────────────────────────────────────────────────────── + string name = d != null && d.Name.Length > 0 ? d.Name : _selectedName; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextColored(Vec(Teal), isDefault ? "DEFAULT" : name); + ImGuiNET.ImGui.PopFont(); + if (isDefault) + { + ImGuiNET.ImGui.TextColored(Vec(Dim), "The spell settings every monster set to Default uses."); + } + else if (nameRule) + { + NameRuleHeader(name); + } + else if (d == null) + { + ImGuiNET.ImGui.TextColored(Vec(Dim), _detail != null && !_detail.Bound ? "Waiting for RynthAi…" : "Loading…"); + } + else + { + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextColored(Vec(Dim), "wcid " + wcid.ToString(CultureInfo.InvariantCulture)); + // Aelrynth only: which difficulty tier these numbers are (the Damage panel's chip picks it). + if (UiSources.Damage.Current?.Value.Tier is { Show: true } tier) + { + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextColored(Vec(tier.View == tier.Current ? Teal : Gold), + tier.View <= 0 ? "· Tier 0 (real Dereth)" : "· Tier " + tier.View.ToString(CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.SetItemTooltip("HP, casts to kill, seconds per kill, hits and damage taken are this difficulty tier's.\n" + + "Damage per cast and weaknesses are the same at every tier. Change it on the Damage panel."); + } + string hp = d.Hp > 0 ? $"HP {d.Hp:N0} ({d.HpSrc})" : "HP unknown"; + string sec = d.SecKill > 0 ? $"{d.SecKill:0.0} s per kill" : "no timed kills yet"; + string hit = d.HitRate >= 0 ? $"{d.HitRate * 100:0}% hits" : "no hits yet"; + ImGuiNET.ImGui.TextColored(Vec(White), $"{hp} · {sec} · {hit}"); + + float bw = ImGuiNET.ImGui.CalcTextSize(RemoveLabel).X + 16; + ImGuiNET.ImGui.SameLine(); + float room = ImGuiNET.ImGui.GetContentRegionAvail().X; + if (room > bw) ImGuiNET.ImGui.SetCursorPosX(ImGuiNET.ImGui.GetCursorPosX() + room - bw); + Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos(); + if (FaceKit.Button("##remove", RemoveLabel, bp, new Vector2(bw, ImGuiNET.ImGui.GetFrameHeight()), White, DeleteBg, border: DeleteBorder)) + _confirmRemove = true; + ImGuiNET.ImGui.SetItemTooltip("Take this monster off the Damage panel: its learned numbers and your settings for it. It comes back if you meet it again."); + if (_confirmRemove) + { + ImGuiNET.ImGui.TextColored(Vec(Gold), "Remove " + name + " and everything learned about it?"); + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.SmallButton("Remove##yes")) + { + DamageCommands.RemoveMonster(wcid); + _confirmRemove = false; + ImGuiPanelHost.Close(Title); + } + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.SmallButton("Cancel##no")) _confirmRemove = false; + } + + WeakSection(d); + AccuracySection(d); + DamageSection(d); + SummonSection(d); + TakenSection(d); + } + + RuleSection(isDefault ? "Default" : name, nameRule); + + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopFont(); + } + + private static bool IsDefaultName(string name) => name.Equals("Default", StringComparison.OrdinalIgnoreCase); + + // A name rule's header: what it matches, and Delete rule (confirmed). + private void NameRuleHeader(string name) + { + Rule? rule = _rules?.FindRule(name); + if (rule != null) _renaming = null; + ImGuiNET.ImGui.PushTextWrapPos(0); + ImGuiNET.ImGui.TextColored(Vec(Dim), rule == null + ? (_rules == null || _renaming == name ? "Loading…" : "There is no rule with this name (deleted?).") + : "A name rule: used for every monster whose name contains \"" + name + "\"" + + (string.IsNullOrWhiteSpace(rule.MatchExpression) ? "" : " and its match expression is true") + + ", unless a rule higher in the Name rules list matches it first."); + ImGuiNET.ImGui.PopTextWrapPos(); + if (rule == null) return; + + Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos(); + float bw = ImGuiNET.ImGui.CalcTextSize(DeleteRuleLabel).X + 16; + if (FaceKit.Button("##delrule", DeleteRuleLabel, bp, new Vector2(bw, ImGuiNET.ImGui.GetFrameHeight()), White, DeleteBg, border: DeleteBorder)) + _confirmRemove = true; + ImGuiNET.ImGui.SetItemTooltip("Delete this rule. Monsters it covered go back to Default (or another rule that matches)."); + if (!_confirmRemove) return; + ImGuiNET.ImGui.TextColored(Vec(Gold), "Delete the rule " + name + "?"); + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.SmallButton("Delete##yes")) + { + DamageCommands.ResetRule(name); + _confirmRemove = false; + ImGuiPanelHost.Close(Title); + } + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.SmallButton("Cancel##no")) _confirmRemove = false; + } + + // ── Sections ───────────────────────────────────────────────────────── + + private static bool Section(string title) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Header, EntryBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, FaceKit.Lighten(EntryBg)); + bool open = ImGuiNET.ImGui.CollapsingHeader(title, ImGuiTreeNodeFlags.DefaultOpen); + ImGuiNET.ImGui.PopStyleColor(2); + return open; + } + + private static void WeakSection(MonsterDetail d) + { + if (!Section("Weak to")) return; + if (d.Weak.Count == 0) + { + ImGuiNET.ImGui.TextColored(Vec(Dim), "Nothing known yet: not in the server data, no creature type, nothing learned."); + return; + } + ImGuiNET.ImGui.TextColored(Vec(Dim), "Damage it takes from each element (1.0 = full, 0.5 = half), from " + d.WeakSrc + "."); + float labelW = ImGuiNET.ImGui.CalcTextSize("Lightning ").X; + float barW = Math.Max(80, ImGuiNET.ImGui.GetContentRegionAvail().X - labelW - ImGuiNET.ImGui.CalcTextSize(" 0.00x").X - 8); + double top = 1.0; + foreach (var (_, m) in d.Weak) if (m > top) top = m; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float h = ImGuiNET.ImGui.GetTextLineHeight(); + foreach (var (e, m) in d.Weak) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddText(p, White, e); + Vector2 b0 = p + new Vector2(labelW, 2), b1 = b0 + new Vector2(barW, h - 4); + dl.AddRectFilled(b0, b1, BarBg, 2); + if (m >= 0) + { + float f = (float)Math.Clamp(m / top, 0, 1); + uint col = m >= 1.0 ? Good : m >= 0.6 ? Mid : Bad; + dl.AddRectFilled(b0, b0 + new Vector2(barW * f, h - 4), col, 2); + dl.AddText(new Vector2(b1.X + 6, p.Y), White, m.ToString("0.00", CultureInfo.InvariantCulture) + "x"); + } + else + dl.AddText(new Vector2(b1.X + 6, p.Y), Dim, "learned"); + ImGuiNET.ImGui.Dummy(new Vector2(labelW + barW + 60, h)); + } + } + + private static void AccuracySection(MonsterDetail d) + { + if (!Section("Accuracy and speed")) return; + if (d.Weapons.Count == 0) { ImGuiNET.ImGui.TextColored(Vec(Dim), "No attacks recorded yet."); return; } + if (!BeginTable("##acc", "Weapon", "Hit %", "Hits", "Misses", "Sec/Kill", "Timed kills")) return; + foreach (var (w, hits, misses, sec, secN) in d.Weapons) + { + ImGuiNET.ImGui.TableNextRow(); + Cell(w); + Cell(hits + misses > 0 ? $"{100.0 * hits / (hits + misses):0}%" : "—"); + Cell(hits.ToString(CultureInfo.InvariantCulture)); + Cell(misses.ToString(CultureInfo.InvariantCulture)); + Cell(sec > 0 ? sec.ToString("0.0", CultureInfo.InvariantCulture) : "—"); + Cell(secN.ToString(CultureInfo.InvariantCulture)); + } + ImGuiNET.ImGui.EndTable(); + } + + private static void DamageSection(MonsterDetail d) + { + if (!Section("Damage")) return; + if (d.Casts.Count == 0) { ImGuiNET.ImGui.TextColored(Vec(Dim), "No damage recorded yet."); return; } + if (!BeginTable("##dmg", "Weapon", "Element", "Tier", "Avg", "Crit", "Non-crit", "Crit %", "Casts/Kill", "Kills")) return; + foreach (DetailCast c in d.Casts) + { + ImGuiNET.ImGui.TableNextRow(); + Cell(c.Weapon); + Cell(c.Elem); + Cell(DamageSource.FormatTier(c.Tier)); + Cell(c.Hits > 0 ? c.Avg.ToString("0", CultureInfo.InvariantCulture) : "—"); + Cell(c.CritN > 0 ? c.Crit.ToString("0", CultureInfo.InvariantCulture) : "—"); + Cell(c.NonCritN > 0 ? c.NonCrit.ToString("0", CultureInfo.InvariantCulture) : "—"); + Cell(c.CritN + c.NonCritN > 0 ? $"{100.0 * c.CritN / (c.CritN + c.NonCritN):0}%" : "—"); + Cell(c.Kills > 0 ? c.Casts.ToString("0.00", CultureInfo.InvariantCulture) : "—"); + Cell(c.Kills.ToString(CultureInfo.InvariantCulture)); + } + ImGuiNET.ImGui.EndTable(); + } + + private static void SummonSection(MonsterDetail d) + { + if (!Section("Summons")) return; + if (d.Summons.Count == 0) + { + ImGuiNET.ImGui.TextColored(Vec(Dim), "No timed kills yet. (The game doesn't report a summon's own damage, so this compares kill times.)"); + return; + } + if (!BeginTable("##pets", "Summon", "Kills", "Sec/Kill")) return; + foreach (var (e, kills, sec) in d.Summons) + { + ImGuiNET.ImGui.TableNextRow(); + Cell(e); + Cell(kills.ToString(CultureInfo.InvariantCulture)); + Cell(sec > 0 ? sec.ToString("0.0", CultureInfo.InvariantCulture) : "—"); + } + ImGuiNET.ImGui.EndTable(); + } + + private static void TakenSection(MonsterDetail d) + { + if (!Section("Damage taken")) return; + if (d.Taken.Count == 0) { ImGuiNET.ImGui.TextColored(Vec(Dim), "It hasn't hit you yet."); return; } + if (!BeginTable("##taken", "Element", "Hits", "Average", "Biggest")) return; + foreach (var (e, hits, avg, max) in d.Taken) + { + ImGuiNET.ImGui.TableNextRow(); + Cell(e); + Cell(hits.ToString(CultureInfo.InvariantCulture)); + Cell(avg.ToString("0", CultureInfo.InvariantCulture)); + Cell(max.ToString("0", CultureInfo.InvariantCulture)); + } + ImGuiNET.ImGui.EndTable(); + } + + // The rule a monster (or Default, or a name rule) uses: priority, damage type, extra vuln, + // match expression, spell shapes; a name rule also debuffs, off hand, pet and its name. + // A monster following Default gets its own rule (a copy of Default) on the first change. + private void RuleSection(string name, bool nameRule) + { + if (!Section("Rule")) return; + if (_rules == null || _rules.Parsed.Rules.Count == 0) + { + ImGuiNET.ImGui.TextColored(Vec(Dim), "Monster rules not loaded yet."); + return; + } + bool isDefault = IsDefaultName(name); + Rule? exact = isDefault ? null : _rules.FindRule(name); + if (nameRule && exact == null) return; // deleted: editing would make it again + bool custom = exact != null; + Rule view = isDefault ? _rules.DefaultRule() : exact ?? _rules.DefaultRule(); + + if (!nameRule) + { + ImGuiNET.ImGui.TextColored(Vec(custom || isDefault ? Gold : Dim), + isDefault ? "Applies to every monster set to Default." : custom ? "Custom settings for this monster." : "Following Default (a change here gives it its own settings)."); + ImGuiNET.ImGui.TextColored(Vec(Dim), DebuffsHint); + if (custom) + { + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.SmallButton("Back to Default")) DamageCommands.ResetRule(name); + } + } + + // The edit boxes reload from the rule when its saved value changes (not every frame, + // so a value just entered stays while the plugin saves it). + if (_bufFor != name) + { + _bufFor = name; + _prioSeen = int.MinValue; + _exprSeen = null; + WriteUtf8(_renameBuf, name); + } + + // Priority + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextColored(Vec(Dim), "Priority"); + ImGuiNET.ImGui.SameLine(); + if (!_prioActive && _prioSeen != view.Priority) + { + WriteUtf8(_prioBuf, view.Priority.ToString(CultureInfo.InvariantCulture)); + _prioSeen = view.Priority; + } + ImGuiNET.ImGui.SetNextItemWidth(ImGuiNET.ImGui.CalcTextSize("0000").X + 12); + bool enter = ImGuiNET.ImGui.InputText("##prio", _prioBuf, (uint)_prioBuf.Length, + ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.EnterReturnsTrue); + _prioActive = ImGuiNET.ImGui.IsItemActive(); + if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + if (int.TryParse(Utf8(_prioBuf).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int prio)) + { + if (prio != view.Priority) DamageCommands.EditRule(name, r => r.Priority = prio); + } + else _prioSeen = int.MinValue; // not a number: show the saved value again + } + ImGuiNET.ImGui.SetItemTooltip("Target priority: while a higher-priority monster is in range it is attacked first, always (1 = normal). Enter to save."); + + // Damage type and Extra vuln + ImGuiNET.ImGui.SameLine(0, 14); + Combo("Damage", "##dtype", DamageCommands.DamageTypes, string.IsNullOrEmpty(view.DamageType) ? "Auto" : view.DamageType, + pick => DamageCommands.EditRule(name, r => r.DamageType = pick), + "Element for spells and weapons against it. Auto = the one it's weakest to."); + ImGuiNET.ImGui.SameLine(0, 14); + Combo("Extra vuln", "##exvuln", DamageCommands.ExVulnTypes, string.IsNullOrEmpty(view.ExVuln) ? "None" : view.ExVuln, + pick => DamageCommands.EditRule(name, r => r.ExVuln = pick), + "A vulnerability of another element, on top of Vuln (which follows the attack's element)."); + + // Match expression (Default never matches by name, so it has none) + if (!isDefault) + { + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextColored(Vec(Dim), "Match"); + ImGuiNET.ImGui.SameLine(); + string expr = view.MatchExpression ?? ""; + if (!_exprActive && _exprSeen != expr) + { + WriteUtf8(_exprBuf, expr); + _exprSeen = expr; + } + ImGuiNET.ImGui.SetNextItemWidth(-1); + bool exprEnter = ImGuiNET.ImGui.InputText("##expr", _exprBuf, (uint)_exprBuf.Length, ImGuiInputTextFlags.EnterReturnsTrue); + _exprActive = ImGuiNET.ImGui.IsItemActive(); + if (exprEnter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + string typed = Utf8(_exprBuf).Trim(); + if (typed != expr) DamageCommands.EditRule(name, r => r.MatchExpression = typed); + } + ImGuiNET.ImGui.SetItemTooltip("Only when this is true as well (empty = by name only). Enter to save.\n" + + "Variables: name, range, typeid, maxhp, metastate, true, false\nExamples: range>5, maxhp>1000"); + } + + ToggleRow("Shapes", DamageCommands.ShapeDefs, view, name); + string casts = DamageCommands.BaseShapeName(view); + if (casts.Length > 0) + { + ImGuiNET.ImGui.SameLine(0, 10); + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextColored(Vec(Dim), "casts " + casts + (view.UseRing ? ", Ring when enough are near" : "")); + ImGuiNET.ImGui.SetItemTooltip("With several shapes on, the first of Arc, Streak, Blast, Bolt is cast.\n" + + "Ring replaces it when at least Min Ring Targets monsters are within Ring Range (Settings)."); + } + if (!nameRule) return; + + // A name rule has no Damage panel row: its debuffs, off hand and pet are set here. + ToggleRow("Debuffs", DamageCommands.DebuffDefs, view, name); + int off = view.OffhandId; + string offText = off >= 0 && off < DamageCommands.OffhandModeNames.Length ? DamageCommands.OffhandModeNames[off] : "Item " + unchecked((uint)off); + Combo("Off hand", "##offhand", DamageCommands.OffhandModeNames, offText, + pick => DamageCommands.EditRule(name, r => r.OffhandId = Array.IndexOf(DamageCommands.OffhandModeNames, pick)), + "Off hand against the monsters it covers. Default = the DEFAULT line's.\n" + + "Auto = a listed shield; Shield; Dual wield (needs the skill); None = leave the off hand alone."); + ImGuiNET.ImGui.SameLine(0, 14); + string pet = string.IsNullOrEmpty(view.PetDamage) || view.PetDamage.Equals("PAuto", StringComparison.OrdinalIgnoreCase) ? "Auto" : view.PetDamage; + Combo("Pet", "##pet", PetLabels, pet, + pick => DamageCommands.EditRule(name, r => r.PetDamage = pick == "Auto" ? "PAuto" : pick), + "Summon element against the monsters it covers. Auto = its Damage type, else the DEFAULT line's."); + + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextColored(Vec(Dim), "Name"); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(Math.Min(260, ImGuiNET.ImGui.GetContentRegionAvail().X)); + bool renamed = ImGuiNET.ImGui.InputText("##rename", _renameBuf, (uint)_renameBuf.Length, ImGuiInputTextFlags.EnterReturnsTrue); + if (renamed || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + string to = Utf8(_renameBuf).Trim(); + if (to.Length > 0 && to != name && !IsDefaultName(to) && (_rules.FindRule(to) == null || to.Equals(name, StringComparison.OrdinalIgnoreCase))) + { + DamageCommands.EditRule(name, r => r.Name = to); + _selectedName = to; + _bufFor = to; + _renaming = to; + } + else WriteUtf8(_renameBuf, name); + } + ImGuiNET.ImGui.SetItemTooltip("The part of a monster's name this rule looks for. Enter to rename."); + } + + private static readonly string[] PetLabels = + { "Auto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + + /// <summary>A label and a combo of <paramref name="items"/>; <paramref name="onPick"/> runs when another one is chosen.</summary> + private static void Combo(string label, string id, string[] items, string current, Action<string> onPick, string tip) + { + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextColored(Vec(Dim), label); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(ImGuiNET.ImGui.CalcTextSize("Dual wield").X + 34); + if (ImGuiNET.ImGui.BeginCombo(id, current)) + { + foreach (string v in items) + if (ImGuiNET.ImGui.Selectable(v, v.Equals(current, StringComparison.OrdinalIgnoreCase)) + && !v.Equals(current, StringComparison.OrdinalIgnoreCase)) + onPick(v); + ImGuiNET.ImGui.EndCombo(); + } + ImGuiNET.ImGui.SetItemTooltip(tip); + } + + private const string RemoveLabel = PhosphorIcons.Trash + " Remove monster"; + private const string DeleteRuleLabel = PhosphorIcons.Trash + " Delete rule"; + private const string DebuffsHint = "Debuffs are set with the " + PhosphorIcons.CaretDown + " in the Damage panel's Debuffs column."; + + private static void ToggleRow(string label, (string Field, string Label, string Tip)[] defs, Rule view, string name) + { + ImGuiNET.ImGui.TextColored(Vec(Dim), label); + float h = ImGuiNET.ImGui.GetFrameHeight(); + foreach (var (field, text, tip) in defs) + { + ImGuiNET.ImGui.SameLine(); + bool on = view.GetToggle(field); + float tw = ImGuiNET.ImGui.CalcTextSize(text).X; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var size = new Vector2(tw + h + 8, h); + if (ImGuiNET.ImGui.InvisibleButton("##t_" + field, size)) + DamageCommands.EditRule(name, rule => DamageCommands.FlipToggle(rule, field)); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.SetItemTooltip(tip); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(p, p + size, hot ? FaceKit.Lighten(EntryBg) : EntryBg, 2); + dl.AddRect(p, p + size, EntryBorder, 2); + float box = h - 8; + dl.AddRectFilled(p + new Vector2(4, 4), p + new Vector2(4 + box, 4 + box), on ? ToggleOn : ToggleOff, 2); + dl.AddText(p + new Vector2(box + 8, (h - ImGuiNET.ImGui.GetTextLineHeight()) * 0.5f), White, text); + } + } + + // ── Helpers ────────────────────────────────────────────────────────── + + private static bool BeginTable(string id, params string[] headers) + { + if (!ImGuiNET.ImGui.BeginTable(id, headers.Length, + ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.PadOuterX)) + return false; + foreach (string h in headers) ImGuiNET.ImGui.TableSetupColumn(h); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Teal); + ImGuiNET.ImGui.TableHeadersRow(); + ImGuiNET.ImGui.PopStyleColor(); + return true; + } + + private static void Cell(string text) + { + ImGuiNET.ImGui.TableNextColumn(); + ImGuiNET.ImGui.TextColored(Vec(White), text); + } + + private static Vector4 Vec(uint abgr) => ImGuiNET.ImGui.ColorConvertU32ToFloat4(abgr); + + private static string Utf8(byte[] buffer) + { + int len = Array.IndexOf(buffer, (byte)0); + return Encoding.UTF8.GetString(buffer, 0, len < 0 ? buffer.Length : len); + } + + /// <summary>Writes <paramref name="text"/> NUL-terminated, cut at a character boundary if it doesn't fit.</summary> + private static void WriteUtf8(byte[] buffer, string text) + { + byte[] all = Encoding.UTF8.GetBytes(text); + int n = Math.Min(all.Length, buffer.Length - 1); + while (n > 0 && n < all.Length && (all[n] & 0xC0) == 0x80) n--; // don't split a sequence + Array.Copy(all, buffer, n); + buffer[n] = 0; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs new file mode 100644 index 0000000..c6b0648 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs @@ -0,0 +1,1448 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/DamageFace.cs +// ImGui face of the Damage panel (UI/Panels/MonsterDamagePanel.cs): RynthAi's +// learned per-monster combat data and the monster rules; the dashboard's +// Monsters button opens it. (The basic Monsters panel was retired +// 2026-10-01; its rule editing moved here and into Monster Detail.) +// +// Top bar: weapon filter, monster/wcid search, Reset stats (confirmed), +// status. Name rules (folded): every rule but Default, by name (one can +// cover many monsters, e.g. Olthoi, or one not met yet): priority, +// expression, open, delete; and an add line. Table: a DEFAULT line (default +// weapon, offhand, pet, Default's priority; its name opens the Default +// settings), then one row per monster: D Monster | Priority | M HP | Weak to | +// Weapon | Offhand | Pet | Kills | Sec/Kill | Debuffs | x. Priority edits the +// monster's rule (- / + or type a number). Click a header to sort, a monster's name for its +// Monster Detail panel (weaknesses, accuracy, damage, summons, damage taken, +// its rule). x removes the monster (confirmed). Gold = set by you, dim = +// automatic. +// Aelrynth only: a tier chip after Reset stats (DamageView.Tier) - which of the +// awakened worlds' / scaled dungeons' difficulty tiers the numbers are for, and +// a picker; "~" marks an HP estimated from real Dereth's. Hidden elsewhere. +// +// Data: UiSources.Damage and UiSources.MonsterRules (hub); every change goes +// through DamageCommands on the pump thread. Rows are drawn only while on +// screen; their display strings are built once per snapshot. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using System.Text; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using Rule = RynthCore.Engine.UI.Panels.MonstersPanel.Rule; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class DamageFace : IImGuiPanel +{ + public const string Title = "Damage"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(1060, 460), new Vector2(480, 200), EdgeToEdge: true), + () => new DamageFace()); + + // ── Palette (MonsterDamagePanel's, a little brighter) ─────────────── + private static readonly uint Teal = C(0xFF26D9E6), Gold = C(0xFFFFD16A), Dim = C(0xFFC8D4E0), + White = C(0xFFF2F7FC), HeaderBg = C(0xFF121C26), PanelBg = C(0xF0081018), RowBg = C(0x40203040), + PickerBg = C(0xFF0A141E), PickSel = C(0xFF1A2E42), EntryBg = C(0xFF16283A), EntryBorder = C(0xFF34587A), + SearchBg = C(0xFF16222E), ToggleOn = C(0xFF33CC66), ToggleOff = C(0xFF4D4D4D), DeleteRed = C(0xFFFF8A8A), + FilterBg = C(0xFF203A52), TargetBg = C(0x5026D9E6), NearbyBg = C(0x3833CC66), NearbyBar = C(0xFF33CC66), ResetBg = C(0xFF5A2020), ResetBorder = C(0xFFFF8A8A), ClearBg = C(0xFF6E1E1E); + private static uint C(uint argb) => RynthTheme.Argb(argb); + + // Column widths (the Avalonia grid's) and their left edges. + // Widths are the user's (dragged in the header, saved per PC), else these defaults. + private static readonly float[] DefaultColW = { 210, 72, 84, 92, 150, 130, 120, 56, 70, 96, 26 }; + // Saved width keys: the columns keep the keys they had before Priority was added (2026-10-03), + // so a saved layout still fits them; Priority has its own. + private static readonly string[] ColKeys = + { "col0", "colPrio", "col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8", "col9" }; + private static readonly float[] ColW = LoadColW(); + private static float[] ColX = BuildColX(); + + private static float[] LoadColW() + { + var w = (float[])DefaultColW.Clone(); + for (int i = 0; i < w.Length; i++) + w[i] = RynthCore.Engine.UI.PanelColumnStore.Get("Damage2." + ColKeys[i], w[i]); + return w; + } + private static readonly string[] Headers = + { "Monster", "Priority", "HP", "Weak to", "Weapon", "Offhand", "Pet", "Kills", "Sec/Kill", "Debuffs", "" }; + private const int ColMonster = 0, ColPrio = 1, ColHp = 2, ColWeak = 3, ColWeapon = 4, ColOffhand = 5, ColPet = 6, ColKills = 7, + ColSec = 8, ColDebuffs = 9, ColDel = 10; + private const float RowH = 22; + private static float TableW => ColX[^1] + ColW[^1]; + + private static float[] BuildColX() + { + var x = new float[ColW.Length]; + for (int i = 1; i < x.Length; i++) x[i] = x[i - 1] + ColW[i - 1]; + return x; + } + + // ── Snapshot + per-row display strings ─────────────────────────────── + private sealed class RowText + { + public string Wcid = "", Tier = "", Crit = "", NonCrit = "", Casts = "", Kills = ""; + public string Weapon = "", Offhand = "", Pet = "", WeakTop = "", Sec = "", SecTip = ""; + public bool CritSet, NonCritSet, WeaponGold, OffhandGold, PetGold; + public string[] TierLines = Array.Empty<string>(); + /// <summary>Priority shown (int.MinValue = rules not loaded), whether it's the monster's own + /// (gold), the rule an edit copies when it has none (a name rule covering it), and the tip.</summary> + public int Prio = int.MinValue; + public bool PrioGold; + public string? PrioCopyFrom; + public string PrioTip = ""; + } + + private DamageView? _view; + private long _seenVersion = -1, _seenRulesVersion = -1; + private MonsterRulesSnapshot? _rules; + private readonly List<DamageRow> _shown = new(); + private readonly Dictionary<DamageRow, RowText> _text = new(); + private string _status = "Binding to RynthAi…"; + + // Filters. + private uint _filterWid; + private string _filterLabel = "Weapon: All " + PhosphorIcons.CaretDown; + private readonly byte[] _search = new byte[64]; + private string _searchText = string.Empty; + + // Sorting (click a header): column, direction. Default is by name. Nearby first puts the + // targeted monster, then the ones on this landblock, above the rest (each in sort order). + private int _sortCol = ColMonster; + private bool _sortDesc; + private static bool _nearbyFirst = true; + + // Debuffs popup: whose rule, where, and the typed-in debuffs being edited. + private string _debuffFor = ""; + private bool _debuffOpen; + private Vector2 _debuffPos; + private readonly byte[] _customBuf = new byte[256]; + + // Remove-monster confirmation. + private uint _removeWcid; + private string _removeName = ""; + private bool _removeOpen; + + // HP boxes, per row key. + private sealed class HpEdit + { + public readonly byte[] Buffer = new byte[16]; + public int Shown = int.MinValue; + public bool Active, ForceManual, FocusNext; + } + private readonly Dictionary<string, HpEdit> _hp = new(); + + // Priority boxes, per row key ("default" for the DEFAULT line). + private sealed class PrioEdit + { + public readonly byte[] Buffer = new byte[8]; + public int Shown = int.MinValue; + public bool Active; + } + private readonly Dictionary<string, PrioEdit> _prio = new(); + + // The one picker popup (weapon filter, per-row weapon/offhand/pet, extra vuln). + private readonly List<(uint Id, string Name)> _pickItems = new(); + private uint _pickSel; + private Action<uint>? _pickAction; + private Vector2 _pickPos; + private bool _pickOpen, _resetOpen; + + // Ellipsized text cache (per text and width). + private readonly Dictionary<string, (float Width, string Shown)> _fit = new(); + + public void OnShown() + { + UiSources.Damage.Subscribe(); + UiSources.MonsterRules.Subscribe(); + UiSources.Damage.RequestRefresh(); + UiSources.MonsterRules.RequestRefresh(); + } + + public void OnHidden() + { + UiSources.Damage.Unsubscribe(); + UiSources.MonsterRules.Unsubscribe(); + } + + // ===================================================================== + // Frame + // ===================================================================== + + public void Draw() + { + TakeSnapshots(); + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail(); + dl.AddRectFilled(origin, origin + size, PanelBg, 4); + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4)); + ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(6, 5)); + ImGuiNET.ImGui.Indent(6); + + TopBar(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + NameRules(origin.X + size.X - 4 - ImGuiNET.ImGui.GetCursorScreenPos().X); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + + Vector2 tableAt = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 tableSize = new(origin.X + size.X - 4 - tableAt.X, origin.Y + size.Y - 4 - tableAt.Y); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1)); + ImGuiNET.ImGui.BeginChild("##dmg_table", Vector2.Max(tableSize, new Vector2(50, 40)), ImGuiChildFlags.None, + ImGuiWindowFlags.HorizontalScrollbar); + Table(); + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + + ImGuiNET.ImGui.Unindent(6); + Popups(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopFont(); + } + + private void TakeSnapshots() + { + bool dirty = false; + var rules = UiSources.MonsterRules.Current; + if (rules != null && rules.Version != _seenRulesVersion) + { + _seenRulesVersion = rules.Version; + _rules = rules.Value; + dirty = true; // the Offhand cells show the monsters' own rules + } + var snap = UiSources.Damage.Current; + if (snap != null && snap.Version != _seenVersion) + { + _seenVersion = snap.Version; + _view = snap.Value; + dirty = true; + } + if (dirty) Rebuild(); + } + + /// <summary>The filtered row list, the status line and every row's display strings. Once per snapshot/filter change.</summary> + private void Rebuild() + { + _shown.Clear(); + _text.Clear(); + _fit.Clear(); + _metByName.Clear(); + if (_view == null) { _status = "Binding to RynthAi…"; return; } + if (!_view.Bound) { _status = "Waiting for RynthAi plugin…"; return; } + foreach (DamageRow r in _view.Rows) + if (!r.IsDefault) _metByName.TryAdd(r.Name, r.Wcid); + + if (_filterWid != 0 && !_view.LearnedWeapons.Exists(w => w.Id == _filterWid)) SetFilter(0, "All weapons"); + foreach (DamageRow r in _view.Rows) + { + if (!r.IsDefault) + { + if (_filterWid != 0 && r.Wid != _filterWid) continue; + if (_searchText.Length > 0 + && r.Name.IndexOf(_searchText, StringComparison.OrdinalIgnoreCase) < 0 + && !r.Wcid.ToString(CultureInfo.InvariantCulture).Contains(_searchText, StringComparison.Ordinal)) + continue; + } + _shown.Add(r); + _text[r] = BuildText(r); + } + SortShown(); + _status = _view.Rows.Count == 0 ? "No kills recorded yet." : $"{_view.Rows.Count} rows · {_view.LearnedWeapons.Count} weapon(s)"; + } + + private void SortShown() + { + int col = _sortCol; + Comparison<DamageRow> cmp = col switch + { + ColPrio => (a, b) => _text[a].Prio.CompareTo(_text[b].Prio), + ColHp => (a, b) => a.Hp.CompareTo(b.Hp), + ColWeak => (a, b) => string.Compare(_text[a].WeakTop, _text[b].WeakTop, StringComparison.OrdinalIgnoreCase), + ColWeapon => (a, b) => string.Compare(_text[a].Weapon, _text[b].Weapon, StringComparison.OrdinalIgnoreCase), + ColOffhand => (a, b) => string.Compare(_text[a].Offhand, _text[b].Offhand, StringComparison.OrdinalIgnoreCase), + ColPet => (a, b) => string.Compare(_text[a].Pet, _text[b].Pet, StringComparison.OrdinalIgnoreCase), + ColKills => (a, b) => a.Kills.CompareTo(b.Kills), + ColSec => (a, b) => (a.SecKill > 0 ? a.SecKill : double.MaxValue).CompareTo(b.SecKill > 0 ? b.SecKill : double.MaxValue), + _ => (a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase), + }; + bool desc = _sortDesc, nearbyFirst = _nearbyFirst; + static int Rank(DamageRow r) => r.Targeted ? 0 : r.Nearby ? 1 : 2; + _shown.Sort((a, b) => + { + if (a.IsDefault != b.IsDefault) return a.IsDefault ? -1 : 1; // Default stays on top + if (nearbyFirst && Rank(a) != Rank(b)) return Rank(a).CompareTo(Rank(b)); + int c = cmp(a, b); + if (desc) c = -c; + return c != 0 ? c : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); + }); + } + + private RowText BuildText(DamageRow r) + { + var inv = CultureInfo.InvariantCulture; + var t = new RowText(); + if (r.IsDefault) + { + t.WeaponGold = r.AssignedWid != 0; + t.Weapon = t.WeaponGold ? Trunc(r.AssignedWeapon.Length > 0 ? r.AssignedWeapon : "Weapon " + r.AssignedWid, 16) : "Auto (per monster)"; + if (_rules != null && _rules.Parsed.Rules.Count > 0) + { + t.Prio = _rules.DefaultRule().Priority; + t.PrioGold = true; + } + t.PrioTip = "Default's priority: a monster or name rule you add starts with it.\n" + + "Targeting adds a bonus for priority above 1 (+5 a step) to monsters with a rule of their own or a name rule."; + return t; + } + BuildPrio(r.Name, t); + t.Wcid = r.Wcid.ToString(inv); + t.Tier = DamageSource.FormatTier(r.Tier); + t.CritSet = r.CritN > 0; + t.Crit = t.CritSet ? r.Crit.ToString("0", inv) : "—"; + t.NonCritSet = r.NonCritN > 0; + t.NonCrit = t.NonCritSet ? r.NonCrit.ToString("0", inv) : "—"; + t.Casts = r.Kills > 0 ? r.Casts.ToString("0.00", inv) : "—"; + t.Kills = r.Kills.ToString(inv); + t.WeaponGold = r.AssignedWid != 0; + t.Weapon = t.WeaponGold + ? Trunc(r.AssignedWeapon.Length > 0 ? r.AssignedWeapon : "Weapon " + r.AssignedWid, 16) + : r.BestWid != 0 ? "Auto: " + Trunc(r.BestWeapon, 12) : "Auto"; + // What applies: the item picked here, else the monster's own rule (a mode, or an old item pick), else Auto. + int ruleOff = _rules?.FindRule(r.Name)?.OffhandId ?? 0; + t.OffhandGold = r.AssignedOff != 0 || ruleOff != 0; + t.Offhand = r.AssignedOff != 0 ? Trunc(r.AssignedOffName.Length > 0 ? r.AssignedOffName : "Offhand " + r.AssignedOff, 16) + : ruleOff is >= 1 and <= 4 ? DamageCommands.OffhandModeNames[ruleOff] + : ruleOff != 0 ? Trunc(WeaponName(unchecked((uint)ruleOff)), 16) + : "Auto"; + t.PetGold = r.Pet.Length > 0; + t.Pet = Trunc(t.PetGold ? r.PetLabel : "Auto", 16); + int comma = r.Weak.IndexOf(','); + string firstWeak = comma > 0 ? r.Weak.Substring(0, comma) : r.Weak; // "Bludgeon 1.0" + int sp = firstWeak.IndexOf(' '); + t.WeakTop = sp > 0 ? firstWeak.Substring(0, sp) : firstWeak; + t.Sec = r.SecKill > 0 ? r.SecKill.ToString("0.0", inv) : "—"; + t.SecTip = (r.SecKill > 0 ? $"{r.SecKill:0.0} s from engaging to the kill (average of timed kills)." : "No timed kills yet.") + + (r.HitRate >= 0 ? $"\nHits: {r.HitRate * 100:0}% of attacks and casts landed." : ""); + t.TierLines = new string[r.Tiers.Count]; + for (int i = 0; i < r.Tiers.Count; i++) + { + DamageTierStat s = r.Tiers[i]; + string crit = s.CritN > 0 ? s.Crit.ToString("0", inv) : "—"; + string nc = s.NonCritN > 0 ? s.NonCrit.ToString("0", inv) : "—"; + string ck = s.Kills > 0 ? s.Casts.ToString("0.00", inv) : "—"; + t.TierLines[i] = $"{DamageSource.FormatTier(s.Tier),-4} {s.Elem,-8} kills {s.Kills,-4} crit {crit,-5} non-crit {nc,-5} casts/kill {ck}"; + } + return t; + } + + // ===================================================================== + // Top bar + // ===================================================================== + + private void TopBar() + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float x = p.X; + + float fw = Math.Max(120, ImGuiNET.ImGui.CalcTextSize(_filterLabel).X + 18); + if (Button("##filter", _filterLabel, new Vector2(x, p.Y), new Vector2(fw, 22), White, FilterBg, FilterBg) && _view != null) + { + _pickItems.Clear(); + _pickItems.Add((0, "All weapons")); + _pickItems.AddRange(_view.LearnedWeapons); + OpenPicker(new Vector2(x, p.Y + 22), _filterWid, id => + { + string name = id == 0 ? "All weapons" : "Weapon " + id; + foreach (var w in _view!.LearnedWeapons) if (w.Id == id) name = w.Name; + SetFilter(id, name); + Rebuild(); + }); + } + x += fw + 6; + + // Search (monster name or wcid). + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y)); + ImGuiNET.ImGui.SetNextItemWidth(160); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, SearchBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, EntryBorder); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, White); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f)); + if (ImGuiNET.ImGui.InputText("##dmg_search", _search, (uint)_search.Length)) + { + string t = Utf8(_search).Trim(); + if (t != _searchText) { _searchText = t; Rebuild(); } + } + bool searching = ImGuiNET.ImGui.IsItemActive(); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(3); + if (_search[0] == 0 && !searching) + dl.AddText(new Vector2(x + 5, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Dim, SearchHint); + x += 166; + + float nw = ImGuiNET.ImGui.CalcTextSize("Nearby first").X + 26; + Vector2 np = new(x, p.Y); + if (Button("##nearby", "", np, new Vector2(nw, 22), White, EntryBg, _nearbyFirst ? ToggleOn : EntryBorder)) + { + _nearbyFirst = !_nearbyFirst; + SortShown(); + } + dl.AddRectFilled(np + new Vector2(5, 6), np + new Vector2(15, 16), _nearbyFirst ? ToggleOn : ToggleOff, 2); + dl.AddText(np + new Vector2(20, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), White, "Nearby first"); + ImGuiNET.ImGui.SetItemTooltip("Keep the monster you're fighting (teal) and the ones on this landblock (green) at the top."); + x += nw + 6; + + if (Button("##reset", ResetLabel, new Vector2(x, p.Y), new Vector2(84, 22), White, ResetBg, ResetBorder)) + _resetOpen = true; + ImGuiNET.ImGui.SetItemTooltip("Clear all learned damage statistics (keeps monster names + your manual settings)."); + x += 90; + + x = TierChip(x, p.Y); + + dl.AddText(new Vector2(x + 4, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Dim, _status); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + // ── Aelrynth difficulty tier (2026-10-03) ──────────────────────────── + // Awakened worlds and scaled dungeons hold the same monsters, +5% health, skills and damage a + // tier, and RynthAi keeps each tier's numbers apart. The chip says which tier the table shows + // and opens a picker; it is drawn only when the data source says so (Aelrynth, tier seen). + + private const uint FollowTier = uint.MaxValue; // the picker's "where I am" entry + + private static string TierName(int tier) => tier <= 0 ? "Tier 0 (real Dereth)" : "Tier " + tier.ToString(CultureInfo.InvariantCulture); + + /// <summary>The tier chip at <paramref name="x"/>; returns the x after it (unchanged when hidden).</summary> + private float TierChip(float x, float y) + { + AwakenedTierView? t = _view?.Tier; + if (t == null || !t.Show) return x; + string label = TierName(t.View) + (t.View == t.Current ? " " + PhosphorIcons.MapPin : "") + " " + PhosphorIcons.CaretDown; + float w = ImGuiNET.ImGui.CalcTextSize(label).X + 16; + bool here = t.View == t.Current; + if (Button("##tier", label, new Vector2(x, y), new Vector2(w, 22), here ? Teal : Gold, FilterBg, here ? EntryBorder : Gold)) + { + _pickItems.Clear(); + _pickItems.Add((FollowTier, "Where I am: " + TierName(t.Current))); + foreach (int tier in t.Tiers) + _pickItems.Add(((uint)tier, tier <= 0 ? TierName(0) + : $"{TierName(tier)} (+{(tier * t.Percent).ToString("0", CultureInfo.InvariantCulture)}%)")); + OpenPicker(new Vector2(x, y + 22), t.Following ? FollowTier : (uint)t.View, id => + DamageCommands.SetViewTier(id == FollowTier ? -1 : (int)id)); + } + ImGuiNET.ImGui.SetItemTooltip( + "Aelrynth's awakened worlds and scaled dungeons have the same monsters, with " + + $"{t.Percent.ToString("0.#", CultureInfo.InvariantCulture)}% more health, skills and damage per tier.\n" + + "HP, kills, casts to kill, seconds per kill and hit rate here are this tier's; damage per cast,\n" + + "weaknesses and your settings are the same at every tier.\n" + + (here ? "Showing the tier where you are (pin)." : $"You are in {TierName(t.Current)}; pick \"Where I am\" to follow it.")); + return x + w + 6; + } + + private void SetFilter(uint wid, string name) + { + _filterWid = wid; + _filterLabel = "Weapon: " + Trunc(name, 22) + " " + PhosphorIcons.CaretDown; + } + + private const string SearchHint = PhosphorIcons.MagnifyingGlass + " Search monster / wcid…"; + private const string RulesHint = "one rule for many monsters (e.g. Olthoi), or for one you haven't met yet"; + private const string ResetLabel = PhosphorIcons.ArrowCounterClockwise + " Reset stats"; + private const string SortDown = " " + PhosphorIcons.CaretDown, SortUp = " " + PhosphorIcons.CaretUp; + + // ===================================================================== + // Name rules (folded by default): every rule but Default, and an add line + // ===================================================================== + + private static bool _rulesOpen; + private readonly byte[] _newRuleName = new byte[128], _newRuleExpr = new byte[512]; + private string _armedDelete = ""; // a rule whose x was clicked once: the second click deletes it + // Monsters met (rows in the table) by name: their rule opens their full Monster Detail. + private readonly Dictionary<string, uint> _metByName = new(StringComparer.OrdinalIgnoreCase); + + private static bool IsDefaultRule(Rule r) => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase); + + private void NameRules(float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + List<Rule>? all = _rules?.Parsed.Rules; + int count = 0; + if (all != null) foreach (Rule r in all) if (!IsDefaultRule(r)) count++; + + string label = (_rulesOpen ? PhosphorIcons.CaretDown : PhosphorIcons.CaretRight) + " Name rules (" + count + ")"; + if (Button("##rules", label, p, new Vector2(w, 22), White, HeaderBg, EntryBorder, leftAlign: true)) + { + _rulesOpen = !_rulesOpen; + _armedDelete = ""; + } + ImGuiNET.ImGui.SetItemTooltip("Rules by name: a rule covers every monster whose name contains it, met or not.\n" + + "The first one that matches, top to bottom, is used; a monster's own settings are rules here too."); + float lw = ImGuiNET.ImGui.CalcTextSize(label).X; + if (w - lw - 30 > 40) + dl.AddText(new Vector2(p.X + lw + 20, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Dim, Fit(RulesHint, w - lw - 30)); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + if (!_rulesOpen) return; + + float listH = Math.Min(Math.Max(1, count), 6) * (RowH + 1) + 2; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1)); + ImGuiNET.ImGui.BeginChild("##name_rules", new Vector2(w, listH)); + if (all == null || count == 0) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 3)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), all == null + ? " Monster rules not loaded yet." : " No name rules yet: add one below."); + } + else + { + int i = 0; + foreach (Rule r in all) + if (!IsDefaultRule(r)) NameRuleRow(r, i++); + } + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + AddRuleLine(w); + } + + // Name | P | expression | edit | x. The name (or the edit button) opens its Monster Detail. + private void NameRuleRow(Rule r, int index) + { + const float prioW = 34, btnW = 24; + float iw = ImGuiNET.ImGui.GetContentRegionAvail().X; + float exprW = Math.Min(240, iw * 0.35f); + float nameW = Math.Max(60, iw - prioW - exprW - 2 * btnW - 4); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.AddRectFilled(p, p + new Vector2(iw, RowH), index % 2 == 0 ? RowBg : HeaderBg); + ImGuiNET.ImGui.PushID(r.Name); + + bool met = _metByName.TryGetValue(r.Name, out uint wcid); + string name = r.Name; + if (NameLink("##rn", name, new Vector2(p.X + 4, p.Y), nameW - 8, met ? White : Gold, ImGuiFonts.Get(UiFont.Ui11))) + OpenRule(name); + ImGuiNET.ImGui.SetItemTooltip(met + ? "This monster's own settings (wcid " + wcid.ToString(CultureInfo.InvariantCulture) + "). Click for its details." + : "Click to edit this rule."); + float x = p.X + nameW; + + dl.AddText(new Vector2(x + 4, ty), White, r.Priority.ToString(CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y)); + ImGuiNET.ImGui.InvisibleButton("##rp", new Vector2(prioW, RowH)); + ImGuiNET.ImGui.SetItemTooltip("Target priority (higher is attacked first)"); + x += prioW; + + bool hasExpr = !string.IsNullOrWhiteSpace(r.MatchExpression); + dl.AddText(new Vector2(x + 4, ty), hasExpr ? White : Dim, hasExpr ? Fit(r.MatchExpression, exprW - 8) : "by name only"); + if (hasExpr) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y)); + ImGuiNET.ImGui.InvisibleButton("##rx", new Vector2(exprW, RowH)); + ImGuiNET.ImGui.SetItemTooltip("Match expression: " + r.MatchExpression); + } + x += exprW; + + if (IconButton("##ro", PhosphorIcons.PencilSimple, new Vector2(x + 2, p.Y + 2), new Vector2(btnW - 4, 18), White, EntryBg, EntryBorder)) + OpenRule(name); + ImGuiNET.ImGui.SetItemTooltip("Edit: priority, damage, expression, spells"); + x += btnW; + + bool armed = _armedDelete.Equals(name, StringComparison.OrdinalIgnoreCase); + if (IconButton("##rd", armed ? PhosphorIcons.Trash : PhosphorIcons.X, new Vector2(x + 2, p.Y + 2), new Vector2(btnW - 4, 18), + armed ? White : DeleteRed, armed ? ClearBg : 0, armed ? ResetBorder : 0)) + { + if (armed) { DamageCommands.ResetRule(name); _armedDelete = ""; } + else _armedDelete = name; + } + ImGuiNET.ImGui.SetItemTooltip(armed ? "Click again to delete " + name : "Delete this rule (click twice)"); + + ImGuiNET.ImGui.PopID(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + RowH)); + ImGuiNET.ImGui.Dummy(new Vector2(iw, 0)); + } + + /// <summary>A rule's Monster Detail: the monster's full page when it was met, else the rule alone.</summary> + private void OpenRule(string name) + { + if (_metByName.TryGetValue(name, out uint wcid)) DamageDetailFace.Show(wcid, name); + else DamageDetailFace.Show(0, name); + } + + // Name | Match expression | Target | Add + private void AddRuleLine(float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float tgtW = 74, addW = 64; + float nameW = Math.Clamp((w - tgtW - addW - 12) * 0.4f, 80, 240); + float exprW = Math.Max(60, w - nameW - tgtW - addW - 12); + bool enter = HintInput("##newrule", _newRuleName, p.X, p.Y, nameW, "Name part, e.g. Olthoi…"); + ImGuiNET.ImGui.SetItemTooltip("Every monster whose name contains this. Enter to add."); + enter |= HintInput("##newexpr", _newRuleExpr, p.X + nameW + 4, p.Y, exprW, "Match expression (optional)…"); + ImGuiNET.ImGui.SetItemTooltip("Only when this is true as well. Variables: name, range, typeid, maxhp, metastate\nExamples: range>5, maxhp>1000"); + float x = p.X + nameW + exprW + 8; + if (Button("##ruletarget", PhosphorIcons.Crosshair + " Target", new Vector2(x, p.Y), new Vector2(tgtW, 22), White, EntryBg, EntryBorder)) + { + string target = _rules?.Parsed.CurrentTargetName ?? ""; + if (target.Length > 0) WriteUtf8(_newRuleName, target); + } + ImGuiNET.ImGui.SetItemTooltip("Fill in the monster you have selected"); + x += tgtW + 4; + if (Button("##ruleadd", PhosphorIcons.Plus + " Add", new Vector2(x, p.Y), new Vector2(addW, 22), Teal, EntryBg, Teal) | enter) + { + string name = Utf8(_newRuleName).Trim(); + if (name.Length > 0) + { + DamageCommands.AddRule(name, Utf8(_newRuleExpr)); + Array.Clear(_newRuleName); + Array.Clear(_newRuleExpr); + } + } + ImGuiNET.ImGui.SetItemTooltip("Add the rule. It starts as a copy of Default: click its name to set it up."); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + /// <summary>An edit box with a grey hint while empty; true when Enter was pressed in it.</summary> + private static bool HintInput(string id, byte[] buffer, float x, float y, float width, string hint) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); + ImGuiNET.ImGui.SetNextItemWidth(width); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, SearchBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, EntryBorder); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, White); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f)); + bool enter = ImGuiNET.ImGui.InputText(id, buffer, (uint)buffer.Length, ImGuiInputTextFlags.EnterReturnsTrue); + bool active = ImGuiNET.ImGui.IsItemActive(); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(3); + if (buffer[0] == 0 && !active) + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(x + 5, y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Dim, hint); + return enter; + } + + // ===================================================================== + // Table + // ===================================================================== + + private void Table() + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 clipMin = ImGuiNET.ImGui.GetWindowPos(); + Vector2 clipMax = clipMin + ImGuiNET.ImGui.GetWindowSize(); + + // Header. + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddRectFilled(p, p + new Vector2(TableW, RowH), HeaderBg); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + for (int c = 0; c < Headers.Length; c++) + { + if (Headers[c].Length == 0) continue; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + ColX[c], p.Y)); + ImGuiNET.ImGui.SetNextItemAllowOverlap(); + if (ImGuiNET.ImGui.InvisibleButton("##sort" + c, new Vector2(Math.Max(1, ColW[c] - 4), RowH))) + { + if (_sortCol == c) _sortDesc = !_sortDesc; + else { _sortCol = c; _sortDesc = c is ColKills or ColHp or ColPrio; } // numbers: biggest first + SortShown(); + } + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + ImGuiNET.ImGui.SetItemTooltip("Sort by " + Headers[c]); + string label = Headers[c] + (_sortCol == c ? (_sortDesc ? SortDown : SortUp) : ""); + dl.AddText(bold, bold.FontSize, new Vector2(p.X + ColX[c] + 4, p.Y + (RowH - bold.FontSize) * 0.5f), + _sortCol == c ? Teal : White, label); + } + ImGuiNET.ImGui.SetCursorScreenPos(p); + // Drag a column's right edge in the header to resize it. + for (int c = 0; c < ColW.Length - 1; c++) + { + int col = c; + if (FaceKit.ColumnDivider($"##dcol{c}", p.X + ColX[c] + ColW[c], p.Y, RowH, ref ColW[c], 18, + v => RynthCore.Engine.UI.PanelColumnStore.Set("Damage2." + ColKeys[col], v))) + ColX = BuildColX(); + } + ImGuiNET.ImGui.Dummy(new Vector2(TableW, RowH)); + + bool anyMonster = false; + foreach (DamageRow r in _shown) + { + anyMonster |= !r.IsDefault; + DrawRow(r, clipMin, clipMax); + } + + if (!anyMonster && _view != null && _view.Bound) + { + bool filtering = _filterWid != 0 || _searchText.Length > 0; + bool anyData = _view.Rows.Exists(r => !r.IsDefault); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), anyData && filtering + ? " No monsters match the current filter." + : " No monsters yet: fight some and they show up here."); + } + } + + private void DrawRow(DamageRow r, Vector2 clipMin, Vector2 clipMax) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (p.Y + RowH < clipMin.Y || p.Y > clipMax.Y) + { + ImGuiNET.ImGui.Dummy(new Vector2(TableW, RowH)); // off screen: keep the layout, skip the drawing + return; + } + RowText t = _text[r]; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(p, p + new Vector2(TableW, RowH), r.IsDefault ? HeaderBg : RowBg); + if (r.Targeted) + { + // The monster being fought (or selected): teal wash, a bar on the left, an outline. + dl.AddRectFilled(p, p + new Vector2(TableW, RowH), TargetBg); + dl.AddRectFilled(p, p + new Vector2(3, RowH), Teal); + dl.AddRect(p, p + new Vector2(TableW, RowH), Teal); + } + else if (r.Nearby) + { + // On the player's landblock: a green wash and bar. + dl.AddRectFilled(p, p + new Vector2(TableW, RowH), NearbyBg); + dl.AddRectFilled(p, p + new Vector2(3, RowH), NearbyBar); + } + ImGuiNET.ImGui.PushID(r.IsDefault ? "default" : r.Key); + float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + + if (r.IsDefault) + { + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + if (NameLink("##dname", "DEFAULT", new Vector2(p.X + ColX[ColMonster] + 4, p.Y), ColW[ColMonster] - 8, Teal, bold)) + DamageDetailFace.Show(0, "Default"); + ImGuiNET.ImGui.SetItemTooltip("Default spell settings (debuffs, shapes): every monster set to Default uses them."); + PrioCell("default", "Default", null, t, p); + dl.AddText(new Vector2(p.X + ColX[ColWeak] + 4, ty), Dim, "weapon →"); + if (CellPicker("##dw", t.Weapon, t.WeaponGold, p, ColWeapon)) + { + _pickItems.Clear(); + _pickItems.Add((0, "Auto (per monster)")); + _pickItems.AddRange(_view!.WeaponChoices); + OpenPicker(new Vector2(p.X + ColX[ColWeapon], p.Y + RowH), r.AssignedWid, DamageCommands.SetDefaultWeapon); + } + ImGuiNET.ImGui.SetItemTooltip("Default weapon: used by every monster that has no weapon of its own."); + DefaultOffhandAndPet(p); + DebuffCell("Default", p, ty); + ImGuiNET.ImGui.PopID(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + RowH)); + ImGuiNET.ImGui.Dummy(new Vector2(TableW, 0)); + return; + } + + // Monster: D (follows Default), then the name, which opens Monster Detail. + bool custom = _rules?.HasCustomRule(r.Name) ?? false; + bool onDefault = !custom && r.AssignedWid == 0; + if (Button("##d", "D", new Vector2(p.X + ColX[ColMonster] + 2, p.Y + 2), new Vector2(16, 18), onDefault ? ToggleOn : Dim, EntryBg, + onDefault ? ToggleOn : EntryBorder)) + { + if (onDefault) DamageCommands.EditRule(r.Name, static _ => { }); // off Default: an editable rule of its own + else + { + DamageCommands.ResetRule(r.Name); // back on Default + DamageCommands.SetWeapon(r.Wcid, 0); + } + } + ImGuiNET.ImGui.SetItemTooltip("Follow the Default config (spells, weapon). Uncheck to customize this monster."); + if (NameLink("##name", r.Name, new Vector2(p.X + ColX[ColMonster] + 22, p.Y), ColW[ColMonster] - 24, custom ? Gold : White, + ImGuiFonts.Get(UiFont.Ui11))) + DamageDetailFace.Show(r.Wcid, r.Name); + ImGuiNET.ImGui.SetItemTooltip("Details: weaknesses, accuracy, damage, summons, damage taken and spell settings (wcid " + t.Wcid + ")."); + + PrioCell(r.Key, r.Name, t.PrioCopyFrom, t, p); + HpCell(r, p); + + if (t.WeakTop.Length > 0) + { + dl.AddText(new Vector2(p.X + ColX[ColWeak] + 4, ty), White, Fit(t.WeakTop, ColW[ColWeak] - 8)); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + ColX[ColWeak], p.Y)); + ImGuiNET.ImGui.InvisibleButton("##weak", new Vector2(ColW[ColWeak], RowH)); + ImGuiNET.ImGui.SetItemTooltip(r.Weak + "\nDamage taken: 1.0 = full, 0.5 = half. From " + r.WeakSrc + + ".\nAuto spells, weapons and summons use the first element this character has."); + } + else + dl.AddText(new Vector2(p.X + ColX[ColWeak] + 4, ty), Dim, "—"); + + if (CellPicker("##w", t.Weapon, t.WeaponGold, p, ColWeapon)) + { + _pickItems.Clear(); + _pickItems.Add((0, "Auto")); + _pickItems.AddRange(_view!.WeaponChoices); + uint wcid = r.Wcid; + OpenPicker(new Vector2(p.X + ColX[ColWeapon], p.Y + RowH), r.AssignedWid, id => DamageCommands.SetWeapon(wcid, id)); + } + ImGuiNET.ImGui.SetItemTooltip("Weapon to use on this monster. Auto = its rule's Damage type (Monster Detail), else an Items weapon of the element it's weakest to, else the learned best."); + + if (CellPicker("##o", t.Offhand, t.OffhandGold, p, ColOffhand)) + OpenOffhandPicker(r, new Vector2(p.X + ColX[ColOffhand], p.Y + RowH)); + ImGuiNET.ImGui.SetItemTooltip("Off hand against this monster. Auto = the DEFAULT line's.\n" + + "Shield; Dual wield (needs the skill); None = leave the off hand alone; or a listed item."); + + if (CellPicker("##p", t.Pet, t.PetGold, p, ColPet)) + { + List<(string Key, string Name)> pets = _view!.PetChoices; + _pickItems.Clear(); + uint sel = 0; + for (int i = 0; i < pets.Count; i++) + { + _pickItems.Add(((uint)i, pets[i].Name)); + if (pets[i].Key == r.Pet) sel = (uint)i; + } + uint wcid = r.Wcid; + OpenPicker(new Vector2(p.X + ColX[ColPet], p.Y + RowH), sel, i => + { + if (i < pets.Count) DamageCommands.SetPet(wcid, pets[(int)i].Key); + }); + } + ImGuiNET.ImGui.SetItemTooltip("Summon for this monster. Auto = an essence of the element it takes most damage from (Weak to); or pick an element or a specific essence."); + + dl.AddText(new Vector2(p.X + ColX[ColKills] + 4, ty), White, t.Kills); + dl.AddText(new Vector2(p.X + ColX[ColSec] + 4, ty), r.SecKill > 0 ? White : Dim, t.Sec); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + ColX[ColSec], p.Y)); + ImGuiNET.ImGui.InvisibleButton("##sec", new Vector2(ColW[ColSec], RowH)); + ImGuiNET.ImGui.SetItemTooltip(t.SecTip); + + DebuffCell(r.Name, p, ty); + + if (IconButton("##del", PhosphorIcons.X, new Vector2(p.X + ColX[ColDel] + 2, p.Y + 2), new Vector2(22, 18), DeleteRed, 0, 0)) + { + _removeWcid = r.Wcid; + _removeName = r.Name; + _removeOpen = true; + } + ImGuiNET.ImGui.SetItemTooltip("Remove " + r.Name + " from this list (asks first)."); + + ImGuiNET.ImGui.PopID(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + RowH)); + ImGuiNET.ImGui.Dummy(new Vector2(TableW, 0)); + } + + // The DEFAULT line's Offhand and Pet: the Default monster rule's OffhandId (1-4 a mode, else an + // item id; 0 = Auto) and PetDamage ("PAuto" or an element). Every monster without its own uses them. + private static readonly (uint Id, string Name)[] OffhandModeChoices = + { (1, "Auto"), (2, "Shield"), (3, "Dual wield"), (4, "None") }; + private static readonly string[] PetElements = { "Fire", "Cold", "Lightning", "Acid", "Nether", "Slash", "Pierce", "Bludgeon" }; + + private void DefaultOffhandAndPet(Vector2 p) + { + Rule? def = _rules?.DefaultRule(); + int offId = def?.OffhandId ?? 0; + string offText = offId is 0 or 1 ? "Auto" : offId is >= 2 and <= 4 ? OffhandModeChoices[offId - 1].Name : ""; + if (offText.Length == 0) + { + foreach (var c in _view!.WeaponChoices) + if (c.Id == unchecked((uint)offId)) { offText = Trunc(c.Name, 16); break; } + if (offText.Length == 0) offText = "Offhand " + unchecked((uint)offId); + } + if (CellPicker("##doff", offText, offId > 1, p, ColOffhand)) + { + _pickItems.Clear(); + _pickItems.AddRange(OffhandModeChoices); + _pickItems.AddRange(_view!.WeaponChoices); + OpenPicker(new Vector2(p.X + ColX[ColOffhand], p.Y + RowH), offId == 0 ? 1u : unchecked((uint)offId), + id => DamageCommands.EditRule("Default", r => r.OffhandId = unchecked((int)id))); + } + ImGuiNET.ImGui.SetItemTooltip("Default offhand: used by every monster without its own.\n" + + "Auto = a listed shield (dual wield only with Prefer dual wield on); Shield; Dual wield (needs the skill);\n" + + "None = leave the off hand alone; or a specific item. Thrown weapons get a shield too."); + + string pet = def?.PetDamage ?? "PAuto"; + int petIdx = Array.FindIndex(PetElements, e => e.Equals(pet, StringComparison.OrdinalIgnoreCase)); + if (CellPicker("##dpet", petIdx >= 0 ? PetElements[petIdx] : "Auto", petIdx >= 0, p, ColPet)) + { + _pickItems.Clear(); + _pickItems.Add((0, "Auto")); + for (int i = 0; i < PetElements.Length; i++) _pickItems.Add(((uint)(i + 1), PetElements[i])); + OpenPicker(new Vector2(p.X + ColX[ColPet], p.Y + RowH), (uint)(petIdx + 1), + i => DamageCommands.EditRule("Default", r => r.PetDamage = i == 0 || i > PetElements.Length ? "PAuto" : PetElements[i - 1])); + } + ImGuiNET.ImGui.SetItemTooltip("Default pet element: used by every monster without its own.\nAuto = an essence of the element the monster takes most damage from."); + } + + // A monster's Offhand picker: Auto, the modes, then the listed items. Modes go in the monster's + // own rule (made if needed) and drop the item picked here; Auto drops both, so the DEFAULT line + // applies; an item is kept per monster (wcid), and lifts a None in its rule (None ignores items). + private static readonly (uint Id, string Name)[] RowOffhandModes = + { (0, "Auto"), (2, "Shield"), (3, "Dual wield"), (4, "None") }; + + private void OpenOffhandPicker(DamageRow r, Vector2 at) + { + Rule? own = _rules?.FindRule(r.Name); + int ruleOff = own?.OffhandId ?? 0; + uint sel = r.AssignedOff != 0 ? r.AssignedOff : ruleOff is 0 or 1 ? 0u : unchecked((uint)ruleOff); + _pickItems.Clear(); + _pickItems.AddRange(RowOffhandModes); + _pickItems.AddRange(_view!.WeaponChoices); + uint wcid = r.Wcid, item = r.AssignedOff; + string name = r.Name; + OpenPicker(at, sel, id => + { + if (id is >= 2 and <= 4) + { + DamageCommands.EditRule(name, rule => rule.OffhandId = (int)id); + if (item != 0) DamageCommands.SetOffhand(wcid, 0); + } + else if (id == 0) + { + if (item != 0) DamageCommands.SetOffhand(wcid, 0); + if (own != null && ruleOff != 0) DamageCommands.EditRule(name, rule => rule.OffhandId = 0); + } + else + { + DamageCommands.SetOffhand(wcid, id); + if (own != null && ruleOff == 4) DamageCommands.EditRule(name, rule => rule.OffhandId = 0); + } + }); + } + + private string WeaponName(uint id) + { + if (_view != null) + foreach (var c in _view.WeaponChoices) + if (c.Id == id) return c.Name; + return "Offhand " + id; + } + + /// <summary>The rule a monster uses: its own, else Default. custom = it has its own.</summary> + private Rule? RuleFor(string name, out bool custom) + { + custom = false; + if (_rules == null || _rules.Parsed.Rules.Count == 0) return null; + if (name.Equals("Default", StringComparison.OrdinalIgnoreCase)) return _rules.DefaultRule(); + Rule? exact = _rules.FindRule(name); + custom = exact != null; + return exact ?? _rules.DefaultRule(); + } + + /// <summary>Debuffs: a caret that opens the debuff popup, then the active ones as letters.</summary> + private void DebuffCell(string name, Vector2 p, float ty) + { + Rule? view = RuleFor(name, out bool custom); + var bp = new Vector2(p.X + ColX[ColDebuffs] + 2, p.Y + 2); + if (IconButton("##debuffs", PhosphorIcons.CaretDown, bp, new Vector2(18, 18), White, EntryBg, EntryBorder) && view != null) + { + _debuffFor = name; + _debuffPos = new Vector2(bp.X, bp.Y + 20); + WriteUtf8(_customBuf, view.CustomDebuffs ?? ""); + _debuffOpen = true; + } + ImGuiNET.ImGui.SetItemTooltip("Debuffs to cast on " + name); + if (view == null) return; + string marks = DamageCommands.DebuffMarks(view); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddText(new Vector2(bp.X + 24, ty), custom || name == "Default" ? Gold : Dim, marks.Length > 0 ? Fit(marks, ColW[ColDebuffs] - 30) : "—"); + if (marks.Length > 0) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bp.X + 22, p.Y)); + ImGuiNET.ImGui.InvisibleButton("##dmarks", new Vector2(Math.Max(1, ColW[ColDebuffs] - 26), RowH)); + ImGuiNET.ImGui.SetItemTooltip(DebuffTip(view)); + } + } + + private static string DebuffTip(Rule v) + { + var parts = new List<string>(); + foreach (var (field, label, _) in DamageCommands.DebuffDefs) if (v.GetToggle(field)) parts.Add(label); + if (!string.IsNullOrEmpty(v.ExVuln) && !v.ExVuln.Equals("None", StringComparison.OrdinalIgnoreCase)) parts.Add("Extra Vuln: " + v.ExVuln); + if (!string.IsNullOrWhiteSpace(v.CustomDebuffs)) parts.Add("Yours: " + v.CustomDebuffs); + return string.Join("\n", parts); + } + + private void DebuffPopup() + { + if (_debuffOpen) + { + _debuffOpen = false; + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Clamp(_debuffPos.X, 0, Math.Max(0, display.X - 300)), _debuffPos.Y)); + ImGuiNET.ImGui.OpenPopup("##dmg_debuffs"); + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, PickerBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 5f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8)); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(300, 0)); + bool open = ImGuiNET.ImGui.BeginPopup("##dmg_debuffs"); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) return; + + string name = _debuffFor; + Rule? view = RuleFor(name, out bool custom); + bool isDefault = name.Equals("Default", StringComparison.OrdinalIgnoreCase); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), "Debuffs · " + name); + ImGuiNET.ImGui.PopFont(); + if (view == null) + { + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), "Monster rules not loaded yet."); + ImGuiNET.ImGui.EndPopup(); + return; + } + ImGuiNET.ImGui.PushTextWrapPos(0); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(custom || isDefault ? 0xFFFFD16A : 0xFFC8D4E0), + isDefault ? "Every monster set to Default uses these." : custom ? "This monster's own debuffs." : "Following Default: a change here gives it its own."); + ImGuiNET.ImGui.PopTextWrapPos(); + + foreach (var (field, label, tip) in DamageCommands.DebuffDefs) + { + bool on = view.GetToggle(field); + if (ImGuiNET.ImGui.Checkbox(label + "##db_" + field, ref on)) + { + bool v = on; + string f = field; + DamageCommands.EditRule(name, rule => rule.SetToggle(f, v)); + } + ImGuiNET.ImGui.SetItemTooltip(tip); + } + + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), "Extra Vuln"); + ImGuiNET.ImGui.SameLine(); + string ex = string.IsNullOrEmpty(view.ExVuln) ? "None" : view.ExVuln; + ImGuiNET.ImGui.SetNextItemWidth(ImGuiNET.ImGui.CalcTextSize("Lightning").X + 40); + if (ImGuiNET.ImGui.BeginCombo("##db_exvuln", ex)) + { + foreach (string v in DamageCommands.ExVulnTypes) + if (ImGuiNET.ImGui.Selectable(v, v == ex)) + { + string pick = v; + DamageCommands.EditRule(name, rule => rule.ExVuln = pick); + } + ImGuiNET.ImGui.EndCombo(); + } + ImGuiNET.ImGui.SetItemTooltip("A vulnerability of another element, on top of Vuln (which follows the attack's element)."); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), "Your own (comma separated):"); + ImGuiNET.ImGui.SetNextItemWidth(-1); + bool enter = ImGuiNET.ImGui.InputText("##db_custom", _customBuf, (uint)_customBuf.Length, ImGuiInputTextFlags.EnterReturnsTrue); + if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + string typed = Utf8(_customBuf).Trim().Trim(',').Trim(); + DamageCommands.EditRule(name, rule => rule.CustomDebuffs = typed); + } + ImGuiNET.ImGui.PushTextWrapPos(0); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF8FA3B5), + "A spell's base name casts the best tier you know (e.g. Corrosion Vulnerability Other); a full name casts that spell. Enter to save."); + ImGuiNET.ImGui.PopTextWrapPos(); + + if (custom) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + if (ImGuiNET.ImGui.SmallButton("Back to Default")) { DamageCommands.ResetRule(name); ImGuiNET.ImGui.CloseCurrentPopup(); } + ImGuiNET.ImGui.SetItemTooltip("Drop this monster's own settings (debuffs and spell shapes) and follow Default again."); + } + ImGuiNET.ImGui.EndPopup(); + } + + /// <summary>Text that opens something: hand cursor and underline on hover.</summary> + private bool NameLink(string id, string text, Vector2 pos, float width, uint color, ImFontPtr font) + { + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, new Vector2(Math.Max(1, width), RowH)); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + if (hot) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + string shown = Fit(text, width); + float ty = pos.Y + (RowH - font.FontSize) * 0.5f; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddText(font, font.FontSize, new Vector2(pos.X, ty), hot ? Teal : color, shown); + if (hot) + { + float w = ImGuiNET.ImGui.CalcTextSize(shown).X; + dl.AddLine(new Vector2(pos.X, ty + font.FontSize), new Vector2(pos.X + w, ty + font.FontSize), Teal); + } + return clicked; + } + + /// <summary> + /// A monster's Priority cell text: its own rule's priority (gold); else the name rule that + /// covers it (as targeting finds it; an edit copies that rule, so its spells stay); else + /// Default's (dim, like the Monster Detail page shows it). + /// </summary> + private void BuildPrio(string monster, RowText t) + { + if (_rules == null || _rules.Parsed.Rules.Count == 0) return; + Rule? own = _rules.FindRule(monster); + if (own != null) + { + t.Prio = own.Priority; + t.PrioGold = true; + t.PrioTip = "This monster's own priority: higher is attacked first (1 = normal). While a higher-priority monster is in range, lower ones wait."; + return; + } + Rule? cover = DamageCommands.CoveringRule(_rules.Parsed.Rules, monster); + if (cover != null) + { + t.Prio = cover.Priority; + // A rule with a match expression only sometimes sets the spells, so a copy starts from Default. + t.PrioCopyFrom = string.IsNullOrWhiteSpace(cover.MatchExpression) ? cover.Name : null; + t.PrioTip = "From the name rule \"" + cover.Name + "\". A change here gives this monster its own rule, copied from " + + (t.PrioCopyFrom != null ? "that one." : "Default."); + return; + } + t.Prio = _rules.DefaultRule().Priority; + t.PrioTip = "Following Default. A change here gives this monster its own rule (a copy of Default).\nHigher is attacked first (1 = normal)."; + } + + /// <summary> + /// Priority: - / + and the number between them (type one, Enter to save). Edits the rule through + /// DamageCommands.EditRule, like the Monster Detail page. Gold = the monster's own (or Default's). + /// </summary> + private void PrioCell(string key, string ruleName, string? copyFrom, RowText t, Vector2 p) + { + if (t.Prio == int.MinValue) + { + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + ColX[ColPrio] + 4, p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Dim, "—"); + return; + } + if (!_prio.TryGetValue(key, out PrioEdit? e)) + _prio[key] = e = new PrioEdit(); + int prio = t.Prio; + float x0 = p.X + ColX[ColPrio], w = ColW[ColPrio]; + const float bw = 16; + bool buttons = w >= 2 * bw + 22; // a narrow column keeps just the box + + if (buttons) + { + if (IconButton("##pdn", PhosphorIcons.Minus, new Vector2(x0 + 1, p.Y + 2), new Vector2(bw, 18), prio > 1 ? White : Dim, EntryBg, EntryBorder) + && prio > 1) + SetPriority(ruleName, copyFrom, prio - 1, e); + ImGuiNET.ImGui.SetItemTooltip("Lower priority"); + if (IconButton("##pup", PhosphorIcons.Plus, new Vector2(x0 + w - bw - 1, p.Y + 2), new Vector2(bw, 18), White, EntryBg, EntryBorder) + && prio < MaxPriority) + SetPriority(ruleName, copyFrom, prio + 1, e); + ImGuiNET.ImGui.SetItemTooltip("Higher priority"); + } + + if (!e.Active && e.Shown != prio) + { + WriteUtf8(e.Buffer, prio.ToString(CultureInfo.InvariantCulture)); + e.Shown = prio; + } + float fx = buttons ? x0 + bw + 3 : x0 + 1; + float fw = buttons ? w - 2 * bw - 6 : w - 2; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(fx, p.Y + 2)); + ImGuiNET.ImGui.SetNextItemWidth(Math.Max(8, fw)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, SearchBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, t.PrioGold ? Gold : Dim); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(2, (18 - ImGuiNET.ImGui.GetFontSize()) * 0.5f)); + bool enter = ImGuiNET.ImGui.InputText("##prio", e.Buffer, (uint)e.Buffer.Length, + ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.EnterReturnsTrue); + e.Active = ImGuiNET.ImGui.IsItemActive(); + bool commit = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + ImGuiNET.ImGui.SetItemTooltip(t.PrioTip + "\nType a number, Enter to save."); + if (!commit) return; + + if (int.TryParse(Utf8(e.Buffer).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int typed)) + { + typed = Math.Clamp(typed, 0, MaxPriority); + if (typed != prio) SetPriority(ruleName, copyFrom, typed, e); + else e.Shown = int.MinValue; + } + else e.Shown = int.MinValue; // not a number: show the saved value again + } + + private const int MaxPriority = 999; + + private static void SetPriority(string ruleName, string? copyFrom, int value, PrioEdit e) + { + DamageCommands.EditRule(ruleName, r => r.Priority = value, copyFrom); + e.Shown = int.MinValue; // show the plugin's value when it comes back + } + + // "M" (manual HP on/off) + the HP box: gold and editable when manual, read-only otherwise. + private void HpCell(DamageRow r, Vector2 p) + { + if (!_hp.TryGetValue(r.Key, out HpEdit? e)) + _hp[r.Key] = e = new HpEdit(); + bool manual = r.HpManual || e.ForceManual; + if (r.HpManual) e.ForceManual = false; + + if (Button("##m", "M", new Vector2(p.X + ColX[ColHp] + 1, p.Y + 2), new Vector2(16, 18), manual ? Gold : Dim, EntryBg, + manual ? Gold : EntryBorder)) + { + if (r.HpManual) { DamageCommands.SetHp(r.Wcid, 0); e.ForceManual = false; } // manual → auto + else + { + if (r.Hp > 0) DamageCommands.SetHp(r.Wcid, r.Hp); // auto → manual, seeded + e.ForceManual = true; + e.FocusNext = true; + } + } + ImGuiNET.ImGui.SetItemTooltip("Manual max-HP for this monster (off = auto)"); + + // An Aelrynth tier not appraised yet shows real Dereth's HP scaled by the tier, marked "~". + bool estimate = r.HpEst && !manual; + int shownKey = estimate ? -r.Hp - 1 : r.Hp; // re-written when the estimate becomes a real value + if (!e.Active && e.Shown != shownKey) + { + WriteUtf8(e.Buffer, r.Hp > 0 ? (estimate ? "~" : "") + r.Hp.ToString(CultureInfo.InvariantCulture) : ""); + e.Shown = shownKey; + } + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + ColX[ColHp] + 19, p.Y + 2)); + ImGuiNET.ImGui.SetNextItemWidth(ColW[ColHp] - 21); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, SearchBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, manual ? Gold : estimate ? Dim : White); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(2, (18 - ImGuiNET.ImGui.GetFontSize()) * 0.5f)); + if (e.FocusNext) { ImGuiNET.ImGui.SetKeyboardFocusHere(); e.FocusNext = false; } + ImGuiInputTextFlags flags = ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.EnterReturnsTrue; + if (!manual) flags |= ImGuiInputTextFlags.ReadOnly; + bool enter = ImGuiNET.ImGui.InputText("##hp", e.Buffer, (uint)e.Buffer.Length, flags); + e.Active = ImGuiNET.ImGui.IsItemActive(); + if (estimate) + ImGuiNET.ImGui.SetItemTooltip("Estimated: real Dereth's HP plus this tier's scaling. The first fight at this tier\n" + + "reads the real number from the game and replaces it."); + bool commit = manual && (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + if (!commit) return; + + string typed = Utf8(e.Buffer).Trim(); + if (typed.Length == 0) DamageCommands.SetHp(r.Wcid, 0); + else if (int.TryParse(typed, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) && v > 0) + DamageCommands.SetHp(r.Wcid, v); + e.Shown = int.MinValue; // show the plugin's value when it comes back + } + + // ===================================================================== + // Popups (the picker and the reset confirmation), in the panel window + // ===================================================================== + + private void OpenPicker(Vector2 pos, uint selected, Action<uint> onPick) + { + _pickPos = pos; + _pickSel = selected; + _pickAction = onPick; + _pickOpen = true; + } + + private void Popups() + { + DebuffPopup(); + if (_pickOpen) + { + _pickOpen = false; + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Clamp(_pickPos.X, 0, Math.Max(0, display.X - 240)), _pickPos.Y)); + ImGuiNET.ImGui.OpenPopup("##dmg_pick"); + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, PickerBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1)); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(240, Math.Min(_pickItems.Count * 23 + 4, 360))); + bool open = ImGuiNET.ImGui.BeginPopup("##dmg_pick"); + ImGuiNET.ImGui.PopStyleVar(3); + ImGuiNET.ImGui.PopStyleColor(2); + if (open) + { + var pdl = ImGuiNET.ImGui.GetWindowDrawList(); + float iw = ImGuiNET.ImGui.GetContentRegionAvail().X; + for (int i = 0; i < _pickItems.Count; i++) + { + (uint id, string name) = _pickItems[i]; + ImGuiNET.ImGui.PushID(i); + Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos(); + bool click = ImGuiNET.ImGui.InvisibleButton("##it", new Vector2(iw, 22)); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + bool sel = id == _pickSel; + pdl.AddRectFilled(ip, ip + new Vector2(iw, 22), sel ? PickSel : hot ? Lighten(EntryBg) : EntryBg); + pdl.AddRect(ip, ip + new Vector2(iw, 22), EntryBorder); + pdl.AddText(ip + new Vector2(6, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), sel ? Teal : White, name); + if (click) + { + Action<uint>? act = _pickAction; + ImGuiNET.ImGui.CloseCurrentPopup(); + act?.Invoke(id); + } + } + ImGuiNET.ImGui.EndPopup(); + } + + if (_removeOpen) + { + _removeOpen = false; + Vector2 wp0 = ImGuiNET.ImGui.GetWindowPos(), ws0 = ImGuiNET.ImGui.GetWindowSize(); + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(wp0.X + Math.Max(4, (ws0.X - 360) / 2), wp0.Y + Math.Max(8, (ws0.Y - 130) / 3))); + ImGuiNET.ImGui.OpenPopup("##dmg_remove"); + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, PickerBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 6f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(14, 12)); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(360, 0)); + bool ropen = ImGuiNET.ImGui.BeginPopup("##dmg_remove"); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + if (ropen) + { + ImGuiNET.ImGui.PushTextWrapPos(0); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "Remove " + _removeName + "?"); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), + "Its learned numbers and your settings for it (weapon, offhand, pet, HP) are deleted. It comes back if you meet it again."); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + float rw = ImGuiNET.ImGui.GetContentRegionAvail().X; + Vector2 rp = ImGuiNET.ImGui.GetCursorScreenPos(); + if (Button("##remove_no", "Cancel", new Vector2(rp.X + rw - 176, rp.Y), new Vector2(80, 24), White, EntryBg, EntryBorder)) + ImGuiNET.ImGui.CloseCurrentPopup(); + if (Button("##remove_yes", PhosphorIcons.Trash + " Remove", new Vector2(rp.X + rw - 88, rp.Y), new Vector2(88, 24), White, ClearBg, ResetBorder)) + { + DamageCommands.RemoveMonster(_removeWcid); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(rp.X, rp.Y + 24)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + ImGuiNET.ImGui.EndPopup(); + } + + if (_resetOpen) + { + _resetOpen = false; + Vector2 wp = ImGuiNET.ImGui.GetWindowPos(), ws = ImGuiNET.ImGui.GetWindowSize(); + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(wp.X + Math.Max(4, (ws.X - 360) / 2), wp.Y + Math.Max(8, (ws.Y - 150) / 3))); + ImGuiNET.ImGui.OpenPopup("##dmg_reset"); + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, PickerBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 6f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(14, 12)); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(360, 0)); + open = ImGuiNET.ImGui.BeginPopup("##dmg_reset"); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + if (open) + { + ImGuiNET.ImGui.PushTextWrapPos(0); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "Reset ALL learned damage statistics?"); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), + "Monster names and your settings (manual HP, weapon/offhand picks, debuffs) are KEPT — only the learned damage, crit, casts-to-kill, kills and HP are cleared. This cannot be undone."); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (Button("##reset_no", "Cancel", new Vector2(p.X + w - 176, p.Y), new Vector2(80, 24), White, EntryBg, EntryBorder)) + ImGuiNET.ImGui.CloseCurrentPopup(); + if (Button("##reset_yes", "Clear stats", new Vector2(p.X + w - 88, p.Y), new Vector2(88, 24), White, ClearBg, ResetBorder)) + { + DamageCommands.ClearStats(); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 24)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + ImGuiNET.ImGui.EndPopup(); + } + } + + // ===================================================================== + // Widgets + // ===================================================================== + + private static bool Button(string id, string label, Vector2 pos, Vector2 size, uint fg, uint bg, uint border, + bool enabled = true, bool leftAlign = false) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size) && enabled; + bool hot = enabled && ImGuiNET.ImGui.IsItemHovered(); + if (bg != 0 || hot) + dl.AddRectFilled(pos, pos + size, enabled && ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : hot ? Lighten(bg == 0 ? EntryBg : bg) : bg, 3); + if (border != 0) dl.AddRect(pos, pos + size, border, 3); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(label); + float x = leftAlign ? pos.X + 5 : pos.X + (size.X - ts.X) * 0.5f; + dl.PushClipRect(pos, pos + size, true); + dl.AddText(new Vector2(x, pos.Y + (size.Y - ts.Y) * 0.5f), enabled ? fg : Dim, label); + dl.PopClipRect(); + return clicked; + } + + /// <summary>Button's look with a Phosphor icon centred on it (Ui11: about 10 px, for the table's 18 px buttons).</summary> + private static bool IconButton(string id, string icon, Vector2 pos, Vector2 size, uint fg, uint bg, uint border) + { + bool clicked = Button(id, string.Empty, pos, size, fg, bg, border); + PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(UiFont.Ui11), icon, pos, size, fg); + return clicked; + } + + private static bool FlowButton(string id, string label, uint fg, uint bg, uint border, float height, bool enabled = true) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var size = new Vector2(ImGuiNET.ImGui.CalcTextSize(label).X + 12, height); + bool clicked = Button(id, label, p, size, fg, bg, border, enabled); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.Dummy(size); + return clicked; + } + + /// <summary>A Weapon/Offhand/Pet cell button: gold when set by you, dim when automatic.</summary> + private static bool CellPicker(string id, string text, bool gold, Vector2 rowPos, int col) + { + var pos = new Vector2(rowPos.X + ColX[col] + 1, rowPos.Y + 2); + return Button(id, text, pos, new Vector2(ColW[col] - 2, 18), gold ? Gold : Dim, EntryBg, EntryBorder, leftAlign: true); + } + + private string Fit(string text, float width) + { + if (_fit.TryGetValue(text, out var hit) && Math.Abs(hit.Width - width) < 0.5f) return hit.Shown; + string shown = text; + if (ImGuiNET.ImGui.CalcTextSize(text).X > width) + { + int n = text.Length; + while (n > 0 && ImGuiNET.ImGui.CalcTextSize(text.Substring(0, n) + "…").X > width) n--; + shown = text.Substring(0, n) + "…"; + } + _fit[text] = (width, shown); + return shown; + } + + private static string Trunc(string s, int max) => + string.IsNullOrEmpty(s) ? "" : s.Length <= max ? s : s.Substring(0, max - 1) + "…"; + + private static string Utf8(byte[] buffer) + { + int len = Array.IndexOf(buffer, (byte)0); + return Encoding.UTF8.GetString(buffer, 0, len < 0 ? buffer.Length : len); + } + + private static void WriteUtf8(byte[] buffer, string text) + { + int n = Encoding.UTF8.GetBytes(text, 0, Math.Min(text.Length, buffer.Length - 1), buffer, 0); + buffer[Math.Min(n, buffer.Length - 1)] = 0; + } + + private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12); + private static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0); + + private static uint Scale(uint abgr, float k, int add) + { + uint a = abgr & 0xFF000000; + uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add); + uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add); + uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add); + return a | (b << 16) | (g << 8) | r; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs new file mode 100644 index 0000000..00af2e3 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs @@ -0,0 +1,319 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/DashboardDrawers.cs +// The RynthAi dashboard's slide-out drawers (Tom 2026-10-05: every drawer on +// the dashboard's left edge; only the vitals / target bars stay at its +// bottom). One tab per drawer, stacked down the left edge; a click slides +// that drawer's panel out to the left (to the right when the dashboard sits +// too close to the screen's left edge for the widest drawer). One drawer is +// open at a time: opening one closes the other, so the panels never stack +// and the tabs never jump. +// +// The mechanics live here (tabs, slide, side, placement, the one window); +// each drawer only draws its panel (DashboardDrawer.DrawPanel) and says how +// big it is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files and +// Patrol (RynthAiFace.Drawers.cs). +// +// A top-level ImGui window of its own, begun from inside the dashboard's Draw +// and placed against the dashboard's window every frame, so it follows the +// dashboard (and goes away with it). Each drawer's open/closed is saved with +// the dashboard's state (RynthAiDashboardState). Popped out the tabs are +// hidden: a popped-out dashboard is its own small window and the area around +// it lets clicks through to the game, so a drawer beside it couldn't be used +// (the dashboard falls back to its inline files block and patrol popup). +// +// AC thread only (inside the dashboard's Draw). +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +/// <summary>One drawer on the dashboard's left edge: its tab's look and its panel.</summary> +internal abstract class DashboardDrawer +{ + /// <summary>Set by the host: close this drawer from inside the panel (its close button).</summary> + public DashboardDrawers? Host { get; set; } + + /// <summary>Unique among the drawers ("##drawer_tab_" + Key is the tab's id).</summary> + public abstract string Key { get; } + /// <summary>Phosphor glyph on the tab.</summary> + public abstract string Icon { get; } + /// <summary>Lower-case name for "Hide the …" tooltips.</summary> + public abstract string Name { get; } + /// <summary>The closed tab's tooltip; <paramref name="right"/>: it slides out to the right.</summary> + public abstract string TabTooltip(bool right); + + /// <summary>Panel size in pixels at text scale <paramref name="k"/>.</summary> + public abstract float Width(float k); + public abstract float Height(float k); + + /// <summary>Every frame before drawing: <paramref name="showing"/> while any of the panel is out (subscriptions, data).</summary> + public virtual void Update(bool showing) { } + + /// <summary>Draws the whole panel at <paramref name="origin"/> (the host clips it to the part slid out).</summary> + public abstract void DrawPanel(Vector2 origin, float width, float height, float k); + + /// <summary>The saved open/closed (RynthAiDashboardState).</summary> + public abstract bool SavedOpen { get; } + public abstract void SaveOpen(bool open); + + private string? _tabId, _hideTip; + /// <summary>The tab's ImGui id and open tooltip (built once).</summary> + internal string TabId => _tabId ??= "##drawer_tab_" + Key; + internal string HideTip => _hideTip ??= "Hide the " + Name + "."; + + protected void Close() => Host?.Close(this); + + protected static float CalcWidth(ImFontPtr font, string text) + { + ImGuiNET.ImGui.PushFont(font); + float w = ImGuiNET.ImGui.CalcTextSize(text).X; + ImGuiNET.ImGui.PopFont(); + return w; + } + + // ── The shared panel frame: background, title row (icon + TITLE + note | close) ── + + protected static readonly uint DTeal = RynthTheme.Argb(0xFF26D9E6), DMute = RynthTheme.Argb(0xFFB8C8D8), + DWhite = RynthTheme.Argb(0xFFF2F7FC), DBtnFill = RynthTheme.Argb(0xFF16283A), DBtnBord = RynthTheme.Argb(0xFF34587A); + protected const float Pad = 6, TitleH = 18; + + /// <summary>Paints the panel's background and title row; returns the y under the title (pixels).</summary> + protected float PanelFrame(Vector2 origin, float panelW, float panelH, float k, string icon, string title, string? note, string closeTip) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(origin, origin + new Vector2(panelW, panelH), RynthTheme.RynthAiBackground, RynthTheme.RynthAiRounding); + dl.AddRect(origin, origin + new Vector2(panelW, panelH), RynthTheme.RynthAiBorder, RynthTheme.RynthAiRounding); + + float x = origin.X + Pad * k, w = panelW - 2 * Pad * k, y = origin.Y + Pad * k; + ImFontPtr f11 = ImGuiFonts.Get(UiFont.Dash11), f9 = ImGuiFonts.Get(UiFont.Dash9); + float th = TitleH * k; + float iconW = CalcWidth(f11, icon); + dl.AddText(f11, f11.FontSize, new Vector2(x, y + (th - f11.FontSize) * 0.5f), DTeal, icon); + dl.AddText(f11, f11.FontSize, new Vector2(x + iconW + 4 * k, y + (th - f11.FontSize) * 0.5f), DWhite, title); + if (note != null) + { + float tw = CalcWidth(f11, title); + dl.AddText(f9, f9.FontSize, new Vector2(x + iconW + 4 * k + tw + 4 * k, y + (th - f9.FontSize) * 0.5f + 1), DMute, note); + } + Vector2 closeSize = new(18 * k, 16 * k); + if (FaceKit.IconButton("##drawer_close", PhosphorIcons.X, new Vector2(x + w - closeSize.X, y + (th - closeSize.Y) * 0.5f), + closeSize, DMute, DBtnFill, border: DBtnBord, font: UiFont.Dash10)) + Close(); + ImGuiNET.ImGui.SetItemTooltip(closeTip); + return y + th + 4 * k; + } +} + +/// <summary>The tabs and the one open drawer beside the RynthAi dashboard.</summary> +internal sealed class DashboardDrawers +{ + private const string WindowId = "##rynthai_drawers"; + private const float SlideSeconds = 0.14f; + + private static readonly uint Teal = RynthTheme.Argb(0xFF26D9E6), Mute = RynthTheme.Argb(0xFFB8C8D8), + White = RynthTheme.Argb(0xFFF2F7FC), BtnFill = RynthTheme.Argb(0xFF16283A), BtnBord = RynthTheme.Argb(0xFF34587A); + + private readonly DashboardDrawer[] _drawers; + private int _open = -1; // the drawer open (or opening); -1 none + private int _shown = -1; // the drawer whose panel draws (a closing one until it has slid in) + private float _t; // slide position of _shown, 0 closed .. 1 open + private bool _loaded; + + public DashboardDrawers(params DashboardDrawer[] drawers) + { + _drawers = drawers; + foreach (DashboardDrawer d in drawers) d.Host = this; + } + + public bool IsOpen(DashboardDrawer d) => _open >= 0 && _drawers[_open] == d; + + /// <summary>Opens <paramref name="d"/> (closing the open one), or closes it when it is the open one.</summary> + public void Toggle(DashboardDrawer d) + { + if (IsOpen(d)) Close(d); + else Open(d); + } + + public void Open(DashboardDrawer d) + { + EnsureLoaded(); + int i = Array.IndexOf(_drawers, d); + if (i < 0 || i == _open) return; + if (_open >= 0) _drawers[_open].SaveOpen(false); + _open = i; + d.SaveOpen(true); + if (_shown != i) + { + // Another drawer was out (or sliding in): this one slides out from closed. + _shown = i; + _t = 0f; + } + } + + public void Close(DashboardDrawer d) + { + if (!IsOpen(d)) return; + _open = -1; + d.SaveOpen(false); + } + + /// <summary>The dashboard closed: every drawer drops its subscriptions. AC thread.</summary> + public void Detach() + { + foreach (DashboardDrawer d in _drawers) d.Update(false); + } + + private void EnsureLoaded() + { + if (_loaded) return; + _loaded = true; + // The first drawer saved open wins (one at a time); any other saved open is closed. + for (int i = 0; i < _drawers.Length; i++) + { + if (!_drawers[i].SavedOpen) continue; + if (_open < 0) _open = i; + else _drawers[i].SaveOpen(false); + } + _shown = _open; + _t = _open >= 0 ? 1f : 0f; + } + + /// <summary> + /// Draws the tabs and the open drawer. Call at the end of the dashboard's Draw, inside its + /// body child (whose rect is the dashboard's: the face is chromeless). + /// </summary> + public void Draw() + { + if (ImGuiPopOuts.InPopOutFrame) + { + // Popped out: no tabs (see the header). Nothing polled meanwhile. + Detach(); + return; + } + EnsureLoaded(); + + // Slide. + float target = _open >= 0 && _open == _shown ? 1f : 0f; + if (_t != target) + { + float step = ImGuiNET.ImGui.GetIO().DeltaTime / SlideSeconds; + if (step <= 0 || float.IsNaN(step)) step = 1f; + _t = target > _t ? MathF.Min(1f, _t + step) : MathF.Max(0f, _t - step); + } + if (_t <= 0f && _open < 0) _shown = -1; + float ease = _t * _t * (3f - 2f * _t); + bool showing = _shown >= 0 && ease > 0.001f; + for (int i = 0; i < _drawers.Length; i++) _drawers[i].Update(showing && i == _shown); + + // Geometry (pixels; k follows the dashboard's text size). + Vector2 dashPos = ImGuiNET.ImGui.GetWindowPos(), dashSize = ImGuiNET.ImGui.GetWindowSize(); + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + float k = MathF.Max(1f, ImGuiFonts.Get(UiFont.Dash11).FontSize / 11f); + int n = _drawers.Length; + float tabW = 14 * k, tabGap = 3 * k, tabTop = 4 * k; + // Tabs share the dashboard's height (40 tall at most, 20 at least: they may run past a minimized dashboard). + float tabH = MathF.Max(20 * k, MathF.Min(40 * k, (dashSize.Y - 2 * tabTop - (n - 1) * tabGap) / Math.Max(1, n))); + float tabsH = n * tabH + (n - 1) * tabGap; + float widest = 0; + foreach (DashboardDrawer d in _drawers) widest = MathF.Max(widest, d.Width(k)); + float panelW = showing ? _drawers[_shown].Width(k) : widest; + float panelH = showing ? _drawers[_shown].Height(k) : 0; + float dashRight = dashPos.X + dashSize.X; + // Left unless there's no room there for the widest drawer and more on the right (so the tabs never switch sides + // as drawers open and close). + bool right = dashPos.X < tabW + widest && display.X - dashRight > dashPos.X; + float shown = showing ? panelW * ease : 0; + + float winX = right ? dashRight : dashPos.X - tabW - shown; + float winW = tabW + shown; + float tabX = right ? dashRight : dashPos.X - tabW; + // Neither side has room (a very wide dashboard): keep it on the screen, over the dashboard. + float shift = 0; + if (winX < 0) shift = -winX; + else if (display.X > 1 && winX + winW > display.X) shift = display.X - (winX + winW); + winX += shift; + tabX += shift; + + float winY = dashPos.Y; + float tabsBottom = tabTop + tabsH; // relative to the dashboard's top + float winH = showing ? MathF.Max(panelH, tabsBottom) : tabsBottom; + if (display.Y > 1 && winY + winH > display.Y) winY = MathF.Max(0, display.Y - winH); + float tabY = dashPos.Y + tabTop; + winH = MathF.Max(winH, tabY + tabsH - winY); + + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(winX, winY), ImGuiCond.Always); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(winW, winH), ImGuiCond.Always); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 0f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowMinSize, Vector2.One); + bool visible = ImGuiNET.ImGui.Begin(WindowId, WindowFlags); + ImGuiNET.ImGui.PopStyleVar(4); + try + { + if (visible) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash10)); + try + { + if (showing) + { + // The panel's visible part; its content slides with the open edge. + float visX0 = right ? tabX + tabW : winX; + float contentX = right ? tabX + tabW + shown - panelW : winX; + Vector2 vMin = new(visX0, winY), vMax = new(visX0 + shown, winY + panelH); + DashboardDrawer d = _drawers[_shown]; + ImGuiNET.ImGui.PushClipRect(vMin, vMax, true); + ImGuiNET.ImGui.PushID(d.Key); + try { d.DrawPanel(new Vector2(contentX, winY), panelW, panelH, k); } + finally + { + ImGuiNET.ImGui.PopID(); + ImGuiNET.ImGui.PopClipRect(); + } + } + for (int i = 0; i < n; i++) + DrawTab(_drawers[i], new Vector2(tabX, tabY + i * (tabH + tabGap)), new Vector2(tabW, tabH), right, k); + } + finally { ImGuiNET.ImGui.PopFont(); } + } + } + finally + { + ImGuiNET.ImGui.End(); + } + } + + private const ImGuiWindowFlags WindowFlags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize + | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse + | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoDocking + | ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoNav; + + private void DrawTab(DashboardDrawer d, Vector2 pos, Vector2 size, bool right, float k) + { + bool open = IsOpen(d); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(d.TabId, size); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + // Like SetItemTooltip (same delay), but the closed tooltip is only built while it shows. + if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip)) + ImGuiNET.ImGui.SetTooltip(open ? d.HideTip : d.TabTooltip(right)); + if (clicked) Toggle(d); + + uint fill = ImGuiNET.ImGui.IsItemActive() ? FaceKit.Darken(BtnFill) : hot ? FaceKit.Lighten(BtnFill) : BtnFill; + ImDrawFlags corners = right ? ImDrawFlags.RoundCornersRight : ImDrawFlags.RoundCornersLeft; + dl.AddRectFilled(pos, pos + size, fill, 4 * k, corners); + dl.AddRect(pos, pos + size, open ? Teal : BtnBord, 4 * k, corners); + ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10); + float half = size.Y * 0.5f; + PhosphorIcons.DrawCentered(dl, f10, d.Icon, pos, new Vector2(size.X, half), open ? Teal : Mute); + // The caret points the way the drawer will move. + string caret = right == open ? PhosphorIcons.CaretLeft : PhosphorIcons.CaretRight; + PhosphorIcons.DrawCentered(dl, f10, caret, pos + new Vector2(0, half), new Vector2(size.X, half), hot ? White : Mute); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs new file mode 100644 index 0000000..558e47b --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs @@ -0,0 +1,659 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/DungeonMapFace.cs +// The Dungeon Map: a large, pannable map of the current dungeon. It replaces +// RynthAi's plugin-drawn DungeonMapUi window (plugin ImGui rendering is no +// longer called; RYNTHCORE_FORCE_IMGUI only) and is opened from the RynthAi +// dashboard's Map launcher. +// +// Data: UiSources.Radar, the same snapshot the Radar face draws +// (RynthPluginGetRadarSnapshot): every floor's walls and fill strips, the +// visited cells, portal / door / creature markers with labels, the player pose. +// The plugin's D3D9 floor textures are not used; floors are strips and walls +// are lines, drawn without anti-aliasing and culled to the canvas. +// +// Like the plugin window it replaces: +// - toolbar: 1U1D (current floor +-1), F1..Fn floor toggles, All, Here, zoom, +// Follow, Rotate, Reset, Doors, Creatures, opacity; it can be hidden; +// - markers: the radar's kinds (RadarKind); the kinds added 2026-10-04 use the +// radar's shapes and colours (RadarMarkerStyle) and its per-kind show boxes; +// - drag pans (and turns Follow off), the wheel zooms; +// - portals always shown with their destination; doors and creatures optional; +// - hidden while you're outdoors or in portal space, back in the next dungeon +// (the panel stays open; ImGuiPanelHost skips drawing it docked). +// Settings are the engine's (dungeon_map_settings.txt beside radar_settings.txt), +// not RynthAi's per-character Map* fields. Zoom, pan and floor picks last for the +// session, as they did. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class DungeonMapFace : IImGuiPanel +{ + public const string Title = "Dungeon Map"; + + public static void Register() + { + DungeonMapSettingsStore.Load(); // engine init thread: the file read stays off AC's thread + ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true, OpenCentered: true), + () => new DungeonMapFace()); + } + + // ── Palette (the plugin map's colours, ARGB) ────────────────────────── + private const uint CanvasBgArgb = 0xFF0A121F, ToolbarBgArgb = 0xE00A121A; + private static readonly uint CanvasBorder = C(0xFF334D66), Wall = C(0xFF8CCCFF), + PlayerCol = C(0xFF33FF66), Portal = C(0xFFE673FF), PortalRing = C(0xB3FFBFFF), PortalLabel = C(0xFFFFE0FF), + Door = C(0xFFBF8C40), DoorRing = C(0xB3E6BF80), DoorLabel = C(0xFFF2D9A6), + Monster = C(0xFFFF4033), MonsterRing = C(0xB3FF8C80), Npc = C(0xFFFFD933), NpcRing = C(0xB3FFF28C), + CreatureLabel = C(0xFFFFE6E6), Hint = C(0xFF8FA3B8), ButtonBg = C(0xC0141F29), ButtonBorder = C(0xFF34587A), + FloorOn = C(0xFF2673B3), FloorHere = C(0xFF1AA64D); + private const uint FillFlat = 0x662E8C38, FillUp = 0x668C1F14, FillDown = 0x661A8026, FillVisited = 0xB84D6B94; + private static uint C(uint argb) => RynthTheme.Argb(argb); + + /// <summary>ARGB colour with its alpha scaled, as an ImGui colour.</summary> + private static uint MulAlpha(uint argb, float k) => + RynthTheme.Argb((argb & 0x00FFFFFF) | ((uint)Math.Clamp((int)MathF.Round((argb >> 24) * k), 0, 255) << 24)); + + private const float DimOtherFloors = 0.25f; // the plugin map's DimCol + private const float DefaultZoom = 5f, MinZoom = 1f, MaxZoom = 20f; + + // ── Session state (per open) ───────────────────────────────────────── + private float _zoom = DefaultZoom; + private Vector2 _pan; + private bool _follow = true; + private bool _oneUpOneDown = true; + private readonly HashSet<int> _visible = new(); + private int _autoLayer = -1; + private uint _landblock; + private int[] _drawOrder = Array.Empty<int>(); + + public int PopOutIdleHz => 20; // markers move + + public bool HiddenWhileDocked + { + get + { + RadarView? view = UiSources.Radar.Current?.Value; + return view != null && !view.Live.IsIndoor; + } + } + + public void OnShown() + { + DungeonMapSettingsStore.Load(); + UiSources.Radar.Subscribe(); + UiSources.Radar.RequestRefresh(); + } + + public void OnHidden() => UiSources.Radar.Unsubscribe(); + + public void Draw() + { + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail(); + if (size.X < 16 || size.Y < 16) return; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + RadarView? view = UiSources.Radar.Current?.Value; + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + try + { + if (view == null) { Message(dl, origin, size, "Waiting for map data from RynthAi..."); return; } + RadarSnapshot live = view.Live; + if (!live.IsIndoor) { Message(dl, origin, size, "Outdoors: the map shows while you're in a dungeon."); return; } + + int layers = live.LayerZs.Count; + TrackLayers(view, live.Player.Landblock, layers); + + // ── Toolbar ── + float top = origin.Y; + if (DungeonMapSettingsStore.ShowToolbar) + { + float barH = Toolbar(dl, origin, size.X, view, layers); + top += barH; + } + + // ── Canvas ── + var canvasMin = new Vector2(origin.X, top); + var canvasMax = origin + size; + if (canvasMax.Y - canvasMin.Y < 24) return; + dl.AddRectFilled(canvasMin, canvasMax, MulAlpha(CanvasBgArgb, Math.Clamp(DungeonMapSettingsStore.BgOpacity, 0f, 1f))); + dl.AddRect(canvasMin, canvasMax, CanvasBorder); + + if (_follow) _pan = Vector2.Zero; + Vector2 centre = (canvasMin + canvasMax) * 0.5f + _pan; + + if (layers == 0) + DrawCentredText(dl, (canvasMin + canvasMax) * 0.5f, Hint, + $"Loading dungeon geometry for {live.Player.Landblock:X4}..."); + else + { + ImDrawListFlags saved = dl.Flags; + dl.Flags = saved & ~(ImDrawListFlags.AntiAliasedLines | ImDrawListFlags.AntiAliasedLinesUseTex | ImDrawListFlags.AntiAliasedFill); + dl.PushClipRect(canvasMin, canvasMax, true); + var proj = new Projection(centre, live.Player, DungeonMapSettingsStore.RotateWithPlayer, _zoom); + DrawFloors(dl, view, proj, canvasMin, canvasMax); + dl.Flags = saved; + DrawMarkers(dl, live, proj, canvasMin, canvasMax); + DrawPlayer(dl, centre, proj); + dl.PopClipRect(); + } + + // Show-toolbar button over the canvas corner (submitted before the surface so it wins the hover). + if (!DungeonMapSettingsStore.ShowToolbar) + { + if (IconButton("##dmap_showbar", canvasMin + new Vector2(4, 4), PhosphorIcons.CaretDown)) + { + DungeonMapSettingsStore.ShowToolbar = true; + DungeonMapSettingsStore.Save(); + } + ImGuiNET.ImGui.SetItemTooltip("Show the map settings"); + } + + CanvasInput(canvasMin, canvasMax); + } + finally + { + ImGuiNET.ImGui.PopFont(); + } + } + + // ── Floors ──────────────────────────────────────────────────────────── + + /// <summary>Follows the player's floor: 1U1D keeps current +-1, Follow alone keeps just the current one.</summary> + private void TrackLayers(RadarView view, uint landblock, int layers) + { + if (landblock != _landblock) + { + _landblock = landblock; + _pan = Vector2.Zero; + _autoLayer = -1; + _visible.Clear(); + } + int best = view.CurrentLayer; + if (best < 0 || best == _autoLayer) return; + _autoLayer = best; + if (_oneUpOneDown) SetOneUpOneDown(layers); + else if (_follow || _visible.Count == 0) { _visible.Clear(); _visible.Add(best); } + } + + private void SetOneUpOneDown(int layers) + { + _visible.Clear(); + if (_autoLayer < 0) return; + if (_autoLayer > 0) _visible.Add(_autoLayer - 1); + _visible.Add(_autoLayer); + if (_autoLayer < layers - 1) _visible.Add(_autoLayer + 1); + } + + private void DrawFloors(ImDrawListPtr dl, RadarView view, in Projection proj, Vector2 clipMin, Vector2 clipMax) + { + int layers = view.Live.LayerZs.Count; + int cur = view.CurrentLayer; + // Other floors first, the player's floor on top. + if (_drawOrder.Length < layers) _drawOrder = new int[layers]; + int n = 0; + foreach (int i in _visible) if (i >= 0 && i < layers && i != cur) _drawOrder[n++] = i; + bool curVisible = cur >= 0 && _visible.Contains(cur); + if (curVisible) _drawOrder[n++] = cur; + + // Fill strips: 5 floats (x0, y0, x1, y1, type). + for (int k = 0; k < n; k++) + { + int layer = _drawOrder[k]; + if (view.FillsByLayer[layer] is not float[] strips) continue; + float a = layer == cur ? 1f : DimOtherFloors; + uint flat = MulAlpha(FillFlat, a), up = MulAlpha(FillUp, a), down = MulAlpha(FillDown, a); + for (int i = 0; i + 4 < strips.Length; i += 5) + { + int type = (int)strips[i + 4]; + FillRect(dl, proj, strips[i], strips[i + 1], strips[i + 2], strips[i + 3], + type == 1 ? up : type == 2 ? down : flat, clipMin, clipMax); + } + } + + // Visited cells, the player's floor only: 4 floats per strip. + if (curVisible && view.VisitedByLayer[cur] is float[] visited) + { + uint fill = RynthTheme.Argb(FillVisited); + for (int i = 0; i + 3 < visited.Length; i += 4) + FillRect(dl, proj, visited[i], visited[i + 1], visited[i + 2], visited[i + 3], fill, clipMin, clipMax); + } + + // Walls: 6 floats (ax, ay, bx, by, cell x, cell y). + for (int k = 0; k < n; k++) + { + int layer = _drawOrder[k]; + if (view.WallsByLayer[layer] is not float[] segs) continue; + bool current = layer == cur; + uint col = current ? Wall : MulAlpha(0xFF8CCCFF, DimOtherFloors); + float thick = current ? 1.5f : 1f; + for (int i = 0; i + 5 < segs.Length; i += 6) + { + Vector2 pa = proj.P(segs[i], segs[i + 1]); + Vector2 pb = proj.P(segs[i + 2], segs[i + 3]); + if (MathF.Max(pa.X, pb.X) < clipMin.X || MathF.Min(pa.X, pb.X) > clipMax.X || + MathF.Max(pa.Y, pb.Y) < clipMin.Y || MathF.Min(pa.Y, pb.Y) > clipMax.Y) continue; + dl.AddLine(pa, pb, col, thick); + } + } + } + + private static void FillRect(ImDrawListPtr dl, in Projection proj, float x0, float y0, float x1, float y1, + uint col, Vector2 clipMin, Vector2 clipMax) + { + Vector2 p00 = proj.P(x0, y0), p11 = proj.P(x1, y1); + if (proj.Rotated) + { + Vector2 p10 = proj.P(x1, y0), p01 = proj.P(x0, y1); + float minX = MathF.Min(MathF.Min(p00.X, p11.X), MathF.Min(p10.X, p01.X)); + float maxX = MathF.Max(MathF.Max(p00.X, p11.X), MathF.Max(p10.X, p01.X)); + float minY = MathF.Min(MathF.Min(p00.Y, p11.Y), MathF.Min(p10.Y, p01.Y)); + float maxY = MathF.Max(MathF.Max(p00.Y, p11.Y), MathF.Max(p10.Y, p01.Y)); + if (maxX < clipMin.X || minX > clipMax.X || maxY < clipMin.Y || minY > clipMax.Y) return; + dl.AddQuadFilled(p00, p10, p11, p01, col); + } + else + { + var a = Vector2.Min(p00, p11); + var b = Vector2.Max(p00, p11); + if (b.X < clipMin.X || a.X > clipMax.X || b.Y < clipMin.Y || a.Y > clipMax.Y) return; + dl.AddRectFilled(a, b, col); + } + } + + // ── Markers and player ──────────────────────────────────────────────── + + private static void DrawMarkers(ImDrawListPtr dl, RadarSnapshot live, in Projection proj, Vector2 clipMin, Vector2 clipMax) + { + const float Margin = 20f; + bool doors = DungeonMapSettingsStore.ShowDoors, creatures = DungeonMapSettingsStore.ShowCreatures; + RadarMarkerStyle.FillColors(KindCols); + foreach (RadarMarker m in live.Markers) + { + if (!ShowOnMap(m.Kind, doors, creatures)) continue; + Vector2 p = proj.P(m.X, m.Y); + if (p.X < clipMin.X - Margin || p.X > clipMax.X + Margin || p.Y < clipMin.Y - Margin || p.Y > clipMax.Y + Margin) continue; + switch (m.Kind) + { + case 0: + dl.AddCircleFilled(p, 4f, Monster, 10); + dl.AddCircle(p, 6f, MonsterRing, 10, 1f); + Label(dl, p + new Vector2(7, -7), CreatureLabel, m.Label, 20); + break; + case 1: + dl.AddCircleFilled(p, 4f, Npc, 10); + dl.AddCircle(p, 6f, NpcRing, 10, 1.2f); + Label(dl, p + new Vector2(7, -7), CreatureLabel, m.Label, 20); + break; + case 2: + dl.AddCircleFilled(p, 5f, Portal, 12); + dl.AddCircle(p, 7f, PortalRing, 12, 1.5f); + Label(dl, p + new Vector2(9, -7), PortalLabel, m.Label, 22); + break; + case 3: + const float r = 5f, o = r + 1.5f; + dl.AddQuadFilled(p + new Vector2(0, -r), p + new Vector2(r, 0), p + new Vector2(0, r), p + new Vector2(-r, 0), Door); + dl.AddQuad(p + new Vector2(0, -o), p + new Vector2(o, 0), p + new Vector2(0, o), p + new Vector2(-o, 0), DoorRing, 1.2f); + Label(dl, p + new Vector2(8, -7), DoorLabel, m.Label, 20); + break; + default: + // The kinds added 2026-10-04: the radar's shape and (user-pickable) colour, a size up. + RadarMarkerStyle.Draw(dl, m.Kind, p, KindCols[m.Kind], 1.35f); + if (m.Kind is not RadarKind.GroundItem) + Label(dl, p + new Vector2(8, -7), CreatureLabel, m.Label, 20); + break; + } + } + } + + private static readonly uint[] KindCols = new uint[RadarKind.Count]; + + /// <summary> + /// Portals always; doors with the map's Doors box; monsters and NPCs with its Creatures box. + /// The kinds added 2026-10-04 also follow the radar's show box for that kind (so items on the + /// ground stay off unless turned on there): players, fellows, pets and vendors with Creatures, + /// corpses, lifestones and ground items on the radar's box alone. Unknown kinds: hidden. + /// </summary> + private static bool ShowOnMap(byte kind, bool doors, bool creatures) => kind switch + { + RadarKind.Portal => true, + RadarKind.Door => doors, + RadarKind.Monster or RadarKind.Npc => creatures, + RadarKind.Player or RadarKind.Fellow or RadarKind.Pet or RadarKind.Vendor => + creatures && UI.Panels.RadarSettingsStore.ShowKind(kind), + _ => UI.Panels.RadarSettingsStore.ShowKind(kind), + }; + + private static void Label(ImDrawListPtr dl, Vector2 pos, uint col, string? text, int max) + { + if (string.IsNullOrEmpty(text)) return; + if (text.Length > max) text = text[..max] + "…"; + dl.AddText(pos, col, text); + } + + private static void DrawPlayer(ImDrawListPtr dl, Vector2 at, in Projection proj) + { + dl.AddCircleFilled(at, 4f, PlayerCol, 10); + // Rotating: facing is always up. North-up: AC heading 0 = east, 90 = north. + Vector2 tip = proj.Rotated ? at + new Vector2(0, -10) : at + new Vector2(proj.Cos * 10, -proj.Sin * 10); + dl.AddLine(at, tip, PlayerCol, 1.5f); + } + + /// <summary>World (AC x east, y north) to screen around the player, north-up or rotated so facing is up.</summary> + private readonly struct Projection + { + private readonly float _cx, _cy, _pwx, _pwy, _sin, _cos, _zoom; + public readonly bool Rotated; + + public Projection(Vector2 playerAt, RadarPlayer p, bool rotate, float zoom) + { + _cx = playerAt.X; _cy = playerAt.Y; _pwx = p.WorldX; _pwy = p.WorldY; + float h = p.Heading * MathF.PI / 180f; + _sin = MathF.Sin(h); _cos = MathF.Cos(h); + Rotated = rotate; _zoom = zoom; + } + + public float Sin => _sin; + public float Cos => _cos; + + public Vector2 P(float wx, float wy) + { + float dx = wx - _pwx, dy = wy - _pwy; + if (Rotated) + { + float right = _sin * dx - _cos * dy; + float forward = _cos * dx + _sin * dy; + return new Vector2(_cx + right * _zoom, _cy - forward * _zoom); + } + return new Vector2(_cx + dx * _zoom, _cy - dy * _zoom); + } + } + + // ── Canvas input ────────────────────────────────────────────────────── + + private void CanvasInput(Vector2 canvasMin, Vector2 canvasMax) + { + ImGuiNET.ImGui.SetCursorScreenPos(canvasMin); + ImGuiNET.ImGui.InvisibleButton("##dmap_canvas", Vector2.Max(canvasMax - canvasMin, new Vector2(1, 1))); + if (ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left)) + { + Vector2 delta = ImGuiNET.ImGui.GetIO().MouseDelta; + if (float.IsFinite(delta.X) && float.IsFinite(delta.Y) && delta != Vector2.Zero) + { + _follow = false; + _pan += delta; + } + } + if (ImGuiNET.ImGui.IsItemHovered()) + { + float wheel = ImGuiNET.ImGui.GetIO().MouseWheel; + if (float.IsFinite(wheel) && wheel != 0f) + _zoom = Math.Clamp(_zoom + wheel * 0.5f, MinZoom, MaxZoom); + } + } + + // ── Toolbar ─────────────────────────────────────────────────────────── + + /// <summary>Draws the settings rows (they wrap to the width). Returns their height.</summary> + private float Toolbar(ImDrawListPtr dl, Vector2 origin, float width, RadarView view, int layers) + { + const float pad = 4; + // Background first, sized once the rows are laid out: a channel split keeps it underneath. + dl.ChannelsSplit(2); + dl.ChannelsSetCurrent(1); + ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(pad, pad)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 1)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4)); + float limit = origin.X + width - pad; + bool changed = false; + + if (IconButton("##dmap_hidebar", ImGuiNET.ImGui.GetCursorScreenPos(), PhosphorIcons.CaretUp)) + { + DungeonMapSettingsStore.ShowToolbar = false; + changed = true; + } + ImGuiNET.ImGui.SetItemTooltip("Hide the map settings"); + + // 1U1D and the floors. + SameLineIfFits(40, limit); + if (ToggleButton("1U1D##dmap_1u1d", _oneUpOneDown, FloorOn)) + { + _oneUpOneDown = !_oneUpOneDown; + if (_oneUpOneDown) SetOneUpOneDown(layers); + } + ImGuiNET.ImGui.SetItemTooltip("Show your floor and the ones just above and below it"); + if (layers > 1) + { + SameLineIfFits(ImGuiNET.ImGui.CalcTextSize("Floors:").X, limit); + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextUnformatted("Floors:"); + for (int i = 0; i < layers; i++) + { + string label = FloorLabel(i); + SameLineIfFits(ImGuiNET.ImGui.CalcTextSize(label).X + 8, limit, 2); + bool on = _visible.Contains(i); + if (ToggleButton(label, on, i == view.CurrentLayer ? FloorHere : FloorOn)) + { + _oneUpOneDown = false; + if (on) _visible.Remove(i); else _visible.Add(i); + } + } + SameLineIfFits(24, limit); + if (ImGuiNET.ImGui.SmallButton("All##dmap_all")) + { + _oneUpOneDown = false; + _visible.Clear(); + for (int i = 0; i < layers; i++) _visible.Add(i); + } + SameLineIfFits(34, limit, 2); + if (ImGuiNET.ImGui.SmallButton("Here##dmap_here")) + { + _oneUpOneDown = false; + _visible.Clear(); + if (view.CurrentLayer >= 0) _visible.Add(view.CurrentLayer); + } + } + + // Zoom. + SameLineIfFits(130, limit, 12); + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextUnformatted("Zoom:"); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(80); + ImGuiNET.ImGui.SliderFloat("##dmap_zoom", ref _zoom, MinZoom, MaxZoom, "%.1fx"); + if (!float.IsFinite(_zoom)) _zoom = DefaultZoom; + + // Follow / Rotate / Reset. + SameLineIfFits(190, limit, 12); + ImGuiNET.ImGui.Checkbox("Follow##dmap_follow", ref _follow); + ImGuiNET.ImGui.SetItemTooltip("Keep the map centred on you (dragging the map turns this off)"); + ImGuiNET.ImGui.SameLine(); + changed |= ImGuiNET.ImGui.Checkbox("Rotate##dmap_rotate", ref DungeonMapSettingsStore.RotateWithPlayer); + ImGuiNET.ImGui.SetItemTooltip("Turn the map so the way you face is up"); + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.SmallButton("Reset##dmap_reset")) + { + _pan = Vector2.Zero; + _zoom = DefaultZoom; + _follow = true; + _oneUpOneDown = true; + SetOneUpOneDown(layers); + } + + // Doors / Creatures. + SameLineIfFits(160, limit, 12); + changed |= ImGuiNET.ImGui.Checkbox("Doors##dmap_doors", ref DungeonMapSettingsStore.ShowDoors); + ImGuiNET.ImGui.SameLine(); + changed |= ImGuiNET.ImGui.Checkbox("Creatures##dmap_creatures", ref DungeonMapSettingsStore.ShowCreatures); + ImGuiNET.ImGui.SetItemTooltip("Monsters, NPCs, players, fellows, your pet and vendors. Players, fellows, pets, vendors, corpses, lifestones and ground items also follow their box in the Radar's settings."); + + // Opacity (of the map's background). + SameLineIfFits(130, limit, 12); + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextUnformatted("Opacity:"); + ImGuiNET.ImGui.SameLine(0, 4); + ImGuiNET.ImGui.SetNextItemWidth(70); + if (ImGuiNET.ImGui.SliderFloat("##dmap_opacity", ref DungeonMapSettingsStore.BgOpacity, 0f, 1f, "%.2f")) + DungeonMapSettingsStore.BgOpacity = Math.Clamp(DungeonMapSettingsStore.BgOpacity, 0f, 1f); + // Save once the drag ends, not on every step. + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) changed = true; + + ImGuiNET.ImGui.PopStyleVar(2); + float bottom = ImGuiNET.ImGui.GetItemRectMax().Y + pad; + dl.ChannelsSetCurrent(0); + dl.AddRectFilled(origin, new Vector2(origin.X + width, bottom), C(ToolbarBgArgb)); + dl.ChannelsMerge(); + + if (changed) DungeonMapSettingsStore.Save(); + return bottom - origin.Y; + } + + private static readonly List<string> FloorLabels = new(); + + private static string FloorLabel(int i) + { + while (FloorLabels.Count <= i) FloorLabels.Add("F" + (FloorLabels.Count + 1) + "##dmap_floor" + FloorLabels.Count); + return FloorLabels[i]; + } + + /// <summary>Keeps the next item on this row when it fits before <paramref name="limit"/>, else starts a new row.</summary> + private static void SameLineIfFits(float nextWidth, float limit, float gap = 8) + { + if (ImGuiNET.ImGui.GetItemRectMax().X + gap + nextWidth <= limit) + ImGuiNET.ImGui.SameLine(0, gap); + } + + private static bool ToggleButton(string label, bool on, uint onColour) + { + if (on) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, onColour); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, onColour); + } + bool clicked = ImGuiNET.ImGui.SmallButton(label); + if (on) ImGuiNET.ImGui.PopStyleColor(2); + return clicked; + } + + private static bool IconButton(string id, Vector2 pos, string glyph) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + var size = new Vector2(18, 18); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); + uint bg = ImGuiNET.ImGui.IsItemActive() ? C(0xE0101820) : ImGuiNET.ImGui.IsItemHovered() ? C(0xE0243444) : ButtonBg; + dl.AddRectFilled(pos, pos + size, bg, 3); + dl.AddRect(pos, pos + size, ButtonBorder, 3); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, size, C(0xFFF2F8FF)); + return clicked; + } + + private static void Message(ImDrawListPtr dl, Vector2 origin, Vector2 size, string text) + { + dl.AddRectFilled(origin, origin + size, MulAlpha(CanvasBgArgb, Math.Clamp(DungeonMapSettingsStore.BgOpacity, 0.6f, 1f))); + DrawCentredText(dl, origin + size * 0.5f, Hint, text); + } + + private static void DrawCentredText(ImDrawListPtr dl, Vector2 centre, uint col, string text) + { + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text); + dl.AddText(centre - ts * 0.5f, col, text); + } +} + +/// <summary> +/// The Dungeon Map's settings (the plugin map's MapShowDoors / MapShowCreatures / +/// MapShowToolbar / MapBgOpacity / MapRotateWithPlayer, same defaults). Engine-wide, +/// in %LOCALAPPDATA%\RynthCore\dungeon_map_settings.txt, like radar_settings.txt. +/// </summary> +internal static class DungeonMapSettingsStore +{ + private static readonly object _sync = new(); + private static bool _loaded; + + public static bool ShowDoors = true; + public static bool ShowCreatures = true; + public static bool ShowToolbar = true; + public static float BgOpacity = 1.0f; + public static bool RotateWithPlayer; + + private static string FilePath + { + get + { + string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + return Path.Combine(root, "RynthCore", "dungeon_map_settings.txt"); + } + } + + public static void Load() + { + lock (_sync) + { + if (_loaded) return; + _loaded = true; + try + { + string path = FilePath; + if (!File.Exists(path)) return; + foreach (string raw in File.ReadAllLines(path)) + { + string line = raw.Trim(); + if (line.Length == 0 || line.StartsWith('#')) continue; + int eq = line.IndexOf('='); + if (eq <= 0) continue; + string key = line[..eq].Trim(); + string val = line[(eq + 1)..].Trim(); + switch (key) + { + case "showDoors": ShowDoors = val == "1"; break; + case "showCreatures": ShowCreatures = val == "1"; break; + case "showToolbar": ShowToolbar = val == "1"; break; + case "rotate": RotateWithPlayer = val == "1"; break; + case "opacity": + if (float.TryParse(val, NumberStyles.Float, CultureInfo.InvariantCulture, out float o)) + BgOpacity = Math.Clamp(o, 0f, 1f); + break; + } + } + } + catch { /* best-effort: defaults already in place */ } + } + } + + /// <summary>Writes the settings in the background (the caller is AC's render thread).</summary> + public static void Save() + { + // Snapshot on the caller's thread: the writer runs later. + string text = "# RynthCore dungeon map settings - auto-generated, hand-edits OK.\n" + + $"showDoors={(ShowDoors ? "1" : "0")}\n" + + $"showCreatures={(ShowCreatures ? "1" : "0")}\n" + + $"showToolbar={(ShowToolbar ? "1" : "0")}\n" + + $"rotate={(RotateWithPlayer ? "1" : "0")}\n" + + FormattableString.Invariant($"opacity={BgOpacity:0.##}\n"); + UiBackgroundWriter.Enqueue("dungeon map settings", () => + { + lock (_sync) + { + try + { + string path = FilePath; + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.WriteAllText(path, text); + } + catch { /* non-fatal */ } + } + }); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs b/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs new file mode 100644 index 0000000..5820054 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs @@ -0,0 +1,316 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/FaceKit.cs +// Widgets the RynthAi-style ImGui faces share: the flat bordered button (and +// its icon-only form), a text box with a grey hint, a picker (button + popup +// list), wrapped button rows, and UTF-8 text buffers. Colours are the panels' palette (ABGR), +// with text brighter than the Avalonia faces (Tom, 2026-09-28). +// +// Everything runs on AC's render thread inside a face's Draw. No per-frame +// allocation except what callers pass in. +// ============================================================================ + +using System; +using System.Numerics; +using System.Text; +using ImGuiNET; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class FaceKit +{ + private static uint C(uint argb) => RynthTheme.Argb(argb); + + public static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Green = C(0xFF33CC66), + Red = C(0xFFE05A5A), Mute = C(0xFFC8D6E4), Text = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), + PanelBg = C(0xFF141F29), RowAlt = C(0xFF101822), BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A), + Selected = C(0xFF1A2E42), StartBg = C(0xFF196119), StopBg = C(0xFF801919), DeleteBg = C(0xFF801A1A); + + // ── Frame ──────────────────────────────────────────────────────────── + + /// <summary> + /// Starts an edge-to-edge face body: shell background, Ui10 font, a 6 px + /// inset kept on every line (Indent). Returns the content width. Pair with End. + /// </summary> + public static float Begin(out Vector2 origin, out Vector2 size) + { + origin = ImGuiNET.ImGui.GetCursorScreenPos(); + size = ImGuiNET.ImGui.GetContentRegionAvail(); + ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(origin, origin + size, ShellBg, 4); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4)); + ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(6, 6)); + ImGuiNET.ImGui.Indent(6); + return size.X - 12; + } + + public static void End(Vector2 origin, Vector2 size) + { + ImGuiNET.ImGui.Unindent(6); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.GetWindowDrawList().AddRect(origin, origin + size, BtnBord, 4); + } + + /// <summary> + /// A GripInBody face: how far the resize grip reaches above the 6 px bottom + /// margin (0 for other faces). A scrolling child that runs to the margin ends + /// this much higher so its scrollbar stays clear of the grip. + /// </summary> + public static float GripOverlap() => Math.Max(0f, ImGuiPanelHost.BodyGripReserve - 6f); + + /// <summary>Space left below the cursor down to the body's bottom (6 px margin).</summary> + public static float Remaining(Vector2 origin, Vector2 size) => + origin.Y + size.Y - 6 - ImGuiNET.ImGui.GetCursorScreenPos().Y; + + /// <summary>Moves the layout cursor to the start of the line below a row drawn at <paramref name="rowStart"/>.</summary> + public static void NextLine(Vector2 rowStart, float rowHeight) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(rowStart.X, rowStart.Y + rowHeight)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + public static void Separator(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.GetWindowDrawList().AddLine(p + new Vector2(0, 1), p + new Vector2(w, 1), BtnBord); + ImGuiNET.ImGui.Dummy(new Vector2(w, 2)); + } + + public static void Label(string text, uint color) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color); + ImGuiNET.ImGui.TextUnformatted(text); + ImGuiNET.ImGui.PopStyleColor(); + } + + // ── Buttons ────────────────────────────────────────────────────────── + + /// <summary>A flat bordered button at <paramref name="pos"/>.</summary> + public static bool Button(string id, string label, Vector2 pos, Vector2 size, uint fg, uint bg, + bool enabled = true, bool leftAlign = false, uint border = 0) + { + bool clicked = ButtonFrame(id, pos, size, bg, enabled, border); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(label); + float tx = leftAlign ? pos.X + 6 : pos.X + (size.X - ts.X) * 0.5f; + dl.PushClipRect(pos, pos + size, true); + dl.AddText(new Vector2(tx, pos.Y + (size.Y - ts.Y) * 0.5f), enabled ? fg : Faded(fg), label); + dl.PopClipRect(); + return clicked; + } + + /// <summary> + /// Button's look with a Phosphor icon centred on it. <paramref name="font"/> + /// sets the icon's size: Ui14 (about 13 px) for 20+ px buttons, Ui11 for smaller. + /// </summary> + public static bool IconButton(string id, string icon, Vector2 pos, Vector2 size, uint fg, uint bg, + bool enabled = true, uint border = 0, UiFont font = UiFont.Ui14) + { + bool clicked = ButtonFrame(id, pos, size, bg, enabled, border); + PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(font), icon, pos, size, enabled ? fg : Faded(fg)); + return clicked; + } + + private static bool ButtonFrame(string id, Vector2 pos, Vector2 size, uint bg, bool enabled, uint border) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size) && enabled; + bool hot = enabled && ImGuiNET.ImGui.IsItemHovered(); + uint fill = enabled && ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : hot ? Lighten(bg) : bg; + dl.AddRectFilled(pos, pos + size, fill, 3); + dl.AddRect(pos, pos + size, border != 0 ? border : BtnBord, 3); + return clicked; + } + + /// <summary>Width a button needs for <paramref name="label"/> at the current font.</summary> + public static float ButtonWidth(string label) => ImGuiNET.ImGui.CalcTextSize(label).X + 16; + + /// <summary> + /// A draggable column edge at screen x (a 6 px handle, resize cursor on hover). + /// Dragging changes <paramref name="width"/> (never below <paramref name="min"/>); + /// <paramref name="onCommit"/> runs when the drag ends, to save it. Leaves the + /// cursor where it was. Returns true while the width is changing. + /// </summary> + public static bool ColumnDivider(string id, float x, float top, float height, ref float width, float min, + Action<float>? onCommit) + { + Vector2 saved = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x - 3, top)); + ImGuiNET.ImGui.SetNextItemAllowOverlap(); + ImGuiNET.ImGui.InvisibleButton(id, new Vector2(6, height)); + bool active = ImGuiNET.ImGui.IsItemActive(); + bool hot = active || ImGuiNET.ImGui.IsItemHovered(); + if (hot) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.ResizeEW); + bool changed = false; + if (active) + { + float dx = ImGuiNET.ImGui.GetIO().MouseDelta.X; + if (dx != 0) + { + width = Math.Max(min, width + dx); + changed = true; + } + } + if (ImGuiNET.ImGui.IsItemDeactivated()) onCommit?.Invoke(width); + ImGuiNET.ImGui.GetWindowDrawList().AddLine(new Vector2(x, top + 3), new Vector2(x, top + height - 3), + hot ? Teal : BtnBord, hot ? 2f : 1f); + ImGuiNET.ImGui.SetCursorScreenPos(saved); + return changed; + } + + /// <summary> + /// A row of buttons that wraps to the width; returns the index clicked or -1. + /// <paramref name="enabled"/> may be null (all enabled). + /// </summary> + public static int WrapButtons(string idPrefix, string[] labels, float w, float height = 24, bool[]? enabled = null) + { + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + float x = start.X, y = start.Y; + int clicked = -1; + for (int i = 0; i < labels.Length; i++) + { + float bw = ButtonWidth(labels[i]); + if (x > start.X && x + bw > start.X + w) { x = start.X; y += height + 4; } + ImGuiNET.ImGui.PushID(idPrefix + i); + if (Button("##b", labels[i], new Vector2(x, y), new Vector2(bw, height), Text, BtnFill, enabled == null || enabled[i])) + clicked = i; + ImGuiNET.ImGui.PopID(); + x += bw + 4; + } + NextLine(start, y - start.Y + height); + return clicked; + } + + // ── Text input ─────────────────────────────────────────────────────── + + /// <summary> + /// A bordered text box with a grey <paramref name="hint"/> while empty. + /// Returns true when Enter was pressed (with EnterReturnsTrue) or the text changed. + /// </summary> + public static bool TextBox(string id, byte[] buffer, Vector2 pos, float width, string hint, out bool active, + ImGuiInputTextFlags flags = ImGuiInputTextFlags.None, float height = 22) + { + ImGuiNET.ImGui.SetCursorScreenPos(pos); + ImGuiNET.ImGui.SetNextItemWidth(width); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 3f); + bool result = ImGuiNET.ImGui.InputText(id, buffer, (uint)buffer.Length, flags); + active = ImGuiNET.ImGui.IsItemActive(); + if (active) ImGuiTextFocus.NoteActive(id); // keys stay out of AC from this frame on + ImGuiNET.ImGui.PopStyleVar(3); + ImGuiNET.ImGui.PopStyleColor(3); + if (buffer[0] == 0 && !active && hint.Length > 0) + ImGuiNET.ImGui.GetWindowDrawList().AddText(pos + new Vector2(5, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute), hint); + return result; + } + + // ── Picker ─────────────────────────────────────────────────────────── + + /// <summary> + /// One popup list per face, opened from any button: call Open from the + /// button's click and Draw once per frame at the end of the face's Draw + /// (outside any child window, so the popup id always matches). + /// </summary> + internal sealed class Picker + { + private readonly string _popupId; + private string[] _items = Array.Empty<string>(); + private int _selected = -1; + private Action<int>? _onPick; + private Vector2 _pos; + private float _width = 220; + private bool _openRequested; + + public Picker(string popupId) => _popupId = popupId; + + public void Open(Vector2 below, string[] items, int selected, Action<int> onPick, float width = 220) + { + _items = items; + _selected = selected; + _onPick = onPick; + _pos = below; + _width = width; + _openRequested = items.Length > 0; + } + + public void Draw() + { + if (_openRequested) + { + _openRequested = false; + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Clamp(_pos.X, 0, Math.Max(0, display.X - _width)), _pos.Y)); + ImGuiNET.ImGui.OpenPopup(_popupId); + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1)); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(_width, Math.Min(_items.Length * 21 + 4, 340))); + bool open = ImGuiNET.ImGui.BeginPopup(_popupId); + ImGuiNET.ImGui.PopStyleVar(3); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) return; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float iw = ImGuiNET.ImGui.GetContentRegionAvail().X; + for (int i = 0; i < _items.Length; i++) + { + ImGuiNET.ImGui.PushID(i); + Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos(); + bool click = ImGuiNET.ImGui.InvisibleButton("##it", new Vector2(iw, 20)); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + bool sel = i == _selected; + dl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? Selected : hot ? Lighten(BtnFill) : BtnFill); + dl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord); + dl.AddText(ip + new Vector2(6, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), sel ? Teal : Text, _items[i]); + if (click) + { + Action<int>? act = _onPick; + ImGuiNET.ImGui.CloseCurrentPopup(); + act?.Invoke(i); + } + } + ImGuiNET.ImGui.EndPopup(); + } + } + + // ── Text buffers ───────────────────────────────────────────────────── + + public static string Utf8(byte[] buffer) + { + int len = Array.IndexOf(buffer, (byte)0); + return Encoding.UTF8.GetString(buffer, 0, len < 0 ? buffer.Length : len); + } + + /// <summary>Writes <paramref name="text"/> NUL-terminated, cut at a character boundary if it doesn't fit.</summary> + public static void WriteUtf8(byte[] buffer, string text) + { + byte[] all = Encoding.UTF8.GetBytes(text ?? string.Empty); + int n = Math.Min(all.Length, buffer.Length - 1); + while (n > 0 && n < all.Length && (all[n] & 0xC0) == 0x80) n--; + Array.Copy(all, buffer, n); + buffer[n] = 0; + } + + // ── Colour helpers ─────────────────────────────────────────────────── + + public static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12); + public static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0); + public static uint Faded(uint abgr) => (abgr & 0x00FFFFFF) | ((abgr >> 25) << 24); + + private static uint Scale(uint abgr, float k, int add) + { + uint a = abgr & 0xFF000000; + uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add); + uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add); + uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add); + return a | (b << 16) | (g << 8) | r; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs new file mode 100644 index 0000000..ab31f00 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs @@ -0,0 +1,847 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/InventoryFace.Classic.cs +// The Inventory panel's Classic look (docs/IMGUI_INVENTORY.md, Phase 2): the +// retail inventory window, drawn with the client's own pictures from +// client_portal.dat (RetailSprites) at the retail layout's positions. +// +// Where the numbers come from: the retail window is LayoutDesc 0x21000023 in +// the client's dats. Tom's OpenAC client rebuilds it from the dat +// (src/AcDream.App/UI/Layout: InventoryController, PaperdollController, +// PaperdollSlotBackgrounds, ItemListCellTemplate, UiItemSlot, RetailChromeSprites) +// and pins the resolved layout in tests/AcDream.App.Tests/UI/Layout/fixtures/ +// inventory_21000023.json. The element positions, sizes and picture ids below +// are read from that layout (and the empty-cell pictures re-resolved from the +// installed dats the way OpenAC's ItemListCellTemplate does); the resize rules +// (the grid and pack column grow with the window's height, the background's +// 25 px title band isn't stretched) follow AcClientReborn's InventoryGeometry. +// Credit: OpenAC (Tom's project) for the layout and sprite research. +// +// title retail title bar "Inventory of <name>", tool toggles, close +// tools search, sort, category chips (toggle, the funnel in the title) +// paperdoll the 24 equip slots at their retail places (the 3D figure isn't +// drawn, so the retail "Slots" view is always on) +// column burden meter, main pack, then the main pack's pack slots: side +// packs, then the items that take a pack slot (foci), as retail +// lists them; its scrollbar +// contents "Contents of <pack>": the open pack's slots, retail scrollbar; +// with a search or filter on, the matches from every pack +// status the action waiting / last outcome (or the pyreals), Drop, Give +// +// Same behaviours as the Modern look: one action at a time, drag to a pack / +// slot / Drop / Give, double-click to use, right-click menu, split dialog. +// Geometry is in retail pixels times the UI scale (DPI x the panel's text size), +// shrunk only to fit a window narrower than 300. +// ============================================================================ + +using System; +using System.IO; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class InventoryFace +{ + // ── Retail art (0x06 textures in client_portal.dat) ───────────────── + private static class Art + { + public const uint Backdrop = 0x06004D0Au; // 300x362 stone background (element 0x100001D0) + public const uint TitleBar = 0x06004CFAu; // 276x25 title bar (0x100001D3) + public const uint Close = 0x06004D0Cu; // 24x25 close button (0x100001D2); +1 = pressed + public const uint GridEmpty = 0x06004D20u; // empty contents cell (prototype 0x1000033A, ItemSlot_Empty) + public const uint PackEmpty = 0x06000F6Eu; // empty side-pack cell (prototype 0x1000033F > 0x1000033E) + public const uint OpenPack = 0x06005D9Cu; // 36x36 gold arrow on the open pack + public const uint MainPackIcon = 0x0600127Eu; // the main pack's backpack + public const uint Selected = 0x06004D21u; // yellow square on the selected item + public const uint Waiting = 0x0600109Au; // hatch on an item waiting for the server + public const uint AcceptGrid = 0x060011F9u, AcceptPack = 0x060011F7u, Reject = 0x060011F8u; + public const uint BurdenBack = 0x0600121Du, BurdenFill = 0x0600121Cu; // meter 0x100001D9 and its fill + public const uint CapacityBack = 0x06004D22u, CapacityFill = 0x06004D23u; // 5x30 pack fill meter + public const uint Track = 0x06004C5Fu; // 16x32 scrollbar chain, tiled (LayoutDesc 0x2100003E) + public const uint ThumbTop = 0x06004C60u, ThumbMid = 0x06004C63u, ThumbBottom = 0x06004C66u; + public const uint Down = 0x06004C69u, Up = 0x06004C6Cu; // +1 rollover, +2 pressed + } + + // Retail geometry (px at scale 1), LayoutDesc 0x21000023. + private const float RetailW = 300, TitleH = 25, FieldY = 23, ContentsY = 237, SideW = 61, CellPx = 32, PackPx = 36; + private const int SideBagSlots = 7; + + private static uint Rgb(uint argb) => RynthTheme.Argb(argb); + private static readonly uint StoneFallback = Rgb(0xFF16140F), CellFallback = Rgb(0xFF1C1B18), CellEdge = Rgb(0xFF4A4436), + Gold = Rgb(0xFFCAB06D), White = Rgb(0xFFFFFFFF), Black = Rgb(0xFF000000), SelYellow = Rgb(0xFFF0E040), + AcceptGreen = Rgb(0xFF30D040), RejectRed = Rgb(0xFFE03030); + + /// <summary>One paperdoll slot: its equip mask, retail place in the paperdoll field, empty picture.</summary> + private readonly struct DollSlot + { + public readonly uint Mask; + public readonly float X, Y; + public readonly uint Empty; + public readonly string Name; + /// <summary>Aetheria slots: the unlock bit (PropertyInt 322); 0 = always shown.</summary> + public readonly uint Sigil; + + public DollSlot(uint mask, float x, float y, uint empty, string name, uint sigil = 0) + { + Mask = mask; + X = x; + Y = y; + Empty = empty; + Name = name; + Sigil = sigil; + } + } + + // Element ids, masks and empty pictures: OpenAC's PaperdollSlotBackgrounds (pinned from the + // live dat there, re-checked against the installed dats); places: the layout's elements. + private static readonly DollSlot[] Doll = + { + new(0x00000001u, 84, 28, 0x06006D7Fu, "Head"), // 0x100005AB + new(0x00000200u, 84, 64, 0x06006D7Bu, "Chest"), // 0x100005AC + new(0x00000400u, 84, 100, 0x06006D79u, "Abdomen"), // 0x100005AD + new(0x00000800u, 48, 64, 0x06006D87u, "Upper arms"), // 0x100005AE + new(0x00001000u, 48, 100, 0x06006D81u, "Lower arms"), // 0x100005AF + new(0x00000020u, 48, 136, 0x06006D7Du, "Hands"), // 0x100005B0 + new(0x00002000u, 120, 100, 0x06006D89u, "Upper legs"), // 0x100005B1 + new(0x00004000u, 120, 136, 0x06006D83u, "Lower legs"), // 0x100005B2 + new(0x00000100u, 120, 172, 0x06006D85u, "Feet"), // 0x100005B3 + new(0x00000002u, 192, 80, 0x060032C5u, "Shirt"), // 0x100001E2 + new(0x00000040u, 192, 116, 0x060032C4u, "Pants"), // 0x100001E3 + new(0x00008000u, 8, 8, 0x06000F68u, "Neck"), // 0x100001DA + new(0x04000000u, 8, 44, 0x06006A6Cu, "Trinket"), // 0x1000058E + new(0x00020000u, 8, 80, 0x06000F6Au, "Right wrist"), // 0x100001DD + new(0x00080000u, 8, 116, 0x06000F6Bu, "Right ring"), // 0x100001DE + new(0x00200000u, 8, 172, 0x06000F6Cu, "Shield"), // 0x100001E1 + new(0x00010000u, 156, 80, 0x06000F5Du, "Left wrist"), // 0x100001DB + new(0x00040000u, 156, 116, 0x06000F5Au, "Left ring"), // 0x100001DC + new(0x03500000u, 156, 172, 0x06000F66u, "Weapon"), // 0x100001DF: melee, missile, held, two-handed + new(0x00800000u, 190, 172, 0x06000F5Eu, "Ammunition"), // 0x100001E0 + new(0x08000000u, 192, 44, 0x0600708Fu, "Cloak"), // 0x100005E9 + new(0x10000000u, 126, 8, 0x06006BEFu, "Blue Aetheria", 1), // 0x10000595 + new(0x20000000u, 158, 8, 0x06006BF0u, "Yellow Aetheria", 2), // 0x10000596 + new(0x40000000u, 190, 8, 0x06006BF1u, "Red Aetheria", 4), // 0x10000597 + }; + + // ── Classic state ─────────────────────────────────────────────────── + private int _gridFirstRow, _packFirstRow; + private float _thumbGrab; + private string _captionText = string.Empty; + private string? _hoverLabel, _hoverLabel2; + private string _titleText = "Inventory"; + private string? _titleFor; + + // ===================================================================== + // Body + // ===================================================================== + + private void ClassicBody(InventoryView view, Vector2 origin, Vector2 size) + { + // Scale: the UI scale (DPI x this panel's text size), shrunk only to fit a narrow window. + float ui = EngineFrameController.FontScale * PanelTextScale.Factor(ImGuiFonts.CurrentStep); + if (!(ui > 0f) || !float.IsFinite(ui)) ui = 1f; + ui *= InventorySettingsStore.SizeFactor; // the panel's own size (the - / + in the title bar) + float s = Math.Max(0.4f, Math.Min(ui, size.X / RetailW)); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float w = size.X; + Vector2 o = origin; + float statusH = MathF.Round(20 * s); + float bottom = o.Y + size.Y - statusH; + + // The open pack: a real pack (Classic has no "All" or "Worn" entry; the paperdoll is Worn). + if (_pack == AllPacks || _pack == WornPacks || view.PackOf(_pack) == null) + _pack = view.Packs.Length > 0 ? view.Packs[0].Id : AllPacks; + bool filtered = _category != 0 || _searchText.Length > 0; + RebuildIfNeeded(view, filtered ? AllPacks : _pack); + + Backdrop(dl, o, w, bottom - o.Y, s); + TitleBar(view, dl, o, w, s); + + // Tools (search, sort, categories): between the title bar and the retail body. + float toolsBottom = o.Y + TitleH * s; + if (InventorySettingsStore.ShowTools) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(o.X + 6, toolsBottom + 4)); + Tools(w - 12); + Chips(w - 12); + toolsBottom = ImGuiNET.ImGui.GetCursorScreenPos().Y; + } + float ry = toolsBottom - TitleH * s; // where retail y = 0 lands + float r = Math.Max(ContentsY + 60, (bottom - ry) / s); // the retail window's height (px at scale 1) + + float sx = o.X + w - SideW * s; // the side column follows the right edge + Paperdoll(view, dl, new Vector2(o.X, ry + FieldY * s), s); + SideColumn(view, dl, new Vector2(sx, ry + FieldY * s), r, s, filtered); + Contents(view, dl, new Vector2(o.X, ry + ContentsY * s), sx, r, s, filtered); + StatusStrip(view, dl, new Vector2(o.X, bottom), w, statusH, s); + + // A press on an item that moves far enough starts a drag. + if (_pressItem != null && _dragItem == null && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) + && Vector2.DistanceSquared(ImGuiNET.ImGui.GetMousePos(), _pressAt) > 25) + _dragItem = _pressItem; + } + + // ── Background and title bar ──────────────────────────────────────── + + /// <summary>The stone background: its 25 px title band at scale, the rest stretched (AcClientReborn's rule).</summary> + private static void Backdrop(ImDrawListPtr dl, Vector2 o, float w, float h, float s) + { + if (!RetailSprites.TryGet(Art.Backdrop, out IntPtr tex)) + { + dl.AddRectFilled(o, o + new Vector2(w, h), StoneFallback); + return; + } + const float ArtH = 362f; + float band = Math.Min(h, TitleH * s); + dl.AddImage(tex, o, o + new Vector2(w, band), Vector2.Zero, new Vector2(1, TitleH / ArtH)); + if (h > band) + dl.AddImage(tex, o + new Vector2(0, band), o + new Vector2(w, h), new Vector2(0, TitleH / ArtH), Vector2.One); + } + + private void TitleBar(InventoryView view, ImDrawListPtr dl, Vector2 o, float w, float s) + { + float h = TitleH * s, closeW = 24 * s; + float barW = w - closeW; + + // The bar: three slices so its bevelled ends keep their shape at any width. + if (RetailSprites.TryGet(Art.TitleBar, out IntPtr tex)) + { + const float Src = 276f, Cap = 14f; + float cap = Math.Min(Cap * s, barW * 0.5f); + float u = Cap / Src; + dl.AddImage(tex, o, o + new Vector2(cap, h), Vector2.Zero, new Vector2(u, 1)); + dl.AddImage(tex, o + new Vector2(cap, 0), o + new Vector2(barW - cap, h), new Vector2(u, 0), new Vector2(1 - u, 1)); + dl.AddImage(tex, o + new Vector2(barW - cap, 0), o + new Vector2(barW, h), new Vector2(1 - u, 0), Vector2.One); + } + else + { + dl.AddRectFilled(o, o + new Vector2(barW, h - 1), Black, 4); + dl.AddRect(o, o + new Vector2(barW, h - 1), Gold, 4); + } + + // Two toggles at the bar's right end: the tools row and the Modern look. + float btn = MathF.Round(18 * s); + var b2 = new Vector2(o.X + barW - 8 * s - btn, o.Y + (h - btn) * 0.5f); + var b1 = new Vector2(b2.X - btn - 2 * s, b2.Y); + var bPlus = new Vector2(b1.X - btn - 6 * s, b2.Y); + var bMinus = new Vector2(bPlus.X - btn - 2 * s, b2.Y); + if (TitleToggle("##inv_smaller", PhosphorIcons.Minus, bMinus, btn, false)) + InventorySettingsStore.StepSize(-1); + ImGuiNET.ImGui.SetItemTooltip($"Smaller ({InventorySettingsStore.SizePct}%)"); + if (TitleToggle("##inv_bigger", PhosphorIcons.Plus, bPlus, btn, false)) + InventorySettingsStore.StepSize(+1); + ImGuiNET.ImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)"); + if (TitleToggle("##inv_tools", PhosphorIcons.Funnel, b1, btn, InventorySettingsStore.ShowTools)) + InventorySettingsStore.SetShowTools(!InventorySettingsStore.ShowTools); + ImGuiNET.ImGui.SetItemTooltip("Search, sort and filter"); + if (TitleToggle("##inv_modern", PhosphorIcons.SquaresFour, b2, btn, false)) + InventorySettingsStore.SetClassic(false); + ImGuiNET.ImGui.SetItemTooltip("Modern look"); + + // Drag surface: the bar left of the toggles (moves the panel, like the header). + float dragW = Math.Max(1, bMinus.X - o.X - 2); + ImGuiNET.ImGui.SetCursorScreenPos(o); + ImGuiNET.ImGui.InvisibleButton("##inv_titledrag", new Vector2(dragW, h)); + ImGuiPanelHost.DragWindowWithLastItem(); + + // "Inventory of <name>", centred on the bar (left of the toggles when it's narrow). + if (!ReferenceEquals(_titleFor, view.PlayerName)) + { + _titleFor = view.PlayerName; + _titleText = view.PlayerName.Length > 0 ? "Inventory of " + view.PlayerName : "Inventory"; + } + ImFontPtr f = ImGuiFonts.Get(UiFont.UiBold11); + ImGuiNET.ImGui.PushFont(f); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_titleText); + ImGuiNET.ImGui.PopFont(); + float tx = o.X + (barW - ts.X) * 0.5f; + if (tx + ts.X > bMinus.X - 4) tx = Math.Max(o.X + 10 * s, bMinus.X - 4 - ts.X); + dl.PushClipRect(o + new Vector2(6 * s, 0), new Vector2(bMinus.X - 2, o.Y + h), true); + dl.AddText(f, f.FontSize * InventorySettingsStore.SizeFactor, new Vector2(tx, o.Y + (h - ts.Y) * 0.5f), White, _titleText); + dl.PopClipRect(); + + // The retail close button. + var cp = new Vector2(o.X + barW, o.Y); + ImGuiNET.ImGui.SetCursorScreenPos(cp); + if (ImGuiNET.ImGui.InvisibleButton("##inv_close", new Vector2(closeW, h))) + ImGuiPanelHost.Close(Title); + bool down = ImGuiNET.ImGui.IsItemActive(); + ImGuiNET.ImGui.SetItemTooltip("Close"); + if (!Sprite(dl, down ? Art.Close + 1 : Art.Close, cp, new Vector2(closeW, h))) + { + dl.AddRect(cp + new Vector2(3 * s, 3 * s), cp + new Vector2(closeW - 3 * s, h - 3 * s), Gold, 2); + dl.AddLine(cp + new Vector2(7 * s, h * 0.5f), cp + new Vector2(closeW - 7 * s, h * 0.5f), Gold, 2); + } + } + + private static bool TitleToggle(string id, string glyph, Vector2 pos, float size, bool on) + { + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, new Vector2(size, size)); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + if (on || hot) dl.AddRect(pos, pos + new Vector2(size, size), on ? Gold : Faded(Gold), 3); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, new Vector2(size, size), on || hot ? Gold : Faded(Gold)); + return clicked; + } + + // ── Paperdoll ─────────────────────────────────────────────────────── + + private void Paperdoll(InventoryView view, ImDrawListPtr dl, Vector2 field, float s) + { + float cell = CellPx * s; + uint pendingId = InventoryModel.Pending?.ItemId ?? 0; + for (int i = 0; i < Doll.Length; i++) + { + DollSlot slot = Doll[i]; + InventoryItem? worn = null; + foreach (InventoryItem it in view.Worn) + if ((it.Location & slot.Mask) != 0) { worn = it; break; } + if (slot.Sigil != 0 && worn == null && (view.AetheriaMask & slot.Sigil) == 0) continue; // locked sigil slot + + var min = new Vector2(field.X + slot.X * s, field.Y + slot.Y * s); + var max = min + new Vector2(cell, cell); + ImGuiNET.ImGui.SetCursorScreenPos(min); + ImGuiNET.ImGui.PushID(i); + ImGuiNET.ImGui.InvisibleButton("##doll", new Vector2(cell, cell), ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight); + bool hovered = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + + if (worn != null) + { + DrawItemIcon(dl, worn.Id, min, cell, ReferenceEquals(worn, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu); + ItemPointer(worn, hovered); + } + else + { + CellPicture(dl, slot.Empty, min, cell); + if (hovered) + { + _hoverLabel = slot.Name; + _hoverLabel2 = "Empty. Drag an item here to wear it."; + } + } + + bool over = MouseIn(min, max); + if (_dragItem != null && over) + { + bool fits = _dragItem.Wielder == 0 && (_dragItem.ValidLocations & slot.Mask) != 0; + Overlay(dl, fits ? Art.AcceptGrid : Art.Reject, min, cell, fits ? AcceptGreen : RejectRed); + } + if (worn != null) + { + if (worn.Id == pendingId) Overlay(dl, Art.Waiting, min, cell, Amber); + if (worn.Id == _selected) Overlay(dl, Art.Selected, min, cell, SelYellow); + } + _targets.Add(new Target { Min = min, Max = max, Kind = DropKind.Slot, Id = slot.Mask, Name = slot.Name }); + } + } + + // ── Side column: burden, main pack, side packs ────────────────────── + + private void SideColumn(InventoryView view, ImDrawListPtr dl, Vector2 field, float r, float s, bool filtered) + { + // Burden: caption and percent (36x15 each at y 7 and 18), meter 11x58 at (44, 8). + ImFontPtr f = ImGuiFonts.Get(UiFont.Ui9); + CenterText(dl, f, "Burden", new Vector2(field.X, field.Y + 7 * s), new Vector2(36 * s, 15 * s), White); + CenterText(dl, f, view.BurdenText, new Vector2(field.X, field.Y + 18 * s), new Vector2(36 * s, 15 * s), White); + var mMin = new Vector2(field.X + 44 * s, field.Y + 8 * s); + var mSize = new Vector2(11 * s, 58 * s); + // Retail's meter holds 0-300% of capacity (OpenAC's BurdenMath.LoadToFill: load / 3). + float load = view.BurdenCapacity > 0 && view.Burden >= 0 ? view.Burden / (float)view.BurdenCapacity : 0f; + float fill = Math.Clamp(load / 3f, 0f, 1f); + if (!Sprite(dl, Art.BurdenBack, mMin, mSize)) dl.AddRectFilled(mMin, mMin + mSize, CellFallback); + if (fill > 0f) + { + var fMin = new Vector2(mMin.X, mMin.Y + mSize.Y * (1 - fill)); + if (RetailSprites.TryGet(Art.BurdenFill, out IntPtr ft)) + dl.AddImage(ft, fMin, mMin + mSize, new Vector2(0, 1 - fill), Vector2.One); + else + dl.AddRectFilled(fMin, mMin + mSize, load > 2f ? Red : load > 1f ? Amber : Green); + } + if (MouseIn(field + new Vector2(0, 7 * s), mMin + mSize) && ImGuiNET.ImGui.IsWindowHovered()) + { + _hoverLabel = "Burden"; + _hoverLabel2 = view.BurdenTip; + } + + // Main pack (36x36 at (6, 32)). + InventoryPack? main = view.Packs.Length > 0 ? view.Packs[0] : null; + PackCell(view, dl, main, new Vector2(field.X + 6 * s, field.Y + 32 * s), s, -1, filtered); + + // The main pack's pack slots (36 px pitch at (6, 73)): the side packs, then the items + // that take a pack slot (foci), as retail lists them; retail's seven slots (eight with + // the augmentation) or more. Scrollbar at (41, 73); they scroll together. + float listY = field.Y + 73 * s; + float listH = Math.Max(PackPx * s, (r - FieldY - 87) * s); + int rows = Math.Max(1, (int)(listH / (PackPx * s))); + int sidePacks = Math.Max(0, view.Packs.Length - 1); + int used = sidePacks + view.SlotItems.Length; + int slots = Math.Max(view.ContainerSlots > 0 ? view.ContainerSlots : SideBagSlots, used); + _packFirstRow = Math.Clamp(_packFirstRow, 0, Math.Max(0, slots - rows)); + uint pendingId = InventoryModel.Pending?.ItemId ?? 0; + for (int row = 0; row < rows; row++) + { + int i = _packFirstRow + row; + if (i >= slots) break; + var min = new Vector2(field.X + 6 * s, listY + row * PackPx * s); + if (i < sidePacks) PackCell(view, dl, view.Packs[i + 1], min, s, i, filtered); + else if (i < used) SlotItemCell(view, dl, view.SlotItems[i - sidePacks], min, s, i, pendingId); + else + { + PackCell(view, dl, null, min, s, i, filtered); + SlotDropHint(view, dl, min + new Vector2(2 * s, 2 * s), CellPx * s); + } + } + // The column itself (after the pack cells, which win): a pack-slot item dropped here + // moves to the main pack, where it lives. Nothing goes *inside* a pack-slot item. + var colMin = new Vector2(field.X, listY); + var colMax = new Vector2(field.X + 41 * s, listY + Math.Min(listH, rows * PackPx * s)); + if (view.PlayerId != 0) + _targets.Add(new Target { Min = colMin, Max = colMax, Kind = DropKind.PackSlots, Id = view.PlayerId, Name = "Main pack" }); + if (MouseIn(new Vector2(field.X, listY), new Vector2(field.X + SideW * s, listY + listH)) + && ImGuiNET.ImGui.IsWindowHovered()) + Wheel(ref _packFirstRow, slots - rows); + Scrollbar("##inv_packsb", new Vector2(field.X + 41 * s, listY), listH, s, ref _packFirstRow, slots, rows); + } + + /// <summary> + /// A pack-slot item (a focus) in the side column: a 36x36 cell with the item at (2, 2), + /// drawn and handled like a grid item (select, double-click use, drag, tooltip, menu). + /// </summary> + private void SlotItemCell(InventoryView view, ImDrawListPtr dl, InventoryItem it, Vector2 min, float s, int index, uint pendingId) + { + float box = PackPx * s, cell = CellPx * s; + var inner = min + new Vector2(2 * s, 2 * s); + ImGuiNET.ImGui.SetCursorScreenPos(min); + ImGuiNET.ImGui.PushID(index + 2); + ImGuiNET.ImGui.InvisibleButton("##slotitem", new Vector2(box, box), ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight); + bool hovered = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + ItemPointer(it, hovered); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts + ItemCell(dl, it, inner, cell, pendingId); + ImGuiNET.ImGui.PopFont(); + SlotDropHint(view, dl, inner, cell); + } + + /// <summary>While a drag is over a pack-slot cell: accept a pack-slot item headed for the main pack, else refuse.</summary> + private void SlotDropHint(InventoryView view, ImDrawListPtr dl, Vector2 inner, float cell) + { + if (_dragItem == null || !MouseIn(inner, inner + new Vector2(cell, cell))) return; + InventoryPack? main = view.Packs.Length > 0 ? view.Packs[0] : null; + if (_dragItem.RequiresPackSlot && _dragItem.Container == view.PlayerId && _dragItem.Wielder == 0) return; // already here + bool ok = main != null && _dragItem.RequiresPackSlot && !PackRefuses(view, main, _dragItem); + Overlay(dl, ok ? Art.AcceptPack : Art.Reject, inner, cell, ok ? AcceptGreen : RejectRed); + } + + /// <summary>One pack cell (36x36, the picture at (2, 2)): click opens it; drop an item on it to move it in.</summary> + private void PackCell(InventoryView view, ImDrawListPtr dl, InventoryPack? pack, Vector2 min, float s, int index, bool filtered) + { + float box = PackPx * s, cell = CellPx * s; + var inner = min + new Vector2(2 * s, 2 * s); + ImGuiNET.ImGui.SetCursorScreenPos(min); + ImGuiNET.ImGui.PushID(index + 2); + bool clicked = ImGuiNET.ImGui.InvisibleButton("##pack", new Vector2(box, box)); + bool hovered = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + + if (pack == null) + { + CellPicture(dl, Art.PackEmpty, inner, cell); + return; + } + if (clicked && _dragItem == null) _pack = pack.Id; + if (pack.IsMain) + { + if (!Sprite(dl, Art.MainPackIcon, inner, new Vector2(cell, cell))) + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Backpack, inner, new Vector2(cell, cell), Amber); + } + else + { + DrawItemIcon(dl, pack.Id, inner, cell); + } + + // Fill meter (5x30 at the cell's right edge), hidden while the pack is empty (retail's + // rule). Pack-slot items (foci) don't count against the main pack's 102. + if (pack.Used > 0 && pack.Capacity > 0) + { + float f = Math.Clamp(pack.Used / (float)pack.Capacity, 0f, 1f); + var bMin = inner + new Vector2(cell - 5 * s, 1 * s); + var bSize = new Vector2(5 * s, 30 * s); + if (!Sprite(dl, Art.CapacityBack, bMin, bSize)) dl.AddRectFilled(bMin, bMin + bSize, Black); + var fMin = new Vector2(bMin.X, bMin.Y + bSize.Y * (1 - f)); + if (RetailSprites.TryGet(Art.CapacityFill, out IntPtr ft)) + dl.AddImage(ft, fMin, bMin + bSize, new Vector2(0, 1 - f), Vector2.One); + else + dl.AddRectFilled(fMin, bMin + bSize, Gold); + } + + if (pack.Id == _pack && !filtered) + { + if (!Sprite(dl, Art.OpenPack, min, new Vector2(box, box))) + dl.AddTriangleFilled(new Vector2(min.X, min.Y + box * 0.35f), new Vector2(min.X + 5 * s, min.Y + box * 0.5f), + new Vector2(min.X, min.Y + box * 0.65f), Gold); + } + if (_dragItem != null && MouseIn(min, min + new Vector2(box, box))) + { + bool here = _dragItem.Container == pack.Id && _dragItem.Wielder == 0; + bool full = !here && PackRefuses(view, pack, _dragItem); + if (!here) Overlay(dl, full ? Art.Reject : Art.AcceptPack, inner, cell, full ? RejectRed : AcceptGreen); + } + if (hovered) + { + _hoverLabel = pack.Name; + _hoverLabel2 = pack.FillText; + } + _targets.Add(new Target { Min = min, Max = min + new Vector2(box, box), Kind = DropKind.Pack, Id = pack.Id, Name = pack.Name }); + } + + // ── Contents: the open pack's slots ───────────────────────────────── + + private void Contents(InventoryView view, ImDrawListPtr dl, Vector2 field, float sideX, float r, float s, bool filtered) + { + float cell = CellPx * s; + var gridPos = new Vector2(field.X + 15 * s, field.Y + 20 * s); + float availW = sideX - 32 * s - gridPos.X; // retail: grid 15..207, scrollbar 207..223, column at 239 + int cols = Math.Max(1, (int)(availW / cell)); + float gridW = cols * cell; + float gridH = Math.Max(cell, (r - ContentsY - 5 - 24) * s); + int rows = Math.Max(1, (int)(gridH / cell + 0.01f)); + + // "Contents of <pack>" over the grid. + CenterText(dl, ImGuiFonts.Get(UiFont.Ui10), _captionText, new Vector2(gridPos.X, field.Y), new Vector2(gridW, 15 * s), White); + + InventoryPack? open = filtered ? null : view.PackOf(_pack); + int cells = open != null ? Math.Max(open.Capacity, _shown.Count) : _shown.Count; + int totalRows = (cells + cols - 1) / cols; + _gridFirstRow = Math.Clamp(_gridFirstRow, 0, Math.Max(0, totalRows - rows)); + + var area = new Vector2(gridW, rows * cell); + ImGuiNET.ImGui.SetCursorScreenPos(gridPos); + ImGuiNET.ImGui.InvisibleButton("##inv_cells", area, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight); + bool hovered = ImGuiNET.ImGui.IsItemHovered(); + Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); + int hoverCell = -1; + if (MouseIn(gridPos, gridPos + area)) + { + int c = (int)((mouse.X - gridPos.X) / cell), rr = (int)((mouse.Y - gridPos.Y) / cell); + if (c >= 0 && c < cols && rr >= 0 && rr < rows) hoverCell = (_gridFirstRow + rr) * cols + c; + if (ImGuiNET.ImGui.IsWindowHovered()) Wheel(ref _gridFirstRow, totalRows - rows); + } + if (hovered && hoverCell >= 0 && hoverCell < _shown.Count) ItemPointer(_shown[hoverCell], true); + + // Only the rows on show; retail draws an item's icon in place of the empty cell. + uint pendingId = InventoryModel.Pending?.ItemId ?? 0; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts + for (int rr = 0; rr < rows; rr++) + { + for (int c = 0; c < cols; c++) + { + int i = (_gridFirstRow + rr) * cols + c; + if (i >= cells) break; + var min = new Vector2(gridPos.X + c * cell, gridPos.Y + rr * cell); + if (i >= _shown.Count) + { + CellPicture(dl, Art.GridEmpty, min, cell); + continue; + } + ItemCell(dl, _shown[i], min, cell, pendingId); + } + } + ImGuiNET.ImGui.PopFont(); + + if (open != null) + { + // Dropping on the grid moves the item into the open pack. + if (_dragItem != null && hoverCell >= 0 && hoverCell < cells && !(_dragItem.Container == open.Id && _dragItem.Wielder == 0)) + { + int c = hoverCell % cols, rr = hoverCell / cols - _gridFirstRow; + var min = new Vector2(gridPos.X + c * cell, gridPos.Y + rr * cell); + bool full = PackRefuses(view, open, _dragItem); + Overlay(dl, full ? Art.Reject : Art.AcceptGrid, min, cell, full ? RejectRed : AcceptGreen); + } + _targets.Add(new Target { Min = gridPos, Max = gridPos + area, Kind = DropKind.Pack, Id = open.Id, Name = open.Name }); + } + else if (_shown.Count == 0) + { + dl.AddText(gridPos + new Vector2(4, 4), Mute, "Nothing matches."); + } + + Scrollbar("##inv_gridsb", new Vector2(gridPos.X + gridW, gridPos.Y), rows * cell, s, ref _gridFirstRow, totalRows, rows); + } + + // ── Status strip: the action / outcome (or pyreals), Drop, Give ───── + + private void StatusStrip(InventoryView view, ImDrawListPtr dl, Vector2 p, float w, float h, float s) + { + dl.AddRectFilled(p, p + new Vector2(w, h), Black); + dl.AddLine(p, p + new Vector2(w, 0), Faded(Gold)); + InventoryTarget? target = InventoryModel.Target; + InventoryItem? sel = SelectedItem(view); + float zh = h - 4, giveW = Math.Min(128 * s, w * 0.42f), dropW = 62 * s; + var give = new Vector2(p.X + w - giveW - 2, p.Y + 2); + var drop = new Vector2(give.X - dropW - 3, p.Y + 2); + Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, "Drop", drop, new Vector2(dropW, zh), 0, "", + InventoryModel.DropAvailable, sel, "Drop on the ground: drag an item here, or click to drop the selected item."); + Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, target?.ZoneLabel ?? "Give", give, new Vector2(giveW, zh), + target?.Id ?? 0, target?.Name ?? "", InventoryModel.GiveAvailable && target != null, sel, + target?.ZoneTip ?? "Select a creature, NPC or player in the game to give to."); + StatusLine(new Vector2(p.X + 3, p.Y), Math.Max(10, drop.X - p.X - 6), h, view); + } + + // ── Pieces ────────────────────────────────────────────────────────── + + /// <summary> + /// One item's cell picture (the contents grid and the side column's pack-slot items): + /// its icon (faded while dragged), stack count (in the caller's font), and the waiting + /// and selected overlays. + /// </summary> + private void ItemCell(ImDrawListPtr dl, InventoryItem it, Vector2 min, float cell, uint pendingId) + { + DrawItemIcon(dl, it.Id, min, cell, ReferenceEquals(it, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu); + if (it.StackText.Length > 0) + { + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(it.StackText); + var tp = new Vector2(min.X + cell - ts.X - 1, min.Y + cell - ts.Y); + dl.AddText(tp + Vector2.One, StackShadow, it.StackText); + dl.AddText(tp, StackCol, it.StackText); + } + if (it.Id == pendingId) Overlay(dl, Art.Waiting, min, cell, Amber); + if (it.Id == _selected) Overlay(dl, Art.Selected, min, cell, SelYellow); + } + + /// <summary>Hover, click (select, and a press that may become a drag), double-click (use), right-click (menu).</summary> + private void ItemPointer(InventoryItem it, bool hovered) + { + if (!hovered) return; + _hover = it; + if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) + { + SelectItem(it); + _pressItem = it; + _pressAt = ImGuiNET.ImGui.GetMousePos(); + } + if (ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left)) + { + _pressItem = null; + Act(InventoryActionKind.Use, it, 0, "", 0); + } + if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) + { + _selected = it.Id; + _ctxItem = it; + _openCtx = true; + } + } + + /// <summary> + /// The retail scrollbar (LayoutDesc 0x2100003E's 16 px variant): tiled chain, up and down + /// gems, three-piece thumb. Clicking a gem moves a row; dragging the thumb, or clicking the + /// chain, moves to that point. + /// </summary> + private void Scrollbar(string id, Vector2 pos, float h, float s, ref int first, int total, int visible) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float w = 16 * s, btn = Math.Min(16 * s, h * 0.5f); + int max = Math.Max(0, total - visible); + first = Math.Clamp(first, 0, max); + if (h < 2 || w < 2) return; + + // Chain, tiled down the shaft (stretching smears the beads). + if (RetailSprites.TryGet(Art.Track, out IntPtr track)) + { + float tile = 32 * s; + for (float y = 0; y < h; y += tile) + { + float th = Math.Min(tile, h - y); + dl.AddImage(track, new Vector2(pos.X, pos.Y + y), new Vector2(pos.X + w, pos.Y + y + th), Vector2.Zero, + new Vector2(1, th / tile)); + } + } + else + { + dl.AddRectFilled(pos + new Vector2(w * 0.3f, 0), pos + new Vector2(w * 0.7f, h), Faded(Gold)); + } + + ImGuiNET.ImGui.PushID(id); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + if (ImGuiNET.ImGui.InvisibleButton("##up", new Vector2(w, btn)) && first > 0) first--; + uint upState = ImGuiNET.ImGui.IsItemActive() ? 2u : ImGuiNET.ImGui.IsItemHovered() ? 1u : 0u; + var downPos = new Vector2(pos.X, pos.Y + h - btn); + ImGuiNET.ImGui.SetCursorScreenPos(downPos); + if (ImGuiNET.ImGui.InvisibleButton("##down", new Vector2(w, btn)) && first < max) first++; + uint downState = ImGuiNET.ImGui.IsItemActive() ? 2u : ImGuiNET.ImGui.IsItemHovered() ? 1u : 0u; + + float t0 = pos.Y + btn, span = h - 2 * btn; + if (max > 0 && span > 4) + { + float th = Math.Clamp(span * visible / Math.Max(1, total), Math.Min(16 * s, span), span); + float t = t0 + (span - th) * first / max; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(pos.X, t0)); + ImGuiNET.ImGui.InvisibleButton("##track", new Vector2(w, span)); + if (ImGuiNET.ImGui.IsItemActive()) + { + float my = ImGuiNET.ImGui.GetMousePos().Y; + if (ImGuiNET.ImGui.IsItemActivated()) _thumbGrab = my >= t && my < t + th ? my - t : th * 0.5f; + float rel = (my - _thumbGrab - t0) / Math.Max(1f, span - th); + first = Math.Clamp((int)MathF.Round(rel * max), 0, max); + t = t0 + (span - th) * first / max; + } + // Thumb: 3 px caps, the middle stretched. + float cap = Math.Min(3 * s, th * 0.5f); + var a = new Vector2(pos.X, t); + if (!Sprite(dl, Art.ThumbTop, a, new Vector2(w, cap)) + | !Sprite(dl, Art.ThumbMid, a + new Vector2(0, cap), new Vector2(w, th - 2 * cap)) + | !Sprite(dl, Art.ThumbBottom, a + new Vector2(0, th - cap), new Vector2(w, cap))) + dl.AddRectFilled(a, a + new Vector2(w, th), Rgb(0xFF203C78), 2); + } + ImGuiNET.ImGui.PopID(); + + if (!Sprite(dl, Art.Up + upState, pos, new Vector2(w, btn))) + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretUp, pos, new Vector2(w, btn), Gold); + if (!Sprite(dl, Art.Down + downState, downPos, new Vector2(w, btn))) + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown, downPos, new Vector2(w, btn), Gold); + } + + private static void Wheel(ref int first, int max) + { + float wheel = ImGuiNET.ImGui.GetIO().MouseWheel; + if (wheel == 0) return; + first = Math.Clamp(first - Math.Sign(wheel), 0, Math.Max(0, max)); + } + + /// <summary>A retail picture at min..min+size; false (nothing drawn) until it has loaded.</summary> + private static bool Sprite(ImDrawListPtr dl, uint id, Vector2 min, Vector2 size) + { + if (!RetailSprites.TryGet(id, out IntPtr tex)) return false; + dl.AddImage(tex, min, min + size); + return true; + } + + /// <summary>An empty cell's picture, or a plain dark cell until it has loaded.</summary> + private static void CellPicture(ImDrawListPtr dl, uint id, Vector2 min, float size) + { + if (Sprite(dl, id, min, new Vector2(size, size))) return; + dl.AddRectFilled(min, min + new Vector2(size, size), CellFallback); + dl.AddRect(min, min + new Vector2(size, size), CellEdge); + } + + /// <summary>A retail overlay (selected, waiting, drop accepted / refused), or an outline in <paramref name="fallback"/>.</summary> + private static void Overlay(ImDrawListPtr dl, uint id, Vector2 min, float size, uint fallback) + { + if (Sprite(dl, id, min, new Vector2(size, size))) return; + dl.AddRect(min, min + new Vector2(size, size), fallback, 2, ImDrawFlags.None, 1.5f); + } + + private static void CenterText(ImDrawListPtr dl, ImFontPtr f, string text, Vector2 pos, Vector2 size, uint color) + { + if (text.Length == 0) return; + ImGuiNET.ImGui.PushFont(f); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text); + ImGuiNET.ImGui.PopFont(); + dl.PushClipRect(pos, pos + size, true); + dl.AddText(f, f.FontSize * InventorySettingsStore.SizeFactor, new Vector2(pos.X + (size.X - ts.X) * 0.5f, pos.Y + (size.Y - ts.Y) * 0.5f), color, text); + dl.PopClipRect(); + } + + private static bool MouseIn(Vector2 min, Vector2 max) + { + Vector2 m = ImGuiNET.ImGui.GetMousePos(); + return m.X >= min.X && m.Y >= min.Y && m.X < max.X && m.Y < max.Y; + } +} + +/// <summary> +/// The Inventory panel's remembered choices: Classic or Modern look, and whether the +/// Classic view shows its tools row. %LOCALAPPDATA%\RynthCore\inventory_settings.txt, +/// read once when the panel opens, written in the background when a choice changes. +/// </summary> +internal static class InventorySettingsStore +{ + private static readonly object Sync = new(); + private static bool _loaded; + + /// <summary>The retail look (default) or the Phase 1 modern layout.</summary> + public static bool Classic { get; private set; } = true; + /// <summary>Classic view: the search / sort / category row under the title bar.</summary> + public static bool ShowTools { get; private set; } + /// <summary>The panel's size in percent of the UI scale (50-150, steps of 10); text follows it.</summary> + public static int SizePct { get; private set; } = 80; + public static float SizeFactor => SizePct / 100f; + + private static string FilePath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "inventory_settings.txt"); + + public static void Load() + { + lock (Sync) + { + if (_loaded) return; + _loaded = true; + try + { + string path = FilePath; + if (!File.Exists(path)) return; + foreach (string raw in File.ReadAllLines(path)) + { + string line = raw.Trim(); + int eq = line.IndexOf('='); + if (line.StartsWith('#') || eq <= 0) continue; + string key = line[..eq].Trim(), val = line[(eq + 1)..].Trim(); + if (key == "classic") Classic = val == "1"; + else if (key == "tools") ShowTools = val == "1"; + else if (key == "size" && int.TryParse(val, out int pct)) SizePct = Math.Clamp(pct, 50, 150); + } + } + catch { /* defaults stay */ } + } + } + + public static void SetClassic(bool on) + { + if (Classic == on) return; + Classic = on; + Save(); + } + + public static void StepSize(int dir) + { + int next = Math.Clamp(SizePct + 10 * Math.Sign(dir), 50, 150); + if (next == SizePct) return; + SizePct = next; + Save(); + } + + public static void SetShowTools(bool on) + { + if (ShowTools == on) return; + ShowTools = on; + Save(); + } + + /// <summary>Writes the settings in the background (the caller is AC's render thread).</summary> + private static void Save() + { + string text = "# RynthCore inventory panel settings - auto-generated, hand-edits OK.\n" + + "classic=" + (Classic ? "1" : "0") + "\n" + + "tools=" + (ShowTools ? "1" : "0") + "\n" + + "size=" + SizePct + "\n"; + UiBackgroundWriter.Enqueue("inventory settings", () => + { + lock (Sync) + { + try + { + string path = FilePath; + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.WriteAllText(path, text); + } + catch { /* non-fatal */ } + } + }); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs new file mode 100644 index 0000000..065b6b4 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs @@ -0,0 +1,1073 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/InventoryFace.cs +// The in-game Inventory panel (docs/IMGUI_INVENTORY.md). Engine only. +// Two looks, one set of behaviours (a toggle switches them, remembered): +// Classic the retail inventory window, drawn from the client's own +// pictures (InventoryFace.Classic.cs; Phase 2) +// Modern the Phase 1 layout, below +// +// header burden (percent of capacity) and pyreals; item count +// tools search box, sort picker; category chips +// packs All, Main pack, each side pack (its icon and fill), Worn +// grid the chosen pack's items as icons with stack counts; hover for a +// tooltip (asks the server to identify an unknown item, throttled); +// double-click uses; right-click for Use / Equip / Split / Move to / +// Drop / Give; drag onto a pack to move, onto Equip / Drop / Give +// zones Equip, Drop, Give-to-<selected creature>: drop targets for a drag, +// or buttons for the selected item +// status the one action waiting for the server (with a timer), or how the +// last one ended +// +// Data: InventoryModel (Compatibility), captured and acted on on AC's main +// thread. This face only reads its published objects and posts requests; one +// item action at a time (a click while one waits is refused, never queued). +// Per frame: no allocation except the tooltip of a newly hovered item and the +// filtered list when the view, pack, filter, search or sort change. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI.ScriptWindows; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class InventoryFace : IImGuiPanel +{ + public const string Title = "Inventory"; + + // Default: the Classic view at its retail size (300 x 362 body, plus the status strip). + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(302, 426), new Vector2(240, 300), EdgeToEdge: true), + () => new InventoryFace()); + + // ── Layout (px, like the other faces) ─────────────────────────────── + private const float Cell = 38, Icon = 32, RowH = 24, PackRowH = 38, ZoneH = 30, StatusH = 20; + private const uint AllPacks = 0, WornPacks = 1; // pseudo pack ids (real ids are never 0 or 1) + + private static readonly uint CellBg = RynthTheme.Argb(0xFF101822), CellHot = RynthTheme.Argb(0xFF1C3148), + CellSel = RynthTheme.Argb(0xFF26D9E6), StackCol = RynthTheme.Argb(0xFFFFFFFF), StackShadow = RynthTheme.Argb(0xE0000000), + DropHot = RynthTheme.Argb(0xFF1F5A3A), Placeholder = RynthTheme.Argb(0xFF1A2633); + + private static readonly string[] SortNames = { "Pack order", "Name", "Value", "Burden", "Type", "Stack" }; + private static readonly string[] SortLabels = Array.ConvertAll(SortNames, n => PhosphorIcons.SortAscending + " " + n); + private static readonly string[] CategoryNames = { "All", "Weapons", "Armor", "Jewelry", "Usable", "Comps", "Salvage", "Misc" }; + private static readonly InventoryCategory[] CategoryOf = + { + default, InventoryCategory.Weapons, InventoryCategory.Armor, InventoryCategory.Jewelry, InventoryCategory.Usable, + InventoryCategory.Components, InventoryCategory.Salvage, InventoryCategory.Misc, + }; + + // ── State ─────────────────────────────────────────────────────────── + private uint _pack = AllPacks; + private int _sort, _category; + private readonly byte[] _search = new byte[64]; + private string _searchText = string.Empty; + private uint _selected; + private readonly Picker _picker = new("##inv_sort"); + + // Filtered, sorted list (rebuilt only when an input changes). + private readonly List<InventoryItem> _shown = new(256); + private InventoryView? _builtFor; + private uint _builtPack = uint.MaxValue; + private int _builtSort = -1, _builtCategory = -1; + private string _builtSearch = "\0"; + private bool _builtClassic; + // Leave pack-slot items (foci) out of this list: the Classic main pack grid (they're in the side column). + private bool _skipSlotItems; + private string _countText = string.Empty; + + // Hover and tooltip cache. + private InventoryItem? _hover, _tipItem; + private string[] _tipBase = Array.Empty<string>(); + + // Drag. + private InventoryItem? _pressItem, _dragItem; + private Vector2 _pressAt; + // Slot: one paperdoll slot (Id = its equip mask, Name = the slot's name). + // PackSlots: the Classic side column's pack slots (Id = the main pack): only a + // pack-slot item (a focus) goes there, which moves it to the main pack. + private enum DropKind : byte { None, Pack, Equip, Drop, Give, Slot, PackSlots } + private struct Target { public Vector2 Min, Max; public DropKind Kind; public uint Id; public string Name; } + private readonly List<Target> _targets = new(16); + + // Context menu and split dialog (opened at the end of Draw, outside any child). + private InventoryItem? _ctxItem; + private bool _openCtx, _openSplit; + private InventoryItem? _splitItem; + private int _splitAmount = 1; + private uint _splitTarget; + // "Add to loot profile..." (right-click): RynthAi builds the rule, the popup previews it. + private readonly LootAddDialog _lootAdd = new("##inv_lootadd"); + + // Status line cache. + private string _statusText = string.Empty; + private int _statusKey = int.MinValue; + private string _refusal = string.Empty; + private long _refusalAt; + + public void OnShown() + { + InventorySettingsStore.Load(); + InventoryModel.Subscribe(); + } + + public void OnHidden() + { + InventoryModel.Hover(0); + InventoryModel.Unsubscribe(); + _dragItem = _pressItem = null; + ItemDragBridge.EndPopOutDrag(); + _lootAdd.Cancel(); + } + + // ===================================================================== + // Frame + // ===================================================================== + + public void Draw() + { + InventoryView view = InventoryModel.Current; + _targets.Clear(); + _hover = null; + + float w = Begin(out Vector2 origin, out Vector2 size); + if (view.PlayerId == 0) + { + Label("Waiting for your character's inventory...", Mute); + End(origin, size); + InventoryModel.Hover(0); + return; + } + + _hoverLabel = _hoverLabel2 = null; + // Text follows the panel's size setting (the - / + in the Classic title bar). + ImGuiNET.ImGui.SetWindowFontScale(InventorySettingsStore.SizeFactor); + if (InventorySettingsStore.Classic) ClassicBody(view, origin, size); + else ModernBody(view, origin, size, w); + + InventoryModel.Hover(_dragItem == null ? _hover?.Id ?? 0 : 0); + FinishDrag(); + End(origin, size); + + Tooltip(); + DrawDragGhost(); + ContextMenu(view); + SplitDialog(view); + _lootAdd.Draw(); + _picker.Draw(); + } + + /// <summary>The Phase 1 layout: header, tools, chips, pack column | grid, zones, status.</summary> + private void ModernBody(InventoryView view, Vector2 origin, Vector2 size, float w) + { + if (_pack != AllPacks && _pack != WornPacks && view.PackOf(_pack) == null) _pack = AllPacks; + RebuildIfNeeded(view, _pack); // the header shows the count + Header(view, w); + Tools(w); + Chips(w); + RebuildIfNeeded(view, _pack); + + // Body: pack column | grid, then zones and the status row at the bottom. + float bottomH = ZoneH + StatusH + 8; + Vector2 bodyPos = ImGuiNET.ImGui.GetCursorScreenPos(); + float bodyH = Math.Max(60, origin.Y + size.Y - 6 - bottomH - bodyPos.Y); + float colW = w >= 380 ? 128 : 46; + PackColumn(view, bodyPos, colW, bodyH); + Grid(new Vector2(bodyPos.X + colW + 4, bodyPos.Y), new Vector2(w - colW - 4, bodyH)); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bodyPos.X, bodyPos.Y + bodyH + 4)); + Zones(view, w); + StatusRow(w); + } + + // ── Header: burden, pyreals, count ────────────────────────────────── + + private void Header(InventoryView view, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr icons = ImGuiFonts.Get(UiFont.Ui14); + float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + + PhosphorIcons.DrawCentered(dl, icons, PhosphorIcons.Scales, p, new Vector2(18, RowH), Amber); + float x = p.X + 20; + dl.AddText(new Vector2(x, ty), BurdenColour(view), view.BurdenText); + float bw = ImGuiNET.ImGui.CalcTextSize(view.BurdenText).X; + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.InvisibleButton("##burden", new Vector2(x + bw - p.X, RowH)); + ImGuiNET.ImGui.SetItemTooltip(view.BurdenTip); + + x += bw + 16; + PhosphorIcons.DrawCentered(dl, icons, PhosphorIcons.Coins, new Vector2(x, p.Y), new Vector2(18, RowH), Amber); + dl.AddText(new Vector2(x + 20, ty), Text, view.PyrealText); + + // Switch to the Classic (retail) look. + var tb = new Vector2(p.X + w - 22, p.Y + 1); + if (IconButton("##inv_classic", PhosphorIcons.AppWindow, tb, new Vector2(22, 22), Amber, BtnFill, font: UiFont.Ui11)) + InventorySettingsStore.SetClassic(true); + ImGuiNET.ImGui.SetItemTooltip("Classic look (the retail inventory window)"); + + float cw = ImGuiNET.ImGui.CalcTextSize(_countText).X; + dl.AddText(new Vector2(tb.X - cw - 6, ty), Mute, _countText); + NextLine(p, RowH + 2); + } + + private static uint BurdenColour(InventoryView view) + { + if (view.BurdenCapacity <= 0 || view.Burden < 0) return Text; + return view.Burden > view.BurdenCapacity ? Red : view.Burden * 10 > view.BurdenCapacity * 9 ? Amber : Green; + } + + // ── Search, sort, categories ──────────────────────────────────────── + + private void Tools(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float sortW = 118; + float boxW = Math.Max(80, w - sortW - 26 - 8); + if (TextBox("##inv_search", _search, p, boxW, PhosphorIcons.MagnifyingGlass + " Search names", out _)) + _searchText = Utf8(_search).Trim().ToLowerInvariant(); + if (IconButton("##inv_clear", PhosphorIcons.X, new Vector2(p.X + boxW + 2, p.Y), new Vector2(22, 22), Mute, BtnFill, + enabled: _search[0] != 0, font: UiFont.Ui11)) + { + Array.Clear(_search); + _searchText = string.Empty; + } + ImGuiNET.ImGui.SetItemTooltip("Clear the search"); + Vector2 sp = new(p.X + w - sortW, p.Y); + if (Button("##inv_sortbtn", SortLabels[_sort], sp, new Vector2(sortW, 22), Text, BtnFill, + leftAlign: true)) + _picker.Open(new Vector2(sp.X, sp.Y + 24), SortNames, _sort, i => _sort = i, sortW); + ImGuiNET.ImGui.SetItemTooltip("Sort the items"); + NextLine(p, 26); + } + + private void Chips(float w) + { + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + float x = start.X, y = start.Y; + ImFontPtr f = ImGuiFonts.Get(UiFont.Ui9); + const float h = 18; + for (int i = 0; i < CategoryNames.Length; i++) + { + string label = CategoryNames[i]; + float cw = CalcWidth(f, label) + 12; + if (x > start.X && x + cw > start.X + w) { x = start.X; y += h + 3; } + var pos = new Vector2(x, y); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + ImGuiNET.ImGui.PushID(i); + if (ImGuiNET.ImGui.InvisibleButton("##chip", new Vector2(cw, h))) _category = i; + bool hot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + bool on = _category == i; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(pos, pos + new Vector2(cw, h), on ? Selected : hot ? Lighten(BtnFill) : BtnFill, 9); + dl.AddRect(pos, pos + new Vector2(cw, h), on ? Teal : BtnBord, 9); + dl.AddText(f, f.FontSize * InventorySettingsStore.SizeFactor, pos + new Vector2(6, (h - f.FontSize) * 0.5f), on ? Teal : Text, label); + x += cw + 4; + } + NextLine(start, y - start.Y + h + 4); + } + + private static float CalcWidth(ImFontPtr font, string text) + { + ImGuiNET.ImGui.PushFont(font); + float w = ImGuiNET.ImGui.CalcTextSize(text).X; + ImGuiNET.ImGui.PopFont(); + return w; + } + + // ── Filtered list ─────────────────────────────────────────────────── + + /// <summary> + /// The filtered, sorted list for <paramref name="pack"/> (a real pack id, AllPacks or + /// WornPacks; the caller makes sure a real id is in the view). Rebuilt only on change. + /// </summary> + private void RebuildIfNeeded(InventoryView view, uint pack) + { + bool classic = InventorySettingsStore.Classic; + if (ReferenceEquals(view, _builtFor) && _builtPack == pack && _builtSort == _sort + && _builtCategory == _category && ReferenceEquals(_builtSearch, _searchText) && _builtClassic == classic) + return; + if (_builtPack != pack || !ReferenceEquals(_builtSearch, _searchText) || _builtCategory != _category) + _gridFirstRow = 0; // another pack or filter: back to the top (Classic grid) + _builtFor = view; + _builtPack = pack; + _builtSort = _sort; + _builtCategory = _category; + _builtSearch = _searchText; + _builtClassic = classic; + + _shown.Clear(); + InventoryPack? one = pack == WornPacks || pack == AllPacks ? null : view.PackOf(pack); + // Classic, the main pack open: its pack-slot items (foci) are in the side column, not + // the grid (retail). A search or filter (all packs) and the Modern look list them. + _skipSlotItems = classic && one != null && one.IsMain; + if (pack == WornPacks) AddFiltered(view.Worn); + else if (one == null) foreach (InventoryPack p in view.Packs) AddFiltered(p.Items); + else AddFiltered(one.Items); + + Comparison<InventoryItem>? cmp = _sort switch + { + 1 => ByName, + 2 => static (a, b) => b.Value != a.Value ? b.Value.CompareTo(a.Value) : ByName(a, b), + 3 => static (a, b) => b.Burden != a.Burden ? b.Burden.CompareTo(a.Burden) : ByName(a, b), + 4 => static (a, b) => a.Category != b.Category ? a.Category.CompareTo(b.Category) : ByName(a, b), + 5 => static (a, b) => b.Stack != a.Stack ? b.Stack.CompareTo(a.Stack) : ByName(a, b), + _ => null, // pack order: as captured (packs in order, ascending id inside each) + }; + if (cmp != null) _shown.Sort(cmp); + + int total = pack == WornPacks ? view.Worn.Length : one == null ? view.ItemCount + : _skipSlotItems ? one.Used : one.Items.Length; + _countText = _shown.Count == total + ? total.ToString(CultureInfo.InvariantCulture) + " items" + : _shown.Count.ToString(CultureInfo.InvariantCulture) + " of " + total.ToString(CultureInfo.InvariantCulture); + // The Classic grid's caption, retail's "Contents of <pack>". + _captionText = pack == WornPacks ? "Worn" + : one == null ? (_shown.Count == total ? "All packs" : "Matches in all packs: " + _countText) + : one.IsMain ? "Contents of Backpack" + : "Contents of " + one.Name; + } + + private static int ByName(InventoryItem a, InventoryItem b) + { + int c = string.CompareOrdinal(a.SearchName, b.SearchName); + return c != 0 ? c : a.Id.CompareTo(b.Id); + } + + private void AddFiltered(InventoryItem[] items) + { + InventoryCategory cat = CategoryOf[_category]; + foreach (InventoryItem it in items) + { + if (_skipSlotItems && it.RequiresPackSlot) continue; + if (_category != 0 && it.Category != cat) continue; + if (_searchText.Length > 0 && !it.SearchName.Contains(_searchText, StringComparison.Ordinal)) continue; + _shown.Add(it); + } + } + + // ── Pack column ───────────────────────────────────────────────────── + + private void PackColumn(InventoryView view, Vector2 pos, float colW, float h) + { + ImGuiNET.ImGui.SetCursorScreenPos(pos); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 2)); + ImGuiNET.ImGui.BeginChild("##inv_packs", new Vector2(colW, h), ImGuiChildFlags.AlwaysUseWindowPadding); + ImGuiNET.ImGui.PopStyleVar(2); + float iw = ImGuiNET.ImGui.GetContentRegionAvail().X; + bool wide = colW > 60; + + PackRow("##p_all", AllPacks, PhosphorIcons.SquaresFour, 0, "All packs", view.ItemCountText, iw, wide, DropKind.None, ""); + for (int i = 0; i < view.Packs.Length; i++) + { + InventoryPack p = view.Packs[i]; + ImGuiNET.ImGui.PushID(i); + PackRow("##p", p.Id, p.IsMain ? PhosphorIcons.Backpack : string.Empty, p.IsMain ? 0 : p.Id, p.Name, p.FillText, + iw, wide, DropKind.Pack, p.Name); + ImGuiNET.ImGui.PopID(); + } + PackRow("##p_worn", WornPacks, PhosphorIcons.Shield, 0, "Worn", view.WornCountText, iw, wide, DropKind.Equip, "Worn"); + + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleColor(); + } + + /// <summary>One pack entry: click shows it; it is a drop target (move into it, or equip for Worn).</summary> + private void PackRow(string id, uint packId, string glyph, uint iconObject, string name, string fill, float w, bool wide, + DropKind drop, string dropName) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var sz = new Vector2(w, PackRowH); + if (ImGuiNET.ImGui.InvisibleButton(id, sz)) _pack = packId; + bool hot = ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem); + if (!wide && hot && _dragItem == null && ImGuiNET.ImGui.BeginTooltip()) + { + ImGuiNET.ImGui.TextUnformatted(name); + ImGuiNET.ImGui.TextUnformatted(fill); + ImGuiNET.ImGui.EndTooltip(); + } + bool on = _pack == packId; + bool dropHot = _dragItem != null && drop != DropKind.None && hot; + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(p, p + sz, dropHot ? DropHot : on ? Selected : hot ? CellHot : BtnFill, 3); + dl.AddRect(p, p + sz, on || dropHot ? Teal : BtnBord, 3); + var iconMin = new Vector2(p.X + 3, p.Y + (PackRowH - Icon) * 0.5f); + if (iconObject != 0) DrawItemIcon(dl, iconObject, iconMin, Icon); + else PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), glyph, iconMin, new Vector2(Icon, Icon), on ? Teal : Mute); + if (wide) + { + float tx = p.X + Icon + 8; + dl.PushClipRect(new Vector2(tx, p.Y), p + sz, true); + dl.AddText(new Vector2(tx, p.Y + 3), on ? Teal : Text, name); + ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9); + dl.AddText(f9, f9.FontSize * InventorySettingsStore.SizeFactor, new Vector2(tx, p.Y + PackRowH - f9.FontSize - 4), Mute, fill); + dl.PopClipRect(); + } + if (drop != DropKind.None) + { + // Only the part inside the (scrolling) pack column counts: a row scrolled out of + // view must not catch a drop over the search box or the zones. + Vector2 wmin = ImGuiNET.ImGui.GetWindowPos(), wmax = wmin + ImGuiNET.ImGui.GetWindowSize(); + Vector2 min = Vector2.Max(p, wmin), max = Vector2.Min(p + sz, wmax); + if (max.X > min.X && max.Y > min.Y) + _targets.Add(new Target { Min = min, Max = max, Kind = drop, Id = packId, Name = dropName }); + } + } + + // ── Grid ──────────────────────────────────────────────────────────── + + private void Grid(Vector2 pos, Vector2 size) + { + ImGuiNET.ImGui.SetCursorScreenPos(pos); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(3, 3)); + ImGuiNET.ImGui.BeginChild("##inv_grid", size, ImGuiChildFlags.AlwaysUseWindowPadding); + ImGuiNET.ImGui.PopStyleVar(); + + // Showing one pack: dropping on the grid moves the item into that pack. + if (_pack != AllPacks && _pack != WornPacks && _builtFor?.PackOf(_pack) is InventoryPack shownPack) + { + Vector2 wmin = ImGuiNET.ImGui.GetWindowPos(); + _targets.Add(new Target { Min = wmin, Max = wmin + ImGuiNET.ImGui.GetWindowSize(), Kind = DropKind.Pack, + Id = shownPack.Id, Name = shownPack.Name }); + } + + float avail = ImGuiNET.ImGui.GetContentRegionAvail().X; + int cols = Math.Max(1, (int)(avail / Cell)); + int rows = (_shown.Count + cols - 1) / cols; + Vector2 o = ImGuiNET.ImGui.GetCursorScreenPos(); + var content = new Vector2(cols * Cell, Math.Max(rows * Cell, 1)); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + + if (_shown.Count == 0) + { + dl.AddText(o + new Vector2(4, 4), Mute, _searchText.Length > 0 || _category != 0 ? "Nothing matches." : "Empty."); + ImGuiNET.ImGui.Dummy(new Vector2(avail, 20)); + } + else + { + // One button over the whole grid: hover, click, double-click, right-click and + // drag are worked out from the mouse position (no item per cell). + ImGuiNET.ImGui.InvisibleButton("##cells", content, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight); + bool hovered = ImGuiNET.ImGui.IsItemHovered(); + Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); + int hoverIdx = -1; + if (hovered) + { + int c = (int)((mouse.X - o.X) / Cell), r = (int)((mouse.Y - o.Y) / Cell); + if (c >= 0 && c < cols && r >= 0 && r < rows) + { + int i = r * cols + c; + if (i < _shown.Count) hoverIdx = i; + } + } + InventoryItem? hot = hoverIdx >= 0 ? _shown[hoverIdx] : null; + _hover = hot; + + if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) + { + SelectItem(hot); + _pressItem = hot; + _pressAt = mouse; + } + if (hot != null && ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left)) + { + _pressItem = null; + Act(InventoryActionKind.Use, hot, 0, "", 0); + } + if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) + { + _selected = hot.Id; + _ctxItem = hot; + _openCtx = true; + } + if (_pressItem != null && _dragItem == null && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) + && Vector2.DistanceSquared(mouse, _pressAt) > 25) + _dragItem = _pressItem; + + // Visible rows only. + Vector2 clipMin = ImGuiNET.ImGui.GetWindowPos(), clipMax = clipMin + ImGuiNET.ImGui.GetWindowSize(); + int firstRow = Math.Max(0, (int)((clipMin.Y - o.Y) / Cell)); + int lastRow = Math.Min(rows - 1, (int)((clipMax.Y - o.Y) / Cell)); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts + for (int r = firstRow; r <= lastRow; r++) + { + for (int c = 0; c < cols; c++) + { + int i = r * cols + c; + if (i >= _shown.Count) break; + InventoryItem it = _shown[i]; + var cmin = new Vector2(o.X + c * Cell, o.Y + r * Cell); + var cmax = cmin + new Vector2(Cell - 2, Cell - 2); + bool sel = it.Id == _selected; + dl.AddRectFilled(cmin, cmax, i == hoverIdx ? CellHot : CellBg, 3); + DrawItemIcon(dl, it.Id, cmin + new Vector2(2, 2), Icon, ReferenceEquals(it, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu); + if (it.StackText.Length > 0) + { + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(it.StackText); + var tp = new Vector2(cmax.X - ts.X - 2, cmax.Y - ts.Y - 1); + dl.AddText(tp + Vector2.One, StackShadow, it.StackText); + dl.AddText(tp, StackCol, it.StackText); + } + if (sel) dl.AddRect(cmin, cmax, CellSel, 3, ImDrawFlags.None, 1.5f); + else if (it.Wielder != 0) dl.AddRect(cmin, cmax, Amber, 3); + } + } + ImGuiNET.ImGui.PopFont(); + } + + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleColor(); + } + + /// <summary>An item's icon (with underlay and overlay) from the shared icon cache, or a placeholder.</summary> + private static void DrawItemIcon(ImDrawListPtr dl, uint objectId, Vector2 min, float size, uint tint = 0xFFFFFFFF) + { + if (ScriptIcons.TryGet(ScriptIconKind.Object, objectId, out IntPtr tex)) + dl.AddImage(tex, min, min + new Vector2(size, size), Vector2.Zero, Vector2.One, tint); + else + dl.AddRectFilled(min, min + new Vector2(size, size), Placeholder, 2); + } + + // ── Zones: equip, drop, give ──────────────────────────────────────── + + private void Zones(InventoryView view, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + InventoryTarget? target = InventoryModel.Target; + InventoryItem? sel = SelectedItem(view); + float zw = (w - 8) / 3f; + var sz = new Vector2(zw, ZoneH); + + Zone("##z_equip", DropKind.Equip, PhosphorIcons.Shield, "Equip", new Vector2(p.X, p.Y), sz, 0, "", + InventoryModel.WieldAvailable, sel, + "Equip: drag an item here, or click to equip the selected item."); + Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, "Drop", new Vector2(p.X + zw + 4, p.Y), sz, 0, "", + InventoryModel.DropAvailable, sel, + "Drop on the ground: drag an item here, or click to drop the selected item."); + Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, target?.ZoneLabel ?? "Give", new Vector2(p.X + 2 * (zw + 4), p.Y), sz, + target?.Id ?? 0, target?.Name ?? "", InventoryModel.GiveAvailable && target != null, sel, + target?.ZoneTip ?? "Select a creature, NPC or player in the game to give to."); + NextLine(p, ZoneH + 4); + } + + private void Zone(string id, DropKind kind, string glyph, string label, Vector2 pos, Vector2 size, uint targetId, + string targetName, bool enabled, InventoryItem? selected, string tip) + { + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); + bool hot = ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem); + ImGuiNET.ImGui.SetItemTooltip(tip); + bool dropHot = enabled && _dragItem != null && hot; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + uint fill = dropHot ? DropHot : _dragItem != null && enabled ? Selected : hot && enabled ? Lighten(BtnFill) : BtnFill; + dl.AddRectFilled(pos, pos + size, fill, 3); + dl.AddRect(pos, pos + size, dropHot || (_dragItem != null && enabled) ? Teal : BtnBord, 3); + uint fg = enabled ? Text : Faded(Mute); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), glyph, pos + new Vector2(4, 0), new Vector2(18, size.Y), fg); + dl.PushClipRect(pos, pos + size, true); + dl.AddText(new Vector2(pos.X + 26, pos.Y + (size.Y - ImGuiNET.ImGui.GetFontSize()) * 0.5f), fg, label); + dl.PopClipRect(); + if (enabled) + _targets.Add(new Target { Min = pos, Max = pos + size, Kind = kind, Id = targetId, Name = targetName }); + if (clicked && enabled && selected != null) + DropOn(kind, targetId, targetName, selected); // refused with a message while one waits + } + + private InventoryItem? SelectedItem(InventoryView view) + { + if (_selected == 0) return null; + foreach (InventoryPack p in view.Packs) + foreach (InventoryItem it in p.Items) + if (it.Id == _selected) return it; + foreach (InventoryItem it in view.Worn) + if (it.Id == _selected) return it; + return null; + } + + // ── Status row ────────────────────────────────────────────────────── + + private void StatusRow(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + StatusLine(p, w, StatusH, null); + NextLine(p, StatusH); + } + + /// <summary> + /// The one action waiting for the server, a refusal, or how the last action ended; when + /// there is nothing to say, the pyreals (<paramref name="idleView"/>, Classic) or a hint. + /// </summary> + private void StatusLine(Vector2 p, float w, float statusH, InventoryView? idleView) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + long now = Stopwatch.GetTimestamp(); + InventoryPending? pending = InventoryModel.Pending; + InventoryResult? result = InventoryModel.LastResult; + float ty = p.Y + (statusH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.PushClipRect(p, p + new Vector2(w, statusH), true); + if (pending != null) + { + int tenths = (int)((now - pending.StartedTicks) * 10 / Stopwatch.Frequency); + int key = (int)(pending.ItemId * 31) ^ tenths ^ ((int)pending.Kind << 24) + ^ (pending.WaitingForGame ? (0x40000000 ^ pending.BusyWith.GetHashCode()) : 0); + if (key != _statusKey) + { + _statusKey = key; + string secs = " " + (tenths / 10.0).ToString("0.0", CultureInfo.InvariantCulture) + "s"; + // Held until the client's own item gate opens (the bot or another action has it). + _statusText = pending.WaitingForGame + ? "Waiting for the game: " + pending.Label + " (busy with " + pending.BusyWith + ")" + secs + : "Waiting for the server: " + pending.Label + secs; + } + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.HourglassMedium, p, new Vector2(16, statusH), Amber); + dl.AddText(new Vector2(p.X + 18, ty), Amber, _statusText); + } + else if (_refusal.Length > 0 && (now - _refusalAt) < Stopwatch.Frequency * 4) + { + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Warning, p, new Vector2(16, statusH), Amber); + dl.AddText(new Vector2(p.X + 18, ty), Amber, _refusal); + } + else if (result != null && (now - result.AtTicks) < Stopwatch.Frequency * 8) + { + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), result.Ok ? PhosphorIcons.Check : PhosphorIcons.Warning, + p, new Vector2(16, statusH), result.Ok ? Green : Red); + dl.AddText(new Vector2(p.X + 18, ty), result.Ok ? Green : Red, result.Text); + } + else if (idleView != null) + { + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Coins, p, new Vector2(16, statusH), Amber); + dl.AddText(new Vector2(p.X + 18, ty), Text, idleView.PyrealText); + float pw = ImGuiNET.ImGui.CalcTextSize(idleView.PyrealText).X; + dl.AddText(new Vector2(p.X + 22 + pw, ty), Mute, "pyreals"); + } + else + { + dl.AddText(new Vector2(p.X + 2, ty), Faded(Mute), "Double-click to use. Drag to a pack, Equip, Drop or Give. Right-click for more."); + } + dl.PopClipRect(); + } + + // ── Actions ───────────────────────────────────────────────────────── + + private void Act(InventoryActionKind kind, InventoryItem item, uint target, string targetName, int amount) + { + var req = new InventoryRequest + { + Kind = kind, ItemId = item.Id, TargetId = target, TargetName = targetName, Amount = amount, ItemName = item.Name, + }; + if (!InventoryModel.Request(req, out string why)) + { + _refusal = why; + _refusalAt = Stopwatch.GetTimestamp(); + } + else + { + _refusal = string.Empty; + } + } + + private void DropOn(DropKind kind, uint targetId, string targetName, InventoryItem item) + { + switch (kind) + { + case DropKind.Pack: + if (item.Container == targetId && item.Wielder == 0) return; // same pack: nothing to do + if (item.RequiresPackSlot && targetId != InventoryModel.Current.PlayerId) + { + // A side pack has no pack slots (ACE: ContainerCapacity 0); the server would refuse. + Refuse(item.Name + " uses a pack slot: it can only go in the main pack."); + return; + } + Act(InventoryActionKind.Move, item, targetId, targetName, 0); + break; + case DropKind.PackSlots: + if (!item.RequiresPackSlot) + { + Refuse("Only items that use a pack slot (foci) go there. Drop it on a pack to move it."); + return; + } + if (item.Container == targetId && item.Wielder == 0) return; // already in the main pack + Act(InventoryActionKind.Move, item, targetId, targetName, 0); + break; + case DropKind.Equip: + if (item.Wielder != 0) return; + Act(InventoryActionKind.Wield, item, 0, "", 0); + break; + case DropKind.Slot: + if (item.Wielder != 0) return; // already worn (moving between slots isn't supported) + if ((item.ValidLocations & targetId) == 0) + { + Refuse(item.Name + " doesn't go in the " + targetName + " slot."); + return; + } + Act(InventoryActionKind.Wield, item, targetId, targetName, 0); + break; + case DropKind.Drop: + Act(InventoryActionKind.Drop, item, 0, "", 0); + break; + case DropKind.Give: + if (targetId != 0) Act(InventoryActionKind.Give, item, targetId, targetName, 0); + break; + } + } + + private void Refuse(string why) + { + _refusal = why; + _refusalAt = Stopwatch.GetTimestamp(); + } + + /// <summary> + /// Would <paramref name="pack"/> refuse <paramref name="item"/> (full, or no place for it)? + /// ACE's rules (Container.TryAddToInventory): a pack-slot item takes one of the main pack's + /// pack slots (a side pack has none); anything else takes an item slot. + /// </summary> + private static bool PackRefuses(InventoryView view, InventoryPack pack, InventoryItem item) + { + if (item.Container == pack.Id && item.Wielder == 0) return false; // already there + if (item.RequiresPackSlot) + return !pack.IsMain || Math.Max(0, view.Packs.Length - 1) + view.SlotItems.Length >= view.ContainerSlots; + return pack.Used >= pack.Capacity; + } + + /// <summary>Mouse released during a drag: act on the target under it (collected this frame).</summary> + private void FinishDrag() + { + if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) + { + InventoryItem? item = _dragItem; + _dragItem = null; + _pressItem = null; + if (item == null) return; + ItemDragBridge.EndPopOutDrag(); + Vector2 m = ImGuiNET.ImGui.GetMousePos(); + foreach (Target t in _targets) + { + if (m.X < t.Min.X || m.Y < t.Min.Y || m.X >= t.Max.X || m.Y >= t.Max.Y) continue; + DropOn(t.Kind, t.Id, t.Name, item); + return; + } + } + } + + /// <summary> + /// ImGui drag-and-drop payload type for one item (uint object id), published while an item is + /// dragged so other ImGui windows (RynthAi's Mini Remote slots) can accept the drop. Must + /// match MiniRemoteHud.ItemPayloadType in RynthAi. + /// </summary> + public const string ItemPayloadType = "RYNTH_INV_ITEM"; + + /// <summary> + /// Selects <paramref name="it"/> here and in the game, like a click in the retail inventory, so + /// "selected item" features (Mini Remote slots, item info, loot rules) see it too. + /// </summary> + private void SelectItem(InventoryItem it) + { + _selected = it.Id; + // Queued, not called inline: Draw runs inside EndScene, and AC's SetSelectedObject rebuilds + // UI elements, so it runs at the main-thread queue's drain point instead. + if (ClientHelperHooks.GetSelectedItemId() != it.Id) + AcMainThreadQueue.EnqueueSetSelectedObject(it.Id); + } + + private unsafe void DrawDragGhost() + { + if (_dragItem == null) return; + var fg = ImGuiNET.ImGui.GetForegroundDrawList(); + Vector2 m = ImGuiNET.ImGui.GetMousePos() - new Vector2(Icon * 0.5f, Icon * 0.5f); + DrawItemIcon(fg, _dragItem.Id, m, Icon, 0xD0FFFFFF); + ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + + // A popped-out Inventory draws in its own ImGui context: the client's drop targets + // only see the drag through the bridge, which republishes it in the main context. + if (ImGuiPopOuts.InPopOutFrame) + { + ItemDragBridge.NotePopOutDrag(_dragItem.Id); + return; + } + + // Re-submitted every frame of the drag (an extern source expires when it isn't); the + // ghost above is the preview, so no ImGui tooltip. + if (ImGuiNET.ImGui.BeginDragDropSource(ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip)) + { + uint id = _dragItem.Id; + ImGuiNET.ImGui.SetDragDropPayload(ItemPayloadType, (IntPtr)(&id), sizeof(uint)); + ImGuiNET.ImGui.EndDragDropSource(); + } + } + + // ── Tooltip ───────────────────────────────────────────────────────── + + private void Tooltip() + { + InventoryItem? it = _hover; + if (_dragItem != null || ImGuiNET.ImGui.IsPopupOpen("", ImGuiPopupFlags.AnyPopupId)) return; + if (it == null) + { + // A pack cell, an empty paperdoll slot, the burden meter (Classic view). + if (_hoverLabel == null) return; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + if (ImGuiNET.ImGui.BeginTooltip()) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.TextUnformatted(_hoverLabel); + ImGuiNET.ImGui.PopStyleColor(); + if (_hoverLabel2 != null) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.TextUnformatted(_hoverLabel2); + ImGuiNET.ImGui.PopStyleColor(); + } + ImGuiNET.ImGui.EndTooltip(); + } + ImGuiNET.ImGui.PopStyleColor(2); + return; + } + if (!ReferenceEquals(it, _tipItem)) + { + _tipItem = it; + _tipBase = BaseLines(it); + } + InventoryTooltip? extra = InventoryModel.Tooltip; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + if (ImGuiNET.ImGui.BeginTooltip()) + { + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetFontSize() * 24); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.TextUnformatted(it.Name); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + foreach (string line in _tipBase) ImGuiNET.ImGui.TextUnformatted(line); + ImGuiNET.ImGui.PopStyleColor(); + if (extra != null && extra.Id == it.Id) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + foreach (string line in extra.Lines) ImGuiNET.ImGui.TextUnformatted(line); + ImGuiNET.ImGui.PopStyleColor(); + } + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.EndTooltip(); + } + ImGuiNET.ImGui.PopStyleColor(2); + } + + private static string[] BaseLines(InventoryItem it) + { + var lines = new List<string>(6); + if (it.Stack > 1) + lines.Add(it.MaxStack > 1 ? $"Stack {it.Stack:N0} of {it.MaxStack:N0}" : $"Stack {it.Stack:N0}"); + lines.Add($"Value {it.Value:N0} Burden {it.Burden:N0}"); + if (it.Workmanship > 0) + lines.Add("Workmanship " + it.Workmanship.ToString("0.##", CultureInfo.InvariantCulture)); + if (it.Wielder != 0) lines.Add("Equipped"); + if (it.IsPack) lines.Add($"Pack: {it.ItemsCapacity} slots"); + if (it.RequiresPackSlot) lines.Add("Uses a pack slot (main pack only)"); + return lines.ToArray(); + } + + // ── Context menu ──────────────────────────────────────────────────── + + private void ContextMenu(InventoryView view) + { + if (_openCtx) + { + _openCtx = false; + ImGuiNET.ImGui.OpenPopup("##inv_ctx"); + } + PushMenuStyle(); + bool open = ImGuiNET.ImGui.BeginPopup("##inv_ctx"); + if (!open) { PopMenuStyle(); return; } + try + { + InventoryItem? it = _ctxItem; + if (it == null) { ImGuiNET.ImGui.CloseCurrentPopup(); return; } + bool idle = InventoryModel.Pending == null; + ImGuiNET.ImGui.TextDisabled(it.Name); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Use", "double-click", false, idle)) + Act(InventoryActionKind.Use, it, 0, "", 0); + if (it.Wielder == 0 && it.ValidLocations != 0 + && ImGuiNET.ImGui.MenuItem("Equip", "", false, idle && InventoryModel.WieldAvailable)) + Act(InventoryActionKind.Wield, it, 0, "", 0); + if (it.Stack > 1 && it.Wielder == 0 && ImGuiNET.ImGui.MenuItem("Split...", "", false, idle)) + { + _splitItem = it; + _splitAmount = Math.Max(1, it.Stack / 2); + _splitTarget = it.Container; + _openSplit = true; + } + if (ImGuiNET.ImGui.BeginMenu("Move to", idle)) + { + foreach (InventoryPack p in view.Packs) + { + bool here = p.Id == it.Container && it.Wielder == 0; + bool fits = !it.RequiresPackSlot || p.IsMain; // a focus goes in the main pack only + if (ImGuiNET.ImGui.MenuItem(p.Name, p.FillText, here, !here && fits)) + Act(InventoryActionKind.Move, it, p.Id, p.Name, 0); + } + ImGuiNET.ImGui.EndMenu(); + } + if (it.Wielder == 0 && ImGuiNET.ImGui.MenuItem("Drop", "", false, idle && InventoryModel.DropAvailable)) + Act(InventoryActionKind.Drop, it, 0, "", 0); + InventoryTarget? target = InventoryModel.Target; + if (target != null && it.Wielder == 0 + && ImGuiNET.ImGui.MenuItem(target.MenuLabel, "", false, idle && InventoryModel.GiveAvailable)) + Act(InventoryActionKind.Give, it, target.Id, target.Name, 0); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Add to loot profile...")) + _lootAdd.Open(it.Id, it.Name, toOpenProfile: false); + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("Make a RynthAi loot rule for this item (preview first)"); + if (!it.IsPack && ImGuiNET.ImGui.MenuItem("Add to item count HUD")) + UI.Data.RynthAiCommands.ApplyRemoteCommand("itemhudadd", it.Name); + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("Track how many of these you carry on RynthAi's floating item count HUD (/ra itemhud add)"); + if (!it.IsPack) MiniRemoteMenu(it); + if (!idle) + ImGuiNET.ImGui.TextDisabled("(an item action is waiting)"); + } + finally + { + ImGuiNET.ImGui.EndPopup(); + PopMenuStyle(); + } + } + + /// <summary>RynthAi Mini Remote quick-use grid size (HudState.MiniRemoteSlotCount, 6 rows of 5).</summary> + private const int MiniRemoteSlots = 30, MiniRemoteColumns = 5; + + /// <summary> + /// "Add to Mini Remote" submenu: first empty slot, or a numbered grid laid out like the + /// remote's own slots. RynthAi validates the item and reports the result in chat. + /// </summary> + private static void MiniRemoteMenu(InventoryItem it) + { + if (!ImGuiNET.ImGui.BeginMenu("Add to Mini Remote")) return; + if (ImGuiNET.ImGui.MenuItem("First empty slot")) + UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot", "first " + it.Id.ToString(CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.Separator(); + ImGuiNET.ImGui.TextDisabled("Or pick a slot (replaces what's there):"); + for (int i = 0; i < MiniRemoteSlots; i++) + { + if (i % MiniRemoteColumns != 0) ImGuiNET.ImGui.SameLine(); + string label = (i + 1).ToString("00", CultureInfo.InvariantCulture); + if (ImGuiNET.ImGui.Button(label, new Vector2(28, 0))) + { + UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot", + (i + 1).ToString(CultureInfo.InvariantCulture) + " " + it.Id.ToString(CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + } + ImGuiNET.ImGui.Separator(); + ImGuiNET.ImGui.TextDisabled("Tip: you can also drag the item onto a slot."); + ImGuiNET.ImGui.EndMenu(); + } + + // ── Split dialog ──────────────────────────────────────────────────── + + private void SplitDialog(InventoryView view) + { + if (_openSplit) + { + _openSplit = false; + ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos(), ImGuiCond.Always); + ImGuiNET.ImGui.OpenPopup("##inv_split"); + } + PushMenuStyle(); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8)); + bool open = ImGuiNET.ImGui.BeginPopup("##inv_split"); + ImGuiNET.ImGui.PopStyleVar(); + if (!open) { PopMenuStyle(); return; } + try + { + InventoryItem? it = _splitItem; + // The stack may have changed or gone since the dialog opened: use the live copy. + InventoryItem? live = it == null ? null : FindById(view, it.Id); + if (live == null || live.Stack < 2) + { + ImGuiNET.ImGui.TextUnformatted("That stack is gone."); + if (Button("##sp_close", "Close", ImGuiNET.ImGui.GetCursorScreenPos(), new Vector2(80, 22), Text, BtnFill)) + ImGuiNET.ImGui.CloseCurrentPopup(); + ImGuiNET.ImGui.Dummy(new Vector2(80, 24)); + return; + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.TextUnformatted(live.Name); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.TextUnformatted("Stack of " + live.StackText + ". Split off:"); + int max = live.Stack - 1; + _splitAmount = Math.Clamp(_splitAmount, 1, max); + ImGuiNET.ImGui.SetNextItemWidth(200); + ImGuiNET.ImGui.SliderInt("##sp_slider", ref _splitAmount, 1, max); + ImGuiNET.ImGui.SetNextItemWidth(200); + ImGuiNET.ImGui.InputInt("##sp_input", ref _splitAmount, 1, 10); + _splitAmount = Math.Clamp(_splitAmount, 1, max); + + ImGuiNET.ImGui.TextUnformatted("Into:"); + InventoryPack? into = view.PackOf(_splitTarget); + if (into == null) { _splitTarget = live.Container; into = view.PackOf(_splitTarget); } + foreach (InventoryPack p in view.Packs) + { + if (ImGuiNET.ImGui.Selectable(p.Name + " (" + p.FillText + ")##sp" + p.Id.ToString(CultureInfo.InvariantCulture), + p.Id == _splitTarget)) + _splitTarget = p.Id; + } + + bool idle = InventoryModel.Pending == null; + Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + if (Button("##sp_ok", PhosphorIcons.Scissors + " Split", bp, new Vector2(96, 24), Teal, BtnFill, enabled: idle && into != null)) + { + Act(InventoryActionKind.Split, live, _splitTarget, into?.Name ?? "", _splitAmount); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + if (Button("##sp_cancel", "Cancel", bp + new Vector2(102, 0), new Vector2(80, 24), Text, BtnFill)) + ImGuiNET.ImGui.CloseCurrentPopup(); + ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28)); + ImGuiNET.ImGui.Dummy(new Vector2(200, 0)); + } + finally + { + ImGuiNET.ImGui.EndPopup(); + PopMenuStyle(); + } + } + + private static InventoryItem? FindById(InventoryView view, uint id) + { + foreach (InventoryPack p in view.Packs) + foreach (InventoryItem it in p.Items) + if (it.Id == id) return it; + return null; + } + + private static void PushMenuStyle() + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Header, Selected); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, Lighten(BtnFill)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + } + + private static void PopMenuStyle() + { + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(7); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs new file mode 100644 index 0000000..cfa8195 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs @@ -0,0 +1,250 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ItemsFace.cs +// ImGui face of the Items panel (UI/Panels/ItemsPanel.cs): weapons (name, +// element, Del), consumables (name, type, Del), each with "Add Selected", +// and mana stone tapping (on/off, keep count, min max-mana to tap). +// +// Edits change a private copy and save the whole payload (ItemsCommands, +// pump thread). A newer snapshot replaces the copy; snapshots from before +// the last save are ignored so an edit never flickers back. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using RynthCore.Engine.UI.Panels; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class ItemsFace : IImGuiPanel +{ + public const string Title = "Items"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(420, 520), new Vector2(340, 260), EdgeToEdge: true), + () => new ItemsFace()); + + private static readonly uint OnBg = RynthTheme.Argb(0xFF104010), OnText = RynthTheme.Argb(0xFF33FF33); + + private ItemsPanel.Payload _data = new(); + private long _seenVersion = -1, _savedAtVersion = -1; + private readonly Picker _picker = new("##items_pick"); + + public void OnShown() + { + UiSources.Items.Subscribe(); + UiSources.Items.RequestRefresh(); + } + + public void OnHidden() => UiSources.Items.Unsubscribe(); + + public void Draw() + { + TakeSnapshot(); + float w = Begin(out Vector2 origin, out Vector2 size); + + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0)); + ImGuiNET.ImGui.BeginChild("##items_body", new Vector2(w, Math.Max(60, Remaining(origin, size)))); + float bw = ImGuiNET.ImGui.GetContentRegionAvail().X; + + // Weapons + Section("Weapons", bw); + if (_data.Weapons.Count == 0) Empty("No weapons configured", bw); + else + { + TableHeader("Element", bw); + for (int i = 0; i < _data.Weapons.Count; i++) + { + ItemsPanel.WeaponEntry wpn = _data.Weapons[i]; + ImGuiNET.ImGui.PushID("w" + i); + int r = Row(wpn.Name, wpn.Element, i, bw); + ImGuiNET.ImGui.PopID(); + if (r == 1) + { + Vector2 at = ImGuiNET.ImGui.GetIO().MousePos; + _picker.Open(at, ItemsCommands.Elements, Array.IndexOf(ItemsCommands.Elements, wpn.Element), e => + { + wpn.Element = ItemsCommands.Elements[e]; + Save(); + }, 160); + } + else if (r == 2) + { + _data.Weapons.RemoveAt(i); + Save(); + break; + } + } + } + AddSelected("##add_weapon", PhosphorIcons.Plus + " Add Selected Weapon", "(select a weapon in inventory first)", ItemsCommands.AddSelectedWeapon); + Divider(bw); + + // Consumables + Section("Consumable Items", bw); + if (_data.Consumables.Count == 0) Empty("No consumables configured", bw); + else + { + TableHeader("Type", bw); + for (int i = 0; i < _data.Consumables.Count; i++) + { + ItemsPanel.ConsumableEntry c = _data.Consumables[i]; + ImGuiNET.ImGui.PushID("c" + i); + int r = Row(c.Name, c.Type, i, bw); + ImGuiNET.ImGui.PopID(); + if (r == 1) + { + Vector2 at = ImGuiNET.ImGui.GetIO().MousePos; + _picker.Open(at, ItemsCommands.ConsumableTypes, Array.IndexOf(ItemsCommands.ConsumableTypes, c.Type), t => + { + c.Type = ItemsCommands.ConsumableTypes[t]; + Save(); + }, 160); + } + else if (r == 2) + { + _data.Consumables.RemoveAt(i); + Save(); + break; + } + } + } + AddSelected("##add_consumable", PhosphorIcons.Plus + " Add Selected Consumable", "(select an item in inventory first)", ItemsCommands.AddSelectedConsumable); + Divider(bw); + + // Mana stone tapping + Section("Mana Stone Tapping", bw); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 4); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float ty = p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.AddText(new Vector2(p.X, ty), Text, "Enable Tapping"); + float x = p.X + ImGuiNET.ImGui.CalcTextSize("Enable Tapping").X + 6; + bool on = _data.EnableManaTapping; + if (Button("##tap", on ? "ON" : "OFF", new Vector2(x, p.Y), new Vector2(50, 22), on ? OnText : Mute, on ? OnBg : BtnFill)) + { + _data.EnableManaTapping = !on; + Save(); + } + x += 66; + dl.AddText(new Vector2(x, ty), Text, "Keep count:"); + x += ImGuiNET.ImGui.CalcTextSize("Keep count:").X + 6; + int keep = Spinner("##keep", _data.ManaStoneKeepCount, 1, 999, new Vector2(x, p.Y)); + if (keep != _data.ManaStoneKeepCount) { _data.ManaStoneKeepCount = keep; Save(); } + NextLine(new Vector2(p.X - 4, p.Y - 4), 30); + if (_data.EnableManaTapping) + { + p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 0); + dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, "Min MaxMana to tap:"); + float sx = p.X + ImGuiNET.ImGui.CalcTextSize("Min MaxMana to tap:").X + 6; + int min = Spinner("##minmana", _data.ManaTapMinMana, 100, 99999, new Vector2(sx, p.Y)); + if (min != _data.ManaTapMinMana) { _data.ManaTapMinMana = min; Save(); } + NextLine(new Vector2(p.X - 4, p.Y), 28); + } + + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + End(origin, size); + _picker.Draw(); + } + + private void TakeSnapshot() + { + var snap = UiSources.Items.Current; + if (snap == null || snap.Version == _seenVersion || snap.Version <= _savedAtVersion) return; + _seenVersion = snap.Version; + _data = snap.Value.ParseCopy(); + } + + private void Save() + { + _savedAtVersion = UiSources.Items.Current?.Version ?? _savedAtVersion; + ItemsCommands.SetJson(ItemsCommands.Serialize(_data)); + } + + // ── Pieces ─────────────────────────────────────────────────────────── + + private static void Section(string title, float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + float h = bold.FontSize + 8; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(p, p + new Vector2(w, h), Selected); + dl.AddText(bold, bold.FontSize, p + new Vector2(8, 4), Amber, title); + ImGuiNET.ImGui.Dummy(new Vector2(w, h)); + } + + private static void TableHeader(string column, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(p, p + new Vector2(w, 22), Selected); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + float ty = p.Y + (22 - bold.FontSize) * 0.5f; + dl.AddText(bold, bold.FontSize, new Vector2(p.X + 6, ty), Text, "Item Name"); + dl.AddText(bold, bold.FontSize, new Vector2(p.X + w - 146 + 6, ty), Text, column); + ImGuiNET.ImGui.Dummy(new Vector2(w, 22)); + } + + private static void Empty(string message, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(p, p + new Vector2(w, 22), RowAlt); + ImGuiNET.ImGui.GetWindowDrawList().AddText(p + new Vector2(8, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, message); + ImGuiNET.ImGui.Dummy(new Vector2(w, 22)); + } + + /// <summary>Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0.</summary> + private static int Row(string name, string value, int index, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(p, p + new Vector2(w, 24), index % 2 == 0 ? RowAlt : PanelBg); + float nameW = w - 146; + dl.PushClipRect(p, p + new Vector2(nameW, 24), true); + dl.AddText(new Vector2(p.X + 6, p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, name); + dl.PopClipRect(); + int result = 0; + if (Button("##pick", value, new Vector2(p.X + nameW + 2, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1; + if (IconButton("##del", PhosphorIcons.Trash, new Vector2(p.X + nameW + 102, p.Y + 2), new Vector2(42, 20), Red, BtnFill)) result = 2; + ImGuiNET.ImGui.SetItemTooltip("Remove"); + NextLine(p, 24); + return result; + } + + private static void AddSelected(string id, string label, string hint, Action onClick) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 4); + float bw = ButtonWidth(label) + 4; + if (Button(id, label, p, new Vector2(bw, 24), Teal, BtnFill)) onClick(); + ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9); + ImGuiNET.ImGui.GetWindowDrawList().AddText(f9, f9.FontSize, new Vector2(p.X + bw + 8, p.Y + (24 - f9.FontSize) * 0.5f), Mute, hint); + NextLine(new Vector2(p.X - 4, p.Y - 4), 32); + } + + private static void Divider(float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + Separator(w); + } + + /// <summary>[-] value [+]; returns the new value (same when nothing was clicked).</summary> + private static int Spinner(string id, int value, int min, int max, Vector2 pos) + { + int v = value; + ImGuiNET.ImGui.PushID(id); + if (IconButton("##dec", PhosphorIcons.Minus, pos, new Vector2(22, 22), Teal, BtnFill)) v = Math.Max(min, v - 1); + string text = v.ToString(CultureInfo.InvariantCulture); + float tw = ImGuiNET.ImGui.CalcTextSize(text).X; + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(pos.X + 24 + (60 - tw) * 0.5f, pos.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, text); + if (IconButton("##inc", PhosphorIcons.Plus, new Vector2(pos.X + 86, pos.Y), new Vector2(22, 22), Teal, BtnFill)) v = Math.Min(max, v + 1); + ImGuiNET.ImGui.PopID(); + return v; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs new file mode 100644 index 0000000..34b14fc --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs @@ -0,0 +1,380 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/LootAddDialog.cs +// "Add to loot profile": the small popup that turns a clicked item into a +// loot rule (2026-10-04). Opened from the Inventory panel's right-click menu +// and from the Loot Editor's "Add selected item"; /ra loot add is the chat +// twin (no popup, defaults straight in). +// +// item its name and the profile the rule goes to +// match name + class (default), name only, items like this +// action Keep, Keep # (with the count), Salvage, Sell, Read +// name the rule's name (empty: RynthAi's default, "Keep Copper Pea") +// preview the rule in words, where it goes in the list and why, notes +// Add RynthAi inserts it, saves (old file kept as .bak) and reloads +// +// RynthAi builds the rule (LootSdk LootItemRules) and does the insert and the +// save; this face only posts item_preview / item_add / item_close through +// LootEditCommands and shows LootEditStateDto.ItemDraft. A face owns one of +// these and calls Draw once per frame outside any child window. +// ============================================================================ + +using System; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class LootAddDialog +{ + private static readonly string[] MatchLabels = { "Name + class", "Name only", "Items like this" }; + private static readonly string[] MatchTips = + { + "This exact item: its name and its kind (object class).", + "Anything with this exact name.", + "Its kind plus key properties: material, workmanship, slot, armor / damage, ratings and spells, at least as good as this one. No name.", + }; + private static readonly int[] ActionIds = + { LootEditVocabulary.Keep, LootEditVocabulary.KeepUpTo, LootEditVocabulary.Salvage, LootEditVocabulary.Sell, LootEditVocabulary.Read }; + private static readonly string[] ActionLabels = { "Keep", "Keep #", "Salvage", "Sell", "Read" }; + + private readonly string _id; + private bool _open, _openRequested, _subscribed; + private uint _itemId; + private string _itemName = string.Empty; + private bool _toOpenProfile; + + // What the popup asks for (0 / -1 = RynthAi's default). + private int _match, _action, _keep = -1; + private readonly byte[] _name = new byte[128]; + private int _keepEdit = 1; + + // Seqs are unique across popups (the inventory's and the editor's share RynthAi's one draft): + // a popup only takes an answer to something it asked. + private static int s_seq; + private readonly System.Collections.Generic.HashSet<int> _mine = new(); + private int _seq; + private DateTime _sentAt; + private long _seenVersion = -1; + private LootEditItemDraftDto? _draft; + private bool _adding; + private DateTime _addedAt; + private bool _justAdded; + + /// <summary>True once after an add went through (the Loot Editor scrolls to the new rule).</summary> + public bool TakeAdded() + { + bool v = _justAdded; + _justAdded = false; + return v; + } + + public LootAddDialog(string id) => _id = id; + + public bool IsOpen => _open; + + /// <summary> + /// Opens the popup for <paramref name="itemId"/> (0: the item selected in the + /// game, resolved once). <paramref name="toOpenProfile"/>: the rule goes to the + /// profile open in the Loot Editor, else to the one RynthAi loots with. + /// </summary> + public void Open(uint itemId, string itemName, bool toOpenProfile) + { + _itemId = itemId; + _itemName = itemName ?? string.Empty; + _toOpenProfile = toOpenProfile; + _match = 0; + _action = 0; + _keep = -1; + Array.Clear(_name); + _draft = null; + _adding = false; + _addedAt = default; + _mine.Clear(); + if (!_subscribed) + { + UiSources.LootEdit.Subscribe(); + _subscribed = true; + } + _openRequested = true; + Send("item_preview"); + } + + private void Send(string op) + { + _seq = System.Threading.Interlocked.Increment(ref s_seq); + _mine.Add(_seq); + _sentAt = DateTime.UtcNow; + LootEditCommands.Send(new LootEditCmd + { + Op = op, + Item = new LootEditItemRequestDto + { + ItemId = _itemId, Match = _match, Action = _action, KeepCount = _keep, + RuleName = Utf8(_name).Trim(), ToOpenProfile = _toOpenProfile, Seq = _seq, + }, + }); + } + + /// <summary>The owning face was hidden: drop the popup (and its subscription and draft).</summary> + public void Cancel() + { + if (_open || _subscribed) Close(); + _openRequested = false; + } + + private void Close() + { + if (_open || _subscribed) LootEditCommands.Simple("item_close"); + _open = false; + if (_subscribed) + { + UiSources.LootEdit.Unsubscribe(); + _subscribed = false; + } + } + + /// <summary>Once per frame, outside any child window.</summary> + public void Draw() + { + if (_openRequested) + { + _openRequested = false; + _open = true; + ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos(), ImGuiCond.Always); + ImGuiNET.ImGui.OpenPopup(_id); + } + if (!_open) return; + TakeDraft(); + + PushStyle(); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8)); + bool visible = ImGuiNET.ImGui.BeginPopup(_id, ImGuiWindowFlags.AlwaysAutoResize); + ImGuiNET.ImGui.PopStyleVar(); + if (!visible) + { + PopStyle(); + Close(); // clicked outside, or Esc + return; + } + try + { + if (Body()) ImGuiNET.ImGui.CloseCurrentPopup(); + } + finally + { + ImGuiNET.ImGui.EndPopup(); + PopStyle(); + } + } + + private void TakeDraft() + { + var snap = UiSources.LootEdit.Current; + if (snap == null || snap.Version == _seenVersion) return; + _seenVersion = snap.Version; + LootEditItemDraftDto? d = snap.Value.State?.ItemDraft; + if (d == null || !_mine.Contains(d.Seq) || (_draft != null && d.Seq < _draft.Seq)) return; + bool first = _draft == null; + _draft = d; + if (d.ItemId != 0) _itemId = d.ItemId; // the selected item, from now on by id + if (d.ItemName.Length > 0) _itemName = d.ItemName; + if (d.Seq == _seq) + { + if (_adding) + { + _adding = false; + if (d.Added) + { + _addedAt = DateTime.UtcNow; + _justAdded = true; + } + } + if (!ImGuiNET.ImGui.IsAnyItemActive() || first) _keepEdit = Math.Max(0, d.KeepCount); + } + } + + /// <summary>The popup's contents; true when it should close.</summary> + private bool Body() + { + const float w = 380; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.TextUnformatted(PhosphorIcons.Plus + " Add to loot profile"); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.TextUnformatted(_itemName.Length > 0 ? _itemName : "the selected item"); + ImGuiNET.ImGui.Separator(); + + LootEditItemDraftDto? d = _draft; + bool current = d != null && d.Seq == _seq; + if (d == null) + { + bool slow = (DateTime.UtcNow - _sentAt).TotalSeconds > 3; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, slow ? Amber : Mute); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(slow + ? "No answer from RynthAi. Is it loaded? (A RynthAi older than this feature doesn't answer; /ra loot add needs the new one too.)" + : "Building the rule..."); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + return CloseRow(w); + } + + if (d.Added && _addedAt != default) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Green); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(d.Message + (d.TargetInUse ? ". RynthAi loots with it now." : " (not the profile RynthAi loots with).")); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + if ((DateTime.UtcNow - _addedAt).TotalSeconds > 2.5) return CloseNow(); + return CloseRow(w); + } + + // Where it goes. + if (d.TargetFile.Length > 0) + { + ImGuiNET.ImGui.TextDisabled("Profile:"); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextUnformatted(d.TargetFile + (d.TargetInUse ? " (in use)" : " (not the one RynthAi loots with)")); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(d.TargetPath); + } + + bool changed = false; + // Match. + ImGuiNET.ImGui.TextDisabled("Match:"); + for (int i = 0; i < MatchLabels.Length; i++) + { + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.RadioButton(MatchLabels[i] + "##m" + i.ToString(CultureInfo.InvariantCulture), d.Match == i) && d.Match != i) + { + _match = i; + changed = true; + } + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(MatchTips[i]); + } + + // Action. + ImGuiNET.ImGui.TextDisabled("Action:"); + for (int i = 0; i < ActionIds.Length; i++) + { + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.RadioButton(ActionLabels[i] + "##a" + i.ToString(CultureInfo.InvariantCulture), d.Action == ActionIds[i]) && d.Action != ActionIds[i]) + { + _action = ActionIds[i]; + changed = true; + } + } + if (d.Action == LootEditVocabulary.KeepUpTo) + { + ImGuiNET.ImGui.TextDisabled("Keep up to:"); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(110); + ImGuiNET.ImGui.InputInt("##la_keep", ref _keepEdit, 1, 10); + _keepEdit = Math.Max(0, _keepEdit); + bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit() || (ImGuiNET.ImGui.IsItemEdited() && !ImGuiNET.ImGui.IsItemActive()); + if (done && _keepEdit != d.KeepCount) + { + _keep = _keepEdit; + _action = LootEditVocabulary.KeepUpTo; + changed = true; + } + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextDisabled(d.Stackable ? "(counts stack sizes)" : "(items)"); + } + + // Name. + ImGuiNET.ImGui.TextDisabled("Name:"); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(w - 50); + ImGuiNET.ImGui.InputText("##la_name", _name, (uint)_name.Length); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) changed = true; + if (Utf8(_name).Trim().Length == 0 && d.DefaultRuleName.Length > 0) + ImGuiNET.ImGui.TextDisabled("Left empty, the rule is named \"" + d.DefaultRuleName + "\"."); + + // Preview. + ImGuiNET.ImGui.Separator(); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, current ? Teal : Faded(Teal)); + foreach (string line in d.Preview) ImGuiNET.ImGui.TextUnformatted(line); + ImGuiNET.ImGui.PopStyleColor(); + if (d.OrderNote.Length > 0) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGuiNET.ImGui.TextUnformatted(d.OrderNote); + ImGuiNET.ImGui.PopStyleColor(); + } + if (d.Notes.Count > 0) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + foreach (string n in d.Notes) ImGuiNET.ImGui.TextUnformatted(n); + ImGuiNET.ImGui.PopStyleColor(); + } + if (!d.Ok && d.Error.Length > 0) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Red); + ImGuiNET.ImGui.TextUnformatted(d.Error); + ImGuiNET.ImGui.PopStyleColor(); + } + ImGuiNET.ImGui.PopTextWrapPos(); + + if (changed) + { + Send("item_preview"); // Add waits for the answer (the preview shows faded until then) + current = false; + } + + // Add / Cancel. + Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + bool canAdd = current && d.Ok && !_adding; + string addLabel = _adding ? "Adding..." : PhosphorIcons.Plus + " Add rule"; + if (Button("##la_add", addLabel, bp, new Vector2(110, 24), canAdd ? Green : Mute, canAdd ? StartBg : BtnFill, canAdd)) + { + _adding = true; + Send("item_add"); + } + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip(d.InsertAt >= 0 + ? $"Insert at {d.InsertAt + 1} of {d.RuleCount + 1}, save {d.TargetFile} (old file kept as .bak) and reload it" + : "Add the rule"); + if (Button("##la_cancel", "Cancel", bp + new Vector2(116, 0), new Vector2(80, 24), Text, BtnFill)) + return CloseNow(); + ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28)); + ImGuiNET.ImGui.Dummy(new Vector2(w, 0)); + return false; + } + + private bool CloseRow(float w) + { + Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + bool close = Button("##la_close", "Close", bp, new Vector2(80, 24), Text, BtnFill); + ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28)); + ImGuiNET.ImGui.Dummy(new Vector2(w, 0)); + return close && CloseNow(); + } + + private bool CloseNow() + { + Close(); + return true; + } + + private static void PushStyle() + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, Lighten(BtnFill)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Separator, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + } + + private static void PopStyle() + { + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(7); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs new file mode 100644 index 0000000..e013cf7 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs @@ -0,0 +1,1208 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/LootEditorFace.cs +// The in-game Loot Editor (docs/IMGUI_LOOT_EDITOR.md), replacing the external +// Avalonia app RynthCore.LootEditor. Phase 1: +// +// toolbar profile picker (LootProfiles and AutoVendor), Reload, Save, and +// "Open external editor"; unsaved / read-only / not-in-use chips. +// List search (names and conditions) and action filter; one row per +// rule: enable, action badge, name, conditions in words, up/down, +// duplicate, delete; click a row to edit it; Add rule at the bottom. +// Rule name, action, Keep # count, enabled; conditions: type picker, +// typed editors for the common types, the raw data lines for the +// rest (and on request for any), reorder, delete, add; Apply/Revert. +// Long keys with named values (WieldSkilltype, MaterialType...) pick +// the value by name when RynthAi sends LongValueTables; else a text box. +// +// Data: UiSources.LootEdit (hub snapshot) and LootEditCommands. RynthAi owns +// the profile, validates each edit and does the saving (no clobbering, hot +// reload). The face only reads snapshots and posts commands (AC's thread: +// no plugin calls, no file I/O). The rule view edits a private copy and sends +// it whole with Apply; the plugin's answer replaces it. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using System.Threading; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class LootEditorFace : IImGuiPanel +{ + public const string Title = "Loot Editor"; + + /// <summary>Changes only on edits and saves: 4 Hz idle when popped out.</summary> + public int PopOutIdleHz => 4; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(600, 560), new Vector2(440, 320), EdgeToEdge: true, GripInBody: true), + () => new LootEditorFace()); + + // ── Opening from the dashboard (any thread) ───────────────────────── + + private static string? _requestedPath; + private static string _shownPath = string.Empty; + + /// <summary> + /// The dashboard's Loot Editor button: opens the panel on <paramref name="path"/> + /// (empty: RynthAi's loot profile). Open on that file already: closes it. + /// </summary> + public static void ToggleFor(string? path) + { + path = (path ?? string.Empty).Trim(); + if (ImGuiPanelHost.IsOpen(Title)) + { + if (path.Length == 0 || SamePath(path, Volatile.Read(ref _shownPath))) + { + PanelRouter.Toggle(Title); + return; + } + Volatile.Write(ref _requestedPath, path); + return; + } + Volatile.Write(ref _requestedPath, path); + PanelRouter.Toggle(Title); + } + + /// <summary>Starts the external Avalonia editor on <paramref name="path"/> (a short STA thread, not AC's).</summary> + public static void LaunchExternal(string? path) + { + var launch = new Thread(() => RynthCore.Engine.UI.Panels.RynthAiPanel.LaunchLootEditor(path)) + { + IsBackground = true, + Name = "RynthCore.LootEditorLaunch", + }; + launch.SetApartmentState(ApartmentState.STA); + launch.Start(); + } + + private static bool SamePath(string? a, string? b) + { + if (string.IsNullOrWhiteSpace(a) || string.IsNullOrWhiteSpace(b)) return false; + try { return string.Equals(System.IO.Path.GetFullPath(a.Trim()), System.IO.Path.GetFullPath(b.Trim()), StringComparison.OrdinalIgnoreCase); } + catch { return false; } + } + + // ── Snapshot and caches ───────────────────────────────────────────── + + private long _seenVersion = -1; + private bool _unavailable; + private LootEditStateDto? _state; + private LootEditVocabDto? _vocab; + private LootEditRuleDto? _ruleSeen; + private string[] _fileItems = Array.Empty<string>(); + private string _fileLabel = "Loading..."; + private string _countLabel = string.Empty; + // Tooltips and titles built when the state changes, not every frame. + private string _saveTip = string.Empty, _newTip = string.Empty, _notInUseTip = string.Empty; + private string _ruleTitle = string.Empty; + private (int Index, int Count, bool Dirty) _ruleTitleKey = (-2, -1, false); + private string _keepText = "0"; + private int _keepTextValue; + + // Vocabulary as picker lists (built when it arrives). + private string[] _actionItems = Array.Empty<string>(); + private int[] _actionIds = Array.Empty<int>(); + private string[] _nodeItems = Array.Empty<string>(); + private int[] _nodeIds = Array.Empty<int>(); + private readonly Dictionary<int, LootEditNodeTypeDto> _nodes = new(); + private (string[] Names, int[] Ids) _classes, _longKeys, _doubleKeys, _stringKeys, _skills; + // Long keys whose value is picked by name (WieldSkilltype's skills...). Items end with + // "Other number..." (Ids has one fewer entry), which opens the raw lines. + private sealed record ValueTable(string[] Items, int[] Ids, bool Flags); + private readonly Dictionary<int, ValueTable> _valueTables = new(); + private const string OtherNumber = "Other number..."; + + private readonly Picker _picker = new("##loot_pick"); + // "Add selected item": a rule for the item selected in the game, into the open profile. + private readonly LootAddDialog _lootAdd = new("##loot_additem"); + + // ── List ───────────────────────────────────────────────────────────── + + private enum Mode { List, Rule } + private Mode _mode = Mode.List; + private readonly byte[] _search = new byte[128]; + private string _searchText = string.Empty; + private int _actionFilter; // index into LootEditVocabulary.FilterActions + private readonly List<int> _filtered = new(); + private int _scrollTo = -1; + private const float RowH = 20; + + // ── Messages and confirmations ────────────────────────────────────── + + private string _msg = string.Empty; + private bool _msgOk = true; + private DateTime _msgAt; + private enum Confirm { None, DiscardOpen, DiscardReload, LeaveRule } + private Confirm _confirm; + private string _confirmPath = string.Empty; + private enum Await { None, OpenFocus, ScrollFocus, Apply } + private Await _await; + private long _awaitSeq = -1; + + // ── Rule view ──────────────────────────────────────────────────────── + + private int _editIndex = -1; + private LootEditRuleDto? _editBase, _edit; + private string? _expect; + private bool _takeNextRule; + private readonly HashSet<int> _rawShown = new(); + private sealed class FieldBuffer + { + public readonly byte[] Bytes = new byte[512]; + public string? Shown; + public bool Active; + } + private readonly Dictionary<(int Cond, int Line), FieldBuffer> _fields = new(); + private readonly FieldBuffer _nameField = new(), _keepField = new(); + + public void OnShown() + { + UiSources.LootEdit.Subscribe(); + UiSources.LootEdit.RequestRefresh(); + UiSources.LootEdit.WantRule(_mode == Mode.Rule ? _editIndex : -1); + } + + public void OnHidden() + { + UiSources.LootEdit.WantRule(-1); + UiSources.LootEdit.Unsubscribe(); + _lootAdd.Cancel(); + } + + // ===================================================================== + // Frame + // ===================================================================== + + public void Draw() + { + string? req = Interlocked.Exchange(ref _requestedPath, null); + if (req != null) RequestOpen(req); + TakeSnapshot(); + + float w = Begin(out Vector2 origin, out Vector2 size); + if (_unavailable) + { + Label("RynthAi isn't loaded, or this RynthAi is older than the in-game Loot Editor.", Amber); + if (Button("##ext_only", PhosphorIcons.ArrowSquareOut + " Open external editor", ImGuiNET.ImGui.GetCursorScreenPos(), + new Vector2(ButtonWidth(PhosphorIcons.ArrowSquareOut + " Open external editor") + 4, 24), Text, BtnFill)) + LaunchExternal(null); + } + else if (_state == null) + Label("Loading the loot profile...", Mute); + else + { + Toolbar(w); + StatusRow(w); + ConfirmBar(w); + if (_mode == Mode.List) ListView(origin, size, w); + else RuleView(origin, size, w); + } + End(origin, size); + _lootAdd.Draw(); + // An item rule added to the open profile: show it (the state already carries it and its Focus). + if (_lootAdd.TakeAdded() && _mode == Mode.List && _state != null && _state.Focus >= 0 && _state.Focus < _state.Rules.Count) + _scrollTo = _state.Focus; + _picker.Draw(); + } + + private void RequestOpen(string path) + { + if (_state != null && _state.Dirty && path.Length > 0 && !SamePath(path, _state.Path)) + { + _confirm = Confirm.DiscardOpen; + _confirmPath = path; + return; + } + LeaveRule(); + LootEditCommands.Simple("open", path: path); + } + + private void TakeSnapshot() + { + var snap = UiSources.LootEdit.Current; + if (snap == null || snap.Version == _seenVersion) return; + _seenVersion = snap.Version; + LootEditView v = snap.Value; + _unavailable = v.Unavailable; + if (v.Vocab != null && !ReferenceEquals(v.Vocab, _vocab)) + { + _vocab = v.Vocab; + BuildVocab(); + } + if (v.State != null && !ReferenceEquals(v.State, _state)) OnState(v.State); + if (_mode == Mode.Rule) OnRule(v.Rule); + } + + private void OnState(LootEditStateDto s) + { + LootEditStateDto? before = _state; + _state = s; + Volatile.Write(ref _shownPath, s.Path); + if (before == null || s.MessageSeq != before.MessageSeq) + if (s.Message.Length > 0) SetMsg(s.Message, s.MessageOk); + + _fileItems = new string[s.Files.Count]; + for (int i = 0; i < _fileItems.Length; i++) + _fileItems[i] = s.Files[i].Display + (SamePath(s.Files[i].Path, s.InUsePath) ? " (in use)" : string.Empty); + _fileLabel = s.Path.Length == 0 ? "No loot profile open" : s.FileName + (s.InUse ? " (in use)" : string.Empty); + _saveTip = s.ReadOnly ? "Read-only: " + s.ReadOnlyReason + : s.Dirty ? "Save to " + s.FileName + " (RynthAi reloads it)" : "No unsaved changes"; + _newTip = "Save creates " + s.Path; + _notInUseTip = s.InUsePath.Length == 0 ? "RynthAi has no loot profile selected" + : "RynthAi loots with " + System.IO.Path.GetFileName(s.InUsePath); + RebuildFilter(); + + // A different file (opened here, or RynthAi switched profiles): back to the list. + if (before != null && !SamePath(before.Path, s.Path)) LeaveRule(); + + if (_await != Await.None && s.MessageSeq > _awaitSeq) + { + Await kind = _await; + _await = Await.None; + if (s.MessageOk && s.Focus >= 0 && s.Focus < s.Rules.Count) + { + if (kind == Await.OpenFocus) OpenRule(s.Focus); + else if (kind == Await.ScrollFocus) _scrollTo = s.Focus; + } + if (kind == Await.Apply && s.MessageOk) _takeNextRule = true; + } + } + + private void OnRule(LootEditRuleDto? rule) + { + if (rule == null || rule.Index != _editIndex || ReferenceEquals(rule, _ruleSeen)) return; + _ruleSeen = rule; + if (_edit != null && !_takeNextRule && EditDirty) return; // keep unapplied edits + _takeNextRule = false; + _editBase = rule; + _edit = rule.Clone(); + _expect = rule.Name; + ClearFields(); + } + + private bool EditDirty => _edit != null && _editBase != null && !_edit.SameAs(_editBase); + + private void BuildVocab() + { + LootEditVocabDto v = _vocab!; + _actionItems = new string[v.Actions.Count]; + _actionIds = new int[v.Actions.Count]; + for (int i = 0; i < v.Actions.Count; i++) { _actionItems[i] = v.Actions[i].Name; _actionIds[i] = v.Actions[i].Id; } + _nodes.Clear(); + var names = new List<string>(); + var ids = new List<int>(); + foreach (LootEditNodeTypeDto n in v.NodeTypes) + { + _nodes[n.Id] = n; + if (n.Id == LootEditVocabulary.DisabledRule) continue; + names.Add(n.Name); + ids.Add(n.Id); + } + _nodeItems = names.ToArray(); + _nodeIds = ids.ToArray(); + _classes = Table(v.ObjectClasses); + _longKeys = Table(v.LongKeys); + _doubleKeys = Table(v.DoubleKeys); + _stringKeys = Table(v.StringKeys); + _skills = Table(v.Skills); + // Absent from an older RynthAi: no tables, every value stays a text box. + _valueTables.Clear(); + foreach (LootEditValueTableDto t in v.LongValueTables ?? new List<LootEditValueTableDto>()) + { + if (t?.Values == null || t.Values.Count == 0) continue; + (string[] tn, int[] ti) = Table(t.Values); + var items = new string[tn.Length + 1]; + Array.Copy(tn, items, tn.Length); + items[tn.Length] = OtherNumber; + _valueTables[t.Key] = new ValueTable(items, ti, t.Flags); + } + + static (string[], int[]) Table(List<LootEditNameDto> list) + { + var n = new string[list.Count]; + var id = new int[list.Count]; + for (int i = 0; i < list.Count; i++) { n[i] = list[i].Name + " (" + list[i].Id.ToString(CultureInfo.InvariantCulture) + ")"; id[i] = list[i].Id; } + return (n, id); + } + } + + private void SetMsg(string text, bool ok) + { + _msg = text; + _msgOk = ok; + _msgAt = DateTime.Now; + } + + // ===================================================================== + // Toolbar, status, confirmations + // ===================================================================== + + private void Toolbar(float w) + { + LootEditStateDto s = _state!; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float icon = 26, saveW = 64, h = 24; + float pickW = w - icon * 2 - saveW - 12; + + if (Button("##file", _fileLabel, p, new Vector2(pickW, h), s.Dirty ? Amber : Text, BtnFill, leftAlign: true)) + { + int sel = s.Files.FindIndex(f => SamePath(f.Path, s.Path)); + _picker.Open(new Vector2(p.X, p.Y + h), _fileItems, sel, i => + { + if (i >= 0 && i < s.Files.Count) RequestOpen(s.Files[i].Path); + }, Math.Max(260, pickW)); + } + ImGuiNET.ImGui.SetItemTooltip(s.Path.Length == 0 ? "Pick a loot profile" : s.Path); + PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown, + new Vector2(p.X + pickW - 18, p.Y), new Vector2(16, h), Mute); + + float x = p.X + pickW + 4; + if (IconButton("##reload", PhosphorIcons.ArrowsClockwise, new Vector2(x, p.Y), new Vector2(icon, h), Text, BtnFill, s.Path.Length > 0)) + { + if (s.Dirty) _confirm = Confirm.DiscardReload; + else { LeaveRule(); LootEditCommands.Simple("reload"); } + } + ImGuiNET.ImGui.SetItemTooltip("Reload from disk"); + x += icon + 4; + + bool canSave = !s.ReadOnly && s.Path.Length > 0 && (s.Dirty || !s.Exists); + if (Button("##save", PhosphorIcons.FloppyDisk + " Save", new Vector2(x, p.Y), new Vector2(saveW, h), + canSave ? Green : Mute, canSave ? StartBg : BtnFill, canSave)) + Save(force: false); + ImGuiNET.ImGui.SetItemTooltip(_saveTip); + x += saveW + 4; + + if (IconButton("##external", PhosphorIcons.ArrowSquareOut, new Vector2(x, p.Y), new Vector2(icon, h), Text, BtnFill)) + LaunchExternal(s.Path.Length > 0 ? s.Path : s.InUsePath); + ImGuiNET.ImGui.SetItemTooltip(s.Dirty + ? "Open external editor (it reads the file on disk: save first to take your edits)" + : "Open external editor"); + NextLine(p, h + 4); + } + + private void Save(bool force) + { + if (_mode == Mode.Rule && EditDirty && !(_state?.ReadOnly ?? true)) + { + SetMsg("Apply or Revert this rule's changes first, then Save.", ok: false); + return; + } + LootEditCommands.Simple("save", force: force); + } + + private void StatusRow(float w) + { + LootEditStateDto s = _state!; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + const float h = 18; + float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.AddText(new Vector2(p.X, ty), Mute, _countLabel); + float x = p.X + ImGuiNET.ImGui.CalcTextSize(_countLabel).X + 10; + if (s.Dirty) x = Chip(dl, x, p.Y, h, "unsaved", Amber, "Changes not saved to the file yet"); + if (s.ReadOnly) x = Chip(dl, x, p.Y, h, "read-only", Red, s.ReadOnlyReason); + if (s.Path.Length > 0 && !s.Exists) x = Chip(dl, x, p.Y, h, "new file", Teal, _newTip); + if (s.Path.Length > 0 && !s.InUse) + Chip(dl, x, p.Y, h, "not in use", Mute, _notInUseTip); + NextLine(p, h + 2); + } + + private static float Chip(ImDrawListPtr dl, float x, float y, float h, string text, uint color, string tooltip) + { + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text); + var a = new Vector2(x, y + 1); + var b = new Vector2(x + ts.X + 12, y + h - 1); + dl.AddRect(a, b, color, 8); + dl.AddText(new Vector2(x + 6, y + (h - ts.Y) * 0.5f), color, text); + if (ImGuiNET.ImGui.IsMouseHoveringRect(a, b) && tooltip.Length > 0) ImGuiNET.ImGui.SetTooltip(tooltip); + return b.X + 6; + } + + private void ConfirmBar(float w) + { + LootEditStateDto s = _state!; + string text; + if (s.ChangedOnDisk) + text = s.FileName + " changed on disk while you have unsaved edits."; + else if (_confirm == Confirm.DiscardOpen) + text = "Unsaved changes in " + s.FileName + " will be lost."; + else if (_confirm == Confirm.DiscardReload) + text = "Reload " + s.FileName + " from disk and drop your edits?"; + else if (_confirm == Confirm.LeaveRule) + text = "This rule has changes you haven't applied."; + else return; + + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + const float h = 26; + dl.AddRectFilled(p, p + new Vector2(w, h), RynthTheme.Argb(0xFF3A2A0A), 3); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Warning, p, new Vector2(22, h), Amber); + + var labels = new List<string>(3); + if (s.ChangedOnDisk) { labels.Add("Save anyway"); labels.Add("Reload"); } + else if (_confirm == Confirm.DiscardOpen) { labels.Add("Discard and open"); labels.Add("Cancel"); } + else if (_confirm == Confirm.DiscardReload) { labels.Add("Reload"); labels.Add("Cancel"); } + else { labels.Add("Apply"); labels.Add("Discard"); labels.Add("Cancel"); } + + float bx = p.X + w - 4; + int clicked = -1; + for (int i = labels.Count - 1; i >= 0; i--) + { + float bw = ButtonWidth(labels[i]); + bx -= bw; + ImGuiNET.ImGui.PushID(900 + i); + if (Button("##c", labels[i], new Vector2(bx, p.Y + 3), new Vector2(bw, h - 6), i == 0 ? Amber : Text, BtnFill)) clicked = i; + ImGuiNET.ImGui.PopID(); + bx -= 4; + } + dl.PushClipRect(p, new Vector2(bx, p.Y + h), true); + dl.AddText(new Vector2(p.X + 24, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Amber, text); + dl.PopClipRect(); + NextLine(p, h + 4); + + if (clicked < 0) return; + if (s.ChangedOnDisk) + { + if (clicked == 0) Save(force: true); + else { LeaveRule(); LootEditCommands.Simple("reload", force: true); } + return; + } + Confirm c = _confirm; + _confirm = Confirm.None; + if (c == Confirm.DiscardOpen && clicked == 0) { LeaveRule(); LootEditCommands.Simple("open", path: _confirmPath, force: true); } + else if (c == Confirm.DiscardReload && clicked == 0) { LeaveRule(); LootEditCommands.Simple("reload", force: true); } + else if (c == Confirm.LeaveRule) + { + if (clicked == 0) { Apply(); LeaveRule(); } + else if (clicked == 1) LeaveRule(); + } + } + + // ===================================================================== + // List view + // ===================================================================== + + private void RebuildFilter() + { + _filtered.Clear(); + LootEditStateDto? s = _state; + if (s == null) { _countLabel = string.Empty; return; } + int action = LootEditVocabulary.FilterActions[_actionFilter]; + string q = _searchText.Trim(); + for (int i = 0; i < s.Rules.Count; i++) + { + LootEditRowDto r = s.Rules[i]; + if (action != 0 && r.Action != action) continue; + if (q.Length > 0 && !r.Name.Contains(q, StringComparison.OrdinalIgnoreCase) + && !r.Summary.Contains(q, StringComparison.OrdinalIgnoreCase)) continue; + _filtered.Add(i); + } + _countLabel = _filtered.Count == s.Rules.Count + ? s.Rules.Count.ToString(CultureInfo.InvariantCulture) + " rules" + : _filtered.Count.ToString(CultureInfo.InvariantCulture) + " of " + s.Rules.Count.ToString(CultureInfo.InvariantCulture) + " rules"; + } + + private bool Filtering => _actionFilter != 0 || _searchText.Trim().Length > 0; + + private void ListView(Vector2 origin, Vector2 size, float w) + { + LootEditStateDto s = _state!; + FilterRow(w); + Separator(w); + + const float bottomH = 24; + float listH = Math.Max(40, Remaining(origin, size) - bottomH - 6); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0)); + ImGuiNET.ImGui.BeginChild("##loot_rules", new Vector2(w, listH)); + if (s.Path.Length == 0) + Label(" No loot profile open. Pick one above, or choose one in the RynthAi dashboard.", Mute); + else if (s.Rules.Count == 0) + Label(" No rules yet. Add rule creates one.", Mute); + else if (_filtered.Count == 0) + Label(" No rules match the filter.", Mute); + else + RuleRows(s, ImGuiNET.ImGui.GetContentRegionAvail().X, listH); + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + BottomBar(w, s); + } + + private void FilterRow(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float h = 22; + float searchW = Math.Min(220, w * 0.38f); + if (TextBox("##search", _search, p, searchW, "Search names and conditions", out _, ImGuiInputTextFlags.None, h)) + { + _searchText = Utf8(_search); + RebuildFilter(); + } + float x = p.X + searchW + 8; + for (int i = 0; i < LootEditVocabulary.FilterLabels.Length; i++) + { + string label = LootEditVocabulary.FilterLabels[i]; + float bw = ButtonWidth(label); + if (x + bw > p.X + w) break; + bool on = _actionFilter == i; + ImGuiNET.ImGui.PushID(800 + i); + if (Button("##f", label, new Vector2(x, p.Y), new Vector2(bw, h), on ? Teal : Mute, on ? Selected : BtnFill, border: on ? Teal : 0)) + { + _actionFilter = i; + RebuildFilter(); + } + ImGuiNET.ImGui.PopID(); + x += bw + 3; + } + NextLine(p, h + 4); + } + + private void RuleRows(LootEditStateDto s, float w, float viewH) + { + if (_scrollTo >= 0) + { + int pos = _filtered.IndexOf(_scrollTo); + if (pos >= 0) + { + float y = pos * RowH, top = ImGuiNET.ImGui.GetScrollY(); + if (y < top || y + RowH > top + viewH) ImGuiNET.ImGui.SetScrollY(Math.Max(0, y - viewH * 0.4f)); + } + _scrollTo = -1; + } + + // Only the visible rows are drawn (LootSnobV4 has 1637). + int n = _filtered.Count; + float scroll = ImGuiNET.ImGui.GetScrollY(); + int first = Math.Clamp((int)(scroll / RowH), 0, n); + int last = Math.Min(n, first + (int)(viewH / RowH) + 2); + if (first > 0) ImGuiNET.ImGui.Dummy(new Vector2(w, first * RowH)); + bool reorder = !Filtering && !s.ReadOnly; + for (int k = first; k < last; k++) + { + int index = _filtered[k]; + if (index >= s.Rules.Count) break; + // A click only posts a command (the list changes when the next snapshot comes), so + // every row still draws: stopping early would shrink the scroll range for a frame. + RuleRow(s, s.Rules[index], index, k, w, reorder); + } + if (last < n) ImGuiNET.ImGui.Dummy(new Vector2(w, (n - last) * RowH)); + } + + /// <summary>One rule row. True when a click sent a command that changes the list.</summary> + private bool RuleRow(LootEditStateDto s, LootEditRowDto r, int index, int k, float w, bool reorder) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool ro = s.ReadOnly; + dl.AddRectFilled(p, p + new Vector2(w, RowH), k % 2 == 0 ? PanelBg : RowAlt); + ImGuiNET.ImGui.PushID(index); + bool changed = false; + + // Enable + float x = p.X + 2; + if (IconButton("##en", r.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square, new Vector2(x, p.Y + 2), new Vector2(16, 16), + r.Enabled ? Green : Mute, BtnFill, !ro, font: UiFont.Ui11)) + { + LootEditCommands.Simple("set_enabled", index, r.Enabled ? "false" : "true", expect: r.Name); + changed = true; + } + ImGuiNET.ImGui.SetItemTooltip(r.Enabled ? "Enabled: click to disable" : "Disabled: click to enable"); + x += 20; + + // Action badge + const float badgeW = 64; + string badge = LootEditVocabulary.Badge(r.Action, r.KeepCount); + uint badgeCol = RynthTheme.Argb(LootEditVocabulary.BadgeArgb(r.Action)); + dl.AddRectFilled(new Vector2(x, p.Y + 3), new Vector2(x + badgeW, p.Y + RowH - 3), r.Enabled ? badgeCol : Faded(badgeCol), 3); + ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9); + ImGuiNET.ImGui.PushFont(f9); + Vector2 bs = ImGuiNET.ImGui.CalcTextSize(badge); + ImGuiNET.ImGui.PopFont(); + dl.AddText(f9, f9.FontSize, new Vector2(x + (badgeW - bs.X) * 0.5f, p.Y + (RowH - bs.Y) * 0.5f), Text, badge); + x += badgeW + 6; + + // Buttons on the right: up, down, duplicate, delete. + const float btns = 18 * 3 + 22 + 4; + float right = p.X + w - btns; + float bx = right; + if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(bx, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, reorder && index > 0, font: UiFont.Ui11)) + { + LootEditCommands.Simple("move", index, to: index - 1, expect: r.Name); + Expect(Await.ScrollFocus); + changed = true; + } + ImGuiNET.ImGui.SetItemTooltip(reorder ? "Move up" : Filtering ? "Clear the search and filter to reorder" : "Move up"); + bx += 18; + if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(bx, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, + reorder && index < s.Rules.Count - 1, font: UiFont.Ui11)) + { + LootEditCommands.Simple("move", index, to: index + 1, expect: r.Name); + Expect(Await.ScrollFocus); + changed = true; + } + ImGuiNET.ImGui.SetItemTooltip(reorder ? "Move down" : Filtering ? "Clear the search and filter to reorder" : "Move down"); + bx += 18; + if (IconButton("##dup", PhosphorIcons.Copy, new Vector2(bx, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, !ro, font: UiFont.Ui11)) + { + LootEditCommands.Simple("duplicate", index, expect: r.Name); + Expect(Await.ScrollFocus); + changed = true; + } + ImGuiNET.ImGui.SetItemTooltip("Duplicate rule"); + bx += 18; + if (IconButton("##del", PhosphorIcons.Trash, new Vector2(bx, p.Y + 2), new Vector2(20, 16), Text, DeleteBg, !ro, font: UiFont.Ui11)) + { + LootEditCommands.Simple("delete", index, expect: r.Name); + changed = true; + } + ImGuiNET.ImGui.SetItemTooltip("Delete rule (Reload undoes it until you Save)"); + + // Name | conditions; click to edit. + float textW = Math.Max(1, right - 4 - x); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y)); + if (ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(textW, RowH))) OpenRule(index); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + if (hot) + { + ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + dl.AddRect(new Vector2(x - 2, p.Y), new Vector2(x + textW, p.Y + RowH), BtnBord, 2); + ImGuiNET.ImGui.SetTooltip((r.Name.Length == 0 ? "(no name)" : r.Name) + "\n" + r.Summary); + } + ImGuiNET.ImGui.PopID(); + + float nameW = textW * 0.42f; + float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + uint nameCol = r.Enabled ? Text : Faded(Text), sumCol = r.Enabled ? Mute : Faded(Mute); + dl.PushClipRect(new Vector2(x, p.Y), new Vector2(x + nameW - 6, p.Y + RowH), true); + dl.AddText(new Vector2(x, ty), r.Name.Length == 0 ? Faded(Mute) : nameCol, r.Name.Length == 0 ? "(no name)" : r.Name); + dl.PopClipRect(); + dl.PushClipRect(new Vector2(x + nameW, p.Y), new Vector2(x + textW, p.Y + RowH), true); + dl.AddText(new Vector2(x + nameW, ty), sumCol, r.Summary); + dl.PopClipRect(); + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + RowH)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + return changed; + } + + private void Expect(Await kind) + { + _await = kind; + _awaitSeq = _state?.MessageSeq ?? 0; + } + + private void BottomBar(float w, LootEditStateDto s) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float h = 24; + float grip = ImGuiPanelHost.BodyGripReserve; + string addLabel = PhosphorIcons.Plus + " Add rule"; + float addW = ButtonWidth(addLabel) + 6; + bool canAdd = !s.ReadOnly && s.Path.Length > 0; + if (Button("##add", addLabel, p, new Vector2(addW, h), canAdd ? Green : Mute, canAdd ? StartBg : BtnFill, canAdd)) + { + LootEditCommands.Simple("add", -1); + Expect(Await.OpenFocus); + } + ImGuiNET.ImGui.SetItemTooltip("Add a rule at the end and edit it"); + string itemLabel = PhosphorIcons.Plus + " Add selected item"; + float itemW = ButtonWidth(itemLabel) + 6; + bool canItem = s.Path.Length > 0 && !s.Dirty && (!s.ReadOnly || s.Format == "json"); + if (Button("##add_item", itemLabel, new Vector2(p.X + addW + 6, p.Y), new Vector2(itemW, h), canItem ? Teal : Mute, BtnFill, canItem)) + _lootAdd.Open(0, string.Empty, toOpenProfile: true); + ImGuiNET.ImGui.SetItemTooltip(canItem + ? "A rule for the item selected in the game (click it first): preview, then add it here" + : s.Dirty ? "Save or discard your edits first" : "This profile is read-only here"); + addW += itemW + 6; + MessageText(new Vector2(p.X + addW + 8, p.Y), p.X + w - grip - 4, h); + NextLine(p, h); + } + + private void MessageText(Vector2 at, float right, float h) + { + if (_msg.Length == 0 || (_msgOk && (DateTime.Now - _msgAt).TotalSeconds > 10)) return; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.PushClipRect(at, new Vector2(Math.Max(at.X + 1, right), at.Y + h), true); + dl.AddText(new Vector2(at.X, at.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), _msgOk ? Green : Red, _msg); + dl.PopClipRect(); + if (ImGuiNET.ImGui.IsMouseHoveringRect(at, new Vector2(right, at.Y + h))) ImGuiNET.ImGui.SetTooltip(_msg); + } + + // ===================================================================== + // Rule view + // ===================================================================== + + private void OpenRule(int index) + { + _mode = Mode.Rule; + _editIndex = index; + _edit = _editBase = null; + _ruleSeen = null; + _takeNextRule = true; + _rawShown.Clear(); + ClearFields(); + if (_confirm == Confirm.LeaveRule) _confirm = Confirm.None; + UiSources.LootEdit.WantRule(index); + } + + private void LeaveRule() + { + if (_mode == Mode.Rule && _editIndex >= 0) _scrollTo = _editIndex; + _mode = Mode.List; + _editIndex = -1; + _edit = _editBase = null; + if (_confirm == Confirm.LeaveRule) _confirm = Confirm.None; + UiSources.LootEdit.WantRule(-1); + } + + private void ClearFields() + { + _fields.Clear(); + _nameField.Shown = null; + _keepField.Shown = null; + } + + private void Apply() + { + if (_edit == null || _state == null || _state.ReadOnly) return; + LootEditCommands.Send(new LootEditCmd { Op = "update_rule", Index = _editIndex, Expect = _expect, Rule = _edit.Clone() }); + Expect(Await.Apply); + } + + private void RuleView(Vector2 origin, Vector2 size, float w) + { + LootEditStateDto s = _state!; + bool ro = s.ReadOnly; + bool dirty = EditDirty; + + // [< Back] Rule 12 of 1637 [Apply] [Revert] + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float h = 24; + string back = PhosphorIcons.ArrowLeft + " Back"; + float backW = ButtonWidth(back) + 4; + if (Button("##back", back, p, new Vector2(backW, h), Text, BtnFill)) + { + if (dirty && !ro) _confirm = Confirm.LeaveRule; + else LeaveRule(); + } + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + if (_ruleTitleKey != (_editIndex, s.Rules.Count, dirty)) + { + _ruleTitleKey = (_editIndex, s.Rules.Count, dirty); + _ruleTitle = "Rule " + (_editIndex + 1).ToString(CultureInfo.InvariantCulture) + " of " + + s.Rules.Count.ToString(CultureInfo.InvariantCulture) + (dirty ? " (changed)" : string.Empty); + } + string title = _ruleTitle; + ImGuiNET.ImGui.GetWindowDrawList().AddText(bold, bold.FontSize, new Vector2(p.X + backW + 10, p.Y + (h - bold.FontSize) * 0.5f), + dirty ? Amber : Teal, title); + string applyL = PhosphorIcons.Check + " Apply", revertL = PhosphorIcons.ArrowCounterClockwise + " Revert"; + float applyW = ButtonWidth(applyL) + 6, revertW = ButtonWidth(revertL) + 6; + float rx = p.X + w - revertW; + if (Button("##revert", revertL, new Vector2(rx, p.Y), new Vector2(revertW, h), Text, BtnFill, dirty)) + { + if (_editBase != null) { _edit = _editBase.Clone(); ClearFields(); } + } + ImGuiNET.ImGui.SetItemTooltip("Drop this rule's changes"); + rx -= applyW + 4; + if (Button("##apply", applyL, new Vector2(rx, p.Y), new Vector2(applyW, h), dirty ? Green : Mute, dirty ? StartBg : BtnFill, dirty && !ro)) + Apply(); + ImGuiNET.ImGui.SetItemTooltip("Put these changes in the profile (then Save writes the file)"); + NextLine(p, h + 4); + Separator(w); + + if (_edit == null) + { + Label("Loading the rule...", Mute); + return; + } + + float bodyH = Math.Max(40, Remaining(origin, size) - GripOverlap()); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0); + ImGuiNET.ImGui.BeginChild("##loot_rule", new Vector2(w, bodyH)); + float cw = ImGuiNET.ImGui.GetContentRegionAvail().X - 4; + RuleBody(_edit, cw, ro); + MessageRow(cw); + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleColor(); + } + + private void MessageRow(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + MessageText(new Vector2(p.X, p.Y + 4), p.X + w, 20); + NextLine(p, 28); + } + + private void RuleBody(LootEditRuleDto r, float w, bool ro) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + const float h = 22, labelW = 64; + + // Name + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + FieldLabel(dl, p, h, "Name"); + if (Field("##name", _nameField, r.Name, new Vector2(p.X + labelW, p.Y), w - labelW, "(no name)", ro, out string name, h)) + r.Name = name; + NextLine(p, h + 6); + + // Action [Keep #: count] Enabled + p = ImGuiNET.ImGui.GetCursorScreenPos(); + FieldLabel(dl, p, h, "Action"); + int ai = Array.IndexOf(_actionIds, r.Action); + string actionText = ai >= 0 ? _actionItems[ai] : "Action " + r.Action.ToString(CultureInfo.InvariantCulture); + float x = p.X + labelW; + if (PickerButton("##action", actionText, new Vector2(x, p.Y), 110, h, ro)) + _picker.Open(new Vector2(x, p.Y + h), _actionItems, ai, i => + { + if (_edit == null) return; + _edit.Action = _actionIds[i]; + if (_edit.Action == LootEditVocabulary.KeepUpTo && _edit.KeepCount <= 0) _edit.KeepCount = 1; + _keepField.Shown = null; + }, 160); + x += 116; + if (r.Action == LootEditVocabulary.KeepUpTo) + { + dl.AddText(new Vector2(x, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "keep up to"); + x += ImGuiNET.ImGui.CalcTextSize("keep up to").X + 6; + if (_keepTextValue != r.KeepCount || _keepText.Length == 0) + { + _keepTextValue = r.KeepCount; + _keepText = r.KeepCount.ToString(CultureInfo.InvariantCulture); + } + string count = _keepText; + if (IconButton("##kc_dec", PhosphorIcons.Minus, new Vector2(x, p.Y), new Vector2(h, h), Teal, BtnFill, !ro && r.KeepCount > 0, font: UiFont.Ui11)) + { r.KeepCount = Math.Max(0, r.KeepCount - 1); _keepField.Shown = null; } + x += h + 2; + if (Field("##kc", _keepField, count, new Vector2(x, p.Y), 56, "0", ro, out string typed, h) + && int.TryParse(typed.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int kc) && kc >= 0) + r.KeepCount = kc; + x += 58; + if (IconButton("##kc_inc", PhosphorIcons.Plus, new Vector2(x, p.Y), new Vector2(h, h), Teal, BtnFill, !ro, font: UiFont.Ui11)) + { r.KeepCount++; _keepField.Shown = null; } + x += h + 10; + } + string en = (r.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " Enabled"; + float enW = ButtonWidth(en); + if (Button("##enabled", en, new Vector2(Math.Max(x, p.X + w - enW), p.Y), new Vector2(enW, h), r.Enabled ? Green : Mute, BtnFill, !ro)) + r.Enabled = !r.Enabled; + NextLine(p, h + 8); + + // Conditions + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + p = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddText(bold, bold.FontSize, p, Amber, "Conditions (all must match)"); + NextLine(p, bold.FontSize + 6); + + int shown = 0; + for (int i = 0; i < r.Conditions.Count; i++) + { + if (r.Conditions[i].NodeType == LootEditVocabulary.DisabledRule) continue; // the Enabled switch owns these + shown++; + ImGuiNET.ImGui.PushID(i); + int result = ConditionRow(r, i, w, ro); + ImGuiNET.ImGui.PopID(); + if (result != 0) break; // the list changed: the rest draws next frame + } + if (shown == 0) Label("No conditions: this rule matches every item.", Mute); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + p = ImGuiNET.ImGui.GetCursorScreenPos(); + string addL = PhosphorIcons.Plus + " Add condition"; + if (Button("##add_cond", addL, p, new Vector2(ButtonWidth(addL) + 6, h), ro ? Mute : Teal, BtnFill, !ro && _nodeItems.Length > 0)) + _picker.Open(new Vector2(p.X, p.Y + h), _nodeItems, -1, i => + { + if (_edit == null) return; + // Before any DisabledRule node, so the rule's file layout stays VTank's. + int at = _edit.Conditions.FindIndex(c => c.NodeType == LootEditVocabulary.DisabledRule); + var c = new LootEditConditionDto { NodeType = _nodeIds[i], Lines = DefaultsFor(_nodeIds[i]) }; + if (at < 0) _edit.Conditions.Add(c); else _edit.Conditions.Insert(at, c); + ClearFields(); + }, 260); + NextLine(p, h + 4); + } + + private static void FieldLabel(ImDrawListPtr dl, Vector2 p, float h, string text) => + dl.AddText(new Vector2(p.X, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, text); + + private List<string> DefaultsFor(int nodeType) => + _nodes.TryGetValue(nodeType, out LootEditNodeTypeDto? n) ? new List<string>(n.Defaults) : new List<string>(); + + /// <summary>One condition: [type] [editor] [raw][^][v][x], raw lines below. Non-zero when the list changed.</summary> + private int ConditionRow(LootEditRuleDto r, int i, float w, bool ro) + { + LootEditConditionDto c = r.Conditions[i]; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + const float h = 22, typeW = 150, tail = 18 * 3 + 22 + 8; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddRectFilled(p - new Vector2(2, 1), p + new Vector2(w + 2, h + 1), RowAlt, 3); + + _nodes.TryGetValue(c.NodeType, out LootEditNodeTypeDto? node); + bool json = c.NodeType < 0; + string typeName = json ? "JSON condition" : node?.Name ?? "Node " + c.NodeType.ToString(CultureInfo.InvariantCulture); + bool canType = !ro && !json && node != null; + if (PickerButton("##type", typeName, p, typeW, h, !canType)) + _picker.Open(new Vector2(p.X, p.Y + h), _nodeItems, Array.IndexOf(_nodeIds, c.NodeType), k => + { + if (_edit == null || i >= _edit.Conditions.Count) return; + LootEditConditionDto target = _edit.Conditions[i]; + if (target.NodeType == _nodeIds[k]) return; + target.NodeType = _nodeIds[k]; + target.Lines = DefaultsFor(_nodeIds[k]); + ClearFields(); + }, 260); + + float ex = p.X + typeW + 4; + float editorW = Math.Max(60, w - typeW - 4 - tail); + string editor = json ? "json" : node?.Editor ?? "raw"; + bool raw = editor == "raw" || _rawShown.Contains(i); + if (!raw) TypedEditor(c, i, node!, editor, new Vector2(ex, p.Y), editorW, h, ro); + else if (json) + { + dl.PushClipRect(new Vector2(ex, p.Y), new Vector2(ex + editorW, p.Y + h), true); + dl.AddText(new Vector2(ex + 2, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, c.Lines.Count > 0 ? c.Lines[0] : string.Empty); + dl.PopClipRect(); + } + else + dl.AddText(new Vector2(ex + 2, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "(raw data lines below)"); + + // Tail: raw toggle, up, down, delete. + float tx = p.X + w - tail + 8; + bool rawToggle = !json && editor != "raw"; + if (IconButton("##raw", PhosphorIcons.Code, new Vector2(tx, p.Y + 3), new Vector2(16, 16), _rawShown.Contains(i) ? Teal : Mute, BtnFill, + rawToggle, font: UiFont.Ui11)) + { + if (!_rawShown.Remove(i)) _rawShown.Add(i); + } + ImGuiNET.ImGui.SetItemTooltip(rawToggle ? "Show the raw data lines (any key id, any value)" : "This condition is edited as raw lines"); + tx += 18; + int result = 0; + int prev = PrevVisible(r, i), next = NextVisible(r, i); + if (IconButton("##cup", PhosphorIcons.ArrowUp, new Vector2(tx, p.Y + 3), new Vector2(16, 16), Mute, BtnFill, !ro && prev >= 0, font: UiFont.Ui11)) + { Swap(r, i, prev); result = 1; } + ImGuiNET.ImGui.SetItemTooltip("Move up"); + tx += 18; + if (IconButton("##cdn", PhosphorIcons.ArrowDown, new Vector2(tx, p.Y + 3), new Vector2(16, 16), Mute, BtnFill, !ro && next >= 0, font: UiFont.Ui11)) + { Swap(r, i, next); result = 1; } + ImGuiNET.ImGui.SetItemTooltip("Move down"); + tx += 18; + if (IconButton("##cdel", PhosphorIcons.X, new Vector2(tx, p.Y + 3), new Vector2(20, 16), Text, DeleteBg, !ro, font: UiFont.Ui11)) + { + r.Conditions.RemoveAt(i); + _rawShown.Clear(); + ClearFields(); + result = 1; + } + ImGuiNET.ImGui.SetItemTooltip("Remove condition"); + NextLine(p, h + 3); + if (result != 0 || !raw || json) return result; + + // Raw lines, one text box each. + List<string> labels = node?.Labels ?? new List<string>(); + for (int line = 0; line < c.Lines.Count; line++) + { + Vector2 rowStart = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 lp = rowStart + new Vector2(typeW + 4, 0); + string label = line < labels.Count ? labels[line] : "Line " + (line + 1).ToString(CultureInfo.InvariantCulture); + float lw = 84; + dl.PushClipRect(lp, lp + new Vector2(lw - 4, 20), true); + dl.AddText(new Vector2(lp.X, lp.Y + (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, label); + dl.PopClipRect(); + ImGuiNET.ImGui.PushID(line); + if (Field("##rawline", FieldFor(i, line), c.Lines[line], new Vector2(lp.X + lw, lp.Y), + Math.Max(60, w - typeW - 4 - lw - 26), string.Empty, ro, out string v, 20)) + c.Lines[line] = v; + ImGuiNET.ImGui.PopID(); + NextLine(rowStart, 22); + } + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + return 0; + } + + private static int PrevVisible(LootEditRuleDto r, int i) + { + for (int j = i - 1; j >= 0; j--) if (r.Conditions[j].NodeType != LootEditVocabulary.DisabledRule) return j; + return -1; + } + + private static int NextVisible(LootEditRuleDto r, int i) + { + for (int j = i + 1; j < r.Conditions.Count; j++) if (r.Conditions[j].NodeType != LootEditVocabulary.DisabledRule) return j; + return -1; + } + + private void Swap(LootEditRuleDto r, int a, int b) + { + (r.Conditions[a], r.Conditions[b]) = (r.Conditions[b], r.Conditions[a]); + bool ra = _rawShown.Remove(a), rb = _rawShown.Remove(b); + if (ra) _rawShown.Add(b); + if (rb) _rawShown.Add(a); + ClearFields(); + } + + /// <summary>The typed editors: object class, key + value, key + pattern, one text, one number.</summary> + private void TypedEditor(LootEditConditionDto c, int i, LootEditNodeTypeDto node, string editor, Vector2 p, float w, float h, bool ro) + { + while (c.Lines.Count < node.Lines) c.Lines.Add(node.Defaults.Count > c.Lines.Count ? node.Defaults[c.Lines.Count] : "0"); + switch (editor) + { + case "class": + IdPicker("##class", c, 0, _classes, "class", p, w, h, ro); + break; + case "keyval": + { + ValueTable? named = NamedValueTable(node, c); + float kw = w * (named != null ? 0.5f : 0.58f); + IdPicker("##key", c, 1, KeyTable(node.KeyTable), node.KeyTable == "skill" ? "skill" : "key", p, kw - 2, h, ro); + if (named != null) + { + ValuePicker(c, i, named, new Vector2(p.X + kw + 2, p.Y), w - kw - 2, h, ro); + break; + } + string hint = node.Labels.Count > 0 ? node.Labels[0].ToLowerInvariant() : "value"; + if (Field("##val", FieldFor(i, 0), c.Lines[0], new Vector2(p.X + kw + 2, p.Y), w - kw - 2, hint, ro, out string v, h)) + c.Lines[0] = v; + ImGuiNET.ImGui.SetItemTooltip(node.Labels.Count > 0 ? node.Labels[0] : "Value"); + break; + } + case "keypattern": + { + float kw = w * 0.34f; + IdPicker("##key", c, 1, KeyTable(node.KeyTable), "key", p, kw - 2, h, ro); + if (Field("##pat", FieldFor(i, 0), c.Lines[0], new Vector2(p.X + kw + 2, p.Y), w - kw - 2, "pattern (regex)", ro, out string v, h)) + c.Lines[0] = v; + break; + } + case "text": + if (Field("##text", FieldFor(i, 0), c.Lines[0], p, w, "pattern (regex)", ro, out string t, h)) c.Lines[0] = t; + break; + default: // "value" + if (Field("##value", FieldFor(i, 0), c.Lines[0], p, w, node.Labels.Count > 0 ? node.Labels[0].ToLowerInvariant() : "value", ro, out string n, h)) + c.Lines[0] = n; + break; + } + } + + private (string[] Names, int[] Ids) KeyTable(string table) => table switch + { + "long" => _longKeys, + "double" => _doubleKeys, + "string" => _stringKeys, + "skill" => _skills, + _ => (Array.Empty<string>(), Array.Empty<int>()), + }; + + /// <summary>A picker for an id line (object class, key, skill) showing the name; unknown ids show as "key N".</summary> + private void IdPicker(string id, LootEditConditionDto c, int line, (string[] Names, int[] Ids) table, string what, Vector2 p, float w, float h, bool ro) + { + if (line >= c.Lines.Count) return; + string raw = c.Lines[line].Trim(); + int sel = -1; + if (int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)) + sel = Array.IndexOf(table.Ids, value); + string shown = sel >= 0 ? table.Names[sel] : what + " " + raw; + if (PickerButton(id, shown, p, w, h, ro || table.Names.Length == 0)) + { + LootEditConditionDto target = c; + _picker.Open(new Vector2(p.X, p.Y + h), table.Names, sel, k => + { + if (line < target.Lines.Count) target.Lines[line] = table.Ids[k].ToString(CultureInfo.InvariantCulture); + ClearFields(); + }, Math.Max(220, w)); + } + ImGuiNET.ImGui.SetItemTooltip(sel >= 0 ? table.Names[sel] : "Not in the list: use the raw lines button to type any id"); + } + + /// <summary>The value names for this condition's long key, or null (no table, or a RynthAi that sends none).</summary> + private ValueTable? NamedValueTable(LootEditNodeTypeDto node, LootEditConditionDto c) + { + if (!node.NamedValues || node.KeyTable != "long" || c.Lines.Count < 2 || _valueTables.Count == 0) return null; + return TryWhole(c.Lines[1], out int key) && _valueTables.TryGetValue(key, out ValueTable? t) ? t : null; + } + + /// <summary> + /// The value line picked by name ("Light Weapons (45)"); a number not in the + /// list shows as "value N". "Other number..." opens the raw lines to type any value. + /// </summary> + private void ValuePicker(LootEditConditionDto c, int cond, ValueTable table, Vector2 p, float w, float h, bool ro) + { + if (c.Lines.Count == 0) return; + string raw = c.Lines[0].Trim(); + int sel = TryWhole(raw, out int value) ? Array.IndexOf(table.Ids, value) : -1; + string shown = sel >= 0 ? table.Items[sel] : "value " + raw; + if (PickerButton("##valpick", shown, p, w, h, ro)) + { + LootEditConditionDto target = c; + _picker.Open(new Vector2(p.X, p.Y + h), table.Items, sel, k => + { + if (k >= table.Ids.Length) { _rawShown.Add(cond); return; } // Other number... + if (target.Lines.Count > 0) target.Lines[0] = table.Ids[k].ToString(CultureInfo.InvariantCulture); + ClearFields(); + }, Math.Max(220, w)); + } + string tip = sel >= 0 ? table.Items[sel] : "Not in the list: pick \"" + OtherNumber + "\" to type any number"; + if (table.Flags) tip += "\nFlags: other combinations are typed as a number"; + ImGuiNET.ImGui.SetItemTooltip(tip); + } + + /// <summary>A whole number: "45", "45.0" (a buffed-long value written as a double).</summary> + private static bool TryWhole(string? raw, out int value) + { + string s = (raw ?? string.Empty).Trim(); + if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) return true; + if (double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) + && d == Math.Floor(d) && d >= int.MinValue && d <= int.MaxValue) + { + value = (int)d; + return true; + } + value = 0; + return false; + } + + /// <summary>A button that opens a picker (a caret on the right). True when clicked.</summary> + private static bool PickerButton(string id, string text, Vector2 p, float w, float h, bool disabled) + { + bool clicked = Button(id, text, p, new Vector2(w, h), disabled ? Mute : Text, BtnFill, !disabled, leftAlign: true); + if (!disabled) + PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown, + new Vector2(p.X + w - 16, p.Y), new Vector2(14, h), Mute); + return clicked; + } + + private FieldBuffer FieldFor(int cond, int line) + { + if (!_fields.TryGetValue((cond, line), out FieldBuffer? buf)) + _fields[(cond, line)] = buf = new FieldBuffer(); + return buf; + } + + /// <summary>A text box bound to <paramref name="value"/>. True (with the new text) when it was typed in.</summary> + private static bool Field(string id, FieldBuffer buf, string value, Vector2 pos, float width, string hint, bool ro, out string typed, float height) + { + if (!buf.Active && !ReferenceEquals(buf.Shown, value)) + { + WriteUtf8(buf.Bytes, value); + buf.Shown = value; + } + bool edited = TextBox(id, buf.Bytes, pos, width, hint, out buf.Active, + ro ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None, height); + if (edited && !ro) + { + typed = Utf8(buf.Bytes); + buf.Shown = typed; + return true; + } + typed = value; + return false; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs new file mode 100644 index 0000000..840d2ec --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs @@ -0,0 +1,577 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/LuaFace.cs +// ImGui face of the Lua panel. Two layouts, picked by the payload: +// +// RynthLua v2 (ScriptInfos present), tabs "Scripts" | "Editor", and on the +// right "N running · RynthAi: loaded / not loaded": +// Scripts one row per script: running dot, name, description, autostart +// (Off / global / this character), Run|Stop, Restart. Click a row +// to select it; below, the selected script's state, "Open in +// editor", its console (Copy, Clear) and a line that runs Lua +// inside it (execin). +// Editor status + Run/Stop for the editor's script (the name box, else +// "editor"), name + Save/New/Delete, the coloured editor +// (CodeEditor, Lua) and the selected script's console. +// Old single-script payload (RynthAi's exports) or no plugin: the v1 face, +// status + Run/Stop, script buttons (click to open), name row, editor, +// console; "Lua: RynthLua not connected" until a plugin answers. +// +// Data: UiSources.Lua (hub) and LuaCommands. The editor takes a script when +// the plugin reports a new load (LoadSeq); on first open it restores the +// plugin's last script only if the editor is empty. Text leaves the editor +// only on Run/Save. The payload's Console is the selected script's. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class LuaFace : IImGuiPanel +{ + public const string Title = "Lua"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(420, 560), new Vector2(380, 360), EdgeToEdge: true, GripInBody: true), + () => new LuaFace()); + + private static readonly uint ConsoleBg = RynthTheme.Argb(0xFF05090D), DotOff = RynthTheme.Argb(0xFF4D5A66); + + private const string NotConnected = "Lua: RynthLua not connected"; + /// <summary>RynthLua's description for a running script that has no file (the editor, /lua exec).</summary> + private const string NotSaved = "(not saved)"; + private const float RowH = 26; + + private static readonly string[] AutoCodes = { "none", "global", "character" }; + private static readonly string[] AutoItems = { "Off", "Every character (global)", "This character" }; + + private LuaPayload? _data; + private long _seenVersion = -1; + private int _lastLoadSeq = -1, _lastConsoleSeq = -1; + private string _lastSelected = string.Empty; + private bool _firstFetch = true, _scrollConsole; + private string _status = NotConnected; + private bool _running; + private string _note = string.Empty; // local hint ("Type a script name first.") + private bool _editorTab; + private string _editorSelectSent = string.Empty; // Editor tab: last "select" sent for its script + private bool _focusExec; + + private readonly byte[] _name = new byte[128]; + private readonly byte[] _exec = new byte[1024]; + private readonly Picker _picker = new("##lua_pick"); + private CodeEditor? _editor; + + public void OnShown() + { + UiSources.Lua.Subscribe(); + UiSources.Lua.RequestRefresh(); + } + + public void OnHidden() + { + UiSources.Lua.Unsubscribe(); + _editor?.Dispose(); + _editor = null; + } + + public void Draw() + { + _editor ??= new CodeEditor("##lua_source", CodeLanguage.Lua, CodeEditor.RynthPalette()); + TakeSnapshot(); + + float w = Begin(out Vector2 origin, out Vector2 size); + LuaPayload? d = _data; + if (d?.ScriptInfos is { } infos) + { + Header(w, d); + if (_editorTab) EditorView(w, origin, size, d, infos); + else ScriptsView(w, origin, size, d, infos); + } + else + LegacyView(w, origin, size); + End(origin, size); + _picker.Draw(); + } + + private void TakeSnapshot() + { + var snap = UiSources.Lua.Current; + if (snap == null) + { + // Plugins unloaded (RL): back to "not connected" until one answers again. + if (_data != null) + { + _data = null; + _seenVersion = -1; + _running = false; + _status = NotConnected; + } + return; + } + if (snap.Version == _seenVersion) return; + _seenVersion = snap.Version; + LuaPayload d = _data = snap.Value; + + _running = d.Running; + _status = d.Running + ? $"Running: {(d.ScriptName.Length > 0 ? d.ScriptName : "(editor)")}" + : d.Status.Length > 0 ? d.Status : "Lua: idle"; + + // A newly loaded script goes into the editor; on first open only if it's empty. + if (d.LoadSeq != _lastLoadSeq) + { + bool take = !_firstFetch || _editor!.GetText().Length == 0; + _lastLoadSeq = d.LoadSeq; + if (take) + { + _editor!.SetText(d.LoadedText); + WriteUtf8(_name, d.LoadedName); + } + } + string selected = d.Selected ?? string.Empty; + if (d.ConsoleSeq != _lastConsoleSeq || selected != _lastSelected) + { + _lastConsoleSeq = d.ConsoleSeq; + _lastSelected = selected; + _scrollConsole = true; + _note = string.Empty; + } + _firstFetch = false; + } + + private const string ScriptsTab = PhosphorIcons.Files + " Scripts", EditorTab = PhosphorIcons.PencilSimple + " Editor"; + private const string RunLabel = PhosphorIcons.Play + " Run", StopLabel = PhosphorIcons.Stop + " Stop", + RestartLabel = PhosphorIcons.ArrowCounterClockwise + " Restart"; + + // ── v2: header ─────────────────────────────────────────────────────── + + // [Scripts][Editor] N running · RynthAi: loaded + private void Header(float w, LuaPayload d) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float h = 24; + float sw = ButtonWidth(ScriptsTab) + 4, ew = ButtonWidth(EditorTab) + 4; + if (Button("##tab_scripts", ScriptsTab, p, new Vector2(sw, h), _editorTab ? Text : Teal, _editorTab ? BtnFill : Selected)) + _editorTab = false; + if (Button("##tab_editor", EditorTab, new Vector2(p.X + sw + 2, p.Y), new Vector2(ew, h), _editorTab ? Teal : Text, _editorTab ? Selected : BtnFill)) + _editorTab = true; + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + bool ai = d.RynthAi == true; + string run = d.RunningCount == 1 ? "1 running" : $"{d.RunningCount} running"; + const string sep = " · "; + string aiText = ai ? "RynthAi: loaded" : "RynthAi: not loaded"; + float runW = ImGuiNET.ImGui.CalcTextSize(run).X, sepW = ImGuiNET.ImGui.CalcTextSize(sep).X, aiW = ImGuiNET.ImGui.CalcTextSize(aiText).X; + float left = p.X + sw + ew + 10, right = p.X + w; + float x = Math.Max(left, right - runW - sepW - aiW); + float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.PushClipRect(new Vector2(left, p.Y), new Vector2(right, p.Y + h), true); + dl.AddText(new Vector2(x, ty), d.RunningCount > 0 ? Green : Mute, run); + dl.AddText(new Vector2(x + runW, ty), Mute, sep); + dl.AddText(new Vector2(x + runW + sepW, ty), ai ? Green : Amber, aiText); + dl.PopClipRect(); + if (ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x + runW + sepW, p.Y), new Vector2(right, p.Y + h))) + ImGuiNET.ImGui.SetTooltip(ai + ? "RynthAi's script interface is there: scripts can use its macro, nav and meta features." + : "RynthAi isn't loaded (or is too old): scripts' RynthAi calls won't work."); + NextLine(p, h + 2); + } + + // ── v2: Scripts tab ────────────────────────────────────────────────── + + private void ScriptsView(float w, Vector2 origin, Vector2 size, LuaPayload d, List<LuaScriptInfo> infos) + { + string sel = d.Selected ?? string.Empty; + ScriptList(w, Remaining(origin, size), infos, sel); + LuaScriptInfo? si = Find(infos, sel); + SelectedRow(w, d, sel, si); + + // Console, then the exec line: Dummy+header (30) + child + spacing (4) + line (22). + float consoleH = Math.Max(40, Remaining(origin, size) - 56); + Console(w, consoleH, sel.Length > 0 ? "Console · " + sel : "Console"); + ExecRow(w, sel, si?.Running == true); + } + + private void ScriptList(float w, float avail, List<LuaScriptInfo> infos, string selected) + { + int n = infos.Count; + float listMax = Math.Max(RowH * 2 + 4, avail * 0.42f); + float listH = Math.Clamp(Math.Max(1, n) * RowH + 4, RowH + 4, listMax); + + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + ImGuiNET.ImGui.BeginChild("##lua_list", new Vector2(w, listH), ImGuiChildFlags.Borders | ImGuiChildFlags.AlwaysUseWindowPadding); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + float rw = ImGuiNET.ImGui.GetContentRegionAvail().X; + if (n == 0) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.GetWindowDrawList().AddText(p + new Vector2(8, (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, + "No scripts yet: write one in the Editor tab and Save."); + ImGuiNET.ImGui.Dummy(new Vector2(rw, RowH)); + } + for (int i = 0; i < n; i++) + { + ImGuiNET.ImGui.PushID(i); + ScriptRow(infos[i], i, rw, selected); + ImGuiNET.ImGui.PopID(); + } + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + } + + // (dot) Name description ........ [Auto: off] [Run] [Restart] + private void ScriptRow(LuaScriptInfo info, int index, float w, string selected) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + bool isSel = info.Name.Equals(selected, StringComparison.OrdinalIgnoreCase); + bool notSaved = IsNotSaved(info); + const float autoW = 74, runW = 50, restartW = 64, gap = 3; + float nameW = Math.Max(40, w - (autoW + runW + restartW + gap * 3 + 2)); + + dl.AddRectFilled(p, p + new Vector2(w, RowH), isSel ? Selected : index % 2 == 0 ? RowAlt : PanelBg); + ImGuiNET.ImGui.SetCursorScreenPos(p); + if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(nameW, RowH)) && !isSel) + LuaCommands.Send("select", info.Name); + if (ImGuiNET.ImGui.IsItemHovered()) + { + if (!isSel) dl.AddRectFilled(p, p + new Vector2(nameW, RowH), BtnFill); + ImGuiNET.ImGui.SetTooltip(RowTooltip(info, notSaved)); + } + if (isSel) dl.AddRectFilled(p, p + new Vector2(2, RowH), Teal); + + float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.AddCircleFilled(new Vector2(p.X + 11, p.Y + RowH * 0.5f), 4, info.Running ? Green : DotOff); + dl.PushClipRect(p, p + new Vector2(nameW - 4, RowH), true); + dl.AddText(new Vector2(p.X + 21, ty), isSel ? Teal : Text, info.Name); + if (info.Description.Length > 0) + dl.AddText(new Vector2(p.X + 21 + ImGuiNET.ImGui.CalcTextSize(info.Name).X + 8, ty), Faded(Mute), info.Description); + dl.PopClipRect(); + + float x = p.X + nameW, by = p.Y + 3, bh = RowH - 6; + bool auto = info.Autostart is "global" or "character"; + if (Button("##auto", AutoLabel(info.Autostart), new Vector2(x, by), new Vector2(autoW, bh), auto ? Teal : Mute, BtnFill, enabled: !notSaved)) + { + string name = info.Name; + // Before login there's no character to autostart for: only off / global. + string[] items = _data?.LoggedIn == false ? AutoItems[..2] : AutoItems; + _picker.Open(new Vector2(x, by + bh + 2), items, Array.IndexOf(AutoCodes, info.Autostart), + k => LuaCommands.Send("autostart", name, AutoCodes[k]), 190); + } + ImGuiNET.ImGui.SetItemTooltip(notSaved + ? "Save it to a file to autostart it." + : "Start at login: off, on every character (global), or on this character only."); + x += autoW + gap; + if (info.Running) + { + if (Button("##run", StopLabel, new Vector2(x, by), new Vector2(runW, bh), Text, StopBg)) + LuaCommands.Send("stopScript", info.Name); + } + else if (Button("##run", RunLabel, new Vector2(x, by), new Vector2(runW, bh), Text, StartBg, enabled: !notSaved)) + LuaCommands.Send("start", info.Name); + x += runW + gap; + if (Button("##restart", RestartLabel, new Vector2(x, by), new Vector2(restartW, bh), Text, BtnFill, enabled: info.Running && !notSaved)) + LuaCommands.Send("restart", info.Name); + ImGuiNET.ImGui.SetItemTooltip(notSaved ? "Not saved: run it again from the Editor." : "Stop it and start it again from its file."); + NextLine(p, RowH); + } + + private static bool IsNotSaved(LuaScriptInfo info) => info.Transient || info.Description == NotSaved; + + private static string RowTooltip(LuaScriptInfo info, bool notSaved) + { + string kind = notSaved ? "Not saved (the editor or /lua exec)" + : info.IsFolder ? $"Folder script ({info.Name}\\index.lua)" : $"Single file ({info.Name}.lua)"; + string desc = notSaved || info.Description.Length == 0 ? string.Empty : info.Description + "\n"; + return $"{info.Name}\n{desc}{kind}\nClick to show its console."; + } + + private static string AutoLabel(string autostart) => autostart switch + { + "global" => "Auto: all", + "character" => "Auto: char", + _ => "Auto: off", + }; + + // name running | stopped (status) [Open in editor] + private void SelectedRow(float w, LuaPayload d, string sel, LuaScriptInfo? si) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float h = 22; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + if (sel.Length == 0) + { + dl.AddText(p + new Vector2(0, (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "Click a script to see its console."); + NextLine(p, h); + return; + } + const string open = PhosphorIcons.PencilSimple + " Open in editor"; + float bw = ButtonWidth(open); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + ImGuiNET.ImGui.PushFont(bold); + float nameW = ImGuiNET.ImGui.CalcTextSize(sel).X; + ImGuiNET.ImGui.PopFont(); + bool running = si?.Running == true; + string state = running ? "running" + : d.ScriptName.Equals(sel, StringComparison.OrdinalIgnoreCase) && d.Status.Length > 0 ? d.Status : "stopped"; + dl.PushClipRect(p, p + new Vector2(w - bw - 6, h), true); + dl.AddText(bold, bold.FontSize, p + new Vector2(0, (h - bold.FontSize) * 0.5f), Teal, sel); + dl.AddText(p + new Vector2(nameW + 10, (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), running ? Green : Amber, state); + dl.PopClipRect(); + bool canOpen = si != null && !IsNotSaved(si); + if (Button("##open", open, new Vector2(p.X + w - bw, p.Y), new Vector2(bw, h), Text, BtnFill, enabled: canOpen)) + { + LuaCommands.Send("load", sel); + _editorTab = true; + } + ImGuiNET.ImGui.SetItemTooltip(canOpen + ? (si!.IsFolder ? "Edit its index.lua in the Editor tab." : "Edit it in the Editor tab.") + : "It has no file to open."); + NextLine(p, h); + } + + // [Lua to run inside <script>...] [Exec] + private void ExecRow(float w, string sel, bool canExec) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float bw = 50; + string hint = sel.Length == 0 ? "Select a script to run code in it" + : canExec ? $"Lua to run inside {sel} (Enter)" : $"Start {sel} to run code in it"; + if (_focusExec) + { + ImGuiNET.ImGui.SetKeyboardFocusHere(); + _focusExec = false; + } + // The row sits on the body's bottom edge: it stops short of the resize grip (GripInBody). + float grip = ImGuiPanelHost.BodyGripReserve; + bool enter = TextBox("##lua_exec", _exec, p, w - bw - 4 - grip, hint, out _, ImGuiInputTextFlags.EnterReturnsTrue); + bool click = Button("##exec", "Exec", new Vector2(p.X + w - bw - grip, p.Y), new Vector2(bw, 22), Text, BtnFill, enabled: canExec); + ImGuiNET.ImGui.SetItemTooltip("Runs the line inside the selected script: its globals, its state."); + if ((enter || click) && canExec) + { + string code = Utf8(_exec).Trim(); + if (code.Length > 0) + { + LuaCommands.Send("execin", sel, code); + _exec[0] = 0; + } + _focusExec = enter; // Enter leaves the box; keep typing in it + } + NextLine(p, 22); + } + + // ── v2: Editor tab ─────────────────────────────────────────────────── + + private void EditorView(float w, Vector2 origin, Vector2 size, LuaPayload d, List<LuaScriptInfo> infos) + { + // RynthLua runs the editor text as a script named by the name box, else "editor". + string edName = Utf8(_name).Trim(); + string runName = edName.Length > 0 ? edName : "editor"; + LuaScriptInfo? ei = Find(infos, runName); + bool running = ei?.Running == true; + // Always say which script the editor holds: the Scripts tab's selection doesn't change it + // (only "Open in editor" does), so the name here is the one Run/Save act on. + string editing = "Editing: " + runName + (_editor?.IsDirty == true ? " (unsaved)" : ""); + string status = running ? editing + " · running" + : d.ScriptName.Equals(runName, StringComparison.OrdinalIgnoreCase) && d.Status.Length > 0 ? editing + " · " + d.Status + : editing; + + // The console below follows the editor's script, not whatever was last clicked on the + // Scripts tab. Select it once per change of name (selecting also moves the Scripts tab). + if (ei != null && !runName.Equals(d.Selected ?? string.Empty, StringComparison.OrdinalIgnoreCase) + && !runName.Equals(_editorSelectSent, StringComparison.OrdinalIgnoreCase)) + { + LuaCommands.Send("select", ei.Name); + _editorSelectSent = runName; + } + else if (runName.Equals(d.Selected ?? string.Empty, StringComparison.OrdinalIgnoreCase)) + _editorSelectSent = string.Empty; + + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + const float bw = 64; + float statusW = w - 2 * (bw + 4); + dl.PushClipRect(p, p + new Vector2(statusW, 24), true); + dl.AddText(bold, bold.FontSize, p + new Vector2(0, (24 - bold.FontSize) * 0.5f), running ? Green : Amber, status); + dl.PopClipRect(); + if (Button("##run", RunLabel, new Vector2(p.X + statusW + 4, p.Y), new Vector2(bw, 24), Text, StartBg)) + LuaCommands.Send("run", edName, _editor?.GetText() ?? string.Empty); + ImGuiNET.ImGui.SetItemTooltip("Run the editor's text as " + runName + " (replaces a running copy)."); + if (Button("##stop", StopLabel, new Vector2(p.X + statusW + bw + 8, p.Y), new Vector2(bw, 24), Text, StopBg, enabled: running)) + LuaCommands.Send("stopScript", runName); + NextLine(p, 24); + + bool folder = ei?.IsFolder == true; + NameRow(w, canDelete: !folder, saveTip: folder ? "Saves its index.lua." : null, + deleteTip: folder ? "Folder scripts are deleted in Explorer." : "Renames it to .lua.bak."); + EditorAndConsole(w, origin, size, 120, ei != null ? "Console · " + ei.Name + : d.Selected is { Length: > 0 } s ? "Console · " + s : "Console"); + } + + // ── v1: old single-script payload / not connected ──────────────────── + + private void LegacyView(float w, Vector2 origin, Vector2 size) + { + TopRow(w); + Scripts(w); + NameRow(w, canDelete: true, saveTip: null, deleteTip: null); + EditorAndConsole(w, origin, size, 150, "Console"); + } + + // Status | Run Stop + private void TopRow(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + const float bw = 64; + float statusW = w - 2 * (bw + 4); + dl.PushClipRect(p, p + new Vector2(statusW, 24), true); + dl.AddText(bold, bold.FontSize, p + new Vector2(0, (24 - bold.FontSize) * 0.5f), _running ? Green : Amber, _status); + dl.PopClipRect(); + if (Button("##run", RunLabel, new Vector2(p.X + statusW + 4, p.Y), new Vector2(bw, 24), Text, StartBg)) + LuaCommands.Send("run", Utf8(_name).Trim(), _editor?.GetText() ?? string.Empty); + if (Button("##stop", StopLabel, new Vector2(p.X + statusW + bw + 8, p.Y), new Vector2(bw, 24), Text, StopBg)) + LuaCommands.Send("stop"); + NextLine(p, 24); + } + + // "Scripts (click to open):" then one button per script, wrapping. + private void Scripts(float w) + { + Label("Scripts (click to open):", Mute); + var scripts = _data?.Scripts; + if (scripts == null || scripts.Count == 0) + { + Label("(none yet: write one and Save)", Mute); + return; + } + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + float x = start.X, y = start.Y; + for (int i = 0; i < scripts.Count; i++) + { + string s = scripts[i]; + float bw = ButtonWidth(s); + if (x > start.X && x + bw > start.X + w) { x = start.X; y += 26; } + ImGuiNET.ImGui.PushID(i); + if (Button("##s", s, new Vector2(x, y), new Vector2(bw, 22), Text, BtnFill)) + LuaCommands.Send("load", s); + ImGuiNET.ImGui.PopID(); + x += bw + 4; + } + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(start.X, y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + // ── Shared pieces ──────────────────────────────────────────────────── + + // [name] Save New Delete + private void NameRow(float w, bool canDelete, string? saveTip, string? deleteTip) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float bw = 58; + float boxW = w - 3 * (bw + 4); + TextBox("##lua_name", _name, p, boxW, "Script name...", out _); + + float x = p.X + boxW + 4; + if (Button("##save", PhosphorIcons.FloppyDisk + " Save", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill)) + { + string name = Utf8(_name).Trim(); + if (name.Length == 0) _note = "Type a script name first."; + else + { + LuaCommands.Send("save", name, _editor?.GetText() ?? string.Empty); + _editor?.MarkClean(); + } + } + if (saveTip != null) ImGuiNET.ImGui.SetItemTooltip(saveTip); + x += bw + 4; + if (Button("##new", PhosphorIcons.FilePlus + " New", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill)) + { + _editor?.SetText(string.Empty); + Array.Clear(_name); + } + x += bw + 4; + if (Button("##delete", PhosphorIcons.Trash + " Delete", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill, enabled: canDelete)) + { + string name = Utf8(_name).Trim(); + if (name.Length > 0) LuaCommands.Send("delete", name); + } + if (deleteTip != null) ImGuiNET.ImGui.SetItemTooltip(deleteTip); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + // The editor takes what the console leaves. + private void EditorAndConsole(float w, Vector2 origin, Vector2 size, float consoleH, string consoleTitle) + { + // The console below scrolls: the pair ends above the resize grip (GripInBody). + float editorH = Math.Max(80, Remaining(origin, size) - consoleH - 34 - GripOverlap()); + if (!CodeEditor.Available) + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE04848), "The script editor needs the new cimgui.dll (a full RynthCore deploy)."); + else + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Code12)); + _editor!.Render(new Vector2(w, editorH)); + ImGuiNET.ImGui.PopFont(); + } + Console(w, consoleH, consoleTitle); + } + + // Console [Copy] [Clear], then the output (green, wrapped, follows new lines). + private void Console(float w, float height, string title) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.PushClipRect(p, p + new Vector2(w - 122, 22), true); + dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, title); + dl.PopClipRect(); + if (Button("##copy", PhosphorIcons.Copy + " Copy", new Vector2(p.X + w - 116, p.Y), new Vector2(56, 22), Text, BtnFill)) + ImGuiNET.ImGui.SetClipboardText(_data?.Console ?? string.Empty); + if (Button("##clear", PhosphorIcons.Eraser + " Clear", new Vector2(p.X + w - 56, p.Y), new Vector2(56, 22), Text, BtnFill)) + LuaCommands.Send("clearConsole"); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 24)); + + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, ConsoleBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4)); + ImGuiNET.ImGui.BeginChild("##lua_console", new Vector2(w, height), ImGuiChildFlags.Borders | ImGuiChildFlags.AlwaysUseWindowPadding); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono10)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Green); + ImGuiNET.ImGui.PushTextWrapPos(0); + string text = _data?.Console ?? string.Empty; + if (text.Length > 0) ImGuiNET.ImGui.TextUnformatted(text); + if (_note.Length > 0) ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "[panel] " + _note); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopFont(); + if (_scrollConsole) + { + ImGuiNET.ImGui.SetScrollHereY(1f); + _scrollConsole = false; + } + ImGuiNET.ImGui.EndChild(); + } + + private static LuaScriptInfo? Find(List<LuaScriptInfo> infos, string name) + { + if (name.Length == 0) return null; + foreach (LuaScriptInfo i in infos) + if (i.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return i; + return null; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs new file mode 100644 index 0000000..d87fc87 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs @@ -0,0 +1,457 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/MetaFace.Schedule.cs +// The Meta panel's Schedule view: RynthAi's Meta Manager, which loads a meta +// when a timer runs out (RynthSuite Docs/META_MANAGER.md). +// +// [x Manager] Poll [5] min [poll now] Wait [60] s Gap [30] s [x While stopped] +// 34 quests, polled 2m ago . last: farm.af (quest x ready) +// # [on] [up][dn] [edit][del] when quest x ready -> farm.af ready | 12m 30s +// ... +// [+ New Rule] first match: amber edge +// +// Data: the "schedule" object of the Meta snapshot (UiSources.Meta). Every +// change is an mm_* MetaCommand, applied by RynthAi on its tick; nothing here +// loads a meta or sends chat. Times are absolute (unix ms) in the snapshot, +// so the countdowns tick here between snapshots. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class MetaFace +{ + private const string ScheduleLabel = PhosphorIcons.HourglassMedium + " Schedule##mode_sch"; + + private static readonly string[] TriggerNames = + { + "Quest ready (/myquests timer)", "After N minutes on the meta", "Every N minutes", "Countdown (you start it)", + }; + + // Rule editor: -2 closed, -1 new rule, else the rule's index. + private int _schedEdit = -2; + private ScheduleRuleDto _schedRule = new(); + private readonly byte[] _schedQuest = new byte[128]; + private readonly byte[] _schedMinutes = new byte[16]; + private readonly byte[] _schedPoll = new byte[8], _schedWait = new byte[8], _schedGap = new byte[8]; + private long _schedFieldsVersion = -1; // snapshot the number boxes were last filled from + private string[] _schedMetaPicks = Array.Empty<string>(), _schedOnlyPicks = Array.Empty<string>(); + + private void ShowSchedule() + { + _view = View.Schedule; + _schedEdit = -2; + } + + private void ScheduleView(Vector2 origin, Vector2 size) + { + float w = size.X; + SchedulePayload? sc = _data.Schedule; + ModeRow(w, source: false, schedule: true); + Separator(w); + if (sc == null) + { + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " This RynthAi has no Meta Manager (update RynthAi)."); + return; + } + + RefreshScheduleFields(sc); + if (_schedEdit != -2) + { + ScheduleEditor(sc, size.Y - (ImGuiNET.ImGui.GetCursorScreenPos().Y - origin.Y) - FaceKit.GripOverlap()); + return; + } + + ScheduleSettings(sc, w); + ScheduleStatusLine(sc, w); + Separator(w); + + const float bottomH = 24; + float listH = Math.Max(40, origin.Y + size.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - bottomH - 9); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0)); + ImGuiNET.ImGui.BeginChild("##sched_rules", new Vector2(w, listH)); + ScheduleRules(sc, ImGuiNET.ImGui.GetContentRegionAvail().X); + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + + Separator(w); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float newW = 80; + if (Button(PhosphorIcons.Plus + " New Rule##sched_new", new Vector2(p.X, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green)) + OpenScheduleEditor(-1, new ScheduleRuleDto { Meta = FirstMetaFile() }); + if (sc.Rules.Count > 0) + { + if (Button(PhosphorIcons.ArrowCounterClockwise + " Re-arm all##sched_reset", new Vector2(p.X + newW + 4, p.Y), new Vector2(86, 24), + Mute, BtnFill, BtnBord)) + MetaCommands.Simple("mm_reset", -1); + ImGuiNET.ImGui.SetItemTooltip("Clear every rule's fired / error / holding state"); + } + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 24)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + /// <summary>Refill the number boxes from a new snapshot (not while one is being typed in).</summary> + private void RefreshScheduleFields(SchedulePayload sc) + { + long v = UiSources.Meta.Current?.Version ?? 0; + if (v == _schedFieldsVersion || ImGuiNET.ImGui.IsAnyItemActive()) return; + _schedFieldsVersion = v; + WriteUtf8(_schedPoll, sc.PollMinutes.ToString(CultureInfo.InvariantCulture)); + WriteUtf8(_schedWait, sc.MaxWaitSeconds.ToString(CultureInfo.InvariantCulture)); + WriteUtf8(_schedGap, sc.MinGapSeconds.ToString(CultureInfo.InvariantCulture)); + var metas = new List<string>(); + foreach (MetaFile f in _data.Files) + if (!string.IsNullOrEmpty(f.Path)) metas.Add(System.IO.Path.GetFileName(f.Path)); + _schedMetaPicks = metas.ToArray(); + var only = new List<string> { "(any meta)" }; + only.AddRange(metas); + _schedOnlyPicks = only.ToArray(); + } + + private string FirstMetaFile() => _schedMetaPicks.Length > 0 ? _schedMetaPicks[0] : string.Empty; + + // [x Manager] Poll [5] min [poll now] | Wait [60] s Gap [30] s [x While stopped] + private void ScheduleSettings(SchedulePayload sc, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float x = p.X; + if (Toggle((sc.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " Manager##sched_on", ref x, p.Y, sc.Enabled)) + { + sc.Enabled = !sc.Enabled; // shows at once; the next snapshot confirms + MetaCommands.Simple("mm_enabled", value: sc.Enabled ? "true" : "false"); + } + ImGuiNET.ImGui.SetItemTooltip("Off by default. While on, it loads the first due rule's meta (also /ra metamgr on|off)."); + x += 4; + NumberField("Poll", "##sched_poll", _schedPoll, "min", ref x, p.Y, 30, "How often it sends /myquests (minimum 1). Only while on and with a quest rule.", + n => { if (n >= 1) MetaCommands.Simple("mm_poll_minutes", value: n.ToString(CultureInfo.InvariantCulture)); }); + if (IconButton("##sched_pollnow", PhosphorIcons.ArrowsClockwise, new Vector2(x, p.Y), new Vector2(24, 22), TextDim, BtnFill, BtnBord, + enabled: sc.Enabled)) + MetaCommands.Simple("mm_poll_now"); + ImGuiNET.ImGui.SetItemTooltip("Check /myquests now"); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + + Vector2 q = ImGuiNET.ImGui.GetCursorScreenPos(); + x = q.X; + NumberField("Wait up to", "##sched_wait", _schedWait, "s", ref x, q.Y, 34, + "A switch waits until the bot is not fighting, looting, buffing or in a portal - at most this long, then it switches anyway.", + n => MetaCommands.Simple("mm_max_wait", value: Math.Max(0, n).ToString(CultureInfo.InvariantCulture))); + NumberField("Gap", "##sched_gap", _schedGap, "s", ref x, q.Y, 34, "At least this long between two switches.", + n => MetaCommands.Simple("mm_min_gap", value: Math.Max(0, n).ToString(CultureInfo.InvariantCulture))); + if (Toggle((sc.AllowWhileStopped ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " While stopped##sched_stopped", ref x, q.Y, + sc.AllowWhileStopped)) + { + sc.AllowWhileStopped = !sc.AllowWhileStopped; + MetaCommands.Simple("mm_allow_stopped", value: sc.AllowWhileStopped ? "true" : "false"); + } + ImGuiNET.ImGui.SetItemTooltip("Also switch metas while the macro is stopped (off: it waits for the macro to run)."); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(q.X, q.Y + 24)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + /// <summary>"Label [box] unit" at (x, y); commits a whole number when the box loses focus after an edit.</summary> + private static void NumberField(string label, string id, byte[] buf, string unit, ref float x, float y, float boxW, string tip, Action<int> commit) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float fy = y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.AddText(new Vector2(x, fy), Mute, label); + x += ImGuiNET.ImGui.CalcTextSize(label).X + 4; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); + TextBox(id, buf, boxW, "", ImGuiInputTextFlags.CharsDecimal, out _); + bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); + ImGuiNET.ImGui.SetItemTooltip(tip); + if (done && int.TryParse(Utf8(buf).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) + commit(n); + x += boxW + 3; + dl.AddText(new Vector2(x, fy), Mute, unit); + x += ImGuiNET.ImGui.CalcTextSize(unit).X + 8; + } + + private void ScheduleStatusLine(SchedulePayload sc, float w) + { + long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + string poll = !sc.Enabled ? "Off - nothing is loaded or polled." + : sc.ServerDisabled ? "The server has /myquests turned off: quest rules can't fire." + : !sc.Polling ? "No quest rules: /myquests is not polled." + : sc.LastPollMs == 0 ? "Waiting for the first /myquests." + : $"{sc.QuestCount} quest timer(s), /myquests {Span(now - sc.LastPollMs)} ago."; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(sc.ServerDisabled ? 0xFFE8B333 : 0xFFC8D6E4), Fit(poll, w)); + if (sc.LastSwitch.Length > 0) + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), + Fit($"Last: {sc.LastSwitch}{(sc.LastSwitchMs > 0 ? $", {Span(now - sc.LastSwitchMs)} ago" : "")}", w)); + ImGuiNET.ImGui.PopFont(); + } + + private void ScheduleRules(SchedulePayload sc, float w) + { + if (sc.Rules.Count == 0) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " No rules. New Rule: when a timer runs out, load a meta."); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " The first due rule (top to bottom) wins."); + return; + } + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + const float h = 20; + for (int i = 0; i < sc.Rules.Count; i++) + { + ScheduleRuleDto r = sc.Rules[i]; + bool first = i == sc.FirstMatch && sc.Enabled; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddRectFilled(p, p + new Vector2(w, h), i % 2 == 0 ? PanelBg : RowAlt); + ImGuiNET.ImGui.PushID(1000 + i); + bool changed = false; + float x = p.X + 1; + + dl.AddText(new Vector2(x + 2, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, (i + 1).ToString(CultureInfo.InvariantCulture)); + x += 16; + if (IconButton("##en", r.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square, new Vector2(x, p.Y + 2), new Vector2(14, 16), + r.Enabled ? Green : Mute, BtnFill, BtnBord)) + { + r.Enabled = !r.Enabled; + MetaCommands.Simple("mm_rule_enabled", i, r.Enabled ? "true" : "false"); + } + ImGuiNET.ImGui.SetItemTooltip(r.Enabled ? "On - click to turn this rule off" : "Off - click to turn it on"); + x += 16; + if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord, enabled: i > 0)) + { + MetaCommands.Simple("mm_move", i, "-1"); + (sc.Rules[i], sc.Rules[i - 1]) = (sc.Rules[i - 1], sc.Rules[i]); + changed = true; + } + ImGuiNET.ImGui.SetItemTooltip("Higher priority"); + x += 18; + if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord, + enabled: i < sc.Rules.Count - 1)) + { + MetaCommands.Simple("mm_move", i, "1"); + (sc.Rules[i], sc.Rules[i + 1]) = (sc.Rules[i + 1], sc.Rules[i]); + changed = true; + } + ImGuiNET.ImGui.SetItemTooltip("Lower priority"); + x += 18; + if (r.Trigger == 3) // countdown: start / stop + { + bool running = r.DueAtMs > 0; + if (IconButton("##cd", running ? PhosphorIcons.Stop : PhosphorIcons.Play, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), + running ? Amber : Green, BtnFill, BtnBord)) + MetaCommands.Simple(running ? "mm_countdown_stop" : "mm_countdown_start", i); + ImGuiNET.ImGui.SetItemTooltip(running ? "Stop the countdown" : $"Start the countdown ({Num(r.Minutes)} min)"); + } + else if (r.Fired || (r.State ?? "").StartsWith("error", StringComparison.Ordinal) || (r.State ?? "").Contains("holding")) + { + if (IconButton("##rearm", PhosphorIcons.ArrowCounterClockwise, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Teal, BtnFill, BtnBord)) + MetaCommands.Simple("mm_reset", i); + ImGuiNET.ImGui.SetItemTooltip("Re-arm this rule"); + } + x += 18; + if (IconButton("##del", PhosphorIcons.Trash, new Vector2(x + 1, p.Y + 2), new Vector2(18, 16), TextDim, DelFill, BtnBord)) + { + MetaCommands.Simple("mm_delete", i); + sc.Rules.RemoveAt(i); + changed = true; + } + ImGuiNET.ImGui.SetItemTooltip("Delete rule"); + x += 22; + + // Text: "when TRIGGER, load META" | time left / state; click to edit. + float textW = p.X + w - x; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y)); + bool open = ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(Math.Max(1, textW), h)); + if (ImGuiNET.ImGui.IsItemHovered()) + { + ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + ImGuiNET.ImGui.SetTooltip(RuleTooltip(r, i, first)); + } + ImGuiNET.ImGui.PopID(); + if (changed) return; // the list changed: draw it again next frame + if (open) + { + OpenScheduleEditor(i, r); + return; + } + + (string when, uint whenCol) = WhenText(r, now); + float whenW = ImGuiNET.ImGui.CalcTextSize(when).X; + float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + uint col = r.Enabled ? TextDim : Faded(TextDim); + dl.AddText(new Vector2(x + 3, ty), col, Fit(RuleText(r), Math.Max(10, textW - whenW - 14))); + dl.AddText(new Vector2(p.X + w - whenW - 4, ty), r.Enabled ? whenCol : Faded(whenCol), when); + if (first) dl.AddRect(p, p + new Vector2(w, h), Amber, 2); + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + } + + private static string RuleText(ScheduleRuleDto r) + { + string trig = r.Trigger switch + { + 0 => $"quest {(r.Quest.Length > 0 ? r.Quest : "?")} ready", + 1 => $"{Num(r.Minutes)} min on the meta", + 2 => $"every {Num(r.Minutes)} min", + _ => $"{Num(r.Minutes)} min countdown", + }; + string on = r.OnlyOnMeta.Length > 0 ? $" (on {r.OnlyOnMeta})" : ""; + return $"{trig}{on} {Arrow} {(r.Meta.Length > 0 ? r.Meta : "?")}{(r.Repeat ? "" : " [once]")}"; + } + + private const string Arrow = "->"; + + /// <summary>The right-hand column: the state words, else the time left, "ready" or "never".</summary> + private static (string Text, uint Color) WhenText(ScheduleRuleDto r, long nowMs) + { + string state = r.State ?? string.Empty; + if (state.StartsWith("error", StringComparison.Ordinal)) return ("error", Red); + if (state.StartsWith("waiting", StringComparison.Ordinal)) return (state, Amber); + if (state == "switching") return (state, Amber); + if (r.Fired) return ("fired", Mute); + if (state.Contains("holding")) return ("holding", Teal); + if (state.Length > 0 && r.DueAtMs == 0) return (Short(state), Mute); + if (r.DueAtMs == -1) return ("never", Mute); + if (r.DueAtMs == 0) return ("-", Mute); + long left = r.DueAtMs - nowMs; + return left <= 0 ? ("ready", Green) : (Span(left), TextDim); + } + + private static string Short(string state) => state switch + { + "no /myquests yet" => "no data yet", + "/myquests is off on this server" => "no /myquests", + "not started" => "not started", + _ => state.Length > 18 ? state.Substring(0, 18) + "…" : state, + }; + + private static string RuleTooltip(ScheduleRuleDto r, int i, bool first) + { + var sb = new System.Text.StringBuilder(); + sb.Append("Rule ").Append(i + 1).Append(": ").Append(TriggerNames[Math.Clamp(r.Trigger, 0, 3)]).Append('\n'); + if (r.Trigger == 0) sb.Append("Quest: ").Append(r.Quest.Length > 0 ? r.Quest : "(none)").Append('\n'); + else sb.Append("Minutes: ").Append(Num(r.Minutes)).Append('\n'); + sb.Append("Loads: ").Append(r.Meta.Length > 0 ? r.Meta : "(none)").Append('\n'); + if (r.OnlyOnMeta.Length > 0) sb.Append("Only while on: ").Append(r.OnlyOnMeta).Append('\n'); + sb.Append(r.Repeat ? "Repeats" : "Once (one-shot)"); + if (r.FireCount > 0) sb.Append(", fired ").Append(r.FireCount).Append("x this session"); + if (!string.IsNullOrEmpty(r.State)) sb.Append('\n').Append(r.State); + if (first) sb.Append("\nFirst match: this rule fires next."); + sb.Append("\nClick to edit."); + return sb.ToString(); + } + + // ── Rule editor ───────────────────────────────────────────────────── + + private void OpenScheduleEditor(int index, ScheduleRuleDto r) + { + _schedEdit = index; + _schedRule = r.CloneSettings(); + WriteUtf8(_schedQuest, _schedRule.Quest); + WriteUtf8(_schedMinutes, Num(_schedRule.Minutes)); + } + + private void ScheduleEditor(SchedulePayload sc, float height) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0); + ImGuiNET.ImGui.BeginChild("##sched_editor", new Vector2(0, Math.Max(60, height))); + ImGuiNET.ImGui.PopStyleColor(); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X; + ScheduleRuleDto r = _schedRule; + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), _schedEdit == -1 ? "New rule" : $"Edit rule {_schedEdit + 1}"); + ImGuiNET.ImGui.PopFont(); + + FieldLabel("When:"); + int picked = FlowPicker("##sched_trig", TriggerNames[Math.Clamp(r.Trigger, 0, 3)], TriggerNames, r.Trigger, w); + if (picked >= 0) r.Trigger = picked; + + if (r.Trigger == 0) + { + FieldLabel("Quest (as /myquests shows it; case doesn't matter):"); + if (TextBox("##sched_quest", _schedQuest, w, "e.g. blightlordlairwait1008", ImGuiInputTextFlags.None, out _)) + r.Quest = Utf8(_schedQuest).Trim(); + } + else + { + FieldLabel(r.Trigger switch + { + 1 => "Minutes on the current meta:", + 2 => "Every how many minutes:", + _ => "Countdown minutes (start it with the play button or /ra metamgr start):", + }); + if (TextBox("##sched_min", _schedMinutes, 80, "30", ImGuiInputTextFlags.CharsDecimal, out _) + && double.TryParse(Utf8(_schedMinutes).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out double m) && m >= 0) + r.Minutes = m; + } + + FieldLabel("Load meta:"); + picked = FlowPicker("##sched_meta", r.Meta.Length > 0 ? r.Meta : "Select a meta...", _schedMetaPicks, + Array.FindIndex(_schedMetaPicks, s => string.Equals(s, r.Meta, StringComparison.OrdinalIgnoreCase)), w); + if (picked >= 0) r.Meta = _schedMetaPicks[picked]; + + FieldLabel("Only while this meta is loaded:"); + int onlyIdx = r.OnlyOnMeta.Length == 0 ? 0 + : Array.FindIndex(_schedOnlyPicks, s => string.Equals(s, r.OnlyOnMeta, StringComparison.OrdinalIgnoreCase)); + picked = FlowPicker("##sched_only", r.OnlyOnMeta.Length > 0 ? r.OnlyOnMeta : _schedOnlyPicks.Length > 0 ? _schedOnlyPicks[0] : "(any meta)", + _schedOnlyPicks, onlyIdx, w); + if (picked >= 0) r.OnlyOnMeta = picked == 0 ? string.Empty : _schedOnlyPicks[picked]; + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float x = p.X; + if (Toggle("Repeat##sched_rep", ref x, p.Y, r.Repeat)) r.Repeat = true; + ImGuiNET.ImGui.SetItemTooltip("Fires every time its timer runs out"); + if (Toggle("Once##sched_once", ref x, p.Y, !r.Repeat)) r.Repeat = false; + ImGuiNET.ImGui.SetItemTooltip("Fires once, then waits until you re-arm it"); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Separator(w); + bool valid = r.Meta.Length > 0 && (r.Trigger != 0 || r.Quest.Length > 0); + Vector2 b = ImGuiNET.ImGui.GetCursorScreenPos(); + string saveLabel = (_schedEdit == -1 ? "Add Rule" : "Save Rule") + "##sched_save"; + float sw = ImGuiNET.ImGui.CalcTextSize(saveLabel.Substring(0, saveLabel.IndexOf("##", StringComparison.Ordinal))).X + 20; + if (Button(saveLabel, b, new Vector2(sw, 22), TextDim, NewFill, Green, enabled: valid)) + { + var send = r.CloneSettings(); + if (_schedEdit == -1) MetaCommands.Send(new MetaCmd { Op = "mm_add", ScheduleRule = send }); + else MetaCommands.Send(new MetaCmd { Op = "mm_update", Index = _schedEdit, ScheduleRule = send }); + _schedEdit = -2; + } + if (!valid) ImGuiNET.ImGui.SetItemTooltip(r.Meta.Length == 0 ? "Pick a meta to load" : "Name the quest"); + if (Button("Cancel##sched_cancel", new Vector2(b.X + sw + 6, b.Y), new Vector2(60, 22), Mute, BtnFill, BtnBord)) + _schedEdit = -2; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(b.X, b.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + if (_schedEdit >= 0) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), "Saving re-arms the rule (clears fired / error)."); + ImGuiNET.ImGui.PopFont(); + } + ImGuiNET.ImGui.EndChild(); + } + + private static string Num(double v) => v.ToString("0.##", CultureInfo.InvariantCulture); + + /// <summary>12s, 4m 05s, 3h 20m, 2d 4h.</summary> + private static string Span(long ms) + { + if (ms < 0) ms = 0; + var t = TimeSpan.FromMilliseconds(ms); + if (t.TotalHours >= 24) return $"{(int)t.TotalDays}d {t.Hours}h"; + if (t.TotalMinutes >= 60) return $"{(int)t.TotalHours}h {t.Minutes:00}m"; + if (t.TotalSeconds >= 60) return $"{(int)t.TotalMinutes}m {t.Seconds:00}s"; + return $"{(int)t.TotalSeconds}s"; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs new file mode 100644 index 0000000..655bc50 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs @@ -0,0 +1,1301 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/MetaFace.cs +// ImGui face of the Meta panel (docs/IMGUI_PARITY_PLAN.md §2.13), with the +// Avalonia face's look and three views: +// +// List file picker / refresh / Save / Save As; Visual|Source; Meta, Debug; +// rules grouped by state (collapsible, red while firing), rows with +// enable, expand, up/down within the state, duplicate, delete; click +// a row to edit it; State picker and New Rule at the bottom. +// Editor state, condition (with nested All/Any/Not sub-conditions), action +// (state and route pickers, DoAll sub-actions); Add/Save, Cancel. +// Source the .af text in a coloured editor (CodeEditor) with Ctrl+Space +// completion (and after "IF: " etc.); Apply shows the plugin's real +// result; unapplied edits survive switching views; Revert. +// +// Data: UiSources.Meta (hub snapshot) and MetaCommands. List edits change a +// private copy at once and the next snapshot (taken after the plugin applied +// the command) replaces it. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using System.Text; +using ImGuiNET; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class MetaFace : IImGuiPanel +{ + /// <summary>A large face that changes on its own only when the meta state moves: 4 Hz idle when popped out.</summary> + public int PopOutIdleHz => 4; + + public const string Title = "Meta"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(440, 540), new Vector2(380, 300), EdgeToEdge: true, GripInBody: true), + () => new MetaFace()); + + // ── Palette (MetaPanel's, ARGB) ───────────────────────────────────── + private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Green = C(0xFF33CC66), + Red = C(0xFFE04848), Mute = C(0xFFC8D6E4), TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), + PanelBg = C(0xFF141F29), RowAlt = C(0xFF101822), BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A), + Fired = C(0xFF3A1212), BtnOn = C(0xFF0E2E3A), StateHdrA = C(0xFF0E1E30), StateHdrB = C(0xFF162A40), + DelFill = C(0xFF7A1414), NewFill = C(0xFF0E2E1A), PickSel = C(0xFF1A2E42); + private static uint C(uint argb) => RynthTheme.Argb(argb); + private static uint Faded(uint abgr) => (abgr & 0x00FFFFFF) | ((abgr >> 25) << 24); // half alpha + + private enum View { List, Editor, Source, Schedule } + + // ── Snapshot copy + caches rebuilt when it changes ─────────────────── + private MetaPayload _data = new(); + private long _seenVersion = -1; + private List<(string State, List<int> Rules)> _groups = new(); + private string[] _condText = Array.Empty<string>(), _actText = Array.Empty<string>(); + private string[] _groupLabel = Array.Empty<string>(); + private bool[] _groupFiring = Array.Empty<bool>(); + private string[] _statePicks = Array.Empty<string>(), _statesOnly = Array.Empty<string>(); + private string[] _routePicks = Array.Empty<string>(), _fileDisplays = Array.Empty<string>(); + private string _fileDisplay = "-- None --", _sourceFileLabel = "File: Unsaved"; + private IReadOnlyList<string> _completionNavs = Array.Empty<string>(); + + // Ellipsized row text, recomputed only when the column width changes. + private readonly Dictionary<string, (float Width, string Shown)> _fit = new(); + + private View _view = View.List; + private readonly HashSet<string> _collapsed = new(); + private readonly HashSet<int> _expanded = new(); + private bool _saveAs, _saveAsFocus; + private readonly byte[] _saveName = new byte[128]; + + // ── Rule editor ────────────────────────────────────────────────────── + private int _editIndex = -1; + private MetaRuleDto _editRule = new() { Action = 1 }; + private sealed class FieldBuffer + { + public readonly byte[] Bytes = new byte[2048]; + public string? Shown; + public bool Active; // being typed in (last frame) + } + private readonly Dictionary<(MetaRuleDto Rule, bool Action), FieldBuffer> _fields = new(); + + // ── Source ─────────────────────────────────────────────────────────── + private CodeEditor? _editor; + private string _sourceBaseline = string.Empty; // snapshot text the editor was last loaded with + private bool _sourceStale; // the meta changed under unapplied edits + private (int Line, int Column) _cursor = (-1, -1); + private string _cursorLabel = string.Empty; + private uint _lastChange; + private long _applySeqBefore = -2; // -2: no apply pending + private DateTime _applySentAt, _msgAt; + private string _msg = string.Empty; + private bool _msgOk = true; + + // Completion list. + private enum SuggestionKind { Struct, Cond, Action, State, Nav } + private readonly List<(string Text, SuggestionKind Kind)> _compItems = new(); + private readonly List<int> _compShown = new(); + private bool _compOpen; + private int _compSel, _compTop, _compLine; + private string _compAnchor = string.Empty; // the line up to where the completed word starts + private string _compWord = string.Empty; + private const int CompRows = 10; + + public void OnShown() + { + UiSources.Meta.Subscribe(); + UiSources.Meta.RequestRefresh(); + CodeEditor.SetMetaVocabulary(MetaVocabulary.StructKeywords, MetaVocabulary.ConditionKeywords, MetaVocabulary.ActionKeywords); + } + + public void OnHidden() + { + UiSources.Meta.Unsubscribe(); + _editor?.Dispose(); + _editor = null; + } + + // ===================================================================== + // Frame + // ===================================================================== + + public void Draw() + { + TakeSnapshot(); + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail(); + dl.AddRectFilled(origin, origin + size, ShellBg, 4); + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4)); + Vector2 inner = origin + new Vector2(6, 6); + Vector2 innerSize = size - new Vector2(12, 12); + // The body has no padding (EdgeToEdge): indent so every new line, not + // just the first, starts 6 px in from the border. + ImGuiNET.ImGui.SetCursorScreenPos(inner); + ImGuiNET.ImGui.Indent(6); + switch (_view) + { + case View.List: ListView(inner, innerSize); break; + // The editor scrolls: it ends above the resize grip (GripInBody). + case View.Editor: EditorView(innerSize - new Vector2(0, FaceKit.GripOverlap())); break; + case View.Source: SourceView(inner, innerSize); break; + case View.Schedule: ScheduleView(inner, innerSize); break; + } + ImGuiNET.ImGui.Unindent(6); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopFont(); + + dl.AddRect(origin, origin + size, BtnBord, 4); + } + + private void TakeSnapshot() + { + var snap = UiSources.Meta.Current; + if (snap == null || snap.Version == _seenVersion) return; + _seenVersion = snap.Version; + MetaPayload fresh = snap.Value; + CheckApplyResult(fresh); + _data = fresh.Clone(); + RebuildCaches(); + + // Keep the source editor on the plugin's text unless it has unapplied edits. + if (_editor != null && fresh.SourceText != _sourceBaseline) + { + if (_editor.IsDirty) _sourceStale = true; + else LoadSource(fresh.SourceText); + } + } + + private void RebuildCaches() + { + List<MetaRuleDto> rules = _data.Rules; + _groups = MetaVocabulary.GroupByState(rules); + _condText = new string[rules.Count]; + _actText = new string[rules.Count]; + for (int i = 0; i < rules.Count; i++) + { + _condText[i] = MetaVocabulary.RowConditionText(rules[i]); + _actText[i] = MetaVocabulary.RowActionText(rules[i]); + } + _groupLabel = new string[_groups.Count]; + _groupFiring = new bool[_groups.Count]; + for (int g = 0; g < _groups.Count; g++) + { + bool firing = false; + foreach (int i in _groups[g].Rules) firing |= rules[i].LastFiredMs < 1500; + _groupFiring[g] = firing; + _groupLabel[g] = firing ? $"{_groups[g].State} ({_groups[g].Rules.Count}) — firing" : $"{_groups[g].State} ({_groups[g].Rules.Count})"; + } + _statePicks = MetaVocabulary.StatePicks(_data); + _statesOnly = _data.States.ToArray(); + _routePicks = MetaVocabulary.RoutePicks(_data); + _fileDisplays = new string[_data.Files.Count]; + for (int i = 0; i < _fileDisplays.Length; i++) _fileDisplays[i] = _data.Files[i].Display; + _fileDisplay = MetaVocabulary.CurrentFileDisplay(_data); + _sourceFileLabel = "File: " + (string.IsNullOrEmpty(_data.CurrentMetaPath) ? "Unsaved" : System.IO.Path.GetFileName(_data.CurrentMetaPath)); + _completionNavs = MetaVocabulary.CompletionNavs(_data); + _fit.Clear(); + } + + // ===================================================================== + // List view + // ===================================================================== + + private void ListView(Vector2 origin, Vector2 size) + { + float w = size.X; + LoadSaveBar(w); + Separator(w); + ModeRow(w, source: false); + Separator(w); + + const float bottomH = 24; + float listH = Math.Max(40, origin.Y + size.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - bottomH - 9); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0)); + ImGuiNET.ImGui.BeginChild("##meta_rules", new Vector2(w, listH)); + RuleList(ImGuiNET.ImGui.GetContentRegionAvail().X); + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + + Separator(w); + BottomBar(w); + } + + private void LoadSaveBar(float w) + { + if (_saveAs) + { + float btn = 52, sx = ImGuiNET.ImGui.GetCursorScreenPos().X, y = ImGuiNET.ImGui.GetCursorScreenPos().Y; + float boxW = w - btn - 26 - 8; + if (_saveAsFocus) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _saveAsFocus = false; } + bool enter = TextBox("##save_name", _saveName, boxW, "Filename (no ext)...", ImGuiInputTextFlags.EnterReturnsTrue, out _); + if (Button(SaveLabel + "##save_as_go", new Vector2(sx + boxW + 4, y), new Vector2(btn, 22), TextDim, BtnFill, BtnBord) || enter) + { + string n = Utf8(_saveName).Trim(); + if (n.Length > 0) + MetaCommands.Simple("save_file", path: System.IO.Path.Combine(MetaVocabulary.MetaFolder, n + ".af")); + _saveAs = false; + } + if (IconButton("##save_as_x", PhosphorIcons.X, new Vector2(sx + boxW + 8 + btn, y), new Vector2(26, 22), TextDim, BtnFill, BtnBord, + font: UiFont.Ui14)) + _saveAs = false; + ImGuiNET.ImGui.SetItemTooltip("Cancel"); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(sx, y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + return; + } + + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float refreshW = 26, saveW = 52, saveAsW = 60; + float pickW = w - refreshW - saveW - saveAsW - 12; + int picked = Picker("##file", _fileDisplay, _fileDisplays, MetaVocabulary.CurrentFileIndex(_data), p, pickW); + if (picked >= 0 && picked < _data.Files.Count) + MetaCommands.Simple("load_file", path: _data.Files[picked].Path); + + float x = p.X + pickW + 4; + if (IconButton("##refresh", PhosphorIcons.ArrowsClockwise, new Vector2(x, p.Y), new Vector2(refreshW, 22), TextDim, BtnFill, BtnBord, + font: UiFont.Ui14)) + UiSources.Meta.RequestRefresh(); + ImGuiNET.ImGui.SetItemTooltip("Refresh file list"); + x += refreshW + 4; + if (Button(SaveLabel + "##save", new Vector2(x, p.Y), new Vector2(saveW, 22), TextDim, BtnFill, BtnBord)) + { + if (!string.IsNullOrEmpty(_data.CurrentMetaPath)) MetaCommands.Simple("save_file", path: _data.CurrentMetaPath); + else BeginSaveAs(); + } + x += saveW + 4; + if (Button("Save As##save_as", new Vector2(x, p.Y), new Vector2(saveAsW, 22), TextDim, BtnFill, BtnBord)) + BeginSaveAs(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + private void BeginSaveAs() + { + _saveAs = true; + _saveAsFocus = true; + Array.Clear(_saveName); + } + + // [Visual][Source][Schedule] | [x Meta][x Debug] (check-box icons; the toggles only in the list view) + private void ModeRow(float w, bool source, bool schedule = false) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float x = p.X; + if (Toggle("Visual##mode_v", ref x, p.Y, !source && !schedule)) ShowList(); + if (Toggle("Source##mode_s", ref x, p.Y, source)) ShowSource(); + if (Toggle(ScheduleLabel, ref x, p.Y, schedule)) ShowSchedule(); + + if (!source && !schedule) + { + ImGuiNET.ImGui.GetWindowDrawList().AddLine(new Vector2(x + 2, p.Y + 2), new Vector2(x + 2, p.Y + 20), BtnBord); + x += 8; + if (Toggle(_data.EnableMeta ? MetaOn : MetaOff, ref x, p.Y, _data.EnableMeta)) + { + _data.EnableMeta = !_data.EnableMeta; + MetaCommands.Simple("set_enabled", value: _data.EnableMeta ? "true" : "false"); + } + if (Toggle(_data.MetaDebug ? DebugOn : DebugOff, ref x, p.Y, _data.MetaDebug)) + { + _data.MetaDebug = !_data.MetaDebug; + MetaCommands.Simple("set_debug", value: _data.MetaDebug ? "true" : "false"); + } + } + else if (source && _editor != null) + { + // Ln/Col and the unapplied-edits marker, right-aligned. + string right = _editor.IsDirty ? "● unapplied " + _cursorLabel : _cursorLabel; + float tw = ImGuiNET.ImGui.CalcTextSize(right).X; + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + w - tw, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), + _editor.IsDirty ? Amber : Mute, right); + } + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + private void ShowList() => _view = View.List; + + private void ShowSource() + { + if (_view == View.Source) return; + _view = View.Source; + if (_editor == null) + { + _editor = new CodeEditor("##meta_source", CodeLanguage.Meta, CodeEditor.RynthPalette()); + LoadSource(_data.SourceText); + } + else if (!_editor.IsDirty && _sourceBaseline != _data.SourceText) + LoadSource(_data.SourceText); + _editor.RequestFocus(); + } + + // Condition/action split of the rule list (dragged in its header) and where + // the text starts within a row (from the last row drawn). + private static float _condFrac = Math.Clamp(RynthCore.Engine.UI.PanelColumnStore.Get("Meta.condFrac", 0.5f), 0.15f, 0.85f); + private float _textStartOff; + + private void RuleList(float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + if (_groups.Count == 0) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " No rules. Click New Rule to add one."); + return; + } + + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + List<MetaRuleDto> rules = _data.Rules; + + // Condition | Action header; drag the divider to move the split (saved per PC). + if (_textStartOff > 0) + { + Vector2 hp = ImGuiNET.ImGui.GetCursorScreenPos(); + const float hh = 16; + float tx = hp.X + _textStartOff, tw = Math.Max(1, hp.X + w - tx); + float split = tw * _condFrac; + float hy = hp.Y + (hh - bold.FontSize) * 0.5f; + dl.AddText(bold, bold.FontSize, new Vector2(tx + 3, hy), C(0xFFC8D6E4), "Condition"); + dl.AddText(bold, bold.FontSize, new Vector2(tx + split + 4, hy), C(0xFFC8D6E4), "Action"); + if (FaceKit.ColumnDivider("##meta_split", tx + split, hp.Y, hh, ref split, 40, + _ => RynthCore.Engine.UI.PanelColumnStore.Set("Meta.condFrac", _condFrac))) + _condFrac = Math.Clamp(split / tw, 0.15f, 0.85f); + ImGuiNET.ImGui.Dummy(new Vector2(w, hh)); + } + + for (int g = 0; g < _groups.Count; g++) + { + (string state, List<int> members) = _groups[g]; + bool collapsed = _collapsed.Contains(state); + bool firing = _groupFiring[g]; + + // Header: caret, State (n) [— firing]; click toggles. + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 hp = ImGuiNET.ImGui.GetCursorScreenPos(); + float hh = bold.FontSize + 6; + ImGuiNET.ImGui.PushID(g); + if (ImGuiNET.ImGui.InvisibleButton("##hdr", new Vector2(w, hh))) + { + if (collapsed) _collapsed.Remove(state); else _collapsed.Add(state); + } + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + ImGuiNET.ImGui.PopID(); + uint hc = firing ? Red : Amber; + dl.AddRectFilled(hp, hp + new Vector2(w, hh), g % 2 == 0 ? StateHdrA : StateHdrB); + dl.AddText(bold, bold.FontSize, hp + new Vector2(3, 3), hc, collapsed ? PhosphorIcons.CaretRight : PhosphorIcons.CaretDown); + dl.AddText(bold, bold.FontSize, hp + new Vector2(18, 3), hc, _groupLabel[g]); + if (collapsed) continue; + + for (int gi = 0; gi < members.Count; gi++) + { + int index = members[gi]; + if (index >= rules.Count) break; + if (RuleRow(rules[index], index, gi, members.Count, w)) return; // the list changed: redraw next frame + } + } + } + + /// <summary>One rule row plus its expanded children. True when a click changed the list.</summary> + private bool RuleRow(MetaRuleDto rule, int index, int gi, int groupCount, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + bool firing = rule.LastFiredMs < 1500; + bool hasChildren = (MetaVocabulary.IsCompositeCondition(rule.Condition) && rule.Children.Count > 0) + || (MetaVocabulary.IsAllAction(rule.Action) && rule.ActionChildren.Count > 0); + bool expanded = _expanded.Contains(index); + + const float h = 20; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddRectFilled(p, p + new Vector2(w, h), firing ? Fired : gi % 2 == 0 ? PanelBg : RowAlt); + ImGuiNET.ImGui.PushID(index); + bool changed = false; + + // Enable + float x = p.X + 1; + if (IconButton("##en", rule.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square, new Vector2(x, p.Y + 2), new Vector2(14, 16), + rule.Enabled ? Green : Mute, BtnFill, BtnBord)) + { + rule.Enabled = !rule.Enabled; + MetaCommands.Simple("set_rule_enabled", index, rule.Enabled ? "true" : "false"); + } + ImGuiNET.ImGui.SetItemTooltip(rule.Enabled ? "Enabled — click to disable" : "Disabled — click to enable"); + x += 16; + + // Expand (only with children) + if (hasChildren && IconButton("##exp", expanded ? PhosphorIcons.Minus : PhosphorIcons.Plus, new Vector2(x + 2, p.Y + 3), new Vector2(14, 14), + Teal, BtnFill, BtnBord)) + { + if (expanded) _expanded.Remove(index); else _expanded.Add(index); + } + x += 18; + + // Up / down within the state (Appendix A3: the plugin now swaps within the state too) + if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord, enabled: gi > 0)) + changed |= Move(index, -1); + ImGuiNET.ImGui.SetItemTooltip("Move up"); + x += 18; + if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord, + enabled: gi < groupCount - 1)) + changed |= Move(index, +1); + ImGuiNET.ImGui.SetItemTooltip("Move down"); + x += 18; + + // Duplicate + if (IconButton("##dup", PhosphorIcons.Copy, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord)) + { + MetaCommands.Send(new MetaCmd { Op = "duplicate_rule", Index = index, Rule = rule.Clone() }); + _data.Rules.Insert(Math.Min(index + 1, _data.Rules.Count), rule.Clone()); + changed = true; + } + ImGuiNET.ImGui.SetItemTooltip("Duplicate rule"); + x += 18; + + // Delete + if (IconButton("##del", PhosphorIcons.Trash, new Vector2(x + 1, p.Y + 2), new Vector2(18, 16), TextDim, DelFill, BtnBord)) + { + MetaCommands.Simple("delete_rule", index); + _data.Rules.RemoveAt(index); + _expanded.Clear(); + changed = true; + } + ImGuiNET.ImGui.SetItemTooltip("Delete rule"); + x += 22; + + // Condition | action text; clicking it edits the rule. + float textW = p.X + w - x; + _textStartOff = x - p.X; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y)); + if (ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(Math.Max(1, textW), h))) + OpenEditor(index, rule); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + ImGuiNET.ImGui.PopID(); + + if (!changed) + { + float col = textW * _condFrac; + float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + uint condCol = firing ? Red : TextDim, actCol = firing ? Amber : C(0xFFC8D8E8); + if (!rule.Enabled) { condCol = Faded(condCol); actCol = Faded(actCol); } + dl.AddText(new Vector2(x + 3, ty), condCol, Fit(_condText[index], col - 5)); + dl.AddText(new Vector2(x + col + 2, ty), actCol, Fit(_actText[index], col - 4)); + } + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + + if (changed) + { + RebuildCaches(); + return true; + } + + if (hasChildren && expanded) ExpandedChildren(rule); + return false; + } + + private void ExpandedChildren(MetaRuleDto rule) + { + ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9); + ImGuiNET.ImGui.PushFont(f9); + Vector4 amber = RynthTheme.Vec(0xFFE8B333), mute = RynthTheme.Vec(0xFFC8D6E4); + ImGuiNET.ImGui.Indent(22); + if (MetaVocabulary.IsCompositeCondition(rule.Condition) && rule.Children.Count > 0) + { + ImGuiNET.ImGui.TextColored(amber, " " + MetaVocabulary.ConditionName(rule.Condition) + ":"); + foreach (MetaRuleDto child in rule.Children) + ImGuiNET.ImGui.TextColored(mute, " • " + MetaVocabulary.CondText(child)); + } + if (MetaVocabulary.IsAllAction(rule.Action) && rule.ActionChildren.Count > 0) + { + ImGuiNET.ImGui.TextColored(amber, " All (actions):"); + foreach (MetaRuleDto child in rule.ActionChildren) + ImGuiNET.ImGui.TextColored(mute, " • " + MetaVocabulary.ActText(child)); + } + ImGuiNET.ImGui.Unindent(22); + ImGuiNET.ImGui.PopFont(); + } + + private bool Move(int index, int direction) + { + int other = MetaVocabulary.SwapPartner(_data.Rules, index, direction); + if (other < 0) return false; + MetaCommands.Simple(direction < 0 ? "move_up" : "move_down", index); + (_data.Rules[index], _data.Rules[other]) = (_data.Rules[other], _data.Rules[index]); + _expanded.Clear(); + return true; + } + + private void BottomBar(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float labelW = ImGuiNET.ImGui.CalcTextSize("State:").X; + dl.AddText(new Vector2(p.X, p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "State:"); + const float newW = 72; + // The bar sits on the body's bottom edge: it stops short of the resize grip (GripInBody). + float grip = ImGuiPanelHost.BodyGripReserve; + float pickW = w - labelW - 4 - newW - 4 - grip; + int picked = Picker("##cur_state", _data.CurrentState, _statePicks, Array.IndexOf(_statePicks, _data.CurrentState), + new Vector2(p.X + labelW + 4, p.Y + 1), pickW); + if (picked >= 0) + { + _data.CurrentState = _statePicks[picked]; + MetaCommands.Simple("set_state", value: _statePicks[picked]); + } + if (Button(PhosphorIcons.Plus + " New Rule##new", new Vector2(p.X + w - newW - grip, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green)) + OpenEditor(-1, new MetaRuleDto { State = _data.CurrentState, Action = 1 }); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 24)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + // ===================================================================== + // Rule editor view + // ===================================================================== + + private void OpenEditor(int index, MetaRuleDto rule) + { + _editIndex = index; + _editRule = index >= 0 ? rule.Clone() : rule; + _fields.Clear(); + _view = View.Editor; + } + + private void EditorView(Vector2 size) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0); + ImGuiNET.ImGui.BeginChild("##meta_editor", size); + ImGuiNET.ImGui.PopStyleColor(); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X; + MetaRuleDto r = _editRule; + + if (FlowButton(PhosphorIcons.ArrowLeft + " Back to List##back", Mute, BtnFill, BtnBord)) _view = View.List; + Separator(w); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), _editIndex == -1 ? "New Rule" : $"Edit Rule (index {_editIndex})"); + ImGuiNET.ImGui.PopFont(); + + // State + FieldLabel("State:"); + int picked = FlowPicker("##ed_state", r.State, _statePicks, Array.IndexOf(_statePicks, r.State), w); + if (picked >= 0) r.State = _statePicks[picked]; + + // Condition + FieldLabel("Condition:"); + picked = FlowPicker("##ed_cond", MetaVocabulary.ConditionName(r.Condition), MetaVocabulary.ConditionNames, r.Condition, w); + if (picked >= 0) + { + r.Condition = picked; + if (!MetaVocabulary.IsCompositeCondition(picked)) r.Children.Clear(); + else if (picked == 20 && r.Children.Count > 1) r.Children.RemoveRange(1, r.Children.Count - 1); + } + if (!MetaVocabulary.IsCompositeCondition(r.Condition)) + DataBox("##ed_cdata", r, action: false, MetaVocabulary.ConditionHint(r.Condition), w); + else + SubRules(r.Children, r.Condition == 20 ? "Not (one condition):" : "Sub-Conditions", action: false, 0, + r.Condition == 20 ? 1 : int.MaxValue, w); + + // Action + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Separator(w); + FieldLabel("Action:"); + picked = FlowPicker("##ed_act", MetaVocabulary.ActionName(r.Action), MetaVocabulary.ActionNames, r.Action, w); + if (picked >= 0) + { + r.Action = picked; + if (!MetaVocabulary.IsAllAction(picked)) r.ActionChildren.Clear(); + } + if (!MetaVocabulary.IsAllAction(r.Action)) + { + if (r.Action is 2 or 5) // Set / Call Meta State + { + picked = FlowPicker("##ed_astate", r.ActionData.Length == 0 ? "Select state..." : r.ActionData, + _statesOnly, Array.IndexOf(_statesOnly, r.ActionData), w); + if (picked >= 0) r.ActionData = _statesOnly[picked]; + } + else if (r.Action == 3) // Embedded Nav Route + { + picked = FlowPicker("##ed_route", r.ActionData.Length == 0 ? "Select route..." : r.ActionData, + _routePicks, Array.IndexOf(_routePicks, r.ActionData), w); + if (picked >= 0) r.ActionData = _routePicks[picked]; + } + else + DataBox("##ed_adata", r, action: true, MetaVocabulary.ActionHint(r.Action), w); + } + else + SubRules(r.ActionChildren, "Sub-Actions", action: true, 0, int.MaxValue, w); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Separator(w); + + // Add/Save, Cancel + if (FlowButton(_editIndex == -1 ? "Add Rule##save_rule" : "Save Rule##save_rule", TextDim, NewFill, Green)) + { + if (_editIndex == -1) MetaCommands.Send(new MetaCmd { Op = "add_rule", Rule = r.Clone() }); + else MetaCommands.Send(new MetaCmd { Op = "update_rule", Index = _editIndex, Rule = r.Clone() }); + _view = View.List; + } + ImGuiNET.ImGui.SameLine(0, 6); + if (FlowButton("Cancel##cancel_rule", Mute, BtnFill, BtnBord)) _view = View.List; + + ImGuiNET.ImGui.EndChild(); + } + + // Sub-conditions nest (All/Any/Not under All/Any/Not, MaxSubConditionDepth + // levels; a Not takes one); DoAll's sub-actions are a flat list. + private void SubRules(List<MetaRuleDto> subs, string label, bool action, int depth, int maxCount, float w) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), label); + ImGuiNET.ImGui.PopFont(); + + string[] names = action ? MetaVocabulary.ActionNames : MetaVocabulary.ConditionNames; + for (int i = 0; i < subs.Count; i++) + { + MetaRuleDto sub = subs[i]; + ImGuiNET.ImGui.PushID(i); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float half = (w - 24) * 0.5f; + + // Appendix A4: the label indexes by the sub-rule's own kind. + int current = action ? sub.Action : sub.Condition; + string shown = action ? MetaVocabulary.ActionName(sub.Action) : MetaVocabulary.ConditionName(sub.Condition); + int picked = Picker("##type", shown, names, current, p, half - 2, 20); + if (picked >= 0) + { + if (action) sub.Action = picked; + else + { + sub.Condition = picked; + if (!MetaVocabulary.IsCompositeCondition(picked)) sub.Children.Clear(); + else if (picked == 20 && sub.Children.Count > 1) sub.Children.RemoveRange(1, sub.Children.Count - 1); + } + } + + bool nests = !action && MetaVocabulary.IsCompositeCondition(sub.Condition) && depth < MetaVocabulary.MaxSubConditionDepth; + if (nests) + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + half + 4, p.Y + (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), + TextDim, sub.Condition == 20 ? "(the condition below)" : "(the conditions below)"); + else + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + half + 2, p.Y)); + DataBox("##data", sub, action, "data...", half, 20); + } + + bool removed = IconButton("##rm", PhosphorIcons.X, new Vector2(p.X + w - 20, p.Y), new Vector2(20, 20), TextDim, DelFill, BtnBord); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 21)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + + if (!removed && nests) + { + ImGuiNET.ImGui.Indent(14); + SubRules(sub.Children, sub.Condition switch { 20 => "Not:", 2 => "All of:", _ => "Any of:" }, + action: false, depth + 1, sub.Condition == 20 ? 1 : int.MaxValue, w - 14); + ImGuiNET.ImGui.Unindent(14); + } + ImGuiNET.ImGui.PopID(); + if (removed) + { + subs.RemoveAt(i); + break; // indices shifted: the rest draws next frame + } + } + + if (subs.Count >= maxCount) return; // a Not already has its one operand + ImGuiNET.ImGui.PushID(depth * 1000 + subs.Count); + if (FlowButton(PhosphorIcons.Plus + " Add##add_sub", Teal, BtnFill, BtnBord, height: 20)) + subs.Add(new MetaRuleDto { State = _editRule.State }); + ImGuiNET.ImGui.PopID(); + } + + // ===================================================================== + // Source view + // ===================================================================== + + private void LoadSource(string text) + { + _editor?.SetText(text); + _sourceBaseline = text; + _sourceStale = false; + _lastChange = _editor?.ChangeCount ?? 0; + CloseCompletion(); + } + + private void SourceView(Vector2 origin, Vector2 size) + { + float w = size.X; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + + // File: name [Save] + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Amber, _sourceFileLabel); + float lw = ImGuiNET.ImGui.CalcTextSize(_sourceFileLabel).X; + if (Button(SaveLabel + "##src_save", new Vector2(p.X + lw + 8, p.Y), new Vector2(52, 22), TextDim, BtnFill, BtnBord) + && !string.IsNullOrEmpty(_data.CurrentMetaPath)) + MetaCommands.Simple("save_file", path: _data.CurrentMetaPath); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + Separator(w); + ModeRow(w, source: true); + Separator(w); + + UpdateApplyTimeout(); + bool showMsg = _msg.Length > 0 && (_applySeqBefore != -2 || (DateTime.Now - _msgAt).TotalSeconds < 8); + if (showMsg) + { + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(_msgOk ? 0xFF33CC66 : 0xFFE04848), _msg); + ImGuiNET.ImGui.PopTextWrapPos(); + } + if (_sourceStale) + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "The meta changed since you started editing. Revert loads it."); + + if (_editor == null || !CodeEditor.Available) + { + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFCC3333), + "The source editor needs the new cimgui.dll (a full RynthCore deploy). Use the Avalonia face meanwhile: /rc ui Meta avalonia"); + return; + } + + const float buttonsH = 26; + float editorH = Math.Max(60, origin.Y + size.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - buttonsH - 4); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Code12)); + bool focused = _editor.Render(new Vector2(w, editorH)); + ImGuiNET.ImGui.PopFont(); + SourceAfterRender(focused); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + if (FlowButton(PhosphorIcons.Check + " Apply##apply", TextDim, NewFill, Green)) Apply(); + ImGuiNET.ImGui.SameLine(0, 6); + if (FlowButton(PhosphorIcons.ArrowCounterClockwise + " Revert##revert", Mute, BtnFill, BtnBord)) + { + LoadSource(_data.SourceText); + _editor.RequestFocus(); + } + } + + private void Apply() + { + if (_editor == null) return; + _applySeqBefore = _data.ApplyResult?.Seq ?? -1; + _applySentAt = DateTime.Now; + MetaCommands.Send(new MetaCmd { Op = "set_source", Text = _editor.GetText() }); + SetMsg("Applying…", ok: true); + } + + /// <summary>The first snapshot with a newer ApplyResult carries this apply's result (Appendix A5).</summary> + private void CheckApplyResult(MetaPayload fresh) + { + if (_applySeqBefore == -2) return; + MetaApplyResult? r = fresh.ApplyResult; + if (r == null || r.Seq <= _applySeqBefore) return; + _applySeqBefore = -2; + SetMsg(r.Text, r.Ok); + if (r.Ok && _editor != null) + { + // Applied: the editor's text is now the meta. Keep the caret and + // scroll; Revert shows the plugin's own formatting. + _editor.MarkClean(); + _sourceBaseline = fresh.SourceText; + _sourceStale = false; + } + } + + private void UpdateApplyTimeout() + { + if (_applySeqBefore == -2 || (DateTime.Now - _applySentAt).TotalSeconds <= 3) return; + _applySeqBefore = -2; + SetMsg("Sent. This RynthAi version reports the result in chat.", ok: true); + } + + private void SetMsg(string text, bool ok) + { + _msg = text; + _msgOk = ok; + _msgAt = DateTime.Now; + } + + // ── Completion ─────────────────────────────────────────────────────── + + private void SourceAfterRender(bool focused) + { + CodeEditor ed = _editor!; + (int Line, int Column) cursor = ed.Cursor; + bool moved = cursor != _cursor; + if (moved) + { + _cursor = cursor; + _cursorLabel = string.Create(CultureInfo.InvariantCulture, $"Ln {cursor.Line + 1}, Col {cursor.Column + 1}"); + } + uint change = ed.ChangeCount; + bool typed = change != _lastChange; + _lastChange = change; + + if (focused && ImGuiNET.ImGui.GetIO().KeyCtrl && ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Space)) + OpenCompletion(auto: false); + else if (typed && focused && !_compOpen) + { + // "IF: " (a space right after a colon) lists what can follow. + string prefix = ed.LinePrefix(); + if (prefix.EndsWith(": ", StringComparison.Ordinal)) OpenCompletion(auto: true, prefix); + } + else if (_compOpen && (typed || moved)) + UpdateCompletion(); + + if (_compOpen) DrawCompletion(focused); + ed.CompletionKeysHeld = _compOpen; + } + + private void OpenCompletion(bool auto, string? prefix = null) // auto: after ": " (else Ctrl+Space) + { + CodeEditor ed = _editor!; + prefix ??= ed.LinePrefix(); + int start = prefix.Length; + while (start > 0 && (char.IsLetterOrDigit(prefix[start - 1]) || prefix[start - 1] == '_')) start--; + _compAnchor = prefix.Substring(0, start); + _compWord = prefix.Substring(start); + _compLine = ed.Cursor.Line; + + BuildSuggestions(prefix); + if (_compItems.Count == 0) { CloseCompletion(); return; } + _compOpen = true; + Filter(); + if (_compShown.Count == 0) { CloseCompletion(); return; } + _compSel = 0; + _compTop = 0; + } + + private void UpdateCompletion() + { + CodeEditor ed = _editor!; + string prefix = ed.LinePrefix(); + if (ed.Cursor.Line != _compLine || !prefix.StartsWith(_compAnchor, StringComparison.Ordinal)) + { + CloseCompletion(); + return; + } + _compWord = prefix.Substring(_compAnchor.Length); + Filter(); + if (_compShown.Count == 0) { CloseCompletion(); return; } + _compSel = Math.Clamp(_compSel, 0, _compShown.Count - 1); + } + + private void CloseCompletion() + { + _compOpen = false; + _compItems.Clear(); + _compShown.Clear(); + } + + /// <summary>Prefix matches first, then matches anywhere (case-insensitive).</summary> + private void Filter() + { + _compShown.Clear(); + for (int pass = 0; pass < 2; pass++) + for (int i = 0; i < _compItems.Count; i++) + { + string t = _compItems[i].Text; + bool prefix = t.StartsWith(_compWord, StringComparison.OrdinalIgnoreCase); + if (pass == 0 ? prefix : !prefix && t.Contains(_compWord, StringComparison.OrdinalIgnoreCase)) + _compShown.Add(i); + } + } + + // MetaSourceEditor.BuildSuggestionsForContext. + private void BuildSuggestions(string prefix) + { + _compItems.Clear(); + string t = prefix.TrimStart().TrimEnd(); + if (StartsWith(t, "IF:", out _)) + { + foreach (string s in MetaVocabulary.ConditionKeywords) _compItems.Add((s, SuggestionKind.Cond)); + return; + } + if (StartsWith(t, "DO:", out string rest)) + { + rest = rest.TrimStart(); + if (StartsWith(rest, "SetState", out _) || StartsWith(rest, "CallState", out _)) + foreach (string s in _data.States) _compItems.Add((s, SuggestionKind.State)); + else if (StartsWith(rest, "EmbedNav", out _)) + foreach (string s in _completionNavs) _compItems.Add((s, SuggestionKind.Nav)); + else + foreach (string s in MetaVocabulary.ActionKeywords) _compItems.Add((s, SuggestionKind.Action)); + return; + } + if (StartsWith(t, "STATE:", out _)) + { + foreach (string s in _data.States) _compItems.Add((s, SuggestionKind.State)); + return; + } + if (StartsWith(t, "NAV:", out _)) + { + foreach (string s in _completionNavs) _compItems.Add((s, SuggestionKind.Nav)); + return; + } + _compItems.Add(("STATE:", SuggestionKind.Struct)); + _compItems.Add(("IF:", SuggestionKind.Struct)); + _compItems.Add(("DO:", SuggestionKind.Struct)); + _compItems.Add(("NAV:", SuggestionKind.Struct)); + } + + private static bool StartsWith(string text, string keyword, out string rest) + { + if (text.StartsWith(keyword, StringComparison.OrdinalIgnoreCase)) + { + rest = text.Substring(keyword.Length); + return true; + } + rest = string.Empty; + return false; + } + + private void Accept(int shownIndex) + { + string text = _compItems[_compShown[shownIndex]].Text; + _editor!.ReplaceBeforeCursor(Encoding.UTF8.GetByteCount(_compWord), text); + CloseCompletion(); + _lastChange = _editor.ChangeCount; // don't re-trigger on our own insert + _editor.RequestFocus(); + } + + private void DrawCompletion(bool editorFocused) + { + int n = _compShown.Count; + int rows = Math.Min(n, CompRows); + const float rowH = 18, width = 260; + Vector2 pos = _editor!.CursorScreenPos + new Vector2(0, 2); + Vector2 size = new(width, rows * rowH + 6); + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + if (pos.Y + size.Y > display.Y) pos.Y -= size.Y + 20; // flip above the line + pos.X = Math.Clamp(pos.X, 0, Math.Max(0, display.X - width)); + + // Keys (the editor ignores these while the list is open). + if (editorFocused) + { + if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.DownArrow)) _compSel = Math.Min(n - 1, _compSel + 1); + if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.UpArrow)) _compSel = Math.Max(0, _compSel - 1); + if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.PageDown)) _compSel = Math.Min(n - 1, _compSel + CompRows); + if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.PageUp)) _compSel = Math.Max(0, _compSel - CompRows); + if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape)) { CloseCompletion(); return; } + if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Enter) || ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.KeypadEnter) + || ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Tab)) + { + Accept(_compSel); + return; + } + } + if (_compSel < _compTop) _compTop = _compSel; + if (_compSel >= _compTop + CompRows) _compTop = _compSel - CompRows + 1; + _compTop = Math.Clamp(_compTop, 0, Math.Max(0, n - CompRows)); + + // A tooltip-class window: drawn above the panels, doesn't grab focus on appearing. + const ImGuiWindowFlags flags = ImGuiWindowFlags.Tooltip | ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize + | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoFocusOnAppearing + | ImGuiWindowFlags.NoNav | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoDocking; + ImGuiNET.ImGui.SetNextWindowPos(pos); + ImGuiNET.ImGui.SetNextWindowSize(size); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(3, 3)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 4f); + ImGuiNET.ImGui.Begin("##meta_completion", flags); + ImGuiNET.ImGui.PopStyleVar(3); + ImGuiNET.ImGui.PopStyleColor(2); + + bool hovered = ImGuiNET.ImGui.IsWindowHovered(); + if (hovered) + { + float wheel = ImGuiNET.ImGui.GetIO().MouseWheel; + if (wheel != 0) _compTop = Math.Clamp(_compTop - Math.Sign(wheel) * 3, 0, Math.Max(0, n - CompRows)); + } + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr code = ImGuiFonts.Get(UiFont.Code12); + ImFontPtr small = ImGuiFonts.Get(UiFont.Ui9); + float iw = ImGuiNET.ImGui.GetContentRegionAvail().X; + int accept = -1; + for (int r = 0; r < rows; r++) + { + int k = _compTop + r; + if (k >= n) break; + (string text, SuggestionKind kind) = _compItems[_compShown[k]]; + Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.PushID(r); + if (ImGuiNET.ImGui.InvisibleButton("##c", new Vector2(iw, rowH))) accept = k; + bool ih = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + bool sel = k == _compSel; + if (sel || ih) dl.AddRectFilled(ip, ip + new Vector2(iw, rowH), sel ? PickSel : BtnFill, 2); + dl.AddText(code, code.FontSize, ip + new Vector2(4, (rowH - code.FontSize) * 0.5f), KindColor(kind), text); + string desc = KindLabel(kind); + ImGuiNET.ImGui.PushFont(small); + float dw = ImGuiNET.ImGui.CalcTextSize(desc).X; + ImGuiNET.ImGui.PopFont(); + dl.AddText(small, small.FontSize, ip + new Vector2(iw - dw - 4, (rowH - small.FontSize) * 0.5f), Mute, desc); + } + ImGuiNET.ImGui.End(); + + if (accept >= 0) Accept(accept); + else if (!editorFocused && !hovered && !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) CloseCompletion(); + } + + private static uint KindColor(SuggestionKind kind) => kind switch + { + SuggestionKind.Struct => Teal, + SuggestionKind.Cond => Amber, + SuggestionKind.Action => C(0xFF7BB8FF), + _ => TextDim, + }; + + private static string KindLabel(SuggestionKind kind) => kind switch + { + SuggestionKind.Struct => "structural keyword", + SuggestionKind.Cond => "condition", + SuggestionKind.Action => "action", + SuggestionKind.State => "meta state", + _ => "nav route", + }; + + // ===================================================================== + // Widgets + // ===================================================================== + + /// <summary>A flat bordered button at <paramref name="pos"/>; the text after "##" is the id.</summary> + private static bool Button(string labelId, Vector2 pos, Vector2 size, uint fg, uint bg, uint border, bool enabled = true) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(labelId, size) && enabled; + bool hot = enabled && ImGuiNET.ImGui.IsItemHovered(); + uint fill = enabled && ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : hot ? Lighten(bg) : bg; + dl.AddRectFilled(pos, pos + size, fill, 3); + dl.AddRect(pos, pos + size, border, 3); + int cut = labelId.IndexOf("##", StringComparison.Ordinal); + string label = cut >= 0 ? labelId.Substring(0, cut) : labelId; + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(label); + dl.AddText(pos + (size - ts) * 0.5f, enabled ? fg : Faded(fg), label); + return clicked; + } + + private const string SaveLabel = PhosphorIcons.FloppyDisk + " Save"; + private const string MetaOn = PhosphorIcons.CheckSquare + " Meta##meta_on", MetaOff = PhosphorIcons.Square + " Meta##meta_on"; + private const string DebugOn = PhosphorIcons.CheckSquare + " Debug##meta_dbg", DebugOff = PhosphorIcons.Square + " Debug##meta_dbg"; + + /// <summary> + /// Button's look with a Phosphor icon centred on it; <paramref name="id"/> is + /// the "##" id. Ui11 (about 10 px) suits the 14-20 px row buttons. + /// </summary> + private static bool IconButton(string id, string icon, Vector2 pos, Vector2 size, uint fg, uint bg, uint border, + bool enabled = true, UiFont font = UiFont.Ui11) + { + bool clicked = Button(id, pos, size, fg, bg, border, enabled); + PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(font), icon, pos, size, enabled ? fg : Faded(fg)); + return clicked; + } + + /// <summary>A button sized to its label, at the layout cursor.</summary> + private static bool FlowButton(string labelId, uint fg, uint bg, uint border, float height = 22) + { + int cut = labelId.IndexOf("##", StringComparison.Ordinal); + float tw = ImGuiNET.ImGui.CalcTextSize(cut >= 0 ? labelId.Substring(0, cut) : labelId).X; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 size = new(tw + 20, height); + bool clicked = Button(labelId, p, size, fg, bg, border); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.Dummy(size); + return clicked; + } + + /// <summary>Visual/Source-style toggle at (x, y); advances x.</summary> + private static bool Toggle(string labelId, ref float x, float y, bool on) + { + int cut = labelId.IndexOf("##", StringComparison.Ordinal); + float tw = ImGuiNET.ImGui.CalcTextSize(labelId.Substring(0, cut)).X; + var size = new Vector2(tw + 16, 22); + bool clicked = Button(labelId, new Vector2(x, y), size, on ? Teal : Mute, on ? BtnOn : BtnFill, on ? Teal : BtnBord); + x += size.X + 4; + return clicked; + } + + /// <summary> + /// A picker button showing <paramref name="shown"/>; click opens a 240 px + /// list (current item highlighted). Returns the picked index or -1. + /// </summary> + private static int Picker(string id, string shown, string[] items, int selected, Vector2 pos, float width, float height = 22) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.PushID(id); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + if (ImGuiNET.ImGui.InvisibleButton("##btn", new Vector2(Math.Max(1, width), height)) && items.Length > 0) + { + float listW = Math.Max(240, width); + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Clamp(pos.X, 0, Math.Max(0, display.X - listW)), pos.Y + height)); + ImGuiNET.ImGui.OpenPopup("##list"); + } + bool hot = ImGuiNET.ImGui.IsItemHovered(); + dl.AddRectFilled(pos, pos + new Vector2(width, height), hot ? Lighten(BtnFill) : BtnFill, 3); + dl.AddRect(pos, pos + new Vector2(width, height), BtnBord, 3); + dl.PushClipRect(pos, pos + new Vector2(width - 4, height), true); + dl.AddText(pos + new Vector2(6, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, shown); + dl.PopClipRect(); + + int picked = -1; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1)); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(Math.Max(240, width), Math.Min(items.Length * 21 + 4, 320))); + bool open = ImGuiNET.ImGui.BeginPopup("##list"); + ImGuiNET.ImGui.PopStyleVar(3); + ImGuiNET.ImGui.PopStyleColor(2); + if (open) + { + var pdl = ImGuiNET.ImGui.GetWindowDrawList(); + float iw = ImGuiNET.ImGui.GetContentRegionAvail().X; + for (int i = 0; i < items.Length; i++) + { + ImGuiNET.ImGui.PushID(i); + Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos(); + bool click = ImGuiNET.ImGui.InvisibleButton("##item", new Vector2(iw, 20)); + bool ih = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + bool sel = i == selected; + pdl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? PickSel : ih ? Lighten(BtnFill) : BtnFill); + pdl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord); + pdl.AddText(ip + new Vector2(6, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), sel ? Teal : TextDim, items[i]); + if (click) + { + picked = i; + ImGuiNET.ImGui.CloseCurrentPopup(); + } + } + ImGuiNET.ImGui.EndPopup(); + } + ImGuiNET.ImGui.PopID(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(pos.X, pos.Y + height)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + return picked; + } + + /// <summary>A full-width picker at the layout cursor.</summary> + private static int FlowPicker(string id, string shown, string[] items, int selected, float width) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + int picked = Picker(id, shown, items, selected, p, width); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.Dummy(new Vector2(width, 22)); + return picked; + } + + /// <summary>A text box bound to a rule's ConditionData or ActionData, with a grey hint while empty.</summary> + private void DataBox(string id, MetaRuleDto rule, bool action, string hint, float width, float height = 22) + { + if (!_fields.TryGetValue((rule, action), out FieldBuffer? buf)) + _fields[(rule, action)] = buf = new FieldBuffer(); + string value = action ? rule.ActionData : rule.ConditionData; + if (!buf.Active && !ReferenceEquals(buf.Shown, value)) + { + WriteUtf8(buf.Bytes, value); + buf.Shown = value; + } + bool edited = TextBox(id, buf.Bytes, width, hint, ImGuiInputTextFlags.None, out buf.Active, height); + if (edited) + { + string typed = Utf8(buf.Bytes); + if (action) rule.ActionData = typed; else rule.ConditionData = typed; + buf.Shown = typed; + } + } + + /// <summary>A bordered InputText with a hint drawn while it is empty. Returns InputText's result.</summary> + private static bool TextBox(string id, byte[] buffer, float width, string hint, ImGuiInputTextFlags flags, out bool active, float height = 22) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.SetNextItemWidth(width); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 3f); + bool result = ImGuiNET.ImGui.InputText(id, buffer, (uint)buffer.Length, flags); + active = ImGuiNET.ImGui.IsItemActive(); + ImGuiNET.ImGui.PopStyleVar(3); + ImGuiNET.ImGui.PopStyleColor(3); + if (buffer[0] == 0 && !active && hint.Length > 0) + ImGuiNET.ImGui.GetWindowDrawList().AddText(p + new Vector2(5, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute), hint); + return result; + } + + private static void FieldLabel(string text) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), text); + } + + private static void Separator(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.GetWindowDrawList().AddLine(p + new Vector2(0, 2), p + new Vector2(w, 2), BtnBord); + ImGuiNET.ImGui.Dummy(new Vector2(w, 5)); + } + + /// <summary><paramref name="text"/> cut to <paramref name="width"/> with "…", cached per text and width.</summary> + private string Fit(string text, float width) + { + if (_fit.TryGetValue(text, out var hit) && Math.Abs(hit.Width - width) < 0.5f) return hit.Shown; + string shown = text; + if (ImGuiNET.ImGui.CalcTextSize(text).X > width) + { + int n = text.Length; + while (n > 0 && ImGuiNET.ImGui.CalcTextSize(text.AsSpan(0, n).ToString() + "…").X > width) n--; + shown = text.Substring(0, n) + "…"; + } + _fit[text] = (width, shown); + return shown; + } + + private static string Utf8(byte[] buffer) + { + int len = Array.IndexOf(buffer, (byte)0); + return Encoding.UTF8.GetString(buffer, 0, len < 0 ? buffer.Length : len); + } + + private static void WriteUtf8(byte[] buffer, string text) + { + int max = buffer.Length - 1; + int n = Encoding.UTF8.GetByteCount(text) <= max ? Encoding.UTF8.GetBytes(text, 0, text.Length, buffer, 0) : TruncatedCopy(buffer, text, max); + buffer[n] = 0; + } + + private static int TruncatedCopy(byte[] buffer, string text, int max) + { + byte[] all = Encoding.UTF8.GetBytes(text); + int n = max; + while (n > 0 && (all[n] & 0xC0) == 0x80) n--; // don't split a UTF-8 sequence + Array.Copy(all, buffer, n); + return n; + } + + private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12); + private static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0); + + private static uint Scale(uint abgr, float k, int add) + { + uint a = abgr & 0xFF000000; + uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add); + uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add); + uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add); + return a | (b << 16) | (g << 8) | r; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/MonstersFace.cs b/src/RynthCore.Engine/ImGui/Panels/MonstersFace.cs new file mode 100644 index 0000000..98171ab --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/MonstersFace.cs @@ -0,0 +1,25 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/MonstersFace.cs +// The basic Monsters panel's ImGui face, retired 2026-10-01 (Tom). What only +// it could do moved to the Damage panel (DamageFace: Name rules, the +// Offhand modes per monster) and Monster Detail (DamageDetailFace: priority, +// damage type, extra vuln, match expression; a name rule's debuffs, off +// hand, pet and name). Categories were dropped from the UI; Rule.Category +// stays in the model so existing rule files keep it. +// +// Only Register is left, because EntryPoint calls it: it registers no face +// (so "Monsters" never shows) and moves a Monsters panel saved open onto +// Damage. PanelRouter sends every other "Monsters" request to Damage. +// ============================================================================ + +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class MonstersFace +{ + public const string Title = "Monsters"; + + /// <summary>Engine init (EntryPoint). Registers nothing: see the file header.</summary> + public static void Register() => PanelRouter.MoveRetiredMonstersPanel(); +} diff --git a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs new file mode 100644 index 0000000..ef81989 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs @@ -0,0 +1,391 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/NavFace.cs +// ImGui face of the Nav panel (UI/Panels/NavPanel.cs): active nav + status, +// Start/Stop, route type and insert mode, the Breadcrumbs and Route overlay +// toggles, Add Waypoint / Portal (not yet) / +// Recall / Clear / Save / Dungeon Patrol, a chat waypoint, Save As, the nav +// file picker, the nav point reach (RynthAi's FollowNavMin, the same row as +// Settings > Navigation), and the waypoint list (click selects the insert +// point, X deletes, => marks the active one). +// +// Data: UiSources.Nav (hub) and NavCommands. Button actions change a private +// copy at once; the plugin applies commands immediately, so the next +// snapshot (requested right after) replaces the copy. The reach row reads +// UiSources.Settings and saves through SettingsCommands, like the Settings face. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class NavFace : IImGuiPanel +{ + public const string Title = "Nav"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(400, 560), new Vector2(360, 380), EdgeToEdge: true), + () => new NavFace()); + + private static readonly string[] Actions = + { + PhosphorIcons.MapPinPlus + " Add Waypoint", PhosphorIcons.Spiral + " Add Portal", PhosphorIcons.MagicWand + " Add Recall", + PhosphorIcons.Trash + " Clear Route", PhosphorIcons.FloppyDisk + " Save Route", PhosphorIcons.Footprints + " Dungeon Patrol", + }; + private const string StartNav = PhosphorIcons.Play + " Start Navigation", StopNav = PhosphorIcons.Stop + " Stop Navigation"; + private const string AddChat = PhosphorIcons.Plus + " Add Chat", SaveAs = PhosphorIcons.FloppyDisk + " Save As"; + private static readonly bool[] ActionsEnabled = { true, false, true, true, true, true }; + + private NavPayload _data = new(); + private long _seenVersion = -1; + private readonly List<string> _pointText = new(); + private int _selected = -1, _addMode; + private bool _typing; + private string _routeLabel = "Route: Once", _insertLabel = "Insert: End", _activeLabel = "Active Nav: None (Unsaved)"; + private string _fileLabel = "Select nav file..."; + private string[] _navFiles = Array.Empty<string>(); + private readonly byte[] _chat = new byte[256]; + private int _chatLoadedFor = -1; // waypoint whose command is in _chat (-1: none) + + private static void SetUtf8(byte[] buffer, string text) + { + Array.Clear(buffer); + byte[] b = System.Text.Encoding.UTF8.GetBytes(text ?? string.Empty); + Array.Copy(b, buffer, Math.Min(b.Length, buffer.Length - 1)); + } + private readonly byte[] _saveName = new byte[128]; + private readonly byte[] _reach = new byte[16]; + private RynthAiSettings? _settings; // last Settings snapshot (null until fetched) + private long _settingsVersion = -1; + private bool _reachTyping; + private readonly Picker _picker = new("##nav_pick"); + + public void OnShown() + { + UiSources.Nav.Subscribe(); + UiSources.Nav.RequestRefresh(); + UiSources.Settings.Subscribe(); + UiSources.Settings.RequestRefresh(); + } + + public void OnHidden() + { + UiSources.Nav.Unsubscribe(); + UiSources.Settings.Unsubscribe(); + } + + public void Draw() + { + TakeSnapshot(); + float w = Begin(out Vector2 origin, out Vector2 size); + bool typing = false; + NavPayload d = _data; + bool navActive = d.MacroRunning && d.NavigationEnabled; + + // Active nav + status + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + Label(_activeLabel, Amber); + ImGuiNET.ImGui.PopFont(); + if (d.NavStatusLine.Length > 0) Label(d.NavStatusLine, d.NavIsStuck ? Amber : Green); + + // Start / Stop + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (Button("##startstop", navActive ? StopNav : StartNav, p, new Vector2(w, 28), Text, navActive ? StopBg : StartBg)) + { + if (navActive) + { + NavCommands.Send(new NavCmd { Cmd = "stopNav" }); + _data.NavigationEnabled = false; + } + else + { + NavCommands.Send(new NavCmd { Cmd = "startNav" }); + _data.MacroRunning = true; + _data.NavigationEnabled = true; + } + } + NextLine(p, 32); + Separator(w); + + // Route type | Insert mode + p = ImGuiNET.ImGui.GetCursorScreenPos(); + float half = (w - 4) / 2; + if (Button("##route", _routeLabel, p, new Vector2(half, 22), Text, BtnFill, leftAlign: true)) + _picker.Open(new Vector2(p.X, p.Y + 22), NavCommands.RouteTypes, NavCommands.RouteIndex(_data.RouteType), i => + { + int routeType = NavCommands.RouteTypeFor(i); + NavCommands.Send(new NavCmd { Cmd = "setRouteType", RouteType = routeType }); + _data.RouteType = routeType; + UpdateLabels(); + }); + if (Button("##insert", _insertLabel, new Vector2(p.X + half + 4, p.Y), new Vector2(half, 22), Text, BtnFill, leftAlign: true)) + _picker.Open(new Vector2(p.X + half + 4, p.Y + 22), NavCommands.AddModes, _addMode, i => + { + _addMode = i; + UpdateLabels(); + }); + NextLine(p, 26); + + // Breadcrumbs | Route overlay (RynthAi's NavOverlaySettings; saved per character) + p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half, + "Record the trail you walk and draw it on the ground (/ra navtrail on|off).\nTurning it off hides the trail; /ra navtrail clear wipes it.")) + { + bool on = !_data.TrackBreadcrumbs; + NavCommands.Send(new NavCmd { Cmd = "setBreadcrumbs", On = on }); + _data.TrackBreadcrumbs = on; + } + if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half, + "Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\nto the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate.")) + { + bool on = !_data.ShowRouteOverlay; + NavCommands.Send(new NavCmd { Cmd = "setRouteOverlay", On = on }); + _data.ShowRouteOverlay = on; + } + NextLine(p, 26); + + typing |= ReachRow(w); + + // Actions + int action = WrapButtons("nav_act", Actions, w, 24, ActionsEnabled); + switch (action) + { + case 0: NavCommands.Send(new NavCmd { Cmd = "addWaypoint", AddMode = _addMode, InsertAt = _selected }); break; + case 2: + _picker.Open(ImGuiNET.ImGui.GetIO().MousePos, NavCommands.RecallLabels, -1, i => + NavCommands.Send(new NavCmd { Cmd = "addRecall", SpellId = NavCommands.RecallIds[i], AddMode = _addMode, InsertAt = _selected })); + break; + case 3: + NavCommands.Send(new NavCmd { Cmd = "clearRoute" }); + _data.Points.Clear(); + _selected = -1; + RebuildPointText(); + break; + case 4: NavCommands.Send(new NavCmd { Cmd = "saveRoute" }); break; + case 5: NavCommands.Send(new NavCmd { Cmd = "dunPatrol" }); break; + } + + // Chat waypoint: sent as if typed when the route reaches it. Selecting an + // existing chat waypoint loads its command here; Update saves the edit. + bool chatSelected = _selected >= 0 && _selected < _data.Points.Count + && _data.Points[_selected].Type == "Chat"; + if (_selected != _chatLoadedFor) + { + if (chatSelected) SetUtf8(_chat, _data.Points[_selected].Text); + else if (_chatLoadedFor >= 0) Array.Clear(_chat); // leaving a chat point: don't keep its text + _chatLoadedFor = chatSelected ? _selected : -1; + } + p = ImGuiNET.ImGui.GetCursorScreenPos(); + float addW = ButtonWidth(AddChat); + float updW = chatSelected ? ButtonWidth("Update") + 4 : 0; + bool chatEnter = TextBox("##nav_chat", _chat, p, w - addW - updW - 4, "Chat command, e.g. /ub usei Healing Kit", + out bool chatActive, ImGuiInputTextFlags.EnterReturnsTrue); + typing |= chatActive; + bool update = chatSelected + && Button("##updchat", "Update", new Vector2(p.X + w - addW - updW, p.Y), new Vector2(updW - 4, 22), Text, BtnFill); + bool addChat = Button("##addchat", AddChat, new Vector2(p.X + w - addW, p.Y), new Vector2(addW, 22), Text, BtnFill); + if (update || (chatEnter && chatSelected)) + { + string text = Utf8(_chat).Trim(); + if (text.Length > 0) + { + NavCommands.Send(new NavCmd { Cmd = "editChat", Index = _selected, Text = text }); + _data.Points[_selected].Text = text; + _data.Points[_selected].Desc = "[Chat] " + text; + RebuildPointText(); + } + } + else if (chatEnter || addChat) + { + string text = Utf8(_chat).Trim(); + if (text.Length > 0) + { + NavCommands.Send(new NavCmd { Cmd = "addChat", Text = text, AddMode = _addMode, InsertAt = _selected }); + Array.Clear(_chat); + _chatLoadedFor = -1; + } + } + NextLine(p, 26); + + // Save as a named nav + p = ImGuiNET.ImGui.GetCursorScreenPos(); + float saveW = ButtonWidth(SaveAs); + bool saveEnter = TextBox("##nav_saveas", _saveName, p, w - saveW - 4, "Nav name...", out bool saveActive, ImGuiInputTextFlags.EnterReturnsTrue); + typing |= saveActive; + bool saveAs = Button("##saveas", SaveAs, new Vector2(p.X + w - saveW, p.Y), new Vector2(saveW, 22), Text, BtnFill); + if (saveEnter || saveAs) + { + string name = Utf8(_saveName).Trim(); + if (name.Length > 0) + { + NavCommands.Send(new NavCmd { Cmd = "saveRoute", NavName = name }); + Array.Clear(_saveName); + } + } + NextLine(p, 26); + + // Nav file picker + if (_navFiles.Length > 0) + { + p = ImGuiNET.ImGui.GetCursorScreenPos(); + float lw = ImGuiNET.ImGui.CalcTextSize("Nav:").X + 6; + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "Nav:"); + if (Button("##navfile", _fileLabel, new Vector2(p.X + lw, p.Y), new Vector2(w - lw, 22), Text, BtnFill, leftAlign: true)) + _picker.Open(new Vector2(p.X + lw, p.Y + 22), _navFiles, Array.IndexOf(_navFiles, _data.ActiveNavName), i => + NavCommands.Send(new NavCmd { Cmd = "loadNav", NavName = _navFiles[i] })); + NextLine(p, 26); + } + + // Waypoints + Separator(w); + Label($"Waypoints ({_data.Points.Count})", Mute); + float listH = Math.Max(60, Remaining(origin, size)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1)); + ImGuiNET.ImGui.BeginChild("##nav_points", new Vector2(w, listH)); + Waypoints(ImGuiNET.ImGui.GetContentRegionAvail().X); + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + + _typing = typing; + End(origin, size); + _picker.Draw(); + } + + /// <summary> + /// A checkbox-style toggle button: ticked box and teal text when on, empty box and muted + /// text when off. Returns true when clicked (the caller flips the value). + /// </summary> + private static bool OverlayToggle(string id, string label, bool on, Vector2 pos, float width, string tooltip) + { + string text = (on ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " " + label; + bool clicked = Button(id, text, pos, new Vector2(width, 22), on ? Teal : Mute, BtnFill, leftAlign: true); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tooltip); + return clicked; + } + + /// <summary> + /// Nav point reach (yd): how close nav gets to each nav point before moving on. Label, + /// [-] value [+]; the typed value commits on Enter or when the box loses focus. Saves the + /// whole settings payload (a copy of the latest snapshot), as the Settings face does. + /// Hidden until RynthAi's settings have been fetched. Returns true while typing. + /// </summary> + private bool ReachRow(float w) + { + var snap = UiSources.Settings.Current; + if (snap != null && snap.Version != _settingsVersion && !_reachTyping) + { + _settingsVersion = snap.Version; + _settings = snap.Value.Clone(); + WriteUtf8(_reach, _settings.FollowNavMin.ToString("0.0#", CultureInfo.InvariantCulture)); + } + if (_settings == null) return false; + + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + string label = SettingsSchema.NavPointReachLabel; + float labelW = ImGuiNET.ImGui.CalcTextSize(label).X; + dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, label); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.InvisibleButton("##reach_label", new Vector2(Math.Max(1, labelW), 22)); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(SettingsSchema.NavPointReachTip); + + const float stepW = 22, boxW = 52; + float right = p.X + w; + float value = _settings.FollowNavMin; + if (Button("##reach_minus", "-", new Vector2(right - stepW * 2 - boxW - 8, p.Y), new Vector2(stepW, 22), Text, BtnFill)) + SaveReach(value - 0.1f); + bool enter = TextBox("##reach", _reach, new Vector2(right - stepW - boxW - 4, p.Y), boxW, "", + out bool active, ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.EnterReturnsTrue); + bool commit = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); + if (Button("##reach_plus", "+", new Vector2(right - stepW, p.Y), new Vector2(stepW, 22), Text, BtnFill)) + SaveReach(value + 0.1f); + if (commit) + { + if (float.TryParse(Utf8(_reach), NumberStyles.Float, CultureInfo.InvariantCulture, out float typed)) SaveReach(typed); + else WriteUtf8(_reach, value.ToString("0.0#", CultureInfo.InvariantCulture)); // bad input reverts + } + _reachTyping = active; + NextLine(p, 26); + return active; + } + + private void SaveReach(float yards) + { + if (_settings == null || float.IsNaN(yards)) return; + yards = MathF.Round(Math.Clamp(yards, 0.5f, 20f) * 10f) / 10f; + _settings.FollowNavMin = yards; + WriteUtf8(_reach, yards.ToString("0.0#", CultureInfo.InvariantCulture)); + SettingsCommands.Save(_settings.Clone()); + } + + private void Waypoints(float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 clipMin = ImGuiNET.ImGui.GetWindowPos(), clipMax = clipMin + ImGuiNET.ImGui.GetWindowSize(); + for (int i = 0; i < _data.Points.Count; i++) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float h = 22; + if (p.Y + h < clipMin.Y || p.Y > clipMax.Y) { ImGuiNET.ImGui.Dummy(new Vector2(w, h)); continue; } + bool active = i == _data.ActiveNavIndex, selected = i == _selected; + ImGuiNET.ImGui.PushID(i); + // Row click selects (drawn first so the X button on top wins). + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.SetNextItemAllowOverlap(); // the X button on top gets its clicks + if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) _selected = i; + dl.AddRectFilled(p, p + new Vector2(w, h), selected ? Selected : i % 2 == 0 ? PanelBg : RowAlt); + if (IconButton("##del", PhosphorIcons.X, new Vector2(p.X + 2, p.Y + 2), new Vector2(18, 18), Text, DeleteBg, font: UiFont.Ui11)) + { + NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i }); + if (_selected == i) _selected = -1; + else if (_selected > i) _selected--; + _data.Points.RemoveAt(i); + RebuildPointText(); + ImGuiNET.ImGui.PopID(); + return; + } + float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + if (active) dl.AddText(new Vector2(p.X + 24, ty), Teal, "=>"); + dl.PushClipRect(p, p + new Vector2(w - 2, h), true); + dl.AddText(new Vector2(p.X + 44, ty), active ? Teal : Text, i < _pointText.Count ? _pointText[i] : ""); + dl.PopClipRect(); + ImGuiNET.ImGui.PopID(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h)); + ImGuiNET.ImGui.Dummy(new Vector2(w, 0)); + } + } + + private void TakeSnapshot() + { + var snap = UiSources.Nav.Current; + if (snap == null || snap.Version == _seenVersion || _typing) return; + _seenVersion = snap.Version; + _data = snap.Value.Clone(); + _navFiles = _data.NavFiles.ToArray(); + if (_selected >= _data.Points.Count) _selected = -1; + RebuildPointText(); + UpdateLabels(); + } + + private void RebuildPointText() + { + _pointText.Clear(); + for (int i = 0; i < _data.Points.Count; i++) _pointText.Add(NavCommands.PointText(_data.Points[i], i)); + } + + private void UpdateLabels() + { + _activeLabel = "Active Nav: " + (string.IsNullOrEmpty(_data.ActiveNavName) ? "None (Unsaved)" : _data.ActiveNavName); + _routeLabel = "Route: " + NavCommands.RouteTypes[NavCommands.RouteIndex(_data.RouteType)]; + _insertLabel = "Insert: " + NavCommands.AddModes[_addMode]; + int fileIdx = string.IsNullOrEmpty(_data.ActiveNavName) ? -1 : _data.NavFiles.IndexOf(_data.ActiveNavName); + _fileLabel = fileIdx >= 0 ? _data.NavFiles[fileIdx] : "Select nav file..."; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs new file mode 100644 index 0000000..b2015ec --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs @@ -0,0 +1,286 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/P1Faces.cs +// ImGui faces of the Status, Log and Tracker panels +// (docs/IMGUI_PARITY_PLAN.md §2.11, §2.12). Each mirrors its Avalonia face in +// UI/Panels and reads the same UiDataHub snapshot. AC thread only; strings +// are built when a snapshot changes, not per frame. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class P1Faces +{ + /// <summary>Registers the P1 faces next to their Avalonia faces (EntryPoint).</summary> + public static void Register(bool trackerPresent) + { + // Status and Log end in a footer of left-aligned buttons: the resize grip + // sits beside it, over the body (GripInBody), instead of in a strip below. + var standard = new PanelSpec(new Vector2(400, 500), new Vector2(320, 240), GripInBody: true); + ImGuiPanelHost.Register("Status", standard, () => new StatusFace()); + ImGuiPanelHost.Register("Log", standard, () => new LogFace()); + if (trackerPresent) + ImGuiPanelHost.Register("Tracker", + new PanelSpec(new Vector2(165, 190), new Vector2(60, 20), Background: 0, GripInBody: true), + () => new TrackerFace()); + // The Skills panel: an engine panel with only an ImGui face, needing no plugin. + // Registered here so engine init needs no new line in EntryPoint; ImGuiBar gives + // it a bar button (ImGuiOnlyPanels). + SkillsFace.Register(); + // Sense (watch list of names, anywhere the client knows): ImGui only, like Skills. + SenseFace.Register(); + } +} + +/// <summary>Status: engine facts, plugin rows, and each panel's face.</summary> +internal sealed class StatusFace : IImGuiPanel +{ + private static readonly Vector4 HeaderColor = RynthTheme.Vec(0xC88CC8FF); + private static readonly Vector4 RowColor = RynthTheme.Vec(0xC8D2D2D2); + private static readonly Vector4 ErrorColor = RynthTheme.Vec(0xDCFF6464); + + private string[] _engineRows = Array.Empty<string>(); + private long _pluginVersion = -1; + private string _pluginHeader = "Plugins"; + private readonly List<(string Text, bool Error)> _pluginRows = new(); + private List<string> _faceRows = new(); + private long _faceRowsTick; + + public void OnShown() + { + UiSources.PluginStatus.Subscribe(); + UiSources.PluginStatus.RequestRefresh(); + BuildEngineRows(); + } + + private void BuildEngineRows() + { + _engineRows = new[] + { + $"Version: {EntryPoint.BuildStamp}", + $"Game HWND: 0x{EntryPoint.GameHwnd:X8}", + $"Plugin dir: {PluginManager.PluginDirectory}", + }; + } + + public void OnHidden() => UiSources.PluginStatus.Unsubscribe(); + + public void Draw() + { + RefreshCaches(); + float footer = ImGuiNET.ImGui.GetFrameHeightWithSpacing(); + ImGuiNET.ImGui.BeginChild("##status", new Vector2(0, -footer)); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + + Header("Engine"); + foreach (string row in _engineRows) Row(row, false); + Separator(); + Header(_pluginHeader); + if (_pluginRows.Count == 0) Row("None loaded", false); + foreach (var (text, error) in _pluginRows) Row(text, error); + Separator(); + Header("UI faces"); + foreach (string row in _faceRows) Row(row, false); + + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.EndChild(); + + if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowsClockwise + " Refresh")) + { + UiSources.PluginStatus.RequestRefresh(); + _faceRowsTick = 0; + BuildEngineRows(); + } + } + + private void RefreshCaches() + { + var snap = UiSources.PluginStatus.Current; + if (snap != null && snap.Version != _pluginVersion) + { + _pluginVersion = snap.Version; + _pluginHeader = $"Plugins ({snap.Value.Length})"; + _pluginRows.Clear(); + foreach (PluginStatusRow r in snap.Value) + _pluginRows.Add(($"{r.Label}: {r.State}", r.IsError)); + } + + long now = Environment.TickCount64; + if (now - _faceRowsTick > 2000) + { + _faceRowsTick = now; + _faceRows = PanelRouter.Describe(); + } + } + + private static void Header(string text) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextColored(HeaderColor, text); + ImGuiNET.ImGui.PopFont(); + } + + private static void Row(string text, bool error) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, error ? ErrorColor : RowColor); + ImGuiNET.ImGui.TextWrapped(text); + ImGuiNET.ImGui.PopStyleColor(); + } + + private static void Separator() + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X; + ImGuiNET.ImGui.GetWindowDrawList().AddLine(p, p + new Vector2(w, 0), RynthTheme.Argb(0x3CFFFFFF)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + } +} + +/// <summary>Log: the engine's recent-log ring, monospace, with Auto-scroll and Clear.</summary> +internal sealed unsafe class LogFace : IImGuiPanel +{ + private ImGuiListClipper* _clipper; + private bool _autoScroll = true; + private long _clearedSeq; + private long _seenVersion = -1; + + public void OnShown() + { + UiSources.Log.Subscribe(); + UiSources.Log.RequestRefresh(); + _clipper = ImGuiNative.ImGuiListClipper_ImGuiListClipper(); + } + + public void OnHidden() + { + UiSources.Log.Unsubscribe(); + if (_clipper != null) ImGuiNative.ImGuiListClipper_destroy(_clipper); + _clipper = null; + } + + public void Draw() + { + var snap = UiSources.Log.Current; + bool changed = snap != null && snap.Version != _seenVersion; + if (snap != null) _seenVersion = snap.Version; + + float footer = ImGuiNET.ImGui.GetFrameHeightWithSpacing(); + ImGuiNET.ImGui.BeginChild("##lines", new Vector2(0, -footer)); + if (snap != null && _clipper != null) + { + LogSnapshot log = snap.Value; + // Clear hides everything up to the sequence number it saw, so it keeps + // working after the 256-line ring wraps (Avalonia bug A6). + int start = (int)Math.Clamp(_clearedSeq - log.FirstSeq + 1, 0, log.Lines.Length); + int count = log.Lines.Length - start; + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono10)); + var clipper = new ImGuiListClipperPtr(_clipper); + clipper.Begin(count); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + ImGuiNET.ImGui.TextUnformatted(log.Lines[start + i]); + clipper.End(); + ImGuiNET.ImGui.PopFont(); + + if (changed && _autoScroll) + ImGuiNET.ImGui.SetScrollHereY(1f); + } + ImGuiNET.ImGui.EndChild(); + + ImGuiNET.ImGui.Checkbox("Auto-scroll", ref _autoScroll); + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.Button(PhosphorIcons.Eraser + " Clear")) + _clearedSeq = snap?.Value.LastSeq ?? EntryPoint.RecentLogSeq; + } +} + +/// <summary>Tracker: nine session-stat rows over an adjustable-opacity background.</summary> +internal sealed class TrackerFace : IImGuiPanel +{ + private static readonly Vector4 TitleColor = RynthTheme.Vec(0xFFE6B450); + private static readonly Vector4 LabelColor = RynthTheme.Vec(0xFF999999); + private static readonly uint ResetBg = RynthTheme.Argb(0xFF1A2E40); + private static readonly uint ResetBorder = RynthTheme.Argb(0xFF264C59); + private int _opacity; + + public void OnShown() + { + UiSources.Tracker.Subscribe(); + UiSources.Tracker.RequestRefresh(); + _opacity = (int)Math.Round(TrackerSettings.BgAlpha / 2.55); + } + + public void OnHidden() => UiSources.Tracker.Unsubscribe(); + + public void Draw() + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + // Background behind the content only (like the Avalonia StackPanel), so + // content goes on channel 1 and the rect, sized afterwards, on channel 0. + dl.ChannelsSplit(2); + dl.ChannelsSetCurrent(1); + Vector2 top = ImGuiNET.ImGui.GetCursorScreenPos() - ImGuiNET.ImGui.GetStyle().WindowPadding; + float width = ImGuiNET.ImGui.GetWindowWidth(); + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + + // Title row: [Tracker] [===slider===] [reset] + ImGuiNET.ImGui.TextColored(TitleColor, "Tracker"); + ImGuiNET.ImGui.SameLine(); + float resetW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.ArrowCounterClockwise).X + 8; + ImGuiNET.ImGui.SetNextItemWidth(Math.Max(10, ImGuiNET.ImGui.GetContentRegionAvail().X - resetW - 4)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(2, 0)); + if (ImGuiNET.ImGui.SliderInt("##opacity", ref _opacity, 0, 100, "")) + TrackerSettings.SetBgAlpha((byte)Math.Round(_opacity * 2.55), save: false); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + TrackerSettings.SetBgAlpha((byte)Math.Round(_opacity * 2.55), save: true); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, ResetBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, ResetBorder); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 1)); + if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + "##reset")) + UiSources.Tracker.RequestReset(); + ImGuiNET.ImGui.SetItemTooltip("Reset the session stats"); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + + TrackerSnapshot? snap = UiSources.Tracker.Current?.Value; + string[]? values = snap?.Values; + string[] labels = snap?.Labels ?? TrackerSnapshot.DefaultLabels; + // The resize grip sits over the body's bottom-right corner (GripInBody): a + // row that reaches down into it right-aligns its value short of it. + float grip = ImGuiPanelHost.BodyGripReserve; + float gripTop = grip > 0 ? ImGuiNET.ImGui.GetWindowPos().Y + ImGuiNET.ImGui.GetWindowHeight() - grip : float.MaxValue; + float rowH = ImGuiNET.ImGui.GetTextLineHeight(); + for (int i = 0; i < labels.Length; i++) + { + float rowRight = ImGuiNET.ImGui.GetCursorPosX() + ImGuiNET.ImGui.GetContentRegionAvail().X; + if (ImGuiNET.ImGui.GetCursorScreenPos().Y + rowH > gripTop) rowRight -= grip; + ImGuiNET.ImGui.TextColored(LabelColor, labels[i]); + string value = values != null && i < values.Length ? values[i] : "—"; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono9)); + float w = ImGuiNET.ImGui.CalcTextSize(value).X; + ImGuiNET.ImGui.SameLine(Math.Max(0, rowRight - w)); + ImGuiNET.ImGui.TextUnformatted(value); + ImGuiNET.ImGui.PopFont(); + } + ImGuiNET.ImGui.PopFont(); + + float bottom = ImGuiNET.ImGui.GetCursorScreenPos().Y; + dl.ChannelsSetCurrent(0); + uint bg = RynthTheme.Argb(((uint)TrackerSettings.BgAlpha << 24) | 0x0A121A); + dl.AddRectFilled(top, new Vector2(top.X + width, bottom), bg); + dl.ChannelsMerge(); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs new file mode 100644 index 0000000..2326b35 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs @@ -0,0 +1,682 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RadarFace.cs +// ImGui face of the Radar (docs/IMGUI_PARITY_PLAN.md §2.2), drawn the way +// the Avalonia face's RadarSurface.Render does: gold rim, canvas, crosshair, +// floors (current layer full, the one above and below at 30%) with slope +// tints, walls (blue when visited), visited overlay, markers, player arrow, +// outlined compass on the playfield perimeter, coordinate strip. Top-right +// pop-out and settings (gear) buttons, wheel zoom, left-drag moves, left-click on a dot +// selects it in game by object id (hover: name, distance, health), right-click menu, settings +// popup. Settings are shared with the Avalonia face (RadarSettingsStore). +// Marker kinds (RadarKind) each have a shape (RadarMarkerStyle), a show box +// and a colour the user can pick; the settings popup doubles as the legend. +// +// Data: UiSources.Radar (RadarView, lookups precomputed). World geometry is +// drawn without anti-aliasing (crisp tiling like the Avalonia face's aliased +// mode, and far fewer vertices for big dungeons); no per-frame allocation. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; +using RynthCore.Engine.UI.Panels; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class RadarFace : IImGuiPanel +{ + public const string Title = "Radar"; + + public static void Register() + { + ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(320, 320), new Vector2(120, 120), PanelChrome.None, + Background: 0, Rounding: 0, EdgeToEdge: true, GoldGrip: true), + () => new RadarFace()); + // The Inventory panel (engine data only, like the radar): registered here so + // engine init needs no new line in EntryPoint (as LootEditor / DungeonMap + // register from RynthAiFace). Opened from the bar and /rc inv. + InventoryFace.Register(); + } + + // ── Palette (RadarPanel's, ARGB) ──────────────────────────────────── + private const uint FrameOuterArgb = 0xFF0A0D14, CanvasBgArgb = 0xFF0A121A; + private static readonly uint FrameInner = C(0xFF9E853D), FrameAccent = C(0xFFE6C766), + Crosshair = C(0x994D6680), Cardinal = C(0xFFFFFFFF), CoordText = C(0xFFF2F8FF), Outline = C(0xF2000000), + PlayerCol = C(0xFF33FF66), ButtonBg = C(0xC0141F29), ButtonBorder = C(0xFF34587A); + // Marker colours per kind (RadarSettingsStore.KindColors, user-pickable), refreshed each frame. + private static readonly uint[] KindCols = new uint[RadarKind.Count]; + private const uint WallUnseen = 0xFFFFFFFF, WallVisited = 0xFF4099FF, FloorFlat = 0x8C2E8C38, + FloorUp = 0x668C1F14, FloorDown = 0x661A8026, FloorVisited = 0xA64D6B94; + private static uint C(uint argb) => RynthTheme.Argb(argb); + + /// <summary>ARGB colour with its alpha scaled, as an ImGui colour.</summary> + private static uint MulAlpha(uint argb, float k) => + RynthTheme.Argb((argb & 0x00FFFFFF) | ((uint)Math.Clamp((int)MathF.Round((argb >> 24) * k), 0, 255) << 24)); + + private static readonly (string Label, float WorldX, float WorldY)[] Compass = + { ("N", 0, 1), ("E", 1, 0), ("S", 0, -1), ("W", -1, 0) }; + + private bool _settingsOpen; + + /// <summary>Markers move: popped out, redraw smoothly even when idle.</summary> + public int PopOutIdleHz => 20; + + public bool ClickThrough => + RadarSettingsStore.CtrlGatedClickThrough && !ImGuiNET.ImGui.GetIO().KeyCtrl; + + public void OnShown() + { + RadarSettingsStore.Load(); + UiSources.Radar.Subscribe(); + UiSources.Radar.RequestRefresh(); + } + + public void OnHidden() => UiSources.Radar.Unsubscribe(); + + public void Draw() + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail(); + if (size.X < 16 || size.Y < 16) return; + RadarView? view = UiSources.Radar.Current?.Value; + + bool rim = RadarSettingsStore.ShowGoldRim; + float canvasInset = rim ? 5 : 0; + const float coordStrip = 14; + float opacity = Math.Clamp(RadarSettingsStore.Opacity, 0f, 1f); + Vector2 frameMax = origin + size; + + // ── Frame: outer black (fades) + gold inner border + accent ── + if (rim) + { + dl.AddRectFilled(origin, frameMax, MulAlpha(FrameOuterArgb, opacity)); + dl.AddRect(origin + new Vector2(1, 1), frameMax - new Vector2(1, 1), FrameInner, 0, ImDrawFlags.None, 2); + dl.AddRect(origin + new Vector2(3, 3), frameMax - new Vector2(3, 3), FrameAccent, 0, ImDrawFlags.None, 1); + } + + // ── Canvas and world playfield (canvas minus the coord strip) ── + Vector2 canvasMin = origin + new Vector2(canvasInset, canvasInset); + Vector2 canvasMax = frameMax - new Vector2(canvasInset, canvasInset); + dl.AddRectFilled(canvasMin, canvasMax, MulAlpha(CanvasBgArgb, opacity)); + var worldMin = canvasMin; + var worldMax = new Vector2(canvasMax.X, canvasMax.Y - coordStrip); + Vector2 centre = (worldMin + worldMax) * 0.5f; + dl.AddLine(new Vector2(centre.X, worldMin.Y), new Vector2(centre.X, worldMax.Y), Crosshair); + dl.AddLine(new Vector2(worldMin.X, centre.Y), new Vector2(worldMax.X, centre.Y), Crosshair); + + if (view != null) + { + ImDrawListFlags saved = dl.Flags; + dl.Flags = saved & ~(ImDrawListFlags.AntiAliasedLines | ImDrawListFlags.AntiAliasedLinesUseTex | ImDrawListFlags.AntiAliasedFill); + dl.PushClipRect(worldMin, worldMax, true); + DrawWorld(dl, view, centre, worldMin, worldMax); + dl.PopClipRect(); + dl.Flags = saved; + + DrawOutlinedText(dl, ImGuiFonts.Get(UiFont.UiBold11), view.CoordText, + new Vector2((canvasMin.X + canvasMax.X) * 0.5f, canvasMax.Y), CoordText, alignBottom: true); + DrawCardinals(dl, view, centre, (worldMax.X - worldMin.X) * 0.5f, (worldMax.Y - worldMin.Y) * 0.5f); + } + + // ── Buttons (submitted before the surface so they win the hover) ── + const float btn = 22, gap = 4, inset = 6; + var gearPos = new Vector2(frameMax.X - inset - btn, origin.Y + inset); + var popPos = gearPos - new Vector2(btn + gap, 0); + if (PanelRouter.CanPopOut) + { + if (IconButton("##radar_pop", popPos, ImGuiPanelHost.PopOutGlyph)) + ImGuiPanelHost.TogglePopOut(Title); + ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); + } + bool gear = IconButton("##radar_gear", gearPos, PhosphorIcons.Gear); + ImGuiNET.ImGui.SetItemTooltip("Radar settings"); + if (gear) + { + if (_settingsOpen) _settingsOpen = false; + else + { + _settingsOpen = true; + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(gearPos.X + btn, gearPos.Y + btn + 4), ImGuiCond.Always, new Vector2(1, 0)); + } + } + + // ── Surface: drag moves the panel, a click on a dot selects, wheel zooms, right-click menu ── + ImGuiNET.ImGui.SetCursorScreenPos(origin); + bool surfaceClicked = ImGuiNET.ImGui.InvisibleButton("##radar_surface", size); + ImGuiPanelHost.DragWindowWithLastItem(); + if (view != null && RadarSettingsStore.ClickToSelect) + MarkerInput(dl, view, centre, worldMin, worldMax, surfaceClicked); + if (ImGuiNET.ImGui.IsItemHovered()) + { + float wheel = ImGuiNET.ImGui.GetIO().MouseWheel; + if (wheel != 0) + { + float next = Math.Clamp(RadarSettingsStore.Zoom + wheel * 0.15f, 0.5f, 6.0f); + if (next != RadarSettingsStore.Zoom) { RadarSettingsStore.Zoom = next; RadarSettingsStore.Save(); } + } + } + if (ImGuiNET.ImGui.BeginPopupContextItem("##radar_menu")) + { + if (PanelRouter.CanPopOut && ImGuiNET.ImGui.MenuItem(ImGuiPopOuts.InPopOutFrame ? "Dock back" : "Pop out")) + ImGuiPanelHost.TogglePopOut(Title); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Rotate with player", "", RadarSettingsStore.RotateWithPlayer)) + { + RadarSettingsStore.RotateWithPlayer = !RadarSettingsStore.RotateWithPlayer; + RadarSettingsStore.Save(); + } + ImGuiPanelHost.TextSizeMenu(Title); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Close")) + ImGuiPanelHost.Close(Title); + ImGuiNET.ImGui.EndPopup(); + } + + SettingsWindow(); + } + + // ── World ───────────────────────────────────────────────────────────── + + /// <summary>World (AC x east, y north) → screen, north-up or rotated so facing is up.</summary> + private readonly struct Projection + { + private readonly float _cx, _cy, _pwx, _pwy, _sin, _cos, _zoom; + private readonly bool _rotate; + + public Projection(Vector2 centre, RadarPlayer p, bool rotate, float zoom) + { + _cx = centre.X; _cy = centre.Y; _pwx = p.WorldX; _pwy = p.WorldY; + float h = p.Heading * MathF.PI / 180f; // AC: 0 = east, 90 = north + _sin = MathF.Sin(h); _cos = MathF.Cos(h); + _rotate = rotate; _zoom = zoom; + } + + public float Sin => _sin; + public float Cos => _cos; + + public Vector2 P(float wx, float wy) + { + float dx = wx - _pwx, dy = wy - _pwy; + if (_rotate) + { + float right = _sin * dx - _cos * dy; + float forward = _cos * dx + _sin * dy; + return new Vector2(_cx + right * _zoom, _cy - forward * _zoom); + } + return new Vector2(_cx + dx * _zoom, _cy - dy * _zoom); + } + } + + private static void DrawWorld(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax) + { + RadarSnapshot live = view.Live; + bool rotate = RadarSettingsStore.RotateWithPlayer; + var proj = new Projection(centre, live.Player, rotate, MathF.Max(0.5f, RadarSettingsStore.Zoom)); + + int cur = view.CurrentLayer, count = live.LayerZs.Count; + // Same order as the Avalonia/ImGui-era radar: below, above (dimmed), current. + if (cur - 1 >= 0) DrawLayer(dl, view, cur - 1, 0.30f, false, proj, rotate, clipMin, clipMax); + if (cur + 1 < count && cur >= 0) DrawLayer(dl, view, cur + 1, 0.30f, false, proj, rotate, clipMin, clipMax); + if (cur >= 0) DrawLayer(dl, view, cur, 1.00f, true, proj, rotate, clipMin, clipMax); + + // Markers (shapes: RadarMarkerStyle). Corpses and items first, creatures on top. + RadarMarkerStyle.FillColors(KindCols); + for (int pass = 0; pass < 2; pass++) + { + foreach (RadarMarker m in live.Markers) + { + if (!RadarSettingsStore.ShowKind(m.Kind)) continue; + if ((pass == 1) != (RadarKind.IsCreature(m.Kind) || m.Kind is RadarKind.Portal or RadarKind.Door)) continue; + Vector2 pp = proj.P(m.X, m.Y); + if (pp.X < clipMin.X || pp.X > clipMax.X || pp.Y < clipMin.Y || pp.Y > clipMax.Y) continue; + RadarMarkerStyle.Draw(dl, m.Kind, pp, KindCols[m.Kind]); + } + } + + // Player dot + 10 px heading arrow (always up when rotating). + dl.AddCircleFilled(centre, 3.5f, PlayerCol, 10); + Vector2 tip = rotate ? centre + new Vector2(0, -10) : centre + new Vector2(proj.Cos * 10, -proj.Sin * 10); + dl.AddLine(centre, tip, PlayerCol, 2); + } + + private static void DrawLayer(ImDrawListPtr dl, RadarView view, int layer, float a, bool current, + in Projection proj, bool rotate, Vector2 clipMin, Vector2 clipMax) + { + // Floor strips: 5 floats (x0, y0, x1, y1, type). + if (view.FillsByLayer[layer] is float[] strips) + { + uint flat = MulAlpha(FloorFlat, a), up = MulAlpha(FloorUp, a), down = MulAlpha(FloorDown, a); + for (int i = 0; i + 4 < strips.Length; i += 5) + { + int type = (int)strips[i + 4]; + uint col = type == 1 ? up : type == 2 ? down : flat; + FillRect(dl, proj, rotate, strips[i], strips[i + 1], strips[i + 2], strips[i + 3], col, clipMin, clipMax); + } + } + + // Walls: 6 floats (ax, ay, bx, by, cell x, cell y); visited tint on the current layer. + if (view.WallsByLayer[layer] is float[] segs) + { + uint unseen = MulAlpha(WallUnseen, a), visited = MulAlpha(WallVisited, a); + float thick = current ? 1.5f : 1.0f; + bool[]? flags = current ? view.CurrentWallVisited : null; + for (int i = 0, w = 0; i + 5 < segs.Length; i += 6, w++) + { + Vector2 pa = proj.P(segs[i], segs[i + 1]); + Vector2 pb = proj.P(segs[i + 2], segs[i + 3]); + if (MathF.Max(pa.X, pb.X) < clipMin.X || MathF.Min(pa.X, pb.X) > clipMax.X || + MathF.Max(pa.Y, pb.Y) < clipMin.Y || MathF.Min(pa.Y, pb.Y) > clipMax.Y) continue; + bool v = flags != null && w < flags.Length && flags[w]; + dl.AddLine(pa, pb, v ? visited : unseen, thick); + } + } + + // Visited overlay (current layer only): 4 floats per strip. + if (current && view.VisitedByLayer[layer] is float[] vStrips) + { + uint fill = MulAlpha(FloorVisited, a); + for (int i = 0; i + 3 < vStrips.Length; i += 4) + FillRect(dl, proj, rotate, vStrips[i], vStrips[i + 1], vStrips[i + 2], vStrips[i + 3], fill, clipMin, clipMax); + } + } + + private static void FillRect(ImDrawListPtr dl, in Projection proj, bool rotate, float x0, float y0, float x1, float y1, + uint col, Vector2 clipMin, Vector2 clipMax) + { + Vector2 p00 = proj.P(x0, y0), p11 = proj.P(x1, y1); + if (rotate) + { + Vector2 p10 = proj.P(x1, y0), p01 = proj.P(x0, y1); + float minX = MathF.Min(MathF.Min(p00.X, p11.X), MathF.Min(p10.X, p01.X)); + float maxX = MathF.Max(MathF.Max(p00.X, p11.X), MathF.Max(p10.X, p01.X)); + float minY = MathF.Min(MathF.Min(p00.Y, p11.Y), MathF.Min(p10.Y, p01.Y)); + float maxY = MathF.Max(MathF.Max(p00.Y, p11.Y), MathF.Max(p10.Y, p01.Y)); + if (maxX < clipMin.X || minX > clipMax.X || maxY < clipMin.Y || minY > clipMax.Y) return; + dl.AddQuadFilled(p00, p10, p11, p01, col); + } + else + { + var a = Vector2.Min(p00, p11); + var b = Vector2.Max(p00, p11); + if (b.X < clipMin.X || a.X > clipMax.X || b.Y < clipMin.Y || a.Y > clipMax.Y) return; + dl.AddRectFilled(a, b, col); + } + } + + // ── Click-to-select ───────────────────────────────────────────────────── + // Left-click a dot: that object is selected in game, as a click on it in the + // 3D world would. A press that moves more than a few pixels is a drag (the + // panel moves) and selects nothing. Hover shows the object's name and + // distance (and its last known health, when the engine has seen one). + // RynthAi 2026-10-01 and later send each marker's object id, and the click + // selects exactly that id. Older RynthAi builds send no id (Id = 0): then + // the clicked marker is matched to the client's object list by position + // (the engine's ~0.1 s position snapshot, same landblock, name preferred), + // which can pick the wrong one of two same-name monsters close together. + // The select itself is queued for AC's main thread + // (AcMainThreadQueue.EnqueueOverlaySelect), which re-checks the object + // still exists before selecting. + + private const float ClickSlop = 4f; // px a press may move and still be a click + private const float MatchTolerance = 5f; // metres between a marker and its object (snapshot lag) + private const uint TypeCreature = 0x10, TypePortal = 0x10000; + + private Vector2 _pressPos; + private float _pressTravel; + private byte _tipKind = byte.MaxValue; + private string? _tipLabel; + private int _tipDistance = int.MinValue; + private int _tipPct = -1; + private string _tipText = ""; + + private void MarkerInput(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax, bool clicked) + { + Vector2 mouse = ImGuiNET.ImGui.GetIO().MousePos; + if (ImGuiNET.ImGui.IsItemActivated()) + { + _pressPos = mouse; + _pressTravel = 0f; + } + if (ImGuiNET.ImGui.IsItemActive()) + { + _pressTravel = MathF.Max(_pressTravel, Vector2.Distance(mouse, _pressPos)); + // Popped out, a 2 px drag hands the move to the OS window (DragWindowWithLastItem), + // which then follows the cursor: the context's mouse barely moves, so mark it a drag. + if (ImGuiPopOuts.InPopOutFrame && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 2f)) + _pressTravel = float.MaxValue; + } + + bool hovered = ImGuiNET.ImGui.IsItemHovered(); + if (!hovered && !clicked) return; + if (mouse.X < clipMin.X || mouse.X > clipMax.X || mouse.Y < clipMin.Y || mouse.Y > clipMax.Y) return; + + float zoom = MathF.Max(0.5f, RadarSettingsStore.Zoom); + var proj = new Projection(centre, view.Live.Player, RadarSettingsStore.RotateWithPlayer, zoom); + // Hit radius: a little more than the dot, growing with zoom, in UI-scaled pixels. + float radius = Math.Clamp(5f + 1.5f * zoom, 6f, 14f) * MathF.Max(1f, EngineFrameController.FontScale); + RadarMarker? hit = MarkerAt(view, proj, mouse, radius, clipMin, clipMax, out Vector2 hitPos); + if (hit == null) return; + + if (clicked && _pressTravel <= ClickSlop) + { + uint id = hit.Id != 0 ? hit.Id : ResolveMarker(view, hit); + if (id != 0) + Compatibility.AcMainThreadQueue.EnqueueOverlaySelect(id); + return; + } + + if (!hovered || ImGuiNET.ImGui.IsItemActive()) return; + dl.PushClipRect(clipMin, clipMax, true); + dl.AddCircle(hitPos, 6.5f, CoordText, 16, 1.5f); + dl.PopClipRect(); + ImGuiNET.ImGui.BeginTooltip(); + ImGuiNET.ImGui.TextUnformatted(TipText(view, hit)); + ImGuiNET.ImGui.EndTooltip(); + } + + /// <summary>The shown marker nearest <paramref name="mouse"/> within <paramref name="radius"/> px, or null.</summary> + private static RadarMarker? MarkerAt(RadarView view, in Projection proj, Vector2 mouse, float radius, + Vector2 clipMin, Vector2 clipMax, out Vector2 at) + { + RadarMarker? best = null; + float bestD2 = radius * radius; + at = default; + foreach (RadarMarker m in view.Live.Markers) + { + if (!RadarSettingsStore.ShowKind(m.Kind)) continue; + Vector2 pp = proj.P(m.X, m.Y); + if (pp.X < clipMin.X || pp.X > clipMax.X || pp.Y < clipMin.Y || pp.Y > clipMax.Y) continue; + float d2 = Vector2.DistanceSquared(pp, mouse); + if (d2 > bestD2) continue; + bestD2 = d2; + best = m; + at = pp; + } + return best; + } + + /// <summary> + /// The object a marker stands for: the nearest object in the player's landblock + /// (world = landblock-local + 192 m per landblock step, as the radar's markers) + /// of the marker's kind, within <see cref="MatchTolerance"/>; a name match wins + /// over a slightly nearer stranger. 0 when nothing matches. Only for markers + /// without an id (older RynthAi builds). + /// </summary> + private static uint ResolveMarker(RadarView view, RadarMarker m) + { + uint landblock = view.Live.Player.Landblock; + if (landblock == 0) return 0; + uint playerId = Compatibility.ClientHelperHooks.GetPlayerId(); + string? label = string.IsNullOrEmpty(m.Label) ? null : m.Label; + const float tol2 = MatchTolerance * MatchTolerance; + uint best = 0; + float bestScore = float.MaxValue; + foreach (uint id in Compatibility.ClientObjectHooks.LiveObjectIds) + { + if (id == 0 || id == playerId) continue; + if (!Compatibility.ClientObjectHooks.TryGetSnapshotPosition(id, out uint cell, out float x, out float y, out float z)) continue; + if ((cell >> 16) != landblock) continue; + float dx = x + ((cell >> 24) & 0xFF) * 192f - m.X; + float dy = y + ((cell >> 16) & 0xFF) * 192f - m.Y; + float dz = z - m.Z; + float d2 = dx * dx + dy * dy + dz * dz; + if (d2 > tol2) continue; + if (m.Kind <= 2) + { + if (!Compatibility.ClientObjectHooks.TryGetSnapshotItemType(id, out uint type)) continue; + uint need = m.Kind == 2 ? TypePortal : TypeCreature; + if ((type & need) == 0) continue; + } + bool named = label != null && Compatibility.ClientObjectHooks.TryGetSnapshotName(id, out string name) + && name.Equals(label, StringComparison.Ordinal); + float score = named ? d2 : d2 + tol2; + if (score < bestScore) { bestScore = score; best = id; } + } + return best; + } + + /// <summary> + /// "Name\n12 yd" for the hovered marker, plus " 75%" when the marker has an id and + /// the engine has a health reading for it (MonsterHudData: one locked lookup, hover + /// only). Rebuilt only when the marker, whole yards or whole percent change. + /// </summary> + private string TipText(RadarView view, RadarMarker m) + { + RadarPlayer p = view.Live.Player; + float dx = m.X - p.WorldX, dy = m.Y - p.WorldY, dz = m.Z - p.Z; + int d = (int)MathF.Round(MathF.Sqrt(dx * dx + dy * dy + dz * dz)); + int pct = -1; + if (m.Id != 0 && RadarKind.IsCreature(m.Kind) && Hud.MonsterHudData.TryGetHealth(m.Id, out Hud.HealthObservation h)) + pct = (int)MathF.Round(h.Ratio * 100f); + // Markers are rebuilt on every radar poll: key on what the text shows, not the instance. + if (m.Kind == _tipKind && d == _tipDistance && pct == _tipPct + && string.Equals(m.Label, _tipLabel, StringComparison.Ordinal)) + return _tipText; + _tipKind = m.Kind; + _tipLabel = m.Label; + _tipDistance = d; + _tipPct = pct; + // A label is the object's name; the kinds a name alone doesn't tell apart say what they are. + string name = string.IsNullOrEmpty(m.Label) ? RadarKind.Name(m.Kind) + : m.Kind is RadarKind.Fellow or RadarKind.Pet or RadarKind.Vendor or RadarKind.OwnCorpse or RadarKind.Player + ? m.Label + " (" + RadarKind.Name(m.Kind) + ")" + : m.Label!; + var inv = System.Globalization.CultureInfo.InvariantCulture; + _tipText = name + "\n" + d.ToString(inv) + " yd" + + (pct >= 0 ? " " + pct.ToString(inv) + "%" : ""); + return _tipText; + } + + // ── Compass and text ─────────────────────────────────────────────────── + + private static void DrawCardinals(ImDrawListPtr dl, RadarView view, Vector2 centre, float halfW, float halfH) + { + const float sz = 14; + bool rotate = RadarSettingsStore.RotateWithPlayer; + float h = view.Live.Player.Heading * MathF.PI / 180f; + float sinH = MathF.Sin(h), cosH = MathF.Cos(h); + float effW = MathF.Max(1, halfW - sz), effH = MathF.Max(1, halfH - sz); + ImFontPtr font = ImGuiFonts.Get(UiFont.UiBold14); + + foreach (var c in Compass) + { + float dirX, dirY; + if (rotate) + { + dirX = sinH * c.WorldX - cosH * c.WorldY; + dirY = -(cosH * c.WorldX + sinH * c.WorldY); + } + else + { + dirX = c.WorldX; + dirY = -c.WorldY; + } + // Onto the rectangular perimeter: max(|dx t|/effW, |dy t|/effH) = 1. + float m = MathF.Max(MathF.Abs(dirX) / effW, MathF.Abs(dirY) / effH); + if (m < 1e-4f) continue; + float t = 1 / m; + DrawOutlinedText(dl, font, c.Label, new Vector2(centre.X + dirX * t, centre.Y + dirY * t), Cardinal, alignBottom: false); + } + } + + /// <summary>Text with a 1 px 4-way black outline, centred on x; centred or bottom-aligned on y.</summary> + private static void DrawOutlinedText(ImDrawListPtr dl, ImFontPtr font, string text, Vector2 anchor, uint col, bool alignBottom) + { + ImGuiNET.ImGui.PushFont(font); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text); + ImGuiNET.ImGui.PopFont(); + var pos = new Vector2(anchor.X - ts.X * 0.5f, alignBottom ? anchor.Y - ts.Y - 1 : anchor.Y - ts.Y * 0.5f); + float fs = font.FontSize; + dl.AddText(font, fs, pos + new Vector2(-1, 0), Outline, text); + dl.AddText(font, fs, pos + new Vector2(1, 0), Outline, text); + dl.AddText(font, fs, pos + new Vector2(0, -1), Outline, text); + dl.AddText(font, fs, pos + new Vector2(0, 1), Outline, text); + dl.AddText(font, fs, pos, col, text); + } + + private static bool IconButton(string id, Vector2 pos, string glyph) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + var size = new Vector2(22, 22); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); + uint bg = ImGuiNET.ImGui.IsItemActive() ? C(0xE0101820) : ImGuiNET.ImGui.IsItemHovered() ? C(0xE0243444) : ButtonBg; + dl.AddRectFilled(pos, pos + size, bg, 3); + dl.AddRect(pos, pos + size, ButtonBorder, 3); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), glyph, pos, size, CoordText); + return clicked; + } + + // ── Settings (gear) ───────────────────────────────────────────────────── + + private void SettingsWindow() + { + if (!_settingsOpen) return; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, C(0xFF0A121A)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, ButtonBorder); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 4f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 10)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 6)); + const ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize + | ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoCollapse; + bool visible = ImGuiNET.ImGui.Begin("##radar_settings", ref _settingsOpen, flags); + ImGuiNET.ImGui.PopStyleVar(3); + ImGuiNET.ImGui.PopStyleColor(2); + if (visible) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextUnformatted("Radar Settings"); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.Separator(); + + bool changed = false; + changed |= Check("Rotate with player", ref RadarSettingsStore.RotateWithPlayer); + changed |= Check("Show gold rim", ref RadarSettingsStore.ShowGoldRim); + changed |= Check("Docked click-through (hold Ctrl to interact)", ref RadarSettingsStore.CtrlGatedClickThrough); + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("On: docked clicks pass through to the game; hold Ctrl to drag, open the gear, or resize."); + changed |= Check("Click a dot to select it", ref RadarSettingsStore.ClickToSelect); + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("Left-click a dot to select that object in game. Hover a dot for its name and distance."); + changed |= Slider("Opacity", ref RadarSettingsStore.Opacity, 0.05f, 1.0f, "%.2f"); + changed |= Slider("Zoom", ref RadarSettingsStore.Zoom, 0.5f, 6.0f, "%.1f"); + ImGuiNET.ImGui.Separator(); + changed |= KindRows(); + if (changed) + { + AvaloniaOverlay.RadarCtrlGatedClickThrough = RadarSettingsStore.CtrlGatedClickThrough; + RadarSettingsStore.Save(); + } + ImGuiNET.ImGui.PopFont(); + } + ImGuiNET.ImGui.End(); + } + + private static bool Check(string label, ref bool value) => ImGuiNET.ImGui.Checkbox(label, ref value); + + // Legend order: creatures, then corpses, then places, then items. + private static readonly (byte Kind, string Label)[] KindRowsOrder = + { + (RadarKind.Monster, "Monsters"), (RadarKind.Player, "Players"), (RadarKind.Fellow, "Fellows"), + (RadarKind.Npc, "NPCs"), (RadarKind.Vendor, "Vendors"), (RadarKind.Pet, "Your pets"), + (RadarKind.Corpse, "Corpses"), (RadarKind.OwnCorpse, "Your corpses"), (RadarKind.Lifestone, "Lifestones"), + (RadarKind.Portal, "Portals"), (RadarKind.Door, "Doors"), (RadarKind.GroundItem, "Items on the ground"), + }; + + private static readonly string[] KindTips = + { + "Creatures you can attack.", + "Creatures you can't attack (townsfolk, quest givers).", + "Portals, with their destination.", + "Doors, gates and hatches.", + "Other players.", + "Players in your fellowship.", + "Your own combat pet.", + "Shopkeepers.", + "Corpses you can't loot (or not identified yet: selecting one tells).", + "Corpses you may loot: your kills, your fellows' kills and your own corpse. Known once the corpse has been identified (looting or selecting it does that).", + "Lifestones.", + "Items lying on the ground. Off by default: there can be a lot of them.", + }; + + /// <summary> + /// The legend and per-kind settings: show box, the marker as drawn, its name and a colour + /// swatch (click to pick). One row per kind, then "Reset colours". True when something changed. + /// </summary> + private static bool KindRows() + { + bool changed = false; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextUnformatted("Show (click a swatch to change its colour):"); + ImGuiNET.ImGui.PopFont(); + RadarMarkerStyle.FillColors(KindCols); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float scale = MathF.Max(1f, EngineFrameController.FontScale); + const ImGuiColorEditFlags pickFlags = ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel + | ImGuiColorEditFlags.AlphaBar | ImGuiColorEditFlags.AlphaPreviewHalf; + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 3)); + foreach (var (kind, label) in KindRowsOrder) + { + ImGuiNET.ImGui.PushID(kind); + changed |= ImGuiNET.ImGui.Checkbox("##show", ref RadarSettingsStore.ShowFlag(kind)); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]); + ImGuiNET.ImGui.SameLine(); + // The marker exactly as the radar draws it. + float box = ImGuiNET.ImGui.GetFrameHeight(); + Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.Dummy(new Vector2(box, box)); + RadarMarkerStyle.Draw(dl, kind, at + new Vector2(box, box) * 0.5f, KindCols[kind], 1.3f * scale); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextUnformatted(label); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]); + ImGuiNET.ImGui.SameLine(190 * scale); + Vector4 v = RynthTheme.Vec(RadarSettingsStore.KindColors[kind]); + if (ImGuiNET.ImGui.ColorEdit4("##col", ref v, pickFlags)) + { + RadarSettingsStore.KindColors[kind] = ToArgb(v); + _colorDirty = true; + } + ImGuiNET.ImGui.PopID(); + } + ImGuiNET.ImGui.PopStyleVar(); + // The picker reports every drag step: save once no colour edit is in progress. + if (_colorDirty && !ImGuiNET.ImGui.IsAnyItemActive()) + { + _colorDirty = false; + changed = true; + } + if (ImGuiNET.ImGui.SmallButton("Reset colours")) + { + RadarSettingsStore.ResetKindColors(); + changed = true; + } + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Every kind back to its default colour (show boxes stay as they are)."); + return changed; + } + + private static bool _colorDirty; + + private static uint ToArgb(Vector4 v) + { + static uint B(float f) => (uint)Math.Clamp((int)MathF.Round(f * 255f), 0, 255); + return (B(v.W) << 24) | (B(v.X) << 16) | (B(v.Y) << 8) | B(v.Z); + } + + private static bool Slider(string label, ref float value, float min, float max, string fmt) + { + ImGuiNET.ImGui.TextUnformatted(label); + ImGuiNET.ImGui.SameLine(60); + ImGuiNET.ImGui.SetNextItemWidth(170); + ImGuiNET.ImGui.PushID(label); + bool changed = ImGuiNET.ImGui.SliderFloat("##v", ref value, min, max, fmt); + ImGuiNET.ImGui.PopID(); + // Save once the drag ends, not on every step. + return changed && !ImGuiNET.ImGui.IsItemActive() || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RadarMarkerStyle.cs b/src/RynthCore.Engine/ImGui/Panels/RadarMarkerStyle.cs new file mode 100644 index 0000000..3186fcf --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RadarMarkerStyle.cs @@ -0,0 +1,117 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RadarMarkerStyle.cs +// One shape per radar marker kind (RadarKind), shared by the Radar face, its +// settings legend and the Dungeon Map. Shapes differ as well as colours, so +// the kinds stay apart for colour-blind players and when a user picks two +// similar colours: +// monster filled dot player dot with a white ring +// NPC filled dot fellow triangle with a white edge +// vendor coin (dot, dark rim) pet small dot, dark edge +// corpse X your corpse bold X with a dark outline +// lifestone ring with a centre item small square +// portal diamond door square with a dark edge +// Colours come in as ImGui colours (RynthTheme.Argb of the ARGB setting). +// ============================================================================ + +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using RynthCore.Engine.UI.Panels; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class RadarMarkerStyle +{ + private static readonly uint White = RynthTheme.Argb(0xF0FFFFFF); + private static readonly uint Black = RynthTheme.Argb(0xE6000000); + + /// <summary> + /// Draws a marker of <paramref name="kind"/> centred on <paramref name="p"/>. <paramref name="s"/> + /// scales it (1 = the radar's size; the Dungeon Map draws a little bigger). + /// </summary> + public static void Draw(ImDrawListPtr dl, byte kind, Vector2 p, uint col, float s = 1f) + { + switch (kind) + { + case RadarKind.Monster: + case RadarKind.Npc: + dl.AddCircleFilled(p, 3f * s, col, 8); + break; + case RadarKind.Portal: + { + float r = 4f * s; + dl.AddQuadFilled(p + new Vector2(0, -r), p + new Vector2(r, 0), p + new Vector2(0, r), p + new Vector2(-r, 0), col); + break; + } + case RadarKind.Door: + { + var h = new Vector2(3.5f * s, 3.5f * s); + dl.AddRectFilled(p - h, p + h, col); + dl.AddRect(p - h, p + h, Darken(col, 0.4f)); + break; + } + case RadarKind.Player: + dl.AddCircleFilled(p, 3.5f * s, col, 10); + dl.AddCircle(p, 4.5f * s, White, 12, 1.5f); + break; + case RadarKind.Fellow: + { + float r = 4.8f * s; + Vector2 a = p + new Vector2(0, -r), b = p + new Vector2(r * 0.9f, r * 0.65f), c = p + new Vector2(-r * 0.9f, r * 0.65f); + dl.AddTriangleFilled(a, b, c, col); + dl.AddTriangle(a, b, c, White, 1.3f); + break; + } + case RadarKind.Pet: + dl.AddCircleFilled(p, 2.3f * s, col, 8); + dl.AddCircle(p, 2.8f * s, Black, 8, 1f); + break; + case RadarKind.Vendor: + dl.AddCircleFilled(p, 4f * s, col, 12); + dl.AddCircle(p, 4f * s, Darken(col, 0.45f), 12, 1.2f); + dl.AddCircle(p, 2f * s, Darken(col, 0.55f), 8, 1f); + break; + case RadarKind.Corpse: + { + float r = 3f * s; + dl.AddLine(p + new Vector2(-r, -r), p + new Vector2(r, r), col, 1.5f); + dl.AddLine(p + new Vector2(-r, r), p + new Vector2(r, -r), col, 1.5f); + break; + } + case RadarKind.OwnCorpse: + { + float r = 3.6f * s; + dl.AddLine(p + new Vector2(-r, -r), p + new Vector2(r, r), Black, 4f); + dl.AddLine(p + new Vector2(-r, r), p + new Vector2(r, -r), Black, 4f); + dl.AddLine(p + new Vector2(-r, -r), p + new Vector2(r, r), col, 2.2f); + dl.AddLine(p + new Vector2(-r, r), p + new Vector2(r, -r), col, 2.2f); + break; + } + case RadarKind.Lifestone: + dl.AddCircle(p, 3.8f * s, col, 12, 2f); + dl.AddCircleFilled(p, 1.2f * s, col, 6); + break; + case RadarKind.GroundItem: + { + var h = new Vector2(2f * s, 2f * s); + dl.AddRectFilled(p - h, p + h, col); + dl.AddRect(p - h - Vector2.One, p + h + Vector2.One, Black); + break; + } + } + } + + /// <summary>An ImGui colour (ABGR) with its RGB scaled by <paramref name="k"/>, alpha kept.</summary> + public static uint Darken(uint col, float k) + { + uint r = (uint)((col & 0xFF) * k), g = (uint)(((col >> 8) & 0xFF) * k), b = (uint)(((col >> 16) & 0xFF) * k); + return (col & 0xFF000000) | (b << 16) | (g << 8) | r; + } + + /// <summary>Each kind's ImGui colour from the radar settings, refreshed into <paramref name="into"/> (length RadarKind.Count).</summary> + public static void FillColors(uint[] into) + { + for (int k = 0; k < into.Length; k++) + into[k] = RynthTheme.Argb(RadarSettingsStore.KindColor((byte)k)); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs new file mode 100644 index 0000000..3e275dc --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs @@ -0,0 +1,501 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RangesSlideOut.cs +// The RynthAi dashboard's "Ranges" drawer (a player request, Tom 2026-10-04): +// a small tab on the dashboard's left edge; clicking it slides a narrow panel +// out to the left (to the right when the dashboard sits too close to the +// screen's left edge for it). Top to bottom: +// title ruler + RANGES (yd) | close +// monster the selected creature: name, priority / damage type / weak +// to, weapon; Edit opens its Monster Detail page, the skull its +// row on the Damage panel (weapon, off hand, pet, debuffs). +// "Select a monster" with nothing selected; "Not a monster" for +// players, NPCs, pets and items (Edit off). +// ranges slider + number rows: Monster range, Nav point reach, Ring +// range, Approach range, Blast range (0 = off), Corpse range +// (max). Labels are short; min/max/step, tooltips and saving +// are the Settings panel's rows (SettingsSchema.Find). +// Values save exactly like the Settings face: a private copy of the hub's +// settings, the row's Set, SettingsCommands.Save of the whole copy (RynthAi +// saves it to the profile). A newer fetch replaces the copy while nothing here +// is typed in or dragged, so Settings > Ranges and this drawer follow each +// other. A slider saves when it's let go; a typed value on Enter or focus loss +// (clamped; bad input reverts). Number boxes are FaceKit.TextBox, so typing +// keeps keys out of AC (ImGuiTextFocus). +// +// One of the dashboard's left-edge drawers (DashboardDrawers.cs: the tab, the +// slide, the side, the window; one drawer open at a time). Open/closed is +// saved with the dashboard's state (RynthAiDashboardState.RangesOpen). Popped +// out the tabs are hidden (see DashboardDrawers); Settings > Ranges still +// works there. +// +// AC thread only (inside the dashboard's Draw). The selection is read once a +// frame while the drawer shows and resolved only when it changes; display +// strings are built when the selection or its data changes, not per frame. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using System.Text; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; +using Rule = RynthCore.Engine.UI.Panels.MonstersPanel.Rule; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class RangesSlideOut : DashboardDrawer +{ + // ── Palette (the dashboard's, ARGB) ──────────────────────────────── + private static readonly uint Teal = C(0xFF26D9E6), TealSoft = C(0xFF264C59), Amber = C(0xFFE8B333), + Gold = C(0xFFFFD16A), Mute = C(0xFFB8C8D8), White = C(0xFFF2F7FC), BarBg = C(0xFF141F29), + BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A); + private static uint C(uint argb) => RynthTheme.Argb(argb); + + // ── Rows: (Settings row label, short label here) ──────────────────── + private static readonly (string Schema, string Short)[] Wanted = + { + ("Monster Range", "Monster range"), + (SettingsSchema.NavPointReachLabel, "Nav point reach"), + ("Ring Range", "Ring range"), + ("Approach Range", "Approach range"), + ("Blast Range (yd)", "Blast (0=off)"), + ("Corpse Max (yd)", "Corpse range"), + }; + + private sealed class Row + { + public required SettingRow Setting; + public required string Label; + public required string Tip; + public required bool IsInt; + public readonly byte[] Buffer = new byte[24]; + public double Shown = double.NaN; + public bool Typing, Dragging; + public double DragValue; + } + + private static Row[]? _rows; + + private static Row[] Rows => _rows ??= BuildRows(); + + private static Row[] BuildRows() + { + var list = new List<Row>(Wanted.Length); + foreach (var (schema, label) in Wanted) + { + SettingRow? s = SettingsSchema.Find(schema); + if (s?.Get == null || s.Set == null) continue; // renamed in the schema: leave it out + string tip = s.Tooltip ?? schema; + if (schema == "Corpse Max (yd)") tip = "Corpse Max on Settings > Ranges.\n" + tip; + list.Add(new Row { Setting = s, Label = label, Tip = tip, IsInt = s.Kind == SettingKind.Int }); + } + return list.ToArray(); + } + + // ── State ──────────────────────────────────────────────────────────── + private RynthAiSettings? _data; + private long _seenVersion = -1; + private bool _busy; // a row was typed in or dragged last frame + private bool _subSettings, _subMonster; + + // The selection, resolved when it changes. + private enum SelKind { None, Unknown, Monster, NotMonster } + private uint _selId = uint.MaxValue; + private long _selSince, _selChecked; + private SelKind _kind = SelKind.None; + private string _selName = ""; + private uint _selWcid; + private long _damageSeen = -1, _rulesSeen = -1; + private bool _factsDirty = true; + private string _facts1 = "", _facts2 = "", _factsTip = ""; + private string _editTip = NoEditTip, _damageTip = NoDamageTip; + private const string NoEditTip = "Select a monster to edit its rule."; + private const string NoDamageTip = "Select a monster to see it on the Damage panel."; + private bool _factsGold; + + private const uint TypeCreature = 0x10; // ITEM_TYPE TYPE_CREATURE + private const uint BfPlayer = 0x8; // PublicWeenieDesc BF_PLAYER + private const uint BfVendor = 0x200; // PublicWeenieDesc BF_VENDOR + private const uint PetOwnerIid = 44; // PropertyInstanceId PetOwner (summoned pets) + + // ── Drawer ─────────────────────────────────────────────────────────── + + public override string Key => "ranges"; + public override string Icon => PhosphorIcons.Ruler; + public override string Name => "ranges"; + public override bool SavedOpen => RynthAiDashboardState.RangesOpen; + public override void SaveOpen(bool open) => RynthAiDashboardState.SetRangesOpen(open); + + public override string TabTooltip(bool right) => right + ? "Ranges: monster range, nav point reach and more, and the selected monster.\nClick to slide them out (to the right: there's no room on the left)." + : "Ranges: monster range, nav point reach and more, and the selected monster.\nClick to slide them out."; + + public override float Width(float k) => 250 * k; + public override float Height(float k) => PanelHeight(k); + + /// <summary>While the panel is out: the selection, the hub subscriptions, a newer settings fetch.</summary> + public override void Update(bool showing) + { + if (showing) ReadSelection(); + SetSubscriptions(showing, showing && _kind == SelKind.Monster); + if (showing) TakeNewerSettings(force: false); + } + + // ── Panel ──────────────────────────────────────────────────────────── + + private const float LineH = 15, RowH = 20, RowGap = 3; + + private static float PanelHeight(float k) => + (Pad + TitleH + 4 + 3 * LineH + 6 + 3 + Math.Max(1, Rows.Length) * (RowH + RowGap) + Pad) * k; + + public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + // Title row: ruler + RANGES (yards) | close. + float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.Ruler, "RANGES", "yards", "Hide the ranges"); + float x = origin.X + Pad * k, w = panelW - 2 * Pad * k; + ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10); + + MonsterBlock(dl, x, y, w, k); + y += 3 * LineH * k + 6 * k; + dl.AddLine(new Vector2(x, y), new Vector2(x + w, y), BtnBord); + y += 3 * k; + + if (_data == null) + { + dl.AddText(f10, f10.FontSize, new Vector2(x, y + 4 * k), Mute, + UiSources.Settings.Current == null ? "Waiting for RynthAi…" : "Loading…"); + _busy = false; + return; + } + + bool busy = false; + Row[] rows = Rows; + float labelW = 0; + foreach (Row r in rows) labelW = MathF.Max(labelW, CalcWidth(f10, r.Label)); + labelW += 6 * k; + for (int i = 0; i < rows.Length; i++) + { + ImGuiNET.ImGui.PushID(i); + busy |= NumberRow(rows[i], x, y, w, labelW, k); + ImGuiNET.ImGui.PopID(); + y += (RowH + RowGap) * k; + } + _busy = busy; + } + + // ── Number rows: label | slider | box ──────────────────────────────── + + /// <summary>Returns true while the row is typed in or dragged.</summary> + private bool NumberRow(Row r, float x, float y, float w, float labelW, float k) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + SettingRow s = r.Setting; + double value = Math.Clamp(s.Get!(_data!), s.Min, s.Max); + double shownValue = r.Dragging ? r.DragValue : value; + float h = RowH * k; + + // Label (tooltip: the Settings row's). + float fs = ImGuiNET.ImGui.GetFontSize(); + dl.AddText(new Vector2(x, y + (h - fs) * 0.5f), White, r.Label); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); + ImGuiNET.ImGui.InvisibleButton("##label", new Vector2(Math.Max(1, labelW - 2 * k), h)); + ImGuiNET.ImGui.SetItemTooltip(r.Tip); + + // Box at the right. + float boxW = 46 * k; + float boxX = x + w - boxW; + if (!r.Typing && r.Shown != shownValue) WriteValue(r, shownValue); + FaceKit.TextBox("##v", r.Buffer, new Vector2(boxX, y), boxW, "", out bool typing, + ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.AutoSelectAll, h); + r.Typing = typing; + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + if (TryParse(r.Buffer, out double typed)) + { + double clamped = Math.Clamp(r.IsInt ? Math.Round(typed) : typed, s.Min, s.Max); + Changed(r, clamped); + } + else WriteValue(r, value); // bad input reverts + } + ImGuiNET.ImGui.SetItemTooltip(r.Tip); + + // Slider between them: drag (or click) to pick, saved when let go. + float sx = x + labelW, sw = boxX - 6 * k - sx; + if (sw > 10 * k) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(sx, y)); + ImGuiNET.ImGui.InvisibleButton("##slider", new Vector2(sw, h)); + bool active = ImGuiNET.ImGui.IsItemActive(); + bool hot = active || ImGuiNET.ImGui.IsItemHovered(); + float knobR = 5 * k; + float trackX0 = sx + knobR, trackX1 = sx + sw - knobR; + if (active && trackX1 > trackX0) + { + float f = Math.Clamp((ImGuiNET.ImGui.GetMousePos().X - trackX0) / (trackX1 - trackX0), 0f, 1f); + r.DragValue = Snap(s.Min + f * (s.Max - s.Min), s, r.IsInt); + r.Dragging = true; + shownValue = r.DragValue; + } + if (ImGuiNET.ImGui.IsItemDeactivated() && r.Dragging) + { + r.Dragging = false; + if (r.DragValue != value) Changed(r, r.DragValue); + } + ImGuiNET.ImGui.SetItemTooltip(r.Tip); + + float cy = y + h * 0.5f; + float frac = s.Max > s.Min ? (float)((shownValue - s.Min) / (s.Max - s.Min)) : 0f; + float kx = trackX0 + (trackX1 - trackX0) * Math.Clamp(frac, 0f, 1f); + dl.AddRectFilled(new Vector2(trackX0, cy - 2 * k), new Vector2(trackX1, cy + 2 * k), BarBg, 2 * k); + dl.AddRect(new Vector2(trackX0, cy - 2 * k), new Vector2(trackX1, cy + 2 * k), BtnBord, 2 * k); + if (kx > trackX0) dl.AddRectFilled(new Vector2(trackX0, cy - 2 * k), new Vector2(kx, cy + 2 * k), TealSoft, 2 * k); + dl.AddCircleFilled(new Vector2(kx, cy), knobR, hot ? White : Teal); + } + return r.Typing || r.Dragging; + } + + private static double Snap(double v, SettingRow s, bool isInt) + { + double step = s.Step > 0 ? s.Step : 1; + v = s.Min + Math.Round((v - s.Min) / step) * step; + v = isInt ? Math.Round(v) : Math.Round(v, 4); + return Math.Clamp(v, s.Min, s.Max); + } + + /// <summary>Saves a new value the way the Settings face does (the row's Set, the whole payload).</summary> + private void Changed(Row r, double value) + { + TakeNewerSettings(force: true); + if (_data == null) return; + r.Setting.Set!(_data, value); + SettingsCommands.Save(_data.Clone()); + WriteValue(r, value); + } + + /// <summary>A newer fetch replaces the copy unless a row is in use (force: about to save anyway).</summary> + private void TakeNewerSettings(bool force) + { + var snap = UiSources.Settings.Current; + if (snap == null || snap.Version == _seenVersion || (_busy && !force)) return; + _seenVersion = snap.Version; + _data = snap.Value.Clone(); + } + + private static void WriteValue(Row r, double value) + { + string text = r.IsInt ? ((long)Math.Round(value)).ToString(CultureInfo.InvariantCulture) + : value.ToString("G4", CultureInfo.InvariantCulture); + int n = Encoding.UTF8.GetBytes(text, 0, text.Length, r.Buffer, 0); + r.Buffer[Math.Min(n, r.Buffer.Length - 1)] = 0; + r.Shown = value; + } + + private static bool TryParse(byte[] buffer, out double value) + { + int len = Array.IndexOf(buffer, (byte)0); + if (len < 0) len = buffer.Length; + return double.TryParse(Encoding.UTF8.GetString(buffer, 0, len), NumberStyles.Float, CultureInfo.InvariantCulture, out value); + } + + // ── Selected monster ───────────────────────────────────────────────── + + private void MonsterBlock(ImDrawListPtr dl, float x, float y, float w, float k) + { + ImFontPtr f11 = ImGuiFonts.Get(UiFont.Dash11), f10 = ImGuiFonts.Get(UiFont.Dash10); + float lh = LineH * k; + bool monster = _kind == SelKind.Monster; + if (monster) BuildFacts(); + + // Buttons at the right of the name line: Edit (Monster Detail), Damage panel row. + Vector2 bsize = new(20 * k, lh); + float bx = x + w - 2 * bsize.X - 2 * k; + if (FaceKit.IconButton("##mon_edit", PhosphorIcons.PencilSimple, new Vector2(bx, y), bsize, monster ? Teal : Mute, BtnFill, + enabled: monster, border: BtnBord, font: UiFont.Dash10)) + DamageDetailFace.Show(_selWcid, _selName); + ImGuiNET.ImGui.SetItemTooltip(monster ? _editTip : NoEditTip); + if (FaceKit.IconButton("##mon_damage", PhosphorIcons.Skull, new Vector2(bx + bsize.X + 2 * k, y), bsize, monster ? Teal : Mute, BtnFill, + enabled: monster, border: BtnBord, font: UiFont.Dash10)) + { + if (!ImGuiPanelHost.IsOpen(DamageFace.Title)) PanelRouter.ToggleMonsters(); + } + ImGuiNET.ImGui.SetItemTooltip(monster ? _damageTip : NoDamageTip); + + // Name line. + string name; uint nameColor; + switch (_kind) + { + case SelKind.None: name = "Select a monster"; nameColor = Mute; break; + case SelKind.Unknown: name = _selName.Length > 0 ? _selName : "Reading…"; nameColor = Mute; break; + default: name = _selName.Length > 0 ? _selName : "(no name)"; nameColor = monster ? White : Mute; break; + } + float crossW = CalcWidth(f11, PhosphorIcons.Crosshair); + dl.AddText(f11, f11.FontSize, new Vector2(x, y + (lh - f11.FontSize) * 0.5f), monster ? Teal : Mute, PhosphorIcons.Crosshair); + dl.PushClipRect(new Vector2(x, y), new Vector2(bx - 4 * k, y + lh), true); + dl.AddText(f11, f11.FontSize, new Vector2(x + crossW + 4 * k, y + (lh - f11.FontSize) * 0.5f), nameColor, name); + dl.PopClipRect(); + + // Two fact lines (one tooltip over both). + float fy = y + lh; + string l1, l2; + uint c1 = Mute; + switch (_kind) + { + case SelKind.None: l1 = "Click one to see its rule here."; l2 = ""; break; + case SelKind.Unknown: l1 = ""; l2 = ""; break; + case SelKind.NotMonster: l1 = "Not a monster"; l2 = ""; c1 = Amber; break; + default: l1 = _facts1; l2 = _facts2; c1 = _factsGold ? Gold : Mute; break; + } + dl.PushClipRect(new Vector2(x, fy), new Vector2(x + w, fy + 2 * lh), true); + if (l1.Length > 0) dl.AddText(f10, f10.FontSize, new Vector2(x, fy + (lh - f10.FontSize) * 0.5f), c1, l1); + if (l2.Length > 0) dl.AddText(f10, f10.FontSize, new Vector2(x, fy + lh + (lh - f10.FontSize) * 0.5f), Mute, l2); + dl.PopClipRect(); + if (monster && _factsTip.Length > 0) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, fy)); + ImGuiNET.ImGui.InvisibleButton("##mon_facts", new Vector2(w, 2 * lh)); + ImGuiNET.ImGui.SetItemTooltip(_factsTip); + } + } + + /// <summary>Reads the selection (one read a frame) and classifies it when it changes.</summary> + private void ReadSelection() + { + uint sel = ClientHelperHooks.GetSelectedItemId(); + long now = Environment.TickCount64; + if (sel == _selId && (_kind != SelKind.Unknown || now - _selChecked < 250)) return; + if (sel != _selId) { _selId = sel; _selSince = now; } + _selChecked = now; + _factsDirty = true; + _selWcid = 0; + if (sel == 0) { _kind = SelKind.None; _selName = ""; return; } + + _selName = ClientObjectHooks.TryGetSnapshotName(sel, out string n) ? n : ""; + SelKind kind = Classify(sel); + // Not in the snapshots a second on: something that isn't out in the world (an item). + if (kind == SelKind.Unknown && now - _selSince > 1000) kind = SelKind.NotMonster; + if (kind == SelKind.Monster) + { + ClientObjectHooks.TryGetObjectWcid(sel, out _selWcid); // 0: the rule alone (by name) + _editTip = "Edit " + _selName + ": its Monster Detail page (priority, damage type, shapes).\n" + + "On Default, a change there gives it a rule of its own."; + _damageTip = "Damage panel: " + _selName + "'s row (weapon, off hand, pet, debuffs).\n" + + "The selected monster is highlighted (and listed first with Nearby first on)."; + } + _kind = kind; + } + + private static SelKind Classify(uint id) + { + if (!ClientObjectHooks.TryGetSnapshotItemType(id, out uint type)) return SelKind.Unknown; + if ((type & TypeCreature) == 0) return SelKind.NotMonster; + if (!ClientObjectHooks.TryGetSnapshotPwdInfo(id, out uint bf, out _, out _)) return SelKind.Unknown; + if ((bf & (BfPlayer | BfVendor)) != 0) return SelKind.NotMonster; + if (ClientObjectHooks.TryGetObjectInstanceIdProperty(id, PetOwnerIid, out uint owner) && owner != 0) return SelKind.NotMonster; + if (!ClientObjectHooks.TryGetSnapshotAttackable(id, out bool attackable)) return SelKind.Unknown; + return attackable ? SelKind.Monster : SelKind.NotMonster; // not attackable: an NPC + } + + /// <summary>Priority / damage type / weak to and the weapon, rebuilt when the monster or its data changes.</summary> + private void BuildFacts() + { + var dmg = UiSources.Damage.Current; + var rules = UiSources.MonsterRules.Current; + long dv = dmg?.Version ?? -1, rv = rules?.Version ?? -1; + if (!_factsDirty && dv == _damageSeen && rv == _rulesSeen) return; + _factsDirty = false; + _damageSeen = dv; + _rulesSeen = rv; + + string name = _selName; + DamageRow? row = null; + if (dmg != null) + foreach (DamageRow r in dmg.Value.Rows) + if (!r.IsDefault && (_selWcid != 0 ? r.Wcid == _selWcid : r.Name.Equals(name, StringComparison.OrdinalIgnoreCase))) + { + row = r; + break; + } + + var tip = new StringBuilder(); + string prio = "?", dtype = "?"; + _factsGold = false; + if (rules != null) + { + MonsterRulesSnapshot rs = rules.Value; + Rule? own = rs.FindRule(name); + Rule? cover = own == null ? DamageCommands.CoveringRule(rs.Parsed.Rules, name) : null; + Rule use = own ?? cover ?? rs.DefaultRule(); + prio = use.Priority.ToString(CultureInfo.InvariantCulture); + dtype = string.IsNullOrEmpty(use.DamageType) ? "Auto" : use.DamageType; + _factsGold = own != null; + tip.Append("Priority ").Append(prio).Append(", damage type ").Append(dtype).Append(": ") + .Append(own != null ? "its own rule." : cover != null ? "the name rule \"" + cover.Name + "\"." : "Default (no rule of its own).") + .Append('\n'); + } + else tip.Append("Monster rules loading…\n"); + + string weakTop = ""; + if (row != null && row.Weak.Length > 0) + { + int comma = row.Weak.IndexOf(','); + string first = comma > 0 ? row.Weak.Substring(0, comma) : row.Weak; + int sp = first.IndexOf(' '); + weakTop = sp > 0 ? first.Substring(0, sp) : first; + tip.Append("Weak to: ").Append(row.Weak); + if (row.WeakSrc.Length > 0) tip.Append(" (").Append(row.WeakSrc).Append(')'); + tip.Append('\n'); + } + _facts1 = "Prio " + prio + " · " + dtype + (weakTop.Length > 0 ? " · weak " + weakTop : ""); + + if (row == null) + { + _facts2 = dmg == null ? "Loading…" : "Not on the Damage panel yet"; + tip.Append(dmg == null ? "" : "Nothing learned about it yet: it joins the Damage panel once fought.\n"); + } + else if (row.AssignedWid != 0) + { + string wname = row.AssignedWeapon.Length > 0 ? row.AssignedWeapon : "Weapon " + row.AssignedWid.ToString(CultureInfo.InvariantCulture); + _facts2 = "Weapon " + wname; + tip.Append("Weapon: ").Append(wname).Append(" (set for it).\n"); + } + else + { + _facts2 = row.BestWid != 0 ? "Weapon Auto: " + row.BestWeapon : "Weapon Auto"; + tip.Append("Weapon: Auto").Append(row.BestWid != 0 ? " (learned best: " + row.BestWeapon + ")" : "").Append(".\n"); + } + tip.Append("Gold = its own rule. Edit opens Monster Detail; the skull, the Damage panel."); + _factsTip = tip.ToString(); + } + + // ── Hub subscriptions ──────────────────────────────────────────────── + + private void SetSubscriptions(bool settings, bool monster) + { + if (settings != _subSettings) + { + _subSettings = settings; + if (settings) { UiSources.Settings.Subscribe(); UiSources.Settings.RequestRefresh(); } + else UiSources.Settings.Unsubscribe(); + } + if (monster != _subMonster) + { + _subMonster = monster; + if (monster) + { + UiSources.Damage.Subscribe(); + UiSources.MonsterRules.Subscribe(); + UiSources.Damage.RequestRefresh(); + UiSources.MonsterRules.RequestRefresh(); + } + else + { + UiSources.Damage.Unsubscribe(); + UiSources.MonsterRules.Unsubscribe(); + } + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs new file mode 100644 index 0000000..cc3946b --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs @@ -0,0 +1,139 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RynthAiFace.Drawers.cs +// The RynthAi dashboard's left-edge drawers that draw with the dashboard's +// own helpers (DashboardDrawers.cs has the tabs and the slide; the Ranges +// drawer is RangesSlideOut.cs): +// Loaded files meta state and bot activity, then the Profile / Nav / Loot +// / Meta pickers and the Loot Editor button. Until +// 2026-10-05 this block folded out inside the dashboard +// (the caret on the control row); a popped-out dashboard +// still shows it inline that way (no drawers popped out). +// Patrol this dungeon's hazard cells (mark / unmark / clear), the +// recorded hazards and the saved routes. Was the Patrol +// launcher's right-click popup; right-click now opens this +// drawer (popped out: still the popup). +// AC thread only (inside the dashboard's Draw). +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class RynthAiFace +{ + /// <summary>Meta state, bot activity and the four file pickers.</summary> + private sealed class FilesDrawer : DashboardDrawer + { + private readonly RynthAiFace _face; + public FilesDrawer(RynthAiFace face) => _face = face; + + public override string Key => "files"; + public override string Icon => PhosphorIcons.Files; + public override string Name => "loaded files"; + public override bool SavedOpen => RynthAiDashboardState.FilesOpen; + public override void SaveOpen(bool open) => RynthAiDashboardState.SetFilesOpen(open); + + public override string TabTooltip(bool right) + { + RynthAiView? v = _face._view; + return "Loaded files: the Profile, Nav, Loot and Meta pickers, meta state and bot activity.\n" + + "Profile: " + (v?.ProfileText ?? "Default") + "\nNav: " + (v?.NavText ?? "None") + + "\nLoot: " + (v?.LootText ?? "None") + "\nMeta: " + (v?.MetaText ?? "None") + + (right ? "\n\nClick to slide them out (to the right: there's no room on the left)." : "\n\nClick to slide them out."); + } + + private const float LineH = 15, SelRow = 16, SelGap = 3; + + public override float Width(float k) => 230 * k; + public override float Height(float k) => + (Pad + TitleH + 4 + 2 * LineH + 6) * k + 4 * SelRow + 3 * SelGap + Pad * k; + + public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) + { + float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.Files, "LOADED FILES", null, "Hide the loaded files"); + float x = origin.X + Pad * k, w = panelW - 2 * Pad * k; + RynthAiView? view = _face._view; + RynthAiSnapshot raw = _face._raw; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10); + float lh = LineH * k; + + // Meta state / bot activity: label, then the value (amber) on the same line. + float labelW = MathF.Max(CalcWidth(f10, "Meta state:"), CalcWidth(f10, "Bot activity:")) + 6 * k; + InfoLine(dl, f10, x, y, w, lh, labelW, "Meta state:", view?.MetaStateText ?? "Default"); + y += lh; + InfoLine(dl, f10, x, y, w, lh, labelW, "Bot activity:", view?.BotActivityText ?? "Idle"); + y += lh + 6 * k; + + _face.Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, x, y, w, null); + y += SelRow + SelGap; + _face.Selector(1, "Nav:", view?.NavText ?? "None", raw.NavProfiles, raw.SelectedNavIdx, 0, x, y, w, null); + y += SelRow + SelGap; + _face.Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, x, y, w, raw); + y += SelRow + SelGap; + _face.Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, x, y, w, null); + } + + private static void InfoLine(ImDrawListPtr dl, ImFontPtr f, float x, float y, float w, float lh, float labelW, string label, string value) + { + float ty = y + (lh - f.FontSize) * 0.5f; + dl.AddText(f, f.FontSize, new Vector2(x, ty), Mute, label); + dl.PushClipRect(new Vector2(x + labelW, y), new Vector2(x + w, y + lh), true); + dl.AddText(f, f.FontSize, new Vector2(x + labelW, ty), Amber, value); + dl.PopClipRect(); + } + } + + /// <summary>Hazard cells and saved routes (the Patrol launcher's right-click).</summary> + private sealed class PatrolDrawer : DashboardDrawer + { + private bool _sub; + + public override string Key => "patrol"; + public override string Icon => PhosphorIcons.Footprints; + public override string Name => "patrol drawer"; + public override bool SavedOpen => RynthAiDashboardState.PatrolOpen; + public override void SaveOpen(bool open) => RynthAiDashboardState.SetPatrolOpen(open); + + public override string TabTooltip(bool right) => right + ? "Patrol: this dungeon's hazard cells, recorded hazards and saved routes (also: right-click Patrol).\nClick to slide it out (to the right: there's no room on the left)." + : "Patrol: this dungeon's hazard cells, recorded hazards and saved routes (also: right-click Patrol).\nClick to slide it out."; + + public override float Width(float k) => 260 * k; + public override float Height(float k) => 320 * k; + + public override void Update(bool showing) + { + if (showing == _sub) return; + _sub = showing; + if (showing) { UiSources.Patrol.Subscribe(); UiSources.Patrol.RequestRefresh(); } + else UiSources.Patrol.Unsubscribe(); + } + + public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) + { + float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.Footprints, "PATROL & ROUTES", null, "Hide the patrol drawer"); + float x = origin.X + Pad * k; + // A scrolling child for the lists. A child window is clipped to its parent's clip rect, + // so the host's slide clip covers it too. + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); + Vector2 size = new(panelW - 2 * Pad * k, MathF.Max(1, origin.Y + panelH - Pad * k - y)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + bool open = ImGuiNET.ImGui.BeginChild("##patrol_body", size, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (open) + { + PatrolInfo info = UiSources.Patrol.Current?.Value ?? new PatrolInfo(); + PatrolBody(info, withTitle: false); + } + } + finally { ImGuiNET.ImGui.EndChild(); } + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs new file mode 100644 index 0000000..d0f493a --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -0,0 +1,935 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RynthAiFace.cs +// ImGui face of the RynthAi dashboard (docs/IMGUI_PARITY_PLAN.md §2.1), +// first laid out from the Avalonia face (UI/Panels/RynthAiPanel.cs), then +// made compact with Phosphor icons, after DrakBot's dashboard. Top to bottom: +// title row RYNTHAI DASHBOARD | target, vitals, lock, opacity -/+, +// minimize, pop out +// header grid popped out only: meta state, bot activity | pickers (docked, +// they are the Loaded files drawer) +// control row macro start/stop, combat, buffing, nav, looting and meta +// toggles, bot activity ... force rebuff +// launchers one row of icon buttons (names in tooltips; labels too +// when the panel is wide enough) +// footer FPS | version | uptime +// bars player vitals, then the target (name + health), each +// toggled from the title row. Last on purpose, like DrakBot's +// target row: what comes and goes with a fight never moves +// the buttons above it. +// drawers tabs on the left edge (DashboardDrawers.cs), one open at a +// time, a window of their own beside the dashboard: Ranges +// (RangesSlideOut.cs), Loaded files and Patrol +// (RynthAiFace.Drawers.cs). Everything that slides out goes +// left; only the bars stay at the bottom (Tom 2026-10-05). +// Minimized keeps the title row, the control row and the bars. The window's +// minimum height is the content's, and toggling the bars or minimize fits the +// window to the content. Data: UiSources.RynthAi (a RynthAiView with every +// string preformatted); clicks: RynthAiCommands. +// +// Chromeless (like the Avalonia face): the title row is the drag surface. +// AC thread only; no per-frame string building except the FPS/uptime footer, +// which is cached until its value changes. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class RynthAiFace : IImGuiPanel +{ + public const string Title = "RynthAi"; + + public static void Register() + { + ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(296, 200), new Vector2(MinWidth, 54), PanelChrome.None, + Background: RynthTheme.RynthAiBackground, BorderColor: RynthTheme.RynthAiBorder, + Rounding: RynthTheme.RynthAiRounding), + () => new RynthAiFace()); + // The Loot Editor edits RynthAi's loot profiles and opens from this dashboard. + LootEditorFace.Register(); + // The Map launcher's panel. Registered here (only with RynthAi present, which + // feeds its data) so engine init needs no new line in EntryPoint. + DungeonMapFace.Register(); + } + + private const float MinWidth = 280; + + // ── Palette (RynthAiPanel's, ARGB) ───────────────────────────────── + private static readonly uint Teal = C(0xFF26D9E6), TealSoft = C(0xFF264C59), Amber = C(0xFFE8B333), + Green = C(0xFF40D973), Mute = C(0xFFB8C8D8), TextDim = C(0xFFF2F7FC), White = C(0xFFFFFFFF), + Hp = C(0xFFD93333), Mana = C(0xFF268CF2), ShellBg = C(0xFF0A0F14), BarBg = C(0xFF141F29), + BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A), MacroRun = C(0xFF1A5926), MacroStop = C(0xFF401F1F), + FrFill = C(0xFF47330A), SelectorBg = C(0xFF2D3847); + private static uint C(uint argb) => RynthTheme.Argb(argb); + + private static readonly uint[] SegmentColors = BuildSegmentColors(); + + private string _fpsText = "FPS —", _upText = "Up —"; + private int _fpsShown = -1; + private long _upShown = -1; + private bool _patrolOpen; + // The drawers on the dashboard's left edge (their own window, placed against this one). + private readonly DashboardDrawers _drawers; + private readonly PatrolDrawer _patrol = new(); + // This frame's data, for the drawers. + private RynthAiView? _view; + private RynthAiSnapshot _raw = Empty; + // Picker toggle: ImGui closes a popup on the press outside it, so remember + // whether it was showing when the selector press began (a second click closes). + private readonly int[] _pickerShownFrame = { -10, -10, -10, -10 }; + private readonly bool[] _pressedWhileOpen = new bool[4]; + // The content's height (logical units, body padding included), measured each + // frame: the window's minimum height. _fit: resize the window to it once. + private float _contentHeight; + private bool _fit; + private const float GripRoom = 12; + + public RynthAiFace() + { + // Tab order top to bottom; the first one saved open wins at load. + _drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol); + } + + public Vector2? MinSize => new Vector2(MinWidth, _contentHeight > 0 ? _contentHeight + : RynthAiDashboardState.Minimized ? 54 : 180); + + public void OnShown() + { + UiSources.RynthAi.Subscribe(); + UiSources.RynthAi.RequestRefresh(); + _fit = true; // drop the empty space a taller saved size leaves under the content + } + + public void OnHidden() + { + UiSources.RynthAi.Unsubscribe(); + if (_patrolOpen) { UiSources.Patrol.Unsubscribe(); _patrolOpen = false; } + _drawers.Detach(); + } + + public void Draw() + { + RynthAiView? view = UiSources.RynthAi.Current?.Value; + RynthAiSnapshot raw = view?.Raw ?? Empty; + bool minimized = RynthAiDashboardState.Minimized; + bool popped = ImGuiPopOuts.InPopOutFrame; + _view = view; + _raw = raw; + uint boxBg = (C(0xFF0A121A) & 0x00FFFFFF) | ((uint)(view?.PanelAlpha ?? 242) << 24); + + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + float x0 = start.X; + float width = ImGuiNET.ImGui.GetContentRegionAvail().X; + + TitleRow(raw, x0, width, minimized); + Gap(4); + // Popped out (no drawers there): the Profile/Nav/Loot/Meta pickers inline while expanded + // (the caret on the control row). Docked they are the Loaded files drawer. + if (popped && !minimized && RynthAiDashboardState.FilesOpen) + { + HeaderGrid(view, raw, x0, width); + Gap(4); + } + ControlRow(view, raw, x0, width, minimized, popped, boxBg); + if (!minimized) + { + Gap(4); + Launchers(x0, width); + Gap(6); + Footer(view, x0, width); + } + Bars(view, raw, x0, width, boxBg); + PatrolPopup(); + CharMenu(); + MeasureAndFit(start.Y); + // Last: a window of its own, placed against this one's rect (hidden popped out). + _drawers.Draw(); + } + + /// <summary> + /// Records the content height as the window's minimum (so the bars at the + /// bottom are never cut off) and, after a toggle, fits the window to it. + /// </summary> + private void MeasureAndFit(float startY) + { + float pad = ImGuiNET.ImGui.GetCursorStartPos().Y; // the body's top padding (the bottom's is the same) + float px = ImGuiNET.ImGui.GetCursorScreenPos().Y - startY + 2 * pad; + float place = ImGuiPanelHost.PlacementScale(); + // + room for the host's resize grip, which is painted over the body's bottom-right corner. + _contentHeight = MathF.Ceiling(px / place) + GripRoom; + if (_fit && !ImGuiPopOuts.InPopOutFrame) + { + _fit = false; + ImGuiPanelHost.RequestSize(Title, new Vector2(ImGuiNET.ImGui.GetWindowWidth() / place, _contentHeight)); + } + } + + // ── Title row: "R" + "YNTHAI DASHBOARD" | chips (drag surface) ────── + + private void TitleRow(RynthAiSnapshot raw, float x0, float width, bool minimized) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float y = ImGuiNET.ImGui.GetCursorScreenPos().Y; + const int chips = 7; + const float chipW = 18, chipH = 16, chipGap = 2; + float chipsW = chips * chipW + (chips - 1) * chipGap; + float rowH = 20; + + // Drag surface: everything left of the chips. + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y)); + ImGuiNET.ImGui.InvisibleButton("##dash_drag", new Vector2(Math.Max(1, width - chipsW), rowH)); + ImGuiPanelHost.DragWindowWithLastItem(); + + ImFontPtr title = ImGuiFonts.Get(UiFont.Dash14); + float ty = y + (rowH - title.FontSize) * 0.5f; + dl.PushClipRect(new Vector2(x0, y), new Vector2(x0 + Math.Max(1, width - chipsW - 4), y + rowH), true); + dl.AddText(title, title.FontSize, new Vector2(x0, ty), Teal, "R"); + float rw = CalcWidth(title, "R"); + dl.AddText(title, title.FontSize, new Vector2(x0 + rw, ty), White, "YNTHAI DASHBOARD"); + dl.PopClipRect(); + + float cx = x0 + width - chipsW; + float cy = y + (rowH - chipH) * 0.5f; + var chip = new Vector2(chipW, chipH); + const UiFont chipFont = UiFont.Dash11; + + bool target = RynthAiDashboardState.ShowTargetBar; + if (IconButton("##chip_target", new Vector2(cx, cy), chip, PhosphorIcons.Crosshair, chipFont, BtnFill, target ? Teal : Mute, BtnBord, 2)) + { + RynthAiDashboardState.SetShowTargetBar(!target); + _fit = true; + } + ImGuiNET.ImGui.SetItemTooltip(target + ? "Target bar on: the target's name and health at the bottom. Click to hide it." + : "Target bar off. Click to show the target's name and health at the bottom."); + cx += chipW + chipGap; + bool vitals = RynthAiDashboardState.ShowVitals; + if (IconButton("##chip_vitals", new Vector2(cx, cy), chip, PhosphorIcons.Heartbeat, chipFont, BtnFill, vitals ? Teal : Mute, BtnBord, 2)) + { + RynthAiDashboardState.SetShowVitals(!vitals); + _fit = true; + } + ImGuiNET.ImGui.SetItemTooltip(vitals + ? "Player vitals on: your health, stamina and mana at the bottom. Click to hide them." + : "Player vitals off. Click to show your health, stamina and mana at the bottom."); + cx += chipW + chipGap; + if (IconButton("##chip_lock", new Vector2(cx, cy), chip, raw.IsLocked ? PhosphorIcons.Lock : PhosphorIcons.LockOpen, + chipFont, BtnFill, raw.IsLocked ? Amber : Mute, BtnBord, 2)) + RynthAiCommands.TogglePanelLock(); + ImGuiNET.ImGui.SetItemTooltip(raw.IsLocked ? "Locked. Click to unlock the dashboard." : "Click to lock the dashboard in place."); + cx += chipW + chipGap; + if (IconButton("##chip_minus", new Vector2(cx, cy), chip, PhosphorIcons.Minus, chipFont, BtnFill, Mute, BtnBord, 2)) + RynthAiCommands.AdjustOpacity(-0.1f); + ImGuiNET.ImGui.SetItemTooltip("More transparent"); + cx += chipW + chipGap; + if (IconButton("##chip_plus", new Vector2(cx, cy), chip, PhosphorIcons.Plus, chipFont, BtnFill, Mute, BtnBord, 2)) + RynthAiCommands.AdjustOpacity(0.1f); + ImGuiNET.ImGui.SetItemTooltip("More opaque"); + cx += chipW + chipGap; + if (IconButton("##chip_min", new Vector2(cx, cy), chip, + minimized ? PhosphorIcons.ArrowsOutLineVertical : PhosphorIcons.ArrowsInLineVertical, chipFont, BtnFill, Mute, BtnBord, 2)) + { + RynthAiDashboardState.SetMinimized(!minimized); + _fit = true; // the window fits the other mode's content next frame + } + ImGuiNET.ImGui.SetItemTooltip(minimized ? "Expand" : "Minimize"); + cx += chipW + chipGap; + if (PanelRouter.CanPopOut) + { + if (IconButton("##chip_dock", new Vector2(cx, cy), chip, ImGuiPanelHost.PopOutGlyph, chipFont, BtnFill, Mute, BtnBord, 2)) + ImGuiPanelHost.TogglePopOut(Title); + ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); + } + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + rowH)); + } + + // ── Header: macro + state (40%) | Profile/Nav/Loot/Meta pickers (60%) ── + + private void HeaderGrid(RynthAiView? view, RynthAiSnapshot raw, float x0, float width) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float y0 = ImGuiNET.ImGui.GetCursorScreenPos().Y + 2; + float leftW = width * 0.4f; + + // Left: Meta State / Bot Activity (the macro start/stop is the control row's first square). + ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10); + float ly = y0; + dl.AddText(f10, f10.FontSize, new Vector2(x0, ly), Mute, "Meta State:"); + dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.MetaStateText ?? "Default"); + ly += 2 * (f10.FontSize + 1) + 4; + dl.AddText(f10, f10.FontSize, new Vector2(x0, ly), Mute, "Bot Activity:"); + dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.BotActivityText ?? "Idle"); + float leftBottom = ly + 2 * (f10.FontSize + 1); + + // Right: four selector rows (label 36 px, picker fills, spacing 3). + float rx = x0 + leftW, rw = width - leftW, ry = y0; + // The fold arrow sits at the end of the Profile row, where it always fits. + const float foldW = 18f; + Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, rx, ry, rw - foldW - 2, null); + if (IconButton("##files_fold", new Vector2(rx + rw - foldW, ry), new Vector2(foldW, 16), PhosphorIcons.CaretUp, UiFont.Dash11, BtnFill, Mute, BtnBord, 2)) + RynthAiDashboardState.SetFilesOpen(false); + ImGuiNET.ImGui.SetItemTooltip("Fold the loaded files into one line"); + ry += 16 + 3; + Selector(1, "Nav:", view?.NavText ?? "None", raw.NavProfiles, raw.SelectedNavIdx, 0, rx, ry, rw, null); + ry += 16 + 3; + Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, rx, ry, rw, raw); + ry += 16 + 3; + Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, rx, ry, rw, null); + ry += 16; + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, Math.Max(leftBottom, ry) + 4)); + } + + private static readonly string[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta" }; + private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta" }; + private static readonly string[] NoneItems = { "None" }; + + private void Selector(int slot, string label, string text, string[] items, int selected, int kind, + float x, float y, float w, RynthAiSnapshot? lootEdit) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10), f9 = ImGuiFonts.Get(UiFont.Dash9); + dl.AddText(f10, f10.FontSize, new Vector2(x, y + (16 - f10.FontSize) * 0.5f), Mute, label); + + float editW = 0; + if (lootEdit != null) + { + editW = 18; + var ep = new Vector2(x + w - editW, y); + if (IconButton("##loot_edit", ep, new Vector2(editW, 16), PhosphorIcons.TreasureChest, UiFont.Dash11, SelectorBg, Mute, 0, 2)) + { + string path = !string.IsNullOrEmpty(lootEdit.VendorProfilePath) ? lootEdit.VendorProfilePath : lootEdit.CurrentLootPath; + // The in-game Loot Editor panel. The external editor is one click away on the + // panel's toolbar (LootEditorFace.LaunchExternal, an STA thread of its own). + LootEditorFace.ToggleFor(path); + } + ImGuiNET.ImGui.SetItemTooltip("Loot Editor: the loot profile in use, or the open vendor's AutoVendor profile."); + editW += 3; + } + + var pos = new Vector2(x + 36, y); + var size = new Vector2(Math.Max(20, w - 36 - editW), 16); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(SelectorIds[slot], size); + bool hovered = ImGuiNET.ImGui.IsItemHovered(); + if (ImGuiNET.ImGui.IsItemActivated()) + _pressedWhileOpen[slot] = ImGuiNET.ImGui.GetFrameCount() - _pickerShownFrame[slot] <= 1; + bool open = ImGuiNET.ImGui.IsPopupOpen(PickerIds[slot]); + dl.AddRectFilled(pos, pos + size, hovered ? Lighten(SelectorBg) : SelectorBg, 2); + dl.AddRect(pos, pos + size, BtnBord, 2); + const float arrowW = 12; + dl.PushClipRect(pos, pos + size - new Vector2(arrowW + 4, 0), true); + dl.AddText(f9, f9.FontSize, pos + new Vector2(5, (16 - f9.FontSize) * 0.5f), White, text); + dl.PopClipRect(); + PhosphorIcons.DrawCentered(dl, f10, open ? PhosphorIcons.CaretUp : PhosphorIcons.CaretDown, + new Vector2(pos.X + size.X - arrowW - 3, y), new Vector2(arrowW, 16), Mute); + + if (clicked && !_pressedWhileOpen[slot] && !open) + { + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(pos.X, pos.Y + size.Y + 2)); + ImGuiNET.ImGui.OpenPopup(PickerIds[slot]); + } + Picker(slot, items.Length == 0 ? NoneItems : items, Math.Clamp(selected, 0, Math.Max(0, items.Length - 1)), kind, items.Length > 0); + } + + private void Picker(int slot, string[] items, int selected, int kind, bool real) + { + // Same look as the Avalonia picker: 200 wide, teal border, radius 6. + float maxH = Math.Min(items.Length * 26 + 12, Math.Max(60, + ImGuiNET.ImGui.GetIO().DisplaySize.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - 20)); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(200, maxH)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 6f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(2, 2)); + bool open = ImGuiNET.ImGui.BeginPopup(PickerIds[slot]); + ImGuiNET.ImGui.PopStyleVar(4); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) return; + _pickerShownFrame[slot] = ImGuiNET.ImGui.GetFrameCount(); + + float w = ImGuiNET.ImGui.GetContentRegionAvail().X; + for (int i = 0; i < items.Length; i++) + { + ImGuiNET.ImGui.PushID(i); + bool isSel = i == selected; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (ItemButton("##item", p, new Vector2(w, 24), items[i], isSel ? TealSoft : BtnFill, isSel ? Teal : White)) + { + if (real) RynthAiCommands.SelectProfile(kind, i); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + ImGuiNET.ImGui.PopID(); + } + ImGuiNET.ImGui.EndPopup(); + } + + private static bool ItemButton(string id, Vector2 pos, Vector2 size, string text, uint bg, uint fg) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); + uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(bg) : bg; + dl.AddRectFilled(pos, pos + size, fill, 3); + dl.AddRect(pos, pos + size, BtnBord, 3); + ImFontPtr f = ImGuiFonts.Get(UiFont.Dash11); + dl.PushClipRect(pos, pos + size, true); + dl.AddText(f, f.FontSize, pos + new Vector2(8, (size.Y - f.FontSize) * 0.5f), fg, text); + dl.PopClipRect(); + return clicked; + } + + // ── Control row: (ON/OFF) combat, buffing, nav, looting, meta ... force rebuff ── + + private const float Square = 24, SquareStep = 27, RowPad = 3; + + private void ControlRow(RynthAiView? view, RynthAiSnapshot raw, float x0, float width, bool minimized, bool popped, uint boxBg) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float top = ImGuiNET.ImGui.GetCursorScreenPos().Y; + float bottom = top + Square + 2 * RowPad; + dl.AddRectFilled(new Vector2(x0, top), new Vector2(x0 + width, bottom), boxBg, 3); + dl.AddRect(new Vector2(x0, top), new Vector2(x0 + width, bottom), BtnBord, 3); + + float x = x0 + 5, y = top + RowPad; + // Macro start/stop: a square like the toggles, green with a Stop glyph while running. + { + bool on = raw.MacroRunning; + if (IconButton("##macro", new Vector2(x, y), new Vector2(Square, Square), on ? PhosphorIcons.Stop : PhosphorIcons.Play, + UiFont.Dash14, on ? MacroRun : BarBg, on ? White : Mute, on ? Green : BtnBord, 3)) + RynthAiCommands.ToggleMacro(); + ImGuiNET.ImGui.SetItemTooltip(on ? "Macro running. Click to stop it." : "Macro stopped. Click to start it."); + x += SquareStep + 6; + } + Toggle("##t_combat", PhosphorIcons.Sword, raw.CombatEnabled, 0, new Vector2(x, y), "Combat"); + x += SquareStep; + Toggle("##t_buff", PhosphorIcons.Sparkle, raw.BuffingEnabled, 1, new Vector2(x, y), "Buffing"); + x += SquareStep; + Toggle("##t_nav", PhosphorIcons.SneakerMove, raw.NavigationEnabled, 2, new Vector2(x, y), "Navigation"); + x += SquareStep; + Toggle("##t_loot", PhosphorIcons.Bag, raw.LootingEnabled, 3, new Vector2(x, y), "Looting"); + x += SquareStep; + Toggle("##t_meta", PhosphorIcons.Code, raw.MetaEnabled, 4, new Vector2(x, y), "Meta (the macro rules)"); + x += SquareStep; + + // Popped out: the pickers fold out from a caret left of FR (expanded mode, while folded away). + // Docked they are the Loaded files drawer on the left edge. + const float caretW = 16f; + bool caret = popped && !minimized && !RynthAiDashboardState.FilesOpen; + float frX = x0 + width - 5 - Square; + if (caret) + { + if (IconButton("##files_open", new Vector2(frX - 4 - caretW, y), new Vector2(caretW, Square), PhosphorIcons.CaretDown, + UiFont.Dash11, BtnFill, Teal, BtnBord, 2)) + RynthAiDashboardState.SetFilesOpen(true); + ImGuiNET.ImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") + + "\nLoot: " + (view?.LootText ?? "None") + "\nMeta: " + (view?.MetaText ?? "None") + + "\n\nClick to show the Profile, Nav, Loot and Meta pickers."); + } + + // What the bot is doing, always in view (every mode, minimized too): between the toggles and FR. + { + ImFontPtr af = ImGuiFonts.Get(UiFont.Dash10); + float ax = x + 2, aRight = (caret ? frX - 4 - caretW : frX) - 6; + if (aRight - ax > 20) + { + string activity = view?.BotActivityText ?? "Idle"; + float ay = y + (Square - af.FontSize) * 0.5f; + dl.PushClipRect(new Vector2(ax, y), new Vector2(aRight, y + Square), true); + dl.AddText(af, af.FontSize, new Vector2(ax, ay), Amber, activity); + dl.PopClipRect(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(ax, y)); + ImGuiNET.ImGui.InvisibleButton("##activity", new Vector2(aRight - ax, Square)); + ImGuiNET.ImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + (view?.MetaStateText ?? "Default")); + } + } + + // Force rebuff, set apart at the right (DrakBot's place for it). + if (IconButton("##fr", new Vector2(x0 + width - 5 - Square, y), new Vector2(Square, Square), PhosphorIcons.ArrowsClockwise, + UiFont.Dash14, FrFill, Amber, BtnBord, 3)) + RynthAiCommands.ForceRebuff(); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + RynthAiCommands.CancelForceRebuff(); + ImGuiNET.ImGui.SetItemTooltip("Force rebuff (FR): recast all buffs. Right-click: cancel."); + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, bottom)); + ImGuiNET.ImGui.Dummy(new Vector2(width, 0)); + } + + private void Toggle(string id, string icon, bool on, int subsystem, Vector2 pos, string name) + { + if (IconButton(id, pos, new Vector2(Square, Square), icon, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, 3)) + RynthAiCommands.SetSubsystemEnabled(subsystem, !on); + ImGuiNET.ImGui.SetItemTooltip(on ? name + " on. Click to turn it off." : name + " off. Click to turn it on."); + } + + // ── Launchers: one row of icon buttons ────────────────────────────── + + private const float LauncherH = 22, LauncherGap = 2; + + private void Launchers(float x0, float width) + { + float y = ImGuiNET.ImGui.GetCursorScreenPos().Y; + const int buttons = 10; + float bw = MathF.Floor((width - buttons * LauncherGap) / buttons); + // Short labels only when every button has room for its icon and label. + bool labels = bw >= 68; + float x = x0; + + Launcher("##l_meta", PhosphorIcons.ListChecks, "Meta", "Meta: the macro rules", x, y, bw, labels, () => PanelRouter.Toggle("Meta")); + x += bw + LauncherGap; + Launcher("##l_lua", PhosphorIcons.FileCode, "Lua", "Lua scripts", x, y, bw, labels, () => PanelRouter.Toggle("Lua")); + x += bw + LauncherGap; + // Monsters opens the Damage panel (the basic Monsters panel and its + // Simple/Advanced chip were retired 2026-10-01). + Launcher("##l_mon", PhosphorIcons.Skull, "Monsters", "Monsters: weapons, spells and rules per monster (the Damage panel)", + x, y, bw, labels, PanelRouter.ToggleMonsters); + x += bw + LauncherGap; + Launcher("##l_set", PhosphorIcons.Gear, "Settings", "Settings", x, y, bw, labels, () => PanelRouter.Toggle("Settings")); + x += bw + LauncherGap; + Launcher("##l_nav", PhosphorIcons.MapTrifold, "Nav", "Nav: routes", x, y, bw, labels, () => PanelRouter.Toggle("Nav")); + x += bw + LauncherGap; + Launcher("##l_map", PhosphorIcons.MapPin, "Map", "Dungeon Map (shows while you're in a dungeon)", x, y, bw, labels, + () => PanelRouter.Toggle(DungeonMapFace.Title)); + x += bw + LauncherGap; + Launcher("##l_items", PhosphorIcons.Backpack, "Items", "Items", x, y, bw, labels, () => PanelRouter.Toggle("Items")); + x += bw + LauncherGap; + bool popped = ImGuiPopOuts.InPopOutFrame; + Launcher("##l_patrol", PhosphorIcons.Footprints, "Patrol", + popped ? "Patrol. Left-click: start dungeon patrol. Right-click: routes & recorded hazards." + : "Patrol. Left-click: start dungeon patrol. Right-click: routes & recorded hazards (the Patrol drawer, left).", + x, y, bw, labels, () => RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}")); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + { + if (popped) + { + // Popped out there are no drawers: the popup, as before. + ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1)); + ImGuiNET.ImGui.OpenPopup("##patrol"); + } + else _drawers.Toggle(_patrol); + } + x += bw + LauncherGap; + + // Char and Hub open RynthAi's own ImGui overlay windows (Mini Remote, which is the ILT + // Hub, its section windows, Inventory HUDs). They draw only when the engine hands plugins + // its ImGui context. + Launcher("##l_char", PhosphorIcons.User, "Char", + "Char. Left-click: ILT Hub / Mini Remote (/ra hub show). Right-click: Hub windows, Progression (Skills panel).", + x, y, bw, labels, () => RynthAiCommands.ApplyRemoteCommand("hub", "show")); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + { + ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1)); + ImGuiNET.ImGui.OpenPopup("##charmenu"); + } + x += bw + LauncherGap; + Launcher("##l_hub", PhosphorIcons.SquaresFour, "Hub", + "Hub. Left-click: Mini Remote (/ra remote). Right-click: Inventory HUDs setup (/ra huds).", + x, y, bw, labels, () => RynthAiCommands.ApplyRemoteCommand("remote", "toggle")); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + RynthAiCommands.ApplyRemoteCommand("huds", "show"); + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + LauncherH)); + } + + private void Launcher(string id, string icon, string label, string tooltip, float x, float y, float w, bool showLabel, Action? onClick) + { + var pos = new Vector2(x, y); + var size = new Vector2(Math.Max(10, w), LauncherH); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); + ImGuiNET.ImGui.SetItemTooltip(tooltip); + uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill; + dl.AddRectFilled(pos, pos + size, fill, 3); + dl.AddRect(pos, pos + size, BtnBord, 3); + + ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Dash14); + if (showLabel) + { + ImFontPtr f9 = ImGuiFonts.Get(UiFont.Dash9); + const float iconBox = 16; + PhosphorIcons.DrawCentered(dl, iconFont, icon, pos + new Vector2(4, 0), new Vector2(iconBox, LauncherH), Mute); + dl.PushClipRect(pos, pos + size, true); + dl.AddText(f9, f9.FontSize, new Vector2(pos.X + 4 + iconBox + 4, pos.Y + (LauncherH - f9.FontSize) * 0.5f), Mute, label); + dl.PopClipRect(); + } + else + { + PhosphorIcons.DrawCentered(dl, iconFont, icon, pos, size, Mute); + } + if (clicked && onClick != null) + { + onClick(); + } + } + + // ── Footer: FPS | version | uptime ───────────────────────────────────── + + private void Footer(RynthAiView? view, float x0, float width) + { + int fps = (int)MathF.Round(D3D9.EndSceneHook.MeasuredFps); + if (fps != _fpsShown) { _fpsShown = fps; _fpsText = fps > 0 ? $"FPS {fps}" : "FPS —"; } + DateTime started = EntryPoint.InitStartedUtc; + if (started != DateTime.MinValue) + { + TimeSpan up = DateTime.UtcNow - started; + long secs = (long)up.TotalSeconds; + if (secs != _upShown) + { + _upShown = secs; + _upText = up.TotalHours >= 1 ? $"Up {(int)up.TotalHours}:{up.Minutes:D2}:{up.Seconds:D2}" : $"Up {up.Minutes}:{up.Seconds:D2}"; + } + } + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10); + float y = ImGuiNET.ImGui.GetCursorScreenPos().Y; + float fpsW = CalcWidth(f10, _fpsText), upW = CalcWidth(f10, _upText); + dl.AddText(f10, f10.FontSize, new Vector2(x0, y), Mute, _fpsText); + dl.AddText(f10, f10.FontSize, new Vector2(x0 + width - upW, y), Mute, _upText); + + // The version between them: centred when there's room, else after FPS, clipped short of the uptime. + string version = view?.Version ?? string.Empty; + if (version.Length > 0) + { + float left = x0 + fpsW + 8, right = x0 + width - upW - 8; + if (right > left) + { + float vw = CalcWidth(f10, version); + float vx = x0 + (width - vw) * 0.5f; + if (vx < left || vx + vw > right) vx = left; + dl.PushClipRect(new Vector2(left, y), new Vector2(right, y + f10.FontSize + 2), true); + dl.AddText(f10, f10.FontSize, new Vector2(vx, y), Mute, version); + dl.PopClipRect(); + } + } + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + f10.FontSize + 2)); + ImGuiNET.ImGui.Dummy(new Vector2(width, 0)); + } + + // ── Bars (bottom): player vitals, then the target ────────────────────── + + private const float VitalsH = 14 + 3 + 14 + 3 + 14; + + private void Bars(RynthAiView? view, RynthAiSnapshot raw, float x0, float width, uint boxBg) + { + bool vitals = RynthAiDashboardState.ShowVitals, target = RynthAiDashboardState.ShowTargetBar; + if (!vitals && !target) return; + Gap(4); + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr f11 = ImGuiFonts.Get(UiFont.Dash11), f10 = ImGuiFonts.Get(UiFont.Dash10); + // The target's stamina/mana rows are held while that option is on, so they + // don't grow the box (and the window) as targets come and go. + bool subRows = raw.ShowTargetStaminaMana; + float targetH = f11.FontSize + 2 + 3 + 12 + (subRows ? 2 * (13 + 3) - 3 : 0); + float top = ImGuiNET.ImGui.GetCursorScreenPos().Y; + float height = 5 + (vitals ? VitalsH : 0) + (vitals && target ? 6 : 0) + (target ? targetH : 0) + 4; + var tl = new Vector2(x0, top); + var br = new Vector2(x0 + width, top + height); + dl.AddRectFilled(tl, br, boxBg, 3); + dl.AddRect(tl, br, BtnBord, 3); + + float rx = x0 + 5, rw = width - 10, ry = top + 5; + if (vitals) + { + VitalRow(dl, rx, ry, rw, PhosphorIcons.Heart, view?.Health ?? default, Hp, f10); ry += 14 + 3; + VitalRow(dl, rx, ry, rw, PhosphorIcons.Lightning, view?.Stamina ?? default, Green, f10); ry += 14 + 3; + VitalRow(dl, rx, ry, rw, PhosphorIcons.Drop, view?.Mana ?? default, Mana, f10); ry += 14; + if (target) ry += 6; + } + if (target) + { + // Crosshair + name | health, then the 15-segment bar. + string hpText = raw.TargetHealthDisplay; + float hpW = CalcWidth(f11, hpText); + float iconW = CalcWidth(f11, PhosphorIcons.Crosshair); + dl.AddText(f11, f11.FontSize, new Vector2(rx, ry), Mute, PhosphorIcons.Crosshair); + dl.PushClipRect(new Vector2(rx, ry), new Vector2(rx + rw - hpW - 4, ry + f11.FontSize + 2), true); + dl.AddText(f11, f11.FontSize, new Vector2(rx + iconW + 3, ry), TextDim, view?.TargetHeadline ?? "NO TARGET"); + dl.PopClipRect(); + dl.AddText(f11, f11.FontSize, new Vector2(rx + rw - hpW, ry), White, hpText); + ry += f11.FontSize + 2 + 3; + + // 15-segment gradient bar, 10 high, 2 px between segments. + int lit = view?.TargetSegmentsLit ?? 0; + float segW = (rw - 2 * (RynthAiView.Segments - 1)) / RynthAiView.Segments; + for (int i = 0; i < RynthAiView.Segments; i++) + { + float sx = rx + i * (segW + 2); + dl.AddRectFilled(new Vector2(sx, ry + 1), new Vector2(sx + segW, ry + 11), i < lit ? SegmentColors[i] : BarBg, 1); + } + ry += 12; + + if (subRows) + { + bool shown = view != null && view.ShowTargetSubBars; + ry += 3; + CompactBar(dl, rx, ry, rw, shown ? view!.TargetStamina : default, Green, f10); ry += 13 + 3; + CompactBar(dl, rx, ry, rw, shown ? view!.TargetMana : default, Mana, f10); + } + } + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, top + height)); + ImGuiNET.ImGui.Dummy(new Vector2(width, 0)); + } + + private static void CompactBar(ImDrawListPtr dl, float x, float y, float w, VitalView bar, uint color, ImFontPtr font) + { + var a = new Vector2(x, y + 1); + var b = new Vector2(x + w, y + 12); + dl.AddRectFilled(a, b, BarBg, 2); + if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, 2); + dl.AddText(font, font.FontSize, new Vector2(x + 4, y + 1 + (11 - font.FontSize) * 0.5f), White, bar.Text ?? ""); + } + + private static void VitalRow(ImDrawListPtr dl, float x, float y, float w, string icon, VitalView bar, uint color, ImFontPtr font) + { + var a = new Vector2(x, y + 1); + var b = new Vector2(x + w, y + 14); + dl.AddRectFilled(a, b, BarBg, 6); + if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, 6); + float ty = y + 1 + (13 - font.FontSize) * 0.5f; + dl.AddText(font, font.FontSize, new Vector2(x + 4, ty), Mute, icon); + dl.AddText(font, font.FontSize, new Vector2(x + 4 + CalcWidth(font, icon) + 3, ty), White, bar.Text ?? ""); + } + + // ── Char menu (right-click Char): RynthAi's character windows ────────── + + /// <summary>ILT Hub section windows: menu label and the "/ra hub open" section name RynthAi parses.</summary> + private static readonly (string Label, string Section)[] HubSections = + { + ("Character", "character"), ("Quests", "quests"), ("Pets", "pets"), + ("Banking", "banking"), ("Gear", "gear"), ("Games", "games"), ("Guardian", "guardian"), + }; + + private static void CharMenu() + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8)); + bool open = ImGuiNET.ImGui.BeginPopup("##charmenu"); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) return; + try + { + // The Mini Remote is the ILT Hub; each former Hub tab is its own window (toggled). + if (ImGuiNET.ImGui.MenuItem("Mini Remote (ILT Hub)", "/ra hub")) + RynthAiCommands.ApplyRemoteCommand("hub", "toggle"); + ImGuiNET.ImGui.Separator(); + foreach ((string label, string section) in HubSections) + { + if (ImGuiNET.ImGui.MenuItem(label, "/ra hub open " + section)) + RynthAiCommands.ApplyRemoteCommand("hub", "open " + section + " toggle"); + } + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Progression (Skills panel)")) + SkillsFace.ShowProgression(); + ImGuiNET.ImGui.SetItemTooltip("XP planner, augmentations and enlightenment (ILT worlds)"); + } + finally + { + ImGuiNET.ImGui.EndPopup(); + } + } + + // ── Patrol popup (right-click Patrol, popped out; docked it's the Patrol drawer) ── + + private void PatrolPopup() + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8)); + ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(260, 0), new Vector2(260, 376)); + bool open = ImGuiNET.ImGui.BeginPopup("##patrol"); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + + if (open != _patrolOpen) + { + _patrolOpen = open; + if (open) { UiSources.Patrol.Subscribe(); UiSources.Patrol.RequestRefresh(); } + else UiSources.Patrol.Unsubscribe(); + } + if (!open) return; + + var snap = UiSources.Patrol.Current; + PatrolInfo info = snap?.Value ?? new PatrolInfo(); + PatrolBody(info, withTitle: true); + ImGuiNET.ImGui.EndPopup(); + } + + /// <summary>The patrol lists at the cursor (the popup's body and the Patrol drawer's).</summary> + private static void PatrolBody(PatrolInfo info, bool withTitle) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash10)); + if (withTitle) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash11)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), PatrolTitle); + ImGuiNET.ImGui.PopFont(); + } + + Section("THIS DUNGEON"); + if (info.InDungeon) + { + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{info.CurrentLandblock} · {info.CurrentHazards} hazard cell(s)"); + if (info.CurrentHazards > 0) + { + ImGuiNET.ImGui.SameLine(); + if (Mini("Clear##cur")) + RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{info.CurrentLandblock}\"}}", refreshPatrol: true); + } + if (Mini(MarkHazardLabel)) + RynthAiCommands.SendNavCommand("{\"Cmd\":\"markHazardHere\"}", refreshPatrol: true); + ImGuiNET.ImGui.SameLine(); + if (Mini("Unmark")) + RynthAiCommands.SendNavCommand("{\"Cmd\":\"unmarkHazardHere\"}", refreshPatrol: true); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, RynthTheme.Vec(0xFFB8C8D8)); + ImGuiNET.ImGui.TextWrapped("Stand on the lava/acid, click Mark, then re-run Patrol."); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopFont(); + } + else + { + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "Not in a dungeon."); + } + + Section($"RECORDED HAZARDS ({info.Dungeons.Length})"); + if (info.Dungeons.Length == 0) + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "None recorded yet."); + for (int i = 0; i < info.Dungeons.Length; i++) + { + DungeonHazards d = info.Dungeons[i]; + ImGuiNET.ImGui.PushID(i); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{d.Landblock} · {d.Cells} cell(s)"); + ImGuiNET.ImGui.SameLine(); + if (Mini("Clear")) + RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{d.Landblock}\"}}", refreshPatrol: true); + ImGuiNET.ImGui.PopID(); + } + if (info.Dungeons.Length > 0 && Mini("Clear all recorded hazards")) + RynthAiCommands.SendNavCommand("{\"Cmd\":\"clearHazardsAll\"}", refreshPatrol: true); + + Section($"SAVED ROUTES ({info.Routes.Length})"); + if (info.Routes.Length == 0) + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "No .nav routes saved."); + foreach (string name in info.Routes) + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "• " + name); + + ImGuiNET.ImGui.PopFont(); + } + + private const string PatrolTitle = PhosphorIcons.Footprints + " PATROL & ROUTES"; + private const string MarkHazardLabel = PhosphorIcons.Warning + " Mark cell as hazard"; + + private static void Section(string text) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), text); + ImGuiNET.ImGui.PopFont(); + } + + private static bool Mini(string label) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, Lighten(BtnFill)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonActive, Darken(BtnFill)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 2f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(6, 1)); + bool clicked = ImGuiNET.ImGui.Button(label); + ImGuiNET.ImGui.PopStyleVar(3); + ImGuiNET.ImGui.PopStyleColor(5); + ImGuiNET.ImGui.PopFont(); + return clicked; + } + + // ── Shared helpers ──────────────────────────────────────────────────── + + /// <summary>Draws the Avalonia face's flat button frame; returns true on left click.</summary> + private static bool ButtonFrame(string id, Vector2 pos, Vector2 size, uint bg, uint border, float rounding) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight) + && ImGuiNET.ImGui.IsMouseReleased(ImGuiMouseButton.Left); + uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(bg) : bg; + dl.AddRectFilled(pos, pos + size, fill, rounding); + if (border != 0) dl.AddRect(pos, pos + size, border, rounding); + return clicked; + } + + /// <summary>A flat button with centred text; returns true on left click.</summary> + private static bool Button(string id, Vector2 pos, Vector2 size, string text, UiFont font, + uint bg, uint fg, uint border, float rounding) + { + bool clicked = ButtonFrame(id, pos, size, bg, border, rounding); + ImFontPtr f = ImGuiFonts.Get(font); + float tw = CalcWidth(f, text); + ImGuiNET.ImGui.GetWindowDrawList().AddText(f, f.FontSize, pos + new Vector2((size.X - tw) * 0.5f, (size.Y - f.FontSize) * 0.5f), fg, text); + return clicked; + } + + /// <summary>A flat button with a Phosphor icon centred on it; returns true on left click.</summary> + private static bool IconButton(string id, Vector2 pos, Vector2 size, string icon, UiFont font, + uint bg, uint fg, uint border, float rounding) + { + bool clicked = ButtonFrame(id, pos, size, bg, border, rounding); + PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(font), icon, pos, size, fg); + return clicked; + } + + private static float CalcWidth(ImFontPtr font, string text) + { + ImGuiNET.ImGui.PushFont(font); + float w = ImGuiNET.ImGui.CalcTextSize(text).X; + ImGuiNET.ImGui.PopFont(); + return w; + } + + private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12); + private static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0); + + private static uint Scale(uint abgr, float k, int add) + { + uint a = abgr & 0xFF000000; + uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add); + uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add); + uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add); + return a | (b << 16) | (g << 8) | r; + } + + private static void Gap(float h) => ImGuiNET.ImGui.Dummy(new Vector2(0, h)); + + private static uint[] BuildSegmentColors() + { + var colors = new uint[RynthAiView.Segments]; + for (int i = 0; i < colors.Length; i++) + { + float t = (float)i / (colors.Length - 1); + uint r, g, b; + if (t < 0.33f) { float f = t / 0.33f; r = 255; g = (uint)(f * 255); b = 0; } + else if (t < 0.66f) { float f = (t - 0.33f) / 0.33f; r = (uint)((1f - f) * 255); g = 255; b = 0; } + else { float f = (t - 0.66f) / 0.34f; r = 0; g = 255; b = (uint)(f * 255); } + colors[i] = C(0xFF000000 | (r << 16) | (g << 8) | b); + } + return colors; + } + + private static readonly RynthAiSnapshot Empty = new(); +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs new file mode 100644 index 0000000..3278248 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs @@ -0,0 +1,226 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RynthNavArrowFace.cs +// RynthNav's arrow: a small draggable overlay that points at RynthNav's arrow +// target relative to the way you face, with the distance, the compass point +// and the target's name (our take on GoArrow's arrow; Digero 2006, Virindi +// 2011, MIT). Shown and hidden from the RynthNav panel's Arrow tab; opens by +// itself when a command sets the arrow (RynthNavArrowWatch). Works popped out. +// +// arrow turns with you every frame (the pose snapshot's heading); green +// within 30 yd, amber while it points at a portal on a route; a +// wand instead of the arrow when the next step is a recall. +// text name, distance and compass point, the route step. +// buttons pop out, hide; Go (RynthNav walks there) and Stop. +// +// The target comes from RynthNav's status (UiSources.RynthNav); RynthNav owns +// it and decides arrival. AC's render thread: snapshots only, no AC calls, and +// strings are rebuilt only when what they show changes. +// ============================================================================ + +using System; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class RynthNavArrowFace : IImGuiPanel +{ + public const string Title = "RynthNav Arrow"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(236, 84), new Vector2(236, 84), PanelChrome.None, Background: 0, Rounding: 6, EdgeToEdge: true), + () => new RynthNavArrowFace()); + + /// <summary>Shows the overlay (any thread). Only where ImGui faces are drawn.</summary> + public static void Show() + { + if (!ImGuiPanelHost.IsOpen(Title) && PanelRouter.ResolveDockedFace(Title) == PanelFace.ImGui) + ImGuiPanelHost.Open(Title); + } + + /// <summary>The arrow turns with you: redraw popped out often enough to look smooth.</summary> + public int PopOutIdleHz => 20; + + private static readonly uint Glass = RynthTheme.Argb(0xDC0A0F14), Ring = RynthTheme.Argb(0xFF1A2A39); + + private readonly ArrowReadout _read = new(); + + public void OnShown() + { + UiSources.RynthNav.Subscribe(); + UiSources.RynthNav.RequestRefresh(); + } + + public void OnHidden() => UiSources.RynthNav.Unsubscribe(); + + public void Draw() + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail(); + if (size.X < 40 || size.Y < 40) return; + RynthNavStatus? st = UiSources.RynthNav.Current?.Value; + _read.Update(st); + + dl.AddRectFilled(origin, origin + size, Glass, 6); + dl.AddRect(origin, origin + size, BtnBord, 6); + + // The arrow, in a ring on the left. + float d = size.Y - 12; + Vector2 c = origin + new Vector2(6 + d * 0.5f, size.Y * 0.5f); + dl.AddCircleFilled(c, d * 0.5f, ShellBg, 32); + dl.AddCircle(c, d * 0.5f, Ring, 32, 1.5f); + _read.DrawPointer(dl, c, d * 0.5f - 6); + + // Text. + float tx = origin.X + d + 14, right = origin.X + size.X - 6; + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), f10 = ImGuiFonts.Get(UiFont.Ui10), f9 = ImGuiFonts.Get(UiFont.Ui9); + dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 46, origin.Y + size.Y), true); + dl.AddText(bold, bold.FontSize, new Vector2(tx, origin.Y + 6), Teal, _read.Line1); + dl.PopClipRect(); + dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right, origin.Y + size.Y), true); + dl.AddText(f10, f10.FontSize, new Vector2(tx, origin.Y + 26), Text, _read.Line2); + dl.PopClipRect(); + dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 48, origin.Y + size.Y), true); + dl.AddText(f9, f9.FontSize, new Vector2(tx, origin.Y + size.Y - 6 - f9.FontSize - 2), Mute, _read.Line3); + dl.PopClipRect(); + + // Buttons (before the surface, so they win the hover). + const float b = 20, gap = 3; + var closePos = new Vector2(right - b, origin.Y + 5); + var popPos = closePos - new Vector2(b + gap, 0); + if (PanelRouter.CanPopOut) + { + if (IconButton("##rna_pop", ImGuiPanelHost.PopOutGlyph, popPos, new Vector2(b, b), Mute, BtnFill, font: UiFont.Ui11)) + ImGuiPanelHost.TogglePopOut(Title); + ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); + } + if (IconButton("##rna_close", PhosphorIcons.X, closePos, new Vector2(b, b), Mute, BtnFill, font: UiFont.Ui11)) + ImGuiPanelHost.Close(Title); + ImGuiNET.ImGui.SetItemTooltip("Hide the arrow (the RynthNav panel's Arrow tab shows it again)"); + var stopPos = new Vector2(right - b, origin.Y + size.Y - b - 5); + var goPos = stopPos - new Vector2(b + gap, 0); + bool canGo = _read.CanGo; + if (IconButton("##rna_go", PhosphorIcons.Play, goPos, new Vector2(b, b), Green, BtnFill, enabled: canGo, font: UiFont.Ui11) + && st?.Arrow is RynthNavArrow ar) + RynthNavCommands.Go(ar.Final, ar.FinalNs, ar.FinalEw); + ImGuiNET.ImGui.SetItemTooltip("Go: RynthNav walks there (with portals and recalls when its routing is on)"); + if (IconButton("##rna_stop", PhosphorIcons.Stop, stopPos, new Vector2(b, b), Red, BtnFill, font: UiFont.Ui11)) + RynthNavCommands.Move(5); + ImGuiNET.ImGui.SetItemTooltip("Stop walking"); + + // Surface: drag moves the overlay (the OS window when popped out). + ImGuiNET.ImGui.SetCursorScreenPos(origin); + ImGuiNET.ImGui.InvisibleButton("##rna_surface", size); + ImGuiPanelHost.DragWindowWithLastItem(); + if (ImGuiNET.ImGui.IsItemHovered() && _read.Tooltip.Length > 0) ImGuiNET.ImGui.SetItemTooltip(_read.Tooltip); + } +} + +/// <summary> +/// What the arrow shows this frame: the target from RynthNav's status, your position and +/// heading from the pose snapshot. Shared by the overlay and the panel's Arrow tab. AC's +/// render thread; the text is rebuilt only when what it shows changes. +/// </summary> +internal sealed class ArrowReadout +{ + public string Line1 = "No arrow", Line2 = "", Line3 = "", Tooltip = ""; + public bool HasTarget, CanGo, Pointing; + public float Relative; // degrees clockwise from straight ahead + public double Distance = double.NaN; + public string Kind = ""; + + private RynthNavArrow? _arrow; + private int _distKey = int.MinValue, _compassKey = -1; + private bool _wasInDungeon, _wasAvailable = true; + private string _compass = ""; + + private static readonly uint NearCol = RynthTheme.Argb(0xFF40D973); + + public void Update(RynthNavStatus? st) + { + RynthNavArrow? a = st?.Arrow; + bool available = st == null || st.Travel; + if (!ReferenceEquals(a, _arrow) || available != _wasAvailable) + { + _arrow = a; + _wasAvailable = available; + _distKey = int.MinValue; + _compassKey = -1; + HasTarget = a != null; + Kind = a?.Kind ?? ""; + CanGo = a != null && (a.FinalNs != 0 || a.FinalEw != 0); + Line1 = a == null ? (available ? "No arrow" : "RynthNav is too old for the arrow") : a.Name; + Line3 = a == null ? (available ? "Atlas, chat coords or /rnav arrow" : "") + : a.Kind == "recall" ? (a.StepText.Length > 0 ? a.StepText : "cast the recall") + : a.Kind == "portal" ? "walk into the portal" + (a.Steps > 1 ? $" · step {a.Step}/{a.Steps}" : "") + : a.Steps > 1 ? $"step {a.Step}/{a.Steps}" : a.Type; + Tooltip = a == null ? "" : (a.Kind == "recall" ? "Cast " + a.Name : a.Name + " " + a.CoordText) + + (a.Steps > 1 ? "\nOn the way to " + a.Final : ""); + Line2 = a == null ? "" : a.Kind == "recall" ? "Cast " + a.Name : a.CoordText; + } + Pointing = false; + if (a == null || a.Kind == "recall" || !a.OnMap) return; + if (!RynthNavAtlas.TryPlayerPos(out double ns, out double ew, out bool onMap, out _)) return; + if (!onMap) + { + if (!_wasInDungeon) { Line2 = "in a dungeon: no direction"; _wasInDungeon = true; _distKey = int.MinValue; } + return; + } + _wasInDungeon = false; + Distance = RynthNavAtlas.Distance(ns, ew, a.Ns, a.Ew); + double bearing = RynthNavAtlas.Bearing(ns, ew, a.Ns, a.Ew); + int compassKey = (int)Math.Round(((bearing % 360.0) + 360.0) % 360.0 / 22.5) & 15; + if (compassKey != _compassKey) { _compassKey = compassKey; _compass = RynthNavAtlas.CompassPoint(bearing); _distKey = int.MinValue; } + int key = Distance < 1000 ? (int)Math.Round(Distance) : 100000 + (int)Math.Round(Distance / 100); + if (key != _distKey) + { + _distKey = key; + Line2 = RynthNavStatus.Yards(Distance) + " " + _compass; + } + if (TryHeading(out float heading)) + { + Relative = (float)bearing - heading; + Pointing = true; + } + } + + /// <summary>The pointer at <paramref name="c"/>: an arrow, a wand for a recall, a dot when there's nothing.</summary> + public void DrawPointer(ImDrawListPtr dl, Vector2 c, float r) + { + if (!HasTarget) { dl.AddCircleFilled(c, 3, FaceKit.Mute); return; } + if (Kind == "recall") + { + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.MagicWand, c - new Vector2(r, r), new Vector2(2 * r, 2 * r), FaceKit.Amber); + return; + } + if (!Pointing) { PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Compass, c - new Vector2(r, r), new Vector2(2 * r, 2 * r), FaceKit.Mute); return; } + uint col = Kind == "portal" ? FaceKit.Amber : Distance <= 30 ? NearCol : FaceKit.Teal; + float rad = Relative * (MathF.PI / 180f); + float s = MathF.Sin(rad), co = MathF.Cos(rad); + Vector2 tip = Rot(c, 0, -r, s, co), left = Rot(c, -0.62f * r, 0.78f * r, s, co), + notch = Rot(c, 0, 0.36f * r, s, co), right = Rot(c, 0.62f * r, 0.78f * r, s, co); + dl.AddTriangleFilled(tip, left, notch, col); + dl.AddTriangleFilled(tip, notch, right, col); + } + + private static Vector2 Rot(Vector2 c, float x, float y, float s, float co) => + new(c.X + x * co - y * s, c.Y + x * s + y * co); + + /// <summary>Your heading this frame (compass degrees) from the pose snapshot; no AC call (SenseFace's way).</summary> + private static bool TryHeading(out float heading) + { + heading = 0; + if (!PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out _, out _, out _, out _, out float qw, out float qz, out bool valid, out float h)) + return false; + if (valid) { heading = h; return true; } + double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + heading = (float)((-yaw % 360.0 + 720.0) % 360.0); + return true; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs new file mode 100644 index 0000000..6bd139a --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs @@ -0,0 +1,1028 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RynthNavFace.cs +// ImGui face of the RynthNav panel (UI/Panels/RynthNavPanel.cs is the old +// Avalonia face, the movement part only). Everything RynthNav's /rnav +// commands do, with buttons and text boxes. Three tabs, under a status line +// (what RynthNav is doing, or how the last goto ended; Stop while walking): +// +// Go the destination box (searches the Atlas as you type: places, +// dungeons, towns, portals, with type and distance; takes +// coordinates too), favorites and recent places while it's empty, +// Go / Route / Arrow / Stop, the "Use portals and recalls" and +// "Recalls" switches, the route step by step (the current step +// highlighted, with the distance left), then two sections that +// fold: Recalls (portal ties and where they land, "which tie was +// it?", the recalls routes can use) and Info (here, the NavData +// folder, the route graph, tiles; Load / Test / Preview and the +// movement pad). +// Atlas every place: search by name and type, Nearby, Favorites, +// Recent; the star, Arrow and Go per row; details on a click. +// Arrow the arrow's target, distance and direction; show or hide the +// arrow overlay (RynthNavArrowFace), Go / Stop / Clear / favorite, +// set it to a place or coordinates, the arrival radius. +// +// Our take on GoArrow's arrow, atlas and routes (Digero 2006, Virindi 2011, +// MIT). RynthNav (the plugin) owns the arrow, favorites, recent, routing and +// recalls; this face shows its status and sends it /rnav commands +// (RynthNavCommands). Atlas rows come from RynthNavAtlasSource (the file read +// read-only here). Older RynthNavs: the parts they can't feed say so. +// +// Data: UiSources.RynthNav (hub, 250 ms), UiSources.RynthNavAtlas (500 ms, +// while the Go or Atlas tab shows) and RynthNavCommands. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class RynthNavFace : IImGuiPanel +{ + public const string Title = "RynthNav"; + + public static void Register() + { + ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(390, 620), new Vector2(330, 420), EdgeToEdge: true, GripInBody: true), + () => new RynthNavFace()); + // The arrow overlay is RynthNav's too; it opens when a command sets the arrow. + RynthNavArrowFace.Register(); + RynthNavArrowWatch.ShowArrow = RynthNavArrowFace.Show; + UiSources.RynthNavArrowWatch.Subscribe(); + } + + private static readonly uint RunGreen = RynthTheme.Argb(0xFF40D973), Sep = RynthTheme.Argb(0xFF1A2A39), + RowHot = RynthTheme.Argb(0xFF16283A), Gold = RynthTheme.Argb(0xFFFFD24D), Purple = RynthTheme.Argb(0xFFBF4DFF); + + private const int TabGo = 0, TabAtlas = 1, TabArrow = 2; + + private static readonly string[] TabNames = + { + PhosphorIcons.SneakerMove + " Go", PhosphorIcons.GlobeHemisphereWest + " Atlas", PhosphorIcons.Compass + " Arrow", + }; + + private RynthNavStatus? _st; + private int _tab; + private bool _atlasSubscribed; + private readonly byte[] _search = new byte[96], _arrowTo = new byte[96], _dest = new byte[96]; + private string _seenSearch = "", _seenDest = ""; + private AtlasMode _mode = AtlasMode.Search; + private int _typeIdx; + private AtlasRow? _sel; + private readonly Picker _typePicker = new("##rnav_type_picker"); + private readonly ArrowReadout _read = new(); + // Strings built when what they show changes, not per frame. + private double _arriveShown = -1; + private string _arriveText = "", _typeLabel = ""; + private int _typeLabelIdx = -1; + private AtlasRow? _detailsFor; + private string _detailsLine = "", _detailsDest = ""; + + // Go tab: the picked destination (a row of the list), what the commands get for it, its line. + private AtlasRow? _pick; + private string _pickArg = "", _pickCoord = "", _pickLine = "", _typedLine = "", _typedCoord = ""; + private bool _recallsOpen, _infoOpen; + + public void OnShown() + { + UiSources.RynthNav.Subscribe(); + UiSources.RynthNav.RequestRefresh(); + PushTabQuery(); + if (_tab != TabArrow) SubscribeAtlas(true); + } + + public void OnHidden() + { + UiSources.RynthNav.Unsubscribe(); + SubscribeAtlas(false); + } + + private void SubscribeAtlas(bool on) + { + if (on == _atlasSubscribed) return; + _atlasSubscribed = on; + if (on) { UiSources.RynthNavAtlas.Subscribe(); UiSources.RynthNavAtlas.RequestRefresh(); } + else UiSources.RynthNavAtlas.Unsubscribe(); + } + + public int PopOutIdleHz => _tab == TabArrow ? 20 : 10; + + public void Draw() + { + _st = UiSources.RynthNav.Current?.Value; + float w = Begin(out Vector2 origin, out Vector2 size); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + RynthNavStatus? st = _st; + + // Title: dot, RynthNav, what it is + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + uint dot = st == null ? Mute : st.TileLoaded ? RunGreen : st.HasPose ? Amber : Mute; + dl.AddCircleFilled(p + new Vector2(5, 10), 4.5f, dot); + ImFontPtr big = ImGuiFonts.Get(UiFont.UiBold14); + dl.AddText(big, big.FontSize, p + new Vector2(16, 1), Teal, "RynthNav"); + float tw = ImGuiNET.ImGui.CalcTextSize("RynthNav").X * big.FontSize / ImGuiNET.ImGui.GetFontSize(); + dl.AddText(p + new Vector2(24 + tw, 6), Mute, "go · atlas · arrow"); + NextLine(p, 22); + DrawTabs(w); + DrawStatusLine(w); + + switch (_tab) + { + case TabAtlas: DrawAtlas(w, origin, size); break; + case TabArrow: DrawArrow(w); break; + default: DrawGo(w, origin, size); break; + } + + End(origin, size); + _typePicker.Draw(); + } + + private void DrawTabs(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float bw = (w - (TabNames.Length - 1) * 4) / TabNames.Length; + for (int i = 0; i < TabNames.Length; i++) + { + bool sel = i == _tab; + if (Button("##rnav_tab" + i, TabNames[i], new Vector2(p.X + i * (bw + 4), p.Y), new Vector2(bw, 22), + sel ? Teal : Text, sel ? Selected : BtnFill, border: sel ? Teal : 0)) + { + _tab = i; + SubscribeAtlas(i != TabArrow); + PushTabQuery(); + } + } + NextLine(p, 28); + } + + /// <summary>The Atlas source serves one query: the Go tab's destination box or the Atlas tab's search.</summary> + private void PushTabQuery() + { + if (_tab == TabGo) PushDestQuery(); + else PushQuery(); + } + + // ── Status line (every tab) ────────────────────────────────────────── + + /// <summary> + /// What RynthNav is doing ("walking to Holtburg, 1.2k yd left", "taking portal ..."), or how + /// the last goto ended ("arrived inside Matron Hive", a stop reason), as it says in chat. + /// Stop sits at its right while a goto runs on the Atlas and Arrow tabs (the Go tab has its own). + /// </summary> + private void DrawStatusLine(float w) + { + RynthNavStatus? st = _st; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float h = 22; + bool walking = st?.Goto == true; + bool stop = walking && _tab != TabGo; + float textRight = p.X + w - (stop ? 26 : 6); + dl.AddRectFilled(p, p + new Vector2(w, h), PanelBg, 3); + uint col = st == null ? Mute : !walking ? Text + : st.GoPhase == "portal" ? Purple : st.GoPhase == "recall" ? Amber : st.GoPhase == "town" ? Teal : RunGreen; + dl.AddCircleFilled(p + new Vector2(9, h * 0.5f), 3.5f, walking ? col : Mute); + string text = st == null ? "RynthNav isn't answering (is it loaded?)" : st.StatusLine.Length > 0 ? st.StatusLine : "ready"; + dl.PushClipRect(p, new Vector2(textRight, p.Y + h), true); + dl.AddText(new Vector2(p.X + 18, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), col, text); + dl.PopClipRect(); + // The whole line on hover (it's clipped to one line). + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.InvisibleButton("##rnav_status", new Vector2(Math.Max(1, textRight - p.X), h)); + if (text.Length > 40) ImGuiNET.ImGui.SetItemTooltip(text); + if (stop) + { + if (IconButton("##rnav_status_stop", PhosphorIcons.Stop, new Vector2(p.X + w - 22, p.Y + 1), new Vector2(20, 20), Text, StopBg, font: UiFont.Ui11)) + RynthNavCommands.Move(5); + ImGuiNET.ImGui.SetItemTooltip("Stop walking"); + } + NextLine(p, h + 6); + } + + // ── Go ─────────────────────────────────────────────────────────────── + + private const int DestRowsShown = 5; + + private void DrawGo(float w, Vector2 origin, Vector2 size) + { + RynthNavStatus? st = _st; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + + // Destination box (+ clear) + SectionLabel("DESTINATION"); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float boxW = Math.Max(80, w - 26); + bool enter = TextBox("##go_dest", _dest, p, boxW, "A place, a dungeon, a town, or 42.1N, 33.6E", out _, + ImGuiInputTextFlags.EnterReturnsTrue); + string text = Utf8(_dest).Trim(); + if (text != _seenDest) + { + _seenDest = text; + if (_pick != null && text != _pick.Name) SetPick(null); + _typedLine = text.Length > 0 ? "To: “" + text + "” (pick a result, or Go and RynthNav looks it up)" : ""; + AtlasRow? typedCoords = RynthNavAtlasSource.CoordRow(text); + _typedCoord = typedCoords != null ? RynthNavStatus.CommandCoord(typedCoords.Ns, typedCoords.Ew) : ""; + PushDestQuery(); + } + if (IconButton("##go_clear", PhosphorIcons.X, new Vector2(p.X + boxW + 4, p.Y), new Vector2(22, 22), Mute, BtnFill, + enabled: text.Length > 0 || _pick != null, font: UiFont.Ui11)) + { + WriteUtf8(_dest, ""); + SetPick(null); + } + ImGuiNET.ImGui.SetItemTooltip("Clear"); + NextLine(p, 26); + + // Results (search), or favorites and recent while the box is empty + AtlasView view = UiSources.RynthNavAtlas.Current?.Value ?? AtlasView.Empty; + AtlasRow[] rows = view.Rows; + if (enter && _pick == null && rows.Length > 0) Pick(rows[0]); + if (rows.Length == 0) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + Wrapped(view.Summary.Length > 0 ? view.Summary + : st != null && !st.Travel ? "This RynthNav is older than the Atlas (0.6.0): type coordinates, or update RynthNav." + : RynthNavAtlas.Status.Length > 0 ? RynthNavAtlas.Status : "Loading…", Mute, w); + ImGuiNET.ImGui.PopFont(); + } + else + { + float listH = Math.Min(rows.Length, DestRowsShown) * RowH; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + bool open = ImGuiNET.ImGui.BeginChild("##go_list", new Vector2(w, listH)); + ImGuiNET.ImGui.PopStyleColor(); + if (open) DrawDestRows(rows, ImGuiNET.ImGui.GetContentRegionAvail().X); + ImGuiNET.ImGui.EndChild(); + } + + // What the buttons act on + string line = _pick != null ? _pickLine : _typedLine; + if (line.Length > 0) + { + p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool canStar = _pick != null && _pick.OnMap && st?.Travel == true; + bool fav = canStar && IsFavorite(st!, _pick!); + float lx = p.X; + if (canStar) + { + if (IconButton("##go_star", PhosphorIcons.Star, p, new Vector2(18, 18), fav ? Gold : Faded(Mute), fav ? Selected : PanelBg, font: UiFont.Ui11)) + RynthNavCommands.ToggleFavorite(_pick!.Name, _pick.Ns, _pick.Ew); + ImGuiNET.ImGui.SetItemTooltip(fav ? "Remove from favorites" : "Add to favorites"); + lx += 22; + } + dl.PushClipRect(new Vector2(lx, p.Y), new Vector2(p.X + w, p.Y + 18), true); + dl.AddText(new Vector2(lx, p.Y + (18 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), _pick != null ? Teal : Mute, line); + dl.PopClipRect(); + NextLine(p, 22); + } + else ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + + // Go / Route / Arrow / Stop + p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool travel = st?.Travel == true; + bool has = _pick != null || text.Length > 0; + bool canGo = st != null && has && (travel || PickCoord().Length > 0); + bool walking = st?.Goto == true; + float bw = (w - 3 * 4) / 4f; + if (Button("##go_go", GoLabel, p, new Vector2(bw, 26), Green, BtnFill, enabled: canGo)) Go(text); + ImGuiNET.ImGui.SetItemTooltip(travel + ? (st!.PortalsOn ? "Walk there, through portals and with recalls when that is quicker" : "Walk there (portals and recalls are switched off)") + : "Walk the navmesh to these coordinates (update RynthNav for places and routes)"); + if (Button("##go_route", PhosphorIcons.Path + " Route", new Vector2(p.X + bw + 4, p.Y), new Vector2(bw, 26), Text, BtnFill, enabled: travel && has)) + RynthNavCommands.Command("route " + Arg(text)); + ImGuiNET.ImGui.SetItemTooltip(travel ? "Plan only: show the steps below, don't walk" : "Update RynthNav (0.6.0+) for routes"); + if (Button("##go_arrow", PhosphorIcons.NavigationArrow + " Arrow", new Vector2(p.X + 2 * (bw + 4), p.Y), new Vector2(bw, 26), Teal, BtnFill, enabled: travel && has)) + RynthNavCommands.Command("arrow " + Arg(text)); + ImGuiNET.ImGui.SetItemTooltip(travel ? "Show the arrow overlay pointing there" : "Update RynthNav (0.6.0+) for the arrow"); + if (Button("##go_stop", PhosphorIcons.Stop + " Stop", new Vector2(p.X + 3 * (bw + 4), p.Y), new Vector2(bw, 26), + walking ? Text : Red, walking ? StopBg : BtnFill, border: walking ? Red : 0)) + RynthNavCommands.Move(5); + ImGuiNET.ImGui.SetItemTooltip(walking ? "Stop walking" : "Stop any movement"); + NextLine(p, 32); + + // Switches + p = ImGuiNET.ImGui.GetCursorScreenPos(); + float half = (w - 4) * 0.5f; + if (travel) + { + if (Toggle("##go_portals", "Use portals and recalls", st!.PortalsOn, p, half)) + RynthNavCommands.Command(st.PortalsOn ? "portals off" : "portals on"); + ImGuiNET.ImGui.SetItemTooltip("Go and Route use portals, the Town Network and (with Recalls) recall spells when that is quicker.\nOff: walking only. From a dungeon there's no walking out, so it says so."); + // Recalls are part of routes: they only count while "Use portals and recalls" is on. + Vector2 rp = new(p.X + half + 4, p.Y); + if (st.PortalsOn) + { + if (Toggle("##go_recalls", "Recalls", st.RecallsOn, rp, half)) + RynthNavCommands.Command(st.RecallsOn ? "recalls off" : "recalls on"); + ImGuiNET.ImGui.SetItemTooltip("Let routes cast the recalls you know (and @lifestone, house recall...)."); + } + else + { + Button("##go_recalls_off", (st.RecallsOn ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " Recalls", rp, new Vector2(half, 22), + Faded(Mute), BtnFill, leftAlign: true); + ImGuiNET.ImGui.SetItemTooltip("Recalls are part of routes: turn on \"Use portals and recalls\" first."); + } + NextLine(p, 28); + if (st.HasAvoid) AvoidRows(st, w); + } + Line(w); + + // Route, Recalls, Info: scroll + float bodyH = Math.Max(40, origin.Y + size.Y - 6 - ImGuiNET.ImGui.GetCursorScreenPos().Y - GripOverlap()); + bool bodyOpen = ImGuiNET.ImGui.BeginChild("##go_body", new Vector2(w, bodyH)); + if (bodyOpen) + { + float cw = ImGuiNET.ImGui.GetContentRegionAvail().X - 4; + DrawRouteView(st, cw); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + if (Fold("##go_fold_recalls", _recallsOpen ? RecallsOpenLabel : RecallsShutLabel, ref _recallsOpen, cw)) DrawRecalls(st, cw); + if (Fold("##go_fold_info", _infoOpen ? InfoOpenLabel : InfoShutLabel, ref _infoOpen, cw)) DrawInfo(st, cw); + } + ImGuiNET.ImGui.EndChild(); + } + + private void PushDestQuery() + { + string text = Utf8(_dest).Trim(); + RynthNavAtlasSource.Query = text.Length == 0 + ? new AtlasQuery("", "All", AtlasMode.Saved) + : new AtlasQuery(text, "All", AtlasMode.Search); + } + + /// <summary>Picks a row as the destination: the box shows its name, the buttons act on it.</summary> + private void Pick(AtlasRow r) + { + WriteUtf8(_dest, r.Name); + _seenDest = Utf8(_dest).Trim(); + _typedLine = ""; + SetPick(r); + PushDestQuery(); + } + + private void SetPick(AtlasRow? r) + { + _pick = r; + if (r == null) { _pickArg = _pickCoord = _pickLine = ""; return; } + _pickCoord = r.OnMap ? RynthNavStatus.CommandCoord(r.Ns, r.Ew) : ""; + // Coordinates and a name ("42.08N, 33.60E Holtburg") pin the exact place; a place off the + // map (in a dungeon) goes by name, and RynthNav finds its entrance portal or says why not. + bool bareCoords = r.Type == "Coordinates" && r.Name == r.Coord; + _pickArg = !r.OnMap ? r.Name : bareCoords ? _pickCoord : _pickCoord + " " + r.Name; + _pickLine = "To: " + r.Name + " · " + r.Type + " · " + r.Coord + (r.Dist.Length > 0 ? " · " + r.Dist : ""); + } + + /// <summary>What a command gets: the picked place, else the typed text (a name or coordinates).</summary> + private string Arg(string typed) => _pick != null ? _pickArg : typed; + + /// <summary>Coordinates for the navmesh goto and Preview: the picked place's, else coordinates typed.</summary> + private string PickCoord() => _pick != null ? _pickCoord : _typedCoord; + + private void Go(string typed) + { + RynthNavStatus? st = _st; + if (st == null) return; + if (st.Travel) RynthNavCommands.Command("go " + Arg(typed)); + else + { + // RynthNav before 0.6.0: only the navmesh goto to coordinates. + string c = PickCoord(); + if (c.Length > 0) RynthNavCommands.Goto(c); + } + } + + private static bool IsFavorite(RynthNavStatus st, AtlasRow r) + { + foreach (RynthNavPlace f in st.Favorites) + if (f.Name.Equals(r.Name, StringComparison.OrdinalIgnoreCase) && Math.Abs(f.Ns - r.Ns) < 0.05 && Math.Abs(f.Ew - r.Ew) < 0.05) + return true; + return false; + } + + /// <summary>The destination list: star, type icon, name, type and distance. A click picks the row.</summary> + private void DrawDestRows(AtlasRow[] rows, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 basePos = ImGuiNET.ImGui.GetCursorScreenPos(); + float scrollY = ImGuiNET.ImGui.GetScrollY(), viewH = ImGuiNET.ImGui.GetWindowHeight(); + int first = Math.Max(0, (int)(scrollY / RowH)); + int last = Math.Min(rows.Length, first + (int)(viewH / RowH) + 2); + ImFontPtr f = ImGuiFonts.Get(UiFont.Ui10), f9 = ImGuiFonts.Get(UiFont.Ui9); + const float btn = 18, iconW = 20; + bool travel = _st?.Travel == true; + for (int i = first; i < last; i++) + { + AtlasRow r = rows[i]; + Vector2 rp = basePos + new Vector2(0, i * RowH); + bool selected = _pick != null && SameRow(_pick, r); + if (selected) dl.AddRectFilled(rp, rp + new Vector2(w, RowH), Selected); + else if ((i & 1) == 1) dl.AddRectFilled(rp, rp + new Vector2(w, RowH), RowAlt); + + ImGuiNET.ImGui.PushID(i); + if (IconButton("##fav", PhosphorIcons.Star, rp + new Vector2(2, 1), new Vector2(btn, btn), r.Favorite ? Gold : Faded(Mute), + r.Favorite ? Selected : PanelBg, enabled: travel && r.OnMap, font: UiFont.Ui11)) + RynthNavCommands.ToggleFavorite(r.Name, r.Ns, r.Ew); + ImGuiNET.ImGui.SetItemTooltip(r.Favorite ? "Remove from favorites" : "Add to favorites"); + + float bodyX = rp.X + btn + 4, bodyW = w - btn - 4; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bodyX, rp.Y)); + if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(Math.Max(1, bodyW), RowH))) Pick(r); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + if (hot && !selected) dl.AddRectFilled(new Vector2(bodyX, rp.Y), new Vector2(bodyX + bodyW, rp.Y + RowH), RowHot); + + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), TypeIcon(r.Type), new Vector2(bodyX, rp.Y), new Vector2(iconW, RowH), TypeColor(r.Type)); + float metaW = r.Meta.Length > 0 ? f9.CalcTextSizeA(f9.FontSize, float.MaxValue, 0, r.Meta).X + 6 : 0; + float nameX = bodyX + iconW + 2, nameMax = bodyX + bodyW - metaW; + dl.PushClipRect(new Vector2(nameX, rp.Y), new Vector2(Math.Max(nameX, nameMax - 2), rp.Y + RowH), true); + dl.AddText(f, f.FontSize, new Vector2(nameX, rp.Y + (RowH - f.FontSize) * 0.5f), r.OnMap ? Text : Mute, r.Name); + dl.PopClipRect(); + if (metaW > 0) + dl.AddText(f9, f9.FontSize, new Vector2(nameMax, rp.Y + (RowH - f9.FontSize) * 0.5f), Mute, r.Meta); + } + ImGuiNET.ImGui.SetCursorScreenPos(basePos); + ImGuiNET.ImGui.Dummy(new Vector2(w, Math.Max(1, rows.Length * RowH))); + } + + private const string GoLabel = PhosphorIcons.Play + " Go"; + private const string RecallsOpenLabel = PhosphorIcons.CaretDown + " RECALLS AND PORTAL TIES", + RecallsShutLabel = PhosphorIcons.CaretRight + " RECALLS AND PORTAL TIES", + InfoOpenLabel = PhosphorIcons.CaretDown + " INFO, LOAD / TEST, MOVEMENT", + InfoShutLabel = PhosphorIcons.CaretRight + " INFO, LOAD / TEST, MOVEMENT"; + + /// <summary>A section header that folds: click to open or shut. Returns whether it's open.</summary> + private static bool Fold(string id, string label, ref bool open, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (Button(id, label, p, new Vector2(w, 22), Teal, open ? Selected : BtnFill, leftAlign: true)) open = !open; + NextLine(p, 26); + return open; + } + + // ── Route view ─────────────────────────────────────────────────────── + + private void DrawRouteView(RynthNavStatus? st, float cw) + { + SectionLabel("ROUTE"); + if (st == null) { Wrapped("RynthNav isn't answering.", Mute, cw); return; } + if (!st.Travel) + { + Wrapped("This RynthNav is older than routes (0.6.0): update RynthNav. " + + "Go still walks the navmesh to coordinates.", Amber, cw); + if (st.PathText.Length > 0) Wrapped(st.PathText, Text, cw); + return; + } + if (st.Route.Length == 0) + { + Wrapped("No route yet: pick a destination, then Route (plan only) or Go.", Mute, cw); + return; + } + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + Wrapped(st.RouteHeader, Text, cw); + ImGuiNET.ImGui.PopFont(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + for (int i = 0; i < st.Route.Length && i < st.RouteLines.Length; i++) + { + RynthNavRouteStep s = st.Route[i]; + bool current = st.RouteActive && i == st.RouteIdx; + bool done = st.RouteActive && i < st.RouteIdx; + uint col = current ? RunGreen : done ? Faded(Mute) + : s.Kind == "recall" ? Amber : s.Kind == "portal" ? Purple : s.Kind == "town" ? Teal : Text; + Vector2 top = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.Indent(8); + Wrapped(st.RouteLines[i], col, cw - 8); + if (current && st.StepLeft.Length > 0) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + Label(st.StepLeft, RunGreen); + ImGuiNET.ImGui.PopFont(); + } + ImGuiNET.ImGui.Unindent(8); + if (current) + { + // A bar down the current step's left edge. + float bottom = ImGuiNET.ImGui.GetItemRectMax().Y; + dl.AddRectFilled(new Vector2(top.X, top.Y), new Vector2(top.X + 3, bottom), RunGreen, 1); + } + } + } + + // ── Recalls section ────────────────────────────────────────────────── + + private static void DrawRecalls(RynthNavStatus? st, float cw) + { + ImGuiNET.ImGui.Indent(4); + float iw = cw - 4; + if (st == null || !st.Travel) + { + Wrapped(st == null ? "RynthNav isn't answering." : "This RynthNav is older than recall routing (0.6.0): update RynthNav.", Amber, iw); + ImGuiNET.ImGui.Unindent(4); + return; + } + + SectionLabel("PORTAL TIES"); + if (st.HasTies) + { + Wrapped(st.Tie1Text, Text, iw); + Wrapped(st.Tie2Text, Text, iw); + if (st.TiePendingText.Length > 0) + { + Wrapped(st.TiePendingText, Amber, iw); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float bw = (iw - 4) * 0.5f; + if (Button("##rc_tie1", "Primary (tie 1)", p, new Vector2(bw, 24), Text, BtnFill, border: Amber)) + RynthNavCommands.Command("tie 1"); + ImGuiNET.ImGui.SetItemTooltip("It was Primary Portal Tie"); + if (Button("##rc_tie2", "Secondary (tie 2)", new Vector2(p.X + bw + 4, p.Y), new Vector2(bw, 24), Text, BtnFill, border: Amber)) + RynthNavCommands.Command("tie 2"); + ImGuiNET.ImGui.SetItemTooltip("It was Secondary Portal Tie"); + NextLine(p, 28); + } + if (st.MineLines.Length > 0) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + SectionLabel("WHERE YOUR RECALLS LAND"); + foreach (string line in st.MineLines) Wrapped(line, Text, iw); + } + } + else Wrapped("Update RynthNav (0.6.1) to see your portal ties here and answer \"which tie was it?\" with a button.", Mute, iw); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + SectionLabel(st.RecallHeader); + foreach (string line in st.RecallLines) Wrapped(line, Text, iw); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + foreach (string n in st.RecallNotes) Wrapped(n, Mute, iw); + Wrapped("Your own recalls (lifestone, portal ties, house...) are learned as you use them.", Mute, iw); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.Unindent(4); + } + + // ── Info section ───────────────────────────────────────────────────── + + private void DrawInfo(RynthNavStatus? st, float cw) + { + ImGuiNET.ImGui.Indent(4); + float iw = cw - 4; + if (st == null) Wrapped("RynthNav isn't answering.", Mute, iw); + else + { + InfoRow("Here", st.InfoHere, iw); + InfoRow("Position", st.PlayerText, iw); + InfoRow("NavData", st.InfoNavData, iw); + if (st.InfoTiles.Length > 0) InfoRow("Tiles", st.InfoTiles, iw); + InfoRow("Route graph", st.InfoGraph, iw); + InfoRow("Town Network", st.InfoTownNet, iw); + InfoRow("Atlas", st.InfoAtlas, iw); + InfoRow("Navmesh", st.InfoStatus, iw); + } + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + + // Load / Test / Preview + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + string coord = PickCoord(); + float bw = (iw - 2 * 4) / 3f; + if (Button("##load", "Load tile", p, new Vector2(bw, 24), Text, BtnFill)) RynthNavCommands.LoadTile(); + ImGuiNET.ImGui.SetItemTooltip("Load the navmesh tiles around you again"); + if (Button("##test", "Test @ me", new Vector2(p.X + bw + 4, p.Y), new Vector2(bw, 24), Text, BtnFill)) RynthNavCommands.TestQuery(); + ImGuiNET.ImGui.SetItemTooltip("Is there navmesh under you?"); + if (Button("##preview", "Preview", new Vector2(p.X + 2 * (bw + 4), p.Y), new Vector2(bw, 24), Text, BtnFill, enabled: coord.Length > 0)) + RynthNavCommands.Preview(coord); + ImGuiNET.ImGui.SetItemTooltip(coord.Length > 0 ? "Plan the navmesh path to the destination (close places only), no walking" + : "Pick a destination on the map first"); + NextLine(p, 30); + + // Movement pad + SectionLabel("MOVE"); + p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float bw2 = 58, bh = 42, gap = 6; + float left = p.X + (iw - (3 * bw2 + 2 * gap)) * 0.5f; + MoveButton(PhosphorIcons.ArrowUp, "Forward (tap to run / stop)", 1, new Vector2(left + bw2 + gap, p.Y), st?.RunState == 1); + MoveButton(PhosphorIcons.ArrowLeft, "Turn left (tap to start / stop)", 3, new Vector2(left, p.Y + bh + gap), st?.TurnState == -1); + MoveButton(PhosphorIcons.Stop, "Stop everything", 5, new Vector2(left + bw2 + gap, p.Y + bh + gap), false); + MoveButton(PhosphorIcons.ArrowRight, "Turn right (tap to start / stop)", 4, new Vector2(left + 2 * (bw2 + gap), p.Y + bh + gap), st?.TurnState == 1); + MoveButton(PhosphorIcons.ArrowDown, "Backward (tap to walk back / stop)", 2, new Vector2(left + bw2 + gap, p.Y + 2 * (bh + gap)), st?.RunState == 2); + NextLine(p, 3 * bh + 2 * gap + 4); + CenteredHint(MoveHint, iw); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.Unindent(4); + } + + private static void InfoRow(string label, string value, float w) + { + const float lw = 78; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.GetWindowDrawList().AddText(p, Mute, label); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + lw, p.Y)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + Math.Max(40, w - lw)); + ImGuiNET.ImGui.TextUnformatted(value.Length > 0 ? value : "—"); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + // Back to the left edge for the next row. + Vector2 end = new(p.X, ImGuiNET.ImGui.GetItemRectMax().Y + 3); + ImGuiNET.ImGui.SetCursorScreenPos(end); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + private const string MoveHint = "tap " + PhosphorIcons.ArrowUp + PhosphorIcons.ArrowDown + " run · tap " + + PhosphorIcons.ArrowLeft + PhosphorIcons.ArrowRight + " turn (tap again to stop) · " + PhosphorIcons.Stop + " stop"; + + private static void MoveButton(string glyph, string tip, int cmd, Vector2 pos, bool active) + { + if (IconButton("##mv" + cmd, glyph, pos, new Vector2(58, 42), Text, active ? RunGreen : BtnFill)) + RynthNavCommands.Move(cmd); + ImGuiNET.ImGui.SetItemTooltip(tip); + } + + // Avoidance, one row per kind of thing kept away from: on/off, then − value +. Each click + // sends /rnav avoid ... (saved in rynthnav.json by RynthNav). + private static void AvoidRows(RynthNavStatus st, float w) + { + AvoidRow("portals", "Avoid portals", st.AvoidPortals, st.AvoidPortalM, 0.5, w, + "Keep this far from every portal that isn't the next step's own (walking into one teleports you)."); + AvoidRow("walls", "Avoid walls", st.AvoidWalls, st.AvoidWallM, 0.5, w, + "Swing this far wide of building and wall corners the path turns round."); + AvoidRow("corners", "Corner reach", null, st.CornerM, 0.5, w, + "A path corner counts as reached this close. Bigger turns earlier and cuts corners."); + } + + private static void AvoidRow(string key, string label, bool? on, double metres, double step, float w, string tip) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float bw = 22, vw = 54, lw = w - 2 * bw - vw - 12; + if (on is bool b) + { + if (Toggle("##av_" + key, label, b, p, lw)) + RynthNavCommands.Command($"avoid {key} {(b ? "off" : "on")}"); + } + else + Button("##av_" + key, label, p, new Vector2(lw, 22), Text, BtnFill, enabled: false, leftAlign: true); + ImGuiNET.ImGui.SetItemTooltip(tip); + bool active = on ?? true; + float x = p.X + lw + 4; + string Fmt(double v) => v.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture); + if (Button("##av_" + key + "_dn", "-", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill, enabled: active)) + RynthNavCommands.Command($"avoid {key} {Fmt(Math.Max(0, metres - step))}"); + Button("##av_" + key + "_v", Fmt(metres) + " m", new Vector2(x + bw + 4, p.Y), new Vector2(vw, 22), active ? Text : Faded(Mute), PanelBg, enabled: false); + if (Button("##av_" + key + "_up", "+", new Vector2(x + bw + vw + 8, p.Y), new Vector2(bw, 22), Text, BtnFill, enabled: active)) + RynthNavCommands.Command($"avoid {key} {Fmt(metres + step)}"); + NextLine(p, 26); + } + + private static bool Toggle(string id, string label, bool on, Vector2 pos, float width) + { + string text = (on ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " " + label; + return Button(id, text, pos, new Vector2(width, 22), on ? Teal : Text, on ? Selected : BtnFill, leftAlign: true, border: on ? Teal : 0); + } + + // ── Atlas ──────────────────────────────────────────────────────────── + + private static readonly (AtlasMode Mode, string Label, string Tip)[] Modes = + { + (AtlasMode.Search, PhosphorIcons.MagnifyingGlass + " Search", "Every place, best name match first"), + (AtlasMode.Nearby, PhosphorIcons.Target + " Nearby", "Places on the map, nearest first"), + (AtlasMode.Favorites, PhosphorIcons.Star + " Favorites", "Places you starred"), + (AtlasMode.Recent, PhosphorIcons.ClockCounterClockwise + " Recent", "Places you pointed the arrow at or went to"), + }; + + private const float RowH = 20f, DetailH = 118f; + + private void DrawAtlas(float w, Vector2 origin, Vector2 size) + { + RynthNavStatus? st = _st; + if (st != null && !st.Travel) { Wrapped("This RynthNav is older than the Atlas (0.6.0): update RynthNav.", Amber, w); return; } + + // Mode buttons + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float mw = (w - 3 * 4) / 4f; + for (int i = 0; i < Modes.Length; i++) + { + bool sel = Modes[i].Mode == _mode; + if (Button("##atl_mode" + i, Modes[i].Label, new Vector2(p.X + i * (mw + 4), p.Y), new Vector2(mw, 22), + sel ? Teal : Text, sel ? Selected : BtnFill, border: sel ? Teal : 0)) + { + _mode = Modes[i].Mode; + PushQuery(); + } + ImGuiNET.ImGui.SetItemTooltip(Modes[i].Tip); + } + NextLine(p, 26); + + // Search box + type + p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float typeW = 112; + float searchW = Math.Max(80, w - typeW - 4); + TextBox("##atl_search", _search, p, searchW, "Search places by name", out _); + string text = Utf8(_search); + if (text != _seenSearch) { _seenSearch = text; PushQuery(); } + var typePos = new Vector2(p.X + searchW + 4, p.Y); + if (_typeLabelIdx != _typeIdx) + { + _typeLabelIdx = _typeIdx; + _typeLabel = "Type: " + RynthNavAtlas.Types[_typeIdx] + " " + PhosphorIcons.CaretDown; + } + if (Button("##atl_type", _typeLabel, typePos, new Vector2(typeW, 22), Text, BtnFill)) + _typePicker.Open(typePos + new Vector2(0, 24), RynthNavAtlas.Types, _typeIdx, i => { _typeIdx = i; PushQuery(); }, typeW); + NextLine(p, 26); + + AtlasView view = UiSources.RynthNavAtlas.Current?.Value ?? AtlasView.Empty; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + Label(view.Summary.Length > 0 ? view.Summary : RynthNavAtlas.Status.Length > 0 ? RynthNavAtlas.Status : "Loading…", Mute); + ImGuiNET.ImGui.PopFont(); + + // List + float listH = Math.Max(60, origin.Y + size.Y - 6 - ImGuiNET.ImGui.GetCursorScreenPos().Y - DetailH - 4); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + bool open = ImGuiNET.ImGui.BeginChild("##atl_list", new Vector2(w, listH)); + ImGuiNET.ImGui.PopStyleColor(); + if (open) DrawRows(view.Rows, ImGuiNET.ImGui.GetContentRegionAvail().X); + ImGuiNET.ImGui.EndChild(); + + DrawDetails(w, origin, size); + } + + private void PushQuery() => + RynthNavAtlasSource.Query = new AtlasQuery(_seenSearch, RynthNavAtlas.Types[_typeIdx], _mode); + + private void DrawRows(AtlasRow[] rows, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 basePos = ImGuiNET.ImGui.GetCursorScreenPos(); + float scrollY = ImGuiNET.ImGui.GetScrollY(), viewH = ImGuiNET.ImGui.GetWindowHeight(); + int first = Math.Max(0, (int)(scrollY / RowH)); + int last = Math.Min(rows.Length, first + (int)(viewH / RowH) + 2); + ImFontPtr f = ImGuiFonts.Get(UiFont.Ui10), f9 = ImGuiFonts.Get(UiFont.Ui9); + const float btn = 18, iconW = 20; + for (int i = first; i < last; i++) + { + AtlasRow r = rows[i]; + Vector2 rp = basePos + new Vector2(0, i * RowH); + bool selected = _sel != null && SameRow(_sel, r); + if (selected) dl.AddRectFilled(rp, rp + new Vector2(w, RowH), Selected); + else if ((i & 1) == 1) dl.AddRectFilled(rp, rp + new Vector2(w, RowH), RowAlt); + + // Star (favorite) + ImGuiNET.ImGui.PushID(i); + var starPos = rp + new Vector2(2, 1); + if (IconButton("##fav", PhosphorIcons.Star, starPos, new Vector2(btn, btn), r.Favorite ? Gold : Faded(Mute), + r.Favorite ? Selected : PanelBg, enabled: r.OnMap, font: UiFont.Ui11)) + RynthNavCommands.ToggleFavorite(r.Name, r.Ns, r.Ew); + ImGuiNET.ImGui.SetItemTooltip(r.Favorite ? "Remove from favorites" : "Add to favorites"); + + // Arrow / Go (right) + var goPos = new Vector2(rp.X + w - btn - 2, rp.Y + 1); + var arPos = goPos - new Vector2(btn + 2, 0); + if (IconButton("##arrow", PhosphorIcons.NavigationArrow, arPos, new Vector2(btn, btn), Teal, BtnFill, enabled: r.OnMap, font: UiFont.Ui11)) + { + RynthNavCommands.Arrow(r.Name, r.Ns, r.Ew); + _sel = r; + } + ImGuiNET.ImGui.SetItemTooltip(r.OnMap ? "Point the arrow here" : "In a dungeon: no arrow"); + if (IconButton("##go", PhosphorIcons.Play, goPos, new Vector2(btn, btn), Green, BtnFill, enabled: r.OnMap, font: UiFont.Ui11)) + { + RynthNavCommands.Go(r.Name, r.Ns, r.Ew); + _sel = r; + } + ImGuiNET.ImGui.SetItemTooltip(r.OnMap ? "Go: RynthNav walks here" : "In a dungeon: RynthNav can't walk there"); + + // Row body: click selects + float bodyX = rp.X + btn + 4, bodyW = arPos.X - 4 - bodyX; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bodyX, rp.Y)); + if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(Math.Max(1, bodyW), RowH))) _sel = r; + bool hot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + if (hot && !selected) dl.AddRectFilled(new Vector2(bodyX, rp.Y), new Vector2(bodyX + bodyW, rp.Y + RowH), RowHot); + + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), TypeIcon(r.Type), new Vector2(bodyX, rp.Y), new Vector2(iconW, RowH), TypeColor(r.Type)); + float distW = r.Dist.Length > 0 ? f9.CalcTextSizeA(f9.FontSize, float.MaxValue, 0, r.Dist).X + 6 : 0; + float nameX = bodyX + iconW + 2, nameMax = bodyX + bodyW - distW; + dl.PushClipRect(new Vector2(nameX, rp.Y), new Vector2(Math.Max(nameX, nameMax - 2), rp.Y + RowH), true); + dl.AddText(f, f.FontSize, new Vector2(nameX, rp.Y + (RowH - f.FontSize) * 0.5f), r.OnMap ? Text : Mute, r.Name); + dl.PopClipRect(); + if (distW > 0) + dl.AddText(f9, f9.FontSize, new Vector2(nameMax, rp.Y + (RowH - f9.FontSize) * 0.5f), Mute, r.Dist); + } + ImGuiNET.ImGui.SetCursorScreenPos(basePos); + ImGuiNET.ImGui.Dummy(new Vector2(w, Math.Max(1, rows.Length * RowH))); + } + + private static bool SameRow(AtlasRow a, AtlasRow b) => + a.Name == b.Name && Math.Abs(a.Ns - b.Ns) < 1e-6 && Math.Abs(a.Ew - b.Ew) < 1e-6 && a.Type == b.Type; + + private void DrawDetails(float w, Vector2 origin, Vector2 size) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float h = Math.Max(40, origin.Y + size.Y - 6 - p.Y); + dl.AddRectFilled(p, p + new Vector2(w, h), PanelBg, 3); + AtlasRow? r = _sel; + if (r == null) + { + dl.AddText(p + new Vector2(6, 6), Mute, "Click a place for its details."); + NextLine(p, h); + return; + } + NavPlace? place = r.Place; + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), f9 = ImGuiFonts.Get(UiFont.Ui9); + float x = p.X + 6, y = p.Y + 5, right = p.X + w - 6; + dl.PushClipRect(p, p + new Vector2(w, h), true); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), TypeIcon(r.Type), new Vector2(x, y), new Vector2(16, 16), TypeColor(r.Type)); + dl.AddText(bold, bold.FontSize, new Vector2(x + 20, y + 1), Teal, r.Name); + y += 19; + if (!ReferenceEquals(_detailsFor, r)) + { + _detailsFor = r; + _detailsLine = r.Type + " · " + r.Coord + (place != null && place.LevelText.Length > 0 ? " · " + place.LevelText : "") + + (place != null && place.Quest ? " · needs a quest flag" : "") + (place != null && place.Closed ? " · closed" : ""); + _detailsDest = place != null && place.HasDest ? PhosphorIcons.Spiral + " Goes to " + place.DestText : ""; + } + dl.AddText(new Vector2(x, y), Text, _detailsLine); + y += 16; + if (_detailsDest.Length > 0) + { + dl.AddText(new Vector2(x, y), Purple, _detailsDest); + y += 16; + } + if (place != null && place.Desc.Length > 0) + { + float wrap = right - x; + dl.AddText(f9, f9.FontSize, new Vector2(x, y), Mute, place.Desc, wrap); + } + dl.PopClipRect(); + + // Buttons along the bottom. + float by = p.Y + h - 26; + float bw = (w - 12 - 3 * 4) / 4f; + bool on = r.OnMap; + if (Button("##det_arrow", PhosphorIcons.NavigationArrow + " Arrow", new Vector2(x, by), new Vector2(bw, 22), Teal, BtnFill, enabled: on)) + RynthNavCommands.Arrow(r.Name, r.Ns, r.Ew); + if (Button("##det_go", PhosphorIcons.Play + " Go", new Vector2(x + (bw + 4), by), new Vector2(bw, 22), Green, BtnFill, enabled: on)) + RynthNavCommands.Go(r.Name, r.Ns, r.Ew); + if (Button("##det_route", PhosphorIcons.Path + " Route", new Vector2(x + 2 * (bw + 4), by), new Vector2(bw, 22), Text, BtnFill, enabled: on)) + { + // The plan shows on the Go tab, with this place as its destination. + RynthNavCommands.Route(r.Name, r.Ns, r.Ew); + _tab = TabGo; + Pick(r); + } + ImGuiNET.ImGui.SetItemTooltip("Plan a route here (portals and recalls) and show it on the Go tab"); + float grip = ImGuiPanelHost.BodyGripReserve; + float favW = Math.Max(24, bw - Math.Max(0, grip - 6)); + if (Button("##det_fav", PhosphorIcons.Star + (favW > 60 ? (r.Favorite ? " Unstar" : " Star") : ""), new Vector2(x + 3 * (bw + 4), by), + new Vector2(favW, 22), r.Favorite ? Gold : Text, BtnFill, enabled: on)) + RynthNavCommands.ToggleFavorite(r.Name, r.Ns, r.Ew); + NextLine(p, h); + } + + private static string TypeIcon(string type) => type switch + { + "Town" => PhosphorIcons.CastleTurret, + "Dungeon" => PhosphorIcons.Skull, + "Portal" => PhosphorIcons.Spiral, + "Lifestone" => PhosphorIcons.Heartbeat, + "Bindstone" => PhosphorIcons.Crown, + "Vendor" => PhosphorIcons.Storefront, + "NPC" => PhosphorIcons.User, + "Recall" => PhosphorIcons.MagicWand, + _ => PhosphorIcons.MapPin, + }; + + private static uint TypeColor(string type) => type switch + { + "Town" => Teal, + "Dungeon" => Red, + "Portal" => Purple, + "Lifestone" => Green, + "Bindstone" => Gold, + "Vendor" => Amber, + "NPC" => Amber, + _ => Mute, + }; + + // ── Arrow ──────────────────────────────────────────────────────────── + + private void DrawArrow(float w) + { + RynthNavStatus? st = _st; + if (st != null && !st.Travel) { Wrapped("This RynthNav is older than the arrow (0.6.0): update RynthNav.", Amber, w); return; } + _read.Update(st); + RynthNavArrow? a = st?.Arrow; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + + // The arrow and its readout + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float d = 76; + Vector2 c = p + new Vector2(d * 0.5f, d * 0.5f); + dl.AddCircleFilled(c, d * 0.5f, PanelBg, 40); + dl.AddCircle(c, d * 0.5f, Sep, 40, 1.5f); + _read.DrawPointer(dl, c, d * 0.5f - 8); + float tx = p.X + d + 10; + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold14), f9 = ImGuiFonts.Get(UiFont.Ui9); + dl.PushClipRect(new Vector2(tx, p.Y), new Vector2(p.X + w, p.Y + d), true); + dl.AddText(bold, bold.FontSize, new Vector2(tx, p.Y + 4), Teal, _read.Line1); + dl.AddText(new Vector2(tx, p.Y + 26), Text, _read.Line2); + dl.AddText(new Vector2(tx, p.Y + 44), Mute, _read.Line3); + if (a != null && a.ThenText.Length > 0) + dl.AddText(f9, f9.FontSize, new Vector2(tx, p.Y + 60), Mute, a.ThenText); + dl.PopClipRect(); + NextLine(p, d + 6); + + // Buttons + p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool shown = ImGuiPanelHost.IsOpen(RynthNavArrowFace.Title); + float bw = (w - 4 * 4) / 5f; + if (Button("##ar_show", (shown ? PhosphorIcons.Eye + " Hide" : PhosphorIcons.Eye + " Show"), p, new Vector2(bw, 24), + shown ? Teal : Text, shown ? Selected : BtnFill, border: shown ? Teal : 0)) + { + if (shown) ImGuiPanelHost.Close(RynthNavArrowFace.Title); + else ImGuiPanelHost.Open(RynthNavArrowFace.Title); + } + ImGuiNET.ImGui.SetItemTooltip("Show or hide the small arrow overlay (drag it anywhere; it pops out too)"); + bool has = a != null; + if (Button("##ar_go", GoLabel, new Vector2(p.X + (bw + 4), p.Y), new Vector2(bw, 24), Green, BtnFill, enabled: has) && a != null) + RynthNavCommands.Go(a.Final, a.FinalNs, a.FinalEw); + if (Button("##ar_stop", PhosphorIcons.Stop + " Stop", new Vector2(p.X + 2 * (bw + 4), p.Y), new Vector2(bw, 24), Red, BtnFill)) + RynthNavCommands.Move(5); + if (Button("##ar_clear", PhosphorIcons.X + " Clear", new Vector2(p.X + 3 * (bw + 4), p.Y), new Vector2(bw, 24), Text, BtnFill, enabled: has)) + RynthNavCommands.Command("arrow off"); + if (Button("##ar_fav", PhosphorIcons.Star + " Star", new Vector2(p.X + 4 * (bw + 4), p.Y), new Vector2(bw, 24), Gold, BtnFill, enabled: has) && a != null) + RynthNavCommands.ToggleFavorite(a.Final, a.FinalNs, a.FinalEw); + ImGuiNET.ImGui.SetItemTooltip("Add the target to favorites (or take it off)"); + NextLine(p, 30); + Line(w); + + // Set the arrow + SectionLabel("POINT THE ARROW AT"); + p = ImGuiNET.ImGui.GetCursorScreenPos(); + float sw = ButtonWidth("Set"), rw = ButtonWidth(PhosphorIcons.Path + " Via route"); + float boxW = Math.Max(80, w - sw - rw - 8); + bool enter = TextBox("##ar_to", _arrowTo, p, boxW, "Holtburg, or 42.1N, 33.6E", out _, ImGuiInputTextFlags.EnterReturnsTrue); + string to = Utf8(_arrowTo).Trim(); + if ((Button("##ar_set", "Set", new Vector2(p.X + boxW + 4, p.Y), new Vector2(sw, 22), Text, BtnFill, enabled: to.Length > 0) || enter) && to.Length > 0) + RynthNavCommands.Command("arrow " + to); + if (Button("##ar_route", PhosphorIcons.Path + " Via route", new Vector2(p.X + boxW + 8 + sw, p.Y), new Vector2(rw, 22), Text, BtnFill, enabled: to.Length > 0)) + RynthNavCommands.Command("arrow route " + to); + ImGuiNET.ImGui.SetItemTooltip("Point along a planned route: each portal and recall, then the place"); + NextLine(p, 28); + + // Arrival radius + p = ImGuiNET.ImGui.GetCursorScreenPos(); + double arrive = a?.ArriveYards > 0 ? a.ArriveYards : 10; + if (arrive != _arriveShown) + { + _arriveShown = arrive; + _arriveText = "Arrives within " + arrive.ToString("0", System.Globalization.CultureInfo.InvariantCulture) + " yd"; + } + dl.AddText(p + new Vector2(0, 4), Mute, _arriveText); + float ax = p.X + ImGuiNET.ImGui.CalcTextSize("Arrives within 000 yd").X + 8; + if (IconButton("##ar_less", PhosphorIcons.Minus, new Vector2(ax, p.Y), new Vector2(22, 22), Text, BtnFill, enabled: has && arrive > 4, font: UiFont.Ui11)) + RynthNavCommands.Command("arrive " + Math.Max(3, arrive - 5).ToString("0", System.Globalization.CultureInfo.InvariantCulture)); + if (IconButton("##ar_more", PhosphorIcons.Plus, new Vector2(ax + 26, p.Y), new Vector2(22, 22), Text, BtnFill, enabled: has && arrive < 150, font: UiFont.Ui11)) + RynthNavCommands.Command("arrive " + Math.Min(150, arrive + 5).ToString("0", System.Globalization.CultureInfo.InvariantCulture)); + NextLine(p, 28); + Line(w); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + Wrapped("Also: the Atlas tab's " + PhosphorIcons.NavigationArrow + " on any place; right-click coordinates in chat; " + + "/rnav arrow <place or coords>; /rnav arrow off.", Mute, w - ImGuiPanelHost.BodyGripReserve); + ImGuiNET.ImGui.PopFont(); + } + + // ── Shared bits ────────────────────────────────────────────────────── + + private static void SectionLabel(string text) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + Label(text, Teal); + ImGuiNET.ImGui.PopFont(); + } + + private static void Wrapped(string text, uint color, float w) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(text); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + } + + private static void CenteredHint(string text, float w) + { + ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9); + ImGuiNET.ImGui.PushFont(f9); + float tw = ImGuiNET.ImGui.CalcTextSize(text).X; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + Math.Max(0, (w - tw) * 0.5f), p.Y), Mute, text); + ImGuiNET.ImGui.PopFont(); + NextLine(p, f9.FontSize + 4); + } + + private static void Line(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.GetWindowDrawList().AddLine(p + new Vector2(0, 3), p + new Vector2(w, 3), Sep); + ImGuiNET.ImGui.Dummy(new Vector2(w, 6)); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs b/src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs new file mode 100644 index 0000000..bf9535a --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs @@ -0,0 +1,103 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ScriptWindowFace.cs +// Script windows (API v71): the panel face of one window a plugin submitted +// (UI/ScriptWindows). Hosted by ImGuiPanelHost like any panel (frame, saved +// placement, error isolation, input capture); Draw is the replay. +// Design: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §3, §2.5 (Geometry). +// +// Before the replay, inside the host's body child, the face reports the +// window's geometry (position, size, content region, cursor start, focused, +// hovered) in logical units at UI scale 1, as a Geometry event when a value +// moved by more than half a unit or a flag changed. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.ScriptWindows; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed unsafe class ScriptWindowFace : IImGuiPanel +{ + private const float GeometryEpsilon = 0.5f; + + private readonly ScriptWindow _window; + + public ScriptWindowFace(ScriptWindow window) => _window = window; + + public bool ClickThrough => (_window.Flags & WindowFlags.ClickThrough) != 0; + + /// <summary> + /// Opened. Unless the owner asked for it (ScriptWindow.ExpectOpen), the player + /// opened it (bar, /rc ui open): the owner hears it once so its own visible flag + /// follows, and its flag stays stale until it has seen this event (§3.3). AC thread. + /// </summary> + public void OnShown() => NoteVisibility(visible: true); + + /// <summary>Closed: as OnShown; a close the owner didn't ask for is the player's X unless the bar said otherwise.</summary> + public void OnHidden() => NoteVisibility(visible: false); + + private void NoteVisibility(bool visible) + { + ScriptWindow w = _window; + bool expected; + if (visible) { expected = w.ExpectOpen; w.ExpectOpen = false; } + else { expected = w.ExpectClose; w.ExpectClose = false; } + int reason = w.PendingReason; + w.PendingReason = 0; + if (w.Removed || expected) return; + byte why = reason != 0 ? (byte)reason + : visible ? VisibilityReason.BarOrCommand : VisibilityReason.PlayerClose; + w.PlayerVisibilitySeq = w.Owner.Events.Visibility(w.Hash, visible, why); + } + + public void Draw() + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + try + { + ScriptWindowMetrics.Refresh(); + ReportGeometry(); + ScriptWindowReplay.Draw(_window); + } + finally + { + ImGuiNET.ImGui.PopFont(); + } + } + + /// <summary>Queues a Geometry event when the body's geometry or focus/hover changed. AC thread.</summary> + private void ReportGeometry() + { + float s = EngineFrameController.FontScale; + if (!(s > 0f) || !float.IsFinite(s)) s = 1f; + Vector2 pos, size, avail, cursor; + ImGuiNative.igGetWindowPos(&pos); + ImGuiNative.igGetWindowSize(&size); + ImGuiNative.igGetContentRegionAvail(&avail); + ImGuiNative.igGetCursorPos(&cursor); + uint flags = 0; + if (ImGuiNative.igIsWindowFocused(ImGuiFocusedFlags.RootAndChildWindows) != 0) flags |= ScriptGeometry.Focused; + if (ImGuiNative.igIsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows) != 0) flags |= ScriptGeometry.Hovered; + var g = new ScriptGeometry + { + Pos = pos / s, + Size = size / s, + Avail = avail / s, + Cursor = cursor / s, + Flags = flags, + }; + ScriptWindow w = _window; + if (w.GeometrySent && g.Flags == w.LastGeometry.Flags + && !Moved(g.Pos, w.LastGeometry.Pos) && !Moved(g.Size, w.LastGeometry.Size) + && !Moved(g.Avail, w.LastGeometry.Avail) && !Moved(g.Cursor, w.LastGeometry.Cursor)) + return; + w.LastGeometry = g; + w.GeometrySent = true; + w.Owner.Events.Geometry(w.Hash, g); + } + + private static bool Moved(Vector2 a, Vector2 b) => + MathF.Abs(a.X - b.X) > GeometryEpsilon || MathF.Abs(a.Y - b.Y) > GeometryEpsilon; +} diff --git a/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs b/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs new file mode 100644 index 0000000..eb5fc01 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs @@ -0,0 +1,430 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/SenseFace.cs +// The Sense panel, our take on Virindi Sense: type a name, and every object +// the client knows about anywhere (not just in radar range) whose name +// matches shows up here. Engine only, ImGui only. +// +// add row a text box (Enter adds), Add, the settings gear, the help mark +// terms one chip per term: click it to switch it on/off, X removes it +// status how many matches among how many known objects (or why none) +// rows direction arrow (relative to where you face), name, kind, +// distance, compass point, map coordinates; nearest first; a new +// match flashes. Click selects it in game, hover for details. +// gear a chat line and/or the system beep when a new match appears +// (both off by default; they work with the panel closed). +// +// Data: SenseStore (the list, sense.txt) and UiSources.Sense (the 2 Hz scan on +// the pump thread, snapshots only; UI/Data/SenseData.cs). This face only reads +// the published view and the player pose snapshot (for the arrows, per frame) +// and parks a click's select with AcMainThreadQueue.EnqueueOverlaySelect, the +// path the Radar and the nameplates use. AC's render thread; no AC calls, no +// file I/O, no per-frame allocation except a hovered row's tooltip. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class SenseFace : IImGuiPanel +{ + public const string Title = "Sense"; + + /// <summary>Registers the face (engine init) and queues the list's load so alerts work before it opens.</summary> + public static void Register() + { + ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(470, 360), new Vector2(300, 220), EdgeToEdge: true, GripInBody: true), + () => new SenseFace()); + SenseStore.EnsureLoadQueued(); + } + + /// <summary>Arrows turn with you: 10 Hz idle popped out, 30 Hz while a new match flashes.</summary> + public int PopOutIdleHz => _flashing ? 30 : 10; + + // ── Layout (px) and palette ────────────────────────────────────────── + private const float RowH = 20f, ArrowW = 20f, KindW = 58f, DistW = 64f, DirW = 34f, LocW = 116f, ChipH = 20f; + private const long FlashMs = 2500; + + private static readonly uint Purple = RynthTheme.Argb(0xFFBF4DFF), ChipOff = RynthTheme.Argb(0xFF0E161E); + + private const string HelpText = + "Sense lists every object the client knows about whose name matches a term on your list, however far away it is.\n\n" + + "How far: the client only knows what the server has sent it. That is everything in the landblocks it has loaded " + + "around you (outdoors: your landblock and the ones around it, a few hundred yards, far past the radar), or the whole " + + "dungeon you are in. Nothing beyond that reaches the client, so no plugin can see it.\n\n" + + "Terms ignore case. Without * or ? a name only has to contain the term (drake finds Dragon's Isle Drake). " + + "With them the whole name must match: Drake* starts with Drake, ? is any one letter.\n\n" + + "The distance shows when you and the object are both outdoors (or in surface buildings), or in the same dungeon. " + + "Otherwise the row says elsewhere and gives the landblock.\n\n" + + "Click a row to select it in game. Gear: a chat line or a beep when a new match appears.\n" + + "/rc sense opens and closes this panel."; + + // ── State ─────────────────────────────────────────────────────────── + private readonly byte[] _input = new byte[SenseStore.MaxTermLength + 1]; + private string _message = ""; + private uint _messageColor; + private long _messageUntilMs; + private bool _openSettings; + private bool _flashing; + + public void OnShown() + { + SenseStore.EnsureLoadQueued(); + UiSources.Sense.Subscribe(); + UiSources.Sense.RequestRefresh(); + } + + public void OnHidden() => UiSources.Sense.Unsubscribe(); + + public void Draw() + { + float w = Begin(out Vector2 origin, out Vector2 size); + DrawAddRow(w); + DrawTerms(w); + + SenseView view = UiSources.Sense.Current?.Value ?? SenseView.Empty; + DrawStatus(view); + bool showLoc = w - (ArrowW + KindW + DistW + DirW + LocW) >= 110; + DrawColumnHeader(w, showLoc); + + float bodyH = Math.Max(40, Remaining(origin, size) - GripOverlap()); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0)); + ImGuiNET.ImGui.BeginChild("##sense_rows", new Vector2(w, bodyH)); + DrawRows(view, showLoc); + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + End(origin, size); + + DrawSettingsPopup(); + } + + // ── Add row ───────────────────────────────────────────────────────── + + private void DrawAddRow(float w) + { + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + const float h = 22, iconW = 22; + string addLabel = PhosphorIcons.Plus + " Add"; + float addW = ButtonWidth(addLabel); + float boxW = Math.Max(60, w - addW - iconW * 2 - 12); + + bool enter = TextBox("##sense_input", _input, start, boxW, + PhosphorIcons.MagnifyingGlass + " Name to watch for (* and ? wildcards)", out _, + ImGuiInputTextFlags.EnterReturnsTrue, h); + bool add = Button("##sense_add", addLabel, new Vector2(start.X + boxW + 4, start.Y), new Vector2(addW, h), Text, BtnFill, + enabled: SenseStore.Loaded); + ImGuiNET.ImGui.SetItemTooltip("Add the name to the watch list (Enter in the box does the same)"); + if (enter || add) AddTerm(); + + float gx = start.X + boxW + 4 + addW + 4; + if (IconButton("##sense_gear", PhosphorIcons.Gear, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill)) + _openSettings = true; + ImGuiNET.ImGui.SetItemTooltip("Alerts"); + IconButton("##sense_help", PhosphorIcons.Info, new Vector2(gx + iconW + 4, start.Y), new Vector2(iconW, h), Mute, BtnFill); + if (ImGuiNET.ImGui.IsItemHovered()) + { + ImGuiNET.ImGui.BeginTooltip(); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetFontSize() * 30); + ImGuiNET.ImGui.TextUnformatted(HelpText); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.EndTooltip(); + } + NextLine(start, h + 4); + } + + private void AddTerm() + { + string text = Utf8(_input); + bool ok = SenseStore.Add(text, out string message); + if (ok) WriteUtf8(_input, ""); + ShowMessage(message, ok ? Mute : Amber); + } + + private void ShowMessage(string text, uint color) + { + _message = text; + _messageColor = color; + _messageUntilMs = Environment.TickCount64 + 3000; + } + + // ── Terms ─────────────────────────────────────────────────────────── + + private void DrawTerms(float w) + { + if (!SenseStore.Loaded) + { + Label("Loading the watch list...", Mute); + return; + } + SensePattern[] terms = SenseStore.Terms; + if (terms.Length == 0) + { + Label("No names yet: type one above and press Enter.", Mute); + return; + } + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Ui11); + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + float x = start.X, y = start.Y; + const float iconW = 18, xW = 16; + int toggle = -1, remove = -1; + for (int i = 0; i < terms.Length; i++) + { + SensePattern t = terms[i]; + float textW = ImGuiNET.ImGui.CalcTextSize(t.Text).X; + float chipW = Math.Min(w, iconW + textW + 6 + xW); + if (x > start.X && x + chipW > start.X + w) { x = start.X; y += ChipH + 4; } + var p = new Vector2(x, y); + uint fg = t.Enabled ? Text : Faded(Mute); + + ImGuiNET.ImGui.PushID(i); + ImGuiNET.ImGui.SetCursorScreenPos(p); + if (ImGuiNET.ImGui.InvisibleButton("##t", new Vector2(chipW - xW, ChipH))) toggle = i; + bool hotT = ImGuiNET.ImGui.IsItemHovered(); + if (hotT) + ImGuiNET.ImGui.SetItemTooltip(t.Enabled + ? (t.IsGlob ? "On: the whole name must match (wildcards). Click to switch off." : "On: names containing this match. Click to switch off.") + : "Off. Click to switch on."); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x + chipW - xW, y)); + if (ImGuiNET.ImGui.InvisibleButton("##x", new Vector2(xW, ChipH))) remove = i; + bool hotX = ImGuiNET.ImGui.IsItemHovered(); + if (hotX) ImGuiNET.ImGui.SetItemTooltip("Remove"); + ImGuiNET.ImGui.PopID(); + + uint bg = t.Enabled ? BtnFill : ChipOff; + if (hotT) bg = Lighten(bg); + dl.AddRectFilled(p, p + new Vector2(chipW, ChipH), bg, 3); + dl.AddRect(p, p + new Vector2(chipW, ChipH), t.Enabled ? Teal : BtnBord, 3); + PhosphorIcons.DrawCentered(dl, iconFont, t.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square, + p, new Vector2(iconW, ChipH), t.Enabled ? Teal : fg); + dl.PushClipRect(p, p + new Vector2(chipW - xW, ChipH), true); + dl.AddText(new Vector2(x + iconW, y + (ChipH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), fg, t.Text); + dl.PopClipRect(); + PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.X, new Vector2(x + chipW - xW, y), new Vector2(xW, ChipH), + hotX ? Red : Faded(Mute)); + x += chipW + 4; + } + NextLine(start, y - start.Y + ChipH + 4); + + if (toggle >= 0) SenseStore.SetEnabled(toggle, !terms[toggle].Enabled); + if (remove >= 0) + { + ShowMessage($"Stopped watching for \"{terms[remove].Text}\".", Mute); + SenseStore.Remove(remove); + } + } + + // ── Status and header ─────────────────────────────────────────────── + + private void DrawStatus(SenseView view) + { + bool msg = _message.Length > 0 && Environment.TickCount64 < _messageUntilMs; + Label(msg ? _message : view.Status.Length > 0 ? view.Status : "Scanning...", msg ? _messageColor : Mute); + } + + private static void DrawColumnHeader(float w, bool showLoc) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float ty = p.Y + 1; + float nameW = NameWidth(w, showLoc); + float x = p.X + ArrowW; + dl.AddText(new Vector2(x, ty), Mute, "Name"); + x += nameW; + dl.AddText(new Vector2(x, ty), Mute, "Kind"); + x += KindW; + dl.AddText(new Vector2(x, ty), Mute, "Dist"); + x += DistW; + dl.AddText(new Vector2(x, ty), Mute, "Dir"); + x += DirW; + if (showLoc) dl.AddText(new Vector2(x, ty), Mute, "Location"); + ImGuiNET.ImGui.Dummy(new Vector2(w, ImGuiNET.ImGui.GetFontSize() + 2)); + Separator(w); + } + + private static float NameWidth(float w, bool showLoc) => + Math.Max(40, w - ArrowW - KindW - DistW - DirW - (showLoc ? LocW : 0)); + + // ── Rows ──────────────────────────────────────────────────────────── + + private void DrawRows(SenseView view, bool showLoc) + { + float bw = ImGuiNET.ImGui.GetContentRegionAvail().X; + SenseRow[] rows = view.Rows; + _flashing = false; + if (rows.Length == 0) + { + Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(6, 6); + ImGuiNET.ImGui.GetWindowDrawList().AddText(at, Faded(Mute), + SenseStore.AnyEnabled ? "Nothing matching is in the client's range right now." : "Switch a term on to start watching."); + return; + } + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + long now = Environment.TickCount64; + uint selected = ClientHelperHooks.GetSelectedItemId(); + float heading = PlayerHeading(out bool haveHeading); + float nameW = NameWidth(bw, showLoc); + float fontH = ImGuiNET.ImGui.GetFontSize(); + + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + float scroll = ImGuiNET.ImGui.GetScrollY(); + float visible = ImGuiNET.ImGui.GetWindowHeight(); + int first = Math.Max(0, (int)(scroll / RowH) - 1); + int last = Math.Min(rows.Length, (int)((scroll + visible) / RowH) + 2); + int clicked = -1, hovered = -1; + + for (int i = first; i < last; i++) + { + SenseRow r = rows[i]; + var p = new Vector2(start.X, start.Y + i * RowH); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.PushID(i); + if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(bw, RowH))) clicked = i; + bool hot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + if (hot) hovered = i; + + bool isSel = r.Id == selected; + uint bg = isSel ? Selected : hot ? Lighten(PanelBg) : (i & 1) == 1 ? RowAlt : 0; + if (bg != 0) dl.AddRectFilled(p, p + new Vector2(bw, RowH), bg); + if (r.FirstSeenMs != 0) + { + long age = now - r.FirstSeenMs; + if (age >= 0 && age < FlashMs) + { + _flashing = true; + float pulse = 0.5f + 0.5f * MathF.Cos(age * 0.0126f); + float a = (1f - age / (float)FlashMs) * (0.2f + 0.35f * pulse); + dl.AddRectFilled(p, p + new Vector2(bw, RowH), WithAlpha(Amber, a)); + } + } + if (isSel) dl.AddRect(p, p + new Vector2(bw, RowH), Teal); + + Vector2 mid = p + new Vector2(ArrowW * 0.5f, RowH * 0.5f); + if (r.Measured && haveHeading && !float.IsNaN(r.Bearing)) + DrawArrow(dl, mid, r.Bearing - heading, KindColor(r.Kind)); + else if (r.Measured) + dl.AddCircleFilled(mid, 2.5f, KindColor(r.Kind)); + else + dl.AddCircle(mid, 3.5f, Faded(Mute), 12, 1.2f); + + float ty = p.Y + (RowH - fontH) * 0.5f; + uint nameCol = r.Measured ? Text : Mute; + float x = p.X + ArrowW; + Cell(dl, r.Name, x, ty, nameW - 4, nameCol); + x += nameW; + Cell(dl, SenseSource.KindName(r.Kind), x, ty, KindW - 4, KindColor(r.Kind)); + x += KindW; + Cell(dl, r.DistanceText, x, ty, DistW - 4, r.Measured ? Text : Faded(Mute)); + x += DistW; + Cell(dl, r.CompassText, x, ty, DirW - 4, Mute); + x += DirW; + if (showLoc) Cell(dl, r.LocationText, x, ty, bw - (x - p.X) - 4, Mute); + } + + ImGuiNET.ImGui.SetCursorScreenPos(start); + ImGuiNET.ImGui.Dummy(new Vector2(bw, rows.Length * RowH)); + + if (clicked >= 0) + AcMainThreadQueue.EnqueueOverlaySelect(rows[clicked].Id); + if (hovered >= 0) + { + ImGuiNET.ImGui.BeginTooltip(); + ImGuiNET.ImGui.TextUnformatted(rows[hovered].Tooltip); + ImGuiNET.ImGui.EndTooltip(); + } + } + + private static void Cell(ImDrawListPtr dl, string text, float x, float y, float width, uint color) + { + if (text.Length == 0 || width <= 0) return; + dl.PushClipRect(new Vector2(x, y - 2), new Vector2(x + width, y + 40), true); + dl.AddText(new Vector2(x, y), color, text); + dl.PopClipRect(); + } + + /// <summary> + /// An arrow pointing <paramref name="degrees"/> clockwise from straight up + /// (up = the way you face). + /// </summary> + private static void DrawArrow(ImDrawListPtr dl, Vector2 c, float degrees, uint color) + { + float rad = degrees * (MathF.PI / 180f); + float s = MathF.Sin(rad), co = MathF.Cos(rad); + Vector2 tip = Rot(c, 0, -6.5f, s, co), left = Rot(c, -4.5f, 5f, s, co), + notch = Rot(c, 0, 2.5f, s, co), right = Rot(c, 4.5f, 5f, s, co); + dl.AddTriangleFilled(tip, left, notch, color); + dl.AddTriangleFilled(tip, notch, right, color); + } + + private static Vector2 Rot(Vector2 c, float x, float y, float s, float co) => + new(c.X + x * co - y * s, c.Y + x * s + y * co); + + /// <summary>Your heading this frame (compass degrees) from the pose snapshot; no AC call.</summary> + private static float PlayerHeading(out bool ok) + { + ok = PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out _, out _, out _, out _, out float qw, out float qz, + out bool headingValid, out float heading); + if (!ok) return 0; + if (headingValid) return heading; + // AC's get_heading not bound yet: the yaw quaternion (ClientObjectHooks' formula). + double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + return (float)((-yaw % 360.0 + 720.0) % 360.0); + } + + private static uint KindColor(SenseKind kind) => kind switch + { + SenseKind.Monster => Red, + SenseKind.Npc => Amber, + SenseKind.Player => Green, + SenseKind.Portal => Purple, + SenseKind.Corpse => Mute, + _ => Teal, + }; + + private static uint WithAlpha(uint abgr, float a) => + (abgr & 0x00FFFFFF) | ((uint)Math.Clamp((int)(a * 255f), 0, 255) << 24); + + // ── Settings (gear) ───────────────────────────────────────────────── + + private void DrawSettingsPopup() + { + if (_openSettings) + { + _openSettings = false; + ImGuiNET.ImGui.OpenPopup("##sense_settings"); + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8)); + bool open = ImGuiNET.ImGui.BeginPopup("##sense_settings"); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(5); + if (!open) return; + + Label("When a new match appears:", Mute); + bool chat = SenseStore.AlertChat, beep = SenseStore.AlertBeep; + if (ImGuiNET.ImGui.Checkbox("Chat line", ref chat)) + SenseStore.SetAlerts(chat, beep); + ImGuiNET.ImGui.SetItemTooltip("A line in chat such as: Sense: Dragon's Isle Drake 140 yd NE\n" + + "(at most three at once; the same object again only after two minutes)."); + if (ImGuiNET.ImGui.Checkbox("System beep", ref beep)) + SenseStore.SetAlerts(chat, beep); + ImGuiNET.ImGui.SetItemTooltip("Windows' default sound, at most every 3 seconds."); + Label("Alerts keep working with the panel closed.", Faded(Mute)); + Label("Saved in %LocalAppData%\\RynthCore\\sense.txt", Faded(Mute)); + ImGuiNET.ImGui.EndPopup(); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs new file mode 100644 index 0000000..e37aac2 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs @@ -0,0 +1,608 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/SettingsFace.cs +// ImGui face of RynthAi's Advanced Settings (docs/IMGUI_PARITY_PLAN.md §2.4). +// +// Draws SettingsSchema (UI/Data/SettingsData.cs), the same list the Avalonia +// face builds from, with that face's look: 150 px tab sidebar, "Advanced +// Settings > Tab" header, square toggle dots, - [value] + steppers (typed +// values commit on Enter or when the field loses focus, then clamp; bad +// input reverts), combo pickers, amber section headers, tooltips. +// +// Edits a private copy of the hub's settings and saves the whole copy +// (SettingsCommands.Save) on each change; a newer fetch replaces the copy +// only while no field here is being typed in. Rows that show or hide other +// rows need nothing special: visibility is re-evaluated every frame. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using System.Text; +using ImGuiNET; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class SettingsFace : IImGuiPanel +{ + public const string Title = "Settings"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(400, 500), new Vector2(320, 240), EdgeToEdge: true), + () => new SettingsFace()); + + // ── Palette (SettingsPanel's, ARGB) ───────────────────────────────── + private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Mute = C(0xFFB8C8D8), + TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), PanelBg = C(0xFF141F29), BtnFill = C(0xFF16283A), + BtnBord = C(0xFF34587A), ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455), TabActive = C(0xFF1A2E42); + private static uint C(uint argb) => RynthTheme.Argb(argb); + + private static readonly string[] Headers = BuildHeaders(); + + private RynthAiSettings _data = new(); + private long _seenVersion = -1; + private int _tab; + private bool _editing; + + // Typed-value buffers, one per numeric row (UTF-8, NUL-terminated). + private sealed class NumberEdit + { + public readonly byte[] Buffer = new byte[24]; + public double Shown = double.NaN; + public bool Active; // the box had keyboard focus last frame + } + private readonly Dictionary<SettingRow, NumberEdit> _edits = new(); + + /// <summary>Extra sidebar tab after the schema tabs; drawn from UiSources.Charms, not settings rows.</summary> + private const string CharmsTabName = "Charms Tracking"; + private static int CharmsTab => SettingsSchema.Tabs.Length; + private const string CharmsHeader = "Advanced Settings > " + CharmsTabName; + + public void OnShown() + { + UiSources.Settings.Subscribe(); + UiSources.Settings.RequestRefresh(); + UiSources.Charms.Subscribe(); + UiSources.Charms.RequestRefresh(); + } + + public void OnHidden() + { + UiSources.Settings.Unsubscribe(); + UiSources.Charms.Unsubscribe(); + } + + public void Draw() + { + // Take a newer fetch unless a value is being typed in. + var snap = UiSources.Settings.Current; + if (snap != null && snap.Version != _seenVersion && !_editing) + { + _seenVersion = snap.Version; + _data = snap.Value.Clone(); + } + _editing = false; + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail(); + dl.AddRectFilled(origin, origin + size, ShellBg, 4); + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + Sidebar(size.Y); + ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(150, 0)); + Content(new Vector2(size.X - 150, size.Y)); + ImGuiNET.ImGui.PopFont(); + + dl.AddRect(origin, origin + size, BtnBord, 4); + } + + // ── Sidebar: one button per tab ──────────────────────────────────────── + + private void Sidebar(float height) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + ImGuiNET.ImGui.BeginChild("##settings_tabs", new Vector2(150, height), ImGuiChildFlags.AlwaysUseWindowPadding); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X; + SettingsTab[] tabs = SettingsSchema.Tabs; + for (int i = 0; i <= tabs.Length; i++) + { + string tabName = i < tabs.Length ? tabs[i].Name : CharmsTabName; + ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImGuiNET.ImGui.PushID(i); + if (ImGuiNET.ImGui.InvisibleButton("##tab", new Vector2(w, 26))) _tab = i; + bool hot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + bool sel = i == _tab; + dl.AddRectFilled(p, p + new Vector2(w, 26), sel ? TabActive : hot ? Lighten(BtnFill) : BtnFill); + dl.AddRect(p, p + new Vector2(w, 26), BtnBord); + float ty = p.Y + (26 - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.AddText(new Vector2(p.X + 8, ty), sel ? Teal : Mute, TabLabel(tabName)); + } + ImGuiNET.ImGui.EndChild(); + } + + // ── Content: header + the tab's rows ─────────────────────────────────── + + private void Content(Vector2 size) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 6)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 0)); + ImGuiNET.ImGui.BeginChild("##settings_content", size, ImGuiChildFlags.AlwaysUseWindowPadding); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X; + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + if (_tab > CharmsTab) _tab = 0; + bool charms = _tab == CharmsTab; + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), charms ? CharmsHeader : Headers[_tab]); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + Vector2 lp = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddLine(lp, lp + new Vector2(w, 0), BtnBord); + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + + if (charms) + { + CharmsTabContent(w); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.EndChild(); + return; + } + + SettingRow[] rows = SettingsSchema.Tabs[_tab].Rows; + for (int i = 0; i < rows.Length; i++) + { + SettingRow row = rows[i]; + if (!row.IsVisible(_data)) continue; + ImGuiNET.ImGui.PushID(i); + DrawRow(row, w); + ImGuiNET.ImGui.PopID(); + } + + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.EndChild(); + } + + private void DrawRow(SettingRow row, float w) + { + switch (row.Kind) + { + case SettingKind.Bool: BoolRow(row, w); break; + case SettingKind.Int: + case SettingKind.Float: + case SettingKind.Double: NumberRow(row, w); break; + case SettingKind.Combo: ComboRow(row, w); break; + case SettingKind.Section: Section(row.Label, w); break; + case SettingKind.Spacer: ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); break; + case SettingKind.Note: Note(row.Label, w); break; + case SettingKind.CraftingStatus: CraftingStatus(row); break; + case SettingKind.Button: ButtonRow(row, w); break; + } + } + + // Label | [caption]; Click posts its own work (never runs plugin code on AC's thread). + private static void ButtonRow(SettingRow row, float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextUnformatted(row.Label); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f)); + if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label)) + row.Click?.Invoke(); + Tooltip(row); + } + + private void Changed(SettingRow row, double value) + { + row.Set!(_data, value); + SettingsCommands.Save(_data.Clone()); + } + + // Square dot + label; the whole row toggles. + private void BoolRow(SettingRow row, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool on = row.Get!(_data) != 0; + float labelW = ImGuiNET.ImGui.CalcTextSize(row.Label).X; + if (ImGuiNET.ImGui.InvisibleButton("##b", new Vector2(Math.Min(w, 18 + labelW), 16))) + Changed(row, on ? 0 : 1); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + Tooltip(row); + dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2); + dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + // Label | [-] [value] [+]; the value commits on Enter or focus loss. + private void NumberRow(SettingRow row, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + bool isInt = row.Kind == SettingKind.Int; + float boxW = isInt ? 52 : 64, boxCol = isInt ? 56 : 68; + double value = Math.Clamp(row.Get!(_data), row.Min, row.Max); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float right = p.X + w; + dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label); + ImGuiNET.ImGui.InvisibleButton("##label", new Vector2(Math.Max(1, w - 40 - boxCol), 22)); + Tooltip(row); + + float plusX = right - 20, boxX = plusX - boxCol + (boxCol - boxW) * 0.5f, minusX = right - 20 - boxCol - 20; + if (StepButton("##minus", new Vector2(minusX + 1, p.Y + 1), PhosphorIcons.Minus)) + Changed(row, Math.Clamp(value - row.Step, row.Min, row.Max)); + + // Typed value (amber on the panel colour). + NumberEdit edit = EditFor(row); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(boxX, p.Y + 1)); + ImGuiNET.ImGui.SetNextItemWidth(boxW); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f); + if (!edit.Active && edit.Shown != value) + WriteValue(edit, value, isInt); + ImGuiNET.ImGui.InputText("##v", edit.Buffer, (uint)edit.Buffer.Length, + ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.AutoSelectAll); + bool active = ImGuiNET.ImGui.IsItemActive(); + edit.Active = active; + _editing |= active; + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + if (TryParse(edit.Buffer, out double typed)) + { + double clamped = Math.Clamp(isInt ? Math.Round(typed) : typed, row.Min, row.Max); + Changed(row, clamped); + WriteValue(edit, clamped, isInt); + } + else WriteValue(edit, value, isInt); // bad input reverts + } + ImGuiNET.ImGui.PopStyleVar(3); + ImGuiNET.ImGui.PopStyleColor(3); + + if (StepButton("##plus", new Vector2(plusX + 1, p.Y + 1), PhosphorIcons.Plus)) + Changed(row, Math.Clamp(value + row.Step, row.Min, row.Max)); + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + private NumberEdit EditFor(SettingRow row) + { + if (!_edits.TryGetValue(row, out NumberEdit? e)) + _edits[row] = e = new NumberEdit(); + return e; + } + + private static void WriteValue(NumberEdit edit, double value, bool isInt) + { + string text = isInt ? ((long)Math.Round(value)).ToString(CultureInfo.InvariantCulture) + : value.ToString("G4", CultureInfo.InvariantCulture); + int n = Encoding.UTF8.GetBytes(text, 0, text.Length, edit.Buffer, 0); + edit.Buffer[Math.Min(n, edit.Buffer.Length - 1)] = 0; + edit.Shown = value; + } + + private static bool TryParse(byte[] buffer, out double value) + { + int len = Array.IndexOf(buffer, (byte)0); + if (len < 0) len = buffer.Length; + return double.TryParse(Encoding.UTF8.GetString(buffer, 0, len), NumberStyles.Float, CultureInfo.InvariantCulture, out value); + } + + // Label | [current item]; click opens a 220 px list with the current item highlighted. + private void ComboRow(SettingRow row, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + string[] items = row.Items!; + int current = Math.Clamp((int)row.Get!(_data), 0, items.Length - 1); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label); + + ImFontPtr f10 = ImGuiFonts.Get(UiFont.Ui10); + const float btnW = 160; + var bp = new Vector2(p.X + w - btnW, p.Y + 1); + ImGuiNET.ImGui.SetCursorScreenPos(bp); + if (ImGuiNET.ImGui.InvisibleButton("##combo", new Vector2(btnW, 20))) + { + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Max(bp.X + btnW - 220, 0), bp.Y + 20)); + ImGuiNET.ImGui.OpenPopup("##combo_list"); + } + bool hot = ImGuiNET.ImGui.IsItemHovered(); + Tooltip(row); + dl.AddRectFilled(bp, bp + new Vector2(btnW, 20), hot ? Lighten(BtnFill) : BtnFill); + dl.AddRect(bp, bp + new Vector2(btnW, 20), BtnBord); + dl.PushClipRect(bp, bp + new Vector2(btnW - 16, 20), true); + dl.AddText(f10, f10.FontSize, bp + new Vector2(4, (20 - f10.FontSize) * 0.5f), TextDim, items[current]); + dl.PopClipRect(); + PhosphorIcons.DrawCentered(dl, f10, PhosphorIcons.CaretDown, bp + new Vector2(btnW - 16, 0), new Vector2(14, 20), Mute); + + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(220, items.Length * 21 + 4)); + bool open = ImGuiNET.ImGui.BeginPopup("##combo_list"); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + if (open) + { + var pdl = ImGuiNET.ImGui.GetWindowDrawList(); + float iw = ImGuiNET.ImGui.GetContentRegionAvail().X; + for (int i = 0; i < items.Length; i++) + { + ImGuiNET.ImGui.PushID(i); + Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos(); + bool picked = ImGuiNET.ImGui.InvisibleButton("##item", new Vector2(iw, 20)); + bool ih = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + bool sel = i == current; + pdl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? TabActive : ih ? Lighten(BtnFill) : BtnFill); + pdl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord); + pdl.AddText(f10, f10.FontSize, ip + new Vector2(6, (20 - f10.FontSize) * 0.5f), sel ? Teal : TextDim, items[i]); + ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); + if (picked) + { + Changed(row, i); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + } + ImGuiNET.ImGui.EndPopup(); + } + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + private static void Section(string text, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + float h = bold.FontSize + 4; + dl.AddRectFilled(p, p + new Vector2(w, h), TabActive); + dl.AddText(bold, bold.FontSize, p + new Vector2(4, 2), Amber, text); + ImGuiNET.ImGui.Dummy(new Vector2(w, h)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + private static void Note(string text, float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + bool small = !text.StartsWith('('); + if (small) ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(text); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + if (small) ImGuiNET.ImGui.PopFont(); + } + + private void CraftingStatus(SettingRow row) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), row.Label); + ImGuiNET.ImGui.SameLine(0, 6); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(_data.MissileCraftingActive ? 0xFFE8B333 : 0xFFB8C8D8), _data.MissileCraftingState); + ImGuiNET.ImGui.PopFont(); + if (!string.IsNullOrEmpty(_data.MissileCraftingStatus)) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); + ImGuiNET.ImGui.TextWrapped(_data.MissileCraftingStatus); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopFont(); + } + } + + // ── Charms Tracking tab ─────────────────────────────────────────────── + + private static readonly uint CharmOn = C(0xFF33FF33), CharmDisabled = C(0xFFFF5555); + + /// <summary>Summary line, one table row per ACECustom registry charm, then how each column is known.</summary> + private static void CharmsTabContent(float w) + { + var snap = UiSources.Charms.Current; + if (snap == null) + { + Note("Waiting for RynthAi...", w); + return; + } + CharmsInfo info = snap.Value; + if (!info.Available) + { + Note("Charm tracking is for ILT (Infinite Leaftide / ACECustom) worlds." + + (info.World.Length > 0 ? " Current world: " + info.World + "." : ""), w); + Note("Use /ra hub force on to treat this world as ILT.", w); + return; + } + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), + $"{info.AcquiredCount} of {info.Total} acquired | {info.ActiveCount} active"); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.CellPadding, new Vector2(4, 3)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableRowBg, PanelBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableRowBgAlt, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableHeaderBg, TabActive); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableBorderLight, BtnBord); + const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit; + if (ImGuiNET.ImGui.BeginTable("##charms", 5, flags, new Vector2(w, 0))) + { + ImGuiNET.ImGui.TableSetupColumn("Charm", ImGuiTableColumnFlags.WidthStretch); + ImGuiNET.ImGui.TableSetupColumn("Acquired", ImGuiTableColumnFlags.WidthFixed, 70); + ImGuiNET.ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.WidthFixed, 44); + ImGuiNET.ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 32); + ImGuiNET.ImGui.TableSetupColumn("Server", ImGuiTableColumnFlags.WidthFixed, 56); + ImGuiNET.ImGui.TableHeadersRow(); + + CharmRow[] rows = info.Charms; + for (int i = 0; i < rows.Length; i++) + { + CharmRow r = rows[i]; + ImGuiNET.ImGui.PushID(i); + ImGuiNET.ImGui.TableNextRow(); + + ImGuiNET.ImGui.TableNextColumn(); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), r.Name); + if (r.Effect.Length > 0) ImGuiNET.ImGui.SetItemTooltip(r.Effect); + + ImGuiNET.ImGui.TableNextColumn(); + switch (r.Acquired) + { + case "carried": + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), r.Count > 1 ? $"Carried x{r.Count}" : "Carried"); + ImGuiNET.ImGui.SetItemTooltip("In your pack or equipped."); + break; + case "seen": + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "Stored"); + ImGuiNET.ImGui.SetItemTooltip("Owned but not carried" + + (r.LastSeen.Length > 0 ? " (last carried " + r.LastSeen + ")" : "") + + ". The client only sees items you carry."); + break; + default: + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "Not yet"); + break; + } + + ImGuiNET.ImGui.TableNextColumn(); + if (r.Acquired != "carried") + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "-"); + else if (r.Active == "on") + ColoredText(CharmOn, "ON"); + else if (r.Active == "off") + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "OFF"); + else + { + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "?"); + ImGuiNET.ImGui.SetItemTooltip("Waiting for the charm's appraisal (requested automatically)."); + } + + ImGuiNET.ImGui.TableNextColumn(); + string tier = r.Tier <= 0 ? "-" : r.MaxTier > 0 ? $"{r.Tier}/{r.MaxTier}" : r.Tier.ToString(CultureInfo.InvariantCulture); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), tier); + + ImGuiNET.ImGui.TableNextColumn(); + if (r.Server == "off") + { + ColoredText(CharmDisabled, "Disabled"); + ImGuiNET.ImGui.SetItemTooltip("The server refused or reported this charm as disabled."); + } + else if (r.Server == "on") + ColoredText(CharmOn, "Enabled"); + else + { + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "-"); + ImGuiNET.ImGui.SetItemTooltip("Not reported. The server only tells players when a charm is refused."); + } + + ImGuiNET.ImGui.PopID(); + } + ImGuiNET.ImGui.EndTable(); + } + ImGuiNET.ImGui.PopStyleColor(4); + ImGuiNET.ImGui.PopStyleVar(); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + Note("Double-click a carried charm in your pack to toggle it. Status comes from the charm's appraisal " + + "(Status: ON/OFF) or your character's ability flag. Charms not carried are inactive.", w); + Note("Stored = carried by this character before; RynthAi remembers it per character.", w); + } + + /// <summary>TextUnformatted in a packed ImGui colour.</summary> + private static void ColoredText(uint abgr, string text) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, abgr); + ImGuiNET.ImGui.TextUnformatted(text); + ImGuiNET.ImGui.PopStyleColor(); + } + + private static bool StepButton(string id, Vector2 pos, string glyph) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, new Vector2(18, 20)); + uint bg = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill; + dl.AddRectFilled(pos, pos + new Vector2(18, 20), bg); + dl.AddRect(pos, pos + new Vector2(18, 20), BtnBord); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, new Vector2(18, 20), TextDim); + return clicked; + } + + // Tab icons by tab name (SettingsSchema); a tab not listed shows its name alone. + private static readonly System.Collections.Generic.Dictionary<string, string> TabIcons = new() + { + ["Display"] = PhosphorIcons.Monitor, + ["UI"] = PhosphorIcons.AppWindow, + ["Misc"] = PhosphorIcons.DotsThree, + ["Recharge"] = PhosphorIcons.BatteryCharging, + ["Melee Combat"] = PhosphorIcons.Sword, + ["Spell Combat"] = PhosphorIcons.MagicWand, + ["Ranges"] = PhosphorIcons.Ruler, + ["Navigation"] = PhosphorIcons.SneakerMove, + ["Buffing"] = PhosphorIcons.Sparkle, + ["Crafting"] = PhosphorIcons.Hammer, + ["Looting"] = PhosphorIcons.Bag, + ["Vendoring"] = PhosphorIcons.Storefront, + [CharmsTabName] = PhosphorIcons.Gift, + }; + private static readonly System.Collections.Generic.Dictionary<string, string> TabLabels = new(); + + /// <summary>"icon Name", built once per tab.</summary> + private static string TabLabel(string name) + { + if (TabLabels.TryGetValue(name, out string? label)) return label; + label = TabIcons.TryGetValue(name, out string? icon) ? icon + " " + name : name; + TabLabels[name] = label; + return label; + } + + private static void Tooltip(SettingRow row) + { + if (row.Tooltip != null) ImGuiNET.ImGui.SetItemTooltip(row.Tooltip); + } + + private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12); + private static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0); + + private static uint Scale(uint abgr, float k, int add) + { + uint a = abgr & 0xFF000000; + uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add); + uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add); + uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add); + return a | (b << 16) | (g << 8) | r; + } + + private static string[] BuildHeaders() + { + var headers = new string[SettingsSchema.Tabs.Length]; + for (int i = 0; i < headers.Length; i++) + headers[i] = "Advanced Settings > " + SettingsSchema.Tabs[i].Name; + return headers; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsData.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsData.cs new file mode 100644 index 0000000..46d7f68 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsData.cs @@ -0,0 +1,226 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/SkillsData.cs +// The Skills panel's static data from client_portal.dat, read once in the +// background (UiBackgroundWriter, never AC's thread): +// +// SkillTable 0x0E000004 id u32, PackedHashTable (u16 count, u16 buckets) of +// u32 skill id + SkillBase: description, name (u16 length + bytes, each +// padded to 4 from the file start), icon u32, trained cost i32, +// specialized cost i32 (total), category u32, chargen use u32, +// min level u32 (1 usable untrained, 2 needs training), formula +// (W, X, Y, Z, attr1, attr2 u32), upper, lower, learn mod f64. +// XpTable 0x0E000018 id u32, counts (attribute, vital, trained, +// specialized i32, level u32), then count+1 u32 each for attributes, +// vitals, trained and specialized skills, count+1 u64 levels, count+1 u32 +// skill credits per level. +// +// Layouts: ACE.DatLoader SkillTable / SkillBase / SkillFormula / XpTable (the +// server raises against the same XpTable). Readers take the published +// immutable tables; any thread. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Threading; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.ScriptWindows; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +/// <summary>One skill from the portal SkillTable.</summary> +internal sealed class SkillDatEntry +{ + public uint Id; + public string Name = ""; + public string Description = ""; + public uint Icon; + public int TrainedCost; + public int SpecializedCost; + public uint Category; // 1 combat, 2 other, 3 magic + public uint MinLevel; // 1 usable untrained, 2 trained or better + public uint Attr1, Attr2, Divisor; + public bool UsableUntrained => MinLevel <= 1; +} + +internal sealed class SkillDatTables +{ + public readonly Dictionary<uint, SkillDatEntry> Skills = new(); + public uint[] AttributeXp = Array.Empty<uint>(); + public uint[] VitalXp = Array.Empty<uint>(); + public uint[] TrainedXp = Array.Empty<uint>(); + public uint[] SpecializedXp = Array.Empty<uint>(); + public ulong[] LevelXp = Array.Empty<ulong>(); +} + +internal static class SkillDat +{ + private const uint SkillTableFileId = 0x0E000004; + private const uint XpTableFileId = 0x0E000018; + private const int MaxFile = 1024 * 1024; + + private static volatile SkillDatTables? _tables; + private static int _queued; + private static volatile string _status = "not loaded"; + + public static SkillDatTables? Tables => _tables; + + /// <summary>"38 skills, 190 attribute ranks" or why not. Any thread.</summary> + public static string Status => _status; + + /// <summary>Queues the one-time read (again after a failure). Cheap once loaded.</summary> + public static void EnsureLoadQueued() + { + if (_tables != null || Interlocked.Exchange(ref _queued, 1) == 1) return; + _status = "loading"; + UiBackgroundWriter.Enqueue("skills dat", Load); + } + + private static void Load() + { + try + { + string? path = AcDatFile.FindPortalDat(); + if (path == null) { Fail("client_portal.dat not found next to acclient.exe"); return; } + using AcDatFile? dat = AcDatFile.Open(path, out string why); + if (dat == null) { Fail($"{Path.GetFileName(path)}: {why}"); return; } + byte[]? skills = dat.Read(SkillTableFileId, MaxFile); + byte[]? xp = dat.Read(XpTableFileId, MaxFile); + if (skills == null || xp == null) { Fail($"{Path.GetFileName(path)}: skill or XP table missing"); return; } + var t = new SkillDatTables(); + if (!ParseSkills(skills, t) || !ParseXp(xp, t)) { Fail($"{Path.GetFileName(path)}: skill or XP table unreadable"); return; } + _tables = t; + _status = string.Format(CultureInfo.InvariantCulture, "{0} skills, {1} attribute and {2} skill ranks from {3}", + t.Skills.Count, t.AttributeXp.Length - 1, t.TrainedXp.Length - 1, Path.GetFileName(path)); + RynthLog.UI($"Skills: {_status}"); + } + catch (Exception ex) + { + Fail($"read failed: {ex.GetType().Name}: {ex.Message}"); + } + } + + private static void Fail(string why) + { + _status = why; + RynthLog.UI($"Skills: {why}"); + Volatile.Write(ref _queued, 0); // the panel's next open tries again + } + + private static bool ParseSkills(byte[] raw, SkillDatTables t) + { + var r = new Reader(raw); + r.U32(); // file id + int count = r.U16(); + r.U16(); // buckets + for (int i = 0; i < count && r.Ok; i++) + { + var s = new SkillDatEntry { Id = r.U32() }; + s.Description = r.PString(); + s.Name = r.PString(); + s.Icon = r.U32(); + s.TrainedCost = (int)r.U32(); + s.SpecializedCost = (int)r.U32(); + s.Category = r.U32(); + r.U32(); // chargen use + s.MinLevel = r.U32(); + r.U32(); r.U32(); r.U32(); // formula W, X, Y + s.Divisor = r.U32(); // Z + s.Attr1 = r.U32(); + s.Attr2 = r.U32(); + r.Skip(24); // upper, lower bound, learn mod + if (!r.Ok) break; + if (s.Name.Length > 0) t.Skills[s.Id] = s; + } + return r.Ok && t.Skills.Count > 0; + } + + private static bool ParseXp(byte[] raw, SkillDatTables t) + { + var r = new Reader(raw); + r.U32(); // file id + int attrs = (int)r.U32(), vitals = (int)r.U32(), trained = (int)r.U32(), spec = (int)r.U32(); + int levels = (int)r.U32(); + if (!r.Ok || attrs < 0 || vitals < 0 || trained < 0 || spec < 0 || levels < 0 + || attrs > 10000 || vitals > 10000 || trained > 10000 || spec > 10000 || levels > 10000) + return false; + t.AttributeXp = r.U32s(attrs + 1); + t.VitalXp = r.U32s(vitals + 1); + t.TrainedXp = r.U32s(trained + 1); + t.SpecializedXp = r.U32s(spec + 1); + var lv = new ulong[levels + 1]; + for (int i = 0; i <= levels; i++) lv[i] = r.U64(); + t.LevelXp = lv; + return r.Ok; + } + + // ── XP arithmetic (the server's: Player.SpendAttributeXp / SpendSkillXp) ── + + /// <summary>True when <paramref name="ranks"/> is the table's top rank (nothing left to buy).</summary> + public static bool IsMax(uint[] table, uint ranks) => table.Length == 0 || ranks + 1 >= (uint)table.Length; + + /// <summary>XP to buy <paramref name="n"/> more ranks from <paramref name="ranks"/> with <paramref name="spent"/> already spent; -1 past the top.</summary> + public static long CostOf(uint[] table, uint ranks, uint spent, int n) + { + if (n < 1) return 0; + long target = (long)ranks + n; + if (target >= table.Length) return -1; + return Math.Max(0L, (long)table[target] - spent); + } + + /// <summary>How many ranks in a row <paramref name="available"/> XP buys (0 when not even one), up to the top rank.</summary> + public static int Affordable(uint[] table, uint ranks, uint spent, long available) + { + int lo = 0, hi = Math.Max(0, table.Length - 1 - (int)Math.Min(ranks, (uint)int.MaxValue)); + while (lo < hi) + { + int mid = (lo + hi + 1) / 2; + long c = CostOf(table, ranks, spent, mid); + if (c >= 0 && c <= available) lo = mid; else hi = mid - 1; + } + return lo; + } + + /// <summary>Bounds-checked little-endian reader; Ok turns false on overrun.</summary> + private ref struct Reader + { + private readonly ReadOnlySpan<byte> _b; + private int _p; + public bool Ok; + + public Reader(byte[] b) { _b = b; _p = 0; Ok = true; } + + private bool Has(int n) + { + if (Ok && n >= 0 && _p + n <= _b.Length) return true; + Ok = false; + return false; + } + + public uint U32() { if (!Has(4)) return 0; uint v = BitConverter.ToUInt32(_b.Slice(_p, 4)); _p += 4; return v; } + public ushort U16() { if (!Has(2)) return 0; ushort v = BitConverter.ToUInt16(_b.Slice(_p, 2)); _p += 2; return v; } + public ulong U64() { if (!Has(8)) return 0; ulong v = BitConverter.ToUInt64(_b.Slice(_p, 8)); _p += 8; return v; } + public void Skip(int n) { if (Has(n)) _p += n; } + + public uint[] U32s(int n) + { + if (!Has(n * 4)) return Array.Empty<uint>(); + var a = new uint[n]; + for (int i = 0; i < n; i++) a[i] = U32(); + return a; + } + + /// <summary>u16 length + Latin-1 bytes, then aligned to 4 from the file start (ACE AlignBoundary).</summary> + public string PString() + { + int n = U16(); + if (!Has(n)) return ""; + string s = Encoding.Latin1.GetString(_b.Slice(_p, n)); + _p += n; + _p = (_p + 3) & ~3; + return s; + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs new file mode 100644 index 0000000..774dd03 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs @@ -0,0 +1,326 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/SkillsFace.Progression.cs +// The Skills panel's Progression tab, shown on ILT-like worlds only: +// - XP planner: exact XP for the next N raises of every attribute and vital, +// from the client's XP tables (raising stays on the Attributes & Vitals tab). +// - Augmentations / Enlightenment: RynthAi's ILT Hub planners. RynthAi owns the +// math and the saved inputs (UiSources.Progression snapshot); edits and +// actions go back as "prog ..." remote commands. /enl and arming +// auto-enlighten ask here first; the server still shows its own dialog. +// ============================================================================ + +using System; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class SkillsFace +{ + private const string ProgConfirmId = "##skills_prog_confirm"; + + private int _planLevels = 10; // XP planner: raises to price per row + private bool _progSubscribed; + + // The confirm the Progression tab asked for; the command is sent only on its Yes button. + private string _progConfirmTitle = "", _progConfirmText = "", _progConfirmYes = "", _progConfirmCommand = ""; + private bool _progConfirmOpenRequested; + + // Set by ShowProgression (any panel, AC thread); the tab is selected once RynthAi's snapshot + // says it exists (the first poll lands a step after the panel opens). + private static bool _progressionRequested; + + /// <summary>RynthAi reports an ILT-like world (its ILT Hub exists and the server has ILT features).</summary> + private static bool ProgressionTabVisible => UiSources.Progression.Current?.Value.Available == true; + + /// <summary>Opens the Skills panel (if closed) on the Progression tab. AC thread.</summary> + public static void ShowProgression() + { + _progressionRequested = true; + if (!ImGuiPanelHost.IsOpen(Title)) PanelRouter.Toggle(Title); + } + + /// <summary>Draw: applies a pending ShowProgression once the tab exists.</summary> + private void ApplyProgressionRequest() + { + if (!_progressionRequested || !ProgressionTabVisible) return; + _progressionRequested = false; + _tab = 2; + } + + private void ProgressionShown() + { + if (_progSubscribed) return; + _progSubscribed = true; + UiSources.Progression.Subscribe(); + UiSources.Progression.RequestRefresh(); + } + + private void ProgressionHidden() + { + _progressionRequested = false; + if (!_progSubscribed) return; + _progSubscribed = false; + UiSources.Progression.Unsubscribe(); + } + + /// <summary>Sends "prog <value>" to RynthAi; the snapshot re-polls after its next tick applies it.</summary> + private static void SendProg(string value) + { + RynthAiCommands.ApplyRemoteCommand("prog", value); + UiSources.Progression.RequestRefreshAfterPluginTick(); + } + + private void AskProgConfirm(string title, string text, string yes, string command) + { + _progConfirmTitle = title; + _progConfirmText = text; + _progConfirmYes = yes; + _progConfirmCommand = command; + _progConfirmOpenRequested = true; + } + + // ── Body ──────────────────────────────────────────────────────────── + + private void DrawProgression(float w) + { + ProgressionInfo? info = UiSources.Progression.Current?.Value; + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4)); + try + { + DrawXpPlanner(w); + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + if (info == null || !info.Available) + { + Message("Augmentations and Enlightenment need RynthAi's ILT Hub on an ILT world.", w); + return; + } + DrawAugPlanner(info.Aug, w); + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + DrawEnlPlanner(info.Enl, w); + ImGuiNET.ImGui.Dummy(new Vector2(0, 8)); + } + finally + { + ImGuiNET.ImGui.PopStyleVar(); + } + } + + private void DrawXpPlanner(float w) + { + Section("XP planner", w); + if (_snap == null || _dat == null || _attributes.Count == 0) + { + Message("Waiting for your character's data...", w); + return; + } + ImGuiNET.ImGui.Indent(8); + long have = _snap.UnassignedXp; + Label($"Unassigned XP: {have:N0}", have > 0 ? Teal : Mute); + ImGuiNET.ImGui.SetNextItemWidth(160); + ImGuiNET.ImGui.SliderInt("Raises to plan##prog_lv", ref _planLevels, 1, 100); + + if (ImGuiNET.ImGui.BeginTable("##prog_xp", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp, + new Vector2(w - 16, 0))) + { + ImGuiNET.ImGui.TableSetupColumn("Stat"); + ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 50); + ImGuiNET.ImGui.TableSetupColumn("Next raise", ImGuiTableColumnFlags.WidthFixed, 100); + ImGuiNET.ImGui.TableSetupColumn($"Next {_planLevels}", ImGuiTableColumnFlags.WidthFixed, 120); + ImGuiNET.ImGui.TableHeadersRow(); + foreach (Row r in _attributes) PlannerRow(r, have); + foreach (Row r in _vitals) PlannerRow(r, have); + ImGuiNET.ImGui.EndTable(); + } + Label("Exact costs from the client's XP tables. Raise on the Attributes & Vitals tab.", Dim); + ImGuiNET.ImGui.Unindent(8); + } + + private void PlannerRow(Row r, long have) + { + ImGuiNET.ImGui.TableNextRow(); + ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Name); + ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Base.ToString(CultureInfo.InvariantCulture)); + uint[]? table = r.Table; + int left = table == null ? 0 : Math.Max(0, table.Length - 1 - (int)Math.Min(r.Ranks, (uint)int.MaxValue)); + ImGuiNET.ImGui.TableNextColumn(); + if (table == null || left == 0) { Label(table == null ? "-" : "max", Dim); ImGuiNET.ImGui.TableNextColumn(); Label("-", Dim); return; } + long one = SkillDat.CostOf(table, r.Ranks, r.Spent, 1); + Label(one >= 0 ? one.ToString("N0", CultureInfo.InvariantCulture) : "-", one >= 0 && one <= have ? Teal : Dim); + ImGuiNET.ImGui.TableNextColumn(); + int n = Math.Min(_planLevels, left); + long many = SkillDat.CostOf(table, r.Ranks, r.Spent, n); + string text = many >= 0 ? many.ToString("N0", CultureInfo.InvariantCulture) : "-"; + if (n < _planLevels) text += $" ({n} to max)"; + Label(text, many >= 0 && many <= have ? Teal : Dim); + } + + private void DrawAugPlanner(AugPlanner a, float w) + { + Section("Augmentations", w); + ImGuiNET.ImGui.Indent(8); + try + { + if (a.Off) { Label("/aug is not available on this server.", Mute); return; } + if (ImGuiNET.ImGui.SmallButton("Load /aug##prog")) SendProg("augload"); + ImGuiNET.ImGui.SameLine(); + Label(a.Status, Dim); + + string lpc = a.LumPerCoin.ToString(CultureInfo.InvariantCulture); + ImGuiNET.ImGui.SetNextItemWidth(160); + if (ImGuiNET.ImGui.InputTextWithHint("Lum per Enlightened Coin##prog_lpc", "0 = don't price coins", ref lpc, 24u)) + SendProg("lumpercoin " + lpc.Replace(" ", "", StringComparison.Ordinal)); + + if (ImGuiNET.ImGui.BeginTable("##prog_augs", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp, + new Vector2(w - 16, 0))) + { + ImGuiNET.ImGui.TableSetupColumn("Aug"); + ImGuiNET.ImGui.TableSetupColumn("Current", ImGuiTableColumnFlags.WidthFixed, 56); + ImGuiNET.ImGui.TableSetupColumn("Target", ImGuiTableColumnFlags.WidthFixed, 86); + ImGuiNET.ImGui.TableSetupColumn("Luminance", ImGuiTableColumnFlags.WidthFixed, 80); + ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 60); + ImGuiNET.ImGui.TableHeadersRow(); + foreach (AugRow row in a.Rows) + { + ImGuiNET.ImGui.TableNextRow(); + ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Label); + ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Current.ToString(CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.TableNextColumn(); + int tgt = row.Target; + ImGuiNET.ImGui.SetNextItemWidth(80); + if (ImGuiNET.ImGui.InputInt("##prog_tgt_" + row.Key, ref tgt, 0)) + SendProg($"augtarget {row.Key} {Math.Clamp(tgt, 0, Math.Max(row.Cap, 0))}"); + ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Lum); + ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Coins > 0 ? row.Coins.ToString(CultureInfo.InvariantCulture) : "-"); + } + ImGuiNET.ImGui.EndTable(); + } + Label(a.Total, Amber); + if (a.Short.Length > 0) Label(a.Short, Text); + Label(a.Banked, Dim); + } + finally + { + ImGuiNET.ImGui.Unindent(8); + } + } + + private void DrawEnlPlanner(EnlPlanner e, float w) + { + Section("Enlightenment", w); + ImGuiNET.ImGui.Indent(8); + float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24; // window-local x + ImGuiNET.ImGui.PushTextWrapPos(wrap); + try + { + if (e.Off) { Label("/enl is not available on this server.", Mute); return; } + Label(e.Header, Text); + Label(e.Next, Teal); + + int target = e.Target; + ImGuiNET.ImGui.SetNextItemWidth(100); + if (ImGuiNET.ImGui.InputInt("Plan to level##prog_enlt", ref target)) + SendProg("enltarget " + Math.Max(e.Level + 1, target).ToString(CultureInfo.InvariantCulture)); + foreach (string line in e.Plan) ImGuiNET.ImGui.BulletText(line); + + int coinsPerToken = e.CoinsPerToken; + ImGuiNET.ImGui.SetNextItemWidth(100); + if (ImGuiNET.ImGui.InputInt("Coins per token (shop price)##prog_cpt", ref coinsPerToken)) + SendProg("coinspertoken " + Math.Max(0, coinsPerToken).ToString(CultureInfo.InvariantCulture)); + if (e.TokensShort.Length > 0) Label(e.TokensShort, Dim); + + ImGuiNET.ImGui.Separator(); + if (e.Blockers.Length == 0) Label("Client-side checks pass.", Green); + foreach (string b in e.Blockers) Label(b, Amber); + Label(e.ServerChecks, Dim); + + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (Button("##prog_enl", "Enlighten now...", p, new Vector2(150, 24), Text, BtnFill, border: Teal)) + AskProgConfirm("Enlighten", + "Send /enl now?\n\nEnlightening resets your level and wipes unassigned XP.\n" + + "The server will show its own Yes/No dialog - you must click Yes there.", + "Send /enl", "enlighten"); + NextLine(p, 28); + + ImGuiNET.ImGui.Separator(); + bool auto = e.Auto; + if (ImGuiNET.ImGui.Checkbox("Auto-enlighten when ready##prog_auto", ref auto)) + { + if (auto) + AskProgConfirm("Arm auto-enlighten", + "Auto-enlighten will send /enl whenever the checks pass (peace mode, level, materials).\n" + + "You still have to click Yes in the AC dialog each time.\n\nArm it for this session?", + "Arm", "autoenl on"); + else + SendProg("autoenl off"); + } + if (e.Auto && !e.Armed) + { + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.SmallButton("Arm for this session...##prog_arm")) + AskProgConfirm("Arm auto-enlighten", "Arm auto-enlighten for this session?", "Arm", "autoenl arm"); + } + bool spend = e.SpendFirst; + if (ImGuiNET.ImGui.Checkbox("Spend unassigned XP on attributes first##prog_spend", ref spend)) + SendProg("spendfirst " + (spend ? "on" : "off")); + int every = e.CheckEvery; + ImGuiNET.ImGui.SetNextItemWidth(100); + if (ImGuiNET.ImGui.InputInt("Check every (s)##prog_every", ref every)) + SendProg("checkevery " + Math.Max(10, every).ToString(CultureInfo.InvariantCulture)); + Label(e.Armed ? "Armed." : "Disarmed.", e.Armed ? Amber : Dim); + if (e.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(e.Status); + } + finally + { + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.Unindent(8); + } + } + + // ── Confirm ───────────────────────────────────────────────────────── + + /// <summary>The Progression tab's Yes/No popup (outside the body child, like DrawConfirm).</summary> + private void DrawProgressionConfirm() + { + if (_progConfirmOpenRequested) + { + _progConfirmOpenRequested = false; + ImGuiNET.ImGui.OpenPopup(ProgConfirmId); + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8)); + bool open = ImGuiNET.ImGui.BeginPopup(ProgConfirmId); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) return; + try + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + Label(_progConfirmTitle, Amber); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 320); + Label(_progConfirmText, Text); + ImGuiNET.ImGui.PopTextWrapPos(); + + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + if (Button("##prog_yes", _progConfirmYes, p, new Vector2(120, 24), Text, StartBg)) + { + SendProg(_progConfirmCommand); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + if (Button("##prog_no", "Cancel", new Vector2(p.X + 126, p.Y), new Vector2(90, 24), Text, BtnFill)) + ImGuiNET.ImGui.CloseCurrentPopup(); + NextLine(p, 28); + } + finally + { + ImGuiNET.ImGui.EndPopup(); + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs new file mode 100644 index 0000000..beb9412 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs @@ -0,0 +1,1472 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/SkillsFace.cs +// The Skills panel (docs/IMGUI_SKILLS.md): a modern stand-in for the retail +// character and skills windows. +// +// - XP summary: level, unassigned XP, total XP, XP to the next level, skill +// credits, luminance and vitae when they apply. +// - Skills tab: grouped Specialized / Trained / Untrained / Unusable like +// retail (groups fold); each row: dat icon, name, buffed, base, XP for the +// next raise, a raise button; search and sort (name, buffed, base, next +// raise; either direction). A click opens the row: ranks, XP spent, the +// skill's description and its buffs with time left. +// - Attributes & Vitals tab: the same rows for the six attributes and the +// three vital maximums. +// - Raise: "+1" raises one rank at once; the caret beside it drops down +10, +// +100 and Max (each with its XP cost; Max asks first only when it spends +// over half the unassigned XP). PlayerTraining.Raise(defer) queues it for +// AC's main thread outside the ImGui frame; raise buttons stay locked until +// the new values arrive (or 5 s pass). Train (skill credits) always asks first. +// - Aelrynth only (ServerInfo.IsAelrynth): skill mastery from the SkillMastery +// mod's /mastery-data reply (MasteryFeed). A crown badge with the mastery +// points on trained rows that have any; the open row shows points, bonus, +// the next raise's Radiance price against the banked Radiance (the reply's +// balance plus the Bank mod's "Radiance earned" since), and "Raise mastery", +// which always asks first and then sends the mod's "/raise <skill> 1". The +// summary shows the banked Radiance; hovering it explains mastery. On any +// other server none of this is drawn and nothing is sent. +// +// Data: PlayerProgressHooks (main-thread snapshot; Want keeps it coming while +// the panel draws), SkillDat (portal.dat skill and XP tables), PortalSpellTable +// (spell names). Rows and their strings are built only when the snapshot, the +// dat tables, the search or the sort change; the open row's time-left text +// once a second. AC's render thread only; no AC reads, locks or file I/O here. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.ImGuiBackend.Hud; +using RynthCore.Engine.UI.ScriptWindows; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class SkillsFace : IImGuiPanel +{ + public const string Title = "Skills"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(480, 640), new Vector2(380, 320), EdgeToEdge: true, GripInBody: true), + () => new SkillsFace()); + + /// <summary>Numbers change on raises, buffs and XP: 4 Hz idle when popped out.</summary> + public int PopOutIdleHz => 4; + + // ── Palette (FaceKit's, plus the vitals') ──────────────────────────── + private static readonly uint Mana = RynthTheme.Argb(0xFF4DA6FF), Dim = RynthTheme.Argb(0xFF7F8FA0), + ExpandedBg = RynthTheme.Argb(0xFF1A2E42), GroupBg = RynthTheme.Argb(0xFF0F1A24), + MasteryColor = RynthTheme.Argb(0xFFC9A2FF); + + private const float RowH = 24f, IconSize = 20f, ColBuffed = 46f, ColBase = 46f, ColCost = 76f, ColButton = 52f, + CaretW = 16f, MultiW = 190f; + + private enum RowKind { Skill, Attribute, Vital } + private enum SortKey { Name, Buffed, Base, Cost } + + private static readonly string[] GroupNames = { "Specialized", "Trained", "Untrained", "Unusable" }; + private static readonly string[] SortNames = { "Name", "Buffed", "Base", "Next raise" }; + private static readonly string[] AttributeNames = { "", "Strength", "Endurance", "Quickness", "Coordination", "Focus", "Self" }; + private static readonly string[] AttributeGlyphs = + { + "", PhosphorIcons.Barbell, PhosphorIcons.Heartbeat, PhosphorIcons.SneakerMove, + PhosphorIcons.Crosshair, PhosphorIcons.Brain, PhosphorIcons.Sparkle, + }; + private static readonly string[] VitalNames = { "", "Health", "Stamina", "Mana" }; + private static readonly string[] VitalGlyphs = { "", PhosphorIcons.Heart, PhosphorIcons.Lightning, PhosphorIcons.Drop }; + private static readonly uint[] VitalColors = { 0, Red, Amber, Mana }; + + private sealed class BuffLine + { + public uint Spell; + public string Name = ""; + public string Amount = ""; + public bool Good; + public double Expiry; + public uint Category; + public float Strength; // |value| (additive) or |value - 1| (multiplicative) + public int Surpassed; // weaker ones in the same spell category, not shown + public string Time = ""; + } + + private sealed class Row + { + public RowKind Kind; + public uint Stype; // skill id, attribute 1..6, vital 1..3 + public int Key; // Kind << 8 | Stype: ImGui id, expanded / confirm lookups + public int Group; // skills: 0 specialized .. 3 unusable + public string Name = ""; + public string Description = ""; + public uint Icon; // skills: dat icon (0x06 texture) + public string Glyph = ""; // attributes / vitals: Phosphor icon + public uint GlyphColor; + public int Buffed, Base; + public string BuffedText = "", BaseText = "", CostText = ""; + public float BuffedW, BaseW, CostW; + public uint BuffedColor, CostColor; + public uint[]? Table; // XP table for raising; null: can't be raised with XP + public uint Ranks, Spent; + public bool Max; + public long NextCost = -1; // XP for one raise; -1 max or not raisable + public int TrainCost; // untrained skills: credits to train (portal TrainedCost); 0 = can't + public int SpecializeCost; // trained skills: more credits to specialize (SpecializedCost - TrainedCost) + public string Detail = ""; + public string Detail2 = ""; // a second, wrapped line (specializing) + public readonly List<BuffLine> Buffs = new(); + public int BuffsUp, BuffsDown; + // Aelrynth skill mastery (trained skills, from the last /mastery-data reply). + public MasterySkill? Mastery; + public string MasteryText = ""; // the row's badge ("3.7"); empty = no badge + public float MasteryW; + public string MasteryLine = ""; // expanded row: points and what they add + public string MasteryLine2 = ""; // expanded row: the next raise's price, or why not + public string MasteryHover = ""; // the badge's tooltip + } + + // ── State ─────────────────────────────────────────────────────────── + private int _tab; // 0 skills, 1 attributes & vitals, 2 progression (ILT worlds) + private SortKey _sort = SortKey.Name; + private bool _descending; + private readonly bool[] _collapsed = { false, false, false, true }; + private readonly byte[] _search = new byte[64]; + private string _filter = ""; + private int _expandedKey = -1; + private long _detailSecond = -1; + + private PlayerProgress? _snap; + private SkillDatTables? _dat; + private bool _spellsReady; + private bool _dirty = true, _orderDirty = true; + private float _widthFont = -1; + + private readonly List<Row> _skills = new(); + private readonly List<Row> _attributes = new(); + private readonly List<Row> _vitals = new(); + private readonly List<Row>[] _groups = { new(), new(), new(), new() }; + private readonly Dictionary<int, Row> _byKey = new(); + + private string[] _summary = Array.Empty<string>(); + private uint[] _summaryColors = Array.Empty<uint>(); + + private readonly Picker _picker = new("##skills_sort"); + + // Raise confirm and the lock after a raise. + private int _confirmKey = -1; + private int _confirmCount = 1; + private bool _confirmTrain; // the confirm trains with credits instead of raising + // The caret's +10 / +100 / Max drop-down. + private int _multiKey = -1; + private Vector2 _multiAt; + private bool _multiOpenRequested; + private bool _confirmOpenRequested; + private Vector2 _confirmAt; + private bool _pending; + private long _pendingUntilMs; + private long _pendingUnassigned; + private int _pendingCredits; + private int _pendingVersion; + + private string _status = ""; + private uint _statusColor; + private long _statusUntilMs; + + // Aelrynth skill mastery: only while ServerInfo.IsAelrynth (nothing shown or sent elsewhere). + private bool _aelrynth; + private bool _masteryUnsupported; + private MasterySnapshot? _mastery; + private long _radiance = -1; // spendable Radiance, estimated once a second + private long _radianceSecond = -1; + private int _radiancePart = -1; // its index in _summary (tooltip) + private string _masteryTip = ""; + private bool _confirmMastery; // the confirm raises mastery with Radiance + private bool _masteryPending; + private long _masteryPendingUntilMs; + private int _masteryPendingVersion; + + public void OnShown() + { + PlayerProgressHooks.Want(); + PlayerProgressHooks.RefreshSoon(); + SkillDat.EnsureLoadQueued(); + PortalSpellTable.EnsureLoadQueued(); + MasteryFeed.PanelOpened(); // asks only on Aelrynth, and only if the last reply is stale + ProgressionShown(); + } + + public void OnHidden() => ProgressionHidden(); + + public void Draw() + { + PlayerProgressHooks.Want(); + Refresh(); + ApplyProgressionRequest(); + if (_tab == 2 && !ProgressionTabVisible) _tab = 0; + + float w = Begin(out Vector2 origin, out Vector2 size); + DrawSummary(w); + DrawTabs(w); + if (_tab == 0) DrawToolbar(w); + if (_tab != 2) DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute"); + + float bodyH = Math.Max(60, Remaining(origin, size) - GripOverlap()); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0)); + ImGuiNET.ImGui.BeginChild("##skills_body", new Vector2(w, bodyH)); + float bw = ImGuiNET.ImGui.GetContentRegionAvail().X; + EnsureWidths(); + if (_tab == 2) + DrawProgression(bw); + else if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead) + Message("Waiting for your character's data...", bw); + else if (_dat == null) + Message("Loading skill names from the client's portal.dat: " + SkillDat.Status, bw); + else if (_tab == 0) + DrawSkills(bw); + else + DrawAttributes(bw); + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + End(origin, size); + + _picker.Draw(); + DrawMulti(); + DrawConfirm(); + DrawProgressionConfirm(); + } + + // ── Data ──────────────────────────────────────────────────────────── + + private void Refresh() + { + PlayerProgress? snap = PlayerProgressHooks.Current; + SkillDatTables? dat = SkillDat.Tables; + bool spells = PortalSpellTable.Ready; + long now = Environment.TickCount64; + long second = now / 1000; + + // Mastery: the flag and the feed's snapshot are volatile reads; the Radiance + // estimate (property-cache lookups) once a second, a rebuild only when it moved. + bool aelrynth = ServerInfo.IsAelrynth; + MasterySnapshot? mastery = aelrynth ? MasteryFeed.Snapshot : null; + if (mastery != null && (second != _radianceSecond || mastery != _mastery)) + { + _radianceSecond = second; + long est = MasteryFeed.EstimateRadiance(mastery); + if (est != _radiance) { _radiance = est; _dirty = true; } + } + if (_masteryPending && (now > _masteryPendingUntilMs || (mastery != null && mastery.Version != _masteryPendingVersion))) + _masteryPending = false; + bool unsupported = aelrynth && MasteryFeed.Unsupported; + if (unsupported != _masteryUnsupported) { _masteryUnsupported = unsupported; _dirty = true; } + + if (snap != _snap || dat != _dat || spells != _spellsReady || aelrynth != _aelrynth || mastery != _mastery || _dirty) + { + _snap = snap; + _dat = dat; + _spellsReady = spells; + _aelrynth = aelrynth; + _mastery = mastery; + if (mastery == null) _radiance = -1; + _dirty = false; + Build(); + _orderDirty = true; + _detailSecond = -1; + } + if (_orderDirty) + { + _orderDirty = false; + Order(); + } + + if (_pending && (now > _pendingUntilMs + || (snap != null && snap.Version != _pendingVersion + && (snap.UnassignedXp != _pendingUnassigned || snap.SkillCredits != _pendingCredits)))) + _pending = false; + + // The open row's time-left text, once a second. + if (second != _detailSecond && _byKey.TryGetValue(_expandedKey, out Row? open)) + { + _detailSecond = second; + double serverNow = TimeSyncHooks.GetCurrentServerTime(); + foreach (BuffLine b in open.Buffs) b.Time = TimeLeft(b.Expiry, serverNow); + } + } + + private void Build() + { + _skills.Clear(); + _attributes.Clear(); + _vitals.Clear(); + _byKey.Clear(); + _widthFont = -1; + PlayerProgress? s = _snap; + SkillDatTables? dat = _dat; + _masteryTip = _aelrynth && _mastery?.Data is { Ok: true } md ? MasteryTip(md) : ""; + if (s == null || dat == null) + { + BuildSummary(s, dat); + return; + } + + foreach (SkillDatEntry e in dat.Skills.Values) + { + if (e.Id < 1 || e.Id > PlayerProgress.MaxSkill) continue; + uint cls = s.SkillClass[e.Id]; + var r = new Row + { + Kind = RowKind.Skill, Stype = e.Id, Name = e.Name, Description = e.Description, Icon = e.Icon, + Group = cls >= 3 ? 0 : cls == 2 ? 1 : e.UsableUntrained ? 2 : 3, + Table = cls >= 3 ? dat.SpecializedXp : cls == 2 ? dat.TrainedXp : null, + Ranks = s.SkillRanks[e.Id], Spent = s.SkillXpSpent[e.Id], + Buffed = s.SkillBuffed[e.Id], Base = s.SkillBase[e.Id], + }; + bool known = s.SkillLevelKnown[e.Id] && (r.Group != 3 || r.Base > 0); + Finish(r, s, known); + if (r.Table == null) + { + // Skills the dat prices at 0 credits are trained for free by the server. + r.TrainCost = Math.Max(0, e.TrainedCost); + r.CostText = r.TrainCost > 0 ? r.TrainCost.ToString(CultureInfo.InvariantCulture) + " cr" : "—"; + r.CostColor = r.TrainCost > 0 && r.TrainCost <= s.SkillCredits ? Teal : Dim; + string train = r.TrainCost > 0 + ? $"Training costs {Credits(r.TrainCost)} (you have {s.SkillCredits})." + : "The skill table has no credit price for it, so it can't be trained from here."; + r.Detail = (r.Group == 3 ? "Needs training to use. " : "Untrained. ") + train; + } + else + { + r.Detail = RankDetail(r) + (s.SkillInit[e.Id] > 0 ? $" · innate +{s.SkillInit[e.Id]}" : "") + + (cls >= 3 ? " · specialized" : " · trained"); + if (cls == 2) + { + r.SpecializeCost = Math.Max(0, e.SpecializedCost - e.TrainedCost); + if (r.SpecializeCost > 0) + r.Detail2 = $"Specializing costs {Credits(r.SpecializeCost)} more (you have {s.SkillCredits}). " + + "The server has no client action for it: it takes this skill's Gem of Enlightenment."; + } + } + CollectBuffs(r, s, PlayerProgressHooks.ModSkill, e.Id); + if (r.Table != null && _aelrynth) ApplyMastery(r); + Add(_skills, r); + } + + for (uint a = 1; a <= 6; a++) + { + var r = new Row + { + Kind = RowKind.Attribute, Stype = a, Name = AttributeNames[a], Glyph = AttributeGlyphs[a], GlyphColor = Teal, + Table = dat.AttributeXp, Ranks = s.AttrRanks[a], Spent = s.AttrXpSpent[a], + Buffed = (int)s.AttrBuffed[a], Base = (int)s.AttrBase[a], + }; + Finish(r, s, s.AttrBase[a] > 0 || s.AttrBuffed[a] > 0); + r.Detail = $"Innate {s.AttrInit[a]} · " + RankDetail(r); + CollectBuffs(r, s, PlayerProgressHooks.ModAttribute, a); + Add(_attributes, r); + } + + for (uint v = 1; v <= 3; v++) + { + var r = new Row + { + Kind = RowKind.Vital, Stype = v, Name = VitalNames[v], Glyph = VitalGlyphs[v], GlyphColor = VitalColors[v], + Table = dat.VitalXp, Ranks = s.VitalRanks[v], Spent = s.VitalXpSpent[v], + Buffed = (int)s.VitalBuffed[v], Base = (int)s.VitalBase[v], + }; + Finish(r, s, s.VitalBase[v] > 0 || s.VitalBuffed[v] > 0); + r.Detail = RankDetail(r) + " · maximum shown"; + // Vital buffs are keyed by the maximum: 1 health, 3 stamina, 5 mana. + CollectBuffs(r, s, PlayerProgressHooks.ModSecondAttribute, v * 2 - 1); + Add(_vitals, r); + } + + BuildSummary(s, dat); + } + + // ── Aelrynth skill mastery ─────────────────────────────────────────── + + /// <summary>"3.7": ranks as points, the way the server prints them (Mastery.Points).</summary> + private static string PointsText(int ranks, int perPoint) => + perPoint <= 1 + ? ranks.ToString("N0", CultureInfo.InvariantCulture) + : (ranks / perPoint).ToString("N0", CultureInfo.InvariantCulture) + "." + (ranks % perPoint).ToString(CultureInfo.InvariantCulture); + + /// <summary>What one raise buys, in words.</summary> + private static string RaiseWord(int perPoint) => perPoint switch + { + <= 1 => "one skill point", + 10 => "a tenth of a skill point", + _ => $"1/{perPoint} of a skill point", + }; + + /// <summary>The hover text that explains mastery, from the server's own settings.</summary> + private static string MasteryTip(MasteryData d) + { + string start = d.RequireCap + ? "Once a skill reaches its retail maximum, you can keep raising it with Radiance from your account bank." + : "You can raise trained skills past what experience buys, with Radiance from your account bank."; + string per = d.PerPoint <= 1 + ? "Each raise adds one point to the skill." + : $"Each raise is {RaiseWord(d.PerPoint)}; every {d.PerPoint} raises add one point to the skill."; + string ceiling = d.CeilingPoints > 0 + ? $" Mastery stops at {d.CeilingPoints:N0} points per skill." + : " There is no ceiling: each raise costs more than the last."; + return "Skill mastery (Aelrynth)\n" + start + " " + per + ceiling + + "\nMastery is kept through enlightenment, and buffs and vitae count on it as on retail skill points." + + "\nThe crown number is the skill's mastery points; open a skill for the price of its next raise."; + } + + /// <summary>A trained skill's mastery badge and detail lines, from the last /mastery-data reply.</summary> + private void ApplyMastery(Row r) + { + MasterySnapshot? snap = _mastery; + if (snap == null) + { + r.MasteryLine = MasteryFeed.NoChatHook + ? "Mastery: not available under Decal." + : MasteryFeed.Unsupported + ? "Mastery: this server didn't answer the mastery request." + : "Mastery: no data yet (asked when this panel opens)."; + return; + } + MasteryData d = snap.Data; + if (!d.Ok) + { + r.MasteryLine = "Mastery: the server couldn't read your mastery" + (d.Why.Length > 0 ? $" ({d.Why})." : "."); + return; + } + if (!d.Skills.TryGetValue((int)r.Stype, out MasterySkill? m)) + { + r.MasteryLine = "Mastery: the server sent nothing for this skill."; + return; + } + r.Mastery = m; + string points = m.Points.Length > 0 ? m.Points : PointsText(m.Ranks, d.PerPoint); + if (m.Ranks > 0) r.MasteryText = points; + r.MasteryLine = m.Ranks > 0 + ? $"Mastery {points} points · +{m.Bonus:N0} on the skill · {m.Ranks:N0} raise{(m.Ranks == 1 ? "" : "s")} bought" + : "Mastery: none yet"; + CanRaiseMastery(r, out string why); + r.MasteryLine2 = why; + r.MasteryHover = r.MasteryLine + "\n" + why + "\n\n" + _masteryTip; + } + + /// <summary>Whether the row's "Raise mastery" works; <paramref name="why"/> is the price line or the reason not.</summary> + private bool CanRaiseMastery(Row r, out string why) + { + MasterySkill? m = r.Mastery; + MasteryData? d = _mastery?.Data; + if (m == null || d == null) { why = "No mastery data for this skill yet."; return false; } + if (!d.Enabled) { why = "Skill mastery is turned off on this server right now."; return false; } + if (m.Ceiling) { why = $"At the mastery ceiling ({d.CeilingPoints:N0} points)."; return false; } + if (m.Locked) { why = "Raise it to its retail maximum with experience first; mastery starts there."; return false; } + if (m.Next <= 0) { why = "The server gave no price for the next raise."; return false; } + string price = $"Next raise ({RaiseWord(d.PerPoint)}): {RadianceText(m.Next)} Radiance"; + long have = _radiance >= 0 ? _radiance : d.Radiance; + if (m.Next > have) { why = $"{price}; you have {RadianceText(have)} banked."; return false; } + if (_masteryPending) { why = $"{price}. Waiting for the last raise to land..."; return false; } + int afford = Math.Max(m.Afford, 1); + why = $"{price}; you have {RadianceText(have)} banked" + + (m.Afford > 1 ? $", enough for about {afford:N0} raises." : "."); + return true; + } + + /// <summary>Radiance with separators, and past a trillion in short form (prices reach 2e15).</summary> + private static string RadianceText(long v) => + Math.Abs(v) >= 1_000_000_000_000L + ? ((double)v).ToString("0.00e0", CultureInfo.InvariantCulture) + : v.ToString("N0", CultureInfo.InvariantCulture); + + private void Add(List<Row> list, Row r) + { + r.Key = ((int)r.Kind << 8) | (int)r.Stype; + list.Add(r); + _byKey[r.Key] = r; + } + + /// <summary>Value texts and colours, and the next raise's cost when the row has an XP table.</summary> + private static void Finish(Row r, PlayerProgress s, bool known) + { + r.BuffedText = known ? r.Buffed.ToString(CultureInfo.InvariantCulture) : "—"; + r.BaseText = known ? r.Base.ToString(CultureInfo.InvariantCulture) : "—"; + r.BuffedColor = !known ? Dim : r.Buffed > r.Base ? Green : r.Buffed < r.Base ? Red : Text; + if (r.Table == null) return; + r.Max = SkillDat.IsMax(r.Table, r.Ranks); + r.NextCost = r.Max ? -1 : SkillDat.CostOf(r.Table, r.Ranks, r.Spent, 1); + if (r.Max || r.NextCost < 0) + { + r.CostText = "max"; + r.CostColor = Amber; + } + else + { + r.CostText = Compact(r.NextCost); + r.CostColor = r.NextCost <= s.UnassignedXp ? Teal : Dim; + } + } + + private static string RankDetail(Row r) + { + int top = Math.Max(0, (r.Table?.Length ?? 1) - 1); + string toMax = r.Max || r.Table == null ? "at the top rank" + : "to max " + Compact(Math.Max(0L, (long)r.Table[top] - r.Spent)); + return $"Ranks {r.Ranks:N0}/{top:N0} · XP spent {r.Spent:N0} · {toMax}"; + } + + private static string Credits(int n) => n == 1 ? "1 credit" : $"{n} credits"; + + /// <summary>The snapshot's buffs on one stat, strongest per spell category first.</summary> + private void CollectBuffs(Row r, PlayerProgress s, uint typeFlag, uint key) + { + for (int i = 0; i < s.BuffCount; i++) + { + if ((s.BuffType[i] & typeFlag) == 0 || s.BuffKey[i] != key) continue; + float val = s.BuffVal[i]; + bool mult = (s.BuffType[i] & PlayerProgressHooks.ModMultiplicative) != 0; + float strength = mult ? MathF.Abs(val - 1f) : MathF.Abs(val); + uint cat = s.BuffCategory[i]; + // Only the strongest of a spell category counts (AC's rule is the highest power; + // the value is what the snapshot has). The weaker ones are counted, not listed. + BuffLine? same = null; + if (cat != 0) + foreach (BuffLine b in r.Buffs) + if (b.Category == cat) { same = b; break; } + string amount = mult + ? "×" + val.ToString("0.##", CultureInfo.InvariantCulture) + : (val >= 0 ? "+" : "") + val.ToString("0.##", CultureInfo.InvariantCulture); + bool good = mult ? val >= 1f : val >= 0f; + if (same != null) + { + same.Surpassed++; + if (strength <= same.Strength) continue; + same.Spell = s.BuffSpell[i]; + same.Name = SpellName(s.BuffSpell[i]); + same.Amount = amount; + same.Good = good; + same.Expiry = s.BuffExpiry[i]; + same.Strength = strength; + continue; + } + r.Buffs.Add(new BuffLine + { + Spell = s.BuffSpell[i], Name = SpellName(s.BuffSpell[i]), Amount = amount, Good = good, + Expiry = s.BuffExpiry[i], Category = cat, Strength = strength, + }); + } + r.Buffs.Sort((a, b) => a.Good != b.Good ? (a.Good ? -1 : 1) : string.CompareOrdinal(a.Name, b.Name)); + foreach (BuffLine b in r.Buffs) + { + if (b.Good) r.BuffsUp++; else r.BuffsDown++; + } + } + + private static string SpellName(uint spell) => + PortalSpellTable.TryGetName(spell, out string n) ? n : $"Spell {spell}"; + + private void BuildSummary(PlayerProgress? s, SkillDatTables? dat) + { + var parts = new List<string>(); + var colors = new List<uint>(); + void Part(string t, uint c) { parts.Add(t); colors.Add(c); } + if (s == null) + { + Part("No character data yet", Dim); + } + else + { + Part($"Level {s.Level}", Amber); + Part($"Unassigned {s.UnassignedXp:N0} XP", s.UnassignedXp > 0 ? Teal : Mute); + Part($"Total {s.TotalXp:N0} XP", Mute); + if (dat != null && s.Level >= 1 && s.Level + 1 < dat.LevelXp.Length) + { + long toNext = (long)Math.Min(dat.LevelXp[s.Level + 1], (ulong)long.MaxValue) - s.TotalXp; + if (toNext > 0) Part($"Next level in {toNext:N0}", Mute); + } + Part(s.SkillCredits == 1 ? "1 skill credit" : $"{s.SkillCredits} skill credits", s.SkillCredits > 0 ? Teal : Mute); + if (s.MaxLuminance > 0) Part($"Luminance {s.Luminance:N0} / {s.MaxLuminance:N0}", Mute); + if (s.Vitae > 0f && s.Vitae < 0.999f) Part($"Vitae {s.Vitae * 100f:0}%", Red); + } + + // Aelrynth: the Radiance a mastery raise spends (hover explains mastery). + _radiancePart = -1; + if (_aelrynth && s != null) + { + MasteryData? d = _mastery?.Data; + if (d != null && d.Ok) + { + _radiancePart = parts.Count; + Part(PhosphorIcons.Sun + " Radiance " + RadianceText(_radiance >= 0 ? _radiance : d.Radiance) + " banked", + d.Enabled ? MasteryColor : Dim); + } + else if (MasteryFeed.NoChatHook) + { + Part(PhosphorIcons.Crown + " Mastery: not available under Decal", Dim); + } + else if (MasteryFeed.Unsupported) + { + Part(PhosphorIcons.Crown + " No mastery on this server", Dim); + } + else + { + Part(PhosphorIcons.Crown + " Mastery: asking the server...", Dim); + } + } + _summary = parts.ToArray(); + _summaryColors = colors.ToArray(); + } + + /// <summary>Skills into their groups, filtered and sorted.</summary> + private void Order() + { + foreach (List<Row> g in _groups) g.Clear(); + foreach (Row r in _skills) + { + if (_filter.Length > 0 && r.Name.IndexOf(_filter, StringComparison.OrdinalIgnoreCase) < 0) continue; + _groups[r.Group].Add(r); + } + Comparison<Row> cmp = _sort switch + { + SortKey.Buffed => (a, b) => Then(a.Buffed.CompareTo(b.Buffed), a, b), + SortKey.Base => (a, b) => Then(a.Base.CompareTo(b.Base), a, b), + SortKey.Cost => (a, b) => Then(CostKey(a).CompareTo(CostKey(b)), a, b), + _ => (a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase), + }; + foreach (List<Row> g in _groups) + { + g.Sort(cmp); + if (_descending) g.Reverse(); + } + } + + private static int Then(int c, Row a, Row b) => + c != 0 ? c : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); + + private static long CostKey(Row r) => r.NextCost >= 0 ? r.NextCost : long.MaxValue; + + /// <summary>Text widths are cached per row; measured again when the font size changes.</summary> + private void EnsureWidths() + { + float fs = ImGuiNET.ImGui.GetFontSize(); + if (fs == _widthFont) return; + _widthFont = fs; + foreach (Row r in _byKey.Values) + { + r.BuffedW = ImGuiNET.ImGui.CalcTextSize(r.BuffedText).X; + r.BaseW = ImGuiNET.ImGui.CalcTextSize(r.BaseText).X; + r.CostW = ImGuiNET.ImGui.CalcTextSize(r.CostText).X; + r.MasteryW = r.MasteryText.Length > 0 ? ImGuiNET.ImGui.CalcTextSize(r.MasteryText).X : 0; + } + } + + // ── Header pieces ─────────────────────────────────────────────────── + + private void DrawSummary(float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + float lineH = ImGuiNET.ImGui.GetTextLineHeight(); + float x = start.X, y = start.Y; + for (int i = 0; i < _summary.Length; i++) + { + float tw = ImGuiNET.ImGui.CalcTextSize(_summary[i]).X; + if (x > start.X && x + tw > start.X + w) { x = start.X; y += lineH + 2; } + dl.AddText(new Vector2(x, y), _summaryColors[i], _summary[i]); + if (i == _radiancePart && _masteryTip.Length > 0 + && ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x, y), new Vector2(x + tw, y + lineH))) + ImGuiNET.ImGui.SetTooltip(_masteryTip); + x += tw + 14; + } + long now = Environment.TickCount64; + string status = _pending ? "Sent... waiting for the server" : now < _statusUntilMs ? _status : ""; + if (status.Length > 0) + { + y += lineH + 2; + dl.AddText(new Vector2(start.X, y), _pending ? Teal : _statusColor, status); + } + else if ((!PlayerTraining.Available || !PlayerTraining.TrainAvailable) && _snap != null) + { + y += lineH + 2; + dl.AddText(new Vector2(start.X, y), Dim, !PlayerTraining.Available + ? "Raising isn't available on this client build (the raise functions weren't found)." + : "Training isn't available on this client build (the train function wasn't found)."); + } + NextLine(start, y - start.Y + lineH + 6); + } + + private void DrawTabs(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + // The Progression tab only exists on ILT-like worlds (RynthAi's snapshot says so). + int count = ProgressionTabVisible ? 3 : 2; + float tabW = (w - 4 * (count - 1)) / count; + if (Button("##tab_skills", "Skills", p, new Vector2(tabW, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill, + border: _tab == 0 ? Teal : 0)) + _tab = 0; + if (Button("##tab_attrs", "Attributes & Vitals", new Vector2(p.X + tabW + 4, p.Y), new Vector2(tabW, 22), + _tab == 1 ? Teal : Text, _tab == 1 ? Selected : BtnFill, border: _tab == 1 ? Teal : 0)) + _tab = 1; + if (count == 3 && Button("##tab_prog", "Progression", new Vector2(p.X + 2 * (tabW + 4), p.Y), new Vector2(tabW, 22), + _tab == 2 ? Teal : Text, _tab == 2 ? Selected : BtnFill, border: _tab == 2 ? Teal : 0)) + _tab = 2; + NextLine(p, 26); + } + + private void DrawToolbar(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float sortW = 120, dirW = 24; + float searchW = Math.Max(80, w - sortW - dirW - 8); + if (TextBox("##skills_search", _search, p, searchW, "Search skills", out _)) + { + string f = Utf8(_search).Trim(); + if (f != _filter) { _filter = f; _orderDirty = true; } + } + PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.MagnifyingGlass, + new Vector2(p.X + searchW - 22, p.Y), new Vector2(22, 22), Dim); + var sortPos = new Vector2(p.X + searchW + 4, p.Y); + if (Button("##skills_sort_btn", "Sort: " + SortNames[(int)_sort], sortPos, new Vector2(sortW, 22), Text, BtnFill)) + _picker.Open(sortPos + new Vector2(0, 24), SortNames, (int)_sort, i => { _sort = (SortKey)i; _orderDirty = true; }, sortW); + if (IconButton("##skills_dir", _descending ? PhosphorIcons.SortDescending : PhosphorIcons.SortAscending, + new Vector2(sortPos.X + sortW + 4, p.Y), new Vector2(dirW, 22), Teal, BtnFill, font: UiFont.Ui11)) + { + _descending = !_descending; + _orderDirty = true; + } + ImGuiNET.ImGui.SetItemTooltip(_descending ? "Highest first" : "Lowest first"); + NextLine(p, 26); + } + + private static void DrawColumnHeader(float w, string first) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr f = ImGuiFonts.Get(UiFont.Ui9); + float y = p.Y + (18 - f.FontSize) * 0.5f; + dl.AddRectFilled(p, p + new Vector2(w, 18), GroupBg); + dl.AddText(f, f.FontSize, new Vector2(p.X + 8 + IconSize, y), Mute, first); + float right = p.X + w - 4 - ColButton - 4; + RightText(dl, f, right, y, Mute, "Cost"); + right -= ColCost; + RightText(dl, f, right, y, Mute, "Base"); + right -= ColBase; + RightText(dl, f, right, y, Mute, "Buffed"); + NextLine(p, 20); + } + + private static void RightText(ImDrawListPtr dl, ImFontPtr f, float right, float y, uint col, string text) + { + float tw = f.CalcTextSizeA(f.FontSize, float.MaxValue, 0f, text).X; + dl.AddText(f, f.FontSize, new Vector2(right - tw, y), col, text); + } + + // ── Lists ─────────────────────────────────────────────────────────── + + private void DrawSkills(float w) + { + bool any = false; + for (int g = 0; g < _groups.Length; g++) + { + List<Row> rows = _groups[g]; + if (rows.Count == 0 && _filter.Length > 0) continue; + any = true; + GroupHeader(g, rows.Count, w); + if (_collapsed[g]) continue; + for (int i = 0; i < rows.Count; i++) DrawRow(rows[i], w, i); + } + if (!any) Message($"No skill matches \"{_filter}\".", w); + } + + private void DrawAttributes(float w) + { + Section("Attributes", w); + for (int i = 0; i < _attributes.Count; i++) DrawRow(_attributes[i], w, i); + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + Section("Vitals (maximum)", w); + for (int i = 0; i < _vitals.Count; i++) DrawRow(_vitals[i], w, i); + } + + private void GroupHeader(int g, int count, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.PushID(1000 + g); + if (ImGuiNET.ImGui.InvisibleButton("##grp", new Vector2(w, 22))) _collapsed[g] = !_collapsed[g]; + bool hot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + dl.AddRectFilled(p, p + new Vector2(w, 22), hot ? Lighten(Selected) : Selected); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), _collapsed[g] ? PhosphorIcons.CaretRight : PhosphorIcons.CaretDown, + p + new Vector2(4, 1), new Vector2(18, 20), Amber); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + dl.AddText(bold, bold.FontSize, new Vector2(p.X + 26, p.Y + (22 - bold.FontSize) * 0.5f), Amber, + $"{GroupNames[g]} ({count})"); + NextLine(p, 23); + } + + private static void Section(string title, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(p, p + new Vector2(w, 22), Selected); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + dl.AddText(bold, bold.FontSize, new Vector2(p.X + 8, p.Y + (22 - bold.FontSize) * 0.5f), Amber, title); + NextLine(p, 23); + } + + private static void Message(string text, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(8, 8); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w - 24); // window-local x + ImGuiNET.ImGui.TextUnformatted(text); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + } + + private void DrawRow(Row r, float w, int index) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool expanded = r.Key == _expandedKey; + if (!ImGuiNET.ImGui.IsRectVisible(p, p + new Vector2(w, RowH))) + { + NextLine(p, RowH); + if (expanded) DrawDetail(r, w); + return; + } + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(p, p + new Vector2(w, RowH), expanded ? ExpandedBg : index % 2 == 0 ? RowAlt : PanelBg); + float textY = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + bool unusable = r.Kind == RowKind.Skill && r.Group == 3; + + // Icon. + var iconMin = new Vector2(p.X + 4, p.Y + (RowH - IconSize) * 0.5f); + if (r.Icon != 0) + { + if (ScriptIcons.TryGet(ScriptIconKind.Icon, r.Icon, out IntPtr tex)) + dl.AddImage(tex, iconMin, iconMin + new Vector2(IconSize, IconSize), Vector2.Zero, Vector2.One, + unusable ? 0x80FFFFFFu : 0xFFFFFFFFu); + else + dl.AddRectFilled(iconMin, iconMin + new Vector2(IconSize, IconSize), BtnFill, 2); + } + else if (r.Glyph.Length > 0) + { + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), r.Glyph, iconMin, new Vector2(IconSize, IconSize), r.GlyphColor); + } + + // Right-hand columns, from the right edge in. + float right = p.X + w - 4; + var btnMin = new Vector2(right - ColButton, p.Y + 1); + right -= ColButton + 4; + float costRight = right; + right -= ColCost; + float baseRight = right; + right -= ColBase; + float buffedRight = right; + right -= ColBuffed; + + // Name, with the buff marks after it; the mastery badge (Aelrynth) at its right end. + float nameX = p.X + 8 + IconSize; + float nameMax = right - 4; + Vector2 badgeMin = default, badgeMax = default; + if (r.MasteryText.Length > 0) + { + float bw = 15 + r.MasteryW; + badgeMin = new Vector2(Math.Max(nameX, nameMax - bw), p.Y); + badgeMax = new Vector2(nameMax, p.Y + RowH); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Crown, badgeMin, new Vector2(14, RowH), MasteryColor); + dl.AddText(new Vector2(badgeMin.X + 15, textY), MasteryColor, r.MasteryText); + nameMax = badgeMin.X - 4; + } + dl.PushClipRect(new Vector2(nameX, p.Y), new Vector2(nameMax, p.Y + RowH), true); + dl.AddText(new Vector2(nameX, textY), unusable ? Dim : Text, r.Name); + dl.PopClipRect(); + if (r.BuffsUp + r.BuffsDown > 0) + { + float nx = Math.Min(nameX + ImGuiNET.ImGui.CalcTextSize(r.Name).X + 4, nameMax - 16); + ImFontPtr f11 = ImGuiFonts.Get(UiFont.Ui11); + if (r.BuffsUp > 0) + PhosphorIcons.DrawCentered(dl, f11, PhosphorIcons.Sparkle, new Vector2(nx, p.Y), new Vector2(14, RowH), Green); + if (r.BuffsDown > 0) + PhosphorIcons.DrawCentered(dl, f11, PhosphorIcons.TrendDown, new Vector2(nx + (r.BuffsUp > 0 ? 14 : 0), p.Y), + new Vector2(14, RowH), Red); + } + + dl.AddText(new Vector2(buffedRight - r.BuffedW, textY), r.BuffedColor, r.BuffedText); + dl.AddText(new Vector2(baseRight - r.BaseW, textY), Mute, r.BaseText); + dl.AddText(new Vector2(costRight - r.CostW, textY), r.CostColor, r.CostText); + + // Row click opens the details (everything but the raise button). + ImGuiNET.ImGui.PushID(r.Key); + ImGuiNET.ImGui.SetCursorScreenPos(p); + if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(Math.Max(1, w - ColButton - 8), RowH))) + { + _expandedKey = expanded ? -1 : r.Key; + _detailSecond = -1; + } + if (ImGuiNET.ImGui.IsItemHovered() && !expanded) + dl.AddRect(p, p + new Vector2(w, RowH), BtnBord); + if (r.MasteryText.Length > 0 && _masteryTip.Length > 0 && ImGuiNET.ImGui.IsMouseHoveringRect(badgeMin, badgeMax)) + ImGuiNET.ImGui.SetTooltip(r.MasteryHover); + + // The row's action buttons: "+1" (raise one rank now, no confirm) and a caret that + // opens +10 / +100 / Max on trained rows, attributes and vitals; Train (skill + // credits, with a confirm) on untrained skills. Greyed with the reason when they can't act. + var btnSize = new Vector2(ColButton, RowH - 2); + if (r.Table != null) + { + var oneSize = new Vector2(ColButton - CaretW - 2, RowH - 2); + bool canRaise = CanRaise(r, out string why); + if (Button("##raise1", r.Max ? "max" : "+1", btnMin, oneSize, Teal, BtnFill, canRaise, border: canRaise ? Teal : 0) + && _snap != null) + SendRaise(r, _snap, 1); + ImGuiNET.ImGui.SetItemTooltip(why); + bool canMore = !r.Max && PlayerTraining.Available && !_pending; + var caretMin = new Vector2(btnMin.X + oneSize.X + 2, btnMin.Y); + if (IconButton("##raiseN", PhosphorIcons.CaretDown, caretMin, new Vector2(CaretW, RowH - 2), Teal, BtnFill, + canMore, font: UiFont.Ui11)) + OpenMulti(r, caretMin + new Vector2(CaretW - MultiW, RowH)); + ImGuiNET.ImGui.SetItemTooltip(canMore ? "Raise more: +10, +100 or Max" + : r.Max ? "At the top rank" : _pending ? "Waiting for the last raise to land" + : "Raising isn't available on this client build"); + } + else if (r.Kind == RowKind.Skill) + { + bool canTrain = CanTrain(r, out string why); + if (Button("##train", "Train", btnMin, btnSize, Amber, BtnFill, canTrain, border: canTrain ? Amber : 0)) + OpenConfirm(r, train: true); + ImGuiNET.ImGui.SetItemTooltip(why); + } + ImGuiNET.ImGui.PopID(); + NextLine(p, RowH); + + if (expanded) DrawDetail(r, w); + } + + /// <summary>Whether the row's raise button works, and its tooltip.</summary> + private bool CanRaise(Row r, out string why) + { + if (r.Max) { why = "At the top rank"; return false; } + if (!PlayerTraining.Available) { why = "Raising isn't available on this client build"; return false; } + if (_pending) { why = "Waiting for the last raise to land"; return false; } + long have = _snap?.UnassignedXp ?? 0; + if (r.NextCost < 0) { why = "Can't be raised"; return false; } + if (r.NextCost > have) + { + why = $"Next raise: {r.NextCost:N0} XP (you have {have:N0} unassigned)"; + return false; + } + why = $"Raise to {r.Base + 1}: {r.NextCost:N0} XP"; + return true; + } + + /// <summary>Whether an untrained skill's Train button works, and its tooltip.</summary> + private bool CanTrain(Row r, out string why) + { + int have = _snap?.SkillCredits ?? 0; + if (r.TrainCost <= 0) { why = "No credit price in the skill table"; return false; } + if (!PlayerTraining.TrainAvailable) { why = "Training isn't available on this client build"; return false; } + if (_pending) { why = "Waiting for the last change to land"; return false; } + if (r.TrainCost > have) + { + why = $"Training costs {Credits(r.TrainCost)}; you have {have}"; + return false; + } + why = $"Train {r.Name}: {Credits(r.TrainCost)} (you have {have})"; + return true; + } + + private void DrawDetail(Row r, float w) + { + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float x = start.X + 8 + IconSize; + float lineH = ImGuiNET.ImGui.GetTextLineHeight() + 3; + ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9); + float y = start.Y + 3; + + dl.AddText(new Vector2(x, y), Mute, r.Detail); + y += lineH; + if (r.Detail2.Length > 0) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + (start.X + w - 8 - x)); // window-local x + ImGuiNET.ImGui.TextUnformatted(r.Detail2); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + y = ImGuiNET.ImGui.GetCursorScreenPos().Y + 3; + } + if (r.MasteryLine.Length > 0) + y = DrawMasteryDetail(r, x, y, start.X + w - 8, lineH); + if (r.Description.Length > 0) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); + ImGuiNET.ImGui.PushFont(f9); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Dim); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + (start.X + w - 8 - x)); // window-local x + ImGuiNET.ImGui.TextUnformatted(r.Description); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopFont(); + y = ImGuiNET.ImGui.GetCursorScreenPos().Y + 3; + } + + if (r.Buffs.Count == 0) + { + dl.AddText(new Vector2(x, y), Dim, "No buffs or debuffs on this."); + y += lineH; + } + foreach (BuffLine b in r.Buffs) + { + var icon = new Vector2(x, y); + if (PortalSpellTable.TryGetIcon(b.Spell, out uint iconId) && iconId != 0 + && ScriptIcons.TryGet(ScriptIconKind.Icon, iconId, out IntPtr tex)) + dl.AddImage(tex, icon, icon + new Vector2(16, 16)); + else + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), b.Good ? PhosphorIcons.Sparkle : PhosphorIcons.TrendDown, + icon, new Vector2(16, 16), b.Good ? Green : Red); + float tx = x + 20; + dl.AddText(new Vector2(tx, y), b.Good ? Green : Red, b.Amount); + tx += 48; + string name = b.Surpassed > 0 ? $"{b.Name} (+{b.Surpassed} weaker)" : b.Name; + float timeW = b.Time.Length > 0 ? ImGuiNET.ImGui.CalcTextSize(b.Time).X : 0; + float nameMax = start.X + w - 12 - timeW - 8; + dl.PushClipRect(new Vector2(tx, y), new Vector2(Math.Max(tx + 1, nameMax), y + lineH), true); + dl.AddText(new Vector2(tx, y), Text, name); + dl.PopClipRect(); + if (timeW > 0) + { + PhosphorIcons.DrawCentered(dl, f9, PhosphorIcons.Hourglass, new Vector2(nameMax - 2, y), new Vector2(10, lineH - 3), Dim); + dl.AddText(new Vector2(start.X + w - 12 - timeW, y), Mute, b.Time); + } + y += Math.Max(lineH, 18); + } + float h = y - start.Y + 4; + dl.AddLine(new Vector2(start.X, start.Y + h - 1), new Vector2(start.X + w, start.Y + h - 1), BtnBord); + NextLine(start, h); + } + + /// <summary> + /// The open row's mastery block (Aelrynth): points and bonus, the next raise's price + /// or why it can't be bought, and "Raise mastery" (asks first). Returns the next y. + /// </summary> + private float DrawMasteryDetail(Row r, float x, float y, float right, float lineH) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Crown, new Vector2(x, y), new Vector2(14, lineH - 3), MasteryColor); + dl.AddText(new Vector2(x + 18, y), MasteryColor, r.MasteryLine); + if (_masteryTip.Length > 0) + { + float tw = ImGuiNET.ImGui.CalcTextSize(r.MasteryLine).X; + if (ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x, y), new Vector2(x + 18 + tw, y + lineH))) + ImGuiNET.ImGui.SetTooltip(_masteryTip); + } + y += lineH; + if (r.MasteryLine2.Length > 0) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x + 18, y)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + Math.Max(40, right - x - 18)); // window-local x + ImGuiNET.ImGui.TextUnformatted(r.MasteryLine2); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + y = ImGuiNET.ImGui.GetCursorScreenPos().Y + 3; + } + if (r.Mastery != null) + { + bool can = CanRaiseMastery(r, out string why); + ImGuiNET.ImGui.PushID(r.Key + 0x10000); + if (Button("##mastery_raise", PhosphorIcons.Crown + " Raise mastery", new Vector2(x + 18, y), new Vector2(130, 22), + MasteryColor, BtnFill, can, border: can ? MasteryColor : 0)) + OpenMasteryConfirm(r); + ImGuiNET.ImGui.SetItemTooltip(can ? why + "\nAsks before it spends anything." : why); + ImGuiNET.ImGui.PopID(); + y += 26; + } + return y; + } + + private void OpenMasteryConfirm(Row r) + { + _confirmKey = r.Key; + _confirmTrain = false; + _confirmMastery = true; + _confirmCount = 1; + _confirmAt = ImGuiNET.ImGui.GetIO().MousePos + new Vector2(-280, 8); + _confirmOpenRequested = true; + } + + /// <summary>The mastery confirm: one raise for Radiance, sent as the mod's own "/raise <skill> 1".</summary> + private void MasteryConfirmBody(Row r) + { + const float width = 300; + MasterySkill m = r.Mastery!; + MasteryData d = _mastery!.Data; + bool ok = CanRaiseMastery(r, out string why); + long have = _radiance >= 0 ? _radiance : d.Radiance; + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + Label($"Raise {r.Name} mastery", MasteryColor); + ImGuiNET.ImGui.PopFont(); + Label($"One raise: {RaiseWord(d.PerPoint)}.", Text); + Label($"Mastery {PointsText(m.Ranks, d.PerPoint)} → {PointsText(m.Ranks + 1, d.PerPoint)} points", Text); + Label($"Cost: {RadianceText(m.Next)} Radiance", ok ? Teal : Red); + Label(m.Next <= have + ? $"Banked: about {RadianceText(have)} → {RadianceText(have - m.Next)}" + : $"Banked: about {RadianceText(have)} (not enough)", Mute); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + width); + Label(ok + ? "Radiance spent on mastery can't be taken back. The server checks the price and your balance again, " + + "and its answer appears in chat." + : why, Dim); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopFont(); + + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + if (Button("##mastery_go", PhosphorIcons.Crown + " Raise", p, new Vector2(120, 24), Text, StartBg, ok)) + { + SendMasteryRaise(r); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + if (Button("##mastery_cancel", "Cancel", new Vector2(p.X + 128, p.Y), new Vector2(90, 24), Text, BtnFill)) + ImGuiNET.ImGui.CloseCurrentPopup(); + NextLine(p, 28); + ImGuiNET.ImGui.Dummy(new Vector2(width, 0)); + } + + private void SendMasteryRaise(Row r) + { + if (r.Mastery == null || _mastery == null) return; + if (MasteryFeed.QueueRaise(r.Mastery, 1, out string why)) + { + _masteryPending = true; + _masteryPendingUntilMs = Environment.TickCount64 + 8000; + _masteryPendingVersion = _mastery.Version; + SetStatus($"Sent: raise {r.Name} mastery for {RadianceText(r.Mastery.Next)} Radiance.", MasteryColor); + } + else + { + SetStatus("Mastery raise not sent: " + why, Red); + } + } + + // ── Raise confirm ─────────────────────────────────────────────────── + + /// <summary>Train (credits), or a Max raise that spends over half the unassigned XP (<paramref name="count"/> ranks).</summary> + private void OpenConfirm(Row r, bool train, int count = 1) + { + _confirmKey = r.Key; + _confirmTrain = train; + _confirmMastery = false; + _confirmCount = count; + _confirmAt = ImGuiNET.ImGui.GetIO().MousePos + new Vector2(-280, 8); + _confirmOpenRequested = true; + } + + // ── Raise more: the +10 / +100 / Max drop-down ─────────────────────── + + private void OpenMulti(Row r, Vector2 at) + { + _multiKey = r.Key; + _multiAt = at; + _multiOpenRequested = true; + } + + /// <summary> + /// The caret's drop-down: +10, +100 and Max, each with its XP cost, greyed when it + /// can't be bought. A click raises at once; Max asks first only when it would spend + /// more than half the unassigned XP. Drawn at the end of Draw, outside the body child. + /// </summary> + private void DrawMulti() + { + const string id = "##skills_multi"; + if (_multiOpenRequested) + { + _multiOpenRequested = false; + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Clamp(_multiAt.X, 0, Math.Max(0, display.X - MultiW)), + Math.Clamp(_multiAt.Y, 0, Math.Max(0, display.Y - 90)))); + ImGuiNET.ImGui.OpenPopup(id); + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(3, 3)); + bool open = ImGuiNET.ImGui.BeginPopup(id); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) return; + try + { + if (!_byKey.TryGetValue(_multiKey, out Row? r) || r.Table == null || _snap == null || r.Max) + { + ImGuiNET.ImGui.CloseCurrentPopup(); + return; + } + PlayerProgress s = _snap; + long have = s.UnassignedXp; + int maxLeft = Math.Max(0, r.Table.Length - 1 - (int)Math.Min(r.Ranks, (uint)int.MaxValue)); + int affordable = SkillDat.Affordable(r.Table, r.Ranks, r.Spent, have); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float y = p.Y; + MultiItem(r, s, "##m10", "+10", 10, maxLeft, have, p.X, ref y); + MultiItem(r, s, "##m100", "+100", 100, maxLeft, have, p.X, ref y); + MultiItem(r, s, "##mmax", affordable > 0 ? $"Max (+{affordable})" : "Max", affordable, maxLeft, have, p.X, ref y); + NextLine(p, y - p.Y); + ImGuiNET.ImGui.PopFont(); + } + finally + { + ImGuiNET.ImGui.EndPopup(); + } + } + + /// <summary>One drop-down line: label left, XP cost right; greyed with the reason when it can't act.</summary> + private void MultiItem(Row r, PlayerProgress s, string id, string label, int n, int maxLeft, long have, float x, ref float y) + { + const float h = 22; + long cost = n > 0 && n <= maxLeft ? SkillDat.CostOf(r.Table!, r.Ranks, r.Spent, n) : -1; + bool isMax = id == "##mmax"; + string right, why; + bool ok = false; + if (n <= 0 || cost < 0) + { + right = isMax ? "not enough XP" : "past top rank"; + why = isMax ? $"The next raise costs {r.NextCost:N0} XP; you have {have:N0}" + : $"Only {maxLeft} rank{(maxLeft == 1 ? "" : "s")} left to the top"; + } + else if (cost > have) + { + right = Compact(cost) + " XP"; + why = $"Costs {cost:N0} XP; you have {have:N0} unassigned"; + } + else + { + right = Compact(cost) + " XP"; + ok = !_pending && PlayerTraining.Available; + why = $"Raise {r.Name} {r.Base} → {r.Base + n} for {cost:N0} XP" + + (isMax && cost * 2 > have ? " (asks first: over half your unassigned XP)" : ""); + } + var pos = new Vector2(x, y); + var size = new Vector2(MultiW - 6, h); + if (Button(id, label, pos, size, ok ? Text : Dim, BtnFill, ok, leftAlign: true)) + { + if (isMax && cost * 2 > have) + OpenConfirm(r, train: false, count: n); + else + SendRaise(r, s, n); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + ImGuiNET.ImGui.SetItemTooltip(why); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float tw = ImGuiNET.ImGui.CalcTextSize(right).X; + dl.AddText(new Vector2(x + size.X - 6 - tw, y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), ok ? Teal : Dim, right); + y += h + 2; + } + + private void DrawConfirm() + { + const string id = "##skills_raise"; + if (_confirmOpenRequested) + { + _confirmOpenRequested = false; + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Clamp(_confirmAt.X, 0, Math.Max(0, display.X - 300)), + Math.Clamp(_confirmAt.Y, 0, Math.Max(0, display.Y - 200)))); + ImGuiNET.ImGui.OpenPopup(id); + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8)); + bool open = ImGuiNET.ImGui.BeginPopup(id); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) return; + try + { + // Closes when the row no longer fits the action (it got trained meanwhile, say). + if (!_byKey.TryGetValue(_confirmKey, out Row? r) || _snap == null + || (_confirmMastery ? r.Mastery == null || _mastery == null || !_aelrynth + : _confirmTrain ? r.Table != null || r.Kind != RowKind.Skill || r.TrainCost <= 0 : r.Table == null)) + { + ImGuiNET.ImGui.CloseCurrentPopup(); + return; + } + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + try + { + if (_confirmMastery) MasteryConfirmBody(r); + else if (_confirmTrain) TrainConfirmBody(r, _snap); + else ConfirmBody(r, _snap); + } + finally { ImGuiNET.ImGui.PopFont(); } + } + finally + { + ImGuiNET.ImGui.EndPopup(); + } + } + + /// <summary>The one confirm a raise can get: Max spending over half the unassigned XP.</summary> + private void ConfirmBody(Row r, PlayerProgress s) + { + const float width = 280; + uint[] table = r.Table!; + long have = s.UnassignedXp; + int maxLeft = Math.Max(0, table.Length - 1 - (int)Math.Min(r.Ranks, (uint)int.MaxValue)); + int n = Math.Clamp(_confirmCount, 1, Math.Max(1, maxLeft)); + long cost = SkillDat.CostOf(table, r.Ranks, r.Spent, n); + + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + ImGuiNET.ImGui.PushFont(bold); + Label($"Raise {r.Name} +{n}", Amber); + ImGuiNET.ImGui.PopFont(); + Label($"Base {r.Base} → {r.Base + n} (rank {r.Ranks} → {r.Ranks + (uint)n})", Text); + + bool ok = cost > 0 && cost <= have && cost <= uint.MaxValue && !_pending && PlayerTraining.Available; + Label(cost < 0 ? "Past the top rank." : $"Cost: {cost:N0} XP", ok ? Teal : Red); + Label(cost >= 0 && cost <= have + ? $"Unassigned: {have:N0} → {have - cost:N0}" + : $"Unassigned: {have:N0} (not enough)", Mute); + ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9); + ImGuiNET.ImGui.PushFont(f9); + Label("That is more than half of your unassigned XP. Spent XP can't be taken back.", Dim); + ImGuiNET.ImGui.PopFont(); + + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + if (Button("##raise_go", PhosphorIcons.ArrowCircleUp + " Raise", p, new Vector2(120, 24), Text, StartBg, ok)) + { + SendRaise(r, s, n); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + if (Button("##raise_cancel", "Cancel", new Vector2(p.X + 128, p.Y), new Vector2(90, 24), Text, BtnFill)) + ImGuiNET.ImGui.CloseCurrentPopup(); + NextLine(p, 28); + ImGuiNET.ImGui.Dummy(new Vector2(width, 0)); + } + + /// <summary>The train confirm: credits for untrained -> trained (0x0047 TrainSkill).</summary> + private void TrainConfirmBody(Row r, PlayerProgress s) + { + const float width = 300; + int have = s.SkillCredits; + int cost = r.TrainCost; + bool ok = cost > 0 && cost <= have && !_pending && PlayerTraining.TrainAvailable; + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + Label("Train " + r.Name, Amber); + ImGuiNET.ImGui.PopFont(); + Label(r.Group == 3 ? "Unusable → trained: you can use it and raise it with XP." + : "Untrained → trained: you can raise it with XP.", Text); + Label($"Cost: {Credits(cost)}", ok ? Teal : Red); + Label(cost <= have ? $"Skill credits: {have} → {have - cost}" : $"Skill credits: {have} (not enough)", Mute); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + width); + Label("Getting the credits back means untraining it with a Gem of Forgetfulness. " + + "Specializing later takes this skill's Gem of Enlightenment.", Dim); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopFont(); + + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + if (Button("##train_go", PhosphorIcons.GraduationCap + " Train", p, new Vector2(120, 24), Text, StartBg, ok)) + { + SendTrain(r, s); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + if (Button("##train_cancel", "Cancel", new Vector2(p.X + 128, p.Y), new Vector2(90, 24), Text, BtnFill)) + ImGuiNET.ImGui.CloseCurrentPopup(); + NextLine(p, 28); + ImGuiNET.ImGui.Dummy(new Vector2(width, 0)); + } + + private void SendTrain(Row r, PlayerProgress s) + { + if (PlayerTraining.TrainSkill(r.Stype, (uint)r.TrainCost, defer: true)) + { + MarkPending(s); + SetStatus($"Sent: train {r.Name} for {Credits(r.TrainCost)}.", Teal); + } + else + { + SetStatus("The train couldn't be sent (the client's train function isn't bound, or the queue is full).", Red); + } + } + + private void MarkPending(PlayerProgress s) + { + _pending = true; + _pendingUntilMs = Environment.TickCount64 + 5000; + _pendingUnassigned = s.UnassignedXp; + _pendingCredits = s.SkillCredits; + _pendingVersion = s.Version; + PlayerProgressHooks.RefreshSoon(); + } + + /// <summary> + /// Raises <paramref name="n"/> ranks at once: the XP is worked out from the current + /// snapshot, checked against the unassigned XP and the top rank, then queued for AC's + /// main thread. Locks the raise buttons until the new numbers arrive (or 5 s). + /// </summary> + private void SendRaise(Row r, PlayerProgress s, int n) + { + if (_pending || r.Table == null || n < 1) return; + long cost = SkillDat.CostOf(r.Table, r.Ranks, r.Spent, n); + if (cost <= 0 || cost > s.UnassignedXp || cost > uint.MaxValue) + { + SetStatus($"Not raised: {r.Name} +{n} costs {(cost < 0 ? "more ranks than are left" : cost.ToString("N0", CultureInfo.InvariantCulture) + " XP")}.", Red); + return; + } + PlayerTraining.TrainKind kind = r.Kind switch + { + RowKind.Attribute => PlayerTraining.TrainKind.Attribute, + RowKind.Vital => PlayerTraining.TrainKind.Vital, + _ => PlayerTraining.TrainKind.Skill, + }; + uint stype = r.Kind == RowKind.Vital ? r.Stype * 2 - 1 : r.Stype; // vitals by their maximum + if (PlayerTraining.Raise(kind, stype, (uint)cost, defer: true)) + { + MarkPending(s); + SetStatus($"Sent: raise {r.Name} +{n} for {cost:N0} XP.", Teal); + } + else + { + SetStatus("The raise couldn't be sent (the client's raise functions aren't bound, or the queue is full).", Red); + } + } + + private void SetStatus(string text, uint color) + { + _status = text; + _statusColor = color; + _statusUntilMs = Environment.TickCount64 + 6000; + } + + // ── Formatting ────────────────────────────────────────────────────── + + private static string Compact(long v) + { + if (v >= 1_000_000_000) return (v / 1e9).ToString("0.##", CultureInfo.InvariantCulture) + "B"; + if (v >= 1_000_000) return (v / 1e6).ToString("0.##", CultureInfo.InvariantCulture) + "M"; + if (v >= 10_000) return (v / 1e3).ToString("0.#", CultureInfo.InvariantCulture) + "K"; + return v.ToString("N0", CultureInfo.InvariantCulture); + } + + private static string TimeLeft(double expiry, double serverNow) + { + if (expiry >= 1e12) return "no end"; // no duration: item spells while worn, and the like + if (serverNow <= 0) return ""; + double left = expiry - serverNow; + if (left <= 0) return "ending"; + long s = (long)left; + if (s >= 3600) return $"{s / 3600}h {s % 3600 / 60:00}m"; + if (s >= 60) return $"{s / 60}m {s % 60:00}s"; + return $"{s}s"; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs b/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs new file mode 100644 index 0000000..01f9a66 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs @@ -0,0 +1,250 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/VisionFace.cs +// ImGui face of the RynthVision settings (UI/Panels/RynthVisionPanel.cs), +// in three tabs: +// Terrain the plugin's overlays (radar ring, unclimbable slopes, +// impassable water), colours (AARRGGBB hex + swatch), tuning +// sliders (Ctrl+click to type a value), water terrain types, +// and "Log terrain types here"; +// Nameplates the RynthVision nameplates (monster plates, debuff icons, +// your own plate), engine-side (Hud/MonsterHudSettingsUi); +// Combat text floating damage / heal numbers, kill burst and gains. +// +// Terrain edits a private copy and saves just the changed field +// (VisionCommands) when a control finishes changing (a slider on release). +// A newer snapshot replaces the copy unless a control is in use. The other +// two tabs edit MonsterHudSettings directly (saved in the background). +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class VisionFace : IImGuiPanel +{ + public const string Title = "Vision"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(320, 560), new Vector2(280, 240), EdgeToEdge: true), + () => new VisionFace()); + + private static readonly Vector4 HeaderColor = RynthTheme.Vec(0xFF7AB8F5); + + private VisionSettings? _s; + private long _seenVersion = -1; + private bool _busy; + private readonly byte[] _slopeHex = new byte[12], _waterHex = new byte[12], _radarHex = new byte[12]; + private readonly byte[] _waterTypes = new byte[128]; + private int _tab; + private static readonly string[] TabNames = { "Terrain", "Nameplates", "Combat text" }; + private static readonly string[] TabIds = { "##vtab0", "##vtab1", "##vtab2" }; + + public void OnShown() + { + UiSources.Vision.Subscribe(); + UiSources.Vision.RequestRefresh(); + } + + public void OnHidden() => UiSources.Vision.Unsubscribe(); + + public void Draw() + { + TakeSnapshot(); + float w = Begin(out Vector2 origin, out Vector2 size); + TabStrip(w); + + if (_tab == 0) + { + _busy = DrawTerrain(w, origin, size); + } + else + { + _busy = false; + ImGuiNET.ImGui.BeginChild("##vision_overlays", new Vector2(w, Math.Max(60, Remaining(origin, size)))); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + float cw = ImGuiNET.ImGui.GetContentRegionAvail().X - 4; + if (_tab == 1) Hud.MonsterHudSettingsUi.DrawNameplates(cw); + else Hud.MonsterHudSettingsUi.DrawCombatText(cw); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.EndChild(); + } + End(origin, size); + } + + /// <summary>Terrain | Nameplates | Combat text, as a row of flat buttons.</summary> + private void TabStrip(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float x = p.X; + float bw = MathF.Floor((w - 8) / TabNames.Length); + for (int i = 0; i < TabNames.Length; i++) + { + bool sel = i == _tab; + if (Button(TabIds[i], TabNames[i], new Vector2(x, p.Y), new Vector2(bw, 24), sel ? Teal : Mute, + sel ? Selected : BtnFill, border: sel ? Teal : 0)) + _tab = i; + x += bw + 4; + } + NextLine(p, 30); + } + + /// <summary>The plugin's own settings. True while a control is in use.</summary> + private bool DrawTerrain(float w, Vector2 origin, Vector2 size) + { + bool busy = false; + if (_s == null) + { + Label("Waiting for the RynthVision plugin…", Mute); + return false; + } + VisionSettings s = _s; + + ImGuiNET.ImGui.BeginChild("##vision_body", new Vector2(w, Math.Max(60, Remaining(origin, size)))); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrabActive, Amber); + + Header("Overlays"); + if (ImGuiNET.ImGui.Checkbox("Radar range ring", ref s.Radar)) Save(VisionKeys.Radar); + if (ImGuiNET.ImGui.Checkbox("Unclimbable slopes", ref s.Slopes)) Save(VisionKeys.Slopes); + if (ImGuiNET.ImGui.Checkbox("Impassable water", ref s.Water)) Save(VisionKeys.Water); + + Header("Colors (hex AARRGGBB)"); + busy |= ColorRow(SlopeColorF, _slopeHex, ref s.SlopeColor); + busy |= ColorRow(WaterColorF, _waterHex, ref s.WaterColor); + busy |= ColorRow(RadarColorF, _radarHex, ref s.RadarColor); + + Header("Tuning"); + ImGuiNET.ImGui.PushItemWidth(Math.Max(120, ImGuiNET.ImGui.GetContentRegionAvail().X - 8)); + busy |= Slider(RadarRangeF, ref s.RadarRange, 24, 300, "%.0f"); + busy |= Slider(RingThickF, ref s.RingThick, 0.5, 6, "%.1f"); + busy |= Slider(RingHeightF, ref s.RingHeight, 0.5, 30, "%.1f"); + busy |= IntSlider(SlopeRadiusF, ref s.SlopeRadius, 1, 24); + busy |= Slider(SlopeFloorZF, ref s.SlopeFloorZ, 0.30, 0.95, "%.3f"); + busy |= Slider(SlopeBiasF, ref s.SlopeBias, 0.00, 1.00, "%.2f"); + busy |= IntSlider(WaterRadiusF, ref s.WaterRadius, 1, 24); + ImGuiNET.ImGui.PopItemWidth(); + + Header("Water terrain types"); + if (ImGuiNET.ImGui.Checkbox("Highlight cell if ANY corner is water (else all four)", ref s.WaterAnyCorner)) Save(VisionKeys.WaterAnyCorner); + if (ImGuiNET.ImGui.Checkbox("Only paint water cells with an unwalkable triangle (real impassable)", ref s.WaterImpassableOnly)) Save(VisionKeys.WaterImpassableOnly); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool enter = TextBox("##water_types", _waterTypes, p, 160, "18,19,20", out bool typing, ImGuiInputTextFlags.EnterReturnsTrue); + bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); + busy |= typing; + bool apply = Button("##water_apply", "Apply", new Vector2(p.X + 164, p.Y), new Vector2(56, 22), Text, BtnFill); + if (enter || done || apply) + { + // An empty list resets to the defaults in the plugin; the republish + // after the save brings them back here. + s.WaterTypes = VisionSettings.ParseCsv(Utf8(_waterTypes)); + WriteUtf8(_waterTypes, string.Join(",", s.WaterTypes)); + Save(VisionKeys.WaterTypes); + } + NextLine(p, 26); + + p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (Button("##inspect", "Log terrain types here", p, new Vector2(ButtonWidth("Log terrain types here") + 8, 24), Text, BtnFill)) + VisionCommands.Inspect(); + NextLine(p, 28); + + ImGuiNET.ImGui.PopStyleColor(5); + ImGuiNET.ImGui.EndChild(); + return busy; + } + + private void TakeSnapshot() + { + var snap = UiSources.Vision.Current; + if (snap == null || snap.Version == _seenVersion || _busy) return; + _seenVersion = snap.Version; + _s = snap.Value.Settings.Clone(); + WriteUtf8(_slopeHex, _s.SlopeColor.ToString("X8")); + WriteUtf8(_waterHex, _s.WaterColor.ToString("X8")); + WriteUtf8(_radarHex, _s.RadarColor.ToString("X8")); + WriteUtf8(_waterTypes, string.Join(",", _s.WaterTypes)); + } + + private void Save(string key) + { + if (_s != null) VisionCommands.SaveField(_s, key); + } + + /// <summary>A control's label, ImGui id and settings key, built once (no per-frame strings).</summary> + private sealed class Field + { + public readonly string Label, Id, Key; + public Field(string label, string id, string key) { Label = label; Id = id; Key = key; } + public static Field Slider(string name, string key) => new(name + ":", "##" + name, key); + public static Field Color(string name, string key) => new(name, "##hex_" + name, key); + } + + private static readonly Field SlopeColorF = Field.Color("Slope", VisionKeys.SlopeColor); + private static readonly Field WaterColorF = Field.Color("Water", VisionKeys.WaterColor); + private static readonly Field RadarColorF = Field.Color("Radar", VisionKeys.RadarColor); + private static readonly Field RadarRangeF = Field.Slider("Radar range", VisionKeys.RadarRange); + private static readonly Field RingThickF = Field.Slider("Ring thickness", VisionKeys.RingThick); + private static readonly Field RingHeightF = Field.Slider("Ring height (m)", VisionKeys.RingHeight); + private static readonly Field SlopeRadiusF = Field.Slider("Slope radius (cells)", VisionKeys.SlopeRadius); + private static readonly Field SlopeFloorZF = Field.Slider("Slope floor Z", VisionKeys.SlopeFloorZ); + private static readonly Field SlopeBiasF = Field.Slider("Slope height bias (m)", VisionKeys.SlopeBias); + private static readonly Field WaterRadiusF = Field.Slider("Water radius (cells)", VisionKeys.WaterRadius); + + private static void Header(string text) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextColored(HeaderColor, text); + ImGuiNET.ImGui.PopFont(); + } + + /// <summary>Name | hex box | swatch. Commits on Enter or focus loss; bad input reverts. True while typing.</summary> + private bool ColorRow(Field f, byte[] hex, ref uint argb) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, f.Label); + bool enter = TextBox(f.Id, hex, new Vector2(p.X + 48, p.Y), 92, "", out bool typing, + ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.CharsHexadecimal | ImGuiInputTextFlags.CharsUppercase); + bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); + if (enter || done) + { + if (VisionSettings.TryParseHex(Utf8(hex), out uint c)) { argb = c; Save(f.Key); } + WriteUtf8(hex, argb.ToString("X8")); + } + // Swatch: AARRGGBB -> ImGui ABGR. + uint abgr = (argb & 0xFF00FF00) | ((argb >> 16) & 0xFF) | ((argb & 0xFF) << 16); + Vector2 sw = new(p.X + 146, p.Y + 3); + dl.AddRectFilled(sw, sw + new Vector2(22, 16), abgr); + dl.AddRect(sw, sw + new Vector2(22, 16), Mute); + NextLine(p, 26); + return typing; + } + + /// <summary>Label, then the slider; saves on release (or after Ctrl+click typing). True while in use.</summary> + private bool Slider(Field f, ref double value, double min, double max, string format) + { + ImGuiNET.ImGui.TextUnformatted(f.Label); + float v = (float)value; + ImGuiNET.ImGui.SliderFloat(f.Id, ref v, (float)min, (float)max, format, ImGuiSliderFlags.AlwaysClamp); + value = v; + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) Save(f.Key); + ImGuiNET.ImGui.SetItemTooltip("Ctrl+click to type a value"); + return ImGuiNET.ImGui.IsItemActive(); + } + + private bool IntSlider(Field f, ref int value, int min, int max) + { + ImGuiNET.ImGui.TextUnformatted(f.Label); + ImGuiNET.ImGui.SliderInt(f.Id, ref value, min, max, "%d", ImGuiSliderFlags.AlwaysClamp); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) Save(f.Key); + ImGuiNET.ImGui.SetItemTooltip("Ctrl+click to type a value"); + return ImGuiNET.ImGui.IsItemActive(); + } +} diff --git a/src/RynthCore.Engine/ImGui/PhosphorIcons.cs b/src/RynthCore.Engine/ImGui/PhosphorIcons.cs new file mode 100644 index 0000000..2546802 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/PhosphorIcons.cs @@ -0,0 +1,206 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/PhosphorIcons.cs +// The Phosphor icons (MIT, Assets/Fonts/Phosphor.ttf; licence in +// THIRD-PARTY-NOTICES.md) as the characters that draw them. ImGuiFonts merges +// the glyphs into every baked font at the web font's code points (the private +// use area), so an icon is just text: put one in a label, or hand it to +// DrawCentered for an icon-only button. The names are Phosphor's. +// +// Only the glyphs in Baked are in the atlas (about 20 fonts plus the scaled +// copies, so the whole 1,500-glyph set would be wasted space). A constant +// that a face uses must be in Baked, or it draws as nothing. +// tools/check_phosphor_icons.py checks the code points against the font and +// that Baked covers every icon the ImGui code uses. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static unsafe class PhosphorIcons +{ + public const string AppWindow = "\uE5DA"; + public const string ArrowCircleUp = "\uE030"; + public const string ArrowCounterClockwise = "\uE038"; + public const string ArrowDown = "\uE03E"; + public const string ArrowFatDown = "\uE518"; + public const string ArrowFatLinesDown = "\uE524"; + public const string ArrowLeft = "\uE058"; + public const string ArrowRight = "\uE06C"; + public const string ArrowSquareIn = "\uE5DC"; + public const string ArrowSquareOut = "\uE5DE"; + public const string ArrowUUpLeft = "\uE08A"; + public const string ArrowUUpRight = "\uE08C"; + public const string ArrowUp = "\uE08E"; + public const string ArrowsClockwise = "\uE094"; + public const string ArrowsInLineVertical = "\uE532"; + public const string ArrowsOutCardinal = "\uE0A4"; + public const string ArrowsOutLineVertical = "\uE536"; + public const string Backpack = "\uE922"; + public const string Bag = "\uE0B0"; + public const string Barbell = "\uE0B6"; + public const string BatteryCharging = "\uE0BA"; + public const string Binoculars = "\uEA64"; + public const string Brain = "\uE74E"; + public const string CaretDown = "\uE136"; + public const string CaretLeft = "\uE138"; + public const string CaretRight = "\uE13A"; + public const string CaretUp = "\uE13C"; + public const string CastleTurret = "\uE9D0"; + public const string ChartBar = "\uE150"; + public const string ChartLineUp = "\uE156"; + public const string ChatCircleText = "\uE16E"; + public const string Check = "\uE182"; + public const string CheckCircle = "\uE184"; + public const string CheckSquare = "\uE186"; + public const string ClipboardText = "\uE198"; + public const string ClockCounterClockwise = "\uE1A0"; + public const string Code = "\uE1BC"; + public const string Coins = "\uE78E"; + public const string Compass = "\uE1C8"; + public const string Copy = "\uE1CA"; + public const string Crosshair = "\uE1D6"; + public const string CrosshairSimple = "\uE1D8"; + public const string Crown = "\uE614"; + public const string DotsSixVertical = "\uEAE2"; + public const string DotsThree = "\uE1FE"; + public const string DotsThreeVertical = "\uE208"; + public const string Drop = "\uE210"; + public const string Eraser = "\uE21E"; + public const string Eye = "\uE220"; + public const string FileCode = "\uE914"; + public const string FilePlus = "\uE236"; + public const string Files = "\uE710"; + public const string Fire = "\uE242"; + public const string Flask = "\uE79E"; + public const string FloppyDisk = "\uE248"; + public const string FolderOpen = "\uE256"; + public const string Footprints = "\uEA88"; + public const string Funnel = "\uE266"; + public const string Gear = "\uE270"; + public const string Gift = "\uE276"; + public const string GlobeHemisphereWest = "\uE28C"; + public const string GraduationCap = "\uE62C"; + public const string Hammer = "\uE80E"; + public const string Heart = "\uE2A8"; + public const string HeartBreak = "\uEBE8"; + public const string Heartbeat = "\uE2AC"; + public const string HourglassMedium = "\uE2B8"; + public const string Hourglass = "\uE2B2"; + public const string Info = "\uE2CE"; + public const string Knife = "\uE636"; + public const string Lightning = "\uE2DE"; + public const string ListChecks = "\uEADC"; + public const string Lock = "\uE2FA"; + public const string LockOpen = "\uE306"; + public const string MagicWand = "\uE6B6"; + public const string MagnifyingGlass = "\uE30C"; + public const string MapPin = "\uE316"; + public const string MapPinPlus = "\uE314"; + public const string MapTrifold = "\uE31A"; + public const string Minus = "\uE32A"; + public const string Monitor = "\uE32E"; + public const string NavigationArrow = "\uEADE"; + public const string Path = "\uE39C"; + public const string PencilSimple = "\uE3B4"; + public const string PersonSimpleRun = "\uE730"; + public const string Play = "\uE3D0"; + public const string Package = "\uE390"; + public const string Plus = "\uE3D4"; + public const string Power = "\uE3DA"; + public const string Resize = "\uED6E"; + public const string Robot = "\uE762"; + public const string Ruler = "\uE6B8"; + public const string Scales = "\uE750"; + public const string Scissors = "\uEAE0"; + public const string Scroll = "\uEB7A"; + public const string Shield = "\uE40A"; + public const string ShieldSlash = "\uE410"; + public const string ShieldWarning = "\uE412"; + public const string Skull = "\uE916"; + public const string SneakerMove = "\uED60"; + public const string Snowflake = "\uE5AA"; + public const string SortAscending = "\uE444"; + public const string SortDescending = "\uE446"; + public const string Sparkle = "\uE6A2"; + public const string Spiral = "\uE9FA"; + public const string Square = "\uE45E"; + public const string SquaresFour = "\uE464"; + public const string Star = "\uE46A"; + public const string Stop = "\uE46C"; + public const string Storefront = "\uE470"; + public const string Sun = "\uE472"; + public const string Sword = "\uE5BA"; + public const string Target = "\uE47C"; + public const string TerminalWindow = "\uEAE8"; + public const string TextAa = "\uE6EE"; + public const string Trash = "\uE4A6"; + public const string TrendDown = "\uE4AC"; + public const string TreasureChest = "\uEDE2"; + public const string User = "\uE4C2"; + public const string UsersThree = "\uE68E"; + public const string Warning = "\uE4E0"; + public const string WarningCircle = "\uE4E2"; + public const string Wrench = "\uE5D4"; + public const string X = "\uE4F6"; + public const string XCircle = "\uE4F8"; + + /// <summary> + /// The icons merged into the atlas: every one the ImGui faces use. Add a + /// constant here when a face starts using it (ImGuiFonts reads this once, + /// at the first atlas build). + /// </summary> + public const string Baked = + AppWindow + ArrowCounterClockwise + ArrowDown + ArrowLeft + ArrowRight + ArrowSquareIn + ArrowSquareOut + + ArrowUp + ArrowsClockwise + ArrowsInLineVertical + ArrowsOutLineVertical + Backpack + Bag + BatteryCharging + + CaretDown + CaretLeft + CaretRight + CaretUp + ChartBar + ChartLineUp + ChatCircleText + Check + CheckSquare + ClipboardText + Code + + Compass + Copy + Crosshair + DotsSixVertical + DotsThree + Drop + Eraser + Eye + FileCode + FilePlus + Files + + FloppyDisk + Footprints + Funnel + Gear + Hammer + Heart + Heartbeat + Info + Lightning + ListChecks + Lock + + LockOpen + MagicWand + MagnifyingGlass + MapPin + MapPinPlus + MapTrifold + Minus + Monitor + NavigationArrow + + PencilSimple + Play + Plus + Resize + Robot + Ruler + Skull + SneakerMove + Sparkle + Spiral + Square + + Stop + Storefront + Sword + TerminalWindow + Trash + TreasureChest + Warning + X + + ArrowFatDown + ArrowFatLinesDown + Fire + Flask + HeartBreak + Knife + ShieldSlash + ShieldWarning + + Snowflake + TrendDown + UsersThree + + Coins + Gift + HourglassMedium + Scales + Scissors + Shield + SortAscending + SquaresFour + + ArrowCircleUp + Barbell + Brain + GraduationCap + Hourglass + SortDescending + Package + + Binoculars + Crown + Sun + + CastleTurret + ClockCounterClockwise + GlobeHemisphereWest + Path + Star + Target + User + + TextAa; + + /// <summary> + /// Draws <paramref name="glyph"/> (one icon) centred in the box at + /// <paramref name="min"/>, by the glyph's own bounds rather than the line + /// box, so icon-only buttons look centred whatever font carries the icon. + /// Falls back to the text size when the glyph isn't baked. + /// </summary> + public static void DrawCentered(ImDrawListPtr dl, ImFontPtr font, string glyph, Vector2 min, Vector2 size, uint color) => + DrawCentered(dl, font, font.FontSize, glyph, min, size, color); + + /// <summary> + /// DrawCentered at <paramref name="px"/> pixels instead of the font's own size + /// (world overlays that scale with distance); the glyph box scales with it. + /// Never pushes a font, so it also works outside any window. + /// </summary> + public static void DrawCentered(ImDrawListPtr dl, ImFontPtr font, float px, string glyph, Vector2 min, Vector2 size, uint color) + { + if (glyph.Length == 0 || px <= 0) return; + float k = font.FontSize > 0 ? px / font.FontSize : 1f; + Vector2 centre; + // ImFontGlyph (1.91): a 4-byte bitfield, AdvanceX, then X0 Y0 X1 Y1. Read by + // offset: ImGui.NET's generated struct splits the bitfield into three fields. + byte* g = font.NativePtr == null ? null : (byte*)ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]); + if (g != null && glyph.Length == 1) + { + float* box = (float*)(g + 8); + centre = new Vector2((box[0] + box[2]) * 0.5f, (box[1] + box[3]) * 0.5f) * k; + } + else + { + centre = font.CalcTextSizeA(px, float.MaxValue, 0f, glyph) * 0.5f; + } + Vector2 at = min + size * 0.5f - centre; + dl.AddText(font, px, new Vector2(MathF.Round(at.X), MathF.Round(at.Y)), color, glyph); + } +} diff --git a/src/RynthCore.Engine/ImGui/PopOutSurface.cs b/src/RynthCore.Engine/ImGui/PopOutSurface.cs new file mode 100644 index 0000000..4db3c3c --- /dev/null +++ b/src/RynthCore.Engine/ImGui/PopOutSurface.cs @@ -0,0 +1,227 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/PopOutSurface.cs +// The D3D9 side of one popped-out panel (docs/IMGUI_PARITY_PLAN.md §4.2): +// its ImGui draw data is rendered into an off-screen render target, read back +// into system memory and handed to the panel's LayeredWindow +// (UpdateLayeredWindow, per-pixel alpha). +// +// Two render targets alternate: each frame renders into one and reads back +// the other, which the GPU finished a frame ago, so the readback never waits +// on the GPU (a one-frame delay, ~33 ms at 30 Hz). The first frame after a +// (re)size reads its own target once. +// +// A picture can be larger than the panel: a tooltip or popup reaching past it +// is drawn in a margin around it (ImGuiPopOuts). Each target remembers where +// the panel sits in its picture, so the late readback is shown with the +// margins it was drawn with (LayeredWindow.Present keeps the panel in place). +// +// The targets are cleared to transparent black; DX9Backend blends colour with +// SRCALPHA/INVSRCALPHA and alpha with ONE/INVSRCALPHA, which leaves exactly +// the premultiplied BGRA that UpdateLayeredWindow wants. +// +// AC's render thread only (inside EndScene). All resources are released by +// Dispose; nothing is static. +// ============================================================================ + +using System; +using ImGuiNET; +using RynthCore.Engine.D3D9; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.ImGuiBackend; + +internal sealed unsafe class PopOutSurface : IDisposable +{ + private const uint D3DFMT_A8R8G8B8 = 21; + private const uint D3DPOOL_SYSTEMMEM = 2; + private const uint D3DCLEAR_TARGET = 1; + private const uint D3DLOCK_READONLY = 0x10; + + // IDirect3DDevice9 slots not in DeviceVTableIndex. + private const int CreateRenderTargetSlot = 28; + private const int GetRenderTargetDataSlot = 32; + private const int CreateOffscreenPlainSurfaceSlot = 36; + private const int SetDepthStencilSurfaceSlot = 39; + private const int GetDepthStencilSurfaceSlot = 40; + // IDirect3DSurface9 + private const int SurfaceLockRectSlot = 13; + private const int SurfaceUnlockRectSlot = 14; + + private struct Viewport { public uint X, Y, Width, Height; public float MinZ, MaxZ; } + private struct LockedRect { public int Pitch; public IntPtr Bits; } + + /// <summary>Where the panel sits in a picture: its offset and size (px).</summary> + public readonly record struct Placement(int InsetLeft, int InsetTop, int ContentWidth, int ContentHeight); + + private readonly IntPtr[] _targets = new IntPtr[2]; + private readonly Placement[] _placements = new Placement[2]; + private IntPtr _readback; + private int _width, _height; + private int _current; + private bool _previousValid; + private int _failures; + + public int Width => _width; + public int Height => _height; + + /// <summary>Diagnostics (/rc ui snap): the next frame pushed is also written here as a 32-bit BMP.</summary> + public string? SnapshotPath; + + /// <summary> + /// Renders <paramref name="drawData"/> (sized <paramref name="width"/> × + /// <paramref name="height"/>, the panel placed in it at <paramref name="placement"/>) + /// and pushes the latest finished frame to <paramref name="window"/>. False when + /// the device refused (logged, retried next frame). + /// </summary> + public bool Render(IntPtr device, ImDrawDataPtr drawData, int width, int height, Placement placement, LayeredWindow window) + { + if (device == IntPtr.Zero || width <= 0 || height <= 0) return false; + if ((width != _width || height != _height || _targets[0] == IntPtr.Zero) && !Create(device, width, height)) + return false; + + void** vt = *(void***)device; + IntPtr oldTarget = IntPtr.Zero, oldDepth = IntPtr.Zero; + Viewport oldViewport; + ((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr*, int>)vt[DeviceVTableIndex.GetRenderTarget])(device, 0, &oldTarget); + ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr*, int>)vt[GetDepthStencilSurfaceSlot])(device, &oldDepth); + ((delegate* unmanaged[Stdcall]<IntPtr, Viewport*, int>)vt[DeviceVTableIndex.GetViewport])(device, &oldViewport); + try + { + IntPtr target = _targets[_current]; + if (((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, int>)vt[DeviceVTableIndex.SetRenderTarget])(device, 0, target) < 0) + return Fail("SetRenderTarget"); + // Our target can be larger than AC's depth buffer (a pop-out bigger than + // the game window); nothing here uses depth, so unbind it. + ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int>)vt[SetDepthStencilSurfaceSlot])(device, IntPtr.Zero); + ((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, uint, uint, float, uint, int>)vt[DeviceVTableIndex.Clear])( + device, 0, IntPtr.Zero, D3DCLEAR_TARGET, 0x00000000, 1f, 0); + DX9Backend.RenderDrawData(drawData, device); + _placements[_current] = placement; + } + finally + { + // SetRenderTarget resets the viewport to the whole target: put AC's back. + ((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, int>)vt[DeviceVTableIndex.SetRenderTarget])(device, 0, oldTarget); + ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int>)vt[SetDepthStencilSurfaceSlot])(device, oldDepth); + ((delegate* unmanaged[Stdcall]<IntPtr, Viewport*, int>)vt[DeviceVTableIndex.SetViewport])(device, &oldViewport); + ReleaseCom(oldTarget); + ReleaseCom(oldDepth); + } + + // Read back the target the GPU has finished: last frame's, or this one on the first frame. + int read = _previousValid ? 1 - _current : _current; + bool pushed = Push(device, vt, read, window); + _unpushed = read != _current; // this frame's picture is still to be shown + _previousValid = true; + _current = 1 - _current; + return pushed; + } + + private bool _unpushed; + + /// <summary> + /// Shows the last rendered frame if it hasn't been shown yet (the readback + /// runs a frame behind): called on a frame that was skipped because nothing + /// changed. Cheap no-op otherwise. + /// </summary> + public void Flush(IntPtr device, LayeredWindow window) + { + if (!_unpushed || device == IntPtr.Zero || _targets[0] == IntPtr.Zero) return; + _unpushed = false; + Push(device, *(void***)device, 1 - _current, window); + } + + private bool Push(IntPtr device, void** vt, int index, LayeredWindow window) + { + IntPtr target = _targets[index]; + Placement at = _placements[index]; + if (((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, IntPtr, int>)vt[GetRenderTargetDataSlot])(device, target, _readback) < 0) + return Fail("GetRenderTargetData"); + void** svt = *(void***)_readback; + LockedRect locked; + if (((delegate* unmanaged[Stdcall]<IntPtr, LockedRect*, IntPtr, uint, int>)svt[SurfaceLockRectSlot])(_readback, &locked, IntPtr.Zero, D3DLOCK_READONLY) < 0) + return Fail("LockRect"); + try + { + window.Present(locked.Bits, locked.Pitch, _width, _height, at.InsetLeft, at.InsetTop, at.ContentWidth, at.ContentHeight); + if (SnapshotPath != null) + { + string path = SnapshotPath; + SnapshotPath = null; + WriteBmp(path, (byte*)locked.Bits, _width, _height, locked.Pitch); + } + } + finally + { + ((delegate* unmanaged[Stdcall]<IntPtr, int>)svt[SurfaceUnlockRectSlot])(_readback); + } + _failures = 0; + return true; + } + + private static void WriteBmp(string path, byte* bits, int width, int height, int pitch) + { + try + { + int rowBytes = width * 4, imageBytes = rowBytes * height; + using var fs = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write); + using var bw = new System.IO.BinaryWriter(fs); + bw.Write((ushort)0x4D42); bw.Write(54 + imageBytes); bw.Write(0); bw.Write(54); + bw.Write(40); bw.Write(width); bw.Write(-height); bw.Write((ushort)1); bw.Write((ushort)32); + bw.Write(0); bw.Write(imageBytes); bw.Write(2835); bw.Write(2835); bw.Write(0); bw.Write(0); + for (int y = 0; y < height; y++) + bw.Write(new ReadOnlySpan<byte>(bits + (long)y * pitch, rowBytes)); + RynthLog.UI($"PopOutSurface: snapshot {width}x{height} written to {path}."); + } + catch (Exception ex) { RynthLog.UI($"PopOutSurface: snapshot failed: {ex.Message}"); } + } + + private bool Create(IntPtr device, int width, int height) + { + Release(); + void** vt = *(void***)device; + for (int i = 0; i < 2; i++) + { + IntPtr surface = IntPtr.Zero; + int hr = ((delegate* unmanaged[Stdcall]<IntPtr, uint, uint, uint, uint, uint, int, IntPtr*, IntPtr, int>)vt[CreateRenderTargetSlot])( + device, (uint)width, (uint)height, D3DFMT_A8R8G8B8, 0, 0, 0, &surface, IntPtr.Zero); + if (hr < 0 || surface == IntPtr.Zero) { Release(); return Fail($"CreateRenderTarget {width}x{height} hr=0x{hr:X8}"); } + _targets[i] = surface; + } + IntPtr readback = IntPtr.Zero; + int rhr = ((delegate* unmanaged[Stdcall]<IntPtr, uint, uint, uint, uint, IntPtr*, IntPtr, int>)vt[CreateOffscreenPlainSurfaceSlot])( + device, (uint)width, (uint)height, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &readback, IntPtr.Zero); + if (rhr < 0 || readback == IntPtr.Zero) { Release(); return Fail($"CreateOffscreenPlainSurface {width}x{height} hr=0x{rhr:X8}"); } + _readback = readback; + _width = width; + _height = height; + _current = 0; + _previousValid = false; + return true; + } + + private bool Fail(string what) + { + if (_failures++ < 5) + RynthLog.Render($"PopOutSurface: {what} failed; the pop-out keeps its last picture."); + return false; + } + + private void Release() + { + for (int i = 0; i < 2; i++) { ReleaseCom(_targets[i]); _targets[i] = IntPtr.Zero; } + ReleaseCom(_readback); + _readback = IntPtr.Zero; + _width = _height = 0; + _previousValid = false; + } + + private static void ReleaseCom(IntPtr obj) + { + if (obj == IntPtr.Zero) return; + void** vt = *(void***)obj; + ((delegate* unmanaged[Stdcall]<IntPtr, uint>)vt[DeviceVTableIndex.Release])(obj); + } + + public void Dispose() => Release(); +} diff --git a/src/RynthCore.Engine/ImGui/RetailSprites.cs b/src/RynthCore.Engine/ImGui/RetailSprites.cs new file mode 100644 index 0000000..32229e4 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/RetailSprites.cs @@ -0,0 +1,239 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/RetailSprites.cs +// The retail UI's own pictures (0x06 textures in client_portal.dat: window +// backgrounds, title bars, slot frames, meters, scrollbar pieces) as ImGui +// textures, for faces that draw the retail look (the Inventory's Classic view). +// +// Unlike ScriptIcons (item icons, many, least recently drawn evicted) this is a +// small fixed set asked for by id: each picture is decoded once, made into a +// texture once and kept until the engine shuts down or ImGui is torn down (hot +// reload). Nothing is decoded or created per frame once a picture is in. +// +// Threads: +// - AC's render thread: TryGet (inside the ImGui frame), BeginFrame (creates +// the textures decoded since the last frame, at most 16 a frame, before +// anything draws) and Shutdown (releases them all). Only it touches D3D. +// - One worker at a time on the thread pool: reads and decodes the pictures +// from client_portal.dat (AcDatFile / AcIconDecoder, pure code, no AC memory). +// The two meet only in two small queues under one lock. +// +// Bounded: at most 192 pictures, each at most 512 x 512 (the biggest the +// inventory uses is its 300 x 362 background, ~0.4 MB). A picture that isn't +// in the dat or doesn't decode is tried again after 30 s; until then the caller +// draws its own stand-in (TryGet returns false). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using RynthCore.Engine.UI.ScriptWindows; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class RetailSprites +{ + private const int MaxSprites = 192; + private const int MaxCreatesPerFrame = 16; + private static readonly long FailedRetryTicks = Stopwatch.Frequency * 30; + + private sealed class Sprite + { + public IntPtr Ptr; + public bool Pending; + public long FailedAt; + } + + private readonly struct Result + { + public readonly uint Id; + public readonly AcIconImage? Image; + public readonly int Generation; + + public Result(uint id, AcIconImage? image, int generation) + { + Id = id; + Image = image; + Generation = generation; + } + } + + // ── AC's render thread only ────────────────────────────────────────── + private static readonly Dictionary<uint, Sprite> Sprites = new(MaxSprites); + private static readonly List<Result> ResultScratch = new(MaxCreatesPerFrame); + + // ── Shared with the worker, under Sync ─────────────────────────────── + private static readonly object Sync = new(); + private static readonly Queue<(uint Id, int Generation)> Requests = new(MaxSprites); + private static readonly Queue<Result> Results = new(MaxSprites); + private static bool _draining; + private static int _generation; + private static bool _datMissingLogged; + + /// <summary>Pictures that are textures now (diagnostics).</summary> + public static int LiveTextures { get; private set; } + + /// <summary> + /// The texture for a retail UI picture (a 0x06 texture id), once it is in; otherwise + /// false, and the first ask queues its decode. AC's render thread. + /// </summary> + public static bool TryGet(uint textureId, out IntPtr texture) + { + texture = IntPtr.Zero; + if (!AcIconDecoder.IsTextureId(textureId)) return false; + if (!Sprites.TryGetValue(textureId, out Sprite? sprite)) + { + if (Sprites.Count >= MaxSprites) return false; + sprite = new Sprite(); + Sprites[textureId] = sprite; + } + if (sprite.Ptr != IntPtr.Zero) + { + texture = sprite.Ptr; + return true; + } + if (!sprite.Pending && (sprite.FailedAt == 0 || Stopwatch.GetTimestamp() - sprite.FailedAt >= FailedRetryTicks) + && Enqueue(textureId)) + sprite.Pending = true; + return false; + } + + /// <summary> + /// Start of the ImGui frame, before anything draws: turns the pictures decoded since the + /// last frame into textures (at most 16). AC's render thread. + /// </summary> + public static void BeginFrame(IntPtr device) + { + ResultScratch.Clear(); + lock (Sync) + { + while (Results.Count > 0 && ResultScratch.Count < MaxCreatesPerFrame) + ResultScratch.Add(Results.Dequeue()); + } + if (ResultScratch.Count == 0) return; + + long now = Stopwatch.GetTimestamp(); + foreach (Result r in ResultScratch) + { + if (r.Generation != _generation || !Sprites.TryGetValue(r.Id, out Sprite? sprite)) continue; + sprite.Pending = false; + if (sprite.Ptr != IntPtr.Zero) continue; + IntPtr ptr = IntPtr.Zero; + if (r.Image != null) + { + try { ptr = DX9Backend.CreateTextureRgba(device, r.Image.Width, r.Image.Height, r.Image.Pixels); } + catch { ptr = IntPtr.Zero; } + } + if (ptr != IntPtr.Zero) + { + sprite.Ptr = ptr; + sprite.FailedAt = 0; + LiveTextures++; + } + else + { + sprite.FailedAt = now; + } + } + ResultScratch.Clear(); + } + + /// <summary> + /// Engine shutdown or ImGui teardown (hot reload, unload): releases every texture and + /// drops the queues; a worker still running finishes into a generation nobody reads. + /// AC's render thread. + /// </summary> + public static void Shutdown() + { + lock (Sync) + { + _generation++; + Requests.Clear(); + Results.Clear(); + } + foreach (Sprite s in Sprites.Values) + { + if (s.Ptr == IntPtr.Zero) continue; + try { DX9Backend.ReleaseTexture(s.Ptr); } catch { } + s.Ptr = IntPtr.Zero; + } + Sprites.Clear(); + ResultScratch.Clear(); + LiveTextures = 0; + } + + // ── Worker ─────────────────────────────────────────────────────────── + + private static bool Enqueue(uint id) + { + lock (Sync) + { + if (Requests.Count + Results.Count >= MaxSprites) return false; + Requests.Enqueue((id, _generation)); + if (_draining) return true; + _draining = true; + } + try + { + ThreadPool.UnsafeQueueUserWorkItem(static _ => Drain(), null); + } + catch + { + lock (Sync) _draining = false; + } + return true; + } + + /// <summary>The worker: decodes one picture at a time until the queue is empty or the engine stops.</summary> + private static void Drain() + { + AcDatFile? dat = null; + bool datTried = false; + try + { + while (true) + { + (uint Id, int Generation) r; + lock (Sync) + { + if (Requests.Count == 0 || EngineThreads.Stopping) + { + Requests.Clear(); + _draining = false; + return; + } + r = Requests.Dequeue(); + } + + if (!datTried) + { + datTried = true; + string? path = AcDatFile.FindPortalDat(); + string why = "client_portal.dat not found next to acclient.exe"; + if (path != null) dat = AcDatFile.Open(path, out why); + if (dat == null && !_datMissingLogged) + { + _datMissingLogged = true; + RynthLog.UI($"RetailSprites: no retail UI pictures ({why}); panels draw their own stand-ins."); + } + } + + AcIconImage? image = null; + try { image = dat == null ? null : AcIconDecoder.Decode(dat, r.Id, AcIconDecoder.MaxUiSide); } + catch { image = null; } + lock (Sync) + { + if (r.Generation == _generation) Results.Enqueue(new Result(r.Id, image, r.Generation)); + } + } + } + catch + { + lock (Sync) { Requests.Clear(); _draining = false; } + } + finally + { + try { dat?.Dispose(); } catch { } + } + } +} diff --git a/src/RynthCore.Engine/ImGui/RynthTheme.cs b/src/RynthCore.Engine/ImGui/RynthTheme.cs new file mode 100644 index 0000000..4cb174d --- /dev/null +++ b/src/RynthCore.Engine/ImGui/RynthTheme.cs @@ -0,0 +1,143 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/RynthTheme.cs +// Colours and metrics for the ImGui panel faces, taken from the Avalonia +// panels so a docked ImGui face looks like its popped-out Avalonia face +// (docs/IMGUI_PARITY_PLAN.md §4.4). Tokens are ABGR-packed ImGui colours +// (ImGui.GetColorU32 order) built from the Avalonia #AARRGGBB literals. +// +// Apply() sets the base style once at context creation; per-window colours +// (bar, RynthAi, Radar) are pushed around Begin by the panel host. +// ============================================================================ + +using System; +using System.Numerics; +using System.Runtime.InteropServices; +using ImGuiNET; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class RynthTheme +{ + /// <summary>Avalonia #AARRGGBB → ImGui packed colour (0xAABBGGRR).</summary> + public static uint Argb(uint argb) => + (argb & 0xFF00FF00) | ((argb & 0x00FF0000) >> 16) | ((argb & 0x000000FF) << 16); + + public static Vector4 Vec(uint argb) => new( + ((argb >> 16) & 0xFF) / 255f, ((argb >> 8) & 0xFF) / 255f, (argb & 0xFF) / 255f, (argb >> 24) / 255f); + + // ── Bar (AvaloniaOverlay.cs BuildRoot) ───────────────────────────── + public static readonly uint BarBackground = Argb(0xE60A0A14); + public const float BarRounding = 4f; + public static readonly uint BarButton = Argb(0xFF1A2230); + public static readonly uint BarButtonBorder = Argb(0xFF3A4A5A); + public static readonly uint BarText = Argb(0xFFFFFFFF); + public static readonly uint RcLabel = Argb(0xFF90EE90); // LightGreen + public static readonly uint ReloadLabel = Argb(0xFFF0E68C); // Khaki + public static readonly uint PopOutLabel = Argb(0xFF87CEFA); // LightSkyBlue + + // ── Standard panel frame ─────────────────────────────────────────── + public static readonly uint PanelGlass = Argb(0xF212121C); // was D2: the game showed through behind text + public static readonly uint PanelBorder = Argb(0xFF008080); // Teal + public const float PanelRounding = 4f; + public static readonly uint PanelHeader = Argb(0xFF1A1A28); + public static readonly uint DragLabel = Argb(0xFF008080); + public const float HeaderHeight = 24f; + public static readonly uint GripIdle = Argb(0x2026C1A6); + public static readonly uint GripHover = Argb(0x5526C1A6); + public static readonly uint GripGlyph = Argb(0xFF008080); + + // ── RynthAi dashboard ────────────────────────────────────────────── + public static readonly uint RynthAiBackground = Argb(0xF20A0F14); + public static readonly uint RynthAiBorder = Argb(0xFF264059); + public const float RynthAiRounding = 3f; + + // ── Radar ────────────────────────────────────────────────────────── + public static readonly uint RadarGold = Argb(0xFFE6C766); + public static readonly uint RadarGripIdle = Argb(0x400A121A); + public static readonly uint RadarGripHover = Argb(0xA00A121A); + + /// <summary> + /// Base style for every ImGui face, scaled for <paramref name="scale"/> + /// (DPI / 96). AC thread, once, right after the context is created. + /// </summary> + public static void Apply(ImGuiStylePtr style, float scale) + { + ImGuiNET.ImGui.StyleColorsDark(); + + style.WindowRounding = PanelRounding; + style.ChildRounding = 3f; + style.FrameRounding = 2f; + style.PopupRounding = 3f; + style.GrabRounding = 2f; + style.ScrollbarRounding = 3f; + style.WindowBorderSize = 1f; + style.FrameBorderSize = 0f; + style.WindowPadding = new Vector2(6f, 6f); + style.FramePadding = new Vector2(5f, 2f); + style.ItemSpacing = new Vector2(6f, 4f); + style.ScrollbarSize = 12f; + style.WindowMinSize = new Vector2(20f, 20f); + + Set(style, ImGuiCol.Text, 0xFFE6E6E6); + Set(style, ImGuiCol.TextDisabled, 0xFF808080); + Set(style, ImGuiCol.WindowBg, 0xD212121C); + Set(style, ImGuiCol.ChildBg, 0x00000000); + Set(style, ImGuiCol.PopupBg, 0xF214141E); + Set(style, ImGuiCol.Border, 0xFF008080); + Set(style, ImGuiCol.FrameBg, 0xFF1A2230); + Set(style, ImGuiCol.FrameBgHovered, 0xFF243044); + Set(style, ImGuiCol.FrameBgActive, 0xFF2C3A52); + Set(style, ImGuiCol.TitleBg, 0xFF1A1A28); + Set(style, ImGuiCol.TitleBgActive, 0xFF1A1A28); + Set(style, ImGuiCol.Button, 0xFF1A2230); + Set(style, ImGuiCol.ButtonHovered, 0xFF2A3850); + Set(style, ImGuiCol.ButtonActive, 0xFF34466A); + Set(style, ImGuiCol.Header, 0xFF1A2230); + Set(style, ImGuiCol.HeaderHovered, 0xFF2A3850); + Set(style, ImGuiCol.HeaderActive, 0xFF34466A); + Set(style, ImGuiCol.CheckMark, 0xFF26C1A6); + Set(style, ImGuiCol.SliderGrab, 0xFF26A18C); + Set(style, ImGuiCol.SliderGrabActive, 0xFF26C1A6); + Set(style, ImGuiCol.Separator, 0x503A4A5A); + Set(style, ImGuiCol.ResizeGrip, 0x2026C1A6); + Set(style, ImGuiCol.ResizeGripHovered, 0x5526C1A6); + Set(style, ImGuiCol.ResizeGripActive, 0x8026C1A6); + Set(style, ImGuiCol.ScrollbarBg, 0x40000000); + Set(style, ImGuiCol.ScrollbarGrab, 0xFF2A3850); + Set(style, ImGuiCol.TableHeaderBg, 0xFF1A1A28); + Set(style, ImGuiCol.TableBorderStrong, 0xFF3A4A5A); + Set(style, ImGuiCol.TableBorderLight, 0x503A4A5A); + Set(style, ImGuiCol.TableRowBgAlt, 0x10FFFFFF); + Set(style, ImGuiCol.ModalWindowDimBg, 0x00000000); + + if (scale != 1f) + style.ScaleAllSizes(scale); + } + + private static void Set(ImGuiStylePtr style, ImGuiCol col, uint argb) => style.Colors[(int)col] = Vec(argb); +} + +/// <summary>DPI scale for the ImGui faces.</summary> +internal static class UiScale +{ + [DllImport("user32.dll")] + private static extern uint GetDpiForWindow(IntPtr hwnd); + + /// <summary> + /// GetDpiForWindow(game) / 96, at least 1. For a DPI-unaware acclient this + /// is 1 (Windows scales the whole window); ImGui then works in the same + /// client pixels AC does. + /// </summary> + public static float ForWindow(IntPtr hwnd) + { + try + { + uint dpi = hwnd != IntPtr.Zero ? GetDpiForWindow(hwnd) : 0; + return dpi > 0 ? Math.Max(1f, dpi / 96f) : 1f; + } + catch (EntryPointNotFoundException) + { + return 1f; // pre-1607 Windows 10 + } + } +} diff --git a/src/RynthCore.Engine/ImGui/ScriptIcons.cs b/src/RynthCore.Engine/ImGui/ScriptIcons.cs new file mode 100644 index 0000000..d2db463 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ScriptIcons.cs @@ -0,0 +1,451 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ScriptIcons.cs +// Script windows: the D3D9 texture cache behind the Image / ImageButton ops. +// An icon is asked for by kind and id: an icon (0x06 texture) id, an object id +// (the item's icon with its underlay and overlay) or a spell id (the spell's +// icon). Design: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §9 (icons). +// +// Threads: +// - AC's render thread: TryGet (from the replay), BeginFrame (creates the +// textures decoded since the last frame, at most 8 a frame, and evicts the +// least recently drawn ones over the cap) and Shutdown (releases them all). +// Only this thread touches D3D. +// - One worker at a time on the thread pool: resolves an object's icon ids +// from the engine's PWD snapshot (ClientObjectHooks, the off-thread path: +// no AC memory), a spell's icon from the portal spell table, and decodes +// and stacks the pictures from client_portal.dat (AcIconDecoder). Nothing +// it does touches AC or D3D. +// The two meet only in two small queues under one lock. +// +// Bounded: about 256 textures kept (32 x 32 icons: 4 KB each, twice with the +// managed pool's system copy), 8 MB of pixels at most (a picture is at most +// 128 x 128), 2048 remembered ids, 128 requests in flight. What was drawn in +// the last frame is never evicted (so a hud showing more icons than the cap +// doesn't thrash); past the byte budget a new picture stays a placeholder. +// Eviction and creation run at the start of the frame, before anything is +// drawn, so a texture is never released while a draw list still points at it +// (every draw list of the frames before has been rendered by then). Shutdown +// (engine unload, hot reload) releases every texture and drops the queues; +// results of an older generation are thrown away. +// +// A missing, not yet decoded or undecodable icon draws a placeholder (the +// replay's job); nothing here throws into the replay. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.ImGuiBackend.Hud; +using RynthCore.Engine.UI.ScriptWindows; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class ScriptIcons +{ + public const int MaxTextures = 256; + private const long MaxLiveBytes = 8L * 1024 * 1024; + private const int MaxSlots = 2048; + private const int MaxCreatesPerFrame = 8; + private const int MaxPendingRequests = 128; + + private static readonly long ObjectRefreshTicks = Stopwatch.Frequency * 2; // enchantment overlays etc. change + private static readonly long UnresolvedRetryTicks = Stopwatch.Frequency; // an object not seen yet, a spell table still loading + private static readonly long FailedRetryTicks = Stopwatch.Frequency * 30; // an icon that didn't decode + private static readonly long BudgetRetryTicks = Stopwatch.Frequency * 2; // no room in the byte budget + + private const uint StypeIcon = 8, StypeIconOverlay = 50, StypeIconUnderlay = 52; + + /// <summary>What one picture is made of: icon, underlay and overlay texture ids (0 = none).</summary> + private readonly record struct Layers(uint Icon, uint Underlay, uint Overlay); + + /// <summary>One asked-for (kind, id): the layers it resolved to.</summary> + private sealed class Slot + { + public Layers Layers; + public bool Resolved; + public bool Pending; + public long ResolvedAt; + public int LastUsed; + } + + /// <summary>One picture's texture (or why it has none yet).</summary> + private sealed class Texture + { + public IntPtr Ptr; + public int Bytes; + public bool Pending; + public long FailedAt; + /// <summary>How long after FailedAt to try again.</summary> + public long RetryTicks; + public int LastUsed; + } + + private enum Work : byte { Resolve, Decode } + + private readonly struct Request + { + public readonly Work Work; + public readonly ScriptIconKind Kind; + public readonly uint Id; + public readonly Layers Layers; + public readonly int Generation; + + public Request(Work work, ScriptIconKind kind, uint id, Layers layers, int generation) + { + Work = work; + Kind = kind; + Id = id; + Layers = layers; + Generation = generation; + } + } + + private readonly struct Result + { + public readonly Work Work; + public readonly ulong SlotKey; + public readonly Layers Layers; + public readonly bool Ok; + public readonly AcIconImage? Image; + public readonly int Generation; + + public Result(Work work, ulong slotKey, Layers layers, bool ok, AcIconImage? image, int generation) + { + Work = work; + SlotKey = slotKey; + Layers = layers; + Ok = ok; + Image = image; + Generation = generation; + } + } + + // ── AC's render thread only ────────────────────────────────────────── + private static readonly Dictionary<ulong, Slot> Slots = new(256); + private static readonly Dictionary<Layers, Texture> Textures = new(MaxTextures); + private static readonly List<(int LastUsed, Layers Key)> EvictScratch = new(MaxTextures); + private static readonly List<ulong> SlotScratch = new(); + private static readonly List<Result> ResultScratch = new(MaxCreatesPerFrame); + private static int _frame; + private static int _live; + private static long _liveBytes; + + // ── Shared with the worker, under Sync ─────────────────────────────── + private static readonly object Sync = new(); + private static readonly Queue<Request> Requests = new(MaxPendingRequests); + private static readonly Queue<Result> Results = new(MaxPendingRequests); + private static bool _draining; + private static int _generation; + private static bool _datMissingLogged; + + /// <summary>Textures alive now (diagnostics).</summary> + public static int LiveTextures => _live; + + private static ulong SlotKey(ScriptIconKind kind, uint id) => ((ulong)kind << 32) | id; + + /// <summary> + /// The texture for an icon, if it is ready; otherwise false and, when needed, the work to + /// get it is queued (the replay draws a placeholder meanwhile). AC's render thread. + /// </summary> + public static bool TryGet(ScriptIconKind kind, uint id, out IntPtr texture) + { + texture = IntPtr.Zero; + if (kind > ScriptIconKind.Spell || id == 0) return false; + long now = Stopwatch.GetTimestamp(); + + ulong key = SlotKey(kind, id); + if (!Slots.TryGetValue(key, out Slot? slot)) + { + if (Slots.Count >= MaxSlots) PruneSlots(); + slot = new Slot(); + if (kind == ScriptIconKind.Icon) + { + slot.Layers = new Layers(AcIconDecoder.NormalizeIconId(id), 0, 0); + slot.Resolved = true; + } + Slots[key] = slot; + } + slot.LastUsed = _frame; + + // Objects are looked up again every 2 s (an overlay can change); a spell's icon never + // changes; an id that didn't resolve is tried again after a second. + if (kind != ScriptIconKind.Icon && !slot.Pending) + { + bool due = !slot.Resolved + ? slot.ResolvedAt == 0 || now - slot.ResolvedAt >= UnresolvedRetryTicks + : kind == ScriptIconKind.Object && now - slot.ResolvedAt >= ObjectRefreshTicks; + if (due && Enqueue(new Request(Work.Resolve, kind, id, default, _generation))) + slot.Pending = true; + } + if (!slot.Resolved) return false; + + if (!Textures.TryGetValue(slot.Layers, out Texture? tex)) + { + tex = new Texture(); + Textures[slot.Layers] = tex; + } + tex.LastUsed = _frame; + if (tex.Ptr != IntPtr.Zero) + { + texture = tex.Ptr; + return true; + } + if (!tex.Pending && (tex.FailedAt == 0 || now - tex.FailedAt >= tex.RetryTicks) + && Enqueue(new Request(Work.Decode, kind, id, slot.Layers, _generation))) + tex.Pending = true; + return false; + } + + /// <summary> + /// Start of the ImGui frame, before anything draws: creates the textures decoded since + /// the last frame (at most 8) and evicts the least recently drawn ones over the cap. + /// AC's render thread. + /// </summary> + public static void BeginFrame(IntPtr device) + { + _frame++; + ResultScratch.Clear(); + lock (Sync) + { + int creates = 0; + while (Results.Count > 0) + { + // Decodes wait their turn once 8 textures were made this frame; lookups don't. + if (Results.Peek().Work == Work.Decode && creates >= MaxCreatesPerFrame) break; + Result r = Results.Dequeue(); + if (r.Work == Work.Decode) creates++; + ResultScratch.Add(r); + } + } + if (ResultScratch.Count == 0 && Textures.Count <= MaxTextures) return; + + long now = Stopwatch.GetTimestamp(); + foreach (Result r in ResultScratch) + { + if (r.Generation != _generation) continue; + if (r.Work == Work.Resolve) + { + if (!Slots.TryGetValue(r.SlotKey, out Slot? slot)) continue; + slot.Pending = false; + slot.ResolvedAt = now; + // A lookup that failed keeps the last picture (an object briefly out of the + // snapshot shouldn't blink); a slot that never resolved stays a placeholder. + if (r.Ok) + { + slot.Layers = r.Layers; + slot.Resolved = true; + } + continue; + } + + if (!Textures.TryGetValue(r.Layers, out Texture? tex)) continue; // evicted meanwhile + tex.Pending = false; + if (tex.Ptr != IntPtr.Zero) continue; + IntPtr ptr = IntPtr.Zero; + int bytes = r.Image == null ? 0 : r.Image.Width * r.Image.Height * 4; + bool room = r.Image != null && (_liveBytes + bytes <= MaxLiveBytes || Evict(bytes)); + if (room) + { + try { ptr = DX9Backend.CreateTextureRgba(device, r.Image!.Width, r.Image.Height, r.Image.Pixels); } + catch { ptr = IntPtr.Zero; } + } + if (ptr != IntPtr.Zero) + { + tex.Ptr = ptr; + tex.Bytes = bytes; + tex.FailedAt = 0; + _live++; + _liveBytes += bytes; + } + else + { + // Didn't decode (try again much later), or no room yet (soon). + tex.FailedAt = now; + tex.RetryTicks = r.Image != null && !room ? BudgetRetryTicks : FailedRetryTicks; + } + } + ResultScratch.Clear(); + + if (Textures.Count > MaxTextures) Evict(0); + } + + /// <summary> + /// Drops the least recently drawn pictures that weren't drawn in the last frame: until at most + /// MaxTextures remain and, for <paramref name="needBytes"/> > 0, until that many more bytes + /// fit the budget. Returns whether they fit. + /// </summary> + private static bool Evict(int needBytes) + { + EvictScratch.Clear(); + foreach (var kv in Textures) + if (!kv.Value.Pending && kv.Value.LastUsed < _frame - 1) + EvictScratch.Add((kv.Value.LastUsed, kv.Key)); + EvictScratch.Sort((a, b) => a.LastUsed.CompareTo(b.LastUsed)); + for (int i = 0; i < EvictScratch.Count; i++) + { + bool overCount = Textures.Count > MaxTextures; + bool overBytes = needBytes > 0 && _liveBytes + needBytes > MaxLiveBytes; + if (!overCount && !overBytes) break; + if (Textures.Remove(EvictScratch[i].Key, out Texture? tex) && tex.Ptr != IntPtr.Zero) + { + try { DX9Backend.ReleaseTexture(tex.Ptr); } catch { } + _live--; + _liveBytes -= tex.Bytes; + } + } + EvictScratch.Clear(); + return _liveBytes + needBytes <= MaxLiveBytes; + } + + /// <summary>Forgets the ids not drawn for the longest (their textures stay until evicted).</summary> + private static void PruneSlots() + { + SlotScratch.Clear(); + int keepAfter = _frame - 600; // ~10 s at 60 fps + foreach (var kv in Slots) + if (!kv.Value.Pending && kv.Value.LastUsed < keepAfter) SlotScratch.Add(kv.Key); + if (SlotScratch.Count == 0) + foreach (var kv in Slots) + if (!kv.Value.Pending) SlotScratch.Add(kv.Key); // every one is recent: start over + foreach (ulong k in SlotScratch) Slots.Remove(k); + SlotScratch.Clear(); + } + + /// <summary> + /// Engine shutdown or ImGui teardown (hot reload, unload): releases every texture and drops + /// the queues; a worker still running finishes into a generation nobody reads. AC's render thread. + /// </summary> + public static void Shutdown() + { + lock (Sync) + { + _generation++; + Requests.Clear(); + Results.Clear(); + } + foreach (Texture t in Textures.Values) + { + if (t.Ptr == IntPtr.Zero) continue; + try { DX9Backend.ReleaseTexture(t.Ptr); } catch { } + t.Ptr = IntPtr.Zero; + } + Textures.Clear(); + Slots.Clear(); + EvictScratch.Clear(); + ResultScratch.Clear(); + _live = 0; + _liveBytes = 0; + } + + // ── Worker ─────────────────────────────────────────────────────────── + + /// <summary>Queues work for the worker (starting it when idle). False when too much is in flight.</summary> + private static bool Enqueue(Request r) + { + lock (Sync) + { + if (Requests.Count + Results.Count >= MaxPendingRequests) return false; + Requests.Enqueue(r); + if (_draining) return true; + _draining = true; + } + try + { + ThreadPool.UnsafeQueueUserWorkItem(static _ => Drain(), null); + } + catch + { + lock (Sync) _draining = false; + } + return true; + } + + /// <summary>The worker: one request at a time until the queue is empty or the engine stops.</summary> + private static void Drain() + { + AcDatFile? dat = null; + bool datTried = false; + try + { + while (true) + { + Request r; + lock (Sync) + { + if (Requests.Count == 0 || EngineThreads.Stopping) + { + Requests.Clear(); + _draining = false; + return; + } + r = Requests.Dequeue(); + } + + Result result; + try + { + result = r.Work == Work.Resolve ? ResolveNow(r) : DecodeNow(r, ref dat, ref datTried); + } + catch + { + result = new Result(r.Work, SlotKey(r.Kind, r.Id), r.Layers, false, null, r.Generation); + } + lock (Sync) + { + if (r.Generation == _generation) Results.Enqueue(result); + } + } + } + catch + { + lock (Sync) { Requests.Clear(); _draining = false; } + } + finally + { + try { dat?.Dispose(); } catch { } + } + } + + /// <summary>An object's icon, underlay and overlay (PWD snapshot, no AC memory), or a spell's icon.</summary> + private static Result ResolveNow(Request r) + { + ulong key = SlotKey(r.Kind, r.Id); + if (r.Kind == ScriptIconKind.Object) + { + // Off AC's main thread these read the 10 Hz main-thread PWD snapshot. + if (!ClientObjectHooks.TryGetObjectDataIdProperty(r.Id, StypeIcon, out uint icon) || icon == 0) + return new Result(Work.Resolve, key, default, false, null, r.Generation); + ClientObjectHooks.TryGetObjectDataIdProperty(r.Id, StypeIconUnderlay, out uint under); + ClientObjectHooks.TryGetObjectDataIdProperty(r.Id, StypeIconOverlay, out uint over); + return new Result(Work.Resolve, key, new Layers(icon, under, over), true, null, r.Generation); + } + if (r.Kind == ScriptIconKind.Spell) + { + PortalSpellTable.EnsureLoadQueued(); + bool ok = PortalSpellTable.TryGetIcon(r.Id, out uint icon) && icon != 0; + return new Result(Work.Resolve, key, ok ? new Layers(icon, 0, 0) : default, ok, null, r.Generation); + } + return new Result(Work.Resolve, key, new Layers(AcIconDecoder.NormalizeIconId(r.Id), 0, 0), true, null, r.Generation); + } + + private static Result DecodeNow(Request r, ref AcDatFile? dat, ref bool datTried) + { + ulong key = SlotKey(r.Kind, r.Id); + if (!datTried) + { + datTried = true; + string? path = AcDatFile.FindPortalDat(); + string why = "client_portal.dat not found next to acclient.exe"; + if (path != null) dat = AcDatFile.Open(path, out why); + if (dat == null && !_datMissingLogged) + { + _datMissingLogged = true; + RynthLog.UI($"ScriptIcons: no icons ({why}); script windows draw placeholders."); + } + } + AcIconImage? image = dat == null ? null : AcIconDecoder.Compose(dat, r.Layers.Icon, r.Layers.Underlay, r.Layers.Overlay); + return new Result(Work.Decode, key, r.Layers, image != null, image, r.Generation); + } +} diff --git a/src/RynthCore.Engine/ImGui/ScriptWindowReplay.cs b/src/RynthCore.Engine/ImGui/ScriptWindowReplay.cs new file mode 100644 index 0000000..6a22324 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ScriptWindowReplay.cs @@ -0,0 +1,839 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ScriptWindowReplay.cs +// Script windows (API v71): the op interpreter. Replays a window's latest +// DisplayList with real ImGui calls every frame and turns what ImGui did +// into events for the owner (clicks, new values, text, open states). +// Design: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §2.5-2.7, §4.2, §6.3. +// +// AC's thread only, inside the panel host's window and try/catch. No +// allocation on a frame without input: ops are pre-parsed, strings are pinned +// NUL-terminated UTF-8 handed to cimgui as byte pointers. +// +// Safety: +// - Script text never reaches cimgui as a format string: TextUnformatted +// for every text op (colour / wrap / bullet done with pushes around it), +// LabelText's text was stored with '%' doubled, SeparatorText takes a +// label, slider formats were validated by the parser. +// - The engine owns every Begin/End and Push/Pop. Scopes are an explicit +// stack (no recursion): leftover PushIDs / PushStyleColors are popped at +// the end of their scope, then TreePop / EndChild. An exception mid-list +// unwinds every open scope in a finally before it propagates to +// ImGuiPanelHost.DrawBody, so ImGui's stacks stay balanced. +// - Icons (Image / ImageButton, op level 2) are ids: ScriptIcons turns them +// into cached D3D9 textures; until one is ready, or when it is missing, +// a dim placeholder square of the same size draws (the font atlas's white +// pixel), so a bad id never throws. +// - Sizes and offsets in ops are logical at UI scale 1: multiplied by +// S = EngineFrameController.FontScale here (the sign is kept, so 0 = auto +// and -1 = fill still work). +// +// Measurements (Phase 0): replay cost per frame and the input -> reaction +// latency are logged every ~10 s while a script window is open +// ("ScriptWindows replay:" lines, UI tag). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.ScriptWindows; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static unsafe class ScriptWindowReplay +{ + private const byte ScopeRoot = 0, ScopeChild = 1, ScopeTree = 2; + + /// <summary>One open scope: the root body, a Child or an open TreeNode.</summary> + private struct Scope + { + public byte Kind; + /// <summary>A CollapsingHeader the player just closed: drawing ops are skipped until the next header.</summary> + public bool Skip; + /// <summary>The op index just past the scope's last child.</summary> + public int End; + public int Ids; + public int Colors; + } + + // AC thread only. Root + at most MaxDepth nested blocks. + private static readonly Scope[] Scopes = new Scope[DisplayListParser.MaxDepth + 1]; + private static int _frame = int.MinValue; + private static int _frameOps; + + private static readonly Vector4 ErrorColor = new(1f, 0.4f, 0.3f, 1f); + + /// <summary>Draws <paramref name="w"/>'s latest list into the current window. AC thread.</summary> + public static void Draw(ScriptWindow w) + { + int frame = ImGuiNative.igGetFrameCount(); + if (frame != _frame) + { + _frame = frame; + _frameOps = 0; + } + + DisplayList list = w.List; + long t0 = Stopwatch.GetTimestamp(); + DrawError(w); + + int ops = 0; + bool over = false; + int budget = ScriptWindowRegistry.MaxReplayOpsPerFrame - _frameOps; + if (list.OpCount > 0 && budget <= 0) + over = true; + else if (list.OpCount > 0) + { + ops = Replay(w, list, frame, budget, out over); + _frameOps += ops; + } + if (over) + { + // Over the per-frame budget for all script windows together. + ReadOnlySpan<byte> msg = "Too large to draw this frame."u8; + fixed (byte* m = msg) ImGuiNative.igTextUnformatted(m, m + msg.Length); + } + long elapsed = Stopwatch.GetTimestamp() - t0; + + // First frame this list is on screen: if it was recorded after the owner applied the + // pending input, that input has had its reaction. + if (!ReferenceEquals(list, w.LastReplayed)) + { + w.LastReplayed = list; + w.Locals.PruneIfLarge(frame); + if (w.PendingInputSeq != 0 && list.AckSeq >= w.PendingInputSeq) + { + ScriptWindowStats.Reaction(w, frame - w.PendingInputFrame, Stopwatch.GetTimestamp() - w.PendingInputTicks); + w.PendingInputSeq = 0; + } + } + ScriptWindowStats.Replay(frame, elapsed, ops); + } + + /// <summary>The script's error (HasError) in red, wrapped at the window edge, above the list.</summary> + private static void DrawError(ScriptWindow w) + { + if ((w.Flags & WindowFlags.HasError) == 0) return; + byte[]? err = w.ErrorUtf8; + if (err == null || err.Length < 1) return; + ImGuiNative.igPushStyleColor_Vec4(ImGuiCol.Text, ErrorColor); + ImGuiNative.igPushTextWrapPos(0f); + try + { + fixed (byte* e = err) ImGuiNative.igTextUnformatted(e, e + err.Length - 1); + } + finally + { + ImGuiNative.igPopTextWrapPos(); + ImGuiNative.igPopStyleColor(1); + } + ImGuiNative.igSeparator(); + } + + /// <summary> + /// Walks the ops with an explicit scope stack. Returns the ops visited; <paramref name="over"/> + /// is set when the per-frame budget ran out before the list ended (the rest isn't drawn). + /// </summary> + private static int Replay(ScriptWindow w, DisplayList list, int frame, int budget, out bool over) + { + over = false; + int n = list.OpCount; + ReplayOp[] ops = list.Ops; + float s = EngineFrameController.FontScale; + if (!(s > 0f) || !float.IsFinite(s)) s = 1f; + uint ack = list.AckSeq; + ScriptLocals locals = w.Locals; + ScriptEventQueue events = w.Owner.Events; + int visited = 0; + int open = 0; // scopes whose closing calls are still owed + + fixed (byte* pool = list.Pool) + { + try + { + Scopes[0] = new Scope { Kind = ScopeRoot, End = n }; + open = 1; + int i = 0; + while (open > 0) + { + ref Scope sc = ref Scopes[open - 1]; + if (i >= sc.End) + { + open--; + CloseScope(ref sc); + continue; + } + if (visited >= budget) { over = true; break; } + visited++; + + ref ReplayOp op = ref ops[i]; + if (sc.Skip) + { + if (op.Code == ScriptOp.CollapsingHeader) sc.Skip = false; + else if (op.Code is not (ScriptOp.PushID or ScriptOp.PopID or ScriptOp.PushStyleColor or ScriptOp.PopStyleColor)) + { + // IDs and colours still run, so the ID stack after the next header is right. + i = op.EndIndex; + continue; + } + } + + int next = i + 1; + byte* str = op.Str >= 0 ? pool + op.Str : null; + switch (op.Code) + { + // ── Text ────────────────────────────────────────── + case ScriptOp.Text: + ImGuiNative.igTextUnformatted(str, str + op.StrLen); + break; + case ScriptOp.TextColored: + ImGuiNative.igPushStyleColor_U32(ImGuiCol.Text, op.Color); + try { ImGuiNative.igTextUnformatted(str, str + op.StrLen); } + finally { ImGuiNative.igPopStyleColor(1); } + break; + case ScriptOp.TextWrapped: + ImGuiNative.igPushTextWrapPos(0f); + try { ImGuiNative.igTextUnformatted(str, str + op.StrLen); } + finally { ImGuiNative.igPopTextWrapPos(); } + break; + case ScriptOp.TextDisabled: + { + Vector4 disabled = *ImGuiNative.igGetStyleColorVec4(ImGuiCol.TextDisabled); + ImGuiNative.igPushStyleColor_Vec4(ImGuiCol.Text, disabled); + try { ImGuiNative.igTextUnformatted(str, str + op.StrLen); } + finally { ImGuiNative.igPopStyleColor(1); } + break; + } + case ScriptOp.BulletText: + ImGuiNative.igBullet(); + ImGuiNative.igTextUnformatted(str, str + op.StrLen); + break; + case ScriptOp.SeparatorText: + ImGuiNative.igSeparatorText(str); // a label, not a format + break; + case ScriptOp.LabelText: + ImGuiNative.igLabelText(str, pool + op.Str2); // text stored with '%' doubled + break; + + // ── Layout ──────────────────────────────────────── + case ScriptOp.Separator: + ImGuiNative.igSeparator(); + break; + case ScriptOp.SameLine: + ImGuiNative.igSameLine(op.A * s, op.B < 0f ? -1f : op.B * s); + break; + case ScriptOp.NewLine: + ImGuiNative.igNewLine(); + break; + case ScriptOp.Spacing: + ImGuiNative.igSpacing(); + break; + case ScriptOp.Dummy: + ImGuiNative.igDummy(new Vector2(op.A * s, op.B * s)); + break; + case ScriptOp.Indent: + ImGuiNative.igIndent(op.A * s); + break; + case ScriptOp.Unindent: + ImGuiNative.igUnindent(op.A * s); + break; + + // ── Widgets ─────────────────────────────────────── + case ScriptOp.Button: + { + byte clicked = op.Flag != 0 + ? ImGuiNative.igSmallButton(str) + : ImGuiNative.igButton(str, new Vector2(op.A * s, op.B * s)); + if (clicked != 0) + w.NoteInput(events.Click(w.Hash, op.Key), frame); + break; + } + case ScriptOp.Checkbox: + { + bool had = locals.Bools.TryGet(op.Key, ack, out bool local); + byte v = had ? (local ? (byte)1 : (byte)0) : op.Flag; + bool changed = ImGuiNative.igCheckbox(str, &v) != 0; + bool active = ImGuiNative.igIsItemActive() != 0; + uint seq = 0; + if (changed) + { + seq = events.Bool(w.Hash, op.Key, v != 0); + w.NoteInput(seq, frame); + } + locals.Bools.After(op.Key, had, changed, v != 0, seq, active, frame); + break; + } + case ScriptOp.SliderInt: + { + bool had = locals.Ints.TryGet(op.Key, ack, out int local); + int v = had ? local : op.I0; + bool changed = ImGuiNative.igSliderInt(str, &v, op.I1, op.I2, pool + op.Str2, ImGuiSliderFlags.AlwaysClamp) != 0; + bool active = ImGuiNative.igIsItemActive() != 0; + uint seq = 0; + if (changed) + { + seq = events.Int(w.Hash, op.Key, v); + w.NoteInput(seq, frame); + } + locals.Ints.After(op.Key, had, changed, v, seq, active, frame); + break; + } + case ScriptOp.SliderFloat: + { + bool had = locals.Floats.TryGet(op.Key, ack, out float local); + float v = had ? local : op.A; + bool changed = ImGuiNative.igSliderFloat(str, &v, op.B, op.C, pool + op.Str2, ImGuiSliderFlags.AlwaysClamp) != 0; + bool active = ImGuiNative.igIsItemActive() != 0; + uint seq = 0; + if (changed && float.IsFinite(v)) + { + seq = events.Float(w.Hash, op.Key, v); + w.NoteInput(seq, frame); + } + else changed = false; + locals.Floats.After(op.Key, had, changed, v, seq, active, frame); + break; + } + case ScriptOp.Combo: + { + bool had = locals.Ints.TryGet(op.Key, ack, out int local); + int v = had ? local : op.I0; + bool changed = ImGuiNative.igCombo_Str(str, &v, pool + op.Str2, -1) != 0; + bool active = ImGuiNative.igIsItemActive() != 0; + uint seq = 0; + if (changed) + { + seq = events.Int(w.Hash, op.Key, v); + w.NoteInput(seq, frame); + } + locals.Ints.After(op.Key, had, changed, v, seq, active, frame); + break; + } + case ScriptOp.InputText: + ReplayInputText(w, ref op, str, pool, ack, frame); + break; + case ScriptOp.Selectable: + if (ImGuiNative.igSelectable_Bool(str, op.Flag, (ImGuiSelectableFlags)op.Flags, new Vector2(op.A * s, op.B * s)) != 0) + w.NoteInput(events.Click(w.Hash, op.Key), frame); + break; + case ScriptOp.ProgressBar: + ImGuiNative.igProgressBar(op.A, new Vector2(op.B * s, op.C * s), op.Str2 >= 0 ? pool + op.Str2 : null); + break; + + // ── Icons and number inputs (op level 2) ────────── + case ScriptOp.Image: + { + var size = new Vector2(op.A * s, op.B * s); + if (ScriptIcons.TryGet((ScriptIconKind)op.Flag, unchecked((uint)op.I0), out IntPtr tex)) + ImGuiNative.igImage(tex, size, new Vector2(op.C, op.D), new Vector2(op.E, op.F), Rgba(op.Color), Rgba(op.Color2)); + else + Placeholder(size, Rgba(op.Color2)); + break; + } + case ScriptOp.ImageButton: + { + var size = new Vector2(op.A * s, op.B * s); + byte clicked; + if (ScriptIcons.TryGet((ScriptIconKind)op.Flag, unchecked((uint)op.I0), out IntPtr tex)) + clicked = ImGuiNative.igImageButton(str, tex, size, new Vector2(op.C, op.D), new Vector2(op.E, op.F), Rgba(op.Color), Rgba(op.Color2)); + else + { + // The same button (same ID, size and frame) with the placeholder inside. + WhitePixel(out IntPtr white, out Vector2 uv); + clicked = ImGuiNative.igImageButton(str, white, size, uv, uv, Rgba(op.Color), PlaceholderFill); + } + if (clicked != 0) + w.NoteInput(events.Click(w.Hash, op.Key), frame); + break; + } + case ScriptOp.InputInt: + { + bool had = locals.Ints.TryGet(op.Key, ack, out int local); + int v = had ? local : op.I0; + bool changed = ImGuiNative.igInputInt(str, &v, op.I1, op.I2, (ImGuiInputTextFlags)op.Flags) != 0; + bool active = ImGuiNative.igIsItemActive() != 0; + if (active) ImGuiTextFocus.NoteActive("number box"); + uint seq = 0; + if (changed) + { + seq = events.Int(w.Hash, op.Key, v); + w.NoteInput(seq, frame); + } + locals.Ints.After(op.Key, had, changed, v, seq, active, frame); + break; + } + case ScriptOp.InputFloat: + { + bool had = locals.Floats.TryGet(op.Key, ack, out float local); + float v = had ? local : op.A; + bool changed = ImGuiNative.igInputFloat(str, &v, op.B, op.C, pool + op.Str2, (ImGuiInputTextFlags)op.Flags) != 0; + bool active = ImGuiNative.igIsItemActive() != 0; + if (active) ImGuiTextFocus.NoteActive("number box"); + uint seq = 0; + if (changed && float.IsFinite(v)) + { + seq = events.Float(w.Hash, op.Key, v); + w.NoteInput(seq, frame); + } + else changed = false; + locals.Floats.After(op.Key, had, changed, v, seq, active, frame); + break; + } + case ScriptOp.DragInt: + { + bool had = locals.Ints.TryGet(op.Key, ack, out int local); + int v = had ? local : op.I0; + bool changed = ImGuiNative.igDragInt(str, &v, op.D, op.I1, op.I2, pool + op.Str2, (ImGuiSliderFlags)op.Flags) != 0; + bool active = ImGuiNative.igIsItemActive() != 0; + uint seq = 0; + if (changed) + { + seq = events.Int(w.Hash, op.Key, v); + w.NoteInput(seq, frame); + } + locals.Ints.After(op.Key, had, changed, v, seq, active, frame); + break; + } + case ScriptOp.DragFloat: + { + bool had = locals.Floats.TryGet(op.Key, ack, out float local); + float v = had ? local : op.A; + bool changed = ImGuiNative.igDragFloat(str, &v, op.D, op.B, op.C, pool + op.Str2, (ImGuiSliderFlags)op.Flags) != 0; + bool active = ImGuiNative.igIsItemActive() != 0; + uint seq = 0; + if (changed && float.IsFinite(v)) + { + seq = events.Float(w.Hash, op.Key, v); + w.NoteInput(seq, frame); + } + else changed = false; + locals.Floats.After(op.Key, had, changed, v, seq, active, frame); + break; + } + + // ── IDs, style, tooltips ────────────────────────── + case ScriptOp.PushID: + if (op.Flag == 0) ImGuiNative.igPushID_Str(str); + else ImGuiNative.igPushID_Int(op.I0); + sc.Ids++; + break; + case ScriptOp.PopID: + if (sc.Ids > 0) + { + sc.Ids--; + ImGuiNative.igPopID(); + } + break; + case ScriptOp.PushStyleColor: + ImGuiNative.igPushStyleColor_U32((ImGuiCol)op.Aux, op.Color); + sc.Colors++; + break; + case ScriptOp.PopStyleColor: + { + int count = Math.Min((int)op.Aux, sc.Colors); + if (count > 0) + { + sc.Colors -= count; + ImGuiNative.igPopStyleColor(count); + } + break; + } + case ScriptOp.SetItemTooltip: + if (ImGuiNative.igIsItemHovered(ImGuiHoveredFlags.ForTooltip) != 0 && ImGuiNative.igBeginTooltip() != 0) + { + try { ImGuiNative.igTextUnformatted(str, str + op.StrLen); } + finally { ImGuiNative.igEndTooltip(); } + } + break; + + // ── Containers ──────────────────────────────────── + case ScriptOp.Child: + { + ImGuiChildFlags childFlags = op.Flag != 0 ? ImGuiChildFlags.Borders : ImGuiChildFlags.None; + bool visible = ImGuiNative.igBeginChild_Str(str, new Vector2(op.A * s, op.B * s), childFlags, (ImGuiWindowFlags)op.Flags) != 0; + if (visible && open < Scopes.Length) + Scopes[open++] = new Scope { Kind = ScopeChild, End = op.EndIndex }; + else + { + ImGuiNative.igEndChild(); // always paired, drawn or not + next = op.EndIndex; + } + break; + } + case ScriptOp.TreeNode: + { + byte live = ImGuiNative.igTreeNodeEx_Str(str, (ImGuiTreeNodeFlags)op.Flags); + ReportOpen(w, ref op, live, frame); + if (live != 0 && op.Flag != 0 && open < Scopes.Length) + Scopes[open++] = new Scope { Kind = ScopeTree, End = op.EndIndex }; + else + { + // Closed, or just opened by the player (recorded closed: no children yet). + if (live != 0) ImGuiNative.igTreePop(); + next = op.EndIndex; + } + break; + } + case ScriptOp.CollapsingHeader: + { + byte live = ImGuiNative.igCollapsingHeader_TreeNodeFlags(str, (ImGuiTreeNodeFlags)op.Flags); + ReportOpen(w, ref op, live, frame); + // Just closed by the player: the recorded contents follow; hide them until the + // next header or the scope's end (one tick, until the next list arrives). + if (live == 0 && op.Flag != 0) sc.Skip = true; + break; + } + } + i = next; + } + } + finally + { + // Normal end: nothing is open. Over budget or an exception: close every open scope + // (colours, IDs, TreePop, EndChild) so ImGui's stacks stay balanced. + while (open > 0) + { + open--; + CloseScope(ref Scopes[open]); + } + } + } + return visited; + } + + /// <summary>The missing-icon placeholder's fill (a dim grey square).</summary> + private static readonly Vector4 PlaceholderFill = new(0.5f, 0.5f, 0.5f, 0.35f); + + /// <summary>0xAABBGGRR as ImGui's Vector4 colour.</summary> + private static Vector4 Rgba(uint c) => + new((c & 0xFF) / 255f, ((c >> 8) & 0xFF) / 255f, ((c >> 16) & 0xFF) / 255f, (c >> 24) / 255f); + + /// <summary>The font atlas's white pixel: a plain-colour "image" that needs no texture of its own.</summary> + private static void WhitePixel(out IntPtr texture, out Vector2 uv) + { + ImFontAtlas* atlas = ImGuiNative.igGetIO()->Fonts; + texture = atlas->TexID; + uv = atlas->TexUvWhitePixel; + } + + /// <summary>An icon that isn't ready, is missing or didn't decode: a dim square of the same size (and border).</summary> + private static void Placeholder(Vector2 size, Vector4 border) + { + WhitePixel(out IntPtr white, out Vector2 uv); + ImGuiNative.igImage(white, size, uv, uv, PlaceholderFill, border); + } + + private static void CloseScope(ref Scope sc) + { + if (sc.Colors > 0) + { + int c = sc.Colors; + sc.Colors = 0; + ImGuiNative.igPopStyleColor(c); + } + while (sc.Ids > 0) + { + sc.Ids--; + ImGuiNative.igPopID(); + } + byte kind = sc.Kind; + sc.Kind = ScopeRoot; + if (kind == ScopeTree) ImGuiNative.igTreePop(); + else if (kind == ScopeChild) ImGuiNative.igEndChild(); + } + + /// <summary> + /// A tree node / header whose live state differs from what was last reported for this list + /// (at first, the recorded state) queues an Open event (coalesced per widget). + /// </summary> + private static void ReportOpen(ScriptWindow w, ref ReplayOp op, byte live, int frame) + { + byte v = live != 0 ? (byte)1 : (byte)0; + if (v == op.LastOpen) return; + op.LastOpen = v; + w.NoteInput(w.Owner.Events.Open(w.Hash, op.Key, v != 0), frame); + } + + private static void ReplayInputText(ScriptWindow w, ref ReplayOp op, byte* label, byte* pool, uint ack, int frame) + { + int maxLen = op.Aux; + ScriptLocals.TextLocal t = w.Locals.Text(op.Key, maxLen, frame); + byte[] buf = t.Buf; + // No newer local text and not being typed in: show the list's value (copied only when it differs). + if (!(t.Seq > ack || t.Active)) + { + t.Seq = 0; + var value = new ReadOnlySpan<byte>(pool + op.Str2, op.Str2Len); + int cur = Array.IndexOf(buf, (byte)0); + if (cur < 0) cur = buf.Length - 1; + if (!value.SequenceEqual(buf.AsSpan(0, cur))) + { + value.CopyTo(buf); + buf[value.Length] = 0; + } + } + + var flags = (ImGuiInputTextFlags)op.Flags; + byte ret; + bool edited; + fixed (byte* b = buf) + { + ret = ImGuiNative.igInputText(label, b, (uint)(maxLen + 1), flags, null, null); + edited = ImGuiNative.igIsItemEdited() != 0; + } + t.Active = ImGuiNative.igIsItemActive() != 0; + if (t.Active) ImGuiTextFocus.NoteActive("text box"); // keys stay out of AC from this frame on + + // EnterReturnsTrue: true = Enter pressed (submitted); edits still send the text, unsubmitted. + // Otherwise true = edited. + bool enterMode = (flags & ImGuiInputTextFlags.EnterReturnsTrue) != 0; + bool submitted = enterMode && ret != 0; + if (submitted || edited || (!enterMode && ret != 0)) + { + buf[maxLen] = 0; + int len = Array.IndexOf(buf, (byte)0); + uint seq = w.Owner.Events.Text(w.Hash, op.Key, buf.AsSpan(0, len), submitted); + t.Seq = seq; + w.NoteInput(seq, frame); + } + } +} + +/// <summary> +/// A window's local widget values (no snap-back, §2.5). AC thread only. A local value shows +/// while its event seq is newer than the list's AckSeq, or while ImGui reported the item +/// active last frame; otherwise it is dropped and the list's value shows. +/// </summary> +internal sealed class ScriptLocals +{ + private const int PruneAbove = 64; + private const int StaleFrames = 600; + + public struct Local<T> where T : struct + { + public T Value; + public uint Seq; + public bool Active; + public int Frame; + } + + public sealed class LocalMap<T> where T : struct + { + private readonly Dictionary<uint, Local<T>> _map = new(); + + public int Count => _map.Count; + + /// <summary>The local value to show instead of the list's, if any (a stale one is dropped).</summary> + public bool TryGet(uint key, uint ack, out T value) + { + value = default; + if (_map.Count == 0) return false; + ref Local<T> l = ref CollectionsMarshal.GetValueRefOrNullRef(_map, key); + if (Unsafe.IsNullRef(ref l)) return false; + if (l.Seq > ack || l.Active) + { + value = l.Value; + return true; + } + _map.Remove(key); + return false; + } + + /// <summary>After the widget call: record a change, or the item's active state.</summary> + public void After(uint key, bool had, bool changed, T value, uint seq, bool active, int frame) + { + if (changed) + { + _map[key] = new Local<T> { Value = value, Seq = seq, Active = active, Frame = frame }; + return; + } + if (had) + { + ref Local<T> l = ref CollectionsMarshal.GetValueRefOrNullRef(_map, key); + if (!Unsafe.IsNullRef(ref l)) + { + l.Active = active; + l.Frame = frame; + } + } + else if (active) + { + // Grabbed without a change yet: hold the shown value while it is held. + _map[key] = new Local<T> { Value = value, Seq = 0, Active = true, Frame = frame }; + } + } + + public void Prune(int frame) + { + foreach (var kv in _map) + if (!kv.Value.Active && frame - kv.Value.Frame > StaleFrames) + _map.Remove(kv.Key); + } + } + + /// <summary>One InputText's pinned buffer (maxLen + 1 bytes) and its local state.</summary> + public sealed class TextLocal + { + public byte[] Buf; + public int MaxLen; + public uint Seq; + public bool Active; + public int Frame; + + public TextLocal(int maxLen) + { + MaxLen = maxLen; + Buf = GC.AllocateArray<byte>(maxLen + 1, pinned: true); + } + } + + public readonly LocalMap<bool> Bools = new(); + public readonly LocalMap<int> Ints = new(); + public readonly LocalMap<float> Floats = new(); + private readonly Dictionary<uint, TextLocal> _texts = new(); + + /// <summary> + /// The InputText buffer for a widget, holding at most <paramref name="maxLen"/> bytes of text + /// (NUL-terminated within maxLen + 1). Allocated when first seen and only ever grown: two + /// InputTexts sharing a key (a duplicate ID the recorder only warns about) with different + /// maxLens would otherwise swap a new pinned buffer in for each of them on every frame. + /// A smaller maxLen cuts the text in place instead. + /// </summary> + public TextLocal Text(uint key, int maxLen, int frame) + { + if (!_texts.TryGetValue(key, out TextLocal? t)) + { + t = new TextLocal(maxLen); + _texts[key] = t; + } + else if (t.MaxLen < maxLen) + { + var bigger = new TextLocal(maxLen) { Seq = t.Seq, Active = t.Active }; + int len = Array.IndexOf(t.Buf, (byte)0); + if (len < 0) len = t.MaxLen; + t.Buf.AsSpan(0, len).CopyTo(bigger.Buf); + t = bigger; + _texts[key] = t; + } + if (t.MaxLen > maxLen && t.Buf[maxLen] != 0) + { + // ImGui copies strlen(buf) bytes into a buffer of the size it's given: the text must fit. + int len = Array.IndexOf(t.Buf, (byte)0); + if (len < 0 || len > maxLen) + { + len = maxLen; + while (len > 0 && (t.Buf[len] & 0xC0) == 0x80) len--; // don't split a character + t.Buf[len] = 0; + } + } + t.Frame = frame; + return t; + } + + /// <summary>On a new list: drop entries for widgets not drawn for a while, once there are many.</summary> + public void PruneIfLarge(int frame) + { + if (Bools.Count > PruneAbove) Bools.Prune(frame); + if (Ints.Count > PruneAbove) Ints.Prune(frame); + if (Floats.Count > PruneAbove) Floats.Prune(frame); + if (_texts.Count > PruneAbove) + foreach (var kv in _texts) + if (!kv.Value.Active && frame - kv.Value.Frame > StaleFrames) + _texts.Remove(kv.Key); + } +} + +/// <summary> +/// Phase 0 measurements, AC thread: replay cost per frame (all script windows +/// together) and input -> reaction latency, logged about every 10 s while a +/// script window draws. Lines are written off AC's thread (UiBackgroundWriter). +/// </summary> +internal static class ScriptWindowStats +{ + private const double LogEverySeconds = 10.0; + + // The frame being summed. + private static int _curFrame = int.MinValue; + private static long _curTicks; + private static int _curOps, _curWindows; + + // The current ~10 s period. + private static long _periodStart; + private static int _frames, _maxWindows, _maxOps; + private static long _sumTicks, _maxTicks, _sumOps; + private static int _reactions, _reactionFramesSum, _reactionFramesMax; + private static long _reactionTicksSum, _reactionTicksMax; + + public static void Replay(int frame, long ticks, int ops) + { + if (frame != _curFrame) + { + FlushFrame(); + _curFrame = frame; + } + _curTicks += ticks; + _curOps += ops; + _curWindows++; + + long now = Stopwatch.GetTimestamp(); + if (_periodStart == 0) _periodStart = now; + if (now - _periodStart >= (long)(Stopwatch.Frequency * LogEverySeconds)) + { + LogPeriod(now); + _periodStart = now; + } + } + + public static void Reaction(ScriptWindow w, int frames, long ticks) + { + _reactions++; + _reactionFramesSum += frames; + _reactionFramesMax = Math.Max(_reactionFramesMax, frames); + _reactionTicksSum += ticks; + _reactionTicksMax = Math.Max(_reactionTicksMax, ticks); + string line = $"ScriptWindows input->reaction: {w.PanelKey} {frames} frame(s), {Ms(ticks):0.0} ms"; + UiBackgroundWriter.Enqueue("script window latency", () => RynthLog.UI(line)); + } + + private static void FlushFrame() + { + if (_curWindows == 0) return; + _frames++; + _sumTicks += _curTicks; + _maxTicks = Math.Max(_maxTicks, _curTicks); + _sumOps += _curOps; + _maxOps = Math.Max(_maxOps, _curOps); + _maxWindows = Math.Max(_maxWindows, _curWindows); + _curTicks = 0; + _curOps = 0; + _curWindows = 0; + } + + private static void LogPeriod(long now) + { + FlushFrame(); + if (_frames > 0) + { + double seconds = (now - _periodStart) / (double)Stopwatch.Frequency; + double avgUs = Ms(_sumTicks) * 1000.0 / _frames; + double maxUs = Ms(_maxTicks) * 1000.0; + double avgOps = _sumOps / (double)_frames; + double usPerOp = _sumOps > 0 ? Ms(_sumTicks) * 1000.0 / _sumOps : 0; + string reaction = _reactions == 0 ? "none" + : $"n={_reactions} avg={_reactionFramesSum / (double)_reactions:0.0} frames/{Ms(_reactionTicksSum) / _reactions:0.0} ms max={_reactionFramesMax} frames/{Ms(_reactionTicksMax):0.0} ms"; + string line = $"ScriptWindows replay: {seconds:0.0}s frames={_frames} windows<={_maxWindows} ops/frame avg={avgOps:0} max={_maxOps} " + + $"us/frame avg={avgUs:0.0} max={maxUs:0.0} us/op={usPerOp:0.000} | input->reaction {reaction}"; + UiBackgroundWriter.Enqueue("script window stats", () => RynthLog.UI(line)); + } + _frames = _maxWindows = _maxOps = 0; + _sumTicks = _maxTicks = _sumOps = 0; + _reactions = _reactionFramesSum = _reactionFramesMax = 0; + _reactionTicksSum = _reactionTicksMax = 0; + } + + private static double Ms(long ticks) => ticks * 1000.0 / Stopwatch.Frequency; +} diff --git a/src/RynthCore.Engine/ImGui/UiFrameStats.cs b/src/RynthCore.Engine/ImGui/UiFrameStats.cs new file mode 100644 index 0000000..4301c6a --- /dev/null +++ b/src/RynthCore.Engine/ImGui/UiFrameStats.cs @@ -0,0 +1,46 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/UiFrameStats.cs +// Cost of the ImGui work on AC's render thread, for the heartbeat's "ui=". +// +// Record() runs once per EndScene (AC thread) with the ticks spent building +// and submitting the ImGui frame (0-ish on early-out frames). Once a second +// it sorts the window in place and publishes the p95 and max; the heartbeat +// thread only reads the two published floats. No allocation. +// ============================================================================ + +using System; +using System.Diagnostics; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class UiFrameStats +{ + private static readonly long[] _samples = new long[1024]; + private static int _count; + private static long _windowStart; + private static volatile float _p95Ms; + private static volatile float _maxMs; + + /// <summary>95th-percentile ImGui cost per frame over the last full second, in ms.</summary> + public static float P95Ms => _p95Ms; + + /// <summary>Worst ImGui frame over the last full second, in ms.</summary> + public static float MaxMs => _maxMs; + + public static void Record(long elapsedTicks) + { + long now = Stopwatch.GetTimestamp(); + if (_windowStart == 0) _windowStart = now; + if (_count < _samples.Length) _samples[_count++] = elapsedTicks; + + if (now - _windowStart < Stopwatch.Frequency) return; + + Array.Sort(_samples, 0, _count); + int p95 = Math.Clamp((int)Math.Ceiling(_count * 0.95) - 1, 0, _count - 1); + double toMs = 1000.0 / Stopwatch.Frequency; + _p95Ms = (float)(_samples[p95] * toMs); + _maxMs = (float)(_samples[_count - 1] * toMs); + _count = 0; + _windowStart = now; + } +} diff --git a/src/RynthCore.Engine/ImGui/UnderUiLayer.cs b/src/RynthCore.Engine/ImGui/UnderUiLayer.cs new file mode 100644 index 0000000..f8a374f --- /dev/null +++ b/src/RynthCore.Engine/ImGui/UnderUiLayer.cs @@ -0,0 +1,181 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/UnderUiLayer.cs +// ImGui geometry that belongs to the 3D world (RynthVision's nameplates, the +// player plate and the combat text): drawn after AC's 3D scene and BEFORE +// AC's own UI, so AC's chat, radar, inventory and other windows cover it the +// way they cover the world. Everything else ImGui draws (the bar, the panels) +// still renders at EndScene, over AC's UI. +// +// How: +// Build inside the main ImGui frame (EndScene), MonsterHud paints into +// one of two ImDrawLists owned here instead of ImGui's background +// list. The lists are created once from the main context's shared +// draw-list data and reset each frame, so their buffers are reused +// (no per-frame allocation once they have grown). +// Commit at the end of EndScene the list just built becomes the one to +// show during the NEXT frame; the other list is built into next. +// Present the next frame, right after the Nav3D markers, when AC's 2D UI +// pass begins (D3D9.AcUiPassHook -> Nav3DRenderInjector -> +// PresentAtUiPass; after all of AC's 3D, alpha-sorted foliage +// included). Without that hook, Nav3DRenderInjector's +// DrawIndexedPrimitive hook spots ZENABLE going 1->0 instead +// (PresentAtTransition; fires before the foliage outdoors). Either +// way the list goes through DX9Backend with a full state save/restore. +// Fallback a frame where neither fired (portal space, a loading screen, no +// AC UI this frame) presents the list at EndScene instead, before +// the ImGui panels - the same place RenderNav3D's fallback draws. +// A list is presented at most once: no double draw. +// +// The plates are therefore one frame behind the frame they were built in - +// the same lag the Nav3D markers have, since both project with the camera +// GameMatrixCapture took at the previous EndScene - on both paths, so a frame +// that falls back doesn't jump. +// +// Threads: AC's render thread only (EndScene, the UI-pass detour and the DIP +// detour all run on it). Shutdown may run on the lifecycle thread while AC's +// thread is still in a detour: it unpublishes the lists, waits for a present in flight to +// finish, then frees them. +// ============================================================================ + +using System; +using System.Numerics; +using System.Threading; +using ImGuiNET; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static unsafe class UnderUiLayer +{ + private static ImDrawList* _listA, _listB; + private static ImDrawList* _building; // being built this frame (null: nothing built) + private static Vector2 _buildingSize; + private static ImDrawList* _ready; // to present this frame (built last frame) + private static Vector2 _readySize; + private static bool _presented; // _ready already drawn this frame + private static int _presenting; // a present is in flight (Shutdown waits for it) + private static volatile bool _shutDown; + + /// <summary>True after <see cref="BeginBuild"/> returned a list this frame. AC's render thread.</summary> + public static bool IsBuilding => _building != null; + + /// <summary>Frames presented at AC's UI pass / at the transition / at the EndScene fallback (diagnostics).</summary> + private static long _atUiPass, _atTransition, _atFallback; + + /// <summary> + /// Inside the main ImGui frame, main context current: a cleared draw list to + /// paint this frame's world overlays into, laid out for <paramref name="display"/> + /// (ImGui display pixels). Null when the layer isn't available. AC's render thread. + /// </summary> + public static ImDrawListPtr BeginBuild(Vector2 display) + { + if (_shutDown) return new ImDrawListPtr(null); + if (_listA == null) + { + IntPtr shared = ImGuiNET.ImGui.GetDrawListSharedData(); + if (shared == IntPtr.Zero) return new ImDrawListPtr(null); + _listA = ImGuiNative.ImDrawList_ImDrawList(shared); + _listB = ImGuiNative.ImDrawList_ImDrawList(shared); + } + // Never the list waiting to be shown (the fallback may still present it this frame). + ImDrawList* list = _ready == _listA ? _listB : _listA; + var ptr = new ImDrawListPtr(list); + // What ImGui does for its own background list each frame: reset (keeps the + // buffers), the frame's flags, the font atlas texture, a full-screen clip. + ptr._ResetForNewFrame(); + ptr.PushTextureID(ImGuiNET.ImGui.GetIO().Fonts.TexID); + ptr.PushClipRect(Vector2.Zero, display, false); + _building = list; + _buildingSize = display; + return ptr; + } + + /// <summary> + /// Called by the DIP hook at AC's 3D->UI transition: draws last frame's world + /// overlays under AC's UI. AC's render thread. + /// </summary> + public static void PresentAtTransition(IntPtr device) + { + if (Present(device)) _atTransition++; + } + + /// <summary> + /// Called by AcUiPassHook (through Nav3DRenderInjector) when AC's 2D UI pass begins: + /// draws last frame's world overlays after all of AC's 3D (foliage included) and + /// under AC's UI. RenderDrawList sets its own full-screen viewport. AC's render thread. + /// </summary> + public static void PresentAtUiPass(IntPtr device) + { + if (Present(device)) _atUiPass++; + } + + /// <summary> + /// EndScene, before the ImGui panels are submitted: when neither the UI pass nor + /// the transition drew them this frame, the overlays are drawn here instead. + /// AC's render thread. + /// </summary> + public static void PresentFallback(IntPtr device) + { + if (Present(device)) _atFallback++; + } + + private static bool Present(IntPtr device) + { + if (_presented) return false; + Interlocked.Exchange(ref _presenting, 1); + try + { + ImDrawList* list = _ready; + if (list == null || _shutDown) return false; + _presented = true; + if (list->VtxBuffer.Size == 0) return false; + DX9Backend.RenderDrawList(list, _readySize, device); + return true; + } + finally + { + Volatile.Write(ref _presenting, 0); + } + } + + /// <summary> + /// End of EndScene (every frame, ImGui on or off): what was built this frame is + /// presented next frame; nothing built means nothing to present. AC's render thread. + /// </summary> + public static void EndFrame() + { + _ready = _shutDown ? null : _building; + _readySize = _buildingSize; + _building = null; + _presented = false; + } + + /// <summary>One line for /rc imgui diag.</summary> + public static string Describe() => + $"under-UI layer: presented at AC UI pass {_atUiPass}, at 3D->UI transition {_atTransition}, at EndScene (fallback) {_atFallback}"; + + /// <summary> + /// Engine shutdown, before DX9Backend and the ImGui context go. Any thread: + /// unpublishes the lists, waits (briefly) for a present in flight, frees them. + /// </summary> + public static void Shutdown() + { + _shutDown = true; + ImDrawList* a = _listA, b = _listB; + _ready = null; + _building = null; + _listA = _listB = null; + Thread.MemoryBarrier(); + var spin = new SpinWait(); + long deadline = Environment.TickCount64 + 200; + while (Volatile.Read(ref _presenting) != 0 && Environment.TickCount64 < deadline) + spin.SpinOnce(); + if (Volatile.Read(ref _presenting) != 0) + { + // Still drawing after 200 ms: leak the two lists rather than free them under it. + RynthLog.Render("UnderUiLayer: a present was still running at shutdown; its lists are left allocated."); + return; + } + if (a != null) ImGuiNative.ImDrawList_destroy(a); + if (b != null) ImGuiNative.ImDrawList_destroy(b); + } +} diff --git a/src/RynthCore.Engine/ImGui/ViewportOffsets.cs b/src/RynthCore.Engine/ImGui/ViewportOffsets.cs deleted file mode 100644 index 62d62a3..0000000 --- a/src/RynthCore.Engine/ImGui/ViewportOffsets.cs +++ /dev/null @@ -1,53 +0,0 @@ -// ═══════════════════════════════════════════════════════════════════════════ -// RynthCore.Engine — ImGui/ViewportOffsets.cs -// Byte offsets of ImGuiPlatformIO callback fields in the cimgui.dll shipped -// with ImGui.NET 1.91.6.1 (docking branch). -// -// WARNING: these do NOT match ImGui.NET's compiled struct layout. ImGui.NET -// prepends 36 bytes of clipboard/IME/OpenInShell fields that this cimgui.dll -// build does not have. Writing via ImGui.NET's ref properties lands 36 bytes -// past the native field, so the native library sees NULL and asserts -// "Platform init didn't install handlers". -// -// Source of truth (disassembled cimgui.dll 1.91.6.1, x86): -// ImGuiPlatformIO_Set_Platform_GetWindowPos → mov [pio+0x10], shim -// ImGuiPlatformIO_Set_Platform_GetWindowSize → mov [pio+0x18], shim -// igUpdatePlatformWindows first callback dispatch → call [g+0x37B8] -// with ImGuiContext PlatformIO offset → pio field 0 = Platform_CreateWindow -// -// Struct size (from constructor memset): 0x74 (116 bytes). Fields 0x00..0x5F -// hold 24 callback pointers; 0x60..0x73 hold Monitors + Viewports ImVectors. -// ═══════════════════════════════════════════════════════════════════════════ - -namespace RynthCore.Engine.ImGuiBackend; - -internal static class ViewportOffsets -{ - // Platform_* (18 callbacks — this cimgui.dll build lacks GetWindowWorkAreaInsets) - public const int PlatformCreateWindow = 0; - public const int PlatformDestroyWindow = 4; - public const int PlatformShowWindow = 8; - public const int PlatformSetWindowPos = 12; - public const int PlatformGetWindowPos = 16; // confirmed via _Set_ helper disasm - public const int PlatformSetWindowSize = 20; - public const int PlatformGetWindowSize = 24; // confirmed via _Set_ helper disasm - public const int PlatformSetWindowFocus = 28; - public const int PlatformGetWindowFocus = 32; - public const int PlatformGetWindowMinimized = 36; - public const int PlatformSetWindowTitle = 40; - public const int PlatformSetWindowAlpha = 44; - public const int PlatformUpdateWindow = 48; - public const int PlatformRenderWindow = 52; - public const int PlatformSwapBuffers = 56; - public const int PlatformGetWindowDpiScale = 60; - public const int PlatformOnChangedViewport = 64; - public const int PlatformCreateVkSurface = 68; - - // Renderer_* (5 callbacks) — RendererCreateWindow at +72 confirmed by - // igUpdatePlatformWindows disasm: [ebx+0x3800] = [pio + 0x48] = +72. - public const int RendererCreateWindow = 72; - public const int RendererDestroyWindow = 76; - public const int RendererSetWindowSize = 80; - public const int RendererRenderWindow = 84; - public const int RendererSwapBuffers = 88; -} diff --git a/src/RynthCore.Engine/ImGui/ViewportPlatformBackend.cs b/src/RynthCore.Engine/ImGui/ViewportPlatformBackend.cs deleted file mode 100644 index 23e6bab..0000000 --- a/src/RynthCore.Engine/ImGui/ViewportPlatformBackend.cs +++ /dev/null @@ -1,829 +0,0 @@ -// ═══════════════════════════════════════════════════════════════════════════ -// RynthCore.Engine — ImGui/ViewportPlatformBackend.cs -// Win32 platform backend for Dear ImGui multi-viewport (equivalent of -// imgui_impl_win32's viewport-capable portion). Installs Platform_* callbacks -// into the native ImGuiPlatformIO struct, registers a window class for -// popped-out ImGui windows, and proxies the required Win32 calls. -// -// Input for viewport HWNDs is forwarded into the existing Dear ImGui IO -// event queue via a dedicated WndProc. -// ═══════════════════════════════════════════════════════════════════════════ - -using System; -using System.Collections.Generic; -using System.Numerics; -using System.Runtime.InteropServices; -using ImGuiNET; - -namespace RynthCore.Engine.ImGuiBackend; - -internal static unsafe class ViewportPlatformBackend -{ - // ── Delegate types (cdecl; ImGui callbacks on x86 use the default C ABI) ── - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void ViewportVoidDelegate(ImGuiViewport* vp); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void ViewportGetVec2Delegate(ImGuiViewport* vp, Vector2* outVec); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void ViewportSetVec2Delegate(ImGuiViewport* vp, Vector2 value); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate byte ViewportGetBoolDelegate(ImGuiViewport* vp); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void ViewportSetStringDelegate(ImGuiViewport* vp, IntPtr str); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void ViewportSetFloatDelegate(ImGuiViewport* vp, float value); - - [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern ushort RegisterClassExW(ref WNDCLASSEXW lpwcx); - - [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern IntPtr CreateWindowExW( - uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle, - int X, int Y, int nWidth, int nHeight, - IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam); - - [DllImport("user32.dll")] - private static extern bool DestroyWindow(IntPtr hWnd); - - [DllImport("user32.dll")] - private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); - - [DllImport("user32.dll")] - private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, - int X, int Y, int cx, int cy, uint uFlags); - - [DllImport("user32.dll")] - private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); - - [DllImport("user32.dll")] - private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect); - - [DllImport("user32.dll", CharSet = CharSet.Unicode)] - private static extern int SetWindowTextW(IntPtr hWnd, string lpString); - - [DllImport("user32.dll")] - private static extern bool SetForegroundWindow(IntPtr hWnd); - - [DllImport("user32.dll")] - private static extern IntPtr GetForegroundWindow(); - - [DllImport("user32.dll")] - private static extern bool IsIconic(IntPtr hWnd); - - [DllImport("user32.dll")] - private static extern IntPtr SetWindowLongW(IntPtr hWnd, int nIndex, IntPtr dwNewLong); - - [DllImport("user32.dll")] - private static extern IntPtr GetWindowLongW(IntPtr hWnd, int nIndex); - - [DllImport("user32.dll")] - private static extern bool SetLayeredWindowAttributes(IntPtr hWnd, uint crKey, byte bAlpha, uint dwFlags); - - [DllImport("user32.dll")] - private static extern IntPtr DefWindowProcW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); - - [DllImport("user32.dll")] - private static extern bool AdjustWindowRectEx(ref RECT lpRect, uint dwStyle, bool bMenu, uint dwExStyle); - - [DllImport("user32.dll")] - private static extern bool PostMessageW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); - - [DllImport("user32.dll")] - private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint); - - [DllImport("user32.dll")] - private static extern IntPtr SetCapture(IntPtr hWnd); - - [DllImport("user32.dll")] - private static extern bool ReleaseCapture(); - - [StructLayout(LayoutKind.Sequential)] - private struct POINT { public int X, Y; } - - [DllImport("kernel32.dll")] - private static extern IntPtr GetModuleHandleW(string? lpModuleName); - - [DllImport("user32.dll")] - private static extern IntPtr LoadCursorW(IntPtr hInstance, IntPtr lpCursorName); - - [DllImport("user32.dll")] - private static extern int GetSystemMetrics(int nIndex); - - [DllImport("user32.dll")] - private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProc lpfnEnum, IntPtr dwData); - - [DllImport("user32.dll", CharSet = CharSet.Unicode)] - private static extern bool GetMonitorInfoW(IntPtr hMonitor, ref MONITORINFO lpmi); - - private delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData); - - [StructLayout(LayoutKind.Sequential)] - private struct MONITORINFO - { - public uint cbSize; - public RECT rcMonitor; - public RECT rcWork; - public uint dwFlags; - } - - private const int SM_CXSCREEN = 0; - private const int SM_CYSCREEN = 1; - private const uint MONITORINFOF_PRIMARY = 0x00000001; - - // ImGuiPlatformIO Monitors ImVector (native cimgui.dll layout). - // Native has 18 Platform_* + 5 Renderer_* = 23 callback pointers = 92 bytes, - // then Monitors ImVector{ int Size; int Capacity; void* Data; } at +92..+103, - // then Viewports ImVector at +104..+115. (ImGui.NET's compiled layout adds - // GetWindowWorkAreaInsets and so puts Monitors at +96 — do NOT use that.) - // Confirmed by probe dump showing Viewports.Size=1, Cap=8, Data=ptr at - // +104..+115 when native had just seeded the main viewport. - private const int MonitorsSize = 92; - private const int MonitorsCapacity = 96; - private const int MonitorsData = 100; - - // ImGuiPlatformMonitor is 40 bytes (confirmed by cimgui.dll ctor "push 28h"): - // +0 MainPos (ImVec2, 8) - // +8 MainSize (ImVec2, 8) - // +16 WorkPos (ImVec2, 8) - // +24 WorkSize (ImVec2, 8) - // +32 DpiScale (float, 4) - // +36 PlatformHandle (void*, 4) - private const int MonitorStructSize = 40; - - private static IntPtr _monitorArrayPtr; - private static int _monitorCount; - - private delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - private struct WNDCLASSEXW - { - public uint cbSize; - public uint style; - public IntPtr lpfnWndProc; - public int cbClsExtra; - public int cbWndExtra; - public IntPtr hInstance; - public IntPtr hIcon; - public IntPtr hCursor; - public IntPtr hbrBackground; - [MarshalAs(UnmanagedType.LPWStr)] public string? lpszMenuName; - [MarshalAs(UnmanagedType.LPWStr)] public string? lpszClassName; - public IntPtr hIconSm; - } - - [StructLayout(LayoutKind.Sequential)] - private struct RECT { public int Left, Top, Right, Bottom; } - - // Win32 constants - private const int GWL_STYLE = -16; - private const int GWL_EXSTYLE = -20; - private const int SW_SHOWNA = 8; - private const int SW_HIDE = 0; - private const uint SWP_NOMOVE = 0x0002; - private const uint SWP_NOSIZE = 0x0001; - private const uint SWP_NOZORDER = 0x0004; - private const uint SWP_NOACTIVATE = 0x0010; - private const uint WS_POPUP = 0x80000000; - private const uint WS_OVERLAPPEDWINDOW = 0x00CF0000; - private const uint WS_CLIPCHILDREN = 0x02000000; - private const uint WS_CLIPSIBLINGS = 0x04000000; - private const uint WS_EX_TOOLWINDOW = 0x00000080; - private const uint WS_EX_LAYERED = 0x00080000; - private const uint WS_EX_APPWINDOW = 0x00040000; - private const uint WS_EX_TOPMOST = 0x00000008; - private const uint WS_EX_NOACTIVATE = 0x08000000; - private const uint LWA_ALPHA = 0x00000002; - private const uint WM_CLOSE = 0x0010; - private const uint WM_MOVE = 0x0003; - private const uint WM_SIZE = 0x0005; - private const uint WM_MOUSEACTIVATE = 0x0021; - private const uint WM_NCHITTEST = 0x0084; - private const uint WM_MOUSEMOVE = 0x0200; - private const uint WM_LBUTTONDOWN = 0x0201; - private const uint WM_LBUTTONUP = 0x0202; - private const uint WM_LBUTTONDBLCLK = 0x0203; - private const uint WM_RBUTTONDOWN = 0x0204; - private const uint WM_RBUTTONUP = 0x0205; - private const uint WM_RBUTTONDBLCLK = 0x0206; - private const uint WM_MBUTTONDOWN = 0x0207; - private const uint WM_MBUTTONUP = 0x0208; - private const uint WM_MBUTTONDBLCLK = 0x0209; - private const uint WM_MOUSEWHEEL = 0x020A; - private const uint WM_XBUTTONDOWN = 0x020B; - private const uint WM_XBUTTONUP = 0x020C; - private const uint WM_MOUSEHWHEEL = 0x020E; - private const uint WM_KEYDOWN = 0x0100; - private const uint WM_KEYUP = 0x0101; - private const uint WM_CHAR = 0x0102; - private const uint WM_SYSKEYDOWN = 0x0104; - private const uint WM_SYSKEYUP = 0x0105; - private const int MA_NOACTIVATE = 3; - private const int HTCLIENT = 1; - private const IntPtr IDC_ARROW = 0x7F00; // MAKEINTRESOURCE(32512) - - private const string WindowClassName = "RynthCoreImGuiViewport"; - - // Pinned delegate instances — prevent GC while ImGui holds function pointers. - private static readonly List<Delegate> _delegateRoots = new(); - private static WndProcDelegate? _viewportWndProc; - private static IntPtr _viewportWndProcPtr; - private static bool _initialized; - private static bool _classRegistered; - private static IntPtr _hInstance; - private static IntPtr _mainHwnd; - - // Per-viewport state kept on the managed side. - // Keyed by the native ImGuiViewport* pointer. - private static readonly Dictionary<IntPtr, ViewportState> _viewports = new(); - - private class ViewportState - { - public IntPtr Hwnd; - public bool HwndOwned; - public uint DwStyle; - public uint DwExStyle; - } - - public static bool Init(IntPtr mainHwnd) - { - if (_initialized) return true; - - _mainHwnd = mainHwnd; - _hInstance = GetModuleHandleW(null); - - if (!EnsureWindowClassRegistered()) - { - RynthLog.Info($"ViewportPlatform: RegisterClassEx failed (err {Marshal.GetLastWin32Error()})"); - return false; - } - - ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO(); - InstallCallbacks(pio); - PopulateMonitors(pio); - - ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); - io.BackendFlags |= ImGuiBackendFlags.PlatformHasViewports; - // Do NOT set HasMouseHoveredViewport: that flag tells ImGui the backend - // will route hovered-viewport info via AddMouseViewportEvent each frame. - // We don't call that, so setting the flag causes mouse input to drop on - // the floor (IsWindowHovered returns false for every window). - - // The main viewport's PlatformHandle points to the game window; store it - // so the very first frame doesn't try to create a new HWND for viewport 0. - ImGuiViewportPtr mainViewport = ImGuiNET.ImGui.GetMainViewport(); - mainViewport.PlatformHandle = _mainHwnd; - mainViewport.PlatformHandleRaw = _mainHwnd; - _viewports[(IntPtr)mainViewport.NativePtr] = new ViewportState - { - Hwnd = _mainHwnd, - HwndOwned = false, - DwStyle = unchecked((uint)(long)GetWindowLongW(_mainHwnd, GWL_STYLE)), - DwExStyle = unchecked((uint)(long)GetWindowLongW(_mainHwnd, GWL_EXSTYLE)), - }; - - _initialized = true; - RynthLog.Info("ViewportPlatform: initialized."); - return true; - } - - public static void Shutdown() - { - if (!_initialized) return; - - // Destroy any viewport windows we created. - foreach (var kv in _viewports) - { - if (kv.Value.HwndOwned && kv.Value.Hwnd != IntPtr.Zero) - DestroyWindow(kv.Value.Hwnd); - } - _viewports.Clear(); - - // Clear the Monitors ImVector pointer in PlatformIO before freeing our - // backing buffer — native ImGui otherwise keeps a stale Data pointer. - if (_monitorArrayPtr != IntPtr.Zero) - { - try - { - ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO(); - IntPtr pioNative = (IntPtr)pio.NativePtr; - Marshal.WriteInt32(pioNative, MonitorsSize, 0); - Marshal.WriteInt32(pioNative, MonitorsCapacity, 0); - Marshal.WriteIntPtr(pioNative, MonitorsData, IntPtr.Zero); - } - catch { /* context may already be torn down */ } - - Marshal.FreeHGlobal(_monitorArrayPtr); - _monitorArrayPtr = IntPtr.Zero; - _monitorCount = 0; - } - - _initialized = false; - } - - // Dear ImGui asserts Monitor.Size > 0 before the first UpdatePlatformWindows - // call when ViewportsEnable is on. Populate the Monitors ImVector with the - // primary (and any secondary) displays so windows can pop out correctly. - private static void PopulateMonitors(ImGuiPlatformIOPtr pio) - { - var rects = new List<(RECT mon, RECT work, bool primary)>(); - MonitorEnumProc cb = (IntPtr hMon, IntPtr hdc, ref RECT r, IntPtr _) => - { - MONITORINFO mi = default; - mi.cbSize = (uint)Marshal.SizeOf<MONITORINFO>(); - if (GetMonitorInfoW(hMon, ref mi)) - rects.Add((mi.rcMonitor, mi.rcWork, (mi.dwFlags & MONITORINFOF_PRIMARY) != 0)); - return true; - }; - - if (!EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, cb, IntPtr.Zero) || rects.Count == 0) - { - // Fallback: single primary display via GetSystemMetrics. - int w = GetSystemMetrics(SM_CXSCREEN); - int h = GetSystemMetrics(SM_CYSCREEN); - RECT r = new RECT { Left = 0, Top = 0, Right = w > 0 ? w : 1920, Bottom = h > 0 ? h : 1080 }; - rects.Add((r, r, true)); - } - - GC.KeepAlive(cb); - - _monitorCount = rects.Count; - _monitorArrayPtr = Marshal.AllocHGlobal(_monitorCount * MonitorStructSize); - - // Primary monitor must be at index 0 for Dear ImGui's viewport code. - rects.Sort((a, b) => (b.primary ? 1 : 0) - (a.primary ? 1 : 0)); - - for (int i = 0; i < _monitorCount; i++) - { - var (mon, work, _) = rects[i]; - IntPtr mp = _monitorArrayPtr + i * MonitorStructSize; - - WriteFloat(mp, 0, mon.Left); - WriteFloat(mp, 4, mon.Top); - WriteFloat(mp, 8, mon.Right - mon.Left); - WriteFloat(mp, 12, mon.Bottom - mon.Top); - WriteFloat(mp, 16, work.Left); - WriteFloat(mp, 20, work.Top); - WriteFloat(mp, 24, work.Right - work.Left); - WriteFloat(mp, 28, work.Bottom - work.Top); - WriteFloat(mp, 32, 1.0f); - Marshal.WriteIntPtr(mp, 36, IntPtr.Zero); - } - - IntPtr pioNative = (IntPtr)pio.NativePtr; - Marshal.WriteInt32(pioNative, MonitorsSize, _monitorCount); - Marshal.WriteInt32(pioNative, MonitorsCapacity, _monitorCount); - Marshal.WriteIntPtr(pioNative, MonitorsData, _monitorArrayPtr); - - RynthLog.Info($"ViewportPlatform: populated {_monitorCount} monitor(s) at 0x{_monitorArrayPtr.ToInt64():X8}"); - } - - private static bool EnsureWindowClassRegistered() - { - if (_classRegistered) return true; - - _viewportWndProc = ViewportWndProc; - _viewportWndProcPtr = Marshal.GetFunctionPointerForDelegate(_viewportWndProc); - - WNDCLASSEXW wc = default; - wc.cbSize = (uint)Marshal.SizeOf<WNDCLASSEXW>(); - wc.style = 0x0020 /*CS_OWNDC*/ | 0x0002 /*CS_HREDRAW*/ | 0x0001 /*CS_VREDRAW*/; - wc.lpfnWndProc = _viewportWndProcPtr; - wc.hInstance = _hInstance; - wc.hCursor = LoadCursorW(IntPtr.Zero, IDC_ARROW); - wc.hbrBackground = IntPtr.Zero; - wc.lpszClassName = WindowClassName; - - ushort atom = RegisterClassExW(ref wc); - if (atom == 0) - { - int err = Marshal.GetLastWin32Error(); - // 1410 = ERROR_CLASS_ALREADY_EXISTS; fine if we were re-initialized. - if (err != 1410) return false; - } - - _classRegistered = true; - return true; - } - - // ─── Callback installation ──────────────────────────────────────────── - private static void InstallCallbacks(ImGuiPlatformIOPtr pio) - { - IntPtr pioNative = (IntPtr)pio.NativePtr; - - IntPtr createPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportCreate); - IntPtr destroyPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportDestroy); - IntPtr showPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportShow); - IntPtr setPosPtr = RootAndGetPointer<ViewportSetVec2Delegate>(ViewportSetPos); - IntPtr setSizePtr = RootAndGetPointer<ViewportSetVec2Delegate>(ViewportSetSize); - IntPtr setFocusPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportSetFocus); - IntPtr getFocusPtr = RootAndGetPointer<ViewportGetBoolDelegate>(ViewportGetFocus); - IntPtr getMinPtr = RootAndGetPointer<ViewportGetBoolDelegate>(ViewportGetMinimized); - IntPtr setTitlePtr = RootAndGetPointer<ViewportSetStringDelegate>(ViewportSetTitle); - IntPtr setAlphaPtr = RootAndGetPointer<ViewportSetFloatDelegate>(ViewportSetAlpha); - IntPtr updatePtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportUpdate); - - // Direct writes at native cimgui.dll offsets (NOT ImGui.NET's compiled - // layout offsets — those are off by 36 bytes). Void-return and - // small-return callbacks match the cdecl ABI naturally. - Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformCreateWindow, createPtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformDestroyWindow, destroyPtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformShowWindow, showPtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowPos, setPosPtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowSize, setSizePtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowFocus, setFocusPtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformGetWindowFocus, getFocusPtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformGetWindowMinimized, getMinPtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowTitle, setTitlePtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowAlpha, setAlphaPtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformUpdateWindow, updatePtr); - - // GetWindowPos / GetWindowSize return ImVec2 by value (x86 cdecl struct - // return — hidden first arg on stack). Our C# delegates take an out-ptr - // instead; cimgui ships a wrapper helper that adapts the ABI and writes - // the wrapper at the right offset for us. Must install via helper, not - // Marshal.WriteIntPtr, or native crashes on the first call. - IntPtr getPosPtr = RootAndGetPointer<ViewportGetVec2Delegate>(ViewportGetPos); - IntPtr getSizePtr = RootAndGetPointer<ViewportGetVec2Delegate>(ViewportGetSize); - ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowPos(pio.NativePtr, getPosPtr); - ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowSize(pio.NativePtr, getSizePtr); - - // Read back and log so a silent mismatch surfaces as a log line, not an IM_ASSERT. - IntPtr verifyCreate = Marshal.ReadIntPtr(pioNative, ViewportOffsets.PlatformCreateWindow); - IntPtr verifyGetPos = Marshal.ReadIntPtr(pioNative, ViewportOffsets.PlatformGetWindowPos); - RynthLog.Info($"ViewportPlatform: installed handlers (CreateWindow readback=0x{verifyCreate.ToInt64():X8}, expected=0x{createPtr.ToInt64():X8}, GetWindowPos shim=0x{verifyGetPos.ToInt64():X8})"); - } - - private static IntPtr RootAndGetPointer<TDelegate>(TDelegate del) where TDelegate : Delegate - { - _delegateRoots.Add(del); - return Marshal.GetFunctionPointerForDelegate<TDelegate>(del); - } - - private static void WriteFloat(IntPtr basePtr, int offset, float value) - { - Marshal.WriteInt32(basePtr, offset, BitConverter.SingleToInt32Bits(value)); - } - - // ─── Callback implementations ───────────────────────────────────────── - private static void ViewportCreate(ImGuiViewport* vp) - { - uint flags = unchecked((uint)vp->Flags); - bool noDecoration = (flags & (uint)ImGuiViewportFlags.NoDecoration) != 0; - bool topMost = (flags & (uint)ImGuiViewportFlags.TopMost) != 0; - - uint dwStyle = noDecoration - ? WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS - : WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; - - // Always use WS_EX_TOOLWINDOW so tear-off viewports don't clutter the taskbar / Alt-Tab - // list when users run many clients. Owned by _mainHwnd so it still closes with the game. - uint dwExStyle = WS_EX_TOOLWINDOW; - if (topMost) dwExStyle |= WS_EX_TOPMOST; - dwExStyle |= WS_EX_NOACTIVATE; - - // Compute outer window rect that yields the requested client size. - RECT rect; - rect.Left = (int)vp->Pos.X; - rect.Top = (int)vp->Pos.Y; - rect.Right = rect.Left + (int)vp->Size.X; - rect.Bottom = rect.Top + (int)vp->Size.Y; - AdjustWindowRectEx(ref rect, dwStyle, false, dwExStyle); - - IntPtr hwnd = CreateWindowExW( - dwExStyle, WindowClassName, "RynthCore Viewport", dwStyle, - rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top, - _mainHwnd, IntPtr.Zero, _hInstance, IntPtr.Zero); - - if (hwnd == IntPtr.Zero) - { - RynthLog.Info($"ViewportPlatform: CreateWindowEx failed (err {Marshal.GetLastWin32Error()})"); - return; - } - - var state = new ViewportState { Hwnd = hwnd, HwndOwned = true, DwStyle = dwStyle, DwExStyle = dwExStyle }; - _viewports[(IntPtr)vp] = state; - - vp->PlatformHandle = (void*)hwnd; - vp->PlatformHandleRaw = (void*)hwnd; - } - - private static void ViewportDestroy(ImGuiViewport* vp) - { - IntPtr key = (IntPtr)vp; - if (_viewports.TryGetValue(key, out var state)) - { - if (state.HwndOwned && state.Hwnd != IntPtr.Zero) - DestroyWindow(state.Hwnd); - _viewports.Remove(key); - } - - vp->PlatformHandle = (void*)IntPtr.Zero; - vp->PlatformHandleRaw = (void*)IntPtr.Zero; - } - - private static void ViewportShow(ImGuiViewport* vp) - { - if (!TryGetState(vp, out var state)) return; - - ShowWindow(state.Hwnd, SW_SHOWNA); - } - - private static void ViewportSetPos(ImGuiViewport* vp, Vector2 pos) - { - if (!TryGetState(vp, out var state)) return; - - RECT rect; - rect.Left = (int)pos.X; - rect.Top = (int)pos.Y; - rect.Right = rect.Left; - rect.Bottom = rect.Top; - AdjustWindowRectEx(ref rect, state.DwStyle, false, state.DwExStyle); - SetWindowPos(state.Hwnd, IntPtr.Zero, rect.Left, rect.Top, 0, 0, - SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); - } - - private static void ViewportSetSize(ImGuiViewport* vp, Vector2 size) - { - if (!TryGetState(vp, out var state)) return; - - RECT rect; - rect.Left = 0; rect.Top = 0; - rect.Right = (int)size.X; - rect.Bottom = (int)size.Y; - AdjustWindowRectEx(ref rect, state.DwStyle, false, state.DwExStyle); - SetWindowPos(state.Hwnd, IntPtr.Zero, 0, 0, - rect.Right - rect.Left, rect.Bottom - rect.Top, - SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); - } - - private static void ViewportGetPos(ImGuiViewport* vp, Vector2* outPos) - { - *outPos = new Vector2(0, 0); - if (!TryGetState(vp, out var state)) return; - // Return the CLIENT-area origin in screen coords, not the outer window - // rect. ImGui's hit-testing uses this as the viewport origin; if we - // include the title-bar height, every click misses by that offset. - POINT p = new POINT { X = 0, Y = 0 }; - if (!ClientToScreen(state.Hwnd, ref p)) return; - *outPos = new Vector2(p.X, p.Y); - } - - private static void ViewportGetSize(ImGuiViewport* vp, Vector2* outSize) - { - *outSize = new Vector2(0, 0); - if (!TryGetState(vp, out var state)) return; - if (!GetClientRect(state.Hwnd, out RECT r)) return; - *outSize = new Vector2(r.Right - r.Left, r.Bottom - r.Top); - } - - private static void ViewportSetFocus(ImGuiViewport* vp) - { - if (!TryGetState(vp, out var state)) return; - SetForegroundWindow(state.Hwnd); - } - - private static byte ViewportGetFocus(ImGuiViewport* vp) - { - if (!TryGetState(vp, out var state)) return 0; - return GetForegroundWindow() == state.Hwnd ? (byte)1 : (byte)0; - } - - private static byte ViewportGetMinimized(ImGuiViewport* vp) - { - if (!TryGetState(vp, out var state)) return 0; - return IsIconic(state.Hwnd) ? (byte)1 : (byte)0; - } - - private static void ViewportSetTitle(ImGuiViewport* vp, IntPtr strPtr) - { - if (!TryGetState(vp, out var state)) return; - string title = Marshal.PtrToStringUTF8(strPtr) ?? "RynthCore Viewport"; - SetWindowTextW(state.Hwnd, title); - } - - private static void ViewportSetAlpha(ImGuiViewport* vp, float alpha) - { - if (!TryGetState(vp, out var state)) return; - IntPtr exStyle = GetWindowLongW(state.Hwnd, GWL_EXSTYLE); - long exs = (long)exStyle; - if (alpha < 1.0f) - SetWindowLongW(state.Hwnd, GWL_EXSTYLE, (IntPtr)(exs | WS_EX_LAYERED)); - byte a = (byte)Math.Clamp((int)(alpha * 255f + 0.5f), 0, 255); - SetLayeredWindowAttributes(state.Hwnd, 0, a, LWA_ALPHA); - } - - private static void ViewportUpdate(ImGuiViewport* vp) - { - // No-op on Win32 — imgui_impl_win32 handles monitor updates and other - // housekeeping elsewhere. We refresh monitors from EngineFrameController. - } - - private static bool TryGetState(ImGuiViewport* vp, out ViewportState state) - { - return _viewports.TryGetValue((IntPtr)vp, out state!); - } - - // ─── WndProc for viewport HWNDs ─────────────────────────────────────── - internal static IntPtr ImGuiContext; - - private static IntPtr ViewportWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) - { - // If the ImGui context has been torn down (Shutdown already ran), don't - // touch any ImGui API — the context memory is freed and any call into it - // is a use-after-free. Just forward to the default handler. - if (ImGuiContext == IntPtr.Zero) - return DefWindowProcW(hWnd, msg, wParam, lParam); - - // OS delivers messages (WM_GETICON, WM_PAINT, etc.) asynchronously outside - // of EndScene. By then our saved context has been restored → GImGui is null, - // and any ImGui call here AVs. Temporarily set our context for the message. - IntPtr saved = ImGuiNET.ImGui.GetCurrentContext(); - if (saved != ImGuiContext) - ImGuiNET.ImGui.SetCurrentContext(ImGuiContext); - - try - { - ImGuiViewportPtr vp = ImGuiNET.ImGui.FindViewportByPlatformHandle(hWnd); - if (vp.NativePtr == null) - return DefWindowProcW(hWnd, msg, wParam, lParam); - - ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); - - // ── Mouse position: forward in screen coords (multi-viewport) ──── - if (msg == WM_MOUSEMOVE || msg == WM_LBUTTONDOWN || msg == WM_LBUTTONUP - || msg == WM_LBUTTONDBLCLK || msg == WM_RBUTTONDOWN || msg == WM_RBUTTONUP - || msg == WM_RBUTTONDBLCLK || msg == WM_MBUTTONDOWN || msg == WM_MBUTTONUP - || msg == WM_MBUTTONDBLCLK || msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP) - { - short cx = (short)((long)lParam & 0xFFFF); - short cy = (short)(((long)lParam >> 16) & 0xFFFF); - POINT pt = new POINT { X = cx, Y = cy }; - ClientToScreen(hWnd, ref pt); - io.AddMouseSourceEvent(ImGuiMouseSource.Mouse); - io.AddMousePosEvent(pt.X, pt.Y); - } - - switch (msg) - { - case WM_LBUTTONDOWN: - case WM_LBUTTONDBLCLK: - if (SetCapture(hWnd) == IntPtr.Zero) { /* ignore */ } - io.AddMouseButtonEvent(0, true); - return IntPtr.Zero; - case WM_LBUTTONUP: - io.AddMouseButtonEvent(0, false); - ReleaseCapture(); - return IntPtr.Zero; - - case WM_RBUTTONDOWN: - case WM_RBUTTONDBLCLK: - SetCapture(hWnd); - io.AddMouseButtonEvent(1, true); - return IntPtr.Zero; - case WM_RBUTTONUP: - io.AddMouseButtonEvent(1, false); - ReleaseCapture(); - return IntPtr.Zero; - - case WM_MBUTTONDOWN: - case WM_MBUTTONDBLCLK: - SetCapture(hWnd); - io.AddMouseButtonEvent(2, true); - return IntPtr.Zero; - case WM_MBUTTONUP: - io.AddMouseButtonEvent(2, false); - ReleaseCapture(); - return IntPtr.Zero; - - case WM_XBUTTONDOWN: - { - int btn = (((int)(long)wParam >> 16) & 0xFFFF) == 1 ? 3 : 4; - SetCapture(hWnd); - io.AddMouseButtonEvent(btn, true); - return IntPtr.Zero; - } - case WM_XBUTTONUP: - { - int btn = (((int)(long)wParam >> 16) & 0xFFFF) == 1 ? 3 : 4; - io.AddMouseButtonEvent(btn, false); - ReleaseCapture(); - return IntPtr.Zero; - } - - case WM_MOUSEWHEEL: - io.AddMouseWheelEvent(0f, (short)(((long)wParam >> 16) & 0xFFFF) / 120f); - return IntPtr.Zero; - case WM_MOUSEHWHEEL: - io.AddMouseWheelEvent((short)(((long)wParam >> 16) & 0xFFFF) / 120f, 0f); - return IntPtr.Zero; - - case WM_KEYDOWN: - case WM_SYSKEYDOWN: - { - ImGuiKey key = VkToImGuiKey((int)(long)wParam); - if (key != ImGuiKey.None) io.AddKeyEvent(key, true); - // Let DefWindowProc run so system keys still function (Alt+F4 etc.). - break; - } - case WM_KEYUP: - case WM_SYSKEYUP: - { - ImGuiKey key = VkToImGuiKey((int)(long)wParam); - if (key != ImGuiKey.None) io.AddKeyEvent(key, false); - break; - } - case WM_CHAR: - { - uint ch = (uint)(long)wParam; - if (ch > 0 && ch < 0x10000) io.AddInputCharacter(ch); - return IntPtr.Zero; - } - - case WM_CLOSE: - vp.PlatformRequestClose = true; - return IntPtr.Zero; - - case WM_MOVE: - vp.PlatformRequestMove = true; - break; - - case WM_SIZE: - vp.PlatformRequestResize = true; - break; - - case WM_MOUSEACTIVATE: - { - // If AC is the foreground app, don't steal its focus — just process the click. - // If the user is tabbed out (some other app is foreground), allow Windows to - // activate this viewport so the click actually brings it to the front. - IntPtr fg = GetForegroundWindow(); - IntPtr game = Win32Backend.GameHwnd; - if (game != IntPtr.Zero && fg == game) - return new IntPtr(MA_NOACTIVATE); - break; - } - - case WM_NCHITTEST: - { - uint flags = unchecked((uint)vp.Flags); - if ((flags & (uint)ImGuiViewportFlags.NoInputs) != 0) - return new IntPtr(-1 /*HTTRANSPARENT*/); - break; - } - } - } - catch (Exception ex) - { - RynthLog.Info($"ViewportPlatform.WndProc: {ex.GetType().Name}: {ex.Message}"); - } - finally - { - if (ImGuiContext != IntPtr.Zero && saved != ImGuiContext) - ImGuiNET.ImGui.SetCurrentContext(saved); - } - - return DefWindowProcW(hWnd, msg, wParam, lParam); - } - - private static ImGuiKey VkToImGuiKey(int vk) - { - return vk switch - { - 0x09 => ImGuiKey.Tab, - 0x25 => ImGuiKey.LeftArrow, - 0x27 => ImGuiKey.RightArrow, - 0x26 => ImGuiKey.UpArrow, - 0x28 => ImGuiKey.DownArrow, - 0x21 => ImGuiKey.PageUp, - 0x22 => ImGuiKey.PageDown, - 0x24 => ImGuiKey.Home, - 0x23 => ImGuiKey.End, - 0x2D => ImGuiKey.Insert, - 0x2E => ImGuiKey.Delete, - 0x08 => ImGuiKey.Backspace, - 0x20 => ImGuiKey.Space, - 0x0D => ImGuiKey.Enter, - 0x1B => ImGuiKey.Escape, - 0xBE => ImGuiKey.Period, - 0xBC => ImGuiKey.Comma, - 0xBD => ImGuiKey.Minus, - 0xBB => ImGuiKey.Equal, - 0xBA => ImGuiKey.Semicolon, - 0xBF => ImGuiKey.Slash, - 0xC0 => ImGuiKey.GraveAccent, - 0xDB => ImGuiKey.LeftBracket, - 0xDC => ImGuiKey.Backslash, - 0xDD => ImGuiKey.RightBracket, - 0xDE => ImGuiKey.Apostrophe, - >= 0x30 and <= 0x39 => ImGuiKey._0 + (vk - 0x30), - >= 0x41 and <= 0x5A => ImGuiKey.A + (vk - 0x41), - >= 0x60 and <= 0x69 => ImGuiKey.Keypad0 + (vk - 0x60), - >= 0x70 and <= 0x7B => ImGuiKey.F1 + (vk - 0x70), - 0x10 => ImGuiKey.LeftShift, - 0x11 => ImGuiKey.LeftCtrl, - 0x12 => ImGuiKey.LeftAlt, - _ => ImGuiKey.None, - }; - } -} diff --git a/src/RynthCore.Engine/ImGui/ViewportProbe.cs b/src/RynthCore.Engine/ImGui/ViewportProbe.cs deleted file mode 100644 index 6fef1e8..0000000 --- a/src/RynthCore.Engine/ImGui/ViewportProbe.cs +++ /dev/null @@ -1,200 +0,0 @@ -// ═══════════════════════════════════════════════════════════════════════════ -// RynthCore.Engine — ImGui/ViewportProbe.cs -// One-shot diagnostic run at startup. Determines the byte offsets of each -// ImGuiPlatformIO callback field in the running cimgui.dll, so that we can -// install Win32/DX9 platform callbacks by writing IntPtrs directly into -// the native struct (ImGui.NET exposes callback fields as get-only). -// -// Remove/gate this once offsets are documented and wired into a static table. -// ═══════════════════════════════════════════════════════════════════════════ - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.InteropServices; -using ImGuiNET; - -namespace RynthCore.Engine.ImGuiBackend; - -internal static class ViewportProbe -{ - // Every Platform_* and Renderer_* callback field ImGui.NET exposes. - // Probing strategy: write a unique sentinel at each 4-byte slot, read - // every getter, record which getter sees the sentinel, restore the slot. - private static readonly string[] FieldsToProbe = - { - "Platform_CreateWindow", - "Platform_DestroyWindow", - "Platform_ShowWindow", - "Platform_SetWindowPos", - "Platform_GetWindowPos", - "Platform_SetWindowSize", - "Platform_GetWindowSize", - "Platform_SetWindowFocus", - "Platform_GetWindowFocus", - "Platform_GetWindowMinimized", - "Platform_SetWindowTitle", - "Platform_SetWindowAlpha", - "Platform_UpdateWindow", - "Platform_RenderWindow", - "Platform_SwapBuffers", - "Platform_GetWindowDpiScale", - "Platform_OnChangedViewport", - "Platform_GetWindowWorkAreaInsets", - "Platform_CreateVkSurface", - "Renderer_CreateWindow", - "Renderer_DestroyWindow", - "Renderer_SetWindowSize", - "Renderer_RenderWindow", - "Renderer_SwapBuffers", - }; - - // ImGuiViewport fields worth locating so we know where ImGui.NET reads from - // vs the authoritative bytes. These are read-back tests — no writes. - private static readonly string[] ViewportFieldsToLog = - { - "ID", - "Flags", - "Pos", - "Size", - "WorkPos", - "WorkSize", - "DpiScale", - "ParentViewportId", - "DrawData", - "RendererUserData", - "PlatformUserData", - "PlatformHandle", - "PlatformHandleRaw", - "PlatformWindowCreated", - "PlatformRequestMove", - "PlatformRequestResize", - "PlatformRequestClose", - }; - - private const int ScanBytes = 768; - - public static void Run() - { - try - { - RynthLog.Info("ViewportProbe: ---- begin ----"); - RunPlatformIOProbe(); - RunMainViewportDump(); - RynthLog.Info("ViewportProbe: ---- end ----"); - } - catch (Exception ex) - { - RynthLog.Info($"ViewportProbe: FAILED {ex.GetType().Name}: {ex.Message}"); - } - } - - private static unsafe void RunPlatformIOProbe() - { - ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO(); - IntPtr pioNative = (IntPtr)pio.NativePtr; - RynthLog.Info($"ViewportProbe: PlatformIO native = 0x{pioNative.ToInt64():X8}"); - - // Log what each getter returns BEFORE probing, so we can see the stock zero state. - var propertyCache = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal); - Type ptrType = typeof(ImGuiPlatformIOPtr); - foreach (string name in FieldsToProbe) - { - PropertyInfo? prop = ptrType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance); - bool intptrLike = prop != null && ( - prop.PropertyType == typeof(IntPtr) || - (prop.PropertyType.IsByRef && prop.PropertyType.GetElementType() == typeof(IntPtr))); - if (intptrLike) - { - propertyCache[name] = prop!; - } - else - { - RynthLog.Info($"ViewportProbe: {name}: NOT FOUND on ImGuiPlatformIOPtr (type={prop?.PropertyType.Name ?? "null"})"); - } - } - - var discovered = new Dictionary<string, int>(StringComparer.Ordinal); - - for (int off = 0; off < ScanBytes; off += 4) - { - IntPtr orig = Marshal.ReadIntPtr(pioNative, off); - IntPtr sentinel = new IntPtr(unchecked((int)0xAB000000) | off); - Marshal.WriteIntPtr(pioNative, off, sentinel); - - foreach (var kv in propertyCache) - { - IntPtr read; - try - { - read = (IntPtr)kv.Value.GetValue(pio)!; - } - catch - { - continue; - } - - if (read == sentinel && !discovered.ContainsKey(kv.Key)) - { - discovered[kv.Key] = off; - } - } - - Marshal.WriteIntPtr(pioNative, off, orig); - } - - // Emit in ascending offset order so the mapping is obvious in the log. - var sorted = new List<KeyValuePair<string, int>>(discovered); - sorted.Sort((a, b) => a.Value.CompareTo(b.Value)); - RynthLog.Info($"ViewportProbe: discovered {sorted.Count}/{propertyCache.Count} offsets:"); - foreach (var kv in sorted) - RynthLog.Info($"ViewportProbe: +{kv.Value,4} {kv.Key}"); - - foreach (string name in FieldsToProbe) - { - if (propertyCache.ContainsKey(name) && !discovered.ContainsKey(name)) - RynthLog.Info($"ViewportProbe: MISSING {name} (getter exists but sentinel never matched)"); - } - - // Hex dump of the first chunk so we can visually scan for anomalies. - DumpRange(pioNative, 0, 256, "PlatformIO"); - } - - private static unsafe void RunMainViewportDump() - { - ImGuiViewportPtr main = ImGuiNET.ImGui.GetMainViewport(); - IntPtr vp = (IntPtr)main.NativePtr; - RynthLog.Info($"ViewportProbe: MainViewport native = 0x{vp.ToInt64():X8}"); - - Type vptrType = typeof(ImGuiViewportPtr); - foreach (string name in ViewportFieldsToLog) - { - PropertyInfo? prop = vptrType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance); - if (prop == null) - { - RynthLog.Info($"ViewportProbe: MainViewport.{name}: (no such property)"); - continue; - } - - object? val; - try { val = prop.GetValue(main); } - catch (Exception ex) { val = $"<throw {ex.GetType().Name}>"; continue; } - - RynthLog.Info($"ViewportProbe: MainViewport.{name} ({prop.PropertyType.Name}) = {val}"); - } - - DumpRange(vp, 0, 160, "MainViewport"); - } - - private static void DumpRange(IntPtr basePtr, int startOffset, int length, string label) - { - for (int off = startOffset; off < startOffset + length; off += 16) - { - uint w0 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 0)); - uint w1 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 4)); - uint w2 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 8)); - uint w3 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 12)); - RynthLog.Info($"ViewportProbe: {label} +{off,4} {w0:X8} {w1:X8} {w2:X8} {w3:X8}"); - } - } -} diff --git a/src/RynthCore.Engine/ImGui/ViewportRendererBackend.cs b/src/RynthCore.Engine/ImGui/ViewportRendererBackend.cs deleted file mode 100644 index 34be465..0000000 --- a/src/RynthCore.Engine/ImGui/ViewportRendererBackend.cs +++ /dev/null @@ -1,367 +0,0 @@ -// ═══════════════════════════════════════════════════════════════════════════ -// RynthCore.Engine — ImGui/ViewportRendererBackend.cs -// Per-viewport D3D9 renderer backend for ImGui multi-viewport. -// Installs Renderer_* callbacks on ImGuiPlatformIO: for each viewport we -// create an additional swap chain on the game's device, render the viewport's -// ImDrawData into that swap chain's back buffer, and Present it so the -// viewport's OS window displays the ImGui content. -// ═══════════════════════════════════════════════════════════════════════════ - -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using ImGuiNET; -using RynthCore.Engine.D3D9; - -namespace RynthCore.Engine.ImGuiBackend; - -internal static unsafe class ViewportRendererBackend -{ - // ─── D3D9 constants ─────────────────────────────────────────────── - private const uint D3DFMT_UNKNOWN = 0; - private const uint D3DFMT_A8R8G8B8 = 21; - private const uint D3DFMT_X8R8G8B8 = 22; - private const uint D3DSWAPEFFECT_DISCARD = 1; - private const uint D3DBACKBUFFER_TYPE_MONO = 0; - private const uint D3DCLEAR_TARGET = 0x00000001; - private const uint D3DPRESENT_INTERVAL_IMMEDIATE = 0x80000000; - - [StructLayout(LayoutKind.Sequential)] - private struct D3DPRESENT_PARAMETERS - { - public uint BackBufferWidth; - public uint BackBufferHeight; - public uint BackBufferFormat; - public uint BackBufferCount; - public uint MultiSampleType; - public uint MultiSampleQuality; - public uint SwapEffect; - public IntPtr hDeviceWindow; - public int Windowed; // BOOL - public int EnableAutoDepthStencil; // BOOL - public uint AutoDepthStencilFormat; - public uint Flags; - public uint FullScreen_RefreshRateInHz; - public uint PresentationInterval; - } - - [StructLayout(LayoutKind.Sequential)] - private struct RECT { public int L, T, R, B; } - - // ─── Device method delegates ────────────────────────────────────── - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int CreateAdditionalSwapChainD(IntPtr pDevice, D3DPRESENT_PARAMETERS* pp, out IntPtr ppSwapChain); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int SetRenderTargetD(IntPtr pDevice, uint rtIndex, IntPtr pSurface); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int GetRenderTargetD(IntPtr pDevice, uint rtIndex, out IntPtr ppSurface); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int ClearD(IntPtr pDevice, uint count, RECT* pRects, uint flags, uint color, float z, uint stencil); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate uint ReleaseD(IntPtr pObj); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int SwapChainGetBackBufferD(IntPtr pSwapChain, uint backBufIdx, uint type, out IntPtr ppBackBuffer); - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int SwapChainPresentD(IntPtr pSwapChain, RECT* src, RECT* dest, IntPtr hDestWnd, IntPtr dirtyRgn, uint flags); - - // ─── Callback delegates (must match imgui types) ────────────────── - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void ViewportCallbackD(ImGuiViewport* vp); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void ViewportSizeCallbackD(ImGuiViewport* vp, System.Numerics.Vector2 size); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void ViewportRenderD(ImGuiViewport* vp, IntPtr renderArg); - - // ─── State ──────────────────────────────────────────────────────── - private sealed class ViewportGpuState - { - public IntPtr SwapChain; - public int Width; - public int Height; - } - - private static IntPtr _device; - private static CreateAdditionalSwapChainD? _createAdditionalSwapChain; - private static SetRenderTargetD? _setRenderTarget; - private static GetRenderTargetD? _getRenderTarget; - private static ClearD? _clear; - private static readonly Dictionary<IntPtr, ViewportGpuState> _viewports = new(); - private static readonly List<Delegate> _delegateRoots = new(); - private static bool _initialized; - - // Diagnostic one-shot logging counters — limited to a few calls so log doesn't explode. - private static int _logCreate; - private static int _logRender; - private static int _logSwap; - private const int MaxLog = 3; - - public static bool Init(IntPtr pDevice) - { - if (_initialized) return true; - if (pDevice == IntPtr.Zero) - { - RynthLog.Info("ViewportRenderer: Init called with null device."); - return false; - } - - _device = pDevice; - - IntPtr vtable = Marshal.ReadIntPtr(pDevice); - _createAdditionalSwapChain = GetMethod<CreateAdditionalSwapChainD>(vtable, DeviceVTableIndex.CreateAdditionalSwapChain); - _setRenderTarget = GetMethod<SetRenderTargetD>(vtable, DeviceVTableIndex.SetRenderTarget); - _getRenderTarget = GetMethod<GetRenderTargetD>(vtable, DeviceVTableIndex.GetRenderTarget); - _clear = GetMethod<ClearD>(vtable, DeviceVTableIndex.Clear); - - InstallCallbacks(); - - ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); - io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports; - - _initialized = true; - RynthLog.Info("ViewportRenderer: initialized."); - return true; - } - - public static void Shutdown() - { - foreach (var kv in _viewports) - { - if (kv.Value.SwapChain != IntPtr.Zero) - ReleaseCom(kv.Value.SwapChain); - } - _viewports.Clear(); - _delegateRoots.Clear(); - _initialized = false; - } - - private static void InstallCallbacks() - { - ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO(); - IntPtr pioNative = (IntPtr)pio.NativePtr; - - ViewportCallbackD createFn = RendererCreateWindow; - ViewportCallbackD destroyFn = RendererDestroyWindow; - ViewportSizeCallbackD setSizeFn = RendererSetWindowSize; - ViewportRenderD renderFn = RendererRenderWindow; - ViewportRenderD swapFn = RendererSwapBuffers; - - _delegateRoots.Add(createFn); - _delegateRoots.Add(destroyFn); - _delegateRoots.Add(setSizeFn); - _delegateRoots.Add(renderFn); - _delegateRoots.Add(swapFn); - - IntPtr createPtr = Marshal.GetFunctionPointerForDelegate(createFn); - IntPtr destroyPtr = Marshal.GetFunctionPointerForDelegate(destroyFn); - IntPtr setSizePtr = Marshal.GetFunctionPointerForDelegate(setSizeFn); - IntPtr renderPtr = Marshal.GetFunctionPointerForDelegate(renderFn); - IntPtr swapPtr = Marshal.GetFunctionPointerForDelegate(swapFn); - - Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererCreateWindow, createPtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererDestroyWindow, destroyPtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererSetWindowSize, setSizePtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererRenderWindow, renderPtr); - Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererSwapBuffers, swapPtr); - - IntPtr verify = Marshal.ReadIntPtr(pioNative, ViewportOffsets.RendererRenderWindow); - RynthLog.Info($"ViewportRenderer: installed handlers (RenderWindow readback=0x{verify.ToInt64():X8}, expected=0x{renderPtr.ToInt64():X8})"); - } - - // ─── Callback implementations ───────────────────────────────────── - private static void RendererCreateWindow(ImGuiViewport* vp) - { - IntPtr key = (IntPtr)vp; - if (_viewports.ContainsKey(key)) return; - - var state = new ViewportGpuState(); - _viewports[key] = state; - - int w = Math.Max(1, (int)vp->Size.X); - int h = Math.Max(1, (int)vp->Size.Y); - CreateSwapChainForViewport(vp, state, w, h); - - if (_logCreate++ < MaxLog) - { - IntPtr hwnd = (IntPtr)vp->PlatformHandleRaw; - if (hwnd == IntPtr.Zero) hwnd = (IntPtr)vp->PlatformHandle; - RynthLog.Info($"ViewportRenderer: CreateWindow vp=0x{key.ToInt64():X8} hwnd=0x{hwnd.ToInt64():X8} size={w}x{h} swapChain=0x{state.SwapChain.ToInt64():X8}"); - } - } - - private static void RendererDestroyWindow(ImGuiViewport* vp) - { - IntPtr key = (IntPtr)vp; - if (!_viewports.TryGetValue(key, out var state)) return; - if (state.SwapChain != IntPtr.Zero) - { - ReleaseCom(state.SwapChain); - state.SwapChain = IntPtr.Zero; - } - _viewports.Remove(key); - } - - private static void RendererSetWindowSize(ImGuiViewport* vp, System.Numerics.Vector2 size) - { - IntPtr key = (IntPtr)vp; - if (!_viewports.TryGetValue(key, out var state)) return; - - int w = Math.Max(1, (int)size.X); - int h = Math.Max(1, (int)size.Y); - if (w == state.Width && h == state.Height) return; - - if (state.SwapChain != IntPtr.Zero) - { - ReleaseCom(state.SwapChain); - state.SwapChain = IntPtr.Zero; - } - CreateSwapChainForViewport(vp, state, w, h); - } - - private static void RendererRenderWindow(ImGuiViewport* vp, IntPtr renderArg) - { - IntPtr key = (IntPtr)vp; - bool diag = _logRender < MaxLog; - if (!_viewports.TryGetValue(key, out var state)) - { - if (diag) { RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} NO STATE"); _logRender++; } - return; - } - if (state.SwapChain == IntPtr.Zero) - { - if (diag) { RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} NO SWAPCHAIN"); _logRender++; } - return; - } - if (_setRenderTarget == null || _getRenderTarget == null || _clear == null) - { - if (diag) { RynthLog.Info("ViewportRenderer: RenderWindow device methods null"); _logRender++; } - return; - } - - // Get the swap chain's back-buffer surface - var getBB = GetMethodFromObj<SwapChainGetBackBufferD>(state.SwapChain, SwapChain9VTableIndex.GetBackBuffer); - int hrBB = getBB(state.SwapChain, 0, D3DBACKBUFFER_TYPE_MONO, out IntPtr backBuffer); - if (hrBB < 0 || backBuffer == IntPtr.Zero) - { - if (diag) { RynthLog.Info($"ViewportRenderer: GetBackBuffer failed hr=0x{hrBB:X8}"); _logRender++; } - return; - } - - IntPtr oldRenderTarget = IntPtr.Zero; - int cmdCount = 0; - float ddW = 0, ddH = 0, ddX = 0, ddY = 0; - try - { - _getRenderTarget(_device, 0, out oldRenderTarget); - int hrSRT = _setRenderTarget(_device, 0, backBuffer); - - // Clear unless the ImGui viewport asked us not to. - uint flags = unchecked((uint)vp->Flags); - if ((flags & (uint)ImGuiViewportFlags.NoRendererClear) == 0) - { - _clear(_device, 0, null, D3DCLEAR_TARGET, 0x00000000u, 1.0f, 0); - } - - // Render the viewport's own draw data through the main DX9 backend, - // which already handles full state save/restore. - ImDrawDataPtr draw = new ImDrawDataPtr((ImDrawData*)vp->DrawData); - if ((IntPtr)draw.NativePtr != IntPtr.Zero) - { - IntPtr dd = (IntPtr)draw.NativePtr; - cmdCount = Marshal.ReadInt32(dd, 4); - ddX = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 20)); - ddY = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 24)); - ddW = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 28)); - ddH = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 32)); - DX9Backend.RenderDrawData(draw, _device); - } - - if (diag) - { - RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} setRT=0x{hrSRT:X8} bb=0x{backBuffer.ToInt64():X8} cmds={cmdCount} ddPos=({ddX},{ddY}) ddSize=({ddW},{ddH})"); - _logRender++; - } - } - finally - { - if (oldRenderTarget != IntPtr.Zero) - { - _setRenderTarget(_device, 0, oldRenderTarget); - ReleaseCom(oldRenderTarget); - } - ReleaseCom(backBuffer); - } - } - - private static void RendererSwapBuffers(ImGuiViewport* vp, IntPtr renderArg) - { - IntPtr key = (IntPtr)vp; - if (!_viewports.TryGetValue(key, out var state)) return; - if (state.SwapChain == IntPtr.Zero) return; - - var present = GetMethodFromObj<SwapChainPresentD>(state.SwapChain, SwapChain9VTableIndex.Present); - int hr = present(state.SwapChain, null, null, IntPtr.Zero, IntPtr.Zero, 0); - if (_logSwap++ < MaxLog) - RynthLog.Info($"ViewportRenderer: SwapBuffers vp=0x{key.ToInt64():X8} Present hr=0x{hr:X8}"); - } - - // ─── Helpers ────────────────────────────────────────────────────── - private static void CreateSwapChainForViewport(ImGuiViewport* vp, ViewportGpuState state, int w, int h) - { - if (_createAdditionalSwapChain == null) return; - - IntPtr hwnd = (IntPtr)vp->PlatformHandleRaw; - if (hwnd == IntPtr.Zero) hwnd = (IntPtr)vp->PlatformHandle; - if (hwnd == IntPtr.Zero) - { - RynthLog.Info("ViewportRenderer: viewport has no HWND — cannot create swap chain."); - return; - } - - var pp = new D3DPRESENT_PARAMETERS - { - BackBufferWidth = (uint)w, - BackBufferHeight = (uint)h, - BackBufferFormat = D3DFMT_UNKNOWN, // match device default - BackBufferCount = 1, - SwapEffect = D3DSWAPEFFECT_DISCARD, - hDeviceWindow = hwnd, - Windowed = 1, - // Don't wait for vblank — each popped viewport adds another Present - // per frame, and stacking vsyncs cuts the effective frame rate. - PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE, - }; - - int hr = _createAdditionalSwapChain(_device, &pp, out IntPtr swapChain); - if (hr < 0 || swapChain == IntPtr.Zero) - { - RynthLog.Info($"ViewportRenderer: CreateAdditionalSwapChain failed (hr=0x{hr:X8}) for {w}x{h} hwnd=0x{hwnd:X}"); - return; - } - - state.SwapChain = swapChain; - state.Width = w; - state.Height = h; - } - - private static T GetMethod<T>(IntPtr vtable, int index) where T : Delegate - { - IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size); - return Marshal.GetDelegateForFunctionPointer<T>(addr); - } - - private static T GetMethodFromObj<T>(IntPtr pObj, int index) where T : Delegate - { - IntPtr vtable = Marshal.ReadIntPtr(pObj); - IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size); - return Marshal.GetDelegateForFunctionPointer<T>(addr); - } - - private static void ReleaseCom(IntPtr pObj) - { - if (pObj == IntPtr.Zero) return; - IntPtr vtable = Marshal.ReadIntPtr(pObj); - IntPtr addr = Marshal.ReadIntPtr(vtable, 2 * IntPtr.Size); // Release is index 2 - var release = Marshal.GetDelegateForFunctionPointer<ReleaseD>(addr); - release(pObj); - } -} diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs index cd199bf..89f3510 100644 --- a/src/RynthCore.Engine/ImGui/Win32Backend.cs +++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using ImGuiNET; @@ -38,9 +39,22 @@ internal static unsafe class Win32Backend private const uint WM_SYSKEYDOWN = 0x0104; private const uint WM_SYSKEYUP = 0x0105; private const uint WM_CHAR = 0x0102; + private const uint WM_DEADCHAR = 0x0103; + private const uint WM_SYSCHAR = 0x0106; + private const uint WM_SYSDEADCHAR = 0x0107; + private const uint WM_UNICHAR = 0x0109; private const uint WM_SETCURSOR = 0x0020; private const uint WM_XBUTTONDOWN = 0x020B; private const uint WM_XBUTTONUP = 0x020C; + private const uint WM_LBUTTONDBLCLK = 0x0203; + private const uint WM_RBUTTONDBLCLK = 0x0206; + private const uint WM_MBUTTONDBLCLK = 0x0209; + // MK_* button bits (WM_MOUSEMOVE wParam) + private const int MK_LBUTTON = 0x0001; + private const int MK_RBUTTON = 0x0002; + private const int MK_MBUTTON = 0x0010; + private const int MK_XBUTTON1 = 0x0020; + private const int MK_XBUTTON2 = 0x0040; private const uint WM_CLOSE = 0x0010; // Set on the first WM_CLOSE so we kick off the engine teardown exactly @@ -71,7 +85,7 @@ internal static unsafe class Win32Backend public const uint WM_RYNTH_RUN_ACTION = 0x8002; // 0x8003 was WM_RYNTH_DESTROY_HWND (destroy a panel via the game window). - // Retired: LayeredWindow now posts WM_RYNTH_SELF_DESTROY (0x8005) to the + // Retired: LayeredWindow now posts WM_RYNTH_SELF_DESTROY (0x8051) to the // panel itself so it is destroyed on its real owner thread. Don't reuse 0x8003. /// <summary>Destroys floating-panel HWNDs on the game thread (their owner). @@ -80,6 +94,24 @@ internal static unsafe class Win32Backend /// load left behind (posted by Init). See LayeredWindow.DestroyThreadPanelWindows.</summary> public const uint WM_RYNTH_SWEEP_PANELS = 0x8004; + /// <summary>Posted by <see cref="PostToGameThread"/>: runs the queued actions on + /// the game thread without the caller waiting (pop-out windows are created this + /// way from inside EndScene, where creating an HWND inline is not safe).</summary> + public const uint WM_RYNTH_POST_ACTION = 0x8005; + + private static readonly System.Collections.Concurrent.ConcurrentQueue<Action> _postedActions = new(); + + /// <summary> + /// Queues <paramref name="action"/> to run on the game thread from the game + /// WndProc, and returns at once. Any thread. False when there is no game window. + /// </summary> + public static bool PostToGameThread(Action action) + { + if (_gameHwnd == IntPtr.Zero) return false; + _postedActions.Enqueue(action); + return PostMessage(_gameHwnd, WM_RYNTH_POST_ACTION, IntPtr.Zero, IntPtr.Zero); + } + private const int VK_CONTROL = 0x11; private const int VK_SHIFT = 0x10; private const int VK_MENU = 0x12; // Alt @@ -129,9 +161,6 @@ internal static unsafe class Win32Backend [DllImport("user32.dll")] private static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint); - [DllImport("user32.dll")] - private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint); - [DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT lpPoint); @@ -256,6 +285,9 @@ internal static unsafe class Win32Backend /// <summary>The game's main window handle.</summary> public static IntPtr GameHwnd => _gameHwnd; + [DllImport("user32.dll")] + private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + /// <summary> /// Populate <see cref="GameHwnd"/> from outside the ImGui Init path. /// Used by Avalonia-only overlay mode where ImGui is disabled but Avalonia @@ -378,6 +410,32 @@ internal static unsafe class Win32Backend private static readonly Queue<QueuedInputMessage> _pendingInput = new(); private static volatile bool _wantCaptureMouse; private static volatile bool _wantCaptureKeyboard; + + /// <summary> + /// True while the game window eats mouse input for the ImGui layer: the capture + /// flag the last ImGui frame published (Insert toggle and focus applied). Read + /// during the next frame, it says whether a click that arrived in between went + /// to ImGui (true) or to AC (false). AC thread. + /// </summary> + public static bool MouseCaptured => _wantCaptureMouse; + /// <summary>Stopwatch timestamp of the last ImGui frame that published capture + /// flags. The WndProc ignores (and clears) flags older than CaptureStaleMs, so a + /// frame that stops running (minimized, device lost, detour disabled during RL) + /// can't leave input being eaten with nothing drawn.</summary> + private static long _captureFlagsTicks; + private const int CaptureStaleMs = 250; + /// <summary>Mouse buttons currently held, as MK_* bits, observed on every mouse message.</summary> + private static int _heldMouseButtons; + /// <summary>True when the press that started the current held-button run was not + /// ImGui's (the cursor was not over an ImGui window). Until every button is + /// released, ImGui eats none of the mouse traffic: an RMB camera drag that + /// crosses an ImGui window keeps its moves and its RBUTTONUP.</summary> + private static bool _heldButtonsBelongToGame; + + /// <summary>io.WantTextInput from the last ImGui frame: an ImGui text box is + /// being typed in. Vetoes chat Enter-capture the way AvaloniaTextInputActive + /// does for Avalonia TextBoxes.</summary> + public static volatile bool ImGuiTextInputActive; private static bool _hasMouseCapture; private static bool _uiCaptureEnabled; private static bool _hasFocus; @@ -473,7 +531,13 @@ internal static unsafe class Win32Backend _wndProcDelegate = WndProcHook; IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate); _installedWndProcPtr = hookPtr; - _originalWndProc = SetWindowLong32(hWnd, GWL_WNDPROC, hookPtr); + // Under the native loader the window keeps the loader's permanent subclass + // (installed once per process); this generation only plugs its handler in. + _viaLoaderSubclass = Hooking.LoaderServices.Available; + if (_viaLoaderSubclass) + _originalWndProc = Hooking.LoaderServices.SubclassInstall(hWnd, hookPtr, out IntPtr previous) ? previous : IntPtr.Zero; + else + _originalWndProc = SetWindowLong32(hWnd, GWL_WNDPROC, hookPtr); // RynthLog.UI (not .Render — RenderEnabled is false) so chain // composition across generations is reconstructible from the log. RynthLog.UI($"Win32Backend: subclass installed — hook=0x{hookPtr:X8}, previous WndProc=0x{_originalWndProc:X8}."); @@ -498,6 +562,7 @@ internal static unsafe class Win32Backend private static IntPtr _installedWndProcPtr; private static volatile bool _forwardOnly; + private static bool _viaLoaderSubclass; public static void Shutdown() { @@ -524,7 +589,14 @@ internal static unsafe class Win32Backend // valid because engine module pages are intentionally leaked across // reloads, and a no-longer-initialized backend just forwards. IntPtr currentProc = GetWindowLong32(_gameHwnd, GWL_WNDPROC); - if (currentProc == _installedWndProcPtr || currentProc == IntPtr.Zero) + if (_viaLoaderSubclass) + { + // The loader's subclass stays in the chain for good and now passes every + // message straight through: nothing points at this generation any more. + Hooking.LoaderServices.SubclassRelease(_gameHwnd); + RynthLog.UI("Win32Backend: Shutdown — handler removed from the loader's subclass (pass-through)."); + } + else if (currentProc == _installedWndProcPtr || currentProc == IntPtr.Zero) { SetWindowLong32(_gameHwnd, GWL_WNDPROC, _originalWndProc); RynthLog.UI("Win32Backend: Shutdown — WndProc restored (we were chain head)."); @@ -577,48 +649,51 @@ internal static unsafe class Win32Backend private static int _newFrameLogCount; - public static void NewFrame() + /// <summary> + /// Reads the game client size and publishes it to the Avalonia overlay. + /// Runs every frame while the ImGui backend is enabled, including frames + /// where no ImGui window is open and NewFrame is skipped. + /// </summary> + public static void UpdateClientMetrics(out int width, out int height) { - // Deferred focus restore: AvaloniaSubclassWndProc sets this flag when - // WM_SETFOCUS lands on the off-screen Avalonia HWND. We reclaim focus - // here (game thread owns _gameHwnd) so there's no cross-thread wait. - ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); - - // Update display size GetClientRect(_gameHwnd, out RECT rect); - int w = rect.Right - rect.Left; - int h = rect.Bottom - rect.Top; + width = rect.Right - rect.Left; + height = rect.Bottom - rect.Top; - _newFrameLogCount++; - - AvaloniaOverlay.ClientPixelWidth = w; - AvaloniaOverlay.ClientPixelHeight = h; - if ((_lastKnownClientWidth != w || _lastKnownClientHeight != h) && w > 1 && h > 1) + AvaloniaOverlay.ClientPixelWidth = width; + AvaloniaOverlay.ClientPixelHeight = height; + if ((_lastKnownClientWidth != width || _lastKnownClientHeight != height) && width > 1 && height > 1) { - _lastKnownClientWidth = w; - _lastKnownClientHeight = h; + _lastKnownClientWidth = width; + _lastKnownClientHeight = height; AvaloniaOverlay.NotifyGameSurfaceMetricsChanged(); AvaloniaOverlay.RequestCapture(); } + } + + public static void NewFrame(int clientWidth, int clientHeight) + { + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + _newFrameLogCount++; // If GetClientRect returns 0x0 or 1x1, the HWND might be wrong. // DisplaySize will be set from D3D viewport in EngineFrameController instead. - if (w > 1 && h > 1) - io.DisplaySize = new System.Numerics.Vector2(w, h); + if (clientWidth > 1 && clientHeight > 1) + io.DisplaySize = new System.Numerics.Vector2(clientWidth, clientHeight); FlushQueuedInput(io); - // Refresh the cursor position. With ViewportsEnable, ImGui expects - // absolute screen coords so it can route clicks to the correct viewport. - // Without it, client-relative coords are the simpler contract. + // Refresh the cursor position (client-relative; multi-viewport is not used). GetCursorPos(out POINT cursorPos); - if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) == 0) - ScreenToClient(_gameHwnd, ref cursorPos); + ScreenToClient(_gameHwnd, ref cursorPos); io.AddMousePosEvent(cursorPos.X, cursorPos.Y); SyncFocusState(io); bool insertDown = (GetAsyncKeyState(VK_INSERT) & 0x8000) != 0; - if (insertDown && !_insertWasDown) + // GetAsyncKeyState reads the physical key whatever window has focus: without + // the focus test, Insert (or Shift/Ctrl+Insert paste/copy) pressed in another + // client or app flipped this client's capture off unseen. + if (insertDown && !_insertWasDown && _hasFocus) { _uiCaptureEnabled = !_uiCaptureEnabled; RynthLog.Render($"Win32Backend: ImGui capture {(_uiCaptureEnabled ? "ENABLED" : "DISABLED")} (Insert)"); @@ -670,7 +745,13 @@ internal static unsafe class Win32Backend // CreateWindowExW etc. aren't stuck behind unrelated input handling. if (msg == WM_RYNTH_RUN_ACTION) { - Action? a = _pendingGameThreadAction; + // Take the action once. A send that timed out is still delivered + // later; without the take, that late delivery ran whatever action + // was pending by then and the action's own send ran it again + // (two LayeredWindows for one popout, one of them orphaned). +#pragma warning disable CS0420 // Interlocked access to a volatile field is still atomic. + Action? a = Interlocked.Exchange(ref _pendingGameThreadAction, null); +#pragma warning restore CS0420 if (a != null) { try { a(); } @@ -679,6 +760,16 @@ internal static unsafe class Win32Backend return IntPtr.Zero; } + if (msg == WM_RYNTH_POST_ACTION) + { + while (_postedActions.TryDequeue(out Action? posted)) + { + try { posted(); } + catch (Exception ex) { RynthLog.Info($"Win32Backend: posted action threw {ex.GetType().Name}: {ex.Message}"); } + } + return IntPtr.Zero; + } + if (msg == WM_RYNTH_SWEEP_PANELS) { try { UI.LayeredWindow.DestroyThreadPanelWindows(includeThisGeneration: wParam != IntPtr.Zero); } @@ -765,7 +856,7 @@ internal static unsafe class Win32Backend // ── Chat capture: consume all key input for the chat TextBox ──── // Game HWND keeps Win32 focus throughout; callbacks dispatch Text // updates to the panel on Avalonia's UI thread — no Avalonia focus needed. - if (ChatCaptureActive && IsKeyMessage(msg)) + if (ChatCaptureActive && (IsKeyMessage(msg) || IsExtraCharMessage(msg))) { if (msg == WM_CHAR) { @@ -843,7 +934,10 @@ internal static unsafe class Win32Backend // RynthChatOwnsChat: only while RynthChat is open AND hiding the retail chatbox — // whichever chat is visible gets Enter. Otherwise Enter belongs to AC's own chat, // which used to be unusable whenever RynthChat was installed, even closed. + // !ImGuiTextInputActive: the same rule for an ImGui text box. + ExpireStaleCaptureFlags(); if (msg == WM_KEYDOWN && (int)wParam == VK_RETURN && !IsExtendedKey(lParam) && !ChatCaptureActive && !AvaloniaTextInputActive + && !ImGuiTextInputActive && !ImGuiPopOuts.HasTextFocus && RynthCore.Engine.Compatibility.ChatHooks.RynthChatOwnsChat) { if (OnChatCaptureActivated != null) @@ -876,8 +970,17 @@ internal static unsafe class Win32Backend // the ImGui EnqueueInput/capture-eat below so ImGui never tracks the // HUD drag (keeps our SetCapture from fighting NewFrame's). No-op // unless the HUD is drawn. - if (IsMouseMessage(msg) && VitalHud.TryHandleMouse(hWnd, msg, wParam, lParam)) - return IntPtr.Zero; + if (IsMouseMessage(msg)) + { + TrackMouseButtons(msg, wParam); + ItemDragBridge.OnGameMouse(msg, wParam, lParam, _heldButtonsBelongToGame); + } + else if (msg == WM_KILLFOCUS) + { + _heldMouseButtons = 0; + _heldButtonsBelongToGame = false; + ItemDragBridge.Reset(); + } // ── Avalonia panel hit-test & input forwarding ──────────────── // Only in the world: between characters the overlay isn't drawn, so its @@ -919,19 +1022,42 @@ internal static unsafe class Win32Backend } // ───────────────────────────────────────────────────────────── + // A popped-out ImGui panel is typing (its window never has focus, so its keys + // arrive here), or the wheel turned over one: the pop-out gets it. A click + // on the game ends a pop-out's text edit (ImGuiPopOuts.RouteInput). + if (ImGuiPopOuts.RouteInput(msg, wParam, lParam)) + { + // Key-ups still reach the game: a key held before the text edit + // began must be released there (the "keeps moving" rule below). + if (msg == WM_KEYUP || msg == WM_SYSKEYUP) + return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam); + return IntPtr.Zero; + } + // Only enqueue if we did NOT already forward to Avalonia above. // (When AvaloniaTextInputActive is true and a key fires, we returned early.) if (IsMouseMessage(msg) || IsKeyMessage(msg) || IsFocusMessage(msg)) EnqueueInput(msg, wParam, lParam); - // If ImGui wants mouse input, eat mouse messages so the game doesn't get them - if (_wantCaptureMouse && IsMouseMessage(msg)) + // ImGui wants the mouse (io.WantCaptureMouse): eat it, unless the held + // buttons were pressed for the game (see _heldButtonsBelongToGame). + if (_wantCaptureMouse && IsMouseMessage(msg) && !_heldButtonsBelongToGame) return IntPtr.Zero; - // If ImGui wants keyboard input, eat keyboard messages - if (_wantCaptureKeyboard && IsKeyMessage(msg)) + // An ImGui text box is being typed in (io.WantTextInput): keep keys from + // the game, except key-ups. A key held before the click must still get + // its release, or AC's edge-triggered input stays latched (the "character + // keeps moving" bug); a stray key-up reaching AC is harmless. + // A pop-out's text box counts the same (RouteInput above took its keys; the + // dead-key / Alt+key char messages it doesn't route are dropped here). + if ((_wantCaptureKeyboard || ImGuiPopOuts.HasTextFocus) && IsTextKeyMessage(msg)) return IntPtr.Zero; + // Field check: a key-down or char about to reach AC while a RynthCore text box + // was active in the last frame is a leak. One log line per typing burst. + if (IsTextKeyMessage(msg)) + NoteKeyReachingGame(msg, wParam); + // ── Background FPS unlock: lie to AC so it never idle-throttles ── if (msg == WM_ACTIVATEAPP && EndSceneHook.FpsLimitEnabled) return CallWindowProcA(_originalWndProc, hWnd, msg, (IntPtr)1, lParam); @@ -953,6 +1079,14 @@ internal static unsafe class Win32Backend } } + // An AC inventory item dragged onto an ImGui window: AC must not drop it on the + // ground behind the window. It gets the release where the drag began instead. + if (ItemDragBridge.TryRedirectNativeDrop(msg, out IntPtr pressLParam)) + { + CallWindowProcA(_originalWndProc, hWnd, WM_MOUSEMOVE, (IntPtr)MK_LBUTTON, pressLParam); + return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, pressLParam); + } + // Pass through to original WndProc return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam); } @@ -963,10 +1097,6 @@ internal static unsafe class Win32Backend } } - /// <summary> - /// If the cursor is over the Avalonia shell panel, PostMessage the mouse event to - /// the off-screen Avalonia HWND and return true (caller should suppress game delivery). - /// </summary> /// <summary> /// ImGui windows are drawn on top of the Avalonia layer, so when the cursor is over /// an ImGui window (or an ImGui widget is active) mouse input must go to ImGui @@ -978,6 +1108,10 @@ internal static unsafe class Win32Backend return _wantCaptureMouse && !AvaloniaOverlay.HasPointerCapture; } + /// <summary> + /// If the cursor is over the Avalonia shell panel, PostMessage the mouse event to + /// the off-screen Avalonia HWND and return true (caller should suppress game delivery). + /// </summary> private static bool TryForwardToAvalonia(uint msg, IntPtr wParam, IntPtr lParam) { IntPtr avHwnd = AvaloniaOverlay.AvaloniaHwnd; @@ -1040,7 +1174,7 @@ internal static unsafe class Win32Backend AvaloniaOverlay.TryGetBarButtonTitleAt(releasePoint.X, releasePoint.Y, out string? releasedButtonTitle) && string.Equals(_pendingBarButtonTitle, releasedButtonTitle, StringComparison.OrdinalIgnoreCase)) { - AvaloniaOverlay.ActivateBarButton(releasedButtonTitle!); + PanelRouter.Toggle(releasedButtonTitle!); } // Persist bar position on drag-end. All the live moves were @@ -1175,7 +1309,7 @@ internal static unsafe class Win32Backend if (!string.IsNullOrEmpty(_pendingBarButtonTitle) && string.Equals(_pendingBarButtonTitle, barButtonTitle, StringComparison.OrdinalIgnoreCase)) { - AvaloniaOverlay.ActivateBarButton(barButtonTitle!); + PanelRouter.Toggle(barButtonTitle!); } _avIsButtonCapture = false; @@ -1278,7 +1412,7 @@ internal static unsafe class Win32Backend return false; } - private static ImGuiKey VkToImGuiKey(int vk) + internal static ImGuiKey VkToImGuiKey(int vk) { return vk switch { @@ -1344,6 +1478,19 @@ internal static unsafe class Win32Backend || msg == WM_CHAR; } + /// <summary>Char messages besides WM_CHAR: dead keys (accents) and Alt+key chars.</summary> + private static bool IsExtraCharMessage(uint msg) + { + return msg == WM_DEADCHAR || msg == WM_SYSCHAR || msg == WM_SYSDEADCHAR || msg == WM_UNICHAR; + } + + /// <summary>What a text box keeps from AC: key-downs and every char message. Never + /// key-ups (a key held before the edit began must still be released in AC).</summary> + private static bool IsTextKeyMessage(uint msg) + { + return msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN || msg == WM_CHAR || IsExtraCharMessage(msg); + } + private static bool IsFocusMessage(uint msg) { return msg == WM_SETFOCUS || msg == WM_KILLFOCUS || msg == WM_ACTIVATEAPP; @@ -1353,16 +1500,7 @@ internal static unsafe class Win32Backend { short x = (short)((long)lParam & 0xFFFF); short y = (short)(((long)lParam >> 16) & 0xFFFF); - if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0) - { - POINT p = new POINT { X = x, Y = y }; - ClientToScreen(_gameHwnd, ref p); - io.AddMousePosEvent(p.X, p.Y); - } - else - { - io.AddMousePosEvent(x, y); - } + io.AddMousePosEvent(x, y); } private static void UpdateMouseButton(ImGuiIOPtr io, int buttonIndex, int virtualKey) @@ -1371,13 +1509,191 @@ internal static unsafe class Win32Backend SetMouseButtonState(io, buttonIndex, isDown); } - public static void UpdateCaptureFlags(bool wantMouse, bool wantKeyboard) + /// <summary> + /// Publishes what the ImGui frame just built wants: <paramref name="wantMouse"/> + /// is io.WantCaptureMouse, <paramref name="wantTextInput"/> a text box holds the + /// keyboard (io.WantTextInput, or a box that went active this frame). + /// Keyboard capture follows text input only (not IsAnyItemActive), so holding + /// a slider never swallows game keys. The Insert toggle (_uiCaptureEnabled) + /// and game focus gate the mouse only. + /// + /// The keyboard is not gated (2026-10-04, keys typed into Chat Filters also + /// reached AC): ImGui is fed every key whatever the gate says (EnqueueInput), so a + /// box left open with the gate shut typed into the box AND the game. A key that + /// reaches the game WndProc means AC has keyboard focus anyway; Insert-off ends + /// the text edit instead (EngineFrameController), so keys go back to the game. + /// </summary> + public static void UpdateCaptureFlags(bool wantMouse, bool wantTextInput) { - // ImGui.NET's WantCaptureMouse/WantCaptureKeyboard read from wrong native - // offsets (struct layout mismatch, same class of bug as ImDrawCmd stride). - // Use _uiCaptureEnabled directly — Insert key gives user explicit control. - _wantCaptureMouse = _uiCaptureEnabled && _hasFocus && wantMouse; - _wantCaptureKeyboard = _uiCaptureEnabled && _hasFocus && wantKeyboard; + bool live = _uiCaptureEnabled && _hasFocus; + _wantCaptureMouse = live && wantMouse; + _wantCaptureKeyboard = wantTextInput; + ImGuiTextInputActive = wantTextInput; + if (wantTextInput) _keyboardExpiryLogged = false; + Volatile.Write(ref _captureFlagsTicks, Stopwatch.GetTimestamp()); + } + + /// <summary>The Insert toggle: false while the player has released the UI. AC thread.</summary> + public static bool UiCaptureEnabled => _uiCaptureEnabled; + + public static string DescribeCapture() => + $"wantMouse={_wantCaptureMouse} wantText={_wantCaptureKeyboard} popOutText={ImGuiPopOuts.TextFocusTitle ?? "-"} insertToggle={_uiCaptureEnabled} focus={_hasFocus} heldButtons=0x{_heldMouseButtons:X} heldForGame={_heldButtonsBelongToGame}"; + + /// <summary>No ImGui frame this tick: ImGui wants nothing.</summary> + public static void ClearCaptureFlags() + { + _wantCaptureMouse = false; + _wantCaptureKeyboard = false; + ImGuiTextInputActive = false; + } + + /// <summary> + /// Keyboard capture outlives a missing frame for this long, counted from the first + /// message after the last frame (see ExpireStaleCaptureFlags). Longer than the mouse's: + /// the FPS governor can run a client at 1 fps. + /// </summary> + private const int KeyboardStaleMs = 1500; + private static long _firstMessageSinceFrameTicks; + private static bool _keyboardExpiryLogged; + + /// <summary> + /// Clears capture flags that no ImGui frame has refreshed recently. + /// Mouse: 250 ms after the last frame, as before. Keyboard: only once messages have + /// kept arriving for KeyboardStaleMs with no frame. Counting from the frame let a + /// stall leak keys: AC's thread runs both the frames and this WndProc, so the keys + /// typed during a slow stretch (a long frame or pop-out readback, AC busy) are + /// dispatched together right after it, and every one of them found the flag "stale" + /// and went to AC while the box was still open. + /// </summary> + private static void ExpireStaleCaptureFlags() + { + if (!_wantCaptureMouse && !_wantCaptureKeyboard && !ImGuiTextInputActive) + return; + long now = Stopwatch.GetTimestamp(); + long frame = Volatile.Read(ref _captureFlagsTicks); + if (_wantCaptureMouse && now - frame > Stopwatch.Frequency * CaptureStaleMs / 1000) + _wantCaptureMouse = false; + if (!_wantCaptureKeyboard && !ImGuiTextInputActive) + return; + if (_firstMessageSinceFrameTicks < frame) + { + _firstMessageSinceFrameTicks = now; // the first message since that frame + return; + } + long waited = now - _firstMessageSinceFrameTicks; + if (waited <= Stopwatch.Frequency * KeyboardStaleMs / 1000) + return; + _wantCaptureKeyboard = false; + ImGuiTextInputActive = false; + if (!_keyboardExpiryLogged) + { + _keyboardExpiryLogged = true; + RynthLog.UI($"[Input] keyboard capture released: no ImGui frame for {(now - frame) * 1000 / Stopwatch.Frequency} ms while a text box was open (owner: {ImGuiTextFocus.ActiveOwner ?? "unknown"})."); + } + } + + // ── Leak diagnostic ───────────────────────────────────────────────── + private const int LeakBurstGapMs = 2000; // keys closer together than this are one burst + private const int MaxLeakLines = 100; // per engine load + private static long _leakBurstEndTicks; + private static int _leakLines; + private static int _leakKeysInBurst; + + /// <summary> + /// A key-down or char is about to reach AC. If a RynthCore text box was active in the + /// last frame (ImGuiTextFocus, which reads the box itself, not the capture flags), that + /// is a keyboard leak: log it, once per typing burst. AC thread (WndProc). + /// </summary> + private static void NoteKeyReachingGame(uint msg, IntPtr wParam) + { + string? owner = ImGuiTextFocus.ActiveOwner; + if (owner == null) return; + long now = Stopwatch.GetTimestamp(); + bool newBurst = now > _leakBurstEndTicks; + _leakBurstEndTicks = now + Stopwatch.Frequency * LeakBurstGapMs / 1000; + if (!newBurst) + { + _leakKeysInBurst++; + return; + } + int previous = _leakKeysInBurst; + _leakKeysInBurst = 1; + if (_leakLines >= MaxLeakLines) return; + _leakLines++; + string name = msg switch + { + WM_KEYDOWN => "WM_KEYDOWN", + WM_SYSKEYDOWN => "WM_SYSKEYDOWN", + WM_CHAR => "WM_CHAR", + WM_SYSCHAR => "WM_SYSCHAR", + WM_DEADCHAR => "WM_DEADCHAR", + WM_SYSDEADCHAR => "WM_SYSDEADCHAR", + WM_UNICHAR => "WM_UNICHAR", + _ => $"0x{msg:X4}", + }; + RynthLog.UI($"[Input] key reached AC while an ImGui text box was active (owner: {owner}; {name} 0x{(long)wParam:X}" + + (previous > 1 ? $"; previous burst {previous} keys" : "") + $"; {DescribeCapture()})."); + } + + /// <summary> + /// Drops queued input while no ImGui frame runs (nothing would drain it) and + /// resets ImGui's key/button state so a key or button released while idle + /// doesn't read as held when frames resume. AC thread, ImGui context current. + /// </summary> + public static void DiscardQueuedInput() + { + lock (_inputLock) + _pendingInput.Clear(); + } + + public static void ResetImGuiInputState(ImGuiIOPtr io) + { + for (int i = 0; i < _mouseButtons.Length; i++) + SetMouseButtonState(io, i, false); + io.ClearInputKeys(); + } + + /// <summary>MK_* bit for a button message's button (0 for non-button messages).</summary> + private static int MouseButtonBit(uint msg, IntPtr wParam) => msg switch + { + WM_LBUTTONDOWN or WM_LBUTTONUP or WM_LBUTTONDBLCLK => MK_LBUTTON, + WM_RBUTTONDOWN or WM_RBUTTONUP or WM_RBUTTONDBLCLK => MK_RBUTTON, + WM_MBUTTONDOWN or WM_MBUTTONUP or WM_MBUTTONDBLCLK => MK_MBUTTON, + WM_XBUTTONDOWN or WM_XBUTTONUP => (((long)wParam >> 16) & 0xFFFF) == 1 ? MK_XBUTTON1 : MK_XBUTTON2, + _ => 0, + }; + + /// <summary> + /// Tracks held buttons and who owns the current press (see + /// _heldButtonsBelongToGame). Runs for every mouse message before anyone + /// handles it, so the bookkeeping never depends on which layer took it. + /// </summary> + private static void TrackMouseButtons(uint msg, IntPtr wParam) + { + if (msg == WM_MOUSEMOVE) + { + // MOUSEMOVE carries the real button state; resync so a release we + // never saw (outside the window, focus change) can't leave a button stuck. + _heldMouseButtons = (int)((long)wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON | MK_XBUTTON1 | MK_XBUTTON2)); + if (_heldMouseButtons == 0) _heldButtonsBelongToGame = false; + return; + } + + int bit = MouseButtonBit(msg, wParam); + if (bit == 0) return; + + bool down = msg is WM_LBUTTONDOWN or WM_RBUTTONDOWN or WM_MBUTTONDOWN or WM_XBUTTONDOWN + or WM_LBUTTONDBLCLK or WM_RBUTTONDBLCLK or WM_MBUTTONDBLCLK; + if (down) + { + if (_heldMouseButtons == 0) + _heldButtonsBelongToGame = !_wantCaptureMouse; + _heldMouseButtons |= bit; + } + else + { + _heldMouseButtons &= ~bit; + } } public static bool IsUiCaptureEnabled() diff --git a/src/RynthCore.Engine/LogSettings.cs b/src/RynthCore.Engine/LogSettings.cs index 2936573..cda2df7 100644 --- a/src/RynthCore.Engine/LogSettings.cs +++ b/src/RynthCore.Engine/LogSettings.cs @@ -152,6 +152,27 @@ internal static class LogSettings return sb.ToString(); } + /// <summary> + /// Categories whose emit level is more verbose than the global level, so none of their lines + /// are written (e.g. every category at Trace with LoggingLevel Info: an almost empty log). + /// Empty when nothing is hidden. + /// </summary> + internal static string HiddenCategoriesWarning() + { + EntryPoint.EngineLogLevel global = EntryPoint.LoggingLevel; + EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels); + var hidden = new StringBuilder(); + for (int i = 0; i < levels.Length; i++) + { + if (levels[i] == EntryPoint.EngineLogLevel.Off || levels[i] <= global) continue; + if (hidden.Length > 0) hidden.Append(", "); + hidden.Append((LogCategory)i).Append('=').Append(levels[i]); + } + return hidden.Length == 0 ? "" + : $"LogSettings: {hidden} write above the global LoggingLevel ({global}), so those lines are NOT logged. " + + "Raise LoggingLevel to the most verbose category level, or set the categories to Info."; + } + /// <summary>Starts the once-a-second engine.json poll. Idempotent.</summary> internal static void StartWatcher() { @@ -199,6 +220,8 @@ internal static class LogSettings // Bypasses the category levels so a change is visible whenever Info is in range. if (EntryPoint.ShouldLog(EntryPoint.EngineLogLevel.Info)) EntryPoint.LogTagged("engine", $"LogSettings: engine.json changed - logging reloaded ({summary}).", "INF"); + string hidden = HiddenCategoriesWarning(); + if (hidden.Length > 0) RynthLog.Warn(hidden); } catch { diff --git a/src/RynthCore.Engine/MainThreadHangWatchdog.cs b/src/RynthCore.Engine/MainThreadHangWatchdog.cs index 48ffc5c..8f571ee 100644 --- a/src/RynthCore.Engine/MainThreadHangWatchdog.cs +++ b/src/RynthCore.Engine/MainThreadHangWatchdog.cs @@ -56,6 +56,12 @@ internal static class MainThreadHangWatchdog // x86 CONTEXT is 716 bytes; over-allocate for safety. ContextFlags is at offset 0. private const int CONTEXT_SIZE = 1232; + // While a wedge lasts, the "still hung" line is repeated this often. + private const long StillHungRepeatMs = 20_000; + + /// <summary>"unhandled ACCESS_VIOLATION at acclient.exe+0x18712F" when the current hang is a crash dialog.</summary> + internal static volatile string? CrashCause; + // Stalls longer than this with no EndScene beat = main thread wedged. private const long HangThresholdMs = 4000; // Max stack samples to take during a single hang (1/sec). A permanent freeze @@ -138,6 +144,7 @@ internal static class MainThreadHangWatchdog bool inHang = false; int sample = 0; long hangStartBeat = 0; + long lastStillHungLog = 0; while (Volatile.Read(ref _running) != 0) { @@ -160,6 +167,10 @@ internal static class MainThreadHangWatchdog hangStartBeat = lastBeat; RynthLog.Info("================================================================"); RynthLog.Error($"==== MAIN THREAD HANG DETECTED tid={tid} build={EntryPoint.BuildStamp} initCount={EntryPoint.InitCount} (stalled {stale}ms) ===="); + // A modal dialog (AC's error MessageBox) holds the main thread: say which. + string? box = Compatibility.MessageBoxHooks.Describe(); + if (box != null) RynthLog.Error($" hang cause: {box}"); + CrashCause = null; } if (sample < MaxSamplesPerHang) @@ -172,11 +183,27 @@ internal static class MainThreadHangWatchdog { sample++; RynthLog.Info($" (still hung after {MaxSamplesPerHang} samples — suppressing further samples until recovery)"); + lastStillHungLog = Environment.TickCount64; // Confirmed permanent wedge (~10s+): write one targeted // minidump for WinDbg post-mortem if the log stack walk // isn't enough. Once per session. TryWriteHangDump(tid, stale); } + else if (Environment.TickCount64 - lastStillHungLog >= StillHungRepeatMs) + { + // Repeat the confirmation while the wedge lasts. The + // launcher's wedge check reads only the last 16 KB of + // this log, and plugin lines kept coming after the + // 2026-09-28 12:04 crash dialog, pushing the single + // line out of that window: the crashed client was + // never restarted. The launcher also needs the banner + // in that window (it looks for "still hung after" AFTER + // the last "MAIN THREAD HANG DETECTED"), so the repeat + // carries it: the 18:06 death-portal crash sat frozen + // for over an hour with only the bare repeat. + lastStillHungLog = Environment.TickCount64; + RynthLog.Info($"==== MAIN THREAD HANG DETECTED (continuing) ==== (still hung after {MaxSamplesPerHang} samples — stalled {stale / 1000}s{(CrashCause != null ? ", " + CrashCause : "")})"); + } } else if (inHang) { @@ -209,6 +236,105 @@ internal static class MainThreadHangWatchdog catch { /* a diagnostic must never destabilize the host */ } } + // ── Crash dialogs ───────────────────────────────────────────────────── + // An unhandled exception on AC's main thread ends in msvcr70's _XcptFilter + // -> kernelbase!UnhandledExceptionFilter -> NtRaiseHardError: Windows' + // "Application Error" box, which waits there - a hang to this watchdog. + // The exception is still on that frozen stack: UnhandledExceptionFilter's + // one argument is the EXCEPTION_POINTERS. Find it by walking the EBP chain + // and checking each frame's first argument for a plausible exception + // record + x86 CONTEXT, then log the exception and walk the faulting stack. + // Read-only, from this thread, while the main thread sits in the dialog: + // nothing runs inside exception dispatch (in-process VEH/SUEF handlers are + // fatal in NativeAOT; see CrashLogger). + + private const int CTX_OFF_EBP = 180; + private const int X86_CONTEXT_BYTES = 716; + private const uint CONTEXT_i386 = 0x10000; + + private static void TryLogUnhandledException(IntPtr hangCtx) + { + try + { + uint ebp = (uint)Marshal.ReadInt32(hangCtx, CTX_OFF_EBP); + for (int frame = 0; frame < 12 && ebp != 0; frame++) + { + IntPtr f = (IntPtr)(long)ebp; + if (!Compatibility.SmartBoxLocator.IsMemoryReadable(f, 12)) return; + uint arg0 = (uint)Marshal.ReadInt32(f, 8); + if (TryReadExceptionPointers(arg0, out uint rec, out uint ctx)) + { + LogUnhandled(rec, ctx); + return; + } + uint next = (uint)Marshal.ReadInt32(f); + if (next <= ebp) return; // the chain must go up the stack + ebp = next; + } + } + catch { /* a diagnostic must never destabilize the host */ } + } + + private static bool TryReadExceptionPointers(uint ep, out uint rec, out uint ctx) + { + rec = ctx = 0; + if (ep < 0x10000 || !Compatibility.SmartBoxLocator.IsMemoryReadable((IntPtr)(long)ep, 8)) return false; + rec = (uint)Marshal.ReadInt32((IntPtr)(long)ep); + ctx = (uint)Marshal.ReadInt32((IntPtr)(long)ep, 4); + if (rec < 0x10000 || ctx < 0x10000) return false; + if (!Compatibility.SmartBoxLocator.IsMemoryReadable((IntPtr)(long)rec, 80)) return false; + if (!Compatibility.SmartBoxLocator.IsMemoryReadable((IntPtr)(long)ctx, X86_CONTEXT_BYTES)) return false; + uint code = (uint)Marshal.ReadInt32((IntPtr)(long)rec); + uint nParams = (uint)Marshal.ReadInt32((IntPtr)(long)rec, 16); + uint flags = (uint)Marshal.ReadInt32((IntPtr)(long)ctx); + // System errors (0xC0xxxxxx), C++ throw, breakpoint. The looser 0xC0000000 + // mask let stack garbage through: a normal close logged "exception + // code=0xD5000B88 at 0x00000000" (2026-09-28 20:16). + bool plausibleCode = (code & 0xFF000000) == 0xC0000000 || code == 0xE06D7363 || code == 0x80000003; + return plausibleCode && nParams <= 15 && (flags & CONTEXT_i386) != 0 + && Marshal.ReadInt32((IntPtr)(long)ctx, 184) != 0; // Eip + } + + private static void LogUnhandled(uint rec, uint ctx) + { + IntPtr r = (IntPtr)(long)rec; + uint code = (uint)Marshal.ReadInt32(r); + uint addr = (uint)Marshal.ReadInt32(r, 12); + uint nParams = (uint)Marshal.ReadInt32(r, 16); + string name = code switch + { + 0xC0000005 => "ACCESS_VIOLATION", + 0xC000001D => "ILLEGAL_INSTRUCTION", + 0xC0000094 => "INT_DIVIDE_BY_ZERO", + 0xC00000FD => "STACK_OVERFLOW", + 0xC0000409 => "STACK_BUFFER_OVERRUN", + 0xC0000374 => "HEAP_CORRUPTION", + 0xE06D7363 => "C++ exception", + _ => "exception", + }; + string where = CrashLogger.ResolveCodeAddr((IntPtr)(long)addr); + string detail = ""; + if (code == 0xC0000005 && nParams >= 2) + { + uint op = (uint)Marshal.ReadInt32(r, 20); + uint target = (uint)Marshal.ReadInt32(r, 24); + detail = $" — {(op == 0 ? "read of" : op == 1 ? "write to" : op == 8 ? "execute at" : "access to")} 0x{target:X8}"; + } + CrashCause = $"unhandled {name} at {where}"; + RynthLog.Error($"==== UNHANDLED EXCEPTION on AC's main thread (Windows' error dialog is open): {name} code=0x{code:X8} at 0x{addr:X8} {where}{detail} ===="); + + // Walk the faulting stack from a private copy of the CONTEXT. + IntPtr copy = Marshal.AllocHGlobal(CONTEXT_SIZE); + try + { + for (int i = 0; i < CONTEXT_SIZE; i += 4) Marshal.WriteInt32(copy, i, 0); + for (int i = 0; i < X86_CONTEXT_BYTES; i += 4) + Marshal.WriteInt32(copy, i, Marshal.ReadInt32((IntPtr)(long)ctx, i)); + CrashLogger.DumpExternalContext(copy, "CRASH"); + } + finally { Marshal.FreeHGlobal(copy); } + } + private static void CaptureMainThreadStack(uint tid, long staleMs, int sampleNum, bool fullStack) { IntPtr h = OpenThread(THREAD_GET_CONTEXT | THREAD_SUSPEND_RESUME | THREAD_QUERY_INFORMATION, false, tid); @@ -247,7 +373,12 @@ internal static class MainThreadHangWatchdog RynthLog.Info($" sample#{sampleNum} (stale {staleMs}ms) eip=0x{eip:X8} {CrashLogger.ResolveCodeAddr((IntPtr)eip)}"); if (fullStack) + { CrashLogger.DumpExternalContext(ctx, "HANG"); + // A closing client stalls in ExitProcess, not in a crash dialog. + if (!Compatibility.ProcessExitHooks.TerminationIntercepted) + TryLogUnhandledException(ctx); + } } catch (Exception ex) { diff --git a/src/RynthCore.Engine/Native/cimgui.dll b/src/RynthCore.Engine/Native/cimgui.dll index 39fcfe5..fc15aa0 100644 Binary files a/src/RynthCore.Engine/Native/cimgui.dll and b/src/RynthCore.Engine/Native/cimgui.dll differ diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index 3878f67..e8692b7 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -7,10 +7,15 @@ namespace RynthCore.Engine.Plugins; internal static class EngineSettings { - private static readonly string SettingsPath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "RynthCore", - "engine.json"); + // RYNTHCORE_ENGINE_SETTINGS points a test client at its own engine.json (its own + // plugin list, no Avalonia, ...) without touching the one real clients share. + private static readonly string SettingsPath = + Environment.GetEnvironmentVariable("RYNTHCORE_ENGINE_SETTINGS") is { Length: > 0 } overridePath + ? overridePath + : Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "RynthCore", + "engine.json"); private static List<string> _pluginPaths = new(); private static bool _enableImGuiShell = true; @@ -23,9 +28,11 @@ internal static class EngineSettings private static bool _enableImGuiBackend = true; private static bool _enablePluginOverlayWindows = true; private static bool _enableHangMinidump = true; - private static bool _drawCustomVitalBars = true; private static bool _preventIdleLogoff = true; private static string _loggingLevel = "Info"; + private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto; + private static bool _decalInGameImGui = true; + private static bool _decalStandDown = true; private static bool _loaded; public static IReadOnlyList<string> PluginPaths @@ -82,10 +89,25 @@ internal static class EngineSettings get { EnsureLoaded(); +#if ENGINE_CORECLR + // Avalonia can't live in an unloadable engine (docs/UNLOADABLE_ENGINE_PLAN.md, + // Phase 5): Skia/HarfBuzz keep strong GC handles for their native callbacks, so + // the generation never unloads, and the next generation's copy finds the old + // one's assemblies ("Call from invalid thread"). The in-game panels are ImGui; + // pop-outs return as ImGui windows (IMGUI_PARITY_PLAN P5). + if (_enableAvaloniaOverlay && System.Threading.Interlocked.Exchange(ref _avaloniaOffLogged, 1) == 0) + RynthLog.Info("EngineSettings: EnableAvaloniaOverlay ignored - the CoreCLR engine runs without Avalonia (it can't be unloaded)."); + return false; +#else return _enableAvaloniaOverlay; +#endif } } +#if ENGINE_CORECLR + private static int _avaloniaOffLogged; +#endif + /// <summary>When false, D3D9Bootstrapper.Start() is skipped at LoginComplete so neither /// Direct3DCreate9/CreateDevice nor IDirect3DDevice9::EndScene get hooked. Eliminates the /// entire D3D9 detour path, ImGui per-frame work, and the in-AC overlay bar. Compatibility @@ -145,6 +167,14 @@ internal static class EngineSettings EnsureLoaded(); return _enableImGuiBackend; } + set + { + // Set in game with /rc imgui on|off; persisted to engine.json. + EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file + if (_enableImGuiBackend == value) return; + _enableImGuiBackend = value; + Save(); + } } /// <summary>When true (default) and the ImGui shell is off, plugins that export @@ -173,27 +203,6 @@ internal static class EngineSettings } } - /// <summary>When true, the engine draws the custom D3D9 Health/Stamina/Mana HUD - /// (<see cref="D3D9.VitalHud"/>) in EndScene. Toggleable live via "/rc vitals"; - /// the setter persists to engine.json so it survives relaunch. Default true. - /// Only takes visible effect on a clean (no-Decal) client where the - /// D3D9/EndScene path runs.</summary> - public static bool DrawCustomVitalBars - { - get - { - EnsureLoaded(); - return _drawCustomVitalBars; - } - set - { - EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file - if (_drawCustomVitalBars == value) return; - _drawCustomVitalBars = value; - Save(); - } - } - /// <summary>When true (default), the engine keeps the retail client's idle clock fresh /// while in the world, so ClientUISystem::UseTime's 20-minute idle auto-logoff /// (InactiveTimeBeforeLogout) can't log off a character a bot is playing: the bot's @@ -220,6 +229,56 @@ internal static class EngineSettings } } + /// <summary>"DecalBridge" in engine.json: Auto (default), On or Off. Only matters when + /// Decal is loaded in the same client (docs/DECAL_BRIDGE_PLAN.md): + /// Auto - bridge mode when the RynthCore Decal bridge is registered and says hello + /// within a short wait; otherwise the old coexistence mode. + /// On - bridge mode whenever Decal is loaded (no fallback; for testing). + /// Off - never bridge mode (the old coexistence mode). + /// Without Decal the setting is never read past this flag.</summary> + public static DecalBridgeMode DecalBridgeMode + { + get + { + EnsureLoaded(); + return _decalBridgeMode; + } + } + + /// <summary>"DecalInGameImGui" in engine.json (default true since 2026-09-30, after the + /// Reset, UB and soak checks in docs/DECAL_BRIDGE_PLAN.md). Only read when Decal is loaded + /// in the same client and bridge mode is on: true installs the normal EndScene hook and + /// ImGui renderer there (the device is found without creating one); false keeps the old + /// Decal-coexistence "no D3D9" path. RYNTHCORE_DECAL_IMGUI=1/0 overrides it for one client. + /// Without Decal it is never read.</summary> + public static bool DecalInGameImGui + { + get + { + string? env = Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_IMGUI"); + if (env == "1") return true; + if (env == "0") return false; + EnsureLoaded(); + return _decalInGameImGui; + } + } + + /// <summary>"DecalStandDown" in engine.json (default true, 2026-10-03). Only read when + /// Decal is loaded in the same client and the Decal bridge is NOT active (not registered + /// as the client sees it, no hello, protocol mismatch): true makes the engine stand down + /// (EntryPoint.InitWorker) - no plugins, no overlay, none of the hooks that collide with + /// Decal; only what the "bridge isn't loaded" chat line needs. The old coexistence path + /// (no overlay, then crashes) ran there before. false brings that path back. + /// DecalBridge=Off always keeps the old path (tests). Without Decal it is never read.</summary> + public static bool DecalStandDown + { + get + { + EnsureLoaded(); + return _decalStandDown; + } + } + public static void AddPluginPath(string path) { EnsureLoaded(); @@ -330,12 +389,24 @@ internal static class EngineSettings _enableHangMinidump = hmEl.GetBoolean(); } - if (doc.RootElement.TryGetProperty("DrawCustomVitalBars", out var cvbEl) && - (cvbEl.ValueKind == JsonValueKind.True || cvbEl.ValueKind == JsonValueKind.False)) + + if (doc.RootElement.TryGetProperty("DecalBridge", out var dbEl)) { - _drawCustomVitalBars = cvbEl.GetBoolean(); + if (dbEl.ValueKind == JsonValueKind.True) _decalBridgeMode = DecalBridgeMode.On; + else if (dbEl.ValueKind == JsonValueKind.False) _decalBridgeMode = DecalBridgeMode.Off; + else if (dbEl.ValueKind == JsonValueKind.String && + Enum.TryParse(dbEl.GetString(), ignoreCase: true, out DecalBridgeMode dbm)) + _decalBridgeMode = dbm; } + if (doc.RootElement.TryGetProperty("DecalInGameImGui", out var dimEl) && + (dimEl.ValueKind == JsonValueKind.True || dimEl.ValueKind == JsonValueKind.False)) + _decalInGameImGui = dimEl.GetBoolean(); + + if (doc.RootElement.TryGetProperty("DecalStandDown", out var dsdEl) && + (dsdEl.ValueKind == JsonValueKind.True || dsdEl.ValueKind == JsonValueKind.False)) + _decalStandDown = dsdEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) && (pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False)) { @@ -381,11 +452,16 @@ internal static class EngineSettings w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend); w.WriteBoolean("EnablePluginOverlayWindows", _enablePluginOverlayWindows); w.WriteBoolean("EnableHangMinidump", _enableHangMinidump); - w.WriteBoolean("DrawCustomVitalBars", _drawCustomVitalBars); w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff); // Preserve the launcher-chosen level; dropping it here would reset logging to Info. w.WriteString("LoggingLevel", _loggingLevel); CopyUnownedFields(w); + if (_decalBridgeMode != DecalBridgeMode.Auto) // default: leave the file as it was + w.WriteString("DecalBridge", _decalBridgeMode.ToString()); + if (!_decalInGameImGui) // default true: leave the file as it was + w.WriteBoolean("DecalInGameImGui", false); + if (!_decalStandDown) // default true: leave the file as it was + w.WriteBoolean("DecalStandDown", false); w.WriteEndObject(); } File.WriteAllBytes(SettingsPath, ms.ToArray()); @@ -403,6 +479,8 @@ internal static class EngineSettings "PluginPaths", "EnableImGuiShell", "EnablePlugins", "EnableDatShareHook", "EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount", "EnableImGuiBackend", "EnablePluginOverlayWindows", "EnableHangMinidump", "DrawCustomVitalBars", "PreventIdleLogoff", "LoggingLevel", + // Save() writes these only when non-default, so copying them through would duplicate keys. + "DecalBridge", "DecalInGameImGui", "DecalStandDown", }; /// <summary>Writes every top-level engine.json field not in <see cref="OwnedFields"/> as-is.</summary> @@ -425,3 +503,6 @@ internal static class EngineSettings } } } + +/// <summary>engine.json "DecalBridge" (see <see cref="EngineSettings.DecalBridgeMode"/>).</summary> +internal enum DecalBridgeMode { Auto = 0, On = 1, Off = 2 } diff --git a/src/RynthCore.Engine/Plugins/ManagedPlugins.cs b/src/RynthCore.Engine/Plugins/ManagedPlugins.cs new file mode 100644 index 0000000..48fa4c3 --- /dev/null +++ b/src/RynthCore.Engine/Plugins/ManagedPlugins.cs @@ -0,0 +1,203 @@ +// ============================================================================ +// RynthCore.Engine - Plugins/ManagedPlugins.cs +// +// Managed plugins (docs/UNLOADABLE_ENGINE_PLAN.md, Phase 4). Under the CoreCLR engine +// a plugin can be a plain managed assembly instead of a NativeAOT DLL: the same +// source, built with -p:PublishAot=false. It keeps its C ABI: the +// [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit")] etc. methods the NativeAOT +// build exports are found by reflection instead of GetProcAddress, so PluginLoader, +// PluginManager and the panels' export lookups work unchanged through a stand-in +// module handle. +// +// Each plugin loads into its own collectible AssemblyLoadContext (its dependencies, +// e.g. RynthCore.PluginSdk or MoonSharp, from its own folder), unloaded after its +// RynthPluginShutdown. Unlike a NativeAOT plugin (its own runtime, never freed) it +// shares the engine's runtime and GC and goes away with a reload. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +#if ENGINE_CORECLR +using System.Runtime.Loader; +#endif + +namespace RynthCore.Engine.Plugins; + +internal static class ManagedPlugins +{ + // Stand-in handles: real module bases are 64 KB aligned, these never are. + private static int _nextHandle = 0x7F000001; + private static readonly object Sync = new(); + private static readonly Dictionary<IntPtr, Entry> Loaded = new(); + + private sealed class Entry + { + public required string Name; + public required Dictionary<string, IntPtr> Exports; +#if ENGINE_CORECLR + public required PluginLoadContext Context; +#endif + } + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true, EntryPoint = "GetProcAddress")] + private static extern IntPtr Kernel32GetProcAddress(IntPtr hModule, string lpProcName); + + /// <summary>GetProcAddress for plugin handles: a managed plugin's export map, else kernel32.</summary> + public static IntPtr GetProcAddress(IntPtr handle, string name) + { + lock (Sync) + { + if (Loaded.TryGetValue(handle, out Entry? e)) + return e.Exports.TryGetValue(name, out IntPtr fn) ? fn : IntPtr.Zero; + } + return Kernel32GetProcAddress(handle, name); + } + + public static bool IsManagedHandle(IntPtr handle) + { + lock (Sync) return Loaded.ContainsKey(handle); + } + + /// <summary>True when <paramref name="path"/> is a .NET assembly (PE with a CLR header).</summary> + public static bool IsManagedAssembly(string path) + { + try + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var pe = new System.Reflection.PortableExecutable.PEReader(fs); + return pe.HasMetadata && pe.PEHeaders.CorHeader != null; + } + catch + { + return false; + } + } + + /// <summary>Loads a managed plugin; returns its stand-in module handle, or zero.</summary> + public static IntPtr Load(string path) + { + string fileName = Path.GetFileName(path); +#if ENGINE_CORECLR + try + { + var context = new PluginLoadContext(fileName, Path.GetDirectoryName(path)!); + Assembly assembly = context.LoadFromFile(path); + var exports = new Dictionary<string, IntPtr>(StringComparer.Ordinal); + foreach (Type type in assembly.GetTypes()) + { + foreach (MethodInfo m in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly)) + { + if (m.GetCustomAttribute<UnmanagedCallersOnlyAttribute>()?.EntryPoint is { Length: > 0 } entry) + exports[entry] = m.MethodHandle.GetFunctionPointer(); + } + } + IntPtr handle; + lock (Sync) + { + handle = (IntPtr)_nextHandle; + _nextHandle += 2; + Loaded[handle] = new Entry { Name = fileName, Exports = exports, Context = context }; + } + RynthLog.Plugin($"ManagedPlugins: {fileName} loaded into its own collectible context ({exports.Count} exports)."); + return handle; + } + catch (Exception ex) + { + RynthLog.Plugin($"ManagedPlugins: FAILED to load {fileName}: {ex}"); + return IntPtr.Zero; + } +#else + RynthLog.Plugin($"ManagedPlugins: {fileName} is a managed plugin; it needs the CoreCLR engine (this is the NativeAOT one). Skipping."); + return IntPtr.Zero; +#endif + } + + private static readonly List<Entry> PendingUnload = new(); + + /// <summary> + /// Retires a managed plugin (after its RynthPluginShutdown). Its context is only + /// unloaded by <see cref="UnloadRetired"/> at the very end of the engine's shutdown: + /// until then the plugin pump, the pop-outs' last frames and cached export pointers + /// can still call into it, and once a context is unloaded any GC may free its code + /// (2026-09-29: RynthAi's shutdown GC freed the others mid-teardown -> runtime abort). + /// </summary> + public static void Unload(IntPtr handle) + { + lock (Sync) + { + // Stays in Loaded (its exports still resolve) until UnloadRetired. + if (Loaded.TryGetValue(handle, out Entry? e) && !PendingUnload.Contains(e)) + PendingUnload.Add(e); + } + } + + /// <summary>Unloads every retired plugin's context. Last step of EngineLifecycle.Shutdown.</summary> + public static void UnloadRetired() + { + List<Entry> retired; + lock (Sync) + { + retired = new List<Entry>(PendingUnload); + PendingUnload.Clear(); + foreach (var kv in new List<KeyValuePair<IntPtr, Entry>>(Loaded)) + if (retired.Contains(kv.Value)) Loaded.Remove(kv.Key); + } +#if ENGINE_CORECLR + foreach (Entry e in retired) + e.Context.Unload(); + if (retired.Count > 0) + RynthLog.Plugin($"ManagedPlugins: {retired.Count} plugin context(s) unloading: {string.Join(", ", retired.ConvertAll(e => e.Name))}."); +#endif + } + +#if ENGINE_CORECLR + /// <summary>A plugin and its private dependencies (from the plugin's folder).</summary> + private sealed class PluginLoadContext : AssemblyLoadContext + { + private readonly string _dir; + + public PluginLoadContext(string name, string dir) : base("plugin " + name, isCollectible: true) => _dir = dir; + + public Assembly LoadFromFile(string path) + { + // From streams, so the plugin's folder stays unlocked (rebuilds overwrite it). + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + string pdb = Path.ChangeExtension(path, ".pdb"); + if (!File.Exists(pdb)) return LoadFromStream(fs); + using var ps = new FileStream(pdb, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + return LoadFromStream(fs, ps); + } + + private static readonly HashSet<string> PrivateFramework = new(StringComparer.OrdinalIgnoreCase) + { + "System.Text.Json", "System.Text.Encodings.Web", "System.IO.Pipelines", + }; + + protected override Assembly? Load(AssemblyName name) + { + // The plugin's own dependencies (SDK, MoonSharp...) load privately; so do the + // framework libraries that cache the types they see process-wide + // (System.Text.Json roots a collectible context from the default one: Phase 0). + // The rest of the framework comes from the default context. + if (PrivateFramework.Contains(name.Name!)) + { + string fx = Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location)!, name.Name + ".dll"); + return File.Exists(fx) ? LoadFromAssemblyPath(fx) : null; + } + string candidate = Path.Combine(_dir, name.Name + ".dll"); + return File.Exists(candidate) ? LoadFromFile(candidate) : null; + } + + protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) + { + string candidate = Path.Combine(_dir, unmanagedDllName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + ? unmanagedDllName + : unmanagedDllName + ".dll"); + return File.Exists(candidate) ? LoadUnmanagedDllFromPath(candidate) : IntPtr.Zero; + } + } +#endif +} diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 7701407..b4b0de8 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -585,8 +585,8 @@ internal struct RynthCoreAPI public IntPtr SendPluginCommandFn; /// <summary>Function pointer: int GetObjectDataIdProperty(uint objectId, uint stype, uint* value) - /// Reads a STypeDID property that lives in the object's PublicWeenieDesc (Icon=8 → _iconID, - /// IconOverlay=50 → _iconOverlayID, IconUnderlay=52 → _iconUnderlayID). Read directly from the embedded PWD struct — network-populated, so it works on + /// Reads a STypeDID property that lives in the object's PublicWeenieDesc (Icon=8 → _iconID; + /// since 2026-09-30 also IconOverlay=50 and IconUnderlay=52, 0 = none). Read directly from the embedded PWD struct — network-populated, so it works on /// UNequipped/never-appraised pack items with no qualities pointer and no main-thread native /// call. Returns 1 on success (value = the DataID, e.g. 0x06xxxxxx), 0 otherwise. Requires API /// v65+. APPENDED-AT-END for ABI safety.</summary> @@ -639,15 +639,247 @@ internal struct RynthCoreAPI /// request has been made this session, 0 if not. Any thread. Requires API v67+.</summary> public IntPtr GetVendorTradeStatusFn; - /// <summary>Function pointer: int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs) - /// Outcome of the latest MergeStackInternal(source, target) request: 0 none, 1 queued, + /// <summary>Function pointer: void* GetPluginInterface(const char* pluginName, const char* iface, uint version) + /// Asks a named plugin for a typed interface table (e.g. RynthAi's "RynthAi.Script" v1 for + /// RynthLua) through the fixed-signature export + /// <c>void* RynthPluginQueryInterface(const char* iface, uint version)</c>. Null when the plugin + /// isn't loaded or doesn't offer it. The table belongs to the target plugin; call its functions + /// only from the plugin pump thread. Requires API v68+.</summary> + public IntPtr GetPluginInterfaceFn; + + /// <summary>v69: <c>int GetLiveObjectIds(uint* buffer, int capacity)</c>: copies up to + /// <paramref name="capacity"/> ids of the objects in the client's object table (the engine's + /// snapshot, refreshed on the game thread) and returns the total count, so a caller whose + /// buffer was too small can retry with a bigger one. Requires API v69+.</summary> + public IntPtr GetLiveObjectIdsFn; + + // ── v70: action outcomes and wield-to-slot ────────────────────────── + // Since v70 the engine also raises RynthPluginOnEnchantmentAdded / Removed (the + // player's enchantment GameEvents 0x02C2-0x02C8 and 0x0312; see SmartBoxHooks). + + /// <summary>v70: <c>int GetLastUseDone(int* seq, uint* error)</c>: the most recent server + /// UseDone (GameEvent 0x01C7): its sequence number (the same count GetUseDoneSeq returns) + /// and its WeenieError code (0 = the action completed; e.g. 0x1D YoureTooBusy, 0x400 + /// YouDontHaveAllTheComponents). Both come from one atomic snapshot, so they always belong + /// together. Returns 1 when the engine watches UseDone (seq 0 = none yet), 0 when it can't. + /// Any thread. Requires API v70+.</summary> + public IntPtr GetLastUseDoneFn; + + /// <summary>v70: <c>int GetLastWeenieError(int* seq, uint* error, uint* eventType, uint* objectId)</c>: + /// the most recent refusal the server sent: WeenieError (eventType 0x028A, e.g. 0x402 + /// YourSpellFizzled — a fizzled cast still ends with UseDone(0)), WeenieErrorWithString + /// (0x028B) or InventoryServerSaveFailed (0x00A0, objectId = the item). seq counts them + /// (0 = none yet). Returns 1 when the engine watches these, 0 when it can't. Any thread. + /// Requires API v70+.</summary> + public IntPtr GetLastWeenieErrorFn; + + /// <summary>v70: <c>int WieldItem(uint objectId, uint equipMask)</c>: wield the item into the + /// given EquipMask slot(s) (the 0x001A GetAndWieldItem game action, as a paperdoll drag + /// sends it; e.g. 0x00200000 Shield, 0x00100000 MeleeWeapon). Queued for AC's main thread + /// when called from another thread. Returns 1 if sent or queued. The server answers with + /// the wield or InventoryServerSaveFailed (see GetLastWeenieError). Requires API v70+.</summary> + public IntPtr WieldItemFn; + + // ── v71: script windows (docs: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §4) ── + // A plugin draws ImGui windows by pushing a display list; the engine replays it every + // frame on AC's thread and sends input back as events. The engine never calls into the + // plugin for this and never keeps `data` / `buffer`: bytes are copied during the call. + + /// <summary>v71: <c>int UiSubmit(const uint8_t* data, int length)</c>: the owner's complete + /// window set (display-list format 1, UI/ScriptWindows/DisplayListParser.cs). Only from the + /// plugin's own tick or event on the pump thread. Returns 0, or -1 malformed, -2 not called + /// from a dispatch, -3 over a limit (nothing applied), -4 unsupported format version. + /// Requires API v71+.</summary> + public IntPtr UiSubmitFn; + + /// <summary>v71: <c>int UiPollEvents(uint8_t* buffer, int capacity, int* remaining)</c>: + /// copies whole events (never a partial one) and returns the bytes written; + /// <c>*remaining</c> = events still queued. Same thread rule as UiSubmit. Requires API v71+.</summary> + public IntPtr UiPollEventsFn; + + /// <summary>v71: <c>int UiGetInfo(UiInfoNative* info)</c>: the caller sets info->Size to the + /// size it knows; the engine fills up to that and returns the bytes written (0 when there is + /// no ImGui). Any thread. Requires API v71+.</summary> + public IntPtr UiGetInfoFn; + + // ── v72: player-to-player trade (docs: Compatibility/PlayerTrade.cs) ── + // The state comes from the server's trade GameEvents, read in the existing game-event + // detour on AC's main thread; plugins poll it (Generation / Sequence / counters tell them + // what changed). The actions go through the client's own CM_Trade / ClientTradeSystem + // functions and are queued for AC's main thread when called from another thread. + + /// <summary>v72: <c>int GetTradeState(TradeStateNative* state)</c>: the caller sets + /// state->Size to the size it knows; the engine fills up to that and returns the bytes + /// written (0 on a bad argument). Any thread. Requires API v72+.</summary> + public IntPtr GetTradeStateFn; + + /// <summary>v72: <c>int GetTradeItems(int side, uint* buffer, int capacity)</c>: copies up to + /// <paramref name="capacity"/> item ids from one side of the window (1 = yours, 2 = the + /// partner's) and returns that side's total count; -1 for a bad side. Any thread. + /// Requires API v72+.</summary> + public IntPtr GetTradeItemsFn; + + /// <summary>v72: <c>int TradeOpen(uint targetId)</c>: ask a player to trade (0x01F6 + /// OpenTradeNegotiations; the server walks you into range). Returns 1 if sent or queued. + /// Requires API v72+.</summary> + public IntPtr TradeOpenFn; + + /// <summary>v72: <c>int TradeAdd(uint itemId, uint slot)</c>: put one of your items in the + /// open trade window (0x01F8 AddToTrade; slot 0 = next free). The server answers with + /// AddToTrade or TradeFailure (see GetTradeState). Returns 1 if sent or queued. + /// Requires API v72+.</summary> + public IntPtr TradeAddFn; + + /// <summary>v72: <c>int TradeAccept(void)</c>: accept the trade as it stands (the window's + /// Accept button, 0x01FA). Returns 1 if sent or queued. Requires API v72+.</summary> + public IntPtr TradeAcceptFn; + + /// <summary>v72: <c>int TradeDecline(void)</c>: withdraw your acceptance (0x01FB). + /// Returns 1 if sent or queued. Requires API v72+.</summary> + public IntPtr TradeDeclineFn; + + /// <summary>v72: <c>int TradeReset(void)</c>: empty both sides of the window (0x0204). + /// Returns 1 if sent or queued. Requires API v72+.</summary> + public IntPtr TradeResetFn; + + /// <summary>v72: <c>int TradeClose(void)</c>: end the trade (0x01F7 CloseTradeNegotiations). + /// Returns 1 if sent or queued. Requires API v72+.</summary> + public IntPtr TradeCloseFn; + + /// <summary>v73: <c>int GetObjectInstanceIdProperty(uint objectId, uint stype, uint* value)</c>: + /// a PropertyInstanceId (another object's id: Container 2, Wielder 3, Monarch 26, HouseOwner 32, + /// PetOwner 44, the player's Allegiance/Patron/..., anything an UpdatePropertyInstanceID set). + /// Any thread; served from the engine's caches and PublicWeenieDesc snapshot. 1 = found (non-zero). + /// Requires API v73+.</summary> + public IntPtr GetObjectInstanceIdPropertyFn; + + /// <summary>v74: <c>int GetVTankState(int* sequence)</c>: VTank's macro, as the Decal bridge + /// sees it (Compatibility/VTankWatch.cs; signal = VTank's documented /vt start and /vt stop + /// through Decal's chat parser). Returns flags: bit0 = the engine watches (Decal bridge mode), + /// bit1 = VTank's macro is running. 0 without Decal. <c>*sequence</c> (may be null) is bumped + /// on every change. Any thread. Requires API v74+.</summary> + public IntPtr GetVTankStateFn; + + /// <summary>v75: <c>int GetCharacterTitles(uint* ids, int maxCount, uint* currentTitle)</c>: the + /// titles the player holds, from the server's title events (0x0029 at login, 0x002B per new + /// title; Compatibility/CharacterTitles.cs). Copies up to maxCount ids (ids may be null to + /// ask for the count) and returns how many the character holds, or -1 when the list isn't + /// known for the current character. *currentTitle (may be null) = the displayed title. + /// Any thread. Requires API v75+.</summary> + public IntPtr GetCharacterTitlesFn; + + /// <summary>v75: <c>int GetServerInfo(byte* worldName, int capacity)</c>: which server this + /// is (Compatibility/ServerInfo.cs). Returns flags: bit0 = Aelrynth (host, announced world + /// name or the Bank mod's properties), bit1 = Aelrynth's staging world, bit2 = the server + /// announced its world name, which is then copied to worldName (UTF-8, NUL-terminated, cut + /// to capacity - 1; worldName may be null). Never the launcher's profile name. Any thread. + /// Requires API v75+.</summary> + public IntPtr GetServerInfoFn; + + /// <summary>v76: <c>int CloseContainer(uint containerId)</c>: close an external container (a + /// corpse, a chest) as the client does when its window is closed: the 0x0195 + /// NoLongerViewingContents game action (CM_Inventory::Event_NoLongerViewingContents). Not an + /// inventory request: no busy count, no pending-request slot. The server answers with + /// CloseGroundContainer, which closes the window and raises StopViewingObjectContents. Runs on + /// AC's main thread (queued in the action ring from other threads, ahead of anything queued + /// after it). Returns 1 if sent or queued. Requires API v76+.</summary> + public IntPtr CloseContainerFn; + + /// <summary>v77: <c>int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs)</c>: + /// outcome of the latest MergeStackInternal(source, target) request: 0 none, 1 queued, /// 2 sent (amount = units sent), 3 skipped because the target was already full, /// 4 failed (invalid ids / AC rejected / threw), 5 dropped (main-thread queue full). /// ageMs = how long ago the outcome was recorded. Either out pointer may be null. - /// Any thread. Requires API v68+. APPENDED-AT-END for ABI safety.</summary> + /// The thunk is cdecl. Any thread. Requires API v77+. APPENDED-AT-END for ABI safety.</summary> public IntPtr GetMergeStackResultFn; } +/// <summary>v72 <see cref="TradeStateNative.Flags"/> bits.</summary> +internal static class TradeStateFlags +{ + public const uint Open = 1u << 0; + public const uint YouAccepted = 1u << 1; + public const uint PartnerAccepted = 1u << 2; + /// <summary>The engine sees the trade GameEvents (its game-event hook is installed).</summary> + public const uint Watching = 1u << 3; + /// <summary>All six trade actions are bound on this client.</summary> + public const uint ActionsAvailable = 1u << 4; +} + +/// <summary> +/// v72 <c>GetTradeState</c> result. Pack 4, 96 bytes; later versions only append. +/// Mirrored by RynthCore.PluginSdk (TradeStateNative in RynthCoreApiNative.cs). +/// </summary> +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal unsafe struct TradeStateNative +{ + /// <summary>In: the caller's sizeof. Out: bytes written.</summary> + public uint Size; + /// <summary><see cref="TradeStateFlags"/>.</summary> + public uint Flags; + /// <summary>+1 for every trade that opens (RegisterTrade).</summary> + public uint Generation; + /// <summary>+1 for every trade event (and TradeComplete).</summary> + public uint Sequence; + /// <summary>The other player; 0 when no trade is open.</summary> + public uint PartnerId; + /// <summary>Who opened the trade.</summary> + public uint InitiatorId; + public int SelfItemCount; + public int PartnerItemCount; + /// <summary>The last trade GameEvent type (0x01FD-0x0208).</summary> + public uint LastEventType; + /// <summary>TradeFailure events so far; the last one's item and WeenieError follow.</summary> + public uint FailureCount; + public uint LastFailureItemId; + public uint LastFailureReason; + /// <summary>EndTradeReason of the last CloseTrade: 1 normal, 2 entered combat, 0x51 cancelled.</summary> + public uint LastCloseReason; + public uint LastAcceptedBy; + public uint LastDeclinedBy; + public uint LastResetBy; + /// <summary>Trades completed so far (WeenieError 0x0529 TradeComplete).</summary> + public uint CompletedCount; + /// <summary>Times the partner has accepted so far (AcceptTrade from the partner).</summary> + public uint PartnerAcceptCount; + public fixed uint Reserved[6]; +} + +/// <summary> +/// v71 <c>UiGetInfo</c> result. Pack 4, 480 bytes in format 1; later versions only append. +/// Mirrored by RynthCore.PluginSdk (UiInfoNative in RynthCoreApiNative.cs). +/// </summary> +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal unsafe struct UiInfoNative +{ + /// <summary>In: the caller's sizeof. Out: bytes written.</summary> + public uint Size; + /// <summary>bit0 ImGui available, bit1 in world, bit2 pop-outs available.</summary> + public uint Flags; + /// <summary>Highest display-list format the engine replays.</summary> + public ushort MaxFormatVersion; + /// <summary>The ops replayed within MaxFormatVersion: 2 = + Image, ImageButton, InputInt, InputFloat, + /// DragInt, DragFloat (2026-09-30). 0 on older engines (the field was reserved) = Phase 1 ops only.</summary> + public ushort OpLevel; + public uint MaxOpsPerWindow; + public uint MaxBytesPerWindow; + public uint MaxWindowsPerOwner; + public uint MaxBytesPerSubmit; + public float DisplayWidth; + public float DisplayHeight; + public float UiScale; + public float TextLineHeight; + public float FrameHeight; + public float ItemSpacingX; + public float ItemSpacingY; + public float FramePaddingX; + public float FramePaddingY; + /// <summary>Default font advance of ' '..'~' (95), pixels at UiScale.</summary> + public fixed float AsciiAdvance[95]; + public uint FrameCounter; + public fixed uint Reserved[8]; +} + // ─── Vendor trading ABI structs (v67) ─────────────────────────────────── // Blittable, Pack=4, 4-byte fields + fixed ANSI buffers only. Mirrored exactly // by RynthCore.PluginSdk/VendorTypes.cs. Never reorder or resize; add new calls @@ -747,7 +979,7 @@ internal unsafe struct VendorTradeStatusNative /// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary> internal static class PluginContractVersion { - public const uint Current = 69; // v69: GetMergeStackResult thunk is cdecl (v68 engines pass a stdcall thunk - unusable) + public const uint Current = 77; // v77: GetMergeStackResult } internal static class ClientActionHookFlags @@ -1200,6 +1432,45 @@ internal unsafe delegate int GetObjectDataIdPropertyCallbackDelegate(uint object [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr GetPluginExportJsonCallbackDelegate(IntPtr pluginNameAnsi, IntPtr exportNameAnsi); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate IntPtr GetPluginInterfaceCallbackDelegate(IntPtr pluginNameAnsi, IntPtr ifaceAnsi, uint version); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetLiveObjectIdsCallbackDelegate(uint* buffer, int capacity); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetLastUseDoneCallbackDelegate(int* seq, uint* error); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetLastWeenieErrorCallbackDelegate(int* seq, uint* error, uint* eventType, uint* objectId); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int WieldItemCallbackDelegate(uint objectId, uint equipMask); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int UiSubmitCallbackDelegate(byte* data, int length); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int UiPollEventsCallbackDelegate(byte* buffer, int capacity, int* remaining); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int UiGetInfoCallbackDelegate(UiInfoNative* info); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetTradeStateCallbackDelegate(TradeStateNative* state); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetTradeItemsCallbackDelegate(int side, uint* buffer, int capacity); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int TradeOpenCallbackDelegate(uint targetId); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int TradeAddCallbackDelegate(uint itemId, uint slot); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int TradeSimpleCallbackDelegate(); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetVendorInfoCallbackDelegate(VendorInfoNative* info); @@ -1218,3 +1489,15 @@ internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeSta // the cdecl caller both pop the args, and the plugin's stack drifts on every call. [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetMergeStackResultCallbackDelegate(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetVTankStateCallbackDelegate(int* sequence); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetCharacterTitlesCallbackDelegate(uint* ids, int maxCount, uint* currentTitle); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetServerInfoCallbackDelegate(byte* worldName, int capacity); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int CloseContainerCallbackDelegate(uint containerId); diff --git a/src/RynthCore.Engine/Plugins/PluginLoader.cs b/src/RynthCore.Engine/Plugins/PluginLoader.cs index ba6b541..8e73b3a 100644 --- a/src/RynthCore.Engine/Plugins/PluginLoader.cs +++ b/src/RynthCore.Engine/Plugins/PluginLoader.cs @@ -19,8 +19,11 @@ internal static class PluginLoader [return: MarshalAs(UnmanagedType.Bool)] private static extern bool FreeLibrary(IntPtr hModule); - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr GetModuleHandleW(string lpModuleName); + + // Managed plugins (CoreCLR engine) answer from their export map; see ManagedPlugins. + private static IntPtr GetProcAddress(IntPtr hModule, string lpProcName) => ManagedPlugins.GetProcAddress(hModule, lpProcName); /// <summary> /// Scans <paramref name="pluginsDir"/> for *.dll files, loads each one, @@ -89,6 +92,11 @@ internal static class PluginLoader // Release managed thunks first so the module ref-count can drop to zero on FreeLibrary. plugin.ClearResolvedDelegates(); + if (ManagedPlugins.IsManagedHandle(plugin.ModuleHandle)) + { + ManagedPlugins.Unload(plugin.ModuleHandle); // a managed plugin really goes away + return; + } if (plugin.ModuleHandle != IntPtr.Zero) { RynthLog.Verbose($"PluginLoader: Skipping FreeLibrary on {plugin.FileName} (NativeAOT — module pages leaked intentionally)."); @@ -311,22 +319,40 @@ internal static class PluginLoader RynthLog.Verbose($"PluginLoader: Loading {fileName}..."); string shadowPath; - try + IntPtr handle; + bool reused = false; + if (ManagedPlugins.IsManagedAssembly(sourcePath)) { - shadowPath = CreateShadowCopy(sourcePath, sessionShadowDir); + // A managed plugin: loaded fresh (from streams, no shadow copy) into its own + // collectible context every time; nothing to reuse, nothing leaked. + shadowPath = sourcePath; + handle = ManagedPlugins.Load(sourcePath); + if (handle == IntPtr.Zero) + return null; } - catch (Exception ex) + else if (reused = TryFindLoadedCopy(sourcePath, sessionShadowDir, out handle, out shadowPath)) { - RynthLog.Plugin($"PluginLoader: FAILED to stage {fileName} ({ex.Message})"); - return null; + RynthLog.Plugin($"PluginLoader: {fileName} unchanged - reusing the copy already loaded from '{shadowPath}' (no new runtime)."); } + else + { + try + { + shadowPath = CreateShadowCopy(sourcePath, sessionShadowDir); + } + catch (Exception ex) + { + RynthLog.Plugin($"PluginLoader: FAILED to stage {fileName} ({ex.Message})"); + return null; + } - IntPtr handle = LoadLibraryW(shadowPath); - if (handle == IntPtr.Zero) - { - int err = Marshal.GetLastWin32Error(); - RynthLog.Plugin($"PluginLoader: FAILED to load {fileName} (Win32 error {err})"); - return null; + handle = LoadLibraryW(shadowPath); + if (handle == IntPtr.Zero) + { + int err = Marshal.GetLastWin32Error(); + RynthLog.Plugin($"PluginLoader: FAILED to load {fileName} (Win32 error {err})"); + return null; + } } // Resolve required exports @@ -336,7 +362,8 @@ internal static class PluginLoader if (initPtr == IntPtr.Zero || shutdownPtr == IntPtr.Zero) { RynthLog.Plugin($"PluginLoader: {fileName} missing required exports (RynthPluginInit/RynthPluginShutdown) — skipping."); - FreeLibrary(handle); + if (ManagedPlugins.IsManagedHandle(handle)) ManagedPlugins.Unload(handle); + else if (!reused) FreeLibrary(handle); return null; } @@ -514,6 +541,59 @@ internal static class PluginLoader return plugin; } + /// <summary> + /// A copy of <paramref name="sourcePath"/> that an earlier engine generation (or + /// plugin rescan) of this process loaded and that is byte-for-byte the same + /// file: re-initialize that module instead of loading a new one. A NativeAOT + /// DLL can never be unloaded, so every fresh copy keeps a whole runtime and its + /// GC heap in acclient's 4 GB for good; before this an engine hot-reload + /// loaded all six plugins again and cost ~600 MB (2026-09-28). A plugin's + /// RynthPluginRuntime builds a new plugin object on every Init, so a reused + /// module starts clean apart from its static caches. + /// </summary> + private static bool TryFindLoadedCopy(string sourcePath, string sessionShadowDir, out IntPtr handle, out string shadowPath) + { + handle = IntPtr.Zero; + shadowPath = ""; + try + { + string fileName = Path.GetFileName(sourcePath); + string? root = Path.GetDirectoryName(sessionShadowDir); + if (root == null || !Directory.Exists(root)) return false; + string mine = Path.GetFullPath(sessionShadowDir); + var sourceInfo = new FileInfo(sourcePath); + byte[]? source = null; + + foreach (string dir in Directory.GetDirectories(root, $"session-*-pid{Environment.ProcessId}-*")) + { + if (string.Equals(Path.GetFullPath(dir), mine, StringComparison.OrdinalIgnoreCase)) continue; + string candidate = Path.Combine(dir, fileName); + var info = new FileInfo(candidate); + if (!info.Exists || info.Length != sourceInfo.Length) continue; + IntPtr h = GetModuleHandleW(candidate); + if (h == IntPtr.Zero) continue; + source ??= ReadShared(sourcePath); + if (!source.AsSpan().SequenceEqual(ReadShared(candidate))) continue; + handle = h; + shadowPath = candidate; + return true; + } + } + catch (Exception ex) + { + RynthLog.Plugin($"PluginLoader: reuse check for {Path.GetFileName(sourcePath)} failed ({ex.GetType().Name}: {ex.Message}) - loading a new copy."); + } + return false; + } + + private static byte[] ReadShared(string path) + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + var bytes = new byte[fs.Length]; + fs.ReadExactly(bytes); + return bytes; + } + private static string PrepareShadowDirectory(string shadowRootDir, int generation) { // Include EntryPoint.InitCount so each engine instance gets its own diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index b56305c..8c788db 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -8,14 +8,18 @@ using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; +using System.Threading; using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI.ScriptWindows; using RynthCore.Engine.D3D9; namespace RynthCore.Engine.Plugins; internal static class PluginManager { - private readonly record struct PendingIncomingChat(string? Text, uint ChatType); + // Held: set when AC hasn't printed the line yet (ChatCallbackHooks holds it until the + // plugins' verdict is in; see IncomingChatHold.cs). Null for lines AC already printed. + private readonly record struct PendingIncomingChat(string? Text, uint ChatType, HeldChatLine? Held); private readonly record struct PendingBusyCountIncremented; private readonly record struct PendingBusyCountDecremented; private readonly record struct PendingTargetChange(uint CurrentTargetId, uint PreviousTargetId); @@ -234,6 +238,27 @@ internal static class PluginManager private static SendPluginCommandCallbackDelegate? _sendPluginCommandCallback; private static GetObjectDataIdPropertyCallbackDelegate? _getObjectDataIdPropertyCallback; private static GetPluginExportJsonCallbackDelegate? _getPluginExportJsonCallback; + private static GetPluginInterfaceCallbackDelegate? _getPluginInterfaceCallback; + private static GetLiveObjectIdsCallbackDelegate? _getLiveObjectIdsCallback; + private static GetLastUseDoneCallbackDelegate? _getLastUseDoneCallback; + private static GetLastWeenieErrorCallbackDelegate? _getLastWeenieErrorCallback; + private static WieldItemCallbackDelegate? _wieldItemCallback; + private static UiSubmitCallbackDelegate? _uiSubmitCallback; + private static UiPollEventsCallbackDelegate? _uiPollEventsCallback; + private static UiGetInfoCallbackDelegate? _uiGetInfoCallback; + private static GetTradeStateCallbackDelegate? _getTradeStateCallback; + private static GetTradeItemsCallbackDelegate? _getTradeItemsCallback; + private static TradeOpenCallbackDelegate? _tradeOpenCallback; + private static TradeAddCallbackDelegate? _tradeAddCallback; + private static TradeSimpleCallbackDelegate? _tradeAcceptCallback; + private static TradeSimpleCallbackDelegate? _tradeDeclineCallback; + private static TradeSimpleCallbackDelegate? _tradeResetCallback; + private static TradeSimpleCallbackDelegate? _tradeCloseCallback; + private static GetObjectDataIdPropertyCallbackDelegate? _getObjectInstanceIdPropertyCallback; // v73 (same shape) + private static GetVTankStateCallbackDelegate? _getVTankStateCallback; // v74 + private static GetCharacterTitlesCallbackDelegate? _getCharacterTitlesCallback; // v75 + private static GetServerInfoCallbackDelegate? _getServerInfoCallback; // v75 + private static CloseContainerCallbackDelegate? _closeContainerCallback; // v76 private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback; private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback; private static VendorBuyCallbackDelegate? _vendorBuyCallback; @@ -546,6 +571,10 @@ internal static class PluginManager if (_loginDispatchPending && _initialized) DispatchLoginCompleteToLoadedPlugins(); + + // v71 script windows: a plugin that failed in one of the events above (or in Init, + // via a rescan) loses its windows now rather than after the next tick. + ScriptWindowRegistry.DropFailedOwners(); } public static bool DispatchChatBarEnter(string? text) @@ -576,7 +605,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatBarEnter threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatBarEnter threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } } @@ -592,20 +621,39 @@ internal static class PluginManager } } - public static void QueueChatWindowText(string? text, uint chatType) + public static void QueueChatWindowText(string? text, uint chatType) => QueueChatWindowText(text, chatType, null); + + /// <summary> + /// Queues an incoming chat line for the plugins (dispatched on the pump). With + /// <paramref name="held"/>, AC hasn't printed the line yet and the plugins' verdict is + /// written to it. Returns false when no plugin is there to hear it (then a held line must + /// be printed by the caller). + /// </summary> + public static bool QueueChatWindowText(string? text, uint chatType, HeldChatLine? held) { + // RynthVision overlays (debuffs, combat text, gains) read chat engine-side, plugins or not. + ImGuiBackend.Hud.HudFeed.OnChat(text); + if (!_initialized || _plugins.Count == 0) - return; + return false; lock (PendingIncomingChatsLock) { if (_pendingIncomingChats.Count >= MaxPendingIncomingChats) - _pendingIncomingChats.Dequeue(); + _pendingIncomingChats.Dequeue().Held?.Decide(eat: false); // dropped unheard: it shows - _pendingIncomingChats.Enqueue(new PendingIncomingChat(text, chatType)); + _pendingIncomingChats.Enqueue(new PendingIncomingChat(text, chatType, held)); } + return true; } + /// <summary> + /// When the pump last looked at the incoming-chat queue (Environment.TickCount64, 0 = never). + /// ChatCallbackHooks holds lines for a verdict only while this is recent. + /// </summary> + internal static long ChatPumpBeatMs => System.Threading.Interlocked.Read(ref _chatPumpBeatMs); + private static long _chatPumpBeatMs; + public static void QueueBusyCountIncremented() { if (!_initialized || _plugins.Count == 0) @@ -636,6 +684,8 @@ internal static class PluginManager public static void QueueSelectedTargetChange(uint currentTargetId, uint previousTargetId) { + ImGuiBackend.Hud.HudFeed.OnSelection(currentTargetId); // debuff target matching + if (!_initialized || _plugins.Count == 0) return; @@ -678,6 +728,7 @@ internal static class PluginManager public static void QueueDeleteObject(uint objectId) { + ImGuiBackend.Hud.HudFeed.OnDeleted(objectId); // nameplate debuffs / kill burst fallback lock (LiveObjectsLock) _liveObjects.Remove(objectId); // Track deletes that arrive before plugin init so we can filter stale creates from the replay. @@ -815,6 +866,9 @@ internal static class PluginManager public static void QueueUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) { + // Monster nameplates keep the last ratio per object (engine-side, plugins or not). + ImGuiBackend.Hud.MonsterHudData.RecordHealth(targetId, healthRatio, currentHealth, maxHealth); + if (_plugins.Count == 0) return; @@ -924,7 +978,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatWindowText threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatWindowText threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } } @@ -974,10 +1028,10 @@ internal static class PluginManager catch { } } - // Sample the real cast gate on the single 30 Hz plugin heartbeat (this - // is the one TickAll driver, off AC's render thread). Self-guarded; - // never throws. Plugins read it via the GetCastBusyState host pull. - CastGate.Sample(); + // The cast gate is sampled on AC's main thread now (MainThreadSnapshots.Tick, + // from the Client::UseTime drain and EndScene); this pump only reads the + // published value through the GetCastBusyState host pull. Sampling it here + // walked SmartBox -> player -> MovementManager -> CMotionInterp off-thread. // Clear the Nav3D submission buffer once per tick so plugins always // submit into a fresh frame. Previously each plugin was expected to @@ -998,6 +1052,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.Tick == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.Tick(); @@ -1005,14 +1060,35 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Error($"PluginManager: {plugin.DisplayName} Tick threw {ex.GetType().Name}: {ex.Message} - disabled."); + RynthLog.Error($"PluginManager: {plugin.DisplayName} Tick threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)} - disabled."); + } + finally + { + LeaveDispatch(outer); } } + // v71 script windows: a plugin that failed (this tick or in an event) loses its windows. + ScriptWindowRegistry.DropFailedOwners(); + // Atomically publish this tick's Nav3D submissions to the render thread. D3D9.Nav3DRenderer.CommitFrame(); } + // The first PluginTraceLimit plugin exceptions also log their stack trace: "Tick threw + // IndexOutOfRangeException" alone left a crash undiagnosable (2026-10-04). Capped so a plugin + // failing in an event every tick can't flood the log. + private const int PluginTraceLimit = 20; + private static int _pluginTracesLogged; + + private static string PluginTrace(Exception ex) + { + if (string.IsNullOrEmpty(ex.StackTrace) || Interlocked.Increment(ref _pluginTracesLogged) > PluginTraceLimit) + return string.Empty; + string inner = ex.InnerException is { } ie ? $"\n inner {ie.GetType().Name}: {ie.Message}\n{ie.StackTrace}" : string.Empty; + return "\n" + ex.StackTrace + inner; + } + public static void RenderAll() { // Suppress plugin rendering while we are not in-world. The window between @@ -1039,7 +1115,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Error($"PluginManager: {plugin.DisplayName} Render threw {ex.GetType().Name}: {ex.Message} - disabled."); + RynthLog.Error($"PluginManager: {plugin.DisplayName} Render threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)} - disabled."); } } } @@ -1125,6 +1201,24 @@ internal static class PluginManager private static int _loggedOverlayBound = -1; private static int _loggedOverlayTotal = -1; + /// <summary> + /// True when an initialized, healthy plugin exports RynthPluginRenderOverlay. Reads the + /// render snapshot only (no lock, no allocation): safe every frame on the render thread. + /// </summary> + internal static bool HasOverlayPlugins + { + get + { + LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot); + for (int i = 0; i < plugins.Length; i++) + { + var p = plugins[i]; + if (p.Initialized && !p.Failed && p.RenderOverlay != null) return true; + } + return false; + } + } + /// <summary>Overlay stats for the ImGui heartbeat line.</summary> internal static string DescribeOverlayState() => $"overlayCalls={_overlayCalls} loginSeen={_loginCompleteObserved} overlayPlugins={_overlayBound}"; @@ -1136,6 +1230,7 @@ internal static class PluginManager LoginLifecycleHooks.LoginComplete -= OnLoginCompleteObserved; LogoutLifecycleHooks.LogoutComplete -= OnLogoutObserved; UnloadAllPlugins(); + ScriptWindowRegistry.Reset(); RynthLog.Info("ShutdownAll: post-UnloadAllPlugins"); // SKIP CleanupShadowCopies during shutdown — it walks the (still-mapped) // plugin DLL directory and was a heavy heap-IO step during the 1.4s @@ -1200,8 +1295,8 @@ internal static class PluginManager RynthLog.Info("ShutdownAll: post-queue-clears"); } - [System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); + // Managed plugins (CoreCLR engine) answer from their export map; see ManagedPlugins. + private static IntPtr GetProcAddress(IntPtr hModule, string lpProcName) => ManagedPlugins.GetProcAddress(hModule, lpProcName); /// <summary> /// Resolve a named export on a loaded plugin's module, matched by display @@ -1298,6 +1393,7 @@ internal static class PluginManager Compatibility.ChatHooks.ResetCachedInstance(); Compatibility.RadarHooks.ResetCachedInstance(); Compatibility.PowerbarHooks.ResetCachedInstance(); + Compatibility.RetailVitalsHooks.ResetCachedInstance(); Compatibility.ChatCallbackHooks.ResetOutgoingTarget(); // Drop the cached PlayerDesc/CACQualities pointer so the next call into the @@ -1313,6 +1409,8 @@ internal static class PluginManager // survive a session, so leaving these unbounded across relogs is a // slow but real leak on this stack's 32-bit VA budget. Compatibility.AppraisalHooks.ClearSession(); + // The update caches and the player's PlayerDescription record likewise (2026-09-30). + Compatibility.PropertyUpdateHooks.ClearSession(); // Reset login observation so the next SendLoginCompleteNotification kicks // off a fresh login-complete cycle. @@ -1338,6 +1436,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnLogout == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnLogout(); @@ -1346,7 +1445,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnLogout threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnLogout threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1379,6 +1482,8 @@ internal static class PluginManager { if (!_initialized || _plugins.Count == 0) return; + // Plugins are here and hearing chat: ChatCallbackHooks may hold lines for their verdict. + System.Threading.Interlocked.Exchange(ref _chatPumpBeatMs, Environment.TickCount64); PendingIncomingChat[] pending; lock (PendingIncomingChatsLock) @@ -1394,11 +1499,14 @@ internal static class PluginManager { foreach (PendingIncomingChat evt in pending) { - IntPtr textPtr = evt.Text != null ? Marshal.StringToHGlobalUni(evt.Text) : IntPtr.Zero; + IntPtr textPtr = IntPtr.Zero; + bool eaten = false; // the verdict for a held line: AC prints it unless this ends true try { + textPtr = evt.Text != null ? Marshal.StringToHGlobalUni(evt.Text) : IntPtr.Zero; int eat = 0; IntPtr eatPtr = new(&eat); + bool threw = false; for (int i = 0; i < _plugins.Count; i++) { @@ -1406,6 +1514,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { if (plugin.OnChatWindowTextPtr != IntPtr.Zero) @@ -1419,13 +1528,23 @@ internal static class PluginManager } catch (Exception ex) { + threw = true; plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatWindowText threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatWindowText threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } + + eaten = HeldChatQueue.PluginsAteIt(eat, threw); } finally { + // Always give a held line its verdict, so AC prints it at once rather than + // after the hold timeout; a line nobody could judge shows. + evt.Held?.Decide(eaten); if (textPtr != IntPtr.Zero) Marshal.FreeHGlobal(textPtr); } @@ -1456,6 +1575,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnSelectedTargetChange == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnSelectedTargetChange(evt.CurrentTargetId, evt.PreviousTargetId); @@ -1463,7 +1583,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnSelectedTargetChange threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnSelectedTargetChange threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1492,6 +1616,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnBusyCountIncremented == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnBusyCountIncremented(); @@ -1499,7 +1624,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnBusyCountIncremented threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnBusyCountIncremented threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1528,6 +1657,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnBusyCountDecremented == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnBusyCountDecremented(); @@ -1535,7 +1665,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnBusyCountDecremented threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnBusyCountDecremented threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1564,6 +1698,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnCombatModeChange == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnCombatModeChange(evt.CurrentCombatMode, evt.PreviousCombatMode); @@ -1571,7 +1706,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCombatModeChange threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCombatModeChange threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1600,6 +1739,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { unsafe @@ -1621,7 +1761,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnSmartBoxEvent threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnSmartBoxEvent threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1663,6 +1807,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { unsafe @@ -1684,7 +1829,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateObject threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateObject threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1717,6 +1866,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnDeleteObject == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnDeleteObject(evt.ObjectId); @@ -1724,7 +1874,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnDeleteObject threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnDeleteObject threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1759,6 +1913,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnCreateObject == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnCreateObject(evt.ObjectId); @@ -1766,7 +1921,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCreateObject threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCreateObject threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1795,6 +1954,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnUpdateObjectInventory == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnUpdateObjectInventory(evt.ObjectId); @@ -1802,7 +1962,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateObjectInventory threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateObjectInventory threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1831,6 +1995,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnViewObjectContents == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnViewObjectContents(evt.ObjectId); @@ -1838,7 +2003,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnViewObjectContents threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnViewObjectContents threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1867,6 +2036,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnStopViewingObjectContents == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnStopViewingObjectContents(evt.ObjectId); @@ -1874,7 +2044,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnStopViewingObjectContents threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnStopViewingObjectContents threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1903,6 +2077,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnVendorOpen == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnVendorOpen(evt.VendorId); @@ -1910,7 +2085,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnVendorOpen threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnVendorOpen threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1939,6 +2118,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnVendorClose == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnVendorClose(evt.VendorId); @@ -1946,7 +2126,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnVendorClose threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnVendorClose threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -1975,6 +2159,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { unsafe @@ -1992,7 +2177,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateHealth threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateHealth threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -2021,6 +2210,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { unsafe @@ -2038,7 +2228,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCombatDamage threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCombatDamage threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -2070,6 +2264,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { unsafe @@ -2087,7 +2282,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnKillNotification threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnKillNotification threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -2122,6 +2321,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnEnchantmentAdded == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnEnchantmentAdded(evt.SpellId, evt.DurationSeconds); @@ -2129,7 +2329,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnEnchantmentAdded threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnEnchantmentAdded threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -2158,6 +2362,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnEnchantmentRemoved == null) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnEnchantmentRemoved(evt.EnchantmentId); @@ -2165,7 +2370,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnEnchantmentRemoved threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnEnchantmentRemoved threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -2260,6 +2469,7 @@ internal static class PluginManager for (int i = 0; i < _plugins.Count; i++) { var plugin = _plugins[i]; + LoadedPlugin? outer = EnterDispatch(plugin); try { int result = plugin.Init!(ref _api); @@ -2280,7 +2490,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } @@ -2303,6 +2517,7 @@ internal static class PluginManager // a FRESH copy of the same plugin → double-instance after reload). if (plugin.Initialized && plugin.Shutdown != null) { + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.Shutdown(); @@ -2312,7 +2527,13 @@ internal static class PluginManager { RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Shutdown threw: {ex.Message}"); } + finally + { + LeaveDispatch(outer); + } } + // v71: its script windows close (their placement is kept). + ScriptWindowRegistry.DropOwner(plugin); PluginLoader.Unload(plugin); } @@ -2337,6 +2558,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnUIInitialized == null || plugin.UIInitializedDispatched) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnUIInitialized(); @@ -2346,7 +2568,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUIInitialized threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUIInitialized threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } } @@ -2364,6 +2590,7 @@ internal static class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.OnLoginComplete == null || plugin.LoginCompleteDispatched) continue; + LoadedPlugin? outer = EnterDispatch(plugin); try { plugin.OnLoginComplete(); @@ -2373,7 +2600,11 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnLoginComplete threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnLoginComplete threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); } } @@ -2513,6 +2744,27 @@ internal static class PluginManager _sendPluginCommandCallback ??= SendPluginCommandAction; _getObjectDataIdPropertyCallback ??= GetObjectDataIdPropertyAction; _getPluginExportJsonCallback ??= GetPluginExportJsonAction; + _getPluginInterfaceCallback ??= GetPluginInterfaceAction; + unsafe { _getLiveObjectIdsCallback ??= GetLiveObjectIdsAction; } + unsafe { _getLastUseDoneCallback ??= GetLastUseDoneAction; } + unsafe { _getLastWeenieErrorCallback ??= GetLastWeenieErrorAction; } + _wieldItemCallback ??= WieldItemAction; + unsafe { _uiSubmitCallback ??= UiSubmitAction; } + unsafe { _uiPollEventsCallback ??= UiPollEventsAction; } + unsafe { _uiGetInfoCallback ??= UiGetInfoAction; } + unsafe { _getTradeStateCallback ??= GetTradeStateAction; } + unsafe { _getTradeItemsCallback ??= GetTradeItemsAction; } + _tradeOpenCallback ??= TradeOpenAction; + _tradeAddCallback ??= TradeAddAction; + _tradeAcceptCallback ??= TradeAcceptAction; + _tradeDeclineCallback ??= TradeDeclineAction; + _tradeResetCallback ??= TradeResetAction; + _tradeCloseCallback ??= TradeCloseAction; + unsafe { _getObjectInstanceIdPropertyCallback ??= GetObjectInstanceIdPropertyAction; } + unsafe { _getVTankStateCallback ??= GetVTankStateAction; } + unsafe { _getCharacterTitlesCallback ??= GetCharacterTitlesAction; } + unsafe { _getServerInfoCallback ??= GetServerInfoAction; } + _closeContainerCallback ??= CloseContainerAction; _getVendorInfoCallback ??= GetVendorInfoAction; _getVendorItemsCallback ??= GetVendorItemsAction; _vendorBuyCallback ??= VendorBuyAction; @@ -2630,16 +2882,78 @@ internal static class PluginManager _api.SendPluginCommandFn = Marshal.GetFunctionPointerForDelegate(_sendPluginCommandCallback); _api.GetObjectDataIdPropertyFn = Marshal.GetFunctionPointerForDelegate(_getObjectDataIdPropertyCallback); _api.GetPluginExportJsonFn = Marshal.GetFunctionPointerForDelegate(_getPluginExportJsonCallback); + _api.GetPluginInterfaceFn = Marshal.GetFunctionPointerForDelegate(_getPluginInterfaceCallback); + _api.GetLiveObjectIdsFn = Marshal.GetFunctionPointerForDelegate(_getLiveObjectIdsCallback); + _api.GetLastUseDoneFn = Marshal.GetFunctionPointerForDelegate(_getLastUseDoneCallback); + _api.GetLastWeenieErrorFn = Marshal.GetFunctionPointerForDelegate(_getLastWeenieErrorCallback); + _api.WieldItemFn = Marshal.GetFunctionPointerForDelegate(_wieldItemCallback); + _api.UiSubmitFn = Marshal.GetFunctionPointerForDelegate(_uiSubmitCallback); + _api.UiPollEventsFn = Marshal.GetFunctionPointerForDelegate(_uiPollEventsCallback); + _api.UiGetInfoFn = Marshal.GetFunctionPointerForDelegate(_uiGetInfoCallback); + _api.GetTradeStateFn = Marshal.GetFunctionPointerForDelegate(_getTradeStateCallback); + _api.GetTradeItemsFn = Marshal.GetFunctionPointerForDelegate(_getTradeItemsCallback); + _api.TradeOpenFn = Marshal.GetFunctionPointerForDelegate(_tradeOpenCallback); + _api.TradeAddFn = Marshal.GetFunctionPointerForDelegate(_tradeAddCallback); + _api.TradeAcceptFn = Marshal.GetFunctionPointerForDelegate(_tradeAcceptCallback); + _api.TradeDeclineFn = Marshal.GetFunctionPointerForDelegate(_tradeDeclineCallback); + _api.TradeResetFn = Marshal.GetFunctionPointerForDelegate(_tradeResetCallback); + _api.TradeCloseFn = Marshal.GetFunctionPointerForDelegate(_tradeCloseCallback); + _api.GetObjectInstanceIdPropertyFn = Marshal.GetFunctionPointerForDelegate(_getObjectInstanceIdPropertyCallback); + _api.GetVTankStateFn = Marshal.GetFunctionPointerForDelegate(_getVTankStateCallback); + _api.GetCharacterTitlesFn = Marshal.GetFunctionPointerForDelegate(_getCharacterTitlesCallback); + _api.GetServerInfoFn = Marshal.GetFunctionPointerForDelegate(_getServerInfoCallback); + _api.CloseContainerFn = Marshal.GetFunctionPointerForDelegate(_closeContainerCallback); _api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback); _api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback); _api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback); _api.VendorSellFn = Marshal.GetFunctionPointerForDelegate(_vendorSellCallback); _api.GetVendorTradeStatusFn = Marshal.GetFunctionPointerForDelegate(_getVendorTradeStatusCallback); _api.GetMergeStackResultFn = Marshal.GetFunctionPointerForDelegate(_getMergeStackResultCallback); + RouteApiThroughLoader(); } + /// <summary> + /// Plugins copy the API table and can never give it back, so under the native loader + /// every function pointer in it becomes one of the loader's permanent stubs + /// (Hooking/LoaderServices): after this engine generation shuts down, a plugin thread + /// that still calls the host waits for the next generation instead of jumping into + /// unloaded code. Fields 0-3 (Version, ImGuiContext, D3DDevice, GameHwnd) are data. + /// </summary> + private static unsafe void RouteApiThroughLoader() + { + if (!Hooking.LoaderServices.Available) + return; + fixed (RynthCoreAPI* api = &_api) + { + IntPtr* slots = (IntPtr*)api; + int count = sizeof(RynthCoreAPI) / sizeof(IntPtr); + for (int i = 4; i < count; i++) + if (slots[i] != IntPtr.Zero) + slots[i] = Hooking.LoaderServices.ApiStub(i, slots[i]); + } + } + + private static int _loggedOffThreadProbe; + private static void ProbeClientHooks() { + // Host ProbeClientHooksFn is called from the plugin pump. A probe Resets and + // rebinds the combat/movement/object delegates the main-thread drain is using + // and re-scans AC memory, so it must not run there: off the main thread, + // ask MainThreadSnapshots.Tick to re-probe on AC's main thread (only if the + // action hooks are not initialized; bootstrap already probed them). + // Fire-and-forget: plugins read readiness through GetClientHookFlags. + if (!MainThreadGuard.IsOnMainThread()) + { + if (!ClientActionHooks.GetStatus().CombatInitialized) + MainThreadSnapshots.RequestClientHookProbe(); + if (System.Threading.Interlocked.Exchange(ref _loggedOffThreadProbe, 1) == 0) + RynthLog.Compat("ProbeClientHooks: called off AC's main thread - " + + (ClientActionHooks.GetStatus().CombatInitialized + ? "hooks already initialized, nothing to do." + : "re-probe queued for AC's main thread.")); + return; + } ClientActionHooks.Probe(); // ClientCombatHooks.Probe() is called during engine bootstrap (EntryPoint.cs) // — do NOT re-probe here, it uses GetDelegateForFunctionPointer (no MinHook). @@ -2758,6 +3072,73 @@ internal static class PluginManager return 1; } + private static unsafe int GetVTankStateAction(int* sequence) + { + try + { + uint flags = Compatibility.VTankWatch.GetPluginState(out int seq); + if (sequence != null) + *sequence = seq; + return (int)flags; + } + catch + { + return 0; + } + } + + private static unsafe int GetCharacterTitlesAction(uint* ids, int maxCount, uint* currentTitle) + { + try + { + return Compatibility.CharacterTitles.Copy(ClientHelperHooks.GetPlayerId(), ids, Math.Max(0, maxCount), currentTitle); + } + catch + { + return -1; + } + } + + private static unsafe int GetServerInfoAction(byte* worldName, int capacity) + { + try + { + ServerVerdict v = ServerInfo.Current; + int flags = (v.IsAelrynth ? 1 : 0) | (v.IsStaging ? 2 : 0); + string? world = AccountHooks.AnnouncedWorldName; + if (!string.IsNullOrEmpty(world)) + { + flags |= 4; + if (worldName != null && capacity > 0) + { + byte[] utf8 = System.Text.Encoding.UTF8.GetBytes(world); + int n = Math.Min(utf8.Length, capacity - 1); + while (n > 0 && n < utf8.Length && (utf8[n] & 0xC0) == 0x80) n--; + for (int i = 0; i < n; i++) worldName[i] = utf8[i]; + worldName[n] = 0; + } + } + else if (worldName != null && capacity > 0) + { + worldName[0] = 0; + } + return flags; + } + catch + { + return 0; + } + } + + private static unsafe int GetObjectInstanceIdPropertyAction(uint objectId, uint stype, uint* value) + { + if (!ClientObjectHooks.TryGetObjectInstanceIdProperty(objectId, stype, out uint v)) + return 0; + + *value = v; + return 1; + } + private static unsafe int GetObjectDoublePropertyAction(uint objectId, uint stype, double* value) { if (!ClientObjectHooks.TryGetObjectDoubleProperty(objectId, stype, out double v)) @@ -3167,14 +3548,59 @@ internal static class PluginManager private static int UseObject(uint objectId) { Compatibility.AcActionTrace.Record("UseObject", objectId); + LogPluginUse("UseObject", objectId, 0); return ToAbiBool(ClientHelperHooks.UseObject(objectId)); } private static int UseObjectOn(uint sourceObjectId, uint targetObjectId) { + LogPluginUse("UseObjectOn", sourceObjectId, targetObjectId); return ToAbiBool(ClientHelperHooks.UseObjectOn(sourceObjectId, targetObjectId)); } + // ── Use backstop log (2026-10-04) ───────────────────────────────────────── + // One line per plugin use, whichever plugin asked, so a use nobody explains + // shows up in the log (doors and corpses opening "on their own" went + // unexplained for months because no use was logged). The plugins log the + // why next to it ("[Use] RynthAi/..."); this line is the engine's record + // that the use was sent. The same object (and target) is logged at most + // once per UseLogRepeatMs: repeats in between are counted and reported on + // the next line for it, so a fight's weapon swaps don't flood the log. + private const long UseLogRepeatMs = 3000; + private static readonly object UseLogGate = new(); + private static readonly Dictionary<ulong, (long LastMs, int Suppressed)> UseLogSeen = new(); + + private static void LogPluginUse(string what, uint objectId, uint targetId) + { + try + { + long now = Environment.TickCount64; + ulong key = ((ulong)targetId << 32) | objectId; + int suppressed; + lock (UseLogGate) + { + if (UseLogSeen.TryGetValue(key, out var seen) && now - seen.LastMs < UseLogRepeatMs) + { + UseLogSeen[key] = (seen.LastMs, seen.Suppressed + 1); + return; + } + suppressed = UseLogSeen.TryGetValue(key, out seen) ? seen.Suppressed : 0; + if (UseLogSeen.Count > 256) UseLogSeen.Clear(); + UseLogSeen[key] = (now, 0); + } + string name = ClientActionHooks.TryGetObjectName(objectId, out string n) && !string.IsNullOrWhiteSpace(n) ? n : "?"; + string target = ""; + if (targetId != 0) + { + string tn = ClientActionHooks.TryGetObjectName(targetId, out string t) && !string.IsNullOrWhiteSpace(t) ? t : "?"; + target = $" on 0x{targetId:X8} '{tn}'"; + } + string more = suppressed > 0 ? $" (+{suppressed} repeat(s) since its last line)" : ""; + RynthLog.Info($"[Use] engine: {what} 0x{objectId:X8} '{name}'{target}{more}"); + } + catch { } + } + private static int UseEquippedItem(uint sourceObjectId, uint targetObjectId) { return ToAbiBool(ClientHelperHooks.UseEquippedItem(sourceObjectId, targetObjectId)); @@ -3354,6 +3780,217 @@ internal static class PluginManager } } + /// <summary> + /// v68: a named plugin's typed interface table, through its fixed-signature + /// <c>void* RynthPluginQueryInterface(const char* iface, uint version)</c> export (never + /// an arbitrary export, so no signature mismatch can reach the stack). Null if missing. + /// </summary> + private static unsafe IntPtr GetPluginInterfaceAction(IntPtr pluginNameAnsi, IntPtr ifaceAnsi, uint version) + { + try + { + string? name = pluginNameAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(pluginNameAnsi) : null; + if (string.IsNullOrEmpty(name) || ifaceAnsi == IntPtr.Zero) + return IntPtr.Zero; + IntPtr fn = ResolvePluginExport(name, "RynthPluginQueryInterface"); + if (fn == IntPtr.Zero) + return IntPtr.Zero; + return ((delegate* unmanaged[Cdecl]<IntPtr, uint, IntPtr>)fn)(ifaceAnsi, version); + } + catch + { + return IntPtr.Zero; + } + } + + /// <summary>v69: the engine's live object id snapshot (see PluginContract.GetLiveObjectIdsFn).</summary> + private static unsafe int GetLiveObjectIdsAction(uint* buffer, int capacity) + { + try + { + uint[] ids = ClientObjectHooks.LiveObjectIds; + if (buffer != null && capacity > 0) + { + int n = Math.Min(capacity, ids.Length); + for (int i = 0; i < n; i++) + buffer[i] = ids[i]; + } + return ids.Length; + } + catch + { + return 0; + } + } + + /// <summary>v70: the last UseDone's seq + error code (see PluginContract.GetLastUseDoneFn).</summary> + private static unsafe int GetLastUseDoneAction(int* seq, uint* error) + { + try + { + bool ok = SmartBoxHooks.TryGetLastUseDone(out int s, out uint e); + if (seq != null) *seq = s; + if (error != null) *error = e; + return ok ? 1 : 0; + } + catch + { + return 0; + } + } + + /// <summary>v70: the last server refusal (see PluginContract.GetLastWeenieErrorFn).</summary> + private static unsafe int GetLastWeenieErrorAction(int* seq, uint* error, uint* eventType, uint* objectId) + { + try + { + bool ok = SmartBoxHooks.TryGetLastWeenieError(out int s, out uint e, out uint t, out uint o); + if (seq != null) *seq = s; + if (error != null) *error = e; + if (eventType != null) *eventType = t; + if (objectId != null) *objectId = o; + return ok ? 1 : 0; + } + catch + { + return 0; + } + } + + // ── v71: script windows ───────────────────────────────────────────── + + // The plugin being called on this thread (Tick, Init, lifecycle events, Shutdown), so + // UiSubmit / UiPollEvents know their owner. Written only by the dispatching thread; a + // call from any other thread (a plugin's own thread, AC's thread) sees no owner. + private static LoadedPlugin? _dispatchPlugin; + private static int _dispatchThread; + + private static LoadedPlugin? EnterDispatch(LoadedPlugin plugin) + { + int thread = Environment.CurrentManagedThreadId; + LoadedPlugin? outer = _dispatchThread == thread ? _dispatchPlugin : null; + _dispatchThread = thread; + _dispatchPlugin = plugin; + return outer; + } + + private static void LeaveDispatch(LoadedPlugin? outer) => _dispatchPlugin = outer; + + /// <summary>The plugin whose tick, event, Init or Shutdown is running on the calling thread, or null.</summary> + internal static LoadedPlugin? CurrentDispatch + { + get + { + LoadedPlugin? plugin = _dispatchPlugin; + return plugin != null && _dispatchThread == Environment.CurrentManagedThreadId ? plugin : null; + } + } + + /// <summary>v71: see PluginContract.UiSubmitFn.</summary> + private static unsafe int UiSubmitAction(byte* data, int length) + { + try + { + LoadedPlugin? owner = CurrentDispatch; + if (owner == null) return -2; + return ScriptWindowRegistry.Submit(owner, data, length); + } + catch (Exception ex) + { + RynthLog.Plugin($"PluginManager: UiSubmit threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + return -1; + } + } + + /// <summary>v71: see PluginContract.UiPollEventsFn.</summary> + private static unsafe int UiPollEventsAction(byte* buffer, int capacity, int* remaining) + { + try + { + if (remaining != null) *remaining = 0; + LoadedPlugin? owner = CurrentDispatch; + if (owner == null) return -2; + return ScriptWindowRegistry.PollEvents(owner, buffer, capacity, remaining); + } + catch (Exception ex) + { + RynthLog.Plugin($"PluginManager: UiPollEvents threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + return 0; + } + } + + /// <summary>v71: see PluginContract.UiGetInfoFn.</summary> + private static unsafe int UiGetInfoAction(UiInfoNative* info) + { + try + { + return ScriptWindowRegistry.GetInfo(info); + } + catch + { + return 0; + } + } + + // ── v72: player-to-player trade ──────────────────────────────────── + + /// <summary>v72: see PluginContract.GetTradeStateFn.</summary> + private static unsafe int GetTradeStateAction(TradeStateNative* state) + { + try + { + return PlayerTrade.GetState(state); + } + catch + { + return 0; + } + } + + /// <summary>v72: see PluginContract.GetTradeItemsFn.</summary> + private static unsafe int GetTradeItemsAction(int side, uint* buffer, int capacity) + { + try + { + return PlayerTrade.GetItems(side, buffer, capacity); + } + catch + { + return -1; + } + } + + /// <summary>v72: see PluginContract.TradeOpenFn.</summary> + private static int TradeOpenAction(uint targetId) => ToAbiBool(PlayerTrade.Open(targetId)); + + /// <summary>v72: see PluginContract.TradeAddFn.</summary> + private static int TradeAddAction(uint itemId, uint slot) => ToAbiBool(PlayerTrade.Add(itemId, slot)); + + /// <summary>v72: see PluginContract.TradeAcceptFn.</summary> + private static int TradeAcceptAction() => ToAbiBool(PlayerTrade.Accept()); + + /// <summary>v72: see PluginContract.TradeDeclineFn.</summary> + private static int TradeDeclineAction() => ToAbiBool(PlayerTrade.Decline()); + + /// <summary>v72: see PluginContract.TradeResetFn.</summary> + private static int TradeResetAction() => ToAbiBool(PlayerTrade.Reset()); + + /// <summary>v72: see PluginContract.TradeCloseFn.</summary> + private static int TradeCloseAction() => ToAbiBool(PlayerTrade.Close()); + + /// <summary>v76: close an external container (see PluginContract.CloseContainerFn).</summary> + private static int CloseContainerAction(uint containerId) + { + Compatibility.AcActionTrace.Record("CloseContainer", containerId); + return ToAbiBool(ClientHelperHooks.CloseContainer(containerId)); + } + + /// <summary>v70: wield into a chosen slot (see PluginContract.WieldItemFn).</summary> + private static int WieldItemAction(uint objectId, uint equipMask) + { + return ToAbiBool(ClientHelperHooks.WieldItem(objectId, equipMask)); + } + private static unsafe int SendPluginCommandAction(IntPtr pluginNameAnsi, IntPtr actionAnsi, IntPtr valueAnsi) { try diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj index 95226b3..6d6a3b2 100644 --- a/src/RynthCore.Engine/RynthCore.Engine.csproj +++ b/src/RynthCore.Engine/RynthCore.Engine.csproj @@ -29,12 +29,40 @@ <Platforms>x86</Platforms> </PropertyGroup> + <!-- + -p:EngineHost=coreclr builds the engine as a plain managed assembly for the native + loader's CoreCLR host (docs/UNLOADABLE_ENGINE_PLAN.md): each hot reload loads it into a + fresh collectible AssemblyLoadContext and unloads the old one. Publish it with + scripts\Publish-EngineCoreClr.ps1. The default (aot) build is unchanged. + --> + <PropertyGroup Condition="'$(EngineHost)' == 'coreclr'"> + <PublishAot>false</PublishAot> + <NativeLib></NativeLib> + <SelfContained>false</SelfContained> + <DefineConstants>$(DefineConstants);ENGINE_CORECLR</DefineConstants> + <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> + <GenerateRuntimeConfigurationFiles>false</GenerateRuntimeConfigurationFiles> + <DebugType>portable</DebugType> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)' == 'Debug'"> <StackTraceSupport>true</StackTraceSupport> <DebugType>full</DebugType> <Optimize>false</Optimize> </PropertyGroup> + <!-- + GC segment size (hex, 8 MB). The GC reserves SOH + LOH + POH segments up + front, 16 MB each by default on x86: 48 MB of acclient's 4 GB address space + per engine copy, kept for the life of the process since a NativeAOT DLL + can't be unloaded and every hot-reload loads a fresh copy. 8 MB segments + reserve 16 MB. The plugins get the same setting (RynthSuite + Plugins/Directory.Build.props). Bare hex: the runtime ignores a 0x prefix. + --> + <ItemGroup> + <IlcArg Include="--runtimeopt:GCSegmentSize=800000" /> + </ItemGroup> + <ItemGroup> <PackageReference Include="ImGui.NET" Version="1.91.6.1" /> <PackageReference Include="Avalonia" Version="11.2.3" /> @@ -50,6 +78,10 @@ <Compile Include="..\RynthCore.App\CharacterCacheStore.cs" Link="Shared\CharacterCacheStore.cs" /> <Compile Include="..\RynthCore.App\SessionStateStore.cs" Link="Shared\SessionStateStore.cs" /> <Compile Include="..\RynthCore.App\BuildVersion.cs" Link="Shared\BuildVersion.cs" /> + <!-- DXT1/3/5 for AC icons in script windows (UI/ScriptWindows/AcIconDecoder.cs); the StatusAgent's copy (MonoGame, Ms-PL). --> + <Compile Include="..\RynthCore.StatusAgent\Dat\DxtUtil.cs" Link="Shared\DxtUtil.cs" /> + <!-- The byte-ring protocol shared with the Decal bridge plugin (docs/DECAL_BRIDGE_PLAN.md). --> + <Compile Include="..\RynthCore.DecalBridge\BridgeProtocol.cs" Link="Shared\BridgeProtocol.cs" /> </ItemGroup> <!-- Prevent trimmer from removing ImGui.NET's DllImport methods --> @@ -69,6 +101,12 @@ <BundledNativeDll Include="Native\cimgui.dll" /> </ItemGroup> + <!-- Phosphor icon font (MIT, Assets\Fonts\Phosphor.LICENSE, THIRD-PARTY-NOTICES.md): + inside the engine DLL, read by ImGuiFonts.Preload, so no deploy step ships it. --> + <ItemGroup> + <EmbeddedResource Include="Assets\Fonts\Phosphor.ttf" LogicalName="RynthCore.Engine.Assets.Fonts.Phosphor.ttf" /> + </ItemGroup> + <ItemGroup> <BundledSupportDll Include="Native\minhook.x86.dll" /> </ItemGroup> diff --git a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs index 75c1a83..87af52f 100644 --- a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs +++ b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs @@ -228,6 +228,9 @@ internal static class AvaloniaOverlay internal static volatile int SurfacePixelWidth; internal static volatile int SurfacePixelHeight; internal static volatile float InputScale = 1f; + + /// <summary>True once the overlay window exists (Start ran and built it).</summary> + internal static bool IsRunning => _window != null; internal static bool UseAnglePreferredBridge { get; private set; } internal static bool UseCustomSkiaBridge { get; private set; } internal static bool ShouldUseCustomSkiaProducer => UseCustomSkiaBridge; @@ -321,6 +324,7 @@ internal static class AvaloniaOverlay internal static void RequestCapture() { + if (_window == null) return; // not started: nothing to capture, no dispatcher to wake Dispatcher.UIThread.Post(() => _window?.RequestCapture(), DispatcherPriority.Input); } @@ -331,27 +335,107 @@ internal static class AvaloniaOverlay { var dcomp = DcompActivateBarButton; if (dcomp != null) { dcomp(title); return; } + // Not started (Avalonia off, e.g. the CoreCLR engine): no Avalonia panels, and + // touching Dispatcher.UIThread would bring up a dispatcher for nothing. + if (_window == null) return; Dispatcher.UIThread.Post(() => _window?.ActivateBarButton(title), DispatcherPriority.Input); } + /// <summary> + /// The ImGui face of <paramref name="title"/> just opened: take down any + /// Avalonia copy of it (docked or popped out) without saving that as the + /// panel's state, so one panel is never on screen twice. Any thread. + /// </summary> + internal static void CloseAvaloniaCopy(string title) + { + if (_window == null) return; // not started: there is no Avalonia copy (and no dispatcher to wake) + Dispatcher.UIThread.Post(() => _window?.CloseAvaloniaCopyCore(title), DispatcherPriority.Input); + } + + /// <summary> + /// Runs <paramref name="action"/> on the Avalonia UI thread at Input + /// priority (same queue as ActivateBarButton), so a sequence of UI steps + /// stays in order. Any thread. + /// </summary> + /// <summary> + /// Takes keyboard focus off any Avalonia TextBox (an ImGui text field just + /// took the keyboard; plan §3.2 d). Clearing Avalonia's focus makes the + /// TextBox lose focus (which clears AvaloniaTextInputActive) without + /// touching Win32 focus. Any thread. + /// </summary> + internal static void ClearTextFocus() + { + if (_window != null) + Dispatcher.UIThread.Post(() => _window?.FocusManager?.ClearFocus(), DispatcherPriority.Input); + } + + internal static void PostToUi(Action action) + { + if (_window != null) + Dispatcher.UIThread.Post(action, DispatcherPriority.Input); + } + + /// <summary>Toggles a panel synchronously. Avalonia UI thread only (inside PostToUi).</summary> + internal static void TogglePanelOnUiThread(string title) => _window?.ActivateBarButton(title); + + /// <summary> + /// True while the ImGui bar stands in for the docked Avalonia bar: the + /// Avalonia bar is laid out but invisible (opacity 0, so pop-out can still + /// measure it) and publishes no hit rects, so it takes no clicks. + /// </summary> + internal static volatile bool DockedBarSuppressed; + + internal static void SetDockedBarSuppressed(bool suppressed) + { + DockedBarSuppressed = suppressed; + // Before Start there is no window (and no UI thread to post to): BuildRoot reads the flag. + if (_window != null) + Dispatcher.UIThread.Post(() => _window?.ApplyDockedBarSuppression(), DispatcherPriority.Input); + } + + /// <summary> + /// The ImGui bar's ↗: move the (hidden) docked Avalonia bar to where the + /// ImGui bar is, then pop it out, in one UI-thread step so PopOutBar + /// snapshots the right docked position. + /// </summary> + internal static void PopOutBarFrom(double left, double top) + { + if (_window == null) return; + Dispatcher.UIThread.Post(() => + { + _window?.MoveDockedBar(left, top); + _window?.PopOutBar(); + }, DispatcherPriority.Input); + } + + /// <summary>Keeps the hidden docked Avalonia bar where the ImGui bar is. Any thread.</summary> + internal static void SyncDockedBarPosition(double left, double top) + { + if (_window != null) + Dispatcher.UIThread.Post(() => _window?.MoveDockedBar(left, top), DispatcherPriority.Input); + } + internal static void CommitDrag(int x, int y) { + if (_window == null) return; Dispatcher.UIThread.Post(() => _window?.CommitBarDrag(x, y), DispatcherPriority.Render); } internal static void MoveBarByPhys(int x, int y) { + if (_window == null) return; Dispatcher.UIThread.Post(() => _window?.MoveBarByPhys(x, y), DispatcherPriority.Input); } internal static void ResizePanelByPhys(int w, int h) { + if (_window == null) return; Dispatcher.UIThread.Post(() => _window?.ResizeShellByPhys(w, h), DispatcherPriority.Input); } internal static void NotifyGameSurfaceMetricsChanged() { - if (!UseCustomSkiaBridge) + if (!UseCustomSkiaBridge || _window == null) return; Dispatcher.UIThread.Post(() => _window?.OnGameSurfaceMetricsChanged(), DispatcherPriority.Render); @@ -396,6 +480,7 @@ internal static class AvaloniaOverlay internal static void DismissLightDismissPopups() { HasOpenLightDismissPopup = false; + if (_window == null) return; Dispatcher.UIThread.Post(() => _window?.CloseLightDismissPopups(), DispatcherPriority.Input); } @@ -1337,13 +1422,13 @@ internal class RynthOverlayWindow : Window ToolTip.SetTip(rcLabel, $"RynthCore {EntryPoint.BuildStamp}"); // plugins: Status panel stack.Children.Add(rcLabel); - var barSuppressed = new HashSet<string> { "Monsters", "Settings", "Nav", "Meta", "Items" }; + var barSuppressed = new HashSet<string> { "Monsters", "Damage", "Settings", "Nav", "Meta", "Items", "Lua" }; foreach (var p in registeredPanels) { _registeredPanels[p.Title] = p.Factory; if (barSuppressed.Contains(p.Title)) continue; var btn = StyleBarButton(new Button { Content = p.Title }); - btn.Click += (_, _) => ActivateBarButton(p.Title); + btn.Click += (_, _) => PanelRouter.Toggle(p.Title); stack.Children.Add(btn); _barButtons[p.Title] = btn; } @@ -1389,6 +1474,11 @@ internal class RynthOverlayWindow : Window CornerRadius = new CornerRadius(4), Child = stack }; + if (AvaloniaOverlay.DockedBarSuppressed) + { + _barBorder.Opacity = 0; + _barBorder.IsHitTestVisible = false; + } // Update physical bar bounds for dragging. Use the persisted position // if we have one so a reload (or AC restart) keeps the user's layout. @@ -1432,7 +1522,8 @@ internal class RynthOverlayWindow : Window // its own comments. Poll briefly; give up after a few seconds so // a never-ready GameHwnd (Decal coexistence?) doesn't leave the // bar lost. - if (PanelStateStore.BarFloating && _floatingBar == null) + // An ImGui-faced bar pops out as an ImGui window (ImGuiBar.SyncPopOut). + if (PanelStateStore.BarFloating && _floatingBar == null && ImGuiBar.ResolveFace() != PanelFace.ImGui) { TryRestoreFloatingBar(attemptsRemaining: 30); } @@ -1454,9 +1545,18 @@ internal class RynthOverlayWindow : Window } if (kv.Value.Floating) { + // Panels with an ImGui face pop out as ImGui windows now + // (ImGuiPopOuts, Tom 2026-09-29): ImGuiPanelHost.RestoreOnce + // reopens them popped out. Leave the saved entry alone. + if (PanelRouter.ResolveDockedFace(kv.Key) == PanelFace.ImGui) + continue; deferred.Add(kv.Key); continue; } + // Docked panels whose docked face is ImGui are restored by + // ImGuiPanelHost.RestoreOnce instead. + if (PanelRouter.ResolveDockedFace(kv.Key) == PanelFace.ImGui) + continue; if (_registeredPanels.TryGetValue(kv.Key, out Func<Control>? factory)) TogglePanel(kv.Key, factory); } @@ -1487,54 +1587,24 @@ internal class RynthOverlayWindow : Window } } - // How often, and for how long, the login-time floating-panel restore waits - // for Win32Backend to be able to create windows on AC's game thread. - private const int FloatingRestorePollMs = 200; - private const long FloatingRestoreMaxWaitMs = 60_000; + private void RestoreFloatingPanels(List<string> titles) => RestoreFloatingPanels(titles, 0); - /// <summary> - /// Restores saved floating panels, but only once - /// <see cref="ImGuiBackend.Win32Backend.CanRunOnGameThread"/> is true, so - /// each panel's LayeredWindow is created on AC's game thread like every - /// other pop-out. LoginComplete can fire before the engine has found and - /// hooked the game window; popping out then makes FloatingPanelHost take - /// its legacy path and create the HWND on the Avalonia UI thread instead - /// (Win11 WS_EX_NOACTIVATE focus race, cross-thread destroy on redock). - /// Polls on the UI thread; after <see cref="FloatingRestoreMaxWaitMs"/> it - /// restores anyway (logged) so a never-hooked client doesn't lose the panels. - /// </summary> - private void RestoreFloatingPanels(List<string> titles) => - RestoreFloatingPanelsWhenGameThreadReady(titles, Environment.TickCount64 + FloatingRestoreMaxWaitMs, loggedWait: false); - - private void RestoreFloatingPanelsWhenGameThreadReady(List<string> titles, long deadline, bool loggedWait) + private void RestoreFloatingPanels(List<string> titles, int waited) { - if (!ImGuiBackend.Win32Backend.CanRunOnGameThread) + // A floating panel's window must be created on AC's thread (PopOut uses + // RunOnGameThread). Login can complete before Win32Backend knows the game + // window (it initialises with ImGui, a few seconds later); restoring then + // created the window on this thread, the later close was posted to the + // game thread, DestroyWindow failed with ACCESS_DENIED and the old window + // stayed up beside every reopened one — the double dashboard + // (2026-09-28). Wait for the game window, up to ~30 s. + if (ImGuiBackend.Win32Backend.GameHwnd == IntPtr.Zero && waited < 120) { - if (Environment.TickCount64 < deadline) - { - if (!loggedWait) - { - try { RynthLog.UI($"AvaloniaOverlay: holding {titles.Count} floating panel(s) until the game window is hooked (GameHwnd=0x{ImGuiBackend.Win32Backend.GameHwnd.ToInt64():X}): [{string.Join(", ", titles)}]"); } catch { } - } - DispatcherTimer.RunOnce( - () => RestoreFloatingPanelsWhenGameThreadReady(titles, deadline, loggedWait: true), - TimeSpan.FromMilliseconds(FloatingRestorePollMs), - DispatcherPriority.Background); - return; - } - - try { RynthLog.UI($"AvaloniaOverlay: game window still not hooked after {FloatingRestoreMaxWaitMs / 1000}s — restoring floating panels on the legacy (UI-thread) path."); } catch { } + DispatcherTimer.RunOnce(() => RestoreFloatingPanels(titles, waited + 1), TimeSpan.FromMilliseconds(250)); + return; } - else if (loggedWait) - { - try { RynthLog.UI("AvaloniaOverlay: game window hooked — restoring held floating panels on the game thread."); } catch { } - } - - RestoreFloatingPanelsNow(titles); - } - - private void RestoreFloatingPanelsNow(List<string> titles) - { + if (waited > 0) + try { RynthLog.UI($"AvaloniaOverlay: restoring floating panel(s) after waiting {waited * 250} ms for the game window."); } catch { } try { foreach (var title in titles) @@ -1561,6 +1631,35 @@ internal class RynthOverlayWindow : Window QueueCapture(); } + internal void CloseAvaloniaCopyCore(string title) + { + try + { + if (_floatingPanels.TryGetValue(title, out FloatingPanelHost? host)) + { + RynthLog.Info($"Panel({title}): ImGui face opened; closing its popped-out Avalonia window."); + _floatingPanels.Remove(title); + RebuildFloatingLayeredSnapshot(); + _panelContents.Remove(title); + try { _desktopCanvas.Children.Remove(host.RootControl); } catch { } + host.Dispose(); + } + if (_activePanels.TryGetValue(title, out Border? docked)) + { + RynthLog.Info($"Panel({title}): ImGui face opened; closing its docked Avalonia copy."); + _desktopCanvas.Children.Remove(docked); + _activePanels.Remove(title); + _panelContents.Remove(title); + } + RefreshHitTestSnapshot(); + RequestFrameRefresh(); + } + catch (Exception ex) + { + RynthLog.Info($"Panel({title}): CloseAvaloniaCopy threw {ex.GetType().Name}: {ex.Message}"); + } + } + internal void ActivateBarButton(string title) { if (_registeredPanels.TryGetValue(title, out Func<Control>? factory)) @@ -1586,20 +1685,63 @@ internal class RynthOverlayWindow : Window } } + // Every docked frame carries this tag so a frame the dictionaries lost + // track of can still be found (see RemoveStrayPanelFrames). + private const string PanelFrameTagPrefix = "rc-panel:"; + + private static string PanelFrameTag(string title) => PanelFrameTagPrefix + title; + + /// <summary> + /// A panel has at most one frame. Before opening a new one, remove any + /// frame for this title still sitting in the canvas that neither + /// _activePanels nor a floating host owns: it would keep drawing under the + /// new one and could never be clicked (hit-testing only covers tracked + /// frames), i.e. the "frozen duplicate" players see. + /// </summary> + private int RemoveStrayPanelFrames(string title) + { + string tag = PanelFrameTag(title); + _activePanels.TryGetValue(title, out Border? tracked); + _floatingPanels.TryGetValue(title, out FloatingPanelHost? host); + var strays = _desktopCanvas.Children + .OfType<Control>() + .Where(c => c.Tag is string t && t == tag + && !ReferenceEquals(c, tracked) + && !ReferenceEquals(c, host?.RootControl)) + .ToList(); + foreach (Control stray in strays) + { + try { _desktopCanvas.Children.Remove(stray); } catch { } + } + if (strays.Count > 0) + RynthLog.Info($"Panel({title}): removed {strays.Count} untracked frame(s) from the overlay - a duplicate was about to show."); + return strays.Count; + } + + private int CountPanelFrames(string title) + { + string tag = PanelFrameTag(title); + return _desktopCanvas.Children.Count(c => c.Tag is string t && t == tag); + } + private void TogglePanel(string title, Func<Control> factory) { if (_activePanels.TryGetValue(title, out var existing)) { + RynthLog.Info($"Panel({title}): toggle -> close docked (frames={CountPanelFrames(title)}, inWorld={LoginLifecycleHooks.HasObservedLoginComplete})."); ClosePanel(title, existing); } else if (_floatingPanels.TryGetValue(title, out var floating)) { // Toggling a panel that's currently popped out closes the // floating window entirely (matches the docked-mode toggle). + RynthLog.Info($"Panel({title}): toggle -> close floating (frames={CountPanelFrames(title)}, inWorld={LoginLifecycleHooks.HasObservedLoginComplete})."); CloseFloatingPanel(title, floating); } else { + RemoveStrayPanelFrames(title); + RynthLog.Info($"Panel({title}): toggle -> open (inWorld={LoginLifecycleHooks.HasObservedLoginComplete}, canvas={_desktopCanvas.Bounds.Width:0}x{_desktopCanvas.Bounds.Height:0})."); bool isRynthAi = string.Equals(title, "RynthAi", StringComparison.OrdinalIgnoreCase); bool isMonsters = string.Equals(title, "Monsters", StringComparison.OrdinalIgnoreCase); bool isRadar = string.Equals(title, "Radar", StringComparison.OrdinalIgnoreCase); @@ -1618,7 +1760,7 @@ internal class RynthOverlayWindow : Window // clamps the effective render size regardless of how Height was // set, so a hardcoded large floor here would silently re-expand // it back to 260 on every reopen despite the smaller saved value. - bool rynthAiMinimized = isRynthAi && Panels.RynthAiPanel.IsAvaloniaMinimized; + bool rynthAiMinimized = isRynthAi && RynthAiDashboardState.Minimized; var windowFrame = new Border { Width = hasSaved && saved.Width > 0 ? saved.Width : defaultW, @@ -2054,6 +2196,7 @@ internal class RynthOverlayWindow : Window windowFrame.Child = grid; windowFrame.PointerPressed += (_, _) => BringPanelToFront(title, windowFrame); + windowFrame.Tag = PanelFrameTag(title); _desktopCanvas.Children.Add(windowFrame); double initialLeft = hasSaved ? saved.Left : 100 + (_activePanels.Count * 20); @@ -2086,16 +2229,30 @@ internal class RynthOverlayWindow : Window private void ClosePanel(string title, Border panel) { + // Only forget the tracked frame if it is the one being closed. A close + // from an older frame's handler must not untrack the live frame: that + // left it drawing in the canvas, unclickable, and the next bar toggle + // opened a second copy on top of it. + bool isTracked = _activePanels.TryGetValue(title, out Border? tracked) && ReferenceEquals(tracked, panel); + // Save final pos/size before tearing the panel down so reopens // start where the user left it. - PersistPanelState(title, panel, open: false); + if (isTracked) + PersistPanelState(title, panel, open: false); _desktopCanvas.Children.Remove(panel); - _activePanels.Remove(title); - // Drop the content reference — closing the panel discards in-panel - // state, matching the previous behavior where reopening called factory() - // again. Popout/redock keeps the entry, full-close removes it. - _panelContents.Remove(title); + if (isTracked) + { + _activePanels.Remove(title); + // Drop the content reference — closing the panel discards in-panel + // state, matching the previous behavior where reopening called factory() + // again. Popout/redock keeps the entry, full-close removes it. + _panelContents.Remove(title); + } + else + { + RynthLog.Info($"Panel({title}): close came from an untracked frame; the tracked frame stays open."); + } // Tear down the radar's settings popup if this is the radar — the // popup lives in _desktopCanvas as a sibling and would otherwise // leak past the panel close. @@ -2288,6 +2445,7 @@ internal class RynthOverlayWindow : Window Canvas.SetLeft(renderWrapper, offBoundsX); Canvas.SetTop(renderWrapper, offBoundsY); + renderWrapper.Tag = PanelFrameTag(title); _desktopCanvas.Children.Add(renderWrapper); // The chrome's caption is 24px tall; reserve ~60px on the right for @@ -2746,6 +2904,11 @@ internal class RynthOverlayWindow : Window // where the user popped out from. Canvas.GetLeft can return NaN if // the bar hasn't been positioned yet — defensive defaults match // BuildRoot's initial 50,5. + // Popped out, the bar is always the Avalonia bar - even while the ImGui + // bar stands in for it docked. + _barBorder.Opacity = 1; + _barBorder.IsHitTestVisible = true; + double dockedLeft = GetCanvasLeft(_barBorder); double dockedTop = GetCanvasTop(_barBorder); if (double.IsNaN(dockedLeft)) dockedLeft = 50; @@ -2951,9 +3114,26 @@ internal class RynthOverlayWindow : Window ToolTip.SetTip(_barPopoutButton, "Pop the bar out into its own floating window."); } + ApplyDockedBarSuppression(); + RynthLog.Info($"RedockBar: redocked to canvas at ({dockedLeft:0.#},{dockedTop:0.#})."); + } + + internal void ApplyDockedBarSuppression() + { + if (_barBorder == null) return; + bool hide = AvaloniaOverlay.DockedBarSuppressed && _floatingBar == null; + _barBorder.Opacity = hide ? 0 : 1; + _barBorder.IsHitTestVisible = !hide; RefreshHitTestSnapshot(); RequestFrameRefresh(); - RynthLog.Info($"RedockBar: redocked to canvas at ({dockedLeft:0.#},{dockedTop:0.#})."); + } + + internal void MoveDockedBar(double left, double top) + { + if (_barBorder == null || _floatingBar != null) return; + Canvas.SetLeft(_barBorder, left); + Canvas.SetTop(_barBorder, top); + RefreshHitTestSnapshot(); } /// <summary> @@ -2972,6 +3152,16 @@ internal class RynthOverlayWindow : Window return; } + // ImGui in game, Avalonia popped out: when this panel's docked face is + // ImGui, redocking closes the floating window and opens the ImGui face. + if (PanelRouter.RedockGoesToImGui(title)) + { + RynthLog.Info($"RedockPanel({title}): docked face is ImGui - handing off."); + CloseFloatingPanel(title, host); + PanelRouter.CompleteRedockToImGui(title); + return; + } + if (!_registeredPanels.TryGetValue(title, out Func<Control>? factory) || factory == null) { RynthLog.Info($"RedockPanel({title}): bailing — no factory."); @@ -3223,6 +3413,7 @@ internal class RynthOverlayWindow : Window Grid.SetRow(resizeGrip, 1); windowFrame.Child = grid; windowFrame.PointerPressed += (_, _) => BringPanelToFront(title, windowFrame); + windowFrame.Tag = PanelFrameTag(title); _desktopCanvas.Children.Add(windowFrame); double initialLeft = hasSaved ? saved.Left : 100 + (_activePanels.Count * 20); @@ -3910,7 +4101,14 @@ internal class RynthOverlayWindow : Window float inputScale = (float)GetEffectiveRenderScale(); AvaloniaOverlay.InputScale = inputScale; - if (_barBorder != null) + bool barSuppressed = AvaloniaOverlay.DockedBarSuppressed && _floatingBar == null; + if (barSuppressed) + { + // Off-screen, zero-size: IsOverPanel/bar drag never match it. + AvaloniaOverlay.PanelPhysLeft = AvaloniaOverlay.PanelPhysRight = -10000; + AvaloniaOverlay.PanelPhysTop = AvaloniaOverlay.PanelPhysBottom = -10000; + } + else if (_barBorder != null) { Point? barOrigin = _barBorder.TranslatePoint(default, _desktopCanvas); double barLeft = barOrigin?.X ?? Canvas.GetLeft(_barBorder); @@ -3930,7 +4128,7 @@ internal class RynthOverlayWindow : Window } var buttonRects = new Dictionary<string, (double Left, double Top, double Width, double Height)>(_barButtons.Count, StringComparer.OrdinalIgnoreCase); - if (_barBorder != null) + if (_barBorder != null && !barSuppressed) { foreach ((string title, Button button) in _barButtons) { @@ -4469,6 +4667,8 @@ internal sealed unsafe class FloatingPanelHost : IDisposable _ownerApplied = true; } + // One popped-out window per panel: retire any earlier window for this title. + LayeredWindow.ClaimTitle(title, _layered.Hwnd); _layered.CaptionHeight = captionHeight; _layered.CaptionRightInset = captionRightInset; // Each chrome button is 20×20 logical + ~4px margin = ~24 @@ -4494,8 +4694,14 @@ internal sealed unsafe class FloatingPanelHost : IDisposable // job and returns immediately, never blocking the game thread. _layered.OnInput = (uint msg, IntPtr wp, IntPtr lp, int cx, int cy) => Dispatcher.UIThread.Post(() => ForwardInput(msg, wp, lp, cx, cy)); + // Post, not Invoke (2026-09-30): OnMoved fires on AC's game thread (the + // LayeredWindow WndProc: WM_MOVE, EndDrag, capture loss) and only persists + // the position, so nothing needs to wait for it. The blocking Invoke held + // AC's frame on panel-state persistence at every drag end, and is the same + // AB-BA deadlock class as OnInput above if the UI thread is inside + // RunOnGameThread / UpdateLayeredWindow on this HWND at that moment. _layered.OnMoved = (x, y) => - Dispatcher.UIThread.Invoke(() => OnLayeredMoved(x, y)); + Dispatcher.UIThread.Post(() => OnLayeredMoved(x, y)); // Invoke (synchronous), NOT Post. This is deliberate: the WndProc runs // on AC's game thread, and during an HTBOTTOMRIGHT drag it sits in the // OS modal resize loop. The synchronous Invoke blocks that loop until @@ -4554,13 +4760,33 @@ internal sealed unsafe class FloatingPanelHost : IDisposable internal void SetShown(bool shown) { if (_disposed || _layered.Hwnd == IntPtr.Zero || _windowShown == shown) return; - _windowShown = shown; - ImGuiBackend.Win32Backend.RunOnGameThread(() => + long now = Environment.TickCount64; + if (now < _setShownRetryAtMs) return; + + // Record the new state only once the game thread has actually run the + // Show/Hide. RunOnGameThread gives up after 2 s and returns false - the + // game thread is often that busy right at login - and recording the + // state first left a popped-out panel hidden for the whole session + // (the bar button then "closes" an invisible window). Retry after 1 s. + bool ran = ImGuiBackend.Win32Backend.RunOnGameThread(() => { if (shown) _layered.Show(); else _layered.Hide(); + return true; }); + if (ran) + { + _windowShown = shown; + _setShownRetryAtMs = 0; + } + else + { + _setShownRetryAtMs = now + 1000; + RynthLog.Info($"FloatingPanelHost({Title}): {(shown ? "Show" : "Hide")} didn't run on the game thread; retrying."); + } } + private long _setShownRetryAtMs; + public void Tick() { if (_disposed || _layered.Hwnd == IntPtr.Zero) return; diff --git a/src/RynthCore.Engine/UI/Data/CharmsData.cs b/src/RynthCore.Engine/UI/Data/CharmsData.cs new file mode 100644 index 0000000..3d3cac4 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/CharmsData.cs @@ -0,0 +1,78 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/CharmsData.cs +// RynthAi's ACECustom charm tracker for the Settings panel's "Charms +// Tracking" tab. RynthAi owns the charm registry (WCIDs, ability flags) and +// the per-character "seen" memory; this side only shows the snapshot. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>RynthPluginGetCharmsJson's payload.</summary> +internal sealed class CharmsInfo +{ + /// <summary>False off ILT-like worlds (or before RynthAi's ILT Hub exists).</summary> + [JsonPropertyName("available")] public bool Available { get; set; } + [JsonPropertyName("world")] public string World { get; set; } = ""; + [JsonPropertyName("total")] public int Total { get; set; } + [JsonPropertyName("acquiredCount")] public int AcquiredCount { get; set; } + [JsonPropertyName("activeCount")] public int ActiveCount { get; set; } + [JsonPropertyName("charms")] public CharmRow[] Charms { get; set; } = Array.Empty<CharmRow>(); +} + +internal sealed class CharmRow +{ + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("effect")] public string Effect { get; set; } = ""; + /// <summary>"carried" (in pack / equipped now), "seen" (carried before, now elsewhere) or "no".</summary> + [JsonPropertyName("acquired")] public string Acquired { get; set; } = "no"; + /// <summary>Copies carried right now.</summary> + [JsonPropertyName("count")] public int Count { get; set; } + /// <summary>Best tier carried or last seen; 0 until an appraisal reports it.</summary> + [JsonPropertyName("tier")] public int Tier { get; set; } + [JsonPropertyName("maxTier")] public int MaxTier { get; set; } + /// <summary>Ability toggled on: "on", "off" or "unknown".</summary> + [JsonPropertyName("active")] public string Active { get; set; } = "unknown"; + /// <summary>Server-side global switch as far as the client has learned it: "on", "off" or "unknown".</summary> + [JsonPropertyName("server")] public string Server { get; set; } = "unknown"; + /// <summary>yyyy-MM-dd the charm was last carried (empty when never).</summary> + [JsonPropertyName("lastSeen")] public string LastSeen { get; set; } = ""; +} + +[JsonSerializable(typeof(CharmsInfo))] +internal sealed partial class CharmsJsonContext : JsonSerializerContext { } + +/// <summary> +/// RynthPluginGetCharmsJson (single static buffer: one caller only) while the Settings panel +/// is open. Every 2 s is plenty: charm state only changes when one is picked up or toggled. +/// </summary> +internal sealed unsafe class CharmsSource : UiSource<CharmsInfo> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _getCharmsJson; + + public CharmsSource() : base("Charms", periodMs: 2000) { } + + protected internal override void Poll() + { + if (_getCharmsJson == null) + _getCharmsJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetCharmsJson"); + if (_getCharmsJson == null) return; + IntPtr p = _getCharmsJson(); + string json = p == IntPtr.Zero ? "{}" : Marshal.PtrToStringAnsi(p) ?? "{}"; + CharmsInfo info; + try { info = JsonSerializer.Deserialize(json, CharmsJsonContext.Default.CharmsInfo) ?? new CharmsInfo(); } + catch (JsonException) { info = new CharmsInfo(); } + Publish(info); + } + + protected internal override void Reset() + { + _getCharmsJson = null; + ClearSnapshot(); + } +} diff --git a/src/RynthCore.Engine/UI/Data/ChatCoords.cs b/src/RynthCore.Engine/UI/Data/ChatCoords.cs new file mode 100644 index 0000000..311b697 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatCoords.cs @@ -0,0 +1,72 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatCoords.cs +// Finds map coordinates in a chat line ("42.1N, 33.6E", "42.1N 33.6E", +// "33.6E 42.1N", "0.5S, 101.2W"), for the chat window's right-click menu +// ("Arrow to ..." / "Go to ..." send them to RynthNav). +// +// Runs when a line's menu opens, never per frame. No engine dependencies: +// tools/ChatCoordTests compiles this file. +// +// To keep ordinary chat from turning into coordinates ("give me 5 s, 2 e"), +// a pair counts when both letters are capitals, or both numbers have a decimal +// point; and every number must be on the map (0 to 102). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Engine.UI.Data; + +internal readonly record struct ChatCoord(int Start, int Length, double Ns, double Ew) +{ + /// <summary>"42.1N, 33.6E".</summary> + public string Text => Fmt(Ns, 'N', 'S') + ", " + Fmt(Ew, 'E', 'W'); + + private static string Fmt(double v, char pos, char neg) => + Math.Abs(v).ToString("0.0##", CultureInfo.InvariantCulture) + (v >= 0 ? pos : neg); +} + +internal static class ChatCoords +{ + private const double MaxDegrees = 102.0; + + // number, optional space, letter; then a separator; then the other axis. + private static readonly Regex NsFirst = new( + @"(?<![\w.])(\d{1,3}(?:\.\d+)?)\s?([NnSs])(?![A-Za-z])[\s,;/]*(\d{1,3}(?:\.\d+)?)\s?([EeWw])(?![\w])", + RegexOptions.CultureInvariant); + private static readonly Regex EwFirst = new( + @"(?<![\w.])(\d{1,3}(?:\.\d+)?)\s?([EeWw])(?![A-Za-z])[\s,;/]*(\d{1,3}(?:\.\d+)?)\s?([NnSs])(?![\w])", + RegexOptions.CultureInvariant); + + /// <summary>Every coordinate pair in <paramref name="text"/>, in order, without overlaps.</summary> + public static List<ChatCoord> Find(string? text) + { + var found = new List<ChatCoord>(); + if (string.IsNullOrEmpty(text) || text.Length > 4000) return found; + Collect(NsFirst, text, nsFirst: true, found); + Collect(EwFirst, text, nsFirst: false, found); + found.Sort((a, b) => a.Start.CompareTo(b.Start)); + for (int i = found.Count - 1; i > 0; i--) + if (found[i].Start < found[i - 1].Start + found[i - 1].Length) found.RemoveAt(i); + return found; + } + + private static void Collect(Regex rx, string text, bool nsFirst, List<ChatCoord> found) + { + foreach (Match m in rx.Matches(text)) + { + string n1 = m.Groups[1].Value, l1 = m.Groups[2].Value, n2 = m.Groups[3].Value, l2 = m.Groups[4].Value; + bool capitals = char.IsUpper(l1[0]) && char.IsUpper(l2[0]); + bool decimals = n1.Contains('.') && n2.Contains('.'); + if (!capitals && !decimals) continue; + if (!double.TryParse(n1, NumberStyles.Float, CultureInfo.InvariantCulture, out double a)) continue; + if (!double.TryParse(n2, NumberStyles.Float, CultureInfo.InvariantCulture, out double b)) continue; + if (a > MaxDegrees || b > MaxDegrees) continue; + double v1 = "SsWw".IndexOf(l1[0]) >= 0 ? -a : a; + double v2 = "SsWw".IndexOf(l2[0]) >= 0 ? -b : b; + found.Add(nsFirst ? new ChatCoord(m.Index, m.Length, v1, v2) : new ChatCoord(m.Index, m.Length, v2, v1)); + } + } +} diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs new file mode 100644 index 0000000..da6ac12 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -0,0 +1,1801 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatData.cs +// RynthChat's state, shared by both chat faces (ImGui/Panels/ChatFace.cs and +// the Avalonia UI/Panels/RynthChatPanel.cs) and both filter editors: +// +// • ChatSource (hub, 100 ms) pulls new lines from RynthChatGetScrollbackJson +// on the pump thread, keeps the newest 500, routes and colours them with +// the rules, and writes the chat log. +// • ChatModel holds the settings (rynthchat_settings.json), the regex +// rules and custom tabs, and the chat input line. +// +// Rules (2026-09-29 overhaul). Each rule is a case-insensitive regex matched +// against the line's text as AC printed it (no timestamp, so ^ and $ work), +// optionally only for one channel or chat type. It can +// Move the line to a tab (it leaves All and its channel tab), +// Copy it to a tab as well (it stays where it was), +// Hide it everywhere, or +// Colour it only, +// and it can colour the whole line or just the matched text. Order: top to +// bottom. Copy rules add up; the first matching Move or Hide decides and +// stops the routing. The first matching line colour wins; matched-text +// colours add up, a higher rule winning where two overlap. +// +// Threads: rules are evaluated ONLY on the pump (ChatSource) - each new line +// once, and every kept line again when the rules change - and the result is +// stored on the line (ChatLine.Route). The faces just read routes; no regex +// runs per frame. The one UI-thread evaluation is the rule editor's test box, +// on a keystroke. Every regex has a 15 ms match timeout; a rule that times +// out is marked Slow and skipped until it is edited, so a pathological +// pattern costs one timeout, not one per line. A rule that never times out +// but spends over 100 ms re-routing the kept lines is marked Slow too: the +// pump is the plugin tick thread, and a slow re-route holds every plugin's +// tick (ChatRouter.Charge). +// +// The input line: while ChatCaptureActive, Win32Backend's WndProc hook turns +// keys into the OnChat* callbacks on AC's main thread. ChatModel installs +// them once at init (InstallInput), so typing works whichever face is on +// screen; RynthChatSendLine runs there too (it feeds AC's chat parser). The +// export is resolved by ChatSource on the pump, since PluginExportBinder +// refuses AC's thread. +// +// Nothing here touches Avalonia: EntryPoint calls ChatModel.EnsureSettingsLoaded +// before the overlay starts (see the dispatcher invariant there). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using System.Threading; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.ImGuiBackend; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>One scrollback line. Immutable except its Route, which the pump replaces.</summary> +internal sealed class ChatLine +{ + public ChatLine(long id, string ts, string chan, int chatType, string? sender, string text) + { + Id = id; + Timestamp = ts; + Channel = chan; + ChatType = chatType; + Sender = sender; + Text = text; + // The text already names the speaker ("Bob says, ..."); until 2026-09-29 + // the sender was printed in front of it as well ("Bob: Bob says, ..."). + FormattedText = $"{ts} {text}"; + } + + /// <summary>Engine-assigned, increasing for the whole session (the plugin's own + /// seq restarts after RL).</summary> + public long Id { get; } + public string Timestamp { get; } + /// <summary>The channel tab it belongs to (ChatClassifier in the plugin).</summary> + public string Channel { get; } + /// <summary>AC's ChatMessageType; -1 from RynthChat before 0.2.0.</summary> + public int ChatType { get; } + /// <summary>Who spoke, for player speech; metadata only (mentions, rules from a line).</summary> + public string? Sender { get; } + /// <summary>The line as AC printed it. Rules match this.</summary> + public string Text { get; } + /// <summary>"HH:mm:ss text": copy, log and the Avalonia face.</summary> + public string FormattedText { get; } + + private ChatRoute _route = ChatRoute.Default; + + /// <summary>Where the rules put this line and how it's coloured. Written by the + /// pump (before the line is published, and again when the rules change); any thread reads.</summary> + public ChatRoute Route + { + get => Volatile.Read(ref _route); + internal set => Volatile.Write(ref _route, value); + } +} + +/// <summary>A run of the line's Text drawn in its own colour (0xAARRGGBB).</summary> +internal readonly record struct ChatSpan(int Start, int Length, uint Argb); + +/// <summary>The rules' verdict for one line. Immutable.</summary> +internal sealed class ChatRoute +{ + public static readonly ChatRoute Default = new(false, true, null, null, null, false); + + public ChatRoute(bool hidden, bool inHome, string[]? tabs, uint? lineArgb, ChatSpan[]? spans, bool mention) + { + Hidden = hidden; + InHome = inHome; + Tabs = tabs; + LineArgb = lineArgb; + Spans = spans; + Mention = mention; + } + + /// <summary>A Hide rule matched: shown nowhere.</summary> + public bool Hidden { get; } + /// <summary>Shown under All and its channel tab (false once a Move rule took it away).</summary> + public bool InHome { get; } + /// <summary>Tabs a Move or Copy rule sent it to.</summary> + public string[]? Tabs { get; } + /// <summary>Whole-line colour from a rule; null = the channel colour.</summary> + public uint? LineArgb { get; } + /// <summary>Matched-text colours: offsets into Text, sorted, not overlapping.</summary> + public ChatSpan[]? Spans { get; } + /// <summary>Someone said your name (or a mention word).</summary> + public bool Mention { get; } + + public bool ShowsIn(string tab, string channel) + { + if (Hidden) return false; + if (InHome && (tab == "All" || string.Equals(tab, channel, StringComparison.OrdinalIgnoreCase))) return true; + if (Tabs != null) + foreach (string t in Tabs) + if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } +} + +internal enum ChatRuleAction +{ + /// <summary>Only in the rule's tab: leaves All and its channel tab.</summary> + Move, + /// <summary>Also in the rule's tab.</summary> + Copy, + /// <summary>Nowhere.</summary> + Hide, + /// <summary>No routing: the rule only colours.</summary> + Color, +} + +internal enum ChatColorMode { None, Line, Match } + +/// <summary>How a rule's Pattern is matched against the raw message text.</summary> +internal enum ChatMatchMode +{ + /// <summary>The pattern is a regex (case-insensitive).</summary> + Regex, + /// <summary>Plain text anywhere in the message.</summary> + Contains, + /// <summary>Plain text at the start of the message.</summary> + StartsWith, + /// <summary>Plain text at the end of the message (trailing spaces ignored).</summary> + EndsWith, +} + +/// <summary> +/// One rule. Its fields are edited in place by a rule editor (then +/// ChatModel.FiltersChanged); the pump reads each field once per line, and a +/// half-applied edit is re-routed by the version bump that follows it. +/// </summary> +internal sealed class ChatFilterRule +{ + public const int TimeoutMs = 15; + + public volatile bool Enabled = true; + public volatile string Pattern = ""; + /// <summary>The Move / Copy target. Empty: a Move or Copy rule routes nowhere (it can still colour).</summary> + public volatile string Tab = ""; + public volatile ChatRuleAction Action = ChatRuleAction.Move; + public volatile ChatColorMode ColorMode = ChatColorMode.None; + /// <summary>Regex, or a plain-text mode (escaped into a regex by <see cref="Recompile"/>).</summary> + public volatile ChatMatchMode Mode = ChatMatchMode.Regex; + /// <summary>A new rule's colour (amber).</summary> + public const uint DefaultColor = 0xFFFFD27A; + /// <summary>0xAARRGGBB.</summary> + public volatile uint ColorArgb = DefaultColor; + + private volatile WhenSpec _when = WhenSpec.Any; + /// <summary>"" any line; "chan:Combat" one channel tab; "type:3" one ChatMessageType (see ChatModel.Conditions).</summary> + public string When + { + get => _when.Raw; + set => _when = WhenSpec.Parse(value); + } + + /// <summary>Kept lines this rule matched (recounted when the rules change, then + /// counted up as lines arrive). Written by the pump; the editor shows it.</summary> + public int Hits; + + public volatile Regex? Compiled; + /// <summary>The pattern doesn't compile (or is empty).</summary> + public volatile bool Invalid; + /// <summary>Why it doesn't compile; null when it does or is just empty.</summary> + public volatile string? Error; + /// <summary>A match timed out: skipped until the pattern is edited.</summary> + public volatile bool Slow; + + /// <summary>Compiles the pattern once (after every pattern edit). Any thread.</summary> + public void Recompile() + { + Slow = false; + string pattern = Pattern; + if (pattern.Length == 0) { Compiled = null; Error = null; Invalid = true; return; } + string expr = Mode switch + { + ChatMatchMode.Contains => Regex.Escape(pattern), + ChatMatchMode.StartsWith => "^" + Regex.Escape(pattern), + ChatMatchMode.EndsWith => Regex.Escape(pattern.TrimEnd()) + @"\s*$", + _ => pattern, + }; + try + { + Compiled = new Regex(expr, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, + TimeSpan.FromMilliseconds(TimeoutMs)); + Error = null; + Invalid = false; + } + catch (ArgumentException ex) + { + Compiled = null; + Error = ex.Message; + Invalid = true; + } + } + + /// <summary>Does the rule route (Move / Copy with a tab, or Hide)?</summary> + public bool Routes => Action == ChatRuleAction.Hide + || (Action is ChatRuleAction.Move or ChatRuleAction.Copy && Tab.Length > 0); + + internal bool WhenMatches(string channel, int chatType) + { + WhenSpec w = _when; + if (w.Channel != null) return string.Equals(w.Channel, channel, StringComparison.OrdinalIgnoreCase); + if (w.Type >= 0) return w.Type == chatType; + return true; + } + + private sealed class WhenSpec + { + public static readonly WhenSpec Any = new("", null, -1); + public readonly string Raw; + public readonly string? Channel; + public readonly int Type; + private WhenSpec(string raw, string? channel, int type) { Raw = raw; Channel = channel; Type = type; } + + public static WhenSpec Parse(string? raw) + { + raw = (raw ?? "").Trim(); + if (raw.StartsWith("chan:", StringComparison.OrdinalIgnoreCase) && raw.Length > 5) + return new WhenSpec(raw, raw[5..], -1); + if (raw.StartsWith("type:", StringComparison.OrdinalIgnoreCase) && int.TryParse(raw[5..], out int t) && t >= 0) + return new WhenSpec(raw, null, t); + return Any; + } + } +} + +/// <summary>New RynthChat lines while a chat face is open (100 ms). Publishes the newest 500, routed.</summary> +internal sealed unsafe class ChatSource : UiSource<ChatLine[]> +{ + private const int MaxLines = 500; + private delegate* unmanaged[Cdecl]<ulong, IntPtr> _get; + private ulong _sinceSeq; + private long _nextId = 1; + private bool _boundLogged; + private long _routedVersion = -1; + private string _routedName = ""; + + public ChatSource() : base("Chat", periodMs: 100) { } + + protected internal override void Poll() + { + if (_get == null) + { + _get = (delegate* unmanaged[Cdecl]<ulong, IntPtr>)PluginExportBinder.Resolve("RynthChat", "RynthChatGetScrollbackJson"); + if (_get != null && !_boundLogged) + { + _boundLogged = true; + RynthLog.UI("ChatSource: bound RynthChat plugin exports."); + } + } + if (ChatModel.SendLinePtr == IntPtr.Zero) + ChatModel.SendLinePtr = PluginExportBinder.Resolve("RynthChat", "RynthChatSendLine"); + ChatModel.PluginBound = _get != null; + ChatModel.PumpLog(null); + + // The rules (or the name mentions look for) changed: route the kept lines again. + long version = ChatModel.FiltersVersion; + string name = ChatModel.PumpCharacterName(); + ChatRouter router = ChatModel.PumpRouter(name); + if (version != _routedVersion || name != _routedName) + { + _routedVersion = version; + _routedName = name; + ChatLine[]? kept = Current?.Value; + router.BeginPass(); + try + { + if (kept != null) + foreach (ChatLine line in kept) line.Route = router.Evaluate(line, null); + } + finally { router.EndPass(); } + ChatModel.BumpRoutes(); + } + + if (_get == null) return; + + IntPtr ptr = _get(_sinceSeq); + if (ptr == IntPtr.Zero) return; + string? json = Marshal.PtrToStringAnsi(ptr); + if (string.IsNullOrEmpty(json) || json == "[]") return; + + RynthChatLineDto[]? dtos = ParseLines(json, out ulong skippedSeq); + // Lines that couldn't be read still move the mark past them, or they'd come back every poll. + if (skippedSeq > _sinceSeq) _sinceSeq = skippedSeq; + if (dtos == null || dtos.Length == 0) return; + + var added = new List<ChatLine>(dtos.Length); + foreach (RynthChatLineDto dto in dtos) + { + if (dto.Seq <= _sinceSeq) continue; + _sinceSeq = dto.Seq; + string text = StripAcLinks(dto.Text ?? "", out string? linkedName); + var line = new ChatLine(_nextId++, dto.Ts ?? "", dto.Chan ?? "Other", dto.Type, + dto.Sender is { Length: > 0 } s ? StripAcLinks(s, out _) : linkedName, text); + line.Route = router.Evaluate(line, null); + if (line.Route.Mention) ChatModel.PumpMentionSound(); + added.Add(line); + } + if (added.Count == 0) return; + + ChatLine[] old = Current?.Value ?? Array.Empty<ChatLine>(); + int keepOld = Math.Max(0, Math.Min(old.Length, MaxLines - added.Count)); + int skipAdded = Math.Max(0, added.Count - MaxLines); + var lines = new ChatLine[keepOld + added.Count - skipAdded]; + Array.Copy(old, old.Length - keepOld, lines, 0, keepOld); + added.CopyTo(skipAdded, lines, keepOld, added.Count - skipAdded); + Publish(lines); + ChatModel.PumpLog(added); + } + + private int _badLinesLogged; + + // AC's clickable-name markup: <Tell:IIDString:0:Chucky>Chucky<\Tell>. The retail chat + // window renders it as a link; the panel printed it raw (fellowship, allegiance and + // channel lines, 2026-09-30). Shown as the name alone. + private static readonly System.Text.RegularExpressions.Regex AcTellLink = new( + @"<Tell:IIDString:\d+:([^>]*)>(.*?)<\\Tell>", + System.Text.RegularExpressions.RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20)); + + /// <summary>The text with AC's name links reduced to their display text; <paramref name="firstName"/> is the first linked name.</summary> + internal static string StripAcLinks(string text, out string? firstName) + { + firstName = null; + if (text.IndexOf("<Tell:", StringComparison.Ordinal) < 0) return text; + try + { + string? first = null; + string result = AcTellLink.Replace(text, m => + { + string shown = m.Groups[2].Value.Length > 0 ? m.Groups[2].Value : m.Groups[1].Value; + first ??= m.Groups[1].Value.Length > 0 ? m.Groups[1].Value : shown; + return shown; + }); + firstName = first; + return result; + } + catch (System.Text.RegularExpressions.RegexMatchTimeoutException) + { + return text; + } + } + + /// <summary> + /// The scrollback batch. A line System.Text.Json refuses (a lone UTF-16 + /// surrogate, which a plugin's chat text can carry) used to fail the whole + /// batch: _sinceSeq never moved, the same batch failed on every poll, and the + /// chat stood still until that line left the plugin's 500-line ring. Now the + /// batch is read line by line when it has to be; an unreadable line is + /// skipped and its seq returned in <paramref name="skippedSeq"/>. + /// </summary> + private RynthChatLineDto[]? ParseLines(string json, out ulong skippedSeq) + { + skippedSeq = 0; + try { return JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatLineDtoArray); } + catch (Exception) { } + try + { + using JsonDocument doc = JsonDocument.Parse(json); + if (doc.RootElement.ValueKind != JsonValueKind.Array) return null; + var list = new List<RynthChatLineDto>(); + foreach (JsonElement el in doc.RootElement.EnumerateArray()) + { + try + { + RynthChatLineDto? dto = el.Deserialize(RynthChatJsonContext.Default.RynthChatLineDto); + if (dto != null) list.Add(dto); + } + catch (Exception ex) + { + if (el.ValueKind == JsonValueKind.Object && el.TryGetProperty("seq", out JsonElement s) + && s.TryGetUInt64(out ulong seq) && seq > skippedSeq) + skippedSeq = seq; + if (_badLinesLogged++ < 5) + RynthLog.UI($"ChatSource: skipped a chat line it couldn't read ({ex.GetType().Name}: {ex.Message})."); + } + } + return list.ToArray(); + } + catch (Exception ex) + { + if (_badLinesLogged++ < 5) + RynthLog.UI($"ChatSource: scrollback JSON unreadable ({ex.GetType().Name}: {ex.Message})."); + return null; + } + } + + protected internal override void Reset() + { + // RL loads a fresh plugin copy whose scrollback numbers from 1 again. + // The lines already shown stay. + _get = null; + _sinceSeq = 0; + ChatModel.SendLinePtr = IntPtr.Zero; + ChatModel.PluginBound = false; + } +} + +/// <summary> +/// Evaluates the rules for one line: a snapshot of the rule list plus the +/// mention regex. Built by ChatModel.PumpRouter (pump) or for the editor's +/// test box (UI thread). One thread per router: each one's cost counters are +/// its own (the pump's lives on the pump; the test box builds a fresh one). +/// </summary> +internal sealed class ChatRouter +{ + /// <summary>Mentions colour the name like this (amber).</summary> + public const uint MentionArgb = 0xFFFFC857; + + // The 15 ms timeout only catches a pattern that is slow on one line. One that + // costs a millisecond or two per line never times out, yet re-routing the 500 + // kept lines (on every keystroke in the rule editor) then holds the pump - + // which is the plugin tick thread - for a second or more. So during a + // re-route pass each rule's matching time is added up, and a rule that uses + // more than PassBudgetMs is marked Slow like a timed-out one. An ordinary + // rule takes a few microseconds a line, a few ms for the pass. One reading + // counts at most MaxChargeMs, so a GC pause or a descheduled thread in the + // middle of a match doesn't condemn the rule on its own. + private const double PassBudgetMs = 100, MaxChargeMs = 30; + private static readonly long PassBudgetTicks = (long)(Stopwatch.Frequency * PassBudgetMs / 1000); + private static readonly long MaxChargeTicks = (long)(Stopwatch.Frequency * MaxChargeMs / 1000); + + /// <summary>ChatMessageType Emote (0x0C).</summary> + private const int EmoteType = 0x0C; + + private readonly ChatFilterRule[] _rules; + private readonly Regex? _mention; + private readonly string _self; + private readonly bool _countHits; + private readonly long[] _passTicks; + private bool _inPass; + + /// <param name="self">Your character's name ("" unknown): your own emotes don't mention you.</param> + /// <param name="countHits">Count matches into ChatFilterRule.Hits (the pump's router; not the test box's).</param> + public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits) + { + _rules = rules; + _mention = mention; + _self = self.Trim(); + _countHits = countHits; + _passTicks = new long[rules.Length]; + } + + /// <summary>Before routing every kept line again: hit counts restart, and each rule's time is watched.</summary> + public void BeginPass() + { + ResetHits(); + Array.Clear(_passTicks); + _inPass = true; + } + + public void EndPass() => _inPass = false; + + /// <summary>Adds a rule's matching time during a pass; marks it Slow past the budget. False once it's Slow.</summary> + private bool Charge(int i, long ticks, List<Step>? trace) + { + if (!_inPass) return true; + _passTicks[i] += Math.Min(ticks, MaxChargeTicks); + if (_passTicks[i] <= PassBudgetTicks) return true; + MarkSlow(_rules[i], trace, i, $"over {PassBudgetMs:0} ms to re-route the kept lines"); + return false; + } + + /// <summary>Before routing every kept line again.</summary> + public void ResetHits() + { + foreach (ChatFilterRule rule in _rules) Volatile.Write(ref rule.Hits, 0); + } + + /// <summary>One step of the editor's test: rule index (-1 = mention, -2 = a standard filter) and what it did.</summary> + public readonly record struct Step(int Rule, string What); + + /// <summary><see cref="Step.Rule"/> of a standard-filter (RynthChatPresets) step.</summary> + public const int StandardFilterStep = -2; + + public ChatRoute Evaluate(ChatLine line, List<Step>? trace) => + Evaluate(line.Text, line.Channel, line.ChatType, trace); + + public ChatRoute Evaluate(string text, string channel, int chatType, List<Step>? trace) + { + bool hidden = false, inHome = true, routed = false; + List<string>? tabs = null; + uint? lineArgb = null; + List<(int Start, int Length, uint Argb)>? spans = null; + + for (int i = 0; i < _rules.Length; i++) + { + ChatFilterRule rule = _rules[i]; + if (!rule.Enabled || rule.Slow) continue; + Regex? rx = rule.Compiled; + if (rx == null) continue; + ChatRuleAction action = rule.Action; + ChatColorMode mode = rule.ColorMode; + string tab = rule.Tab; + bool routes = action == ChatRuleAction.Hide + || (action is ChatRuleAction.Move or ChatRuleAction.Copy && tab.Length > 0); + bool wantsRoute = routes && !routed; + bool wantsLine = mode == ChatColorMode.Line && lineArgb == null; + bool wantsMatch = mode == ChatColorMode.Match; + // Nothing left for it to decide (the test box still shows that it matches). + if (!wantsRoute && !wantsLine && !wantsMatch && trace == null) continue; + if (!rule.WhenMatches(channel, chatType)) continue; + + Match m; + long t0 = Stopwatch.GetTimestamp(); + try { m = rx.Match(text); } + catch (RegexMatchTimeoutException) { MarkSlow(rule, trace, i, $"a match took over {ChatFilterRule.TimeoutMs} ms"); continue; } + if (!Charge(i, Stopwatch.GetTimestamp() - t0, trace)) continue; + if (!m.Success) continue; + if (_countHits) Interlocked.Increment(ref rule.Hits); + + var what = trace != null ? new StringBuilder() : null; + if (wantsRoute) + { + switch (action) + { + case ChatRuleAction.Hide: + hidden = routed = true; + what?.Append("hides it"); + break; + case ChatRuleAction.Move: + inHome = false; + routed = true; + AddTab(ref tabs, tab); + what?.Append("moves it to ").Append(tab); + break; + case ChatRuleAction.Copy: + AddTab(ref tabs, tab); + what?.Append("copies it to ").Append(tab); + break; + } + } + else if (routes && trace != null) + what!.Append("(a Move/Hide above already decided the tab)"); + if (hidden) + { + trace?.Add(new Step(i, what!.ToString())); + break; + } + if (wantsLine) + { + lineArgb = rule.ColorArgb; + what?.Append(what.Length > 0 ? ", " : "").Append("colours the line"); + } + else if (mode == ChatColorMode.Line && trace != null) + what!.Append(what.Length > 0 ? ", " : "").Append("(line colour already set above)"); + if (wantsMatch) + { + int n = 0; + long t1 = Stopwatch.GetTimestamp(); + try + { + for (; m.Success && n < 16; m = m.NextMatch()) + if (m.Length > 0) { (spans ??= new()).Add((m.Index, m.Length, rule.ColorArgb)); n++; } + } + catch (RegexMatchTimeoutException) { MarkSlow(rule, trace, i, $"a match took over {ChatFilterRule.TimeoutMs} ms"); } + if (!rule.Slow) Charge(i, Stopwatch.GetTimestamp() - t1, trace); + what?.Append(what.Length > 0 ? ", " : "").Append(n == 1 ? "colours the match" : $"colours {n} matches"); + } + if (what is { Length: 0 }) what.Append("matches, but has nothing to do yet (no tab, no colour)"); + trace?.Add(new Step(i, what!.ToString())); + } + + // Standard filters (RynthChatPresets) decide only what the custom rules left undecided. + if (!routed) + { + var preset = RynthCore.Engine.UI.Panels.RynthChatPresets.FirstMatch(text, channel); + if (preset != null) + { + string presetTab = preset.Tab; + routed = true; + if (presetTab.Length == 0) + { + hidden = true; + trace?.Add(new Step(StandardFilterStep, $"standard filter \"{preset.Label}\" hides it")); + } + else + { + inHome = false; + AddTab(ref tabs, presetTab); + trace?.Add(new Step(StandardFilterStep, $"standard filter \"{preset.Label}\" moves it to {presetTab}")); + } + } + } + + bool mention = false; + if (!hidden && _mention != null && ChatModel.MentionEligible(channel, chatType)) + { + try + { + Match m = _mention.Match(text); + for (int n = 0; m.Success && n < 8; m = m.NextMatch(), n++) + { + // Your own emote prints as "Tom waves." (type Emote, your name first): that's you, not a mention. + if (m.Index == 0 && chatType == EmoteType && _self.Length > 0 + && string.Equals(m.Value, _self, StringComparison.OrdinalIgnoreCase)) continue; + mention = true; + (spans ??= new()).Add((m.Index, m.Length, MentionArgb)); + } + } + catch (RegexMatchTimeoutException) { } + if (mention) trace?.Add(new Step(-1, "mentions you (highlighted)")); + } + + if (!hidden && inHome && tabs == null && lineArgb == null && spans == null && !mention) + return ChatRoute.Default; + return new ChatRoute(hidden, inHome, tabs?.ToArray(), lineArgb, Resolve(spans, text.Length), mention); + } + + private static void AddTab(ref List<string>? tabs, string tab) + { + tabs ??= new List<string>(2); + foreach (string t in tabs) if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return; + tabs.Add(tab); + } + + private static void MarkSlow(ChatFilterRule rule, List<Step>? trace, int index, string why) + { + if (!rule.Slow) + { + rule.Slow = true; + RynthLog.UI($"ChatModel: rule \"{rule.Pattern}\" is too slow ({why}) and is skipped until edited."); + // Lines already routed with it are routed again without it. + ChatModel.BumpFiltersVersion(); + } + trace?.Add(new Step(index, "too slow - now skipped until edited")); + } + + /// <summary>Overlapping spans: the earlier one (a higher rule) keeps its characters.</summary> + private static ChatSpan[]? Resolve(List<(int Start, int Length, uint Argb)>? spans, int textLength) + { + if (spans == null || spans.Count == 0) return null; + if (spans.Count == 1) + return new[] { new ChatSpan(spans[0].Start, spans[0].Length, spans[0].Argb) }; + var owner = new int[textLength]; // 0 = free, else span index + 1 + for (int s = 0; s < spans.Count; s++) + { + int end = Math.Min(textLength, spans[s].Start + spans[s].Length); + for (int c = spans[s].Start; c < end; c++) + if (owner[c] == 0) owner[c] = s + 1; + } + var result = new List<ChatSpan>(); + for (int c = 0; c < textLength;) + { + int o = owner[c]; + int start = c; + while (c < textLength && owner[c] == o) c++; + if (o != 0) result.Add(new ChatSpan(start, c - start, spans[o - 1].Argb)); + } + return result.ToArray(); + } +} + +internal static class ChatModel +{ + /// <summary>Channel tabs; must match ChatClassifier in the plugin.</summary> + public static readonly string[] BaseTabs = { "All", "Chat", "Channels", "System", "Combat", "Rynth", "Other" }; + + /// <summary>Channel colour as 0xAARRGGBB.</summary> + public static uint ChannelArgb(string chan) => chan switch + { + "Chat" => 0xFFE0E0E0, + "Channels" => 0xFF7AB8F5, + "System" => 0xFF8CA6BF, + "Combat" => 0xFFD93333, + "Rynth" => 0xFFE6B450, // amber, distinct from the blue/grey channels + _ => 0xFFAAAAAA, + }; + + /// <summary>The line's colour: a rule's line colour, else its channel's. 0xAARRGGBB.</summary> + public static uint LineArgb(ChatLine line) => line.Route.LineArgb ?? ChannelArgb(line.Channel); + + /// <summary> + /// What a rule's "When" can be: (stored value, label). Channel tabs, then + /// single ChatMessageTypes (ACE.Entity.Enum.ChatMessageType; retail's too). + /// </summary> + public static readonly (string Value, string Label)[] Conditions = + { + ("", "Any line"), + ("chan:Chat", "Chat tab (say, tells, allegiance, fellowship)"), + ("chan:Channels", "Channels tab (General, Trade, LFG...)"), + ("chan:System", "System tab"), + ("chan:Combat", "Combat tab (combat and magic)"), + ("chan:Rynth", "Rynth tab (plugin output)"), + ("chan:Other", "Other tab"), + ("type:3", "Tells to you"), + ("type:4", "Tells you send"), + ("type:2", "Say (local)"), + ("type:12", "Emotes"), + ("type:18", "Allegiance"), + ("type:19", "Fellowship"), + ("type:8", "Channels (General, Trade...)"), + ("type:17", "Spell words"), + ("type:7", "Magic"), + ("type:22", "Your combat"), + ("type:21", "Enemy combat"), + ("type:13", "Advancement"), + ("type:20", "World broadcast"), + ("type:16", "Appraisal"), + ("type:24", "Crafting"), + ("type:25", "Salvaging"), + ("type:23", "Recall"), + ("type:5", "System messages"), + }; + + /// <summary>The channel tab a ChatMessageType lands in; mirrors ChatClassifier.ChannelFor in the plugin.</summary> + public static string ChannelForType(int chatType) => (uint)chatType switch + { + 0x02 or 0x03 or 0x04 or 0x0A or 0x0B or 0x0C or 0x12 or 0x13 => "Chat", + 0x08 or 0x09 => "Channels", + 0x00 or 0x05 or 0x0D or 0x14 or 0x17 or 0x18 or 0x19 or 0x1F => "System", + 0x06 or 0x07 or 0x11 or 0x15 or 0x16 => "Combat", + _ => "Other", + }; + + public static string ConditionLabel(string when) + { + foreach (var c in Conditions) + if (string.Equals(c.Value, when, StringComparison.OrdinalIgnoreCase)) return c.Label; + return when.Length == 0 ? "Any line" : when; + } + + // ── Settings (any thread; saved with SaveSettings) ─────────────────── + + public static volatile float FontSize = 10f; + public static volatile int BackgroundAlpha = 0xF2; + public static volatile bool AutoScroll = true; + public static volatile bool LogEnabled; + /// <summary>Docked chat lets clicks through unless Ctrl is held (mirrors the radar option). + /// AvaloniaOverlay.ChatCtrlGatedClickThrough is the Avalonia hit-test gate; set both.</summary> + public static volatile bool CtrlGatedClickThrough; + public static volatile string ActiveChannel = "All"; + public static volatile bool ShowTimestamps = true; + /// <summary>Highlight your character's name (and MentionWords) in chat and channel lines.</summary> + public static volatile bool MentionHighlight = true; + /// <summary>A short system beep on a new mention (at most every 3 s).</summary> + public static volatile bool MentionSound; + /// <summary>Extra words to highlight, comma-separated.</summary> + public static volatile string MentionWords = ""; + + public static void SetCtrlGatedClickThrough(bool on) + { + CtrlGatedClickThrough = on; + AvaloniaOverlay.ChatCtrlGatedClickThrough = on; + SaveSettings(); + } + + // ── Rules and custom tabs ──────────────────────────────────────────── + // + // The lists are replaced, never changed in place, so readers on other + // threads can walk them; a rule's own fields are edited in place and then + // FiltersChanged. + + private static readonly object EditLock = new(); + private static ChatFilterRule[] _filters = Array.Empty<ChatFilterRule>(); + private static string[] _customTabs = Array.Empty<string>(); + private static long _filtersVersion = 1; + private static long _routesVersion = 1; + private static (long Version, string[] Tabs) _allTabs; + + public static ChatFilterRule[] Filters => Volatile.Read(ref _filters); + + /// <summary>Bumped on every rule / tab / mention-setting change. The pump re-routes when it moves.</summary> + public static long FiltersVersion => Interlocked.Read(ref _filtersVersion); + + /// <summary>Re-route without saving (a rule was just found too slow). Any thread.</summary> + internal static void BumpFiltersVersion() => Interlocked.Increment(ref _filtersVersion); + + /// <summary>Bumped by the pump once the kept lines carry routes for the current rules; faces rebuild then.</summary> + public static long RoutesVersion => Interlocked.Read(ref _routesVersion); + internal static void BumpRoutes() => Interlocked.Increment(ref _routesVersion); + + /// <summary>Moves when the tabs or the routes change (the Avalonia face rebuilds on it).</summary> + public static long ViewVersion => FiltersVersion + RoutesVersion; + + /// <summary>A rule just made from a chat line: the rule editor scrolls to it and flashes it.</summary> + public static volatile ChatFilterRule? FocusRule; + + public static void EditFilters(Action<List<ChatFilterRule>> edit) + { + lock (EditLock) + { + var list = new List<ChatFilterRule>(_filters); + edit(list); + Volatile.Write(ref _filters, list.ToArray()); + } + FiltersChanged(); + } + + /// <summary>Moves a rule one place up (-1) or down (+1). Order matters (see the header).</summary> + public static void MoveFilter(ChatFilterRule rule, int delta) => EditFilters(list => + { + int i = list.IndexOf(rule), j = i + delta; + if (i < 0 || j < 0 || j >= list.Count) return; + list.RemoveAt(i); + list.Insert(j, rule); + }); + + /// <summary>After a rule's fields changed: re-route lines and save.</summary> + public static void FiltersChanged() + { + Interlocked.Increment(ref _filtersVersion); + SaveSettings(); + } + + /// <summary>Adds <paramref name="rule"/> at the end (its tab too) and asks the editor to show it.</summary> + public static void AddRule(ChatFilterRule rule) + { + rule.Recompile(); + if (rule.Tab.Length > 0) EnsureCustomTab(rule.Tab); + FocusRule = rule; + EditFilters(list => list.Add(rule)); + } + + /// <summary> + /// A pattern for "lines like this": player speech keeps the speaker and the + /// way they spoke ("^Bob tells you, \""); anything else is the whole line + /// with each run of digits made \d+. A long line (an appraisal, a long + /// broadcast) gives only its start, cut at a word: the whole of one could + /// outgrow the rule editor's pattern box, which would cut it mid-escape. + /// </summary> + public static string PatternFor(ChatLine line) + { + const int MaxChars = 140; + string t = line.Text; + if (line.Sender != null) + { + int q = t.IndexOf(", \"", StringComparison.Ordinal); + if (q > 0 && q < 120) return "^" + Escape(t[..(q + 3)]); + } + bool cut = t.Length > MaxChars; + if (cut) + { + int space = t.LastIndexOf(' ', MaxChars - 1, MaxChars / 2); + t = t[..(space > 0 ? space : MaxChars)]; + if (t.Length > 0 && char.IsHighSurrogate(t[^1])) t = t[..^1]; + } + var sb = new StringBuilder("^"); + for (int i = 0; i < t.Length;) + { + int j = i; + if (char.IsDigit(t[i])) + { + while (j < t.Length && char.IsDigit(t[j])) j++; + sb.Append(@"\d+"); + } + else + { + while (j < t.Length && !char.IsDigit(t[j])) j++; + sb.Append(Escape(t[i..j])); + } + i = j; + } + return cut ? sb.ToString() : sb.Append('$').ToString(); + } + + // Regex.Escape escapes spaces too, which is legal but hard to read. + private static string Escape(string s) => Regex.Escape(s).Replace("\\ ", " "); + + /// <summary> + /// Every tab: the channel tabs, then the created ones, then any named by an + /// enabled Move/Copy rule that isn't a created tab (a rule set up in the + /// Avalonia editor, or imported). Cached per filter version. Any thread. + /// </summary> + public static string[] AllTabs() + { + long version = FiltersVersion; + var cached = _allTabs; + if (cached.Tabs != null && cached.Version == version) return cached.Tabs; + var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + var tabs = new List<string>(); + foreach (string t in BaseTabs) if (seen.Add(t)) tabs.Add(t); + foreach (string t in Volatile.Read(ref _customTabs)) if (seen.Add(t)) tabs.Add(t); + foreach (ChatFilterRule rule in Filters) + if (rule.Enabled && rule.Routes && rule.Tab.Length > 0 && seen.Add(rule.Tab)) tabs.Add(rule.Tab); + foreach (string t in RynthCore.Engine.UI.Panels.RynthChatPresets.TargetTabs()) + if (seen.Add(t)) tabs.Add(t); + string[] result = tabs.ToArray(); + _allTabs = (version, result); + return result; + } + + /// <summary>The tabs a Move/Copy rule can send lines to: every tab but All.</summary> + public static string[] TargetTabs() => AllTabs().Where(t => t != "All").ToArray(); + + public static bool IsBaseTab(string tab) => BaseTabs.Contains(tab, StringComparer.OrdinalIgnoreCase); + + /// <summary>The tab to show: the active one, or All when it no longer exists.</summary> + public static string CurrentTab() + { + string active = ActiveChannel; + return AllTabs().Contains(active, StringComparer.OrdinalIgnoreCase) ? active : "All"; + } + + public static void SelectTab(string tab) + { + if (string.Equals(ActiveChannel, tab, StringComparison.Ordinal)) return; + ActiveChannel = tab; + SaveSettings(); + } + + /// <summary>Creates a tab (or finds the existing one) and switches to it.</summary> + public static void AddCustomTab(string name) => AddCustomTab(name, select: true); + + /// <summary>Creates a tab (or finds the existing one); returns its name, or null for a blank name.</summary> + public static string? AddCustomTab(string name, bool select) + { + name = name.Trim(); + if (name.Length == 0) return null; + string? existing = AllTabs().FirstOrDefault(t => string.Equals(t, name, StringComparison.OrdinalIgnoreCase)); + if (existing == null || !IsBaseTab(existing)) EnsureCustomTab(existing ?? name); + if (select) ActiveChannel = existing ?? name; + SaveSettings(); + return existing ?? name; + } + + private static void EnsureCustomTab(string name) + { + if (IsBaseTab(name)) return; + bool added = false; + lock (EditLock) + { + if (!_customTabs.Contains(name, StringComparer.OrdinalIgnoreCase)) + { + Volatile.Write(ref _customTabs, _customTabs.Append(name).ToArray()); + added = true; + } + } + if (added) Interlocked.Increment(ref _filtersVersion); + } + + /// <summary>Renames a created tab and the rules that send lines to it. False when the name is taken or blank.</summary> + public static bool RenameCustomTab(string tab, string newName) + { + newName = newName.Trim(); + if (newName.Length == 0 || IsBaseTab(tab)) return false; + if (!string.Equals(tab, newName, StringComparison.OrdinalIgnoreCase) + && AllTabs().Contains(newName, StringComparer.OrdinalIgnoreCase)) return false; + lock (EditLock) + { + string[] tabs = _customTabs.Select(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase) ? newName : t).ToArray(); + if (!tabs.Contains(newName)) tabs = tabs.Append(newName).ToArray(); + Volatile.Write(ref _customTabs, tabs); + } + foreach (ChatFilterRule rule in Filters) + if (string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) + rule.Tab = newName; + foreach (var preset in RynthCore.Engine.UI.Panels.RynthChatPresets.All) + if (string.Equals(preset.Tab, tab, StringComparison.OrdinalIgnoreCase)) + preset.Tab = newName; + if (string.Equals(ActiveChannel, tab, StringComparison.OrdinalIgnoreCase)) ActiveChannel = newName; + FiltersChanged(); + return true; + } + + /// <summary>Deletes a created tab and disables the rules that fill it, so it + /// doesn't come back through AllTabs and its lines don't vanish.</summary> + public static void DeleteCustomTab(string tab) + { + lock (EditLock) + Volatile.Write(ref _customTabs, + _customTabs.Where(t => !string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)).ToArray()); + foreach (ChatFilterRule rule in Filters) + if (rule.Action is ChatRuleAction.Move or ChatRuleAction.Copy + && string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) + rule.Enabled = false; + foreach (var preset in RynthCore.Engine.UI.Panels.RynthChatPresets.All) + if (string.Equals(preset.Tab, tab, StringComparison.OrdinalIgnoreCase)) + preset.Enabled = false; + FiltersChanged(); + } + + /// <summary>Is the line shown under <paramref name="tab"/> (rules applied, no search)?</summary> + public static bool LineInTab(ChatLine line, string tab) => line.Route.ShowsIn(tab, line.Channel); + + public static bool LineVisible(ChatLine line, string tab, string search) => + LineInTab(line, tab) + && (search.Length == 0 || line.FormattedText.Contains(search, StringComparison.OrdinalIgnoreCase)); + + // ── Mentions ───────────────────────────────────────────────────────── + + /// <summary>Only what other players say mentions you: chat and channel lines, never your own.</summary> + internal static bool MentionEligible(string channel, int chatType) => + (channel == "Chat" || channel == "Channels") && chatType is not (4 or 9 or 11); + + private static string? _pumpName; + private static (long Version, string Name, ChatRouter Router)? _pumpRouter; + private static long _lastBeepTicks; + + [DllImport("user32.dll")] private static extern bool MessageBeep(uint uType); + + /// <summary>Your character's name, "" until known. Pump thread (reads the launch context once).</summary> + internal static string PumpCharacterName() + { + string live = SessionStateRegistry.LastCharacterName; + if (!string.IsNullOrWhiteSpace(live)) return live.Trim(); + return _pumpName ??= TryReadCharacterName() ?? ""; + } + + /// <summary>The router for the current rules and mention settings. Pump thread; rebuilt when they change.</summary> + internal static ChatRouter PumpRouter(string name) + { + long version = FiltersVersion; + var cached = _pumpRouter; + if (cached is { } c && c.Version == version && c.Name == name) return c.Router; + var router = new ChatRouter(Filters, BuildMentionRegex(name), name, countHits: true); + _pumpRouter = (version, name, router); + return router; + } + + /// <summary>A router for the rule editor's test box (UI thread, on an edit).</summary> + public static ChatRouter TestRouter() + { + string name = SessionStateRegistry.LastCharacterName; + if (string.IsNullOrWhiteSpace(name)) name = _pumpName ?? ""; + return new ChatRouter(Filters, BuildMentionRegex(name.Trim()), name, countHits: false); + } + + private static Regex? BuildMentionRegex(string name) + { + if (!MentionHighlight) return null; + var words = new List<string>(); + if (!string.IsNullOrWhiteSpace(name)) words.Add(name.Trim()); + foreach (string w in (MentionWords ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + if (!words.Contains(w, StringComparer.OrdinalIgnoreCase)) words.Add(w); + if (words.Count == 0) return null; + string alt = string.Join("|", words.Select(Regex.Escape)); + return new Regex($@"(?<![\w'])(?:{alt})(?![\w])", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, + TimeSpan.FromMilliseconds(ChatFilterRule.TimeoutMs)); + } + + /// <summary>A new line mentions you. Pump thread.</summary> + internal static void PumpMentionSound() + { + if (!MentionSound) return; + long now = Environment.TickCount64; + if (now - _lastBeepTicks < 3000) return; + _lastBeepTicks = now; + try { MessageBeep(0x40); } catch { } // MB_ICONASTERISK; queued, returns at once + } + + // ── Rule sets (import / export) ────────────────────────────────────── + + /// <summary>The rules and the created tabs as JSON, for the clipboard.</summary> + public static string ExportRules() + { + var dto = new RynthChatRuleSetDto + { + Format = RynthChatRuleSetDto.FormatName, + Tabs = Volatile.Read(ref _customTabs), + Rules = Filters.Select(ToDto).ToArray(), + }; + return JsonSerializer.Serialize(dto, RynthChatJsonContext.Default.RynthChatRuleSetDto); + } + + /// <summary> + /// Adds the rules in <paramref name="json"/> (an export, a whole + /// rynthchat_settings.json, or a bare rule array) after the current ones. + /// Returns a message for the user. + /// </summary> + public static string ImportRules(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return "Clipboard is empty."; + RynthChatFilterDto[]? rules = null; + string[]? tabs = null; + try + { + json = json.Trim(); + if (json.StartsWith('[')) + rules = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatFilterDtoArray); + else + { + var set = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatRuleSetDto); + rules = set?.Rules; + tabs = set?.Tabs; + if (rules == null) + { + var settings = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatSettingsDto); + rules = settings?.Filters; + tabs = settings?.CustomTabs; + } + } + } + catch (JsonException ex) { return "Not a rule set: " + ex.Message; } + if (rules == null || rules.Length == 0) return "No rules found in the clipboard."; + var imported = rules.Select(FromDto).ToList(); + foreach (string t in tabs ?? Array.Empty<string>()) + if (!string.IsNullOrWhiteSpace(t)) EnsureCustomTab(t.Trim()); + foreach (ChatFilterRule r in imported) + if (r.Tab.Length > 0 && r.Action is ChatRuleAction.Move or ChatRuleAction.Copy) EnsureCustomTab(r.Tab); + EditFilters(list => list.AddRange(imported)); + return $"Imported {imported.Count} rule{(imported.Count == 1 ? "" : "s")}."; + } + + private static RynthChatFilterDto ToDto(ChatFilterRule f) => new() + { + Enabled = f.Enabled, + Pattern = f.Pattern, + Tab = f.Tab, + Action = f.Action switch + { + ChatRuleAction.Copy => "copy", + ChatRuleAction.Hide => "hide", + ChatRuleAction.Color => "color", + _ => "move", + }, + When = f.When.Length > 0 ? f.When : null, + ColorMode = f.ColorMode switch { ChatColorMode.Line => "line", ChatColorMode.Match => "match", _ => null }, + // Kept while the rule is set to "No colour" too, so switching colour back on + // after a relaunch finds the colour that was picked. + Color = f.ColorMode != ChatColorMode.None || f.ColorArgb != ChatFilterRule.DefaultColor ? FormatColor(f.ColorArgb) : null, + Mode = f.Mode == ChatMatchMode.Regex ? null : f.Mode.ToString(), + }; + + /// <summary> + /// A rule from its JSON. Rules saved before 2026-09-29 have no "action": an + /// empty tab hid the line and a tab moved it (while leaving it under All, + /// which is why a "Junk" rule seemed to do nothing there; a Move now takes + /// it out of All too). + /// </summary> + private static ChatFilterRule FromDto(RynthChatFilterDto f) + { + string tab = (f.Tab ?? "").Trim(); + var rule = new ChatFilterRule + { + Enabled = f.Enabled, + Pattern = f.Pattern ?? "", + Tab = tab, + Action = (f.Action ?? "").ToLowerInvariant() switch + { + "move" => ChatRuleAction.Move, + "copy" => ChatRuleAction.Copy, + "hide" => ChatRuleAction.Hide, + "color" or "colour" => ChatRuleAction.Color, + _ => tab.Length == 0 ? ChatRuleAction.Hide : ChatRuleAction.Move, + }, + When = f.When ?? "", + ColorMode = (f.ColorMode ?? "").ToLowerInvariant() switch + { + "line" => ChatColorMode.Line, + "match" or "text" => ChatColorMode.Match, + _ => ChatColorMode.None, + }, + ColorArgb = ParseColor(f.Color) ?? ChatFilterRule.DefaultColor, + // Absent (older settings, upstream format): Regex. + Mode = Enum.TryParse(f.Mode, ignoreCase: true, out ChatMatchMode mode) ? mode : ChatMatchMode.Regex, + }; + rule.Recompile(); + return rule; + } + + /// <summary> + /// "#RRGGBB" or "#AARRGGBB" to 0xAARRGGBB (opaque when no alpha is given). + /// An alpha of 00 is taken as opaque: a colour that makes the text invisible + /// is never what a rule wants (hiding is the Hide action). + /// </summary> + public static uint? ParseColor(string? s) + { + if (string.IsNullOrWhiteSpace(s)) return null; + s = s.Trim().TrimStart('#'); + if (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) s = s[2..]; + if (s.Length is not (6 or 8)) return null; + if (!uint.TryParse(s, System.Globalization.NumberStyles.AllowHexSpecifier, null, out uint v)) return null; + if (s.Length == 6 || (v >> 24) == 0) v |= 0xFF000000; + return v; + } + + /// <summary>0xAARRGGBB as "#RRGGBB", or "#AARRGGBB" when it isn't opaque (an imported colour keeps its alpha).</summary> + public static string FormatColor(uint argb) => + (argb >> 24) == 0xFF ? $"#{argb & 0xFFFFFF:X6}" : $"#{argb:X8}"; + + // ── Plugin binding (set by ChatSource on the pump) ─────────────────── + + public static volatile bool PluginBound; + private static IntPtr _sendLinePtr; + public static IntPtr SendLinePtr + { + get => Volatile.Read(ref _sendLinePtr); + set => Volatile.Write(ref _sendLinePtr, value); + } + + // ── Shown ──────────────────────────────────────────────────────────── + + private static int _shown; + + /// <summary> + /// A chat face went on or off screen. Whether RynthChat is shown decides who + /// owns Enter and whether the retail chatbox is hidden (ChatHooks.RynthChatOwnsChat). + /// Counted, since the ImGui face and the popped-out Avalonia face hand over + /// in either order. Any thread. + /// </summary> + public static void SetShown(bool shown) + { + int n = shown ? Interlocked.Increment(ref _shown) : Interlocked.Decrement(ref _shown); + if (n < 0) { Interlocked.Exchange(ref _shown, 0); n = 0; } + ChatHooks.ChatPanelShown = n > 0; + if (n == 0 && Win32Backend.ChatCaptureActive) + { + // Abandon a half-typed line rather than keep swallowing keys for a closed panel. + Win32Backend.ChatCaptureActive = false; + SetInput("", 0, null); + } + } + + // ── Input line (AC's main thread: the WndProc hook) ────────────────── + + private sealed record InputState(string Text, int Cursor, string? Hint); + private static InputState _input = new("", 0, null); + private static readonly List<string> History = new(); + private static int _historyIndex = -1; + private static long _inputVersion; + private static bool _inputInstalled; + + public static string InputText => Volatile.Read(ref _input).Text; + public static int InputCursor => Volatile.Read(ref _input).Cursor; + /// <summary>Shown in the empty input box instead of the usual hint (e.g. "select an NPC first").</summary> + public static string? InputHint => Volatile.Read(ref _input).Hint; + public static long InputVersion => Interlocked.Read(ref _inputVersion); + + /// <summary>Raised on AC's main thread after the input line changes.</summary> + public static event Action? InputChanged; + + private static void SetInput(string text, int cursor, string? hint) + { + Volatile.Write(ref _input, new InputState(text, Math.Clamp(cursor, 0, text.Length), hint)); + Interlocked.Increment(ref _inputVersion); + try { InputChanged?.Invoke(); } + catch (Exception ex) { RynthLog.UI($"ChatModel: InputChanged handler threw {ex.GetType().Name}: {ex.Message}"); } + } + + /// <summary>Clicking the input box starts typing, like Enter. AC's main thread.</summary> + public static void BeginTyping() + { + if (Win32Backend.ChatCaptureActive || !ChatHooks.RynthChatOwnsChat) return; + Win32Backend.ChatCaptureActive = true; + OnActivated(); + } + + /// <summary>Hooks the chat keys up to the input line. Once, at init.</summary> + public static void InstallInput() + { + if (_inputInstalled) return; + _inputInstalled = true; + Win32Backend.OnChatCaptureActivated = OnActivated; + Win32Backend.OnChatTellSelected = () => BeginTellToSelected(); + Win32Backend.OnChatChar = c => + { + // Ctrl+Backspace arrives as WM_CHAR 0x7F (DEL): it used to go into the line + // as an invisible character and be sent with it. + if (c == (char)0x7F) return; + InputState s = _input; + _historyIndex = -1; + SetInput(s.Text[..s.Cursor] + c + s.Text[s.Cursor..], s.Cursor + 1, null); + }; + Win32Backend.OnChatBackspace = () => + { + InputState s = _input; + if (s.Cursor > 0) SetInput(s.Text[..(s.Cursor - 1)] + s.Text[s.Cursor..], s.Cursor - 1, null); + }; + Win32Backend.OnChatDelete = () => + { + InputState s = _input; + if (s.Cursor < s.Text.Length) SetInput(s.Text[..s.Cursor] + s.Text[(s.Cursor + 1)..], s.Cursor, null); + }; + Win32Backend.OnChatLeft = () => { InputState s = _input; SetInput(s.Text, s.Cursor - 1, null); }; + Win32Backend.OnChatRight = () => { InputState s = _input; SetInput(s.Text, s.Cursor + 1, null); }; + Win32Backend.OnChatHome = () => SetInput(_input.Text, 0, null); + Win32Backend.OnChatEnd = () => SetInput(_input.Text, _input.Text.Length, null); + Win32Backend.OnChatUp = () => + { + if (History.Count == 0) return; + _historyIndex = _historyIndex < 0 ? History.Count - 1 : Math.Max(0, _historyIndex - 1); + string text = History[_historyIndex]; + SetInput(text, text.Length, null); + }; + Win32Backend.OnChatDown = () => + { + if (_historyIndex < 0) return; + string text; + if (_historyIndex < History.Count - 1) text = History[++_historyIndex]; + else { _historyIndex = -1; text = ""; } + SetInput(text, text.Length, null); + }; + Win32Backend.OnChatSend = OnSend; + Win32Backend.OnChatCancel = () => + { + _historyIndex = -1; + SetInput("", 0, null); + }; + } + + private static void OnActivated() + { + _historyIndex = -1; + SetInput("", 0, null); + } + + /// <summary> + /// Starts "/tell <selected name>, " and keeps typing. AC's main thread + /// (the Tell button via WM_RYNTHCORE_TELL, or "/tell" alone in OnSend), where + /// the selection and its name read live. + /// </summary> + private static bool BeginTellToSelected() + { + if (!TryGetSelectedTellName(out string name)) + { + SetInput("", 0, "Select an NPC or player in the game first, then Tell."); + return false; + } + string text = $"/tell {name}, "; + _historyIndex = -1; + Win32Backend.ChatCaptureActive = true; // keys now go to this line + SetInput(text, text.Length, null); + return true; + } + + // Win32Backend has already cleared ChatCaptureActive. RynthChatSendLine runs + // here, on AC's main thread, so its CallWindowProcA does too. + private static unsafe void OnSend() + { + string text = _input.Text.Trim(); + // "/tell" or "/t" alone addresses the selected NPC or player instead of + // being sent (AC would only answer with the usage line). + if (text.Equals("/tell", StringComparison.OrdinalIgnoreCase) || text.Equals("/t", StringComparison.OrdinalIgnoreCase)) + { + if (!BeginTellToSelected()) _historyIndex = -1; + return; + } + _historyIndex = -1; + if (text.Length > 0 && (History.Count == 0 || History[^1] != text)) + { + History.Add(text); + if (History.Count > 100) History.RemoveAt(0); + } + SetInput("", 0, null); + IntPtr send = SendLinePtr; + if (text.Length == 0 || send == IntPtr.Zero) return; + IntPtr ptr = Marshal.StringToHGlobalAnsi(text); + try { ((delegate* unmanaged[Cdecl]<IntPtr, void>)send)(ptr); } + finally { Marshal.FreeHGlobal(ptr); } + } + + /// <summary>The creature selected in the game (an NPC or another player), for /tell. + /// AC's main thread only. Never yourself, never an item.</summary> + private static bool TryGetSelectedTellName(out string name) + { + name = ""; + uint id = SelectedTargetHooks.ReadCurrentSelectedId(); + if (id == 0 || id == ClientHelperHooks.GetPlayerId()) return false; + const uint ItemTypeCreature = 0x00000010; + if (ClientObjectHooks.TryGetItemType(id, out uint flags) && (flags & ItemTypeCreature) == 0) return false; + return ClientObjectHooks.TryGetObjectName(id, out name) && !string.IsNullOrWhiteSpace(name); + } + + // ── Clipboard ──────────────────────────────────────────────────────── + + // Written directly as CF_UNICODETEXT: Avalonia's clipboard service is + // unreliable inside acclient (no proper TopLevel owner). + [DllImport("user32.dll")] private static extern bool OpenClipboard(IntPtr hWndNewOwner); + [DllImport("user32.dll")] private static extern bool CloseClipboard(); + [DllImport("user32.dll")] private static extern bool EmptyClipboard(); + [DllImport("user32.dll")] private static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem); + [DllImport("kernel32.dll")] private static extern IntPtr GlobalAlloc(uint uFlags, UIntPtr dwBytes); + [DllImport("kernel32.dll")] private static extern IntPtr GlobalLock(IntPtr hMem); + [DllImport("kernel32.dll")] private static extern bool GlobalUnlock(IntPtr hMem); + [DllImport("kernel32.dll")] private static extern IntPtr GlobalFree(IntPtr hMem); + + public static unsafe bool SetClipboardText(string text) + { + const uint CF_UNICODETEXT = 13; + const uint GMEM_MOVEABLE = 0x0002; + // The clipboard is shared: another app may hold it briefly. + for (int attempt = 0; attempt < 5; attempt++) + { + if (OpenClipboard(IntPtr.Zero)) + { + try + { + EmptyClipboard(); + int bytes = (text.Length + 1) * 2; + IntPtr hMem = GlobalAlloc(GMEM_MOVEABLE, (UIntPtr)bytes); + if (hMem == IntPtr.Zero) return false; + IntPtr dst = GlobalLock(hMem); + if (dst == IntPtr.Zero) { GlobalFree(hMem); return false; } + fixed (char* src = text) + Buffer.MemoryCopy(src, (void*)dst, bytes, text.Length * 2); + ((char*)dst)[text.Length] = '\0'; + GlobalUnlock(hMem); + if (SetClipboardData(CF_UNICODETEXT, hMem) == IntPtr.Zero) + { + GlobalFree(hMem); // ownership not taken + return false; + } + return true; // the system owns hMem now + } + finally { CloseClipboard(); } + } + Thread.Sleep(10); + } + return false; + } + + [DllImport("user32.dll")] private static extern IntPtr GetClipboardData(uint uFormat); + [DllImport("user32.dll")] private static extern bool IsClipboardFormatAvailable(uint format); + [DllImport("kernel32.dll")] private static extern UIntPtr GlobalSize(IntPtr hMem); + + /// <summary>The clipboard's text, or null (empty, not text, or busy). Rule import.</summary> + public static unsafe string? GetClipboardText() + { + const uint CF_UNICODETEXT = 13; + if (!IsClipboardFormatAvailable(CF_UNICODETEXT) || !OpenClipboard(IntPtr.Zero)) return null; + try + { + IntPtr h = GetClipboardData(CF_UNICODETEXT); + if (h == IntPtr.Zero) return null; + IntPtr p = GlobalLock(h); + if (p == IntPtr.Zero) return null; + try + { + int maxChars = (int)Math.Min((ulong)GlobalSize(h) / 2, 1_000_000); + int n = 0; + char* c = (char*)p; + while (n < maxChars && c[n] != '\0') n++; + return new string(c, 0, n); + } + finally { GlobalUnlock(h); } + } + finally { CloseClipboard(); } + } + + /// <summary>"Copied N lines", or the busy message.</summary> + public static string CopyLines(IReadOnlyList<string> lines) + { + bool ok = SetClipboardText(string.Join("\r\n", lines)); + return ok ? $"Copied {lines.Count} line{(lines.Count == 1 ? "" : "s")}" : "Clipboard busy — try again"; + } + + // ── Chat log (pump thread, ChatSource) ─────────────────────────────── + + private static string? _logCharacterName; + private static StreamWriter? _logWriter; + + /// <summary>Writes <paramref name="lines"/> when logging is on; closes the file when it's off.</summary> + internal static void PumpLog(List<ChatLine>? lines) + { + if (!LogEnabled) + { + if (_logWriter != null) { try { _logWriter.Close(); } catch { } _logWriter = null; } + return; + } + if (lines == null || lines.Count == 0) return; + try + { + // The character playing now: after logging in as another character in the + // same client, the log used to carry on in the first one's file. + string name = PumpCharacterName(); + if (name.Length == 0) return; + if (_logWriter != null && !string.Equals(name, _logCharacterName, StringComparison.Ordinal)) + { + try { _logWriter.Close(); } catch { } + _logWriter = null; + } + if (_logWriter == null) + { + _logCharacterName = name; + string file = string.Join("_", name.Split(Path.GetInvalidFileNameChars())); + string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "ChatLogs"); + Directory.CreateDirectory(dir); + // Shared for writing: an engine generation left behind by a hot reload + // (it can't always close the file) must not lock the next one out. + var stream = new FileStream(Path.Combine(dir, $"{file}.log"), FileMode.Append, FileAccess.Write, + FileShare.ReadWrite | FileShare.Delete); + _logWriter = new StreamWriter(stream, System.Text.Encoding.UTF8); + } + foreach (ChatLine line in lines) _logWriter.WriteLine(line.FormattedText); + _logWriter.Flush(); + } + catch (Exception ex) + { + RynthLog.UI($"ChatModel: chat log write failed: {ex.Message}"); + try { _logWriter?.Close(); } catch { } + _logWriter = null; + } + } + + /// <summary> + /// Closes the chat log. Engine shutdown, after the tick pump (PumpLog's + /// thread) has stopped: the file stayed open in the old generation after a + /// hot reload, and the new one couldn't open it (every write failed). + /// </summary> + internal static void CloseLog() + { + StreamWriter? w = _logWriter; + _logWriter = null; + try { w?.Close(); } catch { } + } + + private static string? TryReadCharacterName() + { + try + { + string root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore"); + string perProcPath = Path.Combine(root, "launch_contexts", $"launch_context_{Environment.ProcessId}.json"); + string path = File.Exists(perProcPath) ? perProcPath : Path.Combine(root, "launch_context.json"); + if (!File.Exists(path)) return null; + using var doc = JsonDocument.Parse(File.ReadAllBytes(path)); + if (doc.RootElement.TryGetProperty("TargetCharacter", out JsonElement tc)) + { + string? name = tc.GetString(); + if (!string.IsNullOrWhiteSpace(name)) return name.Trim(); + } + return null; + } + catch { return null; } + } + + // ── Settings persistence ───────────────────────────────────────────── + // + // %AppData%\RynthCore\rynthchat_settings.json. Version 2 (2026-09-29) adds + // "version", showTimestamps, the mention settings, and per rule "action", + // "when", "colorMode" and "color". A version-1 file loads as before (see + // FromDto for what its rules become); the first load copies it to + // rynthchat_settings.v1.bak, and the next save writes version 2. + + public const int SettingsVersion = 2; + private static readonly object SaveLock = new(); + private static int _settingsLoaded; + + private static string SettingsPath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthchat_settings.json"); + + /// <summary>Loads the settings (incl. "Hide retail chat") once. Safe before the overlay starts.</summary> + public static void EnsureSettingsLoaded() + { + if (Interlocked.Exchange(ref _settingsLoaded, 1) != 0) return; + LoadSettings(); + } + + private static void LoadSettings() + { + try + { + string path = SettingsPath; + if (!File.Exists(path)) return; + var dto = JsonSerializer.Deserialize(File.ReadAllText(path), RynthChatJsonContext.Default.RynthChatSettingsDto); + if (dto == null) return; + + if (dto.Version < SettingsVersion) + { + try + { + string backup = Path.ChangeExtension(path, $".v{Math.Max(1, dto.Version)}.bak"); + if (!File.Exists(backup)) File.Copy(path, backup); + } + catch (Exception ex) { RynthLog.UI($"ChatModel: settings backup failed: {ex.Message}"); } + RynthLog.UI($"ChatModel: migrating rynthchat_settings.json v{Math.Max(1, dto.Version)} -> v{SettingsVersion} ({dto.Filters?.Length ?? 0} rules)."); + } + + FontSize = (float)Math.Clamp(dto.FontSize <= 0 ? 10 : dto.FontSize, 8, 18); + BackgroundAlpha = Math.Clamp(dto.BackgroundAlpha, 0, 255); + AutoScroll = dto.AutoScroll; + ChatHooks.SuppressOriginalChat = dto.SuppressChat; + LogEnabled = dto.LogEnabled; + CtrlGatedClickThrough = dto.CtrlGatedClickThrough; + AvaloniaOverlay.ChatCtrlGatedClickThrough = dto.CtrlGatedClickThrough; + ShowTimestamps = dto.ShowTimestamps; + MentionHighlight = dto.MentionHighlight; + MentionSound = dto.MentionSound; + MentionWords = dto.MentionWords ?? ""; + + var tabs = new List<string>(); + foreach (string t in dto.CustomTabs ?? Array.Empty<string>()) + if (!string.IsNullOrWhiteSpace(t) && !IsBaseTab(t.Trim()) + && !tabs.Contains(t.Trim(), StringComparer.OrdinalIgnoreCase)) tabs.Add(t.Trim()); + var rules = new List<ChatFilterRule>(); + foreach (RynthChatFilterDto f in dto.Filters ?? Array.Empty<RynthChatFilterDto>()) + { + ChatFilterRule rule = FromDto(f); + rules.Add(rule); + // A tab typed into a rule used to exist only while the rule was on: + // make it a real tab, so turning the rule off doesn't drop the tab. + if (rule.Action is ChatRuleAction.Move or ChatRuleAction.Copy && rule.Tab.Length > 0 + && !IsBaseTab(rule.Tab) && !tabs.Contains(rule.Tab, StringComparer.OrdinalIgnoreCase)) + tabs.Add(rule.Tab); + } + foreach (RynthChatPresetDto p in dto.Presets ?? Array.Empty<RynthChatPresetDto>()) + { + var preset = p.Id == null ? null : RynthCore.Engine.UI.Panels.RynthChatPresets.Get(p.Id); + if (preset == null) continue; // a preset a later build removed + preset.Enabled = p.Enabled; + preset.Tab = (p.Tab ?? "").Trim(); + if (preset.Tab.Length > 0 && !IsBaseTab(preset.Tab) + && !tabs.Contains(preset.Tab, StringComparer.OrdinalIgnoreCase)) + tabs.Add(preset.Tab); + } + _customTabs = tabs.ToArray(); + _filters = rules.ToArray(); + Interlocked.Increment(ref _filtersVersion); + + if (!string.IsNullOrEmpty(dto.ActiveChannel) && AllTabs().Contains(dto.ActiveChannel, StringComparer.OrdinalIgnoreCase)) + ActiveChannel = dto.ActiveChannel; + } + catch (Exception ex) + { + RynthLog.UI($"ChatModel: settings load failed: {ex.Message}"); + KeepUnreadable(); + } + } + + /// <summary> + /// The settings file didn't load: keep a copy before the next save writes the + /// defaults over it, so the rules and tabs in it can be recovered (Import + /// takes a whole settings file). + /// </summary> + private static void KeepUnreadable() + { + try + { + string path = SettingsPath; + if (!File.Exists(path)) return; + string copy = Path.ChangeExtension(path, $".unreadable-{DateTime.Now:yyyyMMdd-HHmmss}.json"); + File.Copy(path, copy, overwrite: false); + RynthLog.UI($"ChatModel: kept the unreadable settings as {Path.GetFileName(copy)}."); + } + catch (Exception ex) { RynthLog.UI($"ChatModel: couldn't keep the unreadable settings: {ex.Message}"); } + } + + /// <summary>Saves in the background (a rule edit saves on every keystroke). Any thread.</summary> + public static void SaveSettings() + { + var dto = new RynthChatSettingsDto + { + Version = SettingsVersion, + FontSize = FontSize, + BackgroundAlpha = BackgroundAlpha, + AutoScroll = AutoScroll, + SuppressChat = ChatHooks.SuppressOriginalChat, + LogEnabled = LogEnabled, + CtrlGatedClickThrough = CtrlGatedClickThrough, + ActiveChannel = ActiveChannel, + ShowTimestamps = ShowTimestamps, + MentionHighlight = MentionHighlight, + MentionSound = MentionSound, + MentionWords = MentionWords, + CustomTabs = Volatile.Read(ref _customTabs), + Filters = Filters.Select(ToDto).ToArray(), + // Only presets the user touched: new presets in later builds start off. + Presets = RynthCore.Engine.UI.Panels.RynthChatPresets.All + .Where(p => p.Enabled || p.Tab.Length > 0) + .Select(p => new RynthChatPresetDto { Id = p.Id, Enabled = p.Enabled, Tab = p.Tab.Length > 0 ? p.Tab : null }) + .ToArray(), + }; + UiBackgroundWriter.Enqueue("persist chat settings", () => + { + lock (SaveLock) + { + // Written beside it and swapped in: the client dying mid-write (a rule + // edit saves on every keystroke) used to leave a cut-off file, which + // loaded as nothing and was then saved over with the defaults. + string path = SettingsPath; + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + string tmp = $"{path}.{Environment.ProcessId}.tmp"; // every client shares the file + try + { + File.WriteAllText(tmp, JsonSerializer.Serialize(dto, RynthChatJsonContext.Default.RynthChatSettingsDto)); + File.Move(tmp, path, overwrite: true); + } + catch + { + try { File.Delete(tmp); } catch { } + throw; // UiBackgroundWriter logs it + } + } + }); + } +} + +// JsonSerializerContext must be at namespace scope (not nested) for source generation. +internal sealed class RynthChatLineDto +{ + [JsonPropertyName("seq")] public ulong Seq { get; set; } + [JsonPropertyName("ts")] public string Ts { get; set; } = ""; + [JsonPropertyName("chan")] public string Chan { get; set; } = ""; + /// <summary>ChatMessageType; RynthChat before 0.2.0 doesn't send it.</summary> + [JsonPropertyName("type")] public int Type { get; set; } = -1; + [JsonPropertyName("sender")] public string? Sender { get; set; } + [JsonPropertyName("text")] public string Text { get; set; } = ""; +} + +// Property names match the legacy hand-written JSON so existing settings load. +internal sealed class RynthChatFilterDto +{ + [JsonPropertyName("pattern")] public string? Pattern { get; set; } + [JsonPropertyName("tab")] public string? Tab { get; set; } + [JsonPropertyName("enabled")] public bool Enabled { get; set; } = true; + // Version 2: + /// <summary>"move" | "copy" | "hide" | "color"; absent in version 1 (see ChatModel.FromDto).</summary> + [JsonPropertyName("action")] public string? Action { get; set; } + /// <summary>"" / absent: any line; "chan:Combat"; "type:3".</summary> + [JsonPropertyName("when")] public string? When { get; set; } + /// <summary>"line" | "match"; absent: no colour.</summary> + [JsonPropertyName("colorMode")] public string? ColorMode { get; set; } + /// <summary>"#RRGGBB".</summary> + [JsonPropertyName("color")] public string? Color { get; set; } + /// <summary>ChatMatchMode name; absent = Regex.</summary> + [JsonPropertyName("mode")] public string? Mode { get; set; } +} + +/// <summary>A standard filter's user state (RynthChatPresets), by preset id.</summary> +internal sealed class RynthChatPresetDto +{ + [JsonPropertyName("id")] public string? Id { get; set; } + [JsonPropertyName("enabled")] public bool Enabled { get; set; } + [JsonPropertyName("tab")] public string? Tab { get; set; } +} + +internal sealed class RynthChatSettingsDto +{ + /// <summary>Absent (0) in version-1 files.</summary> + [JsonPropertyName("version")] public int Version { get; set; } + [JsonPropertyName("fontSize")] public double FontSize { get; set; } = 10; + [JsonPropertyName("backgroundAlpha")] public int BackgroundAlpha { get; set; } = 0xF2; + [JsonPropertyName("autoScroll")] public bool AutoScroll { get; set; } = true; + [JsonPropertyName("suppressChat")] public bool SuppressChat { get; set; } + [JsonPropertyName("logEnabled")] public bool LogEnabled { get; set; } + // Chat's own Ctrl-gated click-through, like RadarPanel's (2026-09-02). + [JsonPropertyName("ctrlGatedClickThrough")] public bool CtrlGatedClickThrough { get; set; } + [JsonPropertyName("activeChannel")] public string? ActiveChannel { get; set; } + [JsonPropertyName("showTimestamps")] public bool ShowTimestamps { get; set; } = true; + [JsonPropertyName("mentionHighlight")] public bool MentionHighlight { get; set; } = true; + [JsonPropertyName("mentionSound")] public bool MentionSound { get; set; } + [JsonPropertyName("mentionWords")] public string? MentionWords { get; set; } + [JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; } + [JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; } + [JsonPropertyName("presets")] public RynthChatPresetDto[]? Presets { get; set; } +} + +/// <summary>Export / import on the clipboard (the rule editor's Export and Import).</summary> +internal sealed class RynthChatRuleSetDto +{ + public const string FormatName = "rynthchat-rules/2"; + [JsonPropertyName("format")] public string? Format { get; set; } + [JsonPropertyName("tabs")] public string[]? Tabs { get; set; } + [JsonPropertyName("rules")] public RynthChatFilterDto[]? Rules { get; set; } +} + +[JsonSerializable(typeof(RynthChatLineDto[]))] +[JsonSerializable(typeof(RynthChatLineDto))] +[JsonSerializable(typeof(RynthChatSettingsDto))] +[JsonSerializable(typeof(RynthChatRuleSetDto))] +[JsonSerializable(typeof(RynthChatFilterDto[]))] +[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = false, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +internal partial class RynthChatJsonContext : JsonSerializerContext { } diff --git a/src/RynthCore.Engine/UI/Data/DamageData.cs b/src/RynthCore.Engine/UI/Data/DamageData.cs new file mode 100644 index 0000000..c41e301 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/DamageData.cs @@ -0,0 +1,806 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/DamageData.cs +// RynthAi's learned per-monster combat data (the Damage panel) and the +// name-keyed monster rules (Monsters panel, Damage drawer), for both faces. +// +// Every getter here frees its previous return buffer on the next call, so +// the hub is the only caller: DamageSource (damage rows, selectable weapons, +// pet choices) and MonsterRulesSource (rules). Before this, the Avalonia +// Monsters and Damage panels both polled RynthPluginGetMonstersJson from the +// UI thread. Setters run on the pump too (DamageCommands), so they no longer +// race the plugin tick. +// +// Aelrynth difficulty tiers (2026-10-03): RynthAi keeps a monster's HP, kills, +// casts to kill, seconds per kill and hit rate per tier of Aelrynth's awakened +// worlds and scaled copies (same monsters, +5% a tier). The rows describe the +// tier RynthAi is showing; RynthPluginGetAwakenedTierJson says which, and the +// panel's picker sets it (RynthPluginSetDamageViewTier). Shown only on +// Aelrynth (ServerInfo.IsAelrynth) and once RynthAi has seen the server's tier; +// an older RynthAi without the export shows nothing of it. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Text.Json; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Panels; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>One row of RynthPluginGetMonsterDamageJson (a monster, per weapon/element/tier key).</summary> +internal sealed class DamageRow +{ + public uint Wcid; public string Name = ""; public uint Wid; public string Weapon = ""; + public string Elem = ""; public int Tier; public int Hp; public bool HpManual; + /// <summary>Hp is an estimate: real Dereth's +5% per Aelrynth difficulty tier (that tier not appraised yet).</summary> + public bool HpEst; + public double Crit; public int CritN; public double NonCrit; public int NonCritN; + public double Casts; public int Kills; public string Key = ""; + /// <summary>Per-monster (wcid) weapon state, the same on every row of a wcid.</summary> + public uint AssignedWid; public string AssignedWeapon = ""; + public uint BestWid; public string BestWeapon = ""; + public uint AssignedOff; public string AssignedOffName = ""; + public string Pet = ""; public string PetLabel = "Auto"; + /// <summary>What the monster takes most damage from ("Bludgeon 1.0, Pierce 0.86") and where that came from.</summary> + public string Weak = ""; public string WeakSrc = ""; + /// <summary>Seconds per kill and hit rate (0-1) over every weapon; -1 = not learned yet.</summary> + public double SecKill = -1, HitRate = -1; + /// <summary>The monster being fought (or selected) right now.</summary> + public bool Targeted; + /// <summary>One of these is on the player's landblock.</summary> + public bool Nearby; + public List<DamageTierStat> Tiers = new(); + /// <summary>The synthetic top "Default" line (wcid 0).</summary> + public bool IsDefault; +} + +internal sealed class DamageTierStat +{ + public int Tier; public string Elem = ""; public string Weapon = ""; + public double Crit; public int CritN; public double NonCrit; public int NonCritN; + public double Casts; public int Kills; +} + +internal sealed class DamageView +{ + public List<DamageRow> Rows = new(); + /// <summary>Weapons with learned rows (the filter list), in first-seen order.</summary> + public List<(uint Id, string Name)> LearnedWeapons = new(); + /// <summary>Configured weapons (ItemRules) plus learned ones, by name: the per-row pickers.</summary> + public List<(uint Id, string Name)> WeaponChoices = new(); + /// <summary>("" = Auto, "E:<element>", "I:<essence id>", label).</summary> + public List<(string Key, string Name)> PetChoices = new(); + public bool Bound; + /// <summary>The Aelrynth difficulty tier the rows describe; Show false = say nothing of tiers.</summary> + public AwakenedTierView Tier = AwakenedTierView.Hidden; +} + +/// <summary>RynthPluginGetAwakenedTierJson, gated on ServerInfo.IsAelrynth.</summary> +internal sealed class AwakenedTierView +{ + public static readonly AwakenedTierView Hidden = new(); + + public bool Show; + /// <summary>The tier where the player stands; the tier the rows describe; whether that follows Current.</summary> + public int Current, View; + public bool Following = true; + public double Percent = 5; + /// <summary>Tiers with something learned, plus 0 and the current one, ascending.</summary> + public List<int> Tiers = new(); + + public static AwakenedTierView Parse(string? json) + { + if (string.IsNullOrEmpty(json)) return Hidden; + try + { + using var doc = JsonDocument.Parse(json); + JsonElement r = doc.RootElement; + if (!r.TryGetProperty("show", out var sh) || sh.ValueKind != JsonValueKind.True) return Hidden; + var t = new AwakenedTierView { Show = true }; + if (r.TryGetProperty("current", out var c)) t.Current = c.GetInt32(); + if (r.TryGetProperty("view", out var v)) t.View = v.GetInt32(); + if (r.TryGetProperty("following", out var f)) t.Following = f.ValueKind == JsonValueKind.True; + if (r.TryGetProperty("percent", out var pc)) t.Percent = pc.GetDouble(); + if (r.TryGetProperty("tiers", out var arr) && arr.ValueKind == JsonValueKind.Array) + foreach (JsonElement e in arr.EnumerateArray()) t.Tiers.Add(e.GetInt32()); + return t; + } + catch { return Hidden; } + } +} + +/// <summary>The monster rules (RynthPluginGetMonstersJson). Parsed is shared: copy before changing (ParseCopy).</summary> +internal sealed class MonsterRulesSnapshot +{ + public MonsterRulesSnapshot(string json, MonstersPanel.Payload parsed) + { + Json = json; + Parsed = parsed; + foreach (MonstersPanel.Rule r in parsed.Rules) + if (!r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)) + _custom.Add(r.Name); + } + + public string Json { get; } + public MonstersPanel.Payload Parsed { get; } + private readonly HashSet<string> _custom = new(StringComparer.OrdinalIgnoreCase); + + /// <summary>An exact-name rule exists for <paramref name="name"/> (it doesn't inherit Default).</summary> + public bool HasCustomRule(string name) => _custom.Contains(name); + + public MonstersPanel.Rule? FindRule(string name) + { + foreach (MonstersPanel.Rule r in Parsed.Rules) + if (!r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase) && r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) + return r; + return null; + } + + public MonstersPanel.Rule DefaultRule() + { + foreach (MonstersPanel.Rule r in Parsed.Rules) + if (r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)) + return r; + return new MonstersPanel.Rule { Name = "Default", UseBolt = true }; + } + + /// <summary>A private, editable copy of the payload.</summary> + public MonstersPanel.Payload ParseCopy() => + JsonSerializer.Deserialize(Json, MonstersPanelJsonContext.Default.Payload) ?? new MonstersPanel.Payload(); +} + +/// <summary>Damage rows + weapons (500 ms) and pet choices (2 s) while a Damage face is open.</summary> +internal sealed unsafe class DamageSource : UiSource<DamageView> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _getRows, _getWeapons, _getPets, _getTier; + private string? _rowsJson, _weaponsJson, _petsJson, _tierJson; + private AwakenedTierView _tier = AwakenedTierView.Hidden; + private bool _tierAelrynth; + private List<DamageRow> _rows = new(); + private List<(uint Id, string Name)> _items = new(); + private List<(string Key, string Name)> _pets = new(); + private long _nextPetTicks; + + public DamageSource() : base("Damage", periodMs: 500) { } + + protected internal override void Poll() + { + if (_getRows == null) + { + _getRows = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetMonsterDamageJson"); + _getWeapons = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetCombatWeaponsJson"); + _getPets = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetPetChoicesJson"); + _getTier = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetAwakenedTierJson"); + if (_getRows == null) + { + if (Current == null) Publish(new DamageView { Bound = false }); + return; + } + } + + bool changed = Current == null || !Current.Value.Bound; + string? json = Read(_getRows); + if (json != null && json != _rowsJson) { _rowsJson = json; _rows = ParseRows(json); changed = true; } + + if (_getWeapons != null && (json = Read(_getWeapons)) != null && json != _weaponsJson) + { + _weaponsJson = json; + _items = ParseItems(json); + changed = true; + } + + // The difficulty tier, only on Aelrynth: anywhere else the panel says nothing of tiers. + bool aelrynth = ServerInfo.IsAelrynth; + string? tierJson = aelrynth && _getTier != null ? Read(_getTier) : null; + if (aelrynth != _tierAelrynth || tierJson != _tierJson) + { + _tierAelrynth = aelrynth; + _tierJson = tierJson; + _tier = aelrynth ? AwakenedTierView.Parse(tierJson) : AwakenedTierView.Hidden; + changed = true; + } + + long now = Stopwatch.GetTimestamp(); + if (_getPets != null && now >= _nextPetTicks) + { + _nextPetTicks = now + Stopwatch.Frequency * 2; + if ((json = Read(_getPets)) != null && json != _petsJson) + { + _petsJson = json; + _pets = ParsePets(json); + changed = true; + } + } + + if (changed) Publish(BuildView()); + } + + /// <summary>Re-read the pet choices on the next poll too (after a pet change).</summary> + public void RefreshPetsSoon() => _nextPetTicks = 0; + + protected internal override void Reset() + { + _getRows = _getWeapons = _getPets = _getTier = null; + _rowsJson = _weaponsJson = _petsJson = _tierJson = null; + _tier = AwakenedTierView.Hidden; + _tierAelrynth = false; + ClearSnapshot(); + } + + private static string? Read(delegate* unmanaged[Cdecl]<IntPtr> fn) + { + IntPtr p = fn(); + return p == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(p); + } + + private DamageView BuildView() + { + var view = new DamageView { Rows = _rows, Bound = true, Tier = _tier }; + var seen = new HashSet<uint>(); + foreach (DamageRow r in _rows) + if (r.Wid != 0 && seen.Add(r.Wid)) view.LearnedWeapons.Add((r.Wid, r.Weapon)); + + var choiceSeen = new HashSet<uint>(); + foreach (var it in _items) if (it.Id != 0 && choiceSeen.Add(it.Id)) view.WeaponChoices.Add(it); + foreach (var w in view.LearnedWeapons) if (choiceSeen.Add(w.Id)) view.WeaponChoices.Add(w); + view.WeaponChoices.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); + + view.PetChoices = _pets.Count > 0 ? _pets : new List<(string, string)> { ("", "Auto (update RynthAi for pet choices)") }; + return view; + } + + private static List<DamageRow> ParseRows(string json) + { + var list = new List<DamageRow>(); + try + { + using var doc = JsonDocument.Parse(json); + foreach (JsonElement e in doc.RootElement.EnumerateArray()) + { + var row = new DamageRow + { + Wcid = (uint)e.GetProperty("wcid").GetInt64(), + Name = e.GetProperty("name").GetString() ?? "", + Wid = (uint)e.GetProperty("wid").GetInt64(), + Weapon = e.GetProperty("weapon").GetString() ?? "", + Elem = e.GetProperty("elem").GetString() ?? "", + Tier = e.GetProperty("tier").GetInt32(), + Hp = e.GetProperty("hp").GetInt32(), + HpManual = e.GetProperty("hpManual").GetBoolean(), + Crit = e.GetProperty("crit").GetDouble(), + CritN = e.GetProperty("critN").GetInt32(), + NonCrit = e.GetProperty("noncrit").GetDouble(), + NonCritN = e.GetProperty("noncritN").GetInt32(), + Casts = e.GetProperty("casts").GetDouble(), + Kills = e.GetProperty("kills").GetInt32(), + Key = e.GetProperty("key").GetString() ?? "", + }; + // Optional fields: an older plugin omits them. + if (e.TryGetProperty("assignedWid", out var aw)) row.AssignedWid = (uint)aw.GetInt64(); + if (e.TryGetProperty("assignedWeapon", out var awn)) row.AssignedWeapon = awn.GetString() ?? ""; + if (e.TryGetProperty("bestWid", out var bw)) row.BestWid = (uint)bw.GetInt64(); + if (e.TryGetProperty("bestWeapon", out var bwn)) row.BestWeapon = bwn.GetString() ?? ""; + if (e.TryGetProperty("assignedOff", out var ao)) row.AssignedOff = (uint)ao.GetInt64(); + if (e.TryGetProperty("assignedOffName", out var aon)) row.AssignedOffName = aon.GetString() ?? ""; + if (e.TryGetProperty("isDefault", out var idf)) row.IsDefault = idf.GetBoolean(); + if (e.TryGetProperty("hpEst", out var he)) row.HpEst = he.ValueKind == JsonValueKind.True; + if (e.TryGetProperty("pet", out var pc)) row.Pet = pc.GetString() ?? ""; + if (e.TryGetProperty("petLabel", out var pl)) row.PetLabel = pl.GetString() ?? "Auto"; + if (e.TryGetProperty("weak", out var wk)) row.Weak = wk.GetString() ?? ""; + if (e.TryGetProperty("weakSrc", out var ws)) row.WeakSrc = ws.GetString() ?? ""; + if (e.TryGetProperty("secKill", out var sk)) row.SecKill = sk.GetDouble(); + if (e.TryGetProperty("hitRate", out var hr)) row.HitRate = hr.GetDouble(); + if (e.TryGetProperty("targeted", out var tg)) row.Targeted = tg.GetBoolean(); + if (e.TryGetProperty("nearby", out var nb)) row.Nearby = nb.GetBoolean(); + if (e.TryGetProperty("tiers", out var tarr) && tarr.ValueKind == JsonValueKind.Array) + foreach (JsonElement te in tarr.EnumerateArray()) + row.Tiers.Add(new DamageTierStat + { + Tier = te.GetProperty("tier").GetInt32(), + Elem = te.GetProperty("elem").GetString() ?? "", + Weapon = te.GetProperty("weapon").GetString() ?? "", + Crit = te.GetProperty("crit").GetDouble(), + CritN = te.GetProperty("critN").GetInt32(), + NonCrit = te.GetProperty("noncrit").GetDouble(), + NonCritN = te.GetProperty("noncritN").GetInt32(), + Casts = te.GetProperty("casts").GetDouble(), + Kills = te.GetProperty("kills").GetInt32(), + }); + list.Add(row); + } + } + catch { } + return list; + } + + private static List<(uint, string)> ParseItems(string json) + { + var list = new List<(uint, string)>(); + try + { + using var doc = JsonDocument.Parse(json); + foreach (JsonElement e in doc.RootElement.EnumerateArray()) + list.Add(((uint)e.GetProperty("id").GetInt64(), e.GetProperty("name").GetString() ?? "")); + } + catch { } + return list; + } + + private static List<(string, string)> ParsePets(string json) + { + var list = new List<(string, string)>(); + try + { + using var doc = JsonDocument.Parse(json); + foreach (JsonElement e in doc.RootElement.EnumerateArray()) + list.Add((e.GetProperty("key").GetString() ?? "", e.GetProperty("name").GetString() ?? "")); + } + catch { } + return list; + } + + /// <summary>Tier display: 0 = none ("—"); negative = ring spell ("R<level>"); positive = spell level.</summary> + public static string FormatTier(int t) => + t == 0 ? "—" : t < 0 ? "R" + (-t).ToString(CultureInfo.InvariantCulture) : t.ToString(CultureInfo.InvariantCulture); +} + +/// <summary>One monster's breakdown (RynthPluginGetMonsterDetailJson), for the Monster Detail panel.</summary> +internal sealed class MonsterDetail +{ + public uint Wcid; public string Name = ""; public int Hp; public string HpSrc = ""; + public double SecKill = -1, HitRate = -1; + public string WeakSrc = ""; + public List<(string Element, double Mult)> Weak = new(); // Mult -1 = order only + public List<DetailCast> Casts = new(); + public List<(string Weapon, int Hits, int Misses, double Sec, int SecN)> Weapons = new(); + public List<(string Element, int Kills, double Sec)> Summons = new(); + public List<(string Element, int Hits, double Avg, double Max)> Taken = new(); + public bool Bound; +} + +internal sealed class DetailCast +{ + public string Weapon = "", Elem = ""; public int Tier, Hits, CritN, NonCritN, Kills; + public double Avg, Crit, NonCrit, Casts; +} + +/// <summary>The selected monster's detail (1 s) while the Monster Detail panel is open.</summary> +internal sealed unsafe class MonsterDetailSource : UiSource<MonsterDetail> +{ + private delegate* unmanaged[Cdecl]<uint, IntPtr> _get; + private string? _lastJson; + private uint _lastWcid; + + public MonsterDetailSource() : base("MonsterDetail", periodMs: 1000) { } + + /// <summary>The monster to show (any thread); the next poll reads it.</summary> + public static volatile uint SelectedWcid; + + protected internal override void Poll() + { + uint wcid = SelectedWcid; + if (_get == null) + { + _get = (delegate* unmanaged[Cdecl]<uint, IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetMonsterDetailJson"); + if (_get == null) + { + if (Current == null) Publish(new MonsterDetail { Bound = false }); + return; + } + } + if (wcid == 0) return; + IntPtr p = _get(wcid); + string? json = p == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(p); + if (json == null || (json == _lastJson && wcid == _lastWcid)) return; + _lastJson = json; + _lastWcid = wcid; + Publish(Parse(json, wcid)); + } + + protected internal override void Reset() + { + _get = null; + _lastJson = null; + ClearSnapshot(); + } + + private static MonsterDetail Parse(string json, uint wcid) + { + var d = new MonsterDetail { Wcid = wcid, Bound = true }; + try + { + using var doc = JsonDocument.Parse(json); + JsonElement r = doc.RootElement; + if (!r.TryGetProperty("wcid", out _)) return d; + d.Name = r.GetProperty("name").GetString() ?? ""; + d.Hp = r.GetProperty("hp").GetInt32(); + d.HpSrc = r.GetProperty("hpSrc").GetString() ?? ""; + d.SecKill = r.GetProperty("secKill").GetDouble(); + d.HitRate = r.GetProperty("hitRate").GetDouble(); + d.WeakSrc = r.GetProperty("weakSrc").GetString() ?? ""; + foreach (JsonElement e in r.GetProperty("weak").EnumerateArray()) + d.Weak.Add((e.GetProperty("e").GetString() ?? "", e.GetProperty("m").GetDouble())); + foreach (JsonElement e in r.GetProperty("casts").EnumerateArray()) + d.Casts.Add(new DetailCast + { + Weapon = e.GetProperty("weapon").GetString() ?? "", Elem = e.GetProperty("elem").GetString() ?? "", + Tier = e.GetProperty("tier").GetInt32(), Hits = e.GetProperty("hits").GetInt32(), + Avg = e.GetProperty("avg").GetDouble(), Crit = e.GetProperty("crit").GetDouble(), + CritN = e.GetProperty("critN").GetInt32(), NonCrit = e.GetProperty("noncrit").GetDouble(), + NonCritN = e.GetProperty("noncritN").GetInt32(), Casts = e.GetProperty("casts").GetDouble(), + Kills = e.GetProperty("kills").GetInt32(), + }); + foreach (JsonElement e in r.GetProperty("weapons").EnumerateArray()) + d.Weapons.Add((e.GetProperty("weapon").GetString() ?? "", e.GetProperty("hits").GetInt32(), + e.GetProperty("misses").GetInt32(), e.GetProperty("sec").GetDouble(), e.GetProperty("secN").GetInt32())); + foreach (JsonElement e in r.GetProperty("summons").EnumerateArray()) + d.Summons.Add((e.GetProperty("elem").GetString() ?? "", e.GetProperty("kills").GetInt32(), e.GetProperty("sec").GetDouble())); + foreach (JsonElement e in r.GetProperty("taken").EnumerateArray()) + d.Taken.Add((e.GetProperty("elem").GetString() ?? "", e.GetProperty("hits").GetInt32(), + e.GetProperty("avg").GetDouble(), e.GetProperty("max").GetDouble())); + } + catch { } + return d; + } +} + +/// <summary>RynthPluginGetMonstersJson while a Monsters or Damage face is open (1 s, and after each write).</summary> +internal sealed unsafe class MonsterRulesSource : UiSource<MonsterRulesSnapshot> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _get; + private string? _lastJson; + + public MonsterRulesSource() : base("MonsterRules", periodMs: 1000) { } + + protected internal override void Poll() + { + string? json = FetchJson(); + if (string.IsNullOrEmpty(json) || json == _lastJson) return; + MonstersPanel.Payload? parsed; + try { parsed = JsonSerializer.Deserialize(json, MonstersPanelJsonContext.Default.Payload); } + catch { return; } + if (parsed == null) return; + _lastJson = json; + Publish(new MonsterRulesSnapshot(json, parsed)); + } + + /// <summary>The plugin's current rules JSON. Pump thread only (hub commands use it to edit the latest rules).</summary> + internal string? FetchJson() + { + if (_get == null) + _get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetMonstersJson"); + if (_get == null) return null; + IntPtr p = _get(); + return p == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(p); + } + + protected internal override void Reset() + { + _get = null; + _lastJson = null; + ClearSnapshot(); + } +} + +/// <summary>The Damage and Monsters panels' mutating exports, on the pump thread. Any thread may call these.</summary> +internal static unsafe class DamageCommands +{ + private static delegate* unmanaged[Cdecl]<uint, int, void> _setHp; + private static delegate* unmanaged[Cdecl]<IntPtr, int> _deleteRow; + private static delegate* unmanaged[Cdecl]<uint, uint, void> _setWeapon, _setOffhand; + private static delegate* unmanaged[Cdecl]<uint, void> _setDefaultWeapon; + private static delegate* unmanaged[Cdecl]<IntPtr, void> _setMonsters; + private static delegate* unmanaged[Cdecl]<void> _clearStats; + private static delegate* unmanaged[Cdecl]<uint, IntPtr, void> _setPet; + private static delegate* unmanaged[Cdecl]<int, void> _setViewTier; + + static DamageCommands() + { + PluginManager.PluginsUnloaded += () => + { + _setHp = null; _deleteRow = null; _setWeapon = null; _setOffhand = null; _setDefaultWeapon = null; + _setMonsters = null; _clearStats = null; _setPet = null; _setViewTier = null; + }; + } + + private static IntPtr Export(string name) => PluginExportBinder.Resolve("RynthAi", name); + + private static void Run(string label, Action action, bool rules = false) + { + UiDataHub.Post("Damage " + label, () => + { + action(); + UiSources.Damage.RequestRefreshAfterPluginTick(); + if (rules) UiSources.MonsterRules.RequestRefreshAfterPluginTick(); + }); + } + + /// <summary>Manual max HP; 0 returns the monster to auto.</summary> + public static void SetHp(uint wcid, int hp) => Run("hp", () => + { + if (_setHp == null) _setHp = (delegate* unmanaged[Cdecl]<uint, int, void>)Export("RynthPluginSetMonsterHp"); + if (_setHp != null) _setHp(wcid, hp); + }); + + public static void DeleteRow(string key) => Run("delete row", () => + { + if (_deleteRow == null) _deleteRow = (delegate* unmanaged[Cdecl]<IntPtr, int>)Export("RynthPluginDeleteMonsterRow"); + if (_deleteRow == null || key.Length == 0) return; + IntPtr k = Marshal.StringToHGlobalAnsi(key); + try { _deleteRow(k); } + finally { Marshal.FreeHGlobal(k); } + }); + + /// <summary>Per-monster weapon (0 = Auto, the learned best).</summary> + public static void SetWeapon(uint wcid, uint weaponId) => Run("weapon", () => + { + if (_setWeapon == null) _setWeapon = (delegate* unmanaged[Cdecl]<uint, uint, void>)Export("RynthPluginSetMonsterWeapon"); + if (_setWeapon != null) _setWeapon(wcid, weaponId); + }); + + /// <summary>Per-monster offhand item (0 = none: the monster's rule, else the DEFAULT line, decides).</summary> + public static void SetOffhand(uint wcid, uint offhandId) => Run("offhand", () => + { + if (_setOffhand == null) _setOffhand = (delegate* unmanaged[Cdecl]<uint, uint, void>)Export("RynthPluginSetMonsterOffhand"); + if (_setOffhand != null) _setOffhand(wcid, offhandId); + }); + + /// <summary>The Default line's weapon: every monster set to Default uses it (0 = learned best).</summary> + public static void SetDefaultWeapon(uint weaponId) => Run("default weapon", () => + { + if (_setDefaultWeapon == null) _setDefaultWeapon = (delegate* unmanaged[Cdecl]<uint, void>)Export("RynthPluginSetDefaultWeapon"); + if (_setDefaultWeapon != null) _setDefaultWeapon(weaponId); + }); + + /// <summary>Pet for this monster: "" = Auto, "E:<element>", "I:<essence id>".</summary> + public static void SetPet(uint wcid, string choice) => Run("pet", () => + { + if (_setPet == null) _setPet = (delegate* unmanaged[Cdecl]<uint, IntPtr, void>)Export("RynthPluginSetMonsterPet"); + if (_setPet == null) return; + IntPtr a = Marshal.StringToHGlobalAnsi(choice); + try { _setPet(wcid, a); } + finally { Marshal.FreeHGlobal(a); } + UiSources.Damage.RefreshPetsSoon(); + }); + + /// <summary>The Aelrynth difficulty tier the panel shows: -1 follows the one where the player stands.</summary> + public static void SetViewTier(int tier) => Run("view tier", () => + { + if (_setViewTier == null) _setViewTier = (delegate* unmanaged[Cdecl]<int, void>)Export("RynthPluginSetDamageViewTier"); + if (_setViewTier != null) _setViewTier(tier); + UiSources.MonsterDetail.RequestRefresh(); + }); + + /// <summary>Removes one monster from the Damage tab: its learned data and its settings.</summary> + public static void RemoveMonster(uint wcid) => DeleteRow(wcid.ToString(CultureInfo.InvariantCulture)); + + /// <summary>Clears all learned damage statistics (names and manual settings are kept).</summary> + public static void ClearStats() => Run("clear stats", () => + { + if (_clearStats == null) _clearStats = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginClearMonsterStats"); + if (_clearStats != null) _clearStats(); + }); + + /// <summary>Writes the whole rules array, already serialized (the Monsters panel's save).</summary> + public static void SetRulesJson(string json) => Run("rules", () => + { + if (_setMonsters == null) _setMonsters = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthPluginSetMonstersJson"); + if (_setMonsters == null) return; + IntPtr ansi = Marshal.StringToHGlobalAnsi(json); + try { _setMonsters(ansi); } + finally { Marshal.FreeHGlobal(ansi); } + }, rules: true); + + /// <summary> + /// Edits <paramref name="name"/>'s exact-name rule on the plugin's latest + /// rules (read fresh here, so an edit can't clobber one made elsewhere). + /// A monster that inherits Default gets a copy of Default first, inserted + /// right after it so the specific rule wins. "Default" edits Default itself. + /// <paramref name="copyFrom"/>: the rule to copy instead of Default when the monster has no + /// rule of its own yet (the name rule that covers it, so an edit doesn't swap its spells). + /// </summary> + public static void EditRule(string name, Action<MonstersPanel.Rule> edit, string? copyFrom = null) => Run("edit rule", () => + { + MonstersPanel.Payload? rules = FreshRules(); + if (rules == null) return; + edit(EnsureRule(rules, name, copyFrom)); + PushRules(rules.Rules); + }, rules: true); + + /// <summary> + /// The first rule other than Default whose name <paramref name="monsterName"/> contains, in list + /// order, the way RynthAi's targeting priority finds it (CombatManager.ScoreCandidate, which + /// goes by name only: a match expression doesn't limit the priority bonus). + /// </summary> + public static MonstersPanel.Rule? CoveringRule(List<MonstersPanel.Rule> rules, string monsterName) + { + foreach (MonstersPanel.Rule r in rules) + { + if (IsDefault(r) || string.IsNullOrWhiteSpace(r.Name)) continue; + if (monsterName.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0) return r; + } + return null; + } + + /// <summary>Makes <paramref name="name"/> follow Default again (drops its exact-name rule).</summary> + public static void ResetRule(string name) => Run("reset rule", () => + { + MonstersPanel.Payload? rules = FreshRules(); + if (rules == null) return; + int i = rules.Rules.FindIndex(r => !IsDefault(r) && r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + if (i < 0) return; + rules.Rules.RemoveAt(i); + PushRules(rules.Rules); + }, rules: true); + + private static bool IsDefault(MonstersPanel.Rule r) => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase); + + private static MonstersPanel.Payload? FreshRules() + { + string? json = UiSources.MonsterRules.FetchJson(); + if (string.IsNullOrEmpty(json)) return null; + MonstersPanel.Payload? p; + try { p = JsonSerializer.Deserialize(json, MonstersPanelJsonContext.Default.Payload); } + catch { return null; } + // Never write back an empty or unloaded array: it would wipe the rules (Default included). + return p?.Rules == null || p.Rules.Count == 0 ? null : p; + } + + private static MonstersPanel.Rule EnsureRule(MonstersPanel.Payload rules, string name, string? copyFrom = null) + { + int defIdx = rules.Rules.FindIndex(IsDefault); + if (name.Equals("Default", StringComparison.OrdinalIgnoreCase)) + { + if (defIdx >= 0) return rules.Rules[defIdx]; + var created = new MonstersPanel.Rule { Name = "Default", UseBolt = true }; + rules.Rules.Add(created); + return created; + } + MonstersPanel.Rule? existing = rules.Rules.Find(r => !IsDefault(r) && r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + if (existing != null) return existing; + MonstersPanel.Rule s = defIdx >= 0 ? rules.Rules[defIdx] : new MonstersPanel.Rule { Name = "Default", UseBolt = true }; + MonstersPanel.Rule? from = string.IsNullOrEmpty(copyFrom) ? null + : rules.Rules.Find(r => !IsDefault(r) && r.Name.Equals(copyFrom, StringComparison.OrdinalIgnoreCase)); + MonstersPanel.Rule clone = CopyOfDefault(from ?? s, name); + if (from != null) { clone.OffhandId = from.OffhandId; clone.PetDamage = from.PetDamage; } // a name rule's own choices, kept + rules.Rules.Insert(defIdx >= 0 ? defIdx + 1 : 0, clone); + return clone; + } + + /// <summary> + /// A new rule named <paramref name="name"/> with Default's settings. Off hand and pet are + /// left on "follow Default" (0 / PAuto) rather than copied, so a later change on the + /// DEFAULT line still reaches it. + /// </summary> + private static MonstersPanel.Rule CopyOfDefault(MonstersPanel.Rule s, string name) => new() + { + Name = name, Category = s.Category, + MatchExpression = "", // an exact-name rule matches by name, not by a (possibly false) expression + Priority = s.Priority, DamageType = s.DamageType, WeaponId = s.WeaponId, OffhandId = 0, + ExVuln = s.ExVuln, PetDamage = "PAuto", + Fester = s.Fester, Broadside = s.Broadside, GravityWell = s.GravityWell, + Imperil = s.Imperil, Yield = s.Yield, Vuln = s.Vuln, + UseArc = s.UseArc, UseBolt = s.UseBolt, UseRing = s.UseRing, UseStreak = s.UseStreak, UseBlast = s.UseBlast, + CustomDebuffs = s.CustomDebuffs, + }; + + /// <summary> + /// Adds a name rule (the Damage panel's Name rules): it covers every monster whose name + /// contains <paramref name="name"/>, and the expression too when one is given. Starts as a + /// copy of Default and goes at the end of the list, so a monster's own rule (inserted + /// after Default) still wins over it. An existing rule of that name only takes the expression. + /// </summary> + public static void AddRule(string name, string expression) => Run("add rule", () => + { + name = name.Trim(); + expression = expression.Trim(); + if (name.Length == 0 || name.Equals("Default", StringComparison.OrdinalIgnoreCase)) return; + MonstersPanel.Payload? rules = FreshRules(); + if (rules == null) return; + MonstersPanel.Rule? existing = rules.Rules.Find(r => !IsDefault(r) && r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + if (existing != null) + { + if (expression.Length == 0) return; + existing.MatchExpression = expression; + } + else + { + MonstersPanel.Rule def = rules.Rules.Find(IsDefault) ?? new MonstersPanel.Rule { Name = "Default", UseBolt = true }; + MonstersPanel.Rule added = CopyOfDefault(def, name); + added.MatchExpression = expression; + rules.Rules.Add(added); + } + PushRules(rules.Rules); + }, rules: true); + + private static void PushRules(List<MonstersPanel.Rule> rules) + { + if (rules.Count == 0) return; // never wipe the plugin's rules + if (_setMonsters == null) _setMonsters = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthPluginSetMonstersJson"); + if (_setMonsters == null) return; + string json = JsonSerializer.Serialize(new MonstersPanel.Payload { Rules = rules }, MonstersPanelJsonContext.Default.Payload); + IntPtr ansi = Marshal.StringToHGlobalAnsi(json); + try { _setMonsters(ansi); } + finally { Marshal.FreeHGlobal(ansi); } + } + + // ── Drawer vocabulary (shared by both faces) ───────────────────────── + + public static readonly (string Field, string Label, string Tip)[] DebuffDefs = + { + ("Imperil", "Imperil", "Imperil (Gossamer Flesh / Imperil Other)"), + ("Vuln", "Vuln", "Vulnerability (element-matched)"), + ("Fester", "Fester", "Fester (Decrepitude's Grasp / Fester Other)"), + ("Yield", "Yield", "Yield (Magic Yield Other)"), + ("Broadside", "Broadside","Broadside (Missile Weapons Ineptitude)"), + ("GravityWell", "Gravity", "Gravity Well (Vulnerability Other)"), + }; + + /// <summary>The Damage panel's one-letter debuff marks, in DebuffDefs order.</summary> + public static readonly (string Field, char Letter)[] DebuffLetters = + { + ("Imperil", 'I'), ("Vuln", 'V'), ("Fester", 'F'), ("Yield", 'Y'), ("Broadside", 'B'), ("GravityWell", 'G'), + }; + + /// <summary>"IVF" for the debuffs a rule has on; X = an extra vuln, + = typed-in ones.</summary> + public static string DebuffMarks(MonstersPanel.Rule r) + { + var sb = new System.Text.StringBuilder(8); + foreach (var (field, letter) in DebuffLetters) if (r.GetToggle(field)) sb.Append(letter); + if (!string.IsNullOrEmpty(r.ExVuln) && !r.ExVuln.Equals("None", StringComparison.OrdinalIgnoreCase)) sb.Append('X'); + if (!string.IsNullOrWhiteSpace(r.CustomDebuffs)) sb.Append('+'); + return sb.ToString(); + } + + public static readonly (string Field, string Label, string Tip)[] ShapeDefs = + { + ("UseArc", "Arc", "Arc spells"), + ("UseBolt", "Bolt", "Bolt spells (default)"), + ("UseRing", "Ring", "Ring spells"), + ("UseStreak", "Streak", "Streak spells"), + ("UseBlast", "Blast", "Blast spells (Flame Blast, Frost Blast...): a spread of projectiles, from level III.\n" + + "Used instead of Bolt when both are on (Arc and Streak come first). A character who knows\n" + + "no blast of the element casts its Bolt."), + }; + + public static readonly string[] ExVulnTypes = + { "None", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + + /// <summary>Rule.DamageType choices (Auto = from the monster's weaknesses).</summary> + public static readonly string[] DamageTypes = + { "Auto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + + /// <summary>Rule.OffhandId as RynthAi reads it: 0 = follow the DEFAULT line, 1-4 a mode, anything else an item id.</summary> + public static readonly string[] OffhandModeNames = { "Default", "Auto", "Shield", "Dual wield", "None" }; + + /// <summary>Rule.PetDamage choices; "PAuto" is shown as Auto.</summary> + public static readonly string[] PetDamageTypes = + { "PAuto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + + /// <summary>Flips a debuff/shape toggle; a monster is never left with no spell shape (combat would refuse to cast).</summary> + public static void FlipToggle(MonstersPanel.Rule rule, string field) + { + bool on = !rule.GetToggle(field); + rule.SetToggle(field, on); + bool shape = field is "UseArc" or "UseBolt" or "UseRing" or "UseStreak" or "UseBlast"; + if (shape && !on && !HasAnyShape(rule)) + rule.UseBolt = true; + } + + /// <summary>At least one spell shape is on (RynthAi refuses to attack with magic otherwise).</summary> + public static bool HasAnyShape(MonstersPanel.Rule r) => r.UseArc || r.UseBolt || r.UseRing || r.UseStreak || r.UseBlast; + + /// <summary>The shape RynthAi casts when no ring is due (RynthAi CombatManager.PickBaseShape): Arc, Streak, Blast, then Bolt.</summary> + public static string BaseShapeName(MonstersPanel.Rule r) + { + if (r.UseArc) return "Arc"; + if (r.UseStreak) return "Streak"; + if (r.UseBlast) return "Blast"; + if (r.UseBolt || r.UseRing) return "Bolt"; + return ""; + } +} diff --git a/src/RynthCore.Engine/UI/Data/ItemsData.cs b/src/RynthCore.Engine/UI/Data/ItemsData.cs new file mode 100644 index 0000000..26e55bf --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ItemsData.cs @@ -0,0 +1,122 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ItemsData.cs +// RynthAi's item rules (weapons with their element, consumables with their +// type, mana stone tapping) for both Items faces. +// +// RynthPluginGetItemsJson frees its previous buffer on each call, so the hub +// is its only caller (ItemsSource, 1 s). RynthPluginSetItemsJson and the two +// Add Selected exports apply on the spot; they run on the pump (they read +// and change plugin state the tick also uses) and refresh the snapshot. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Text.Json; +using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Panels; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>The items JSON and its parse. Parsed is shared: copy before changing (ParseCopy).</summary> +internal sealed class ItemsSnapshot +{ + public ItemsSnapshot(string json, ItemsPanel.Payload parsed) { Json = json; Parsed = parsed; } + public string Json { get; } + public ItemsPanel.Payload Parsed { get; } + + public ItemsPanel.Payload ParseCopy() => + JsonSerializer.Deserialize(Json, ItemsPanelJsonContext.Default.Payload) ?? new ItemsPanel.Payload(); +} + +/// <summary>RynthPluginGetItemsJson while an Items face is open (1 s, and after each change).</summary> +internal sealed unsafe class ItemsSource : UiSource<ItemsSnapshot> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _get; + private string? _lastJson; + + public ItemsSource() : base("Items", periodMs: 1000) { } + + protected internal override void Poll() + { + if (_get == null) + _get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetItemsJson"); + if (_get == null) return; + IntPtr ptr = _get(); + string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr); + if (string.IsNullOrEmpty(json) || json == _lastJson) return; + ItemsPanel.Payload? parsed; + try { parsed = JsonSerializer.Deserialize(json, ItemsPanelJsonContext.Default.Payload); } + catch { return; } + if (parsed == null) return; + _lastJson = json; + Publish(new ItemsSnapshot(json, parsed)); + } + + protected internal override void Reset() + { + _get = null; + _lastJson = null; + ClearSnapshot(); + } +} + +internal static unsafe class ItemsCommands +{ + private static delegate* unmanaged[Cdecl]<IntPtr, void> _set; + private static delegate* unmanaged[Cdecl]<void> _addWeapon, _addShield, _addConsumable; + + /// <summary>ItemRule.Action value the plugin uses for off-hand shields.</summary> + public const string ShieldAction = "Shield"; + + static ItemsCommands() + { + PluginManager.PluginsUnloaded += () => { _set = null; _addWeapon = null; _addShield = null; _addConsumable = null; }; + } + + public static readonly string[] Elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + public static readonly string[] ConsumableTypes = { "General", "Lockpick", "HealthKit", "HealthPotion", "ManaPotion", "StaminaPotion", "ManaStone", "Stamina", "Pet" }; + + private static IntPtr Export(string name) => PluginExportBinder.Resolve("RynthAi", name); + + /// <summary>Saves the whole items payload, already serialized (a copy the caller no longer changes).</summary> + public static void SetJson(string json) => UiDataHub.Post("Items save", () => + { + if (_set == null) _set = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthPluginSetItemsJson"); + if (_set == null) return; + IntPtr ansi = Marshal.StringToHGlobalAnsi(json); + try { _set(ansi); } + finally { Marshal.FreeHGlobal(ansi); } + UiSources.Items.RequestRefresh(); + }); + + /// <summary>Adds the item selected in the inventory as a weapon.</summary> + public static void AddSelectedWeapon() => UiDataHub.Post("Items add weapon", () => + { + if (_addWeapon == null) _addWeapon = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginAddSelectedWeapon"); + if (_addWeapon != null) _addWeapon(); + UiSources.Items.RequestRefresh(); + }); + + /// <summary> + /// Adds the item selected in the inventory as an off-hand shield. RynthAi older than + /// 0.6.20 has no such export: the click is logged and dropped. + /// </summary> + public static void AddSelectedShield() => UiDataHub.Post("Items add shield", () => + { + if (_addShield == null) _addShield = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginAddSelectedShield"); + if (_addShield != null) _addShield(); + else RynthLog.UI("ItemsCommands: Add Selected Shield unavailable - RynthAi 0.6.20 or newer is required."); + UiSources.Items.RequestRefresh(); + }); + + /// <summary>Adds the item selected in the inventory as a consumable.</summary> + public static void AddSelectedConsumable() => UiDataHub.Post("Items add consumable", () => + { + if (_addConsumable == null) _addConsumable = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginAddSelectedConsumable"); + if (_addConsumable != null) _addConsumable(); + UiSources.Items.RequestRefresh(); + }); + + public static string Serialize(ItemsPanel.Payload payload) => + JsonSerializer.Serialize(payload, ItemsPanelJsonContext.Default.Payload); +} diff --git a/src/RynthCore.Engine/UI/Data/LootEditData.cs b/src/RynthCore.Engine/UI/Data/LootEditData.cs new file mode 100644 index 0000000..7148ea5 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/LootEditData.cs @@ -0,0 +1,394 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/LootEditData.cs +// RynthAi's loot profile editor state for the ImGui Loot Editor face +// (docs/IMGUI_LOOT_EDITOR.md). RynthAi owns the data (LootSdk's +// LootEditSession); these DTOs mirror RynthSuite's Shared/RynthCore.LootSdk/ +// Editing/LootEditWire.cs - keep the two in step. The engine does not +// reference LootSdk. +// +// LootEditSource (pump thread, after the plugin tick) asks for the cheap +// revision every second and fetches the rule list only when it moved; the +// full rule the face has open comes from a second export, the pickers' names +// from a third (once per plugin load). Strings are UTF-8 both ways. +// LootEditCommands posts edits through the hub; the plugin applies them at +// once, so the same hub step's poll already shows the result. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +internal sealed class LootEditStateDto +{ + public long Revision { get; set; } + public string Path { get; set; } = string.Empty; + public string FileName { get; set; } = string.Empty; + public string Format { get; set; } = string.Empty; + public bool Exists { get; set; } + public bool ReadOnly { get; set; } + public string ReadOnlyReason { get; set; } = string.Empty; + public bool Dirty { get; set; } + public bool ChangedOnDisk { get; set; } + public string InUsePath { get; set; } = string.Empty; + public bool InUse { get; set; } + public string Message { get; set; } = string.Empty; + public bool MessageOk { get; set; } = true; + public long MessageSeq { get; set; } + public int Focus { get; set; } = -1; + public List<LootEditFileDto> Files { get; set; } = new(); + public List<LootEditRowDto> Rules { get; set; } = new(); + /// <summary>"Add to loot profile" popup's rule (added 2026-10); null from an older RynthAi.</summary> + public LootEditItemDraftDto? ItemDraft { get; set; } +} + +internal sealed class LootEditFileDto +{ + public string Path { get; set; } = string.Empty; + public string Display { get; set; } = string.Empty; +} + +internal sealed class LootEditRowDto +{ + public string Name { get; set; } = string.Empty; + public bool Enabled { get; set; } = true; + public int Action { get; set; } + public int KeepCount { get; set; } + public string Summary { get; set; } = string.Empty; + public int Conditions { get; set; } +} + +internal sealed class LootEditRuleDto +{ + public int Index { get; set; } = -1; + public string Name { get; set; } = string.Empty; + public bool Enabled { get; set; } = true; + public int Action { get; set; } = 1; + public int KeepCount { get; set; } + public int Priority { get; set; } + public string? CustomExpression { get; set; } + public List<LootEditConditionDto> Conditions { get; set; } = new(); + + public LootEditRuleDto Clone() + { + var r = (LootEditRuleDto)MemberwiseClone(); + r.Conditions = new List<LootEditConditionDto>(Conditions.Count); + foreach (LootEditConditionDto c in Conditions) r.Conditions.Add(c.Clone()); + return r; + } + + /// <summary>Same content (the rule view's "edited?" test).</summary> + public bool SameAs(LootEditRuleDto o) + { + if (Name != o.Name || Enabled != o.Enabled || Action != o.Action || Priority != o.Priority + || CustomExpression != o.CustomExpression || Conditions.Count != o.Conditions.Count) + return false; + if (Action == LootEditVocabulary.KeepUpTo && KeepCount != o.KeepCount) return false; + for (int i = 0; i < Conditions.Count; i++) + if (!Conditions[i].SameAs(o.Conditions[i])) return false; + return true; + } +} + +internal sealed class LootEditConditionDto +{ + public int NodeType { get; set; } + public string LengthCode { get; set; } = "0"; + public List<string> Lines { get; set; } = new(); + + public LootEditConditionDto Clone() => new() { NodeType = NodeType, LengthCode = LengthCode, Lines = new List<string>(Lines) }; + + public bool SameAs(LootEditConditionDto o) + { + if (NodeType != o.NodeType || LengthCode != o.LengthCode || Lines.Count != o.Lines.Count) return false; + for (int i = 0; i < Lines.Count; i++) if (Lines[i] != o.Lines[i]) return false; + return true; + } +} + +internal sealed class LootEditCmd +{ + public string Op { get; set; } = string.Empty; + public int Index { get; set; } = -1; + public int To { get; set; } = -1; + public string Value { get; set; } = string.Empty; + public string Path { get; set; } = string.Empty; + public string? Expect { get; set; } + public bool Force { get; set; } + public LootEditRuleDto? Rule { get; set; } + /// <summary>item_preview / item_add (added 2026-10).</summary> + public LootEditItemRequestDto? Item { get; set; } +} + +/// <summary>"Add to loot profile": the popup's ask (LootEditWire's LootEditItemRequest).</summary> +internal sealed class LootEditItemRequestDto +{ + /// <summary>0 = the item selected in the game.</summary> + public uint ItemId { get; set; } + /// <summary>0 name + class, 1 name only, 2 items like this.</summary> + public int Match { get; set; } + /// <summary>VTank action code; 0 = the item's default.</summary> + public int Action { get; set; } + /// <summary>-1 = default (one full stack).</summary> + public int KeepCount { get; set; } = -1; + public string RuleName { get; set; } = string.Empty; + /// <summary>True: the profile open in the Loot Editor; false: the one RynthAi loots with.</summary> + public bool ToOpenProfile { get; set; } + public int Seq { get; set; } +} + +/// <summary>The rule an item makes and what an add did (LootEditWire's LootEditItemDraft).</summary> +internal sealed class LootEditItemDraftDto +{ + public int Seq { get; set; } + public bool Ok { get; set; } + public string Error { get; set; } = string.Empty; + public uint ItemId { get; set; } + public string ItemName { get; set; } = string.Empty; + public string ClassName { get; set; } = string.Empty; + public bool Stackable { get; set; } + public string TargetPath { get; set; } = string.Empty; + public string TargetFile { get; set; } = string.Empty; + public bool TargetInUse { get; set; } + public string Format { get; set; } = string.Empty; + public int Match { get; set; } + public int Action { get; set; } + public int KeepCount { get; set; } + public string RuleName { get; set; } = string.Empty; + public string DefaultRuleName { get; set; } = string.Empty; + public List<string> Preview { get; set; } = new(); + public int InsertAt { get; set; } = -1; + public int RuleCount { get; set; } + public string OrderNote { get; set; } = string.Empty; + public List<string> Notes { get; set; } = new(); + public bool Added { get; set; } + public string Message { get; set; } = string.Empty; +} + +internal sealed class LootEditVocabDto +{ + public List<LootEditNameDto> Actions { get; set; } = new(); + public List<LootEditNodeTypeDto> NodeTypes { get; set; } = new(); + public List<LootEditNameDto> ObjectClasses { get; set; } = new(); + public List<LootEditNameDto> LongKeys { get; set; } = new(); + public List<LootEditNameDto> DoubleKeys { get; set; } = new(); + public List<LootEditNameDto> StringKeys { get; set; } = new(); + public List<LootEditNameDto> Skills { get; set; } = new(); + /// <summary>Names for long keys' values (added 2026-10); empty from an older RynthAi (the value stays a text box).</summary> + public List<LootEditValueTableDto> LongValueTables { get; set; } = new(); +} + +internal sealed class LootEditNameDto +{ + public int Id { get; set; } + public string Name { get; set; } = string.Empty; +} + +internal sealed class LootEditValueTableDto +{ + public int Key { get; set; } + public bool Flags { get; set; } + public List<LootEditNameDto> Values { get; set; } = new(); +} + +internal sealed class LootEditNodeTypeDto +{ + public int Id { get; set; } + public string Name { get; set; } = string.Empty; + public int Lines { get; set; } + public List<string> Labels { get; set; } = new(); + public List<string> Defaults { get; set; } = new(); + public string Editor { get; set; } = "raw"; + public string KeyTable { get; set; } = string.Empty; + /// <summary>keyval "long": pick the value by name when the key has a LongValueTables entry (added 2026-10).</summary> + public bool NamedValues { get; set; } +} + +[JsonSerializable(typeof(LootEditStateDto))] +[JsonSerializable(typeof(LootEditRuleDto))] +[JsonSerializable(typeof(LootEditCmd))] +[JsonSerializable(typeof(LootEditVocabDto))] +[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false)] +internal partial class LootEditJsonContext : JsonSerializerContext { } + +/// <summary>What the face reads. Immutable once published (the face clones what it edits).</summary> +internal sealed class LootEditView +{ + /// <summary>RynthAi isn't loaded, or is too old to have the loot editor exports.</summary> + public bool Unavailable { get; init; } + public LootEditStateDto? State { get; init; } + /// <summary>The rule asked for with LootEditSource.WantRule, fetched at State's revision; null if none.</summary> + public LootEditRuleDto? Rule { get; init; } + public LootEditVocabDto? Vocab { get; init; } +} + +/// <summary>The loot editor's state while the face is open (revision each second, the list when it changes).</summary> +internal sealed unsafe class LootEditSource : UiSource<LootEditView> +{ + private delegate* unmanaged[Cdecl]<int> _revision; + private delegate* unmanaged[Cdecl]<IntPtr> _getState, _getVocab; + private delegate* unmanaged[Cdecl]<int, IntPtr> _getRule; + private bool _bound; + private int _lastRevision; + private bool _haveState; + private LootEditStateDto? _state; + private LootEditVocabDto? _vocab; + private LootEditRuleDto? _rule; + private int _ruleIndex = -1, _ruleRevision; + private int _wantRule = -1; + + public LootEditSource() : base("LootEdit", periodMs: 1000) { } + + /// <summary>The rule the face has open (-1: none). Any thread.</summary> + public void WantRule(int index) + { + if (Interlocked.Exchange(ref _wantRule, index) != index) RequestRefresh(); + } + + protected internal override void Poll() + { + if (!_bound) + { + _revision = (delegate* unmanaged[Cdecl]<int>)PluginExportBinder.Resolve("RynthAi", "RynthPluginLootEditRevision"); + _getState = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetLootEditJson"); + _getRule = (delegate* unmanaged[Cdecl]<int, IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetLootEditRuleJson"); + _getVocab = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetLootEditVocabJson"); + _bound = _revision != null && _getState != null && _getRule != null && _getVocab != null; + if (!_bound) + { + if (Current == null || !Current.Value.Unavailable) Publish(new LootEditView { Unavailable = true }); + return; + } + } + + bool changed = false; + if (_vocab == null) + { + _vocab = Parse(_getVocab(), LootEditJsonContext.Default.LootEditVocabDto); + changed |= _vocab != null; + } + + int revision = _revision(); + if (!_haveState || revision != _lastRevision) + { + LootEditStateDto? state = Parse(_getState(), LootEditJsonContext.Default.LootEditStateDto); + if (state != null) + { + _state = state; + _haveState = true; + // The list call may have opened the profile (first look): the state's own revision is current. + _lastRevision = unchecked((int)state.Revision); + changed = true; + } + } + + int want = Volatile.Read(ref _wantRule); + if (want != _ruleIndex || (want >= 0 && _ruleRevision != _lastRevision)) + { + _rule = want < 0 ? null : Parse(_getRule(want), LootEditJsonContext.Default.LootEditRuleDto); + if (_rule != null && _rule.Index < 0) _rule = null; + _ruleIndex = want; + _ruleRevision = _lastRevision; + changed = true; + } + + if (changed) Publish(new LootEditView { State = _state, Rule = _rule, Vocab = _vocab }); + } + + private static T? Parse<T>(IntPtr utf8, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> info) where T : class + { + if (utf8 == IntPtr.Zero) return null; + string? json = Marshal.PtrToStringUTF8(utf8); + if (string.IsNullOrEmpty(json)) return null; + try { return JsonSerializer.Deserialize(json, info); } + catch (JsonException ex) + { + RynthLog.UI($"LootEditSource: bad JSON from RynthAi ({typeof(T).Name}): {ex.Message}"); + return null; + } + } + + protected internal override void Reset() + { + _bound = false; + _revision = null; + _getState = null; + _getVocab = null; + _getRule = null; + _haveState = false; + _state = null; + _vocab = null; + _rule = null; + _ruleIndex = -1; + ClearSnapshot(); + } +} + +/// <summary>RynthPluginSendLootEditCommand on the pump thread. Any thread may call Send.</summary> +internal static unsafe class LootEditCommands +{ + private static delegate* unmanaged[Cdecl]<IntPtr, void> _send; + + static LootEditCommands() + { + PluginManager.PluginsUnloaded += () => _send = null; + } + + /// <summary><paramref name="cmd"/> (and its Rule) must not be changed after this call.</summary> + public static void Send(LootEditCmd cmd) + { + UiDataHub.Post("LootEdit " + cmd.Op, () => + { + if (_send == null) + _send = (delegate* unmanaged[Cdecl]<IntPtr, void>)PluginExportBinder.Resolve("RynthAi", "RynthPluginSendLootEditCommand"); + if (_send == null) return; + string json = JsonSerializer.Serialize(cmd, LootEditJsonContext.Default.LootEditCmd); + IntPtr utf8 = Marshal.StringToCoTaskMemUTF8(json); + try { _send(utf8); } + finally { Marshal.FreeCoTaskMem(utf8); } + UiSources.LootEdit.RequestRefresh(); + }); + } + + public static void Simple(string op, int index = -1, string value = "", string path = "", string? expect = null, + bool force = false, int to = -1) + => Send(new LootEditCmd { Op = op, Index = index, Value = value, Path = path, Expect = expect, Force = force, To = to }); +} + +/// <summary>Action codes and badge text shared by the face.</summary> +internal static class LootEditVocabulary +{ + public const int Keep = 1, Salvage = 2, Sell = 3, Read = 4, KeepUpTo = 10; + + /// <summary>The action filter's chips: 0 = all.</summary> + public static readonly int[] FilterActions = { 0, Keep, KeepUpTo, Salvage, Sell, Read }; + public static readonly string[] FilterLabels = { "All", "Keep", "Keep #", "Salvage", "Sell", "Read" }; + + public static string Badge(int action, int keepCount) => action switch + { + Keep => "KEEP", + KeepUpTo => "KEEP " + keepCount.ToString(System.Globalization.CultureInfo.InvariantCulture), + Salvage => "SALVAGE", + Sell => "SELL", + Read => "READ", + _ => "?", + }; + + /// <summary>Badge fill, ARGB (the external editor's colours).</summary> + public static uint BadgeArgb(int action) => action switch + { + Keep => 0xFF1F6F3A, + KeepUpTo => 0xFF196E6E, + Salvage => 0xFFA35C15, + Sell => 0xFF7A1F1F, + Read => 0xFF1F497D, + _ => 0xFF444444, + }; + + public const int DisabledRule = 9999; +} diff --git a/src/RynthCore.Engine/UI/Data/LuaData.cs b/src/RynthCore.Engine/UI/Data/LuaData.cs new file mode 100644 index 0000000..295cc7d --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/LuaData.cs @@ -0,0 +1,143 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/LuaData.cs +// Lua scripts (state, script list, console, last loaded script) for both Lua +// faces, from RynthLua (v2: several scripts, ScriptInfos / Selected / ...) +// or an older RynthAi that still exports the single-script payload. +// +// RynthPluginGetLuaJson frees its previous buffer on each call, so the hub is +// its only caller. RynthPluginSendLuaCommand queues: the plugin runs the +// command on its next tick, so the refresh waits for that tick. UTF-8 both +// ways (scripts keep non-ASCII text). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +internal sealed class LuaPayload +{ + public bool Running { get; set; } + public string ScriptName { get; set; } = string.Empty; + public string Status { get; set; } = string.Empty; + public List<string> Scripts { get; set; } = new(); + public string Console { get; set; } = string.Empty; + public int ConsoleSeq { get; set; } + /// <summary>Text of the last script loaded; an editor takes it when LoadSeq changes.</summary> + public string LoadedText { get; set; } = string.Empty; + public string LoadedName { get; set; } = string.Empty; + public int LoadSeq { get; set; } + + // ── RynthLua v2 (several scripts at once). Null from the old RynthAi + // exports, which the faces then show the single-script way. ───────── + /// <summary>Every script (files, plus running ones that aren't saved). Null = old single-script payload.</summary> + public List<LuaScriptInfo>? ScriptInfos { get; set; } + /// <summary>The script the panel shows: Console / Running / ScriptName / Status are its.</summary> + public string? Selected { get; set; } + public int RunningCount { get; set; } + /// <summary>RynthAi's "RynthAi.Script" interface is there (macro, nav, meta features for scripts).</summary> + public bool? RynthAi { get; set; } + /// <summary>A character is logged in (per-character autostart needs one). Null from older plugins.</summary> + public bool? LoggedIn { get; set; } +} + +/// <summary>One script in the v2 list (RynthLua's LuaScriptInfo).</summary> +internal sealed class LuaScriptInfo +{ + public string Name { get; set; } = string.Empty; + public bool Running { get; set; } + /// <summary>"none", "global" or "character" (for the logged-in character).</summary> + public string Autostart { get; set; } = "none"; + /// <summary>From script.json; "(not saved)" for a running script with no file (the editor, /lua exec).</summary> + public string Description { get; set; } = string.Empty; + /// <summary>A folder script (index.lua); false for a single Name.lua.</summary> + public bool IsFolder { get; set; } + /// <summary>No file behind it (the editor, /lua exec): no autostart, restart or open.</summary> + public bool Transient { get; set; } +} + +internal sealed class LuaCmd +{ + public string Cmd { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + public string Code { get; set; } = string.Empty; +} + +[JsonSerializable(typeof(LuaPayload))] +[JsonSerializable(typeof(LuaCmd))] +[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false)] +internal partial class LuaJsonContext : JsonSerializerContext { } + +/// <summary>RynthPluginGetLuaJson while a Lua face is open (500 ms, and after each command).</summary> +internal sealed unsafe class LuaSource : UiSource<LuaPayload> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _getLuaJson; + private string? _lastJson; + + public LuaSource() : base("Lua", periodMs: 500) { } + + /// <summary> + /// Lua is the RynthLua plugin since 2026-09-29; before that the same exports were + /// RynthAi's. Ask RynthLua first, then an older RynthAi that still has them. + /// </summary> + internal static IntPtr ResolveLua(string export) + { + IntPtr p = PluginExportBinder.Resolve("RynthLua", export); + return p != IntPtr.Zero ? p : PluginExportBinder.Resolve("RynthAi", export); + } + + protected internal override void Poll() + { + if (_getLuaJson == null) + _getLuaJson = (delegate* unmanaged[Cdecl]<IntPtr>)ResolveLua("RynthPluginGetLuaJson"); + if (_getLuaJson == null) return; + IntPtr ptr = _getLuaJson(); + string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(ptr); + if (string.IsNullOrEmpty(json) || json == _lastJson) return; + _lastJson = json; + LuaPayload? parsed = JsonSerializer.Deserialize(json, LuaJsonContext.Default.LuaPayload); + if (parsed != null) Publish(parsed); + } + + protected internal override void Reset() + { + _getLuaJson = null; + _lastJson = null; + ClearSnapshot(); + } +} + +/// <summary> +/// RynthPluginSendLuaCommand on the pump thread: run / stop / load / save / delete / clearConsole, +/// and RynthLua's select / start / restart / stopScript (Name), autostart (Code = none|global|character), +/// execin (Name, Code). +/// </summary> +internal static unsafe class LuaCommands +{ + private static delegate* unmanaged[Cdecl]<IntPtr, void> _send; + + static LuaCommands() + { + PluginManager.PluginsUnloaded += () => _send = null; + } + + public static void Send(string cmd, string name = "", string code = "") + { + var command = new LuaCmd { Cmd = cmd, Name = name, Code = code }; + UiDataHub.Post("Lua " + cmd, () => + { + if (_send == null) + _send = (delegate* unmanaged[Cdecl]<IntPtr, void>)LuaSource.ResolveLua("RynthPluginSendLuaCommand"); + if (_send == null) return; + string json = JsonSerializer.Serialize(command, LuaJsonContext.Default.LuaCmd); + IntPtr utf8 = Marshal.StringToCoTaskMemUTF8(json); + try { _send(utf8); } + finally { Marshal.FreeCoTaskMem(utf8); } + UiSources.Lua.RequestRefreshAfterPluginTick(); + }); + } +} diff --git a/src/RynthCore.Engine/UI/Data/MetaData.cs b/src/RynthCore.Engine/UI/Data/MetaData.cs new file mode 100644 index 0000000..ecdfa8c --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/MetaData.cs @@ -0,0 +1,456 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/MetaData.cs +// RynthAi's meta (rules, files, states, .af source) for both Meta faces +// (docs/IMGUI_PARITY_PLAN.md §2.13). +// +// RynthPluginGetMetaJson frees its previous buffer on each call, so the hub +// is its only caller. RynthPluginSendMetaCommand only queues: the plugin +// applies the command on its next tick, so a command defers the refresh to +// after that tick (UiSource.RequestRefreshAfterPluginTick) and the next +// snapshot already shows the result. +// +// The faces edit their own copies (Clone) for instant feedback; the next +// snapshot replaces the copy. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +internal sealed class MetaRuleDto +{ + public string State { get; set; } = "Default"; + public int Condition { get; set; } + public string ConditionData { get; set; } = string.Empty; + public int Action { get; set; } + public string ActionData { get; set; } = string.Empty; + public List<MetaRuleDto> Children { get; set; } = new(); + public List<MetaRuleDto> ActionChildren { get; set; } = new(); + public bool Enabled { get; set; } = true; + public long LastFiredMs { get; set; } = 99999; + + public MetaRuleDto Clone() + { + var r = new MetaRuleDto + { + State = State, Condition = Condition, ConditionData = ConditionData, + Action = Action, ActionData = ActionData, Enabled = Enabled, LastFiredMs = LastFiredMs, + }; + foreach (MetaRuleDto c in Children) r.Children.Add(c.Clone()); + foreach (MetaRuleDto a in ActionChildren) r.ActionChildren.Add(a.Clone()); + return r; + } +} + +internal sealed class MetaFile +{ + public string Path { get; set; } = string.Empty; + public string Display { get; set; } = string.Empty; +} + +/// <summary>The plugin's answer to the last Source "Apply" (set_source). Seq counts applies.</summary> +internal sealed class MetaApplyResult +{ + public long Seq { get; set; } + public bool Ok { get; set; } + public string Text { get; set; } = string.Empty; +} + +/// <summary> +/// One Meta Manager rule ("when TRIGGER, load META"): the settings the panel edits (also the +/// mm_add / mm_update wire format) plus the plugin's read-only status. +/// </summary> +internal sealed class ScheduleRuleDto +{ + public bool Enabled { get; set; } = true; + /// <summary>0 quest ready, 1 after N minutes on the meta, 2 every N minutes, 3 countdown.</summary> + public int Trigger { get; set; } + public string Quest { get; set; } = string.Empty; + public double Minutes { get; set; } = 30; + public string Meta { get; set; } = string.Empty; + public string OnlyOnMeta { get; set; } = string.Empty; + public bool Repeat { get; set; } = true; + + // Status (the plugin's; not sent back). + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool Fired { get; set; } + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public int FireCount { get; set; } + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public long LastFiredMs { get; set; } + /// <summary>When it is due (unix ms): 0 = not known / not running, -1 = never.</summary> + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public long DueAtMs { get; set; } + /// <summary>A few words ("waiting: combat", "error: ...") or empty when the due time says it all.</summary> + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? State { get; set; } + + internal ScheduleRuleDto MemberwiseCloneRule() => (ScheduleRuleDto)MemberwiseClone(); + + public ScheduleRuleDto CloneSettings() => new() + { + Enabled = Enabled, Trigger = Trigger, Quest = Quest, Minutes = Minutes, + Meta = Meta, OnlyOnMeta = OnlyOnMeta, Repeat = Repeat, + }; +} + +/// <summary>RynthAi's Meta Manager: its settings, poll state and rules (the "schedule" object).</summary> +internal sealed class SchedulePayload +{ + public bool Enabled { get; set; } + public int PollMinutes { get; set; } = 5; + public int MaxWaitSeconds { get; set; } = 60; + public int MinGapSeconds { get; set; } = 30; + public bool AllowWhileStopped { get; set; } + public bool Polling { get; set; } + public bool ServerDisabled { get; set; } + public bool HaveQuestList { get; set; } + public int QuestCount { get; set; } + public long LastPollMs { get; set; } + public string LastSwitch { get; set; } = string.Empty; + public long LastSwitchMs { get; set; } + /// <summary>The rule that fires next (first due rule, or the one waiting to switch); -1 none.</summary> + public int FirstMatch { get; set; } = -1; + public List<ScheduleRuleDto> Rules { get; set; } = new(); + + /// <summary>A copy the face may change for instant feedback (the snapshot stays as published).</summary> + public SchedulePayload Clone() + { + var p = (SchedulePayload)MemberwiseClone(); + p.Rules = new List<ScheduleRuleDto>(Rules.Count); + foreach (ScheduleRuleDto r in Rules) p.Rules.Add(r.MemberwiseCloneRule()); + return p; + } +} + +internal sealed class MetaPayload +{ + public bool EnableMeta { get; set; } + public bool MetaDebug { get; set; } + public string CurrentState { get; set; } = "Default"; + public string CurrentMetaPath { get; set; } = string.Empty; + public List<MetaRuleDto> Rules { get; set; } = new(); + public List<MetaFile> Files { get; set; } = new(); + public List<string> States { get; set; } = new(); + public List<string> NavFiles { get; set; } = new(); + public List<string> EmbeddedNavKeys { get; set; } = new(); + public string SourceText { get; set; } = string.Empty; + /// <summary>Null from a plugin that doesn't report apply results yet (it reports to chat).</summary> + public MetaApplyResult? ApplyResult { get; set; } + /// <summary>The Meta Manager; null from a RynthAi without it.</summary> + public SchedulePayload? Schedule { get; set; } + + /// <summary>Deep copy of the rules; the rest is shared (faces never change it).</summary> + public MetaPayload Clone() + { + var p = (MetaPayload)MemberwiseClone(); + p.Rules = new List<MetaRuleDto>(Rules.Count); + foreach (MetaRuleDto r in Rules) p.Rules.Add(r.Clone()); + p.Schedule = Schedule?.Clone(); + return p; + } +} + +internal sealed class MetaCmd +{ + public string Op { get; set; } = string.Empty; + public int Index { get; set; } = -1; + public string Value { get; set; } = string.Empty; + public string Path { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; + public MetaRuleDto? Rule { get; set; } + /// <summary>mm_add / mm_update: the Meta Manager rule (settings only).</summary> + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ScheduleRuleDto? ScheduleRule { get; set; } +} + +[JsonSerializable(typeof(MetaPayload))] +[JsonSerializable(typeof(MetaCmd))] +[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)] +internal partial class MetaJsonContext : JsonSerializerContext { } + +/// <summary>RynthPluginGetMetaJson while a Meta face is open (2 s, and after each command).</summary> +internal sealed unsafe class MetaSource : UiSource<MetaPayload> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _getMetaJson; + private string? _lastJson; + + public MetaSource() : base("Meta", periodMs: 2000) { } + + protected internal override void Poll() + { + if (_getMetaJson == null) + _getMetaJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetMetaJson"); + if (_getMetaJson == null) return; + IntPtr ptr = _getMetaJson(); + string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr); + if (string.IsNullOrEmpty(json) || json == _lastJson) return; + _lastJson = json; + MetaPayload? parsed = JsonSerializer.Deserialize(json, MetaJsonContext.Default.MetaPayload); + if (parsed != null) Publish(parsed); + } + + protected internal override void Reset() + { + _getMetaJson = null; + _lastJson = null; + ClearSnapshot(); + } +} + +/// <summary>RynthPluginSendMetaCommand on the pump thread. Any thread may call Send.</summary> +internal static unsafe class MetaCommands +{ + private static delegate* unmanaged[Cdecl]<IntPtr, void> _sendMetaCommand; + + static MetaCommands() + { + PluginManager.PluginsUnloaded += () => _sendMetaCommand = null; + } + + /// <summary><paramref name="cmd"/> (and its Rule) must not be changed after this call.</summary> + public static void Send(MetaCmd cmd) + { + UiDataHub.Post("Meta " + cmd.Op, () => + { + if (_sendMetaCommand == null) + _sendMetaCommand = (delegate* unmanaged[Cdecl]<IntPtr, void>)PluginExportBinder.Resolve("RynthAi", "RynthPluginSendMetaCommand"); + if (_sendMetaCommand == null) return; + string json = JsonSerializer.Serialize(cmd, MetaJsonContext.Default.MetaCmd); + IntPtr ansi = Marshal.StringToHGlobalAnsi(json); + try { _sendMetaCommand(ansi); } + finally { Marshal.FreeHGlobal(ansi); } + UiSources.Meta.RequestRefreshAfterPluginTick(); + }); + } + + public static void Simple(string op, int index = -1, string value = "", string path = "") + => Send(new MetaCmd { Op = op, Index = index, Value = value, Path = path }); +} + +/// <summary>Names, hints and .af keywords shared by the Meta faces (mirror RynthSuite's MetaSchema).</summary> +internal static class MetaVocabulary +{ + /// <summary>RynthAi's meta folder under the installed RynthSuite folder (installer-chosen).</summary> + public static string MetaFolder => System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles"); + + public static readonly string[] ConditionNames = + { + "Never", "Always", "All", "Any", "Chat Message", "Pack Slots <=", + "Seconds in State >=", "Character Death", "Any Vendor Open", + "Vendor Closed", "Inventory Item Count <=", "Inventory Item Count >=", + "Monster Name Count Within Dist", "Monster Priority Count Within Dist", + "Need To Buff", "No Monsters Within Dist", "Landblock ==", + "Landcell ==", "Portalspace Entered", "Portalspace Exited", "Not", + "Seconds in State (P) >=", "Time Left On Spell >=", "Time Left On Spell <=", + "Burden % >=", "Dist Any Route PT >=", "Expression", + "Chat Message Capture", "Navroute Empty", + "Main Health <=", "Main Health % >=", "Main Mana <=", "Main Mana % >=", + "Main Stam <=", "Vitae % >=", + }; + + public static readonly string[] ConditionHints = + { + "", "", "(sub-conditions)", "(sub-conditions)", "Regex pattern", "Min slots (e.g. 5)", + "Seconds (e.g. 10)", "", "", "", + "name,count (e.g. Mana Stone,5)", "name,count (e.g. Mana Stone,5)", + "name regex,distance,count", "count,distance (e.g. 1,20)", + "", "Distance (e.g. 20)", "Hex (e.g. A9B40000)", "Hex (e.g. A9B40000)", + "", "", "(sub-conditions)", "Seconds (e.g. 10)", + "spellId,seconds (e.g. 2293,30)", "spellId,seconds (e.g. 2293,30)", + "Percentage (e.g. 250)", "Distance (e.g. 10)", "Expression", + "Regex pattern", "", + "", "", "", "", "", "Vitae % (e.g. 5)", + }; + + public static readonly string[] ActionNames = + { + "None", "Chat Command", "Set Meta State", "Embedded Nav Route", "All", + "Call Meta State", "Return From Call", "Expression Action", "Chat Expression", + "Set Watchdog", "Clear Watchdog", "Get RA Option", "Set RA Option", + "Create View", "Destroy View", "Destroy All Views", + }; + + public static readonly string[] ActionHints = + { + "", "e.g. /say hello", "State name", "Route name", "(sub-actions)", + "State name", "", "Expression", "Expression", + "state;meters;seconds (e.g. Default;10;60)", "", "Option name", "OptionName;Value", + "", "", "", + }; + + // ── .af source keywords (keyword form, as written in the file) ────────── + public static readonly string[] StructKeywords = { "STATE", "IF", "DO", "NAV" }; + + public static readonly string[] ConditionKeywords = + { + "Never", "Always", "All", "Any", "ChatMatch", "MainSlotsLE", + "SecsInStateGE", "Death", "VendorOpen", "VendorClosed", + "ItemCountLE", "ItemCountGE", + "MobsInDist_Name", "MobsInDist_Priority", + "NeedToBuff", "NoMobsInDist", "BlockE", "CellE", + "IntoPortal", "ExitPortal", "Not", + "PSecsInStateGE", "SecsOnSpellGE", "SecsOnSpellLE", + "BuPercentGE", "DistToRteGE", "Expr", + "ChatCapture", "NavEmpty", + "MainHealthLE", "MainHealthPHE", "MainManaLE", "MainManaPHE", + "MainStamLE", "VitaePHE", + }; + + public static readonly string[] ActionKeywords = + { + "None", "Chat", "SetState", "EmbedNav", "DoAll", + "CallState", "Return", "DoExpr", "ChatExpr", + "SetWatchdog", "ClearWatchdog", "GetOpt", "SetOpt", + "CreateView", "DestroyView", "DestroyAllViews", + }; + + /// <summary>All=2, Any=3, Not=20 hold sub-conditions.</summary> + public static bool IsCompositeCondition(int idx) => idx is 2 or 3 or 20; + + /// <summary>All (DoAll) = 4 holds sub-actions.</summary> + public static bool IsAllAction(int idx) => idx == 4; + + /// <summary>Sub-conditions nest this deep (Not/All/Any under Not/All/Any).</summary> + public const int MaxSubConditionDepth = 4; + + public static string ConditionName(int idx) => + idx >= 0 && idx < ConditionNames.Length ? ConditionNames[idx] : $"Cond({idx})"; + + public static string ActionName(int idx) => + idx >= 0 && idx < ActionNames.Length ? ActionNames[idx] : $"Act({idx})"; + + public static string ConditionHint(int idx) => + idx >= 0 && idx < ConditionHints.Length ? ConditionHints[idx] : ""; + + public static string ActionHint(int idx) => + idx >= 0 && idx < ActionHints.Length ? ActionHints[idx] : ""; + + /// <summary>One condition as text, nested ones included: "Not No Monsters Within Dist: 5", "Any(Chat Message: …, Navroute Empty)".</summary> + public static string CondText(MetaRuleDto c, int depth = 0) + { + string name = ConditionName(c.Condition); + if (IsCompositeCondition(c.Condition) && c.Children.Count > 0 && depth < MaxSubConditionDepth) + { + if (c.Condition == 20) return $"Not {CondText(c.Children[0], depth + 1)}"; + var sb = new StringBuilder(name).Append('('); + for (int i = 0; i < c.Children.Count; i++) + { + if (i > 0) sb.Append(", "); + sb.Append(CondText(c.Children[i], depth + 1)); + } + return sb.Append(')').ToString(); + } + return string.IsNullOrEmpty(c.ConditionData) ? name : $"{name}: {c.ConditionData}"; + } + + public static string ActText(MetaRuleDto a) + { + string name = ActionName(a.Action); + return string.IsNullOrEmpty(a.ActionData) ? name : $"{name}: {a.ActionData}"; + } + + /// <summary>A rule row's condition column: composite ones show the first child and "(+N)".</summary> + public static string RowConditionText(MetaRuleDto rule) + { + string name = ConditionName(rule.Condition); + if (IsCompositeCondition(rule.Condition) && rule.Children.Count > 0) + { + string first = CondText(rule.Children[0]); + return rule.Children.Count > 1 ? $"{name}: {first} (+{rule.Children.Count - 1})" : $"{name}: {first}"; + } + return string.IsNullOrEmpty(rule.ConditionData) ? name : $"{name}: {rule.ConditionData}"; + } + + /// <summary>A rule row's action column: DoAll shows the first sub-action and "(+N)".</summary> + public static string RowActionText(MetaRuleDto rule) + { + string name = ActionName(rule.Action); + if (IsAllAction(rule.Action) && rule.ActionChildren.Count > 0) + { + string first = ActText(rule.ActionChildren[0]); + return rule.ActionChildren.Count > 1 ? $"{name}: {first} (+{rule.ActionChildren.Count - 1})" : $"{name}: {first}"; + } + return string.IsNullOrEmpty(rule.ActionData) ? name : $"{name}: {rule.ActionData}"; + } + + /// <summary>The state picker's list: the meta's states, with Default first if it is missing.</summary> + public static string[] StatePicks(MetaPayload d) + { + var states = new List<string>(d.States); + if (!states.Contains("Default")) states.Insert(0, "Default"); + return states.ToArray(); + } + + /// <summary>Embedded Nav's route picker: nav files, then "[emb] key" for embedded routes.</summary> + public static string[] RoutePicks(MetaPayload d) + { + var routes = new List<string>(); + foreach (string n in d.NavFiles) if (n != "None") routes.Add(n); + foreach (string k in d.EmbeddedNavKeys) if (!routes.Contains(k)) routes.Add($"[emb] {k}"); + return routes.ToArray(); + } + + /// <summary>Nav names for source completion (nav files and embedded keys, no duplicates).</summary> + public static IReadOnlyList<string> CompletionNavs(MetaPayload d) + { + var combined = new List<string>(d.NavFiles.Count + d.EmbeddedNavKeys.Count); + combined.AddRange(d.NavFiles); + foreach (string n in d.EmbeddedNavKeys) if (!combined.Contains(n)) combined.Add(n); + return combined; + } + + /// <summary>The file picker's current entry; "-- None --" without a loaded file.</summary> + public static string CurrentFileDisplay(MetaPayload d) + { + if (!string.IsNullOrEmpty(d.CurrentMetaPath) && d.Files.Count > 1) + foreach (MetaFile f in d.Files) + if (string.Equals(f.Path, d.CurrentMetaPath, StringComparison.OrdinalIgnoreCase)) + return f.Display; + return "-- None --"; + } + + public static int CurrentFileIndex(MetaPayload d) + { + if (string.IsNullOrEmpty(d.CurrentMetaPath)) return 0; + return d.Files.FindIndex(f => string.Equals(f.Path, d.CurrentMetaPath, StringComparison.OrdinalIgnoreCase)); + } + + /// <summary> + /// The rule list grouped by state (sorted by state name), each group's rules + /// in list order: the order the plugin's move_up/move_down swap within. + /// </summary> + public static List<(string State, List<int> Rules)> GroupByState(List<MetaRuleDto> rules) + { + var byState = new Dictionary<string, List<int>>(); + var order = new List<string>(); + for (int i = 0; i < rules.Count; i++) + { + string s = rules[i].State; + if (!byState.TryGetValue(s, out List<int>? list)) + { + byState[s] = list = new List<int>(); + order.Add(s); + } + list.Add(i); + } + order.Sort(StringComparer.CurrentCulture); + var groups = new List<(string, List<int>)>(order.Count); + foreach (string s in order) groups.Add((s, byState[s])); + return groups; + } + + /// <summary> + /// The rule index move_up (-1) or move_down (+1) swaps <paramref name="index"/> + /// with: the neighbour in the same state, or -1 at the group's end. + /// </summary> + public static int SwapPartner(List<MetaRuleDto> rules, int index, int direction) + { + if (index < 0 || index >= rules.Count) return -1; + string state = rules[index].State; + for (int j = index + direction; j >= 0 && j < rules.Count; j += direction) + if (string.Equals(rules[j].State, state, StringComparison.Ordinal)) + return j; + return -1; + } +} diff --git a/src/RynthCore.Engine/UI/Data/NavData.cs b/src/RynthCore.Engine/UI/Data/NavData.cs new file mode 100644 index 0000000..43f2ad3 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/NavData.cs @@ -0,0 +1,144 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/NavData.cs +// RynthAi's nav route (active nav, status, route type, waypoints, nav files) +// for both Nav faces. +// +// RynthPluginGetNavJson frees its previous buffer on each call, so the hub is +// its only caller (NavSource, 1 s). Commands go through +// RynthAiCommands.SendNavCommand on the pump; the plugin applies them on the +// spot, so the next poll (requested right after) shows the result. ANSI JSON. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RynthCore.Engine.UI.Data; + +internal sealed class NavPoint +{ + public int Idx { get; set; } + public string Type { get; set; } = string.Empty; + public string Desc { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; // Chat points: the command (editable) + public double NS { get; set; } + public double EW { get; set; } + public double Z { get; set; } +} + +internal sealed class NavPayload +{ + public string ActiveNavName { get; set; } = string.Empty; + public string NavStatusLine { get; set; } = string.Empty; + public bool NavIsStuck { get; set; } + public bool MacroRunning { get; set; } + public bool NavigationEnabled { get; set; } + public int RouteType { get; set; } + public int ActiveNavIndex { get; set; } + public List<string> NavFiles { get; set; } = new(); + public List<NavPoint> Points { get; set; } = new(); + /// <summary>RynthAi records (and draws) the walked breadcrumb trail. Older plugins omit it (false).</summary> + public bool TrackBreadcrumbs { get; set; } + /// <summary>RynthAi draws the route overlay (rings / lines, waypoint labels, guide line).</summary> + public bool ShowRouteOverlay { get; set; } + + /// <summary>A copy a face may change (its own point list); the points themselves are shared.</summary> + public NavPayload Clone() + { + var c = (NavPayload)MemberwiseClone(); + c.Points = new List<NavPoint>(Points); + return c; + } +} + +internal sealed class NavCmd +{ + public string Cmd { get; set; } = string.Empty; + public int SpellId { get; set; } + public int Index { get; set; } + public int RouteType { get; set; } + public int AddMode { get; set; } + public int InsertAt { get; set; } = -1; + public string NavName { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; // addChat + public bool On { get; set; } // setBreadcrumbs / setRouteOverlay +} + +[JsonSerializable(typeof(NavPayload))] +[JsonSerializable(typeof(NavCmd))] +[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)] +internal partial class NavJsonContext : JsonSerializerContext { } + +/// <summary>RynthPluginGetNavJson while a Nav face is open (1 s, and after each command).</summary> +internal sealed unsafe class NavSource : UiSource<NavPayload> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _getNavJson; + private string? _lastJson; + + public NavSource() : base("Nav", periodMs: 1000) { } + + protected internal override void Poll() + { + if (_getNavJson == null) + _getNavJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetNavJson"); + if (_getNavJson == null) return; + IntPtr ptr = _getNavJson(); + string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr); + if (string.IsNullOrEmpty(json) || json == _lastJson) return; + _lastJson = json; + NavPayload? parsed = JsonSerializer.Deserialize(json, NavJsonContext.Default.NavPayload); + if (parsed != null) Publish(parsed); + } + + protected internal override void Reset() + { + _getNavJson = null; + _lastJson = null; + ClearSnapshot(); + } +} + +/// <summary>Nav panel commands and vocabulary, shared by both faces.</summary> +internal static class NavCommands +{ + public static void Send(NavCmd cmd) => + RynthAiCommands.SendNavCommand(JsonSerializer.Serialize(cmd, NavJsonContext.Default.NavCmd)); + + public static readonly string[] RouteTypes = { "Once", "Circular", "Linear", "Follow" }; + public static readonly string[] AddModes = { "End", "Above", "Below" }; + + /// <summary>Route picker index for the plugin's RouteType (1 Circular, 2 Linear, 3 Follow, else Once).</summary> + public static int RouteIndex(int routeType) => routeType switch { 1 => 1, 2 => 2, 3 => 3, _ => 0 }; + + /// <summary>The plugin's RouteType for a route picker index (Once = 4).</summary> + public static int RouteTypeFor(int index) => index switch { 1 => 1, 2 => 2, 3 => 3, _ => 4 }; + + public static readonly int[] RecallIds = + { + 48, 2645, 2647, + 1635, 1636, + 157, 158, 1637, + 2648, 2649, 2650, + 2931, 2023, 2041, 2358, 2813, 2941, 2943, + 3865, 3929, 3930, 4084, 4198, 4213, + 4907, 4908, 4909, + 5175, 5330, 5541, 6150, 6321, 6322, + }; + + public static readonly string[] RecallLabels = BuildRecallLabels(); + + private static string[] BuildRecallLabels() + { + var labels = new string[RecallIds.Length]; + for (int i = 0; i < labels.Length; i++) labels[i] = $"Spell {RecallIds[i]} ({RecallIds[i]})"; + return labels; + } + + /// <summary>"[3] Recall ..." or "[3] Point (12.34N, 56.78E, 12.3)".</summary> + public static string PointText(NavPoint pt, int i) => + !string.IsNullOrEmpty(pt.Desc) + ? $"[{i}] {pt.Desc}" + : $"[{i}] {pt.Type} ({pt.NS:F2}N, {pt.EW:F2}E, {pt.Z:F1})"; +} diff --git a/src/RynthCore.Engine/UI/Data/PanelSources.cs b/src/RynthCore.Engine/UI/Data/PanelSources.cs new file mode 100644 index 0000000..103ac9d --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/PanelSources.cs @@ -0,0 +1,135 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/PanelSources.cs +// Hub sources for the P1 panels (Log, Tracker). Both faces of a panel read +// the same snapshot; display strings are formatted here, on the pump thread, +// so drawing allocates nothing. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>The engine's recent-log ring with the sequence number of its last line.</summary> +internal sealed record LogSnapshot(string[] Lines, long LastSeq) +{ + /// <summary>Sequence number of Lines[0].</summary> + public long FirstSeq => LastSeq - Lines.Length + 1; +} + +internal sealed class LogSource : UiSource<LogSnapshot> +{ + public LogSource() : base("Log", periodMs: 1000) { } + + protected internal override void Poll() + { + if (Current is { } cur && cur.Value.LastSeq == EntryPoint.RecentLogSeq) return; + string[] lines = EntryPoint.GetRecentLogLines(out long lastSeq); + Publish(new LogSnapshot(lines, lastSeq)); + } +} + +/// <summary>The Tracker panel's rows, formatted: nine, plus two Radiance rows on Aelrynth once earned.</summary> +internal sealed record TrackerSnapshot(string[] Labels, string[] Values) +{ + public static readonly string[] DefaultLabels = { "Session", "XP/hr", "Lum/hr", "Kls/hr", "XP", "Lum", "Kills", "XP/kl", "Deaths" }; +} + +/// <summary> +/// RynthTracker's RynthTrackerGetSnapshotJson (single consumer: it frees the +/// previous buffer on each call, so only the hub may call it). +/// </summary> +internal sealed unsafe class TrackerSource : UiSource<TrackerSnapshot> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _getSnapshotJson; + private delegate* unmanaged[Cdecl]<void> _reset; + private string? _lastJson; + + public TrackerSource() : base("Tracker", periodMs: 500) { } + + /// <summary>Resets the session counters (RynthTrackerReset). Any thread; runs on the pump.</summary> + public void RequestReset() + { + UiDataHub.Post("Tracker reset", () => + { + Bind(); + if (_reset != null) _reset(); + RequestRefresh(); + }); + } + + protected internal override void Poll() + { + Bind(); + if (_getSnapshotJson == null) return; + + IntPtr ptr = _getSnapshotJson(); + string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr); // copy now: freed on the next call + if (string.IsNullOrEmpty(json) || json == _lastJson) return; + _lastJson = json; + + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement r = doc.RootElement; + double Num(string key) => r.TryGetProperty(key, out JsonElement v) && v.TryGetDouble(out double d) ? d : 0; + + CultureInfo ic = CultureInfo.InvariantCulture; + // At the level cap the server adds no experience, so the XP rows say so instead of 0. + bool maxLevel = Num("ml") > 0; + string Xp(long v) => maxLevel ? "max level" : FormatNum(v); + var labels = new List<string> { "Session", "XP/hr", "Lum/hr" }; + var values = new List<string> { FormatTime(Num("ss")), Xp((long)Num("xh")), FormatNum((long)Num("lh")) }; + // Radiance (Aelrynth's Bank session total): rows only once some has been earned. + long rad = (long)Num("rt"); + if (rad > 0) { labels.Add("Rad/hr"); values.Add(FormatNum((long)Num("rh"))); } + labels.AddRange(new[] { "Kls/hr", "XP", "Lum" }); + values.AddRange(new[] { Num("kh").ToString("F1", ic), Xp((long)Num("xt")), FormatNum((long)Num("lt")) }); + if (rad > 0) { labels.Add("Rad"); values.Add(FormatNum(rad)); } + labels.AddRange(new[] { "Kills", "XP/kl", "Deaths" }); + values.AddRange(new[] { ((long)Num("kt")).ToString(ic), Xp((long)Num("xk")), ((long)Num("dt")).ToString(ic) }); + Publish(new TrackerSnapshot(labels.ToArray(), values.ToArray())); + } + + protected internal override void Reset() + { + _getSnapshotJson = null; + _reset = null; + _lastJson = null; + ClearSnapshot(); + } + + private void Bind() + { + if (_getSnapshotJson == null) + _getSnapshotJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthTracker", "RynthTrackerGetSnapshotJson"); + if (_reset == null) + _reset = (delegate* unmanaged[Cdecl]<void>)PluginExportBinder.Resolve("RynthTracker", "RynthTrackerReset"); + } + + // Same formatting as the Avalonia Tracker had. + private static string FormatTime(double totalSeconds) + { + var ts = TimeSpan.FromSeconds(totalSeconds); + return ts.TotalHours >= 1 + ? $"{(int)ts.TotalHours}:{ts.Minutes:D2}:{ts.Seconds:D2}" + : $"{ts.Minutes}:{ts.Seconds:D2}"; + } + + private static string FormatNum(long value) + { + if (value == 0) return "0"; + bool neg = value < 0; + string s = (neg ? -value : value).ToString(CultureInfo.InvariantCulture); + var sb = new StringBuilder(s.Length + s.Length / 3); + int offset = s.Length % 3; + for (int i = 0; i < s.Length; i++) + { + if (i > 0 && (i - offset) % 3 == 0) sb.Append(','); + sb.Append(s[i]); + } + return neg ? "-" + sb : sb.ToString(); + } +} diff --git a/src/RynthCore.Engine/UI/Data/PluginExportBinder.cs b/src/RynthCore.Engine/UI/Data/PluginExportBinder.cs new file mode 100644 index 0000000..000c5b3 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/PluginExportBinder.cs @@ -0,0 +1,48 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/PluginExportBinder.cs +// Resolves a plugin's C export for a UiSource. Pump thread only. +// +// Plugin exports are [UnmanagedCallersOnly] cdecl functions; sources call +// them through `delegate* unmanaged[Cdecl]<...>` pointers (no delegate +// marshalling). Resolving on AC's render thread is refused and logged: plugin +// code on AC's thread is the fail-fast crash class (4b70ef1). +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +internal static class PluginExportBinder +{ + // Managed plugins (CoreCLR engine) answer from their export map; see ManagedPlugins. + private static IntPtr GetProcAddress(IntPtr hModule, string procName) => Plugins.ManagedPlugins.GetProcAddress(hModule, procName); + + private static int _acThreadRefusals; + + /// <summary> + /// The export <paramref name="exportName"/> of the first loaded plugin whose + /// display name contains <paramref name="pluginNamePart"/>, or zero when the + /// plugin isn't loaded (or doesn't have it). + /// </summary> + public static IntPtr Resolve(string pluginNamePart, string exportName) + { + if (MainThreadGuard.IsOnMainThread()) + { + if (_acThreadRefusals++ < 5) + RynthLog.UI($"PluginExportBinder: refused to bind {exportName} on AC's thread; plugin exports are called from UiDataHub only."); + return IntPtr.Zero; + } + + // PluginManager mutates its list on this (pump) thread, so reading it here is race-free. + foreach (LoadedPlugin plugin in PluginManager.Plugins) + { + if (plugin.ModuleHandle == IntPtr.Zero) continue; + if (!plugin.DisplayName.Contains(pluginNamePart, StringComparison.OrdinalIgnoreCase)) continue; + return GetProcAddress(plugin.ModuleHandle, exportName); + } + return IntPtr.Zero; + } +} diff --git a/src/RynthCore.Engine/UI/Data/ProgressionData.cs b/src/RynthCore.Engine/UI/Data/ProgressionData.cs new file mode 100644 index 0000000..60bef5a --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ProgressionData.cs @@ -0,0 +1,105 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ProgressionData.cs +// RynthAi's ILT progression planners (augmentations, enlightenment) for the +// Skills panel's Progression tab. RynthAi owns the math and the persisted +// inputs; this side only shows the snapshot and sends "prog ..." remote +// commands (RynthAiCommands.ApplyRemoteCommand) for edits and actions. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>RynthPluginGetProgressionJson's payload. Display strings arrive preformatted.</summary> +internal sealed class ProgressionInfo +{ + /// <summary>False off ILT-like worlds (or before the ILT Hub exists): the tab is hidden.</summary> + [JsonPropertyName("available")] public bool Available { get; set; } + [JsonPropertyName("world")] public string World { get; set; } = ""; + [JsonPropertyName("aug")] public AugPlanner Aug { get; set; } = new(); + [JsonPropertyName("enl")] public EnlPlanner Enl { get; set; } = new(); +} + +internal sealed class AugPlanner +{ + /// <summary>The server reports /aug off.</summary> + [JsonPropertyName("off")] public bool Off { get; set; } + [JsonPropertyName("status")] public string Status { get; set; } = ""; + [JsonPropertyName("lumPerCoin")] public long LumPerCoin { get; set; } + [JsonPropertyName("rows")] public AugRow[] Rows { get; set; } = Array.Empty<AugRow>(); + [JsonPropertyName("total")] public string Total { get; set; } = ""; + /// <summary>Empty when the bank holds enough Enlightened Coins.</summary> + [JsonPropertyName("short")] public string Short { get; set; } = ""; + [JsonPropertyName("banked")] public string Banked { get; set; } = ""; +} + +internal sealed class AugRow +{ + [JsonPropertyName("key")] public string Key { get; set; } = ""; + [JsonPropertyName("label")] public string Label { get; set; } = ""; + [JsonPropertyName("cur")] public int Current { get; set; } + [JsonPropertyName("tgt")] public int Target { get; set; } + /// <summary>Highest target allowed (the aug's cap, or the current level when the server reports more).</summary> + [JsonPropertyName("cap")] public int Cap { get; set; } + [JsonPropertyName("lum")] public string Lum { get; set; } = "-"; + [JsonPropertyName("coins")] public long Coins { get; set; } +} + +internal sealed class EnlPlanner +{ + /// <summary>The server reports /enl off.</summary> + [JsonPropertyName("off")] public bool Off { get; set; } + [JsonPropertyName("header")] public string Header { get; set; } = ""; + [JsonPropertyName("next")] public string Next { get; set; } = ""; + [JsonPropertyName("enl")] public int Level { get; set; } + [JsonPropertyName("target")] public int Target { get; set; } + [JsonPropertyName("plan")] public string[] Plan { get; set; } = Array.Empty<string>(); + [JsonPropertyName("coinsPerToken")] public int CoinsPerToken { get; set; } + [JsonPropertyName("tokensShort")] public string TokensShort { get; set; } = ""; + /// <summary>Client-side requirements not yet met; empty = the client checks pass.</summary> + [JsonPropertyName("blockers")] public string[] Blockers { get; set; } = Array.Empty<string>(); + [JsonPropertyName("serverChecks")] public string ServerChecks { get; set; } = ""; + [JsonPropertyName("auto")] public bool Auto { get; set; } + /// <summary>Auto-enlighten is disarmed every session until confirmed again.</summary> + [JsonPropertyName("armed")] public bool Armed { get; set; } + [JsonPropertyName("spendFirst")] public bool SpendFirst { get; set; } + [JsonPropertyName("checkEvery")] public int CheckEvery { get; set; } + [JsonPropertyName("status")] public string Status { get; set; } = ""; +} + +[JsonSerializable(typeof(ProgressionInfo))] +internal sealed partial class ProgressionJsonContext : JsonSerializerContext { } + +/// <summary> +/// RynthPluginGetProgressionJson (single static buffer: one caller only) while the Skills +/// panel is open, and right after each Progression edit (RequestRefreshAfterPluginTick). +/// </summary> +internal sealed unsafe class ProgressionSource : UiSource<ProgressionInfo> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _getProgressionJson; + + public ProgressionSource() : base("Progression", periodMs: 1000) { } + + protected internal override void Poll() + { + if (_getProgressionJson == null) + _getProgressionJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetProgressionJson"); + if (_getProgressionJson == null) return; + IntPtr p = _getProgressionJson(); + string json = p == IntPtr.Zero ? "{}" : Marshal.PtrToStringAnsi(p) ?? "{}"; + ProgressionInfo info; + try { info = JsonSerializer.Deserialize(json, ProgressionJsonContext.Default.ProgressionInfo) ?? new ProgressionInfo(); } + catch (JsonException) { info = new ProgressionInfo(); } + Publish(info); + } + + protected internal override void Reset() + { + _getProgressionJson = null; + ClearSnapshot(); + } +} diff --git a/src/RynthCore.Engine/UI/Data/RadarData.cs b/src/RynthCore.Engine/UI/Data/RadarData.cs new file mode 100644 index 0000000..3dd2218 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/RadarData.cs @@ -0,0 +1,185 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/RadarData.cs +// The radar's data (docs/IMGUI_PARITY_PLAN.md §2.2), shared by its Avalonia +// face (UI/Panels/RadarPanel.cs) and ImGui face (ImGui/Panels/RadarFace.cs). +// +// RadarSource calls RynthPluginGetRadarSnapshot at 33 ms on the pump thread +// while a radar face is open. Walls/fills only travel when the landblock +// changes (the export skips them when told the cached MapVersion), so the +// source keeps that cache - the logic moved here from the Avalonia panel's +// timer - and publishes a RadarView with per-layer lookups and the current +// layer's wall "visited" flags precomputed, so drawing does no dictionary +// or point-in-strip work per frame. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.UI.Data; + +// The snapshot DTOs (RadarSnapshot, RadarMarker, ...) are in RadarSnapshotJson.cs. + +/// <summary>What either radar face draws: the live snapshot plus cached geometry and lookups.</summary> +internal sealed class RadarView +{ + public required RadarSnapshot Live { get; init; } + public required List<RadarWallLayer> Walls { get; init; } + public required List<RadarFillLayer> Fills { get; init; } + + /// <summary>Index into Live.LayerZs of the layer the player is on (-1: none).</summary> + public required int CurrentLayer { get; init; } + /// <summary>Per layer index (parallel to Live.LayerZs): its walls / fill strips / visited strips, or null.</summary> + public required float[]?[] WallsByLayer { get; init; } + public required float[]?[] FillsByLayer { get; init; } + public required float[]?[] VisitedByLayer { get; init; } + /// <summary>Per wall of the current layer: true when its midpoint is in a visited strip (drawn blue).</summary> + public required bool[]? CurrentWallVisited { get; init; } + /// <summary>"LB AABB Z 12.3" indoors, "33.1N 44.8E Z 12.3" outdoors.</summary> + public required string CoordText { get; init; } +} + +internal sealed unsafe class RadarSource : UiSource<RadarView> +{ + private delegate* unmanaged[Cdecl]<uint, IntPtr> _getRadarSnapshot; + private uint _cachedMapVersion; + private List<RadarWallLayer> _cachedWalls = new(); + private List<RadarFillLayer> _cachedFills = new(); + private string? _lastJson; + + // Wall "visited" flags depend only on the current layer's walls and visited + // strips; recompute when either changes, not on every pose update. + private float[]? _visitedKeyStrips; + private float[]? _visitedKeyWalls; + private bool[]? _visitedFlags; + + public RadarSource() : base("Radar", periodMs: 33) { } + + protected internal override void Poll() + { + if (_getRadarSnapshot == null) + _getRadarSnapshot = (delegate* unmanaged[Cdecl]<uint, IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetRadarSnapshot"); + if (_getRadarSnapshot == null) return; + + IntPtr ptr = _getRadarSnapshot(_cachedMapVersion); + string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr); // copy now: freed on the next call + if (string.IsNullOrEmpty(json) || json == "{}" || json == _lastJson) return; + _lastJson = json; + + RadarSnapshot? fresh = RadarSnapshot.Parse(json); + if (fresh == null) return; + + if (fresh.GeometryIncluded) + { + _cachedMapVersion = fresh.MapVersion; + _cachedWalls = fresh.Walls; + _cachedFills = fresh.Fills; + } + else if (fresh.MapVersion != _cachedMapVersion && fresh.MapVersion != 0 && !fresh.IsIndoor) + { + // Outdoor landblocks carry no geometry but still bump the version: + // drop stale walls so they don't bleed through indoor -> outdoor. + _cachedMapVersion = fresh.MapVersion; + _cachedWalls = new List<RadarWallLayer>(); + _cachedFills = new List<RadarFillLayer>(); + } + + // First polls after login can land before raycast is ready: an indoor + // snapshot with no walls. Re-ask with version 0 until geometry arrives, + // or the plugin keeps skipping it and the radar stays blank. + if (fresh.IsIndoor && _cachedWalls.Count == 0) + _cachedMapVersion = 0; + + Publish(BuildView(fresh)); + } + + protected internal override void Reset() + { + _getRadarSnapshot = null; + _cachedMapVersion = 0; + _cachedWalls = new List<RadarWallLayer>(); + _cachedFills = new List<RadarFillLayer>(); + _lastJson = null; + _visitedKeyStrips = _visitedKeyWalls = null; + _visitedFlags = null; + ClearSnapshot(); + } + + private RadarView BuildView(RadarSnapshot live) + { + List<float> layers = live.LayerZs; + int cur = -1; + if (layers.Count > 0) + { + cur = 0; + float best = MathF.Abs(layers[0] - live.CurrentLayerZ); + for (int i = 1; i < layers.Count; i++) + { + float d = MathF.Abs(layers[i] - live.CurrentLayerZ); + if (d < best) { best = d; cur = i; } + } + } + + var walls = new float[]?[layers.Count]; + var fills = new float[]?[layers.Count]; + var visited = new float[]?[layers.Count]; + for (int i = 0; i < layers.Count; i++) + { + float z = layers[i]; + foreach (RadarWallLayer w in _cachedWalls) if (w.Z == z) { walls[i] = w.Segments; break; } + foreach (RadarFillLayer f in _cachedFills) if (f.Z == z) { fills[i] = f.Strips; break; } + foreach (RadarVisitedLayer v in live.Visited) if (v.Z == z) { visited[i] = v.Strips; break; } + } + + bool[]? wallVisited = null; + if (cur >= 0 && walls[cur] is float[] curWalls && visited[cur] is float[] curVisited) + { + if (!ReferenceEquals(curWalls, _visitedKeyWalls) || _visitedKeyStrips == null + || !curVisited.AsSpan().SequenceEqual(_visitedKeyStrips)) + { + _visitedKeyWalls = curWalls; + _visitedKeyStrips = curVisited; + _visitedFlags = new bool[curWalls.Length / 6]; + for (int w = 0; w < _visitedFlags.Length; w++) + { + float mx = (curWalls[w * 6] + curWalls[w * 6 + 2]) * 0.5f; + float my = (curWalls[w * 6 + 1] + curWalls[w * 6 + 3]) * 0.5f; + _visitedFlags[w] = PointInStrips(mx, my, curVisited); + } + } + wallVisited = _visitedFlags; + } + + return new RadarView + { + Live = live, + Walls = _cachedWalls, + Fills = _cachedFills, + CurrentLayer = cur, + WallsByLayer = walls, + FillsByLayer = fills, + VisitedByLayer = visited, + CurrentWallVisited = wallVisited, + CoordText = FormatCoords(live), + }; + } + + private static bool PointInStrips(float x, float y, float[] strips) + { + for (int i = 0; i + 3 < strips.Length; i += 4) + if (x >= strips[i] && x <= strips[i + 2] && y >= strips[i + 1] && y <= strips[i + 3]) + return true; + return false; + } + + // Same readout as the ImGui-era and Avalonia radars. + private static string FormatCoords(RadarSnapshot s) + { + RadarPlayer p = s.Player; + if (s.IsIndoor) + return $"LB {p.Landblock:X4} Z {p.Z:0.0}"; + if (!double.IsNaN(s.Ns) && !double.IsNaN(s.Ew)) + return $"{Math.Abs(s.Ns):0.0}{(s.Ns >= 0 ? "N" : "S")} {Math.Abs(s.Ew):0.0}{(s.Ew >= 0 ? "E" : "W")} Z {p.Z:0.0}"; + return $"Z {p.Z:0.0}"; + } +} diff --git a/src/RynthCore.Engine/UI/Data/RadarSnapshotJson.cs b/src/RynthCore.Engine/UI/Data/RadarSnapshotJson.cs new file mode 100644 index 0000000..8ddb4c7 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/RadarSnapshotJson.cs @@ -0,0 +1,136 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/RadarSnapshotJson.cs +// The radar snapshot's JSON shape, as RynthAi's RynthPluginGetRadarSnapshot +// writes it (mirrors RynthCore.Plugin.RynthAi.LegacyUi.RadarSnapshotPayload). +// Split out of RadarData.cs so it stays self-contained: RynthSuite's +// RynthAiHostTests links this file to check the plugin's output parses here. +// +// Compatibility: System.Text.Json skips properties it doesn't know (the +// default, never set to Disallow here), and a missing property keeps its +// default. So fields can be added on either side: an older engine ignores +// a newer plugin's extra fields, and a newer engine reads an older plugin's +// snapshot with the new fields at their defaults (marker Id = 0: unknown). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RynthCore.Engine.UI.Data; + +internal sealed class RadarSnapshot +{ + [JsonPropertyName("mapVersion")] public uint MapVersion { get; set; } + [JsonPropertyName("geometryIncluded")] public bool GeometryIncluded { get; set; } + [JsonPropertyName("isIndoor")] public bool IsIndoor { get; set; } + [JsonPropertyName("player")] public RadarPlayer Player { get; set; } = new(); + [JsonPropertyName("ns")] public double Ns { get; set; } = double.NaN; + [JsonPropertyName("ew")] public double Ew { get; set; } = double.NaN; + [JsonPropertyName("layerZs")] public List<float> LayerZs { get; set; } = new(); + [JsonPropertyName("currentLayerZ")] public float CurrentLayerZ { get; set; } + [JsonPropertyName("walls")] public List<RadarWallLayer> Walls { get; set; } = new(); + [JsonPropertyName("fills")] public List<RadarFillLayer> Fills { get; set; } = new(); + [JsonPropertyName("visited")] public List<RadarVisitedLayer> Visited { get; set; } = new(); + [JsonPropertyName("markers")] public List<RadarMarker> Markers { get; set; } = new(); + + /// <summary>Parses one RynthPluginGetRadarSnapshot reply; null for "null". Throws on malformed JSON.</summary> + public static RadarSnapshot? Parse(string json) => + JsonSerializer.Deserialize(json, RadarJsonContext.Default.RadarSnapshot); +} + +internal sealed class RadarPlayer +{ + [JsonPropertyName("cellId")] public uint CellId { get; set; } + [JsonPropertyName("landblock")] public uint Landblock { get; set; } + [JsonPropertyName("x")] public float X { get; set; } + [JsonPropertyName("y")] public float Y { get; set; } + [JsonPropertyName("z")] public float Z { get; set; } + [JsonPropertyName("worldX")] public float WorldX { get; set; } + [JsonPropertyName("worldY")] public float WorldY { get; set; } + [JsonPropertyName("heading")] public float Heading { get; set; } +} + +internal sealed class RadarWallLayer +{ + [JsonPropertyName("z")] public float Z { get; set; } + /// <summary>6 floats per wall: ax, ay, bx, by, cellX, cellY.</summary> + [JsonPropertyName("segments")] public float[] Segments { get; set; } = Array.Empty<float>(); +} + +internal sealed class RadarFillLayer +{ + [JsonPropertyName("z")] public float Z { get; set; } + /// <summary>5 floats per strip: x0, y0, x1, y1, type (0 flat, 1 slope up, 2 slope down).</summary> + [JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty<float>(); +} + +internal sealed class RadarVisitedLayer +{ + [JsonPropertyName("z")] public float Z { get; set; } + /// <summary>4 floats per strip: x0, y0, x1, y1.</summary> + [JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty<float>(); +} + +/// <summary> +/// Marker kinds (RadarMarker.Kind). 0-3 are the original four; 4 and up were added +/// 2026-10-04 and are only sent by RynthAi builds from then on, so a newer engine +/// reading an older RynthAi simply never sees them. An older engine drops kinds it +/// doesn't know (its ShowKind returns false). Numbers never change meaning: new kinds +/// are appended. +/// </summary> +internal static class RadarKind +{ + public const byte Monster = 0; + public const byte Npc = 1; + public const byte Portal = 2; + public const byte Door = 3; + public const byte Player = 4; // another player + public const byte Fellow = 5; // a player in your fellowship + public const byte Pet = 6; // your own combat pet / summon + public const byte Vendor = 7; + public const byte Corpse = 8; // someone else's corpse (or not yet identified) + public const byte OwnCorpse = 9; // a corpse you may loot: your kill, a fellow's kill, or your own + public const byte Lifestone = 10; + public const byte GroundItem = 11; // an item lying on the ground + public const int Count = 12; + + /// <summary>A creature (has health, can be hovered for a health reading).</summary> + public static bool IsCreature(byte kind) => + kind is Monster or Npc or Player or Fellow or Pet or Vendor; + + /// <summary>Singular name, for the hover tooltip when a marker has no label.</summary> + public static string Name(byte kind) => kind switch + { + Monster => "Monster", + Npc => "NPC", + Portal => "Portal", + Door => "Door", + Player => "Player", + Fellow => "Fellow", + Pet => "Your pet", + Vendor => "Vendor", + Corpse => "Corpse", + OwnCorpse => "Your corpse", + Lifestone => "Lifestone", + GroundItem => "Item", + _ => "Object", + }; +} + +internal sealed class RadarMarker +{ + /// <summary>A <see cref="RadarKind"/>: 0 monster, 1 NPC, 2 portal, 3 door, 4 player, 5 fellow, + /// 6 your pet, 7 vendor, 8 corpse, 9 your corpse, 10 lifestone, 11 item on the ground.</summary> + [JsonPropertyName("kind")] public byte Kind { get; set; } + [JsonPropertyName("x")] public float X { get; set; } + [JsonPropertyName("y")] public float Y { get; set; } + [JsonPropertyName("z")] public float Z { get; set; } + [JsonPropertyName("label")] public string? Label { get; set; } + /// <summary>The object's id (RynthAi 2026-10-01 and later); 0 from older RynthAi builds.</summary> + [JsonPropertyName("id")] public uint Id { get; set; } +} + +[JsonSerializable(typeof(RadarSnapshot))] +[JsonSourceGenerationOptions(WriteIndented = false)] +internal partial class RadarJsonContext : JsonSerializerContext { } diff --git a/src/RynthCore.Engine/UI/Data/RynthAiData.cs b/src/RynthCore.Engine/UI/Data/RynthAiData.cs new file mode 100644 index 0000000..4f02cb4 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/RynthAiData.cs @@ -0,0 +1,416 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/RynthAiData.cs +// The RynthAi dashboard's data (docs/IMGUI_PARITY_PLAN.md §2.1), shared by +// its Avalonia face (UI/Panels/RynthAiPanel.cs) and ImGui face. +// +// RynthAiSource polls RynthPluginGetSnapshotJson at 33 ms on the pump thread +// (the same thread as RynthAi's tick, so no race with the plugin) and +// publishes a RynthAiView: the raw fields plus every display string, sticky +// vitals applied. RynthAiCommands runs the dashboard's mutating exports on +// the pump too. PatrolSource fetches the patrol flyout's data on demand. +// ============================================================================ + +using System; +using System.Globalization; +using System.IO; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>RynthPluginGetSnapshotJson's fields the dashboard uses.</summary> +internal sealed class RynthAiSnapshot +{ + [JsonPropertyName("macroRunning")] public bool MacroRunning { get; set; } + [JsonPropertyName("currentState")] public string CurrentState { get; set; } = string.Empty; + [JsonPropertyName("botAction")] public string BotAction { get; set; } = string.Empty; + [JsonPropertyName("selectedProfile")] public string SelectedProfile { get; set; } = "Default"; + [JsonPropertyName("profiles")] public string[] Profiles { get; set; } = Array.Empty<string>(); + [JsonPropertyName("navProfiles")] public string[] NavProfiles { get; set; } = Array.Empty<string>(); + [JsonPropertyName("lootProfiles")] public string[] LootProfiles { get; set; } = Array.Empty<string>(); + [JsonPropertyName("metaProfiles")] public string[] MetaProfiles { get; set; } = Array.Empty<string>(); + [JsonPropertyName("currentNavName")] public string CurrentNavName { get; set; } = string.Empty; + [JsonPropertyName("currentLootName")] public string CurrentLootName { get; set; } = string.Empty; + [JsonPropertyName("currentLootPath")] public string CurrentLootPath { get; set; } = string.Empty; + // Set while a vendor is open: the AutoVendor profile it would use (may not exist yet). + [JsonPropertyName("vendorProfilePath")] public string VendorProfilePath { get; set; } = string.Empty; + [JsonPropertyName("currentMetaName")] public string CurrentMetaName { get; set; } = string.Empty; + [JsonPropertyName("selectedNavIdx")] public int SelectedNavIdx { get; set; } + [JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; } + [JsonPropertyName("selectedMetaIdx")] public int SelectedMetaIdx { get; set; } + [JsonPropertyName("selectedProfileIdx")] public int SelectedProfileIdx { get; set; } + [JsonPropertyName("combatEnabled")] public bool CombatEnabled { get; set; } + [JsonPropertyName("buffingEnabled")] public bool BuffingEnabled { get; set; } + [JsonPropertyName("navigationEnabled")] public bool NavigationEnabled { get; set; } + [JsonPropertyName("lootingEnabled")] public bool LootingEnabled { get; set; } + [JsonPropertyName("metaEnabled")] public bool MetaEnabled { get; set; } + [JsonPropertyName("currentTargetId")] public uint CurrentTargetId { get; set; } + [JsonPropertyName("targetLabel")] public string TargetLabel { get; set; } = "NO TARGET"; + [JsonPropertyName("targetHealthPercent")] public float TargetHealthPercent { get; set; } + [JsonPropertyName("targetHealthDisplay")] public string TargetHealthDisplay { get; set; } = "0"; + [JsonPropertyName("targetHealth")] public uint TargetHealth { get; set; } + [JsonPropertyName("targetMaxHealth")] public uint TargetMaxHealth { get; set; } + [JsonPropertyName("targetStamina")] public uint TargetStamina { get; set; } + [JsonPropertyName("targetMaxStamina")] public uint TargetMaxStamina { get; set; } + [JsonPropertyName("targetMana")] public uint TargetMana { get; set; } + [JsonPropertyName("targetMaxMana")] public uint TargetMaxMana { get; set; } + [JsonPropertyName("playerHealth")] public uint PlayerHealth { get; set; } + [JsonPropertyName("playerMaxHealth")] public uint PlayerMaxHealth { get; set; } + [JsonPropertyName("playerStamina")] public uint PlayerStamina { get; set; } + [JsonPropertyName("playerMaxStamina")] public uint PlayerMaxStamina { get; set; } + [JsonPropertyName("playerMana")] public uint PlayerMana { get; set; } + [JsonPropertyName("playerMaxMana")] public uint PlayerMaxMana { get; set; } + [JsonPropertyName("showTargetStaminaMana")] public bool ShowTargetStaminaMana { get; set; } + [JsonPropertyName("isLocked")] public bool IsLocked { get; set; } + [JsonPropertyName("isMinimized")] public bool IsMinimized { get; set; } + [JsonPropertyName("bgOpacity")] public float BgOpacity { get; set; } = 0.95f; +} + +[JsonSerializable(typeof(RynthAiSnapshot))] +internal sealed partial class RynthAiSnapshotJsonContext : JsonSerializerContext { } + +/// <summary>A vital bar: fill fraction and its text ("HP: 92% (314/341)").</summary> +internal readonly record struct VitalView(float Fraction, string Text); + +/// <summary>Everything either dashboard face draws, formatted on the pump thread.</summary> +internal sealed class RynthAiView +{ + public required RynthAiSnapshot Raw { get; init; } + public required string Version { get; init; } + public required string MetaStateText { get; init; } + public required string BotActivityText { get; init; } + public required string ProfileText { get; init; } + public required string NavText { get; init; } + public required string LootText { get; init; } + public required string MetaText { get; init; } + public required string TargetHeadline { get; init; } + public required int TargetSegmentsLit { get; init; } + public required bool ShowTargetSubBars { get; init; } + public required VitalView TargetStamina { get; init; } + public required VitalView TargetMana { get; init; } + public required VitalView Health { get; init; } + public required VitalView Stamina { get; init; } + public required VitalView Mana { get; init; } + /// <summary>Combat box background alpha 0-255 (the header +/- chips; floor 10%).</summary> + public required byte PanelAlpha { get; init; } + + public const int Segments = 15; +} + +/// <summary>RynthPluginGetSnapshotJson at 33 ms while a dashboard face is open.</summary> +internal sealed unsafe class RynthAiSource : UiSource<RynthAiView> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _getSnapshotJson; + private string? _lastJson; + private string _version = ""; + private long _versionTicks; + + public RynthAiSource() : base("RynthAi", periodMs: 33) { } + + protected internal override void Poll() + { + if (_getSnapshotJson == null) + _getSnapshotJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetSnapshotJson"); + if (_getSnapshotJson == null) return; + + long now = Environment.TickCount64; + bool versionChanged = false; + if (now - _versionTicks > 2000) + { + _versionTicks = now; + string ver = ""; + foreach (LoadedPlugin p in PluginManager.Plugins) + if (p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)) { ver = p.VersionString; break; } + versionChanged = ver != _version; + _version = ver; + } + + IntPtr ptr = _getSnapshotJson(); + string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr); + if (string.IsNullOrWhiteSpace(json)) return; + if (json == _lastJson && !versionChanged) return; + _lastJson = json; + + RynthAiSnapshot snap = JsonSerializer.Deserialize(json, RynthAiSnapshotJsonContext.Default.RynthAiSnapshot) ?? new RynthAiSnapshot(); + Publish(BuildView(snap, _version)); + } + + protected internal override void Reset() + { + _getSnapshotJson = null; + _lastJson = null; + ClearSnapshot(); + } + + private static RynthAiView BuildView(RynthAiSnapshot s, string version) + { + StickyVitals.Update(s); + string label = string.IsNullOrWhiteSpace(s.TargetLabel) ? "NO TARGET" : s.TargetLabel.ToUpperInvariant(); + bool showSub = s.ShowTargetStaminaMana && s.TargetMaxStamina > 0; + float pct = Math.Clamp(s.TargetHealthPercent, 0f, 1f); + int lit = 0; + for (int i = 0; i < RynthAiView.Segments; i++) + if ((float)i / RynthAiView.Segments <= pct) lit++; + + return new RynthAiView + { + Raw = s, + Version = version, + MetaStateText = string.IsNullOrWhiteSpace(s.CurrentState) ? "Default" : s.CurrentState, + BotActivityText = string.IsNullOrWhiteSpace(s.BotAction) || s.BotAction == "Default" ? "Idle" : s.BotAction, + ProfileText = Truncate(s.SelectedProfile, 16), + NavText = Truncate(s.CurrentNavName, 16), + LootText = Truncate(s.CurrentLootName, 16), + MetaText = Truncate(s.CurrentMetaName, 16), + TargetHeadline = Truncate(label, 32), + TargetSegmentsLit = lit, + ShowTargetSubBars = showSub, + TargetStamina = showSub ? Compact("ST", s.TargetStamina, s.TargetMaxStamina) : default, + TargetMana = showSub ? Compact("MN", s.TargetMana, s.TargetMaxMana) : default, + Health = Vital("HP", StickyVitals.Hp, StickyVitals.MaxHp), + Stamina = Vital("ST", StickyVitals.St, StickyVitals.MaxSt), + Mana = Vital("MN", StickyVitals.Mn, StickyVitals.MaxMn), + PanelAlpha = (byte)Math.Clamp(Math.Round(s.BgOpacity * 255f), 25.5, 255), + }; + } + + private static VitalView Vital(string label, uint v, uint max) + { + float pct = max == 0 ? 0 : Math.Clamp((float)v / max, 0, 1); + string display = max == 0 ? (v == 0 ? "--/--" : $"{v}/--") : $"{v}/{max}"; + return new VitalView(pct, $"{label}: {(int)(pct * 100)}% ({display})"); + } + + private static VitalView Compact(string prefix, uint v, uint max) => + new(max == 0 ? 0 : Math.Clamp((float)v / max, 0, 1), $"{prefix} {v}/{max}"); + + internal static string Truncate(string? value, int max) + { + if (string.IsNullOrEmpty(value)) return "None"; + return value.Length > max ? value[..(max - 1)] + "…" : value; + } +} + +/// <summary> +/// Last-known good vitals, so a hot reload (when the plugin's vital cache is +/// cold for a tick or two) doesn't show 0/0. Persisted to vitals.cache, at +/// most once a second, off the pump thread. +/// </summary> +internal static class StickyVitals +{ + public static uint Hp, MaxHp, St, MaxSt, Mn, MaxMn; + private static bool _loaded; + private static long _lastSaved; + + private static string CachePath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "vitals.cache"); + + /// <summary>Pump thread (RynthAiSource.Poll).</summary> + public static void Update(RynthAiSnapshot s) + { + if (!_loaded) Load(); + bool changed = false; + if (s.PlayerMaxHealth != 0) { changed |= Hp != s.PlayerHealth || MaxHp != s.PlayerMaxHealth; Hp = s.PlayerHealth; MaxHp = s.PlayerMaxHealth; } + if (s.PlayerMaxStamina != 0) { changed |= St != s.PlayerStamina || MaxSt != s.PlayerMaxStamina; St = s.PlayerStamina; MaxSt = s.PlayerMaxStamina; } + if (s.PlayerMaxMana != 0) { changed |= Mn != s.PlayerMana || MaxMn != s.PlayerMaxMana; Mn = s.PlayerMana; MaxMn = s.PlayerMaxMana; } + if (!changed) return; + + long now = Environment.TickCount64; + if (now - _lastSaved < 1000) return; + _lastSaved = now; + string text = $"{Hp},{MaxHp},{St},{MaxSt},{Mn},{MaxMn}"; + UiBackgroundWriter.Enqueue("vitals cache", () => + { + try + { + string path = CachePath; + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, text); + } + catch { } + }); + } + + private static void Load() + { + _loaded = true; + try + { + string path = CachePath; + if (!File.Exists(path)) return; + string[] p = File.ReadAllText(path).Split(','); + if (p.Length < 6) return; + CultureInfo ic = CultureInfo.InvariantCulture; + Hp = uint.Parse(p[0], ic); MaxHp = uint.Parse(p[1], ic); + St = uint.Parse(p[2], ic); MaxSt = uint.Parse(p[3], ic); + Mn = uint.Parse(p[4], ic); MaxMn = uint.Parse(p[5], ic); + } + catch { } + } +} + +/// <summary> +/// The dashboard's mutating exports, run on the pump thread (UiDataHub.Post). +/// Any thread may call these; each refreshes the snapshot afterwards. +/// </summary> +internal static unsafe class RynthAiCommands +{ + private static delegate* unmanaged[Cdecl]<void> _toggleMacro; + private static delegate* unmanaged[Cdecl]<int, int, void> _setSubsystemEnabled; + private static delegate* unmanaged[Cdecl]<int, int, void> _selectProfile; + private static delegate* unmanaged[Cdecl]<void> _forceRebuff; + private static delegate* unmanaged[Cdecl]<void> _cancelForceRebuff; + private static delegate* unmanaged[Cdecl]<float, void> _adjustOpacity; + private static delegate* unmanaged[Cdecl]<void> _togglePanelLock; + private static delegate* unmanaged[Cdecl]<IntPtr, void> _sendNavCommand; + private static delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void> _applyRemoteCommand; + + static RynthAiCommands() + { + PluginManager.PluginsUnloaded += () => + { + _toggleMacro = null; _setSubsystemEnabled = null; _selectProfile = null; _forceRebuff = null; + _cancelForceRebuff = null; _adjustOpacity = null; _togglePanelLock = null; _sendNavCommand = null; + _applyRemoteCommand = null; + }; + } + + private static IntPtr Export(string name) => PluginExportBinder.Resolve("RynthAi", name); + + private static void Run(string label, Action action) + { + UiDataHub.Post("RynthAi " + label, () => + { + action(); + UiSources.RynthAi.RequestRefresh(); + }); + } + + public static void ToggleMacro() => Run("toggle macro", () => + { + if (_toggleMacro == null) _toggleMacro = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginToggleMacro"); + if (_toggleMacro != null) _toggleMacro(); + }); + + /// <summary>0 Combat, 1 Buff, 2 Nav, 3 Loot, 4 Meta.</summary> + public static void SetSubsystemEnabled(int id, bool on) => Run("subsystem", () => + { + if (_setSubsystemEnabled == null) _setSubsystemEnabled = (delegate* unmanaged[Cdecl]<int, int, void>)Export("RynthPluginSetSubsystemEnabled"); + if (_setSubsystemEnabled != null) _setSubsystemEnabled(id, on ? 1 : 0); + }); + + /// <summary>kind: 0 nav, 1 loot, 2 meta, 3 profile.</summary> + public static void SelectProfile(int kind, int index) => Run("select profile", () => + { + if (_selectProfile == null) _selectProfile = (delegate* unmanaged[Cdecl]<int, int, void>)Export("RynthPluginSelectProfile"); + if (_selectProfile != null) _selectProfile(kind, index); + }); + + public static void ForceRebuff() => Run("force rebuff", () => + { + if (_forceRebuff == null) _forceRebuff = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginForceRebuff"); + if (_forceRebuff != null) _forceRebuff(); + }); + + public static void CancelForceRebuff() => Run("cancel force rebuff", () => + { + if (_cancelForceRebuff == null) _cancelForceRebuff = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginCancelForceRebuff"); + if (_cancelForceRebuff != null) _cancelForceRebuff(); + }); + + public static void AdjustOpacity(float delta) => Run("opacity", () => + { + if (_adjustOpacity == null) _adjustOpacity = (delegate* unmanaged[Cdecl]<float, void>)Export("RynthPluginAdjustOpacity"); + if (_adjustOpacity != null) _adjustOpacity(delta); + }); + + public static void TogglePanelLock() => Run("lock", () => + { + if (_togglePanelLock == null) _togglePanelLock = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginTogglePanelLock"); + if (_togglePanelLock != null) _togglePanelLock(); + }); + + /// <summary>RynthPluginSendNavCommand with a JSON command ({"Cmd":"dunPatrol"} ...).</summary> + public static void SendNavCommand(string json, bool refreshPatrol = false) => Run("nav command", () => + { + if (_sendNavCommand == null) _sendNavCommand = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthPluginSendNavCommand"); + if (_sendNavCommand == null) return; + IntPtr p = Marshal.StringToHGlobalAnsi(json); + try { _sendNavCommand(p); } + finally { Marshal.FreeHGlobal(p); } + if (refreshPatrol) UiSources.Patrol.RequestRefresh(); + UiSources.Nav.RequestRefresh(); // the plugin applied it: the Nav panels show it next poll + }); + + /// <summary> + /// RynthPluginApplyRemoteCommand(action, value) - the same (action, value) pairs as the + /// plugin's /ra chat commands ("huds","show"; "remote","toggle"; "hub","show" ...). + /// Older RynthAi builds without the export drop the command (logged once per bind miss). + /// </summary> + public static void ApplyRemoteCommand(string action, string value) => Run("remote command " + action, () => + { + if (_applyRemoteCommand == null) _applyRemoteCommand = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)Export("RynthPluginApplyRemoteCommand"); + if (_applyRemoteCommand == null) + { + RynthLog.UI($"RynthAiCommands: RynthPluginApplyRemoteCommand not exported; dropped '{action} {value}'."); + return; + } + IntPtr a = Marshal.StringToHGlobalAnsi(action); + IntPtr b = Marshal.StringToHGlobalAnsi(value); + try { _applyRemoteCommand(a, b); } + finally + { + Marshal.FreeHGlobal(a); + Marshal.FreeHGlobal(b); + } + }); +} + +/// <summary>RynthPluginGetPatrolInfoJson's payload (patrol flyout).</summary> +internal sealed class PatrolInfo +{ + [JsonPropertyName("inDungeon")] public bool InDungeon { get; set; } + [JsonPropertyName("currentLandblock")] public string CurrentLandblock { get; set; } = "0000"; + [JsonPropertyName("currentHazards")] public int CurrentHazards { get; set; } + [JsonPropertyName("liveHazards")] public int LiveHazards { get; set; } + [JsonPropertyName("dungeons")] public DungeonHazards[] Dungeons { get; set; } = Array.Empty<DungeonHazards>(); + [JsonPropertyName("routes")] public string[] Routes { get; set; } = Array.Empty<string>(); +} + +internal sealed class DungeonHazards +{ + [JsonPropertyName("landblock")] public string Landblock { get; set; } = "0000"; + [JsonPropertyName("cells")] public int Cells { get; set; } +} + +[JsonSerializable(typeof(PatrolInfo))] +internal sealed partial class PatrolInfoJsonContext : JsonSerializerContext { } + +/// <summary> +/// RynthPluginGetPatrolInfoJson (single static buffer: one caller only) while +/// the patrol flyout is open, and right after each patrol action. +/// </summary> +internal sealed unsafe class PatrolSource : UiSource<PatrolInfo> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _getPatrolInfoJson; + + public PatrolSource() : base("Patrol", periodMs: 2000) { } + + protected internal override void Poll() + { + if (_getPatrolInfoJson == null) + _getPatrolInfoJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetPatrolInfoJson"); + if (_getPatrolInfoJson == null) return; + IntPtr p = _getPatrolInfoJson(); + string json = p == IntPtr.Zero ? "{}" : Marshal.PtrToStringAnsi(p) ?? "{}"; + Publish(JsonSerializer.Deserialize(json, PatrolInfoJsonContext.Default.PatrolInfo) ?? new PatrolInfo()); + } + + protected internal override void Reset() + { + _getPatrolInfoJson = null; + ClearSnapshot(); + } +} diff --git a/src/RynthCore.Engine/UI/Data/RynthNavAtlasData.cs b/src/RynthCore.Engine/UI/Data/RynthNavAtlasData.cs new file mode 100644 index 0000000..a286b38 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/RynthNavAtlasData.cs @@ -0,0 +1,395 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/RynthNavAtlasData.cs +// The Go and Atlas tabs' data: RynthNav's location database (NavData\locations.json, +// made by tools\navdata\gen_locations.py from the world database), read here +// read-only so thousands of places don't travel through the status JSON +// (RynthNav itself owns favorites, recent, the arrow and routing). The file's +// path comes from RynthNav's status, so both read the same file. +// +// RynthNavAtlas the loaded places (a background load, UiBackgroundWriter), +// and the player's map position from the pose snapshot. +// RynthNavAtlasSource the rows the face shows for its query (search by name +// and type, typed coordinates as the first row, Nearby, +// Favorites, Recent; Saved = favorites then recent, the Go +// tab's list while its box is empty), worked out on +// the pump thread twice a second and only when the query, +// the data or your position (by 3 yd) changed. +// +// Map coordinates are the /loc numbers (north and east positive); distances are +// in yards (world units, 240 per degree). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text.Json; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>One place from locations.json, with its display strings.</summary> +internal sealed class NavPlace +{ + public int Id; + public string Name = "", Type = "", Desc = "", Place = "", Lb = "", Cell = ""; + public bool OnMap; + public double Ns, Ew; + public bool HasDest, DestOnMap; + public double DestNs, DestEw; + public string DestName = ""; + public int MinLevel, MaxLevel; + public bool Quest, Closed; + public string CoordText = "", DestText = "", LevelText = ""; +} + +/// <summary>Saved: favorites, then recent places (the Go tab's list while its box is empty).</summary> +internal enum AtlasMode { Search, Nearby, Favorites, Recent, Saved } + +internal sealed record AtlasQuery(string Text, string Type, AtlasMode Mode); + +internal sealed class AtlasRow +{ + public required string Name, Type, Coord; + public string Dist = ""; + /// <summary>"Town · 1.2k yd NE": the type and distance, for the Go tab's short list.</summary> + public string Meta = ""; + public double Distance = double.PositiveInfinity; + public bool OnMap, Favorite; + public double Ns, Ew; + /// <summary>The Atlas entry, when the row is one (a favorite or recent may not be).</summary> + public NavPlace? Place; +} + +internal sealed class AtlasView +{ + public static readonly AtlasView Empty = new(Array.Empty<AtlasRow>(), ""); + public AtlasView(AtlasRow[] rows, string summary) { Rows = rows; Summary = summary; } + public AtlasRow[] Rows { get; } + public string Summary { get; } +} + +internal static class RynthNavAtlas +{ + public static readonly string[] Types = + { "All", "Town", "Dungeon", "Portal", "Lifestone", "Bindstone", "Vendor", "NPC", "Landmark" }; + + private static readonly object Sync = new(); + private static string _requested = ""; + private static volatile NavPlace[] _places = Array.Empty<NavPlace>(); + private static volatile HashSet<uint> _mapLandblocks = new(); + private static volatile string _status = ""; + private static long _version; + + public static NavPlace[] Places => _places; + public static string Status => _status; + public static long Version => System.Threading.Interlocked.Read(ref _version); + + /// <summary>Loads <paramref name="path"/> in the background unless it is already loaded or on its way. Any thread.</summary> + public static void EnsureLoaded(string path) + { + if (string.IsNullOrEmpty(path)) return; + lock (Sync) + { + if (path == _requested) return; + _requested = path; + } + _status = "loading the Atlas…"; + UiBackgroundWriter.Enqueue("RynthNav atlas (load)", () => Load(path)); + } + + private static void Load(string path) + { + try + { + if (!File.Exists(path)) { _status = "No Atlas: " + path + " is missing."; return; } + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + var list = new List<NavPlace>(); + var lbs = new HashSet<uint>(); + if (doc.RootElement.TryGetProperty("locations", out var arr) && arr.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement e in arr.EnumerateArray()) + { + var p = new NavPlace + { + Id = Int(e, "id"), Name = Str(e, "name"), Type = Str(e, "type"), Desc = Str(e, "desc"), + Place = Str(e, "place"), Lb = Str(e, "lb"), Cell = Str(e, "cell"), + MinLevel = Int(e, "minLevel"), MaxLevel = Int(e, "maxLevel"), + Quest = e.TryGetProperty("quest", out var q) && q.ValueKind == JsonValueKind.True, + Closed = e.TryGetProperty("closed", out var c) && c.ValueKind == JsonValueKind.True, + }; + p.OnMap = TryNum(e, "ns", out p.Ns) & TryNum(e, "ew", out p.Ew); + if (e.TryGetProperty("dest", out var d) && d.ValueKind == JsonValueKind.Object) + { + p.HasDest = true; + p.DestOnMap = TryNum(d, "ns", out p.DestNs) & TryNum(d, "ew", out p.DestEw); + p.DestName = Str(d, "name"); + p.DestText = p.DestOnMap ? RynthNavStatus.Coord(p.DestNs, p.DestEw) + : p.DestName.Length > 0 ? p.DestName + " (a dungeon)" : "a dungeon"; + } + p.CoordText = p.OnMap ? RynthNavStatus.Coord(p.Ns, p.Ew) : "in a dungeon"; + p.LevelText = p.MinLevel > 0 && p.MaxLevel > 0 ? $"levels {p.MinLevel}–{p.MaxLevel}" + : p.MinLevel > 0 ? $"level {p.MinLevel}+" : p.MaxLevel > 0 ? $"up to level {p.MaxLevel}" : ""; + if (p.OnMap && p.Cell.Length == 8 && uint.TryParse(p.Cell.AsSpan(0, 4), NumberStyles.HexNumber, null, out uint lb)) + lbs.Add(lb); + list.Add(p); + } + } + _places = list.ToArray(); + _mapLandblocks = lbs; + string generated = doc.RootElement.TryGetProperty("generated", out var g) ? g.GetString() ?? "" : ""; + _status = $"{list.Count} places" + (generated.Length >= 10 ? ", from " + generated.Substring(0, 10) : ""); + System.Threading.Interlocked.Increment(ref _version); + } + catch (Exception ex) + { + _status = "The Atlas didn't load: " + ex.Message; + lock (Sync) _requested = ""; // try again on the next request + } + } + + /// <summary> + /// Your map position from the pose snapshot (no AC call). <paramref name="onMap"/> is + /// false in a dungeon, where the numbers aren't real map coordinates. + /// </summary> + public static bool TryPlayerPos(out double ns, out double ew, out bool onMap, out uint cell) + { + ns = ew = 0; onMap = false; + if (!PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out cell, out float x, out float y, out _, out _, out _, out _, out _) + || (cell >> 16) == 0) + return false; + int lbX = (int)((cell >> 24) & 0xFF), lbY = (int)((cell >> 16) & 0xFF); + ew = (lbX * 8.0 + x / 24.0 - 1019.5) / 10.0; + ns = (lbY * 8.0 + y / 24.0 - 1019.5) / 10.0; + onMap = (cell & 0xFFFF) < 0x100 || _mapLandblocks.Contains(cell >> 16); + return true; + } + + public static double Distance(double ns1, double ew1, double ns2, double ew2) + { + double dn = (ns2 - ns1) * 240.0, de = (ew2 - ew1) * 240.0; + return Math.Sqrt(dn * dn + de * de); + } + + /// <summary>Compass bearing: 0 = north, clockwise.</summary> + public static double Bearing(double fromNs, double fromEw, double toNs, double toEw) + { + double b = Math.Atan2(toEw - fromEw, toNs - fromNs) * 180.0 / Math.PI; + return b < 0 ? b + 360.0 : b; + } + + private static readonly string[] Compass16 = + { "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW" }; + + public static string CompassPoint(double bearing) => Compass16[(int)Math.Round(((bearing % 360.0) + 360.0) % 360.0 / 22.5) & 15]; + + /// <summary>How well a name matches a search (RynthNav's Atlas.MatchScore): 0 = not at all.</summary> + public static int MatchScore(string name, string q) + { + if (q.Length == 0) return 1; + if (name.Equals(q, StringComparison.OrdinalIgnoreCase)) return 100; + int at = name.IndexOf(q, StringComparison.OrdinalIgnoreCase); + if (at == 0) return 80; + if (at > 0) return char.IsLetterOrDigit(name[at - 1]) ? 40 : 60; + string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (words.Length < 2) return 0; + foreach (string w in words) + if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return 0; + return 30; + } + + public static int TypeRank(string type) => type switch + { + "Town" => 0, "Dungeon" => 1, "Landmark" => 2, "Lifestone" => 3, "Bindstone" => 4, + "Portal" => 5, "Vendor" => 6, "NPC" => 7, _ => 8, + }; + + private static string Str(JsonElement e, string name) => + e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; + + private static int Int(JsonElement e, string name) => + e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : 0; + + private static bool TryNum(JsonElement e, string name, out double d) + { + d = 0; + return e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out d); + } +} + +/// <summary>The Go or Atlas tab's rows for <see cref="Query"/> (pump thread, 500 ms, while either tab is open).</summary> +internal sealed class RynthNavAtlasSource : UiSource<AtlasView> +{ + private const int MaxRows = 300; + + /// <summary>What the Go or Atlas tab asks for (the one showing). Set by the face (AC's thread), read here.</summary> + public static volatile AtlasQuery Query = new("", "All", AtlasMode.Search); + + private AtlasQuery? _seenQuery; + private long _seenAtlas = -1, _seenStatus = -1; + private double _seenNs = double.NaN, _seenEw = double.NaN; + + public RynthNavAtlasSource() : base("RynthNavAtlas", periodMs: 500) { } + + protected internal override void Poll() + { + UiSnapshot<RynthNavStatus>? stSnap = UiSources.RynthNav.Current; + RynthNavStatus? st = stSnap?.Value; + if (st != null && st.AtlasPath.Length > 0) RynthNavAtlas.EnsureLoaded(st.AtlasPath); + + AtlasQuery q = Query; + bool hasPos = RynthNavAtlas.TryPlayerPos(out double pns, out double pew, out bool onMap, out _); + hasPos &= onMap; + long atlasV = RynthNavAtlas.Version, statusV = stSnap?.Version ?? -1; + bool moved = hasPos != !double.IsNaN(_seenNs) + || (hasPos && RynthNavAtlas.Distance(pns, pew, _seenNs, _seenEw) > 3); + // The status moves with favorites (the stars) and recent, so it counts for every mode. + if (q == _seenQuery && atlasV == _seenAtlas && !moved && statusV == _seenStatus && Current != null) + return; + _seenQuery = q; _seenAtlas = atlasV; _seenStatus = statusV; + _seenNs = hasPos ? pns : double.NaN; _seenEw = hasPos ? pew : double.NaN; + + var favorites = st?.Favorites ?? Array.Empty<RynthNavPlace>(); + NavPlace[] places = RynthNavAtlas.Places; + var rows = new List<AtlasRow>(); + string summary; + switch (q.Mode) + { + case AtlasMode.Saved: + { + // Favorites first, then recent places that aren't favorites (each place once). + foreach (RynthNavPlace s in favorites) rows.Add(SavedRow(places, s)); + foreach (RynthNavPlace s in st?.Recent ?? Array.Empty<RynthNavPlace>()) + { + bool fav = false; + foreach (RynthNavPlace f in favorites) + if (SamePlace(f.Name, f.Ns, f.Ew, s.Name, s.Ns, s.Ew)) { fav = true; break; } + if (!fav) rows.Add(SavedRow(places, s)); + } + summary = st == null ? "RynthNav isn't answering." + : rows.Count == 0 ? "Type a place, or coordinates like 42.1N, 33.6E. Favorites and recent places show here." + : $"{favorites.Length} favorite{(favorites.Length == 1 ? "" : "s")}, {rows.Count - favorites.Length} recent"; + break; + } + case AtlasMode.Favorites: + case AtlasMode.Recent: + { + RynthNavPlace[] saved = q.Mode == AtlasMode.Favorites ? favorites : st?.Recent ?? Array.Empty<RynthNavPlace>(); + foreach (RynthNavPlace s in saved) + { + if (!TypeMatches(q.Type, s.Type) || RynthNavAtlas.MatchScore(s.Name, q.Text.Trim()) == 0) continue; + rows.Add(SavedRow(places, s)); + } + summary = st == null ? "RynthNav isn't answering." + : rows.Count == 0 ? (q.Mode == AtlasMode.Favorites ? "No favorites yet: the star on a place adds it." : "Nothing yet: places you point the arrow at show here.") + : $"{rows.Count} {(q.Mode == AtlasMode.Favorites ? "favorite" : "recent place")}{(rows.Count == 1 ? "" : "s")}"; + break; + } + case AtlasMode.Nearby: + { + if (!hasPos) { summary = places.Length == 0 ? RynthNavAtlas.Status : "Nearby needs you on the map (not in a dungeon)."; break; } + var hits = new List<(NavPlace P, double D)>(); + string text = q.Text.Trim(); + foreach (NavPlace p in places) + { + if (!p.OnMap || !TypeMatches(q.Type, p.Type) || RynthNavAtlas.MatchScore(p.Name, text) == 0) continue; + hits.Add((p, RynthNavAtlas.Distance(pns, pew, p.Ns, p.Ew))); + } + hits.Sort((a, b) => a.D.CompareTo(b.D)); + for (int i = 0; i < hits.Count && rows.Count < MaxRows; i++) rows.Add(Row(hits[i].P)); + summary = places.Length == 0 ? RynthNavAtlas.Status : $"{hits.Count} on the map, nearest first"; + break; + } + default: + { + string text = q.Text.Trim(); + var hits = new List<(NavPlace P, int S)>(); + foreach (NavPlace p in places) + { + if (!TypeMatches(q.Type, p.Type)) continue; + int sc = RynthNavAtlas.MatchScore(p.Name, text); + if (sc > 0) hits.Add((p, sc)); + } + hits.Sort((a, b) => + { + int c = b.S.CompareTo(a.S); + if (c != 0) return c; + c = RynthNavAtlas.TypeRank(a.P.Type).CompareTo(RynthNavAtlas.TypeRank(b.P.Type)); + if (c != 0) return c; + c = b.P.OnMap.CompareTo(a.P.OnMap); + return c != 0 ? c : string.Compare(a.P.Name, b.P.Name, StringComparison.OrdinalIgnoreCase); + }); + for (int i = 0; i < hits.Count && rows.Count < MaxRows; i++) rows.Add(Row(hits[i].P)); + summary = places.Length == 0 ? RynthNavAtlas.Status + : hits.Count > rows.Count ? $"{hits.Count} matches, the first {rows.Count} shown" : $"{hits.Count} of {places.Length} places"; + break; + } + } + + // Coordinates typed ("42.1N, 33.6E", a name after them is kept): the first row. + if (q.Mode == AtlasMode.Search && CoordRow(q.Text) is AtlasRow coordRow) + { + rows.Insert(0, coordRow); + if (rows.Count == 1) summary = "Coordinates: " + coordRow.Coord; + } + + foreach (AtlasRow r in rows) + { + if (hasPos && r.OnMap) + { + r.Distance = RynthNavAtlas.Distance(pns, pew, r.Ns, r.Ew); + r.Dist = RynthNavStatus.Yards(r.Distance) + " " + RynthNavAtlas.CompassPoint(RynthNavAtlas.Bearing(pns, pew, r.Ns, r.Ew)); + } + r.Meta = r.Dist.Length > 0 ? r.Type + " · " + r.Dist : r.OnMap ? r.Type : r.Type + " · in a dungeon"; + foreach (RynthNavPlace f in favorites) + if (SamePlace(f.Name, f.Ns, f.Ew, r.Name, r.Ns, r.Ew)) { r.Favorite = true; break; } + } + Publish(new AtlasView(rows.ToArray(), summary)); + } + + private static AtlasRow SavedRow(NavPlace[] places, RynthNavPlace s) => new() + { + Name = s.Name, Type = s.Type.Length > 0 ? s.Type : "Place", Coord = s.CoordText, OnMap = true, Ns = s.Ns, Ew = s.Ew, + Place = Find(places, s.Name, s.Ns, s.Ew), + }; + + private static bool SamePlace(string n1, double ns1, double ew1, string n2, double ns2, double ew2) => + n1.Equals(n2, StringComparison.OrdinalIgnoreCase) && Math.Abs(ns1 - ns2) < 0.05 && Math.Abs(ew1 - ew2) < 0.05; + + /// <summary>A row for typed coordinates (the whole text, or coordinates then a name), else null.</summary> + internal static AtlasRow? CoordRow(string text) + { + text = text.Trim(); + if (text.Length == 0) return null; + var found = ChatCoords.Find(text); + if (found.Count == 0 || found[0].Start != 0) return null; + ChatCoord c = found[0]; + string name = text.Substring(c.Length).Trim().TrimStart(',', ';').Trim(); + return new AtlasRow + { + Name = name.Length > 0 ? name : c.Text, Type = "Coordinates", Coord = c.Text, OnMap = true, Ns = c.Ns, Ew = c.Ew, + }; + } + + private static AtlasRow Row(NavPlace p) => new() + { + Name = p.Name, Type = p.Type, Coord = p.CoordText, OnMap = p.OnMap, Ns = p.Ns, Ew = p.Ew, Place = p, + }; + + private static bool TypeMatches(string filter, string type) => + filter.Length == 0 || filter == "All" || filter.Equals(type, StringComparison.OrdinalIgnoreCase); + + private static NavPlace? Find(NavPlace[] places, string name, double ns, double ew) + { + foreach (NavPlace p in places) + if (p.OnMap && p.Name.Equals(name, StringComparison.OrdinalIgnoreCase) && Math.Abs(p.Ns - ns) < 0.05 && Math.Abs(p.Ew - ew) < 0.05) + return p; + return null; + } + + protected internal override void Reset() + { + _seenQuery = null; + ClearSnapshot(); + } +} diff --git a/src/RynthCore.Engine/UI/Data/RynthNavData.cs b/src/RynthCore.Engine/UI/Data/RynthNavData.cs new file mode 100644 index 0000000..a495be1 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/RynthNavData.cs @@ -0,0 +1,521 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/RynthNavData.cs +// The RynthNav plugin's status (pose, loaded navmesh tile, status line, last +// path, run/turn state; and its travel side: the arrow, the last planned +// route, the recalls this character can use, favorites and recent, where its +// Atlas lives; and, from 0.6.1, the Go tab's status line, the current step's +// distance left, portal ties and the Info section's NavData facts) for both +// RynthNav faces, and its commands. +// +// RynthNavGetStatusJson (and RynthNavGetStatusJsonUtf8, 0.6.1+, tried first) +// frees its previous buffer on each call, so the hub is its only caller +// (RynthNavSource, 250 ms). Load tile / test / preview / go / +// move / command run on the pump too. RynthNavArrowWatch reads one int (how +// many times a command asked to show the arrow) twice a second, always, so +// "/rnav arrow Holtburg" opens the arrow overlay with every RynthNav face shut. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Text.Json; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>A place RynthNav keeps (favorites, recent) or can recall to.</summary> +internal sealed record RynthNavPlace(string Name, string Type, double Ns, double Ew, string Detail = "") +{ + /// <summary>"42.1N, 33.6E".</summary> + public string CoordText { get; } = RynthNavStatus.Coord(Ns, Ew); +} + +/// <summary>One leg of the last planned route.</summary> +internal sealed record RynthNavRouteStep(string Kind, string Label, double Ns, double Ew, bool HasLanding, double LandNs, double LandEw) +{ + /// <summary>What to do, as the route view shows it.</summary> + public string Text { get; } = Kind switch + { + "recall" => "Cast " + Label + (HasLanding ? " → " + RynthNavStatus.Coord(LandNs, LandEw) : ""), + "portal" => "Take portal " + Label + " at " + RynthNavStatus.Coord(Ns, Ew) + (HasLanding ? " → " + RynthNavStatus.Coord(LandNs, LandEw) : ""), + // Town Network legs (a later RynthNav): shown as they come; unknown kinds read as a leg to take. + "town" => "Town Network: " + Label + (HasLanding ? " → " + RynthNavStatus.Coord(LandNs, LandEw) : ""), + "walk" or "" => "Walk to " + RynthNavStatus.Coord(Ns, Ew), + _ => (Label.Length > 0 ? Label : Kind) + " at " + RynthNavStatus.Coord(Ns, Ew), + }; +} + +/// <summary>A recall spot RynthNav learned for this character (portal ties, @lifestone, house...). RynthNav 0.6.1+.</summary> +internal sealed record RynthNavRecallSpot(string Slot, string Name, bool OnMap, double Ns, double Ew, string At) +{ + /// <summary>"Holtburg Lifestone, 42.1N, 33.6E" or "Matron Hive (a dungeon)".</summary> + public string Where { get; } = OnMap + ? (At.Length > 0 ? At + ", " : "") + RynthNavStatus.Coord(Ns, Ew) + : (At.Length > 0 ? At : "somewhere") + " (a dungeon)"; +} + +/// <summary>What the arrow points at now (a place, a portal on the way, or a recall to cast).</summary> +internal sealed class RynthNavArrow +{ + public string Name = "", Type = "", Kind = "place", Hint = "", Final = "", FinalType = ""; + public bool OnMap; + public double Ns, Ew, FinalNs, FinalEw, ArriveYards = 10; + public int Step = 1, Steps = 1; + public string StepText = "", CoordText = "", ThenText = ""; +} + +internal sealed class RynthNavStatus +{ + public bool HasPose, TileLoaded; + public int PolyCount, RunState, TurnState; + public string Landblock = "----", LoadedLb = "----", Status = "", LastPath = ""; + public double NS, EW; + public bool Goto; + + // Travel (RynthNav 0.6+; absent from older plugins: Travel stays false). + public bool Travel; + public string AtlasPath = "", AtlasStatus = "", AtlasGenerated = ""; + public int AtlasCount; + public bool PortalsOn, RecallsOn = true; + // Avoidance settings (RynthNav 0.6.4+; HasAvoid false on older plugins). + public bool HasAvoid, AvoidPortals, AvoidWalls; + public double AvoidPortalM, AvoidWallM, CornerM; + public int OpenArrow; + public RynthNavArrow? Arrow; + public string RouteFor = "", RouteSummary = ""; + public bool RouteActive; + public int RouteIdx = -1; + public RynthNavRouteStep[] Route = Array.Empty<RynthNavRouteStep>(); + public RynthNavPlace[] Recalls = Array.Empty<RynthNavPlace>(); + public string[] RecallNotes = Array.Empty<string>(); + public RynthNavPlace[] Favorites = Array.Empty<RynthNavPlace>(); + public RynthNavPlace[] Recent = Array.Empty<RynthNavPlace>(); + // The route view's lines, built here (not per frame): the header, one per step, one per recall. + public string RouteHeader = "", RecallHeader = "RECALLS FOR ROUTES (0)"; + public string[] RouteLines = Array.Empty<string>(), RecallLines = Array.Empty<string>(); + + // Panel (RynthNav 0.6.1+; absent from older plugins: Panel, HasInfo and HasTies stay false). + public bool Panel; + public string Version = ""; + public string GoLine = "", GoPhase = ""; + public double GoLeft = -1; + public bool HasInfo, GraphLoaded, Indoors; + public int TileHere = -1, OnDisk = -1; + public string NavDir = "", NavSource = "", GraphStatus = ""; + // The Town Network (RynthNav 0.6.2+): townnet.json loaded or not, and why. + public bool HasTownNet, TownNetLoaded; + public string TownNetStatus = ""; + public bool HasTies; + public int Tie1Known = -1, Tie2Known = -1; + public string TiePending = ""; + public RynthNavRecallSpot[] Mine = Array.Empty<RynthNavRecallSpot>(); + // Built once per status for the Go tab. + /// <summary>The status line: what RynthNav is doing, or how the last goto ended.</summary> + public string StatusLine = ""; + /// <summary>The current route step's "340 yd left" (empty when not walking a step).</summary> + public string StepLeft = ""; + public string Tie1Text = "", Tie2Text = "", TiePendingText = ""; + public string[] MineLines = Array.Empty<string>(); + public string InfoHere = "", InfoNavData = "", InfoTiles = "", InfoGraph = "", InfoTownNet = "", InfoAtlas = "", InfoStatus = ""; + + // Display strings, built once per status. + public string PlayerText = "— no pose —", MeshText = "not loaded", PathText = ""; + public bool OnMap = true; + + public static RynthNavStatus? Parse(string json) + { + try + { + using var doc = JsonDocument.Parse(json); + JsonElement r = doc.RootElement; + var s = new RynthNavStatus(); + if (r.TryGetProperty("hasPose", out var v)) s.HasPose = v.GetInt32() != 0; + if (r.TryGetProperty("landblock", out v)) s.Landblock = v.GetString() ?? "----"; + if (r.TryGetProperty("ns", out v)) s.NS = v.GetDouble(); + if (r.TryGetProperty("ew", out v)) s.EW = v.GetDouble(); + if (r.TryGetProperty("tileLoaded", out v)) s.TileLoaded = v.GetInt32() != 0; + if (r.TryGetProperty("loadedLb", out v)) s.LoadedLb = v.GetString() ?? "----"; + if (r.TryGetProperty("polyCount", out v)) s.PolyCount = v.GetInt32(); + if (r.TryGetProperty("status", out v)) s.Status = v.GetString() ?? ""; + if (r.TryGetProperty("lastPath", out v)) s.LastPath = v.GetString() ?? ""; + if (r.TryGetProperty("runState", out v)) s.RunState = v.GetInt32(); + if (r.TryGetProperty("turnState", out v)) s.TurnState = v.GetInt32(); + if (r.TryGetProperty("goto", out v)) s.Goto = v.GetInt32() != 0; + // RynthNav 0.6.3+: "onMap" 0 in a dungeon, where ns/ew aren't map coordinates. + s.OnMap = !r.TryGetProperty("onMap", out v) || v.ValueKind != JsonValueKind.Number || v.GetInt32() != 0; + s.PlayerText = !s.HasPose ? "— no pose —" + : s.OnMap ? $"0x{s.Landblock} {Loc(s.NS, 'N', 'S')} {Loc(s.EW, 'E', 'W')}" + : $"0x{s.Landblock} in a dungeon (no map position: routes start with a recall)"; + // polyCount is RynthNav's loaded TILE count (a window of landblocks around + // the player), not a polygon count; it was labelled "polys". + s.MeshText = s.TileLoaded ? $"{s.PolyCount} tiles around 0x{s.LoadedLb}" : "not loaded"; + s.PathText = string.IsNullOrEmpty(s.LastPath) ? "" : "↳ " + s.LastPath; + ParseTravel(r, s); + ParsePanel(r, s); + return s; + } + catch { return null; } // transient partial JSON + } + + private static void ParseTravel(JsonElement r, RynthNavStatus s) + { + if (!r.TryGetProperty("atlas", out var atlas) || atlas.ValueKind != JsonValueKind.Object) return; + s.Travel = true; + s.AtlasPath = Str(atlas, "path"); + s.AtlasStatus = Str(atlas, "status"); + s.AtlasGenerated = Str(atlas, "generated"); + s.AtlasCount = Int(atlas, "count"); + s.PortalsOn = Int(r, "portalsOn") != 0; + s.RecallsOn = Int(r, "recallsOn") != 0; + s.HasAvoid = r.TryGetProperty("avoidPortals", out _); + s.AvoidPortals = Int(r, "avoidPortals") != 0; + s.AvoidWalls = Int(r, "avoidWalls") != 0; + s.AvoidPortalM = Num(r, "avoidPortalM"); + s.AvoidWallM = Num(r, "avoidWallM"); + s.CornerM = Num(r, "cornerM"); + s.OpenArrow = Int(r, "openArrow"); + + if (r.TryGetProperty("arrow", out var a) && a.ValueKind == JsonValueKind.Object) + { + var ar = new RynthNavArrow + { + Name = Str(a, "name"), Type = Str(a, "type"), Kind = Str(a, "kind"), Hint = Str(a, "hint"), + Final = Str(a, "final"), FinalType = Str(a, "finalType"), + OnMap = Int(a, "onMap") != 0, Ns = Num(a, "ns"), Ew = Num(a, "ew"), + FinalNs = Num(a, "finalNs"), FinalEw = Num(a, "finalEw"), + Step = Int(a, "step"), Steps = Int(a, "steps"), ArriveYards = Num(a, "arrive"), + }; + ar.CoordText = ar.OnMap ? Coord(ar.Ns, ar.Ew) : ""; + ar.StepText = ar.Steps > 1 ? $"step {ar.Step} of {ar.Steps}, to {ar.Final}" : ""; + ar.ThenText = ar.Steps > 1 ? "then " + ar.Final + " " + Coord(ar.FinalNs, ar.FinalEw) : ""; + s.Arrow = ar; + } + + if (r.TryGetProperty("route", out var route) && route.ValueKind == JsonValueKind.Object) + { + s.RouteFor = Str(route, "for"); + s.RouteActive = Int(route, "active") != 0; + s.RouteIdx = Int(route, "idx", -1); + var steps = new List<RynthNavRouteStep>(); + int teleports = 0; + if (route.TryGetProperty("steps", out var arr) && arr.ValueKind == JsonValueKind.Array) + foreach (JsonElement e in arr.EnumerateArray()) + { + bool land = e.TryGetProperty("lns", out _); + var step = new RynthNavRouteStep(Str(e, "k"), Str(e, "l"), Num(e, "ns"), Num(e, "ew"), land, Num(e, "lns"), Num(e, "lew")); + if (step.Kind != "walk") teleports++; + steps.Add(step); + } + s.Route = steps.ToArray(); + double est = Num(route, "est"); + s.RouteSummary = teleports == 0 + ? $"walk, about {Yards(est)}" + : $"{teleports} teleport{(teleports == 1 ? "" : "s")}, about {Yards(est)} of effort"; + s.RouteHeader = "To " + s.RouteFor + ": " + s.RouteSummary + (s.RouteActive ? " (walking)" : ""); + var lines = new string[s.Route.Length]; + for (int i = 0; i < lines.Length; i++) + { + RynthNavRouteStep st = s.Route[i]; + string icon = st.Kind == "recall" ? StepIconRecall : st.Kind == "portal" ? StepIconPortal + : st.Kind == "town" ? StepIconTown : StepIconWalk; + lines[i] = icon + " " + (i + 1).ToString(CultureInfo.InvariantCulture) + ". " + st.Text; + } + s.RouteLines = lines; + } + + s.Recalls = Places(r, "recalls", recall: true); + s.RecallHeader = "RECALLS FOR ROUTES (" + s.Recalls.Length.ToString(CultureInfo.InvariantCulture) + ")"; + var recallLines = new string[s.Recalls.Length]; + for (int i = 0; i < recallLines.Length; i++) + recallLines[i] = StepIconRecall + " " + s.Recalls[i].Name + " → " + s.Recalls[i].CoordText + " (" + s.Recalls[i].Detail + ")"; + s.RecallLines = recallLines; + if (r.TryGetProperty("recallNotes", out var notes) && notes.ValueKind == JsonValueKind.Array) + { + var list = new List<string>(); + foreach (JsonElement n in notes.EnumerateArray()) list.Add(n.GetString() ?? ""); + s.RecallNotes = list.ToArray(); + } + s.Favorites = Places(r, "favs", recall: false); + s.Recent = Places(r, "recent", recall: false); + } + + /// <summary> + /// The Go tab's fields (RynthNav 0.6.1+): the status line, the current step's distance + /// left, the Info section (NavData, route graph, the tile here) and the Recalls section's + /// portal ties and learned recall spots. Older RynthNavs: the status line falls back to + /// the technical status, and the sections say what an update adds. + /// </summary> + private static void ParsePanel(JsonElement r, RynthNavStatus s) + { + s.Version = Str(r, "v"); + if (r.TryGetProperty("go", out var go) && go.ValueKind == JsonValueKind.Object) + { + s.Panel = true; + s.GoLine = Str(go, "line"); + s.GoPhase = Str(go, "phase"); + s.GoLeft = go.TryGetProperty("left", out var l) && l.ValueKind == JsonValueKind.Number ? l.GetDouble() : -1; + } + s.StatusLine = s.Panel ? (s.GoLine.Length > 0 ? s.GoLine : s.Goto ? "walking" : "ready") : s.Status; + // "town": walking inside the Town Network (RynthNav 0.6.2+). + s.StepLeft = s.Goto && (s.GoPhase == "walk" || s.GoPhase == "town") && s.GoLeft >= 0 ? Yards(s.GoLeft) + " left" : ""; + + if (r.TryGetProperty("info", out var info) && info.ValueKind == JsonValueKind.Object) + { + s.HasInfo = true; + s.NavDir = Str(info, "dir"); + s.NavSource = Str(info, "source"); + s.GraphLoaded = Int(info, "graph") != 0; + s.GraphStatus = Str(info, "graphStatus"); + s.TileHere = Int(info, "tileHere", -1); + s.Indoors = Int(info, "indoors") != 0; + s.OnDisk = Int(info, "onDisk", -1); + s.HasTownNet = info.TryGetProperty("townNet", out _); + s.TownNetLoaded = Int(info, "townNet") != 0; + s.TownNetStatus = Str(info, "townNetStatus"); + } + string meshHere = !s.HasInfo ? (s.TileLoaded ? "loaded" : "not loaded") + : s.TileHere == 1 ? "yes" : s.TileHere == 0 ? "no (no tile for this landblock)" : "not checked yet"; + s.InfoHere = s.HasPose + ? $"0x{s.Landblock}{(s.Indoors ? " (indoors)" : "")} \u00B7 navmesh here: {meshHere} \u00B7 {s.PolyCount} tile{(s.PolyCount == 1 ? "" : "s")} loaded" + : "no position yet"; + s.InfoNavData = s.HasInfo ? s.NavDir + (s.NavSource.Length > 0 ? " (" + s.NavSource + ")" : "") : "update RynthNav for the NavData folder"; + s.InfoTiles = !s.HasInfo ? "" : s.OnDisk >= 0 ? $"{s.OnDisk} tile files in the folder" : "tile files: counting\u2026"; + s.InfoGraph = s.HasInfo ? (s.GraphLoaded ? "loaded: " : "not loaded: ") + s.GraphStatus : "update RynthNav for the route graph"; + s.InfoTownNet = s.HasTownNet ? (s.TownNetLoaded ? "loaded: " : "not loaded: ") + s.TownNetStatus : "update RynthNav (0.6.2) for Town Network routes"; + s.InfoAtlas = !s.Travel ? "update RynthNav for the Atlas" + : $"{s.AtlasCount} places" + (s.AtlasStatus.Length > 0 && !s.AtlasStatus.EndsWith(" places", StringComparison.Ordinal) ? " (" + s.AtlasStatus + ")" : "") + + (s.AtlasGenerated.Length >= 10 ? ", from " + s.AtlasGenerated.Substring(0, 10) : ""); + s.InfoStatus = s.Status + (s.LastPath.Length > 0 ? " \u00B7 " + s.LastPath : ""); + + if (r.TryGetProperty("mine", out var mine) && mine.ValueKind == JsonValueKind.Array) + { + s.HasTies = true; + var spots = new List<RynthNavRecallSpot>(); + foreach (JsonElement e in mine.EnumerateArray()) + spots.Add(new RynthNavRecallSpot(Str(e, "s"), Str(e, "n"), Int(e, "on") != 0, Num(e, "ns"), Num(e, "ew"), Str(e, "at"))); + s.Mine = spots.ToArray(); + if (r.TryGetProperty("ties", out var ties) && ties.ValueKind == JsonValueKind.Object) + { + s.Tie1Known = Int(ties, "t1", -1); + s.Tie2Known = Int(ties, "t2", -1); + } + s.TiePending = Str(r, "tiePending"); + s.Tie1Text = TieText("Primary", "Tie1", s.Tie1Known, s.Mine); + s.Tie2Text = TieText("Secondary", "Tie2", s.Tie2Known, s.Mine); + s.TiePendingText = s.TiePending.Length > 0 ? "Portal tie noted: " + s.TiePending + ". Which tie was it?" : ""; + var lines = new List<string>(); + foreach (RynthNavRecallSpot m in s.Mine) + if (m.Slot != "Tie1" && m.Slot != "Tie2") lines.Add(StepIconRecall + " " + m.Name + ": " + m.Where); + s.MineLines = lines.ToArray(); + } + } + + private static string TieText(string which, string slot, int known, RynthNavRecallSpot[] mine) + { + foreach (RynthNavRecallSpot m in mine) + if (m.Slot == slot) return which + " tie: " + m.Where; + return which + " tie: " + (known == 0 ? "you don't know " + which + " Portal Tie" : "not tied yet (cast " + which + " Portal Tie on a portal)"); + } + + // Phosphor glyphs (ImGui/PhosphorIcons.cs: MagicWand, Spiral, Footprints, CastleTurret), kept here + // so this data class needs nothing from the ImGui layer. + private const string StepIconRecall = "\uE6B6", StepIconPortal = "\uE9FA", StepIconWalk = "\uEA88", StepIconTown = "\uE9D0"; + + private static RynthNavPlace[] Places(JsonElement r, string key, bool recall) + { + if (!r.TryGetProperty(key, out var arr) || arr.ValueKind != JsonValueKind.Array) return Array.Empty<RynthNavPlace>(); + var list = new List<RynthNavPlace>(); + foreach (JsonElement e in arr.EnumerateArray()) + list.Add(new RynthNavPlace(Str(e, "n"), recall ? "Recall" : Str(e, "t"), Num(e, "ns"), Num(e, "ew"), + recall ? Str(e, "how") + (Int(e, "learned") != 0 ? ", learned" : "") : "")); + return list.ToArray(); + } + + private static string Str(JsonElement e, string name) => + e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; + + private static int Int(JsonElement e, string name, int fallback = 0) => + e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback; + + private static double Num(JsonElement e, string name) => + e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) ? d : 0; + + private static string Loc(double v, char pos, char neg) => + v.ToString("F1", CultureInfo.InvariantCulture).TrimStart('-') + (v >= 0 ? pos : neg); + + /// <summary>"42.1N, 33.6E".</summary> + public static string Coord(double ns, double ew) => Loc(ns, 'N', 'S') + ", " + Loc(ew, 'E', 'W'); + + /// <summary>What RynthNav's commands take: "42.08N, 33.60E" (two decimals, so a place's own spot).</summary> + public static string CommandCoord(double ns, double ew) => + Math.Abs(ns).ToString("F2", CultureInfo.InvariantCulture) + (ns >= 0 ? "N" : "S") + ", " + + Math.Abs(ew).ToString("F2", CultureInfo.InvariantCulture) + (ew >= 0 ? "E" : "W"); + + public static string Yards(double units) => + units < 1000 ? units.ToString("0", CultureInfo.InvariantCulture) + " yd" + : (units / 1000.0).ToString("0.0", CultureInfo.InvariantCulture) + "k yd"; +} + +/// <summary>RynthNavGetStatusJson while a RynthNav face is open (250 ms).</summary> +internal sealed unsafe class RynthNavSource : UiSource<RynthNavStatus> +{ + // RynthNav 0.6.1+ also has a UTF-8 getter (names with characters the ANSI code page lacks); + // older ones only the ANSI one. Each frees its own previous buffer; only one is called. + private delegate* unmanaged[Cdecl]<IntPtr> _get; + private bool _utf8; + private string? _lastJson; + + public RynthNavSource() : base("RynthNav", periodMs: 250) { } + + protected internal override void Poll() + { + if (_get == null) + { + _get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthNav", "RynthNavGetStatusJsonUtf8"); + _utf8 = _get != null; + if (_get == null) + _get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthNav", "RynthNavGetStatusJson"); + } + if (_get == null) return; + IntPtr ptr = _get(); + string? json = ptr == IntPtr.Zero ? null : _utf8 ? Marshal.PtrToStringUTF8(ptr) : Marshal.PtrToStringAnsi(ptr); + if (string.IsNullOrEmpty(json) || json == _lastJson) return; + RynthNavStatus? status = RynthNavStatus.Parse(json); + if (status == null) return; + _lastJson = json; + Publish(status); + } + + protected internal override void Reset() + { + _get = null; + _utf8 = false; + _lastJson = null; + ClearSnapshot(); + } +} + +internal static unsafe class RynthNavCommands +{ + private static delegate* unmanaged[Cdecl]<void> _loadTile, _testQuery; + private static delegate* unmanaged[Cdecl]<IntPtr, void> _preview, _goto, _command; + private static delegate* unmanaged[Cdecl]<int, void> _move; + + static RynthNavCommands() + { + PluginManager.PluginsUnloaded += () => { _loadTile = null; _testQuery = null; _preview = null; _goto = null; _move = null; _command = null; }; + } + + private static IntPtr Export(string name) => PluginExportBinder.Resolve("RynthNav", name); + + private static void Run(string label, Action action) => UiDataHub.Post("RynthNav " + label, () => + { + action(); + UiSources.RynthNav.RequestRefresh(); + }); + + public static void LoadTile() => Run("load tile", () => + { + if (_loadTile == null) _loadTile = (delegate* unmanaged[Cdecl]<void>)Export("RynthNavLoadTile"); + if (_loadTile != null) _loadTile(); + }); + + public static void TestQuery() => Run("test", () => + { + if (_testQuery == null) _testQuery = (delegate* unmanaged[Cdecl]<void>)Export("RynthNavTestQuery"); + if (_testQuery != null) _testQuery(); + }); + + /// <summary>Preview a route to a /loc coordinate ("42.5N, 33.6E").</summary> + public static void Preview(string coord) => Run("preview", () => + { + if (_preview == null) _preview = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthNavPreviewPath"); + if (_preview == null) return; + IntPtr p = Marshal.StringToHGlobalAnsi(coord); + try { _preview(p); } + finally { Marshal.FreeHGlobal(p); } + }); + + /// <summary>Walk the navmesh path to a /loc coordinate.</summary> + public static void Goto(string coord) => Run("go", () => + { + if (_goto == null) _goto = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthNavGoto"); + if (_goto == null) return; + IntPtr p = Marshal.StringToHGlobalAnsi(coord); + try { _goto(p); } + finally { Marshal.FreeHGlobal(p); } + }); + + /// <summary>1 forward, 2 back, 3 turn left, 4 turn right, 5 stop.</summary> + public static void Move(int cmd) => Run("move", () => + { + if (_move == null) _move = (delegate* unmanaged[Cdecl]<int, void>)Export("RynthNavMove"); + if (_move != null) _move(cmd); + }); + + /// <summary> + /// A /rnav command without the "/rnav" ("arrow 42.08N, 33.60E Holtburg", "go Holtburg", + /// "fav ...", "portals on"). RynthNav 0.6+ (RynthNavCommand); RynthNav queues it for its + /// tick, so the status shows the result a poll or two later. + /// </summary> + public static void Command(string text) => Run("command", () => + { + if (_command == null) _command = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthNavCommand"); + if (_command == null) return; + IntPtr p = Marshal.StringToCoTaskMemUTF8(text); + try { _command(p); } + finally { Marshal.FreeCoTaskMem(p); } + }); + + public static void Arrow(string name, double ns, double ew) => + Command("arrow " + RynthNavStatus.CommandCoord(ns, ew) + " " + name); + + public static void Go(string name, double ns, double ew) => + Command("go " + RynthNavStatus.CommandCoord(ns, ew) + " " + name); + + public static void Route(string name, double ns, double ew) => + Command("route " + RynthNavStatus.CommandCoord(ns, ew) + " " + name); + + public static void ToggleFavorite(string name, double ns, double ew) => + Command("fav " + RynthNavStatus.CommandCoord(ns, ew) + " " + name); +} + +/// <summary> +/// Opens the arrow overlay when a RynthNav command asks to show the arrow (any arrow +/// set: /rnav arrow, go, the Atlas, the chat menu), even with every RynthNav face shut. +/// RynthNavArrowSeq is one int; polled twice a second while RynthNav is loaded. +/// </summary> +internal sealed unsafe class RynthNavArrowWatch : UiSource<object> +{ + private delegate* unmanaged[Cdecl]<int> _get; + private int _last = int.MinValue; + private long _retryAtMs; + + /// <summary>Set by the face registration: what to call when the arrow should show. Pump thread.</summary> + public static Action? ShowArrow; + + public RynthNavArrowWatch() : base("RynthNavArrowWatch", periodMs: 500) { } + + protected internal override void Poll() + { + if (_get == null) + { + // Not loaded yet, or an older RynthNav (no overlay auto-open): look again later. + long now = Environment.TickCount64; + if (now < _retryAtMs) return; + _get = (delegate* unmanaged[Cdecl]<int>)PluginExportBinder.Resolve("RynthNav", "RynthNavArrowSeq"); + if (_get == null) { _retryAtMs = now + 10000; return; } + } + int seq = _get(); + if (_last != int.MinValue && seq != _last) ShowArrow?.Invoke(); + _last = seq; + } + + protected internal override void Reset() + { + _get = null; + _retryAtMs = 0; + _last = int.MinValue; + } +} diff --git a/src/RynthCore.Engine/UI/Data/SenseData.cs b/src/RynthCore.Engine/UI/Data/SenseData.cs new file mode 100644 index 0000000..36eab8f --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/SenseData.cs @@ -0,0 +1,679 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/SenseData.cs +// Sense, our take on Virindi Sense: a watch list of names, and every object +// the client knows about, anywhere, whose name matches one. +// +// SenseStore the watch list and the alert settings, in +// %LocalAppData%\RynthCore\sense.txt (read and written on +// UiBackgroundWriter, never on AC's render thread). +// SensePattern one term, case-insensitive. Without wildcards the name only +// has to contain it ("drake" finds "Dragon's Isle Drake"); +// with * or ? the whole name must match ("Drake*", "?ire Ant"). +// SenseSource the scan: on the plugin pump thread at 2 Hz, reading only the +// engine's main-thread snapshots (LiveObjectIds, the identity, +// position, PWD and attackable snapshots, the player pose), +// never AC memory. Publishes an immutable SenseView and raises +// the optional chat line / beep for a new match. Polled while +// the Sense face is open, and while an alert is on with at least +// one enabled term, so alerts work with the panel closed. +// +// How far it sees: the whole client object table, not a radar radius. The +// client knows what the server has sent it, which is every object in the +// landblocks it has loaded around you (outdoors on ACE: your 192 m landblock +// and the eight around it, so a few hundred yards, far past the radar), or +// the dungeon you are in. +// +// Distances: outdoors and in surface buildings the landblock grid is one +// space (world = landblock x 192 m + cell-local origin). A dungeon has its own +// space: a distance is shown only when you and the object are in the same +// landblock, or both in the overworld; otherwise the row says "elsewhere" and +// gives the landblock. A landblock counts as overworld when anything known in +// it (or you) stands in an outdoor cell; indoor cells of a landblock with no +// outdoor objects are taken for a dungeon. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>One watch-list term. Immutable.</summary> +internal sealed class SensePattern +{ + public SensePattern(string text, bool enabled) + { + Text = (text ?? string.Empty).Trim(); + Enabled = enabled; + IsGlob = Text.IndexOfAny(Wildcards) >= 0; + } + + private static readonly char[] Wildcards = { '*', '?' }; + + public string Text { get; } + public bool Enabled { get; } + /// <summary>True when the term has * or ?: the whole name must match it.</summary> + public bool IsGlob { get; } + + public bool Matches(string name) + { + if (Text.Length == 0 || string.IsNullOrEmpty(name)) return false; + return IsGlob ? Glob(name, Text) : name.Contains(Text, StringComparison.OrdinalIgnoreCase); + } + + /// <summary> + /// Case-insensitive whole-string match of <paramref name="s"/> against + /// <paramref name="p"/> (* any run, ? one character). Iterative, backtracking + /// only to the last *; no allocation. + /// </summary> + internal static bool Glob(string s, string p) + { + int si = 0, pi = 0, star = -1, mark = 0; + while (si < s.Length) + { + if (pi < p.Length && p[pi] == '*') { star = pi++; mark = si; } + else if (pi < p.Length && (p[pi] == '?' || Same(p[pi], s[si]))) { si++; pi++; } + else if (star >= 0) { pi = star + 1; si = ++mark; } + else return false; + } + while (pi < p.Length && p[pi] == '*') pi++; + return pi == p.Length; + } + + private static bool Same(char a, char b) => a == b || char.ToUpperInvariant(a) == char.ToUpperInvariant(b); +} + +/// <summary> +/// The watch list and alert settings. Edited on AC's thread (the face, /rc sense), +/// read by the scan on the pump thread: the term list is an immutable array +/// swapped whole, with a version the scan compares. File I/O on UiBackgroundWriter. +/// </summary> +internal static class SenseStore +{ + public const int MaxTerms = 40; + public const int MaxTermLength = 64; + + private static readonly object Sync = new(); + private static SensePattern[] _terms = Array.Empty<SensePattern>(); + private static long _version; + private static volatile bool _loaded; + private static bool _loadQueued; + private static volatile bool _alertChat; + private static volatile bool _alertBeep; + private static bool _alertSubscribed; + + /// <summary>The current terms (never null; do not modify). Any thread.</summary> + public static SensePattern[] Terms => Volatile.Read(ref _terms); + + /// <summary>Bumped on every change to the terms. Any thread.</summary> + public static long Version => Interlocked.Read(ref _version); + + public static bool Loaded => _loaded; + + /// <summary>A chat line when a new match appears (off by default).</summary> + public static bool AlertChat => _alertChat; + + /// <summary>The system beep when a new match appears (off by default).</summary> + public static bool AlertBeep => _alertBeep; + + public static bool AnyEnabled + { + get + { + foreach (SensePattern t in Terms) + if (t.Enabled && t.Text.Length > 0) return true; + return false; + } + } + + private static string FilePath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "sense.txt"); + + /// <summary>Queues the one-time read off the calling thread. Any thread; cheap after the first call.</summary> + public static void EnsureLoadQueued() + { + if (_loaded) return; + lock (Sync) + { + if (_loadQueued) return; + _loadQueued = true; + } + UiBackgroundWriter.Enqueue("sense list (load)", LoadNow); + } + + private static void LoadNow() + { + var list = new List<SensePattern>(); + bool chat = false, beep = false; + try + { + string path = FilePath; + if (File.Exists(path)) + { + foreach (string raw in File.ReadAllLines(path)) + { + string line = raw.Trim(); + if (line.Length == 0 || line.StartsWith('#')) continue; + int eq = line.IndexOf('='); + if (eq <= 0) continue; + string key = line[..eq].Trim(); + string val = line[(eq + 1)..]; + switch (key) + { + case "alertChat": chat = val.Trim() == "1"; break; + case "alertBeep": beep = val.Trim() == "1"; break; + case "term": + { + // term=1|pattern (1 on, 0 off); a bare term=pattern is on. + bool on = true; + string text = val; + int bar = val.IndexOf('|'); + if (bar is 1 && (val[0] == '0' || val[0] == '1')) + { + on = val[0] == '1'; + text = val[2..]; + } + text = Clean(text); + if (text.Length > 0 && list.Count < MaxTerms && IndexOf(list, text) < 0) + list.Add(new SensePattern(text, on)); + break; + } + } + } + } + } + catch (Exception ex) + { + RynthLog.UI($"Sense: reading sense.txt failed - {ex.GetType().Name}: {ex.Message}"); + } + + lock (Sync) + { + Volatile.Write(ref _terms, list.ToArray()); + _alertChat = chat; + _alertBeep = beep; + Interlocked.Increment(ref _version); + _loaded = true; + } + SyncAlertSubscription(); + } + + private static string Clean(string text) + { + text = (text ?? string.Empty).Replace('\r', ' ').Replace('\n', ' ').Trim(); + return text.Length > MaxTermLength ? text[..MaxTermLength] : text; + } + + private static int IndexOf(IReadOnlyList<SensePattern> list, string text) + { + for (int i = 0; i < list.Count; i++) + if (string.Equals(list[i].Text, text, StringComparison.OrdinalIgnoreCase)) return i; + return -1; + } + + /// <summary> + /// Adds a term (switched on). An existing term with the same text is switched + /// on instead. False when the text is empty, the list is full or not loaded yet. + /// </summary> + public static bool Add(string text, out string message) + { + text = Clean(text); + if (!_loaded) { message = "The watch list is still loading."; return false; } + if (text.Length == 0) { message = "Type a name first."; return false; } + lock (Sync) + { + SensePattern[] cur = _terms; + int at = IndexOf(cur, text); + if (at >= 0) + { + message = cur[at].Enabled ? $"\"{cur[at].Text}\" is already on the list." : $"\"{cur[at].Text}\" switched on."; + if (!cur[at].Enabled) Replace(at, new SensePattern(cur[at].Text, true)); + return true; + } + if (cur.Length >= MaxTerms) { message = $"The list is full ({MaxTerms} terms)."; return false; } + var next = new SensePattern[cur.Length + 1]; + Array.Copy(cur, next, cur.Length); + next[^1] = new SensePattern(text, true); + Publish(next); + message = $"Watching for \"{text}\"."; + return true; + } + } + + public static void SetEnabled(int index, bool enabled) + { + lock (Sync) + { + SensePattern[] cur = _terms; + if ((uint)index >= (uint)cur.Length || cur[index].Enabled == enabled) return; + Replace(index, new SensePattern(cur[index].Text, enabled)); + } + } + + public static void Remove(int index) + { + lock (Sync) + { + SensePattern[] cur = _terms; + if ((uint)index >= (uint)cur.Length) return; + var next = new SensePattern[cur.Length - 1]; + Array.Copy(cur, 0, next, 0, index); + Array.Copy(cur, index + 1, next, index, cur.Length - index - 1); + Publish(next); + } + } + + public static void SetAlerts(bool chat, bool beep) + { + if (chat == _alertChat && beep == _alertBeep) return; + _alertChat = chat; + _alertBeep = beep; + SyncAlertSubscription(); + Save(); + } + + // Under Sync. + private static void Replace(int index, SensePattern pattern) + { + var next = (SensePattern[])_terms.Clone(); + next[index] = pattern; + Publish(next); + } + + // Under Sync. + private static void Publish(SensePattern[] next) + { + Volatile.Write(ref _terms, next); + Interlocked.Increment(ref _version); + UiSources.Sense.RequestRefresh(); + SyncAlertSubscription(); + Save(); + } + + /// <summary> + /// Keeps the scan running with the panel closed while an alert is on and a term + /// is enabled (one subscription of its own). Any thread. + /// </summary> + public static void SyncAlertSubscription() + { + bool want = _loaded && (_alertChat || _alertBeep) && AnyEnabled; + lock (Sync) + { + if (want == _alertSubscribed) return; + _alertSubscribed = want; + if (want) UiSources.Sense.Subscribe(); + else UiSources.Sense.Unsubscribe(); + } + } + + /// <summary>Writes the list in the background. Any thread.</summary> + public static void Save() + { + if (!_loaded) return; // never overwrite the file with the empty pre-load list + UiBackgroundWriter.Enqueue("sense list", SaveNow); + } + + private static void SaveNow() + { + try + { + SensePattern[] terms = Terms; + var sb = new StringBuilder(); + sb.AppendLine("# RynthCore Sense watch list - auto-generated, hand-edits OK. /rc sense in game."); + sb.AppendLine("# term=1|name (1 on, 0 off). No * or ?: the name contains it. With * or ?: the whole name matches."); + sb.AppendLine(_alertChat ? "alertChat=1" : "alertChat=0"); + sb.AppendLine(_alertBeep ? "alertBeep=1" : "alertBeep=0"); + foreach (SensePattern t in terms) + sb.Append("term=").Append(t.Enabled ? '1' : '0').Append('|').AppendLine(t.Text); + string path = FilePath; + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.WriteAllText(path, sb.ToString()); + } + catch (Exception ex) + { + RynthLog.UI($"Sense: writing sense.txt failed - {ex.GetType().Name}: {ex.Message}"); + } + } +} + +internal enum SenseKind : byte { Monster, Npc, Player, Item, Portal, Corpse } + +/// <summary>One match, with its texts built by the scan. Immutable once published.</summary> +internal sealed class SenseRow +{ + public uint Id; + public string Name = ""; + public SenseKind Kind; + /// <summary>True when a distance and bearing mean something (same space as you).</summary> + public bool Measured; + public float Distance; // yd (= m); +inf when not measured + public float Bearing = float.NaN; // compass degrees from you, 0 = North, clockwise; NaN unknown / on top of you + public string DistanceText = ""; + public string CompassText = ""; + public string LocationText = ""; + public string Tooltip = ""; + /// <summary>Environment.TickCount64 when the match first appeared (0 = was already there when the scan started).</summary> + public long FirstSeenMs; +} + +/// <summary>A published scan.</summary> +internal sealed class SenseView +{ + public static readonly SenseView Empty = new(Array.Empty<SenseRow>(), "", 0); + + public SenseView(SenseRow[] rows, string status, int known) + { + Rows = rows; + Status = status; + Known = known; + } + + public SenseRow[] Rows { get; } + public string Status { get; } + /// <summary>Objects in the client's table at the scan.</summary> + public int Known { get; } +} + +/// <summary>The Sense scan (see the file header). Pump thread.</summary> +internal sealed class SenseSource : UiSource<SenseView> +{ + public SenseSource() : base("Sense", periodMs: 500) { } + + private const uint TypeCreature = 0x10, TypePortal = 0x10000; + private const uint BfPlayer = 0x8, BfCorpse = 0x2000, BfPortal = 0x40000; + private const float LandblockSize = 192f; + private const int MaxRows = 300; + private const int MaxAlertLines = 3; + private const long AlertCooldownMs = 120_000; // the same object again within this: no second alert + private const long GapMs = 3000; // longer between polls: the scan was off, nothing is "new" + private const int ChatType = 1; // the colour of RynthCore's own replies + + private static readonly string[] Compass16 = { "N", "NE", "NE", "E", "E", "SE", "SE", "S", "S", "SW", "SW", "W", "W", "NW", "NW", "N" }; + + private long _lastPollMs; + private long _seenVersion = -1; + private Dictionary<uint, long> _firstSeen = new(); + private Dictionary<uint, long> _firstSeenNext = new(); + private readonly Dictionary<uint, long> _lastAlertMs = new(); + private long _nextAlertPruneMs; + private long _lastBeepMs; + private readonly List<(uint Id, string Name, SensePattern Term)> _hits = new(); + private readonly HashSet<uint> _overworldBlocks = new(); + private readonly List<SenseRow> _rows = new(); + private readonly List<SenseRow> _alerts = new(); + + [DllImport("user32.dll")] private static extern bool MessageBeep(uint uType); + + protected internal override void Poll() + { + long now = Environment.TickCount64; + bool gap = _lastPollMs == 0 || now - _lastPollMs > GapMs; + _lastPollMs = now; + + if (!SenseStore.Loaded) { PublishStatus("Loading the watch list...", 0); return; } + + SensePattern[] terms = SenseStore.Terms; + long version = SenseStore.Version; + bool termsChanged = version != _seenVersion; + _seenVersion = version; + + int enabled = 0; + foreach (SensePattern t in terms) if (t.Enabled && t.Text.Length > 0) enabled++; + if (enabled == 0) + { + _firstSeen.Clear(); + PublishStatus(terms.Length == 0 ? "Add a name to watch for." : "Every term is switched off.", 0); + return; + } + + uint playerId = ClientHelperHooks.GetPlayerId(); + if (playerId == 0 || !LoginLifecycleHooks.HasObservedLoginComplete || LogoutLifecycleHooks.HasObservedLogout) + { + _firstSeen.Clear(); + PublishStatus("Not in the world.", 0); + return; + } + if (TeleportStateHooks.IsPortaling) + { + PublishStatus("In portal space...", 0); + return; + } + // Position only: the face turns the arrows with the heading of the frame it draws. + if (!PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out uint pCell, out float px, out float py, out float pz, + out _, out _, out _, out _) || (pCell >> 16) == 0) + { + PublishStatus("Waiting for your position...", 0); + return; + } + + // Pass 1: names only (a dictionary lookup per id). + uint[] ids = ClientObjectHooks.LiveObjectIds; + _hits.Clear(); + for (int i = 0; i < ids.Length; i++) + { + uint id = ids[i]; + if (id == 0 || id == playerId) continue; + if (!ClientObjectHooks.TryGetSnapshotName(id, out string name) || name.Length == 0) continue; + foreach (SensePattern t in terms) + { + if (!t.Enabled || !t.Matches(name)) continue; + _hits.Add((id, name, t)); + break; + } + } + + // Which landblocks are overworld (only needed when someone stands indoors). + _overworldBlocks.Clear(); + bool needBlocks = !IsOutdoorCell(pCell); + if (!needBlocks) + { + foreach (var h in _hits) + if (ClientObjectHooks.TryGetSnapshotPosition(h.Id, out uint c, out _, out _, out _) && !IsOutdoorCell(c)) { needBlocks = true; break; } + } + if (needBlocks) + { + if (IsOutdoorCell(pCell)) _overworldBlocks.Add(pCell >> 16); + for (int i = 0; i < ids.Length; i++) + if (ClientObjectHooks.TryGetSnapshotPosition(ids[i], out uint c, out _, out _, out _) && (c >> 16) != 0 && IsOutdoorCell(c)) + _overworldBlocks.Add(c >> 16); + } + bool playerOverworld = IsOverworld(pCell); + + // Pass 2: rows for the hits that stand somewhere (not in a pack, not wielded). + _rows.Clear(); + _alerts.Clear(); + _firstSeenNext.Clear(); + bool flashNew = !gap; + bool alertNew = !gap && !termsChanged && (SenseStore.AlertChat || SenseStore.AlertBeep); + foreach (var h in _hits) + { + if (_rows.Count >= MaxRows) break; + if (!ClientObjectHooks.TryGetSnapshotPosition(h.Id, out uint cell, out float x, out float y, out float z) || (cell >> 16) == 0) + continue; + bool hasPwd = ClientObjectHooks.TryGetSnapshotPwdInfo(h.Id, out uint bf, out uint container, out uint wielder); + if (hasPwd && (container != 0 || wielder != 0)) continue; + + var row = new SenseRow { Id = h.Id, Name = h.Name, Kind = Classify(h.Id, hasPwd ? bf : 0) }; + bool objOverworld = IsOverworld(cell); + row.Measured = (cell >> 16) == (pCell >> 16) || (playerOverworld && objOverworld); + uint lb = cell >> 16; + string coords = objOverworld ? Coords(cell, x, y) : ""; + if (row.Measured) + { + Offset(pCell, cell, out float ox, out float oy); + float dx = x + ox - px, dy = y + oy - py, dz = z - pz; + row.Distance = MathF.Sqrt(dx * dx + dy * dy + dz * dz); + float flat = MathF.Sqrt(dx * dx + dy * dy); + if (flat >= 0.5f) + { + float b = MathF.Atan2(dx, dy) * (180f / MathF.PI); + row.Bearing = b < 0 ? b + 360f : b; + row.CompassText = Compass16[(int)(row.Bearing / 22.5f) & 15]; + } + else + { + row.CompassText = "here"; + } + row.DistanceText = row.Distance.ToString("0", CultureInfo.InvariantCulture) + " yd"; + row.LocationText = objOverworld ? coords : "LB " + lb.ToString("X4", CultureInfo.InvariantCulture); + } + else + { + row.Distance = float.PositiveInfinity; + row.DistanceText = "elsewhere"; + row.CompassText = ""; + row.LocationText = objOverworld + ? coords + " (LB " + lb.ToString("X4", CultureInfo.InvariantCulture) + ")" + : "dungeon LB " + lb.ToString("X4", CultureInfo.InvariantCulture); + } + + bool isNew; + if (_firstSeen.TryGetValue(h.Id, out long first)) { isNew = false; } + else { isNew = true; first = flashNew ? now : 0; } + row.FirstSeenMs = first; + _firstSeenNext[h.Id] = first; + row.Tooltip = BuildTooltip(row, h.Term, cell, coords); + _rows.Add(row); + + if (isNew && alertNew && (!_lastAlertMs.TryGetValue(h.Id, out long last) || now - last > AlertCooldownMs)) + { + _lastAlertMs[h.Id] = now; + _alerts.Add(row); + } + } + (_firstSeen, _firstSeenNext) = (_firstSeenNext, _firstSeen); + + _rows.Sort(static (a, b) => + { + int c = a.Distance.CompareTo(b.Distance); + return c != 0 ? c : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); + }); + + RaiseAlerts(now); + + string status = _rows.Count switch + { + 0 => $"No matches among {ids.Length:N0} objects the client knows.", + 1 => $"1 match among {ids.Length:N0} objects the client knows.", + _ => $"{_rows.Count:N0} matches among {ids.Length:N0} objects the client knows.", + }; + Publish(new SenseView(_rows.ToArray(), status, ids.Length)); + } + + private void PublishStatus(string status, int known) + { + SenseView? cur = Current?.Value; + if (cur != null && cur.Rows.Length == 0 && cur.Status == status) return; + Publish(new SenseView(Array.Empty<SenseRow>(), status, known)); + } + + private void RaiseAlerts(long now) + { + if (now >= _nextAlertPruneMs) + { + _nextAlertPruneMs = now + 60_000; + List<uint>? stale = null; + foreach (var kv in _lastAlertMs) + if (now - kv.Value > AlertCooldownMs) (stale ??= new List<uint>()).Add(kv.Key); + if (stale != null) foreach (uint id in stale) _lastAlertMs.Remove(id); + } + if (_alerts.Count == 0) return; + + if (SenseStore.AlertChat) + { + _alerts.Sort(static (a, b) => a.Distance.CompareTo(b.Distance)); + int shown = Math.Min(MaxAlertLines, _alerts.Count); + for (int i = 0; i < shown; i++) + { + SenseRow r = _alerts[i]; + string where = r.Measured + ? r.DistanceText + (r.CompassText.Length > 0 && r.CompassText != "here" ? " " + r.CompassText : "") + : "elsewhere (" + r.LocationText + ")"; + AcMainThreadQueue.EnqueueWriteToChat("Sense: " + r.Name + " " + where, ChatType); + } + if (_alerts.Count > shown) + AcMainThreadQueue.EnqueueWriteToChat($"Sense: and {_alerts.Count - shown} more (open the Sense panel).", ChatType); + } + if (SenseStore.AlertBeep && now - _lastBeepMs > 3000) + { + _lastBeepMs = now; + try { MessageBeep(0x40); } catch { } // MB_ICONASTERISK; queued, returns at once + } + } + + private static SenseKind Classify(uint id, uint bitfield) + { + if ((bitfield & BfPlayer) != 0) return SenseKind.Player; + if ((bitfield & BfCorpse) != 0) return SenseKind.Corpse; + ClientObjectHooks.TryGetSnapshotItemType(id, out uint type); + if ((type & TypePortal) != 0 || (bitfield & BfPortal) != 0) return SenseKind.Portal; + if ((type & TypeCreature) != 0) + return ClientObjectHooks.TryGetSnapshotAttackable(id, out bool attackable) && attackable ? SenseKind.Monster : SenseKind.Npc; + return SenseKind.Item; + } + + public static string KindName(SenseKind kind) => kind switch + { + SenseKind.Monster => "Monster", + SenseKind.Npc => "NPC", + SenseKind.Player => "Player", + SenseKind.Portal => "Portal", + SenseKind.Corpse => "Corpse", + _ => "Item", + }; + + private static bool IsOutdoorCell(uint cell) => (cell & 0xFFFF) < 0x100; + + private bool IsOverworld(uint cell) => IsOutdoorCell(cell) || _overworldBlocks.Contains(cell >> 16); + + /// <summary>Metres from the player's landblock origin to <paramref name="cell"/>'s (192 m per landblock step).</summary> + private static void Offset(uint fromCell, uint cell, out float ox, out float oy) + { + int dxb = (int)((cell >> 24) & 0xFF) - (int)((fromCell >> 24) & 0xFF); + int dyb = (int)((cell >> 16) & 0xFF) - (int)((fromCell >> 16) & 0xFF); + ox = dxb * LandblockSize; + oy = dyb * LandblockSize; + } + + /// <summary>"42.1N 33.6E" (PlayerPhysicsHooks.TryGetLiveCoords' basis).</summary> + internal static string Coords(uint cell, float x, float y) + { + int lbX = (int)((cell >> 24) & 0xFF), lbY = (int)((cell >> 16) & 0xFF); + double ew = (lbX * 8.0 + x / 24.0 - 1019.5) / 10.0; + double ns = (lbY * 8.0 + y / 24.0 - 1019.5) / 10.0; + return Math.Abs(ns).ToString("0.0", CultureInfo.InvariantCulture) + (ns >= 0 ? "N " : "S ") + + Math.Abs(ew).ToString("0.0", CultureInfo.InvariantCulture) + (ew >= 0 ? "E" : "W"); + } + + private static string BuildTooltip(SenseRow r, SensePattern term, uint cell, string coords) + { + var sb = new StringBuilder(160); + sb.Append(r.Name).Append('\n'); + sb.Append(KindName(r.Kind)).Append(" 0x").Append(r.Id.ToString("X8", CultureInfo.InvariantCulture)).Append('\n'); + if (r.Measured) + { + sb.Append(r.DistanceText); + if (!float.IsNaN(r.Bearing)) + sb.Append(' ').Append(r.CompassText).Append(" (bearing ").Append(r.Bearing.ToString("0", CultureInfo.InvariantCulture)).Append("°)"); + else + sb.Append(", right here"); + sb.Append('\n'); + } + else + { + sb.Append("Elsewhere: not in the same space as you (another dungeon or landblock), so no distance.\n"); + } + if (coords.Length > 0) sb.Append(coords).Append(" "); + sb.Append("landblock ").Append((cell >> 16).ToString("X4", CultureInfo.InvariantCulture)) + .Append(", cell 0x").Append(cell.ToString("X8", CultureInfo.InvariantCulture)).Append('\n'); + sb.Append("Matches \"").Append(term.Text).Append("\"\n"); + sb.Append("Click to select it."); + return sb.ToString(); + } +} diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs new file mode 100644 index 0000000..45704cb --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -0,0 +1,741 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/SettingsData.cs +// RynthAi's Advanced Settings (docs/IMGUI_PARITY_PLAN.md §2.4): the payload, +// its hub source and save command, and the ONE schema both faces draw from +// (UI/Panels/SettingsPanel.cs, ImGui/Panels/SettingsFace.cs). +// +// To add a setting: add the property to RynthAiSettings (it must match +// RynthAi's SettingsBridgePayload) and a row to SettingsSchema.Tabs. Both +// faces pick it up. The payload always carries every property, so a save +// can't send a field missing (RynthAi applied missing fields as 0, 2026-09-27). +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>Mirrors RynthAi's SettingsBridgePayload (RynthPluginGet/SetSettingsJson).</summary> +internal sealed class RynthAiSettings +{ + // Display + public bool ShowTargetStaminaMana { get; set; } + // UI + public bool SuppressRetailRadar { get; set; } + // No rows (RynthAi's plugin-drawn radar/chat windows are gone); kept so the payload + // still carries them - a field missing from a save is applied as false. + public bool ShowRynthRadar { get; set; } + public bool RadarClickThrough { get; set; } + // Retail-chatbox suppression is owned by the RynthChat plugin ("Hide retail chat" + // in its gear menu); routing it through RynthAi's settings push fought that toggle. + public bool ShowRynthChat { get; set; } + public bool ChatClickThrough { get; set; } + public bool SuppressRetailPowerbar { get; set; } + // Misc + public bool EnableFPSLimit { get; set; } + public int TargetFPSFocused { get; set; } = 60; + public int TargetFPSBackground { get; set; } = 30; + public bool EnableAutocram { get; set; } + public bool PeaceModeWhenIdle { get; set; } + public bool StartMacroOnLogin { get; set; } + public bool PatrolOnLogin { get; set; } + // Decal bridge: stop RynthAi's macro when VTank's starts (one bot per client). Default on; + // an older RynthAi doesn't send it, and a missing field must not read as "off". + public bool YieldToVTank { get; set; } = true; + public bool EnableRaycasting { get; set; } + public bool UseArcs { get; set; } + public float BowArcVelocity { get; set; } = 25f; + public float MissileArcClearance { get; set; } = 0.5f; + // Vendoring (RynthAi AutoVendor; defaults match LegacyUiSettings) + public bool AutoVendorEnabled { get; set; } + public bool AutoVendorEnableBuying { get; set; } = true; + public bool AutoVendorEnableSelling { get; set; } = true; + public bool AutoVendorTestMode { get; set; } = true; + public bool AutoVendorThink { get; set; } + public bool AutoVendorShowMerchantInfo { get; set; } = true; + public bool AutoVendorOnlyFromMainPack { get; set; } + public int AutoVendorTries { get; set; } = 4; + public int AutoVendorTriesTime { get; set; } = 5000; + public bool LosDebugLog { get; set; } + public float CrossbowArcVelocity { get; set; } = 40f; + public float AtlatlArcVelocity { get; set; } = 22f; + // Arc spells' horizontal speed: ACE flies every player arc at 40 m/s across the ground. + public float MagicArcVelocity { get; set; } = 40f; + public int BlacklistAttempts { get; set; } = 3; + public int BlacklistTimeoutSec { get; set; } = 30; + // Not shown in the panel, but carried so a save doesn't send them missing. + public int BlacklistCastSettleMs { get; set; } = 1500; + public int MonsterDisengageRange { get; set; } + public int TargetNoProgressTimeoutSec { get; set; } + public int GiveQueueIntervalMs { get; set; } = 150; + // Recharge + public int HealAt { get; set; } = 60; + public int RestamAt { get; set; } = 30; + public int GetManaAt { get; set; } = 40; + public int TopOffHP { get; set; } = 95; + public int TopOffStam { get; set; } = 95; + public int TopOffMana { get; set; } = 95; + public int HealOthersAt { get; set; } = 50; + public int RestamOthersAt { get; set; } = 10; + public int InfuseOthersAt { get; set; } = 10; + // Kits, potions and safety stops + public bool UsePotions { get; set; } = true; + public bool UseBuffItems { get; set; } = true; + public int MakeRationsBelow { get; set; } = 5; + public bool UseKitsInMagicMode { get; set; } = true; + public bool PeaceModeForKits { get; set; } + public int KitMinSuccessPct { get; set; } = 70; + public int EmergencyHealAt { get; set; } = 30; + public int StaminaToHealthAt { get; set; } = 30; + public int StaminaToHealthMinStamina { get; set; } = 20; + public bool StopMacroOnDeath { get; set; } + public bool StopMacroOnNoComponents { get; set; } + public bool StopLootingWhenPackFull { get; set; } = true; + public bool StopMacroWhenPackFull { get; set; } + // Melee Combat + public bool UseRecklessness { get; set; } + public int MeleeAttackPower { get; set; } = -1; + public int MeleeAttackHeight { get; set; } = 1; + public int MissileAttackPower { get; set; } = -1; + public int MissileAttackHeight { get; set; } = 1; + public bool UseNativeAttack { get; set; } = true; + public bool SummonPets { get; set; } + public int PetMinMonsters { get; set; } = 1; + // Spell Combat + public int SpellCastIntervalMs { get; set; } = 400; + public int AttackSpellIntervalMs { get; set; } = 1500; + public bool CastDispelSelf { get; set; } + public int MinRingTargets { get; set; } = 4; + public int BlastRange { get; set; } + public int MinBlastTargets { get; set; } = 3; + public int MinSkillLevelTier1 { get; set; } = 35; + public int MinSkillLevelTier2 { get; set; } = 85; + public int MinSkillLevelTier3 { get; set; } = 135; + public int MinSkillLevelTier4 { get; set; } = 185; + public int MinSkillLevelTier5 { get; set; } = 235; + public int MinSkillLevelTier6 { get; set; } = 285; + public int MinSkillLevelTier7 { get; set; } = 335; + public int MinSkillLevelTier8 { get; set; } = 435; + // Ranges + public int MonsterRange { get; set; } = 50; + public int RingRange { get; set; } = 5; + public int ApproachRange { get; set; } = 4; + public double CorpseApproachRangeMax { get; set; } = 10.0; + public double CorpseApproachRangeMin { get; set; } = 2.0; + // Navigation + public bool BoostNavPriority { get; set; } + public float FollowNavMin { get; set; } = 1.5f; + public float NavRingThickness { get; set; } = 6f; + public float NavLineThickness { get; set; } = 6f; + public float NavHeightOffset { get; set; } = 0.05f; + public float NavSlopeSink { get; set; } = 1.5f; + public bool ShowTerrainPassability { get; set; } = true; + public bool OpenDoors { get; set; } + public float OpenDoorRange { get; set; } = 5f; + public bool AutoUnlockDoors { get; set; } + public int MovementMode { get; set; } + public float NavStopTurnAngle { get; set; } = 20f; + public float NavResumeTurnAngle { get; set; } = 10f; + public float NavDeadZone { get; set; } = 4f; + public float NavSweepMult { get; set; } = 2.5f; + public float NavLookaheadYards { get; set; } = 4f; + public float NavShortcutYards { get; set; } = 1f; + public float NavTurnRateDegPerSec { get; set; } = 270f; + public float NavTier1TurnSpeed { get; set; } = 3f; + public float PostPortalDelaySec { get; set; } = 4f; + public float T2Speed { get; set; } = 1f; + public float T2WalkWithinYd { get; set; } = 5f; + public float T2DistanceTo { get; set; } = 0.5f; + public float T2ReissueMs { get; set; } = 2000f; + public float T2MaxRangeYd { get; set; } = 500f; + public int T2MaxLandblocks { get; set; } = 3; + // Buffing + public bool EnableBuffing { get; set; } = true; + public bool RebuffWhenIdle { get; set; } + public int RebuffSecondsRemaining { get; set; } = 300; + public int RebuffTopOffSecondsRemaining { get; set; } = 1200; + public int BuffMinSkillLevelTier1 { get; set; } = 35; + public int BuffMinSkillLevelTier2 { get; set; } = 85; + public int BuffMinSkillLevelTier3 { get; set; } = 135; + public int BuffMinSkillLevelTier4 { get; set; } = 185; + public int BuffMinSkillLevelTier5 { get; set; } = 235; + public int BuffMinSkillLevelTier6 { get; set; } = 285; + public int BuffMinSkillLevelTier7 { get; set; } = 335; + public int BuffMinSkillLevelTier8 { get; set; } = 435; + // Crafting + public bool EnableMissileCrafting { get; set; } = true; + public string MissileCraftingState { get; set; } = string.Empty; + public bool MissileCraftingActive { get; set; } + public string MissileCraftingStatus { get; set; } = string.Empty; + // Looting + public bool EnableLooting { get; set; } + public bool BoostLootPriority { get; set; } + public bool LootOnlyRareCorpses { get; set; } + public bool LootJumpEnabled { get; set; } + public int LootJumpHeight { get; set; } = 10; + public int LootOwnership { get; set; } + public bool EnableAutostack { get; set; } = true; + public bool ReadUnknownScrolls { get; set; } = true; // VTank's default + public bool EnableCombineSalvage { get; set; } = true; + public bool CombineBagsDuringSalvage { get; set; } = true; + public int LootInterItemDelayMs { get; set; } = 50; + public int LootContentSettleMs { get; set; } = 100; + public int LootEmptyCorpseMs { get; set; } = 300; + public int LootClosingDelayMs { get; set; } = 200; + public int LootAssessWindowMs { get; set; } = 200; + public int LootRetryTimeoutMs { get; set; } = 500; + public int LootOpenRetryMs { get; set; } = 1500; + public int LootCorpseTimeoutMs { get; set; } = 12000; + public int SalvageOpenDelayFirstMs { get; set; } = 400; + public int SalvageOpenDelayFastMs { get; set; } = 50; + public int SalvageAddDelayFirstMs { get; set; } = 600; + public int SalvageAddDelayFastMs { get; set; } = 50; + public int SalvageSalvageDelayMs { get; set; } = 50; + public int SalvageResultDelayFirstMs { get; set; } = 1000; + public int SalvageResultDelayFastMs { get; set; } = 250; + + /// <summary>A private copy for a face to edit (all members are values or strings).</summary> + public RynthAiSettings Clone() => (RynthAiSettings)MemberwiseClone(); +} + +[JsonSerializable(typeof(RynthAiSettings))] +[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)] +internal partial class RynthAiSettingsJsonContext : JsonSerializerContext { } + +/// <summary>RynthPluginGetSettingsJson while a Settings face is open (5 s, and right after each save).</summary> +internal sealed unsafe class SettingsSource : UiSource<RynthAiSettings> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _getSettingsJson; + private string? _lastJson; + + public SettingsSource() : base("Settings", periodMs: 5000) { } + + protected internal override void Poll() + { + if (_getSettingsJson == null) + _getSettingsJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetSettingsJson"); + if (_getSettingsJson == null) return; + IntPtr ptr = _getSettingsJson(); + string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr); + if (string.IsNullOrEmpty(json) || json == _lastJson) return; + _lastJson = json; + RynthAiSettings? parsed = JsonSerializer.Deserialize(json, RynthAiSettingsJsonContext.Default.RynthAiSettings); + if (parsed != null) Publish(parsed); + } + + protected internal override void Reset() + { + _getSettingsJson = null; + _lastJson = null; + ClearSnapshot(); + } +} + +/// <summary>Saves the whole settings payload through RynthPluginSetSettingsJson, on the pump thread.</summary> +internal static unsafe class SettingsCommands +{ + private static delegate* unmanaged[Cdecl]<IntPtr, void> _setSettingsJson; + + static SettingsCommands() + { + Plugins.PluginManager.PluginsUnloaded += () => _setSettingsJson = null; + } + + /// <summary> + /// <paramref name="settings"/> must be a copy the caller no longer changes + /// (it is serialized later, on the pump thread). Any thread. + /// </summary> + public static void Save(RynthAiSettings settings) + { + UiDataHub.Post("RynthAi settings save", () => + { + if (_setSettingsJson == null) + _setSettingsJson = (delegate* unmanaged[Cdecl]<IntPtr, void>)PluginExportBinder.Resolve("RynthAi", "RynthPluginSetSettingsJson"); + if (_setSettingsJson == null) return; + string json = JsonSerializer.Serialize(settings, RynthAiSettingsJsonContext.Default.RynthAiSettings); + IntPtr ansi = Marshal.StringToHGlobalAnsi(json); + try { _setSettingsJson(ansi); } + finally { Marshal.FreeHGlobal(ansi); } + UiSources.Settings.RequestRefresh(); + }); + } +} + +// ── Schema ───────────────────────────────────────────────────────────────── + +internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button } + +/// <summary> +/// One row of a settings tab. Numeric values go through double (bools as +/// 0/1, combos as the index). <see cref="Gates"/> marks rows whose value +/// shows or hides other rows (the Avalonia face rebuilds the tab on change). +/// </summary> +internal sealed record SettingRow( + SettingKind Kind, + string Label, + string? Tooltip = null, + Func<RynthAiSettings, double>? Get = null, + Action<RynthAiSettings, double>? Set = null, + double Min = 0, + double Max = 0, + double Step = 1, + string[]? Items = null, + Func<RynthAiSettings, bool>? VisibleWhen = null, + bool Gates = false, + // Button rows: the button's caption (Label is the row label) and its action. Any thread. + string? ButtonText = null, + Action? Click = null) +{ + public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s); +} + +internal sealed record SettingsTab(string Name, SettingRow[] Rows); + +internal static class SettingsSchema +{ + // Also drawn on the Nav panel (ImGui/Panels/NavFace.cs). + public const string NavPointReachLabel = "Nav point reach (yd)"; + public const string NavPointReachTip = + "How close to get to each nav point before moving on to the next, in yards. VTank calls it " + + "Follow/Nav Min Distance (metas: FollowNavMin, or VTank's NavCloseStopRange). Follow stops this " + + "close to its leader, and the nav marker ring shows it. Dungeon doorways use at most 1 yd."; + + // Also shown by the dashboard's Ranges slide-out (ImGui/Panels/RangesSlideOut.cs), which + // edits these same rows (found by label with Find). + public const string MonsterRangeTip = + "How far away a monster can be for the bot to attack it, in yards. Monsters inside it also\n" + + "count as \"in combat\" for buffing and the In Combat heal/stamina/mana thresholds."; + public const string RingRangeTip = + "Ring spells replace a monster's other shape when at least Min Ring Targets monsters are\n" + + "within this many yards (the monster's rule needs Ring on)."; + public const string ApproachRangeTip = + "VTank's Approach Distance, in yards (metas: ApproachRange or ApproachDistance). Saved with\n" + + "the profile for metas; RynthAi's own combat doesn't use it at the moment."; + public const string CorpseMaxTip = + "Corpses within this many yards are walked to and looted (Looting on). Further ones are left."; + + /// <summary>The first row with <paramref name="label"/> on any tab (null if none). Not for per-frame use.</summary> + public static SettingRow? Find(string label) + { + foreach (SettingsTab tab in Tabs) + foreach (SettingRow row in tab.Rows) + if (row.Label == label) return row; + return null; + } + + public static readonly string[] AttackHeights = { "Low", "Medium", "High" }; + public static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" }; + + private static SettingRow Bool(string label, Func<RynthAiSettings, bool> get, Action<RynthAiSettings, bool> set, + string? tip = null, Func<RynthAiSettings, bool>? when = null, bool gates = false) => + new(SettingKind.Bool, label, tip, s => get(s) ? 1 : 0, (s, v) => set(s, v != 0), VisibleWhen: when, Gates: gates); + + private static SettingRow Int(string label, Func<RynthAiSettings, int> get, Action<RynthAiSettings, int> set, + int min, int max, int step, string? tip = null, Func<RynthAiSettings, bool>? when = null) => + new(SettingKind.Int, label, tip, s => get(s), (s, v) => set(s, (int)Math.Round(v)), min, max, step, VisibleWhen: when); + + private static SettingRow Float(string label, Func<RynthAiSettings, float> get, Action<RynthAiSettings, float> set, + float min, float max, float step, string? tip = null, Func<RynthAiSettings, bool>? when = null) => + new(SettingKind.Float, label, tip, s => get(s), (s, v) => set(s, (float)v), min, max, step, VisibleWhen: when); + + private static SettingRow Double(string label, Func<RynthAiSettings, double> get, Action<RynthAiSettings, double> set, + double min, double max, double step, string? tip = null) => + new(SettingKind.Double, label, tip, get, set, min, max, step); + + private static SettingRow Combo(string label, string[] items, Func<RynthAiSettings, int> get, Action<RynthAiSettings, int> set, + string? tip = null) => + new(SettingKind.Combo, label, tip, s => get(s), (s, v) => set(s, (int)v), 0, items.Length - 1, 1, items); + + // Text size rows are stored by the engine (PanelTextScale), not in the + // RynthAi profile, so the settings object is ignored here. + private static SettingRow TextSize(string label, string panelTitle) => + Combo(" " + label, PanelTextScale.SizeNames, _ => PanelTextScale.GetOwn(panelTitle), (_, v) => PanelTextScale.Set(panelTitle, v), + "Text size for this panel in the game: 0 = normal, each step 10% bigger, yourjokin = 2.5x.") + with { VisibleWhen = _ => PanelTextScale.PerPanel }; + + private static SettingRow Section(string text, Func<RynthAiSettings, bool>? when = null) => + new(SettingKind.Section, text, VisibleWhen: when); + + private static SettingRow Spacer(Func<RynthAiSettings, bool>? when = null) => + new(SettingKind.Spacer, "", VisibleWhen: when); + + private static SettingRow Note(string text, Func<RynthAiSettings, bool>? when = null) => + new(SettingKind.Note, text, VisibleWhen: when); + + private static SettingRow Button(string label, string buttonText, Action click, string? tip = null) => + new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click); + + private static SettingRow[] Tiers(Func<RynthAiSettings, int>[] get, Action<RynthAiSettings, int>[] set) + { + var rows = new SettingRow[get.Length]; + for (int i = 0; i < rows.Length; i++) + rows[i] = Int($"Level {i + 1}", get[i], set[i], 1, 500, 5); + return rows; + } + + private static SettingRow[] Concat(params object[] parts) + { + var list = new System.Collections.Generic.List<SettingRow>(); + foreach (object p in parts) + { + if (p is SettingRow r) list.Add(r); + else if (p is SettingRow[] rs) list.AddRange(rs); + } + return list.ToArray(); + } + + public static readonly SettingsTab[] Tabs = + { + new("Display", new[] + { + Bool("Show Target Stamina / Mana", s => s.ShowTargetStaminaMana, (s, v) => s.ShowTargetStaminaMana = v, + "When enabled, displays stamina and mana bars for the selected target (requires appraisal data)."), + Spacer(), + Section("Text Size (in-game panels)"), + Combo("All Panels", PanelTextScale.SizeNames, _ => PanelTextScale.GetAll(), (_, v) => PanelTextScale.SetAll(v), + "Text size for every in-game panel: 0 = normal, each step 10% bigger, yourjokin = 2.5x."), + Bool("Size Each Panel Separately", _ => PanelTextScale.PerPanel, (_, v) => PanelTextScale.PerPanel = v, + "Off: every panel uses All Panels. On: set each panel's text size below.", gates: true), + TextSize("RynthAi Dashboard", "RynthAi"), + TextSize("Meta", "Meta"), + TextSize("Damage", "Damage"), + TextSize("Settings", "Settings"), + TextSize("Monsters", "Monsters"), + TextSize("Nav", "Nav"), + TextSize("Items", "Items"), + TextSize("Lua", "Lua"), + TextSize("Radar", "Radar"), + TextSize("Chat Filters", "ChatFilters"), + TextSize("RynthNav", "RynthNav"), + TextSize("Vision", "Vision"), + TextSize("Status", "Status"), + TextSize("Log", "Log"), + TextSize("Tracker", "Tracker"), + }), + + new("UI", new[] + { + Section("Radar"), + Bool("Hide retail radar", s => s.SuppressRetailRadar, (s, v) => s.SuppressRetailRadar = v, + "Suppress the game's built-in radar (bezel, compass, coords, blips)."), + // "Show RynthRadar" / "Radar Click-Through" and "Show RynthChat" / "Chat Click-Through" + // drove RynthAi's plugin-drawn radar and chat windows, which the engine no longer + // draws (plugin ImGui rendering is RYNTHCORE_FORCE_IMGUI only). The Radar and Chat + // panels open from the bar and have their own click-through (hold Ctrl) in their + // gear menus. "Hide retail chat" lives in the Chat panel's gear menu + // ("Hide retail chat"). The four fields stay in the payload so RynthAi and the + // engine keep round-tripping them whichever is newer. + Spacer(), + Section("Power Bar"), + Bool("Hide retail power bar", s => s.SuppressRetailPowerbar, (s, v) => s.SuppressRetailPowerbar = v, + "Hide the vanilla attack/magic power bar that appears under the cursor while charging.\nThe bar's underlying combat state still works — only the on-screen widget is hidden."), + Spacer(), + Section("Vitals"), + // Stored by the engine (RetailVitalsHooks, %LOCALAPPDATA%\RynthCore\retail_ui.txt), + // not in the RynthAi profile, so the settings object is ignored here. + Bool("Hide retail vitals bar", _ => Compatibility.RetailVitalsHooks.HideRetailVitals, + (_, v) => Compatibility.RetailVitalsHooks.HideRetailVitals = v, + "Hide the game's own health/stamina/mana bars; the RynthVision player plate and the RynthAi dashboard show them.\nSaved for this PC. Also: /rc ui retailvitals on|off."), + }), + + new("Misc", new[] + { + Bool("Enable FPS Limit", s => s.EnableFPSLimit, (s, v) => s.EnableFPSLimit = v, gates: true), + Int("Focused FPS", s => s.TargetFPSFocused, (s, v) => s.TargetFPSFocused = v, 10, 240, 1, when: s => s.EnableFPSLimit), + Int("Background FPS", s => s.TargetFPSBackground, (s, v) => s.TargetFPSBackground = v, 5, 60, 1, when: s => s.EnableFPSLimit), + Spacer(), + Bool("Auto Cram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v, + "Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."), + Bool("Peace Mode When Idle", s => s.PeaceModeWhenIdle, (s, v) => s.PeaceModeWhenIdle = v), + Bool("Start Macro On Login", s => s.StartMacroOnLogin, (s, v) => s.StartMacroOnLogin = v, + "Automatically starts the macro when RynthAi loads."), + Bool("Patrol On Login", s => s.PatrolOnLogin, (s, v) => s.PatrolOnLogin = v, + "Automatically starts dungeon patrol when RynthAi loads."), + Bool("Yield to VTank", s => s.YieldToVTank, (s, v) => s.YieldToVTank = v, + "With Decal: when VTank's macro starts (/vt start), RynthAi's macro stops, and it won't start while VTank runs.\nOne bot per client. Without Decal this does nothing. Also: /ra vtankyield on|off."), + Bool("Enable Raycasting", s => s.EnableRaycasting, (s, v) => s.EnableRaycasting = v), + Spacer(), + Section("Missile Arc Velocities (m/s)"), + Bool("Use Arcs for Missile LoS", s => s.UseArcs, (s, v) => s.UseArcs = v, + "A missile target must pass both the straight line and the real arrow arc, ceilings included (dungeons too).\nWhen off, all missile LoS checks are linear (eye-to-eye).", gates: true), + Float("Bow", s => s.BowArcVelocity, (s, v) => s.BowArcVelocity = v, 10f, 60f, 0.5f, + "Bow projectile speed (m/s). Lower = higher arc.", when: s => s.UseArcs), + Float("Crossbow", s => s.CrossbowArcVelocity, (s, v) => s.CrossbowArcVelocity = v, 10f, 80f, 0.5f, when: s => s.UseArcs), + Float("Atlatl", s => s.AtlatlArcVelocity, (s, v) => s.AtlatlArcVelocity = v, 10f, 60f, 0.5f, when: s => s.UseArcs), + Float("Magic Arc", s => s.MagicArcVelocity, (s, v) => s.MagicArcVelocity = v, 10f, 60f, 0.5f, + "Arc spells' horizontal speed (m/s). ACE: 40. Lower = higher arc.\nA monster rule with Arc on casts an arc only when this path reaches the target (walls, and ceilings in dungeons); otherwise its other shape (Streak, Blast) or a bolt. Needs Enable Raycasting. /ra lostest magic shows the arc to the selected mob."), + Float("Arc Clearance (m)", s => s.MissileArcClearance, (s, v) => s.MissileArcClearance = MathF.Max(0f, v), 0f, 3f, 0.1f, + "Extra headroom the arc must have at mid-flight. Raise it if arrows still hit ceilings; lower it if reachable mobs get skipped.", when: s => s.UseArcs), + Bool("LoS Debug Log", s => s.LosDebugLog, (s, v) => s.LosDebugLog = v, + "Log each blocked missile target and why (arc peak, where it hits) to the RynthCore log. /ra lostest bow tests the selected mob."), + Spacer(), + Section("Monster Blacklist"), + Int("Attempts Before Blacklist", s => s.BlacklistAttempts, (s, v) => s.BlacklistAttempts = v, 1, 20, 1, + "How many failed attack attempts on a mob before it gets blacklisted."), + Int("Blacklist Timeout (sec)", s => s.BlacklistTimeoutSec, (s, v) => s.BlacklistTimeoutSec = v, 5, 120, 5, + "How long a blacklisted mob is ignored before re-trying."), + Int("No Progress Timeout (sec)", s => s.TargetNoProgressTimeoutSec, (s, v) => s.TargetNoProgressTimeoutSec = v, 0, 300, 10, + "Blacklist a target after being engaged this many seconds without dealing damage.\n0 = disabled. Default 60s."), + Spacer(), + Section("Give Queue"), + Int("Give Interval (ms)", s => s.GiveQueueIntervalMs, (s, v) => s.GiveQueueIntervalMs = v, 50, 2000, 50, + "Minimum delay between each item sent by /ra givea commands."), + }), + + new("Recharge", new[] + { + Section("In Combat — target within Monster Range (%)"), + Int("Heal At", s => s.HealAt, (s, v) => s.HealAt = v, 0, 100, 1, + "While a target is within Monster Range, cast Heal Self when HP < this %."), + Int("Re-stam At", s => s.RestamAt, (s, v) => s.RestamAt = v, 0, 100, 1, + "While a target is within Monster Range, cast Revitalize Self when Stamina < this %."), + Int("Get Mana At", s => s.GetManaAt, (s, v) => s.GetManaAt = v, 0, 100, 1, + "While a target is within Monster Range, cast Stamina to Mana Self when Mana < this % (needs stam > 15%)."), + Spacer(), + Section("Idle Top-Off — no targets in range (%)"), + Int("Top HP", s => s.TopOffHP, (s, v) => s.TopOffHP = v, 0, 100, 1, + "When no targets are within Monster Range, heal up to this HP %. Usually set higher than Heal At."), + Int("Top Stam", s => s.TopOffStam, (s, v) => s.TopOffStam = v, 0, 100, 1, + "When no targets are within Monster Range, re-stam up to this %."), + Int("Top Mana", s => s.TopOffMana, (s, v) => s.TopOffMana = v, 0, 100, 1, + "When no targets are within Monster Range, recharge mana up to this %."), + Spacer(), + Section("Kits & Potions"), + Bool("Use Potions", s => s.UsePotions, (s, v) => s.UsePotions = v, + "Drink health, mana and stamina potions from the Items panel when a vital is low\nand no spell can fix it (no spell, Life Magic untrained, out of components)."), + Bool("Use Buff Items", s => s.UseBuffItems, (s, v) => s.UseBuffItems = v, + "Use Asheron's Benediction, Asheron's Lesser Benediction and Blackmoor's Favor\nfrom your pack whenever their buff isn't on you (they're never used up)."), + Int("Make Field Rations Below", s => s.MakeRationsBelow, (s, v) => s.MakeRationsBelow = v, 0, 100, 1, + "Cook field rations (Cooking Pot on Dried Rations, 25 at a time) when you have fewer than this.\n0 = off. Rations restore stamina and are eaten like stamina potions."), + Bool("Use Kits In Magic Mode", s => s.UseKitsInMagicMode, (s, v) => s.UseKitsInMagicMode = v, + "Allow healing kits while in magic mode."), + Bool("Peace Mode For Kits", s => s.PeaceModeForKits, (s, v) => s.PeaceModeForKits = v, + "Switch to peace mode before using a healing kit."), + Int("Emergency Heal At", s => s.EmergencyHealAt, (s, v) => s.EmergencyHealAt = v, 0, 100, 1, + "At or under this health %, out of Magic mode a healing kit is used ahead of the\nnormal Heal At chain (kit, Heal Self, potion), and while a spell cast is pending a kit\nor potion is used. Stamina to Health has its own line below. 0 = off. Starts at 30."), + Int("Stamina To Health At", s => s.StaminaToHealthAt, (s, v) => s.StaminaToHealthAt = v, 0, 100, 1, + "At or under this health %, cast Stamina to Health Self ahead of the normal\nHeal At chain (out of Magic mode a kit is tried first). If it can't be cast,\nthe normal chain (kit, Heal Self, potion) runs. 0 = never cast it. Starts at 30."), + Int("Stamina To Health Min Stamina", s => s.StaminaToHealthMinStamina, (s, v) => s.StaminaToHealthMinStamina = v, 0, 100, 1, + "Cast Stamina to Health only while stamina is over this %, so it doesn't\ndrain you to nothing. Starts at 20."), + Int("Kit Min Success %", s => s.KitMinSuccessPct, (s, v) => s.KitMinSuccessPct = v, 0, 100, 1, + "Use a healing or stamina kit only when its chance to work is at least this %,\nworked out like the server does: Healing skill + the kit's bonus vs. what's missing.\nBelow it, the spell is cast instead. 0 = always use kits. Starts at 70."), + Spacer(), + Section("Safety Stops"), + Bool("Stop Macro On Death", s => s.StopMacroOnDeath, (s, v) => s.StopMacroOnDeath = v, + "Stop the macro when you die. Off by default: most metas run back on their own."), + Bool("Stop Macro On No Components", s => s.StopMacroOnNoComponents, (s, v) => s.StopMacroOnNoComponents = v, + "Stop the macro after 3 \"missing components\" failures within a minute."), + Bool("Stop Macro When Pack Full", s => s.StopMacroWhenPackFull, (s, v) => s.StopMacroWhenPackFull = v, + "Stop the macro when no pack has a free slot."), + Spacer(), + Section("Helper Settings (%) — NOT WIRED YET"), + Int("Heal Others", s => s.HealOthersAt, (s, v) => s.HealOthersAt = v, 0, 100, 1, + "Intended: cast Heal Other on a fellow when their HP < this %. Not implemented yet — slider is inert."), + Int("Re-stam Others", s => s.RestamOthersAt, (s, v) => s.RestamOthersAt = v, 0, 100, 1, + "Intended: cast Revitalize Other on a fellow when their Stamina < this %. Not implemented yet — slider is inert."), + Int("Infuse Others", s => s.InfuseOthersAt, (s, v) => s.InfuseOthersAt = v, 0, 100, 1, + "Intended: cast Infuse Mana Other on a fellow when their Mana < this %. Not implemented yet — slider is inert."), + }), + + new("Melee Combat", new[] + { + Section("Attack Power & Height"), + Bool("Use Recklessness", s => s.UseRecklessness, (s, v) => s.UseRecklessness = v, + "When enabled and Recklessness is trained, auto power uses 80% instead of 100%."), + Spacer(), + Bool("Melee Auto Power", s => s.MeleeAttackPower < 0, (s, v) => s.MeleeAttackPower = v ? -1 : 100, gates: true), + Int("Melee Power %", s => s.MeleeAttackPower, (s, v) => s.MeleeAttackPower = v, 0, 100, 5, when: s => s.MeleeAttackPower >= 0), + Combo("Melee Attack Height", AttackHeights, s => s.MeleeAttackHeight, (s, v) => s.MeleeAttackHeight = v), + Spacer(), + Bool("Missile Auto Power", s => s.MissileAttackPower < 0, (s, v) => s.MissileAttackPower = v ? -1 : 100, gates: true), + Int("Missile Power %", s => s.MissileAttackPower, (s, v) => s.MissileAttackPower = v, 0, 100, 5, when: s => s.MissileAttackPower >= 0), + Combo("Missile Attack Height", AttackHeights, s => s.MissileAttackHeight, (s, v) => s.MissileAttackHeight = v), + Spacer(), + Bool("Use Native Attack", s => s.UseNativeAttack, (s, v) => s.UseNativeAttack = v, + "Uses the client's combat pipeline for attacks.\nThe client handles turn-to-face naturally (no backwards arrows)."), + Spacer(), + Bool("Summon Pets", s => s.SummonPets, (s, v) => s.SummonPets = v), + Int("Pet Min Monsters", s => s.PetMinMonsters, (s, v) => s.PetMinMonsters = v, 1, 20, 1), + }), + + new("Spell Combat", Concat( + Section("War/Void Casting Settings"), + Int("Buff Spell Interval (ms)", s => s.SpellCastIntervalMs, (s, v) => s.SpellCastIntervalMs = v, 100, 1500, 50, + "Delay between BUFF / utility spell casts (not combat).\nLower = faster buff chains. 400ms is a good balance.\nBelow 200ms may cause fizzles or dropped casts on laggy servers."), + Int("Attack Spell Delay (ms)", s => s.AttackSpellIntervalMs, (s, v) => s.AttackSpellIntervalMs = v, 250, 5000, 50, + "Delay between offensive (war/void) COMBAT casts only.\nSpacing casts ~1-2s (1500ms default) stops back-to-back\n\"You're too busy!\" refusals that drop casts and cost kills.\nDoes NOT affect buffing speed."), + Bool("Cast Dispel Self", s => s.CastDispelSelf, (s, v) => s.CastDispelSelf = v), + Spacer(), + Section("Ring Spell Override"), + Int("Min Ring Targets", s => s.MinRingTargets, (s, v) => s.MinRingTargets = v, 1, 20, 1, + "If this many monsters are within ring range, ring spells are used instead of arc/bolt/streak."), + Spacer(), + Section("Blast Spell Override"), + Int("Blast Range (yd)", s => s.BlastRange, (s, v) => s.BlastRange = v, 0, 100, 1, + "0 = off: monsters with Blast on always cast blasts.\nAbove 0: a blast is cast only when Min Blast Targets monsters are\nwithin this range in the blast's fan toward the target (it fires 3\nprojectiles over 90 degrees); otherwise the monster's other shape, or a bolt."), + Int("Min Blast Targets", s => s.MinBlastTargets, (s, v) => s.MinBlastTargets = v, 1, 20, 1, + "How many monsters (the target included) must be in the blast's fan, within Blast Range."), + Spacer(), + Section("Spell Difficulty (Min Buffed Skill)"), + Tiers( + new Func<RynthAiSettings, int>[] { s => s.MinSkillLevelTier1, s => s.MinSkillLevelTier2, s => s.MinSkillLevelTier3, s => s.MinSkillLevelTier4, + s => s.MinSkillLevelTier5, s => s.MinSkillLevelTier6, s => s.MinSkillLevelTier7, s => s.MinSkillLevelTier8 }, + new Action<RynthAiSettings, int>[] { (s, v) => s.MinSkillLevelTier1 = v, (s, v) => s.MinSkillLevelTier2 = v, (s, v) => s.MinSkillLevelTier3 = v, (s, v) => s.MinSkillLevelTier4 = v, + (s, v) => s.MinSkillLevelTier5 = v, (s, v) => s.MinSkillLevelTier6 = v, (s, v) => s.MinSkillLevelTier7 = v, (s, v) => s.MinSkillLevelTier8 = v }))), + + new("Ranges", new[] + { + Section("Standard Ranges (Yards)"), + Int("Monster Range", s => s.MonsterRange, (s, v) => s.MonsterRange = v, 1, 200, 1, MonsterRangeTip), + Int("Ring Range", s => s.RingRange, (s, v) => s.RingRange = v, 1, 50, 1, RingRangeTip), + Int("Approach Range", s => s.ApproachRange, (s, v) => s.ApproachRange = v, 1, 50, 1, ApproachRangeTip), + Spacer(), + Section("Corpse Acquisition (Yards)"), + Double("Corpse Max (yd)", s => s.CorpseApproachRangeMax, (s, v) => s.CorpseApproachRangeMax = v, 0.5, 50.0, 0.5, CorpseMaxTip), + Double("Corpse Min (yd)", s => s.CorpseApproachRangeMin, (s, v) => s.CorpseApproachRangeMin = v, 0.5, 20.0, 0.5, + "How close to walk to a corpse before opening it, in yards (never more than Corpse Max)."), + }), + + new("Navigation", new[] + { + Bool("Boost Nav Priority", s => s.BoostNavPriority, (s, v) => s.BoostNavPriority = v), + Float(NavPointReachLabel, s => s.FollowNavMin, (s, v) => s.FollowNavMin = v, 0.5f, 20f, 0.1f, NavPointReachTip), + Spacer(), + Section("Nav Marker Display"), + Float("Ring Thickness", s => s.NavRingThickness, (s, v) => s.NavRingThickness = v, 1f, 16f, 1f), + Float("Line Thickness", s => s.NavLineThickness, (s, v) => s.NavLineThickness = v, 1f, 16f, 1f), + Float("Height Offset", s => s.NavHeightOffset, (s, v) => s.NavHeightOffset = v, -5f, 5f, 0.05f, + "Vertical offset for nav markers above the ground. Negative = lower."), + Float("Slope Sink", s => s.NavSlopeSink, (s, v) => s.NavSlopeSink = v, 0f, 8f, 0.1f, + "Extra downward offset on slopes only, per unit of terrain steepness. 0 = off; flat ground is unaffected. ~1.5 cancels the float for a default-radius ring."), + Bool("Show Terrain Passability", s => s.ShowTerrainPassability, (s, v) => s.ShowTerrainPassability = v, + "Highlight impassable terrain triangles in red."), + Spacer(), + Section("Doors"), + Bool("Open Doors While Navigating", s => s.OpenDoors, (s, v) => s.OpenDoors = v, + "Automatically open doors encountered during navigation.", gates: true), + Float("Door Detection Range (yd)", s => s.OpenDoorRange, (s, v) => s.OpenDoorRange = v, 0.1f, 70f, 1f, when: s => s.OpenDoors), + Bool("Auto-Unlock Doors", s => s.AutoUnlockDoors, (s, v) => s.AutoUnlockDoors = v, + "If a door is locked, try to use a lockpick from your Consumable Items list.", when: s => s.OpenDoors), + Spacer(), + Section("Steering"), + Float("Stop & Turn Angle", s => s.NavStopTurnAngle, (s, v) => s.NavStopTurnAngle = v, 1f, 90f, 1f, + "Stop forward motion and turn in place when heading error exceeds this."), + Float("Resume Run Angle", s => s.NavResumeTurnAngle, (s, v) => s.NavResumeTurnAngle = v, 1f, 45f, 1f, + "Resume running once the turn-in-place error drops below this."), + Float("Dead Zone", s => s.NavDeadZone, (s, v) => s.NavDeadZone = v, 0.5f, 20f, 0.5f, + "Ignore heading corrections smaller than this."), + Float("Sweep Detect Mult", s => s.NavSweepMult, (s, v) => s.NavSweepMult = v, 0.5f, 10f, 0.1f, + "Closest-approach detection radius multiplier."), + Float("Lookahead (yd)", s => s.NavLookaheadYards, (s, v) => s.NavLookaheadYards = MathF.Max(0f, v), 0f, 30f, 0.5f, + "Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off."), + Float("Turn Rate (deg/s)", s => s.NavTurnRateDegPerSec, (s, v) => s.NavTurnRateDegPerSec = v, 30f, 720f, 15f, + "Max turn speed while navigating. Higher = snappier turns, lower = gentler."), + Float("Post-Portal Delay (s)", s => s.PostPortalDelaySec, (s, v) => s.PostPortalDelaySec = MathF.Max(0f, v), 0f, 30f, 0.25f, + "Seconds to settle after any portal/recall teleport before nav resumes."), + Spacer(when: s => s.MovementMode == 2), + Section("Tier 2 Tuning", when: s => s.MovementMode == 2), + Float("Speed", s => s.T2Speed, (s, v) => s.T2Speed = v, 0.1f, 5f, 0.1f, when: s => s.MovementMode == 2), + Float("Walk Within (yd)", s => s.T2WalkWithinYd, (s, v) => s.T2WalkWithinYd = v, 1f, 50f, 1f, when: s => s.MovementMode == 2), + Float("Stop Distance (yd)", s => s.T2DistanceTo, (s, v) => s.T2DistanceTo = v, 0.1f, 10f, 0.1f, when: s => s.MovementMode == 2), + Float("Reissue Timeout (ms)", s => s.T2ReissueMs, (s, v) => s.T2ReissueMs = v, 100f, 10000f, 100f, when: s => s.MovementMode == 2), + Float("Max Range (yd)", s => s.T2MaxRangeYd, (s, v) => s.T2MaxRangeYd = v, 50f, 2000f, 50f, when: s => s.MovementMode == 2), + Int("Max Landblock Dist", s => s.T2MaxLandblocks, (s, v) => s.T2MaxLandblocks = v, 1, 20, 1, when: s => s.MovementMode == 2), + }), + + new("Buffing", Concat( + Bool("Enable Buffing", s => s.EnableBuffing, (s, v) => s.EnableBuffing = v), + Bool("Rebuff When Idle", s => s.RebuffWhenIdle, (s, v) => s.RebuffWhenIdle = v), + Int("Rebuff With (seconds left)", s => s.RebuffSecondsRemaining, (s, v) => s.RebuffSecondsRemaining = v, 30, 1800, 30, + "Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly."), + Int("Also Refresh Under (seconds left)", s => s.RebuffTopOffSecondsRemaining, (s, v) => s.RebuffTopOffSecondsRemaining = v, 30, 3600, 60, + "When a buff is due, also recast every other buff with less than this much time left,\nso they land together. Buffs with more time are left alone. Default 1200 (20 minutes).\nAt or below 'Rebuff With', only the expiring buff is recast."), + Spacer(), + Section("Buff Difficulty (Min Buffed Skill)"), + Tiers( + new Func<RynthAiSettings, int>[] { s => s.BuffMinSkillLevelTier1, s => s.BuffMinSkillLevelTier2, s => s.BuffMinSkillLevelTier3, s => s.BuffMinSkillLevelTier4, + s => s.BuffMinSkillLevelTier5, s => s.BuffMinSkillLevelTier6, s => s.BuffMinSkillLevelTier7, s => s.BuffMinSkillLevelTier8 }, + new Action<RynthAiSettings, int>[] { (s, v) => s.BuffMinSkillLevelTier1 = v, (s, v) => s.BuffMinSkillLevelTier2 = v, (s, v) => s.BuffMinSkillLevelTier3 = v, (s, v) => s.BuffMinSkillLevelTier4 = v, + (s, v) => s.BuffMinSkillLevelTier5 = v, (s, v) => s.BuffMinSkillLevelTier6 = v, (s, v) => s.BuffMinSkillLevelTier7 = v, (s, v) => s.BuffMinSkillLevelTier8 = v }))), + + new("Crafting", new[] + { + Section("Missile Ammo Crafting"), + Bool("Enable Missile Crafting", s => s.EnableMissileCrafting, (s, v) => s.EnableMissileCrafting = v, + "Auto-manage missile ammo when the ammo slot is empty or low.", gates: true), + Note("(Disabled)", when: s => !s.EnableMissileCrafting), + Spacer(when: s => s.EnableMissileCrafting), + new SettingRow(SettingKind.CraftingStatus, "State:", VisibleWhen: s => s.EnableMissileCrafting && !string.IsNullOrEmpty(s.MissileCraftingState)), + }), + + new("Looting", new[] + { + Bool("Enable Looting", s => s.EnableLooting, (s, v) => s.EnableLooting = v), + Bool("Boost Loot Priority", s => s.BoostLootPriority, (s, v) => s.BoostLootPriority = v), + Bool("Loot Only Rare Corpses", s => s.LootOnlyRareCorpses, (s, v) => s.LootOnlyRareCorpses = v), + Bool("Learn Unknown Spells", s => s.ReadUnknownScrolls, (s, v) => s.ReadUnknownScrolls = v, + "Loots scrolls of spells you don't know and can learn (magic school trained or\nspecialized, skill high enough), and reads them when it's safe. Scrolls already\nin your pack are read too. Needs Enable Looting for corpses."), + Bool("Stop Looting When Pack Full", s => s.StopLootingWhenPackFull, (s, v) => s.StopLootingWhenPackFull = v, + "Don't start on another corpse when no pack has a free slot (says so once in chat)."), + Bool("Jump When Looting", s => s.LootJumpEnabled, (s, v) => s.LootJumpEnabled = v, gates: true), + Int("Jump Height", s => s.LootJumpHeight, (s, v) => s.LootJumpHeight = v, 1, 100, 5, when: s => s.LootJumpEnabled), + Spacer(), + Section("Corpse Ownership"), + Combo("Loot From", LootOwnershipModes, s => s.LootOwnership, (s, v) => s.LootOwnership = v), + Spacer(), + Section("Inventory Management"), + Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v), + Bool("Enable Autocram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v, + "Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."), + Bool("Combine Salvage Bags", s => s.EnableCombineSalvage, (s, v) => s.EnableCombineSalvage = v, + "After the salvage queue empties, move same-name bags together so the server merges them."), + Bool("Combine Bags During Salvage", s => s.CombineBagsDuringSalvage, (s, v) => s.CombineBagsDuringSalvage = v, + "When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel."), + Button("Floating HUDs", "Inventory HUDs...", () => RynthAiCommands.ApplyRemoteCommand("huds", "show"), + "Opens the item count HUD / Mini Remote setup window (/ra huds)."), + Spacer(), + Section("Loot Timers (ms)"), + Int("Inter-Item Delay", s => s.LootInterItemDelayMs, (s, v) => s.LootInterItemDelayMs = v, 0, 5000, 25), + Int("Content Settle", s => s.LootContentSettleMs, (s, v) => s.LootContentSettleMs = v, 0, 5000, 25), + Int("Empty Corpse Wait", s => s.LootEmptyCorpseMs, (s, v) => s.LootEmptyCorpseMs = v, 0, 5000, 25), + Int("Closing Delay", s => s.LootClosingDelayMs, (s, v) => s.LootClosingDelayMs = v, 0, 5000, 25), + Int("Assess Window", s => s.LootAssessWindowMs, (s, v) => s.LootAssessWindowMs = v, 0, 5000, 25), + Int("Loot Retry Timeout", s => s.LootRetryTimeoutMs, (s, v) => s.LootRetryTimeoutMs = v, 0, 10000, 100), + Int("Corpse Open Retry", s => s.LootOpenRetryMs, (s, v) => s.LootOpenRetryMs = v, 0, 10000, 100), + Int("Corpse Timeout", s => s.LootCorpseTimeoutMs, (s, v) => s.LootCorpseTimeoutMs = v, 0, 60000, 500), + Spacer(), + Section("Salvage Timers (ms) - First / Fast"), + Int("Open (First)", s => s.SalvageOpenDelayFirstMs, (s, v) => s.SalvageOpenDelayFirstMs = v, 0, 5000, 50), + Int("Open (Fast)", s => s.SalvageOpenDelayFastMs, (s, v) => s.SalvageOpenDelayFastMs = v, 0, 2000, 25), + Int("Add Item (First)", s => s.SalvageAddDelayFirstMs, (s, v) => s.SalvageAddDelayFirstMs = v, 0, 5000, 50), + Int("Add Item (Fast)", s => s.SalvageAddDelayFastMs, (s, v) => s.SalvageAddDelayFastMs = v, 0, 2000, 25), + Int("Salvage Click", s => s.SalvageSalvageDelayMs, (s, v) => s.SalvageSalvageDelayMs = v, 0, 2000, 25), + Int("Result (First)", s => s.SalvageResultDelayFirstMs, (s, v) => s.SalvageResultDelayFirstMs = v, 0, 5000, 50), + Int("Result (Fast)", s => s.SalvageResultDelayFastMs, (s, v) => s.SalvageResultDelayFastMs = v, 0, 2000, 25), + }), + + new("Vendoring", new[] + { + Section("AutoVendor"), + Bool("Enabled", s => s.AutoVendorEnabled, (s, v) => s.AutoVendorEnabled = v, + "Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\nProfile: <Vendor Name>.utl, else default.utl, in the AutoVendor folder."), + Bool("Test Mode (only print what it would do)", s => s.AutoVendorTestMode, (s, v) => s.AutoVendorTestMode = v, + "Lists what would be bought and sold without trading. Leave this on until the lists look right."), + Bool("Buy", s => s.AutoVendorEnableBuying, (s, v) => s.AutoVendorEnableBuying = v), + Bool("Sell", s => s.AutoVendorEnableSelling, (s, v) => s.AutoVendorEnableSelling = v), + Bool("Only Sell From Main Pack", s => s.AutoVendorOnlyFromMainPack, (s, v) => s.AutoVendorOnlyFromMainPack = v), + Bool("Show Merchant Info", s => s.AutoVendorShowMerchantInfo, (s, v) => s.AutoVendorShowMerchantInfo = v, + "Print the vendor's buy/sell rates and max value when it opens."), + Bool("Think When Finished", s => s.AutoVendorThink, (s, v) => s.AutoVendorThink = v, + "Send 'AutoVendor finished: <vendor>' (and failures) as a /tell to yourself, for metas."), + Spacer(), + Section("/ub vendor open"), + Int("Tries", s => s.AutoVendorTries, (s, v) => s.AutoVendorTries = v, 1, 20, 1), + Int("Time Between Tries (ms)", s => s.AutoVendorTriesTime, (s, v) => s.AutoVendorTriesTime = v, 500, 30000, 250), + Spacer(), + Note("Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match."), + }), + }; +} diff --git a/src/RynthCore.Engine/UI/Data/UiDataHub.cs b/src/RynthCore.Engine/UI/Data/UiDataHub.cs new file mode 100644 index 0000000..8f38040 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/UiDataHub.cs @@ -0,0 +1,152 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/UiDataHub.cs +// The one fetcher for panel data (docs/IMGUI_PARITY_PLAN.md §4.3). +// +// Step() runs on the plugin pump thread right after PluginManager.TickAll, +// so every plugin export a panel needs is called on the same thread as the +// plugin's own tick and object events: no race with the plugin, and exports +// that free their previous return buffer on the next call never see two +// callers. Panels (either face) only read published snapshots and post +// commands; they never call a plugin export themselves. +// +// Commands (mutating calls: toggles, settings writes, nav edits) are queued +// from any thread and executed here, before the sources poll, so the next +// snapshot already reflects them. +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Threading; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +internal static class UiDataHub +{ + private const int MaxQueuedCommands = 256; + private const double CommandBudgetMs = 2.0; + /// <summary>A step slower than this is logged (at most once a minute).</summary> + private const double StepWarnMs = 4.0; + + private static UiSource[] _sources = Array.Empty<UiSource>(); + private static readonly object RegisterSync = new(); + private static readonly ConcurrentQueue<(string Label, Action Action)> _commands = new(); + private static int _queued; + private static volatile bool _armed = true; + private static volatile bool _resetPending; + private static long _lastSlowLogTicks; + private static int _droppedCommands; + + static UiDataHub() + { + // Raised on the pump thread after every plugin is shut down (RL / + // rescan). Sources re-bind to the fresh plugin copies on their next poll. + PluginManager.PluginsUnloaded += () => _resetPending = true; + } + + /// <summary>Adds a source. Call at init (any thread); sources are never removed.</summary> + public static void Register(UiSource source) + { + lock (RegisterSync) + { + var next = new UiSource[_sources.Length + 1]; + Array.Copy(_sources, next, _sources.Length); + next[^1] = source; + Volatile.Write(ref _sources, next); + } + } + + /// <summary> + /// Queues <paramref name="action"/> to run on the pump thread at the next + /// step. Any thread. Returns false (and logs) when the hub is shutting down + /// or the queue is full; commands are never run after shutdown begins. + /// </summary> + public static bool Post(string label, Action action) + { + if (!_armed) + { + RynthLog.UI($"UiDataHub: '{label}' dropped - shutting down."); + return false; + } + if (Interlocked.Increment(ref _queued) > MaxQueuedCommands) + { + Interlocked.Decrement(ref _queued); + if (Interlocked.Increment(ref _droppedCommands) <= 20) + RynthLog.UI($"UiDataHub: '{label}' dropped - command queue full."); + return false; + } + _commands.Enqueue((label, action)); + return true; + } + + /// <summary>Stops accepting commands and drops the queued ones. Engine shutdown.</summary> + public static void Disarm() + { + _armed = false; + int dropped = 0; + while (_commands.TryDequeue(out _)) dropped++; + Interlocked.Exchange(ref _queued, 0); + if (dropped > 0) + RynthLog.UI($"UiDataHub: disarmed, {dropped} queued command(s) dropped."); + } + + /// <summary>Pump thread only, right after PluginManager.TickAll.</summary> + public static void Step() + { + if (!_armed) return; + long start = Stopwatch.GetTimestamp(); + UiSource[] sources = Volatile.Read(ref _sources); + + if (_resetPending) + { + _resetPending = false; + foreach (UiSource source in sources) + { + try { source.Reset(); } + catch (Exception ex) { RynthLog.UI($"UiDataHub: {source.Name}.Reset threw {ex.GetType().Name}: {ex.Message}"); } + } + } + + // A refresh deferred by a command in the previous step: the plugin has + // ticked since, so it has applied that command. + foreach (UiSource source in sources) + source.PromoteDeferredRefresh(); + + // Commands first, so this step's polls already see their effect. A long + // burst yields after the budget; the rest run next step. + long commandDeadline = start + (long)(Stopwatch.Frequency * CommandBudgetMs / 1000); + while (_commands.TryDequeue(out var command)) + { + Interlocked.Decrement(ref _queued); + try { command.Action(); } + catch (Exception ex) { RynthLog.UI($"UiDataHub: command '{command.Label}' threw {ex.GetType().Name}: {ex.Message}"); } + if (Stopwatch.GetTimestamp() > commandDeadline) break; + } + + string? slowest = null; + long slowestTicks = 0; + foreach (UiSource source in sources) + { + long now = Stopwatch.GetTimestamp(); + if (!source.HasSubscribers || !source.IsDue(now)) continue; + try { source.Poll(); } + catch (Exception ex) { RynthLog.UI($"UiDataHub: {source.Name}.Poll threw {ex.GetType().Name}: {ex.Message}"); } + long after = Stopwatch.GetTimestamp(); + source.MarkPolled(after, after - now); // an expensive poll backs off (UiSource.CostBackoff) + if (after - now > slowestTicks) { slowestTicks = after - now; slowest = source.Name; } + } + + long total = Stopwatch.GetTimestamp() - start; + if (total > Stopwatch.Frequency * StepWarnMs / 1000 && total > 0) + { + long nowTicks = Stopwatch.GetTimestamp(); + if (nowTicks - _lastSlowLogTicks > Stopwatch.Frequency * 60) + { + _lastSlowLogTicks = nowTicks; + double toMs = 1000.0 / Stopwatch.Frequency; + RynthLog.UI($"UiDataHub: slow step {total * toMs:0.0} ms (slowest source {slowest ?? "-"} {slowestTicks * toMs:0.0} ms). The plugin tick waits for this."); + } + } + } +} diff --git a/src/RynthCore.Engine/UI/Data/UiSource.cs b/src/RynthCore.Engine/UI/Data/UiSource.cs new file mode 100644 index 0000000..250362c --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/UiSource.cs @@ -0,0 +1,125 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/UiSource.cs +// One piece of panel data kept fresh by UiDataHub (docs/IMGUI_PARITY_PLAN.md +// §4.3). A source polls on the plugin pump thread and publishes an immutable +// snapshot; the ImGui faces (AC's render thread) and the Avalonia faces (the +// Avalonia UI thread) only ever read the published snapshot. +// ============================================================================ + +using System.Diagnostics; +using System.Threading; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>An immutable published value. Readers compare Version to detect change.</summary> +internal sealed class UiSnapshot<T> where T : class +{ + public UiSnapshot(long version, T value) + { + Version = version; + Value = value; + } + + public long Version { get; } + public T Value { get; } +} + +internal abstract class UiSource +{ + private int _subscribers; + private long _nextDueTicks; + private volatile bool _refreshRequested; + private volatile bool _refreshAfterPluginTick; + + protected UiSource(string name, int periodMs) + { + Name = name; + PeriodMs = periodMs; + } + + public string Name { get; } + + /// <summary>Minimum time between polls while subscribed.</summary> + public int PeriodMs { get; } + + /// <summary> + /// A panel face that shows this data calls Subscribe when it opens and + /// Unsubscribe when it closes; a source with no subscribers is not polled. + /// Any thread. + /// </summary> + public void Subscribe() => Interlocked.Increment(ref _subscribers); + + public void Unsubscribe() + { + if (Interlocked.Decrement(ref _subscribers) < 0) + Interlocked.Exchange(ref _subscribers, 0); + } + + public bool HasSubscribers => Volatile.Read(ref _subscribers) > 0; + + /// <summary>Poll on the next hub step regardless of the period (e.g. after a command). Any thread.</summary> + public void RequestRefresh() => _refreshRequested = true; + + /// <summary> + /// Poll after the plugin's next tick, not before: for exports that only + /// queue a command the plugin applies on its tick (Meta). Until then the + /// source is not polled at all, so no snapshot from before the command + /// lands in between. Pump thread (from a hub command). + /// </summary> + public void RequestRefreshAfterPluginTick() => _refreshAfterPluginTick = true; + + /// <summary>Hub, at the start of a step (the plugin has ticked since the last step).</summary> + internal void PromoteDeferredRefresh() + { + if (!_refreshAfterPluginTick) return; + _refreshAfterPluginTick = false; + _refreshRequested = true; + } + + internal bool IsDue(long now) => !_refreshAfterPluginTick && (_refreshRequested || now >= _nextDueTicks); + + /// <summary> + /// A source whose poll took <c>cost</c> waits at least CostBackoff times that before its + /// next poll, so no source can take more than ~1/CostBackoff of the plugin pump however + /// big its data gets. Below PeriodMs / CostBackoff (3.3 ms for the radar's 33 ms) nothing + /// changes. Added 2026-10-02: in a crowded dungeon the radar's poll (snapshot build, JSON, + /// parse; 300+ markers) took 4-7 ms every 33 ms on the thread the plugin tick runs on. + /// </summary> + internal const int CostBackoff = 10; + + internal void MarkPolled(long now, long costTicks = 0) + { + _refreshRequested = false; + long period = Stopwatch.Frequency * PeriodMs / 1000; + long backoff = costTicks > 0 ? costTicks * CostBackoff : 0; + _nextDueTicks = now + (backoff > period ? backoff : period); + } + + /// <summary>Fetch and publish. Pump thread, after the plugin tick; may call plugin exports.</summary> + protected internal abstract void Poll(); + + /// <summary> + /// Plugins were unloaded (RL / rescan): drop cached export bindings and + /// anything derived from the old plugin copy. Pump thread. + /// </summary> + protected internal virtual void Reset() { } +} + +/// <summary>A source that publishes a <typeparamref name="T"/> snapshot.</summary> +internal abstract class UiSource<T> : UiSource where T : class +{ + private UiSnapshot<T>? _current; + + protected UiSource(string name, int periodMs) : base(name, periodMs) { } + + /// <summary>The latest snapshot, or null before the first poll / after a reset. Any thread; never blocks.</summary> + public UiSnapshot<T>? Current => Volatile.Read(ref _current); + + protected void Publish(T value) + { + long version = (Volatile.Read(ref _current)?.Version ?? 0) + 1; + Volatile.Write(ref _current, new UiSnapshot<T>(version, value)); + } + + protected void ClearSnapshot() => Volatile.Write(ref _current, null); +} diff --git a/src/RynthCore.Engine/UI/Data/UiSources.cs b/src/RynthCore.Engine/UI/Data/UiSources.cs new file mode 100644 index 0000000..4be0072 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/UiSources.cs @@ -0,0 +1,96 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/UiSources.cs +// The hub's sources, one instance each. Touching this class registers them +// with UiDataHub; a source is only polled while a panel face subscribes. +// ============================================================================ + +using System; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +internal static class UiSources +{ + public static readonly PluginStatusSource PluginStatus = new(); + public static readonly LogSource Log = new(); + public static readonly TrackerSource Tracker = new(); + public static readonly RynthAiSource RynthAi = new(); + public static readonly PatrolSource Patrol = new(); + public static readonly ProgressionSource Progression = new(); + public static readonly CharmsSource Charms = new(); + public static readonly RadarSource Radar = new(); + public static readonly SettingsSource Settings = new(); + public static readonly MetaSource Meta = new(); + public static readonly LuaSource Lua = new(); + public static readonly NavSource Nav = new(); + public static readonly ItemsSource Items = new(); + public static readonly VisionSource Vision = new(); + public static readonly RynthNavSource RynthNav = new(); + public static readonly RynthNavAtlasSource RynthNavAtlas = new(); + public static readonly RynthNavArrowWatch RynthNavArrowWatch = new(); + public static readonly ChatSource Chat = new(); + public static readonly DamageSource Damage = new(); + public static readonly MonsterRulesSource MonsterRules = new(); + public static readonly MonsterDetailSource MonsterDetail = new(); + public static readonly LootEditSource LootEdit = new(); + public static readonly SenseSource Sense = new(); + + static UiSources() + { + UiDataHub.Register(Settings); + UiDataHub.Register(Meta); + UiDataHub.Register(LootEdit); + UiDataHub.Register(Lua); + UiDataHub.Register(Nav); + UiDataHub.Register(Items); + UiDataHub.Register(Vision); + UiDataHub.Register(RynthNav); + UiDataHub.Register(RynthNavAtlas); + UiDataHub.Register(RynthNavArrowWatch); + UiDataHub.Register(Chat); + UiDataHub.Register(Damage); + UiDataHub.Register(MonsterRules); + UiDataHub.Register(MonsterDetail); + UiDataHub.Register(Radar); + UiDataHub.Register(RynthAi); + UiDataHub.Register(Patrol); + UiDataHub.Register(Progression); + UiDataHub.Register(Charms); + UiDataHub.Register(PluginStatus); + UiDataHub.Register(Log); + UiDataHub.Register(Tracker); + UiDataHub.Register(Sense); + } +} + +/// <summary>One row of the Status panel's plugin list, preformatted.</summary> +internal readonly record struct PluginStatusRow(string Label, string State, bool IsError); + +/// <summary> +/// Loaded plugins with version and state, for the Status panel. Engine-local: +/// reads PluginManager's list on the pump thread (which owns it) instead of +/// from a UI thread as the Avalonia panel used to. +/// </summary> +internal sealed class PluginStatusSource : UiSource<PluginStatusRow[]> +{ + public PluginStatusSource() : base("PluginStatus", periodMs: 1000) { } + + protected internal override void Poll() + { + var plugins = PluginManager.Plugins; + var rows = new PluginStatusRow[plugins.Count]; + for (int i = 0; i < rows.Length; i++) + { + LoadedPlugin p = plugins[i]; + string version = p.VersionString.Length > 0 ? " " + p.VersionString : ""; + string state = p.Failed ? "FAILED" : p.Initialized ? "OK" : "pending"; + rows[i] = new PluginStatusRow(p.DisplayName + version, state, p.Failed); + } + + PluginStatusRow[]? previous = Current?.Value; + if (previous == null || !previous.AsSpan().SequenceEqual(rows)) + Publish(rows); + } + + protected internal override void Reset() => ClearSnapshot(); +} diff --git a/src/RynthCore.Engine/UI/Data/VisionData.cs b/src/RynthCore.Engine/UI/Data/VisionData.cs new file mode 100644 index 0000000..1b5ac01 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/VisionData.cs @@ -0,0 +1,212 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/VisionData.cs +// The RynthVision plugin's settings (overlays, colours, tuning, water terrain +// types) for both Vision faces. +// +// RynthVisionGetSettingsJson frees its previous buffer on each call, so the +// hub is its only caller (VisionSource, 5 s). Saving and "Log terrain types +// here" run on the pump too. The JSON keys are the plugin's; a still-starting +// plugin answers "{}", which is never published (a face would otherwise show +// defaults and save them over the real settings). +// +// Faces save one field at a time ({"key":value}; the plugin applies any +// subset), so a save never writes back stale values over a change made +// elsewhere (a /rv command, the other face). After every save the settings +// are re-read and republished even if unchanged: the plugin may have +// normalised the value (an empty water-type list resets to the defaults). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Text.Json; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +internal sealed class VisionSettings +{ + public bool Radar, Slopes, Water, WaterAnyCorner, WaterImpassableOnly; + public uint SlopeColor = 0x60FF2020, WaterColor = 0x600060FF, RadarColor = 0x80FFD000; + public double RadarRange = 192, RingThick = 2, RingHeight = 3, SlopeFloorZ = 0.664, SlopeBias = 0.15; + public int SlopeRadius = 12, WaterRadius = 12; + public List<int> WaterTypes = new(); + + public VisionSettings Clone() + { + var c = (VisionSettings)MemberwiseClone(); + c.WaterTypes = new List<int>(WaterTypes); + return c; + } + + /// <summary>Parses the plugin's JSON; false for "{}" or when no known field is present.</summary> + public static bool TryParse(string json, out VisionSettings settings) + { + settings = new VisionSettings(); + if (string.IsNullOrEmpty(json) || json == "{}") return false; + try + { + using var doc = JsonDocument.Parse(json); + JsonElement r = doc.RootElement; + bool any = false; + bool Int(string key, ref bool field) { if (!r.TryGetProperty(key, out var v)) return false; field = v.GetInt32() != 0; return true; } + any |= Int("radar", ref settings.Radar); + any |= Int("slopes", ref settings.Slopes); + any |= Int("water", ref settings.Water); + any |= Int("waterAnyCorner", ref settings.WaterAnyCorner); + any |= Int("waterImpassableOnly", ref settings.WaterImpassableOnly); + if (r.TryGetProperty("slopeColor", out var e)) { settings.SlopeColor = e.GetUInt32(); any = true; } + if (r.TryGetProperty("waterColor", out e)) { settings.WaterColor = e.GetUInt32(); any = true; } + if (r.TryGetProperty("radarColor", out e)) { settings.RadarColor = e.GetUInt32(); any = true; } + if (r.TryGetProperty("radarRange", out e)) { settings.RadarRange = e.GetDouble(); any = true; } + if (r.TryGetProperty("ringThick", out e)) { settings.RingThick = e.GetDouble(); any = true; } + if (r.TryGetProperty("ringHeight", out e)) { settings.RingHeight = e.GetDouble(); any = true; } + if (r.TryGetProperty("slopeRadius", out e)) { settings.SlopeRadius = e.GetInt32(); any = true; } + if (r.TryGetProperty("slopeFloorZ", out e)) { settings.SlopeFloorZ = e.GetDouble(); any = true; } + if (r.TryGetProperty("slopeBias", out e)) { settings.SlopeBias = e.GetDouble(); any = true; } + if (r.TryGetProperty("waterRadius", out e)) { settings.WaterRadius = e.GetInt32(); any = true; } + if (r.TryGetProperty("waterTypes", out e) && e.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement t in e.EnumerateArray()) settings.WaterTypes.Add(t.GetInt32()); + any = true; + } + return any; + } + catch { return false; } + } + + /// <summary>One field as the plugin's JSON, e.g. {"radar":1}. Key: a <see cref="VisionKeys"/> constant.</summary> + public string FieldJson(string key) + { + var ci = CultureInfo.InvariantCulture; + string value = key switch + { + VisionKeys.Radar => Radar ? "1" : "0", + VisionKeys.Slopes => Slopes ? "1" : "0", + VisionKeys.Water => Water ? "1" : "0", + VisionKeys.WaterAnyCorner => WaterAnyCorner ? "1" : "0", + VisionKeys.WaterImpassableOnly => WaterImpassableOnly ? "1" : "0", + VisionKeys.SlopeColor => SlopeColor.ToString(ci), + VisionKeys.WaterColor => WaterColor.ToString(ci), + VisionKeys.RadarColor => RadarColor.ToString(ci), + VisionKeys.RadarRange => RadarRange.ToString("R", ci), + VisionKeys.RingThick => RingThick.ToString("R", ci), + VisionKeys.RingHeight => RingHeight.ToString("R", ci), + VisionKeys.SlopeRadius => SlopeRadius.ToString(ci), + VisionKeys.SlopeFloorZ => SlopeFloorZ.ToString("R", ci), + VisionKeys.SlopeBias => SlopeBias.ToString("R", ci), + VisionKeys.WaterRadius => WaterRadius.ToString(ci), + VisionKeys.WaterTypes => "[" + string.Join(",", WaterTypes) + "]", + _ => throw new ArgumentException($"Unknown Vision setting '{key}'", nameof(key)), + }; + return "{\"" + key + "\":" + value + "}"; + } + + /// <summary>"18,19,20" -> the numbers in it (anything else is dropped).</summary> + public static List<int> ParseCsv(string? csv) + { + var list = new List<int>(); + if (string.IsNullOrWhiteSpace(csv)) return list; + foreach (string part in csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + if (int.TryParse(part, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) list.Add(n); + return list; + } + + /// <summary>"AARRGGBB" or "RRGGBB" (opaque), with or without '#'.</summary> + public static bool TryParseHex(string? s, out uint argb) + { + argb = 0; + if (string.IsNullOrWhiteSpace(s)) return false; + s = s.Trim().TrimStart('#'); + if (s.Length == 6) s = "FF" + s; + return s.Length == 8 && uint.TryParse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out argb); + } +} + +/// <summary>The plugin's settings JSON keys.</summary> +internal static class VisionKeys +{ + public const string Radar = "radar", Slopes = "slopes", Water = "water"; + public const string WaterAnyCorner = "waterAnyCorner", WaterImpassableOnly = "waterImpassableOnly"; + public const string SlopeColor = "slopeColor", WaterColor = "waterColor", RadarColor = "radarColor"; + public const string RadarRange = "radarRange", RingThick = "ringThick", RingHeight = "ringHeight"; + public const string SlopeRadius = "slopeRadius", SlopeFloorZ = "slopeFloorZ", SlopeBias = "slopeBias"; + public const string WaterRadius = "waterRadius", WaterTypes = "waterTypes"; +} + +internal sealed class VisionSnapshot +{ + public VisionSnapshot(string json, VisionSettings settings) { Json = json; Settings = settings; } + public string Json { get; } + /// <summary>Shared: copy before changing (Clone).</summary> + public VisionSettings Settings { get; } +} + +/// <summary>RynthVisionGetSettingsJson while a Vision face is open (5 s, and after each save).</summary> +internal sealed unsafe class VisionSource : UiSource<VisionSnapshot> +{ + private delegate* unmanaged[Cdecl]<IntPtr> _get; + private string? _lastJson; + + public VisionSource() : base("Vision", periodMs: 5000) { } + + protected internal override void Poll() + { + if (_get == null) + _get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthVision", "RynthVisionGetSettingsJson"); + if (_get == null) return; + IntPtr ptr = _get(); + string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr); + if (string.IsNullOrEmpty(json) || json == _lastJson) return; + if (!VisionSettings.TryParse(json, out VisionSettings settings)) return; + _lastJson = json; + Publish(new VisionSnapshot(json, settings)); + } + + protected internal override void Reset() + { + _get = null; + _lastJson = null; + ClearSnapshot(); + } + + /// <summary>Publish on the next poll even if the JSON is unchanged. Pump thread.</summary> + internal void RequestRepublish() + { + _lastJson = null; + RequestRefresh(); + } +} + +internal static unsafe class VisionCommands +{ + private static delegate* unmanaged[Cdecl]<IntPtr, void> _set; + private static delegate* unmanaged[Cdecl]<void> _inspect; + + static VisionCommands() + { + PluginManager.PluginsUnloaded += () => { _set = null; _inspect = null; }; + } + + /// <summary>Applies and saves one field: <paramref name="key"/>'s value from <paramref name="settings"/>.</summary> + public static void SaveField(VisionSettings settings, string key) => Save(settings.FieldJson(key)); + + /// <summary>Applies and saves the settings in <paramref name="json"/> (any subset of the keys).</summary> + public static void Save(string json) => UiDataHub.Post("Vision save", () => + { + if (_set == null) _set = (delegate* unmanaged[Cdecl]<IntPtr, void>)PluginExportBinder.Resolve("RynthVision", "RynthVisionSetSettings"); + if (_set == null) return; + IntPtr p = Marshal.StringToHGlobalAnsi(json); + try { _set(p); } + finally { Marshal.FreeHGlobal(p); } + UiSources.Vision.RequestRepublish(); + }); + + /// <summary>Logs the terrain types under the player (RynthVision's diagnostic).</summary> + public static void Inspect() => UiDataHub.Post("Vision inspect", () => + { + if (_inspect == null) _inspect = (delegate* unmanaged[Cdecl]<void>)PluginExportBinder.Resolve("RynthVision", "RynthVisionInspectTerrain"); + if (_inspect != null) _inspect(); + }); +} diff --git a/src/RynthCore.Engine/UI/Dcomp/DcompOverlayWindow.cs b/src/RynthCore.Engine/UI/Dcomp/DcompOverlayWindow.cs index 084678e..48e241e 100644 --- a/src/RynthCore.Engine/UI/Dcomp/DcompOverlayWindow.cs +++ b/src/RynthCore.Engine/UI/Dcomp/DcompOverlayWindow.cs @@ -308,6 +308,7 @@ internal sealed class DcompOverlayWindow : Window ["Monsters"] = new(MonstersPanel.Create, true, 460, 480), ["Nav"] = new(NavPanel.Create, true, 420, 480), ["Meta"] = new(MetaPanel.Create, true, 460, 480), + ["Lua"] = new(LuaPanel.Create, true, 460, 560), }; } diff --git a/src/RynthCore.Engine/UI/LayeredWindow.cs b/src/RynthCore.Engine/UI/LayeredWindow.cs index 9ba8939..ed1a32d 100644 --- a/src/RynthCore.Engine/UI/LayeredWindow.cs +++ b/src/RynthCore.Engine/UI/LayeredWindow.cs @@ -67,10 +67,6 @@ internal sealed unsafe class LayeredWindow : IDisposable // because LayeredWindow lives in UI/ and avoids depending on the ImGui // subsystem. private const uint WM_RYNTH_RESTORE_FOCUS = 0x8001; - // Posted by DestroyOnOwnerThread to the panel HWND itself, so DestroyWindow - // runs in StaticWndProc on whichever thread owns it. Must not collide with - // Win32Backend's game-window messages (0x8001-0x8004). - private const uint WM_RYNTH_SELF_DESTROY = 0x8005; private const uint WM_ENTERSIZEMOVE = 0x0231; private const uint WM_EXITSIZEMOVE = 0x0232; private const uint WM_NCHITTEST = 0x0084; @@ -197,7 +193,15 @@ internal sealed unsafe class LayeredWindow : IDisposable [DllImport("user32.dll")] private static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("user32.dll")] private static extern IntPtr SetCapture(IntPtr hwnd); + [DllImport("user32.dll")] private static extern IntPtr GetCapture(); [DllImport("user32.dll")] private static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd); + + [StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] + private struct MONITORINFO { public int cbSize; public RECT rcMonitor; public RECT rcWork; public uint dwFlags; } + private const uint MONITOR_DEFAULTTONEAREST = 2; + [DllImport("user32.dll")] private static extern IntPtr MonitorFromRect(ref RECT rect, uint flags); + [DllImport("user32.dll")] private static extern bool GetMonitorInfoW(IntPtr monitor, ref MONITORINFO info); [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool BringWindowToTop(IntPtr hWnd); @@ -265,6 +269,16 @@ internal sealed unsafe class LayeredWindow : IDisposable private static readonly Dictionary<IntPtr, LayeredWindow> _instances = new(); private static int _hittestDiagCount; + /// <summary> + /// Posted to a panel window to destroy itself. Handled here, before the + /// instance lookup, so it runs on whichever thread created the window — + /// DestroyWindow only works there. A window created on the overlay thread + /// (not the game thread) could not be destroyed by a destroy posted to the + /// game thread (ACCESS_DENIED) and stayed on screen: the double dashboard. + /// Must not collide with Win32Backend's game-window messages (0x8001-0x8005). + /// </summary> + private const uint WM_RYNTH_SELF_DESTROY = 0x8051; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] private static IntPtr StaticWndProc(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam) { @@ -318,6 +332,106 @@ internal sealed unsafe class LayeredWindow : IDisposable /// load's own windows (class names carry a per-load Guid) and removes only /// ones an earlier load left behind. /// </summary> + [DllImport("user32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); + [DllImport("user32.dll")] private static extern bool IsWindow(IntPtr hWnd); + [DllImport("user32.dll")] private static extern int EnumWindows(delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int> lpfn, IntPtr lParam); + [DllImport("kernel32.dll")] private static extern uint GetCurrentProcessId(); + + /// <summary> + /// Takes a panel window off the screen at once (never blocks, any thread) + /// and asks its own thread to destroy it. + /// </summary> + internal static bool Retire(IntPtr hwnd) + { + if (hwnd == IntPtr.Zero || !IsWindow(hwnd)) return false; + ShowWindowAsync(hwnd, SW_HIDE); + return PostMessage(hwnd, WM_RYNTH_SELF_DESTROY, IntPtr.Zero, IntPtr.Zero); + } + + // Panel title → the window currently showing it popped out. + private static readonly Dictionary<string, IntPtr> _windowByTitle = new(StringComparer.OrdinalIgnoreCase); + + /// <summary> + /// Records <paramref name="hwnd"/> as the one popped-out window for + /// <paramref name="title"/>; any earlier window for that title is retired. + /// A panel can never have two popped-out windows. + /// </summary> + internal static void ClaimTitle(string title, IntPtr hwnd) + { + IntPtr prior; + lock (_instancesLock) + { + _windowByTitle.TryGetValue(title, out prior); + _windowByTitle[title] = hwnd; + } + if (prior != IntPtr.Zero && prior != hwnd && IsWindow(prior)) + { + RynthCore.Engine.RynthLog.Info($"LayeredWindow: '{title}' already had window 0x{prior.ToInt64():X}; retiring it for 0x{hwnd.ToInt64():X}."); + Retire(prior); + } + } + + /// <summary> + /// The content rects (screen px: left, top, width, height) of every visible panel window. + /// They sit above the game window, so nothing drawn in the game frame can show over them. + /// </summary> + internal static List<(int Left, int Top, int Width, int Height)> VisibleContentRects() + { + LayeredWindow[] windows; + lock (_instancesLock) + { + windows = new LayeredWindow[_instances.Count]; + _instances.Values.CopyTo(windows, 0); + } + var rects = new List<(int, int, int, int)>(windows.Length); + foreach (LayeredWindow w in windows) + if (w.IsVisible && w.Width > 0 && w.Height > 0) + rects.Add((w.ScreenLeft, w.ScreenTop, w.Width, w.Height)); + return rects; + } + + private static readonly HashSet<IntPtr> _sweptLogged = new(); + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int CollectTopWindow(IntPtr hwnd, IntPtr lParam) + { + if (GCHandle.FromIntPtr(lParam).Target is List<IntPtr> found) + found.Add(hwnd); + return 1; + } + + /// <summary> + /// Every visible panel window of this process that no live LayeredWindow + /// owns (it was disposed but survived, or an earlier engine load left it) + /// is hidden and destroyed. Live windows are always in _instances, so this + /// can't touch an open panel. Any thread; run from the heartbeat. + /// </summary> + internal static void SweepOrphans() + { + var found = new List<IntPtr>(); + GCHandle handle = GCHandle.Alloc(found); + try { EnumWindows(&CollectTopWindow, GCHandle.ToIntPtr(handle)); } + finally { handle.Free(); } + + uint pid = GetCurrentProcessId(); + char* buffer = stackalloc char[128]; + foreach (IntPtr hwnd in found) + { + GetWindowThreadProcessId(hwnd, out uint winPid); + if (winPid != pid || !IsWindowVisible(hwnd)) continue; + int length = GetClassNameW(hwnd, buffer, 128); + if (length <= 0) continue; + if (!new string(buffer, 0, length).StartsWith(ClassNamePrefix, StringComparison.Ordinal)) continue; + bool live; + lock (_instancesLock) live = _instances.ContainsKey(hwnd); + if (live) continue; + bool first; + lock (_instancesLock) first = _sweptLogged.Add(hwnd); + if (first) RynthCore.Engine.RynthLog.Info($"LayeredWindow: orphan panel window 0x{hwnd.ToInt64():X} still visible; hiding and destroying it."); + Retire(hwnd); + } + } + internal static void DestroyThreadPanelWindows(bool includeThisGeneration) { var found = new List<IntPtr>(); @@ -351,17 +465,44 @@ internal sealed unsafe class LayeredWindow : IDisposable // ─── Instance state ──────────────────────────────────────────────────── public IntPtr Hwnd { get; private set; } + + // The panel ("content") rect on the screen. The HWND can be larger: a popped-out + // ImGui panel's window grows a transparent margin while a tooltip or popup reaches + // past the panel (Present). The margins are the _inset* fields; they are always 0 + // for windows fed by UpdatePixels (the Avalonia pop-outs), where the HWND is the + // content. Drag band, grip, moves, resizes and EnsureOnScreen all work on the content. public int Width { get; private set; } public int Height { get; private set; } public int ScreenLeft { get; private set; } public int ScreenTop { get; private set; } + private int _insetL, _insetT, _insetR, _insetB; + + /// <summary>The HWND's rect (the content plus its transparent margins).</summary> + public int SurfaceLeft => ScreenLeft - _insetL; + public int SurfaceTop => ScreenTop - _insetT; + public int SurfaceWidth => Width + _insetL + _insetR; + public int SurfaceHeight => Height + _insetT + _insetB; + + /// <summary>True while the window is being moved or resized by the mouse.</summary> + public bool IsDragging => _dragMode != DragNone; + + /// <summary> + /// True: only the content rect takes the mouse; anything drawn in the margins (a + /// tooltip) lets clicks through to the window below, like its transparent pixels. + /// Set false while the margins hold something clickable (a popup menu). + /// </summary> + public bool MarginsClickThrough { get; set; } = true; + /// <summary> /// Pixel height of the top "drag" region — WM_NCHITTEST returns HTCAPTION /// here so the OS handles drag-to-move with no input forwarding needed. /// </summary> public int CaptionHeight { get; set; } = 24; + /// <summary>False: no bottom-right resize corner (a window sized to its content, like the bar).</summary> + public bool ResizeGripEnabled { get; set; } = true; + /// <summary> /// Pixel width of the right portion of the caption that should NOT act /// as a drag handle — used to keep the popout/close buttons clickable @@ -515,8 +656,13 @@ internal sealed unsafe class LayeredWindow : IDisposable // lParam is screen coord — convert to layered-client. int sx = (short)((long)lParam & 0xFFFF); int sy = (short)(((long)lParam >> 16) & 0xFFFF); - int cx = sx - ScreenLeft; - int cy = sy - ScreenTop; + int cx = sx - SurfaceLeft; + int cy = sy - SurfaceTop; + + // Outside the content, in a margin holding only a tooltip: not ours. + if (MarginsClickThrough && (_insetL | _insetT | _insetR | _insetB) != 0 + && (cx < _insetL || cy < _insetT || cx >= _insetL + Width || cy >= _insetT + Height)) + return (IntPtr)HTTRANSPARENT; // NOTE: we intentionally do NOT return HTBOTTOMRIGHT (resize // grip) or HTCAPTION (move) here. Either would make DefWindowProc @@ -617,15 +763,16 @@ internal sealed unsafe class LayeredWindow : IDisposable { int x = (short)((long)lParam & 0xFFFF); int y = (short)(((long)lParam >> 16) & 0xFFFF); - ScreenLeft = x; - ScreenTop = y; + ScreenLeft = x + _insetL; + ScreenTop = y + _insetT; // During the OS HTCAPTION modal drag loop, WM_TIMER can be // suppressed so Tick() / UpdateLayeredWindow may not fire // while the HWND moves. Repaint existing pixels at the new // screen position on every WM_MOVE so the layered visual // tracks the HWND without waiting for the next timer tick. // No pixel copy — just repositions the existing DIB. - if (_modalSizeMoveActive) + // (Not from inside Present's own UpdateLayeredWindow.) + if (_modalSizeMoveActive && !_presenting) PaintExistingPixelsAt(x, y); if (_suppressMoveCallback) break; // Defer the persist callback to drag end (WM_EXITSIZEMOVE) — @@ -633,14 +780,14 @@ internal sealed unsafe class LayeredWindow : IDisposable if (_modalSizeMoveActive) _pendingMoveNotify = true; else - OnMoved?.Invoke(x, y); + OnMoved?.Invoke(ScreenLeft, ScreenTop); break; } case WM_SIZE: { - int w = (short)((long)lParam & 0xFFFF); - int h = (short)(((long)lParam >> 16) & 0xFFFF); + int w = (short)((long)lParam & 0xFFFF) - _insetL - _insetR; + int h = (short)(((long)lParam >> 16) & 0xFFFF) - _insetT - _insetB; if (w > 0 && h > 0) { Width = w; @@ -660,8 +807,9 @@ internal sealed unsafe class LayeredWindow : IDisposable case WM_LBUTTONDOWN: { - int cx = (short)((long)lParam & 0xFFFF); - int cy = (short)(((long)lParam >> 16) & 0xFFFF); + // Client coordinates are the HWND's; the chrome below is the content's. + int cx = (short)((long)lParam & 0xFFFF) - _insetL; + int cy = (short)(((long)lParam >> 16) & 0xFFFF) - _insetT; RynthCore.Engine.RynthLog.Info($"LayeredWindow(0x{Hwnd.ToInt64():X}): WM_LBUTTONDOWN at layered=({cx},{cy})."); // Native chrome-button detection: floating panels live at @@ -690,7 +838,7 @@ internal sealed unsafe class LayeredWindow : IDisposable // Resize grip (bottom-right). Handle the resize ourselves rather // than via the OS modal loop — see BeginDrag / the WM_NCHITTEST // note. Checked before the caption so the corner wins. - if (cx >= Width - GripPx && cy >= Height - GripPx && cx < Width && cy < Height) + if (ResizeGripEnabled && cx >= Width - GripPx && cy >= Height - GripPx && cx < Width && cy < Height) { BeginDrag(DragResize); return IntPtr.Zero; @@ -756,7 +904,12 @@ internal sealed unsafe class LayeredWindow : IDisposable case WM_CAPTURECHANGED: // Mouse capture was taken from us (alt-tab, another grab, or our // own ReleaseCapture in EndDrag). Don't leave a drag latched. - CancelDragFromCaptureLoss(); + // lParam is the window gaining capture: this window taking it + // again is not a loss (a content drag starts while the press + // already holds capture, and SetCapture on the capturing window + // still sends this message - it cancelled every content drag). + if (lParam != Hwnd) + CancelDragFromCaptureLoss(); break; case WM_DESTROY: @@ -868,7 +1021,7 @@ internal sealed unsafe class LayeredWindow : IDisposable { if (_disposed || Hwnd == IntPtr.Zero || _memDc == IntPtr.Zero || _hbm == IntPtr.Zero) return; var dstPt = new POINT { X = screenX, Y = screenY }; - var size = new SIZE { CX = Width, CY = Height }; + var size = new SIZE { CX = SurfaceWidth, CY = SurfaceHeight }; var srcPt = new POINT { X = 0, Y = 0 }; var blend = new BLENDFUNCTION { @@ -882,6 +1035,29 @@ internal sealed unsafe class LayeredWindow : IDisposable // ─── Custom non-modal move/resize (see the _dragMode fields) ───────────── + /// <summary> + /// Starts moving the window from a press inside the content (a chromeless + /// ImGui panel dragged by its own surface). The content saw the button go + /// down, so it is sent a button-up at the end of the move. + /// </summary> + public void BeginContentMove() + { + if (_disposed || Hwnd == IntPtr.Zero || _dragMode != DragNone) return; + _dragFromContent = true; + BeginDrag(DragMove); + } + + private bool _dragFromContent; + + private void ReleaseContentButton() + { + if (!_dragFromContent) return; + _dragFromContent = false; + if (!GetCursorPos(out POINT p)) return; + int cx = p.X - SurfaceLeft, cy = p.Y - SurfaceTop; // HWND client coordinates, like any mouse message + ForwardInput(WM_LBUTTONUP, IntPtr.Zero, (IntPtr)((cy << 16) | (cx & 0xFFFF))); + } + private void BeginDrag(int mode) { if (!GetCursorPos(out POINT p)) return; @@ -899,7 +1075,12 @@ internal sealed unsafe class LayeredWindow : IDisposable _pendingMoveNotify = false; _pendingResizeNotify = false; _lastResizeApplyTick = 0; - SetCapture(Hwnd); + // A content move starts while the press that began it already holds capture + // (WM_LBUTTONDOWN took it). Taking it again sent WM_CAPTURECHANGED, which + // ended the drag as soon as it began: popped-out faces that drag by their + // own surface (the RynthAi dashboard, the bar) could not be moved. + if (GetCapture() != Hwnd) + SetCapture(Hwnd); } private void UpdateDrag() @@ -941,11 +1122,15 @@ internal sealed unsafe class LayeredWindow : IDisposable _pendingMoveNotify = false; _pendingResizeNotify = false; ReleaseCapture(); + ReleaseContentButton(); // Persist the final geometry (mirrors what WM_EXITSIZEMOVE used to do - // for the OS modal loop). + // for the OS modal loop). A move never leaves the window off the screen. if (mode == DragMove) + { + EnsureOnScreen(); OnMoved?.Invoke(ScreenLeft, ScreenTop); + } else if (mode == DragResize) OnResizeEnd?.Invoke(Width, Height); } @@ -965,12 +1150,65 @@ internal sealed unsafe class LayeredWindow : IDisposable _modalSizeMoveActive = false; _pendingMoveNotify = false; _pendingResizeNotify = false; + ReleaseContentButton(); if (mode == DragMove) + { + EnsureOnScreen(); OnMoved?.Invoke(ScreenLeft, ScreenTop); + } else if (mode == DragResize) OnResizeEnd?.Invoke(Width, Height); } + /// <summary> + /// Pulls a (left, top, width, height) rectangle inside the work area of the + /// monitor nearest to it: wholly inside when it fits, else its top-left corner. + /// True when it had to move. Any thread. + /// </summary> + public static bool ClampToWorkArea(ref int left, ref int top, int width, int height) + { + var r = new RECT { Left = left, Top = top, Right = left + Math.Max(1, width), Bottom = top + Math.Max(1, height) }; + IntPtr monitor = MonitorFromRect(ref r, MONITOR_DEFAULTTONEAREST); + var info = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() }; + if (monitor == IntPtr.Zero || !GetMonitorInfoW(monitor, ref info)) return false; + RECT work = info.rcWork; + int x = Math.Clamp(left, work.Left, Math.Max(work.Left, work.Right - width)); + int y = Math.Clamp(top, work.Top, Math.Max(work.Top, work.Bottom - height)); + if (x == left && y == top) return false; + left = x; + top = y; + return true; + } + + /// <summary>The work area of the monitor nearest a rectangle (screen px). Any thread.</summary> + public static bool TryGetWorkArea(int left, int top, int width, int height, out int workLeft, out int workTop, out int workRight, out int workBottom) + { + workLeft = workTop = workRight = workBottom = 0; + var r = new RECT { Left = left, Top = top, Right = left + Math.Max(1, width), Bottom = top + Math.Max(1, height) }; + IntPtr monitor = MonitorFromRect(ref r, MONITOR_DEFAULTTONEAREST); + var info = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() }; + if (monitor == IntPtr.Zero || !GetMonitorInfoW(monitor, ref info)) return false; + workLeft = info.rcWork.Left; + workTop = info.rcWork.Top; + workRight = info.rcWork.Right; + workBottom = info.rcWork.Bottom; + return workRight > workLeft && workBottom > workTop; + } + + /// <summary> + /// Moves the window back inside the nearest monitor's work area when any of + /// it is off the screen. No OnMoved (the caller persists). True when it moved. + /// The window's thread. + /// </summary> + public bool EnsureOnScreen() + { + if (_disposed || Hwnd == IntPtr.Zero || _dragMode != DragNone) return false; // a drag ends with its own check + int x = ScreenLeft, y = ScreenTop; + if (!ClampToWorkArea(ref x, ref y, Width, Height)) return false; + Move(x, y); + return true; + } + /// <summary> /// Resize the HWND in place without the OS modal loop. SetWindowPos sends /// WM_SIZE synchronously to our WndProc, which updates Width/Height and fires @@ -983,7 +1221,7 @@ internal sealed unsafe class LayeredWindow : IDisposable if (newW < MinDragW) newW = MinDragW; if (newH < MinDragH) newH = MinDragH; if (newW == Width && newH == Height) return; - SetWindowPos(Hwnd, IntPtr.Zero, 0, 0, newW, newH, + SetWindowPos(Hwnd, IntPtr.Zero, 0, 0, newW + _insetL + _insetR, newH + _insetT + _insetB, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); } @@ -1119,6 +1357,69 @@ internal sealed unsafe class LayeredWindow : IDisposable } } + private bool _presenting; + + /// <summary> + /// Shows a picture of <paramref name="surfaceWidth"/> x <paramref name="surfaceHeight"/> + /// premultiplied BGRA pixels in which the content (the panel) is the + /// <paramref name="contentWidth"/> x <paramref name="contentHeight"/> rect at + /// (<paramref name="insetLeft"/>, <paramref name="insetTop"/>); the rest is margin + /// (transparent, or a tooltip or popup reaching past the panel). The content stays + /// where it is on the screen: the HWND takes the picture's size and moves by the + /// margin, all in one UpdateLayeredWindow call, so nothing flickers or jumps. + /// The popped-out ImGui panels use this; UpdatePixels (no margins) is the Avalonia + /// pop-outs'. The window's thread. + /// </summary> + public void Present(IntPtr bgraData, int rowPitch, int surfaceWidth, int surfaceHeight, + int insetLeft, int insetTop, int contentWidth, int contentHeight) + { + if (_disposed || Hwnd == IntPtr.Zero || bgraData == IntPtr.Zero) return; + if (surfaceWidth <= 0 || surfaceHeight <= 0 || contentWidth <= 0 || contentHeight <= 0) return; + int insetRight = surfaceWidth - insetLeft - contentWidth; + int insetBottom = surfaceHeight - insetTop - contentHeight; + if (insetLeft < 0 || insetTop < 0 || insetRight < 0 || insetBottom < 0) return; + // A resize drag outran this picture (it was rendered at the size before the last + // step): keep the last one up; the next frame is drawn at the new size. + if (_dragMode == DragResize && (contentWidth != Width || contentHeight != Height)) return; + + EnsureDib(surfaceWidth, surfaceHeight); + if (_dibBits == IntPtr.Zero) return; + int dibStride = _dibWidth * 4; + int rowBytes = surfaceWidth * 4; + for (int y = 0; y < surfaceHeight; y++) + Buffer.MemoryCopy((byte*)bgraData + (long)y * rowPitch, (byte*)_dibBits + (long)y * dibStride, dibStride, rowBytes); + + // The picture's geometry becomes the window's. Set first: the WM_MOVE / WM_SIZE + // the update sends read the content back out of the HWND rect with these. + _insetL = insetLeft; _insetT = insetTop; _insetR = insetRight; _insetB = insetBottom; + Width = contentWidth; + Height = contentHeight; + + var dstPt = new POINT { X = ScreenLeft - insetLeft, Y = ScreenTop - insetTop }; + var size = new SIZE { CX = surfaceWidth, CY = surfaceHeight }; + var srcPt = new POINT { X = 0, Y = 0 }; + var blend = new BLENDFUNCTION { BlendOp = AC_SRC_OVER, BlendFlags = 0, SourceConstantAlpha = 255, AlphaFormat = AC_SRC_ALPHA }; + _suppressMoveCallback = true; + _suppressResizeCallback = true; + _presenting = true; + bool ok; + try + { + ok = UpdateLayeredWindow(Hwnd, IntPtr.Zero, ref dstPt, ref size, _memDc, ref srcPt, 0, ref blend, ULW_ALPHA); + } + finally + { + _presenting = false; + _suppressMoveCallback = false; + _suppressResizeCallback = false; + } + if (!ok && _updateLogCount < 6) + { + _updateLogCount++; + RynthLog.Info($"LayeredWindow(0x{Hwnd.ToInt64():X}): Present {surfaceWidth}x{surfaceHeight} at ({dstPt.X},{dstPt.Y}) failed, err={Marshal.GetLastWin32Error()}."); + } + } + private const int GWL_HWNDPARENT = -8; /// <summary> @@ -1146,7 +1447,7 @@ internal sealed unsafe class LayeredWindow : IDisposable _suppressMoveCallback = true; try { - SetWindowPos(Hwnd, IntPtr.Zero, screenLeft, screenTop, 0, 0, + SetWindowPos(Hwnd, IntPtr.Zero, screenLeft - _insetL, screenTop - _insetT, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); } finally { _suppressMoveCallback = false; } @@ -1191,7 +1492,18 @@ internal sealed unsafe class LayeredWindow : IDisposable if (hwnd != IntPtr.Zero) { lock (_instancesLock) + { _instances.Remove(hwnd); + string? owned = null; + foreach (var kv in _windowByTitle) if (kv.Value == hwnd) { owned = kv.Key; break; } + if (owned != null) _windowByTitle.Remove(owned); + } + + // Off the screen now, and ask the window's own thread to destroy it + // (works for a window created on any thread). Only if that post fails + // fall back to the game-thread destroy below: doing both could destroy + // an unrelated window that reused the handle in between. + if (Retire(hwnd)) { DisposeDib(); return; } // DestroyWindow MUST run on the thread that owns the HWND (Win32 // fails it with ERROR_ACCESS_DENIED otherwise); a missed destroy diff --git a/src/RynthCore.Engine/UI/PanelColumnStore.cs b/src/RynthCore.Engine/UI/PanelColumnStore.cs new file mode 100644 index 0000000..7d64687 --- /dev/null +++ b/src/RynthCore.Engine/UI/PanelColumnStore.cs @@ -0,0 +1,67 @@ +// ============================================================================ +// RynthCore.Engine - UI/PanelColumnStore.cs +// Column widths the user dragged in the in-game panels (Damage, Monsters, +// Meta). Stored for the whole PC in %LOCALAPPDATA%\RynthCore\panel_columns.txt +// as "Panel.key=value" lines. Read once; written when a drag ends. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; + +namespace RynthCore.Engine.UI; + +internal static class PanelColumnStore +{ + private static readonly object Sync = new(); + private static readonly Dictionary<string, float> Values = new(StringComparer.OrdinalIgnoreCase); + private static bool _loaded; + + private static string FilePath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_columns.txt"); + + public static float Get(string key, float fallback) + { + lock (Sync) + { + Load(); + return Values.TryGetValue(key, out float v) ? v : fallback; + } + } + + public static void Set(string key, float value) + { + lock (Sync) + { + Load(); + Values[key] = value; + try + { + Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); + var lines = new List<string>(); + foreach (var kv in Values) lines.Add($"{kv.Key}={kv.Value.ToString("0.###", CultureInfo.InvariantCulture)}"); + File.WriteAllLines(FilePath, lines); + } + catch { } + } + } + + private static void Load() + { + if (_loaded) return; + _loaded = true; + try + { + if (!File.Exists(FilePath)) return; + foreach (string line in File.ReadAllLines(FilePath)) + { + int eq = line.IndexOf('='); + if (eq <= 0) continue; + if (float.TryParse(line.AsSpan(eq + 1).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float v)) + Values[line[..eq].Trim()] = v; + } + } + catch { } + } +} diff --git a/src/RynthCore.Engine/UI/PanelFaceStore.cs b/src/RynthCore.Engine/UI/PanelFaceStore.cs new file mode 100644 index 0000000..e014378 --- /dev/null +++ b/src/RynthCore.Engine/UI/PanelFaceStore.cs @@ -0,0 +1,120 @@ +// ============================================================================ +// RynthCore.Engine - UI/PanelFaceStore.cs +// Which face shows a panel while it is docked in the client: +// %LocalAppData%\RynthCore\panel_faces.txt, one "<Title>=avalonia|imgui|both" +// per line. Popped-out panels are always Avalonia windows, so only the docked +// face is a choice (docs/IMGUI_PARITY_PLAN.md, "ImGui in game, Avalonia when +// popped out"). +// +// Its own file rather than a panel_state.txt row: PanelStateStore rewrites +// that file from memory and drops rows it doesn't recognise, so an older +// engine would silently erase the choice. Engine-owned; the launcher never +// writes it. A missing entry means "use the code default". +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace RynthCore.Engine.UI; + +internal enum PanelFace +{ + Avalonia, + ImGui, + /// <summary>Both faces docked at once, the ImGui copy offset, for side-by-side checks.</summary> + Both, +} + +internal static class PanelFaceStore +{ + private static readonly object Sync = new(); + private static readonly Dictionary<string, PanelFace> Faces = new(StringComparer.OrdinalIgnoreCase); + private static bool _loaded; + + private static string FilePath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_faces.txt"); + + public static bool TryGet(string title, out PanelFace face) + { + lock (Sync) + { + EnsureLoaded(); + return Faces.TryGetValue(title, out face); + } + } + + /// <summary>Stores a choice; null clears it back to the code default.</summary> + public static void Set(string title, PanelFace? face) + { + lock (Sync) + { + EnsureLoaded(); + if (face is PanelFace f) Faces[title] = f; + else Faces.Remove(title); + } + // May be called from AC's thread (the ImGui bar's menu): write in the background. + UiBackgroundWriter.Enqueue("panel faces", () => { lock (Sync) Save(); }); + } + + public static string FaceName(PanelFace face) => face switch + { + PanelFace.ImGui => "imgui", + PanelFace.Both => "both", + _ => "avalonia", + }; + + public static bool TryParseFace(string text, out PanelFace face) + { + switch (text.Trim().ToLowerInvariant()) + { + case "avalonia": face = PanelFace.Avalonia; return true; + case "imgui": face = PanelFace.ImGui; return true; + case "both": face = PanelFace.Both; return true; + default: face = PanelFace.Avalonia; return false; + } + } + + private static void EnsureLoaded() + { + if (_loaded) return; + _loaded = true; + try + { + string path = FilePath; + if (!File.Exists(path)) return; + foreach (string raw in File.ReadAllLines(path)) + { + string line = raw.Trim(); + if (line.Length == 0 || line[0] == '#') continue; + int eq = line.IndexOf('='); + if (eq <= 0) continue; + if (TryParseFace(line.Substring(eq + 1), out PanelFace face)) + Faces[line.Substring(0, eq).Trim()] = face; + } + } + catch (Exception ex) + { + RynthLog.UI($"PanelFaceStore: load failed - {ex.GetType().Name}: {ex.Message}"); + } + } + + private static void Save() + { + try + { + string path = FilePath; + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var sb = new StringBuilder(); + sb.AppendLine("# RynthCore docked panel face (avalonia|imgui|both). Set with /rc ui <Panel> <face>."); + foreach (var (title, face) in Faces) + sb.Append(title).Append('=').AppendLine(FaceName(face)); + File.WriteAllText(path, sb.ToString()); + } + catch (Exception ex) + { + RynthLog.UI($"PanelFaceStore: save failed - {ex.GetType().Name}: {ex.Message}"); + } + } +} diff --git a/src/RynthCore.Engine/UI/PanelRouter.cs b/src/RynthCore.Engine/UI/PanelRouter.cs new file mode 100644 index 0000000..a399778 --- /dev/null +++ b/src/RynthCore.Engine/UI/PanelRouter.cs @@ -0,0 +1,227 @@ +// ============================================================================ +// RynthCore.Engine - UI/PanelRouter.cs +// The one place that decides which face shows a panel. +// +// Model (Tom, 2026-09-27): a panel docked in the client is drawn by its +// ImGui face; a panel popped out of the client is an Avalonia window. While +// the ImGui faces are being built, each panel's docked face is chosen per +// panel (PanelFaceStore; code default Avalonia) and falls back to Avalonia +// whenever ImGui can't show it. +// +// Every "open/close this panel" request goes through Toggle: bar buttons +// (docked and floating bar), the RynthAi launcher, Chat's Filters button and +// chat commands. Bar actions that aren't panels (RL, bar pop-out) pass +// straight through. +// +// Pop-out/redock: the ImGui face's ↗ and ↙ go through ImGuiPanelHost.PopOut +// and Redock; a popped-out panel is the same ImGui face in its own window +// (ImGuiPopOuts; Tom, 2026-09-29). The Avalonia face's ↙ (a panel still popped +// out in Avalonia from before) asks RedockToImGui first. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Text; +using RynthCore.Engine.ImGuiBackend; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI; + +internal static class PanelRouter +{ + /// <summary>The face that shows <paramref name="title"/> while it is docked in the client.</summary> + public static PanelFace ResolveDockedFace(string title) + { + title = Canonical(title); + if (!EngineSettings.EnableImGuiBackend || !ImGuiPanelHost.HasFace(title)) + return PanelFace.Avalonia; + // Tom, 2026-09-28: in the client it's always ImGui; Avalonia only when + // popped out. A per-panel face saved while the faces were being built + // (PanelFaceStore) no longer puts an Avalonia panel back in the client. + return PanelFace.ImGui; + } + + /// <summary>True when panels can pop out of the client (into ImGui windows, ImGuiPopOuts).</summary> + public static bool CanPopOut => EngineSettings.EnableImGuiBackend; + + /// <summary>Opens the panel if it is closed, closes it if it is open. Any thread.</summary> + public static void Toggle(string title) + { + title = Canonical(title); + PanelFace face = ResolveDockedFace(title); + if (face == PanelFace.Avalonia) + { + AvaloniaOverlay.ActivateBarButton(title); + return; + } + + if (ImGuiPanelHost.IsOpen(title)) + { + ImGuiPanelHost.Close(title); + if (face == PanelFace.Both) AvaloniaOverlay.ActivateBarButton(title); + return; + } + + // Open (popped out or in the client, the button closes it) is handled above; + // a panel last left popped out reopens popped out (ImGuiPanelHost.Apply). + ImGuiPanelHost.Open(title); + if (face == PanelFace.Both) AvaloniaOverlay.ActivateBarButton(title); + } + + // The basic Monsters panel was retired (2026-10-01): its rule editing moved into + // the Damage panel and Monster Detail. "Monsters" stays a known title (EntryPoint + // still registers its Avalonia view, and saved layouts and commands name it), and + // every request for it goes to Damage. + private const string RetiredMonstersTitle = "Monsters", MonstersPanelTitle = "Damage"; + + /// <summary>The panel that shows <paramref name="title"/>: "Monsters" is the Damage panel now.</summary> + public static string Canonical(string title) => + title.Equals(RetiredMonstersTitle, StringComparison.OrdinalIgnoreCase) ? MonstersPanelTitle : title; + + /// <summary>The dashboard's Monsters button: the Damage panel.</summary> + public static void ToggleMonsters() => Toggle(MonstersPanelTitle); + + /// <summary> + /// Engine init, before any panel restores: a "Monsters" panel saved open is saved + /// closed, and Damage open in its place (where Monsters was if Damage has no spot yet). + /// </summary> + public static void MoveRetiredMonstersPanel() + { + if (!PanelStateStore.TryGetPanel(RetiredMonstersTitle, out PanelStateStore.PanelEntry mon) || !mon.Open) return; + PanelStateStore.MarkPanelClosed(RetiredMonstersTitle); + if (PanelStateStore.TryGetPanel(MonstersPanelTitle, out PanelStateStore.PanelEntry dmg)) + { + if (!dmg.Open) PanelStateStore.SetPanel(MonstersPanelTitle, dmg with { Open = true }); + } + else PanelStateStore.SetPanel(MonstersPanelTitle, mon); + RynthLog.UI("PanelRouter: the Monsters panel was saved open; opening Damage in its place (Monsters is retired)."); + } + + /// <summary> + /// Asked by the Avalonia face's redock (↙) before it docks itself. True + /// when the docked face is ImGui: the caller closes its floating window and + /// calls <see cref="CompleteRedockToImGui"/> instead of docking. + /// </summary> + public static bool RedockGoesToImGui(string title) => ResolveDockedFace(title) == PanelFace.ImGui; + + /// <summary> + /// After the Avalonia floating window closed (its close saved "popped out, + /// closed"): mark the panel docked and open, then open the ImGui face at + /// the docked placement. Ordered with the other UI writes. + /// </summary> + public static void CompleteRedockToImGui(string title) + { + title = Canonical(title); + UiBackgroundWriter.Enqueue($"redock {title}", () => + { + PanelStateStore.TryGetPanel(title, out PanelStateStore.PanelEntry prior); + PanelStateStore.SetPanel(title, prior with { Open = true, Floating = false }); + ImGuiPanelHost.Open(title); + }); + } + + /// <summary> + /// Stores the docked face for a panel ("bar" for the overlay bar) and, if + /// the panel is open docked, moves it to the new face now. Returns a + /// one-line result for chat. Game thread or AC thread. + /// </summary> + public static string SetDockedFace(string title, PanelFace face) + { + if (title.Equals("bar", StringComparison.OrdinalIgnoreCase) || title == ImGuiBar.FaceKey) + { + PanelFaceStore.Set(ImGuiBar.FaceKey, face == PanelFace.ImGui ? null : face); + ImGuiBar.ApplyFace(); + PanelFace barNow = ImGuiBar.ResolveFace(); + return $"Bar: docked face = {PanelFaceStore.FaceName(face)}{Note(barNow, face)}."; + } + + string? known = FindRegisteredTitle(Canonical(title)); + if (known == null) + return $"No panel named '{title}'. Try /rc ui list."; + if (face != PanelFace.Avalonia && !ImGuiPanelHost.HasFace(known)) + return $"{known} has no ImGui version yet; it stays Avalonia."; + + PanelFace before = ResolveDockedFace(known); + PanelFaceStore.Set(known, face == ImGuiPanelHost.CodeDefault(known) ? null : face); + PanelFace now = ResolveDockedFace(known); + if (now != before) + MoveOpenPanel(known, before, now); + // Last closed while popped out: Toggle would reopen the Avalonia + // window. The player just picked the docked face, so the next open + // shows that instead. (An open pop-out is left alone.) + if (now != PanelFace.Avalonia && PanelStateStore.TryGetPanel(known, out PanelStateStore.PanelEntry saved) + && saved.Floating && !saved.Open) + PanelStateStore.SetPanel(known, saved with { Floating = false }); + return $"{known}: docked face = {PanelFaceStore.FaceName(face)}{Note(now, face)}."; + } + + private static string Note(PanelFace now, PanelFace asked) => + now == asked ? "" : $" (showing {PanelFaceStore.FaceName(now)}: the ImGui layer is off or Avalonia is disabled)"; + + /// <summary> + /// "Switching while the panel is open: close in the old face, open in the + /// new one at the same place" (plan §3.4). Popped-out panels aren't + /// affected - they are always the Avalonia window. Each hand-off runs its + /// steps in one ordered sequence so the last panel_state write wins. + /// </summary> + private static void MoveOpenPanel(string title, PanelFace before, PanelFace now) + { + if (!PanelStateStore.TryGetPanel(title, out PanelStateStore.PanelEntry saved) || saved.Floating) + return; + bool imguiOpen = ImGuiPanelHost.IsOpen(title); + bool avaloniaOpen = before != PanelFace.ImGui && saved.Open; // docked Avalonia face showing + + switch (before, now) + { + case (PanelFace.Avalonia, PanelFace.ImGui): + if (avaloniaOpen) + AvaloniaOverlay.PostToUi(() => + { + AvaloniaOverlay.TogglePanelOnUiThread(title); // closes it, saving its placement + ImGuiPanelHost.Open(title); // then opens there (and saves open) + }); + break; + case (PanelFace.Avalonia, PanelFace.Both): + if (avaloniaOpen) ImGuiPanelHost.Open(title); + break; + case (PanelFace.ImGui, PanelFace.Avalonia): + if (imguiOpen) ImGuiPanelHost.HandOffToAvalonia(title); + break; + case (PanelFace.ImGui, PanelFace.Both): + if (imguiOpen) AvaloniaOverlay.ActivateBarButton(title); + break; + case (PanelFace.Both, PanelFace.ImGui): + if (avaloniaOpen) AvaloniaOverlay.ActivateBarButton(title); // the ImGui copy stays + break; + case (PanelFace.Both, PanelFace.Avalonia): + if (imguiOpen) ImGuiPanelHost.Close(title); // the Avalonia copy stays + break; + } + } + + /// <summary>One line per registered panel for /rc ui list and the Status panel.</summary> + public static List<string> Describe() + { + var lines = new List<string> + { + $"Bar: docked={PanelFaceStore.FaceName(ImGuiBar.ResolveFace())}{(PanelStateStore.BarFloating ? ", popped out" : ", docked")}", + }; + foreach (var (title, _) in OverlayHost.GetPanels()) + { + var sb = new StringBuilder(title).Append(": docked=").Append(PanelFaceStore.FaceName(ResolveDockedFace(title))); + sb.Append(ImGuiPanelHost.HasFace(title) ? "" : " (no ImGui version yet)"); + if (PanelStateStore.TryGetPanel(title, out var entry)) + sb.Append(entry.Floating ? ", popped out" : ", docked").Append(entry.Open ? ", open" : ", closed"); + lines.Add(sb.ToString()); + } + return lines; + } + + private static string? FindRegisteredTitle(string title) + { + foreach (var (registered, _) in OverlayHost.GetPanels()) + if (string.Equals(registered, title, StringComparison.OrdinalIgnoreCase)) + return registered; + return null; + } +} diff --git a/src/RynthCore.Engine/UI/PanelTextScale.cs b/src/RynthCore.Engine/UI/PanelTextScale.cs new file mode 100644 index 0000000..e3aa193 --- /dev/null +++ b/src/RynthCore.Engine/UI/PanelTextScale.cs @@ -0,0 +1,195 @@ +// ============================================================================ +// RynthCore.Engine - UI/PanelTextScale.cs +// Per-panel text size for the in-client (ImGui) panels. Sizes 0-10; 0 is the +// normal size, each step is 10% bigger, and the last one ("yourjokin") is +// 2.5x. Stored for the whole PC in %LOCALAPPDATA%\RynthCore\panel_text_size.txt +// as "Title=size" lines; set from Settings > Display or from a window's own +// title bar (the text size button, Ctrl+wheel; ImGuiPanelHost). One size +// ("All Panels") applies to every panel unless "Size each panel separately" +// is on. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; + +namespace RynthCore.Engine.UI; + +internal static class PanelTextScale +{ + /// <summary>Picker labels, index = size.</summary> + public static readonly string[] SizeNames = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "yourjokin" }; + + private static readonly float[] Scales = { 1.0f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f, 1.6f, 1.7f, 1.8f, 1.9f, 2.5f }; + + private static readonly object Sync = new(); + private static readonly Dictionary<string, int> Sizes = new(StringComparer.OrdinalIgnoreCase); + private static bool _loaded; + + private static string FilePath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_text_size.txt"); + + private const string AllKey = "__all"; + private const string PerPanelKey = "__perPanel"; + + /// <summary>The size (0-10) a panel is drawn at: its own when sizing per panel, else All Panels.</summary> + public static int Get(string title) + { + lock (Sync) + { + Load(); + int all = Sizes.TryGetValue(AllKey, out int a) ? a : 0; + if (!(Sizes.TryGetValue(PerPanelKey, out int pp) && pp != 0)) return all; + return Sizes.TryGetValue(title, out int s) ? s : all; + } + } + + /// <summary>The panel's own size setting (per-panel rows), falling back to All Panels.</summary> + public static int GetOwn(string title) + { + lock (Sync) + { + Load(); + if (Sizes.TryGetValue(title, out int s)) return s; + return Sizes.TryGetValue(AllKey, out int a) ? a : 0; + } + } + + public static int GetAll() => GetOwn(AllKey); + public static void SetAll(int size) => Set(AllKey, size); + + /// <summary>Off: every panel uses All Panels. On: each panel has its own size.</summary> + public static bool PerPanel + { + get { lock (Sync) { Load(); return Sizes.TryGetValue(PerPanelKey, out int v) && v != 0; } } + set => Set(PerPanelKey, value ? 1 : 0); + } + + public static void Set(string title, int size) + { + size = Math.Clamp(size, 0, SizeNames.Length - 1); + lock (Sync) + { + Load(); + if (Sizes.TryGetValue(title, out int cur) && cur == size) return; + Sizes[title] = size; + Save(); + RynthCore.Engine.ImGuiBackend.ImGuiFonts.RequestRebuild(RebuildDelayMs); + } + } + + // Changes a few clicks or wheel notches apart re-bake the fonts once, after the + // last one (ImGuiFonts.RequestRebuild). Until then a panel draws at the nearest + // size already baked (ImGuiFonts.BakedStepNear). + private const int RebuildDelayMs = 250; + + /// <summary> + /// Sets one window's size from its own title bar (ImGuiPanelHost). If every panel + /// shares All Panels, this switches on "Size each panel separately" with every + /// other panel kept at the All Panels size, so only this window changes. + /// </summary> + public static void SetForWindow(string title, int size) + { + size = Math.Clamp(size, 0, SizeNames.Length - 1); + lock (Sync) + { + Load(); + bool perPanel = Sizes.TryGetValue(PerPanelKey, out int pp) && pp != 0; + if (perPanel) + { + if (Sizes.TryGetValue(title, out int cur) && cur == size) return; + } + else + { + int all = Sizes.TryGetValue(AllKey, out int a) ? a : 0; + if (size == all) return; + // Rows left over from an earlier per-panel session would come back into + // effect: start them from what every panel shows now. + var keys = new List<string>(Sizes.Keys); + foreach (string k in keys) + if (k != AllKey && k != PerPanelKey) Sizes[k] = all; + Sizes[PerPanelKey] = 1; + } + Sizes[title] = size; + Save(); + RynthCore.Engine.ImGuiBackend.ImGuiFonts.RequestRebuild(RebuildDelayMs); + } + } + + /// <summary>One window back to the size every other panel uses (All Panels).</summary> + public static void ResetWindow(string title) => SetForWindow(title, GetAll()); + + /// <summary>Every panel at <paramref name="size"/>: All Panels, per-panel sizing off.</summary> + public static void UseForAll(int size) + { + size = Math.Clamp(size, 0, SizeNames.Length - 1); + lock (Sync) + { + Load(); + Sizes[AllKey] = size; + Sizes[PerPanelKey] = 0; + Save(); + RynthCore.Engine.ImGuiBackend.ImGuiFonts.RequestRebuild(RebuildDelayMs); + } + } + + /// <summary>"Size 3 (130%)": a size for tooltips.</summary> + public static string Describe(int step) + { + step = Math.Clamp(step, 0, SizeNames.Length - 1); + int pct = (int)MathF.Round(Factor(step) * 100f); + return step == 0 ? "normal (100%)" : $"{SizeNames[step]} ({pct.ToString(CultureInfo.InvariantCulture)}%)"; + } + + /// <summary>Font size factor for a size step.</summary> + public static float Factor(int step) => Scales[Math.Clamp(step, 0, Scales.Length - 1)]; + + /// <summary>The distinct non-zero sizes any panel uses (fonts are baked for these).</summary> + public static List<int> StepsInUse() + { + lock (Sync) + { + Load(); + var steps = new List<int>(); + bool perPanel = Sizes.TryGetValue(PerPanelKey, out int pp) && pp != 0; + foreach (var kv in Sizes) + { + if (kv.Key == PerPanelKey) continue; + if (!perPanel && kv.Key != AllKey) continue; // only All Panels is in use + if (kv.Value > 0 && !steps.Contains(kv.Value)) steps.Add(kv.Value); + } + return steps; + } + } + + private static void Load() + { + if (_loaded) return; + _loaded = true; + try + { + if (!File.Exists(FilePath)) return; + foreach (string line in File.ReadAllLines(FilePath)) + { + int eq = line.IndexOf('='); + if (eq <= 0) continue; + if (int.TryParse(line.AsSpan(eq + 1).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int s)) + Sizes[line[..eq].Trim()] = Math.Clamp(s, 0, SizeNames.Length - 1); + } + } + catch { } + } + + private static void Save() + { + try + { + Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); + var lines = new List<string>(); + foreach (var kv in Sizes) lines.Add($"{kv.Key}={kv.Value.ToString(CultureInfo.InvariantCulture)}"); + File.WriteAllLines(FilePath, lines); + } + catch { } + } +} diff --git a/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs b/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs index 298c522..a9e5c72 100644 --- a/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs @@ -8,13 +8,10 @@ // Consumables — Name, Type picker, Delete // Mana Stones — Enable tapping toggle, keep count, min mana threshold // -// Plugin exports used: -// RynthPluginGetItemsJson → polled every 1s for external edits -// RynthPluginSetItemsJson → write-back on edit -// RynthPluginAddSelectedWeapon → add currently selected inventory item as weapon -// RynthPluginAddSelectedShield → add currently selected inventory item as off-hand shield -// (RynthAi 0.6.20+; button explains when missing) -// RynthPluginAddSelectedConsumable → add currently selected inventory item as consumable +// Data goes through UiDataHub (UI/Data/ItemsData.cs): UiSources.Items polls +// RynthPluginGetItemsJson on the pump thread; ItemsCommands saves +// (RynthPluginSetItemsJson) and adds the selected item there. The ImGui face +// (ImGui/Panels/ItemsFace.cs) reads the same snapshot. // ============================================================================ using System; @@ -29,6 +26,7 @@ using Avalonia.Layout; using Avalonia.Media; using Avalonia.Threading; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; @@ -38,25 +36,6 @@ internal partial class ItemsPanelJsonContext : JsonSerializerContext { } internal static class ItemsPanel { - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate IntPtr GetItemsJsonFn(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void SetItemsJsonFn(IntPtr ansiJson); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void VoidFn(); - - private static GetItemsJsonFn? _getItemsJson; - private static SetItemsJsonFn? _setItemsJson; - private static VoidFn? _addSelectedWeapon; - private static VoidFn? _addSelectedShield; - private static VoidFn? _addSelectedConsumable; - - /// <summary>ItemRule.Action value the plugin uses for off-hand shields.</summary> - private const string ShieldAction = "Shield"; - private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33)); private static readonly IBrush ColRed = new SolidColorBrush(Color.FromRgb(0xFF, 0x55, 0x55)); private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6)); @@ -73,7 +52,7 @@ internal static class ItemsPanel { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; private static readonly string[] ConsumableTypes = - { "General", "Lockpick", "HealthKit", "ManaStone", "Stamina", "Pet" }; + { "General", "Lockpick", "HealthKit", "HealthPotion", "ManaPotion", "StaminaPotion", "ManaStone", "Stamina", "Pet" }; internal sealed class Payload { @@ -95,7 +74,7 @@ internal static class ItemsPanel // "Weapon" or "Shield" (older settings may hold "Loot"). Round-tripped untouched. [JsonPropertyName("action")] public string Action { get; set; } = "Weapon"; - public bool IsShield => string.Equals(Action, ShieldAction, StringComparison.OrdinalIgnoreCase); + public bool IsShield => string.Equals(Action, ItemsCommands.ShieldAction, StringComparison.OrdinalIgnoreCase); } internal sealed class ConsumableEntry @@ -113,7 +92,6 @@ internal static class ItemsPanel public static Control Create() { - TryBind(); var state = new State(); @@ -266,11 +244,7 @@ internal static class ItemsPanel } body.Children.Add(BuildAddButton("Add Selected Weapon", "(select a weapon in inventory first)", - () => - { - if (_addSelectedWeapon == null) TryBind(); - _addSelectedWeapon?.Invoke(); - })); + ItemsCommands.AddSelectedWeapon)); body.Children.Add(BuildDivider()); @@ -309,12 +283,7 @@ internal static class ItemsPanel } body.Children.Add(BuildAddButton("Add Selected Shield", "(select a shield in inventory first)", - () => - { - if (_addSelectedShield == null) TryBind(); - if (_addSelectedShield != null) _addSelectedShield(); - else RynthLog.UI("ItemsPanel: Add Selected Shield unavailable — RynthAi 0.6.20 or newer is required."); - })); + ItemsCommands.AddSelectedShield)); body.Children.Add(BuildDivider()); @@ -345,11 +314,7 @@ internal static class ItemsPanel } body.Children.Add(BuildAddButton("Add Selected Consumable", "(select an item in inventory first)", - () => - { - if (_addSelectedConsumable == null) TryBind(); - _addSelectedConsumable?.Invoke(); - })); + ItemsCommands.AddSelectedConsumable)); body.Children.Add(BuildDivider()); @@ -368,7 +333,6 @@ internal static class ItemsPanel var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) }; timer.Tick += (_, _) => { - if (_getItemsJson == null) TryBind(); if (state.Dirty) return; if (!TryFetch(out var fresh)) return; @@ -402,8 +366,17 @@ internal static class ItemsPanel // Stop with the visual tree — a running DispatcherTimer roots the closed // view forever (one immortal poller per open/close). RadarPanel idiom; // must restart on attach: drag/resize fires Detached→Attached. - root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); }; - root.DetachedFromVisualTree += (_, _) => timer.Stop(); + root.AttachedToVisualTree += (_, _) => + { + UiSources.Items.Subscribe(); + UiSources.Items.RequestRefresh(); + if (!timer.IsEnabled) timer.Start(); + }; + root.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.Items.Unsubscribe(); + }; return root; } @@ -864,87 +837,26 @@ internal static class ItemsPanel return b; } - // ── Plugin binding ──────────────────────────────────────────────────────── - // RL loads fresh plugin copies without unloading the old ones: drop the - // exports bound below so the next poll re-binds to the live copy. - static ItemsPanel() => PluginManager.PluginsUnloaded += () => - { - _getItemsJson = null; - _setItemsJson = null; - _addSelectedWeapon = null; - _addSelectedShield = null; - _addSelectedConsumable = null; - }; - - private static void TryBind() - { - var plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - if (_getItemsJson == null) - { - IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetItemsJson"); - if (p != IntPtr.Zero) _getItemsJson = Marshal.GetDelegateForFunctionPointer<GetItemsJsonFn>(p); - } - if (_setItemsJson == null) - { - IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetItemsJson"); - if (p != IntPtr.Zero) _setItemsJson = Marshal.GetDelegateForFunctionPointer<SetItemsJsonFn>(p); - } - if (_addSelectedWeapon == null) - { - IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginAddSelectedWeapon"); - if (p != IntPtr.Zero) _addSelectedWeapon = Marshal.GetDelegateForFunctionPointer<VoidFn>(p); - } - if (_addSelectedShield == null) - { - IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginAddSelectedShield"); - if (p != IntPtr.Zero) _addSelectedShield = Marshal.GetDelegateForFunctionPointer<VoidFn>(p); - } - if (_addSelectedConsumable == null) - { - IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginAddSelectedConsumable"); - if (p != IntPtr.Zero) _addSelectedConsumable = Marshal.GetDelegateForFunctionPointer<VoidFn>(p); - } - } + // ── Hub ─────────────────────────────────────────────────────────────────── + // The hub version at the last save: older snapshots predate it and would + // briefly revert the edit on screen, so they're skipped. + private static long _savedAtVersion = -1; + // A private copy of the hub's latest items (the panel edits it in place). private static bool TryFetch(out Payload payload) { payload = new Payload(); - if (_getItemsJson == null) return false; - try - { - IntPtr ptr = _getItemsJson(); - if (ptr == IntPtr.Zero) return false; - string? json = Marshal.PtrToStringAnsi(ptr); - if (string.IsNullOrEmpty(json)) return false; - var parsed = JsonSerializer.Deserialize(json, ItemsPanelJsonContext.Default.Payload); - if (parsed == null) return false; - payload = parsed; - return true; - } - catch { return false; } + var snap = UiSources.Items.Current; + if (snap == null || snap.Version <= _savedAtVersion) return false; + payload = snap.Value.ParseCopy(); + return true; } private static void PushChanges(State state) { - if (_setItemsJson == null) TryBind(); - if (_setItemsJson == null) return; - - IntPtr ansi = IntPtr.Zero; - try - { - string json = JsonSerializer.Serialize(state.Data, ItemsPanelJsonContext.Default.Payload); - ansi = Marshal.StringToHGlobalAnsi(json); - _setItemsJson(ansi); - state.Dirty = false; - } - catch { } - finally - { - if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi); - } + _savedAtVersion = UiSources.Items.Current?.Version ?? _savedAtVersion; + ItemsCommands.SetJson(ItemsCommands.Serialize(state.Data)); + state.Dirty = false; } // ── Change detection ────────────────────────────────────────────────────── diff --git a/src/RynthCore.Engine/UI/Panels/LogPanel.cs b/src/RynthCore.Engine/UI/Panels/LogPanel.cs index baf0f2b..954f591 100644 --- a/src/RynthCore.Engine/UI/Panels/LogPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/LogPanel.cs @@ -1,6 +1,6 @@ // ============================================================================ // RynthCore.Engine - UI/Panels/LogPanel.cs -// Scrollable log viewer. Polls EntryPoint.GetRecentLogLines() every second. +// Scrollable log viewer. Shows UiDataHub's log snapshot (UiSources.Log). // Auto-scroll follows the tail; checkbox to pin scroll position. // ============================================================================ @@ -11,6 +11,8 @@ using Avalonia.Layout; using Avalonia.Media; using Avalonia.Threading; +using RynthCore.Engine.UI.Data; + namespace RynthCore.Engine.UI.Panels; internal static class LogPanel @@ -25,6 +27,10 @@ internal static class LogPanel BorderThickness = new Avalonia.Thickness(0) }; ScrollViewer.SetHorizontalScrollBarVisibility(listBox, ScrollBarVisibility.Disabled); + // Not virtualized: popped out, the panel is rendered from a copy parked + // off-screen (x=2500), where a virtualizing panel realizes no rows and + // the list showed empty. At most 256 lines, so realizing all is cheap. + listBox.ItemsPanel = new Avalonia.Controls.Templates.FuncTemplate<Panel?>(() => new StackPanel()); var autoScrollCheck = new CheckBox { @@ -39,10 +45,15 @@ internal static class LogPanel Margin = new Avalonia.Thickness(4, 0, 0, 0) }; - string[]? _clearedSnapshot = null; + // Clear remembers the sequence number of the newest line; later ticks + // show only newer lines. (It used to remember a line count, which left + // the panel blank for good once the 256-line ring was full.) + long clearedSeq = 0; + long seenVersion = -1; clearButton.Click += (_, _) => { - _clearedSnapshot = EntryPoint.GetRecentLogLines(); + clearedSeq = UiSources.Log.Current?.Value.LastSeq ?? EntryPoint.RecentLogSeq; + seenVersion = -1; listBox.ItemsSource = Array.Empty<string>(); }; @@ -67,29 +78,34 @@ internal static class LogPanel var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) }; timer.Tick += (_, _) => { - string[] lines = EntryPoint.GetRecentLogLines(); - - // If cleared, only show lines that arrived after the clear snapshot - if (_clearedSnapshot != null) - { - int clearCount = _clearedSnapshot.Length; - if (lines.Length > clearCount) - lines = lines[clearCount..]; - else - lines = Array.Empty<string>(); - } + var snap = UiSources.Log.Current; + if (snap == null || snap.Version == seenVersion) return; + seenVersion = snap.Version; + LogSnapshot log = snap.Value; + int start = (int)Math.Clamp(clearedSeq - log.FirstSeq + 1, 0, log.Lines.Length); + string[] lines = start == 0 ? log.Lines : log.Lines[start..]; listBox.ItemsSource = lines; if (autoScrollCheck.IsChecked == true && lines.Length > 0) scroll.ScrollToEnd(); }; - timer.Start(); // Stop with the visual tree — a running DispatcherTimer roots the closed // view forever (one immortal poller per open/close). RadarPanel idiom; - // must restart on attach: drag/resize fires Detached→Attached. - root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); }; - root.DetachedFromVisualTree += (_, _) => timer.Stop(); + // must restart on attach: drag/resize fires Detached→Attached. The data + // comes from UiDataHub, which polls only while a face is subscribed. + root.AttachedToVisualTree += (_, _) => + { + UiSources.Log.Subscribe(); + UiSources.Log.RequestRefresh(); + seenVersion = -1; + if (!timer.IsEnabled) timer.Start(); + }; + root.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.Log.Unsubscribe(); + }; return root; } diff --git a/src/RynthCore.Engine/UI/Panels/LuaPanel.cs b/src/RynthCore.Engine/UI/Panels/LuaPanel.cs new file mode 100644 index 0000000..0a26585 --- /dev/null +++ b/src/RynthCore.Engine/UI/Panels/LuaPanel.cs @@ -0,0 +1,279 @@ +// ============================================================================ +// RynthCore.Engine — UI/Panels/LuaPanel.cs +// Lua scripts for RynthAi: script list, editor, Run/Stop, console. +// +// Data goes through UiDataHub (UI/Data/LuaData.cs): UiSources.Lua polls +// RynthPluginGetLuaJson on the pump thread and LuaCommands sends +// RynthPluginSendLuaCommand there; the ImGui face (ImGui/Panels/LuaFace.cs) +// reads the same snapshot. +// +// Controls are built once and updated in place: a full rebuild every poll +// (the NavPanel pattern) would reset the editor's caret while typing. The +// script list uses plain buttons, not a dropdown, because overlay popups +// blank the docked panels. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Threading; +using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.UI.Panels; + +internal static class LuaPanel +{ + // Lazy: see the dispatcher-poison invariant in EntryPoint.InitWorker. + private static IBrush? _amber, _green, _mute, _text, _shell, _btnFill, _btnBord, _startBg, _stopBg, _consoleBg; + private static IBrush ColAmber => _amber ??= new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33)); + private static IBrush ColGreen => _green ??= new SolidColorBrush(Color.FromRgb(0x33, 0xCC, 0x66)); + private static IBrush ColMute => _mute ??= new SolidColorBrush(Color.FromRgb(0x8C, 0xA6, 0xBF)); + private static IBrush ColTextDim => _text ??= new SolidColorBrush(Color.FromRgb(0xD9, 0xE6, 0xF2)); + private static IBrush ColShellBg => _shell ??= new SolidColorBrush(Color.FromRgb(0x0A, 0x0F, 0x14)); + private static IBrush ColBtnFill => _btnFill ??= new SolidColorBrush(Color.FromRgb(0x0F, 0x1F, 0x2E)); + private static IBrush ColBtnBord => _btnBord ??= new SolidColorBrush(Color.FromRgb(0x26, 0x40, 0x59)); + private static IBrush ColStartBg => _startBg ??= new SolidColorBrush(Color.FromRgb(0x19, 0x61, 0x19)); + private static IBrush ColStopBg => _stopBg ??= new SolidColorBrush(Color.FromRgb(0x80, 0x19, 0x19)); + private static IBrush ColConsole => _consoleBg ??= new SolidColorBrush(Color.FromRgb(0x05, 0x09, 0x0D)); + + // ========================================================================= + // Create + // ========================================================================= + + public static Control Create() + { + + var root = new Border + { + Background = ColShellBg, + BorderBrush = ColBtnBord, + BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(4), + MinWidth = 380, + }; + var content = new StackPanel { Margin = new Thickness(6), Spacing = 4 }; + root.Child = new ScrollViewer + { + VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, + HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled, + Content = content, + }; + + // ── Status + Run/Stop ──────────────────────────────────────────────── + var statusText = new TextBlock + { + Text = "Lua: idle", Foreground = ColAmber, FontSize = 11, FontWeight = FontWeight.Bold, + TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center, + }; + var runBtn = MakeBtn("▶ Run"); + runBtn.Background = ColStartBg; + var stopBtn = MakeBtn("■ Stop"); + stopBtn.Background = ColStopBg; + var topRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto") }; + Grid.SetColumn(statusText, 0); + Grid.SetColumn(runBtn, 1); + Grid.SetColumn(stopBtn, 2); + topRow.Children.Add(statusText); + topRow.Children.Add(runBtn); + topRow.Children.Add(stopBtn); + content.Children.Add(topRow); + + // ── Script list (LuaScripts folder) ────────────────────────────────── + content.Children.Add(new TextBlock { Text = "Scripts (click to open):", Foreground = ColMute, FontSize = 10 }); + var scriptWrap = new WrapPanel { Orientation = Orientation.Horizontal }; + content.Children.Add(scriptWrap); + + // ── Name + Save ────────────────────────────────────────────────────── + var nameBox = new TextBox + { + Watermark = "Script name...", + Background = ColBtnFill, Foreground = ColTextDim, + BorderBrush = ColBtnBord, BorderThickness = new Thickness(1), + FontSize = 10, Height = 22, Padding = new Thickness(4, 1), + Margin = new Thickness(0, 0, 4, 0), + }; + var saveBtn = MakeBtn("Save"); + var deleteBtn = MakeBtn("Delete"); + var newBtn = MakeBtn("New"); + var saveRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto,Auto") }; + Grid.SetColumn(nameBox, 0); + Grid.SetColumn(saveBtn, 1); + Grid.SetColumn(newBtn, 2); + Grid.SetColumn(deleteBtn, 3); + saveRow.Children.Add(nameBox); + saveRow.Children.Add(saveBtn); + saveRow.Children.Add(newBtn); + saveRow.Children.Add(deleteBtn); + content.Children.Add(saveRow); + + // ── Editor ─────────────────────────────────────────────────────────── + var editor = new TextBox + { + AcceptsReturn = true, + AcceptsTab = true, + TextWrapping = TextWrapping.NoWrap, + FontFamily = new FontFamily("Consolas, Courier New, monospace"), + FontSize = 11, + Height = 240, + Background = ColBtnFill, Foreground = ColTextDim, + BorderBrush = ColBtnBord, BorderThickness = new Thickness(1), + Padding = new Thickness(4), + Watermark = "-- Lua script\nprint('hello from ' .. me.name)", + }; + ScrollViewer.SetHorizontalScrollBarVisibility(editor, Avalonia.Controls.Primitives.ScrollBarVisibility.Auto); + ScrollViewer.SetVerticalScrollBarVisibility(editor, Avalonia.Controls.Primitives.ScrollBarVisibility.Auto); + content.Children.Add(editor); + + // ── Console ────────────────────────────────────────────────────────── + var clearBtn = MakeBtn("Clear"); + var consoleHdr = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; + var consoleLbl = new TextBlock { Text = "Console", Foreground = ColMute, FontSize = 10, VerticalAlignment = VerticalAlignment.Center }; + Grid.SetColumn(consoleLbl, 0); + Grid.SetColumn(clearBtn, 1); + consoleHdr.Children.Add(consoleLbl); + consoleHdr.Children.Add(clearBtn); + content.Children.Add(consoleHdr); + + var consoleText = new SelectableTextBlock + { + Foreground = ColGreen, + FontFamily = new FontFamily("Consolas, Courier New, monospace"), + FontSize = 10, + TextWrapping = TextWrapping.Wrap, + }; + var consoleScroll = new ScrollViewer + { + Height = 150, + VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, + HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled, + Content = consoleText, + }; + content.Children.Add(new Border + { + Background = ColConsole, BorderBrush = ColBtnBord, BorderThickness = new Thickness(1), + Padding = new Thickness(4), Child = consoleScroll, + }); + + // ── Actions ────────────────────────────────────────────────────────── + runBtn.Click += (_, _) => + LuaCommands.Send("run", nameBox.Text?.Trim() ?? string.Empty, editor.Text ?? string.Empty); + stopBtn.Click += (_, _) => LuaCommands.Send("stop"); + clearBtn.Click += (_, _) => { LuaCommands.Send("clearConsole"); consoleText.Text = string.Empty; }; + saveBtn.Click += (_, _) => + { + string name = nameBox.Text?.Trim() ?? string.Empty; + if (name.Length == 0) { consoleText.Text += "\n[panel] Type a script name first."; return; } + LuaCommands.Send("save", name, editor.Text ?? string.Empty); + }; + newBtn.Click += (_, _) => { editor.Text = string.Empty; nameBox.Text = string.Empty; }; + deleteBtn.Click += (_, _) => + { + string name = nameBox.Text?.Trim() ?? string.Empty; + if (name.Length > 0) LuaCommands.Send("delete", name); + }; + + // ── Poll ───────────────────────────────────────────────────────────── + int lastConsoleSeq = -1, lastLoadSeq = -1; + string lastScripts = "\0"; + bool firstFetch = true; + long seenVersion = -1; + + void Refresh() + { + var snap = UiSources.Lua.Current; + if (snap == null) + { + statusText.Text = "Lua: RynthLua not connected"; + return; + } + if (snap.Version == seenVersion) return; + seenVersion = snap.Version; + LuaPayload d = snap.Value; + + statusText.Text = d.Running + ? $"Running: {(d.ScriptName.Length > 0 ? d.ScriptName : "(editor)")}" + : (d.Status.Length > 0 ? d.Status : "Lua: idle"); + statusText.Foreground = d.Running ? ColGreen : ColAmber; + + string joined = string.Join("\n", d.Scripts); + if (joined != lastScripts) + { + lastScripts = joined; + scriptWrap.Children.Clear(); + if (d.Scripts.Count == 0) + scriptWrap.Children.Add(new TextBlock { Text = "(none yet: write one and Save)", Foreground = ColMute, FontSize = 10 }); + foreach (string s in d.Scripts) + { + string name = s; + var b = MakeBtn(name); + b.Click += (_, _) => LuaCommands.Send("load", name); + scriptWrap.Children.Add(b); + } + } + + // Take a loaded script into the editor; on first open, restore the + // plugin's current editor text without counting it as a new load. + if (d.LoadSeq != lastLoadSeq) + { + bool take = !firstFetch || string.IsNullOrEmpty(editor.Text); + lastLoadSeq = d.LoadSeq; + if (take) + { + editor.Text = d.LoadedText; + nameBox.Text = d.LoadedName; + } + } + + if (d.ConsoleSeq != lastConsoleSeq) + { + lastConsoleSeq = d.ConsoleSeq; + consoleText.Text = d.Console; + consoleScroll.ScrollToEnd(); + } + firstFetch = false; + } + + // Reads the hub's snapshot (fetched every 500 ms while subscribed, and + // right after each command). + var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) }; + timer.Tick += (_, _) => Refresh(); + // Stop with the visual tree (RadarPanel idiom); restart on attach since + // drag/resize fires Detached→Attached. + root.AttachedToVisualTree += (_, _) => + { + UiSources.Lua.Subscribe(); + UiSources.Lua.RequestRefresh(); + if (!timer.IsEnabled) timer.Start(); + }; + root.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.Lua.Unsubscribe(); + }; + + Refresh(); + return root; + } + + private static Button MakeBtn(string text) => new Button + { + Content = text, + Background = ColBtnFill, + Foreground = ColTextDim, + BorderBrush = ColBtnBord, + BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(3), + Padding = new Thickness(8, 3), + FontSize = 10, + Height = 24, + Margin = new Thickness(0, 0, 4, 4), + }; +} diff --git a/src/RynthCore.Engine/UI/Panels/MetaPanel.cs b/src/RynthCore.Engine/UI/Panels/MetaPanel.cs index 2f8fc04..89c24bd 100644 --- a/src/RynthCore.Engine/UI/Panels/MetaPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/MetaPanel.cs @@ -2,9 +2,10 @@ // RynthCore.Engine — UI/Panels/MetaPanel.cs // Avalonia port of LegacyMetaUi.cs (RynthSuite plugin). // -// Plugin exports used: -// RynthPluginGetMetaJson → polled every 2s for live state -// RynthPluginSendMetaCommand → dispatched on user actions +// Data goes through UiDataHub (UI/Data/MetaData.cs): the snapshot comes +// from UiSources.Meta and commands go out through MetaCommands, so the +// plugin's exports run on the pump thread, not on this UI thread. The ImGui +// face (ImGui/Panels/MetaFace.cs) reads the same snapshot. // ============================================================================= using System; @@ -20,33 +21,13 @@ using Avalonia.Layout; using Avalonia.Media; using Avalonia.Threading; using RynthCore.Engine.Plugins; -using RynthCore.Install; +using RynthCore.Engine.UI.Data; +using Payload = RynthCore.Engine.UI.Data.MetaPayload; namespace RynthCore.Engine.UI.Panels; -[JsonSerializable(typeof(MetaPanel.Payload))] -[JsonSerializable(typeof(MetaPanel.MetaCmd))] -[JsonSerializable(typeof(MetaPanel.MetaRuleDto))] -[JsonSerializable(typeof(MetaPanel.MetaFile))] -[JsonSerializable(typeof(List<MetaPanel.MetaRuleDto>), TypeInfoPropertyName = "MetaRuleDtoList")] -[JsonSerializable(typeof(List<MetaPanel.MetaFile>), TypeInfoPropertyName = "MetaFileList")] -[JsonSerializable(typeof(List<string>), TypeInfoPropertyName = "StringList")] -[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)] -internal partial class MetaPanelJsonContext : JsonSerializerContext { } - internal static class MetaPanel { - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate IntPtr GetMetaJsonFn(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void SendMetaCommandFn(IntPtr ansiJson); - - private static GetMetaJsonFn? _getMetaJson; - private static SendMetaCommandFn? _sendMetaCommand; - // ── Colors ──────────────────────────────────────────────────────────────── private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6)); private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33)); @@ -64,115 +45,14 @@ internal static class MetaPanel private static readonly IBrush ColStateHdrA = new SolidColorBrush(Color.FromRgb(0x0E, 0x1E, 0x30)); private static readonly IBrush ColStateHdrB = new SolidColorBrush(Color.FromRgb(0x16, 0x2A, 0x40)); - // ── Condition / action name tables (mirrors LegacyMetaUi) ───────────────── - private static readonly string[] ConditionNames = - { - "Never", "Always", "All", "Any", "Chat Message", "Pack Slots <=", - "Seconds in State >=", "Character Death", "Any Vendor Open", - "Vendor Closed", "Inventory Item Count <=", "Inventory Item Count >=", - "Monster Name Count Within Dist", "Monster Priority Count Within Dist", - "Need To Buff", "No Monsters Within Dist", "Landblock ==", - "Landcell ==", "Portalspace Entered", "Portalspace Exited", "Not", - "Seconds in State (P) >=", "Time Left On Spell >=", "Time Left On Spell <=", - "Burden % >=", "Dist Any Route PT >=", "Expression", - "Chat Message Capture", "Navroute Empty", - "Main Health <=", "Main Health % >=", "Main Mana <=", "Main Mana % >=", - "Main Stam <=", "Vitae % >=", - }; - - private static readonly string[] ConditionHints = - { - "", "", "(sub-conditions)", "(sub-conditions)", "Regex pattern", "Min slots (e.g. 5)", - "Seconds (e.g. 10)", "", "", "", - "name,count (e.g. Mana Stone,5)", "name,count (e.g. Mana Stone,5)", - "name regex,distance,count", "count,distance (e.g. 1,20)", - "", "Distance (e.g. 20)", "Hex (e.g. A9B40000)", "Hex (e.g. A9B40000)", - "", "", "(sub-conditions)", "Seconds (e.g. 10)", - "spellId,seconds (e.g. 2293,30)", "spellId,seconds (e.g. 2293,30)", - "Percentage (e.g. 250)", "Distance (e.g. 10)", "Expression", - "Regex pattern", "", - "", "", "", "", "", "Vitae % (e.g. 5)", - }; - - private static readonly string[] ActionNames = - { - "None", "Chat Command", "Set Meta State", "Embedded Nav Route", "All", - "Call Meta State", "Return From Call", "Expression Action", "Chat Expression", - "Set Watchdog", "Clear Watchdog", "Get RA Option", "Set RA Option", - "Create View", "Destroy View", "Destroy All Views", - }; - - private static readonly string[] ActionHints = - { - "", "e.g. /say hello", "State name", "Route name", "(sub-actions)", - "State name", "", "Expression", "Expression", - "state;meters;seconds (e.g. Default;10;60)", "", "Option name", "OptionName;Value", - "", "", "", - }; - - // Composite condition indices: All=2, Any=3, Not=20 - private static bool IsCompositeCondition(int idx) => idx is 2 or 3 or 20; - - /// <summary>One condition as text, nested ones included: "Not No Monsters Within Dist: 5", - /// "Any(Chat Message: …, Navroute Empty)".</summary> - private static string CondText(MetaRuleDto c, int depth = 0) - { - string name = c.Condition >= 0 && c.Condition < ConditionNames.Length - ? ConditionNames[c.Condition] : $"Cond({c.Condition})"; - if (IsCompositeCondition(c.Condition) && c.Children.Count > 0 && depth < MaxSubConditionDepth) - { - if (c.Condition == 20) return $"Not {CondText(c.Children[0], depth + 1)}"; - return $"{name}({string.Join(", ", c.Children.Select(x => CondText(x, depth + 1)))})"; - } - return string.IsNullOrEmpty(c.ConditionData) ? name : $"{name}: {c.ConditionData}"; - } - // All action index = 4 - private static bool IsAllAction(int idx) => idx == 4; - - // ── Data types ──────────────────────────────────────────────────────────── - - internal sealed class MetaRuleDto - { - public string State { get; set; } = "Default"; - public int Condition { get; set; } - public string ConditionData { get; set; } = string.Empty; - public int Action { get; set; } - public string ActionData { get; set; } = string.Empty; - public List<MetaRuleDto> Children { get; set; } = new(); - public List<MetaRuleDto> ActionChildren { get; set; } = new(); - public bool Enabled { get; set; } = true; - public long LastFiredMs { get; set; } = 99999; - } - - internal sealed class MetaFile - { - public string Path { get; set; } = string.Empty; - public string Display { get; set; } = string.Empty; - } - - internal sealed class Payload - { - public bool EnableMeta { get; set; } - public bool MetaDebug { get; set; } - public string CurrentState { get; set; } = "Default"; - public string CurrentMetaPath { get; set; } = string.Empty; - public List<MetaRuleDto> Rules { get; set; } = new(); - public List<MetaFile> Files { get; set; } = new(); - public List<string> States { get; set; } = new(); - public List<string> NavFiles { get; set; } = new(); - public List<string> EmbeddedNavKeys { get; set; } = new(); - public string SourceText { get; set; } = string.Empty; - } - - internal sealed class MetaCmd - { - public string Op { get; set; } = string.Empty; - public int Index { get; set; } = -1; - public string Value { get; set; } = string.Empty; - public string Path { get; set; } = string.Empty; - public string Text { get; set; } = string.Empty; - public MetaRuleDto? Rule { get; set; } - } + // ── Names, hints, text helpers (shared with the ImGui face) ────────────── + private static readonly string[] ConditionNames = MetaVocabulary.ConditionNames; + private static readonly string[] ConditionHints = MetaVocabulary.ConditionHints; + private static readonly string[] ActionNames = MetaVocabulary.ActionNames; + private static readonly string[] ActionHints = MetaVocabulary.ActionHints; + private static bool IsCompositeCondition(int idx) => MetaVocabulary.IsCompositeCondition(idx); + private static bool IsAllAction(int idx) => MetaVocabulary.IsAllAction(idx); + private static string CondText(MetaRuleDto c) => MetaVocabulary.CondText(c); // ── View state ──────────────────────────────────────────────────────────── @@ -186,7 +66,13 @@ internal static class MetaPanel public MetaRuleDto EditingRule = new() { State = "Default", Action = 1 }; public string SourceText = string.Empty; public string SourceMsg = string.Empty; + public bool SourceMsgOk = true; public DateTime SourceMsgTime = DateTime.MinValue; + public TextBlock? SourceMsgRef; + // Source "Apply": the plugin's ApplyResult.Seq before the apply was + // sent; a newer seq in a snapshot is this apply's result. -2 = none pending. + public long ApplySeqBefore = -2; + public DateTime ApplySentAt; public string SaveName = string.Empty; public bool ShowSaveInput; public HashSet<string> CollapsedStates = new(); @@ -205,9 +91,7 @@ internal static class MetaPanel // reusing stale ones built from a prior Payload. public Dictionary<string, Panel> GroupRowCache = new(); public string LastSig = "init_sig"; // content signature of the last Rebuild - // UI deep-dive Roadmap #4 (2026-07-02): one-shot reconcile timer for - // the optimistic-local-mutation pattern — see ScheduleReconcile. - public DispatcherTimer? ReconcileTimer; + public long SeenVersion = -1; // hub snapshot version last taken // Roadmap #5 (2026-07-02): live references to the bottom-bar state // button and the file-picker button, so the poll timer can update // their displayed text in place once CurrentState/CurrentMetaPath @@ -217,37 +101,11 @@ internal static class MetaPanel public Button? FileBtnRef; } - // Roadmap #4 (2026-07-02): enable/move/duplicate/delete used to be pure - // fire-and-forget Send() calls with no local mutation — the row buttons - // stayed dead until the next 2s poll rebuilt the list from the plugin's - // authoritative state. Two problems: (1) up to 2s of "did my click even - // register?" with no feedback, and (2) capturedGlobalIdx is captured at - // RENDER time — a second click on a stale row (e.g. rapid double-delete - // before the poll catches up) sends an index that no longer matches - // what the plugin thinks is at that position once the first command - // has already shifted subsequent rows, deleting/moving/toggling the - // WRONG rule. Fix: apply the same mutation locally to ps.Data.Rules - // immediately (so capturedGlobalIdx stays valid for anything queued - // behind it in the SAME rebuild), rebuild once (user-initiated, so a - // single rebuild here is acceptable — this isn't the poll-driven flash - // path), then reconcile with the plugin's authoritative state ~250ms - // later in case the local guess and the plugin's actual result diverged - // (e.g. a command that failed server-side). - private static void ScheduleReconcile(PanelState ps, Action rebuild) - { - ps.ReconcileTimer?.Stop(); - var t = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) }; - t.Tick += (_, _) => - { - t.Stop(); - if (!TryFetch(out var fresh)) return; - ps.Data = fresh; - ps.LastSig = PayloadSig(fresh); - rebuild(); - }; - ps.ReconcileTimer = t; - t.Start(); - } + // Roadmap #4 (2026-07-02): enable/move/duplicate/delete apply the same + // change locally to ps.Data.Rules right away (instant feedback, and a + // second click on a stale row can't hit the wrong index), then the hub's + // next snapshot, taken after the plugin applied the command, replaces the + // local guess (MetaCommands defers the refresh past the plugin tick). // Cheap content signature — everything the list view shows EXCEPT the // per-tick LastFiredMs (excluded so an idle/botting panel stops flashing; @@ -357,7 +215,6 @@ internal static class MetaPanel public static Control Create() { - TryBind(); var ps = new PanelState(); var root = new Border @@ -401,13 +258,20 @@ internal static class MetaPanel } } - var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) }; + // Polls the hub's snapshot (fetched every 2 s while subscribed, and + // right after each command). + var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) }; timer.Tick += (_, _) => { - if (_getMetaJson == null) TryBind(); + var snap = UiSources.Meta.Current; + if (snap != null && snap.Version != ps.SeenVersion) + CheckApplyResult(ps, snap.Value); + UpdateSourceMsg(ps); if (picker.ActivePicker != null) return; if (ps.Mode == ViewMode.Editor) return; // don't clobber in-progress edits - if (!TryFetch(out var fresh)) return; + if (snap == null || snap.Version == ps.SeenVersion) return; + ps.SeenVersion = snap.Version; + var fresh = snap.Value.Clone(); ps.Data = fresh; // keep click-handlers on fresh data even if we skip the redraw if (ps.Mode == ViewMode.Source && string.IsNullOrEmpty(ps.SourceText)) ps.SourceText = fresh.SourceText; @@ -417,16 +281,7 @@ internal static class MetaPanel // controls in place, every poll, regardless of whether the sig // changed — property sets only, no layout churn, no rebuild. if (ps.StateBtnRef != null) ps.StateBtnRef.Content = fresh.CurrentState; - if (ps.FileBtnRef != null) - { - string display = "-- None --"; - if (!string.IsNullOrEmpty(fresh.CurrentMetaPath) && fresh.Files.Count > 1) - { - var match = fresh.Files.FirstOrDefault(f => string.Equals(f.Path, fresh.CurrentMetaPath, StringComparison.OrdinalIgnoreCase)); - if (match != null) display = match.Display; - } - ps.FileBtnRef.Content = display; - } + if (ps.FileBtnRef != null) ps.FileBtnRef.Content = MetaVocabulary.CurrentFileDisplay(fresh); string sig = PayloadSig(fresh); if (sig == ps.LastSig) return; // nothing visible changed → no rebuild → no flash ps.LastSig = sig; @@ -447,13 +302,28 @@ internal static class MetaPanel if (ps.Mode != ViewMode.List) return; Rebuild(); }; - timer.Start(); // Stop with the visual tree — a running DispatcherTimer roots the closed // view forever (one immortal poller per open/close). RadarPanel idiom; // must restart on attach: drag/resize fires Detached→Attached. - root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); }; - root.DetachedFromVisualTree += (_, _) => timer.Stop(); + root.AttachedToVisualTree += (_, _) => + { + UiSources.Meta.Subscribe(); + UiSources.Meta.RequestRefresh(); + if (!timer.IsEnabled) timer.Start(); + }; + root.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.Meta.Unsubscribe(); + }; + var first = UiSources.Meta.Current; + if (first != null) + { + ps.SeenVersion = first.Version; + ps.Data = first.Value.Clone(); + ps.LastSig = PayloadSig(ps.Data); + } Rebuild(); return root; } @@ -661,7 +531,6 @@ internal static class MetaPanel if (capturedGlobalIdx >= 0 && capturedGlobalIdx < ps.Data.Rules.Count) ps.Data.Rules[capturedGlobalIdx].Enabled = newEnabled; rebuild(); - ScheduleReconcile(ps, rebuild); }; Grid.SetColumn(enBtn, 0); row.Children.Add(enBtn); @@ -717,7 +586,6 @@ internal static class MetaPanel (ps.Data.Rules[otherGlobalIdx], ps.Data.Rules[capturedGlobalIdx]); } rebuild(); - ScheduleReconcile(ps, rebuild); }; Grid.SetColumn(upBtn, 2); row.Children.Add(upBtn); @@ -746,7 +614,6 @@ internal static class MetaPanel (ps.Data.Rules[otherGlobalIdx], ps.Data.Rules[capturedGlobalIdx]); } rebuild(); - ScheduleReconcile(ps, rebuild); }; Grid.SetColumn(dnBtn, 3); row.Children.Add(dnBtn); @@ -772,7 +639,6 @@ internal static class MetaPanel int insertAt = Math.Clamp(capturedGlobalIdx + 1, 0, ps.Data.Rules.Count); ps.Data.Rules.Insert(insertAt, CloneRule(rule)); rebuild(); - ScheduleReconcile(ps, rebuild); }; Grid.SetColumn(dupBtn, 4); row.Children.Add(dupBtn); @@ -800,7 +666,6 @@ internal static class MetaPanel if (capturedGlobalIdx >= 0 && capturedGlobalIdx < ps.Data.Rules.Count) ps.Data.Rules.RemoveAt(capturedGlobalIdx); rebuild(); - ScheduleReconcile(ps, rebuild); }; Grid.SetColumn(delBtn, 5); row.Children.Add(delBtn); @@ -956,7 +821,7 @@ internal static class MetaPanel string n = ps.SaveName.Trim(); if (!string.IsNullOrEmpty(n)) { - string path = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, "MetaFiles", $"{n}.af"); + string path = System.IO.Path.Combine(MetaVocabulary.MetaFolder, n + ".af"); Send(new MetaCmd { Op = "save_file", Path = path }); } ps.ShowSaveInput = false; @@ -977,13 +842,7 @@ internal static class MetaPanel var bar = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto,Auto") }; // File picker button - string currentDisplay = string.Empty; - if (!string.IsNullOrEmpty(d.CurrentMetaPath) && d.Files.Count > 1) - { - var match = d.Files.FirstOrDefault(f => string.Equals(f.Path, d.CurrentMetaPath, StringComparison.OrdinalIgnoreCase)); - if (match != null) currentDisplay = match.Display; - } - var fileBtn = MakePickerBtn(string.IsNullOrEmpty(currentDisplay) ? "-- None --" : currentDisplay); + var fileBtn = MakePickerBtn(MetaVocabulary.CurrentFileDisplay(d)); fileBtn.Click += (_, _) => { var items = ps.Data.Files.Select(f => f.Display).ToArray(); @@ -1001,10 +860,7 @@ internal static class MetaPanel var refreshBtn = MakeSmallBtn("↺"); ToolTip.SetTip(refreshBtn, "Refresh file list"); - refreshBtn.Click += (_, _) => - { - if (TryFetch(out var fresh)) { ps.Data = fresh; rebuild(); } - }; + refreshBtn.Click += (_, _) => UiSources.Meta.RequestRefresh(); // the timer rebuilds on the new snapshot Grid.SetColumn(refreshBtn, 1); bar.Children.Add(refreshBtn); @@ -1263,7 +1119,7 @@ internal static class MetaPanel var subRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,Auto"), Margin = new Thickness(0, 1, 0, 0) }; - var typeBtn = MakePickerBtn(sub.Condition < names.Length ? names[isAction ? sub.Action : sub.Condition] : "?"); + var typeBtn = MakePickerBtn(isAction ? MetaVocabulary.ActionName(sub.Action) : MetaVocabulary.ConditionName(sub.Condition)); typeBtn.FontSize = 9; typeBtn.Height = 20; typeBtn.Click += (_, _) => @@ -1370,13 +1226,9 @@ internal static class MetaPanel content.Children.Add(new Border { Height = 1, Background = ColBtnBord }); - if (!string.IsNullOrEmpty(ps.SourceMsg) && (DateTime.Now - ps.SourceMsgTime).TotalSeconds < 5) - { - content.Children.Add(new TextBlock - { - Text = ps.SourceMsg, Foreground = ColGreen, FontSize = 10, - }); - } + ps.SourceMsgRef = new TextBlock { FontSize = 10, TextWrapping = TextWrapping.Wrap }; + content.Children.Add(ps.SourceMsgRef); + UpdateSourceMsg(ps); var sourceEditor = MetaSourceEditor.Create( getText: () => ps.SourceText, @@ -1397,10 +1249,10 @@ internal static class MetaPanel }; applyBtn.Click += (_, _) => { + ps.ApplySeqBefore = UiSources.Meta.Current?.Value.ApplyResult?.Seq ?? -1; + ps.ApplySentAt = DateTime.Now; Send(new MetaCmd { Op = "set_source", Text = ps.SourceText }); - ps.SourceMsg = "Applied."; - ps.SourceMsgTime = DateTime.Now; - rebuild(); + SetSourceMsg(ps, "Applying…", ok: true); }; btnRow.Children.Add(applyBtn); @@ -1510,85 +1362,48 @@ internal static class MetaPanel return combined; } - private static MetaRuleDto CloneRule(MetaRuleDto src) - { - var r = new MetaRuleDto - { - State = src.State, Condition = src.Condition, - ConditionData = src.ConditionData, Action = src.Action, - ActionData = src.ActionData, LastFiredMs = src.LastFiredMs, - Enabled = src.Enabled, - }; - foreach (var c in src.Children) r.Children.Add(CloneRule(c)); - foreach (var a in src.ActionChildren) r.ActionChildren.Add(CloneRule(a)); - return r; - } + private static MetaRuleDto CloneRule(MetaRuleDto src) => src.Clone(); // ========================================================================= - // Plugin bridge + // Source Apply result // ========================================================================= - // RL loads fresh plugin copies without unloading the old ones: drop the - // exports bound below so the next poll re-binds to the live copy. - static MetaPanel() => PluginManager.PluginsUnloaded += () => + private static void SetSourceMsg(PanelState ps, string text, bool ok) { - _getMetaJson = null; - _sendMetaCommand = null; - }; + ps.SourceMsg = text; + ps.SourceMsgOk = ok; + ps.SourceMsgTime = DateTime.Now; + UpdateSourceMsg(ps); + } - private static void TryBind() + /// <summary>A snapshot whose ApplyResult is newer than the pending Apply is its result.</summary> + private static void CheckApplyResult(PanelState ps, Payload fresh) { - var plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - if (_getMetaJson == null) + if (ps.ApplySeqBefore == -2) return; + MetaApplyResult? r = fresh.ApplyResult; + if (r != null && r.Seq > ps.ApplySeqBefore) { - IntPtr p1 = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetMetaJson"); - if (p1 != IntPtr.Zero) - _getMetaJson = Marshal.GetDelegateForFunctionPointer<GetMetaJsonFn>(p1); - } - if (_sendMetaCommand == null) - { - IntPtr p2 = GetProcAddress(plugin.ModuleHandle, "RynthPluginSendMetaCommand"); - if (p2 != IntPtr.Zero) - _sendMetaCommand = Marshal.GetDelegateForFunctionPointer<SendMetaCommandFn>(p2); + ps.ApplySeqBefore = -2; + SetSourceMsg(ps, r.Text, r.Ok); } } - private static bool TryFetch(out Payload payload) + /// <summary>Shows the message for 8 s; a plugin that doesn't report results gets a pointer to chat.</summary> + private static void UpdateSourceMsg(PanelState ps) { - payload = new Payload(); - if (_getMetaJson == null) return false; - try + if (ps.ApplySeqBefore != -2 && (DateTime.Now - ps.ApplySentAt).TotalSeconds > 3) { - IntPtr ptr = _getMetaJson(); - if (ptr == IntPtr.Zero) return false; - string? json = Marshal.PtrToStringAnsi(ptr); - if (string.IsNullOrEmpty(json)) return false; - var parsed = JsonSerializer.Deserialize(json, MetaPanelJsonContext.Default.Payload); - if (parsed == null) return false; - payload = parsed; - return true; + ps.ApplySeqBefore = -2; + SetSourceMsg(ps, "Sent. This RynthAi version reports the result in chat.", ok: true); + return; } - catch { return false; } + if (ps.SourceMsgRef == null) return; + bool show = ps.SourceMsg.Length > 0 && (ps.ApplySeqBefore != -2 || (DateTime.Now - ps.SourceMsgTime).TotalSeconds < 8); + ps.SourceMsgRef.IsVisible = show; + if (!show) return; + ps.SourceMsgRef.Text = ps.SourceMsg; + ps.SourceMsgRef.Foreground = ps.SourceMsgOk ? ColGreen : ColRed; } - private static void Send(MetaCmd cmd) - { - if (_sendMetaCommand == null) TryBind(); - if (_sendMetaCommand == null) return; - IntPtr ansi = IntPtr.Zero; - try - { - string json = JsonSerializer.Serialize(cmd, MetaPanelJsonContext.Default.MetaCmd); - ansi = Marshal.StringToHGlobalAnsi(json); - _sendMetaCommand(ansi); - } - catch { } - finally - { - if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi); - } - } + private static void Send(MetaCmd cmd) => MetaCommands.Send(cmd); } diff --git a/src/RynthCore.Engine/UI/Panels/MetaSourceEditor.cs b/src/RynthCore.Engine/UI/Panels/MetaSourceEditor.cs index 8d277dc..67e35b0 100644 --- a/src/RynthCore.Engine/UI/Panels/MetaSourceEditor.cs +++ b/src/RynthCore.Engine/UI/Panels/MetaSourceEditor.cs @@ -19,41 +19,18 @@ using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using RynthCore.Engine.ImGuiBackend; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; internal static class MetaSourceEditor { // ── .af vocabulary (mirrors MetaSchema in RynthSuite plugin) ────────────── - // Top-level structural keywords. - private static readonly HashSet<string> StructKeywords = new(StringComparer.OrdinalIgnoreCase) - { - "STATE", "IF", "DO", "NAV", - }; - - // Condition keywords as they appear in .af source (keyword form, not labels). - internal static readonly string[] ConditionKeywords = - { - "Never", "Always", "All", "Any", "ChatMatch", "MainSlotsLE", - "SecsInStateGE", "Death", "VendorOpen", "VendorClosed", - "ItemCountLE", "ItemCountGE", - "MobsInDist_Name", "MobsInDist_Priority", - "NeedToBuff", "NoMobsInDist", "BlockE", "CellE", - "IntoPortal", "ExitPortal", "Not", - "PSecsInStateGE", "SecsOnSpellGE", "SecsOnSpellLE", - "BuPercentGE", "DistToRteGE", "Expr", - "ChatCapture", "NavEmpty", - "MainHealthLE", "MainHealthPHE", "MainManaLE", "MainManaPHE", - "MainStamLE", "VitaePHE", - }; - - internal static readonly string[] ActionKeywords = - { - "None", "Chat", "SetState", "EmbedNav", "DoAll", - "CallState", "Return", "DoExpr", "ChatExpr", - "SetWatchdog", "ClearWatchdog", "GetOpt", "SetOpt", - "CreateView", "DestroyView", "DestroyAllViews", - }; + // The keyword lists live in UI/Data/MetaData.cs (MetaVocabulary), shared + // with the ImGui face's editor. + private static readonly HashSet<string> StructKeywords = new(MetaVocabulary.StructKeywords, StringComparer.OrdinalIgnoreCase); + internal static readonly string[] ConditionKeywords = MetaVocabulary.ConditionKeywords; + internal static readonly string[] ActionKeywords = MetaVocabulary.ActionKeywords; private static readonly HashSet<string> CondSet = new(ConditionKeywords, StringComparer.OrdinalIgnoreCase); private static readonly HashSet<string> ActSet = new(ActionKeywords, StringComparer.OrdinalIgnoreCase); diff --git a/src/RynthCore.Engine/UI/Panels/MonsterDamagePanel.cs b/src/RynthCore.Engine/UI/Panels/MonsterDamagePanel.cs index 71d6bf2..31f29fd 100644 --- a/src/RynthCore.Engine/UI/Panels/MonsterDamagePanel.cs +++ b/src/RynthCore.Engine/UI/Panels/MonsterDamagePanel.cs @@ -1,14 +1,18 @@ // ============================================================================ // RynthCore.Engine — UI/Panels/MonsterDamagePanel.cs // Interactive table of the RynthAi plugin's learned per-monster combat data. -// Bridge exports (polled every 500ms): +// Data comes through UiDataHub (UI/Data/DamageData.cs: UiSources.Damage and +// UiSources.MonsterRules, DamageCommands), which calls these plugin exports +// on the pump thread; the ImGui face (ImGui/Panels/DamageFace.cs) shares it: // RynthPluginGetMonsterDamageJson() → JSON rows (STABLE order) // RynthPluginSetMonsterHp(wcid, hp) → manual HP override // RynthPluginDeleteMonsterRow(key) → delete one learned row // RynthPluginGetCombatWeaponsJson() → selectable weapons [{id,name}] // RynthPluginSetMonsterWeapon(wcid, wid) → per-monster weapon override (0 = Auto/best) // RynthPluginSetMonsterOffhand(wcid, oid) → per-monster offhand override (0 = none; stored only) -// Columns: WCID | Monster | Elem | Tier | HP(edit) | Crit | NonCrit | Casts/Kill | Kills | Weapon | Offhand | ✕ +// RynthPluginGetPetChoicesJson / RynthPluginSetMonsterPet(wcid, choice) → per-monster pet +// ("" = Auto by weakest element, "E:<element>", "I:<essence id>") +// Columns: WCID | Monster | Elem | Tier | HP(edit) | Crit | NonCrit | Casts/Kill | Kills | Weapon | Offhand | Pet | ✕ // Weapon is per-MONSTER (wcid): it defaults to the learned-best ("Auto") and the // same value shows on every row of that monster; picking pins an override (gold). // Rows update IN PLACE (cells only) — the row Grids + HP TextBoxes are never @@ -31,81 +35,15 @@ using Avalonia.Media; using Avalonia.Threading; using RynthCore.Engine.ImGuiBackend; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; internal static class MonsterDamagePanel { - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetJsonFn(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetHpFn(uint wcid, int hp); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int DelRowFn(IntPtr keyAnsi); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetU2Fn(uint wcid, uint id); // weapon/offhand override - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetU1Fn(uint id); // default weapon (one arg) - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetJsonFn(IntPtr ansiJson); // monsters rules write-back - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void VoidFn(); // parameterless action (clear stats) - - private static GetJsonFn? _getJson; - private static SetHpFn? _setHp; - private static DelRowFn? _delRow; - private static GetJsonFn? _getWeapons; // RynthPluginGetCombatWeaponsJson - private static SetU2Fn? _setWeapon; // RynthPluginSetMonsterWeapon - private static SetU2Fn? _setOffhand; // RynthPluginSetMonsterOffhand - private static SetU1Fn? _setDefaultWeapon; // RynthPluginSetDefaultWeapon (sweeping default) - private static GetJsonFn? _getMonsters; // RynthPluginGetMonstersJson (per-monster debuff/shape rules) - private static SetJsonFn? _setMonsters; // RynthPluginSetMonstersJson (write-back, whole rules array) - private static VoidFn? _clearStats; // RynthPluginClearMonsterStats (master reset) - - // RL loads fresh plugin copies without unloading the old ones: drop the - // exports bound below so the next poll re-binds to the live copy. - static MonsterDamagePanel() => PluginManager.PluginsUnloaded += () => - { - _getJson = null; - _setHp = null; - _delRow = null; - _getWeapons = null; - _setWeapon = null; - _setOffhand = null; - _getMonsters = null; - _setMonsters = null; - _clearStats = null; - _setDefaultWeapon = null; - }; - - private static void TryBind() - { - if (_getJson != null) return; - LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - IntPtr a = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetMonsterDamageJson"); - IntPtr b = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetMonsterHp"); - IntPtr c = GetProcAddress(plugin.ModuleHandle, "RynthPluginDeleteMonsterRow"); - IntPtr d = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetCombatWeaponsJson"); - IntPtr e = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetMonsterWeapon"); - IntPtr f = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetMonsterOffhand"); - IntPtr g = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetMonstersJson"); - IntPtr h = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetMonstersJson"); - IntPtr i = GetProcAddress(plugin.ModuleHandle, "RynthPluginClearMonsterStats"); - IntPtr j = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetDefaultWeapon"); - if (a != IntPtr.Zero) _getJson = Marshal.GetDelegateForFunctionPointer<GetJsonFn>(a); - if (b != IntPtr.Zero) _setHp = Marshal.GetDelegateForFunctionPointer<SetHpFn>(b); - if (c != IntPtr.Zero) _delRow = Marshal.GetDelegateForFunctionPointer<DelRowFn>(c); - if (d != IntPtr.Zero) _getWeapons = Marshal.GetDelegateForFunctionPointer<GetJsonFn>(d); - if (e != IntPtr.Zero) _setWeapon = Marshal.GetDelegateForFunctionPointer<SetU2Fn>(e); - if (f != IntPtr.Zero) _setOffhand = Marshal.GetDelegateForFunctionPointer<SetU2Fn>(f); - if (g != IntPtr.Zero) _getMonsters = Marshal.GetDelegateForFunctionPointer<GetJsonFn>(g); - if (h != IntPtr.Zero) _setMonsters = Marshal.GetDelegateForFunctionPointer<SetJsonFn>(h); - if (i != IntPtr.Zero) _clearStats = Marshal.GetDelegateForFunctionPointer<VoidFn>(i); - if (j != IntPtr.Zero) _setDefaultWeapon = Marshal.GetDelegateForFunctionPointer<SetU1Fn>(j); - } - internal static Control Create() => new View().Root; - private const string Cols = "60,156,54,36,80,56,60,68,48,120,110,26"; + private const string Cols = "60,156,54,36,80,56,60,68,48,120,110,120,26"; private static readonly IBrush HeaderBg = new SolidColorBrush(Color.FromArgb(0xFF, 0x12, 0x1C, 0x26)); private static readonly IBrush PanelBg = new SolidColorBrush(Color.FromArgb(0xF0, 0x08, 0x10, 0x18)); @@ -128,47 +66,9 @@ internal static class MonsterDamagePanel // MonstersPanel.Rule.GetToggle/SetToggle; combat consumes them via BuildDebuffList / // the UseArc/Bolt/Ring/Streak shape gate — so this drawer is just an editor of the // existing name-keyed rule (no combat/storage changes). - private static readonly (string Field, string Label, string Tip)[] DebuffDefs = - { - ("Imperil", "Imperil", "Imperil (Gossamer Flesh / Imperil Other)"), - ("Vuln", "Vuln", "Vulnerability (element-matched)"), - ("Fester", "Fester", "Fester (Decrepitude's Grasp / Fester Other)"), - ("Yield", "Yield", "Yield (Magic Yield Other)"), - ("Broadside", "Broadside","Broadside (Missile Weapons Ineptitude)"), - ("GravityWell", "Gravity", "Gravity Well (Vulnerability Other)"), - }; - private static readonly (string Field, string Label, string Tip)[] ShapeDefs = - { - ("UseArc", "Arc", "Arc spells"), - ("UseBolt", "Bolt", "Bolt spells (default)"), - ("UseRing", "Ring", "Ring spells"), - ("UseStreak", "Streak", "Streak spells"), - }; - private static readonly string[] ExVulnTypes = - { "None", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; - private static bool IsShape(string f) => f is "UseArc" or "UseBolt" or "UseRing" or "UseStreak"; - private static bool NoShapeOn(MonstersPanel.Rule r) => !r.UseArc && !r.UseBolt && !r.UseRing && !r.UseStreak; - - private sealed class Row - { - public uint Wcid; public string Name = ""; public uint Wid; public string Weapon = ""; - public string Elem = ""; public int Tier; public int Hp; public bool HpManual; - public double Crit; public int CritN; public double NonCrit; public int NonCritN; - public double Casts; public int Kills; public string Key = ""; - // Per-monster (wcid) weapon picker state (same on every row of a wcid). - public uint AssignedWid; public string AssignedWeapon = ""; // user override (0 = none) - public uint BestWid; public string BestWeapon = ""; // learned recommendation (0 = none yet) - public uint AssignedOff; public string AssignedOffName = ""; // offhand override (stored only) - public List<TierStat> Tiers = new(); // per-tier breakdown for the expand drawer - public bool IsDefault; // the synthetic top "Default" line (wcid 0) - } - - private sealed class TierStat - { - public int Tier; public string Elem = ""; public string Weapon = ""; - public double Crit; public int CritN; public double NonCrit; public int NonCritN; - public double Casts; public int Kills; - } + private static (string Field, string Label, string Tip)[] DebuffDefs => DamageCommands.DebuffDefs; + private static (string Field, string Label, string Tip)[] ShapeDefs => DamageCommands.ShapeDefs; + private static string[] ExVulnTypes => DamageCommands.ExVulnTypes; private sealed class RowWidgets { @@ -178,9 +78,9 @@ internal static class MonsterDamagePanel public TextBox Hp = null!; public Button HpManualToggle = null!; // "M": on = manual HP entry, off = auto public Button DefaultToggle = null!; // "D": on = this monster follows Default (debuffs/shapes/weapon) - public Button Weapon = null!, Offhand = null!; + public Button Weapon = null!, Offhand = null!, Pet = null!; public Button Chevron = null!; // toggles the per-monster debuff drawer - public Row Data = null!; // latest row data (so picker click handlers read current best/override) + public DamageRow Data = null!; // latest row data (so picker click handlers read current best/override) } private sealed class View @@ -202,14 +102,13 @@ internal static class MonsterDamagePanel private uint _filterWid; // 0 = all weapons private string _filterName = "All weapons"; private string _filterText = ""; // monster name / wcid search (case-insensitive) - private string _lastJson = ""; + private long _seenVersion = -1, _seenRulesVersion = -1; private bool _editing; // an HP box is focused → defer structural rebuilds - private List<Row> _data = new(); - private readonly List<(uint Wid, string Name)> _weapons = new(); - private readonly List<(uint Id, string Name)> _items = new(); // selectable weapons (from plugin ItemRules) - private string _lastWeaponsJson = ""; - private MonstersPanel.Payload _monsters = new(); // name-keyed debuff/shape rules (for the drawer) - private string _lastMonstersJson = ""; + private List<DamageRow> _data = new(); + private List<(uint Id, string Name)> _weapons = new(); // learned weapons (filter) + private List<(uint Id, string Name)> _choices = new(); // per-row weapon picker list + private List<(string Key, string Name)> _pets = new(); + private MonsterRulesSnapshot? _rules; // name-keyed debuff/shape rules (drawer) private uint _expandedWcid; // monster (wcid) whose drawer is open (0 = none) private bool _defaultExpanded; // the top Default line's drawer is open @@ -310,80 +209,59 @@ internal static class MonsterDamagePanel rootGrid.Children.Add(_pickerCanvas); Root = rootGrid; - TryBind(); - var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) }; + // Reads the hub's snapshots (fetched every 500 ms / 1 s while + // subscribed, and right after each command). + var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) }; timer.Tick += (_, _) => Poll(); - timer.Start(); // Stop with the visual tree (RadarPanel idiom): a running - // DispatcherTimer roots the closed panel view forever — every - // open/close otherwise adds another immortal poller hitting the - // plugin C exports against a detached tree. - rootGrid.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); }; - rootGrid.DetachedFromVisualTree += (_, _) => timer.Stop(); + // DispatcherTimer roots the closed panel view forever. + rootGrid.AttachedToVisualTree += (_, _) => + { + UiSources.Damage.Subscribe(); + UiSources.MonsterRules.Subscribe(); + UiSources.Damage.RequestRefresh(); + UiSources.MonsterRules.RequestRefresh(); + if (!timer.IsEnabled) timer.Start(); + }; + rootGrid.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.Damage.Unsubscribe(); + UiSources.MonsterRules.Unsubscribe(); + }; Poll(); } private void Poll() { - if (_getJson == null) { TryBind(); if (_getJson == null) { _status.Text = "Waiting for RynthAi plugin…"; return; } } + var rules = UiSources.MonsterRules.Current; + bool rulesChanged = rules != null && rules.Version != _seenRulesVersion; + if (rulesChanged) + { + _seenRulesVersion = rules!.Version; + _rules = rules.Value; + } - RefreshItems(); - RefreshMonsters(); - - IntPtr ptr; - try { ptr = _getJson(); } catch { return; } - if (ptr == IntPtr.Zero) return; - string json = Marshal.PtrToStringAnsi(ptr) ?? "[]"; - if (json == _lastJson) return; - _lastJson = json; - - _data = Parse(json); + var snap = UiSources.Damage.Current; + if (snap == null) { _status.Text = "Binding to RynthAi…"; return; } + if (!snap.Value.Bound) { _status.Text = "Waiting for RynthAi plugin…"; return; } + if (snap.Version == _seenVersion) + { + if (rulesChanged) RebuildDrawer(); // drawer + chevron/D colours follow the rules + return; + } + _seenVersion = snap.Version; + _data = snap.Value.Rows; + _weapons = snap.Value.LearnedWeapons; + _choices = snap.Value.WeaponChoices; + _pets = snap.Value.PetChoices; UpdateWeapons(); - Reconcile(); - } - - // Refresh the selectable-weapons list (configured ItemRules) shown in the row pickers. - private void RefreshItems() - { - if (_getWeapons == null) return; - IntPtr p; - try { p = _getWeapons(); } catch { return; } - if (p == IntPtr.Zero) return; - string json = Marshal.PtrToStringAnsi(p) ?? "[]"; - if (json == _lastWeaponsJson) return; - _lastWeaponsJson = json; - _items.Clear(); - try - { - using var doc = JsonDocument.Parse(json); - foreach (var e in doc.RootElement.EnumerateArray()) - _items.Add(((uint)e.GetProperty("id").GetInt64(), e.GetProperty("name").GetString() ?? "")); - } - catch { } - } - - // Refresh the name-keyed debuff/shape rules (shared with the Monsters tab) used by - // the per-monster drawer. Reuses MonstersPanel's payload type + JSON context. - private void RefreshMonsters() - { - if (_getMonsters == null) return; - IntPtr p; - try { p = _getMonsters(); } catch { return; } - if (p == IntPtr.Zero) return; - string json = Marshal.PtrToStringAnsi(p) ?? ""; - if (json.Length == 0 || json == _lastMonstersJson) return; - _lastMonstersJson = json; - try - { - var parsed = JsonSerializer.Deserialize(json, MonstersPanelJsonContext.Default.Payload); - if (parsed != null) _monsters = parsed; - } - catch { } + if (rulesChanged) RebuildDrawer(); else Reconcile(); } private void Reconcile() { - List<Row> filtered = ApplyFilters(); + List<DamageRow> filtered = ApplyFilters(); var newKeys = filtered.Select(r => r.Key).ToList(); bool structural = !newKeys.SequenceEqual(_displayedKeys); @@ -434,9 +312,9 @@ internal static class MonsterDamagePanel } // Weapon filter (dropdown) AND monster search (name substring or wcid) combined. - private List<Row> ApplyFilters() + private List<DamageRow> ApplyFilters() { - IEnumerable<Row> q = _data; + IEnumerable<DamageRow> q = _data; // The Default line is always kept (pinned at top), exempt from filters. if (_filterWid != 0) q = q.Where(r => r.IsDefault || r.Wid == _filterWid); @@ -447,75 +325,9 @@ internal static class MonsterDamagePanel return q.ToList(); } - private static List<Row> Parse(string json) - { - var list = new List<Row>(); - try - { - using var doc = JsonDocument.Parse(json); - foreach (var e in doc.RootElement.EnumerateArray()) - { - var row = new Row - { - Wcid = (uint)e.GetProperty("wcid").GetInt64(), - Name = e.GetProperty("name").GetString() ?? "", - Wid = (uint)e.GetProperty("wid").GetInt64(), - Weapon = e.GetProperty("weapon").GetString() ?? "", - Elem = e.GetProperty("elem").GetString() ?? "", - Tier = e.GetProperty("tier").GetInt32(), - Hp = e.GetProperty("hp").GetInt32(), - HpManual = e.GetProperty("hpManual").GetBoolean(), - Crit = e.GetProperty("crit").GetDouble(), - CritN = e.GetProperty("critN").GetInt32(), - NonCrit = e.GetProperty("noncrit").GetDouble(), - NonCritN = e.GetProperty("noncritN").GetInt32(), - Casts = e.GetProperty("casts").GetDouble(), - Kills = e.GetProperty("kills").GetInt32(), - Key = e.GetProperty("key").GetString() ?? "", - }; - // New per-monster weapon fields (TryGetProperty so an older plugin - // build that omits them doesn't blank the whole table). - if (e.TryGetProperty("assignedWid", out var aw)) row.AssignedWid = (uint)aw.GetInt64(); - if (e.TryGetProperty("assignedWeapon", out var awn)) row.AssignedWeapon = awn.GetString() ?? ""; - if (e.TryGetProperty("bestWid", out var bw)) row.BestWid = (uint)bw.GetInt64(); - if (e.TryGetProperty("bestWeapon", out var bwn)) row.BestWeapon = bwn.GetString() ?? ""; - if (e.TryGetProperty("assignedOff", out var ao)) row.AssignedOff = (uint)ao.GetInt64(); - if (e.TryGetProperty("assignedOffName", out var aon))row.AssignedOffName = aon.GetString() ?? ""; - if (e.TryGetProperty("isDefault", out var idf)) row.IsDefault = idf.GetBoolean(); - // Per-tier breakdown (for the expand drawer). Optional so an older plugin doesn't break the table. - if (e.TryGetProperty("tiers", out var tarr) && tarr.ValueKind == JsonValueKind.Array) - { - foreach (var te in tarr.EnumerateArray()) - { - row.Tiers.Add(new TierStat - { - Tier = te.GetProperty("tier").GetInt32(), - Elem = te.GetProperty("elem").GetString() ?? "", - Weapon = te.GetProperty("weapon").GetString() ?? "", - Crit = te.GetProperty("crit").GetDouble(), - CritN = te.GetProperty("critN").GetInt32(), - NonCrit = te.GetProperty("noncrit").GetDouble(), - NonCritN = te.GetProperty("noncritN").GetInt32(), - Casts = te.GetProperty("casts").GetDouble(), - Kills = te.GetProperty("kills").GetInt32(), - }); - } - } - list.Add(row); - } - } - catch { } - return list; - } - private void UpdateWeapons() { - _weapons.Clear(); - var seen = new HashSet<uint>(); - foreach (var r in _data) - if (r.Wid != 0 && seen.Add(r.Wid)) _weapons.Add((r.Wid, r.Weapon)); - - if (_filterWid != 0 && !seen.Contains(_filterWid)) { _filterWid = 0; _filterName = "All weapons"; } + if (_filterWid != 0 && !_weapons.Exists(w => w.Id == _filterWid)) { _filterWid = 0; _filterName = "All weapons"; } _filterBtn.Content = "Weapon: " + Trunc(_filterName, 22) + " ▾"; _status.Text = _data.Count == 0 ? "No kills recorded yet." : $"{_data.Count} rows · {_weapons.Count} weapon(s)"; } @@ -586,11 +398,11 @@ internal static class MonsterDamagePanel private void ShowWeaponPicker() { var items = new List<(uint Id, string Name)>(_weapons.Count + 1) { (0u, "All weapons") }; - foreach (var w in _weapons) items.Add((w.Wid, w.Name)); + foreach (var w in _weapons) items.Add((w.Id, w.Name)); ShowPicker(_filterBtn, items, _filterWid, id => { _filterWid = id; - var match = _weapons.FirstOrDefault(w => w.Wid == id); + var match = _weapons.FirstOrDefault(w => w.Id == id); _filterName = id == 0 ? "All weapons" : (match.Name ?? ("Weapon " + id)); _filterBtn.Content = "Weapon: " + Trunc(_filterName, 22) + " ▾"; _displayedKeys = new List<string> { "\0force" }; // force a structural rebuild for the new filter @@ -598,20 +410,9 @@ internal static class MonsterDamagePanel }); } - // Distinct selectable weapons for the per-row pickers: configured weapons - // (ItemRules, from the plugin) merged with weapons we have learned data for, - // sorted by name. - private List<(uint Id, string Name)> WeaponChoices() - { - var seen = new HashSet<uint>(); - var list = new List<(uint Id, string Name)>(); - foreach (var it in _items) - if (it.Id != 0 && seen.Add(it.Id)) list.Add(it); - foreach (var w in _weapons) - if (w.Wid != 0 && seen.Add(w.Wid)) list.Add((w.Wid, w.Name)); - list.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); - return list; - } + private List<(string Key, string Name)> PetChoices() => _pets; + + private List<(uint Id, string Name)> WeaponChoices() => _choices; private void ClosePicker() { @@ -655,10 +456,8 @@ internal static class MonsterDamagePanel cancel.Click += (_, _) => ClosePicker(); confirm.Click += (_, _) => { - if (_clearStats != null) { try { _clearStats(); } catch { } } + DamageCommands.ClearStats(); ClosePicker(); - _lastJson = ""; // force the next poll to re-read the zeroed stats - Dispatcher.UIThread.Post(Poll); }; var btnRow = new StackPanel { @@ -688,92 +487,11 @@ internal static class MonsterDamagePanel // The drawer edits an EXACT-name rule for the monster: editing while inheriting // clones Default into one (so other config carries over); Reset deletes it. - private MonstersPanel.Rule? FindRule(string name) => - _monsters.Rules?.FirstOrDefault(r => - !r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase) - && r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + private MonstersPanel.Rule? FindRule(string name) => _rules?.FindRule(name); - private bool HasCustomRule(string name) => FindRule(name) != null; + private bool HasCustomRule(string name) => _rules?.HasCustomRule(name) ?? false; - private MonstersPanel.Rule DefaultRule() => - _monsters.Rules?.FirstOrDefault(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)) - ?? new MonstersPanel.Rule { Name = "Default", UseBolt = true }; - - private static MonstersPanel.Rule CloneRule(MonstersPanel.Rule s, string name) => new MonstersPanel.Rule - { - Name = name, - Category = s.Category, - MatchExpression = "", // exact-name rule matches by name, not a (possibly false) expression - Priority = s.Priority, - DamageType = s.DamageType, - WeaponId = s.WeaponId, - OffhandId = s.OffhandId, - ExVuln = s.ExVuln, - PetDamage = s.PetDamage, - Fester = s.Fester, Broadside = s.Broadside, GravityWell = s.GravityWell, - Imperil = s.Imperil, Yield = s.Yield, Vuln = s.Vuln, - UseArc = s.UseArc, UseBolt = s.UseBolt, UseRing = s.UseRing, UseStreak = s.UseStreak, - }; - - // Force a fresh re-read of the rules right before a write. Both panels run on the - // single UI thread, so re-reading here means the drawer builds its edit on the very - // latest plugin state and can't clobber a rule just added on the Monsters tab. - private void RefreshMonstersNow() { _lastMonstersJson = ""; RefreshMonsters(); } - - // Return the editable exact-name rule, creating it (cloned from Default) if the - // monster is currently inheriting. Inserted right after Default so the more-specific - // rule wins GetRuleForTarget's first-substring-match resolution. - private MonstersPanel.Rule EnsureCustomRule(string name) - { - RefreshMonstersNow(); - // The Default line edits the real Default rule in place (not a clone). - if (name.Equals("Default", StringComparison.OrdinalIgnoreCase)) - { - var def = DefaultRule(); - if (_monsters.Rules != null && !_monsters.Rules.Contains(def)) _monsters.Rules.Add(def); - return def; - } - var existing = FindRule(name); - if (existing != null) return existing; - var clone = CloneRule(DefaultRule(), name); - int defIdx = _monsters.Rules.FindIndex(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); - _monsters.Rules.Insert(defIdx >= 0 ? defIdx + 1 : 0, clone); - return clone; - } - - private void ResetRule(string name) - { - RefreshMonstersNow(); - int i = _monsters.Rules.FindIndex(r => - !r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase) - && r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); - if (i < 0) return; - _monsters.Rules.RemoveAt(i); - PushMonsters(); - RebuildDrawer(); - } - - // Whole-rules-array write-back over the existing Monsters bridge (same shape the - // Monsters tab pushes). The plugin's ApplyMonstersJson preserves the Default rule. - private void PushMonsters() - { - if (_setMonsters == null) return; - // Never write back an empty/un-loaded array — that would wipe the user's rules - // (incl. Default) on the plugin side. - if (_monsters?.Rules == null || _monsters.Rules.Count == 0) return; - IntPtr ansi = IntPtr.Zero; - try - { - string json = JsonSerializer.Serialize( - new MonstersPanel.Payload { Rules = _monsters.Rules }, - MonstersPanelJsonContext.Default.Payload); - ansi = Marshal.StringToHGlobalAnsi(json); - _setMonsters(ansi); - } - catch { } - finally { if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi); } - _lastMonstersJson = ""; // re-read the plugin's applied copy on the next poll - } + private MonstersPanel.Rule DefaultRule() => _rules?.DefaultRule() ?? new MonstersPanel.Rule { Name = "Default", UseBolt = true }; private void RebuildDrawer() { @@ -781,7 +499,7 @@ internal static class MonsterDamagePanel Reconcile(); } - private Control BuildDebuffDrawer(Row row) + private Control BuildDebuffDrawer(DamageRow row) { string monsterName = row.Name; var border = new Border @@ -796,7 +514,7 @@ internal static class MonsterDamagePanel border.Child = stack; // Guard: never write back an empty/un-loaded rules array (would clobber Default). - if (_setMonsters == null || _monsters.Rules == null || _monsters.Rules.Count == 0) + if (_rules == null || _rules.Parsed.Rules.Count == 0) { stack.Children.Add(new TextBlock { @@ -831,7 +549,7 @@ internal static class MonsterDamagePanel Background = EntryBg, Foreground = custom ? Brushes.White : Dim, BorderBrush = EntryBorder, BorderThickness = new Thickness(1), IsEnabled = custom, }; - reset.Click += (_, _) => ResetRule(monsterName); + reset.Click += (_, _) => DamageCommands.ResetRule(monsterName); header.Children.Add(reset); stack.Children.Add(header); @@ -866,9 +584,8 @@ internal static class MonsterDamagePanel uint sel = (uint)Math.Max(0, Array.IndexOf(ExVulnTypes, nowEx)); ShowPicker(exBtn, items, sel, id => { - EnsureCustomRule(monsterName).ExVuln = ExVulnTypes[id]; - PushMonsters(); - RebuildDrawer(); + string ex = ExVulnTypes[id]; + DamageCommands.EditRule(monsterName, r => r.ExVuln = ex); }); }; exRow.Children.Add(exBtn); @@ -889,7 +606,7 @@ internal static class MonsterDamagePanel string crit = t.CritN > 0 ? t.Crit.ToString("0", CultureInfo.InvariantCulture) : "—"; string nc = t.NonCritN > 0 ? t.NonCrit.ToString("0", CultureInfo.InvariantCulture) : "—"; string ck = t.Kills > 0 ? t.Casts.ToString("0.00", CultureInfo.InvariantCulture) : "—"; - string line = $"{FormatTier(t.Tier),-4} {(string.IsNullOrEmpty(t.Elem) ? "" : t.Elem),-8} kills {t.Kills,-4} crit {crit,-5} non-crit {nc,-5} casts/kill {ck}"; + string line = $"{DamageSource.FormatTier(t.Tier),-4} {(string.IsNullOrEmpty(t.Elem) ? "" : t.Elem),-8} kills {t.Kills,-4} crit {crit,-5} non-crit {nc,-5} casts/kill {ck}"; stack.Children.Add(new TextBlock { Text = line, FontSize = 11, Foreground = Brushes.White, @@ -923,16 +640,7 @@ internal static class MonsterDamagePanel }, }; ToolTip.SetTip(btn, tip); - btn.Click += (_, _) => - { - var rule = EnsureCustomRule(monsterName); - bool nv = !rule.GetToggle(field); - rule.SetToggle(field, nv); - // Never leave a monster with no offensive shape (combat would refuse to cast). - if (IsShape(field) && !nv && NoShapeOn(rule)) rule.UseBolt = true; - PushMonsters(); - RebuildDrawer(); - }; + btn.Click += (_, _) => DamageCommands.EditRule(monsterName, r => DamageCommands.FlipToggle(r, field)); return btn; } @@ -963,7 +671,8 @@ internal static class MonsterDamagePanel AddCell(g, 8, "Kills", bold: true); AddCell(g, 9, "Weapon", bold: true); AddCell(g, 10, "Offhand", bold: true); - AddCell(g, 11, "", bold: true); + AddCell(g, 11, "Pet", bold: true); + AddCell(g, 12, "", bold: true); return g; } @@ -984,7 +693,7 @@ internal static class MonsterDamagePanel BorderThickness = new Thickness(1), }; - private RowWidgets CreateRow(Row r) + private RowWidgets CreateRow(DamageRow r) { if (r.IsDefault) return CreateDefaultRow(); var g = NewRowGrid(22); @@ -1028,17 +737,12 @@ internal static class MonsterDamagePanel var cur = rw.Data; bool onDefault = !HasCustomRule(cur.Name) && cur.AssignedWid == 0; if (onDefault) - { - EnsureCustomRule(cur.Name); // turn OFF default → give it an editable custom rule - PushMonsters(); - } + DamageCommands.EditRule(cur.Name, static _ => { }); // turn OFF default → an editable custom rule else { - ResetRule(cur.Name); // turn ON default → drop custom rule (PushMonsters inside) - if (_setWeapon != null && cur.Wcid != 0) { try { _setWeapon(cur.Wcid, 0); } catch { } } // weapon → Default + DamageCommands.ResetRule(cur.Name); // turn ON default → drop the custom rule + if (cur.Wcid != 0) DamageCommands.SetWeapon(cur.Wcid, 0); // weapon → Default } - _lastJson = ""; - Dispatcher.UIThread.Post(Poll); }; rw.DefaultToggle = dToggle; @@ -1074,14 +778,10 @@ internal static class MonsterDamagePanel uint wcid = r.Wcid; void CommitHp() { - if (_setHp == null) return; string t = (hp.Text ?? "").Trim(); - if (t.Length == 0) { try { _setHp(wcid, 0); } catch { } _lastJson = ""; return; } + if (t.Length == 0) { DamageCommands.SetHp(wcid, 0); return; } if (int.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) && v > 0) - { - try { _setHp(wcid, v); } catch { } - _lastJson = ""; // force a refresh so the gold "manual" flag shows - } + DamageCommands.SetHp(wcid, v); } hp.GotFocus += (_, _) => { _editing = true; Win32Backend.AvaloniaTextInputActive = true; }; hp.LostFocus += (_, _) => { Win32Backend.AvaloniaTextInputActive = false; _editing = false; CommitHp(); }; @@ -1112,17 +812,13 @@ internal static class MonsterDamagePanel ToolTip.SetTip(mToggle, "Manual max-HP for this monster (off = auto)"); mToggle.Click += (_, _) => { - if (_setHp == null) return; var cur = rw.Data; if (cur.HpManual) - { - try { _setHp(cur.Wcid, 0); } catch { } // manual -> auto - _lastJson = ""; - } + DamageCommands.SetHp(cur.Wcid, 0); // manual -> auto else { // auto -> manual: seed with the known auto HP (if any), then open the box. - if (cur.Hp > 0) { try { _setHp(cur.Wcid, cur.Hp); } catch { } _lastJson = ""; } + if (cur.Hp > 0) DamageCommands.SetHp(cur.Wcid, cur.Hp); rw.Hp.IsReadOnly = false; rw.Hp.Focus(); } @@ -1151,12 +847,7 @@ internal static class MonsterDamagePanel : "Auto (best: —)"; var choices = new List<(uint Id, string Name)> { (0u, bestLabel) }; choices.AddRange(WeaponChoices()); - ShowPicker(weaponBtn, choices, cur.AssignedWid, id => - { - if (_setWeapon != null) { try { _setWeapon(cur.Wcid, id); } catch { } } - _lastJson = ""; - Dispatcher.UIThread.Post(Poll); - }); + ShowPicker(weaponBtn, choices, cur.AssignedWid, id => DamageCommands.SetWeapon(cur.Wcid, id)); }; rw.Weapon = weaponBtn; g.Children.Add(weaponBtn); Grid.SetColumn(weaponBtn, 9); @@ -1169,16 +860,35 @@ internal static class MonsterDamagePanel var cur = rw.Data; var choices = new List<(uint Id, string Name)> { (0u, "(none)") }; choices.AddRange(WeaponChoices()); - ShowPicker(offhandBtn, choices, cur.AssignedOff, id => - { - if (_setOffhand != null) { try { _setOffhand(cur.Wcid, id); } catch { } } - _lastJson = ""; - Dispatcher.UIThread.Post(Poll); - }); + ShowPicker(offhandBtn, choices, cur.AssignedOff, id => DamageCommands.SetOffhand(cur.Wcid, id)); }; rw.Offhand = offhandBtn; g.Children.Add(offhandBtn); Grid.SetColumn(offhandBtn, 10); + // Pet (col 11): which combat pet to summon for this monster. Auto = the + // essence whose element it resists least; or an element; or a specific + // essence from the Items panel. + var petBtn = MakePickerButton(); + ToolTip.SetTip(petBtn, "Pet to summon for this monster. Auto = the essence element it resists least (learned resists); or pick an element or a specific essence from the Items panel."); + petBtn.Click += (_, _) => + { + var cur = rw.Data; + var opts = PetChoices(); + var items = new List<(uint Id, string Name)>(); + uint sel = 0; + for (int pi = 0; pi < opts.Count; pi++) + { + items.Add(((uint)pi, opts[pi].Name)); + if (opts[pi].Key == cur.Pet) sel = (uint)pi; + } + ShowPicker(petBtn, items, sel, idx => + { + if (idx < opts.Count) DamageCommands.SetPet(cur.Wcid, opts[(int)idx].Key); + }); + }; + rw.Pet = petBtn; + g.Children.Add(petBtn); Grid.SetColumn(petBtn, 11); + var del = new Button { Content = "✕", FontSize = 11, Padding = new Thickness(0), @@ -1190,17 +900,8 @@ internal static class MonsterDamagePanel }; ToolTip.SetTip(del, $"Delete learned history for this row (wcid {r.Wcid})."); string key = r.Key; - del.Click += (_, _) => - { - if (_delRow != null && key.Length > 0) - { - IntPtr k = Marshal.StringToHGlobalAnsi(key); - try { _delRow(k); } catch { } finally { Marshal.FreeHGlobal(k); } - } - _lastJson = ""; - Dispatcher.UIThread.Post(Poll); - }; - g.Children.Add(del); Grid.SetColumn(del, 11); + del.Click += (_, _) => DamageCommands.DeleteRow(key); + g.Children.Add(del); Grid.SetColumn(del, 12); rw.Data = r; return rw; @@ -1255,12 +956,7 @@ internal static class MonsterDamagePanel var cur = rw.Data; var choices = new List<(uint Id, string Name)> { (0u, "Auto (learned best)") }; choices.AddRange(WeaponChoices()); - ShowPicker(weaponBtn, choices, cur.AssignedWid, id => - { - if (_setDefaultWeapon != null) { try { _setDefaultWeapon(id); } catch { } } - _lastJson = ""; - Dispatcher.UIThread.Post(Poll); - }); + ShowPicker(weaponBtn, choices, cur.AssignedWid, id => DamageCommands.SetDefaultWeapon(id)); }; rw.Weapon = weaponBtn; g.Children.Add(weaponBtn); Grid.SetColumn(weaponBtn, 9); @@ -1268,7 +964,7 @@ internal static class MonsterDamagePanel return rw; } - private void UpdateRow(RowWidgets rw, Row r) + private void UpdateRow(RowWidgets rw, DamageRow r) { rw.Data = r; // picker click handlers read the latest best/override from here if (r.IsDefault) @@ -1288,7 +984,7 @@ internal static class MonsterDamagePanel rw.Chevron.Content = expanded ? "▾" : "▸"; rw.Chevron.Foreground = HasCustomRule(r.Name) ? ManualHp : Dim; rw.Elem.Text = r.Elem; - rw.Tier.Text = FormatTier(r.Tier); + rw.Tier.Text = DamageSource.FormatTier(r.Tier); rw.Crit.Text = r.CritN > 0 ? r.Crit.ToString("0") : "—"; rw.Crit.Foreground = r.CritN > 0 ? Brushes.White : Dim; rw.NonCrit.Text = r.NonCritN > 0 ? r.NonCrit.ToString("0") : "—"; @@ -1318,6 +1014,12 @@ internal static class MonsterDamagePanel rw.Offhand.Content = "(none)"; rw.Offhand.Foreground = Dim; } + // Pet: gold = chosen element/essence, dim "Auto" otherwise. + if (rw.Pet != null) + { + rw.Pet.Content = Trunc(r.Pet.Length > 0 ? r.PetLabel : "Auto", 16); + rw.Pet.Foreground = r.Pet.Length > 0 ? ManualHp : Dim; + } // Never overwrite the HP box while the user is editing it. if (!rw.Hp.IsFocused) @@ -1337,11 +1039,6 @@ internal static class MonsterDamagePanel rw.DefaultToggle.BorderBrush = onDefault ? ToggleOn : EntryBorder; } - // Tier display: 0 = none ("—"); negative = ring spell ("R<level>"); positive = spell level. - private static string FormatTier(int t) => - t == 0 ? "—" : (t < 0 ? "R" + (-t).ToString(CultureInfo.InvariantCulture) - : t.ToString(CultureInfo.InvariantCulture)); - private static TextBlock AddCell(Grid g, int col, string text, bool bold = false, bool trim = false, IBrush? brush = null) { var tb = new TextBlock diff --git a/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs b/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs index 2735d9d..0443d8d 100644 --- a/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs @@ -9,8 +9,8 @@ // the snapshot. // // Plugin exports used: -// RynthPluginGetMonstersJson → polled every 1s for external edits -// RynthPluginSetMonstersJson → debounced write-back on edit +// RynthPluginGetMonstersJson → UiSources.MonsterRules (hub, pump thread; shared with Damage) +// RynthPluginSetMonstersJson → DamageCommands.SetRulesJson (hub) // ============================================================================ using System; @@ -25,6 +25,7 @@ using Avalonia.Layout; using Avalonia.Media; using Avalonia.Threading; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; @@ -35,16 +36,8 @@ internal partial class MonstersPanelJsonContext : JsonSerializerContext { } internal static class MonstersPanel { - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate IntPtr GetMonstersJsonFn(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void SetMonstersJsonFn(IntPtr ansiJson); - private static GetMonstersJsonFn? _getMonstersJson; - private static SetMonstersJsonFn? _setMonstersJson; private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6)); private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33)); @@ -125,9 +118,13 @@ internal static class MonstersPanel public bool UseRing { get; set; } public bool UseStreak { get; set; } public bool UseBolt { get; set; } = true; + /// <summary>Blast spells (a spread of projectiles). Off in rules saved before 2026-10-03.</summary> + public bool UseBlast { get; set; } public string ExVuln { get; set; } = "None"; public int OffhandId { get; set; } public string PetDamage { get; set; } = "PAuto"; + /// <summary>Debuffs the player typed in, comma separated (spell base or full names).</summary> + public string CustomDebuffs { get; set; } = string.Empty; public bool GetToggle(string field) => field switch { @@ -141,6 +138,7 @@ internal static class MonstersPanel "UseBolt" => UseBolt, "UseRing" => UseRing, "UseStreak" => UseStreak, + "UseBlast" => UseBlast, _ => false, }; @@ -158,6 +156,7 @@ internal static class MonstersPanel case "UseBolt": UseBolt = v; break; case "UseRing": UseRing = v; break; case "UseStreak": UseStreak = v; break; + case "UseBlast": UseBlast = v; break; } } } @@ -175,7 +174,6 @@ internal static class MonstersPanel public static Control Create() { - TryBind(); var state = new State(); @@ -424,7 +422,6 @@ internal static class MonstersPanel var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) }; timer.Tick += (_, _) => { - if (_getMonstersJson == null) TryBind(); if (state.Dirty) return; // don't clobber pending edits if (!TryFetch(out var fresh)) return; @@ -449,8 +446,17 @@ internal static class MonstersPanel // Stop with the visual tree — a running DispatcherTimer roots the closed // view forever (one immortal poller per open/close). RadarPanel idiom; // must restart on attach: drag/resize fires Detached→Attached. - root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); }; - root.DetachedFromVisualTree += (_, _) => timer.Stop(); + root.AttachedToVisualTree += (_, _) => + { + UiSources.MonsterRules.Subscribe(); + UiSources.MonsterRules.RequestRefresh(); + if (!timer.IsEnabled) timer.Start(); + }; + root.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.MonsterRules.Unsubscribe(); + }; return root; } @@ -957,73 +963,28 @@ internal static class MonstersPanel // ── Plugin export binding ─────────────────────────────────────────────── // RL loads fresh plugin copies without unloading the old ones: drop the // exports bound below so the next poll re-binds to the live copy. - static MonstersPanel() => PluginManager.PluginsUnloaded += () => - { - _getMonstersJson = null; - _setMonstersJson = null; - }; - - private static void TryBind() - { - var plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - if (_getMonstersJson == null) - { - IntPtr p1 = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetMonstersJson"); - if (p1 != IntPtr.Zero) - _getMonstersJson = Marshal.GetDelegateForFunctionPointer<GetMonstersJsonFn>(p1); - } - - if (_setMonstersJson == null) - { - IntPtr p2 = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetMonstersJson"); - if (p2 != IntPtr.Zero) - _setMonstersJson = Marshal.GetDelegateForFunctionPointer<SetMonstersJsonFn>(p2); - } - } + // The hub version at the last save: older snapshots predate it and would + // briefly revert the edit on screen, so they're skipped. + private static long _savedAtVersion = -1; + // A private copy of the hub's latest rules (the panel edits it in place). private static bool TryFetch(out Payload payload) { payload = new Payload(); - if (_getMonstersJson == null) return false; - try - { - IntPtr ptr = _getMonstersJson(); - if (ptr == IntPtr.Zero) return false; - string? json = Marshal.PtrToStringAnsi(ptr); - if (string.IsNullOrEmpty(json)) return false; - var parsed = JsonSerializer.Deserialize(json, MonstersPanelJsonContext.Default.Payload); - if (parsed == null) return false; - payload = parsed; - return true; - } - catch - { - return false; - } + var snap = UiSources.MonsterRules.Current; + if (snap == null || snap.Version <= _savedAtVersion) return false; + payload = snap.Value.ParseCopy(); + return true; } private static void PushChanges(State state) { - if (_setMonstersJson == null) TryBind(); - if (_setMonstersJson == null) return; - - IntPtr ansi = IntPtr.Zero; - try - { - // Only the rules array is needed by the setter — avoids round-tripping items list. - string json = JsonSerializer.Serialize(new Payload { Rules = state.Data.Rules }, MonstersPanelJsonContext.Default.Payload); - ansi = Marshal.StringToHGlobalAnsi(json); - _setMonstersJson(ansi); - state.Dirty = false; - } - catch { } - finally - { - if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi); - } + // Only the rules array is needed by the setter; serialized here, on the + // UI thread, because the panel keeps editing state.Data afterwards. + string json = JsonSerializer.Serialize(new Payload { Rules = state.Data.Rules }, MonstersPanelJsonContext.Default.Payload); + _savedAtVersion = UiSources.MonsterRules.Current?.Version ?? _savedAtVersion; + DamageCommands.SetRulesJson(json); + state.Dirty = false; } private static bool CapturedEqual(Dictionary<string, CapturedInfo>? a, Dictionary<string, CapturedInfo>? b) @@ -1056,7 +1017,8 @@ internal static class MonstersPanel || x.Fester != y.Fester || x.Broadside != y.Broadside || x.GravityWell != y.GravityWell || x.Imperil != y.Imperil || x.Yield != y.Yield || x.Vuln != y.Vuln || x.UseArc != y.UseArc || x.UseBolt != y.UseBolt - || x.UseRing != y.UseRing || x.UseStreak != y.UseStreak) + || x.UseRing != y.UseRing || x.UseStreak != y.UseStreak || x.UseBlast != y.UseBlast + || (x.CustomDebuffs ?? "") != (y.CustomDebuffs ?? "")) return false; } return true; diff --git a/src/RynthCore.Engine/UI/Panels/NavPanel.cs b/src/RynthCore.Engine/UI/Panels/NavPanel.cs index b1d9c11..62d46be 100644 --- a/src/RynthCore.Engine/UI/Panels/NavPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/NavPanel.cs @@ -2,9 +2,10 @@ // RynthCore.Engine — UI/Panels/NavPanel.cs // Avalonia replica of LegacyNavigationUi.cs (RynthSuite plugin). // -// Plugin exports used: -// RynthPluginGetNavJson → polled every 1s for live state -// RynthPluginSendNavCommand → dispatched on button actions +// Data goes through UiDataHub (UI/Data/NavData.cs): UiSources.Nav polls +// RynthPluginGetNavJson on the pump thread and NavCommands sends +// RynthPluginSendNavCommand there; the ImGui face (ImGui/Panels/NavFace.cs) +// reads the same snapshot. // ============================================================================ using System; @@ -19,29 +20,13 @@ using Avalonia.Layout; using Avalonia.Media; using Avalonia.Threading; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; +using Payload = RynthCore.Engine.UI.Data.NavPayload; namespace RynthCore.Engine.UI.Panels; -[JsonSerializable(typeof(NavPanel.Payload))] -[JsonSerializable(typeof(NavPanel.NavCmd))] -[JsonSerializable(typeof(List<NavPanel.NavPoint>))] -[JsonSerializable(typeof(List<string>), TypeInfoPropertyName = "StringList")] -[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)] -internal partial class NavPanelJsonContext : JsonSerializerContext { } - internal static class NavPanel { - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate IntPtr GetNavJsonFn(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void SendNavCommandFn(IntPtr ansiJson); - - private static GetNavJsonFn? _getNavJson; - private static SendNavCommandFn? _sendNavCommand; - private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33)); private static readonly IBrush ColGreen = new SolidColorBrush(Color.FromRgb(0x33, 0xCC, 0x66)); private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6)); @@ -56,62 +41,20 @@ internal static class NavPanel private static readonly IBrush ColStartBg = new SolidColorBrush(Color.FromRgb(0x19, 0x61, 0x19)); private static readonly IBrush ColStopBg = new SolidColorBrush(Color.FromRgb(0x80, 0x19, 0x19)); - private static readonly string[] RouteTypes = { "Once", "Circular", "Linear", "Follow" }; - private static readonly string[] AddModes = { "End", "Above", "Below" }; + private static readonly string[] RouteTypes = NavCommands.RouteTypes; + private static readonly string[] AddModes = NavCommands.AddModes; - private static readonly int[] RecallIds = - { - 48, 2645, 2647, - 1635, 1636, - 157, 158, 1637, - 2648, 2649, 2650, - 2931, 2023, 2041, 2358, 2813, 2941, 2943, - 3865, 3929, 3930, 4084, 4198, 4213, - 4907, 4908, 4909, - 5175, 5330, 5541, 6150, 6321, 6322, - }; - - // ── Data types (mirror NavBridgePayload / NavCommand on plugin side) ────── - - internal sealed class NavPoint - { - public int Idx { get; set; } - public string Type { get; set; } = string.Empty; - public string Desc { get; set; } = string.Empty; - public double NS { get; set; } - public double EW { get; set; } - public double Z { get; set; } - } - - internal sealed class Payload - { - public string ActiveNavName { get; set; } = string.Empty; - public string NavStatusLine { get; set; } = string.Empty; - public bool NavIsStuck { get; set; } - public bool MacroRunning { get; set; } - public bool NavigationEnabled { get; set; } - public int RouteType { get; set; } - public int ActiveNavIndex { get; set; } - public List<string> NavFiles { get; set; } = new(); - public List<NavPoint> Points { get; set; } = new(); - } - - internal sealed class NavCmd - { - public string Cmd { get; set; } = string.Empty; - public int SpellId { get; set; } - public int Index { get; set; } - public int RouteType { get; set; } - public int AddMode { get; set; } - public int InsertAt { get; set; } = -1; - public string NavName { get; set; } = string.Empty; - } + private static readonly int[] RecallIds = NavCommands.RecallIds; private sealed class State { public Payload Data = new(); public int SelectedIdx = -1; public int AddModeIdx = 0; + public string SaveName = string.Empty; + public string ChatText = string.Empty; + public int ChatFor = -1; // waypoint whose command is in ChatText + public bool Typing; // name box focused: the poll must not rebuild it away } // ── Picker overlay (identical pattern to SettingsPanel) ────────────────── @@ -195,7 +138,6 @@ internal static class NavPanel public static Control Create() { - TryBind(); var state = new State(); var root = new Border @@ -361,7 +303,7 @@ internal static class NavPanel var addRecallBtn = MakeActionBtn("Add Recall"); var recallLabels = new string[RecallIds.Length]; for (int ri = 0; ri < RecallIds.Length; ri++) - recallLabels[ri] = $"Spell {RecallIds[ri]} ({RecallIds[ri]})"; + recallLabels[ri] = NavCommands.RecallLabels[ri]; addRecallBtn.Click += (_, _) => picker.Show(addRecallBtn, recallLabels, -1, idx => Send(new NavCmd { Cmd = "addRecall", SpellId = RecallIds[idx], AddMode = state.AddModeIdx, InsertAt = state.SelectedIdx })); @@ -387,6 +329,100 @@ internal static class NavPanel content.Children.Add(actionWrap); + // ── Chat waypoint ───────────────────────────────────────────────── + // Sent as if typed when the route reaches it: /ra, /ub, /mt commands, + // game commands, or plain text to say. Placed per the Add mode. + // Selecting an existing chat waypoint loads its command; Update saves the edit. + bool chatSelected = state.SelectedIdx >= 0 && state.SelectedIdx < d.Points.Count + && d.Points[state.SelectedIdx].Type == "Chat"; + if (state.SelectedIdx != state.ChatFor) + { + if (chatSelected) state.ChatText = d.Points[state.SelectedIdx].Text; + else if (state.ChatFor >= 0) state.ChatText = string.Empty; + state.ChatFor = chatSelected ? state.SelectedIdx : -1; + } + var chatRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto") }; + var chatBox = new TextBox + { + Text = state.ChatText, Watermark = "Chat command, e.g. /ub usei Healing Kit", + Background = ColBtnFill, Foreground = ColTextDim, + BorderBrush = ColBtnBord, BorderThickness = new Thickness(1), + FontSize = 10, Height = 22, Padding = new Thickness(4, 1), + Margin = new Thickness(0, 0, 4, 0), + }; + chatBox.TextChanged += (_, _) => state.ChatText = chatBox.Text ?? string.Empty; + chatBox.GotFocus += (_, _) => state.Typing = true; + chatBox.LostFocus += (_, _) => state.Typing = false; + var addChatBtn = MakeActionBtn("Add Chat"); + var updChatBtn = MakeActionBtn("Update"); + updChatBtn.IsVisible = chatSelected; + void AddChat() + { + string text = state.ChatText.Trim(); + if (text.Length == 0) return; + Send(new NavCmd { Cmd = "addChat", Text = text, AddMode = state.AddModeIdx, InsertAt = state.SelectedIdx }); + state.ChatText = string.Empty; + state.ChatFor = -1; + state.Typing = false; + Rebuild(); + } + void UpdateChat() + { + string text = state.ChatText.Trim(); + if (text.Length == 0 || !chatSelected) return; + Send(new NavCmd { Cmd = "editChat", Index = state.SelectedIdx, Text = text }); + state.Typing = false; + Rebuild(); + } + addChatBtn.Click += (_, _) => AddChat(); + updChatBtn.Click += (_, _) => UpdateChat(); + chatBox.KeyDown += (_, e) => + { + if (e.Key != Avalonia.Input.Key.Enter) return; + e.Handled = true; + if (chatSelected) UpdateChat(); else AddChat(); + }; + Grid.SetColumn(chatBox, 0); + Grid.SetColumn(updChatBtn, 1); + Grid.SetColumn(addChatBtn, 2); + chatRow.Children.Add(chatBox); + chatRow.Children.Add(updChatBtn); + chatRow.Children.Add(addChatBtn); + content.Children.Add(chatRow); + + // ── Save as a named nav ─────────────────────────────────────────── + // Save Route writes the current file; a route with no file got + // nowhere to go and there was no way to name one. + var saveAsRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; + var nameBox = new TextBox + { + Text = state.SaveName, Watermark = "Nav name...", + Background = ColBtnFill, Foreground = ColTextDim, + BorderBrush = ColBtnBord, BorderThickness = new Thickness(1), + FontSize = 10, Height = 22, Padding = new Thickness(4, 1), + Margin = new Thickness(0, 0, 4, 0), + }; + nameBox.TextChanged += (_, _) => state.SaveName = nameBox.Text ?? string.Empty; + nameBox.GotFocus += (_, _) => state.Typing = true; + nameBox.LostFocus += (_, _) => state.Typing = false; + var saveAsBtn = MakeActionBtn("Save As"); + void SaveAs() + { + string name = state.SaveName.Trim(); + if (name.Length == 0) return; + Send(new NavCmd { Cmd = "saveRoute", NavName = name }); + state.SaveName = string.Empty; + state.Typing = false; + Rebuild(); + } + saveAsBtn.Click += (_, _) => SaveAs(); + nameBox.KeyDown += (_, e) => { if (e.Key == Avalonia.Input.Key.Enter) { e.Handled = true; SaveAs(); } }; + Grid.SetColumn(nameBox, 0); + Grid.SetColumn(saveAsBtn, 1); + saveAsRow.Children.Add(nameBox); + saveAsRow.Children.Add(saveAsBtn); + content.Children.Add(saveAsRow); + // ── Nav file selector ───────────────────────────────────────────── if (d.NavFiles.Count > 0) { @@ -476,9 +512,7 @@ internal static class NavPanel Grid.SetColumn(indicator, 1); row.Children.Add(indicator); - string disp = !string.IsNullOrEmpty(pt.Desc) - ? $"[{i}] {pt.Desc}" - : $"[{i}] {pt.Type} ({pt.NS:F2}N, {pt.EW:F2}E, {pt.Z:F1})"; + string disp = NavCommands.PointText(pt, i); var desc = new TextBlock { Text = disp, @@ -508,29 +542,36 @@ internal static class NavPanel } // ── Poll timer ──────────────────────────────────────────────────────── - // Rebuilds only when the plugin's nav state actually changed, and never while the - // pointer is over the waypoint list (a rebuild between press and release eats the - // click on X / row select). Skipped polls leave lastJson alone, so the change is - // picked up on the first poll after the pointer leaves. - var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) }; + // Reads the hub's snapshot (fetched every 1 s while subscribed, and + // right after each command). + long seenVersion = -1; + var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) }; timer.Tick += (_, _) => { - if (_getNavJson == null) TryBind(); - if (picker.ActivePicker != null) return; + if (picker.ActivePicker != null || state.Typing) return; + // A rebuild between press and release eats the click on X / row select. seenVersion + // is left alone, so the change is picked up once the pointer leaves the list. if (waypointHost.IsPointerOver) return; - if (!TryFetch(out var fresh, out string json)) return; - if (json == lastJson) return; - state.Data = fresh; - rebuildFromPoll = true; - try { Rebuild(); } finally { rebuildFromPoll = false; } - lastJson = json; + var snap = UiSources.Nav.Current; + if (snap == null || snap.Version == seenVersion) return; + seenVersion = snap.Version; + state.Data = snap.Value.Clone(); + Rebuild(); }; - timer.Start(); // Stop with the visual tree — a running DispatcherTimer roots the closed // view forever (one immortal poller per open/close). RadarPanel idiom; // must restart on attach: drag/resize fires Detached→Attached. - root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); }; - root.DetachedFromVisualTree += (_, _) => timer.Stop(); + root.AttachedToVisualTree += (_, _) => + { + UiSources.Nav.Subscribe(); + UiSources.Nav.RequestRefresh(); + if (!timer.IsEnabled) timer.Start(); + }; + root.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.Nav.Unsubscribe(); + }; Rebuild(); return root; @@ -569,75 +610,5 @@ internal static class NavPanel Margin = new Thickness(0, 0, 4, 4), }; - // ========================================================================= - // Plugin bridge - // ========================================================================= - - // RL loads fresh plugin copies without unloading the old ones: drop the - // exports bound below so the next poll re-binds to the live copy. - static NavPanel() => PluginManager.PluginsUnloaded += () => - { - _getNavJson = null; - _sendNavCommand = null; - }; - - private static void TryBind() - { - var plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - if (_getNavJson == null) - { - IntPtr p1 = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetNavJson"); - if (p1 != IntPtr.Zero) - _getNavJson = Marshal.GetDelegateForFunctionPointer<GetNavJsonFn>(p1); - } - if (_sendNavCommand == null) - { - IntPtr p2 = GetProcAddress(plugin.ModuleHandle, "RynthPluginSendNavCommand"); - if (p2 != IntPtr.Zero) - _sendNavCommand = Marshal.GetDelegateForFunctionPointer<SendNavCommandFn>(p2); - } - } - - /// <summary>Polls the plugin's nav JSON. <paramref name="json"/> is the raw text, used by - /// the poll timer to skip rebuilding the panel when nothing changed.</summary> - private static bool TryFetch(out Payload payload, out string json) - { - payload = new Payload(); - json = string.Empty; - if (_getNavJson == null) return false; - try - { - IntPtr ptr = _getNavJson(); - if (ptr == IntPtr.Zero) return false; - string? raw = Marshal.PtrToStringAnsi(ptr); - if (string.IsNullOrEmpty(raw)) return false; - var parsed = JsonSerializer.Deserialize(raw, NavPanelJsonContext.Default.Payload); - if (parsed == null) return false; - payload = parsed; - json = raw; - return true; - } - catch { return false; } - } - - private static void Send(NavCmd cmd) - { - if (_sendNavCommand == null) TryBind(); - if (_sendNavCommand == null) return; - IntPtr ansi = IntPtr.Zero; - try - { - string json = JsonSerializer.Serialize(cmd, NavPanelJsonContext.Default.NavCmd); - ansi = Marshal.StringToHGlobalAnsi(json); - _sendNavCommand(ansi); - } - catch { } - finally - { - if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi); - } - } + private static void Send(NavCmd cmd) => NavCommands.Send(cmd); } diff --git a/src/RynthCore.Engine/UI/Panels/RadarPanel.cs b/src/RynthCore.Engine/UI/Panels/RadarPanel.cs index e591de8..ea45404 100644 --- a/src/RynthCore.Engine/UI/Panels/RadarPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RadarPanel.cs @@ -2,9 +2,10 @@ // RynthCore.Engine — UI/Panels/RadarPanel.cs // Avalonia replica of the ImGui RynthRadar (RynthRadarUi.cs). // -// Renders the same view, fed by the plugin's RynthPluginGetRadarSnapshot -// export. Geometry is cached by MapVersion (= landblock); per-frame data -// (player pose, visited overlay, markers) refreshes every 100 ms. +// Renders the same view from UiDataHub's radar view (UiSources.Radar, +// UI/Data/RadarData.cs), which calls RynthPluginGetRadarSnapshot on the pump +// thread and keeps the per-landblock geometry cache. The ImGui face +// (ImGui/Panels/RadarFace.cs) draws the same view. // // Render order matches the ImGui original: // 1. Frame outer/inner/accent + canvas bg @@ -38,6 +39,7 @@ using Avalonia.Layout; using Avalonia.Media; using Avalonia.Threading; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; @@ -60,6 +62,76 @@ internal static class RadarSettingsStore public static bool ShowNpcs = true; public static bool ShowPortals = true; public static bool ShowDoors = true; + // Kinds added 2026-10-04 (RadarKind 4..11). Items on the ground start hidden: noisy. + public static bool ShowPlayers = true; + public static bool ShowFellows = true; + public static bool ShowPets = true; + public static bool ShowVendors = true; + public static bool ShowCorpses = true; + public static bool ShowOwnCorpses = true; + public static bool ShowLifestones = true; + public static bool ShowGroundItems = false; + /// <summary>ImGui face: a left-click on a dot selects that object in game.</summary> + public static bool ClickToSelect = true; + + /// <summary> + /// Default marker colour per <see cref="RadarKind"/> (ARGB). Chosen to stay apart for + /// red-green colour blindness as well: the kinds that share a hue family also differ + /// in shape (see RadarMarkerStyle) or brightness. + /// </summary> + public static readonly uint[] DefaultKindColors = + { + 0xFFFF3333, // monster: red + 0xFFFFD933, // NPC: yellow + 0xFFBF4DFF, // portal: purple + 0xFFFF8C1A, // door: orange + 0xFF33C7FF, // player: cyan-blue + 0xFF4DE673, // fellow: green + 0xFF26BFA6, // your pet: teal + 0xFFFFB31A, // vendor: gold + 0xFF8C9399, // corpse: grey + 0xFFF2F2F2, // your corpse: near white + 0xFF99D1FF, // lifestone: light blue + 0xFFD9C78C, // item on the ground: pale tan + }; + + /// <summary>Marker colour per <see cref="RadarKind"/> (ARGB); the user's picks, else the defaults.</summary> + public static readonly uint[] KindColors = (uint[])DefaultKindColors.Clone(); + + // Settings-file keys per kind (color.<key>=AARRGGBB). + private static readonly string[] KindKeys = + { + "monster", "npc", "portal", "door", "player", "fellow", + "pet", "vendor", "corpse", "ownCorpse", "lifestone", "groundItem", + }; + + /// <summary>The show/hide flag of a kind (the radar's per-kind check boxes).</summary> + public static ref bool ShowFlag(byte kind) + { + switch (kind) + { + case RadarKind.Monster: return ref ShowMonsters; + case RadarKind.Npc: return ref ShowNpcs; + case RadarKind.Portal: return ref ShowPortals; + case RadarKind.Door: return ref ShowDoors; + case RadarKind.Player: return ref ShowPlayers; + case RadarKind.Fellow: return ref ShowFellows; + case RadarKind.Pet: return ref ShowPets; + case RadarKind.Vendor: return ref ShowVendors; + case RadarKind.Corpse: return ref ShowCorpses; + case RadarKind.OwnCorpse: return ref ShowOwnCorpses; + case RadarKind.Lifestone: return ref ShowLifestones; + default: return ref ShowGroundItems; + } + } + + /// <summary>Whether markers of this kind are drawn; false for kinds this engine doesn't know.</summary> + public static bool ShowKind(byte kind) => kind < RadarKind.Count && ShowFlag(kind); + + /// <summary>The kind's colour (ARGB); white for a kind this engine doesn't know.</summary> + public static uint KindColor(byte kind) => kind < KindColors.Length ? KindColors[kind] : 0xFFFFFFFF; + + public static void ResetKindColors() => Array.Copy(DefaultKindColors, KindColors, KindColors.Length); private static string FilePath { @@ -105,6 +177,23 @@ internal static class RadarSettingsStore case "showNpcs": ShowNpcs = val == "1"; break; case "showPortals": ShowPortals = val == "1"; break; case "showDoors": ShowDoors = val == "1"; break; + case "showPlayers": ShowPlayers = val == "1"; break; + case "showFellows": ShowFellows = val == "1"; break; + case "showPets": ShowPets = val == "1"; break; + case "showVendors": ShowVendors = val == "1"; break; + case "showCorpses": ShowCorpses = val == "1"; break; + case "showOwnCorpses": ShowOwnCorpses = val == "1"; break; + case "showLifestones": ShowLifestones = val == "1"; break; + case "showGroundItems": ShowGroundItems = val == "1"; break; + case "clickSelect": ClickToSelect = val == "1"; break; + default: + if (key.StartsWith("color.", StringComparison.Ordinal)) + { + int k = Array.IndexOf(KindKeys, key["color.".Length..]); + if (k >= 0 && uint.TryParse(val, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint argb)) + KindColors[k] = argb; + } + break; } } } @@ -112,7 +201,10 @@ internal static class RadarSettingsStore } } - public static void Save() + /// <summary>Writes the settings in the background (callers include AC's render thread).</summary> + public static void Save() => UiBackgroundWriter.Enqueue("radar settings", SaveNow); + + private static void SaveNow() { lock (_sync) { @@ -132,6 +224,19 @@ internal static class RadarSettingsStore sw.WriteLine($"showNpcs={(ShowNpcs ? "1" : "0")}"); sw.WriteLine($"showPortals={(ShowPortals ? "1" : "0")}"); sw.WriteLine($"showDoors={(ShowDoors ? "1" : "0")}"); + sw.WriteLine($"showPlayers={(ShowPlayers ? "1" : "0")}"); + sw.WriteLine($"showFellows={(ShowFellows ? "1" : "0")}"); + sw.WriteLine($"showPets={(ShowPets ? "1" : "0")}"); + sw.WriteLine($"showVendors={(ShowVendors ? "1" : "0")}"); + sw.WriteLine($"showCorpses={(ShowCorpses ? "1" : "0")}"); + sw.WriteLine($"showOwnCorpses={(ShowOwnCorpses ? "1" : "0")}"); + sw.WriteLine($"showLifestones={(ShowLifestones ? "1" : "0")}"); + sw.WriteLine($"showGroundItems={(ShowGroundItems ? "1" : "0")}"); + sw.WriteLine($"clickSelect={(ClickToSelect ? "1" : "0")}"); + // Only colours that differ from the default, so a later default change still lands. + for (int k = 0; k < KindColors.Length; k++) + if (KindColors[k] != DefaultKindColors[k]) + sw.WriteLine(FormattableString.Invariant($"color.{KindKeys[k]}={KindColors[k]:X8}")); } catch { /* non-fatal */ } } @@ -140,14 +245,6 @@ internal static class RadarSettingsStore internal static partial class RadarPanel { - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate IntPtr GetRadarSnapshotFn(uint mapVersion); - - private static GetRadarSnapshotFn? _getRadarSnapshot; - // ── Chrome-less integration hooks ─────────────────────────────────────── // The radar lives inside the panel system but visually has no window // chrome — just the gold-bordered square + coords below. The overlay @@ -231,81 +328,19 @@ internal static partial class RadarPanel private static readonly IBrush ColDoor = new SolidColorBrush(Color.FromRgb(0xFF, 0x8C, 0x1A)); private static readonly IBrush ColDoorEdge = new SolidColorBrush(Color.FromRgb(0x66, 0x33, 0x00)); - // ── Snapshot DTO (mirrors RynthCore.Plugin.RynthAi.LegacyUi.RadarSnapshotPayload) ── - public sealed class Snapshot - { - [JsonPropertyName("mapVersion")] public uint MapVersion { get; set; } - [JsonPropertyName("geometryIncluded")] public bool GeometryIncluded { get; set; } - [JsonPropertyName("isIndoor")] public bool IsIndoor { get; set; } - [JsonPropertyName("player")] public PlayerInfo Player { get; set; } = new(); - [JsonPropertyName("ns")] public double Ns { get; set; } = double.NaN; - [JsonPropertyName("ew")] public double Ew { get; set; } = double.NaN; - [JsonPropertyName("layerZs")] public List<float> LayerZs { get; set; } = new(); - [JsonPropertyName("currentLayerZ")] public float CurrentLayerZ { get; set; } - [JsonPropertyName("walls")] public List<WallLayer> Walls { get; set; } = new(); - [JsonPropertyName("fills")] public List<FillLayer> Fills { get; set; } = new(); - [JsonPropertyName("visited")] public List<VisitedLayer> Visited { get; set; } = new(); - [JsonPropertyName("markers")] public List<Marker> Markers { get; set; } = new(); - } - - public sealed class PlayerInfo - { - [JsonPropertyName("cellId")] public uint CellId { get; set; } - [JsonPropertyName("landblock")] public uint Landblock { get; set; } - [JsonPropertyName("x")] public float X { get; set; } - [JsonPropertyName("y")] public float Y { get; set; } - [JsonPropertyName("z")] public float Z { get; set; } - [JsonPropertyName("worldX")] public float WorldX { get; set; } - [JsonPropertyName("worldY")] public float WorldY { get; set; } - [JsonPropertyName("heading")] public float Heading { get; set; } - } - - public sealed class WallLayer - { - [JsonPropertyName("z")] public float Z { get; set; } - [JsonPropertyName("segments")] public float[] Segments { get; set; } = Array.Empty<float>(); - } - - public sealed class FillLayer - { - [JsonPropertyName("z")] public float Z { get; set; } - [JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty<float>(); - } - - public sealed class VisitedLayer - { - [JsonPropertyName("z")] public float Z { get; set; } - [JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty<float>(); - } - - public sealed class Marker - { - [JsonPropertyName("kind")] public byte Kind { get; set; } - [JsonPropertyName("x")] public float X { get; set; } - [JsonPropertyName("y")] public float Y { get; set; } - [JsonPropertyName("z")] public float Z { get; set; } - [JsonPropertyName("label")] public string? Label { get; set; } - } - - [JsonSerializable(typeof(Snapshot))] - [JsonSourceGenerationOptions(WriteIndented = false)] - internal partial class RadarJsonContext : JsonSerializerContext { } - // ── Per-instance state, captured by the surface control ──────────────── private sealed class State { // Live data (refreshed every poll). - public Snapshot Live = new(); + public RadarSnapshot Live = new(); - // Cached geometry, indexed by MapVersion. Walls/fills don't change - // until the player crosses landblocks — store and reuse. - public uint CachedMapVersion; - public List<WallLayer> CachedWalls = new(); - public List<FillLayer> CachedFills = new(); + // Geometry cached per landblock by the hub (RadarSource). + public List<RadarWallLayer> CachedWalls = new(); + public List<RadarFillLayer> CachedFills = new(); - // UI deep-dive finding P1-A (2026-07-02): last raw snapshot JSON, - // used to gate InvalidateVisual — see the timer tick below. - public string? LastRawJson; + // Hub view version last drawn; gates InvalidateVisual (UI deep-dive + // finding P1-A: don't re-raster when nothing moved). + public long SeenVersion = -1; // User-controlled settings — driven by the gear popup. Loaded from // RadarSettingsStore on construction; Persist() writes back. @@ -359,7 +394,6 @@ internal static partial class RadarPanel public static Control Create() { - TryBind(); State state = _persistentState ??= new State(); var surface = new RadarSurface(state); @@ -600,38 +634,14 @@ internal static partial class RadarPanel // re-rastered at 30Hz for no visible change. Track whether // anything actually changed this tick and skip the whole // refresh+invalidate when it didn't. - bool fetched = TryFetch(state.CachedMapVersion, out Snapshot? fresh, out string? rawJson); - bool contentChanged = fetched && rawJson != null && rawJson != state.LastRawJson; - if (fetched && rawJson != null) state.LastRawJson = rawJson; - - if (fetched && fresh != null) + var current = UiSources.Radar.Current; + bool contentChanged = current != null && current.Version != state.SeenVersion; + if (contentChanged) { - state.Live = fresh; - if (fresh.GeometryIncluded) - { - state.CachedMapVersion = fresh.MapVersion; - state.CachedWalls = fresh.Walls; - state.CachedFills = fresh.Fills; - } - else if (fresh.MapVersion != state.CachedMapVersion && fresh.MapVersion != 0 && !fresh.IsIndoor) - { - // Outdoor landblocks: no geometry sent, but version still - // tracks landblock — clear stale walls so they don't bleed - // through when transitioning indoor→outdoor. - state.CachedMapVersion = fresh.MapVersion; - state.CachedWalls = new List<WallLayer>(); - state.CachedFills = new List<FillLayer>(); - } - - // First poll after login can land before raycast is ready, so - // the plugin returns an indoor snapshot with empty walls. Once - // raycast comes online, we have to re-ask with version=0 or - // the plugin sees a matching version and skips the geometry - // payload — leaving the radar permanently blank until the - // user manually closes/reopens it. Force a re-fetch next tick - // whenever we're indoors but lack walls. - if (state.Live.IsIndoor && state.CachedWalls.Count == 0) - state.CachedMapVersion = 0; + state.SeenVersion = current!.Version; + state.Live = current.Value.Live; + state.CachedWalls = current.Value.Walls; + state.CachedFills = current.Value.Fills; } // Sync overlay button visibility with current pop-out state. // docked → [↗ popout, ⚙ gear] @@ -659,9 +669,19 @@ internal static partial class RadarPanel MarkDirty?.Invoke(); } }; - timer.Start(); - surface.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); }; - surface.DetachedFromVisualTree += (_, _) => timer.Stop(); + // The hub polls the plugin only while some radar face is subscribed. + surface.AttachedToVisualTree += (_, _) => + { + UiSources.Radar.Subscribe(); + UiSources.Radar.RequestRefresh(); + state.SeenVersion = -1; + if (!timer.IsEnabled) timer.Start(); + }; + surface.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.Radar.Unsubscribe(); + }; return radarGrid; } @@ -1304,7 +1324,7 @@ internal static partial class RadarPanel } private static float AlphaToFloat(byte a) => a == 0 ? 1f : a / 255f; - private static string FormatCoords(Snapshot s) + private static string FormatCoords(RadarSnapshot s) { // Match the ImGui radar's footer behaviour exactly: // indoor → "LB AABB Z 12.3" (landblock id, no NS/EW) @@ -1318,46 +1338,4 @@ internal static partial class RadarPanel return $"Z {p.Z:0.0}"; } - - // ── Plugin export binding ─────────────────────────────────────────────── - // RL loads fresh plugin copies without unloading the old ones: drop the - // exports bound below so the next poll re-binds to the live copy. - static RadarPanel() => PluginManager.PluginsUnloaded += () => - { - _getRadarSnapshot = null; - }; - - private static void TryBind() - { - if (_getRadarSnapshot != null) return; - var plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - IntPtr p1 = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetRadarSnapshot"); - if (p1 != IntPtr.Zero) - _getRadarSnapshot = Marshal.GetDelegateForFunctionPointer<GetRadarSnapshotFn>(p1); - } - - private static bool TryFetch(uint engineKnownVersion, out Snapshot? snapshot, out string? rawJson) - { - snapshot = null; - rawJson = null; - if (_getRadarSnapshot == null) TryBind(); - if (_getRadarSnapshot == null) return false; - try - { - IntPtr ptr = _getRadarSnapshot(engineKnownVersion); - if (ptr == IntPtr.Zero) return false; - string? json = Marshal.PtrToStringAnsi(ptr); - if (string.IsNullOrEmpty(json) || json == "{}") return false; - snapshot = JsonSerializer.Deserialize(json, RadarJsonContext.Default.Snapshot); - rawJson = json; - return snapshot != null; - } - catch - { - return false; - } - } } diff --git a/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs index 96c245c..bc2c0d4 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs @@ -12,16 +12,12 @@ // • Launcher grid: 3 cols × 2-3 rows of GridBtns (visual only — opens // no sub-windows yet; main-dashboard scope only). // -// Live data comes from the RynthAi plugin via these C exports: -// RynthPluginGetSnapshotJson → JSON blob (polled every 33 ms) -// RynthPluginToggleMacro → flip IsMacroRunning -// RynthPluginSetSubsystemEnabled(id) → 0=Combat 1=Buff 2=Nav 3=Loot 4=Meta -// RynthPluginSelectProfile(kind, i) → 0=nav 1=loot 2=meta 3=profile -// RynthPluginForceRebuff → buff manager force rebuff -// RynthPluginCancelForceRebuff → cancel pending FR -// RynthPluginAdjustOpacity(delta) → header +/- chips (mirrored) -// RynthPluginTogglePanelLock → Lock chip (mirrored) -// RynthPluginTogglePanelMinimize → _ chip (mirrored) +// Live data comes from UiDataHub (UiSources.RynthAi / UiSources.Patrol, +// UI/Data/RynthAiData.cs), which calls the plugin's exports on the pump +// thread; clicks go through RynthAiCommands. This face never calls a +// plugin export itself (they used to run on the Avalonia thread, racing the +// plugin tick). The ImGui face (ImGui/Panels/RynthAiFace.cs) reads the same +// view. // ============================================================================ using System; @@ -39,29 +35,12 @@ using Avalonia.Layout; using Avalonia.Media; using Avalonia.Threading; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; internal static partial class RynthAiPanel { - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate IntPtr GetSnapshotJsonFn(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void VoidFn(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void IntFn(int arg); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void IntIntFn(int a, int b); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void FloatFn(float arg); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void PtrFn(IntPtr arg); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void PtrPtrFn(IntPtr a, IntPtr b); - // ── Color palette — exact match to LegacyDashboardRenderer ImGui Vector4 // floats (multiplied by 255 and rounded). Don't deepen these; the ImGui // contrast is what makes the dashboard read crisp against AC scenes. @@ -112,21 +91,6 @@ internal static partial class RynthAiPanel // FR button: (0.28,0.20,0.04). private static readonly IBrush ColFrFill = new SolidColorBrush(Color.FromRgb(0x47, 0x33, 0x0A)); - private static GetSnapshotJsonFn? _getSnapshotJson; - private static VoidFn? _toggleMacro; - private static IntIntFn? _setSubsystemEnabled; - private static IntIntFn? _selectProfile; - private static VoidFn? _forceRebuff; - private static VoidFn? _cancelForceRebuff; - private static FloatFn? _adjustOpacity; - private static VoidFn? _togglePanelLock; - private static VoidFn? _togglePanelMinimize; - private static PtrFn? _sendNavCommand; - private static GetSnapshotJsonFn? _getPatrolInfoJson; - // RynthPluginApplyRemoteCommand(action, value): queued and applied on the plugin pump thread. - private static PtrPtrFn? _applyRemoteCommand; - private static bool _bindingLogged; - /// <summary> /// Set by AvaloniaOverlay.TogglePanel before invoking the factory. The /// panel calls this with its in-panel title-row Border so the wrapping @@ -171,122 +135,21 @@ internal static partial class RynthAiPanel private const double MinimizedHeightPreset = 110; private const double MinimizedMinHeightFloor = 46; - // Last-known good vitals — persists across panel recreates AND across - // engine hot-reloads (saved to disk). After a reload the plugin's vital - // cache is cold for a tick or two; without this the panel shows 0/0, - // which the user sees as the bars wiping. Updated only when the snapshot - // gives us a real (non-zero max) reading. - private static uint _cachedHp, _cachedMaxHp; - private static uint _cachedSt, _cachedMaxSt; - private static uint _cachedMn, _cachedMaxMn; - private static bool _vitalCacheLoaded; - private static long _vitalCacheLastSavedTick; + // The minimized state lives in UI/RynthAiDashboardState.cs, not here: + // engine init reads it before the overlay starts, and touching this class + // then would run its static brushes on the wrong thread. - // Avalonia panel's OWN minimize state, persisted independently of the - // ImGui dashboard. Sharing snap.IsMinimized via the plugin caused the - // ImGui "_" chip to also collapse the Avalonia panel (and vice versa) — - // which the user noticed because the Avalonia minimized look hadn't - // been built out yet, so the panel just blanked. - private static bool _avaloniaMinimized; - private static bool _avaloniaMinimizedLoaded; - - /// <summary> - /// Live-testing finding 2026-09-02: lets the overlay pick the right - /// initial MinHeight floor when (re)docking the panel, so a saved small - /// (minimized) height from a previous session isn't immediately - /// re-clamped back up to the expanded floor. Loads on first access if - /// not already loaded, same as the panel's own Create() does. - /// </summary> - internal static bool IsAvaloniaMinimized - { - get { LoadAvaloniaMinimized(); return _avaloniaMinimized; } - } - - private static string VitalCachePath => - System.IO.Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "RynthCore", "vitals.cache"); - - private static string AvaloniaMinimizedPath => - System.IO.Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "RynthCore", "rynthai_avalonia.cache"); - - private static void LoadAvaloniaMinimized() - { - if (_avaloniaMinimizedLoaded) return; - _avaloniaMinimizedLoaded = true; - try - { - string path = AvaloniaMinimizedPath; - if (!System.IO.File.Exists(path)) return; - _avaloniaMinimized = string.Equals( - System.IO.File.ReadAllText(path).Trim(), - "minimized", - StringComparison.OrdinalIgnoreCase); - } - catch { /* corrupt cache — start fresh */ } - } - - private static void SaveAvaloniaMinimized() - { - try - { - string path = AvaloniaMinimizedPath; - string dir = System.IO.Path.GetDirectoryName(path)!; - System.IO.Directory.CreateDirectory(dir); - System.IO.File.WriteAllText(path, _avaloniaMinimized ? "minimized" : "expanded"); - } - catch { /* best-effort */ } - } - - private static void LoadVitalCache() - { - if (_vitalCacheLoaded) return; - _vitalCacheLoaded = true; - try - { - string path = VitalCachePath; - if (!System.IO.File.Exists(path)) return; - string[] parts = System.IO.File.ReadAllText(path).Split(','); - if (parts.Length < 6) return; - _cachedHp = uint.Parse(parts[0], System.Globalization.CultureInfo.InvariantCulture); - _cachedMaxHp = uint.Parse(parts[1], System.Globalization.CultureInfo.InvariantCulture); - _cachedSt = uint.Parse(parts[2], System.Globalization.CultureInfo.InvariantCulture); - _cachedMaxSt = uint.Parse(parts[3], System.Globalization.CultureInfo.InvariantCulture); - _cachedMn = uint.Parse(parts[4], System.Globalization.CultureInfo.InvariantCulture); - _cachedMaxMn = uint.Parse(parts[5], System.Globalization.CultureInfo.InvariantCulture); - } - catch { /* corrupt cache — start fresh */ } - } - - private static void SaveVitalCache() - { - // Throttle disk writes to once per second so polling 4×/s doesn't - // beat up AppData. We only save when at least one max changed anyway. - long now = Environment.TickCount64; - if (now - _vitalCacheLastSavedTick < 1000) return; - _vitalCacheLastSavedTick = now; - try - { - string path = VitalCachePath; - string dir = System.IO.Path.GetDirectoryName(path)!; - System.IO.Directory.CreateDirectory(dir); - System.IO.File.WriteAllText(path, - $"{_cachedHp},{_cachedMaxHp},{_cachedSt},{_cachedMaxSt},{_cachedMn},{_cachedMaxMn}"); - } - catch { /* best-effort, never throw out of a UI tick */ } - } + public const double ExpandedHeight = ExpandedHeightPreset, ExpandedMinHeight = ExpandedMinHeightFloor; + public const double MinimizedHeight = MinimizedHeightPreset, MinimizedMinHeight = MinimizedMinHeightFloor; internal static Control Create() { RynthLog.Info("RynthAiPanel.Create: entry"); - TryBind(); - LoadVitalCache(); - LoadAvaloniaMinimized(); - RynthLog.Info("RynthAiPanel.Create: TryBind ok"); + RynthAiDashboardState.EnsureLoaded(); - Snapshot snap = new(); + // The latest hub view; its raw snapshot backs click handlers (current + // toggle states, picker lists) exactly as the old per-tick snapshot did. + RynthAiSnapshot snap = new(); Border? activePicker = null; Button? activeAnchor = null; @@ -359,7 +222,6 @@ internal static partial class RynthAiPanel VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 2, 0, 0) }; - int versionPollTicks = 0; titleStack.Children.Add(versionText); titleRow.Children.Add(titleStack); @@ -386,20 +248,19 @@ internal static partial class RynthAiPanel // Chip clicks must NOT also trigger drag — Button itself handles // PointerPressed and marks the event handled, so it doesn't bubble // to the title-border drag handler. - lockChip.Click += (_, _) => { ClosePicker(); _togglePanelLock?.Invoke(); }; - minusChip.Click += (_, _) => { ClosePicker(); _adjustOpacity?.Invoke(-0.1f); }; - plusChip.Click += (_, _) => { ClosePicker(); _adjustOpacity?.Invoke(0.1f); }; + lockChip.Click += (_, _) => { ClosePicker(); RynthAiCommands.TogglePanelLock(); }; + minusChip.Click += (_, _) => { ClosePicker(); RynthAiCommands.AdjustOpacity(-0.1f); }; + plusChip.Click += (_, _) => { ClosePicker(); RynthAiCommands.AdjustOpacity(0.1f); }; minChip.Click += (_, _) => { ClosePicker(); - _avaloniaMinimized = !_avaloniaMinimized; - SaveAvaloniaMinimized(); + RynthAiDashboardState.SetMinimized(!RynthAiDashboardState.Minimized); // Live-testing finding 2026-09-02: reducing used to hide content // rows but leave the window's own size untouched. Actually // resize to the preset for the mode just switched to. RequestDockedResize?.Invoke( - _avaloniaMinimized ? MinimizedHeightPreset : ExpandedHeightPreset, - _avaloniaMinimized ? MinimizedMinHeightFloor : ExpandedMinHeightFloor); + RynthAiDashboardState.Minimized ? MinimizedHeightPreset : ExpandedHeightPreset, + RynthAiDashboardState.Minimized ? MinimizedMinHeightFloor : ExpandedMinHeightFloor); }; dockChip.Click += (_, _) => { @@ -443,7 +304,7 @@ internal static partial class RynthAiPanel CornerRadius = new CornerRadius(3), Padding = new Thickness(0) }; - macroButton.Click += (_, _) => { ClosePicker(); _toggleMacro?.Invoke(); }; + macroButton.Click += (_, _) => { ClosePicker(); RynthAiCommands.ToggleMacro(); }; macroRow.Children.Add(macroButton); // Status circle: 8px filled + 14px ring while running @@ -559,7 +420,7 @@ internal static partial class RynthAiPanel IsVisible = false }; ToolTip.SetTip(minimizedMacroButton, "Click to Start / Stop Macro"); - minimizedMacroButton.Click += (_, _) => { ClosePicker(); _toggleMacro?.Invoke(); }; + minimizedMacroButton.Click += (_, _) => { ClosePicker(); RynthAiCommands.ToggleMacro(); }; togglesPanel.Children.Add(minimizedMacroButton); // Avalonia 11 Grid has no ColumnSpacing/RowSpacing; we lay the cells @@ -616,25 +477,25 @@ internal static partial class RynthAiPanel Margin = new Thickness(0, 1, 0, 0) }; ToolTip.SetTip(frButton, "Force-recast all buffs."); - frButton.Click += (_, _) => { ClosePicker(); _forceRebuff?.Invoke(); }; + frButton.Click += (_, _) => { ClosePicker(); RynthAiCommands.ForceRebuff(); }; // Right-click cancel frButton.PointerPressed += (_, e) => { if (e.GetCurrentPoint(frButton).Properties.IsRightButtonPressed) { e.Handled = true; - _cancelForceRebuff?.Invoke(); + RynthAiCommands.CancelForceRebuff(); } }; togglesPanel.Children.Add(frButton); combatGrid.Children.Add(togglesPanel); - combatToggle.Click += (_, _) => { ClosePicker(); _setSubsystemEnabled?.Invoke(0, snap.CombatEnabled ? 0 : 1); }; - buffToggle.Click += (_, _) => { ClosePicker(); _setSubsystemEnabled?.Invoke(1, snap.BuffingEnabled ? 0 : 1); }; - navToggle.Click += (_, _) => { ClosePicker(); _setSubsystemEnabled?.Invoke(2, snap.NavigationEnabled ? 0 : 1); }; - lootToggle.Click += (_, _) => { ClosePicker(); _setSubsystemEnabled?.Invoke(3, snap.LootingEnabled ? 0 : 1); }; - metaToggle.Click += (_, _) => { ClosePicker(); _setSubsystemEnabled?.Invoke(4, snap.MetaEnabled ? 0 : 1); }; + combatToggle.Click += (_, _) => { ClosePicker(); RynthAiCommands.SetSubsystemEnabled(0, !snap.CombatEnabled); }; + buffToggle.Click += (_, _) => { ClosePicker(); RynthAiCommands.SetSubsystemEnabled(1, !snap.BuffingEnabled); }; + navToggle.Click += (_, _) => { ClosePicker(); RynthAiCommands.SetSubsystemEnabled(2, !snap.NavigationEnabled); }; + lootToggle.Click += (_, _) => { ClosePicker(); RynthAiCommands.SetSubsystemEnabled(3, !snap.LootingEnabled); }; + metaToggle.Click += (_, _) => { ClosePicker(); RynthAiCommands.SetSubsystemEnabled(4, !snap.MetaEnabled); }; // Right column: target + vitals ────────────────────── var vitalsStack = new StackPanel { Orientation = Orientation.Vertical, Spacing = 3, Margin = new Thickness(6, 2, 0, 0) }; @@ -700,40 +561,25 @@ internal static partial class RynthAiPanel RowDefinitions = new RowDefinitions("Auto,Auto,Auto"), Margin = new Thickness(0, 4, 0, 0) }; - // Lua: the Lua Scripts editor is an ImGui window inside RynthAi (drawn from its - // RynthPluginRenderOverlay), so the button toggles it like "/ra lua". - var (_, luaBtn) = AddSplitLauncher(launcherGrid, 0, 0, "Meta", "⚙", "Lua", "<>", - onLeftClick: () => AvaloniaOverlay.ActivateBarButton("Meta"), - onRightClick: () => - { - ClosePicker(); - if (_applyRemoteCommand == null) TryBind(); - SendRemoteCmd("lua", "toggle"); - }); - ToolTip.SetTip(luaBtn, "Show/hide the Lua Scripts editor (/ra lua)."); - AddLauncher(launcherGrid, 0, 1, "Monsters", "◎", - onClick: () => AvaloniaOverlay.ActivateBarButton("Monsters")); + AddSplitLauncher(launcherGrid, 0, 0, "Meta", "⚙", "Lua", "<>", + onLeftClick: () => PanelRouter.Toggle("Meta"), + onRightClick: () => PanelRouter.Toggle("Lua")); + AddMonstersLauncher(launcherGrid, 0, 1); AddLauncher(launcherGrid, 0, 2, "Settings", "⚒", - onClick: () => AvaloniaOverlay.ActivateBarButton("Settings")); - // Map: the dungeon map is an ImGui window inside RynthAi (DashWindows.ShowDungeonMap), - // drawn from its RynthPluginRenderOverlay; the button toggles it like "/ra map". + onClick: () => PanelRouter.Toggle("Settings")); + // Map: RynthAi's dungeon map is an ImGui overlay window; the right half toggles it like "/ra map". var (_, mapBtn) = AddSplitLauncher(launcherGrid, 1, 0, "Nav", "➤", "Map", "🗺", - onLeftClick: () => AvaloniaOverlay.ActivateBarButton("Nav"), + onLeftClick: () => PanelRouter.Toggle("Nav"), onRightClick: () => { ClosePicker(); - if (_applyRemoteCommand == null) TryBind(); - SendRemoteCmd("map", "toggle"); + RynthAiCommands.ApplyRemoteCommand("map", "toggle"); }); ToolTip.SetTip(mapBtn, "Show/hide the dungeon map (/ra map). It appears when you are indoors."); AddLauncher(launcherGrid, 1, 1, "Items", "🛡", - onClick: () => AvaloniaOverlay.ActivateBarButton("Items")); + onClick: () => PanelRouter.Toggle("Items")); var patrolBtn = AddLauncher(launcherGrid, 1, 2, "Patrol", "⬡", - onClick: () => - { - if (_sendNavCommand == null) TryBind(); - SendNavCmd("{\"Cmd\":\"dunPatrol\"}"); - }); + onClick: () => RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}")); ToolTip.SetTip(patrolBtn, "Left-click: start dungeon patrol. Right-click: routes & recorded hazards."); // Right-click → patrol management flyout (saved routes + recorded dungeon hazards). patrolBtn.PointerPressed += (_, e) => @@ -750,8 +596,7 @@ internal static partial class RynthAiPanel onClick: () => { ClosePicker(); - if (_applyRemoteCommand == null) TryBind(); - SendRemoteCmd("hub", "show"); + RynthAiCommands.ApplyRemoteCommand("hub", "show"); }); ToolTip.SetTip(charBtn, "Open the character hub (ILT Hub) window (/ra hub show)."); @@ -760,8 +605,7 @@ internal static partial class RynthAiPanel onClick: () => { ClosePicker(); - if (_applyRemoteCommand == null) TryBind(); - SendRemoteCmd("remote", "toggle"); + RynthAiCommands.ApplyRemoteCommand("remote", "toggle"); }); ToolTip.SetTip(hudBtn, "Left-click: show/hide the Mini Remote (/ra remote). Right-click: Inventory HUDs setup (/ra huds)."); hudBtn.PointerPressed += (_, e) => @@ -770,8 +614,7 @@ internal static partial class RynthAiPanel { e.Handled = true; ClosePicker(); - if (_applyRemoteCommand == null) TryBind(); - SendRemoteCmd("huds", "show"); + RynthAiCommands.ApplyRemoteCommand("huds", "show"); } }; @@ -897,11 +740,11 @@ internal static partial class RynthAiPanel } profileSelector.Click += (_, _) => - ShowPicker(profileSelector, snap.Profiles, snap.SelectedProfileIdx, idx => _selectProfile?.Invoke(3, idx)); + ShowPicker(profileSelector, snap.Profiles, snap.SelectedProfileIdx, idx => RynthAiCommands.SelectProfile(3, idx)); navSelector.Click += (_, _) => - ShowPicker(navSelector, snap.NavProfiles, snap.SelectedNavIdx, idx => _selectProfile?.Invoke(0, idx)); + ShowPicker(navSelector, snap.NavProfiles, snap.SelectedNavIdx, idx => RynthAiCommands.SelectProfile(0, idx)); lootSelector.Click += (_, _) => - ShowPicker(lootSelector, snap.LootProfiles, snap.SelectedLootIdx, idx => _selectProfile?.Invoke(1, idx)); + ShowPicker(lootSelector, snap.LootProfiles, snap.SelectedLootIdx, idx => RynthAiCommands.SelectProfile(1, idx)); lootEditButton.Click += (_, _) => { ClosePicker(); @@ -909,7 +752,7 @@ internal static partial class RynthAiPanel LaunchLootEditor(path); }; metaSelector.Click += (_, _) => - ShowPicker(metaSelector, snap.MetaProfiles, snap.SelectedMetaIdx, idx => _selectProfile?.Invoke(2, idx)); + ShowPicker(metaSelector, snap.MetaProfiles, snap.SelectedMetaIdx, idx => RynthAiCommands.SelectProfile(2, idx)); // ── Polling timer: refresh from snapshot ──────────────────────────── // 33 ms (~30 Hz) — vital changes feel instant to the eye. The @@ -920,15 +763,6 @@ internal static partial class RynthAiPanel var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(33) }; timer.Tick += (_, _) => { - if (versionPollTicks-- <= 0) // ~every 2 s; the timer runs at 30 Hz - { - versionPollTicks = 60; - string ver = ""; - foreach (var p in PluginManager.Plugins) - if (p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)) { ver = p.VersionString; break; } - if (versionText.Text != ver) versionText.Text = ver; - } - if (_getSnapshotJson == null) TryBind(); // TL;DR #7: signal the popout host (if floating) that a new // snapshot arrived this 33ms tick. Unconditional (not gated on @@ -937,19 +771,37 @@ internal static partial class RynthAiPanel // (was 60Hz via alwaysRender), not further gating below that. MarkDirty?.Invoke(); - snap = ReadSnapshot(); + // Footer: FPS (refreshed once/sec by EndSceneHook) + engine + // gen uptime (re-stamped on every hot-reload). Engine-local, so it + // updates even before the first hub view arrives. + float liveFps = D3D9.EndSceneHook.MeasuredFps; + SetText(fpsText, liveFps > 0 ? $"FPS {liveFps:F0}" : "FPS —"); + DateTime startedUtc = EntryPoint.InitStartedUtc; + if (startedUtc != DateTime.MinValue) + { + TimeSpan up = DateTime.UtcNow - startedUtc; + SetText(uptimeText, up.TotalHours >= 1 + ? $"Up {(int)up.TotalHours}:{up.Minutes:D2}:{up.Seconds:D2}" + : $"Up {up.Minutes}:{up.Seconds:D2}"); + } + SetText(minChip, RynthAiDashboardState.Minimized ? "^" : "_"); + SetText(dockChip, IsFloatingNow?.Invoke() == true ? "↙" : "↗"); + + var current = UiSources.RynthAi.Current; + if (current == null) return; + RynthAiView view = current.Value; + snap = view.Raw; + SetText(versionText, view.Version); // Live-testing finding 2026-09-02: apply the opacity the header // +/- chips set (see ColPanelBg's declaration above). Same 0.1 // floor as the plugin-side clamp so the panel can never fade to // fully invisible/unclickable-looking. - byte bgAlpha = (byte)Math.Clamp(Math.Round(snap.BgOpacity * 255f), 25.5, 255); + byte bgAlpha = view.PanelAlpha; if (ColPanelBg.Color.A != bgAlpha) ColPanelBg.Color = new Color(bgAlpha, ColPanelBg.Color.R, ColPanelBg.Color.G, ColPanelBg.Color.B); SetText(lockChip, snap.IsLocked ? "Unlk" : "Lock"); - SetText(minChip, _avaloniaMinimized ? "^" : "_"); - SetText(dockChip, IsFloatingNow?.Invoke() == true ? "↙" : "↗"); // Mirrors LegacyDashboardRenderer's minimized layout: // • title row (always visible — chips live there) @@ -957,7 +809,7 @@ internal static partial class RynthAiPanel // • inline ON/OFF macro button at top of toggles when minimized // • header grid (macro state, dropdowns) — hidden when minimized // • launcher grid (6 buttons) — hidden when minimized - bool minimized = _avaloniaMinimized; + bool minimized = RynthAiDashboardState.Minimized; headerGrid.IsVisible = !minimized; launcherGrid.IsVisible = !minimized; footerGrid.IsVisible = !minimized; @@ -986,13 +838,13 @@ internal static partial class RynthAiPanel statusDot.Fill = running ? ColGreen : ColMute; statusRing.IsVisible = running; - SetText(metaStateValue, string.IsNullOrWhiteSpace(snap.CurrentState) ? "Default" : snap.CurrentState); - SetText(botActivityValue, string.IsNullOrWhiteSpace(snap.BotAction) || snap.BotAction == "Default" ? "Idle" : snap.BotAction); + SetText(metaStateValue, view.MetaStateText); + SetText(botActivityValue, view.BotActivityText); - SetText(profileSelector, Truncate(snap.SelectedProfile, 16)); - SetText(navSelector, Truncate(snap.CurrentNavName, 16)); - SetText(lootSelector, Truncate(snap.CurrentLootName, 16)); - SetText(metaSelector, Truncate(snap.CurrentMetaName, 16)); + SetText(profileSelector, view.ProfileText); + SetText(navSelector, view.NavText); + SetText(lootSelector, view.LootText); + SetText(metaSelector, view.MetaText); UpdateToggle(combatToggle, snap.CombatEnabled); UpdateToggle(buffToggle, snap.BuffingEnabled); @@ -1001,58 +853,25 @@ internal static partial class RynthAiPanel UpdateMetaToggle(metaToggle, snap.MetaEnabled); // Target headline + segmented bar - string label = string.IsNullOrWhiteSpace(snap.TargetLabel) ? "NO TARGET" : snap.TargetLabel.ToUpperInvariant(); - SetText(targetLabel, Truncate(label, 32)); + SetText(targetLabel, view.TargetHeadline); SetText(targetHp, snap.TargetHealthDisplay); - UpdateSegmentedBar(targetSegments, snap.TargetHealthPercent, ref targetSegLastLit); + UpdateSegmentedBar(targetSegments, view.TargetSegmentsLit, ref targetSegLastLit); - bool showTargetSubBars = snap.ShowTargetStaminaMana && snap.TargetMaxStamina > 0; - targetStRow.IsVisible = showTargetSubBars; - targetMnRow.IsVisible = showTargetSubBars; - if (showTargetSubBars) + targetStRow.IsVisible = view.ShowTargetSubBars; + targetMnRow.IsVisible = view.ShowTargetSubBars; + if (view.ShowTargetSubBars) { - UpdateCompactBar(targetStFill, targetStLabel, "ST", snap.TargetStamina, snap.TargetMaxStamina); - UpdateCompactBar(targetMnFill, targetMnLabel, "MN", snap.TargetMana, snap.TargetMaxMana); + UpdateBar(targetStFill, targetStLabel, view.TargetStamina); + UpdateBar(targetMnFill, targetMnLabel, view.TargetMana); } - // Sticky vitals: keep showing last-known values when the plugin - // briefly returns 0 after a hot reload (host cache is cold for a - // tick or two). Update + persist the cache only when we get a - // real reading. - bool cacheChanged = false; - if (snap.PlayerMaxHealth != 0) { _cachedHp = snap.PlayerHealth; _cachedMaxHp = snap.PlayerMaxHealth; cacheChanged = true; } - if (snap.PlayerMaxStamina != 0) { _cachedSt = snap.PlayerStamina; _cachedMaxSt = snap.PlayerMaxStamina; cacheChanged = true; } - if (snap.PlayerMaxMana != 0) { _cachedMn = snap.PlayerMana; _cachedMaxMn = snap.PlayerMaxMana; cacheChanged = true; } - if (cacheChanged) SaveVitalCache(); - - UpdateVitalRow(hpFill, hpText, "HP", - snap.PlayerMaxHealth != 0 ? snap.PlayerHealth : _cachedHp, - snap.PlayerMaxHealth != 0 ? snap.PlayerMaxHealth : _cachedMaxHp); - UpdateVitalRow(stFill, stText, "ST", - snap.PlayerMaxStamina != 0 ? snap.PlayerStamina : _cachedSt, - snap.PlayerMaxStamina != 0 ? snap.PlayerMaxStamina : _cachedMaxSt); - UpdateVitalRow(mnFill, mnText, "MN", - snap.PlayerMaxMana != 0 ? snap.PlayerMana : _cachedMn, - snap.PlayerMaxMana != 0 ? snap.PlayerMaxMana : _cachedMaxMn); - - // Footer: FPS (refreshed once/sec by EndSceneHook) + engine - // gen uptime (re-stamped on every hot-reload). Cheap to recompute - // every 100 ms — string interpolation only, no native calls. - float liveFps = D3D9.EndSceneHook.MeasuredFps; - SetText(fpsText, liveFps > 0 ? $"FPS {liveFps:F0}" : "FPS —"); - - DateTime startedUtc = EntryPoint.InitStartedUtc; - if (startedUtc != DateTime.MinValue) - { - TimeSpan up = DateTime.UtcNow - startedUtc; - string upStr = up.TotalHours >= 1 - ? $"Up {(int)up.TotalHours}:{up.Minutes:D2}:{up.Seconds:D2}" - : $"Up {up.Minutes}:{up.Seconds:D2}"; - SetText(uptimeText, upStr); - } + // Sticky vitals are applied by the hub (StickyVitals). + UpdateBar(hpFill, hpText, view.Health); + UpdateBar(stFill, stText, view.Stamina); + UpdateBar(mnFill, mnText, view.Mana); }; - timer.Start(); - RynthLog.Info("RynthAiPanel.Create: timer started, returning root"); + // Not started here: AttachedToVisualTree starts it (and subscribes). + RynthLog.Info("RynthAiPanel.Create: returning root"); // BringPanelToFront in AvaloniaOverlay does Remove+Add on the // windowFrame whenever a drag or resize starts — that fires @@ -1061,8 +880,17 @@ internal static partial class RynthAiPanel // killed snapshot polling: numbers froze and dropdown selections // appeared not to change (the click DID reach the plugin, the // panel just never re-polled to refresh the visible label). - root.AttachedToVisualTree += (_, _) => timer.Start(); - root.DetachedFromVisualTree += (_, _) => { timer.Stop(); ClosePicker(); }; + root.AttachedToVisualTree += (_, _) => + { + UiSources.RynthAi.Subscribe(); + timer.Start(); + }; + root.DetachedFromVisualTree += (_, _) => + { + UiSources.RynthAi.Unsubscribe(); + timer.Stop(); + ClosePicker(); + }; return root; } @@ -1142,7 +970,7 @@ internal static partial class RynthAiPanel /// engine module (Runtime\ or Runtime\.engine_loads\) to find it. ShellExecute, not /// Process.Start: the Process API is the documented AV hazard inside acclient.exe. /// </summary> - private static void LaunchLootEditor(string? profilePath) + internal static void LaunchLootEditor(string? profilePath) { try { @@ -1301,14 +1129,9 @@ internal static partial class RynthAiPanel return brushes; } - private static void UpdateSegmentedBar(Rectangle[] segments, float pct, ref int lastLitCount) + private static void UpdateSegmentedBar(Rectangle[] segments, int litCount, ref int lastLitCount) { - float clamped = Math.Clamp(pct, 0f, 1f); int n = segments.Length; - int litCount = 0; - for (int i = 0; i < n; i++) - if ((float)i / n <= clamped) litCount++; - if (litCount == lastLitCount) return; // nothing crossed a segment boundary since the last call — skip entirely @@ -1359,13 +1182,12 @@ internal static partial class RynthAiPanel return grid; } - private static void UpdateCompactBar(Rectangle fill, TextBlock label, string prefix, uint v, uint maxV) + /// <summary>Sizes a bar's fill to the view's fraction and sets its text.</summary> + private static void UpdateBar(Rectangle fill, TextBlock text, VitalView bar) { - double pct = maxV == 0 ? 0 : Math.Clamp((double)v / maxV, 0, 1); - // Width set via parent bounds — bind via width binding using grid actual width if (fill.Parent is Grid g && g.Bounds.Width > 0) - fill.Width = g.Bounds.Width * pct; - SetText(label, $"{prefix} {v}/{maxV}"); + fill.Width = g.Bounds.Width * bar.Fraction; + SetText(text, bar.Text); } private static Grid BuildVitalRow(string icon, IBrush color, out Rectangle fill, out TextBlock text) @@ -1408,15 +1230,6 @@ internal static partial class RynthAiPanel return grid; } - private static void UpdateVitalRow(Rectangle fill, TextBlock text, string label, uint v, uint maxV) - { - double pct = maxV == 0 ? 0 : Math.Clamp((double)v / maxV, 0, 1); - if (fill.Parent is Grid g && g.Bounds.Width > 0) - fill.Width = g.Bounds.Width * pct; - string display = maxV == 0 ? (v == 0 ? "--/--" : $"{v}/--") : $"{v}/{maxV}"; - SetText(text, $"{label}: {(int)(pct * 100)}% ({display})"); - } - /// <summary> /// Splits a single launcher cell into two half-width buttons sitting side /// by side. Used for Nav | Map so the user can pop the navigation panel @@ -1470,6 +1283,14 @@ internal static partial class RynthAiPanel return btn; } + // Monsters opens the Damage panel (the basic Monsters panel and its + // Simple/Advanced chip were retired 2026-10-01). + private static void AddMonstersLauncher(Grid grid, int row, int col) + { + Button open = AddLauncher(grid, row, col, "Monsters", "◎", onClick: PanelRouter.ToggleMonsters); + ToolTip.SetTip(open, "Monsters: weapons, spells and rules per monster (the Damage panel)"); + } + private static void UpdateToggle(Button btn, bool on) { btn.Background = on ? ColTealSoft : ColBarBg; @@ -1484,12 +1305,6 @@ internal static partial class RynthAiPanel btn.Foreground = on ? ColTeal : ColMute; } - private static string Truncate(string? value, int max) - { - if (string.IsNullOrEmpty(value)) return "None"; - return value.Length > max ? value[..(max - 1)] + "…" : value; - } - private static void SetText(TextBlock tb, string s) { if (!string.Equals(tb.Text, s, StringComparison.Ordinal)) tb.Text = s; @@ -1506,197 +1321,6 @@ internal static partial class RynthAiPanel if (!Equals(btn.Content as string, s)) btn.Content = s; } - // ──────────────────────────────────────────────────────────────────────── - // Plugin export binding + snapshot ingest - // ──────────────────────────────────────────────────────────────────────── - - private static int _snapshotDiagsLogged; - private static string _lastLoggedTargetLabel = string.Empty; - private static uint _lastLoggedPlayerHealth; - private static uint _lastLoggedPlayerMaxHealth; - - private static Snapshot ReadSnapshot() - { - if (_getSnapshotJson == null) return new Snapshot(); - - try - { - IntPtr ptr = _getSnapshotJson(); - if (ptr == IntPtr.Zero) return new Snapshot(); - string json = Marshal.PtrToStringAnsi(ptr) ?? string.Empty; - if (string.IsNullOrWhiteSpace(json)) return new Snapshot(); - Snapshot snap = JsonSerializer.Deserialize(json, SnapshotJsonContext.Default.Snapshot) ?? new Snapshot(); - - // Log first 3 snapshots for pipeline-up diagnostic. Then log on - // any change to a vital/target field so we can see when data - // starts flowing post-login without flooding. - if (_snapshotDiagsLogged < 3 || - snap.TargetLabel != _lastLoggedTargetLabel || - snap.PlayerHealth != _lastLoggedPlayerHealth || - snap.PlayerMaxHealth != _lastLoggedPlayerMaxHealth) - { - _snapshotDiagsLogged++; - _lastLoggedTargetLabel = snap.TargetLabel; - _lastLoggedPlayerHealth = snap.PlayerHealth; - _lastLoggedPlayerMaxHealth = snap.PlayerMaxHealth; - RynthLog.Info( - $"RynthAiPanel.ReadSnapshot[{_snapshotDiagsLogged}]: " + - $"player HP={snap.PlayerHealth}/{snap.PlayerMaxHealth} " + - $"ST={snap.PlayerStamina}/{snap.PlayerMaxStamina} " + - $"MN={snap.PlayerMana}/{snap.PlayerMaxMana} " + - $"target='{snap.TargetLabel}' hp={snap.TargetHealth}/{snap.TargetMaxHealth} " + - $"jsonLen={json.Length}"); - } - - return snap; - } - catch (Exception ex) - { - RynthLog.Info($"RynthAiPanel.ReadSnapshot: deserialize threw {ex.GetType().Name}: {ex.Message}"); - return new Snapshot(); - } - } - - // RL loads fresh plugin copies without unloading the old ones: drop the - // exports bound below so the next poll re-binds to the live copy. - static RynthAiPanel() => PluginManager.PluginsUnloaded += () => - { - _getSnapshotJson = null; - _toggleMacro = null; - _setSubsystemEnabled = null; - _selectProfile = null; - _forceRebuff = null; - _cancelForceRebuff = null; - _adjustOpacity = null; - _togglePanelLock = null; - _togglePanelMinimize = null; - _sendNavCommand = null; - _getPatrolInfoJson = null; - _applyRemoteCommand = null; - }; - - private static void TryBind() - { - LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - _getSnapshotJson ??= Bind<GetSnapshotJsonFn>(plugin, "RynthPluginGetSnapshotJson"); - _toggleMacro ??= Bind<VoidFn>(plugin, "RynthPluginToggleMacro"); - _setSubsystemEnabled ??= Bind<IntIntFn>(plugin, "RynthPluginSetSubsystemEnabled"); - _selectProfile ??= Bind<IntIntFn>(plugin, "RynthPluginSelectProfile"); - _forceRebuff ??= Bind<VoidFn>(plugin, "RynthPluginForceRebuff"); - _cancelForceRebuff ??= Bind<VoidFn>(plugin, "RynthPluginCancelForceRebuff"); - _adjustOpacity ??= Bind<FloatFn>(plugin, "RynthPluginAdjustOpacity"); - _togglePanelLock ??= Bind<VoidFn>(plugin, "RynthPluginTogglePanelLock"); - _togglePanelMinimize ??= Bind<VoidFn>(plugin, "RynthPluginTogglePanelMinimize"); - _sendNavCommand ??= Bind<PtrFn>(plugin, "RynthPluginSendNavCommand"); - _getPatrolInfoJson ??= Bind<GetSnapshotJsonFn>(plugin, "RynthPluginGetPatrolInfoJson"); - _applyRemoteCommand ??= Bind<PtrPtrFn>(plugin, "RynthPluginApplyRemoteCommand"); - - if (!_bindingLogged && _getSnapshotJson != null) - { - _bindingLogged = true; - RynthLog.UI("RynthAiPanel: bound RynthAi plugin exports for live dashboard data."); - } - } - - private static T? Bind<T>(LoadedPlugin plugin, string exportName) where T : Delegate - { - IntPtr addr = GetProcAddress(plugin.ModuleHandle, exportName); - return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr); - } - - private static void SendNavCmd(string json) - { - if (_sendNavCommand == null) return; - IntPtr ptr = Marshal.StringToHGlobalAnsi(json); - try { _sendNavCommand(ptr); } - finally { Marshal.FreeHGlobal(ptr); } - } - - /// <summary> - /// Sends an (action, value) pair to RynthPluginApplyRemoteCommand — the same path as - /// typing "/ra <action> <value>". The plugin copies both strings and applies - /// the command on its pump thread, so the buffers can be freed as soon as this returns. - /// </summary> - /// <summary> - /// Lets other engine panels send a "/ra <action> <value>" command to the RynthAi - /// plugin, binding the plugin export first if this panel has not done so yet. - /// </summary> - internal static void SendRynthAiCommand(string action, string value) - { - if (_applyRemoteCommand == null) TryBind(); - SendRemoteCmd(action, value); - } - - private static void SendRemoteCmd(string action, string value) - { - if (_applyRemoteCommand == null) - { - RynthLog.UI($"RynthAiPanel: RynthPluginApplyRemoteCommand not bound; dropped '{action} {value}'."); - return; - } - IntPtr a = Marshal.StringToHGlobalAnsi(action); - IntPtr b = Marshal.StringToHGlobalAnsi(value); - try { _applyRemoteCommand(a, b); } - finally - { - Marshal.FreeHGlobal(a); - Marshal.FreeHGlobal(b); - } - } - - private sealed class Snapshot - { - [JsonPropertyName("macroRunning")] public bool MacroRunning { get; set; } - [JsonPropertyName("currentState")] public string CurrentState { get; set; } = string.Empty; - [JsonPropertyName("botAction")] public string BotAction { get; set; } = string.Empty; - [JsonPropertyName("selectedProfile")] public string SelectedProfile { get; set; } = "Default"; - [JsonPropertyName("profiles")] public string[] Profiles { get; set; } = Array.Empty<string>(); - [JsonPropertyName("navProfiles")] public string[] NavProfiles { get; set; } = Array.Empty<string>(); - [JsonPropertyName("lootProfiles")] public string[] LootProfiles { get; set; } = Array.Empty<string>(); - [JsonPropertyName("metaProfiles")] public string[] MetaProfiles { get; set; } = Array.Empty<string>(); - [JsonPropertyName("currentNavName")] public string CurrentNavName { get; set; } = string.Empty; - [JsonPropertyName("currentLootName")] public string CurrentLootName { get; set; } = string.Empty; - [JsonPropertyName("currentLootPath")] public string CurrentLootPath { get; set; } = string.Empty; - // Set while a vendor is open: the AutoVendor profile it would use (may not exist yet). - [JsonPropertyName("vendorProfilePath")] public string VendorProfilePath { get; set; } = string.Empty; - [JsonPropertyName("currentMetaName")] public string CurrentMetaName { get; set; } = string.Empty; - [JsonPropertyName("selectedNavIdx")] public int SelectedNavIdx { get; set; } - [JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; } - [JsonPropertyName("selectedMetaIdx")] public int SelectedMetaIdx { get; set; } - [JsonPropertyName("selectedProfileIdx")] public int SelectedProfileIdx { get; set; } - [JsonPropertyName("combatEnabled")] public bool CombatEnabled { get; set; } - [JsonPropertyName("buffingEnabled")] public bool BuffingEnabled { get; set; } - [JsonPropertyName("navigationEnabled")] public bool NavigationEnabled { get; set; } - [JsonPropertyName("lootingEnabled")] public bool LootingEnabled { get; set; } - [JsonPropertyName("metaEnabled")] public bool MetaEnabled { get; set; } - [JsonPropertyName("currentTargetId")] public uint CurrentTargetId { get; set; } - [JsonPropertyName("targetLabel")] public string TargetLabel { get; set; } = "NO TARGET"; - [JsonPropertyName("targetHealthPercent")] public float TargetHealthPercent { get; set; } - [JsonPropertyName("targetHealthDisplay")] public string TargetHealthDisplay { get; set; } = "0"; - [JsonPropertyName("targetHealth")] public uint TargetHealth { get; set; } - [JsonPropertyName("targetMaxHealth")] public uint TargetMaxHealth { get; set; } - [JsonPropertyName("targetStamina")] public uint TargetStamina { get; set; } - [JsonPropertyName("targetMaxStamina")] public uint TargetMaxStamina { get; set; } - [JsonPropertyName("targetMana")] public uint TargetMana { get; set; } - [JsonPropertyName("targetMaxMana")] public uint TargetMaxMana { get; set; } - [JsonPropertyName("playerHealth")] public uint PlayerHealth { get; set; } - [JsonPropertyName("playerMaxHealth")] public uint PlayerMaxHealth { get; set; } - [JsonPropertyName("playerStamina")] public uint PlayerStamina { get; set; } - [JsonPropertyName("playerMaxStamina")] public uint PlayerMaxStamina { get; set; } - [JsonPropertyName("playerMana")] public uint PlayerMana { get; set; } - [JsonPropertyName("playerMaxMana")] public uint PlayerMaxMana { get; set; } - [JsonPropertyName("showTargetStaminaMana")] public bool ShowTargetStaminaMana { get; set; } - [JsonPropertyName("isLocked")] public bool IsLocked { get; set; } - [JsonPropertyName("isMinimized")] public bool IsMinimized { get; set; } - [JsonPropertyName("bgOpacity")] public float BgOpacity { get; set; } = 0.95f; - } - - [JsonSerializable(typeof(Snapshot))] - private sealed partial class SnapshotJsonContext : JsonSerializerContext { } - // ──────────────────────────────────────────────────────────────────────── // Patrol management flyout (right-click the Patrol launcher button) // ──────────────────────────────────────────────────────────────────────── @@ -1705,6 +1329,17 @@ internal static partial class RynthAiPanel { var root = new StackPanel { Orientation = Orientation.Vertical, Spacing = 4, Width = 244, Margin = new Thickness(8) }; PopulatePatrolFlyout(root); + // Patrol info comes from the hub (single-consumer export): subscribe + // while the flyout is open and repopulate when it changes. + long seen = UiSources.Patrol.Current?.Version ?? -1; + var poll = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(150) }; + poll.Tick += (_, _) => + { + var cur = UiSources.Patrol.Current; + if (cur == null || cur.Version == seen) return; + seen = cur.Version; + PopulatePatrolFlyout(root); + }; var scroll = new ScrollViewer { Content = root, @@ -1716,13 +1351,15 @@ internal static partial class RynthAiPanel Content = scroll, Placement = PlacementMode.Top, }; + flyout.Opened += (_, _) => { UiSources.Patrol.Subscribe(); UiSources.Patrol.RequestRefresh(); poll.Start(); }; + flyout.Closed += (_, _) => { poll.Stop(); UiSources.Patrol.Unsubscribe(); }; flyout.ShowAt(anchor); } private static void PopulatePatrolFlyout(StackPanel root) { root.Children.Clear(); - PatrolInfo info = FetchPatrolInfo(); + PatrolInfo info = UiSources.Patrol.Current?.Value ?? new PatrolInfo(); root.Children.Add(new TextBlock { @@ -1744,8 +1381,7 @@ internal static partial class RynthAiPanel var clear = MiniButton("Clear"); clear.Click += (_, _) => { - SendNavCmd($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{info.CurrentLandblock}\"}}"); - PopulatePatrolFlyout(root); + RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{info.CurrentLandblock}\"}}", refreshPatrol: true); }; Grid.SetColumn(clear, 1); row.Children.Add(clear); @@ -1756,9 +1392,9 @@ internal static partial class RynthAiPanel // environmental lava/acid the name detector can't see. var markRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Margin = new Thickness(0, 2, 0, 0) }; var mark = MiniButton("Mark cell as hazard"); - mark.Click += (_, _) => { SendNavCmd("{\"Cmd\":\"markHazardHere\"}"); PopulatePatrolFlyout(root); }; + mark.Click += (_, _) => RynthAiCommands.SendNavCommand("{\"Cmd\":\"markHazardHere\"}", refreshPatrol: true); var unmark = MiniButton("Unmark"); - unmark.Click += (_, _) => { SendNavCmd("{\"Cmd\":\"unmarkHazardHere\"}"); PopulatePatrolFlyout(root); }; + unmark.Click += (_, _) => RynthAiCommands.SendNavCommand("{\"Cmd\":\"unmarkHazardHere\"}", refreshPatrol: true); markRow.Children.Add(mark); markRow.Children.Add(unmark); root.Children.Add(markRow); @@ -1781,7 +1417,7 @@ internal static partial class RynthAiPanel } else { - foreach (DungeonHaz d in info.Dungeons) + foreach (DungeonHazards d in info.Dungeons) { var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; row.Children.Add(new TextBlock @@ -1792,8 +1428,7 @@ internal static partial class RynthAiPanel var clear = MiniButton("Clear"); clear.Click += (_, _) => { - SendNavCmd($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{d.Landblock}\"}}"); - PopulatePatrolFlyout(root); + RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{d.Landblock}\"}}", refreshPatrol: true); }; Grid.SetColumn(clear, 1); row.Children.Add(clear); @@ -1805,8 +1440,7 @@ internal static partial class RynthAiPanel clearAll.Margin = new Thickness(0, 3, 0, 0); clearAll.Click += (_, _) => { - SendNavCmd("{\"Cmd\":\"clearHazardsAll\"}"); - PopulatePatrolFlyout(root); + RynthAiCommands.SendNavCommand("{\"Cmd\":\"clearHazardsAll\"}", refreshPatrol: true); }; root.Children.Add(clearAll); } @@ -1842,36 +1476,4 @@ internal static partial class RynthAiPanel HorizontalContentAlignment = HorizontalAlignment.Center, }; - private static PatrolInfo FetchPatrolInfo() - { - if (_getPatrolInfoJson == null) TryBind(); - if (_getPatrolInfoJson == null) return new PatrolInfo(); - try - { - IntPtr p = _getPatrolInfoJson(); - if (p == IntPtr.Zero) return new PatrolInfo(); - string json = Marshal.PtrToStringAnsi(p) ?? "{}"; - return JsonSerializer.Deserialize(json, PatrolJsonContext.Default.PatrolInfo) ?? new PatrolInfo(); - } - catch { return new PatrolInfo(); } - } - - private sealed class PatrolInfo - { - [JsonPropertyName("inDungeon")] public bool InDungeon { get; set; } - [JsonPropertyName("currentLandblock")] public string CurrentLandblock { get; set; } = "0000"; - [JsonPropertyName("currentHazards")] public int CurrentHazards { get; set; } - [JsonPropertyName("liveHazards")] public int LiveHazards { get; set; } - [JsonPropertyName("dungeons")] public DungeonHaz[] Dungeons { get; set; } = Array.Empty<DungeonHaz>(); - [JsonPropertyName("routes")] public string[] Routes { get; set; } = Array.Empty<string>(); - } - - private sealed class DungeonHaz - { - [JsonPropertyName("landblock")] public string Landblock { get; set; } = "0000"; - [JsonPropertyName("cells")] public int Cells { get; set; } - } - - [JsonSerializable(typeof(PatrolInfo))] - private sealed partial class PatrolJsonContext : JsonSerializerContext { } } diff --git a/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs index a7b6694..4588fba 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs @@ -1,21 +1,21 @@ // ============================================================================ // RynthCore.Engine — UI/Panels/RynthChatFiltersPanel.cs -// Editor for RynthChat filters. Registered as its own "ChatFilters" panel -// (dockable/floatable). +// Standalone editor for RynthChat regex filter rules. Registered as its own +// "ChatFilters" panel (dockable/floatable) — rules get complex enough that +// a small overlay inside the chat panel doesn't cut it. // -// Two pages: -// • Standard — canned UB-IT-style filters (RynthChatPresets) grouped by -// Combat / Casting / Items / Social / NPCs / Pets. Tick to hide; type a -// tab name to move the lines there instead. Searchable. -// • Custom — user rules. Match mode Contains / Starts with / Ends with -// (plain text, no regex needed) or Regex. First match wins (▲▼ reorder). -// A tester at the bottom shows which filter would catch a pasted line. -// -// Evaluation order (RynthChatPanel.EffectiveTab): custom rules, then presets. -// Tab set → matching lines MOVE to that tab (still visible in All). -// Tab empty → matching lines are hidden everywhere. -// No ComboBox / popups: the overlay's popup hosting is unreliable, so -// pickers are click-to-cycle buttons. +// Rule semantics (the rules live in ChatModel, UI/Data/ChatData.cs; the ImGui +// face is ImGui/Panels/ChatFiltersFace.cs): +// • Regex, or plain text Contains / Starts with / Ends with (the mode +// button), case-insensitive. +// • Standard filters (RynthChatPresets) below the rules apply only to +// lines no rule moved or hid. +// • FIRST matching rule wins — order matters, hence the ▲▼ buttons. +// • Tab name set → matching lines MOVE to that tab (and leave All). +// • Tab name empty → matching lines are hidden everywhere. +// Since 2026-09-29 rules can also copy and colour (action, when, colour); +// only the ImGui face edits those. Editing a tab here makes the rule a plain +// Move (or Hide when empty) again. // ============================================================================ using System; @@ -26,6 +26,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Layout; using Avalonia.Media; using RynthCore.Engine.ImGuiBackend; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; @@ -36,96 +37,39 @@ internal static class RynthChatFiltersPanel private static readonly IBrush FieldBorder = new SolidColorBrush(Color.FromArgb(0xFF, 0x26, 0x40, 0x59)); private static readonly IBrush AccentBg = new SolidColorBrush(Color.FromArgb(0xFF, 0x26, 0x4C, 0x59)); private static readonly IBrush ButtonBg = new SolidColorBrush(Color.FromArgb(0xFF, 0x0F, 0x1F, 0x2E)); - private static readonly IBrush GroupFg = new SolidColorBrush(Color.FromArgb(0xFF, 0xE6, 0xB4, 0x50)); - private static readonly IBrush ResultFg = new SolidColorBrush(Color.FromArgb(0xFF, 0x9F, 0xD8, 0xFF)); - - // Channels the tester can pretend a line arrived on (must match the plugin's ChatClassifier names). - private static readonly string[] TestChannels = { "System", "Combat", "Chat", "Channels", "Other" }; - - private static readonly string[] ModeLabels = { "Regex", "Contains", "Starts with", "Ends with" }; internal static Control Create() { - RynthChatPanel.EnsureSettingsLoaded(); - - bool showStandard = true; - string search = ""; - - // ── Page switcher + search ─────────────────────────────────────── - var standardBtn = PageButton("Standard filters"); - var customBtn = PageButton("Custom rules"); - var searchBox = Field("search standard filters…", 170); - var header = new StackPanel - { - Orientation = Orientation.Horizontal, - Spacing = 4, - Margin = new Thickness(4, 4, 4, 2), - Children = { standardBtn, customBtn, searchBox }, - }; + ChatModel.EnsureSettingsLoaded(); var hint = new TextBlock { + Text = "Regex rules, case-insensitive — FIRST match wins (reorder with ▲▼).\n" + + "Tab set: matching lines move to that tab (and leave All).\n" + + "Tab empty: matching lines are hidden everywhere.", FontSize = 9, Foreground = Brushes.Gray, - Margin = new Thickness(4, 0, 4, 2), - TextWrapping = TextWrapping.Wrap, + Margin = new Thickness(4, 4, 4, 2), }; - var rows = new StackPanel { Orientation = Orientation.Vertical, Spacing = 3, Margin = new Thickness(4) }; + var rows = new StackPanel { Orientation = Orientation.Vertical, Spacing = 4, Margin = new Thickness(4) }; var addBtn = new Button { - Content = "+ Add rule", + Content = "+ Add filter", FontSize = 10, Padding = new Thickness(8, 3), - Margin = new Thickness(4, 2, 4, 2), + Margin = new Thickness(4, 2, 4, 6), Background = AccentBg, Foreground = Brushes.White, BorderThickness = new Thickness(0), }; - // ── Tester ─────────────────────────────────────────────────────── - int testChannel = 0; - var testBox = Field("test: paste a chat line here", 260); - var testChanBtn = SmallBtn($"as {TestChannels[0]}", Brushes.White); - ToolTip.SetTip(testChanBtn, "Channel the test line is treated as arriving on (click to change)."); - var makeRuleBtn = SmallBtn("Make rule", Brushes.White); - ToolTip.SetTip(makeRuleBtn, "Create a custom 'Contains' rule from the test text (trim it down to the part that matters)."); - var testResult = new TextBlock - { - FontSize = 10, - Foreground = ResultFg, - Margin = new Thickness(4, 0, 4, 4), - TextWrapping = TextWrapping.Wrap, - }; - var testPanel = new StackPanel - { - Orientation = Orientation.Vertical, - Children = - { - new StackPanel - { - Orientation = Orientation.Horizontal, - Spacing = 4, - Margin = new Thickness(4, 2, 4, 2), - Children = { testBox, testChanBtn, makeRuleBtn }, - }, - testResult, - }, - }; - - void RefreshTest() => - testResult.Text = RynthChatPanel.DescribeTestLine(testBox.Text ?? "", TestChannels[testChannel]); - - var bottom = new StackPanel { Orientation = Orientation.Vertical, Children = { addBtn, testPanel } }; - var layout = new DockPanel { Background = PanelBg }; - DockPanel.SetDock(header, Dock.Top); DockPanel.SetDock(hint, Dock.Top); - DockPanel.SetDock(bottom, Dock.Bottom); - layout.Children.Add(header); + DockPanel.SetDock(addBtn, Dock.Bottom); layout.Children.Add(hint); - layout.Children.Add(bottom); + layout.Children.Add(addBtn); layout.Children.Add(new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, @@ -133,66 +77,176 @@ internal static class RynthChatFiltersPanel Content = rows, }); - void Changed() - { - RynthChatPanel.NotifyFiltersChanged(); - RefreshTest(); - } - - // ── Standard page ──────────────────────────────────────────────── - void BuildStandard() + void RebuildRows() { + var filters = ChatModel.Filters; rows.Children.Clear(); - foreach (string group in RynthChatPresets.Groups) + for (int i = 0; i < filters.Length; i++) { - var presets = RynthChatPresets.All - .Where(p => p.Group == group && MatchesSearch(p, search)) - .ToList(); - if (presets.Count == 0) continue; + var r = filters[i]; + int index = i; - int on = RynthChatPresets.All.Count(p => p.Group == group && p.Enabled); - int total = RynthChatPresets.All.Count(p => p.Group == group); - var allOn = SmallBtn("All on", Brushes.White); - var allOff = SmallBtn("All off", Brushes.White); - string g = group; - allOn.Click += (_, _) => + var enabledCheck = new CheckBox { - foreach (var p in RynthChatPresets.All.Where(p => p.Group == g)) p.Enabled = true; - Changed(); - BuildStandard(); + IsChecked = r.Enabled, + Margin = new Thickness(0, 0, 2, 0), + VerticalAlignment = VerticalAlignment.Center, }; - allOff.Click += (_, _) => + enabledCheck.IsCheckedChanged += (_, _) => { - foreach (var p in RynthChatPresets.All.Where(p => p.Group == g)) p.Enabled = false; - Changed(); - BuildStandard(); + r.Enabled = enabledCheck.IsChecked == true; + ChatModel.FiltersChanged(); }; + + // Click-to-cycle (no ComboBox: the overlay's popup hosting is unreliable). + var modeBtn = new Button + { + Content = ModeLabels[(int)r.Mode], + FontSize = 10, + Width = 62, + Padding = new Thickness(4, 2), + Background = ButtonBg, + Foreground = Brushes.White, + BorderThickness = new Thickness(0), + VerticalAlignment = VerticalAlignment.Center, + }; + ToolTip.SetTip(modeBtn, "How the text is matched: Regex, or plain text Contains / Starts with / Ends with."); + + var patternBox = new TextBox + { + Text = r.Pattern, + Watermark = PatternWatermark(r.Mode), + FontSize = 10, + MinWidth = 220, + Height = 24, + Background = FieldBg, + Foreground = Brushes.White, + BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder, + BorderThickness = new Thickness(1), + }; + ScrollViewer.SetHorizontalScrollBarVisibility(patternBox, ScrollBarVisibility.Disabled); + ScrollViewer.SetVerticalScrollBarVisibility(patternBox, ScrollBarVisibility.Disabled); + patternBox.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true; + patternBox.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false; + patternBox.TextChanged += (_, _) => + { + r.Pattern = patternBox.Text ?? ""; + r.Recompile(); + patternBox.BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder; + ChatModel.FiltersChanged(); + }; + modeBtn.Click += (_, _) => + { + r.Mode = (ChatMatchMode)(((int)r.Mode + 1) % ModeLabels.Length); + r.Recompile(); + modeBtn.Content = ModeLabels[(int)r.Mode]; + patternBox.Watermark = PatternWatermark(r.Mode); + patternBox.BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder; + ChatModel.FiltersChanged(); + }; + + var tabBox = new TextBox + { + Text = r.Tab, + Watermark = "tab (empty = hide)", + FontSize = 10, + Width = 120, + Height = 24, + Background = FieldBg, + Foreground = Brushes.White, + BorderBrush = FieldBorder, + BorderThickness = new Thickness(1), + }; + ScrollViewer.SetHorizontalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled); + ScrollViewer.SetVerticalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled); + tabBox.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true; + tabBox.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false; + tabBox.TextChanged += (_, _) => + { + r.Tab = (tabBox.Text ?? "").Trim(); + r.Action = r.Tab.Length == 0 ? ChatRuleAction.Hide : ChatRuleAction.Move; + ChatModel.FiltersChanged(); + }; + + Button SmallBtn(string label, IBrush fg) => new() + { + Content = label, + FontSize = 10, + Padding = new Thickness(5, 2), + Background = ButtonBg, + Foreground = fg, + BorderThickness = new Thickness(0), + VerticalAlignment = VerticalAlignment.Center, + }; + + var upBtn = SmallBtn("▲", Brushes.White); + upBtn.IsEnabled = index > 0; + upBtn.Click += (_, _) => + { + ChatModel.MoveFilter(r, -1); + RebuildRows(); + }; + + var downBtn = SmallBtn("▼", Brushes.White); + downBtn.IsEnabled = index < filters.Length - 1; + downBtn.Click += (_, _) => + { + ChatModel.MoveFilter(r, +1); + RebuildRows(); + }; + + var delBtn = SmallBtn("Delete", Brushes.IndianRed); + delBtn.Click += (_, _) => + { + ChatModel.EditFilters(list => list.Remove(r)); + RebuildRows(); + }; + rows.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, - Spacing = 6, - Margin = new Thickness(0, 6, 0, 1), - Children = - { - new TextBlock - { - Text = $"{group} ({on}/{total} on)", - FontSize = 11, - FontWeight = FontWeight.Bold, - Foreground = GroupFg, - VerticalAlignment = VerticalAlignment.Center, - }, - allOn, - allOff, - }, + Spacing = 4, + Children = { enabledCheck, modeBtn, patternBox, tabBox, upBtn, downBtn, delBtn }, }); - - foreach (var preset in presets) - rows.Children.Add(PresetRow(preset)); } - if (rows.Children.Count == 0) - rows.Children.Add(Muted($"No standard filter matches \"{search}\".")); + if (filters.Length == 0) + { + rows.Children.Add(new TextBlock + { + Text = "No filters yet — click \"+ Add filter\".", + FontSize = 10, + Foreground = Brushes.Gray, + Margin = new Thickness(2, 6), + }); + } + + AddStandardFilters(); + } + + // Canned UB-IT-style filters (RynthChatPresets), checked after the rules above. + void AddStandardFilters() + { + rows.Children.Add(new TextBlock + { + Text = "Standard filters — tick to hide; type a tab to move the lines there instead.", + FontSize = 10, + FontWeight = FontWeight.Bold, + Foreground = Brushes.White, + Margin = new Thickness(2, 10, 2, 2), + }); + foreach (string group in RynthChatPresets.Groups) + { + rows.Children.Add(new TextBlock + { + Text = group, + FontSize = 10, + Foreground = Brushes.LightSteelBlue, + Margin = new Thickness(2, 6, 2, 0), + }); + foreach (var p in RynthChatPresets.All.Where(p => p.Group == group)) + rows.Children.Add(PresetRow(p)); + } } Control PresetRow(RynthChatPresets.Preset p) @@ -201,23 +255,36 @@ internal static class RynthChatFiltersPanel { IsChecked = p.Enabled, Content = new TextBlock { Text = p.Label, FontSize = 10, Foreground = Brushes.White }, - MinWidth = 210, VerticalAlignment = VerticalAlignment.Center, + MinWidth = 220, }; - ToolTip.SetTip(check, $"{p.Description}\n\nExample:\n{p.Example}"); + ToolTip.SetTip(check, $"{p.Description}\nExample: {p.Example}"); check.IsCheckedChanged += (_, _) => { p.Enabled = check.IsChecked == true; - Changed(); + ChatModel.FiltersChanged(); }; - var tabBox = Field("hide", 110); - tabBox.Text = p.Tab; - ToolTip.SetTip(tabBox, "Leave empty to hide these lines. Type a tab name to move them to that tab instead."); + var tabBox = new TextBox + { + Text = p.Tab, + Watermark = "tab (empty = hide)", + FontSize = 10, + Width = 120, + Height = 24, + Background = FieldBg, + Foreground = Brushes.White, + BorderBrush = FieldBorder, + BorderThickness = new Thickness(1), + }; + ScrollViewer.SetHorizontalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled); + ScrollViewer.SetVerticalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled); + tabBox.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true; + tabBox.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false; tabBox.TextChanged += (_, _) => { p.Tab = (tabBox.Text ?? "").Trim(); - if (p.Enabled) Changed(); + ChatModel.FiltersChanged(); }; return new StackPanel @@ -229,231 +296,43 @@ internal static class RynthChatFiltersPanel }; } - // ── Custom page ────────────────────────────────────────────────── - void BuildCustom() - { - var filters = RynthChatPanel.Filters; - rows.Children.Clear(); - for (int i = 0; i < filters.Count; i++) - rows.Children.Add(CustomRow(filters, i)); - if (filters.Count == 0) - rows.Children.Add(Muted("No custom rules yet — click \"+ Add rule\", or use \"Make rule\" on a test line.")); - } - - Control CustomRow(System.Collections.Generic.List<RynthChatPanel.ChatFilterRule> filters, int index) - { - var r = filters[index]; - - var enabledCheck = new CheckBox - { - IsChecked = r.Enabled, - Margin = new Thickness(0, 0, 2, 0), - VerticalAlignment = VerticalAlignment.Center, - }; - enabledCheck.IsCheckedChanged += (_, _) => - { - r.Enabled = enabledCheck.IsChecked == true; - Changed(); - }; - - var modeBtn = SmallBtn(ModeLabels[(int)r.Mode], Brushes.White); - modeBtn.MinWidth = 72; - ToolTip.SetTip(modeBtn, "Click to change how the text is matched.\n" + - "Contains / Starts with / Ends with: plain text, case-insensitive.\n" + - "Regex: regular expression against \"hh:mm:ss Sender: message\"."); - - var patternBox = Field(PatternWatermark(r.Mode), 210); - patternBox.Text = r.Pattern; - patternBox.BorderBrush = r.Invalid && r.Pattern.Length > 0 ? Brushes.IndianRed : FieldBorder; - patternBox.TextChanged += (_, _) => - { - r.Pattern = patternBox.Text ?? ""; - r.Recompile(); - patternBox.BorderBrush = r.Invalid && r.Pattern.Length > 0 ? Brushes.IndianRed : FieldBorder; - Changed(); - }; - - modeBtn.Click += (_, _) => - { - r.Mode = (RynthChatPanel.FilterMatchMode)(((int)r.Mode + 1) % ModeLabels.Length); - modeBtn.Content = ModeLabels[(int)r.Mode]; - patternBox.Watermark = PatternWatermark(r.Mode); - r.Recompile(); - patternBox.BorderBrush = r.Invalid && r.Pattern.Length > 0 ? Brushes.IndianRed : FieldBorder; - Changed(); - }; - - var tabBox = Field("hide", 100); - tabBox.Text = r.Tab; - ToolTip.SetTip(tabBox, "Leave empty to hide matching lines. Type a tab name to move them to that tab."); - tabBox.TextChanged += (_, _) => - { - r.Tab = (tabBox.Text ?? "").Trim(); - Changed(); - }; - - var upBtn = SmallBtn("▲", Brushes.White); - upBtn.IsEnabled = index > 0; - upBtn.Click += (_, _) => - { - if (index <= 0) return; - filters.RemoveAt(index); - filters.Insert(index - 1, r); - BuildCustom(); - Changed(); - }; - - var downBtn = SmallBtn("▼", Brushes.White); - downBtn.IsEnabled = index < filters.Count - 1; - downBtn.Click += (_, _) => - { - if (index >= filters.Count - 1) return; - filters.RemoveAt(index); - filters.Insert(index + 1, r); - BuildCustom(); - Changed(); - }; - - var delBtn = SmallBtn("Delete", Brushes.IndianRed); - delBtn.Click += (_, _) => - { - filters.Remove(r); - BuildCustom(); - Changed(); - }; - - return new StackPanel - { - Orientation = Orientation.Horizontal, - Spacing = 4, - Children = { enabledCheck, modeBtn, patternBox, tabBox, upBtn, downBtn, delBtn }, - }; - } - - // ── Page switching ─────────────────────────────────────────────── - void ShowPage() - { - standardBtn.Background = showStandard ? AccentBg : ButtonBg; - customBtn.Background = showStandard ? ButtonBg : AccentBg; - searchBox.IsVisible = showStandard; - addBtn.IsVisible = !showStandard; - hint.Text = showStandard - ? "Tick a box to hide those lines. Type a tab name next to it to move them to that tab instead. " + - "Hover a filter for an example line. Custom rules are checked before these." - : "Plain-text rules need no regex: pick Contains / Starts with / Ends with (click the mode button). " + - "First matching rule wins — reorder with ▲▼. Empty tab = hide; a tab name = move there."; - if (showStandard) BuildStandard(); else BuildCustom(); - } - - standardBtn.Click += (_, _) => { showStandard = true; ShowPage(); }; - customBtn.Click += (_, _) => { showStandard = false; ShowPage(); }; - searchBox.TextChanged += (_, _) => - { - search = (searchBox.Text ?? "").Trim(); - if (showStandard) BuildStandard(); - }; - addBtn.Click += (_, _) => { - // New rules default to Contains — the easiest mode for non-regex users. - var rule = new RynthChatPanel.ChatFilterRule { Mode = RynthChatPanel.FilterMatchMode.Contains }; + var rule = new ChatFilterRule(); rule.Recompile(); - RynthChatPanel.Filters.Add(rule); - BuildCustom(); - // Empty pattern is inert until typed; persisting keeps the row across a relaunch mid-edit. - Changed(); + // Empty pattern is inert until typed — no display change yet, but + // persist the row so it survives a relaunch mid-edit. + ChatModel.EditFilters(list => list.Add(rule)); + RebuildRows(); }; - testBox.TextChanged += (_, _) => RefreshTest(); - testChanBtn.Click += (_, _) => + // The other face (ImGui) may change the rules too. + long seen = ChatModel.FiltersVersion; + var timer = new Avalonia.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) }; + timer.Tick += (_, _) => { - testChannel = (testChannel + 1) % TestChannels.Length; - testChanBtn.Content = $"as {TestChannels[testChannel]}"; - RefreshTest(); - }; - makeRuleBtn.Click += (_, _) => - { - string text = (testBox.Text ?? "").Trim(); - if (text.Length == 0) return; - var rule = new RynthChatPanel.ChatFilterRule { Mode = RynthChatPanel.FilterMatchMode.Contains, Pattern = text }; - rule.Recompile(); - RynthChatPanel.Filters.Add(rule); - showStandard = false; - ShowPage(); - Changed(); + long v = ChatModel.FiltersVersion; + if (v == seen) return; + seen = v; + // Don't rebuild under the user's typing (a keystroke bumps the version too). + if (Win32Backend.AvaloniaTextInputActive && layout.IsKeyboardFocusWithin) return; + RebuildRows(); }; + layout.AttachedToVisualTree += (_, _) => { seen = ChatModel.FiltersVersion; RebuildRows(); timer.Start(); }; + layout.DetachedFromVisualTree += (_, _) => timer.Stop(); - ShowPage(); - RefreshTest(); + RebuildRows(); return layout; } - // ── Helpers ────────────────────────────────────────────────────────── + /// <summary>Button captions, indexed by <see cref="ChatMatchMode"/>.</summary> + private static readonly string[] ModeLabels = { "Regex", "Contains", "Starts", "Ends" }; - private static bool MatchesSearch(RynthChatPresets.Preset p, string search) => - search.Length == 0 - || p.Label.Contains(search, StringComparison.OrdinalIgnoreCase) - || p.Description.Contains(search, StringComparison.OrdinalIgnoreCase) - || p.Example.Contains(search, StringComparison.OrdinalIgnoreCase) - || p.Group.Contains(search, StringComparison.OrdinalIgnoreCase); - - private static string PatternWatermark(RynthChatPanel.FilterMatchMode mode) => mode switch + private static string PatternWatermark(ChatMatchMode mode) => mode switch { - RynthChatPanel.FilterMatchMode.Contains => "text anywhere in the line", - RynthChatPanel.FilterMatchMode.StartsWith => "line starts with…", - RynthChatPanel.FilterMatchMode.EndsWith => "line ends with…", - _ => "regex (e.g. AutoRun)", - }; - - /// <summary>Single-line text box that hands keyboard input to Avalonia while focused.</summary> - private static TextBox Field(string watermark, double width) - { - var box = new TextBox - { - Watermark = watermark, - FontSize = 10, - Width = width, - Height = 24, - Background = FieldBg, - Foreground = Brushes.White, - BorderBrush = FieldBorder, - BorderThickness = new Thickness(1), - }; - ScrollViewer.SetHorizontalScrollBarVisibility(box, ScrollBarVisibility.Disabled); - ScrollViewer.SetVerticalScrollBarVisibility(box, ScrollBarVisibility.Disabled); - box.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true; - box.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false; - return box; - } - - private static Button SmallBtn(string label, IBrush fg) => new() - { - Content = label, - FontSize = 10, - Padding = new Thickness(5, 2), - Background = ButtonBg, - Foreground = fg, - BorderThickness = new Thickness(0), - VerticalAlignment = VerticalAlignment.Center, - }; - - private static Button PageButton(string label) => new() - { - Content = label, - FontSize = 10, - Padding = new Thickness(8, 3), - Background = ButtonBg, - Foreground = Brushes.White, - BorderThickness = new Thickness(0), - VerticalAlignment = VerticalAlignment.Center, - }; - - private static TextBlock Muted(string text) => new() - { - Text = text, - FontSize = 10, - Foreground = Brushes.Gray, - Margin = new Thickness(2, 6), - TextWrapping = TextWrapping.Wrap, + ChatMatchMode.Contains => "text anywhere in the line", + ChatMatchMode.StartsWith => "line starts with...", + ChatMatchMode.EndsWith => "line ends with...", + _ => "regex (e.g. AutoRun)", }; } diff --git a/src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs index bc78c59..2ada387 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs @@ -1,34 +1,24 @@ // ============================================================================ // RynthCore.Engine — UI/Panels/RynthChatPanel.cs -// Avalonia chat-replacement panel backed by the RynthChat plugin (RynthSuite). +// Avalonia face of RynthChat (the popped-out chat; docked it's +// ImGui/Panels/ChatFace.cs). Both read the same state (UI/Data/ChatData.cs): // -// Phase 1: read-only display alongside retail chat (retail not yet suppressed). // • Per-channel tabs: All / Chat / Channels / System / Combat / Rynth / Other // plus user-defined tabs fed by regex filter rules -// • Filter rules (custom Contains / Starts with / Ends with / Regex, plus -// canned standard filters in RynthChatPresets): move matching lines to a -// custom tab, or hide them -// • Per-channel accent colors + timestamps -// • Auto-scroll to tail -// • Search/filter TextBox (wired; typing requires mouse hover — Phase 4 fix) +// • Per-channel accent colors + timestamps, auto-scroll to the tail +// • Search box // • Mouse line-selection: drag across lines to highlight, copies to the // Windows clipboard on release (works docked and floating — keyboard // stays with the game, so copy is mouse-driven by design) -// • Incremental polling via RynthChatGetScrollbackJson(sinceSeq) every 100 ms +// • The input line: ChatModel owns it (Win32Backend's chat keys); this +// face only shows it // -// Bridge exports (resolved from the RynthChat plugin DLL via GetProcAddress): -// RynthChatGetScrollbackJson(ulong sinceSeq) → ANSI JSON array of new lines -// RynthChatSendLine(char* ansiText) → submit via InvokeChatParser (Phase 5) +// Lines come from UiSources.Chat (RynthChatGetScrollbackJson on the pump). // ============================================================================ using System; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Runtime.InteropServices; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Text.RegularExpressions; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; @@ -39,62 +29,12 @@ using Avalonia.Threading; using Avalonia.VisualTree; using RynthCore.Engine.Compatibility; using RynthCore.Engine.ImGuiBackend; -using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; internal static class RynthChatPanel { - // ── P/Invoke ────────────────────────────────────────────────────────── - - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - - // Win32 clipboard — Avalonia's clipboard service is unreliable inside the - // injected acclient process (no proper TopLevel ownership), so write - // CF_UNICODETEXT directly. - [DllImport("user32.dll")] private static extern bool OpenClipboard(IntPtr hWndNewOwner); - [DllImport("user32.dll")] private static extern bool CloseClipboard(); - [DllImport("user32.dll")] private static extern bool EmptyClipboard(); - [DllImport("user32.dll")] private static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem); - [DllImport("kernel32.dll")] private static extern IntPtr GlobalAlloc(uint uFlags, UIntPtr dwBytes); - [DllImport("kernel32.dll")] private static extern IntPtr GlobalLock(IntPtr hMem); - [DllImport("kernel32.dll")] private static extern bool GlobalUnlock(IntPtr hMem); - [DllImport("kernel32.dll")] private static extern IntPtr GlobalFree(IntPtr hMem); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate IntPtr GetScrollbackJsonFn(ulong sinceSeq); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void SendLineFn(IntPtr ansiText); - - // ── Bridge state ───────────────────────────────────────────────────── - - private static GetScrollbackJsonFn? _getScrollbackJson; - private static SendLineFn? _sendLine; - private static bool _bindingLogged; - - // ── Runtime state (Avalonia UI thread only) ────────────────────────── - - private static ulong _lastSeq; - private static readonly List<ChatDisplayLine> _allLines = new(500); - private static string _activeChannel = "All"; - private static string _searchFilter = ""; - // Game-thread state for the chat input — all fields written only from WndProcHook callbacks. - private static string _captureText = ""; - private static int _cursorPos; - private static readonly List<string> _history = new(); - private static int _historyIndex = -1; - - // ── Chat display settings ───────────────────────────────────────────── - private static double _chatFontSize = 10.0; - private static byte _backgroundAlpha = 0xF2; - private static bool _autoScroll = true; - // Live-testing finding 2026-09-02: click-through toggle, mirrors - // RadarPanel.CtrlGatedClickThrough. Mirrored into - // AvaloniaOverlay.ChatCtrlGatedClickThrough (the actual hit-test gate) - // wherever this is set — see the checkbox handler and LoadSettings. - internal static bool CtrlGatedClickThrough; // Runtime: true while the view is pinned to the newest line. Cleared when the // user scrolls up so incoming lines stop yanking the view back to the tail. private static bool _stickToBottom = true; @@ -102,158 +42,6 @@ internal static class RynthChatPanel // ScrollToEnd landing a line short under deferred layout without dropping follow. private const double ScrollStickThresholdPx = 24.0; - // ── Regex filter rules + custom tabs (Avalonia UI thread only) ──────── - // - // Each rule is a regex matched against the formatted line. First match - // wins. An empty Tab means "hide the line entirely"; otherwise the line - // is MOVED to that tab (it leaves its original channel tab but still - // shows under "All"). Rules are edited in the separate "ChatFilters" - // panel (RynthChatFiltersPanel); the lists live here because the chat - // panel owns persistence and display routing. - private static readonly List<ChatFilterRule> _filters = new(); - private static readonly List<string> _customTabs = new(); - private static bool _settingsLoaded; - // Set by Create(): rebuilds tab strip + display. Invoked (via - // NotifyFiltersChanged) when the filters panel mutates the rule list. - private static Action? _onFiltersChanged; - - internal static List<ChatFilterRule> Filters => _filters; - internal static List<string> CustomTabsStore => _customTabs; - - /// <summary>Persist + re-route after any rule/tab mutation. Safe to call - /// when the chat panel was never created (settings still save).</summary> - internal static void NotifyFiltersChanged() - { - SaveSettings(); - _onFiltersChanged?.Invoke(); - } - - /// <summary>How a custom rule's pattern is interpreted.</summary> - internal enum FilterMatchMode - { - /// <summary>Regex against the formatted line ("ts sender: text") — the original behaviour.</summary> - Regex, - /// <summary>Plain text anywhere in the message.</summary> - Contains, - /// <summary>Plain text at the start of the message.</summary> - StartsWith, - /// <summary>Plain text at the end of the message.</summary> - EndsWith, - } - - internal sealed class ChatFilterRule - { - internal bool Enabled = true; - internal string Pattern = ""; - internal string Tab = ""; // "" = hide matching lines - internal FilterMatchMode Mode = FilterMatchMode.Regex; - internal Regex? Compiled; - internal bool Invalid; - - internal void Recompile() - { - Compiled = null; - Invalid = false; - if (Pattern.Length == 0) { Invalid = true; return; } - // Plain-text modes match the raw message, so the timestamp prefix can't break StartsWith. - string expr = Mode switch - { - FilterMatchMode.Contains => Regex.Escape(Pattern), - FilterMatchMode.StartsWith => "^" + Regex.Escape(Pattern), - FilterMatchMode.EndsWith => Regex.Escape(Pattern.TrimEnd()) + @"\s*$", - _ => Pattern, - }; - try - { - Compiled = new Regex(expr, - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, - TimeSpan.FromMilliseconds(50)); - } - catch { Invalid = true; } - } - - /// <summary>Tests the rule against a line; <paramref name="formatted"/> is used only by Regex mode.</summary> - internal bool Matches(string formatted, string rawText) - { - if (!Enabled || Compiled == null) return false; - try { return Compiled.IsMatch(Mode == FilterMatchMode.Regex ? formatted : rawText); } - catch (RegexMatchTimeoutException) { return false; } - } - } - - /// <summary>Resolve where a line should display after filter rules. - /// Custom rules are checked first (in order, first match wins), then the - /// standard presets. Returns null when a hide-rule matched; otherwise the - /// effective tab (a custom tab name, or the line's classified channel).</summary> - private static string? EffectiveTab(ChatDisplayLine line) - { - foreach (var rule in _filters) - { - if (!rule.Matches(line.FormattedText, line.Text)) continue; - return rule.Tab.Length == 0 ? null : rule.Tab; - } - var preset = RynthChatPresets.FirstMatch(line.Text, line.Channel); - if (preset != null) return preset.Tab.Length == 0 ? null : preset.Tab; - return line.Channel; - } - - /// <summary> - /// Filters-panel tester: which custom rule (index) or preset would claim a message typed by the - /// user, treating it as arriving on <paramref name="channel"/>. Returns a human-readable result. - /// </summary> - internal static string DescribeTestLine(string text, string channel) - { - if (string.IsNullOrWhiteSpace(text)) return "Type or paste a chat line to see which filter catches it."; - string formatted = $"00:00:00 {text}"; - for (int i = 0; i < _filters.Count; i++) - { - var rule = _filters[i]; - if (!rule.Matches(formatted, text)) continue; - return $"Custom rule #{i + 1} → {(rule.Tab.Length == 0 ? "hidden" : $"moved to '{rule.Tab}'")}"; - } - var preset = RynthChatPresets.FirstMatch(text, channel); - if (preset != null) - return $"Standard filter '{preset.Label}' → {(preset.Tab.Length == 0 ? "hidden" : $"moved to '{preset.Tab}'")}"; - // Not caught by an enabled filter — say which disabled preset would, to help users find the right box. - foreach (var p in RynthChatPresets.All) - if (!p.Enabled && p.Matches(text, channel)) - return $"Not filtered. Tick '{p.Group} › {p.Label}' to catch it."; - return "Not filtered — no rule or standard filter matches."; - } - - /// <summary>Custom tabs = explicitly created tabs plus any tab named by an - /// ENABLED rule (typing a tab name in a rule creates the tab implicitly). - /// Deleting a tab removes it from the explicit list AND disables rules - /// targeting it, so it doesn't resurrect through this union.</summary> - internal static IEnumerable<string> CustomTabs() - { - var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase); - foreach (var t in Tabs) seen.Add(t); - foreach (var t in _customTabs) - if (seen.Add(t)) yield return t; - foreach (var rule in _filters) - if (rule.Enabled && rule.Tab.Length > 0 && seen.Add(rule.Tab)) - yield return rule.Tab; - foreach (var t in RynthChatPresets.TargetTabs()) - if (seen.Add(t)) - yield return t; - } - - internal static bool IsBaseTab(string tab) => - Tabs.Contains(tab, StringComparer.OrdinalIgnoreCase); - - internal static void DeleteCustomTab(string tab) - { - _customTabs.RemoveAll(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)); - foreach (var rule in _filters) - if (string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) - rule.Enabled = false; - foreach (var p in RynthChatPresets.All) - if (string.Equals(p.Tab, tab, StringComparison.OrdinalIgnoreCase)) - p.Enabled = false; - NotifyFiltersChanged(); - } - // ── Mouse line-selection state (Avalonia UI thread only) ───────────── // // Drag across scrollback lines to highlight a range; releasing the mouse @@ -269,59 +57,35 @@ internal static class RynthChatPanel private static TextBlock? _flashLabel; private static DispatcherTimer? _flashTimer; - // ⚠ Lazy, NOT eager. These construct Avalonia SolidColorBrush objects. - // If they were eager static initializers, the first *static* touch of this - // class (EntryPoint.InitWorker calls RynthChatPanel.EnsureSettingsLoaded() - // to apply persisted "hide retail chat" at login) would run the static - // ctor on the InitWorker thread — constructing Avalonia objects BEFORE - // AvaloniaOverlay.Start() sets up the Win32 platform. That prematurely - // creates Dispatcher.UIThread with the non-controlled fallback impl, so the - // overlay thread's Dispatcher.MainLoop later throws PlatformNotSupportedException - // ("Operation is not supported on this platform") — the entire overlay dies - // and no RynthCore/plugin UI renders while the game + plugin pump run fine. - // Lazy init keeps the static ctor Avalonia-free; the brushes build on first - // access, which only ever happens on the Avalonia UI thread (panel render). + // ⚠ Lazy, NOT eager: an eager Avalonia-object static initializer would run + // on the first static touch of this class. Nothing touches it before + // AvaloniaOverlay.Start() any more (the settings load moved to ChatModel), + // but keep the brushes lazy so that stays harmless — see the dispatcher + // invariant in EntryPoint. private static IBrush? _selectionBrush; private static IBrush SelectionBrush => _selectionBrush ??= new SolidColorBrush(Color.FromArgb(0x66, 0x3A, 0x6E, 0xA5)); - - // ── Chat logging (Avalonia UI thread only) ──────────────────────────── - private static bool _logEnabled; - private static string? _logCharacterName; - private static StreamWriter? _logWriter; - - // ── Channel definitions (must match ChatClassifier in plugin) ───────── - - private static readonly string[] Tabs = - { "All", "Chat", "Channels", "System", "Combat", "Rynth", "Other" }; - - private static Color ChannelColor(string chan) => chan switch - { - "Chat" => Color.FromArgb(0xFF, 0xE0, 0xE0, 0xE0), - "Channels" => Color.FromArgb(0xFF, 0x7A, 0xB8, 0xF5), - "System" => Color.FromArgb(0xFF, 0x8C, 0xA6, 0xBF), - "Combat" => Color.FromArgb(0xFF, 0xD9, 0x33, 0x33), - "Rynth" => Color.FromArgb(0xFF, 0xE6, 0xB4, 0x50), // amber — distinct from the blue/grey channels - _ => Color.FromArgb(0xFF, 0xAA, 0xAA, 0xAA), - }; - - // Lazy — see the SelectionBrush note above: eager Avalonia-object static - // initializers here would poison Dispatcher.UIThread when EnsureSettingsLoaded - // triggers the static ctor off the Avalonia thread before platform init. private static IBrush? _tabActiveBrush; private static IBrush TabActiveBrush => _tabActiveBrush ??= new SolidColorBrush(Color.FromArgb(0xFF, 0x26, 0x4C, 0x59)); private static IBrush? _tabInactiveBrush; private static IBrush TabInactiveBrush => _tabInactiveBrush ??= new SolidColorBrush(Color.FromArgb(0xFF, 0x0F, 0x1F, 0x2E)); + private static Color ChannelColor(string chan) => Color.FromUInt32(ChatModel.ChannelArgb(chan)); + // ── Panel construction ──────────────────────────────────────────────── internal static Control Create() { - EnsureSettingsLoaded(); - TryBind(); + ChatModel.EnsureSettingsLoaded(); + + string activeTab = ChatModel.CurrentTab(); + string searchFilter = ""; + long lastShownId = 0; + long seenLinesVersion = -1; + long seenFiltersVersion = ChatModel.ViewVersion; // ── Tab strip with filter + gear buttons ─────────────────────── - var tabButtons = new Dictionary<string, Button>(); + var tabButtons = new Dictionary<string, Button>(StringComparer.OrdinalIgnoreCase); var tabInner = new WrapPanel { Orientation = Orientation.Horizontal }; var gearBtn = new Button { @@ -380,10 +144,11 @@ internal static class RynthChatPanel _selStack = chatStack; ClearSelectionState(); - // ── Chat input ───────────────────────────────────────────────── + // ── Chat input (shows ChatModel's line; keys never reach Avalonia) ── + const string defaultWatermark = "Press Enter to chat…"; var chatInputBox = new TextBox { - Watermark = "Press Enter to chat…", + Watermark = defaultWatermark, FontSize = 10, Height = 22, Margin = new Thickness(2, 1, 2, 1), @@ -419,7 +184,7 @@ internal static class RynthChatPanel // ── Main layout ──────────────────────────────────────────────── var mainLayout = new DockPanel { - Background = new SolidColorBrush(Color.FromArgb(_backgroundAlpha, 0x0A, 0x12, 0x1A)), + Background = new SolidColorBrush(Color.FromArgb((byte)ChatModel.BackgroundAlpha, 0x0A, 0x12, 0x1A)), }; DockPanel.SetDock(tabStrip, Dock.Top); DockPanel.SetDock(searchBox, Dock.Top); @@ -448,7 +213,7 @@ internal static class RynthChatPanel var autoScrollCheck = new CheckBox { Content = "Auto-scroll", - IsChecked = _autoScroll, + IsChecked = ChatModel.AutoScroll, FontSize = 9, Foreground = Brushes.White, }; @@ -466,45 +231,37 @@ internal static class RynthChatPanel suppressChatCheck.IsCheckedChanged += (_, _) => { ChatHooks.SuppressOriginalChat = suppressChatCheck.IsChecked == true; - SaveSettings(); + ChatModel.SaveSettings(); }; var logChatCheck = new CheckBox { Content = "Log to file", - IsChecked = _logEnabled, + IsChecked = ChatModel.LogEnabled, FontSize = 9, Foreground = Brushes.White, }; logChatCheck.IsCheckedChanged += (_, _) => { - _logEnabled = logChatCheck.IsChecked == true; - if (!_logEnabled) CloseLog(); - SaveSettings(); + ChatModel.LogEnabled = logChatCheck.IsChecked == true; // the pump closes the file + ChatModel.SaveSettings(); }; - // Live-testing finding 2026-09-02: mirrors RadarPanel's own - // "Docked click-through (hold Ctrl to interact)" checkbox — chat had - // no such option at all before this. var clickThroughCheck = new CheckBox { Content = "Click-through (hold Ctrl to interact)", - IsChecked = CtrlGatedClickThrough, + IsChecked = ChatModel.CtrlGatedClickThrough, FontSize = 9, Foreground = Brushes.White, }; ToolTip.SetTip(clickThroughCheck, "Applies to the DOCKED chat panel only — the undocked/popped-out chat is always interactive, like every other floating panel.\nOn: docked clicks pass through to the game; hold Ctrl to interact with chat.\nOff: docked chat is always interactive (default)."); clickThroughCheck.IsCheckedChanged += (_, _) => - { - CtrlGatedClickThrough = clickThroughCheck.IsChecked == true; - AvaloniaOverlay.ChatCtrlGatedClickThrough = CtrlGatedClickThrough; - SaveSettings(); - }; + ChatModel.SetCtrlGatedClickThrough(clickThroughCheck.IsChecked == true); var fontSizeLabel = new TextBlock { - Text = $"Font size: {_chatFontSize:F0}", + Text = $"Font size: {ChatModel.FontSize:F0}", FontSize = 9, Foreground = Brushes.White, VerticalAlignment = VerticalAlignment.Center, @@ -512,13 +269,13 @@ internal static class RynthChatPanel }; var fontSizeSlider = new Slider { - Minimum = 8, Maximum = 18, Value = _chatFontSize, + Minimum = 8, Maximum = 18, Value = ChatModel.FontSize, Width = 110, TickFrequency = 1, IsSnapToTickEnabled = true, }; var bgOpacityLabel = new TextBlock { - Text = $"Background: {(int)Math.Round(_backgroundAlpha / 2.55)}%", + Text = $"Background: {(int)Math.Round(ChatModel.BackgroundAlpha / 2.55)}%", FontSize = 9, Foreground = Brushes.White, VerticalAlignment = VerticalAlignment.Center, @@ -526,20 +283,20 @@ internal static class RynthChatPanel }; var bgOpacitySlider = new Slider { - Minimum = 0, Maximum = 255, Value = _backgroundAlpha, + Minimum = 0, Maximum = 255, Value = ChatModel.BackgroundAlpha, Width = 110, }; bgOpacitySlider.ValueChanged += (_, e) => { - _backgroundAlpha = (byte)Math.Round(e.NewValue); - bgOpacityLabel.Text = $"Background: {(int)Math.Round(_backgroundAlpha / 2.55)}%"; - mainLayout.Background = new SolidColorBrush(Color.FromArgb(_backgroundAlpha, 0x0A, 0x12, 0x1A)); - SaveSettings(); + ChatModel.BackgroundAlpha = (int)Math.Round(e.NewValue); + bgOpacityLabel.Text = $"Background: {(int)Math.Round(ChatModel.BackgroundAlpha / 2.55)}%"; + mainLayout.Background = new SolidColorBrush(Color.FromArgb((byte)ChatModel.BackgroundAlpha, 0x0A, 0x12, 0x1A)); + ChatModel.SaveSettings(); }; var statusLabel = new TextBlock { - Text = _getScrollbackJson != null ? "" : "Plugin not bound", + Text = ChatModel.PluginBound ? "" : "Plugin not bound", FontSize = 8, Foreground = Brushes.Gray, }; @@ -567,24 +324,25 @@ internal static class RynthChatPanel autoScrollCheck, suppressChatCheck, logChatCheck, + clickThroughCheck, statusLabel, }, }, }; autoScrollCheck.IsCheckedChanged += (_, _) => { - _autoScroll = autoScrollCheck.IsChecked == true; - if (_autoScroll) + ChatModel.AutoScroll = autoScrollCheck.IsChecked == true; + if (ChatModel.AutoScroll) { _stickToBottom = true; scrollViewer.ScrollToEnd(); } - SaveSettings(); + ChatModel.SaveSettings(); }; gearBtn.Click += (_, _) => settingsOverlay.IsVisible = !settingsOverlay.IsVisible; - // Filter rules now live in their own panel — they get complex fast. - filtersBtn.Click += (_, _) => AvaloniaOverlay.ActivateBarButton("ChatFilters"); + // Filter rules live in their own panel — they get complex fast. + filtersBtn.Click += (_, _) => PanelRouter.Toggle("ChatFilters"); // ── New-tab prompt (opened by the "+" tab button) ────────────── var newTabBox = new TextBox @@ -645,25 +403,16 @@ internal static class RynthChatPanel // ── Helpers ──────────────────────────────────────────────────── - bool LineVisible(ChatDisplayLine line, out string? effTab) - { - effTab = EffectiveTab(line); - if (effTab == null) return false; // hidden by rule - if (_activeChannel != "All" && !string.Equals(effTab, _activeChannel, StringComparison.OrdinalIgnoreCase)) - return false; - string filter = _searchFilter; - if (filter.Length > 0 && !line.FormattedText.Contains(filter, StringComparison.OrdinalIgnoreCase)) - return false; - return true; - } + ChatLine[] CurrentLines() => UiSources.Chat.Current?.Value ?? Array.Empty<ChatLine>(); void RebuildDisplay() { ClearSelectionState(); chatStack.Children.Clear(); - foreach (var line in _allLines) + foreach (var line in CurrentLines()) { - if (!LineVisible(line, out _)) continue; + lastShownId = line.Id; + if (!ChatModel.LineVisible(line, activeTab, searchFilter)) continue; chatStack.Children.Add(MakeTextBlock(line)); } // A full rebuild (tab/filter/font change) re-pins to the newest line. @@ -678,7 +427,7 @@ internal static class RynthChatPanel { tabInner.Children.Clear(); tabButtons.Clear(); - foreach (var tab in Tabs.Concat(CustomTabs())) + foreach (var tab in ChatModel.AllTabs()) { var btn = new Button { @@ -686,7 +435,7 @@ internal static class RynthChatPanel FontSize = 9, Padding = new Thickness(5, 2), Margin = new Thickness(1, 1, 0, 0), - Background = string.Equals(tab, _activeChannel, StringComparison.OrdinalIgnoreCase) + Background = string.Equals(tab, activeTab, StringComparison.OrdinalIgnoreCase) ? TabActiveBrush : TabInactiveBrush, Foreground = Brushes.White, BorderThickness = new Thickness(0), @@ -698,7 +447,7 @@ internal static class RynthChatPanel // Custom tabs only: a small ✕ to delete the tab (disables any // rules that target it so it doesn't resurrect via the union). - if (!IsBaseTab(tab)) + if (!ChatModel.IsBaseTab(tab)) { var delTabBtn = new Button { @@ -710,7 +459,7 @@ internal static class RynthChatPanel Foreground = Brushes.IndianRed, BorderThickness = new Thickness(0), }; - delTabBtn.Click += (_, _) => DeleteCustomTab(captured); + delTabBtn.Click += (_, _) => ChatModel.DeleteCustomTab(captured); tabInner.Children.Add(delTabBtn); } } @@ -734,29 +483,34 @@ internal static class RynthChatPanel tabInner.Children.Add(addTabBtn); // Active tab's source was deleted: fall back to All. - if (!tabButtons.ContainsKey(_activeChannel)) + if (!tabButtons.ContainsKey(activeTab)) { - _activeChannel = "All"; + activeTab = "All"; tabButtons["All"].Background = TabActiveBrush; } } - void SelectTab(string tab) + void ShowTab(string tab) { - RynthLog.Info($"[RynthChat] SelectTab({tab}) called."); - _activeChannel = tab; + activeTab = tab; foreach (var kv in tabButtons) { kv.Value.Background = string.Equals(kv.Key, tab, StringComparison.OrdinalIgnoreCase) ? TabActiveBrush : TabInactiveBrush; } RebuildDisplay(); - SaveSettings(); } - void AppendLine(ChatDisplayLine line) + void SelectTab(string tab) { - if (!LineVisible(line, out _)) return; + ChatModel.SelectTab(tab); + ShowTab(tab); + } + + void AppendLine(ChatLine line) + { + lastShownId = line.Id; + if (!ChatModel.LineVisible(line, activeTab, searchFilter)) return; chatStack.Children.Add(MakeTextBlock(line)); // While a selection drag is live, don't trim from the top — it would // shift the highlighted indices under the cursor. The next rebuild @@ -786,15 +540,10 @@ internal static class RynthChatPanel newTabOverlay.IsVisible = false; Win32Backend.AvaloniaTextInputActive = false; if (name.Length == 0) return; - if (Tabs.Concat(CustomTabs()).Contains(name, StringComparer.OrdinalIgnoreCase)) - { - SelectTab(name); // already exists — just switch to it - return; - } - _customTabs.Add(name); - SaveSettings(); + ChatModel.AddCustomTab(name); + seenFiltersVersion = ChatModel.ViewVersion; RebuildTabs(); - SelectTab(name); + ShowTab(ChatModel.CurrentTab()); } newTabAddBtn.Click += (_, _) => CommitNewTab(); @@ -809,19 +558,11 @@ internal static class RynthChatPanel else if (e.Key == Key.Escape) { newTabOverlay.IsVisible = false; e.Handled = true; } }; - // The filters panel mutates the rule list and calls - // NotifyFiltersChanged(); re-route + rebuild the tab strip here. - _onFiltersChanged = () => - { - RebuildTabs(); - RebuildDisplay(); - }; - // ── Event wiring ─────────────────────────────────────────────── searchBox.TextChanged += (_, _) => { - _searchFilter = searchBox.Text ?? ""; + searchFilter = searchBox.Text ?? ""; RebuildDisplay(); }; @@ -861,269 +602,104 @@ internal static class RynthChatPanel } }; - // ── Chat input callbacks (all key handling in WndProcHook) ──────── - // WndProcHook intercepts WM_CHAR / VK_BACK / VK_RETURN / VK_ESCAPE while - // ChatCaptureActive and fires these callbacks. No Avalonia focus needed. - + // ── Chat input: ChatModel's line (updated on AC's thread) ───── var defaultBorderBrush = chatInputBox.BorderBrush; var activeBorderBrush = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xD7, 0x00)); - string defaultWatermark = chatInputBox.Watermark ?? ""; - - Win32Backend.OnChatCaptureActivated = () => + void ShowInput() { - _captureText = ""; - _cursorPos = 0; - _historyIndex = -1; - Dispatcher.UIThread.Post(() => - { - chatInputBox.Text = ""; - chatInputBox.BorderBrush = activeBorderBrush; - chatInputBox.Watermark = defaultWatermark; - }); - }; - - // Start "/tell <selected name>, " and leave the player typing. Game thread only - // (Tell button via WM_RYNTHCORE_TELL, or "/tell" alone in OnChatSend), where the - // selection and its name read live. Nothing selected → a hint in the input box. - bool BeginTellToSelected() - { - if (!TryGetSelectedTellName(out string name)) - { - Dispatcher.UIThread.Post(() => - { - chatInputBox.Text = ""; - chatInputBox.Watermark = "Select an NPC or player in the game first, then Tell."; - }); - return false; - } - _captureText = $"/tell {name}, "; - _cursorPos = _captureText.Length; - _historyIndex = -1; - Win32Backend.ChatCaptureActive = true; // keep typing: keys now go to this line - var (snap, pos) = (_captureText, _cursorPos); - Dispatcher.UIThread.Post(() => - { - chatInputBox.Text = snap; - chatInputBox.CaretIndex = pos; - chatInputBox.BorderBrush = activeBorderBrush; - chatInputBox.Watermark = defaultWatermark; - }); - return true; + string text = ChatModel.InputText; + chatInputBox.Text = text; + chatInputBox.CaretIndex = Math.Min(ChatModel.InputCursor, text.Length); + chatInputBox.Watermark = ChatModel.InputHint ?? defaultWatermark; + chatInputBox.BorderBrush = Win32Backend.ChatCaptureActive ? activeBorderBrush : defaultBorderBrush; } - Win32Backend.OnChatTellSelected = () => BeginTellToSelected(); + void OnInputChanged() => Dispatcher.UIThread.Post(ShowInput); - Win32Backend.OnChatChar = c => - { - _captureText = _captureText[.._cursorPos] + c + _captureText[_cursorPos..]; - _cursorPos++; - _historyIndex = -1; - var (snap, pos) = (_captureText, _cursorPos); - Dispatcher.UIThread.Post(() => { chatInputBox.Text = snap; chatInputBox.CaretIndex = pos; }); - }; - - Win32Backend.OnChatBackspace = () => - { - if (_cursorPos > 0) - { - _captureText = _captureText[..(_cursorPos - 1)] + _captureText[_cursorPos..]; - _cursorPos--; - } - var (snap, pos) = (_captureText, _cursorPos); - Dispatcher.UIThread.Post(() => { chatInputBox.Text = snap; chatInputBox.CaretIndex = pos; }); - }; - - Win32Backend.OnChatDelete = () => - { - if (_cursorPos < _captureText.Length) - _captureText = _captureText[.._cursorPos] + _captureText[(_cursorPos + 1)..]; - var (snap, pos) = (_captureText, _cursorPos); - Dispatcher.UIThread.Post(() => { chatInputBox.Text = snap; chatInputBox.CaretIndex = pos; }); - }; - - Win32Backend.OnChatLeft = () => - { - if (_cursorPos > 0) _cursorPos--; - var pos = _cursorPos; - Dispatcher.UIThread.Post(() => chatInputBox.CaretIndex = pos); - }; - - Win32Backend.OnChatRight = () => - { - if (_cursorPos < _captureText.Length) _cursorPos++; - var pos = _cursorPos; - Dispatcher.UIThread.Post(() => chatInputBox.CaretIndex = pos); - }; - - Win32Backend.OnChatHome = () => - { - _cursorPos = 0; - Dispatcher.UIThread.Post(() => chatInputBox.CaretIndex = 0); - }; - - Win32Backend.OnChatEnd = () => - { - _cursorPos = _captureText.Length; - var pos = _cursorPos; - Dispatcher.UIThread.Post(() => chatInputBox.CaretIndex = pos); - }; - - Win32Backend.OnChatUp = () => - { - if (_history.Count == 0) return; - _historyIndex = _historyIndex < 0 ? _history.Count - 1 - : Math.Max(0, _historyIndex - 1); - _captureText = _history[_historyIndex]; - _cursorPos = _captureText.Length; - var (snap, pos) = (_captureText, _cursorPos); - Dispatcher.UIThread.Post(() => { chatInputBox.Text = snap; chatInputBox.CaretIndex = pos; }); - }; - - Win32Backend.OnChatDown = () => - { - if (_historyIndex < 0) return; - if (_historyIndex < _history.Count - 1) - { - _historyIndex++; - _captureText = _history[_historyIndex]; - } - else - { - _historyIndex = -1; - _captureText = ""; - } - _cursorPos = _captureText.Length; - var (snap, pos) = (_captureText, _cursorPos); - Dispatcher.UIThread.Post(() => { chatInputBox.Text = snap; chatInputBox.CaretIndex = pos; }); - }; - - // OnChatSend fires on the game thread (WndProcHook). _sendLine must be - // called here — before Dispatcher.UIThread.Post — so SimulateChatInput's - // CallWindowProcA runs on the game thread, not the Avalonia UI thread. - Win32Backend.OnChatSend = () => - { - string text = _captureText.Trim(); - // "/tell" or "/t" alone addresses the selected NPC or player instead of being - // sent (AC would only answer with the usage line). - if (text.Equals("/tell", StringComparison.OrdinalIgnoreCase) || text.Equals("/t", StringComparison.OrdinalIgnoreCase)) - { - if (!BeginTellToSelected()) - { - _captureText = ""; _cursorPos = 0; _historyIndex = -1; - Dispatcher.UIThread.Post(() => chatInputBox.BorderBrush = defaultBorderBrush); - } - return; - } - _captureText = ""; - _cursorPos = 0; - _historyIndex = -1; - if (text.Length > 0 && (_history.Count == 0 || _history[^1] != text)) - { - _history.Add(text); - if (_history.Count > 100) _history.RemoveAt(0); - } - Dispatcher.UIThread.Post(() => - { - chatInputBox.Text = ""; - chatInputBox.BorderBrush = defaultBorderBrush; - }); - if (text.Length > 0 && _sendLine != null) - { - IntPtr ptr = Marshal.StringToHGlobalAnsi(text); - try { _sendLine(ptr); } - finally { Marshal.FreeHGlobal(ptr); } - } - }; - - Win32Backend.OnChatCancel = () => - { - _captureText = ""; - _cursorPos = 0; - _historyIndex = -1; - Dispatcher.UIThread.Post(() => - { - chatInputBox.Text = ""; - chatInputBox.BorderBrush = defaultBorderBrush; - }); - }; - - // ── Poll timer ───────────────────────────────────────────────── + // ── Poll timer: new lines, filter/tab changes ────────────────── var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) }; + bool captureShown = false; timer.Tick += (_, _) => { - if (_getScrollbackJson == null) + statusLabel.Text = ChatModel.PluginBound ? "" : "Plugin not bound"; + + long filtersVersion = ChatModel.ViewVersion; + string current = ChatModel.CurrentTab(); + if (filtersVersion != seenFiltersVersion) { - TryBind(); - if (_getScrollbackJson != null) - statusLabel.Text = ""; // clear "Plugin not bound" - return; + seenFiltersVersion = filtersVersion; + activeTab = current; + RebuildTabs(); + ShowTab(activeTab); + seenLinesVersion = UiSources.Chat.Current?.Version ?? -1; + } + else if (!string.Equals(current, activeTab, StringComparison.OrdinalIgnoreCase)) + ShowTab(current); + + var snap = UiSources.Chat.Current; + if (snap != null && snap.Version != seenLinesVersion) + { + seenLinesVersion = snap.Version; + foreach (var line in snap.Value) + if (line.Id > lastShownId) AppendLine(line); } - IntPtr ptr = _getScrollbackJson(_lastSeq); - if (ptr == IntPtr.Zero) return; - string? json = Marshal.PtrToStringAnsi(ptr); - if (string.IsNullOrEmpty(json) || json == "[]") return; - - RynthChatLineDto[]? dtos; - try { dtos = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatLineDtoArray); } - catch { return; } - if (dtos == null || dtos.Length == 0) return; - - foreach (var dto in dtos) + // Capture ends inside Win32Backend (Enter / Escape) without an input change. + if (captureShown != Win32Backend.ChatCaptureActive) { - if (dto.Seq <= _lastSeq) continue; - _lastSeq = dto.Seq; - - var line = new ChatDisplayLine(dto.Seq, dto.Ts, dto.Chan, dto.Sender, dto.Text); - if (_allLines.Count >= 500) _allLines.RemoveAt(0); - _allLines.Add(line); - AppendLine(line); - LogLine(line); + captureShown = Win32Backend.ChatCaptureActive; + ShowInput(); } }; - timer.Start(); - // Stop with the visual tree — a running DispatcherTimer roots the closed - // view forever (this one polls at 100ms!). RadarPanel idiom; must - // restart on attach: drag/resize fires Detached→Attached. - root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); }; - root.DetachedFromVisualTree += (_, _) => timer.Stop(); fontSizeSlider.ValueChanged += (_, e) => { - _chatFontSize = e.NewValue; - fontSizeLabel.Text = $"Font size: {_chatFontSize:F0}"; + ChatModel.FontSize = (float)e.NewValue; + fontSizeLabel.Text = $"Font size: {ChatModel.FontSize:F0}"; RebuildDisplay(); - SaveSettings(); + ChatModel.SaveSettings(); }; - // Build tabs (base + custom from loaded filters), filter rows, then - // apply loaded active-channel to tab button visuals. RebuildTabs(); - SelectTab(_activeChannel); + ShowTab(activeTab); + seenLinesVersion = UiSources.Chat.Current?.Version ?? -1; - // Whether RynthChat is on screen decides who owns Enter and whether the retail - // chatbox is hidden (ChatHooks.RynthChatOwnsChat). A closed RynthChat used to keep - // both: Enter typed into the invisible panel — every key swallowed until Enter or - // Escape — and the retail chat stayed hidden, so there was no chat at all. - root.AttachedToVisualTree += (_, _) => SetShown(true); - root.DetachedFromVisualTree += (_, _) => SetShown(false); + // Stop with the visual tree — a running DispatcherTimer roots the closed + // view forever. Drag/resize fires Detached→Attached, so restart on attach. + // Whether chat is on screen decides who owns Enter and whether the retail + // chatbox is hidden (ChatModel.SetShown). + root.AttachedToVisualTree += (_, _) => + { + UiSources.Chat.Subscribe(); + UiSources.Chat.RequestRefresh(); + ChatModel.InputChanged += OnInputChanged; + ShowInput(); + ChatModel.SetShown(true); + if (!timer.IsEnabled) timer.Start(); + }; + root.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + ChatModel.SetShown(false); + ChatModel.InputChanged -= OnInputChanged; + UiSources.Chat.Unsubscribe(); + }; return root; } // ── Helpers ─────────────────────────────────────────────────────────── - private static TextBlock MakeTextBlock(ChatDisplayLine line) + private static TextBlock MakeTextBlock(ChatLine line) { - string prefix = line.Sender != null ? $"{line.Timestamp} {line.Sender}: " : $"{line.Timestamp} "; // Plain TextBlock, IsHitTestVisible=false: line-range selection is // handled at the ScrollViewer level (drag → highlight → copy on // release). Tag carries the formatted text for the clipboard join. return new TextBlock { - Text = prefix + line.Text, + Text = line.FormattedText, Tag = line.FormattedText, - FontSize = _chatFontSize, + FontSize = ChatModel.FontSize, FontFamily = new FontFamily("Consolas,Courier New,monospace"), Foreground = new SolidColorBrush(ChannelColor(line.Channel)), TextWrapping = TextWrapping.Wrap, @@ -1224,46 +800,7 @@ internal static class RynthChatPanel if (children[i] is TextBlock tb && tb.Tag is string s) parts.Add(s); if (parts.Count == 0) return; - bool ok = SetClipboardText(string.Join("\r\n", parts)); - FlashStatus(ok ? $"Copied {parts.Count} line{(parts.Count == 1 ? "" : "s")}" : "Clipboard busy — try again"); - } - - private static bool SetClipboardText(string text) - { - const uint CF_UNICODETEXT = 13; - const uint GMEM_MOVEABLE = 0x0002; - // The clipboard is a shared resource — another app may hold it briefly. - for (int attempt = 0; attempt < 5; attempt++) - { - if (OpenClipboard(IntPtr.Zero)) - { - try - { - EmptyClipboard(); - int bytes = (text.Length + 1) * 2; - IntPtr hMem = GlobalAlloc(GMEM_MOVEABLE, (UIntPtr)bytes); - if (hMem == IntPtr.Zero) return false; - IntPtr dst = GlobalLock(hMem); - if (dst == IntPtr.Zero) { GlobalFree(hMem); return false; } - unsafe - { - fixed (char* src = text) - Buffer.MemoryCopy(src, (void*)dst, bytes, text.Length * 2); - ((char*)dst)[text.Length] = '\0'; - } - GlobalUnlock(hMem); - if (SetClipboardData(CF_UNICODETEXT, hMem) == IntPtr.Zero) - { - GlobalFree(hMem); // ownership not taken — free it - return false; - } - return true; // system owns hMem now - } - finally { CloseClipboard(); } - } - System.Threading.Thread.Sleep(10); - } - return false; + FlashStatus(ChatModel.CopyLines(parts)); } private static void FlashStatus(string message) @@ -1329,292 +866,4 @@ internal static class RynthChatPanel } internal static bool FloatingSelectionActive => _selDragging; - - /// <summary>The panel went on or off screen (opened, closed, popped out or back in).</summary> - private static void SetShown(bool shown) - { - ChatHooks.ChatPanelShown = shown; - if (!shown && Win32Backend.ChatCaptureActive) - { - // Abandon a half-typed line rather than keep swallowing keys for a closed panel. - Win32Backend.ChatCaptureActive = false; - _captureText = ""; - _cursorPos = 0; - _historyIndex = -1; - } - } - - /// <summary> - /// Name of the creature selected in the game — an NPC or another player — for /tell. - /// AC's main thread only (the name read is live there). Never yourself, never an item. - /// </summary> - private static bool TryGetSelectedTellName(out string name) - { - name = ""; - uint id = SelectedTargetHooks.ReadCurrentSelectedId(); - if (id == 0 || id == ClientHelperHooks.GetPlayerId()) return false; - const uint ItemTypeCreature = 0x00000010; - if (ClientObjectHooks.TryGetItemType(id, out uint flags) && (flags & ItemTypeCreature) == 0) return false; - return ClientObjectHooks.TryGetObjectName(id, out name) && !string.IsNullOrWhiteSpace(name); - } - - // RL loads fresh plugin copies without unloading the old ones: drop the - // exports bound below so the next poll re-binds to the live copy. - static RynthChatPanel() => PluginManager.PluginsUnloaded += () => - { - _getScrollbackJson = null; - _sendLine = null; - _lastSeq = 0; // the fresh copy's scrollback numbers from 1 again - }; - - private static void TryBind() - { - LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthChat", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - _getScrollbackJson ??= Bind<GetScrollbackJsonFn>(plugin, "RynthChatGetScrollbackJson"); - _sendLine ??= Bind<SendLineFn>(plugin, "RynthChatSendLine"); - - if (!_bindingLogged && _getScrollbackJson != null) - { - _bindingLogged = true; - RynthLog.UI("RynthChatPanel: bound RynthChat plugin exports."); - } - } - - private static T? Bind<T>(LoadedPlugin plugin, string exportName) where T : Delegate - { - IntPtr addr = GetProcAddress(plugin.ModuleHandle, exportName); - return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr); - } - - // ── Chat logging helpers (Avalonia UI thread) ───────────────────────── - - private static void LogLine(ChatDisplayLine line) - { - if (!_logEnabled) return; - if (_logWriter == null) EnsureLogOpen(); - _logWriter?.WriteLine(line.FormattedText); - } - - private static void EnsureLogOpen() - { - if (_logWriter != null) return; - _logCharacterName ??= TryReadCharacterName(); - if (_logCharacterName == null) return; - - string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "ChatLogs"); - Directory.CreateDirectory(dir); - string path = Path.Combine(dir, $"{_logCharacterName}.log"); - _logWriter = new StreamWriter(path, append: true, System.Text.Encoding.UTF8) { AutoFlush = true }; - } - - private static void CloseLog() - { - _logWriter?.Close(); - _logWriter = null; - } - - // ── Settings persistence ────────────────────────────────────────────── - - private static string SettingsPath => - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "RynthCore", "rynthchat_settings.json"); - - /// <summary>Idempotent settings load — called from both the chat panel and - /// the filters panel Create(), whichever runs first.</summary> - internal static void EnsureSettingsLoaded() - { - if (_settingsLoaded) return; - _settingsLoaded = true; - LoadSettings(); - } - - private static void LoadSettings() - { - try - { - string path = SettingsPath; - if (!File.Exists(path)) return; - var dto = JsonSerializer.Deserialize(File.ReadAllText(path), - RynthChatJsonContext.Default.RynthChatSettingsDto); - if (dto == null) return; - - _chatFontSize = Math.Clamp(dto.FontSize <= 0 ? 10 : dto.FontSize, 8, 18); - _backgroundAlpha = (byte)Math.Clamp(dto.BackgroundAlpha, 0, 255); - _autoScroll = dto.AutoScroll; - ChatHooks.SuppressOriginalChat = dto.SuppressChat; - _logEnabled = dto.LogEnabled; - CtrlGatedClickThrough = dto.CtrlGatedClickThrough; - AvaloniaOverlay.ChatCtrlGatedClickThrough = CtrlGatedClickThrough; - - _customTabs.Clear(); - if (dto.CustomTabs != null) - foreach (var t in dto.CustomTabs) - if (!string.IsNullOrWhiteSpace(t)) _customTabs.Add(t.Trim()); - - _filters.Clear(); - if (dto.Filters != null) - { - foreach (var f in dto.Filters) - { - var rule = new ChatFilterRule - { - Enabled = f.Enabled, - Pattern = f.Pattern ?? "", - Tab = (f.Tab ?? "").Trim(), - Mode = Enum.TryParse(f.Mode, true, out FilterMatchMode m) ? m : FilterMatchMode.Regex, - }; - rule.Recompile(); - _filters.Add(rule); - } - } - - if (dto.Presets != null) - { - foreach (var ps in dto.Presets) - { - var p = ps.Id != null ? RynthChatPresets.Get(ps.Id) : null; - if (p == null) continue; - p.Enabled = ps.Enabled; - p.Tab = (ps.Tab ?? "").Trim(); - } - } - - if (!string.IsNullOrEmpty(dto.ActiveChannel) && - (Tabs.Contains(dto.ActiveChannel) || - CustomTabs().Contains(dto.ActiveChannel, StringComparer.OrdinalIgnoreCase))) - _activeChannel = dto.ActiveChannel; - } - catch { } - } - - private static void SaveSettings() - { - try - { - string path = SettingsPath; - Directory.CreateDirectory(Path.GetDirectoryName(path)!); - var dto = new RynthChatSettingsDto - { - FontSize = _chatFontSize, - BackgroundAlpha = _backgroundAlpha, - AutoScroll = _autoScroll, - SuppressChat = ChatHooks.SuppressOriginalChat, - LogEnabled = _logEnabled, - CtrlGatedClickThrough = CtrlGatedClickThrough, - ActiveChannel = _activeChannel, - CustomTabs = _customTabs.ToArray(), - Filters = _filters.Select(f => new RynthChatFilterDto - { - Enabled = f.Enabled, - Pattern = f.Pattern, - Tab = f.Tab, - Mode = f.Mode.ToString(), - }).ToArray(), - // Only presets the user touched are written; the rest stay at their defaults (off, hide). - Presets = RynthChatPresets.All - .Where(p => p.Enabled || p.Tab.Length > 0) - .Select(p => new RynthChatPresetDto { Id = p.Id, Enabled = p.Enabled, Tab = p.Tab }) - .ToArray(), - }; - File.WriteAllText(path, JsonSerializer.Serialize(dto, - RynthChatJsonContext.Default.RynthChatSettingsDto)); - } - catch { } - } - - private static string? TryReadCharacterName() - { - try - { - string root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore"); - string perProcPath = Path.Combine(root, "launch_contexts", $"launch_context_{Environment.ProcessId}.json"); - string path = File.Exists(perProcPath) ? perProcPath : Path.Combine(root, "launch_context.json"); - if (!File.Exists(path)) return null; - - using var doc = JsonDocument.Parse(File.ReadAllBytes(path)); - if (doc.RootElement.TryGetProperty("TargetCharacter", out JsonElement tc)) - { - string? name = tc.GetString(); - if (!string.IsNullOrWhiteSpace(name)) return name.Trim(); - } - return null; - } - catch { return null; } - } - - // ── Display line (Avalonia UI thread only) ──────────────────────────── - - private sealed class ChatDisplayLine - { - internal ulong Seq { get; } - internal string Channel { get; } - internal string FormattedText { get; } - internal string Text { get; } - internal string? Sender { get; } - internal string Timestamp { get; } - - internal ChatDisplayLine(ulong seq, string ts, string chan, string? sender, string text) - { - Seq = seq; - Channel = chan; - Sender = sender; - Text = text; - Timestamp = ts; - FormattedText = sender != null ? $"{ts} {sender}: {text}" : $"{ts} {text}"; - } - } } - -// JsonSerializerContext must be at namespace scope (not nested) for source generation. -internal sealed class RynthChatLineDto -{ - [JsonPropertyName("seq")] public ulong Seq { get; set; } - [JsonPropertyName("ts")] public string Ts { get; set; } = ""; - [JsonPropertyName("chan")] public string Chan { get; set; } = ""; - [JsonPropertyName("sender")] public string? Sender { get; set; } - [JsonPropertyName("text")] public string Text { get; set; } = ""; -} - -// Property names match the legacy hand-written JSON so existing settings load. -internal sealed class RynthChatFilterDto -{ - [JsonPropertyName("pattern")] public string? Pattern { get; set; } - [JsonPropertyName("tab")] public string? Tab { get; set; } - [JsonPropertyName("enabled")] public bool Enabled { get; set; } = true; - /// <summary>FilterMatchMode name; missing (older settings) = Regex.</summary> - [JsonPropertyName("mode")] public string? Mode { get; set; } -} - -/// <summary>Persisted state of one standard (canned) filter.</summary> -internal sealed class RynthChatPresetDto -{ - [JsonPropertyName("id")] public string? Id { get; set; } - [JsonPropertyName("enabled")] public bool Enabled { get; set; } - [JsonPropertyName("tab")] public string? Tab { get; set; } -} - -internal sealed class RynthChatSettingsDto -{ - [JsonPropertyName("fontSize")] public double FontSize { get; set; } = 10; - [JsonPropertyName("backgroundAlpha")] public int BackgroundAlpha { get; set; } = 0xF2; - [JsonPropertyName("autoScroll")] public bool AutoScroll { get; set; } = true; - [JsonPropertyName("suppressChat")] public bool SuppressChat { get; set; } - [JsonPropertyName("logEnabled")] public bool LogEnabled { get; set; } - // Live-testing finding 2026-09-02: chat had no click-through option at - // all, unlike Radar's Ctrl-gated one — every docked panel except Radar - // is unconditionally interactive (AvaloniaOverlay.IsOverPanel). Mirrors - // RadarPanel's CtrlGatedClickThrough exactly. - [JsonPropertyName("ctrlGatedClickThrough")] public bool CtrlGatedClickThrough { get; set; } - [JsonPropertyName("activeChannel")] public string? ActiveChannel { get; set; } - [JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; } - [JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; } - [JsonPropertyName("presets")] public RynthChatPresetDto[]? Presets { get; set; } -} - -[JsonSerializable(typeof(RynthChatLineDto[]))] -[JsonSerializable(typeof(RynthChatSettingsDto))] -[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = false)] -internal partial class RynthChatJsonContext : JsonSerializerContext { } diff --git a/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs b/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs index aa3c05d..0df795c 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs @@ -6,8 +6,9 @@ // // Presets match the raw line text (no timestamp / sender prefix). Most are // limited to non-chat channels so a player typing the same words in Local or -// a channel is never eaten. Avalonia UI thread only, like the rest of the -// RynthChat filter state. +// a channel is never eaten. ChatRouter evaluates them on the plugin pump +// (after the custom rules); editors change Enabled / Tab from any thread and +// then call ChatModel.FiltersChanged so every kept line is routed again. // ============================================================================ using System; @@ -42,9 +43,10 @@ internal static class RynthChatPresets internal Scope Where { get; } internal Regex Pattern { get; } - // User state (persisted via RynthChatPanel settings). - internal bool Enabled; - internal string Tab = ""; // "" = hide matching lines + // User state (persisted in rynthchat_settings.json "presets" by ChatModel). + // Volatile: written by an editor, read by the pump's router. + internal volatile bool Enabled; + internal volatile string Tab = ""; // "" = hide matching lines internal Preset(string id, string group, string label, string description, string example, Scope where, string pattern) { diff --git a/src/RynthCore.Engine/UI/Panels/RynthNavPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthNavPanel.cs index cc1b530..e0e46c9 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthNavPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthNavPanel.cs @@ -1,11 +1,14 @@ // ============================================================================ // RynthCore.Engine — UI/Panels/RynthNavPanel.cs -// Avalonia bar panel for the RynthNav plugin (mesh navigation). Bridges to the -// plugin DLL via GetProcAddress: polls a status JSON and drives load/test/preview. +// Avalonia bar panel for the RynthNav plugin (mesh navigation): shows its +// status and drives load/test/preview/go/move. Data goes through UiDataHub +// (UI/Data/RynthNavData.cs): UiSources.RynthNav polls the status on the pump +// thread and RynthNavCommands runs the actions there; the ImGui face +// (ImGui/Panels/RynthNavFace.cs) reads the same snapshot. // This is the only visible RynthNav surface in Decal-coexistence mode (ImGui and // the Nav3D world overlay are both unavailable there). // -// Bridge exports (resolved from the RynthNav plugin DLL): +// Plugin exports (called by the hub): // RynthNavGetStatusJson() → ANSI JSON status // RynthNavLoadTile() → load current landblock's baked tile // RynthNavTestQuery() → FindNearestPoly at the player @@ -25,28 +28,12 @@ using Avalonia.Media; using Avalonia.Threading; using RynthCore.Engine.ImGuiBackend; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; internal static class RynthNavPanel { - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetStatusJsonFn(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void VoidFn(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void PreviewFn(IntPtr ansiCoord); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void MoveFn(int cmd); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void GotoFn(IntPtr ansiCoord); - - private static GetStatusJsonFn? _getStatus; - private static VoidFn? _loadTile; - private static VoidFn? _testQuery; - private static PreviewFn? _preview; - private static MoveFn? _move; - private static GotoFn? _goto; - private static bool _bindingLogged; - // ── Palette (matches RynthAiPanel) ────────────────────────────────────────── private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6)); private static readonly IBrush ColGreen = new SolidColorBrush(Color.FromRgb(0x40, 0xD9, 0x73)); @@ -68,7 +55,6 @@ internal static class RynthNavPanel internal static Control Create() { - TryBind(); var root = new StackPanel { Orientation = Orientation.Vertical, Margin = new Thickness(10), Spacing = 5, MinWidth = 300 }; @@ -96,8 +82,8 @@ internal static class RynthNavPanel // Actions var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 0 }; - actions.Children.Add(Btn("Load tile", () => { TryBind(); _loadTile?.Invoke(); })); - actions.Children.Add(Btn("Test @ me", () => { TryBind(); _testQuery?.Invoke(); })); + actions.Children.Add(Btn("Load tile", RynthNavCommands.LoadTile)); + actions.Children.Add(Btn("Test @ me", RynthNavCommands.TestQuery)); root.Children.Add(actions); root.Children.Add(Sep()); @@ -125,118 +111,49 @@ internal static class RynthNavPanel // Poll the plugin for status (UI thread). var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) }; + long seenVersion = -1; timer.Tick += (_, _) => { - if (_getStatus == null) TryBind(); - Refresh(); + var snap = UiSources.RynthNav.Current; + if (snap == null) { if (_dot != null) _dot.Fill = ColMute; return; } + if (snap.Version == seenVersion) return; + seenVersion = snap.Version; + Refresh(snap.Value); }; var outer = new Border { Background = ColShellBg, CornerRadius = new CornerRadius(5), Child = new ScrollViewer { Content = root } }; - outer.AttachedToVisualTree += (_, _) => timer.Start(); - outer.DetachedFromVisualTree += (_, _) => timer.Stop(); + outer.AttachedToVisualTree += (_, _) => + { + UiSources.RynthNav.Subscribe(); + UiSources.RynthNav.RequestRefresh(); + timer.Start(); + }; + outer.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.RynthNav.Unsubscribe(); + }; return outer; } - private static void Refresh() + private static void Refresh(RynthNavStatus st) { - if (_getStatus == null) { if (_dot != null) _dot.Fill = ColMute; return; } - IntPtr ptr; - try { ptr = _getStatus(); } catch { return; } - if (ptr == IntPtr.Zero) return; - string? json = Marshal.PtrToStringAnsi(ptr); - if (string.IsNullOrEmpty(json)) return; - - try - { - using var doc = JsonDocument.Parse(json); - var r = doc.RootElement; - - bool hasPose = r.TryGetProperty("hasPose", out var v) && v.GetInt32() != 0; - string lb = r.TryGetProperty("landblock", out v) ? v.GetString() ?? "----" : "----"; - double ns = r.TryGetProperty("ns", out v) ? v.GetDouble() : 0; - double ew = r.TryGetProperty("ew", out v) ? v.GetDouble() : 0; - bool loaded = r.TryGetProperty("tileLoaded", out v) && v.GetInt32() != 0; - string loadLb = r.TryGetProperty("loadedLb", out v) ? v.GetString() ?? "----" : "----"; - int polys = r.TryGetProperty("polyCount", out v) ? v.GetInt32() : 0; - string status = r.TryGetProperty("status", out v) ? v.GetString() ?? "" : ""; - string path = r.TryGetProperty("lastPath", out v) ? v.GetString() ?? "" : ""; - - // Change-detection: only touch a control when its value actually changed, - // so an idle panel issues zero invalidations (no GDI-overlay flicker). - SetText(_playerVal, hasPose ? $"0x{lb} {Loc(ns, 'N', 'S')} {Loc(ew, 'E', 'W')}" : "— no pose —"); - SetText(_meshVal, loaded ? $"LOADED 0x{loadLb} · {polys} polys" : "not loaded"); - SetFg(_meshVal, loaded ? ColGreen : ColAmber); - SetFill(_dot, loaded ? ColGreen : (hasPose ? ColAmber : ColMute)); - SetText(_statusVal, status); - SetText(_pathVal, string.IsNullOrEmpty(path) ? "" : "↳ " + path); - - int run = r.TryGetProperty("runState", out v) ? v.GetInt32() : 0; - int turn = r.TryGetProperty("turnState", out v) ? v.GetInt32() : 0; - SetBg(_fwdBtn, run == 1 ? ColGreen : ColBtnFill); - SetBg(_backBtn, run == 2 ? ColGreen : ColBtnFill); - SetBg(_leftBtn, turn == -1 ? ColGreen : ColBtnFill); - SetBg(_rightBtn, turn == 1 ? ColGreen : ColBtnFill); - } - catch { /* transient partial JSON — ignore */ } + // Change-detection: only touch a control when its value actually changed, + // so an idle panel issues zero invalidations (no GDI-overlay flicker). + SetText(_playerVal, st.PlayerText); + SetText(_meshVal, st.MeshText); + SetFg(_meshVal, st.TileLoaded ? ColGreen : ColAmber); + SetFill(_dot, st.TileLoaded ? ColGreen : (st.HasPose ? ColAmber : ColMute)); + SetText(_statusVal, st.Status); + SetText(_pathVal, st.PathText); + SetBg(_fwdBtn, st.RunState == 1 ? ColGreen : ColBtnFill); + SetBg(_backBtn, st.RunState == 2 ? ColGreen : ColBtnFill); + SetBg(_leftBtn, st.TurnState == -1 ? ColGreen : ColBtnFill); + SetBg(_rightBtn, st.TurnState == 1 ? ColGreen : ColBtnFill); } - private static void Preview() - { - TryBind(); - if (_preview == null) return; - string txt = _coordBox?.Text ?? ""; - IntPtr p = Marshal.StringToHGlobalAnsi(txt); - try { _preview(p); } - finally { Marshal.FreeHGlobal(p); } - } + private static void Preview() => RynthNavCommands.Preview(_coordBox?.Text ?? ""); - private static void Go() - { - TryBind(); - if (_goto == null) return; - string txt = _coordBox?.Text ?? ""; - IntPtr p = Marshal.StringToHGlobalAnsi(txt); - try { _goto(p); } - finally { Marshal.FreeHGlobal(p); } - } - - // ── Plugin binding ────────────────────────────────────────────────────────── - // RL loads fresh plugin copies without unloading the old ones: drop the - // exports bound below so the next poll re-binds to the live copy. - static RynthNavPanel() => PluginManager.PluginsUnloaded += () => - { - _getStatus = null; - _loadTile = null; - _testQuery = null; - _preview = null; - _move = null; - _goto = null; - }; - - private static void TryBind() - { - LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthNav", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - _getStatus ??= Bind<GetStatusJsonFn>(plugin, "RynthNavGetStatusJson"); - _loadTile ??= Bind<VoidFn>(plugin, "RynthNavLoadTile"); - _testQuery ??= Bind<VoidFn>(plugin, "RynthNavTestQuery"); - _preview ??= Bind<PreviewFn>(plugin, "RynthNavPreviewPath"); - _move ??= Bind<MoveFn>(plugin, "RynthNavMove"); - _goto ??= Bind<GotoFn>(plugin, "RynthNavGoto"); - - if (!_bindingLogged && _getStatus != null) - { - _bindingLogged = true; - RynthLog.UI("RynthNavPanel: bound RynthNav plugin exports."); - } - } - - private static T? Bind<T>(LoadedPlugin plugin, string export) where T : Delegate - { - IntPtr addr = GetProcAddress(plugin.ModuleHandle, export); - return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr); - } + private static void Go() => RynthNavCommands.Goto(_coordBox?.Text ?? ""); // ── UI helpers ────────────────────────────────────────────────────────────── private static TextBlock ValueRow(StackPanel parent, string label) @@ -316,7 +233,7 @@ internal static class RynthNavPanel VerticalContentAlignment = VerticalAlignment.Center, }; ToolTip.SetTip(b, tip); - b.Click += (_, _) => { TryBind(); _move?.Invoke(cmd); }; + b.Click += (_, _) => RynthNavCommands.Move(cmd); return b; } @@ -325,6 +242,4 @@ internal static class RynthNavPanel private static void SetBg(Button? b, IBrush br) { if (b != null && !ReferenceEquals(b.Background, br)) b.Background = br; } private static void SetFill(Ellipse? e, IBrush br) { if (e != null && !ReferenceEquals(e.Fill, br)) e.Fill = br; } - private static string Loc(double v, char pos, char neg) - => v.ToString("F1", CultureInfo.InvariantCulture).TrimStart('-') + (v >= 0 ? pos : neg); } diff --git a/src/RynthCore.Engine/UI/Panels/RynthTrackerPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthTrackerPanel.cs index d293269..d08c7aa 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthTrackerPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthTrackerPanel.cs @@ -2,54 +2,29 @@ // RynthCore.Engine — UI/Panels/RynthTrackerPanel.cs // Session-stats panel backed by the RynthTracker plugin (RynthSuite). // -// Bridge exports (resolved from the RynthTracker plugin DLL via GetProcAddress): -// RynthTrackerGetSnapshotJson() → ANSI JSON object, polled every 500ms -// RynthTrackerReset() → resets session counters + timer +// Data comes from UiDataHub (UiSources.Tracker), which is the only caller of +// RynthTrackerGetSnapshotJson: the export frees its previous buffer on each +// call, so this face and the ImGui face (ImGui/Panels/P1Faces.cs) must never +// call it themselves. Reset goes through the hub too. The background opacity +// is shared with the ImGui face (TrackerSettings). // ============================================================================ using System; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using System.Text.Json; using Avalonia; using Avalonia.Controls; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Threading; -using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; internal static class RynthTrackerPanel { - // ── P/Invoke ────────────────────────────────────────────────────────────── - - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate IntPtr GetSnapshotJsonFn(); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void ResetFn(); - - // ── Bridge state ────────────────────────────────────────────────────────── - - private static GetSnapshotJsonFn? _getSnapshotJson; - private static ResetFn? _reset; - private static bool _bindingLogged; - - // ── Persisted settings ──────────────────────────────────────────────────── - - private static byte _bgAlpha = 0xCC; // ~80% default - // ── Panel construction ──────────────────────────────────────────────────── internal static Control Create() { - LoadSettings(); - TryBind(); // ── Value TextBlocks (updated by poll timer) ─────────────────── // Rates first — most important at the top when panel is tiny. @@ -64,7 +39,7 @@ internal static class RynthTrackerPanel var deathVal = Val(); // ── Background brush — only this changes with the slider ─────── - SolidColorBrush MakeBg() => new(Color.FromArgb(_bgAlpha, 0x0A, 0x12, 0x1A)); + SolidColorBrush MakeBg() => new(Color.FromArgb(TrackerSettings.BgAlpha, 0x0A, 0x12, 0x1A)); var stack = new StackPanel { Orientation = Orientation.Vertical, @@ -76,7 +51,7 @@ internal static class RynthTrackerPanel { Minimum = 0, Maximum = 100, - Value = Math.Round(_bgAlpha / 2.55), + Value = Math.Round(TrackerSettings.BgAlpha / 2.55), Padding = new Thickness(0), Margin = new Thickness(4, 0, 4, 0), VerticalAlignment = VerticalAlignment.Center, @@ -84,9 +59,8 @@ internal static class RynthTrackerPanel }; opacitySlider.ValueChanged += (_, e) => { - _bgAlpha = (byte)Math.Round(e.NewValue * 2.55); + TrackerSettings.SetBgAlpha((byte)Math.Round(e.NewValue * 2.55), save: true); stack.Background = MakeBg(); - SaveSettings(); }; // ── Reset button ─────────────────────────────────────────────── @@ -101,7 +75,7 @@ internal static class RynthTrackerPanel BorderThickness = new Thickness(1), VerticalAlignment = VerticalAlignment.Center, }; - resetBtn.Click += (_, _) => _reset?.Invoke(); + resetBtn.Click += (_, _) => UiSources.Tracker.RequestReset(); // ── Title row: [Tracker] [===slider===] [R] ──────────────────── var titleText = new TextBlock @@ -136,51 +110,35 @@ internal static class RynthTrackerPanel var root = new Grid { ClipToBounds = true }; root.Children.Add(stack); - // ── Poll timer (500ms) ───────────────────────────────────────── + // ── Hub snapshot (500ms) ─────────────────────────────────────── + var values = new[] { sessionVal, xpHrVal, lumHrVal, killHrVal, xpVal, lumVal, killVal, xpkVal, deathVal }; + long seen = -1; var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) }; timer.Tick += (_, _) => { - if (_getSnapshotJson == null) { TryBind(); return; } - - IntPtr ptr = _getSnapshotJson(); - if (ptr == IntPtr.Zero) return; - string? json = Marshal.PtrToStringAnsi(ptr); - if (string.IsNullOrEmpty(json)) return; - - try - { - using var doc = JsonDocument.Parse(json); - var r = doc.RootElement; - - double ss = r.TryGetProperty("ss", out var v) ? v.GetDouble() : 0; - long xt = r.TryGetProperty("xt", out v) ? v.GetInt64() : 0; - long xh = r.TryGetProperty("xh", out v) ? v.GetInt64() : 0; - long lt = r.TryGetProperty("lt", out v) ? v.GetInt64() : 0; - long lh = r.TryGetProperty("lh", out v) ? v.GetInt64() : 0; - int kt = r.TryGetProperty("kt", out v) ? v.GetInt32() : 0; - double kh = r.TryGetProperty("kh", out v) ? v.GetDouble() : 0; - long xk = r.TryGetProperty("xk", out v) ? v.GetInt64() : 0; - int dt = r.TryGetProperty("dt", out v) ? v.GetInt32() : 0; - - var ic = System.Globalization.CultureInfo.InvariantCulture; - sessionVal.Text = FormatTime(ss); - xpHrVal.Text = FormatNum(xh); - lumHrVal.Text = FormatNum(lh); - killHrVal.Text = kh.ToString("F1", ic); - xpVal.Text = FormatNum(xt); - lumVal.Text = FormatNum(lt); - killVal.Text = kt.ToString(); - xpkVal.Text = FormatNum(xk); - deathVal.Text = dt.ToString(); - } - catch { } + var snap = UiSources.Tracker.Current; + if (snap == null || snap.Version == seen) return; + seen = snap.Version; + for (int i = 0; i < values.Length; i++) + values[i].Text = snap.Value.Values[i]; + // Opacity may have been changed by the ImGui face. + stack.Background = MakeBg(); }; - timer.Start(); // Stop with the visual tree — a running DispatcherTimer roots the closed // view forever (one immortal poller per open/close). RadarPanel idiom; - // must restart on attach: drag/resize fires Detached→Attached. - root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); }; - root.DetachedFromVisualTree += (_, _) => timer.Stop(); + // must restart on attach: drag/resize fires Detached→Attached. The hub + // only polls the plugin while some face is subscribed. + root.AttachedToVisualTree += (_, _) => + { + UiSources.Tracker.Subscribe(); + UiSources.Tracker.RequestRefresh(); + if (!timer.IsEnabled) timer.Start(); + }; + root.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.Tracker.Unsubscribe(); + }; return root; } @@ -216,87 +174,4 @@ internal static class RynthTrackerPanel Foreground = Brushes.White, HorizontalAlignment = HorizontalAlignment.Right, }; - - private static string FormatTime(double totalSeconds) - { - var ts = TimeSpan.FromSeconds(totalSeconds); - return ts.TotalHours >= 1 - ? $"{(int)ts.TotalHours}:{ts.Minutes:D2}:{ts.Seconds:D2}" - : $"{ts.Minutes}:{ts.Seconds:D2}"; - } - - private static string FormatNum(long value) - { - if (value == 0) return "0"; - bool neg = value < 0; - string s = (neg ? -value : value).ToString(); - var sb = new System.Text.StringBuilder(s.Length + s.Length / 3); - int offset = s.Length % 3; - for (int i = 0; i < s.Length; i++) - { - if (i > 0 && (i - offset) % 3 == 0) sb.Append(','); - sb.Append(s[i]); - } - return neg ? "-" + sb : sb.ToString(); - } - - // RL loads fresh plugin copies without unloading the old ones: drop the - // exports bound below so the next poll re-binds to the live copy. - static RynthTrackerPanel() => PluginManager.PluginsUnloaded += () => - { - _getSnapshotJson = null; - _reset = null; - }; - - private static void TryBind() - { - LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthTracker", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - _getSnapshotJson ??= Bind<GetSnapshotJsonFn>(plugin, "RynthTrackerGetSnapshotJson"); - _reset ??= Bind<ResetFn>(plugin, "RynthTrackerReset"); - - if (!_bindingLogged && _getSnapshotJson != null) - { - _bindingLogged = true; - RynthLog.UI("RynthTrackerPanel: bound RynthTracker plugin exports."); - } - } - - private static T? Bind<T>(LoadedPlugin plugin, string exportName) where T : Delegate - { - IntPtr addr = GetProcAddress(plugin.ModuleHandle, exportName); - return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr); - } - - // ── Settings persistence ────────────────────────────────────────────────── - - private static string SettingsPath => - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "RynthCore", "rynthtracker_settings.json"); - - private static void LoadSettings() - { - try - { - string path = SettingsPath; - if (!File.Exists(path)) return; - using var doc = JsonDocument.Parse(File.ReadAllText(path)); - if (doc.RootElement.TryGetProperty("bgAlpha", out var v)) - _bgAlpha = (byte)Math.Clamp(v.GetInt32(), 0, 255); - } - catch { } - } - - private static void SaveSettings() - { - try - { - string path = SettingsPath; - Directory.CreateDirectory(Path.GetDirectoryName(path)!); - File.WriteAllText(path, $"{{\"bgAlpha\":{_bgAlpha}}}"); - } - catch { } - } } diff --git a/src/RynthCore.Engine/UI/Panels/RynthVisionPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthVisionPanel.cs index 5fa87f5..06810c8 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthVisionPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthVisionPanel.cs @@ -1,20 +1,19 @@ // ============================================================================ // RynthCore.Engine — UI/Panels/RynthVisionPanel.cs -// Avalonia settings panel for the RynthVision plugin (RynthSuite). Bridges to -// the plugin via GetProcAddress on its DLL: reads settings JSON to populate -// controls and pushes changes back. Replaces the abandoned in-plugin ImGui UI. +// Avalonia settings panel for the RynthVision plugin (RynthSuite): reads the +// settings JSON to populate controls and pushes changes back. // -// Bridge exports (resolved from the RynthVision plugin DLL): -// RynthVisionGetSettingsJson() → ANSI JSON of current settings -// RynthVisionSetSettings(char* json) → apply + persist settings -// RynthVisionInspectTerrain() → log terrain types under the player +// Data goes through UiDataHub (UI/Data/VisionData.cs): UiSources.Vision polls +// RynthVisionGetSettingsJson on the pump thread; VisionCommands saves +// (RynthVisionSetSettings) and runs RynthVisionInspectTerrain there. The +// ImGui face (ImGui/Panels/VisionFace.cs) reads the same snapshot. Each +// change pushes only its own field, like the ImGui face. // ============================================================================ using System; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; -using System.Text; using System.Text.Json; using Avalonia; using Avalonia.Controls; @@ -23,30 +22,12 @@ using Avalonia.Media; using Avalonia.Threading; using RynthCore.Engine.ImGuiBackend; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; internal static class RynthVisionPanel { - // ── P/Invoke ────────────────────────────────────────────────────────────── - - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate IntPtr GetSettingsJsonFn(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void SetSettingsFn(IntPtr ansiJson); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void InspectFn(); - - // ── Bridge state ────────────────────────────────────────────────────────── - - private static GetSettingsJsonFn? _getSettings; - private static SetSettingsFn? _setSettings; - private static InspectFn? _inspect; - private static bool _bindingLogged; - // ── Controls (Avalonia UI thread only) ───────────────────────────────────── private static CheckBox? _cbRadar, _cbSlopes, _cbWater, _cbWaterAnyCorner, _cbWaterImpassableOnly; @@ -62,6 +43,14 @@ internal static class RynthVisionPanel private static bool _populated; private static int _createCounter; + // The panel's one retry timer (see Create). It also re-runs Populate after + // a water-types save: the plugin may normalise the list (empty resets to + // the defaults), so the box is refreshed from the first snapshot newer + // than _populateAfterVersion. + private static DispatcherTimer? _populateTimer; + private static int _populateRetries; + private static long _populateAfterVersion = -1; + // ── Panel construction ────────────────────────────────────────────────────── internal static Control Create() @@ -79,6 +68,7 @@ internal static class RynthVisionPanel // Populate flips _suppressPush back to false in its finally block. _populated = false; _suppressPush = true; + _populateAfterVersion = -1; int createN = System.Threading.Interlocked.Increment(ref _createCounter); RynthLog.UI($"RynthVisionPanel.Create #{createN}: starting (_populated reset, _suppressPush=true)"); @@ -89,43 +79,41 @@ internal static class RynthVisionPanel _cbRadar = AddCheck(root, "Radar range ring"); _cbSlopes = AddCheck(root, "Unclimbable slopes"); _cbWater = AddCheck(root, "Impassable water"); - var dungeon = AddCheck(root, "Dungeon lighting (planned)"); - dungeon.IsEnabled = false; - _cbRadar.IsCheckedChanged += (_, _) => Push(); - _cbSlopes.IsCheckedChanged += (_, _) => Push(); - _cbWater.IsCheckedChanged += (_, _) => Push(); + _cbRadar.IsCheckedChanged += (_, _) => Push(VisionKeys.Radar); + _cbSlopes.IsCheckedChanged += (_, _) => Push(VisionKeys.Slopes); + _cbWater.IsCheckedChanged += (_, _) => Push(VisionKeys.Water); root.Children.Add(Header("Colors (hex AARRGGBB)")); - (_tbSlope, _swSlope) = AddColorRow(root, "Slope", () => _slopeColor, c => _slopeColor = c); - (_tbWater, _swWater) = AddColorRow(root, "Water", () => _waterColor, c => _waterColor = c); - (_tbRadar, _swRadar) = AddColorRow(root, "Radar", () => _radarColor, c => _radarColor = c); + (_tbSlope, _swSlope) = AddColorRow(root, "Slope", VisionKeys.SlopeColor, () => _slopeColor, c => _slopeColor = c); + (_tbWater, _swWater) = AddColorRow(root, "Water", VisionKeys.WaterColor, () => _waterColor, c => _waterColor = c); + (_tbRadar, _swRadar) = AddColorRow(root, "Radar", VisionKeys.RadarColor, () => _radarColor, c => _radarColor = c); root.Children.Add(Header("Tuning")); - (_slRange, _) = AddSlider(root, "Radar range", 24, 300, 0, false); - (_slThick, _) = AddSlider(root, "Ring thickness", 0.5, 6, 1, false); - (_slHeight, _) = AddSlider(root, "Ring height (m)",0.5, 30, 1, false); - (_slSlopeR, _) = AddSlider(root, "Slope radius (cells)", 1, 24, 0, true); - (_slSlopeFloor, _)= AddSlider(root, "Slope floor Z", 0.30, 0.95, 3, false); - (_slSlopeBias, _) = AddSlider(root, "Slope height bias (m)",0.00, 1.00, 2, false); - (_slWaterR, _) = AddSlider(root, "Water radius (cells)", 1, 24, 0, true); + (_slRange, _) = AddSlider(root, "Radar range", VisionKeys.RadarRange, 24, 300, 0, false); + (_slThick, _) = AddSlider(root, "Ring thickness", VisionKeys.RingThick, 0.5, 6, 1, false); + (_slHeight, _) = AddSlider(root, "Ring height (m)",VisionKeys.RingHeight, 0.5, 30, 1, false); + (_slSlopeR, _) = AddSlider(root, "Slope radius (cells)", VisionKeys.SlopeRadius, 1, 24, 0, true); + (_slSlopeFloor, _)= AddSlider(root, "Slope floor Z", VisionKeys.SlopeFloorZ, 0.30, 0.95, 3, false); + (_slSlopeBias, _) = AddSlider(root, "Slope height bias (m)",VisionKeys.SlopeBias, 0.00, 1.00, 2, false); + (_slWaterR, _) = AddSlider(root, "Water radius (cells)", VisionKeys.WaterRadius, 1, 24, 0, true); root.Children.Add(Header("Water terrain types")); _cbWaterAnyCorner = AddCheck(root, "Highlight cell if ANY corner is water (else all four)"); - _cbWaterAnyCorner.IsCheckedChanged += (_, _) => Push(); + _cbWaterAnyCorner.IsCheckedChanged += (_, _) => Push(VisionKeys.WaterAnyCorner); _cbWaterImpassableOnly = AddCheck(root, "Only paint water cells with an unwalkable triangle (real impassable)"); - _cbWaterImpassableOnly.IsCheckedChanged += (_, _) => Push(); + _cbWaterImpassableOnly.IsCheckedChanged += (_, _) => Push(VisionKeys.WaterImpassableOnly); _tbWaterTypes = new TextBox { Watermark = "18,19,20", FontSize = 11, MinWidth = 120 }; _tbWaterTypes.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true; - _tbWaterTypes.LostFocus += (_, _) => { Win32Backend.AvaloniaTextInputActive = false; Push(); }; + _tbWaterTypes.LostFocus += (_, _) => { Win32Backend.AvaloniaTextInputActive = false; Push(VisionKeys.WaterTypes); }; var applyBtn = new Button { Content = "Apply", FontSize = 11, Margin = new Thickness(4, 0, 0, 0) }; - applyBtn.Click += (_, _) => Push(); + applyBtn.Click += (_, _) => Push(VisionKeys.WaterTypes); var wtRow = new StackPanel { Orientation = Orientation.Horizontal }; wtRow.Children.Add(_tbWaterTypes); wtRow.Children.Add(applyBtn); root.Children.Add(wtRow); var inspectBtn = new Button { Content = "Log terrain types here", FontSize = 11, Margin = new Thickness(0, 4, 0, 0) }; - inspectBtn.Click += (_, _) => { TryBind(); _inspect?.Invoke(); }; + inspectBtn.Click += (_, _) => VisionCommands.Inspect(); root.Children.Add(inspectBtn); // Bind + populate once the plugin DLL is loaded AND the plugin has @@ -136,14 +124,15 @@ internal static class RynthVisionPanel // Retries every 500 ms until Populate succeeds (returns true) or the // panel is closed. Caps at 60 retries (~30 s) so we don't spin forever // if the plugin never initializes. - int retries = 0; + _populateRetries = 0; var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) }; + _populateTimer?.Stop(); + _populateTimer = timer; timer.Tick += (_, _) => { if (_populated) { timer.Stop(); return; } - if (++retries > 60) { timer.Stop(); RynthLog.UI("RynthVisionPanel: gave up populating after 30s"); return; } - TryBind(); - if (_getSettings != null && Populate()) + if (++_populateRetries > 60) { timer.Stop(); RynthLog.UI("RynthVisionPanel: gave up populating after 30s"); return; } + if (Populate()) { _populated = true; timer.Stop(); @@ -151,7 +140,19 @@ internal static class RynthVisionPanel }; timer.Start(); - return new ScrollViewer { Content = root }; + var scroll = new ScrollViewer { Content = root }; + scroll.AttachedToVisualTree += (_, _) => + { + UiSources.Vision.Subscribe(); + UiSources.Vision.RequestRefresh(); + if (!_populated && !timer.IsEnabled) { _populateRetries = 0; timer.Start(); } + }; + scroll.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.Vision.Unsubscribe(); + }; + return scroll; } // ── Control factories ─────────────────────────────────────────────────────── @@ -172,7 +173,7 @@ internal static class RynthVisionPanel return cb; } - private static (Slider, TextBlock) AddSlider(StackPanel parent, string name, double min, double max, int decimals, bool snap) + private static (Slider, TextBlock) AddSlider(StackPanel parent, string name, string key, double min, double max, int decimals, bool snap) { var label = new TextBlock { FontSize = 11, Foreground = Brushes.White, Text = name + ":" }; var slider = new Slider { Minimum = min, Maximum = max, Width = 170, VerticalAlignment = VerticalAlignment.Center }; @@ -212,7 +213,7 @@ internal static class RynthVisionPanel syncing = true; box.Text = s; syncing = false; - Push(); + Push(key); }; box.GotFocus += (_, _) => { @@ -237,14 +238,14 @@ internal static class RynthVisionPanel box.Text = s; label.Text = $"{name}: {s}"; syncing = false; - Push(); + Push(key); } }; return (slider, label); } - private static (TextBox, Border) AddColorRow(StackPanel parent, string name, Func<uint> get, Action<uint> set) + private static (TextBox, Border) AddColorRow(StackPanel parent, string name, string key, Func<uint> get, Action<uint> set) { var lbl = new TextBlock { Text = name, FontSize = 11, Foreground = Brushes.White, Width = 44, VerticalAlignment = VerticalAlignment.Center }; var tb = new TextBox { FontSize = 11, Width = 92, FontFamily = new FontFamily("Consolas,monospace") }; @@ -259,46 +260,12 @@ internal static class RynthVisionPanel tb.LostFocus += (_, _) => { Win32Backend.AvaloniaTextInputActive = false; - if (TryParseHex(tb.Text, out uint c)) { set(c); sw.Background = ToBrush(c); Push(); } + if (TryParseHex(tb.Text, out uint c)) { set(c); sw.Background = ToBrush(c); Push(key); } else tb.Text = get().ToString("X8"); // revert on bad input }; return (tb, sw); } - // ── Plugin binding ──────────────────────────────────────────────────────── - - // RL loads fresh plugin copies without unloading the old ones: drop the - // exports bound below so the next poll re-binds to the live copy. - static RynthVisionPanel() => PluginManager.PluginsUnloaded += () => - { - _getSettings = null; - _setSettings = null; - _inspect = null; - }; - - private static void TryBind() - { - LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthVision", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - _getSettings ??= Bind<GetSettingsJsonFn>(plugin, "RynthVisionGetSettingsJson"); - _setSettings ??= Bind<SetSettingsFn>(plugin, "RynthVisionSetSettings"); - _inspect ??= Bind<InspectFn>(plugin, "RynthVisionInspectTerrain"); - - if (!_bindingLogged && _getSettings != null) - { - _bindingLogged = true; - RynthLog.UI("RynthVisionPanel: bound RynthVision plugin exports."); - } - } - - private static T? Bind<T>(LoadedPlugin plugin, string export) where T : Delegate - { - IntPtr addr = GetProcAddress(plugin.ModuleHandle, export); - return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr); - } - // ── Sync ────────────────────────────────────────────────────────────────── /// <summary> @@ -310,10 +277,9 @@ internal static class RynthVisionPanel /// </summary> private static bool Populate() { - if (_getSettings == null) return false; - IntPtr ptr = _getSettings(); - if (ptr == IntPtr.Zero) return false; - string? json = Marshal.PtrToStringAnsi(ptr); + var snap = UiSources.Vision.Current; + if (snap == null || snap.Version <= _populateAfterVersion) return false; + string? json = snap.Value.Json; if (string.IsNullOrEmpty(json) || json == "{}") return false; RynthLog.UI($"RynthVisionPanel.Populate: applying JSON ({json.Length} chars): {json}"); @@ -352,46 +318,59 @@ internal static class RynthVisionPanel return true; } - private static void Push() + /// <summary> + /// Saves just the field that changed (<paramref name="key"/>, a + /// <see cref="VisionKeys"/> constant) from its control, so values changed + /// elsewhere since Populate (a /rv command, the ImGui face) aren't + /// written back over. + /// </summary> + private static void Push(string key) { if (_suppressPush) { RynthLog.UI("RynthVisionPanel.Push: SUPPRESSED (Populate in flight or panel not yet ready)"); return; } - if (_setSettings == null) - { - RynthLog.UI("RynthVisionPanel.Push: SKIPPED (plugin not yet bound)"); - return; - } var ci = CultureInfo.InvariantCulture; - var sb = new StringBuilder(256); - sb.Append('{'); - sb.Append("\"radar\":").Append(_cbRadar?.IsChecked == true ? 1 : 0).Append(','); - sb.Append("\"slopes\":").Append(_cbSlopes?.IsChecked == true ? 1 : 0).Append(','); - sb.Append("\"water\":").Append(_cbWater?.IsChecked == true ? 1 : 0).Append(','); - sb.Append("\"slopeColor\":").Append(_slopeColor).Append(','); - sb.Append("\"waterColor\":").Append(_waterColor).Append(','); - sb.Append("\"radarColor\":").Append(_radarColor).Append(','); - sb.Append("\"radarRange\":").Append((_slRange?.Value ?? 192).ToString("R", ci)).Append(','); - sb.Append("\"ringThick\":").Append((_slThick?.Value ?? 2).ToString("R", ci)).Append(','); - sb.Append("\"ringHeight\":").Append((_slHeight?.Value ?? 3).ToString("R", ci)).Append(','); - sb.Append("\"slopeRadius\":").Append((int)(_slSlopeR?.Value ?? 12)).Append(','); - sb.Append("\"slopeFloorZ\":").Append((_slSlopeFloor?.Value ?? 0.664).ToString("R", ci)).Append(','); - sb.Append("\"slopeBias\":").Append((_slSlopeBias?.Value ?? 0.15).ToString("R", ci)).Append(','); - sb.Append("\"waterRadius\":").Append((int)(_slWaterR?.Value ?? 12)).Append(','); - sb.Append("\"waterAnyCorner\":").Append(_cbWaterAnyCorner?.IsChecked == true ? 1 : 0).Append(','); - sb.Append("\"waterImpassableOnly\":").Append(_cbWaterImpassableOnly?.IsChecked == true ? 1 : 0).Append(','); - sb.Append("\"waterTypes\":[").Append(CleanCsv(_tbWaterTypes?.Text)).Append(']'); - sb.Append('}'); + string? value = key switch + { + VisionKeys.Radar => Flag(_cbRadar), + VisionKeys.Slopes => Flag(_cbSlopes), + VisionKeys.Water => Flag(_cbWater), + VisionKeys.WaterAnyCorner => Flag(_cbWaterAnyCorner), + VisionKeys.WaterImpassableOnly => Flag(_cbWaterImpassableOnly), + VisionKeys.SlopeColor => _slopeColor.ToString(ci), + VisionKeys.WaterColor => _waterColor.ToString(ci), + VisionKeys.RadarColor => _radarColor.ToString(ci), + VisionKeys.RadarRange => _slRange?.Value.ToString("R", ci), + VisionKeys.RingThick => _slThick?.Value.ToString("R", ci), + VisionKeys.RingHeight => _slHeight?.Value.ToString("R", ci), + VisionKeys.SlopeRadius => _slSlopeR != null ? ((int)_slSlopeR.Value).ToString(ci) : null, + VisionKeys.SlopeFloorZ => _slSlopeFloor?.Value.ToString("R", ci), + VisionKeys.SlopeBias => _slSlopeBias?.Value.ToString("R", ci), + VisionKeys.WaterRadius => _slWaterR != null ? ((int)_slWaterR.Value).ToString(ci) : null, + // Empty resets to the defaults in the plugin; the republish after + // the save repopulates the box. + VisionKeys.WaterTypes => "[" + CleanCsv(_tbWaterTypes?.Text) + "]", + _ => null, + }; + if (value == null) return; - string outJson = sb.ToString(); - RynthLog.UI($"RynthVisionPanel.Push: writing JSON ({outJson.Length} chars): {outJson}"); - IntPtr p = Marshal.StringToHGlobalAnsi(outJson); - try { _setSettings(p); } - finally { Marshal.FreeHGlobal(p); } + string outJson = "{\"" + key + "\":" + value + "}"; + RynthLog.UI($"RynthVisionPanel.Push: writing JSON: {outJson}"); + VisionCommands.Save(outJson); + + if (key == VisionKeys.WaterTypes) + { + _populateAfterVersion = UiSources.Vision.Current?.Version ?? 0; + _populated = false; + _populateRetries = 0; + _populateTimer?.Start(); + } } + private static string? Flag(CheckBox? cb) => cb == null ? null : (cb.IsChecked == true ? "1" : "0"); + // ── Helpers ─────────────────────────────────────────────────────────────── private static void SetColor(TextBox? tb, Border? sw, uint argb) diff --git a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs index 1ac5170..c8f4e1d 100644 --- a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs @@ -2,12 +2,10 @@ // RynthCore.Engine — UI/Panels/SettingsPanel.cs // Avalonia replica of LegacyAdvancedSettingsUi (RynthSuite plugin). // -// 11 tabs: Display | UI | Misc | Recharge | Melee Combat | Spell Combat | -// Ranges | Navigation | Buffing | Crafting | Looting -// -// Plugin exports used: -// RynthPluginGetSettingsJson → polled every 5s for external edits -// RynthPluginSetSettingsJson → immediate write-back on any control change +// Tabs and rows come from SettingsSchema (UI/Data/SettingsData.cs), which +// the ImGui face draws too: add a setting there, not here. Data goes through +// UiDataHub (UiSources.Settings, SettingsCommands.Save), so the plugin's +// exports run on the pump thread instead of this UI thread. // ============================================================================ using System; @@ -25,26 +23,12 @@ using Avalonia.Media; using Avalonia.Threading; using RynthCore.Engine.ImGuiBackend; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; -[JsonSerializable(typeof(SettingsPanel.Settings))] -[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)] -internal partial class SettingsPanelJsonContext : JsonSerializerContext { } - internal static class SettingsPanel { - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate IntPtr GetSettingsJsonFn(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void SetSettingsJsonFn(IntPtr ansiJson); - - private static GetSettingsJsonFn? _getSettingsJson; - private static SetSettingsJsonFn? _setSettingsJson; - // ── Color palette (shared with other panels) ───────────────────────────── private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6)); private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33)); @@ -59,181 +43,12 @@ internal static class SettingsPanel private static readonly IBrush ColToggleOff = new SolidColorBrush(Color.FromRgb(0x33, 0x44, 0x55)); private static readonly IBrush ColTabActive = new SolidColorBrush(Color.FromRgb(0x1A, 0x2E, 0x42)); - private static readonly string[] Tabs = - { "Display", "UI", "Misc", "Recharge", "Melee Combat", "Spell Combat", - "Ranges", "Navigation", "Buffing", "Crafting", "Looting", "Vendoring" }; - - private static readonly string[] AttackHeights = { "Low", "Medium", "High" }; - private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" }; - private static readonly string[] MovementModes = { "Legacy (Autorun)", "Tier 1 (CM_Movement)", "Tier 2 (MoveToPosition)" }; - - // ── Settings mirror (matches SettingsBridgePayload on plugin side) ──────── - internal sealed class Settings - { - // Display - public bool ShowTargetStaminaMana { get; set; } - // UI - public bool SuppressRetailRadar { get; set; } - public bool ShowRynthRadar { get; set; } - public bool RadarClickThrough { get; set; } - // NOTE: retail-chatbox suppression intentionally removed here — it is owned by the - // RynthChat plugin ("Hide retail chat" in the RynthChat panel's gear menu). Routing it - // through RynthAi's settings push fought that toggle and didn't work. See RynthChatPanel. - public bool ShowRynthChat { get; set; } - public bool ChatClickThrough { get; set; } - public bool SuppressRetailPowerbar { get; set; } - // Misc - public bool EnableFPSLimit { get; set; } - public int TargetFPSFocused { get; set; } = 60; - public int TargetFPSBackground { get; set; } = 30; - public bool EnableAutocram { get; set; } - public bool PeaceModeWhenIdle { get; set; } - public bool StartMacroOnLogin { get; set; } - public bool PatrolOnLogin { get; set; } - public bool EnableRaycasting { get; set; } - public bool UseArcs { get; set; } - public float BowArcVelocity { get; set; } = 25f; - public float MissileArcClearance { get; set; } = 0.5f; - // Vendoring (RynthAi AutoVendor; defaults match LegacyUiSettings) - public bool AutoVendorEnabled { get; set; } - public bool AutoVendorEnableBuying { get; set; } = true; - public bool AutoVendorEnableSelling { get; set; } = true; - public bool AutoVendorTestMode { get; set; } = true; - public bool AutoVendorThink { get; set; } - public bool AutoVendorShowMerchantInfo { get; set; } = true; - public bool AutoVendorOnlyFromMainPack { get; set; } - public int AutoVendorTries { get; set; } = 4; - public int AutoVendorTriesTime { get; set; } = 5000; - public bool LosDebugLog { get; set; } - public float CrossbowArcVelocity { get; set; } = 40f; - public float AtlatlArcVelocity { get; set; } = 22f; - public float MagicArcVelocity { get; set; } = 25f; - public int BlacklistAttempts { get; set; } = 3; - public int BlacklistTimeoutSec { get; set; } = 30; - // Not shown in this panel, but carried so a save doesn't send them missing: - // RynthAi applied the missing value as 0 on every panel click (2026-09-27). - public int BlacklistCastSettleMs { get; set; } = 1500; - public int MonsterDisengageRange { get; set; } - public int TargetNoProgressTimeoutSec { get; set; } - public int GiveQueueIntervalMs { get; set; } = 150; - // Recharge - public int HealAt { get; set; } = 60; - public int RestamAt { get; set; } = 30; - public int GetManaAt { get; set; } = 40; - public int TopOffHP { get; set; } = 95; - public int TopOffStam { get; set; } = 95; - public int TopOffMana { get; set; } = 95; - public int HealOthersAt { get; set; } = 50; - public int RestamOthersAt { get; set; } = 10; - public int InfuseOthersAt { get; set; } = 10; - // Melee Combat - public bool UseRecklessness { get; set; } - public int MeleeAttackPower { get; set; } = -1; - public int MeleeAttackHeight { get; set; } = 1; - public int MissileAttackPower { get; set; } = -1; - public int MissileAttackHeight { get; set; } = 1; - public bool UseNativeAttack { get; set; } = true; - public bool SummonPets { get; set; } - public int PetMinMonsters { get; set; } = 1; - // Spell Combat - public int SpellCastIntervalMs { get; set; } = 400; - public int AttackSpellIntervalMs { get; set; } = 1500; - public bool CastDispelSelf { get; set; } - public int MinRingTargets { get; set; } = 4; - public int MinSkillLevelTier1 { get; set; } = 35; - public int MinSkillLevelTier2 { get; set; } = 85; - public int MinSkillLevelTier3 { get; set; } = 135; - public int MinSkillLevelTier4 { get; set; } = 185; - public int MinSkillLevelTier5 { get; set; } = 235; - public int MinSkillLevelTier6 { get; set; } = 285; - public int MinSkillLevelTier7 { get; set; } = 335; - public int MinSkillLevelTier8 { get; set; } = 435; - // Ranges - public int MonsterRange { get; set; } = 50; - public int RingRange { get; set; } = 5; - public int ApproachRange { get; set; } = 4; - public double CorpseApproachRangeMax { get; set; } = 10.0; - public double CorpseApproachRangeMin { get; set; } = 2.0; - // Navigation - public bool BoostNavPriority { get; set; } - public float FollowNavMin { get; set; } = 1.5f; - public float NavRingThickness { get; set; } = 6f; - public float NavLineThickness { get; set; } = 6f; - public float NavHeightOffset { get; set; } = 0.05f; - public float NavSlopeSink { get; set; } = 1.5f; - public bool ShowTerrainPassability { get; set; } = true; - public bool OpenDoors { get; set; } - public float OpenDoorRange { get; set; } = 5f; - public bool AutoUnlockDoors { get; set; } - public int MovementMode { get; set; } - public float NavStopTurnAngle { get; set; } = 20f; - public float NavResumeTurnAngle { get; set; } = 10f; - public float NavDeadZone { get; set; } = 4f; - public float NavSweepMult { get; set; } = 2.5f; - public float NavLookaheadYards { get; set; } = 4f; - public float NavShortcutYards { get; set; } = 1f; - public float NavTurnRateDegPerSec { get; set; } = 270f; - public float NavTier1TurnSpeed { get; set; } = 3f; - public float PostPortalDelaySec { get; set; } = 4f; - public float T2Speed { get; set; } = 1f; - public float T2WalkWithinYd { get; set; } = 5f; - public float T2DistanceTo { get; set; } = 0.5f; - public float T2ReissueMs { get; set; } = 2000f; - public float T2MaxRangeYd { get; set; } = 500f; - public int T2MaxLandblocks { get; set; } = 3; - // Buffing - public bool EnableBuffing { get; set; } = true; - public bool RebuffWhenIdle { get; set; } - public int RebuffSecondsRemaining { get; set; } = 300; - public int RebuffTopOffSecondsRemaining { get; set; } = 1200; - public int BuffMinSkillLevelTier1 { get; set; } = 35; - public int BuffMinSkillLevelTier2 { get; set; } = 85; - public int BuffMinSkillLevelTier3 { get; set; } = 135; - public int BuffMinSkillLevelTier4 { get; set; } = 185; - public int BuffMinSkillLevelTier5 { get; set; } = 235; - public int BuffMinSkillLevelTier6 { get; set; } = 285; - public int BuffMinSkillLevelTier7 { get; set; } = 335; - public int BuffMinSkillLevelTier8 { get; set; } = 435; - // Crafting - public bool EnableMissileCrafting { get; set; } = true; - public string MissileCraftingState { get; set; } = string.Empty; - public bool MissileCraftingActive { get; set; } - public string MissileCraftingStatus { get; set; } = string.Empty; - // Looting - public bool EnableLooting { get; set; } - public bool BoostLootPriority { get; set; } - public bool LootOnlyRareCorpses { get; set; } - public bool LootJumpEnabled { get; set; } - public int LootJumpHeight { get; set; } = 10; - public int LootOwnership { get; set; } - public bool EnableAutostack { get; set; } = true; - public bool EnableCombineSalvage { get; set; } = true; - public bool CombineBagsDuringSalvage { get; set; } = true; - public int LootInterItemDelayMs { get; set; } = 50; - public int LootContentSettleMs { get; set; } = 100; - public int LootEmptyCorpseMs { get; set; } = 300; - public int LootClosingDelayMs { get; set; } = 200; - public int LootAssessWindowMs { get; set; } = 200; - public int LootRetryTimeoutMs { get; set; } = 500; - public int LootOpenRetryMs { get; set; } = 1500; - public int LootCorpseTimeoutMs { get; set; } = 12000; - public int SalvageOpenDelayFirstMs { get; set; } = 400; - public int SalvageOpenDelayFastMs { get; set; } = 50; - public int SalvageAddDelayFirstMs { get; set; } = 600; - public int SalvageAddDelayFastMs { get; set; } = 50; - public int SalvageSalvageDelayMs { get; set; } = 50; - public int SalvageResultDelayFirstMs { get; set; } = 1000; - public int SalvageResultDelayFastMs { get; set; } = 250; - } - private sealed class PanelState { - public Settings Data = new(); + public RynthAiSettings Data = new(); public int SelectedTab; - public bool Dirty; - // UI deep-dive finding TL;DR #9 (2026-07-02): raw JSON from the last - // poll that actually rebuilt content — see the timer.Tick JSON gate. - public string? LastJson; + // Hub snapshot version last applied (replaces the old raw-JSON gate). + public long SeenVersion = -1; // Companion fix (SettingsPanel.cs:501 finding): visibility-gating // controls (EnableFPSLimit, UseArcs, meleeAuto, missileAuto, // OpenDoors, MovementMode, EnableMissileCrafting, LootJumpEnabled) @@ -321,7 +136,6 @@ internal static class SettingsPanel public static Control Create() { - TryBind(); var state = new PanelState(); var root = new Border @@ -387,12 +201,13 @@ internal static class SettingsPanel // ── Tab buttons ─────────────────────────────────────────────────────── var tabButtons = new List<Button>(); - for (int i = 0; i < Tabs.Length; i++) + SettingsTab[] tabs = SettingsSchema.Tabs; + for (int i = 0; i < tabs.Length; i++) { int idx = i; var btn = new Button { - Content = Tabs[i], + Content = tabs[i].Name, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Left, Background = ColBtnFill, @@ -417,45 +232,43 @@ internal static class SettingsPanel state.Rebuild = () => RebuildContent(state, contentStack, picker); - // ── Initial data load ───────────────────────────────────────────────── - if (TryFetch(out var initial)) state.Data = initial; + // ── Data: the hub's settings snapshot ───────────────────────────────── + void ApplySnapshot() + { + var snap = UiSources.Settings.Current; + if (snap == null || snap.Version == state.SeenVersion) return; + state.SeenVersion = snap.Version; + state.Data = snap.Value.Clone(); + RebuildContent(state, contentStack, picker); + } + picker.Root = root; UpdateTabHighlight(tabButtons, 0); RebuildContent(state, contentStack, picker); - // ── Poll timer ──────────────────────────────────────────────────────── - var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) }; + // Poll the snapshot (the hub fetches every 5 s while subscribed, and + // right after each save). Never while a field is being typed in: that + // used to clobber in-progress edits (UI deep-dive TL;DR #9). + var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) }; timer.Tick += (_, _) => { - if (_getSettingsJson == null) TryBind(); - if (state.Dirty) return; - // UI deep-dive finding TL;DR #9 (2026-07-02): state.Dirty was - // declared, checked, and reset — but never actually SET true - // anywhere in this file, making the guard above dead code. This - // rebuild ran unconditionally every 5s, clobbering whatever the - // user was doing in ANY field (in-progress typing, an open - // picker, a slider mid-drag) with a fresh copy from the plugin. - // Real guards: (1) AvaloniaTextInputActive is already wired by - // every TextBox in this panel (GotFocus/LostFocus below) — reuse - // it directly as a focus guard instead of the dead Dirty flag. - // (2) A raw-JSON diff — the full payload (all settings including - // any gating toggles) is compared, so a rebuild still fires - // whenever a toggle that would reveal/hide conditional rows - // actually changes; nothing is excluded from this gate the way - // PayloadSig deliberately excludes fields elsewhere. if (Win32Backend.AvaloniaTextInputActive) return; - if (!TryFetch(out var fresh, out string? rawJson)) return; - if (rawJson != null && rawJson == state.LastJson) return; - state.LastJson = rawJson; - state.Data = fresh; - RebuildContent(state, contentStack, picker); + ApplySnapshot(); }; - timer.Start(); // Stop with the visual tree — a running DispatcherTimer roots the closed // view forever (one immortal poller per open/close). RadarPanel idiom; // must restart on attach: drag/resize fires Detached→Attached. - root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); }; - root.DetachedFromVisualTree += (_, _) => timer.Stop(); + root.AttachedToVisualTree += (_, _) => + { + UiSources.Settings.Subscribe(); + UiSources.Settings.RequestRefresh(); + if (!timer.IsEnabled) timer.Start(); + }; + root.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.Settings.Unsubscribe(); + }; return root; } @@ -476,7 +289,7 @@ internal static class SettingsPanel // Tab header var header = new TextBlock { - Text = $"Advanced Settings > {Tabs[state.SelectedTab]}", + Text = $"Advanced Settings > {SettingsSchema.Tabs[state.SelectedTab].Name}", Foreground = ColTeal, FontSize = 11, FontWeight = Avalonia.Media.FontWeight.Bold, @@ -485,507 +298,73 @@ internal static class SettingsPanel panel.Children.Add(header); panel.Children.Add(new Border { Height = 1, Background = ColBtnBord, Margin = new Thickness(0, 0, 0, 6) }); - switch (state.SelectedTab) + foreach (SettingRow row in SettingsSchema.Tabs[state.SelectedTab].Rows) { - case 0: BuildDisplayTab(state, panel, picker); break; - case 1: BuildUITab(state, panel, picker); break; - case 2: BuildMiscTab(state, panel, picker); break; - case 3: BuildRechargeTab(state, panel, picker); break; - case 4: BuildMeleeCombatTab(state, panel, picker); break; - case 5: BuildSpellCombatTab(state, panel, picker); break; - case 6: BuildRangesTab(state, panel, picker); break; - case 7: BuildNavigationTab(state, panel, picker); break; - case 8: BuildBuffingTab(state, panel, picker); break; - case 9: BuildCraftingTab(state, panel, picker); break; - case 10: BuildLootingTab(state, panel, picker); break; - case 11: BuildVendoringTab(state, panel, picker); break; + if (!row.IsVisible(state.Data)) continue; + Control? control = BuildRow(state, row, picker); + if (control != null) panel.Children.Add(control); } } - // ========================================================================= - // Tab content builders - // ========================================================================= - - private static void BuildDisplayTab(PanelState state, StackPanel p, PickerState picker) + /// <summary>One schema row as the Avalonia control it has always been.</summary> + private static Control? BuildRow(PanelState state, SettingRow row, PickerState picker) { - p.Children.Add(BoolRow("Show Target Stamina / Mana", - state.Data.ShowTargetStaminaMana, - v => { state.Data.ShowTargetStaminaMana = v; Push(state); }, - "When enabled, displays stamina and mana bars for the selected target (requires appraisal data).")); - } - - private static void BuildUITab(PanelState state, StackPanel p, PickerState picker) - { - p.Children.Add(SectionHeader("Radar")); - p.Children.Add(BoolRow("Get Rid of Retail Radar", state.Data.SuppressRetailRadar, - v => { state.Data.SuppressRetailRadar = v; Push(state); }, - "Suppress the game's built-in radar (bezel, compass, coords, blips).")); - p.Children.Add(BoolRow("Show RynthRadar", state.Data.ShowRynthRadar, - v => { state.Data.ShowRynthRadar = v; Push(state); }, - "Render the custom square radar widget (indoor walls + dot markers, works outdoors).")); - p.Children.Add(BoolRow("Radar Click-Through", state.Data.RadarClickThrough, - v => { state.Data.RadarClickThrough = v; Push(state); }, - "Mouse events over the radar pass through to the game instead of the widget.")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Chat")); - // "Get Rid of Retail Chatbox" lives in the RynthChat panel's gear menu ("Hide retail chat"), - // which owns ChatHooks.SuppressOriginalChat directly. The old row here routed through RynthAi's - // settings push and was clobbered every tick, so it was removed. - p.Children.Add(BoolRow("Show RynthChat", state.Data.ShowRynthChat, - v => { state.Data.ShowRynthChat = v; Push(state); }, - "Render the custom chat viewer (scrollback + channel coloring).")); - p.Children.Add(BoolRow("Chat Click-Through", state.Data.ChatClickThrough, - v => { state.Data.ChatClickThrough = v; Push(state); }, - "Mouse events over the chat pass through to the game. The gear button stays clickable.")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Power Bar")); - p.Children.Add(BoolRow("Get Rid of Retail Power Bar", state.Data.SuppressRetailPowerbar, - v => { state.Data.SuppressRetailPowerbar = v; Push(state); }, - "Hide the vanilla attack/magic power bar that appears under the cursor while charging.\nThe bar's underlying combat state still works — only the on-screen widget is hidden.")); - } - - private static void BuildMiscTab(PanelState state, StackPanel p, PickerState picker) - { - p.Children.Add(BoolRow("Enable FPS Limit", state.Data.EnableFPSLimit, - v => { state.Data.EnableFPSLimit = v; Push(state); state.Rebuild?.Invoke(); })); - if (state.Data.EnableFPSLimit) + RynthAiSettings d = state.Data; + void Changed(double v) { - p.Children.Add(IntRow("Focused FPS", state.Data.TargetFPSFocused, 10, 240, 1, - v => { state.Data.TargetFPSFocused = v; Push(state); })); - p.Children.Add(IntRow("Background FPS", state.Data.TargetFPSBackground, 5, 60, 1, - v => { state.Data.TargetFPSBackground = v; Push(state); })); - } - - p.Children.Add(Spacer()); - p.Children.Add(BoolRow("Auto Cram", state.Data.EnableAutocram, - v => { state.Data.EnableAutocram = v; Push(state); }, - "Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack.")); - p.Children.Add(BoolRow("Peace Mode When Idle", state.Data.PeaceModeWhenIdle, - v => { state.Data.PeaceModeWhenIdle = v; Push(state); })); - p.Children.Add(BoolRow("Start Macro On Login", state.Data.StartMacroOnLogin, - v => { state.Data.StartMacroOnLogin = v; Push(state); }, - "Automatically starts the macro when RynthAi loads.")); - p.Children.Add(BoolRow("Patrol On Login", state.Data.PatrolOnLogin, - v => { state.Data.PatrolOnLogin = v; Push(state); }, - "Automatically starts dungeon patrol when RynthAi loads.")); - p.Children.Add(BoolRow("Enable Raycasting", state.Data.EnableRaycasting, - v => { state.Data.EnableRaycasting = v; Push(state); })); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Missile Arc Velocities (m/s)")); - p.Children.Add(BoolRow("Use Arcs for Missile LoS", state.Data.UseArcs, - v => { state.Data.UseArcs = v; Push(state); state.Rebuild?.Invoke(); }, - "A missile target must pass both the straight line and the real arrow arc, ceilings included (dungeons too).\nWhen off, all missile LoS checks are linear (eye-to-eye).")); - if (state.Data.UseArcs) - { - p.Children.Add(FloatRow("Bow", state.Data.BowArcVelocity, 10f, 60f, 0.5f, v => { state.Data.BowArcVelocity = v; Push(state); }, "Bow projectile speed (m/s). Lower = higher arc.")); - p.Children.Add(FloatRow("Crossbow", state.Data.CrossbowArcVelocity, 10f, 80f, 0.5f, v => { state.Data.CrossbowArcVelocity = v; Push(state); })); - p.Children.Add(FloatRow("Atlatl", state.Data.AtlatlArcVelocity, 10f, 60f, 0.5f, v => { state.Data.AtlatlArcVelocity = v; Push(state); })); - p.Children.Add(FloatRow("Magic Arc", state.Data.MagicArcVelocity, 10f, 60f, 0.5f, v => { state.Data.MagicArcVelocity = v; Push(state); })); - p.Children.Add(FloatRow("Arc Clearance (m)", state.Data.MissileArcClearance, 0f, 3f, 0.1f, - v => { state.Data.MissileArcClearance = MathF.Max(0f, v); Push(state); }, - "Extra headroom the arc must have at mid-flight. Raise it if arrows still hit ceilings; lower it if reachable mobs get skipped.")); - } - p.Children.Add(BoolRow("LoS Debug Log", state.Data.LosDebugLog, - v => { state.Data.LosDebugLog = v; Push(state); }, - "Log each blocked missile target and why (arc peak, where it hits) to the RynthCore log. /ra lostest bow tests the selected mob.")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Monster Blacklist")); - p.Children.Add(IntRow("Attempts Before Blacklist", state.Data.BlacklistAttempts, 1, 20, 1, - v => { state.Data.BlacklistAttempts = v; Push(state); }, - "How many failed attack attempts on a mob before it gets blacklisted.")); - p.Children.Add(IntRow("Blacklist Timeout (sec)", state.Data.BlacklistTimeoutSec, 5, 120, 5, - v => { state.Data.BlacklistTimeoutSec = v; Push(state); }, - "How long a blacklisted mob is ignored before re-trying.")); - p.Children.Add(IntRow("No Progress Timeout (sec)", state.Data.TargetNoProgressTimeoutSec, 0, 300, 10, - v => { state.Data.TargetNoProgressTimeoutSec = v; Push(state); }, - "Blacklist a target after being engaged this many seconds without dealing damage.\n0 = disabled. Default 60s.")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Give Queue")); - p.Children.Add(IntRow("Give Interval (ms)", state.Data.GiveQueueIntervalMs, 50, 2000, 50, - v => { state.Data.GiveQueueIntervalMs = v; Push(state); }, - "Minimum delay between each item sent by /ra givea commands.")); - } - - private static void BuildRechargeTab(PanelState state, StackPanel p, PickerState picker) - { - p.Children.Add(SectionHeader("In Combat — target within Monster Range (%)")); - p.Children.Add(IntRow("Heal At", state.Data.HealAt, 0, 100, 1, v => { state.Data.HealAt = v; Push(state); }, - "While a target is within Monster Range, cast Heal Self when HP < this %.")); - p.Children.Add(IntRow("Re-stam At", state.Data.RestamAt, 0, 100, 1, v => { state.Data.RestamAt = v; Push(state); }, - "While a target is within Monster Range, cast Revitalize Self when Stamina < this %.")); - p.Children.Add(IntRow("Get Mana At", state.Data.GetManaAt, 0, 100, 1, v => { state.Data.GetManaAt = v; Push(state); }, - "While a target is within Monster Range, cast Stamina to Mana Self when Mana < this % (needs stam > 15%).")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Idle Top-Off — no targets in range (%)")); - p.Children.Add(IntRow("Top HP", state.Data.TopOffHP, 0, 100, 1, v => { state.Data.TopOffHP = v; Push(state); }, - "When no targets are within Monster Range, heal up to this HP %. Usually set higher than Heal At.")); - p.Children.Add(IntRow("Top Stam", state.Data.TopOffStam, 0, 100, 1, v => { state.Data.TopOffStam = v; Push(state); }, - "When no targets are within Monster Range, re-stam up to this %.")); - p.Children.Add(IntRow("Top Mana", state.Data.TopOffMana, 0, 100, 1, v => { state.Data.TopOffMana = v; Push(state); }, - "When no targets are within Monster Range, recharge mana up to this %.")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Helper Settings (%) — NOT WIRED YET")); - p.Children.Add(IntRow("Heal Others", state.Data.HealOthersAt, 0, 100, 1, v => { state.Data.HealOthersAt = v; Push(state); }, - "Intended: cast Heal Other on a fellow when their HP < this %. Not implemented yet — slider is inert.")); - p.Children.Add(IntRow("Re-stam Others", state.Data.RestamOthersAt, 0, 100, 1, v => { state.Data.RestamOthersAt = v; Push(state); }, - "Intended: cast Revitalize Other on a fellow when their Stamina < this %. Not implemented yet — slider is inert.")); - p.Children.Add(IntRow("Infuse Others", state.Data.InfuseOthersAt, 0, 100, 1, v => { state.Data.InfuseOthersAt = v; Push(state); }, - "Intended: cast Infuse Mana Other on a fellow when their Mana < this %. Not implemented yet — slider is inert.")); - } - - private static void BuildMeleeCombatTab(PanelState state, StackPanel p, PickerState picker) - { - p.Children.Add(SectionHeader("Attack Power & Height")); - p.Children.Add(BoolRow("Use Recklessness", state.Data.UseRecklessness, - v => { state.Data.UseRecklessness = v; Push(state); }, - "When enabled and Recklessness is trained, auto power uses 80% instead of 100%.")); - - p.Children.Add(Spacer()); - bool meleeAuto = state.Data.MeleeAttackPower < 0; - p.Children.Add(BoolRow("Melee Auto Power", meleeAuto, v => - { - state.Data.MeleeAttackPower = v ? -1 : 100; + row.Set!(state.Data, v); Push(state); - state.Rebuild?.Invoke(); - })); - if (!meleeAuto) - { - p.Children.Add(IntRow("Melee Power %", state.Data.MeleeAttackPower, 0, 100, 5, - v => { state.Data.MeleeAttackPower = v; Push(state); })); - } - p.Children.Add(ComboRow("Melee Attack Height", AttackHeights, state.Data.MeleeAttackHeight, - v => { state.Data.MeleeAttackHeight = v; Push(state); }, picker)); - - p.Children.Add(Spacer()); - bool missileAuto = state.Data.MissileAttackPower < 0; - p.Children.Add(BoolRow("Missile Auto Power", missileAuto, v => - { - state.Data.MissileAttackPower = v ? -1 : 100; - Push(state); - state.Rebuild?.Invoke(); - })); - if (!missileAuto) - { - p.Children.Add(IntRow("Missile Power %", state.Data.MissileAttackPower, 0, 100, 5, - v => { state.Data.MissileAttackPower = v; Push(state); })); - } - p.Children.Add(ComboRow("Missile Attack Height", AttackHeights, state.Data.MissileAttackHeight, - v => { state.Data.MissileAttackHeight = v; Push(state); }, picker)); - - p.Children.Add(Spacer()); - p.Children.Add(BoolRow("Use Native Attack", state.Data.UseNativeAttack, - v => { state.Data.UseNativeAttack = v; Push(state); }, - "Uses the client's combat pipeline for attacks.\nThe client handles turn-to-face naturally (no backwards arrows).")); - - p.Children.Add(Spacer()); - p.Children.Add(BoolRow("Summon Pets", state.Data.SummonPets, - v => { state.Data.SummonPets = v; Push(state); })); - p.Children.Add(IntRow("Pet Min Monsters", state.Data.PetMinMonsters, 1, 20, 1, - v => { state.Data.PetMinMonsters = v; Push(state); })); - } - - private static void BuildSpellCombatTab(PanelState state, StackPanel p, PickerState picker) - { - p.Children.Add(SectionHeader("War/Void Casting Settings")); - p.Children.Add(IntRow("Buff Spell Interval (ms)", state.Data.SpellCastIntervalMs, 100, 1500, 50, - v => { state.Data.SpellCastIntervalMs = v; Push(state); }, - "Delay between BUFF / utility spell casts (not combat).\nLower = faster buff chains. 400ms is a good balance.\nBelow 200ms may cause fizzles or dropped casts on laggy servers.")); - p.Children.Add(IntRow("Attack Spell Delay (ms)", state.Data.AttackSpellIntervalMs, 250, 5000, 50, - v => { state.Data.AttackSpellIntervalMs = v; Push(state); }, - "Delay between offensive (war/void) COMBAT casts only.\nSpacing casts ~1-2s (1500ms default) stops back-to-back\n\"You're too busy!\" refusals that drop casts and cost kills.\nDoes NOT affect buffing speed.")); - p.Children.Add(BoolRow("Cast Dispel Self", state.Data.CastDispelSelf, - v => { state.Data.CastDispelSelf = v; Push(state); })); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Ring Spell Override")); - p.Children.Add(IntRow("Min Ring Targets", state.Data.MinRingTargets, 1, 20, 1, - v => { state.Data.MinRingTargets = v; Push(state); }, - "If this many monsters are within ring range, ring spells are used instead of arc/bolt/streak.")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Spell Difficulty (Min Buffed Skill)")); - p.Children.Add(IntRow("Level 1", state.Data.MinSkillLevelTier1, 1, 500, 5, v => { state.Data.MinSkillLevelTier1 = v; Push(state); })); - p.Children.Add(IntRow("Level 2", state.Data.MinSkillLevelTier2, 1, 500, 5, v => { state.Data.MinSkillLevelTier2 = v; Push(state); })); - p.Children.Add(IntRow("Level 3", state.Data.MinSkillLevelTier3, 1, 500, 5, v => { state.Data.MinSkillLevelTier3 = v; Push(state); })); - p.Children.Add(IntRow("Level 4", state.Data.MinSkillLevelTier4, 1, 500, 5, v => { state.Data.MinSkillLevelTier4 = v; Push(state); })); - p.Children.Add(IntRow("Level 5", state.Data.MinSkillLevelTier5, 1, 500, 5, v => { state.Data.MinSkillLevelTier5 = v; Push(state); })); - p.Children.Add(IntRow("Level 6", state.Data.MinSkillLevelTier6, 1, 500, 5, v => { state.Data.MinSkillLevelTier6 = v; Push(state); })); - p.Children.Add(IntRow("Level 7", state.Data.MinSkillLevelTier7, 1, 500, 5, v => { state.Data.MinSkillLevelTier7 = v; Push(state); })); - p.Children.Add(IntRow("Level 8", state.Data.MinSkillLevelTier8, 1, 500, 5, v => { state.Data.MinSkillLevelTier8 = v; Push(state); })); - } - - private static void BuildRangesTab(PanelState state, StackPanel p, PickerState picker) - { - p.Children.Add(SectionHeader("Standard Ranges (Yards)")); - p.Children.Add(IntRow("Monster Range", state.Data.MonsterRange, 1, 200, 1, v => { state.Data.MonsterRange = v; Push(state); })); - p.Children.Add(IntRow("Ring Range", state.Data.RingRange, 1, 50, 1, v => { state.Data.RingRange = v; Push(state); })); - p.Children.Add(IntRow("Approach Range", state.Data.ApproachRange, 1, 50, 1, v => { state.Data.ApproachRange = v; Push(state); })); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Corpse Acquisition (Yards)")); - p.Children.Add(DoubleRow("Corpse Max (yd)", state.Data.CorpseApproachRangeMax, 0.5, 50.0, 0.5, - v => { state.Data.CorpseApproachRangeMax = v; Push(state); })); - p.Children.Add(DoubleRow("Corpse Min (yd)", state.Data.CorpseApproachRangeMin, 0.5, 20.0, 0.5, - v => { state.Data.CorpseApproachRangeMin = v; Push(state); })); - } - - private static void BuildNavigationTab(PanelState state, StackPanel p, PickerState picker) - { - p.Children.Add(BoolRow("Boost Nav Priority", state.Data.BoostNavPriority, - v => { state.Data.BoostNavPriority = v; Push(state); })); - p.Children.Add(FloatRow("Follow/Nav Min (yd)", state.Data.FollowNavMin, 0.5f, 20f, 0.1f, - v => { state.Data.FollowNavMin = v; Push(state); }, - "Arrival distance in yards. Also sets the nav marker ring radius.")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Nav Marker Display")); - p.Children.Add(FloatRow("Ring Thickness", state.Data.NavRingThickness, 1f, 16f, 1f, - v => { state.Data.NavRingThickness = v; Push(state); })); - p.Children.Add(FloatRow("Line Thickness", state.Data.NavLineThickness, 1f, 16f, 1f, - v => { state.Data.NavLineThickness = v; Push(state); })); - p.Children.Add(FloatRow("Height Offset", state.Data.NavHeightOffset, -5f, 5f, 0.05f, - v => { state.Data.NavHeightOffset = v; Push(state); }, - "Vertical offset for nav markers above the ground. Negative = lower.")); - p.Children.Add(FloatRow("Slope Sink", state.Data.NavSlopeSink, 0f, 8f, 0.1f, - v => { state.Data.NavSlopeSink = v; Push(state); }, - "Extra downward offset on slopes only, per unit of terrain steepness. 0 = off; flat ground is unaffected. ~1.5 cancels the float for a default-radius ring.")); - p.Children.Add(BoolRow("Show Terrain Passability", state.Data.ShowTerrainPassability, - v => { state.Data.ShowTerrainPassability = v; Push(state); }, - "Highlight impassable terrain triangles in red.")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Doors")); - p.Children.Add(BoolRow("Open Doors While Navigating", state.Data.OpenDoors, - v => { state.Data.OpenDoors = v; Push(state); state.Rebuild?.Invoke(); }, - "Automatically open doors encountered during navigation.")); - if (state.Data.OpenDoors) - { - p.Children.Add(FloatRow("Door Detection Range (yd)", state.Data.OpenDoorRange, 0.1f, 70f, 1f, - v => { state.Data.OpenDoorRange = v; Push(state); })); - p.Children.Add(BoolRow("Auto-Unlock Doors", state.Data.AutoUnlockDoors, - v => { state.Data.AutoUnlockDoors = v; Push(state); }, - "If a door is locked, try to use a lockpick from your Consumable Items list.")); + if (row.Gates) state.Rebuild?.Invoke(); } - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Movement Engine")); - p.Children.Add(ComboRow("Mode", MovementModes, state.Data.MovementMode, - v => { state.Data.MovementMode = v; Push(state); state.Rebuild?.Invoke(); }, picker, - "Legacy: SetAutorun + smooth heading servo (TurnToHeading)\nTier 1: SetAutorun + CM_Movement turn commands (DoMovement)\nTier 2: Client physics MoveToPosition (not built yet — falls back to Legacy)")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Steering")); - p.Children.Add(FloatRow("Stop & Turn Angle", state.Data.NavStopTurnAngle, 1f, 90f, 1f, - v => { state.Data.NavStopTurnAngle = v; Push(state); }, - "Stop forward motion and turn in place when heading error exceeds this.")); - p.Children.Add(FloatRow("Resume Run Angle", state.Data.NavResumeTurnAngle, 1f, 45f, 1f, - v => { state.Data.NavResumeTurnAngle = v; Push(state); }, - "Resume running once the turn-in-place error drops below this.")); - p.Children.Add(FloatRow("Dead Zone", state.Data.NavDeadZone, 0.5f, 20f, 0.5f, - v => { state.Data.NavDeadZone = v; Push(state); }, - "Ignore heading corrections smaller than this.")); - p.Children.Add(FloatRow("Sweep Detect Mult", state.Data.NavSweepMult, 0.5f, 10f, 0.1f, - v => { state.Data.NavSweepMult = v; Push(state); }, - "Closest-approach detection radius multiplier.")); - p.Children.Add(FloatRow("Lookahead (yd)", state.Data.NavLookaheadYards, 0f, 30f, 0.5f, - v => { state.Data.NavLookaheadYards = MathF.Max(0f, v); Push(state); }, - "Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off.")); - p.Children.Add(FloatRow("Shortcut Tolerance (yd)", state.Data.NavShortcutYards, 0f, 10f, 0.5f, - v => { state.Data.NavShortcutYards = MathF.Max(0f, v); Push(state); }, - "On reaching a waypoint, skip ahead only past points that all lie within this distance of the straight line to the new target. 0 = visit every waypoint.")); - p.Children.Add(FloatRow("Turn Rate (deg/s)", state.Data.NavTurnRateDegPerSec, 30f, 720f, 15f, - v => { state.Data.NavTurnRateDegPerSec = v; Push(state); }, - "Legacy / Mode 0 heading-servo max turn speed. Ignored by Tier 1 and Tier 2.")); - p.Children.Add(FloatRow("Tier1 Turn Speed", state.Data.NavTier1TurnSpeed, 0.5f, 15f, 0.5f, - v => { state.Data.NavTier1TurnSpeed = v; Push(state); }, - "Tier 1 (CM_Movement) turn-command speed = magnitude of the client turn_speed. Higher = snappier turns. Only used in Tier 1 mode.")); - p.Children.Add(FloatRow("Post-Portal Delay (s)", state.Data.PostPortalDelaySec, 0f, 30f, 0.25f, - v => { state.Data.PostPortalDelaySec = MathF.Max(0f, v); Push(state); }, - "Seconds to settle after any portal/recall teleport before nav resumes.")); - - if (state.Data.MovementMode == 2) + switch (row.Kind) { - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Tier 2 Tuning")); - p.Children.Add(FloatRow("Speed", state.Data.T2Speed, 0.1f, 5f, 0.1f, v => { state.Data.T2Speed = v; Push(state); })); - p.Children.Add(FloatRow("Walk Within (yd)", state.Data.T2WalkWithinYd, 1f, 50f, 1f, v => { state.Data.T2WalkWithinYd = v; Push(state); })); - p.Children.Add(FloatRow("Stop Distance (yd)", state.Data.T2DistanceTo, 0.1f, 10f, 0.1f, v => { state.Data.T2DistanceTo = v; Push(state); })); - p.Children.Add(FloatRow("Reissue Timeout (ms)",state.Data.T2ReissueMs, 100f, 10000f,100f, v => { state.Data.T2ReissueMs = v; Push(state); })); - p.Children.Add(FloatRow("Max Range (yd)", state.Data.T2MaxRangeYd, 50f, 2000f, 50f, v => { state.Data.T2MaxRangeYd = v; Push(state); })); - p.Children.Add(IntRow("Max Landblock Dist", state.Data.T2MaxLandblocks, 1, 20, 1, v => { state.Data.T2MaxLandblocks = v; Push(state); })); - } - } - - private static void BuildBuffingTab(PanelState state, StackPanel p, PickerState picker) - { - p.Children.Add(BoolRow("Enable Buffing", state.Data.EnableBuffing, - v => { state.Data.EnableBuffing = v; Push(state); })); - p.Children.Add(BoolRow("Rebuff When Idle", state.Data.RebuffWhenIdle, - v => { state.Data.RebuffWhenIdle = v; Push(state); })); - p.Children.Add(IntRow("Rebuff With (seconds left)", state.Data.RebuffSecondsRemaining, 30, 1800, 30, - v => { state.Data.RebuffSecondsRemaining = v; Push(state); }, - "Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly.")); - p.Children.Add(IntRow("Also Refresh Under (seconds left)", state.Data.RebuffTopOffSecondsRemaining, 30, 3600, 60, - v => { state.Data.RebuffTopOffSecondsRemaining = v; Push(state); }, - "When a buff is due, also recast every other buff with less than this much time left,\nso they land together. Buffs with more time are left alone. Default 1200 (20 minutes).\nAt or below 'Rebuff With', only the expiring buff is recast.")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Buff Difficulty (Min Buffed Skill)")); - p.Children.Add(IntRow("Level 1", state.Data.BuffMinSkillLevelTier1, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier1 = v; Push(state); })); - p.Children.Add(IntRow("Level 2", state.Data.BuffMinSkillLevelTier2, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier2 = v; Push(state); })); - p.Children.Add(IntRow("Level 3", state.Data.BuffMinSkillLevelTier3, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier3 = v; Push(state); })); - p.Children.Add(IntRow("Level 4", state.Data.BuffMinSkillLevelTier4, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier4 = v; Push(state); })); - p.Children.Add(IntRow("Level 5", state.Data.BuffMinSkillLevelTier5, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier5 = v; Push(state); })); - p.Children.Add(IntRow("Level 6", state.Data.BuffMinSkillLevelTier6, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier6 = v; Push(state); })); - p.Children.Add(IntRow("Level 7", state.Data.BuffMinSkillLevelTier7, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier7 = v; Push(state); })); - p.Children.Add(IntRow("Level 8", state.Data.BuffMinSkillLevelTier8, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier8 = v; Push(state); })); - } - - private static void BuildCraftingTab(PanelState state, StackPanel p, PickerState picker) - { - p.Children.Add(SectionHeader("Missile Ammo Crafting")); - p.Children.Add(BoolRow("Enable Missile Crafting", state.Data.EnableMissileCrafting, - v => { state.Data.EnableMissileCrafting = v; Push(state); state.Rebuild?.Invoke(); }, - "Auto-manage missile ammo when the ammo slot is empty or low.")); - - if (!state.Data.EnableMissileCrafting) - { - p.Children.Add(new TextBlock { Text = "(Disabled)", Foreground = ColMute, FontSize = 11, Margin = new Thickness(0, 4, 0, 0) }); - return; - } - - p.Children.Add(Spacer()); - if (!string.IsNullOrEmpty(state.Data.MissileCraftingState)) - { - var stateRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 2, 0, 2) }; - stateRow.Children.Add(new TextBlock { Text = "State:", Foreground = ColMute, FontSize = 11, VerticalAlignment = VerticalAlignment.Center }); - stateRow.Children.Add(new TextBlock - { - Text = state.Data.MissileCraftingState, - Foreground = state.Data.MissileCraftingActive ? ColAmber : ColMute, - FontSize = 11, - FontWeight = Avalonia.Media.FontWeight.Bold, - VerticalAlignment = VerticalAlignment.Center, - }); - p.Children.Add(stateRow); - - if (!string.IsNullOrEmpty(state.Data.MissileCraftingStatus)) - { - p.Children.Add(new TextBlock + case SettingKind.Bool: + return BoolRow(row.Label, row.Get!(d) != 0, v => Changed(v ? 1 : 0), row.Tooltip); + case SettingKind.Int: + return IntRow(row.Label, (int)row.Get!(d), (int)row.Min, (int)row.Max, (int)row.Step, v => Changed(v), row.Tooltip); + case SettingKind.Float: + return FloatRow(row.Label, (float)row.Get!(d), (float)row.Min, (float)row.Max, (float)row.Step, v => Changed(v), row.Tooltip); + case SettingKind.Double: + return DoubleRow(row.Label, row.Get!(d), row.Min, row.Max, row.Step, v => Changed(v), row.Tooltip); + case SettingKind.Combo: + return ComboRow(row.Label, row.Items!, (int)row.Get!(d), v => Changed(v), picker, row.Tooltip); + case SettingKind.Section: + return SectionHeader(row.Label); + case SettingKind.Spacer: + return Spacer(); + case SettingKind.Button: + return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => row.Click?.Invoke(), row.Tooltip); + case SettingKind.Note: + return new TextBlock { - Text = state.Data.MissileCraftingStatus, - Foreground = ColTextDim, - FontSize = 10, - TextWrapping = Avalonia.Media.TextWrapping.Wrap, - Margin = new Thickness(0, 2, 0, 0), + Text = row.Label, Foreground = ColMute, FontSize = row.Label.StartsWith('(') ? 11 : 10, + TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 0), + }; + case SettingKind.CraftingStatus: + { + var box = new StackPanel(); + var stateRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 2, 0, 2) }; + stateRow.Children.Add(new TextBlock { Text = row.Label, Foreground = ColMute, FontSize = 11, VerticalAlignment = VerticalAlignment.Center }); + stateRow.Children.Add(new TextBlock + { + Text = d.MissileCraftingState, + Foreground = d.MissileCraftingActive ? ColAmber : ColMute, + FontSize = 11, + FontWeight = Avalonia.Media.FontWeight.Bold, + VerticalAlignment = VerticalAlignment.Center, }); + box.Children.Add(stateRow); + if (!string.IsNullOrEmpty(d.MissileCraftingStatus)) + box.Children.Add(new TextBlock + { + Text = d.MissileCraftingStatus, Foreground = ColTextDim, FontSize = 10, + TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 0), + }); + return box; } } - } - - private static void BuildVendoringTab(PanelState state, StackPanel p, PickerState picker) - { - p.Children.Add(SectionHeader("AutoVendor")); - p.Children.Add(BoolRow("Enabled", state.Data.AutoVendorEnabled, - v => { state.Data.AutoVendorEnabled = v; Push(state); }, - "Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\nProfile: <Vendor Name>.utl, else default.utl, in the AutoVendor folder.")); - p.Children.Add(BoolRow("Test Mode (only print what it would do)", state.Data.AutoVendorTestMode, - v => { state.Data.AutoVendorTestMode = v; Push(state); }, - "Lists what would be bought and sold without trading. Leave this on until the lists look right.")); - p.Children.Add(BoolRow("Buy", state.Data.AutoVendorEnableBuying, - v => { state.Data.AutoVendorEnableBuying = v; Push(state); })); - p.Children.Add(BoolRow("Sell", state.Data.AutoVendorEnableSelling, - v => { state.Data.AutoVendorEnableSelling = v; Push(state); })); - p.Children.Add(BoolRow("Only Sell From Main Pack", state.Data.AutoVendorOnlyFromMainPack, - v => { state.Data.AutoVendorOnlyFromMainPack = v; Push(state); })); - p.Children.Add(BoolRow("Show Merchant Info", state.Data.AutoVendorShowMerchantInfo, - v => { state.Data.AutoVendorShowMerchantInfo = v; Push(state); }, - "Print the vendor's buy/sell rates and max value when it opens.")); - p.Children.Add(BoolRow("Think When Finished", state.Data.AutoVendorThink, - v => { state.Data.AutoVendorThink = v; Push(state); }, - "Send 'AutoVendor finished: <vendor>' (and failures) as a /tell to yourself, for metas.")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("/ub vendor open")); - p.Children.Add(IntRow("Tries", state.Data.AutoVendorTries, 1, 20, 1, - v => { state.Data.AutoVendorTries = v; Push(state); })); - p.Children.Add(IntRow("Time Between Tries (ms)", state.Data.AutoVendorTriesTime, 500, 30000, 250, - v => { state.Data.AutoVendorTriesTime = v; Push(state); })); - - p.Children.Add(Spacer()); - p.Children.Add(new TextBlock - { - Text = "Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match.", - Foreground = ColMute, FontSize = 10, TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 0), - }); - } - - private static void BuildLootingTab(PanelState state, StackPanel p, PickerState picker) - { - p.Children.Add(BoolRow("Enable Looting", state.Data.EnableLooting, - v => { state.Data.EnableLooting = v; Push(state); })); - p.Children.Add(BoolRow("Boost Loot Priority", state.Data.BoostLootPriority, - v => { state.Data.BoostLootPriority = v; Push(state); })); - p.Children.Add(BoolRow("Loot Only Rare Corpses", state.Data.LootOnlyRareCorpses, - v => { state.Data.LootOnlyRareCorpses = v; Push(state); })); - p.Children.Add(BoolRow("Jump When Looting", state.Data.LootJumpEnabled, - v => { state.Data.LootJumpEnabled = v; Push(state); state.Rebuild?.Invoke(); })); - if (state.Data.LootJumpEnabled) - { - p.Children.Add(IntRow("Jump Height", state.Data.LootJumpHeight, 1, 100, 5, - v => { state.Data.LootJumpHeight = v; Push(state); })); - } - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Corpse Ownership")); - p.Children.Add(ComboRow("Loot From", LootOwnershipModes, state.Data.LootOwnership, - v => { state.Data.LootOwnership = v; Push(state); }, picker)); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Inventory Management")); - p.Children.Add(BoolRow("Enable Autostack", state.Data.EnableAutostack, - v => { state.Data.EnableAutostack = v; Push(state); })); - p.Children.Add(BoolRow("Enable Autocram", state.Data.EnableAutocram, - v => { state.Data.EnableAutocram = v; Push(state); }, - "Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack.")); - p.Children.Add(BoolRow("Combine Salvage Bags", state.Data.EnableCombineSalvage, - v => { state.Data.EnableCombineSalvage = v; Push(state); }, - "After the salvage queue empties, move same-name bags together so the server merges them.")); - p.Children.Add(BoolRow("Combine Bags During Salvage", state.Data.CombineBagsDuringSalvage, - v => { state.Data.CombineBagsDuringSalvage = v; Push(state); }, - "When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel.")); - // The HUD windows are ImGui windows owned by the RynthAi plugin, so the engine only asks it to open them. - p.Children.Add(ButtonRow("Floating HUDs", "Inventory HUDs...", - () => RynthAiPanel.SendRynthAiCommand("huds", "show"), - "Opens the item count HUD / Mini Remote setup window (/ra huds).")); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Loot Timers (ms)")); - p.Children.Add(IntRow("Inter-Item Delay", state.Data.LootInterItemDelayMs, 0, 5000, 25, v => { state.Data.LootInterItemDelayMs = v; Push(state); })); - p.Children.Add(IntRow("Content Settle", state.Data.LootContentSettleMs, 0, 5000, 25, v => { state.Data.LootContentSettleMs = v; Push(state); })); - p.Children.Add(IntRow("Empty Corpse Wait", state.Data.LootEmptyCorpseMs, 0, 5000, 25, v => { state.Data.LootEmptyCorpseMs = v; Push(state); })); - p.Children.Add(IntRow("Closing Delay", state.Data.LootClosingDelayMs, 0, 5000, 25, v => { state.Data.LootClosingDelayMs = v; Push(state); })); - p.Children.Add(IntRow("Assess Window", state.Data.LootAssessWindowMs, 0, 5000, 25, v => { state.Data.LootAssessWindowMs = v; Push(state); })); - p.Children.Add(IntRow("Loot Retry Timeout", state.Data.LootRetryTimeoutMs, 0, 10000, 100, v => { state.Data.LootRetryTimeoutMs = v; Push(state); })); - p.Children.Add(IntRow("Corpse Open Retry", state.Data.LootOpenRetryMs, 0, 10000, 100, v => { state.Data.LootOpenRetryMs = v; Push(state); })); - p.Children.Add(IntRow("Corpse Timeout", state.Data.LootCorpseTimeoutMs, 0, 60000, 500, v => { state.Data.LootCorpseTimeoutMs = v; Push(state); })); - - p.Children.Add(Spacer()); - p.Children.Add(SectionHeader("Salvage Timers (ms) - First / Fast")); - p.Children.Add(IntRow("Open (First)", state.Data.SalvageOpenDelayFirstMs, 0, 5000, 50, v => { state.Data.SalvageOpenDelayFirstMs = v; Push(state); })); - p.Children.Add(IntRow("Open (Fast)", state.Data.SalvageOpenDelayFastMs, 0, 2000, 25, v => { state.Data.SalvageOpenDelayFastMs = v; Push(state); })); - p.Children.Add(IntRow("Add Item (First)", state.Data.SalvageAddDelayFirstMs, 0, 5000, 50, v => { state.Data.SalvageAddDelayFirstMs = v; Push(state); })); - p.Children.Add(IntRow("Add Item (Fast)", state.Data.SalvageAddDelayFastMs, 0, 2000, 25, v => { state.Data.SalvageAddDelayFastMs = v; Push(state); })); - p.Children.Add(IntRow("Salvage Click", state.Data.SalvageSalvageDelayMs, 0, 2000, 25, v => { state.Data.SalvageSalvageDelayMs = v; Push(state); })); - p.Children.Add(IntRow("Result (First)", state.Data.SalvageResultDelayFirstMs, 0, 5000, 50, v => { state.Data.SalvageResultDelayFirstMs = v; Push(state); })); - p.Children.Add(IntRow("Result (Fast)", state.Data.SalvageResultDelayFastMs, 0, 2000, 25, v => { state.Data.SalvageResultDelayFastMs = v; Push(state); })); + return null; } // ========================================================================= @@ -1403,75 +782,8 @@ internal static class SettingsPanel private static Border Spacer() => new Border { Height = 6 }; // ========================================================================= - // Plugin bridge + // Save // ========================================================================= - // RL loads fresh plugin copies without unloading the old ones: drop the - // exports bound below so the next poll re-binds to the live copy. - static SettingsPanel() => PluginManager.PluginsUnloaded += () => - { - _getSettingsJson = null; - _setSettingsJson = null; - }; - - private static void TryBind() - { - var plugin = PluginManager.Plugins.FirstOrDefault( - p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)); - if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return; - - if (_getSettingsJson == null) - { - IntPtr p1 = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetSettingsJson"); - if (p1 != IntPtr.Zero) - _getSettingsJson = Marshal.GetDelegateForFunctionPointer<GetSettingsJsonFn>(p1); - } - if (_setSettingsJson == null) - { - IntPtr p2 = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetSettingsJson"); - if (p2 != IntPtr.Zero) - _setSettingsJson = Marshal.GetDelegateForFunctionPointer<SetSettingsJsonFn>(p2); - } - } - - private static bool TryFetch(out Settings settings) => TryFetch(out settings, out _); - - private static bool TryFetch(out Settings settings, out string? rawJson) - { - settings = new Settings(); - rawJson = null; - if (_getSettingsJson == null) return false; - try - { - IntPtr ptr = _getSettingsJson(); - if (ptr == IntPtr.Zero) return false; - string? json = Marshal.PtrToStringAnsi(ptr); - if (string.IsNullOrEmpty(json)) return false; - var parsed = JsonSerializer.Deserialize(json, SettingsPanelJsonContext.Default.Settings); - if (parsed == null) return false; - settings = parsed; - rawJson = json; - return true; - } - catch { return false; } - } - - private static void Push(PanelState state) - { - if (_setSettingsJson == null) TryBind(); - if (_setSettingsJson == null) return; - IntPtr ansi = IntPtr.Zero; - try - { - string json = JsonSerializer.Serialize(state.Data, SettingsPanelJsonContext.Default.Settings); - ansi = Marshal.StringToHGlobalAnsi(json); - _setSettingsJson(ansi); - state.Dirty = false; - } - catch { } - finally - { - if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi); - } - } + private static void Push(PanelState state) => SettingsCommands.Save(state.Data.Clone()); } diff --git a/src/RynthCore.Engine/UI/Panels/StatusPanel.cs b/src/RynthCore.Engine/UI/Panels/StatusPanel.cs index 4062ef1..273ab0d 100644 --- a/src/RynthCore.Engine/UI/Panels/StatusPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/StatusPanel.cs @@ -9,6 +9,7 @@ using Avalonia.Controls; using Avalonia.Layout; using Avalonia.Media; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.UI.Panels; @@ -19,7 +20,11 @@ internal static class StatusPanel var content = new StackPanel { Spacing = 4 }; var refreshButton = new Button { Content = "Refresh", HorizontalAlignment = HorizontalAlignment.Left }; - refreshButton.Click += (_, _) => Populate(content); + refreshButton.Click += (_, _) => + { + UiSources.PluginStatus.RequestRefresh(); + Populate(content); + }; var root = new DockPanel { Margin = new Avalonia.Thickness(8) }; DockPanel.SetDock(refreshButton, Dock.Bottom); @@ -32,6 +37,29 @@ internal static class StatusPanel }; root.Children.Add(scroll); + // Plugin rows come from UiDataHub (read on the pump thread that owns the + // plugin list); repopulate when that snapshot changes. + long seen = -1; + var timer = new Avalonia.Threading.DispatcherTimer { Interval = TimeSpan.FromSeconds(1) }; + timer.Tick += (_, _) => + { + var snap = UiSources.PluginStatus.Current; + if (snap == null || snap.Version == seen) return; + seen = snap.Version; + Populate(content); + }; + root.AttachedToVisualTree += (_, _) => + { + UiSources.PluginStatus.Subscribe(); + UiSources.PluginStatus.RequestRefresh(); + if (!timer.IsEnabled) timer.Start(); + }; + root.DetachedFromVisualTree += (_, _) => + { + timer.Stop(); + UiSources.PluginStatus.Unsubscribe(); + }; + Populate(content); return root; } @@ -52,22 +80,33 @@ internal static class StatusPanel Margin = new Avalonia.Thickness(0, 6, 0, 6) }); - var plugins = PluginManager.Plugins; - AddHeader(panel, $"Plugins ({plugins.Count})"); + PluginStatusRow[] plugins = UiSources.PluginStatus.Current?.Value ?? Array.Empty<PluginStatusRow>(); + AddHeader(panel, $"Plugins ({plugins.Length})"); - if (plugins.Count == 0) + if (plugins.Length == 0) { AddRow(panel, "", "None loaded"); } else { - foreach (var p in plugins) - { - string state = p.Failed ? "FAILED" : p.Initialized ? "OK" : "pending"; - string version = p.VersionString.Length > 0 ? $" {p.VersionString}" : ""; - AddRow(panel, p.DisplayName + version, state, p.Failed); - } + foreach (PluginStatusRow p in plugins) + AddRow(panel, p.Label, p.State, p.IsError); } + + AddSeparator(panel); + AddHeader(panel, "UI faces"); + foreach (string line in PanelRouter.Describe()) + AddRow(panel, "", line); + } + + private static void AddSeparator(StackPanel panel) + { + panel.Children.Add(new Border + { + Height = 1, + Background = new SolidColorBrush(Color.FromArgb(60, 255, 255, 255)), + Margin = new Avalonia.Thickness(0, 6, 0, 6) + }); } private static void AddHeader(StackPanel panel, string text) diff --git a/src/RynthCore.Engine/UI/RynthAiDashboardState.cs b/src/RynthCore.Engine/UI/RynthAiDashboardState.cs new file mode 100644 index 0000000..31f2692 --- /dev/null +++ b/src/RynthCore.Engine/UI/RynthAiDashboardState.cs @@ -0,0 +1,187 @@ +// ============================================================================ +// RynthCore.Engine - UI/RynthAiDashboardState.cs +// The RynthAi dashboard's minimized state, shared by its Avalonia and ImGui +// faces, and the ImGui face's target bar and player vitals toggles, +// persisted to %AppData%\RynthCore\rynthai_avalonia.cache (line 1 +// minimized|expanded, line 2 unused, line 3 target|notarget, line 4 +// vitals|novitals; line 5 filesopen|nofiles, the Loaded files drawer; line 9 +// ranges|noranges, the Ranges drawer; line 10 patrol|nopatrol, the Patrol +// drawer: the left-edge drawers, ImGui/Panels/DashboardDrawers.cs). Line 2 +// was the Monsters button's Simple/Advanced mode, retired 2026-10-01 with the +// basic Monsters panel: it is still written ("advanced") so the lines after +// it keep their places, and ignored on read. Lines 7 and 8 (the dashboard's +// size with the files block folded / open) are unused since the files moved +// to a drawer (2026-10-05); kept as read so the lines after them keep their +// places. +// +// Deliberately NOT on RynthAiPanel: the engine loads this before +// AvaloniaOverlay.Start(), and touching RynthAiPanel there runs its static +// constructor, whose brushes create Dispatcher.UIThread on the wrong thread +// and kill the whole overlay (PlatformNotSupportedException in MainLoop; see +// the invariant in EntryPoint next to ChatModel.EnsureSettingsLoaded). +// Keep Avalonia types out of this class. +// ============================================================================ + +using System; +using System.IO; + +namespace RynthCore.Engine.UI; + +internal static class RynthAiDashboardState +{ + private static volatile bool _minimized; + private static volatile bool _showTargetBar = true; + private static volatile bool _showVitals = true; + private static volatile bool _filesOpen; // the Loaded files drawer (Profile/Nav/Loot/Meta pickers); a popped-out + // dashboard shows the same block inline instead + private static volatile bool _barCollapsed; // the RynthCore bar shows only its grip + expand + private static volatile bool _rangesOpen; // the Ranges drawer beside the dashboard is open + private static volatile bool _patrolOpen; // the Patrol drawer beside the dashboard is open + // Lines 7 and 8, unused since 2026-10-05: written back as read. + private static string _line7 = "-", _line8 = "-"; + private static bool _loaded; + private static readonly object LoadSync = new(); + + private static string CachePath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthai_avalonia.cache"); + + /// <summary>Minimized (loaded from disk on first use). Any thread.</summary> + public static bool Minimized + { + get { EnsureLoaded(); return _minimized; } + } + + /// <summary>Any thread; the file is written in the background.</summary> + public static void SetMinimized(bool minimized) + { + EnsureLoaded(); + _minimized = minimized; + UiBackgroundWriter.Enqueue("rynthai minimized", Save); + } + + /// <summary>The ImGui dashboard shows the target's name and health bar (at its bottom). Any thread.</summary> + public static bool ShowTargetBar + { + get { EnsureLoaded(); return _showTargetBar; } + } + + public static void SetShowTargetBar(bool show) + { + EnsureLoaded(); + _showTargetBar = show; + UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); + } + + /// <summary>The ImGui dashboard shows the player's health, stamina and mana bars (at its bottom). Any thread.</summary> + public static bool ShowVitals + { + get { EnsureLoaded(); return _showVitals; } + } + + public static void SetShowVitals(bool show) + { + EnsureLoaded(); + _showVitals = show; + UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); + } + + /// <summary> + /// The loaded-files block (Profile/Nav/Loot/Meta pickers, meta state) is open: the Loaded files drawer + /// beside the dashboard, or the block inline on a popped-out dashboard. Any thread. + /// </summary> + public static bool FilesOpen + { + get { EnsureLoaded(); return _filesOpen; } + } + + public static void SetFilesOpen(bool open) + { + EnsureLoaded(); + _filesOpen = open; + UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); + } + + /// <summary>The ImGui bar is collapsed to its grip and an expand button. Any thread.</summary> + public static bool BarCollapsed + { + get { EnsureLoaded(); return _barCollapsed; } + } + + public static void SetBarCollapsed(bool collapsed) + { + EnsureLoaded(); + _barCollapsed = collapsed; + UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); + } + + /// <summary>The Ranges drawer (ImGui/Panels/RangesSlideOut.cs) is open beside the dashboard. Any thread.</summary> + public static bool RangesOpen + { + get { EnsureLoaded(); return _rangesOpen; } + } + + public static void SetRangesOpen(bool open) + { + EnsureLoaded(); + _rangesOpen = open; + UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); + } + + /// <summary>The Patrol drawer (routes and recorded hazards) is open beside the dashboard. Any thread.</summary> + public static bool PatrolOpen + { + get { EnsureLoaded(); return _patrolOpen; } + } + + public static void SetPatrolOpen(bool open) + { + EnsureLoaded(); + _patrolOpen = open; + UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); + } + + /// <summary>Reads the file if it hasn't been read yet. Engine init calls this so AC's thread never does.</summary> + public static void EnsureLoaded() + { + if (_loaded) return; + lock (LoadSync) + { + if (_loaded) return; + try + { + string path = CachePath; + if (File.Exists(path)) + { + string[] lines = File.ReadAllLines(path); + _minimized = lines.Length > 0 && lines[0].Trim().Equals("minimized", StringComparison.OrdinalIgnoreCase); + _showTargetBar = lines.Length < 3 || !lines[2].Trim().Equals("notarget", StringComparison.OrdinalIgnoreCase); + _showVitals = lines.Length < 4 || !lines[3].Trim().Equals("novitals", StringComparison.OrdinalIgnoreCase); + // "filesopen" only once the player opened them; the old "files" default reads as folded. + _filesOpen = lines.Length >= 5 && lines[4].Trim().Equals("filesopen", StringComparison.OrdinalIgnoreCase); + _barCollapsed = lines.Length >= 6 && lines[5].Trim().Equals("barcollapsed", StringComparison.OrdinalIgnoreCase); + if (lines.Length >= 7 && lines[6].Trim().Length > 0) _line7 = lines[6].Trim(); + if (lines.Length >= 8 && lines[7].Trim().Length > 0) _line8 = lines[7].Trim(); + _rangesOpen = lines.Length >= 9 && lines[8].Trim().Equals("ranges", StringComparison.OrdinalIgnoreCase); + _patrolOpen = lines.Length >= 10 && lines[9].Trim().Equals("patrol", StringComparison.OrdinalIgnoreCase); + } + } + catch { /* corrupt cache: start expanded */ } + _loaded = true; + } + } + + private static void Save() + { + try + { + string path = CachePath; + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, (_minimized ? "minimized" : "expanded") + "\nadvanced\n" + + (_showTargetBar ? "target" : "notarget") + "\n" + (_showVitals ? "vitals" : "novitals") + "\n" + + (_filesOpen ? "filesopen" : "nofiles") + "\n" + (_barCollapsed ? "barcollapsed" : "bar") + "\n" + + _line7 + "\n" + _line8 + "\n" + + (_rangesOpen ? "ranges" : "noranges") + "\n" + (_patrolOpen ? "patrol" : "nopatrol") + "\n"); + } + catch { /* best-effort */ } + } +} diff --git a/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs b/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs new file mode 100644 index 0000000..0366a5b --- /dev/null +++ b/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs @@ -0,0 +1,379 @@ +// ============================================================================ +// RynthCore.Engine - UI/ScriptWindows/AcIconDecoder.cs +// Script windows: decodes Asheron's Call icons (0x06 Texture files in +// client_portal.dat) to RGBA, and stacks an item's underlay, icon and overlay +// into one picture. Pure code: no AC memory, no D3D, no engine state, so the +// RynthSuite offline tests compile it in and decode real icons. +// +// The texture formats and their byte layouts are the ones RynthCore.StatusAgent +// (Dat/IconDecoder.cs, the phone remote's icons) decodes, ported from +// ACEmulator's DatLoader; DXT1/3/5 use the StatusAgent's DxtUtil.cs (MonoGame, +// Ms-PL), linked into the engine project. The dat reader is the on-demand +// B-tree walk of ImGui/MonsterHud/PortalSpellTable.cs over one open stream: +// header at 0x140, a B-tree searched by file id, block chains whose first +// dword is the next block's offset. +// +// Threads: whatever thread owns the AcDatFile (the icon worker). Every read is +// bounds-checked; a bad file returns null, never throws out of Decode/Compose. +// ============================================================================ + +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using ACE.DatLoader; + +namespace RynthCore.Engine.UI.ScriptWindows; + +/// <summary>A read-only portal.dat opened for a batch of reads. Not thread-safe.</summary> +internal sealed class AcDatFile : IDisposable +{ + private const int HeaderOffset = 0x140; + private const int Branches = 62, MaxEntries = 61, EntrySize = 24; + private const int NodeSize = 4 * Branches + 4 + EntrySize * MaxEntries; // 1716 + private const int MaxDepth = 16; + + private readonly FileStream _fs; + private readonly uint _blockSize; + private readonly uint _root; + + private AcDatFile(FileStream fs, uint blockSize, uint root) + { + _fs = fs; + _blockSize = blockSize; + _root = root; + } + + /// <summary>Opens <paramref name="path"/> read-only, sharing everything (AC holds its own handles).</summary> + public static AcDatFile? Open(string path, out string why) + { + FileStream? fs = null; + try + { + fs = new FileStream(path, FileMode.Open, FileAccess.Read, + FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess); + Span<byte> hdr = stackalloc byte[36]; + fs.Seek(HeaderOffset, SeekOrigin.Begin); + if (!ReadFully(fs, hdr)) { why = "short header"; fs.Dispose(); return null; } + uint blockSize = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4)); + uint root = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(32, 4)); + if (blockSize <= 4 || blockSize > 65536 || root == 0 || root >= fs.Length) + { + why = "bad header"; + fs.Dispose(); + return null; + } + why = string.Empty; + return new AcDatFile(fs, blockSize, root); + } + catch (Exception ex) + { + fs?.Dispose(); + why = $"{ex.GetType().Name}: {ex.Message}"; + return null; + } + } + + /// <summary>client_portal.dat (or portal.dat) next to the running exe or in the current directory; null when none.</summary> + public static string? FindPortalDat() + { + var dirs = new List<string>(2); + try + { + string? exe = Environment.ProcessPath; + string? dir = string.IsNullOrEmpty(exe) ? null : Path.GetDirectoryName(exe); + if (!string.IsNullOrEmpty(dir)) dirs.Add(dir); + } + catch { } + try { dirs.Add(Environment.CurrentDirectory); } catch { } + foreach (string dir in dirs) + foreach (string name in new[] { "client_portal.dat", "portal.dat" }) + { + try + { + string full = Path.Combine(dir, name); + if (File.Exists(full)) return full; + } + catch { } + } + return null; + } + + /// <summary>A file's bytes by id, or null (not in the dat, over <paramref name="maxSize"/>, or unreadable).</summary> + public byte[]? Read(uint fileId, int maxSize) + { + try + { + uint offset = _root; + for (int depth = 0; depth < MaxDepth && offset != 0; depth++) + { + byte[]? node = ReadChain(offset, NodeSize); + if (node == null) return null; + uint count = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(4 * Branches)); + if (count > MaxEntries) return null; + int i = 0; + while (i < count && EntryId(node, i) < fileId) i++; + if (i < count && EntryId(node, i) == fileId) + { + int e = 4 * Branches + 4 + i * EntrySize; + uint fileOffset = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(e + 8)); + uint fileSize = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(e + 12)); + if (fileSize == 0 || fileSize > (uint)maxSize) return null; + return ReadChain(fileOffset, (int)fileSize); + } + bool leaf = BinaryPrimitives.ReadUInt32LittleEndian(node) == 0; + if (leaf || i >= Branches) return null; + offset = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(i * 4)); + } + return null; + } + catch + { + return null; + } + } + + private static uint EntryId(byte[] node, int i) => + BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(4 * Branches + 4 + i * EntrySize + 4)); + + /// <summary>A block chain: each block starts with the next block's offset (0 = last).</summary> + private byte[]? ReadChain(uint offset, int size) + { + if ((long)offset + 4 > _fs.Length) return null; + var buffer = new byte[size]; + Span<byte> next = stackalloc byte[4]; + _fs.Seek(offset, SeekOrigin.Begin); + if (!ReadFully(_fs, next)) return null; + uint nextAddr = BinaryPrimitives.ReadUInt32LittleEndian(next); + int done = 0; + int guard = 0; + while (done < size) + { + int take = Math.Min((int)_blockSize - 4, size - done); + if (!ReadFully(_fs, buffer.AsSpan(done, take))) return null; + done += take; + if (done >= size) break; + if (nextAddr == 0 || nextAddr >= _fs.Length || ++guard > 1_000_000) return null; + _fs.Seek(nextAddr, SeekOrigin.Begin); + if (!ReadFully(_fs, next)) return null; + nextAddr = BinaryPrimitives.ReadUInt32LittleEndian(next); + } + return buffer; + } + + private static bool ReadFully(FileStream fs, Span<byte> dest) + { + while (dest.Length > 0) + { + int n = fs.Read(dest); + if (n <= 0) return false; + dest = dest.Slice(n); + } + return true; + } + + public void Dispose() => _fs.Dispose(); +} + +/// <summary>An RGBA picture (Pixels = Width * Height * 4, bytes R, G, B, A).</summary> +internal sealed class AcIconImage +{ + public int Width; + public int Height; + public byte[] Pixels = Array.Empty<byte>(); +} + +internal static class AcIconDecoder +{ + /// <summary>Icons are 32 x 32; anything bigger than this (a UI picture, not an icon) is refused.</summary> + public const int MaxSide = 128; + /// <summary>The largest side a retail UI picture (a window background, a title bar) may have.</summary> + public const int MaxUiSide = 512; + private const int MaxTextureFile = 1024 * 1024; + private const int MaxPaletteFile = 256 * 1024; + + /// <summary>UtilityBelt's rule for an icon id: below 0x06000000, 0x06000000 is added.</summary> + public static uint NormalizeIconId(uint id) => id < 0x06000000u ? id + 0x06000000u : id; + + /// <summary>0x06xxxxxx: a Texture file (icons live there).</summary> + public static bool IsTextureId(uint id) => (id >> 24) == 0x06; + + /// <summary> + /// The item picture AC shows: the underlay, then the icon, then the overlay, each drawn over + /// the last (alpha blended) at the icon's size. 0 = no underlay / overlay. Null when the icon + /// itself can't be decoded; an underlay or overlay that can't be is left out. + /// </summary> + public static AcIconImage? Compose(AcDatFile dat, uint icon, uint underlay, uint overlay) + { + AcIconImage? baseImage = Decode(dat, icon); + if (baseImage == null) return null; + AcIconImage? under = underlay != 0 ? Decode(dat, underlay) : null; + AcIconImage? over = overlay != 0 ? Decode(dat, overlay) : null; + if (under == null && over == null) return baseImage; + + int w = baseImage.Width, h = baseImage.Height; + var outPx = new byte[w * h * 4]; + if (under != null) Over(outPx, w, h, under); + Over(outPx, w, h, baseImage); + if (over != null) Over(outPx, w, h, over); + return new AcIconImage { Width = w, Height = h, Pixels = outPx }; + } + + /// <summary>Draws <paramref name="src"/> over <paramref name="dst"/> (w x h), scaled nearest-neighbour when sizes differ.</summary> + private static void Over(byte[] dst, int w, int h, AcIconImage src) + { + for (int y = 0; y < h; y++) + { + int sy = src.Height == h ? y : y * src.Height / h; + for (int x = 0; x < w; x++) + { + int sx = src.Width == w ? x : x * src.Width / w; + int s = (sy * src.Width + sx) * 4, d = (y * w + x) * 4; + int sa = src.Pixels[s + 3]; + if (sa == 0) continue; + if (sa == 255) + { + dst[d] = src.Pixels[s]; + dst[d + 1] = src.Pixels[s + 1]; + dst[d + 2] = src.Pixels[s + 2]; + dst[d + 3] = 255; + continue; + } + int da = dst[d + 3]; + int outA = sa + da * (255 - sa) / 255; + if (outA <= 0) continue; + for (int c = 0; c < 3; c++) + dst[d + c] = (byte)((src.Pixels[s + c] * sa + dst[d + c] * da * (255 - sa) / 255) / outA); + dst[d + 3] = (byte)outA; + } + } + } + + /// <summary> + /// A 0x06 Texture as RGBA, or null (not a texture id, missing, an unsupported format, larger + /// than <see cref="MaxSide"/>, or short data). Layout: id u32, unknown i32, width i32, + /// height i32, format u32, length i32, data[length], then for INDEX16/P8 a palette id u32. + /// </summary> + public static AcIconImage? Decode(AcDatFile dat, uint textureId) => Decode(dat, textureId, MaxSide); + + /// <summary> + /// As <see cref="Decode(AcDatFile, uint)"/>, allowing sides up to <paramref name="maxSide"/> + /// (at most <see cref="MaxUiSide"/>): the retail UI pictures (ImGui/RetailSprites). + /// </summary> + public static AcIconImage? Decode(AcDatFile dat, uint textureId, int maxSide) + { + if (!IsTextureId(textureId)) return null; + try + { + byte[]? data = dat.Read(textureId, MaxTextureFile); + return data == null ? null : DecodeTextureFile(data, id => dat.Read(id, MaxPaletteFile), maxSide); + } + catch + { + return null; + } + } + + /// <summary>A Texture file's bytes as RGBA (see <see cref="Decode(AcDatFile, uint)"/>); <paramref name="readPalette"/> loads a 0x04 palette.</summary> + internal static AcIconImage? DecodeTextureFile(byte[] data, Func<uint, byte[]?> readPalette, int maxSide = MaxSide) + { + if (data.Length < 24) return null; + maxSide = Math.Clamp(maxSide, 1, MaxUiSide); + ReadOnlySpan<byte> d = data; + int w = BinaryPrimitives.ReadInt32LittleEndian(d[8..]); + int h = BinaryPrimitives.ReadInt32LittleEndian(d[12..]); + uint fmt = BinaryPrimitives.ReadUInt32LittleEndian(d[16..]); + int len = BinaryPrimitives.ReadInt32LittleEndian(d[20..]); + if (w <= 0 || h <= 0 || w > maxSide || h > maxSide || len < 0 || len > data.Length - 24) return null; + byte[] src = d.Slice(24, len).ToArray(); + int n = w * h; + + switch (fmt) + { + case 827611204: return Dxt(src, w, h, 8, DxtUtil.DecompressDxt1); // DXT1 + case 861165636: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt3); // DXT3 + case 894720068: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt5); // DXT5 + } + + var rgba = new byte[n * 4]; + void Px(int i, int r, int g, int b, int a) + { + int o = i * 4; + rgba[o] = (byte)r; rgba[o + 1] = (byte)g; rgba[o + 2] = (byte)b; rgba[o + 3] = (byte)a; + } + + switch (fmt) + { + case 20: // R8G8B8, stored B, G, R + for (int i = 0; i < n && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255); + break; + case 243: // CUSTOM_LSCAPE_R8G8B8, stored R, G, B + for (int i = 0; i < n && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255); + break; + case 21: // A8R8G8B8, stored B, G, R, A + case 22: // X8R8G8B8 + for (int i = 0; i < n && i * 4 + 3 < src.Length; i++) + Px(i, src[i * 4 + 2], src[i * 4 + 1], src[i * 4], fmt == 22 ? 255 : src[i * 4 + 3]); + break; + case 23: // R5G6B5 + for (int i = 0; i < n && i * 2 + 1 < src.Length; i++) + { + int v = src[i * 2] | (src[i * 2 + 1] << 8); + Px(i, ((v >> 11) & 0x1F) << 3, ((v >> 5) & 0x3F) << 2, (v & 0x1F) << 3, 255); + } + break; + case 26: // A4R4G4B4 + for (int i = 0; i < n && i * 2 + 1 < src.Length; i++) + { + int v = src[i * 2] | (src[i * 2 + 1] << 8); + Px(i, ((v >> 8) & 0xF) * 17, ((v >> 4) & 0xF) * 17, (v & 0xF) * 17, ((v >> 12) & 0xF) * 17); + } + break; + case 28: // A8 (greyscale) + case 244: // LSCAPE_ALPHA + for (int i = 0; i < n && i < src.Length; i++) Px(i, src[i], src[i], src[i], 255); + break; + case 101: // INDEX16 + case 41: // P8 + { + if (data.Length < 24 + len + 4) return null; + uint paletteId = BinaryPrimitives.ReadUInt32LittleEndian(d[(24 + len)..]); + uint[]? pal = Palette(readPalette(paletteId)); + if (pal == null || pal.Length == 0) return null; + bool p8 = fmt == 41; + for (int i = 0; i < n; 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); } + uint c = pal[idx % pal.Length]; + Px(i, (int)((c >> 16) & 0xFF), (int)((c >> 8) & 0xFF), (int)(c & 0xFF), (int)((c >> 24) & 0xFF)); + } + break; + } + default: + return null; // a format icons don't use + } + return new AcIconImage { Width = w, Height = h, Pixels = rgba }; + } + + private static AcIconImage? Dxt(byte[] src, int w, int h, int blockBytes, Func<byte[], int, int, byte[]> decompress) + { + long need = (long)((w + 3) / 4) * ((h + 3) / 4) * blockBytes; + if (src.Length < need) return null; // DxtUtil would read past the end + byte[] rgba = decompress(src, w, h); + return rgba.Length == w * h * 4 ? new AcIconImage { Width = w, Height = h, Pixels = rgba } : null; + } + + /// <summary>Palette (0x04): id u32, count i32, count x u32 ARGB.</summary> + private static uint[]? Palette(byte[]? data) + { + if (data == null || data.Length < 8) return null; + int n = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(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] = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8 + i * 4)); + return pal; + } +} diff --git a/src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs b/src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs new file mode 100644 index 0000000..6152eb3 --- /dev/null +++ b/src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs @@ -0,0 +1,1007 @@ +// ============================================================================ +// RynthCore.Engine - UI/ScriptWindows/DisplayListParser.cs +// Script windows (API v71): validates a UiSubmit buffer and turns each window +// body into an immutable DisplayList the replay walks every frame. +// Design: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2 (format 1), §6.3. +// +// Runs on the plugin pump thread inside UiSubmit. It reads the plugin's +// buffer only during the call and copies everything it keeps: strings go +// into one pinned, NUL-terminated UTF-8 pool per list, so the replay hands +// cimgui byte pointers with no per-frame encoding or allocation. +// +// Format 1 ops (Phase 1 MVP): +// 0x01 Text 0x02 TextColored 0x03 TextWrapped 0x04 TextDisabled +// 0x05 BulletText 0x06 SeparatorText 0x07 LabelText +// 0x10 Separator 0x11 SameLine 0x12 NewLine 0x13 Spacing 0x14 Dummy +// 0x15 Indent 0x16 Unindent +// 0x20 Button 0x21 Checkbox 0x22 SliderInt 0x23 SliderFloat +// 0x24 InputText 0x25 Combo 0x26 Selectable 0x27 ProgressBar +// Op level 2 (2026-09-30, still format 1: older engines skip these ops): +// 0x28 Image 0x29 ImageButton 0x2A InputInt 0x2B InputFloat +// 0x2C DragInt 0x2D DragFloat +// 0x30 PushID 0x31 PopID 0x32 PushStyleColor 0x33 PopStyleColor +// 0x38 SetItemTooltip +// 0x40 Child (block) 0x41 CollapsingHeader (plain op) 0x42 TreeNode (block) +// 0x00 End (root body only) +// An op this engine doesn't know is skipped by its PayloadLength (and its +// block), so newer recorders still draw what this engine can. A known op +// that carries a block it can't have, or a block op without one, refuses the +// list. Every flag field is masked to a whitelist, every f32 must be finite, +// and no script text can reach cimgui as a format string (LabelText's text +// is stored with '%' doubled; slider, drag and InputFloat formats are +// validated). Icons are ids the engine resolves (ScriptIcons), never pointers. +// ============================================================================ + +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Numerics; +using System.Text; +using System.Text.Unicode; +using ImGuiNET; + +namespace RynthCore.Engine.UI.ScriptWindows; + +internal enum ScriptOp : byte +{ + End = 0x00, + Text = 0x01, + TextColored = 0x02, + TextWrapped = 0x03, + TextDisabled = 0x04, + BulletText = 0x05, + SeparatorText = 0x06, + LabelText = 0x07, + Separator = 0x10, + SameLine = 0x11, + NewLine = 0x12, + Spacing = 0x13, + Dummy = 0x14, + Indent = 0x15, + Unindent = 0x16, + Button = 0x20, + Checkbox = 0x21, + SliderInt = 0x22, + SliderFloat = 0x23, + InputText = 0x24, + Combo = 0x25, + Selectable = 0x26, + ProgressBar = 0x27, + Image = 0x28, + ImageButton = 0x29, + InputInt = 0x2A, + InputFloat = 0x2B, + DragInt = 0x2C, + DragFloat = 0x2D, + PushID = 0x30, + PopID = 0x31, + PushStyleColor = 0x32, + PopStyleColor = 0x33, + SetItemTooltip = 0x38, + Child = 0x40, + CollapsingHeader = 0x41, + TreeNode = 0x42, +} + +/// <summary>What an Image / ImageButton op's id is (op level 2).</summary> +internal enum ScriptIconKind : byte +{ + /// <summary>An icon (0x06 texture) id; below 0x06000000, 0x06000000 is added (UtilityBelt's rule).</summary> + Icon = 0, + /// <summary>An object id: the item's icon with its underlay and overlay.</summary> + Object = 1, + /// <summary>A spell id: the spell's icon.</summary> + Spell = 2, + /// <summary>A kind this engine doesn't know: drawn as the missing-icon placeholder.</summary> + Unknown = 0xFF, +} + +/// <summary> +/// One validated op, ready to replay. Strings are offsets into the list's pool (-1 = none). +/// Field use per op (see <see cref="DisplayListParser"/>): +/// Str/StrLen the text, label, PushID string, tooltip or child id. +/// Str2/Str2Len LabelText's escaped text, a slider's format, InputText's value, +/// Combo's NUL-separated items, ProgressBar's overlay. +/// Flag Button small; Checkbox value; Selectable selected; Child border; +/// CollapsingHeader/TreeNode recordedOpen; PushID kind; Image/ImageButton +/// icon kind (ScriptIconKind). +/// Aux PushStyleColor ImGuiCol; PopStyleColor count; InputText maxLen; Combo count. +/// Flags the op's masked ImGui flags. +/// Color TextColored / PushStyleColor colour (0xAABBGGRR); Image tint; +/// ImageButton background. +/// Color2 Image border; ImageButton tint. +/// I0..I2 SliderInt v/min/max; Combo index; PushID integer; InputInt v/step/stepFast; +/// DragInt v/min/max; Image/ImageButton id (I0, as u32). +/// A..F sizes and offsets (logical, UI scale 1); SliderFloat v/min/max; +/// ProgressBar fraction (A) and size (B, C); Image size (A, B), uv0 (C, D) +/// and uv1 (E, F); InputFloat v/step/stepFast; DragFloat v/min/max (A..C); +/// DragInt/DragFloat speed (D). +/// EndIndex the index just past the op (a block op: past its last child). +/// </summary> +internal struct ReplayOp +{ + public ScriptOp Code; + public byte Flag; + /// <summary>AC thread only: the open state last reported for this list (CollapsingHeader, TreeNode).</summary> + public byte LastOpen; + public ushort Aux; + public int Str; + public int StrLen; + public int Str2; + public int Str2Len; + public uint Key; + public uint Flags; + public uint Color; + public uint Color2; + public int I0, I1, I2; + public float A, B, C, D, E, F; + public int EndIndex; +} + +/// <summary>An immutable parsed window body. Published to AC's thread with Volatile.Write.</summary> +internal sealed class DisplayList +{ + public static readonly DisplayList Empty = new(Array.Empty<ReplayOp>(), 0, GC.AllocateArray<byte>(1, pinned: true), 0, 0); + + public readonly ReplayOp[] Ops; + public readonly int OpCount; + /// <summary>Pinned (pinned-object heap), NUL-terminated UTF-8 strings.</summary> + public readonly byte[] Pool; + public readonly uint ListSeq; + /// <summary>The last event seq the plugin had applied when it recorded this list.</summary> + public readonly uint AckSeq; + + public DisplayList(ReplayOp[] ops, int opCount, byte[] pool, uint listSeq, uint ackSeq) + { + Ops = ops; + OpCount = opCount; + Pool = pool; + ListSeq = listSeq; + AckSeq = ackSeq; + } +} + +/// <summary>One window of a submit, validated.</summary> +internal sealed class ParsedWindow +{ + public required string Key; + public required uint Hash; + public required string Title; + public required uint Flags; + /// <summary>Panel logical units. RequestSize/RequestPos: NaN = none.</summary> + public Vector2 DefaultSize, MinSize, RequestSize, RequestPos; + /// <summary>Flags bit10: RequestPos is a FirstUseEver default position, not a request.</summary> + public bool PosIsDefault; + /// <summary>The script's error (Flags bit9 HasError), control characters made spaces; null = none.</summary> + public string? ErrorText; + public uint ListSeq; + /// <summary>Null: unchanged since the last submit (no body sent).</summary> + public DisplayList? List; +} + +internal static class WindowFlags +{ + public const uint Visible = 1u << 0; + public const uint ShowInBar = 1u << 1; + public const uint ChromeNone = 1u << 2; + public const uint ClickThrough = 1u << 3; + public const uint NoBackground = 1u << 4; + public const uint NoScrollbar = 1u << 5; + public const uint NoScrollWithMouse = 1u << 6; + /// <summary>Phase 2: parsed, ignored.</summary> + public const uint AutoSize = 1u << 7; + /// <summary>Phase 2: parsed, ignored.</summary> + public const uint NoPopOut = 1u << 8; + /// <summary>An ErrorText field follows RequestPos; the window draws it above the list.</summary> + public const uint HasError = 1u << 9; + /// <summary>RequestPos is a FirstUseEver default position (used only when nothing is saved).</summary> + public const uint PosIsDefault = 1u << 10; + public const uint Known = (1u << 11) - 1; +} + +internal static class DisplayListParser +{ + public const uint Magic = 0x31575352; // 'RSW1' + public const ushort FormatVersion = 1; + /// <summary> + /// The ops this engine replays within format 1 (UiGetInfo OpLevel): 1 = Phase 1; 2 = + Image, + /// ImageButton, InputInt, InputFloat, DragInt, DragFloat. Older engines report 0 (the field + /// was reserved) and skip level-2 ops; RynthLua refuses to record them there. + /// </summary> + public const ushort OpLevel = 2; + public const int HeaderSize = 16; + public const int MaxString = 4096; + public const int MaxStr8 = 128; + public const int MaxErrorText = 1024; + /// <summary>Blocks plus the PushID depth (§6.1).</summary> + public const int MaxDepth = 32; + public const int MaxComboItems = 512; + private const uint BodyUnchanged = 0xFFFFFFFF; + private const byte OpHasBlock = 1; + + // ── Whitelists (ImGui.NET 1.91.6.1) ───────────────────────────────── + + private const uint InputTextMask = (uint)(ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.CharsHexadecimal + | ImGuiInputTextFlags.CharsUppercase | ImGuiInputTextFlags.CharsNoBlank | ImGuiInputTextFlags.EnterReturnsTrue + | ImGuiInputTextFlags.ReadOnly | ImGuiInputTextFlags.Password | ImGuiInputTextFlags.AutoSelectAll); + + private const uint SelectableMask = (uint)(ImGuiSelectableFlags.AllowDoubleClick | ImGuiSelectableFlags.Disabled + | ImGuiSelectableFlags.AllowOverlap); + + /// <summary>TreeNode / CollapsingHeader. NoTreePushOnOpen is never allowed (the engine owns TreePop).</summary> + private const uint TreeNodeMask = (uint)(ImGuiTreeNodeFlags.Selected | ImGuiTreeNodeFlags.Framed + | ImGuiTreeNodeFlags.AllowOverlap | ImGuiTreeNodeFlags.DefaultOpen | ImGuiTreeNodeFlags.OpenOnDoubleClick + | ImGuiTreeNodeFlags.OpenOnArrow | ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet + | ImGuiTreeNodeFlags.FramePadding | ImGuiTreeNodeFlags.SpanAvailWidth | ImGuiTreeNodeFlags.SpanFullWidth + | ImGuiTreeNodeFlags.SpanTextWidth) & ~(uint)ImGuiTreeNodeFlags.NoTreePushOnOpen; + + /// <summary>InputInt / InputFloat (ImGui's InputScalar picks its own character filter).</summary> + private const uint NumberInputMask = (uint)(ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.ReadOnly + | ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.ParseEmptyRefVal | ImGuiInputTextFlags.DisplayEmptyRefVal); + + /// <summary>DragInt / DragFloat (ImGuiSliderFlags; AlwaysClamp = ClampOnInput | ClampZeroRange).</summary> + private const uint DragMask = (uint)(ImGuiSliderFlags.Logarithmic | ImGuiSliderFlags.NoRoundToFormat + | ImGuiSliderFlags.NoInput | ImGuiSliderFlags.WrapAround | ImGuiSliderFlags.AlwaysClamp); + + /// <summary>Image uv coordinates are clamped to this (the texture repeats or clamps beyond 0..1).</summary> + private const float UvLimit = 16f; + /// <summary>Drag speed per pixel of mouse movement, clamped to this either way.</summary> + private const float DragSpeedLimit = 1_000_000f; + + private const uint ChildWindowMask = (uint)(ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse + | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.HorizontalScrollbar + | ImGuiWindowFlags.AlwaysVerticalScrollbar | ImGuiWindowFlags.AlwaysHorizontalScrollbar); + + /// <summary>The style colours a script may push; any other id drops the push (and its pop).</summary> + public static bool IsAllowedColor(int col) => (ImGuiCol)col switch + { + ImGuiCol.Text or ImGuiCol.TextDisabled or ImGuiCol.ChildBg or ImGuiCol.Border or ImGuiCol.FrameBg + or ImGuiCol.CheckMark or ImGuiCol.SliderGrab or ImGuiCol.Button or ImGuiCol.ButtonHovered + or ImGuiCol.ButtonActive or ImGuiCol.Header or ImGuiCol.HeaderHovered or ImGuiCol.PlotHistogram => true, + _ => false, + }; + + // Slider range limits ImGui asserts on (SliderBehavior). + private const int SliderIntLimit = int.MaxValue / 2; + private const float SliderFloatLimit = float.MaxValue / 2; + + /// <summary>FNV-1a, the hash both sides use for window keys (and the recorder for widget keys).</summary> + public static uint Fnv1a(ReadOnlySpan<byte> bytes, uint hash = 2166136261) + { + foreach (byte b in bytes) + { + hash ^= b; + hash *= 16777619; + } + return hash; + } + + /// <summary> + /// Validates a whole submit. Returns 0 with <paramref name="windows"/> set, or + /// -1 malformed / -3 over a limit / -4 unsupported version, with <paramref name="error"/>. + /// Nothing is applied on failure. + /// </summary> + public static unsafe int Parse(byte* data, int length, float displayMax, + out uint ackSeq, out List<ParsedWindow> windows, out string error) + { + ackSeq = 0; + windows = new List<ParsedWindow>(); + error = string.Empty; + if (data == null || length < HeaderSize) { error = "submit shorter than its header"; return -1; } + if (length > ScriptWindowRegistry.MaxBytesPerSubmit) + { + error = $"submit of {length} bytes is over the {ScriptWindowRegistry.MaxBytesPerSubmit}-byte limit"; + return -3; + } + + var span = new ReadOnlySpan<byte>(data, length); + if (BinaryPrimitives.ReadUInt32LittleEndian(span) != Magic) { error = "bad magic"; return -1; } + ushort version = BinaryPrimitives.ReadUInt16LittleEndian(span[4..]); + if (version == 0 || version > FormatVersion) { error = $"format {version} isn't supported (max {FormatVersion})"; return -4; } + int windowCount = BinaryPrimitives.ReadUInt16LittleEndian(span[6..]); + ackSeq = BinaryPrimitives.ReadUInt32LittleEndian(span[8..]); + uint total = BinaryPrimitives.ReadUInt32LittleEndian(span[12..]); + if (total != (uint)length) { error = "TotalLength doesn't match the length"; return -1; } + if (windowCount > ScriptWindowRegistry.MaxWindowsPerOwner) + { + error = $"{windowCount} windows is over the {ScriptWindowRegistry.MaxWindowsPerOwner}-window limit"; + return -3; + } + + var r = new Reader(span, HeaderSize); + var keys = new HashSet<string>(StringComparer.Ordinal); + var ctx = new BodyContext(displayMax); + for (int w = 0; w < windowCount; w++) + { + if (!r.Str8(out string key, out ReadOnlySpan<byte> keyBytes) || key.Length == 0) + { error = $"window {w}: bad key"; return -1; } + if (!keys.Add(key)) { error = $"window '{key}' appears twice"; return -1; } + if (!r.Str8(out string title, out _)) { error = $"window '{key}': bad title"; return -1; } + if (!r.U32(out uint flags)) { error = $"window '{key}': truncated"; return -1; } + flags &= WindowFlags.Known; + var pw = new ParsedWindow + { + Key = key, + Hash = Fnv1a(keyBytes), + Title = title.Length > 0 ? title : key, + Flags = flags, + PosIsDefault = (flags & WindowFlags.PosIsDefault) != 0, + }; + if (!r.Vec2(out pw.DefaultSize, allowNaN: false) || !r.Vec2(out pw.MinSize, allowNaN: false) + || !r.Vec2(out pw.RequestSize, allowNaN: true) || !r.Vec2(out pw.RequestPos, allowNaN: true)) + { error = $"window '{key}': bad sizes (not finite)"; return -1; } + pw.DefaultSize = ClampSize(pw.DefaultSize, displayMax); + pw.MinSize = ClampSize(pw.MinSize, displayMax); + if (!float.IsNaN(pw.RequestSize.X)) pw.RequestSize = ClampSize(pw.RequestSize, displayMax); + if (!float.IsNaN(pw.RequestPos.X)) + pw.RequestPos = new Vector2(Math.Clamp(pw.RequestPos.X, -displayMax, displayMax), Math.Clamp(pw.RequestPos.Y, -displayMax, displayMax)); + if ((flags & WindowFlags.HasError) != 0) + { + if (!r.U16(out ushort errLen) || errLen > MaxErrorText || !r.Take(errLen, out ReadOnlySpan<byte> errBytes)) + { error = $"window '{key}': bad error text"; return -1; } + pw.ErrorText = Sanitize(Encoding.UTF8.GetString(errBytes)); + } + if (!r.U32(out pw.ListSeq) || !r.U32(out uint bodyLength)) { error = $"window '{key}': truncated"; return -1; } + if (bodyLength != BodyUnchanged) + { + if (bodyLength > ScriptWindowRegistry.MaxBytesPerWindow) + { error = $"window '{key}' is {bodyLength} bytes, over the {ScriptWindowRegistry.MaxBytesPerWindow}-byte limit"; return -3; } + if (!r.Take((int)bodyLength, out ReadOnlySpan<byte> body)) { error = $"window '{key}': body runs past the end"; return -1; } + ctx.Reset(key); + int rc = ParseRoot(body, ctx); + if (rc != 0) { error = ctx.Error; return rc; } + pw.List = new DisplayList(ctx.Ops.ToArray(), ctx.Ops.Count, ctx.Pool.ToPinned(), pw.ListSeq, ackSeq); + } + windows.Add(pw); + } + if (r.Pos != span.Length) { error = "bytes after the last window"; return -1; } + return 0; + } + + private static Vector2 ClampSize(Vector2 v, float max) => + new(Math.Clamp(v.X, 0, max), Math.Clamp(v.Y, 0, max)); + + /// <summary>Per-body parse state, reused across the windows of one submit.</summary> + private sealed class BodyContext + { + public readonly float DisplayMax; + public readonly List<ReplayOp> Ops = new(); + public readonly PoolBuilder Pool = new(); + /// <summary>PushStyleColor stack across scopes: true = a real push, false = a dropped one.</summary> + public readonly List<bool> Colors = new(); + public string Key = string.Empty; + public string Error = string.Empty; + /// <summary>Every op read (known, unknown or dropped), children included.</summary> + public int OpsRead; + public int DefaultIntFmt = -1, DefaultIntFmtLen, DefaultFloatFmt = -1, DefaultFloatFmtLen; + + public BodyContext(float displayMax) => DisplayMax = displayMax; + + public void Reset(string key) + { + Ops.Clear(); + Pool.Clear(); + Colors.Clear(); + Key = key; + Error = string.Empty; + OpsRead = 0; + DefaultIntFmt = DefaultFloatFmt = -1; + } + + public int Fail(int rc, string message) + { + Error = $"window '{Key}': {message}"; + return rc; + } + } + + private static int ParseRoot(ReadOnlySpan<byte> body, BodyContext ctx) + { + if (body.Length == 0) return 0; // empty list + var r = new Reader(body, 0); + int rc = ParseScope(ref r, ctx, depth: 0, root: true); + if (rc != 0) return rc; + if (r.Pos != body.Length) return ctx.Fail(-1, "bytes after End"); + return 0; + } + + /// <summary> + /// Parses one scope: the root body (ends with End) or a block's children (end with the block). + /// <paramref name="depth"/> is the enclosing blocks plus PushIDs still open outside this scope. + /// </summary> + private static int ParseScope(ref Reader r, BodyContext ctx, int depth, bool root) + { + int ids = 0; // PushIDs open in this scope + int colorBase = ctx.Colors.Count; // this scope's part of the colour stack starts here + try + { + while (true) + { + if (!root && r.AtEnd) return 0; + if (!r.U8(out byte code) || !r.U8(out byte opFlags) || !r.U16(out ushort payloadLength)) + return ctx.Fail(-1, "op header runs past the end"); + if (code == (byte)ScriptOp.End) + { + if (!root) return ctx.Fail(-1, "End inside a block"); + return 0; + } + if (++ctx.OpsRead > ScriptWindowRegistry.MaxOpsPerWindow) + return ctx.Fail(-3, $"more than {ScriptWindowRegistry.MaxOpsPerWindow} items"); + if (!r.Take(payloadLength, out ReadOnlySpan<byte> payload)) + return ctx.Fail(-1, $"op 0x{code:X2} runs past the end"); + bool hasBlock = (opFlags & OpHasBlock) != 0; + ReadOnlySpan<byte> block = default; + if (hasBlock) + { + if (!r.U32(out uint blockLength) || blockLength > int.MaxValue || !r.Take((int)blockLength, out block)) + return ctx.Fail(-1, $"op 0x{code:X2} block runs past the end"); + } + + var op = new ReplayOp { Code = (ScriptOp)code, Str = -1, Str2 = -1 }; + var p = new Reader(payload, 0); + bool ok; + bool keep = true; + bool isBlockOp = false; + float max = ctx.DisplayMax; + switch ((ScriptOp)code) + { + case ScriptOp.Text: + case ScriptOp.TextWrapped: + case ScriptOp.TextDisabled: + case ScriptOp.BulletText: + case ScriptOp.SeparatorText: + case ScriptOp.SetItemTooltip: + ok = p.Str(ctx.Pool, out op.Str, out op.StrLen); + break; + case ScriptOp.TextColored: + ok = p.U32(out op.Color) && p.Str(ctx.Pool, out op.Str, out op.StrLen); + break; + case ScriptOp.LabelText: + ok = p.Str(ctx.Pool, out op.Str, out op.StrLen) && p.StrEscaped(ctx.Pool, out op.Str2, out op.Str2Len); + break; + case ScriptOp.Separator: + case ScriptOp.NewLine: + case ScriptOp.Spacing: + ok = true; + break; + case ScriptOp.SameLine: + ok = p.F32(out op.A) && p.F32(out op.B); + op.A = Math.Clamp(op.A, 0f, max); + op.B = op.B < 0f ? -1f : Math.Min(op.B, max); + break; + case ScriptOp.Dummy: + ok = p.F32(out op.A) && p.F32(out op.B); + op.A = Math.Clamp(op.A, 0f, max); + op.B = Math.Clamp(op.B, 0f, max); + break; + case ScriptOp.Indent: + case ScriptOp.Unindent: + ok = p.F32(out op.A); + op.A = Math.Clamp(op.A, 0f, max); + break; + case ScriptOp.Button: + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) + && p.F32(out op.A) && p.F32(out op.B) && p.U8(out op.Flag); + op.A = Math.Clamp(op.A, -max, max); + op.B = Math.Clamp(op.B, -max, max); + op.Flag = op.Flag != 0 ? (byte)1 : (byte)0; + break; + case ScriptOp.Checkbox: + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) && p.U8(out op.Flag); + op.Flag = op.Flag != 0 ? (byte)1 : (byte)0; + break; + case ScriptOp.SliderInt: + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) + && p.I32(out op.I0) && p.I32(out op.I1) && p.I32(out op.I2) + && p.SliderFormat(ctx, isInt: true, out op.Str2, out op.Str2Len); + if (ok) + { + op.I1 = Math.Clamp(op.I1, -SliderIntLimit, SliderIntLimit); + op.I2 = Math.Clamp(op.I2, -SliderIntLimit, SliderIntLimit); + if (op.I1 > op.I2) (op.I1, op.I2) = (op.I2, op.I1); + op.I0 = Math.Clamp(op.I0, op.I1, op.I2); + } + break; + case ScriptOp.SliderFloat: + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) + && p.F32(out op.A) && p.F32(out op.B) && p.F32(out op.C) + && p.SliderFormat(ctx, isInt: false, out op.Str2, out op.Str2Len); + if (ok) + { + op.B = Math.Clamp(op.B, -SliderFloatLimit, SliderFloatLimit); + op.C = Math.Clamp(op.C, -SliderFloatLimit, SliderFloatLimit); + if (op.B > op.C) (op.B, op.C) = (op.C, op.B); + op.A = Math.Clamp(op.A, op.B, op.C); + } + break; + case ScriptOp.InputText: + { + ReadOnlySpan<byte> value = default; + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) + && p.StrRaw(out value) && p.U16(out op.Aux) && p.U32(out op.Flags); + if (ok) + { + op.Aux = (ushort)Math.Clamp((int)op.Aux, 1, MaxString); + op.Flags &= InputTextMask; // no Callback* flag ever: no callback is passed + (op.Str2, op.Str2Len) = ctx.Pool.Add(value, op.Aux); + } + break; + } + case ScriptOp.Combo: + { + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) + && p.I32(out op.I0) && p.U16(out op.Aux) && op.Aux <= MaxComboItems; + if (ok) + { + op.Str2 = ctx.Pool.BeginItems(); + for (int k = 0; k < op.Aux && ok; k++) + { + ok = p.StrRaw(out ReadOnlySpan<byte> item); + if (ok) ctx.Pool.AddItem(item); + } + op.Str2Len = ctx.Pool.EndItems(op.Str2); + op.I0 = Math.Clamp(op.I0, -1, op.Aux - 1); + } + break; + } + case ScriptOp.Selectable: + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) && p.U8(out op.Flag) + && p.U32(out op.Flags) && p.F32(out op.A) && p.F32(out op.B); + op.Flag = op.Flag != 0 ? (byte)1 : (byte)0; + op.Flags &= SelectableMask; + op.A = Math.Clamp(op.A, -max, max); + op.B = Math.Clamp(op.B, -max, max); + break; + case ScriptOp.ProgressBar: + { + ReadOnlySpan<byte> overlay = default; + ok = p.F32(out op.A) && p.F32(out op.B) && p.F32(out op.C) && p.StrRaw(out overlay); + if (ok) + { + op.A = Math.Clamp(op.A, 0f, 1f); + op.B = Math.Clamp(op.B, -max, max); + op.C = Math.Clamp(op.C, -max, max); + if (overlay.Length > 0) (op.Str2, op.Str2Len) = ctx.Pool.Add(overlay); // empty: ImGui's percentage + } + break; + } + case ScriptOp.Image: + ok = IconRef(ref p, ref op) && p.F32(out op.A) && p.F32(out op.B) + && p.F32(out op.C) && p.F32(out op.D) && p.F32(out op.E) && p.F32(out op.F) + && p.U32(out op.Color) && p.U32(out op.Color2); + if (ok) ClampImage(ref op, max); + break; + case ScriptOp.ImageButton: + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) && IconRef(ref p, ref op) + && p.F32(out op.A) && p.F32(out op.B) + && p.F32(out op.C) && p.F32(out op.D) && p.F32(out op.E) && p.F32(out op.F) + && p.U32(out op.Color) && p.U32(out op.Color2); + if (ok) ClampImage(ref op, max); + break; + case ScriptOp.InputInt: + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) + && p.I32(out op.I0) && p.I32(out op.I1) && p.I32(out op.I2) && p.U32(out op.Flags); + op.Flags &= NumberInputMask; + break; + case ScriptOp.InputFloat: + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) + && p.F32(out op.A) && p.F32(out op.B) && p.F32(out op.C) + && p.SliderFormat(ctx, isInt: false, out op.Str2, out op.Str2Len) && p.U32(out op.Flags); + if (ok) + { + op.B = Math.Clamp(op.B, -SliderFloatLimit, SliderFloatLimit); + op.C = Math.Clamp(op.C, -SliderFloatLimit, SliderFloatLimit); + } + op.Flags &= NumberInputMask; + break; + case ScriptOp.DragInt: + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) + && p.I32(out op.I0) && p.F32(out op.D) && p.I32(out op.I1) && p.I32(out op.I2) + && p.SliderFormat(ctx, isInt: true, out op.Str2, out op.Str2Len) && p.U32(out op.Flags); + if (ok) + { + // min == max (0, 0 by default) is ImGui's "no bounds". + op.D = Math.Clamp(op.D, -DragSpeedLimit, DragSpeedLimit); + op.I1 = Math.Clamp(op.I1, -SliderIntLimit, SliderIntLimit); + op.I2 = Math.Clamp(op.I2, -SliderIntLimit, SliderIntLimit); + if (op.I1 > op.I2) (op.I1, op.I2) = (op.I2, op.I1); + } + op.Flags &= DragMask; + break; + case ScriptOp.DragFloat: + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) + && p.F32(out op.A) && p.F32(out op.D) && p.F32(out op.B) && p.F32(out op.C) + && p.SliderFormat(ctx, isInt: false, out op.Str2, out op.Str2Len) && p.U32(out op.Flags); + if (ok) + { + op.D = Math.Clamp(op.D, -DragSpeedLimit, DragSpeedLimit); + op.B = Math.Clamp(op.B, -SliderFloatLimit, SliderFloatLimit); + op.C = Math.Clamp(op.C, -SliderFloatLimit, SliderFloatLimit); + if (op.B > op.C) (op.B, op.C) = (op.C, op.B); + } + op.Flags &= DragMask; + break; + case ScriptOp.PushID: + ok = p.U8(out op.Flag); + if (ok) + { + if (op.Flag == 0) ok = p.Str(ctx.Pool, out op.Str, out op.StrLen); + else if (op.Flag == 1) ok = p.I32(out op.I0); + else ok = false; + } + if (ok) + { + if (depth + ids + 1 > MaxDepth) return ctx.Fail(-3, $"nesting deeper than {MaxDepth}"); + ids++; + } + break; + case ScriptOp.PopID: + ok = true; + if (ids > 0) ids--; + else keep = false; // unmatched in its scope: dropped + break; + case ScriptOp.PushStyleColor: + ok = p.U16(out op.Aux) && p.U32(out op.Color); + if (ok) + { + bool allowed = IsAllowedColor(op.Aux); + ctx.Colors.Add(allowed); + keep = allowed; // not whitelisted: dropped, and its pop won't pop + } + break; + case ScriptOp.PopStyleColor: + { + ok = p.U8(out byte count); + if (ok) + { + // Pop up to count entries of this scope's stack; only real pushes pop. + int real = 0; + for (int k = 0; k < count && ctx.Colors.Count > colorBase; k++) + { + if (ctx.Colors[^1]) real++; + ctx.Colors.RemoveAt(ctx.Colors.Count - 1); + } + op.Aux = (ushort)real; + keep = real > 0; + } + break; + } + case ScriptOp.Child: + isBlockOp = true; + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) + && p.F32(out op.A) && p.F32(out op.B) && p.U8(out op.Flag) && p.U32(out op.Flags); + op.A = Math.Clamp(op.A, -max, max); + op.B = Math.Clamp(op.B, -max, max); + op.Flag = op.Flag != 0 ? (byte)1 : (byte)0; + op.Flags &= ChildWindowMask; + break; + case ScriptOp.CollapsingHeader: + case ScriptOp.TreeNode: + isBlockOp = (ScriptOp)code == ScriptOp.TreeNode; + ok = p.U32(out op.Key) && p.Str(ctx.Pool, out op.Str, out op.StrLen) + && p.U32(out op.Flags) && p.U8(out op.Flag); + op.Flags &= TreeNodeMask; + op.Flag = op.Flag != 0 ? (byte)1 : (byte)0; + op.LastOpen = op.Flag; + break; + default: + continue; // unknown op (a newer recorder): skipped with its block + } + if (!ok) return ctx.Fail(-1, $"op 0x{code:X2} payload is short or has a bad value"); + if (isBlockOp != hasBlock) + return ctx.Fail(-1, isBlockOp ? $"op 0x{code:X2} needs a block" : $"op 0x{code:X2} can't have a block"); + if (!keep) continue; + + int index = ctx.Ops.Count; + op.EndIndex = index + 1; + ctx.Ops.Add(op); + if (isBlockOp) + { + if (depth + ids + 1 > MaxDepth) return ctx.Fail(-3, $"nesting deeper than {MaxDepth}"); + var br = new Reader(block, 0); + int rc = ParseScope(ref br, ctx, depth + ids + 1, root: false); + if (rc != 0) return rc; + ReplayOp done = ctx.Ops[index]; + done.EndIndex = ctx.Ops.Count; + ctx.Ops[index] = done; + } + } + } + finally + { + // Pushes left in this scope are the replay's to pop; the enclosing scope never sees them. + if (ctx.Colors.Count > colorBase) ctx.Colors.RemoveRange(colorBase, ctx.Colors.Count - colorBase); + } + } + + /// <summary>An icon reference: u8 kind, u32 id. A kind this engine doesn't know becomes Unknown (a placeholder).</summary> + private static bool IconRef(ref Reader p, ref ReplayOp op) + { + if (!p.U8(out byte kind) || !p.U32(out uint id)) return false; + op.Flag = kind <= (byte)ScriptIconKind.Spell ? kind : (byte)ScriptIconKind.Unknown; + op.I0 = unchecked((int)id); + return true; + } + + /// <summary>Image sizes 0..max (no auto or fill for images); uvs within UvLimit.</summary> + private static void ClampImage(ref ReplayOp op, float max) + { + op.A = Math.Clamp(op.A, 0f, max); + op.B = Math.Clamp(op.B, 0f, max); + op.C = Math.Clamp(op.C, -UvLimit, UvLimit); + op.D = Math.Clamp(op.D, -UvLimit, UvLimit); + op.E = Math.Clamp(op.E, -UvLimit, UvLimit); + op.F = Math.Clamp(op.F, -UvLimit, UvLimit); + } + + /// <summary> + /// A slider format: exactly one conversion %[-+ #0]*[0-9]{0,2}(\.[0-9]{1,2})? ending in d/i + /// (int) or f/F/g/G/e/E (float); "%%" anywhere; nothing else. + /// </summary> + internal static bool IsValidSliderFormat(ReadOnlySpan<byte> f, bool isInt) + { + int conversions = 0; + int i = 0; + while (i < f.Length) + { + if (f[i] != (byte)'%') { i++; continue; } + i++; + if (i < f.Length && f[i] == (byte)'%') { i++; continue; } + if (conversions == 1) return false; + while (i < f.Length && f[i] is (byte)'-' or (byte)'+' or (byte)' ' or (byte)'#' or (byte)'0') i++; + int digits = 0; + while (i < f.Length && f[i] >= (byte)'0' && f[i] <= (byte)'9') { i++; digits++; } + if (digits > 2) return false; + if (i < f.Length && f[i] == (byte)'.') + { + i++; + digits = 0; + while (i < f.Length && f[i] >= (byte)'0' && f[i] <= (byte)'9') { i++; digits++; } + if (digits is 0 or > 2) return false; + } + if (i >= f.Length) return false; + byte c = f[i++]; + bool okConv = isInt ? c is (byte)'d' or (byte)'i' + : c is (byte)'f' or (byte)'F' or (byte)'g' or (byte)'G' or (byte)'e' or (byte)'E'; + if (!okConv) return false; + conversions++; + } + return conversions == 1; + } + + /// <summary>Little-endian reader with bounds checks; every read returns false instead of throwing.</summary> + private ref struct Reader + { + private readonly ReadOnlySpan<byte> _s; + public int Pos; + + public Reader(ReadOnlySpan<byte> s, int pos) { _s = s; Pos = pos; } + + public readonly bool AtEnd => Pos >= _s.Length; + + public bool Take(int n, out ReadOnlySpan<byte> bytes) + { + if (n < 0 || n > _s.Length - Pos) { bytes = default; return false; } + bytes = _s.Slice(Pos, n); + Pos += n; + return true; + } + + public bool U8(out byte v) + { + if (Pos >= _s.Length) { v = 0; return false; } + v = _s[Pos++]; + return true; + } + + public bool U16(out ushort v) + { + if (!Take(2, out var b)) { v = 0; return false; } + v = BinaryPrimitives.ReadUInt16LittleEndian(b); + return true; + } + + public bool U32(out uint v) + { + if (!Take(4, out var b)) { v = 0; return false; } + v = BinaryPrimitives.ReadUInt32LittleEndian(b); + return true; + } + + public bool I32(out int v) + { + if (!Take(4, out var b)) { v = 0; return false; } + v = BinaryPrimitives.ReadInt32LittleEndian(b); + return true; + } + + /// <summary>A finite f32 (anything else is refused).</summary> + public bool F32(out float v) + { + if (!Take(4, out var b)) { v = 0; return false; } + v = BinaryPrimitives.ReadSingleLittleEndian(b); + return float.IsFinite(v); + } + + public bool Vec2(out Vector2 v, bool allowNaN) + { + v = default; + if (!Take(8, out var b)) return false; + float x = BinaryPrimitives.ReadSingleLittleEndian(b); + float y = BinaryPrimitives.ReadSingleLittleEndian(b[4..]); + v = new Vector2(x, y); + if (allowNaN && float.IsNaN(x) && float.IsNaN(y)) return true; // NaN = none + return float.IsFinite(x) && float.IsFinite(y); + } + + /// <summary>str8: u8 length + UTF-8, decoded to a managed string (keys, titles).</summary> + public bool Str8(out string s, out ReadOnlySpan<byte> raw) + { + s = string.Empty; + raw = default; + if (!U8(out byte n) || !Take(n, out raw)) return false; + s = Sanitize(Encoding.UTF8.GetString(raw)); + return true; + } + + /// <summary>str: u16 length (≤ 4096) + UTF-8, not copied.</summary> + public bool StrRaw(out ReadOnlySpan<byte> bytes) + { + bytes = default; + return U16(out ushort n) && n <= MaxString && Take(n, out bytes); + } + + /// <summary>str, copied into the pool.</summary> + public bool Str(PoolBuilder pool, out int offset, out int length) + { + offset = -1; + length = 0; + if (!StrRaw(out var bytes)) return false; + (offset, length) = pool.Add(bytes); + return true; + } + + /// <summary>str, copied into the pool with every '%' doubled (a cimgui format argument).</summary> + public bool StrEscaped(PoolBuilder pool, out int offset, out int length) + { + offset = -1; + length = 0; + if (!StrRaw(out var bytes)) return false; + (offset, length) = pool.AddEscaped(bytes); + return true; + } + + /// <summary>A slider's format: empty or invalid becomes the default ("%d" / "%.3f").</summary> + public bool SliderFormat(BodyContext ctx, bool isInt, out int offset, out int length) + { + offset = -1; + length = 0; + if (!StrRaw(out var bytes)) return false; + if (bytes.Length > 0 && IsValidSliderFormat(bytes, isInt)) + { + (offset, length) = ctx.Pool.Add(bytes); + return true; + } + if (isInt) + { + if (ctx.DefaultIntFmt < 0) (ctx.DefaultIntFmt, ctx.DefaultIntFmtLen) = ctx.Pool.Add("%d"u8); + (offset, length) = (ctx.DefaultIntFmt, ctx.DefaultIntFmtLen); + } + else + { + if (ctx.DefaultFloatFmt < 0) (ctx.DefaultFloatFmt, ctx.DefaultFloatFmtLen) = ctx.Pool.Add("%.3f"u8); + (offset, length) = (ctx.DefaultFloatFmt, ctx.DefaultFloatFmtLen); + } + return true; + } + } + + /// <summary>Control characters (NUL included) become spaces; keys, titles and error text.</summary> + private static string Sanitize(string s) + { + foreach (char c in s) + { + if (char.IsControl(c)) + { + var sb = new StringBuilder(s.Length); + foreach (char d in s) sb.Append(char.IsControl(d) ? ' ' : d); + return sb.ToString(); + } + } + return s; + } + + /// <summary> + /// Collects one list's strings; valid UTF-8 is copied as is, anything else re-encoded. + /// Every string ends with a NUL; an embedded NUL becomes '?' (it would cut a label short). + /// </summary> + private sealed class PoolBuilder + { + private byte[] _buf = new byte[1024]; + private int _len; + + private static ReadOnlySpan<byte> Valid(ReadOnlySpan<byte> bytes) => + Utf8.IsValid(bytes) ? bytes : Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bytes)); // invalid → U+FFFD + + /// <summary>Adds a string, cut to at most <paramref name="maxBytes"/> without splitting a character.</summary> + public (int Offset, int Length) Add(ReadOnlySpan<byte> bytes, int maxBytes = int.MaxValue) + { + bytes = Valid(bytes); + if (bytes.Length > maxBytes) + { + int n = maxBytes; + while (n > 0 && (bytes[n] & 0xC0) == 0x80) n--; + bytes = bytes[..n]; + } + Ensure(bytes.Length + 1); + int offset = _len; + AppendNoNul(bytes); + _buf[_len++] = 0; + return (offset, bytes.Length); + } + + /// <summary>Adds a string with every '%' doubled.</summary> + public (int Offset, int Length) AddEscaped(ReadOnlySpan<byte> bytes) + { + bytes = Valid(bytes); + Ensure(bytes.Length * 2 + 1); + int offset = _len; + foreach (byte b in bytes) + { + if (b == (byte)'%') { _buf[_len++] = (byte)'%'; _buf[_len++] = (byte)'%'; } + else _buf[_len++] = b == 0 ? (byte)'?' : b; + } + int length = _len - offset; + _buf[_len++] = 0; + return (offset, length); + } + + /// <summary>Combo items: "a\0b\0c\0\0". Returns the offset.</summary> + public int BeginItems() => _len; + + /// <summary>One item; an empty one becomes " " so it doesn't end the list early.</summary> + public void AddItem(ReadOnlySpan<byte> bytes) + { + bytes = Valid(bytes); + if (bytes.Length == 0) bytes = " "u8; + Ensure(bytes.Length + 1); + AppendNoNul(bytes); + _buf[_len++] = 0; + } + + /// <summary>Ends the items with the extra NUL; returns their length (without the final NUL).</summary> + public int EndItems(int offset) + { + Ensure(1); + int length = _len - offset; + _buf[_len++] = 0; + return length; + } + + private void AppendNoNul(ReadOnlySpan<byte> bytes) + { + Span<byte> dst = _buf.AsSpan(_len, bytes.Length); + bytes.CopyTo(dst); + for (int i = 0; i < dst.Length; i++) + if (dst[i] == 0) dst[i] = (byte)'?'; + _len += bytes.Length; + } + + private void Ensure(int extra) + { + if (_len + extra <= _buf.Length) return; + int size = _buf.Length; + while (size < _len + extra) size *= 2; + Array.Resize(ref _buf, size); + } + + public byte[] ToPinned() + { + byte[] pinned = GC.AllocateArray<byte>(Math.Max(1, _len), pinned: true); + _buf.AsSpan(0, _len).CopyTo(pinned); + return pinned; + } + + public void Clear() => _len = 0; + } +} diff --git a/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs new file mode 100644 index 0000000..36be8ff --- /dev/null +++ b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs @@ -0,0 +1,962 @@ +// ============================================================================ +// RynthCore.Engine - UI/ScriptWindows/ScriptWindowRegistry.cs +// Script windows (API v71): owners, their windows, the latest display list +// per window and the event queue back to each owner. +// Design: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §3, §4. +// +// Threads: +// Submit / PollEvents plugin pump thread, inside the owner's own dispatch +// (PluginManager.CurrentDispatch). The buffer is read +// or written only during the call. +// GetInfo any thread. +// Replay (the faces) AC's thread: reads each window's latest list +// (Volatile) and appends events under the owner's +// short queue lock. It never takes Sync. +// The engine never calls into a plugin for this and keeps no plugin pointer: +// an owner is the engine's own LoadedPlugin record, dropped at unload. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using RynthCore.Engine.ImGuiBackend; +using RynthCore.Engine.ImGuiBackend.Panels; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.ScriptWindows; + +/// <summary> +/// Event types (format 1, §4.3). Every event starts with u16 Type, u16 Size (whole event), +/// u32 Seq, u32 WindowHash, u32 WidgetKey (0 for window-level events); payloads: +/// Clicked u16 count, u8 button (0 = left) +/// Bool u8 value +/// Int i32 value (SliderInt, Combo) +/// Float f32 value (SliderFloat) +/// Text u8 submitted, u16 length + UTF-8 (≤ 4096 bytes) +/// Open u8 open (CollapsingHeader, TreeNode) +/// Geometry f32×8 windowPos x,y; windowSize w,h; contentAvail w,h; cursorStart x,y +/// (logical units at UI scale 1), u32 flags (bit0 focused, bit1 collapsed, bit2 hovered) +/// Visibility u8 visible, u8 reason +/// Error u16 length + UTF-8 +/// </summary> +internal static class ScriptEventType +{ + public const ushort Clicked = 1; + public const ushort Bool = 2; + public const ushort Int = 3; + public const ushort Float = 4; + public const ushort Text = 5; + public const ushort Open = 6; + public const ushort Geometry = 7; + public const ushort Visibility = 8; + public const ushort Error = 10; + + /// <summary>Per-widget value events: coalesced per (type, window, key), latest wins.</summary> + public static bool IsValue(ushort type) => type is Bool or Int or Float or Text or Open; +} + +/// <summary>Visibility event reasons (§4.3).</summary> +internal static class VisibilityReason +{ + public const byte Script = 0; + /// <summary>The player closed it with the X (the default for a close the owner didn't ask for).</summary> + public const byte PlayerClose = 1; + /// <summary>The bar's Scripts menu or a command (the default for an open the owner didn't ask for).</summary> + public const byte BarOrCommand = 2; +} + +/// <summary>A window's geometry, in logical units at UI scale 1 (Geometry events).</summary> +internal struct ScriptGeometry +{ + public Vector2 Pos, Size, Avail, Cursor; + public uint Flags; + + public const uint Focused = 1u << 0; + public const uint Collapsed = 1u << 1; + public const uint Hovered = 1u << 2; +} + +/// <summary>One owner's queue of events for the plugin. Appended on AC's thread, drained on the pump thread.</summary> +internal sealed class ScriptEventQueue +{ + public const int MaxTextBytes = 4096; + + private struct Item + { + public ushort Type; + public uint Seq; + public uint WindowHash; + public uint WidgetKey; + public int Count; // Clicked + public byte Value; // Bool/Open value; Visibility visible; Text submitted + public byte Reason; // Visibility reason + public int Int; // Int + public float Float; // Float + public string? Text; // Error + public byte[]? Bytes; // Text (UTF-8) + public ScriptGeometry Geo; // Geometry + } + + private readonly object _lock = new(); + private readonly List<Item> _items = new(); + private uint _nextSeq = 1; + + /// <summary> + /// Adds a value or geometry event, replacing the queued one for the same (type, window, key) + /// (Geometry: the same window). A Text event keeps "submitted" if either had it. Returns the seq. + /// </summary> + private uint AddCoalesced(Item item) + { + lock (_lock) + { + uint seq = _nextSeq++; + item.Seq = seq; + bool geometry = item.Type == ScriptEventType.Geometry; + for (int i = 0; i < _items.Count; i++) + { + Item e = _items[i]; + if (e.Type == item.Type && e.WindowHash == item.WindowHash && (geometry || e.WidgetKey == item.WidgetKey)) + { + if (item.Type == ScriptEventType.Text) item.Value |= e.Value; + _items.RemoveAt(i); + break; + } + } + MakeRoom(); + _items.Add(item); + return seq; + } + } + + /// <summary>A new integer value (SliderInt, Combo index). Returns the event's seq.</summary> + public uint Int(uint windowHash, uint key, int value) => + AddCoalesced(new Item { Type = ScriptEventType.Int, WindowHash = windowHash, WidgetKey = key, Int = value }); + + /// <summary>A new float value (SliderFloat). Returns the event's seq.</summary> + public uint Float(uint windowHash, uint key, float value) => + AddCoalesced(new Item { Type = ScriptEventType.Float, WindowHash = windowHash, WidgetKey = key, Float = value }); + + /// <summary>InputText's text (UTF-8, cut to 4096 bytes); <paramref name="submitted"/> = Enter on an EnterReturnsTrue field.</summary> + public uint Text(uint windowHash, uint key, ReadOnlySpan<byte> utf8, bool submitted) + { + if (utf8.Length > MaxTextBytes) + { + int n = MaxTextBytes; + while (n > 0 && (utf8[n] & 0xC0) == 0x80) n--; + utf8 = utf8[..n]; + } + return AddCoalesced(new Item { Type = ScriptEventType.Text, WindowHash = windowHash, WidgetKey = key, Value = submitted ? (byte)1 : (byte)0, Bytes = utf8.ToArray() }); + } + + /// <summary>A tree node's or collapsing header's live open state. Returns the event's seq.</summary> + public uint Open(uint windowHash, uint key, bool open) => + AddCoalesced(new Item { Type = ScriptEventType.Open, WindowHash = windowHash, WidgetKey = key, Value = open ? (byte)1 : (byte)0 }); + + /// <summary>The window's geometry changed (coalesced per window). Returns the event's seq.</summary> + public uint Geometry(uint windowHash, in ScriptGeometry geo) => + AddCoalesced(new Item { Type = ScriptEventType.Geometry, WindowHash = windowHash, Geo = geo }); + + /// <summary>A click on a button: coalesced per widget into a count, never dropped. Returns the event's seq.</summary> + public uint Click(uint windowHash, uint key) + { + lock (_lock) + { + uint seq = _nextSeq++; + for (int i = 0; i < _items.Count; i++) + { + Item e = _items[i]; + if (e.Type == ScriptEventType.Clicked && e.WindowHash == windowHash && e.WidgetKey == key) + { + e.Count = Math.Min(e.Count + 1, ushort.MaxValue); + e.Seq = seq; + _items[i] = e; + return seq; + } + } + MakeRoom(); + _items.Add(new Item { Type = ScriptEventType.Clicked, Seq = seq, WindowHash = windowHash, WidgetKey = key, Count = 1 }); + return seq; + } + } + + /// <summary>A new bool value: coalesced per widget (the latest wins). Returns the event's seq.</summary> + public uint Bool(uint windowHash, uint key, bool value) => + AddCoalesced(new Item { Type = ScriptEventType.Bool, WindowHash = windowHash, WidgetKey = key, Value = value ? (byte)1 : (byte)0 }); + + /// <summary>The window was shown or hidden outside the owner's own flag. Returns the event's seq.</summary> + public uint Visibility(uint windowHash, bool visible, byte reason) + { + lock (_lock) + { + uint seq = _nextSeq++; + MakeRoom(); + _items.Add(new Item { Type = ScriptEventType.Visibility, Seq = seq, WindowHash = windowHash, Value = visible ? (byte)1 : (byte)0, Reason = reason }); + return seq; + } + } + + public void Error(uint windowHash, string text) + { + if (text.Length > 1024) text = text[..1024]; + lock (_lock) + { + MakeRoom(); + _items.Add(new Item { Type = ScriptEventType.Error, Seq = _nextSeq++, WindowHash = windowHash, Text = text }); + } + } + + /// <summary> + /// Full: drop the oldest Geometry event, else the oldest value/Open event, else the oldest + /// Visibility or Error event. Clicks are counted, never dropped. Caller holds the lock. + /// </summary> + private void MakeRoom() + { + if (_items.Count < ScriptWindowRegistry.MaxEventsPerOwner) return; + int value = -1, other = -1; + for (int i = 0; i < _items.Count; i++) + { + ushort t = _items[i].Type; + if (t == ScriptEventType.Geometry) { _items.RemoveAt(i); return; } + if (value < 0 && ScriptEventType.IsValue(t)) value = i; + else if (other < 0 && t is ScriptEventType.Visibility or ScriptEventType.Error) other = i; + } + if (value >= 0) _items.RemoveAt(value); + else if (other >= 0) _items.RemoveAt(other); + } + + /// <summary>Writes whole events into <paramref name="buffer"/>; returns the bytes written.</summary> + public unsafe int Drain(byte* buffer, int capacity, int* remaining) + { + lock (_lock) + { + int written = 0, taken = 0; + var dst = buffer == null || capacity <= 0 ? Span<byte>.Empty : new Span<byte>(buffer, capacity); + for (; taken < _items.Count; taken++) + { + Item e = _items[taken]; + int size = 16 + e.Type switch + { + ScriptEventType.Clicked => 3, + ScriptEventType.Bool => 1, + ScriptEventType.Int => 4, + ScriptEventType.Float => 4, + ScriptEventType.Text => 3 + (e.Bytes?.Length ?? 0), + ScriptEventType.Open => 1, + ScriptEventType.Geometry => 36, + ScriptEventType.Visibility => 2, + ScriptEventType.Error => 2 + Encoding.UTF8.GetByteCount(e.Text ?? string.Empty), + _ => 0, + }; + if (written + size > dst.Length) break; + Span<byte> o = dst.Slice(written, size); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(o, e.Type); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(o[2..], (ushort)size); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(o[4..], e.Seq); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(o[8..], e.WindowHash); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(o[12..], e.WidgetKey); + Span<byte> p = o[16..]; + switch (e.Type) + { + case ScriptEventType.Clicked: + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(p, (ushort)e.Count); + p[2] = 0; // left button + break; + case ScriptEventType.Bool: + case ScriptEventType.Open: + p[0] = e.Value; + break; + case ScriptEventType.Int: + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(p, e.Int); + break; + case ScriptEventType.Float: + System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p, e.Float); + break; + case ScriptEventType.Text: + { + byte[] text = e.Bytes ?? Array.Empty<byte>(); + p[0] = e.Value; + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(p[1..], (ushort)text.Length); + text.CopyTo(p[3..]); + break; + } + case ScriptEventType.Geometry: + { + ScriptGeometry g = e.Geo; + System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p, g.Pos.X); + System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[4..], g.Pos.Y); + System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[8..], g.Size.X); + System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[12..], g.Size.Y); + System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[16..], g.Avail.X); + System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[20..], g.Avail.Y); + System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[24..], g.Cursor.X); + System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[28..], g.Cursor.Y); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(p[32..], g.Flags); + break; + } + case ScriptEventType.Visibility: + p[0] = e.Value; + p[1] = e.Reason; + break; + case ScriptEventType.Error: + int n = Encoding.UTF8.GetBytes(e.Text ?? string.Empty, p[2..]); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(p, (ushort)n); + break; + } + written += size; + } + _items.RemoveRange(0, taken); + if (remaining != null) *remaining = _items.Count; + return written; + } + } +} + +/// <summary>A plugin that has script windows.</summary> +internal sealed class ScriptWindowOwner +{ + public readonly LoadedPlugin Plugin; + public readonly Dictionary<string, ScriptWindow> Windows = new(StringComparer.Ordinal); + public readonly ScriptEventQueue Events = new(); + + public ScriptWindowOwner(LoadedPlugin plugin) => Plugin = plugin; +} + +/// <summary>One script window: shared between the pump thread (submit) and AC's thread (replay).</summary> +internal sealed class ScriptWindow +{ + public readonly ScriptWindowOwner Owner; + public readonly string Key; + public readonly string PanelKey; + public readonly uint Hash; + + // Pump thread (Submit), read on AC's thread. + private DisplayList _list = DisplayList.Empty; + public DisplayList List => Volatile.Read(ref _list); + public void Publish(DisplayList list) => Volatile.Write(ref _list, list); + public volatile bool SubmittedVisible; + public volatile bool Removed; + public string Title = string.Empty; + public uint Flags; + /// <summary>Panel logical units. RequestSize/RequestPos: NaN = none.</summary> + public Vector2 DefaultSize, MinSize, RequestSize = new(float.NaN), RequestPos = new(float.NaN); + /// <summary>RequestPos is a FirstUseEver default position, used only when nothing is saved.</summary> + public bool PosIsDefault; + /// <summary>The spec's first-open position (PosIsDefault with a RequestPos); null = the cascade.</summary> + public Vector2? DefaultPos; + // Pump thread only: the placement requests last passed to the panel host (NaN = none) + // and the window's ListSeq at that time (the §3.2 re-application rule). + public Vector2 AppliedRequestSize = new(float.NaN), AppliedRequestPos = new(float.NaN); + public uint AppliedSizeListSeq, AppliedPosListSeq; + + // Visibility, last change wins (§3.3). The markers are set on the pump thread just + // before the owner's own Open/Close and consumed by the face on AC's thread, so an + // open or close the owner asked for sends no Visibility event. + public volatile bool ExpectOpen, ExpectClose; + /// <summary>Seq of the last Visibility event the player caused; an owner flag recorded before it (AckSeq below it) is stale.</summary> + public volatile uint PlayerVisibilitySeq; + /// <summary>The reason for the next player-caused open/close (0 = none: the face's default). Any thread.</summary> + public volatile int PendingReason; + // Pump thread only, under Sync: the owner's last submit for this window, kept so a + // visibility decision put off while an open/close was still in flight (ApplyVisible) + // is made at the owner's next poll, without waiting for another submit. + public bool VisibilityDeferred; + public uint LastAckSeq; + public uint LastListSeq; + /// <summary>The script error text the pump thread last applied (compared to avoid re-encoding).</summary> + public string? ErrorText; + private byte[]? _errorUtf8; + /// <summary>The script's error as pinned, NUL-terminated UTF-8; null = no error. Read on AC's thread.</summary> + public byte[]? ErrorUtf8 => Volatile.Read(ref _errorUtf8); + + /// <summary>Pump thread: stores the error text, allocating only when it changed.</summary> + public void SetError(string? text) + { + if (string.IsNullOrEmpty(text)) text = null; + if (string.Equals(text, ErrorText, StringComparison.Ordinal)) return; + ErrorText = text; + byte[]? bytes = null; + if (text != null) + { + int n = Encoding.UTF8.GetByteCount(text); + bytes = GC.AllocateArray<byte>(n + 1, pinned: true); + Encoding.UTF8.GetBytes(text, bytes); + } + Volatile.Write(ref _errorUtf8, bytes); + } + + // AC thread only (replay). + /// <summary>The player's edits the plugin hasn't acknowledged yet, and InputText buffers (no snap-back, §2.5).</summary> + public readonly ScriptLocals Locals = new(); + /// <summary>The geometry last sent in a Geometry event (logical units).</summary> + public ScriptGeometry LastGeometry; + public bool GeometrySent; + public DisplayList? LastReplayed; + /// <summary>First input not yet reflected in a replayed list: for the click → reaction measurement.</summary> + public uint PendingInputSeq; + public int PendingInputFrame; + public long PendingInputTicks; + + public ScriptWindow(ScriptWindowOwner owner, string key, string panelKey, uint hash) + { + Owner = owner; + Key = key; + PanelKey = panelKey; + Hash = hash; + } + + /// <summary>Records an input for the latency measurement (AC thread).</summary> + public void NoteInput(uint seq, int frame) + { + if (PendingInputSeq != 0) return; + PendingInputSeq = seq; + PendingInputFrame = frame; + PendingInputTicks = Stopwatch.GetTimestamp(); + } +} + +/// <summary>One line of the bar's Scripts menu. Built once per snapshot, never per frame.</summary> +internal sealed class ScriptBarItem +{ + public readonly ScriptWindow Window; + /// <summary>The key up to its last '/', e.g. "RynthLua/Tracker" (the owner's name when the key has none).</summary> + public readonly string Group; + /// <summary>True for the first item of its group (the menu draws the group header above it).</summary> + public readonly bool GroupStart; + /// <summary>The title plus "##sw" and the window hash in hex: unique, and the same across snapshots.</summary> + public readonly string MenuLabel; + public readonly string PanelKey; + + public ScriptBarItem(ScriptWindow window, string group, bool groupStart) + { + Window = window; + Group = group; + GroupStart = groupStart; + // A '##' inside the title would cut the visible text short (and '###' replace the ID). + string title = window.Title.Contains("##", StringComparison.Ordinal) ? window.Title.Replace("##", "# #") : window.Title; + MenuLabel = title + "##sw" + window.Hash.ToString("X8"); + PanelKey = window.PanelKey; + } +} + +internal static class ScriptWindowRegistry +{ + // §6.1 limits (Phase 0 starting values). + public const int MaxOpsPerWindow = 1500; + public const int MaxBytesPerWindow = 64 * 1024; + public const int MaxWindowsPerOwner = 32; + public const int MaxBytesPerSubmit = 256 * 1024; + public const int MaxEventsPerOwner = 1024; + /// <summary>Ops replayed per frame across all script windows; windows past it draw a placeholder.</summary> + public const int MaxReplayOpsPerFrame = 4000; + public const string PanelKeyPrefix = "script:"; + + private static readonly object Sync = new(); + private static readonly Dictionary<LoadedPlugin, ScriptWindowOwner> Owners = new(ReferenceEqualityComparer.Instance); + /// <summary>Panel key → window, across owners: a key belongs to the first owner that used it.</summary> + private static readonly Dictionary<string, ScriptWindow> ByPanelKey = new(StringComparer.OrdinalIgnoreCase); + private static long _lastRejectLogTicks; + + // The bar's Scripts menu: a copy-on-write snapshot of the ShowInBar windows, republished + // (under Sync) when the window set, a title or a ShowInBar flag changed. AC's thread + // reads it without taking Sync. + private static ScriptBarItem[] _barItems = Array.Empty<ScriptBarItem>(); + private static bool _barDirty; + + /// <summary>The Scripts menu's items, grouped (empty = no Scripts button). Any thread.</summary> + public static ScriptBarItem[] BarItems => Volatile.Read(ref _barItems); + + // ── Host functions ─────────────────────────────────────────────────── + + /// <summary>UiSubmit: the owner's complete window set. Pump thread, inside the owner's dispatch.</summary> + public static unsafe int Submit(LoadedPlugin plugin, byte* data, int length) + { + float displayMax = DisplayMax(); + int rc = DisplayListParser.Parse(data, length, displayMax, out uint ackSeq, out List<ParsedWindow> windows, out string error); + if (rc != 0) + { + // Nothing applied: the previous lists stay; the owner hears why. + GetOrAddOwner(plugin).Events.Error(0, $"list refused: {error}"); + long now = Stopwatch.GetTimestamp(); + if (now - Interlocked.Read(ref _lastRejectLogTicks) > Stopwatch.Frequency * 5) + { + Interlocked.Exchange(ref _lastRejectLogTicks, now); + RynthLog.UI($"ScriptWindows: {plugin.DisplayName} submit refused ({rc}): {error}"); + } + return rc; + } + + lock (Sync) + { + ScriptWindowOwner owner = GetOrAddOwnerLocked(plugin); + var seen = new HashSet<string>(StringComparer.Ordinal); + foreach (ParsedWindow pw in windows) + { + seen.Add(pw.Key); + string panelKey = PanelKeyPrefix + SanitizeKey(pw.Key); + if (!owner.Windows.TryGetValue(pw.Key, out ScriptWindow? w)) + { + // Panel keys ignore case and sanitise '=', ',' and '#', so two keys can meet + // on one panel entry, from another owner or from this one ("Hud" and "hud"). + // Sharing it would let each window open, close and unregister the other's. + if (ByPanelKey.TryGetValue(panelKey, out ScriptWindow? other)) + { + owner.Events.Error(pw.Hash, other.Owner != owner + ? $"window '{pw.Key}' belongs to {other.Owner.Plugin.DisplayName}" + : $"window '{pw.Key}' clashes with window '{other.Key}' (window keys ignore case, and '=', ',' and '#' count as '_')"); + continue; + } + w = new ScriptWindow(owner, pw.Key, panelKey, pw.Hash); + owner.Windows[pw.Key] = w; + ByPanelKey[panelKey] = w; + Apply(w, pw, ackSeq, isNew: true); + } + else + { + Apply(w, pw, ackSeq, isNew: false); + } + } + + // A window missing from the set is closed (the script stopped, or the hud was disposed). + List<string>? gone = null; + foreach (var kv in owner.Windows) + if (!seen.Contains(kv.Key)) (gone ??= new List<string>()).Add(kv.Key); + if (gone != null) + foreach (string key in gone) + RemoveLocked(owner, owner.Windows[key]); + PublishBarLocked(); + } + return 0; + } + + /// <summary>UiPollEvents. Pump thread, inside the owner's dispatch.</summary> + public static unsafe int PollEvents(LoadedPlugin plugin, byte* buffer, int capacity, int* remaining) + { + ScriptWindowOwner? owner; + lock (Sync) + { + if (Owners.TryGetValue(plugin, out owner)) + RecheckDeferredLocked(owner); + } + if (owner == null) + { + if (remaining != null) *remaining = 0; + return 0; + } + return owner.Events.Drain(buffer, capacity, remaining); + } + + /// <summary>UiGetInfo. Any thread.</summary> + public static unsafe int GetInfo(UiInfoNative* info) + { + if (info == null) return 0; + uint want = info->Size; + if (want < 8) return 0; + UiInfoNative full = default; + full.Size = (uint)sizeof(UiInfoNative); + bool imgui = EngineSettings.EnableImGuiBackend; + full.Flags = (imgui ? 1u : 0u) | (Compatibility.LoginLifecycleHooks.HasObservedLoginComplete ? 2u : 0u); + full.MaxFormatVersion = DisplayListParser.FormatVersion; + full.OpLevel = DisplayListParser.OpLevel; + full.MaxOpsPerWindow = MaxOpsPerWindow; + full.MaxBytesPerWindow = MaxBytesPerWindow; + full.MaxWindowsPerOwner = MaxWindowsPerOwner; + full.MaxBytesPerSubmit = MaxBytesPerSubmit; + ScriptWindowMetrics.Fill(&full); + int n = (int)Math.Min(want, (uint)sizeof(UiInfoNative)); + full.Size = (uint)n; + Buffer.MemoryCopy(&full, info, n, n); + return imgui ? n : 0; + } + + // ── Owners ─────────────────────────────────────────────────────────── + + private static ScriptWindowOwner GetOrAddOwner(LoadedPlugin plugin) + { + lock (Sync) return GetOrAddOwnerLocked(plugin); + } + + private static ScriptWindowOwner GetOrAddOwnerLocked(LoadedPlugin plugin) + { + if (!Owners.TryGetValue(plugin, out ScriptWindowOwner? owner)) + Owners[plugin] = owner = new ScriptWindowOwner(plugin); + return owner; + } + + /// <summary>The plugin unloaded (or failed): its windows close and its queue goes. Pump thread.</summary> + public static void DropOwner(LoadedPlugin plugin) + { + lock (Sync) + { + if (!Owners.TryGetValue(plugin, out ScriptWindowOwner? owner)) return; + foreach (ScriptWindow w in new List<ScriptWindow>(owner.Windows.Values)) + RemoveLocked(owner, w); + Owners.Remove(plugin); + PublishBarLocked(); + } + } + + /// <summary>After each tick: owners whose plugin failed lose their windows.</summary> + public static void DropFailedOwners() + { + List<LoadedPlugin>? failed = null; + lock (Sync) + { + if (Owners.Count == 0) return; + foreach (LoadedPlugin p in Owners.Keys) + if (p.Failed) (failed ??= new List<LoadedPlugin>()).Add(p); + } + if (failed == null) return; + foreach (LoadedPlugin p in failed) + { + RynthLog.UI($"ScriptWindows: {p.DisplayName} failed; closing its windows."); + DropOwner(p); + } + } + + /// <summary>Engine shutdown: everything goes.</summary> + public static void Reset() + { + lock (Sync) + { + foreach (ScriptWindowOwner owner in new List<ScriptWindowOwner>(Owners.Values)) + foreach (ScriptWindow w in new List<ScriptWindow>(owner.Windows.Values)) + RemoveLocked(owner, w); + Owners.Clear(); + ByPanelKey.Clear(); + _barDirty = false; + Volatile.Write(ref _barItems, Array.Empty<ScriptBarItem>()); + } + } + + /// <summary>Rebuilds the Scripts menu snapshot when something it shows changed. Caller holds Sync.</summary> + private static void PublishBarLocked() + { + if (!_barDirty) return; + _barDirty = false; + var rows = new List<(string Group, ScriptWindow W)>(); + foreach (ScriptWindowOwner o in Owners.Values) + foreach (ScriptWindow w in o.Windows.Values) + { + if ((w.Flags & WindowFlags.ShowInBar) == 0) continue; + int slash = w.Key.LastIndexOf('/'); + string group = slash > 0 ? w.Key[..slash] : o.Plugin.DisplayName; + rows.Add((group, w)); + } + if (rows.Count == 0) + { + Volatile.Write(ref _barItems, Array.Empty<ScriptBarItem>()); + return; + } + rows.Sort(static (a, b) => + { + int c = string.Compare(a.Group, b.Group, StringComparison.OrdinalIgnoreCase); + if (c == 0) c = string.Compare(a.Group, b.Group, StringComparison.Ordinal); + if (c == 0) c = string.Compare(a.W.Title, b.W.Title, StringComparison.OrdinalIgnoreCase); + return c != 0 ? c : string.Compare(a.W.Key, b.W.Key, StringComparison.Ordinal); + }); + var items = new ScriptBarItem[rows.Count]; + for (int i = 0; i < rows.Count; i++) + items[i] = new ScriptBarItem(rows[i].W, rows[i].Group, + groupStart: i == 0 || !string.Equals(rows[i].Group, rows[i - 1].Group, StringComparison.Ordinal)); + Volatile.Write(ref _barItems, items); + } + + // ── Windows ────────────────────────────────────────────────────────── + + /// <summary>The flag bits that shape the panel spec (a change re-registers the entry).</summary> + private const uint SpecFlags = WindowFlags.ChromeNone | WindowFlags.NoBackground + | WindowFlags.NoScrollbar | WindowFlags.NoScrollWithMouse; + + private static void Apply(ScriptWindow w, ParsedWindow pw, uint ackSeq, bool isNew) + { + Vector2? defaultPos = pw.PosIsDefault && !float.IsNaN(pw.RequestPos.X) ? pw.RequestPos : null; + bool specChanged = isNew || ((w.Flags ^ pw.Flags) & SpecFlags) != 0 + || w.DefaultSize != pw.DefaultSize || w.MinSize != pw.MinSize || w.DefaultPos != defaultPos; + bool titleChanged = w.Title != pw.Title; + if (isNew || titleChanged || ((w.Flags ^ pw.Flags) & WindowFlags.ShowInBar) != 0) + _barDirty = true; + w.Flags = pw.Flags; + w.Title = pw.Title; + w.DefaultSize = pw.DefaultSize; + w.MinSize = pw.MinSize; + w.RequestSize = pw.RequestSize; + w.RequestPos = pw.RequestPos; + w.PosIsDefault = pw.PosIsDefault; + w.DefaultPos = defaultPos; + w.SetError((pw.Flags & WindowFlags.HasError) != 0 ? pw.ErrorText : null); + if (pw.List != null) w.Publish(pw.List); + + // DrawPanel reads the entry's spec every frame, so a new spec applies at once. + if (specChanged) + ImGuiPanelHost.RegisterDynamic(w.PanelKey, w.Title, SpecFor(w), () => new ScriptWindowFace(w)); + else if (titleChanged) + ImGuiPanelHost.SetDisplayTitle(w.PanelKey, w.Title); + + w.LastAckSeq = ackSeq; + w.LastListSeq = pw.ListSeq; + bool opened = ApplyVisible(w, (pw.Flags & WindowFlags.Visible) != 0, ackSeq); + ApplyRequests(w, pw.ListSeq, opened); + } + + /// <summary> + /// The visibility decisions ApplyVisible put off while an open/close was in flight, made + /// now from the owner's last submit. Without this a window stayed as the in-flight change + /// left it until the owner happened to submit again, which a hud whose picture doesn't + /// change never does (e.g. hidden and shown again before AC drew a frame, or while AC was + /// minimised and drew none). Pump thread (the owner's poll), under Sync. + /// </summary> + private static void RecheckDeferredLocked(ScriptWindowOwner owner) + { + foreach (ScriptWindow w in owner.Windows.Values) + { + if (!w.VisibilityDeferred || w.Removed) continue; + if (ApplyVisible(w, w.SubmittedVisible, w.LastAckSeq)) + ApplyRequests(w, w.LastListSeq, opened: true); + } + } + + /// <summary> + /// The owner's Visible flag, last change wins (§3.3). The player's X, the bar and + /// /rc ui open|close change the window locally and queue one Visibility event (the + /// face's OnShown/OnHidden); the owner's flag is stale until its AckSeq reaches that + /// event's seq, and a stale flag neither opens nor closes. Otherwise the window follows + /// the flag; the expect markers keep the owner's own open/close from sending an event. + /// While a queued open/close hasn't reached AC's thread yet, nothing is decided: the + /// player's X closes locally at once but its event is queued only when the close is + /// applied, so a submit in between would otherwise reopen it. The decision is kept + /// (VisibilityDeferred) and made at the owner's next poll or submit, whichever comes + /// first. Returns true when this call opened the window. Pump thread, under Sync. + /// </summary> + private static bool ApplyVisible(ScriptWindow w, bool visible, uint ackSeq) + { + w.SubmittedVisible = visible; + w.VisibilityDeferred = false; + // In-flight first: AC's thread sets PlayerVisibilitySeq (OnShown/OnHidden) before the + // entry stops transitioning, so once it has stopped the stale check below sees the seq. + if (ImGuiPanelHost.IsTransitioning(w.PanelKey)) + { + w.VisibilityDeferred = true; // decided at the owner's next poll + return false; + } + if (ackSeq < w.PlayerVisibilitySeq) return false; // stale: the player changed it since + bool open = ImGuiPanelHost.IsOpen(w.PanelKey); + if (visible && !open) + { + w.ExpectOpen = true; + ImGuiPanelHost.Open(w.PanelKey); + return true; + } + if (!visible && open) + { + w.ExpectClose = true; + ImGuiPanelHost.Close(w.PanelKey); + } + return false; + } + + /// <summary> + /// The bar's (or a command's) show/hide: the window opens or closes at once and the + /// owner gets a Visibility event with reason 2 (bar/command). Any thread. + /// </summary> + public static void PlayerSetVisible(ScriptWindow w, bool visible) + { + if (w.Removed || ImGuiPanelHost.IsOpen(w.PanelKey) == visible) return; + w.PendingReason = VisibilityReason.BarOrCommand; + if (visible) ImGuiPanelHost.Open(w.PanelKey); + else ImGuiPanelHost.Close(w.PanelKey); + } + + /// <summary> + /// SetNextWindowSize / SetNextWindowPos (§3.2): a request is passed to the panel host + /// when its value changed since the last one applied, when the window was re-recorded + /// (a new ListSeq), or when this submit opens the window. A NaN value (none) forgets the + /// last one. The host applies it on the window's next docked frame, after an open's + /// placement from the saved state. Pump thread. + /// </summary> + private static void ApplyRequests(ScriptWindow w, uint listSeq, bool opened) + { + Vector2 size = w.RequestSize; + if (float.IsNaN(size.X)) + { + w.AppliedRequestSize = new Vector2(float.NaN); + } + else if (opened || size != w.AppliedRequestSize || listSeq != w.AppliedSizeListSeq) + { + w.AppliedRequestSize = size; + w.AppliedSizeListSeq = listSeq; + ImGuiPanelHost.RequestSize(w.PanelKey, size); + } + + Vector2 pos = w.RequestPos; + if (float.IsNaN(pos.X) || w.PosIsDefault) + { + // None, or a FirstUseEver default (the spec's DefaultPos), which is not a request. + w.AppliedRequestPos = new Vector2(float.NaN); + } + else if (opened || pos != w.AppliedRequestPos || listSeq != w.AppliedPosListSeq) + { + w.AppliedRequestPos = pos; + w.AppliedPosListSeq = listSeq; + ImGuiPanelHost.RequestPos(w.PanelKey, pos); + } + } + + private static PanelSpec SpecFor(ScriptWindow w) + { + Vector2 size = w.DefaultSize; + if (size.X <= 0) size.X = 300; + if (size.Y <= 0) size.Y = 200; + Vector2 min = Vector2.Max(w.MinSize, new Vector2(60, 40)); + uint f = w.Flags; + bool none = (f & WindowFlags.ChromeNone) != 0; + ImGuiNET.ImGuiWindowFlags body = ImGuiNET.ImGuiWindowFlags.None; + if ((f & WindowFlags.NoScrollbar) != 0) body |= ImGuiNET.ImGuiWindowFlags.NoScrollbar; + if ((f & WindowFlags.NoScrollWithMouse) != 0) body |= ImGuiNET.ImGuiWindowFlags.NoScrollWithMouse; + // ClickThrough stays on the face (IImGuiPanel.ClickThrough), read every frame. + // Pop-outs aren't in the MVP (decision 8): no ↗. + return new PanelSpec(size, min, none ? PanelChrome.None : PanelChrome.Standard, + Background: (f & WindowFlags.NoBackground) != 0 ? 0u : null, + NoPopOut: true, + BodyFlags: body, + DefaultPos: w.DefaultPos); + } + + private static void RemoveLocked(ScriptWindowOwner owner, ScriptWindow w) + { + w.Removed = true; + w.SubmittedVisible = false; + _barDirty = true; + owner.Windows.Remove(w.Key); + if (ByPanelKey.TryGetValue(w.PanelKey, out ScriptWindow? cur) && ReferenceEquals(cur, w)) + ByPanelKey.Remove(w.PanelKey); + ImGuiPanelHost.Unregister(w.PanelKey); + } + + /// <summary>PanelStateStore rows are "panel.<key>=..." lines: no '=', ',' or control characters.</summary> + private static string SanitizeKey(string key) + { + var sb = new StringBuilder(key.Length); + foreach (char c in key) sb.Append(c is '=' or ',' or '#' || char.IsControl(c) ? '_' : c); + return sb.ToString(); + } + + private static float DisplayMax() + { + float m = ScriptWindowMetrics.DisplayMax; + return m > 0 ? m : 16384f; + } + + /// <summary>A line per owner and window, for diagnostics. Any thread.</summary> + public static List<string> Describe() + { + var lines = new List<string>(); + lock (Sync) + { + foreach (ScriptWindowOwner o in Owners.Values) + foreach (ScriptWindow w in o.Windows.Values) + lines.Add($"script window {w.PanelKey}: owner={o.Plugin.DisplayName} visible={w.SubmittedVisible} open={ImGuiPanelHost.IsOpen(w.PanelKey)}" + + $" flags=0x{w.Flags:X3}({DescribeFlags(w.Flags)}) error={(w.ErrorUtf8 != null ? "shown" : "none")}" + + $" ops={w.List.OpCount} listSeq={w.List.ListSeq} playerSeq={w.PlayerVisibilitySeq}"); + } + lines.Add($"script windows: {BarItems.Length} in the bar's Scripts menu"); + return lines; + } + + private static string DescribeFlags(uint f) + { + var sb = new StringBuilder(); + void Add(uint bit, string name) { if ((f & bit) != 0) { if (sb.Length > 0) sb.Append('|'); sb.Append(name); } } + Add(WindowFlags.Visible, "Visible"); + Add(WindowFlags.ShowInBar, "ShowInBar"); + Add(WindowFlags.ChromeNone, "ChromeNone"); + Add(WindowFlags.ClickThrough, "ClickThrough"); + Add(WindowFlags.NoBackground, "NoBackground"); + Add(WindowFlags.NoScrollbar, "NoScrollbar"); + Add(WindowFlags.NoScrollWithMouse, "NoScrollWithMouse"); + Add(WindowFlags.AutoSize, "AutoSize"); + Add(WindowFlags.NoPopOut, "NoPopOut"); + Add(WindowFlags.HasError, "HasError"); + Add(WindowFlags.PosIsDefault, "PosIsDefault"); + return sb.Length > 0 ? sb.ToString() : "none"; + } +} + +/// <summary> +/// Layout facts for UiGetInfo, taken on AC's thread while a script window +/// draws (the panel's font pushed) and published as one snapshot. +/// </summary> +internal static unsafe class ScriptWindowMetrics +{ + private sealed class Snapshot + { + public float DisplayW, DisplayH, UiScale, LineH, FrameH, SpacingX, SpacingY, PadX, PadY; + public readonly float[] Advance = new float[95]; + public uint Frame; + } + + private static Snapshot? _current; + private static long _takenAt; + + public static float DisplayMax + { + get + { + Snapshot? s = Volatile.Read(ref _current); + return s == null ? 0 : 4f * Math.Max(s.DisplayW, s.DisplayH); + } + } + + /// <summary>Retakes the snapshot about once a second. AC thread, inside the ImGui frame.</summary> + public static void Refresh() + { + long now = Stopwatch.GetTimestamp(); + if (_current != null && now - _takenAt < Stopwatch.Frequency) return; + _takenAt = now; + var io = ImGuiNET.ImGui.GetIO(); + var style = ImGuiNET.ImGui.GetStyle(); + var s = new Snapshot + { + DisplayW = io.DisplaySize.X, + DisplayH = io.DisplaySize.Y, + UiScale = EngineFrameController.FontScale, + LineH = ImGuiNET.ImGui.GetTextLineHeight(), + FrameH = ImGuiNET.ImGui.GetFrameHeight(), + SpacingX = style.ItemSpacing.X, + SpacingY = style.ItemSpacing.Y, + PadX = style.FramePadding.X, + PadY = style.FramePadding.Y, + Frame = (uint)ImGuiNET.ImGui.GetFrameCount(), + }; + byte* one = stackalloc byte[2]; + for (int i = 0; i < 95; i++) + { + one[0] = (byte)(' ' + i); + one[1] = 0; + Vector2 size; + ImGuiNET.ImGuiNative.igCalcTextSize(&size, one, one + 1, 0, -1f); + s.Advance[i] = size.X; + } + Volatile.Write(ref _current, s); + } + + public static void Fill(UiInfoNative* info) + { + Snapshot? s = Volatile.Read(ref _current); + if (s == null) return; + info->DisplayWidth = s.DisplayW; + info->DisplayHeight = s.DisplayH; + info->UiScale = s.UiScale; + info->TextLineHeight = s.LineH; + info->FrameHeight = s.FrameH; + info->ItemSpacingX = s.SpacingX; + info->ItemSpacingY = s.SpacingY; + info->FramePaddingX = s.PadX; + info->FramePaddingY = s.PadY; + for (int i = 0; i < 95; i++) info->AsciiAdvance[i] = s.Advance[i]; + info->FrameCounter = s.Frame; + } +} diff --git a/src/RynthCore.Engine/UI/TrackerSettings.cs b/src/RynthCore.Engine/UI/TrackerSettings.cs new file mode 100644 index 0000000..170d66d --- /dev/null +++ b/src/RynthCore.Engine/UI/TrackerSettings.cs @@ -0,0 +1,74 @@ +// ============================================================================ +// RynthCore.Engine - UI/TrackerSettings.cs +// The Tracker panel's background opacity, shared by its ImGui and Avalonia +// faces: %APPDATA%\RynthCore\rynthtracker_settings.json ({"bgAlpha":0-255}). +// Loaded on the engine init worker; saves go through UiBackgroundWriter so +// the ImGui face never writes a file from AC's thread. +// ============================================================================ + +using System; +using System.IO; +using System.Text.Json; + +namespace RynthCore.Engine.UI; + +internal static class TrackerSettings +{ + private static volatile int _bgAlpha = 0xCC; // ~80% + private static volatile bool _loaded; + private static readonly object LoadSync = new(); + + private static string SettingsPath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthtracker_settings.json"); + + /// <summary>Background alpha 0-255.</summary> + public static byte BgAlpha + { + get + { + EnsureLoaded(); + return (byte)_bgAlpha; + } + } + + /// <summary>Sets the alpha now; <paramref name="save"/> writes the file in the background.</summary> + public static void SetBgAlpha(byte alpha, bool save) + { + EnsureLoaded(); + _bgAlpha = alpha; + if (save) + UiBackgroundWriter.Enqueue("tracker settings", Save); + } + + public static void EnsureLoaded() + { + if (_loaded) return; + lock (LoadSync) + { + if (_loaded) return; + try + { + string path = SettingsPath; + if (File.Exists(path)) + { + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + if (doc.RootElement.TryGetProperty("bgAlpha", out var v)) + _bgAlpha = Math.Clamp(v.GetInt32(), 0, 255); + } + } + catch { } + _loaded = true; + } + } + + private static void Save() + { + try + { + string path = SettingsPath; + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, $"{{\"bgAlpha\":{_bgAlpha}}}"); + } + catch { } + } +} diff --git a/src/RynthCore.Engine/UI/UiBackgroundWriter.cs b/src/RynthCore.Engine/UI/UiBackgroundWriter.cs new file mode 100644 index 0000000..81d1899 --- /dev/null +++ b/src/RynthCore.Engine/UI/UiBackgroundWriter.cs @@ -0,0 +1,54 @@ +// ============================================================================ +// RynthCore.Engine - UI/UiBackgroundWriter.cs +// Runs UI persistence (panel_state.txt, per-panel settings files) off the +// calling thread, strictly in the order it was queued. +// +// ImGui panel faces run on AC's render thread, which must not do file I/O +// (docs/IMGUI_PARITY_PLAN.md §4.1). Order matters: closing an ImGui face and +// then popping the panel out writes the same panel_state row twice, and the +// second write must win. One queue, drained by one pool work item at a time. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Threading; + +namespace RynthCore.Engine.UI; + +internal static class UiBackgroundWriter +{ + private static readonly object Sync = new(); + private static readonly Queue<(string Label, Action Work)> Pending = new(); + private static bool _draining; + + public static void Enqueue(string label, Action work) + { + lock (Sync) + { + Pending.Enqueue((label, work)); + if (_draining) return; + _draining = true; + } + ThreadPool.UnsafeQueueUserWorkItem(static _ => Drain(), null); + } + + private static void Drain() + { + while (true) + { + (string Label, Action Work) item; + lock (Sync) + { + if (Pending.Count == 0) + { + _draining = false; + return; + } + item = Pending.Dequeue(); + } + + try { item.Work(); } + catch (Exception ex) { RynthLog.UI($"UiBackgroundWriter: '{item.Label}' threw {ex.GetType().Name}: {ex.Message}"); } + } + } +} diff --git a/src/RynthCore.Injector/EngineInjectionService.cs b/src/RynthCore.Injector/EngineInjectionService.cs index 3214bda..e549b8b 100644 --- a/src/RynthCore.Injector/EngineInjectionService.cs +++ b/src/RynthCore.Injector/EngineInjectionService.cs @@ -437,6 +437,39 @@ public sealed class EngineInjectionService onProcessCreated); } + /// <summary> + /// Spike (Decal bridge): launches AC suspended, injects Decal's Inject.dll + + /// DecalStartup (as <see cref="LaunchSuspendedAndInjectDecal"/>), then, unless + /// <paramref name="enginePath"/> is null, the RynthCore loader, and resumes. + /// Decal goes first, as it would for a player whose client Decal launched. + /// </summary> + public InjectionResult LaunchSuspendedAndInjectDecalThenEngine( + string clientPath, + string arguments, + string decalInjectDllPath, + string? enginePath, + Action<string>? log = null, + Action<int>? onProcessCreated = null) + { + return LaunchSuspendedAndInvoke( + clientPath, + arguments, + stackLabel: enginePath == null ? "Decal" : "Decal + RynthCore", + failureContextPath: enginePath ?? decalInjectDllPath, + successMessage: enginePath == null + ? "Launched AC and injected Decal successfully." + : "Launched AC and injected Decal, then RynthCore, successfully.", + inject: (proc, perCallLog) => + { + InjectionResult decal = InjectDecalIntoProcess(proc, decalInjectDllPath, perCallLog); + if (!decal.Success || enginePath == null) + return decal; + return InjectIntoProcess(proc, enginePath, perCallLog); + }, + log, + onProcessCreated); + } + private InjectionResult LaunchSuspendedAndInvoke( string clientPath, string arguments, @@ -841,6 +874,12 @@ public sealed class EngineInjectionService "RynthCore.Engine.dll", }; + /// <summary>True when the RynthCore Decal bridge (a Decal network filter) is loaded in the + /// client: any Decal client of this Windows user while the bridge is registered, with or + /// without RynthCore. The core update replaces that DLL, so it waits for these too.</summary> + public bool IsDecalBridgeLoaded(Process targetProcess) => + IsModuleLoaded(targetProcess, "RynthCore.DecalBridge.dll"); + public bool IsRynthCoreLoaded(Process targetProcess) { foreach (string name in RynthCoreModuleNames) diff --git a/src/RynthCore.Injector/LaunchCommand.cs b/src/RynthCore.Injector/LaunchCommand.cs index 74ca2e1..f1059f4 100644 --- a/src/RynthCore.Injector/LaunchCommand.cs +++ b/src/RynthCore.Injector/LaunchCommand.cs @@ -25,7 +25,11 @@ namespace RynthCore.Injector; /// Usage: /// RynthCore.Injector.exe --launch [--account <name|id>] [--server <name|id>] /// [--client <acclient.exe>] [--engine <loader.dll>] -/// [--no-login] +/// [--no-login] [--character <name>] +/// [--decal | --decal-only] [--host <host>] [--port <n>] +/// +/// --decal also injects Decal (Inject.dll + DecalStartup, found through Decal's +/// registry key) before the RynthCore loader; --decal-only injects Decal alone. /// /// On success prints a machine-readable <c>LAUNCHED_PID=<pid></c> line and /// returns 0. Never prompts (safe for non-interactive shells). @@ -58,6 +62,15 @@ internal static class LaunchCommand string? clientOverride = GetOpt(args, "--client"); string? engineOverride = GetOpt(args, "--engine"); bool noLogin = HasFlag(args, "--no-login"); + string? characterOverride = GetOpt(args, "--character"); + // Spike (Decal bridge): --decal injects Decal's Inject.dll (DecalStartup) before + // the RynthCore loader; --decal-only injects Decal alone (a measurement baseline). + bool decalOnly = HasFlag(args, "--decal-only"); + bool withDecal = decalOnly || HasFlag(args, "--decal"); + // Spike: point a saved server profile at another host/port for this launch only + // (the profile itself is not changed). + string? hostOverride = GetOpt(args, "--host"); + string? portOverride = GetOpt(args, "--port"); string settingsPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @@ -84,15 +97,46 @@ internal static class LaunchCommand return 2; } + // "Decal + RynthCore" accounts are listed in decal-accounts.json; appsettings.json has + // them as RynthCore so older launchers can read it (RynthCore.App.DecalAccountModes). + HashSet<string> decalBridgeIds = RynthCore.App.DecalAccountModes.ReadIds( + RynthCore.App.DecalAccountModes.PathIn(Path.GetDirectoryName(settingsPath)!), out string? decalModesError); + if (decalModesError != null) + Log(decalModesError); + foreach (AccountDto a in settings.AccountProfiles ?? new()) + { + if (RynthCore.App.DecalAccountModes.IsDecalBridge(decalBridgeIds, a.Id, (RynthCore.App.InjectionMode)(int)a.InjectionMode)) + a.InjectionMode = InjMode.DecalBridge; + } + // ── Resolve account ────────────────────────────────────────────────── List<AccountDto> accounts = settings.AccountProfiles ?? new(); + List<ServerDto> servers = settings.ServerProfiles ?? new(); + ServerDto? selectedServer = string.IsNullOrWhiteSpace(serverSelector) + ? null + : servers.FirstOrDefault(s => + string.Equals(s.Id, serverSelector, StringComparison.OrdinalIgnoreCase) || + string.Equals(s.Name, serverSelector, StringComparison.OrdinalIgnoreCase)); string? selector = accountSelector ?? settings.SelectedAccountProfileId; AccountDto? account = null; if (!string.IsNullOrWhiteSpace(selector)) { account = accounts.FirstOrDefault(a => - string.Equals(a.Id, selector, StringComparison.OrdinalIgnoreCase) || - string.Equals(a.AccountName, selector, StringComparison.OrdinalIgnoreCase)); + string.Equals(a.Id, selector, StringComparison.OrdinalIgnoreCase)); + if (account == null) + { + // The same account name can exist on several servers: when a + // server was given, prefer the profile saved for that server. + List<AccountDto> byName = accounts + .Where(a => string.Equals(a.AccountName, selector, StringComparison.OrdinalIgnoreCase)) + .ToList(); + account = (selectedServer != null + ? byName.FirstOrDefault(a => string.Equals(a.ServerId, selectedServer.Id, StringComparison.OrdinalIgnoreCase)) + : null) + ?? byName.FirstOrDefault(); + if (byName.Count > 1 && selectedServer == null) + Log($"WARNING: account name '{selector}' is saved for {byName.Count} servers; using the first. Pass --server or the profile id to pick one."); + } } if (account == null && (settings.CheckedLaunchAccountProfileIds?.Count ?? 0) > 0) { @@ -106,18 +150,42 @@ internal static class LaunchCommand return 2; } - if (account.InjectionMode == InjMode.Decal) - Log($"WARNING: account '{account.AccountName}' is configured for Decal mode; --launch always injects the RynthCore engine."); + if (account.InjectionMode == InjMode.Decal && !withDecal) + Log($"WARNING: account '{account.AccountName}' is configured for Decal mode; --launch always injects the RynthCore engine (pass --decal for both)."); + // "Decal + RynthCore" accounts launch as --decal does. Registration of the Decal + // bridge is left to the launcher / --decal-bridge register (explicit, never implied). + if (account.InjectionMode == InjMode.DecalBridge && !withDecal) + { + withDecal = true; + Log($"Account '{account.AccountName}' is set to Decal + RynthCore: injecting Decal, then RynthCore."); + } + + string? decalInjectPath = null; + if (withDecal) + { + decalInjectPath = TryGetDecalInjectPath(); + if (decalInjectPath == null) + { + Log("--decal: Decal's Inject.dll not found (HKLM\\SOFTWARE\\Decal\\Agent AgentPath)."); + return 2; + } + // Say up front whether Decal will load the bridge in this client (read-only; this + // tool never registers on its own). Without it the engine runs the old coexistence path. + if (account.InjectionMode == InjMode.DecalBridge) + { + try + { + var check = RynthCore.App.RealDecalCheckHost.Check(RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory, + RynthCore.App.DecalLocator.TryGetDecalAcClientPath(), null); + Log((check.Blocking ? "WARNING: " : "") + check.Summary + + (check.Blocking ? " (RynthCore.Injector --decal-bridge check for details, --decal-bridge register to fix)" : "")); + } + catch (Exception ex) { Log($"Decal bridge check failed: {ex.GetType().Name}: {ex.Message}"); } + } + } // ── Resolve server ─────────────────────────────────────────────────── - List<ServerDto> servers = settings.ServerProfiles ?? new(); - ServerDto? server = null; - if (!string.IsNullOrWhiteSpace(serverSelector)) - { - server = servers.FirstOrDefault(s => - string.Equals(s.Id, serverSelector, StringComparison.OrdinalIgnoreCase) || - string.Equals(s.Name, serverSelector, StringComparison.OrdinalIgnoreCase)); - } + ServerDto? server = selectedServer; server ??= servers.FirstOrDefault(s => string.Equals(s.Id, account.ServerId, StringComparison.OrdinalIgnoreCase)); if (server == null) @@ -126,6 +194,18 @@ internal static class LaunchCommand return 2; } + if (!string.IsNullOrWhiteSpace(hostOverride)) + server.Host = hostOverride!; + if (!string.IsNullOrWhiteSpace(portOverride)) + { + if (!int.TryParse(portOverride, NumberStyles.Integer, CultureInfo.InvariantCulture, out int port) || port <= 0 || port > 65535) + { + Log($"--port: '{portOverride}' is not a port number."); + return 2; + } + server.Port = port; + } + // ── Resolve paths ──────────────────────────────────────────────────── string clientPath; if (!string.IsNullOrWhiteSpace(clientOverride)) @@ -154,7 +234,25 @@ internal static class LaunchCommand string conn = ComputeConnectionString(server); string rodat = server.RodatEnabled ? "on" : "off"; string acct = account.AccountName ?? string.Empty; - string pwd = account.Password ?? string.Empty; + // Saved passwords are DPAPI-encrypted for the Windows user that saved them + // (LaunchAccountProfile.PasswordProtected). Decrypted here, at the moment of use; + // never logged. A plain "Password" means the launcher hasn't migrated the file yet. + string pwd; + if (!string.IsNullOrEmpty(account.Password)) + { + pwd = account.Password; + Log("WARNING: this account's password is still stored in plain text; open the launcher once to encrypt it."); + } + else if (string.IsNullOrEmpty(account.PasswordProtected)) + { + pwd = string.Empty; + } + else if (!RynthCore.App.AccountPasswordProtection.TryUnprotect(account.PasswordProtected, out pwd)) + { + Log($"The saved password for account '{acct}' can't be read on this Windows user (settings copied from another user or PC?). " + + "Password needs re-entering: edit the account in the launcher and type it again."); + return 2; + } string arguments = server.Emulator == EmulatorKind.Gdle ? string.Join(" ", @@ -168,8 +266,9 @@ internal static class LaunchCommand "-h", Quote(conn), "-rodat", rodat); - string targetCharacter = noLogin || account.CharacterName == NoneOption - ? string.Empty + string targetCharacter = noLogin ? string.Empty + : !string.IsNullOrWhiteSpace(characterOverride) ? characterOverride! + : account.CharacterName == NoneOption ? string.Empty : account.CharacterName ?? string.Empty; // Credentials deliberately NOT logged (the args carry the password). @@ -181,28 +280,30 @@ internal static class LaunchCommand // ── Launch suspended + inject ──────────────────────────────────────── var service = new EngineInjectionService(); int createdPid = 0; - InjectionResult result = service.LaunchSuspendedAndInject( - clientPath, - arguments, - enginePath, - line => + void LaunchLog(string line) + { + Console.WriteLine(line); + logToFile($"[launch] {line}"); + } + void OnCreated(int processId) + { + createdPid = processId; + try { - Console.WriteLine(line); - logToFile($"[launch] {line}"); - }, - processId => + WriteLaunchContext(processId, acct, server.Name ?? string.Empty, + targetCharacter, settings.SkipLoginLogos, account.OnLoginWaitMs); + } + catch (Exception ex) { - createdPid = processId; - try - { - WriteLaunchContext(processId, acct, server.Name ?? string.Empty, - targetCharacter, settings.SkipLoginLogos, account.OnLoginWaitMs); - } - catch (Exception ex) - { - Log($"WARNING: failed to write launch context for PID {processId}: {ex.Message}"); - } - }); + Log($"WARNING: failed to write launch context for PID {processId}: {ex.Message}"); + } + } + if (withDecal) + Log($"Decal : {decalInjectPath}{(decalOnly ? " (Decal only, no RynthCore)" : " (injected before RynthCore)")}"); + InjectionResult result = withDecal + ? service.LaunchSuspendedAndInjectDecalThenEngine( + clientPath, arguments, decalInjectPath!, decalOnly ? null : enginePath, LaunchLog, OnCreated) + : service.LaunchSuspendedAndInject(clientPath, arguments, enginePath, LaunchLog, OnCreated); if (result.Success && result.ProcessId is int pid) { @@ -248,6 +349,27 @@ internal static class LaunchCommand JsonSerializer.Serialize(record)); } + // Same registry probe as RynthCore.App's DecalLocator / ThwargLauncher: Decal records + // its agent directory (where Inject.dll lives) at HKLM\SOFTWARE\Decal\Agent. + private static string? TryGetDecalInjectPath() + { + try + { + using var hklm = Microsoft.Win32.RegistryKey.OpenBaseKey( + Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry32); + using var key = hklm.OpenSubKey(@"SOFTWARE\Decal\Agent"); + string? agentPath = key?.GetValue("AgentPath") as string; + if (string.IsNullOrWhiteSpace(agentPath)) + return null; + string inject = Path.Combine(agentPath, "Inject.dll"); + return File.Exists(inject) ? inject : null; + } + catch + { + return null; + } + } + private static string ComputeConnectionString(ServerDto s) => string.IsNullOrWhiteSpace(s.Host) || s.Port <= 0 ? string.Empty @@ -297,7 +419,8 @@ internal static class LaunchCommand { public string Id { get; set; } = string.Empty; public string AccountName { get; set; } = string.Empty; - public string Password { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; // legacy plain text (pre-encryption files) + public string PasswordProtected { get; set; } = string.Empty; // DPAPI, base64 public string CharacterName { get; set; } = string.Empty; public string ServerId { get; set; } = string.Empty; public int OnLoginWaitMs { get; set; } @@ -316,7 +439,7 @@ internal static class LaunchCommand private enum EmulatorKind { Ace = 0, Gdle = 1 } - private enum InjMode { RynthCore = 0, Decal = 1 } + private enum InjMode { RynthCore = 0, Decal = 1, DecalBridge = 2 } private sealed class LaunchContextDto { diff --git a/src/RynthCore.Injector/Program.cs b/src/RynthCore.Injector/Program.cs index 7203fd7..918f949 100644 --- a/src/RynthCore.Injector/Program.cs +++ b/src/RynthCore.Injector/Program.cs @@ -19,6 +19,7 @@ internal static class Program // harness with no interactive console. bool headless = args.Any(a => string.Equals(a, "--launch", StringComparison.OrdinalIgnoreCase) || + string.Equals(a, "--decal-bridge", StringComparison.OrdinalIgnoreCase) || string.Equals(a, "--no-prompt", StringComparison.OrdinalIgnoreCase)); try @@ -28,6 +29,9 @@ internal static class Program if (args.Any(a => string.Equals(a, "--launch", StringComparison.OrdinalIgnoreCase))) return LaunchCommand.Run(args, LogToFile); + if (args.Any(a => string.Equals(a, "--decal-bridge", StringComparison.OrdinalIgnoreCase))) + return DecalBridgeCommand(args); + return Run(args); } catch (Exception ex) @@ -50,6 +54,67 @@ internal static class Program } } + /// <summary> + /// --decal-bridge register [--dir <folder>] | check | status | unregister + /// | register-machine [--dir <folder>] | unregister-machine + /// register: where a Decal client started now reads Decal's filter list (per-user copy for + /// a non-elevated client, the machine-wide list otherwise; that needs an elevated prompt), + /// then the check. check: the launcher's "Check Decal bridge", read-only. + /// The launcher does the same when an account is set to "Decal + RynthCore". + /// See docs/DECAL_BRIDGE_PLAN.md. + /// </summary> + private static int DecalBridgeCommand(string[] args) + { + int i = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge", StringComparison.OrdinalIgnoreCase)); + string verb = i + 1 < args.Length ? args[i + 1].ToLowerInvariant() : "status"; + int d = Array.FindIndex(args, a => string.Equals(a, "--dir", StringComparison.OrdinalIgnoreCase)); + string dir = d >= 0 && d + 1 < args.Length ? args[d + 1] : RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory; + string? acClient = RynthCore.App.DecalLocator.TryGetDecalAcClientPath(); + string engineJson = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "engine.json"); + bool ok; + string report; + switch (verb) + { + case "register": + { + var outcome = RynthCore.App.DecalBridgeRegistration.RegisterForClients(dir, acClient, engineJson, out report, out var check); + ok = outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered; + if (outcome == RynthCore.App.DecalBridgeRegistration.Outcome.NeedsAdmin) + report += " Run this again from an administrator prompt: RynthCore.Injector --decal-bridge register-machine"; + if (check != null) report += Environment.NewLine + check.ToReport(); + break; + } + case "register-machine": + ok = RynthCore.App.DecalBridgeRegistration.RegisterMachineWide(dir, out report) == RynthCore.App.DecalBridgeRegistration.Outcome.Registered; + break; + case "unregister-machine": + ok = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out report) == RynthCore.App.DecalBridgeRegistration.Outcome.Registered; + break; + case "unregister": + ok = RynthCore.App.DecalBridgeRegistration.Unregister(out report); + if (RynthCore.App.DecalBridgeRegistration.MachineEntryIsOurs()) + report += " A machine-wide entry is left: remove it with --decal-bridge unregister-machine from an administrator prompt."; + break; + case "check": + { + var check = RynthCore.App.RealDecalCheckHost.Check(dir, acClient, engineJson); + ok = !check.Blocking; + report = check.ToReport(); + break; + } + case "status": + ok = true; + report = RynthCore.App.DecalBridgeRegistration.GetStatus(acClient).ToString(); + break; + default: + Console.WriteLine("usage: --decal-bridge register [--dir <folder>] | check | status | unregister | register-machine [--dir <folder>] | unregister-machine"); + return 2; + } + Console.WriteLine(report); + LogToFile($"[decal-bridge] {verb}: {report}"); + return ok ? 0 : 1; + } + private static int Run(string[] args) { var service = new EngineInjectionService(); diff --git a/src/RynthCore.Injector/RynthCore.Injector.csproj b/src/RynthCore.Injector/RynthCore.Injector.csproj index ecf5c14..b70a802 100644 --- a/src/RynthCore.Injector/RynthCore.Injector.csproj +++ b/src/RynthCore.Injector/RynthCore.Injector.csproj @@ -13,6 +13,16 @@ <ItemGroup> <!-- Install-location resolver (installer-chosen RynthCore / RynthSuite folders). --> <Compile Include="..\RynthCore.App\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" /> + <!-- Decal bridge registration (docs/DECAL_BRIDGE_PLAN.md), shared with the launcher. --> + <Compile Include="..\RynthCore.App\DecalLocator.cs" Link="Shared\DecalLocator.cs" /> + <Compile Include="..\RynthCore.App\DecalBridgeRegistration.cs" Link="Shared\DecalBridgeRegistration.cs" /> + <Compile Include="..\RynthCore.App\DecalBridgeCheck.cs" Link="Shared\DecalBridgeCheck.cs" /> + <Compile Include="..\RynthCore.App\RealDecalCheckHost.cs" Link="Shared\RealDecalCheckHost.cs" /> + <!-- "Decal + RynthCore" accounts live in decal-accounts.json beside appsettings.json. --> + <Compile Include="..\RynthCore.App\InjectionMode.cs" Link="Shared\InjectionMode.cs" /> + <Compile Include="..\RynthCore.App\DecalAccountModes.cs" Link="Shared\DecalAccountModes.cs" /> + <!-- Saved account passwords are DPAPI-encrypted (PasswordProtected in appsettings.json). --> + <Compile Include="..\RynthCore.App\AccountPasswordProtection.cs" Link="Shared\AccountPasswordProtection.cs" /> </ItemGroup> </Project> diff --git a/src/RynthCore.Loader/EntryPoint.cs b/src/RynthCore.Loader/EntryPoint.cs index 1db01ed..4b76d41 100644 --- a/src/RynthCore.Loader/EntryPoint.cs +++ b/src/RynthCore.Loader/EntryPoint.cs @@ -382,6 +382,19 @@ public static class EntryPoint } } + // Address-space gate. Every reload leaves the old engine and plugin + // copies mapped (NativeAOT can't unload) and costs hundreds of MB of + // acclient's 4 GB; below this the next reload, or the play after it, + // runs the client out and it dies without a trace (2026-09-28 13:57, + // measured 600-670 MB per reload). Refuse and ask for a restart. + long freeMb = FreeAddressSpaceMb(); + if (freeMb >= 0 && freeMb < MinFreeMbForReload) + { + Log($"ReloadWatcher: reload REFUSED - only {freeMb} MB of address space free (need {MinFreeMbForReload} MB). Restart the client to load the new engine.", "WRN"); + NotifyReloadRefused(freeMb); + continue; + } + // CAS gate. The watcher thread is the only caller, so this should // never trip — but if it ever does (a future code path signals // reload reentrantly, or someone adds a second watcher) we'd @@ -419,6 +432,61 @@ public static class EntryPoint } } + private const long MinFreeMbForReload = 1200; + + /// <summary>Free (unreserved) address space in MB, or -1 if it can't be read.</summary> + private static long FreeAddressSpaceMb() + { + try + { + long free = 0; + long addr = 0x10000; + int size = Marshal.SizeOf<MEMORY_BASIC_INFORMATION>(); + while (addr < 0xFFFF0000L) + { + if (VirtualQuery((IntPtr)addr, out MEMORY_BASIC_INFORMATION mbi, (IntPtr)size) == IntPtr.Zero) + break; + long region = (long)(ulong)mbi.RegionSize; + if (region <= 0) break; + if (mbi.State == MEM_FREE) free += region; + addr = (long)(ulong)mbi.BaseAddress + region; + } + return free / (1024 * 1024); + } + catch { return -1; } + } + + /// <summary>Tells the running engine, which says so in chat (engines without the export just skip it).</summary> + private static void NotifyReloadRefused(long freeMb) + { + IntPtr module = _engineModule; + if (module == IntPtr.Zero) return; + IntPtr fn = GetProcAddress(module, "RynthCoreReloadRefused"); + if (fn == IntPtr.Zero) return; + try { Marshal.GetDelegateForFunctionPointer<ReloadRefusedFn>(fn)((int)freeMb); } + catch (Exception ex) { Log($"ReloadWatcher: RynthCoreReloadRefused threw {ex.GetType().Name}: {ex.Message}"); } + } + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint ReloadRefusedFn(int freeMb); + + private const uint MEM_FREE = 0x10000; + + [StructLayout(LayoutKind.Sequential)] + private struct MEMORY_BASIC_INFORMATION + { + public IntPtr BaseAddress; + public IntPtr AllocationBase; + public uint AllocationProtect; + public IntPtr RegionSize; + public uint State; + public uint Protect; + public uint Type; + } + + [DllImport("kernel32.dll")] + private static extern IntPtr VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, IntPtr dwLength); + private static void Reload() { Log("Reload requested."); diff --git a/src/RynthCore.Loader/RynthCore.Loader.csproj b/src/RynthCore.Loader/RynthCore.Loader.csproj index adc15cf..306faee 100644 --- a/src/RynthCore.Loader/RynthCore.Loader.csproj +++ b/src/RynthCore.Loader/RynthCore.Loader.csproj @@ -31,4 +31,8 @@ <Compile Include="..\RynthCore.App\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" /> </ItemGroup> + <!-- GC segment size (hex, 8 MB): reserves 16 MB of acclient's address space instead of 48. See RynthCore.Engine.csproj. --> + <ItemGroup> + <IlcArg Include="--runtimeopt:GCSegmentSize=800000" /> + </ItemGroup> </Project> diff --git a/src/RynthCore.PluginCore/RynthPluginRuntime.cs b/src/RynthCore.PluginCore/RynthPluginRuntime.cs index 3c631ac..4d84b64 100644 --- a/src/RynthCore.PluginCore/RynthPluginRuntime.cs +++ b/src/RynthCore.PluginCore/RynthPluginRuntime.cs @@ -13,28 +13,51 @@ public unsafe sealed class RynthPluginRuntime<TPlugin> private int _exceptionCount; private const int MaxLoggedExceptions = 20; + // Init results besides the plugin's own Initialize() return value. The + // engine treats any non-zero result as "Init failed" (PluginManager marks + // the plugin failed, logs the code, and never ticks or shuts it down). + public const int InitNullApi = 9; + public const int InitApiTooOld = 10; + public const int InitThrew = 11; + public TPlugin? Plugin => _plugin; public bool IsInitialized => _initialized && _plugin != null; + // Init and Shutdown are called straight from [UnmanagedCallersOnly] + // exports: an exception escaping them takes acclient.exe down (NativeAOT + // fails fast), so both catch everything and log. public int Init(RynthCoreApiNative* api) { if (api == null) - return 9; + return InitNullApi; - var plugin = new TPlugin(); - RynthCoreApiNative hostApi = *api; + TPlugin? plugin = null; + try + { + plugin = new TPlugin(); + RynthCoreApiNative hostApi = *api; - if (hostApi.Version < plugin.MinimumApiVersion) - return 10; + if (hostApi.Version < plugin.MinimumApiVersion) + return InitApiTooOld; - plugin.Attach(hostApi); - int result = plugin.Initialize(); - if (result != 0) - return result; + plugin.Attach(hostApi); + int result = plugin.Initialize(); + if (result != 0) + return result; - _plugin = plugin; - _initialized = true; - return 0; + _plugin = plugin; + _initialized = true; + return 0; + } + catch (Exception ex) + { + // Shutdown isn't called on a plugin whose Init failed, and isn't + // attempted here either: on a half-initialized plugin it could + // do more harm (e.g. save settings it never loaded). + try { plugin?.LogInternal($"[RynthCore] Initialize threw {ex.GetType().Name}: {ex.Message} - plugin not started."); } + catch { } + return InitThrew; + } } public void Shutdown() @@ -46,6 +69,11 @@ public unsafe sealed class RynthPluginRuntime<TPlugin> { _plugin!.Shutdown(); } + catch (Exception ex) + { + try { _plugin?.LogInternal($"[RynthCore] Shutdown threw {ex.GetType().Name}: {ex.Message}"); } + catch { } + } finally { _plugin = null; diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index dd191ea..018a37e 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -125,5 +125,102 @@ public struct RynthCoreApiNative public IntPtr VendorBuyFn; // uint VendorBuy(uint vendorId, VendorTradeEntryNative*, int count) public IntPtr VendorSellFn; // uint VendorSell(uint vendorId, uint* itemIds, int count) public IntPtr GetVendorTradeStatusFn; // int GetVendorTradeStatus(VendorTradeStatusNative*) - public IntPtr GetMergeStackResultFn; // v68: int GetMergeStackResult(uint src, uint tgt, int* amount, int* ageMs) + public IntPtr GetPluginInterfaceFn; // v68: void* GetPluginInterface(const char* plugin, const char* iface, uint version) + public IntPtr GetLiveObjectIdsFn; // v69: int GetLiveObjectIds(uint* buffer, int capacity) -> total count + // v70: action outcomes + wield-to-slot (and the engine raises OnEnchantmentAdded/Removed) + public IntPtr GetLastUseDoneFn; // int GetLastUseDone(int* seq, uint* error) + public IntPtr GetLastWeenieErrorFn; // int GetLastWeenieError(int* seq, uint* error, uint* eventType, uint* objectId) + public IntPtr WieldItemFn; // int WieldItem(uint objectId, uint equipMask) + // v71: script windows (display list in, events out; RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §4) + public IntPtr UiSubmitFn; // int UiSubmit(const uint8_t* data, int length) + public IntPtr UiPollEventsFn; // int UiPollEvents(uint8_t* buffer, int capacity, int* remaining) + public IntPtr UiGetInfoFn; // int UiGetInfo(UiInfoNative* info) + // v72: player-to-player trade (state polled; actions queued for AC's main thread) + public IntPtr GetTradeStateFn; // int GetTradeState(TradeStateNative* state) + public IntPtr GetTradeItemsFn; // int GetTradeItems(int side, uint* buffer, int capacity) -> total + public IntPtr TradeOpenFn; // int TradeOpen(uint targetId) + public IntPtr TradeAddFn; // int TradeAdd(uint itemId, uint slot) + public IntPtr TradeAcceptFn; // int TradeAccept(void) + public IntPtr TradeDeclineFn; // int TradeDecline(void) + public IntPtr TradeResetFn; // int TradeReset(void) + public IntPtr TradeCloseFn; // int TradeClose(void) + // v73: every property type off the main thread + public IntPtr GetObjectInstanceIdPropertyFn; // int GetObjectInstanceIdProperty(uint objectId, uint stype, uint* value) + // v74: VTank's macro under the Decal bridge (one bot per client) + public IntPtr GetVTankStateFn; // int GetVTankState(int* sequence) -> flags (bit0 watching, bit1 running) + // v75: the character's titles and which server this is + public IntPtr GetCharacterTitlesFn; // int GetCharacterTitles(uint* ids, int maxCount, uint* currentTitle) -> count, -1 unknown + public IntPtr GetServerInfoFn; // int GetServerInfo(byte* worldName, int capacity) -> flags (bit0 Aelrynth, bit1 staging, bit2 world name known) + // v76: close an external container (corpse, chest) like the client's window close + public IntPtr CloseContainerFn; // int CloseContainer(uint containerId) -> 1 sent or queued + // v77: outcome of the latest merge-stack request (cdecl thunk) + public IntPtr GetMergeStackResultFn; // int GetMergeStackResult(uint src, uint tgt, int* amount, int* ageMs) +} + +/// <summary> +/// v72 GetTradeState result (Pack 4, 96 bytes; later versions only append). +/// Mirrors RynthCore.Engine/Plugins/PluginContract.cs TradeStateNative exactly. +/// </summary> +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public unsafe struct TradeStateNative +{ + /// <summary>In: sizeof(TradeStateNative). Out: bytes the engine wrote.</summary> + public uint Size; + /// <summary>bit0 open, bit1 you accepted, bit2 partner accepted, bit3 engine sees trade + /// events, bit4 all trade actions bound.</summary> + public uint Flags; + /// <summary>+1 for every trade that opens.</summary> + public uint Generation; + /// <summary>+1 for every trade event.</summary> + public uint Sequence; + public uint PartnerId; + public uint InitiatorId; + public int SelfItemCount; + public int PartnerItemCount; + public uint LastEventType; + public uint FailureCount; + public uint LastFailureItemId; + public uint LastFailureReason; + public uint LastCloseReason; + public uint LastAcceptedBy; + public uint LastDeclinedBy; + public uint LastResetBy; + public uint CompletedCount; + public uint PartnerAcceptCount; + public fixed uint Reserved[6]; +} + +/// <summary> +/// v71 UiGetInfo result (Pack 4, 480 bytes in format 1; later versions only append). +/// Mirrors RynthCore.Engine/Plugins/PluginContract.cs UiInfoNative exactly. +/// </summary> +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public unsafe struct UiInfoNative +{ + /// <summary>In: sizeof(UiInfoNative). Out: bytes the engine wrote.</summary> + public uint Size; + /// <summary>bit0 ImGui available, bit1 in world, bit2 pop-outs available.</summary> + public uint Flags; + /// <summary>Highest display-list format the engine replays.</summary> + public ushort MaxFormatVersion; + /// <summary>The ops replayed within MaxFormatVersion: 2 = + Image, ImageButton, InputInt, InputFloat, + /// DragInt, DragFloat (2026-09-30). 0 on older engines (the field was reserved) = Phase 1 ops only.</summary> + public ushort OpLevel; + public uint MaxOpsPerWindow; + public uint MaxBytesPerWindow; + public uint MaxWindowsPerOwner; + public uint MaxBytesPerSubmit; + public float DisplayWidth; + public float DisplayHeight; + public float UiScale; + public float TextLineHeight; + public float FrameHeight; + public float ItemSpacingX; + public float ItemSpacingY; + public float FramePaddingX; + public float FramePaddingY; + /// <summary>Default font advance of ' '..'~' (95), pixels at UiScale.</summary> + public fixed float AsciiAdvance[95]; + public uint FrameCounter; + public fixed uint Reserved[8]; } diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index c134889..3b24926 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -6,7 +6,7 @@ namespace RynthCore.PluginSdk; public readonly unsafe struct RynthCoreHost { - public const uint CurrentApiVersion = 69; // v69: GetMergeStackResult usable (cdecl thunk) + public const uint CurrentApiVersion = 77; // v77: GetMergeStackResult /// <summary> /// The oldest engine API a plugin built on this SDK loads on by default @@ -128,10 +128,40 @@ public readonly unsafe struct RynthCoreHost public bool HasGetPluginSnapshotJson => _api.Version >= 64 && _api.GetPluginSnapshotJsonFn != IntPtr.Zero; public bool HasSendPluginCommand => _api.Version >= 64 && _api.SendPluginCommandFn != IntPtr.Zero; public bool HasGetObjectDataIdProperty => _api.Version >= 65 && _api.GetObjectDataIdPropertyFn != IntPtr.Zero; + /// <summary>v73: <see cref="TryGetObjectInstanceIdProperty"/> (any PropertyInstanceId).</summary> + public bool HasGetObjectInstanceIdProperty => _api.Version >= 73 && _api.GetObjectInstanceIdPropertyFn != IntPtr.Zero; + /// <summary>v74: <see cref="TryGetVTankState"/> (VTank's macro under the Decal bridge).</summary> + public bool HasGetVTankState => _api.Version >= 74 && _api.GetVTankStateFn != IntPtr.Zero; + /// <summary>v75: <see cref="TryGetCharacterTitles"/> (the titles the player holds).</summary> + public bool HasGetCharacterTitles => _api.Version >= 75 && _api.GetCharacterTitlesFn != IntPtr.Zero; + /// <summary>v75: <see cref="TryGetServerInfo"/> (which server this is).</summary> + public bool HasGetServerInfo => _api.Version >= 75 && _api.GetServerInfoFn != IntPtr.Zero; + /// <summary>v76: <see cref="CloseContainer"/> (close a corpse or chest like the client's window close).</summary> + public bool HasCloseContainer => _api.Version >= 76 && _api.CloseContainerFn != IntPtr.Zero; public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero; // Version-checked first: on an older engine the field lies past the end of its API table. - // v68 engines export a stdcall thunk that corrupts the caller's stack, so require v69. - public bool HasGetMergeStackResult => _api.Version >= 69 && _api.GetMergeStackResultFn != IntPtr.Zero; + public bool HasGetMergeStackResult => _api.Version >= 77 && _api.GetMergeStackResultFn != IntPtr.Zero; + public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero; + public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero; + public bool HasGetLastUseDone => _api.Version >= 70 && _api.GetLastUseDoneFn != IntPtr.Zero; + public bool HasGetLastWeenieError => _api.Version >= 70 && _api.GetLastWeenieErrorFn != IntPtr.Zero; + public bool HasWieldItem => _api.Version >= 70 && _api.WieldItemFn != IntPtr.Zero; + /// <summary> + /// v70: the engine raises OnEnchantmentAdded / OnEnchantmentRemoved for the player's + /// enchantment changes (older engines never called them). Added carries the spell id and + /// the duration in seconds (-1 or 0 for ones without a timer); Removed carries the spell id. + /// Both reach the plugin after AC applied the change, so a registry read then sees it. + /// </summary> + public bool HasEnchantmentEvents => _api.Version >= 70; + /// <summary>v71: script windows (UiSubmit / UiPollEvents / UiGetInfo).</summary> + public bool HasUi => _api.Version >= 71 && _api.UiSubmitFn != IntPtr.Zero + && _api.UiPollEventsFn != IntPtr.Zero && _api.UiGetInfoFn != IntPtr.Zero; + /// <summary>v72: player-to-player trade (TryGetTradeState / GetTradeItems / Trade* actions).</summary> + public bool HasTrade => _api.Version >= 72 && _api.GetTradeStateFn != IntPtr.Zero + && _api.GetTradeItemsFn != IntPtr.Zero && _api.TradeOpenFn != IntPtr.Zero + && _api.TradeAddFn != IntPtr.Zero && _api.TradeAcceptFn != IntPtr.Zero + && _api.TradeDeclineFn != IntPtr.Zero && _api.TradeResetFn != IntPtr.Zero + && _api.TradeCloseFn != IntPtr.Zero; // ─── Methods ──────────────────────────────────────────────────────────── @@ -451,16 +481,27 @@ public readonly unsafe struct RynthCoreHost } } + /// <summary> + /// Raised (static: per plugin DLL) after this plugin issues <see cref="UseObject"/> (target 0) or + /// <see cref="UseObjectOn"/>: (source, target). Lets a plugin know which items' + /// properties (uses left, stack size ...) may have just changed. + /// </summary> + public static event Action<uint, uint>? ObjectUsed; + public bool UseObject(uint objectId) { - return _api.UseObjectFn != IntPtr.Zero && - ((delegate* unmanaged[Cdecl]<uint, int>)_api.UseObjectFn)(objectId) != 0; + bool ok = _api.UseObjectFn != IntPtr.Zero && + ((delegate* unmanaged[Cdecl]<uint, int>)_api.UseObjectFn)(objectId) != 0; + ObjectUsed?.Invoke(objectId, 0); + return ok; } public bool UseObjectOn(uint sourceObjectId, uint targetObjectId) { - return _api.UseObjectOnFn != IntPtr.Zero && - ((delegate* unmanaged[Cdecl]<uint, uint, int>)_api.UseObjectOnFn)(sourceObjectId, targetObjectId) != 0; + bool ok = _api.UseObjectOnFn != IntPtr.Zero && + ((delegate* unmanaged[Cdecl]<uint, uint, int>)_api.UseObjectOnFn)(sourceObjectId, targetObjectId) != 0; + ObjectUsed?.Invoke(sourceObjectId, targetObjectId); + return ok; } public bool UseEquippedItem(uint sourceObjectId, uint targetObjectId) @@ -847,10 +888,11 @@ public readonly unsafe struct RynthCoreHost } /// <summary> - /// Reads a STypeDID property that lives in the object's PublicWeenieDesc — Icon=8, and on - /// engines 2026.10.4.19+ also IconOverlay=50 / IconUnderlay=52 (0x06xxxxxx; older engines - /// return false for those). Works on UNequipped/never-appraised pack items - /// (PWD is network-populated; no qualities pointer or appraisal required). Returns false + /// Reads a STypeDID property that lives in the object's PublicWeenieDesc: Icon=8 (→ _iconID, + /// e.g. 0x06xxxxxx), and on engines from 2026-09-30 IconOverlay=50 / IconUnderlay=52 (0 = none). Works on UNequipped/never-appraised pack items + /// (PWD is network-populated; no qualities pointer or appraisal required). Engines from + /// API v73 answer every data id the client knows (an identified object's data id table, + /// the player's PlayerDescription, UpdatePropertyDataID, the PWD Spell 28). Returns false /// when the engine predates API v65 or the read fails. /// </summary> public bool TryGetObjectDataIdProperty(uint objectId, uint stype, out uint value) @@ -865,6 +907,112 @@ public readonly unsafe struct RynthCoreHost } } + /// <summary> + /// v73: reads a PropertyInstanceId (STypeIID) - another object's id, e.g. Container 2, + /// Wielder 3, Monarch 26, HouseOwner 32, PetOwner 44, or the player's Allegiance/Patron. + /// Any thread. False when the engine predates v73, or the client doesn't know it (0). + /// On older engines Container and Wielder are still available through + /// <see cref="TryGetObjectOwnershipInfo"/>. + /// </summary> + public bool TryGetObjectInstanceIdProperty(uint objectId, uint stype, out uint value) + { + value = 0; + if (!HasGetObjectInstanceIdProperty) + return false; + + fixed (uint* valuePtr = &value) + { + return ((delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)_api.GetObjectInstanceIdPropertyFn)(objectId, stype, valuePtr) != 0; + } + } + + /// <summary> + /// v74: VTank's macro in this client, as the engine sees it under the Decal bridge + /// (VTank's documented /vt start and /vt stop through Decal's chat parser; VTank's own + /// Run Macro button is not seen). <paramref name="watching"/> is false without Decal, or + /// when Decal runs without the bridge: then <paramref name="running"/> is always false. + /// <paramref name="sequence"/> changes on every change. False when the engine predates v74. + /// Any thread. + /// </summary> + public bool TryGetVTankState(out bool watching, out bool running, out int sequence) + { + watching = false; + running = false; + sequence = 0; + if (!HasGetVTankState) + return false; + + int seq = 0; + int flags = ((delegate* unmanaged[Cdecl]<int*, int>)_api.GetVTankStateFn)(&seq); + watching = (flags & 1) != 0; + running = watching && (flags & 2) != 0; + sequence = seq; + return true; + } + + /// <summary> + /// v75: the title ids the player holds and the one on display, from the server's title + /// events (sent at login and for each new title). False when the engine predates v75 or + /// hasn't received the list for this character (e.g. a plugin build on an engine that was + /// updated mid-session: it comes at the next login). Any thread. + /// </summary> + public bool TryGetCharacterTitles(out uint[] titleIds, out uint currentTitle) + { + titleIds = Array.Empty<uint>(); + currentTitle = 0; + if (!HasGetCharacterTitles) + return false; + var fn = (delegate* unmanaged[Cdecl]<uint*, int, uint*, int>)_api.GetCharacterTitlesFn; + uint cur = 0; + int count = fn(null, 0, &cur); + if (count < 0) + return false; + for (int attempt = 0; attempt < 3; attempt++) + { + uint[] buffer = new uint[Math.Max(count, 1)]; + int total; + fixed (uint* p = buffer) total = fn(p, buffer.Length, &cur); + if (total < 0) + return false; + if (total <= buffer.Length) + { + Array.Resize(ref buffer, total); + titleIds = buffer; + currentTitle = cur; + return true; + } + count = total; + } + return false; + } + + /// <summary> + /// v75: which server this client is on, as the engine decides it: <paramref name="isAelrynth"/> + /// (the connect host, the world name the server announced, or the Bank mod's properties), + /// <paramref name="isStaging"/> (Aelrynth's staging world), and the world name the server + /// announced at login ("" until then; never the launcher's profile name). False when the + /// engine predates v75. Any thread. + /// </summary> + public bool TryGetServerInfo(out bool isAelrynth, out bool isStaging, out string worldName) + { + isAelrynth = false; + isStaging = false; + worldName = string.Empty; + if (!HasGetServerInfo) + return false; + byte* buf = stackalloc byte[257]; + int flags = ((delegate* unmanaged[Cdecl]<byte*, int, int>)_api.GetServerInfoFn)(buf, 257); + isAelrynth = (flags & 1) != 0; + isStaging = (flags & 2) != 0; + if ((flags & 4) != 0) + { + int n = 0; + while (n < 256 && buf[n] != 0) n++; + worldName = System.Text.Encoding.UTF8.GetString(buf, n); + } + return true; + } + public bool TryGetObjectBoolProperty(uint objectId, uint stype, out bool value) { value = false; @@ -1448,6 +1596,252 @@ public readonly unsafe struct RynthCoreHost /// The target owns the returned buffer (valid until its next call on that export), so this copies it. /// Returns null pre-v66 or on failure. Requires API v66+ (check <see cref="HasGetPluginExportJson"/>). /// </summary> + /// <summary> + /// A named plugin's typed interface table (v68): <paramref name="iface"/> at + /// <paramref name="version"/>, e.g. ("RynthAi", "RynthAi.Script", 1). The pointer belongs to + /// the target plugin; call its functions only from the plugin pump thread (OnTick and the + /// events it drains). IntPtr.Zero when the plugin isn't loaded, isn't initialised yet, or + /// doesn't offer that interface: resolve lazily and again after each Init. + /// </summary> + public IntPtr GetPluginInterface(string pluginName, string iface, uint version) + { + if (_api.Version < 68 || _api.GetPluginInterfaceFn == IntPtr.Zero || string.IsNullOrEmpty(pluginName) || string.IsNullOrEmpty(iface)) + return IntPtr.Zero; + IntPtr namePtr = Marshal.StringToHGlobalAnsi(pluginName); + IntPtr ifacePtr = Marshal.StringToHGlobalAnsi(iface); + try + { + return ((delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint, IntPtr>)_api.GetPluginInterfaceFn)(namePtr, ifacePtr, version); + } + finally + { + Marshal.FreeHGlobal(namePtr); + Marshal.FreeHGlobal(ifacePtr); + } + } + + /// <summary> + /// v69: every object the client currently knows (landscape, inventory, everything in its + /// object table), from the engine's snapshot (refreshed on the game thread a few times a + /// second). Empty on older engines or before the first snapshot. + /// </summary> + public uint[] GetLiveObjectIds() + { + if (_api.Version < 69 || _api.GetLiveObjectIdsFn == IntPtr.Zero) + return Array.Empty<uint>(); + var fn = (delegate* unmanaged[Cdecl]<uint*, int, int>)_api.GetLiveObjectIdsFn; + int capacity = 1024; + for (int attempt = 0; attempt < 3; attempt++) + { + uint[] buffer = new uint[capacity]; + int total; + fixed (uint* p = buffer) total = fn(p, capacity); + if (total <= 0) return Array.Empty<uint>(); + if (total <= capacity) + { + if (total == capacity) return buffer; + Array.Resize(ref buffer, total); + return buffer; + } + capacity = total + 256; + } + return Array.Empty<uint>(); + } + + /// <summary> + /// v70: the most recent server UseDone (GameEvent 0x01C7): <paramref name="seq"/> is its + /// number in the same count <see cref="GetUseDoneSeq"/> returns, <paramref name="error"/> its + /// WeenieError code (0 = the action completed, e.g. 0x1D YoureTooBusy). Both come from one + /// snapshot. False on older engines or when the engine can't watch UseDone; seq 0 = none yet. + /// </summary> + public bool TryGetLastUseDone(out int seq, out uint error) + { + seq = 0; + error = 0; + if (_api.Version < 70 || _api.GetLastUseDoneFn == IntPtr.Zero) + return false; + int s; + uint e; + int ok = ((delegate* unmanaged[Cdecl]<int*, uint*, int>)_api.GetLastUseDoneFn)(&s, &e); + seq = s; + error = e; + return ok != 0; + } + + /// <summary> + /// v70: the most recent refusal the server sent: <paramref name="eventType"/> 0x028A + /// WeenieError (e.g. 0x402 YourSpellFizzled; a fizzled cast still ends with UseDone(0)), + /// 0x028B WeenieErrorWithString, or 0x00A0 InventoryServerSaveFailed (a refused wield or + /// move; <paramref name="objectId"/> is the item, else 0). <paramref name="seq"/> counts them + /// (0 = none yet): record it before an action and compare. False on older engines. + /// </summary> + public bool TryGetLastWeenieError(out int seq, out uint error, out uint eventType, out uint objectId) + { + seq = 0; + error = eventType = objectId = 0; + if (_api.Version < 70 || _api.GetLastWeenieErrorFn == IntPtr.Zero) + return false; + int s; + uint e, t, o; + int ok = ((delegate* unmanaged[Cdecl]<int*, uint*, uint*, uint*, int>)_api.GetLastWeenieErrorFn)(&s, &e, &t, &o); + seq = s; + error = e; + eventType = t; + objectId = o; + return ok != 0; + } + + /// <summary> + /// v70: wield an item into the given EquipMask slot(s), as dragging it onto that paperdoll + /// slot does (the 0x001A GetAndWieldItem game action). E.g. 0x00100000 MeleeWeapon, + /// 0x00200000 Shield, 0x00400000 MissileWeapon, 0x01000000 Held, 0x02000000 TwoHanded; + /// rings and bracelets have a left and a right bit. The server checks the slot against the + /// item and answers with the wield or InventoryServerSaveFailed (see + /// <see cref="TryGetLastWeenieError"/>). Check <see cref="HasWieldItem"/>. + /// </summary> + public bool WieldItem(uint objectId, uint equipMask) + { + return _api.Version >= 70 && _api.WieldItemFn != IntPtr.Zero && + ((delegate* unmanaged[Cdecl]<uint, uint, int>)_api.WieldItemFn)(objectId, equipMask) != 0; + } + + /// <summary> + /// v76: close an external container (a corpse, a chest) the way the client does when its + /// window is closed: the 0x0195 NoLongerViewingContents game action. It is not an inventory + /// request, so it adds nothing to the busy count and doesn't hold the client's one pending + /// item request. The server closes the container (if this player is viewing it) and answers + /// with CloseGroundContainer, so <c>OnStopViewingObjectContents</c> follows. Queued on AC's + /// main thread ahead of any action queued after it (a following UseObject goes out after + /// it, in the same frame). False when the engine predates v76. Check <see cref="HasCloseContainer"/>. + /// </summary> + public bool CloseContainer(uint containerId) + { + return HasCloseContainer && + ((delegate* unmanaged[Cdecl]<uint, int>)_api.CloseContainerFn)(containerId) != 0; + } + + /// <summary> + /// v71: submits this plugin's complete set of script windows (display-list format 1, + /// RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2). Call only from the plugin's own tick or + /// event (else -2). The engine copies what it needs before returning. Returns 0, or -1 + /// malformed, -2 not in a dispatch, -3 over a limit (nothing applied), -4 unsupported + /// format; -100 on an engine without <see cref="HasUi"/>. + /// </summary> + public int UiSubmit(ReadOnlySpan<byte> data) + { + if (!HasUi) return -100; + fixed (byte* p = data) + return ((delegate* unmanaged[Cdecl]<byte*, int, int>)_api.UiSubmitFn)(p, data.Length); + } + + /// <summary> + /// v71: copies whole queued window events (format 1, §4.3) into <paramref name="buffer"/> and + /// returns the bytes written; <paramref name="remaining"/> = events still queued. Same thread + /// rule as <see cref="UiSubmit"/>. 0 on an engine without <see cref="HasUi"/>. + /// </summary> + public int UiPollEvents(Span<byte> buffer, out int remaining) + { + remaining = 0; + if (!HasUi) return 0; + int rem = 0; + int written; + fixed (byte* p = buffer) + written = ((delegate* unmanaged[Cdecl]<byte*, int, int*, int>)_api.UiPollEventsFn)(p, buffer.Length, &rem); + remaining = rem; + return written < 0 ? 0 : written; + } + + /// <summary> + /// v71: limits and layout facts for script windows (text line height, ASCII advances for + /// CalcTextSize, display size). False on an engine without <see cref="HasUi"/> or with no + /// ImGui (e.g. Decal coexistence mode). + /// </summary> + public bool TryGetUiInfo(out UiInfoNative info) + { + info = default; + if (!HasUi) return false; + UiInfoNative local = default; + local.Size = (uint)sizeof(UiInfoNative); + int n = ((delegate* unmanaged[Cdecl]<UiInfoNative*, int>)_api.UiGetInfoFn)(&local); + info = local; + return n > 0; + } + + // ─── Player-to-player trade (API v72) ────────────────────────────────── + // The engine tracks the trade window from the server's trade events (on AC's main + // thread) and serves copies; poll TryGetTradeState from your tick and compare + // Generation / Sequence / the counters with your last read to see what changed. + // The actions send the retail client's own trade game actions, queued for AC's + // main thread; the server's answer shows up in the next state reads. + + /// <summary> + /// v72: the trade window right now. False on an engine without <see cref="HasTrade"/>. + /// A closed trade still returns true (IsOpen false) with the counters. + /// </summary> + public bool TryGetTradeState(out TradeState state) + { + state = default; + if (!HasTrade) return false; + TradeStateNative raw = default; + raw.Size = (uint)sizeof(TradeStateNative); + int n = ((delegate* unmanaged[Cdecl]<TradeStateNative*, int>)_api.GetTradeStateFn)(&raw); + if (n < 8) return false; + state = new TradeState(raw); + return true; + } + + /// <summary> + /// v72: the item ids on one side of the trade window (<see cref="TradeSide.You"/> or + /// <see cref="TradeSide.Partner"/>); empty when none, or on an older engine. + /// </summary> + public uint[] GetTradeItems(TradeSide side) + { + if (!HasTrade) return Array.Empty<uint>(); + var fn = (delegate* unmanaged[Cdecl]<int, uint*, int, int>)_api.GetTradeItemsFn; + int capacity = 32; + for (int attempt = 0; attempt < 4; attempt++) + { + uint[] buffer = new uint[capacity]; + int total; + fixed (uint* p = buffer) total = fn((int)side, p, capacity); + if (total <= 0) return Array.Empty<uint>(); + if (total <= capacity) + { + if (total < capacity) Array.Resize(ref buffer, total); + return buffer; + } + capacity = total + 16; + } + return Array.Empty<uint>(); + } + + /// <summary>v72: ask a player to trade (the server walks you into range first).</summary> + public bool TradeOpen(uint targetId) + => HasTrade && ((delegate* unmanaged[Cdecl]<uint, int>)_api.TradeOpenFn)(targetId) != 0; + + /// <summary> + /// v72: put one of your items in the open trade window (slot 0 = next free). The server + /// answers with the item on your side, or a TradeFailure (FailureCount / LastFailure*). + /// </summary> + public bool TradeAdd(uint itemId, uint slot = 0) + => HasTrade && ((delegate* unmanaged[Cdecl]<uint, uint, int>)_api.TradeAddFn)(itemId, slot) != 0; + + /// <summary>v72: accept the trade as it stands (the trade window's Accept button).</summary> + public bool TradeAccept() + => HasTrade && ((delegate* unmanaged[Cdecl]<int>)_api.TradeAcceptFn)() != 0; + + /// <summary>v72: withdraw your acceptance (the Decline button).</summary> + public bool TradeDecline() + => HasTrade && ((delegate* unmanaged[Cdecl]<int>)_api.TradeDeclineFn)() != 0; + + /// <summary>v72: empty both sides of the trade window.</summary> + public bool TradeReset() + => HasTrade && ((delegate* unmanaged[Cdecl]<int>)_api.TradeResetFn)() != 0; + + /// <summary>v72: end the trade.</summary> + public bool TradeClose() + => HasTrade && ((delegate* unmanaged[Cdecl]<int>)_api.TradeCloseFn)() != 0; + public string? GetPluginExportJson(string pluginName, string exportName) { if (_api.GetPluginExportJsonFn == IntPtr.Zero || string.IsNullOrEmpty(pluginName) || string.IsNullOrEmpty(exportName)) diff --git a/src/RynthCore.PluginSdk/TradeTypes.cs b/src/RynthCore.PluginSdk/TradeTypes.cs new file mode 100644 index 0000000..08a1111 --- /dev/null +++ b/src/RynthCore.PluginSdk/TradeTypes.cs @@ -0,0 +1,84 @@ +using System; + +namespace RynthCore.PluginSdk; + +// ─── Player-to-player trade (engine API v72) ──────────────────────────────── +// TradeStateNative (RynthCoreApiNative.cs) is the ABI struct; plugins use the +// TradeState view below, from RynthCoreHost.TryGetTradeState. + +/// <summary>Which side of the trade window (the AC trade side numbers).</summary> +public enum TradeSide +{ + /// <summary>Your items.</summary> + You = 1, + /// <summary>The other player's items.</summary> + Partner = 2, +} + +/// <summary> +/// A copy of the engine's trade state (API v72). Compare <see cref="Generation"/>, +/// <see cref="Sequence"/> and the counters with an earlier read to see what changed: +/// a new trade bumps Generation; every trade event bumps Sequence. +/// </summary> +public readonly struct TradeState +{ + public TradeState(TradeStateNative raw) + { + Flags = raw.Flags; + Generation = raw.Generation; + Sequence = raw.Sequence; + PartnerId = raw.PartnerId; + InitiatorId = raw.InitiatorId; + YourItemCount = raw.SelfItemCount; + PartnerItemCount = raw.PartnerItemCount; + LastEventType = raw.LastEventType; + FailureCount = raw.FailureCount; + LastFailureItemId = raw.LastFailureItemId; + LastFailureReason = raw.LastFailureReason; + LastCloseReason = raw.LastCloseReason; + LastAcceptedBy = raw.LastAcceptedBy; + LastDeclinedBy = raw.LastDeclinedBy; + LastResetBy = raw.LastResetBy; + CompletedCount = raw.CompletedCount; + PartnerAcceptCount = raw.PartnerAcceptCount; + } + + public uint Flags { get; } + /// <summary>A trade window is open.</summary> + public bool IsOpen => (Flags & 1u) != 0; + /// <summary>You have accepted the trade as it stands.</summary> + public bool YouAccepted => (Flags & 2u) != 0; + /// <summary>The other player has accepted the trade as it stands.</summary> + public bool PartnerAccepted => (Flags & 4u) != 0; + /// <summary>The engine sees the server's trade events (false: the state never changes).</summary> + public bool Watching => (Flags & 8u) != 0; + /// <summary>All trade actions (open, add, accept, decline, reset, close) are bound on this client.</summary> + public bool ActionsAvailable => (Flags & 16u) != 0; + + /// <summary>+1 for every trade that opens.</summary> + public uint Generation { get; } + /// <summary>+1 for every trade event.</summary> + public uint Sequence { get; } + /// <summary>The other player; 0 when no trade is open.</summary> + public uint PartnerId { get; } + /// <summary>The player who opened the trade.</summary> + public uint InitiatorId { get; } + public int YourItemCount { get; } + public int PartnerItemCount { get; } + /// <summary>The last trade GameEvent (0x01FD RegisterTrade ... 0x0208 ClearTradeAcceptance).</summary> + public uint LastEventType { get; } + /// <summary>TradeFailure events so far (an item the server refused to put in the window).</summary> + public uint FailureCount { get; } + public uint LastFailureItemId { get; } + /// <summary>WeenieError of the last TradeFailure (e.g. 0x0426 AttunedItem).</summary> + public uint LastFailureReason { get; } + /// <summary>Why the last trade closed: 1 normal, 2 entered combat, 0x51 cancelled.</summary> + public uint LastCloseReason { get; } + public uint LastAcceptedBy { get; } + public uint LastDeclinedBy { get; } + public uint LastResetBy { get; } + /// <summary>Trades completed so far ("Trade Complete!").</summary> + public uint CompletedCount { get; } + /// <summary>Times the other player has accepted so far.</summary> + public uint PartnerAcceptCount { get; } +} diff --git a/src/RynthCore.Shim/RynthCore.Shim.csproj b/src/RynthCore.Shim/RynthCore.Shim.csproj new file mode 100644 index 0000000..fca322a --- /dev/null +++ b/src/RynthCore.Shim/RynthCore.Shim.csproj @@ -0,0 +1,22 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + RynthCore.Shim: the only RynthCore code in CoreCLR's default AssemblyLoadContext. + Loaded once by the native loader (native/Loader/Clr.c) and never reloaded, so keep it + small and free of any reference to engine types. See docs/UNLOADABLE_ENGINE_PLAN.md. + --> + <PropertyGroup> + <TargetFramework>net10.0-windows</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <Platforms>x86</Platforms> + <OutputType>Library</OutputType> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <Nullable>enable</Nullable> + <ImplicitUsings>disable</ImplicitUsings> + <RootNamespace>RynthCore.Shim</RootNamespace> + <AssemblyName>RynthCore.Shim</AssemblyName> + <InvariantGlobalization>true</InvariantGlobalization> + <GenerateDocumentationFile>false</GenerateDocumentationFile> + </PropertyGroup> + +</Project> diff --git a/src/RynthCore.Shim/ShimHost.cs b/src/RynthCore.Shim/ShimHost.cs new file mode 100644 index 0000000..e2ac0f5 --- /dev/null +++ b/src/RynthCore.Shim/ShimHost.cs @@ -0,0 +1,264 @@ +// ============================================================================ +// RynthCore.Shim - ShimHost.cs +// +// Called by the native loader (native/Loader/Clr.c) once CoreCLR is up. Loads each +// engine generation into its own collectible AssemblyLoadContext, hands the loader +// the engine's [UnmanagedCallersOnly(EntryPoint = ...)] methods in place of DLL +// exports, and on reload unloads the context and waits until it is really gone. +// +// Rules (docs/UNLOADABLE_ENGINE_PLAN.md): nothing here may hold an engine type, +// delegate, MethodInfo or object across a generation; only raw function pointers, +// which are dropped before the unload. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using System.Runtime; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Loader; +using System.Text; +using System.Threading; + +namespace RynthCore.Shim; + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct LoaderApi +{ + public int Size; + public delegate* unmanaged[Stdcall]<byte*, byte*, void> Log; + public delegate* unmanaged[Stdcall]<int*, int> FreeMb; + public byte* LoaderDir; + public delegate* unmanaged[Stdcall]<int> HookCount; +} + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct ShimApi +{ + public int Size; + public delegate* unmanaged[Stdcall]<int, byte*, int> LoadEngine; + public delegate* unmanaged[Stdcall]<int> UnloadEngine; + public delegate* unmanaged[Stdcall]<byte*, nint> EngineExport; +} + +public static unsafe class ShimHost +{ + private const string EngineEntryType = "RynthCore.Engine.EntryPoint"; + private const int UnloadWaitMs = 5000; + + private static LoaderApi* s_api; + private static string s_loaderDir = ""; + private static string s_runtimeDir = ""; + + private static EngineLoadContext? s_alc; + private static readonly Dictionary<string, nint> s_exports = new(StringComparer.Ordinal); + private static int s_generation; + private static int s_leakedGenerations; + // Generations that outlived their unload wait (e.g. AC's main thread was inside one of + // their hook detours behind a modal dialog). They are still unloading and usually go + // later; checked, and reported, at every reload. + private static readonly List<(int Generation, WeakReference Context)> s_pending = new(); + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + public static int Init(LoaderApi* api, ShimApi* shim) + { + try + { + s_api = api; + s_loaderDir = Marshal.PtrToStringUTF8((nint)api->LoaderDir) ?? ""; + s_runtimeDir = Path.GetDirectoryName(typeof(object).Assembly.Location) ?? ""; + shim->LoadEngine = &LoadEngine; + shim->UnloadEngine = &UnloadEngine; + shim->EngineExport = &EngineExport; + Log("INF", $"Shim up: CoreCLR {Environment.Version}, {RuntimeInformation.ProcessArchitecture}, " + + $"runtime {s_runtimeDir}, GC {(GCSettings.IsServerGC ? "server" : "workstation")}."); + return 0; + } + catch (Exception ex) + { + Log("ERR", "Shim init failed: " + ex); + return 1; + } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int LoadEngine(int generation, byte* stagedPathUtf8) + { + try + { + string path = Marshal.PtrToStringUTF8((nint)stagedPathUtf8) ?? ""; + var sw = Stopwatch.StartNew(); + LoadGeneration(generation, path); + Log("INF", $"Engine gen {generation} loaded into a collectible context in {sw.ElapsedMilliseconds} ms " + + $"({s_exports.Count} exports: {string.Join(", ", s_exports.Keys)})."); + return 0; + } + catch (Exception ex) + { + Log("ERR", $"Loading engine gen {generation} failed: {ex}"); + return 1; + } + } + + // Kept out of LoadEngine so no local of the unmanaged entry frame holds the context. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void LoadGeneration(int generation, string stagedPath) + { + var alc = new EngineLoadContext($"RynthCore.Engine gen{generation}", s_loaderDir, s_runtimeDir); + Assembly engine = alc.LoadFromAssemblyPath(stagedPath); + Type entry = engine.GetType(EngineEntryType, throwOnError: true)!; + s_exports.Clear(); + foreach (MethodInfo m in entry.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)) + { + var uco = m.GetCustomAttribute<UnmanagedCallersOnlyAttribute>(); + if (uco?.EntryPoint is { Length: > 0 } name) + s_exports[name] = m.MethodHandle.GetFunctionPointer(); + } + s_alc = alc; + s_generation = generation; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static nint EngineExport(byte* nameUtf8) + { + string name = Marshal.PtrToStringUTF8((nint)nameUtf8) ?? ""; + return s_exports.TryGetValue(name, out nint fn) ? fn : 0; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int UnloadEngine() + { + try + { + s_exports.Clear(); + ReportLateUnloads(); + if (s_alc == null) return 1; + int gen = s_generation; + int freeBefore = FreeMb(out _); + var sw = Stopwatch.StartNew(); + WeakReference alcRef = StartUnload(); + int collections = 0; + while (alcRef.IsAlive && sw.ElapsedMilliseconds < UnloadWaitMs) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + collections++; + if (alcRef.IsAlive) Thread.Sleep(20); + } + GC.Collect(); + int freeAfter = FreeMb(out int largest); + if (!alcRef.IsAlive) + { + Log("INF", $"Engine gen {gen} unloaded in {sw.ElapsedMilliseconds} ms ({collections} GCs): " + + $"{freeAfter} MB free ({freeAfter - freeBefore:+0;-0} MB), largest block {largest} MB."); + return 1; + } + s_leakedGenerations++; + s_pending.Add((gen, alcRef)); + Log("WRN", $"Engine gen {gen} NOT unloaded after {UnloadWaitMs} ms ({collections} GCs): something still " + + $"references it (a thread still running engine code, an event, a static in the default " + + $"context...). {s_leakedGenerations} generation(s) leaked so far; {freeAfter} MB free."); + return 0; + } + catch (Exception ex) + { + Log("ERR", "Unload failed: " + ex); + return 0; + } + } + + private static void ReportLateUnloads() + { + for (int i = s_pending.Count - 1; i >= 0; i--) + { + if (s_pending[i].Context.IsAlive) continue; + s_leakedGenerations--; + Log("INF", $"Engine gen {s_pending[i].Generation} has unloaded since (late). {s_leakedGenerations} generation(s) still held."); + s_pending.RemoveAt(i); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference StartUnload() + { + EngineLoadContext alc = s_alc!; + s_alc = null; + alc.Unload(); + return new WeakReference(alc, trackResurrection: true); + } + + private static int FreeMb(out int largest) + { + int l = 0; + int free = s_api->FreeMb(&l); + largest = l; + return free; + } + + internal static void Log(string level, string message) + { + if (s_api == null) return; + byte[] lvl = Encoding.ASCII.GetBytes(level + "\0"); + byte[] msg = Encoding.UTF8.GetBytes(message + "\0"); + fixed (byte* pl = lvl) + fixed (byte* pm = msg) + s_api->Log(pl, pm); + } +} + +/// <summary> +/// One engine generation. The engine's own dependencies (Avalonia, ImGui.NET, SkiaSharp...) +/// load here from Runtime\ so they go away with it; so do the framework libraries that keep +/// process-wide caches of the types they see (System.Text.Json: Phase 0 found it roots a +/// collectible context from the default one). Everything else comes from the default context. +/// </summary> +internal sealed class EngineLoadContext : AssemblyLoadContext +{ + private static readonly HashSet<string> PrivateFramework = new(StringComparer.OrdinalIgnoreCase) + { + "System.Text.Json", "System.Text.Encodings.Web", "System.IO.Pipelines", + }; + + private readonly string _engineDir; + private readonly string _runtimeDir; + + public EngineLoadContext(string name, string engineDir, string runtimeDir) : base(name, isCollectible: true) + { + _engineDir = engineDir; + _runtimeDir = runtimeDir; + } + + protected override Assembly? Load(AssemblyName name) + { + string? simple = name.Name; + if (string.IsNullOrEmpty(simple) || simple == "RynthCore.Shim") return null; + + if (PrivateFramework.Contains(simple)) + { + string fx = Path.Combine(_runtimeDir, simple + ".dll"); + return File.Exists(fx) ? LoadFromAssemblyPath(fx) : null; + } + + string local = Path.Combine(_engineDir, simple + ".dll"); + if (!File.Exists(local)) return null; + // From a stream, so Runtime\ stays unlocked (a deploy can overwrite it while clients run). + using var fs = new FileStream(local, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + string pdb = Path.ChangeExtension(local, ".pdb"); + if (!File.Exists(pdb)) return LoadFromStream(fs); + using var ps = new FileStream(pdb, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + return LoadFromStream(fs, ps); + } + + protected override nint LoadUnmanagedDll(string unmanagedDllName) + { + // Native libraries (cimgui, libSkiaSharp, minhook...) are process-wide and stay + // loaded; resolve them from Runtime\ first. + string candidate = Path.Combine(_engineDir, unmanagedDllName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + ? unmanagedDllName + : unmanagedDllName + ".dll"); + return File.Exists(candidate) ? LoadUnmanagedDllFromPath(candidate) : 0; + } +} diff --git a/tools/AelrynthTests/AelrynthTests.csproj b/tools/AelrynthTests/AelrynthTests.csproj new file mode 100644 index 0000000..8eddd08 --- /dev/null +++ b/tools/AelrynthTests/AelrynthTests.csproj @@ -0,0 +1,24 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the engine's Aelrynth detection and /mastery-data parser + (src\RynthCore.Engine\Compatibility\AelrynthWire.cs, compiled in): server detection + from launch command lines, hosts, world names and the Bank mod's properties, and + mastery reply lines serialized the way the SkillMastery mod writes them + (DataCommand.Describe + CompanionFeed.Send). Nothing native: no AC, no engine state. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>AelrynthTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/AelrynthTests/Program.cs b/tools/AelrynthTests/Program.cs new file mode 100644 index 0000000..9ebd77d --- /dev/null +++ b/tools/AelrynthTests/Program.cs @@ -0,0 +1,317 @@ +using System.Text.Json; +using RynthCore.Engine.Compatibility; + +namespace AelrynthTests; + +/// <summary> +/// Server detection and the /mastery-data parser, offline. Reply lines are built the way +/// the SkillMastery mod builds them (ServerFormat below mirrors DataCommand.Describe and +/// CompanionFeed.Send in Mods/src/Aeshnidae.SkillMastery), then fed through the engine's +/// parser; every value the Skills panel reads is checked. +/// </summary> +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + LaunchCommandLines(); + HostClassification(); + WorldNames(); + Decisions(); + TypicalReply(); + RefusalReply(); + HugeNumbersAndLongLine(); + PrefixPlacement(); + OtherDataLinesAndDamage(); + UnknownCommand(); + RaiseCommands(); + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL AELRYNTH TESTS PASSED." : $"{_failed} FAILED."); + return _failed == 0 ? 0 : 1; + } + + // ── Server detection ──────────────────────────────────────────────────── + + private static void LaunchCommandLines() + { + Case("launch command lines"); + // The RynthCore launcher's ACE form: -h host:port (AcLaunchArgumentBuilder). + Check(ServerDetect.TryParseLaunchHost( + "\"C:\\Turbine\\Asheron's Call\\acclient.exe\" -a tom -v \"pa ss -h x\" -h aelrynth.com:9020 -rodat off", + out string h, out int p) && h == "aelrynth.com" && p == 9020, $"ACE form: {h}:{p}"); + // GDLE form and other launchers: -h host -p port, account:password in -a. + Check(ServerDetect.TryParseLaunchHost("acclient.exe -h 144.217.84.148 -p 9030 -a tom:secret -rodat on", out h, out p) + && h == "144.217.84.148" && p == 9030, $"GDLE form: {h}:{p}"); + Check(ServerDetect.TryParseLaunchHost("acclient.exe -H Play.Aelrynth.COM. -P 9021", out h, out p) + && h == "play.aelrynth.com" && p == 9021, $"case and trailing dot: {h}:{p}"); + Check(ServerDetect.TryParseLaunchHost("acclient.exe -h \"localhost:9000\"", out h, out p) && h == "localhost" && p == 9000, + $"quoted host:port: {h}:{p}"); + Check(!ServerDetect.TryParseLaunchHost("acclient.exe -a tom -v pw", out h, out _) && h == "", "no -h"); + Check(!ServerDetect.TryParseLaunchHost("", out _, out _) && !ServerDetect.TryParseLaunchHost(null, out _, out _), "empty / null"); + Check(!ServerDetect.TryParseLaunchHost("acclient.exe -h", out _, out _), "-h with nothing after it"); + } + + private static void HostClassification() + { + Case("host classification"); + Check(ServerDetect.ClassifyHost("aelrynth.com") == ServerHostKind.Aelrynth, "aelrynth.com"); + Check(ServerDetect.ClassifyHost("play.aelrynth.com") == ServerHostKind.Aelrynth, "subdomain"); + Check(ServerDetect.ClassifyHost("144.217.84.148") == ServerHostKind.Aelrynth, "the VPS address"); + Check(ServerDetect.ClassifyHost("notaelrynth.com") == ServerHostKind.Other, "a look-alike domain is not Aelrynth"); + Check(ServerDetect.ClassifyHost("aelrynth.com.evil.net") == ServerHostKind.Other, "aelrynth.com as a prefix is not Aelrynth"); + Check(ServerDetect.ClassifyHost("144.217.84.149") == ServerHostKind.Other, "the next address over"); + Check(ServerDetect.ClassifyHost("localhost") == ServerHostKind.Local, "localhost"); + Check(ServerDetect.ClassifyHost("127.0.0.1") == ServerHostKind.Local, "loopback"); + Check(ServerDetect.ClassifyHost("192.168.1.20") == ServerHostKind.Local, "192.168/16"); + Check(ServerDetect.ClassifyHost("10.0.0.5") == ServerHostKind.Local, "10/8"); + Check(ServerDetect.ClassifyHost("172.20.1.1") == ServerHostKind.Local, "172.16/12"); + Check(ServerDetect.ClassifyHost("172.32.1.1") == ServerHostKind.Other, "172.32 is public"); + Check(ServerDetect.ClassifyHost("play.coldeve.ac") == ServerHostKind.Other, "someone else's server"); + Check(ServerDetect.ClassifyHost("") == ServerHostKind.Unknown && ServerDetect.ClassifyHost(null) == ServerHostKind.Unknown, "nothing"); + } + + private static void WorldNames() + { + Case("world names"); + Check(ServerDetect.IsAelrynthWorldName("Aelrynth"), "Aelrynth"); + Check(ServerDetect.IsAelrynthWorldName("Aeshnidae"), "Aeshnidae (the live config's name)"); + Check(ServerDetect.IsAelrynthWorldName("Aeshnidae Staging"), "Aeshnidae Staging (ops/staging.sh)"); + Check(!ServerDetect.IsAelrynthWorldName("ACEmulator"), "ACE's default name"); + Check(!ServerDetect.IsAelrynthWorldName("Coldeve") && !ServerDetect.IsAelrynthWorldName("") && !ServerDetect.IsAelrynthWorldName(null), "others"); + } + + private static void Decisions() + { + Case("decisions"); + ServerVerdict v = ServerDetect.Decide(ServerHostKind.Aelrynth, "aelrynth.com", 9020, null, false); + Check(v.IsAelrynth && !v.IsStaging, "live by host alone: " + v.Reason); + v = ServerDetect.Decide(ServerHostKind.Aelrynth, "144.217.84.148", 9030, "Aeshnidae Staging", true); + Check(v.IsAelrynth && v.IsStaging, "staging by port: " + v.Reason); + v = ServerDetect.Decide(ServerHostKind.Aelrynth, "aelrynth.com", 0, "Aeshnidae Staging", false); + Check(v.IsAelrynth && v.IsStaging, "staging by world name"); + v = ServerDetect.Decide(ServerHostKind.Other, "play.coldeve.ac", 9000, "Coldeve", false); + Check(!v.IsAelrynth, "someone else's server: " + v.Reason); + v = ServerDetect.Decide(ServerHostKind.Other, "1.2.3.4", 9000, "Aelrynth", false); + Check(!v.IsAelrynth, "another host calling itself Aelrynth is not enough"); + v = ServerDetect.Decide(ServerHostKind.Other, "1.2.3.4", 9000, null, true); + Check(!v.IsAelrynth, "another host with property 9101 alone is not enough"); + v = ServerDetect.Decide(ServerHostKind.Other, "1.2.3.4", 9000, "Aelrynth", true); + Check(v.IsAelrynth, "a new address with both server-sent signals: " + v.Reason); + v = ServerDetect.Decide(ServerHostKind.Local, "localhost", 9000, "Aeshnidae", false); + Check(v.IsAelrynth && !v.IsStaging, "a dev copy on localhost by world name"); + v = ServerDetect.Decide(ServerHostKind.Local, "localhost", 9000, null, true); + Check(v.IsAelrynth, "a dev copy by the Bank properties"); + v = ServerDetect.Decide(ServerHostKind.Local, "localhost", 9000, "ACEmulator", false); + Check(!v.IsAelrynth, "a plain local ACE"); + v = ServerDetect.Decide(ServerHostKind.Unknown, "", 0, null, false); + Check(!v.IsAelrynth && v.Reason.Length > 0, "unknown means not Aelrynth: " + v.Reason); + Check(!ServerVerdict.Unknown.IsAelrynth, "the starting verdict is not Aelrynth"); + } + + // ── /mastery-data ─────────────────────────────────────────────────────── + + private static void TypicalReply() + { + Case("typical reply (ten raises per point)"); + string line = ServerFormat.Reply(enabled: true, radiance: 5_600_000, perPoint: 10, ceiling: 0, requireCap: true, + ServerFormat.Skill(6, "MeleeDefense", "Melee Defense", spec: true, @base: 433, cur: 520, ranks: 37, perPoint: 10, + next: 1_234_567, afford: 4, atCeiling: false, locked: false), + ServerFormat.Skill(34, "WarMagic", "War Magic", spec: false, @base: 300, cur: 300, ranks: 0, perPoint: 10, + next: 900_000, afford: 6, atCeiling: false, locked: true), + ServerFormat.Skill(15, "MagicDefense", "Magic Defense", spec: false, @base: 410, cur: 410, ranks: 120, perPoint: 10, + next: 2_000_000, afford: 2, atCeiling: false, locked: false)); + Check(line.StartsWith("~ael1 {\"t\":\"mastery\",\"ok\":true,", StringComparison.Ordinal), "wire shape: " + line[..Math.Min(60, line.Length)]); + Check(MasteryWire.IsDataLine(line) && MasteryWire.TypeOf(line) == "mastery", "recognised"); + Check(MasteryWire.TryParse(line, out MasteryData? d) && d != null, "parsed"); + if (d == null) return; + Check(d.Ok && d.Enabled && d.Radiance == 5_600_000 && d.PerPoint == 10 && d.CeilingPoints == 0 && d.RequireCap, "header fields"); + Check(d.Skills.Count == 3, $"three skills ({d.Skills.Count})"); + MasterySkill md = d.Skills[6]; + Check(md.Key == "meleedefense" && md.Name == "Melee Defense" && md.Specialized, "melee defense: key, name, specialized"); + Check(md.Base == 433 && md.Current == 520 && md.Ranks == 37 && md.Points == "3.7" && md.Bonus == 3, "melee defense: numbers"); + Check(md.Next == 1_234_567 && md.Afford == 4 && !md.Ceiling && !md.Locked, "melee defense: price"); + MasterySkill war = d.Skills[34]; + Check(!war.Specialized && war.Locked && war.Ranks == 0 && war.Points == "0.0" && war.Bonus == 0, "war magic: locked, none yet"); + Check(d.Skills[15].Points == "12.0" && d.Skills[15].Bonus == 12, "magic defense: whole points"); + } + + private static void RefusalReply() + { + Case("the mod's refusal and a disabled server"); + string refusal = ServerFormat.Send(new { t = "mastery", ok = false, why = "could not read your mastery" }); + Check(MasteryWire.TryParse(refusal, out MasteryData? d) && d != null && !d.Ok && d.Why == "could not read your mastery" + && d.Skills.Count == 0, "ok=false keeps the reason"); + string off = ServerFormat.Reply(enabled: false, radiance: 0, perPoint: 1, ceiling: 500, requireCap: false, + ServerFormat.Skill(6, "MeleeDefense", "Melee Defense", spec: false, @base: 200, cur: 200, ranks: 500, perPoint: 1, + next: 0, afford: 0, atCeiling: true, locked: false)); + Check(MasteryWire.TryParse(off, out d) && d != null && d.Ok && !d.Enabled && d.CeilingPoints == 500 && d.PerPoint == 1, + "enabled=false, ceiling 500, one raise per point"); + Check(d != null && d.Skills[6].Ceiling && d.Skills[6].Next == 0 && d.Skills[6].Points == "500", "at the ceiling: next 0"); + } + + private static void HugeNumbersAndLongLine() + { + Case("huge prices and a long line"); + const long priceCeiling = (long.MaxValue / 4) / 1024; // Mastery.PriceCeiling + var skills = new List<object>(); + string[] names = + { + "Alchemy", "ArcaneLore", "ArmorTinkering", "AssessCreature", "AssessPerson", "Cooking", "CreatureEnchantment", + "Deception", "DirtyFighting", "DualWield", "Fletching", "Healing", "HeavyWeapons", "ItemEnchantment", + "ItemTinkering", "Jump", "Leadership", "LifeMagic", "LightWeapons", "Lockpick", "Loyalty", "MagicDefense", + "MagicItemTinkering", "ManaConversion", "MeleeDefense", "MissileDefense", "MissileWeapons", "Recklessness", + "Run", "Salvaging", "Shield", "SneakAttack", "Summoning", "TwoHandedCombat", "VoidMagic", "WarMagic", + "WeaponTinkering", "FinesseWeapons", + }; + for (int i = 0; i < names.Length; i++) + skills.Add(ServerFormat.Skill(i + 1, names[i], names[i], spec: i % 3 == 0, @base: 500 + i, cur: 600 + i, + ranks: 2400 + i, perPoint: 10, next: i == 0 ? priceCeiling : 1_000_000_000_000L + i, afford: i == 0 ? 0 : 999, + atCeiling: false, locked: false)); + string line = ServerFormat.Reply(true, 70_000_000_000_000_000L, 10, 0, true, skills.ToArray()); + Check(line.Length > 6000, $"line is {line.Length} chars (the chat hook reads data lines past its 1024 cap)"); + Check(MasteryWire.TryParse(line, out MasteryData? d) && d != null && d.Skills.Count == names.Length, "all skills parsed"); + if (d == null) return; + Check(d.Radiance == 70_000_000_000_000_000L, "7e16 Radiance (a test account)"); + Check(d.Skills[1].Next == priceCeiling && d.Skills[1].Afford == 0, "price at the ceiling: " + d.Skills[1].Next); + Check(d.Skills[2].Afford == 999 && d.Skills[2].Points == "240.1", "afford capped at 999, points 240.1"); + } + + private static void PrefixPlacement() + { + Case("where the prefix may sit"); + string body = "{\"t\":\"mastery\",\"ok\":true,\"enabled\":true,\"radiance\":5,\"perPoint\":1,\"ceiling\":0,\"requireCap\":false,\"skills\":[]}"; + Check(MasteryWire.TryParse("~ael1 " + body, out _), "at the start"); + Check(MasteryWire.TryParse("~ael1 " + body + "\n", out _), "trailing newline"); + Check(MasteryWire.TryParse("[System] ~ael1 " + body, out _), "after a short tag"); + Check(!MasteryWire.IsDataLine("Bob says, \"~ael1 " + body + "\""), "a player saying it is not a server line"); + Check(!MasteryWire.TryParse("Somebody tells you, \"~ael1 " + body + "\"", out _), "nor a tell"); + Check(!MasteryWire.IsDataLine(new string(' ', 40) + "~ael1 " + body), "too far into the line"); + Check(!MasteryWire.IsDataLine("~ael2 " + body), "another protocol version"); + Check(!MasteryWire.IsDataLine("~ael1") && !MasteryWire.IsDataLine(null) && !MasteryWire.IsDataLine(""), "short / null / empty"); + } + + private static void OtherDataLinesAndDamage() + { + Case("other data lines and damage"); + string inspect = ServerFormat.Send(new { t = "inspect", guid = "0x80000201", ok = true }); + Check(MasteryWire.IsDataLine(inspect) && MasteryWire.TypeOf(inspect) == "inspect", "an /inspect-data line is a data line"); + Check(!MasteryWire.TryParse(inspect, out _), "but not a mastery reply"); + Check(!MasteryWire.TryParse("~ael1 {\"t\":\"mastery\",\"ok\":tr", out _), "cut off"); + Check(!MasteryWire.TryParse("~ael1 not json at all", out _), "not JSON"); + Check(!MasteryWire.TryParse("~ael1 [1,2,3]", out _), "an array, not an object"); + // Extra fields and type drift: ignored / tolerated. + string drift = "~ael1 {\"t\":\"mastery\",\"ok\":true,\"enabled\":true,\"radiance\":\"42\",\"perPoint\":0,\"future\":{\"x\":1}," + + "\"skills\":[{\"id\":6,\"k\":\"meleedefense\",\"ranks\":3,\"next\":10.0,\"newField\":true}," + + "{\"id\":7,\"k\":\"Melee Defense\",\"ranks\":1},{\"id\":0,\"k\":\"run\"},\"junk\"]}"; + Check(MasteryWire.TryParse(drift, out MasteryData? d) && d != null, "parsed with extra fields"); + if (d == null) return; + Check(d.Radiance == 42 && d.PerPoint == 1, "a number sent as a string; perPoint 0 read as 1"); + Check(d.Skills.Count == 1 && d.Skills[6].Ranks == 3 && d.Skills[6].Next == 10 && d.Skills[6].Points == "", + "a bad key, id 0 and a non-object are skipped; missing points stay empty"); + } + + private static void UnknownCommand() + { + Case("ACE's unknown-command refusal"); + Check(MasteryWire.IsUnknownCommand("Unknown command: mastery-data", "mastery-data"), "exact (GameActionTalk's text)"); + Check(MasteryWire.IsUnknownCommand("Unknown command: MASTERY-DATA ", "mastery-data"), "case and trailing space"); + Check(!MasteryWire.IsUnknownCommand("Unknown command: raise", "mastery-data"), "another command"); + Check(!MasteryWire.IsUnknownCommand("Bob says, \"Unknown command: mastery-data\"", "mastery-data"), "a player saying it"); + Check(!MasteryWire.IsUnknownCommand("You have 5 mastery points.", "mastery-data") && !MasteryWire.IsUnknownCommand(null, "mastery-data"), + "ordinary lines"); + Check(MasteryWire.DataRequest == "@mastery-data", "the request is sent as @mastery-data"); + } + + private static void RaiseCommands() + { + Case("/raise command text"); + // The mod's /raise: "/raise <skill> [points]"; the last word is the count when it is a number, + // the rest is matched against the Skill enum with spaces removed (Commands.TryParseSkill). + Check(MasteryWire.RaiseCommand("meleedefense", 1) == "@raise meleedefense 1", "one raise"); + Check(MasteryWire.RaiseCommand("warmagic", 25) == "@raise warmagic 25", "several"); + Check(MasteryWire.RaiseCommand("Melee Defense", 1) == null, "a display name is refused (not the enum key)"); + Check(MasteryWire.RaiseCommand("meleedefense", 0) == null && MasteryWire.RaiseCommand("meleedefense", -3) == null, "count below 1"); + Check(MasteryWire.RaiseCommand("meleedefense", 1000) == null, "count above 999"); + Check(MasteryWire.RaiseCommand("", 1) == null && MasteryWire.RaiseCommand(null, 1) == null, "no key"); + Check(MasteryWire.RaiseCommand("melee;defense", 1) == null, "punctuation"); + // Every key the mod sends round-trips: skill.ToString().ToLowerInvariant() is letters only. + foreach (string k in new[] { "alchemy", "twohandedcombat", "missileweapons", "voidmagic" }) + Check(MasteryWire.IsSkillKey(k), "key " + k); + } + + // ── harness ───────────────────────────────────────────────────────────── + + private static void Case(string name) + { + _case = name; + Console.WriteLine($"-- {name}"); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}"); + } +} + +/// <summary> +/// The SkillMastery mod's wire format, mirrored: CompanionFeed.Send serializes an object with +/// UnsafeRelaxedJsonEscaping and WhenWritingNull after the "~ael1 " prefix; DataCommand.Describe +/// builds the object (field names and order as there; Mastery.Points for "points", +/// Mastery.SkillPointsFor for "bonus"). +/// </summary> +internal static class ServerFormat +{ + private static readonly JsonSerializerOptions Json = new() + { + Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, + }; + + public static string Send(object data) => "~ael1 " + JsonSerializer.Serialize(data, Json); + + public static string Reply(bool enabled, long radiance, int perPoint, int ceiling, bool requireCap, params object[] skills) => + Send(new + { + t = "mastery", + ok = true, + enabled, + radiance, + perPoint, + ceiling, + requireCap, + skills, + }); + + public static object Skill(int id, string enumName, string name, bool spec, long @base, long cur, int ranks, int perPoint, + long next, int afford, bool atCeiling, bool locked) => + new + { + id, + k = enumName.ToLowerInvariant(), + name, + adv = spec ? "spec" : "trained", + @base, + cur, + ranks, + points = Points(ranks, perPoint), + bonus = perPoint < 1 ? ranks : ranks / perPoint, + next, + afford, + ceiling = atCeiling, + locked, + }; + + /// <summary>Mastery.Points: "N0" with one rank per point, else "{ranks/per:N0}.{ranks%per}".</summary> + private static string Points(int ranks, int perPoint) + { + int per = Math.Max(1, perPoint); + return per == 1 ? ranks.ToString("N0") : $"{ranks / per:N0}.{ranks % per}"; + } +} diff --git a/tools/AlcRoots/AlcRoots.csproj b/tools/AlcRoots/AlcRoots.csproj new file mode 100644 index 0000000..e523c54 --- /dev/null +++ b/tools/AlcRoots/AlcRoots.csproj @@ -0,0 +1,15 @@ +<Project Sdk="Microsoft.NET.Sdk"> + <!-- x86 because ClrMD must match the target's bitness (acclient is 32-bit). --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <RuntimeIdentifier>win-x86</RuntimeIdentifier> + <SelfContained>false</SelfContained> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + </PropertyGroup> + <ItemGroup> + <PackageReference Include="Microsoft.Diagnostics.Runtime" Version="3.1.512801" /> + </ItemGroup> +</Project> diff --git a/tools/AlcRoots/Program.cs b/tools/AlcRoots/Program.cs new file mode 100644 index 0000000..b83c7fa --- /dev/null +++ b/tools/AlcRoots/Program.cs @@ -0,0 +1,146 @@ +// AlcRoots: why didn't an engine generation unload? +// +// Attaches (read-only snapshot) to a CoreCLR-hosted acclient and prints +// 1. every managed thread with frames in collectible (engine) code, and +// 2. the shortest reference path from each kind of GC root to the first object that +// belongs to a collectible context (an object of a collectible type, a +// LoaderAllocator, or the Shim's EngineLoadContext). +// Anything on those lists keeps an unloaded generation alive. +// +// AlcRoots.exe <pid> [maxPaths] +using Microsoft.Diagnostics.Runtime; + +if (args.Length < 1 || !int.TryParse(args[0], out int pid)) +{ + Console.WriteLine("usage: AlcRoots <pid> [maxPaths]"); + return 1; +} +int maxPaths = args.Length > 1 && int.TryParse(args[1], out int mp) ? mp : 25; +uint stackOfOsThread = args.Length > 2 && args[1] == "--stack" ? Convert.ToUInt32(args[2], 16) : 0; + +using DataTarget dt = DataTarget.CreateSnapshotAndAttach(pid); +// A client that also runs Decal has the desktop CLR (clr.dll) loaded too: take CoreCLR. +foreach (ClrInfo c in dt.ClrVersions) + Console.WriteLine($"runtime in process: {c.Flavor} {c.Version} ({c.ModuleInfo.FileName})"); +ClrInfo info = dt.ClrVersions.Single(c => c.Flavor == ClrFlavor.Core); +string dac = Path.Combine(Path.GetDirectoryName(info.ModuleInfo.FileName)!, "mscordaccore.dll"); +using ClrRuntime runtime = File.Exists(dac) ? info.CreateRuntime(dac, ignoreMismatch: true) : info.CreateRuntime(); +ClrHeap heap = runtime.Heap; +Console.WriteLine($"CLR {info.Version} in pid {pid}; heap {heap.Segments.Sum(s => (long)s.Length) / 1048576} MB in {heap.Segments.Length} segments"); + +if (stackOfOsThread != 0 || (args.Length > 1 && args[1] == "--stack")) +{ + // AlcRoots <pid> --stack <osThreadIdHex>: managed stack of one thread. + foreach (ClrThread th in runtime.Threads.Where(t => t.OSThreadId == stackOfOsThread)) + foreach (ClrStackFrame f in th.EnumerateStackTrace().Take(60)) + Console.WriteLine($" {f.InstructionPointer:x8} {(f.Method != null ? f.Method.Signature : f.FrameName)}"); + return 0; +} + +// --- collectible contexts still alive ------------------------------------------------- +// The newest generation is the running one; every older context still alive is a leak +// (with only one context, it is the target: useful before a reload). +var allocators = heap.EnumerateObjects().Where(o => o.Type?.Name == "System.Reflection.LoaderAllocator").ToList(); +var contexts = heap.EnumerateObjects().Where(o => o.Type?.Name == "RynthCore.Shim.EngineLoadContext") + .Select(o => (Obj: o, Name: o.ReadStringField("_name") ?? "?")) + .OrderBy(c => GenOf(c.Name)) + .ToList(); +Console.WriteLine($"LoaderAllocators alive: {allocators.Count}; EngineLoadContexts alive: {contexts.Count}"); +var targetContexts = new HashSet<ulong>( + (contexts.Count > 1 ? contexts.Take(contexts.Count - 1) : contexts).Select(c => c.Obj.Address)); +foreach (var (obj, name) in contexts) + Console.WriteLine($" context 0x{obj.Address:x8} \"{name}\"{(targetContexts.Contains(obj.Address) ? " <- should be gone" : " (running)")}"); + +static int GenOf(string name) => + int.TryParse(System.Text.RegularExpressions.Regex.Match(name, @"gen(\d+)").Groups[1].Value, out int g) ? g : 0; + +bool InTarget(ClrType? t) => t != null && t.IsCollectible && targetContexts.Contains(t.AssemblyLoadContextAddress); + +// --- threads running code of the leaked generation(s) ----------------------------------- +Console.WriteLine(); +Console.WriteLine("Threads with frames in the leaked generation(s):"); +int engineThreads = 0; +foreach (ClrThread thread in runtime.Threads) +{ + if (!thread.IsAlive) continue; + var frames = thread.EnumerateStackTrace().Take(200).ToList(); + if (!frames.Any(f => InTarget(f.Method?.Type))) continue; + engineThreads++; + Console.WriteLine($" thread managed={thread.ManagedThreadId} os=0x{thread.OSThreadId:x}"); + foreach (ClrStackFrame f in frames.Where(f => f.Method != null).Take(12)) + Console.WriteLine($" {(InTarget(f.Method!.Type) ? "*" : " ")} {f.Method.Signature ?? f.Method.Name}"); +} +if (engineThreads == 0) Console.WriteLine(" (none)"); + +// --- reference paths from roots -------------------------------------------------------- +Console.WriteLine(); +Console.WriteLine("Root paths into the leaked generation(s):"); +var parent = new Dictionary<ulong, ulong>(); +var rootOf = new Dictionary<ulong, string>(); +var queue = new Queue<ClrObject>(); +foreach (ClrRoot root in heap.EnumerateRoots()) +{ + ClrObject o = root.Object; + if (!o.IsValid || rootOf.ContainsKey(o.Address)) continue; + string desc = root.RootKind.ToString(); + if (root is ClrStackRoot sr && sr.StackFrame != null) + desc += $" thread os=0x{sr.StackFrame.Thread?.OSThreadId:x} in {sr.StackFrame.Method?.Signature ?? sr.StackFrame.FrameName}"; + rootOf[o.Address] = desc; + queue.Enqueue(o); +} + +var hits = new List<ulong>(); +var visited = new HashSet<ulong>(rootOf.Keys); +while (queue.Count > 0) +{ + ClrObject o = queue.Dequeue(); + if (InTarget(o.Type)) { hits.Add(o.Address); continue; } // stop at the boundary + if (o.Type?.IsCollectible == true) continue; // the running generation's own objects + foreach (ClrObject r in o.EnumerateReferences(false, true)) + { + if (!r.IsValid || !visited.Add(r.Address)) continue; + parent[r.Address] = o.Address; + queue.Enqueue(r); + } +} + +// Group by root description + path shape so one leak doesn't print a thousand times. +var seen = new HashSet<string>(); +int printed = 0; +foreach (ulong hit in hits) +{ + var chain = new List<ulong> { hit }; + ulong cur = hit; + while (parent.TryGetValue(cur, out ulong p)) { chain.Add(p); cur = p; } + chain.Reverse(); + string rootDesc = rootOf.TryGetValue(chain[0], out string? d) ? d : "?"; + var types = chain.Select(a => heap.GetObject(a).Type?.Name ?? "?").ToList(); + string key = rootDesc.Split(" thread")[0] + "|" + string.Join(">", types); + if (!seen.Add(key)) continue; + Console.WriteLine($" [{rootDesc}]"); + for (int i = 0; i < chain.Count; i++) + { + ClrObject o = heap.GetObject(chain[i]); + string extra = o.Type?.IsString == true ? $" \"{Trim(o.AsString())}\"" : ""; + if (o.Type?.Name?.Contains("Delegate") == true || o.Type?.BaseType?.Name == "System.MulticastDelegate") + extra = DescribeDelegate(runtime, o); + Console.WriteLine($" {(i == chain.Count - 1 ? "=>" : "->")} {o.Type?.Name}{extra} @0x{o.Address:x8}"); + } + if (++printed >= maxPaths) { Console.WriteLine($" ... ({hits.Count} hits, stopping at {maxPaths} distinct paths)"); break; } +} +if (printed == 0) Console.WriteLine(" (no strong path found: check the threads above and dependent handles)"); +return 0; + +static string Trim(string? s) => s == null ? "" : s.Length > 80 ? s[..80] + "..." : s; + +static string DescribeDelegate(ClrRuntime runtime, ClrObject del) +{ + try + { + ulong methodPtr = del.ReadValueTypeField("_methodPtr").Address != 0 ? del.ReadField<ulong>("_methodPtr") : 0; + ClrObject target = del.ReadObjectField("_target"); + ClrMethod? m = runtime.GetMethodByInstructionPointer(methodPtr); + return $" (target {target.Type?.Name ?? "null"}, method {m?.Signature ?? "?"})"; + } + catch { return ""; } +} diff --git a/tools/CharacterTitlesTests/CharacterTitlesTests.csproj b/tools/CharacterTitlesTests/CharacterTitlesTests.csproj new file mode 100644 index 0000000..b17091b --- /dev/null +++ b/tools/CharacterTitlesTests/CharacterTitlesTests.csproj @@ -0,0 +1,23 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the character-title tracking behind plugin API v75 GetCharacterTitles + (src\RynthCore.Engine\Compatibility\CharacterTitles.cs, compiled in): ACE's 0x0029 and + 0x002B game events, the owner rule and the hot-reload mirror. Nothing native: no AC. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>CharacterTitlesTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\CharacterTitles.cs" Link="Engine\CharacterTitles.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/CharacterTitlesTests/Program.cs b/tools/CharacterTitlesTests/Program.cs new file mode 100644 index 0000000..6fcfb1f --- /dev/null +++ b/tools/CharacterTitlesTests/Program.cs @@ -0,0 +1,98 @@ +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using RynthCore.Engine.Compatibility; + +namespace CharacterTitlesTests; + +/// <summary>CharacterTitles (plugin API v75) without AC: hand-built ACE title events.</summary> +internal static unsafe class Program +{ + private static int _checks, _failed; + + private static int Main() + { + Environment.SetEnvironmentVariable("RYNTHCORE_CHAR_TITLES", null); + + // Nothing received yet. + Check(Copy(0x50000001, out _, out _) == -1, "unknown before any event"); + + // 0x0029 at login: [type][1][current][count][ids...], as ACE's GameEventCharacterTitle writes it. + Send(TitleList(current: 9, 1, 9, 42, 42)); + Check(Copy(0x50000001, out uint[] ids, out uint cur) == 3 && cur == 9 && ids.SequenceEqual(new uint[] { 1, 9, 42 }), + "title list (duplicate dropped)"); + + // Received before the player id was known (owner 0): adopted by the first reader, then kept. + Check(Copy(0x50000002, out _, out _) == -1, "another character's list isn't served"); + + // 0x002B: a new title, then a display change. + Send(Update(77, display: false)); + Check(Copy(0x50000001, out ids, out cur) == 4 && cur == 9 && ids.Contains(77u), "a new title is added"); + Send(Update(42, display: true)); + Check(Copy(0x50000001, out ids, out cur) == 4 && cur == 42, "a display change sets the current title"); + + // Malformed: a count past the end is ignored (the old list stays). + byte[] bad = TitleList(current: 1, 5, 6); + BinaryPrimitives.WriteUInt32LittleEndian(bad.AsSpan(12), 1000); + Send(bad); + Check(Copy(0x50000001, out ids, out _) == 4, "a count past the end is refused"); + Check(!CharacterTitles.TryParseUpdate(new byte[8], out _, out _), "a short update is refused"); + + // The hot-reload mirror round-trips. + string? env = Environment.GetEnvironmentVariable("RYNTHCORE_CHAR_TITLES"); + Check(CharacterTitles.TryParseMirror(env, out uint owner, out uint mcur, out List<uint> mids) + && owner == 0x50000001 && mcur == 42 && mids.Count == 4, "mirror: " + env); + Check(!CharacterTitles.TryParseMirror("garbage", out _, out _, out _), "a bad mirror is refused"); + + // Ids only: ask for the count first (ids null). + uint c2 = 0; + Check(CharacterTitles.Copy(0x50000001, null, 0, &c2) == 4 && c2 == 42, "count without ids"); + + Console.WriteLine($"{_checks - _failed} passed, {_failed} failed"); + return _failed == 0 ? 0 : 1; + } + + private static int Copy(uint player, out uint[] ids, out uint current) + { + uint[] buf = new uint[64]; + uint cur = 0; + int n; + fixed (uint* p = buf) n = CharacterTitles.Copy(player, p, buf.Length, &cur); + ids = n > 0 ? buf.Take(n).ToArray() : Array.Empty<uint>(); + current = cur; + return n; + } + + private static void Send(byte[] msg) + { + uint type = BinaryPrimitives.ReadUInt32LittleEndian(msg); + fixed (byte* p = msg) CharacterTitles.OnGameEvent(type, (IntPtr)p, (uint)msg.Length, playerId: 0); + } + + private static byte[] TitleList(uint current, params uint[] ids) + { + var b = new byte[16 + ids.Length * 4]; + BinaryPrimitives.WriteUInt32LittleEndian(b, CharacterTitles.EventCharacterTitle); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4), 1); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(8), current); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(12), (uint)ids.Length); + for (int i = 0; i < ids.Length; i++) BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(16 + i * 4), ids[i]); + return b; + } + + private static byte[] Update(uint title, bool display) + { + var b = new byte[12]; + BinaryPrimitives.WriteUInt32LittleEndian(b, CharacterTitles.EventUpdateTitle); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4), title); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(8), display ? 1u : 0u); + return b; + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine("FAIL: " + what); + } +} diff --git a/tools/ChatCoordTests/ChatCoordTests.csproj b/tools/ChatCoordTests/ChatCoordTests.csproj new file mode 100644 index 0000000..fc8ce8f --- /dev/null +++ b/tools/ChatCoordTests/ChatCoordTests.csproj @@ -0,0 +1,22 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the chat window's coordinate finder (src\RynthCore.Engine\UI\Data\ + ChatCoords.cs, compiled in): which chat lines hold map coordinates, in which order and + format, and which ordinary lines must not turn into coordinates. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>ChatCoordTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatCoords.cs" Link="Engine\ChatCoords.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/ChatCoordTests/Program.cs b/tools/ChatCoordTests/Program.cs new file mode 100644 index 0000000..2fad6ca --- /dev/null +++ b/tools/ChatCoordTests/Program.cs @@ -0,0 +1,72 @@ +using RynthCore.Engine.UI.Data; + +namespace ChatCoordTests; + +/// <summary> +/// The chat window's coordinate finder (ChatCoords): the forms players and the game write +/// coordinates in, and ordinary chat that must not become coordinates. +/// </summary> +internal static class Program +{ + private static int _checks, _failed; + + private static int Main() + { + One("Meet me at 42.1N, 33.6E", 42.1, 33.6, "42.1N, 33.6E"); + One("42.1N 33.6E", 42.1, 33.6, "42.1N, 33.6E"); + One("42.1N33.6E", 42.1, 33.6, "42.1N, 33.6E"); + One("loc 21.5S, 1.8W please", -21.5, -1.8, "21.5S, 1.8W"); + One("33.6E, 42.1N", 42.1, 33.6, "42.1N, 33.6E"); + One("at 42.1 N, 33.6 E now", 42.1, 33.6, "42.1N, 33.6E"); + One("(12.5n, 0.4w)", 12.5, -0.4, "12.5N, 0.4W"); + One("Your location is: 0xA9B40019 [84.000 7.100 42.005] 0.0 0.0 0.0 1.0 = 42.1N, 33.6E", 42.1, 33.6, "42.1N, 33.6E"); + One("drudges at 42N 33E", 42, 33, "42.0N, 33.0E"); + One("0.0N, 101.9W", 0, -101.9, "0.0N, 101.9W"); + + // Two in one line, in order. + var two = ChatCoords.Find("from 42.1N, 33.6E to 21.5S, 1.8W"); + Check(two.Count == 2, "two pairs"); + Check(two.Count == 2 && two[0].Ns == 42.1 && two[1].Ns == -21.5, "in order"); + Check(two.Count == 2 && two[0].Start < two[1].Start, "start positions"); + var first = two.Count > 0 ? two[0] : default; + Check(first.Start == 5 && "from 42.1N, 33.6E to".Substring(first.Start, first.Length) == "42.1N, 33.6E", "the span covers the pair"); + + // Not coordinates. + None("give me 5 s, 2 e"); + None("lvl 120N 33E"); // off the map + None("Holtburg is nice"); + None("brb 5 min"); + None("42.1N"); // half a pair + None("42.1N 33.6N"); // two N/S + None("v1.2.3n 4.5e"); // part of a word / version + None(""); + None(null); + + Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks})"); + return _failed == 0 && _checks > 0 ? 0 : 1; + } + + private static void One(string text, double ns, double ew, string formatted) + { + var found = ChatCoords.Find(text); + Check(found.Count == 1, $"one pair in \"{text}\" (found {found.Count})"); + if (found.Count != 1) return; + Check(Math.Abs(found[0].Ns - ns) < 1e-9 && Math.Abs(found[0].Ew - ew) < 1e-9, + $"\"{text}\" -> {ns}, {ew} (got {found[0].Ns}, {found[0].Ew})"); + Check(found[0].Text == formatted, $"\"{text}\" formats as {formatted} (got {found[0].Text})"); + } + + private static void None(string? text) + { + var found = ChatCoords.Find(text); + Check(found.Count == 0, $"no pair in \"{text}\" (found {found.Count}: {string.Join("; ", found.Select(f => f.Text))})"); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine(" [FAIL] " + what); + } +} diff --git a/tools/ChatHoldTests/ChatHoldTests.csproj b/tools/ChatHoldTests/ChatHoldTests.csproj new file mode 100644 index 0000000..7ab8f25 --- /dev/null +++ b/tools/ChatHoldTests/ChatHoldTests.csproj @@ -0,0 +1,23 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the engine's incoming-chat hold (src\RynthCore.Engine\Compatibility\ + IncomingChatHold.cs, compiled in): when a line is held for the plugins' verdict, when it + prints at once, the order held lines print in, eaten lines, the timeout, flushing, and the + "a plugin threw, so the line shows" rule. Nothing native: no AC, no engine state. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>ChatHoldTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\IncomingChatHold.cs" Link="Engine\IncomingChatHold.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/ChatHoldTests/Program.cs b/tools/ChatHoldTests/Program.cs new file mode 100644 index 0000000..2177fd2 --- /dev/null +++ b/tools/ChatHoldTests/Program.cs @@ -0,0 +1,269 @@ +using System.Collections.Concurrent; +using RynthCore.Engine.Compatibility; + +namespace ChatHoldTests; + +/// <summary> +/// The engine's incoming-chat hold (IncomingChatHold.cs) without AC: the hold decision, the +/// release order, eaten lines, the timeout, flushing, and a two-thread run shaped like the +/// real one (AC's main thread holds and prints, the plugin pump writes verdicts). +/// </summary> +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + DecideHoldsANormalLine(); + DecidePassThroughCases(); + DecideFlushCases(); + ReleaseKeepsOrder(); + ReleaseDropsEatenLines(); + ReleaseTimeout(); + ReleaseFlushAll(); + ReleasePrintThrows(); + FirstVerdictWins(); + PluginsAteItRule(); + MetaManagerPollShape(); + TwoThreads(); + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL CHAT HOLD TESTS PASSED." : $"{_failed} FAILED."); + return _failed == 0 ? 0 : 1; + } + + // ── the hold decision ─────────────────────────────────────────────────── + + private const long Now = 100_000; + + private static ChatHoldInputs Normal() => new( + Enabled: true, Disarmed: false, OnMainThread: true, Replaying: false, + HasText: true, Truncated: false, HasStringInfo: false, + NowMs: Now, PumpBeatMs: Now - 10, DrainBeatMs: Now - 10, HeldCount: 0); + + private static void DecideHoldsANormalLine() + { + Case("decide: a normal line is held"); + Check(HeldChatQueue.Decide(Normal()) == ChatHoldDecision.Hold, "normal line held"); + Check(HeldChatQueue.Decide(Normal() with { HeldCount = HeldChatQueue.MaxHeld - 1 }) == ChatHoldDecision.Hold, "held while under the cap"); + Check(HeldChatQueue.Decide(Normal() with { PumpBeatMs = Now - HeldChatQueue.PumpStaleMs }) == ChatHoldDecision.Hold, "pump beat exactly at the limit still holds"); + Check(HeldChatQueue.Decide(Normal() with { DrainBeatMs = Now - HeldChatQueue.DrainStaleMs }) == ChatHoldDecision.Hold, "drain beat exactly at the limit still holds"); + } + + private static void DecidePassThroughCases() + { + Case("decide: lines that print at once, held lines untouched"); + Check(HeldChatQueue.Decide(Normal() with { Replaying = true }) == ChatHoldDecision.PassThrough, "inside our own print"); + Check(HeldChatQueue.Decide(Normal() with { Replaying = true, Enabled = false }) == ChatHoldDecision.PassThrough, "inside our own print, even when switched off (never flush mid-release)"); + Check(HeldChatQueue.Decide(Normal() with { OnMainThread = false }) == ChatHoldDecision.PassThrough, "off AC's main thread"); + Check(HeldChatQueue.Decide(Normal() with { OnMainThread = false, Enabled = false }) == ChatHoldDecision.PassThrough, "off the main thread never touches the held list"); + Check(HeldChatQueue.Decide(Normal() with { HasStringInfo = true }) == ChatHoldDecision.PassThrough, "caller passed a StringInfo"); + Check(HeldChatQueue.Decide(Normal() with { Truncated = true }) == ChatHoldDecision.PassThrough, "line longer than we read"); + Check(HeldChatQueue.Decide(Normal() with { HasText = false }) == ChatHoldDecision.PassThrough, "empty line"); + } + + private static void DecideFlushCases() + { + Case("decide: holding off or unsafe flushes what is held"); + Check(HeldChatQueue.Decide(Normal() with { Enabled = false }) == ChatHoldDecision.FlushThenPassThrough, "/rc chathold off"); + Check(HeldChatQueue.Decide(Normal() with { Disarmed = true }) == ChatHoldDecision.FlushThenPassThrough, "engine teardown"); + Check(HeldChatQueue.Decide(Normal() with { PumpBeatMs = 0 }) == ChatHoldDecision.FlushThenPassThrough, "pump never ran"); + Check(HeldChatQueue.Decide(Normal() with { PumpBeatMs = Now - HeldChatQueue.PumpStaleMs - 1 }) == ChatHoldDecision.FlushThenPassThrough, "pump stalled"); + Check(HeldChatQueue.Decide(Normal() with { DrainBeatMs = 0 }) == ChatHoldDecision.FlushThenPassThrough, "drain never ran"); + Check(HeldChatQueue.Decide(Normal() with { DrainBeatMs = Now - HeldChatQueue.DrainStaleMs - 1 }) == ChatHoldDecision.FlushThenPassThrough, "drain stalled"); + Check(HeldChatQueue.Decide(Normal() with { HeldCount = HeldChatQueue.MaxHeld }) == ChatHoldDecision.FlushThenPassThrough, "too many held"); + Check(HeldChatQueue.Decide(Normal() with { Enabled = false, HasStringInfo = true }) == ChatHoldDecision.FlushThenPassThrough, "switched off wins over a StringInfo line (keeps the order)"); + } + + // ── releasing ─────────────────────────────────────────────────────────── + + private static HeldChatLine Line(string text, long at = 0) => new(text + "\n", 0, 1, new IntPtr(0x1234), at); + + private static void ReleaseKeepsOrder() + { + Case("release: oldest first, stops at the first line still waiting"); + var q = new HeldChatQueue(); + var printed = new List<string>(); + HeldChatLine a = Line("a"), b = Line("b"), c = Line("c"); + q.Add(a); q.Add(b); q.Add(c); + a.Decide(eat: false); + c.Decide(eat: false); + int n = q.Release(10, false, l => printed.Add(l.Raw)); + Check(n == 1 && printed.SequenceEqual(new[] { "a\n" }), "only a prints while b waits"); + Check(q.Count == 2, "b and c still held"); + b.Decide(eat: false); + q.Release(20, false, l => printed.Add(l.Raw)); + Check(printed.SequenceEqual(new[] { "a\n", "b\n", "c\n" }), "then b and c, in order"); + Check(q.Count == 0 && q.ShownTotal == 3 && q.HeldTotal == 3, "counters"); + Check(q.Release(30, false, l => printed.Add(l.Raw)) == 0, "empty release prints nothing"); + } + + private static void ReleaseDropsEatenLines() + { + Case("release: eaten lines never print"); + var q = new HeldChatQueue(); + var printed = new List<string>(); + HeldChatLine a = Line("a"), b = Line("quest line"), c = Line("c"); + q.Add(a); q.Add(b); q.Add(c); + a.Decide(false); b.Decide(true); c.Decide(false); + q.Release(5, false, l => printed.Add(l.Raw)); + Check(printed.SequenceEqual(new[] { "a\n", "c\n" }), "a and c print, the eaten line doesn't"); + Check(q.EatenTotal == 1 && q.ShownTotal == 2 && q.Count == 0, "counters"); + } + + private static void ReleaseTimeout() + { + Case("release: a line with no verdict prints after the timeout"); + var q = new HeldChatQueue(); + var printed = new List<string>(); + HeldChatLine a = Line("a", at: 1000), b = Line("b", at: 1100); + q.Add(a); q.Add(b); + q.Release(1000 + HeldChatQueue.HoldTimeoutMs - 1, false, l => printed.Add(l.Raw)); + Check(printed.Count == 0, "not yet"); + q.Release(1000 + HeldChatQueue.HoldTimeoutMs, false, l => printed.Add(l.Raw)); + Check(printed.SequenceEqual(new[] { "a\n" }) && q.TimedOutTotal == 1, "a prints late; b (held later) still waits"); + b.Decide(true); + q.Release(1000 + HeldChatQueue.HoldTimeoutMs + 1, false, l => printed.Add(l.Raw)); + Check(printed.Count == 1 && q.EatenTotal == 1 && q.Count == 0, "b eaten in time"); + a.Decide(true); // a verdict after the line already printed does nothing + Check(q.EatenTotal == 1 && q.Count == 0, "late verdict ignored"); + } + + private static void ReleaseFlushAll() + { + Case("release: flushAll prints everything not eaten"); + var q = new HeldChatQueue(); + var printed = new List<string>(); + HeldChatLine a = Line("a"), b = Line("b"), c = Line("c"); + q.Add(a); q.Add(b); q.Add(c); + b.Decide(true); + q.Release(0, true, l => printed.Add(l.Raw)); + Check(printed.SequenceEqual(new[] { "a\n", "c\n" }), "a and c print without a verdict, eaten b still dropped"); + Check(q.TimedOutTotal == 2 && q.EatenTotal == 1 && q.Count == 0, "counters"); + } + + private static void ReleasePrintThrows() + { + Case("release: a print that throws doesn't stop the rest"); + var q = new HeldChatQueue(); + var printed = new List<string>(); + HeldChatLine a = Line("bad"), b = Line("b"); + q.Add(a); q.Add(b); + a.Decide(false); b.Decide(false); + q.Release(0, false, l => { if (l.Raw.StartsWith("bad")) throw new InvalidOperationException(); printed.Add(l.Raw); }); + Check(printed.SequenceEqual(new[] { "b\n" }) && q.PrintFailedTotal == 1 && q.Count == 0, "b still prints"); + } + + private static void FirstVerdictWins() + { + Case("verdict: the first one wins"); + HeldChatLine a = Line("a"); + Check(a.Verdict == HeldChatLine.Pending, "starts pending"); + a.Decide(true); + a.Decide(false); + Check(a.Verdict == HeldChatLine.Eat, "eat then show stays eat"); + HeldChatLine b = Line("b"); + b.Decide(false); + b.Decide(true); + Check(b.Verdict == HeldChatLine.Show, "show then eat stays show (an overflow drop can't be undone)"); + Check(a.Raw == "a\n" && a.Unknown == 1 && a.This == new IntPtr(0x1234), "fields kept for the reprint"); + } + + private static void PluginsAteItRule() + { + Case("verdict: eat flag and plugin errors"); + Check(HeldChatQueue.PluginsAteIt(1, false), "eat set, no error: eaten"); + Check(HeldChatQueue.PluginsAteIt(-1, false), "any non-zero eat counts"); + Check(!HeldChatQueue.PluginsAteIt(0, false), "nobody ate it: shows"); + Check(!HeldChatQueue.PluginsAteIt(1, true), "a plugin threw: shows even if eaten"); + Check(!HeldChatQueue.PluginsAteIt(0, true), "a plugin threw, not eaten: shows"); + } + + // ── shaped like the real thing ────────────────────────────────────────── + + // A burst of chat with RynthAi's own /myquests reply in the middle: only the reply goes. + private static void MetaManagerPollShape() + { + Case("shape: a /myquests reply in the middle of combat text"); + var q = new HeldChatQueue(); + var printed = new List<string>(); + string[] lines = + { + "You hit the Drudge Slinker for 42 points of slashing damage!", + "blightlordlairwait1008 - 3 solves (1759190400)\"Blight Lord Lair\" -1 72000", + "stipendtimer_monthly - 2 solves (1759276800)\"Monthly stipend\" -1 2592000", + "Vessa tells you, \"hi\"", + "The Drudge Slinker hits you for 7 points of bludgeoning damage!", + }; + var held = lines.Select(t => Line(t)).ToArray(); + foreach (var h in held) q.Add(h); + // The pump: RynthAi eats the lines that parse as /myquests while its poll is in flight. + foreach (var h in held) h.Decide(eat: h.Raw.Contains(" solves (")); + q.Release(1, false, l => printed.Add(l.Raw.TrimEnd('\n'))); + Check(printed.SequenceEqual(new[] { lines[0], lines[3], lines[4] }), "combat, tell, combat print in order; the two quest lines don't"); + } + + // AC's main thread holds and releases while the pump decides on its own thread; with no + // timeouts in play every line not eaten prints exactly once, in order. + private static void TwoThreads() + { + Case("two threads: main holds/releases, pump decides"); + const int total = 20000; + var q = new HeldChatQueue(); + var toPump = new ConcurrentQueue<HeldChatLine>(); + var printed = new List<int>(); + using var done = new ManualResetEventSlim(false); + + var pump = new Thread(() => + { + int seen = 0; + while (seen < total) + { + if (toPump.TryDequeue(out var h)) + { + int n = int.Parse(h.Raw.AsSpan(0, h.Raw.Length - 1)); + h.Decide(eat: n % 7 == 3); + seen++; + } + else Thread.Yield(); + } + done.Set(); + }); + pump.Start(); + + for (int i = 0; i < total; i++) + { + var h = new HeldChatLine(i + "\n", 0, 1, IntPtr.Zero, 0); + q.Add(h); + toPump.Enqueue(h); + if ((i & 15) == 0) + q.Release(0, false, l => printed.Add(int.Parse(l.Raw.AsSpan(0, l.Raw.Length - 1)))); // clock frozen: no timeouts + } + done.Wait(); + pump.Join(); + q.Release(0, false, l => printed.Add(int.Parse(l.Raw.AsSpan(0, l.Raw.Length - 1)))); + + var expected = Enumerable.Range(0, total).Where(n => n % 7 != 3).ToList(); + Check(q.Count == 0, "nothing left held"); + Check(printed.SequenceEqual(expected), "every line not eaten printed once, in order"); + Check(q.EatenTotal == total - expected.Count && q.TimedOutTotal == 0, "counters"); + } + + // ── helpers ───────────────────────────────────────────────────────────── + + private static void Case(string name) + { + _case = name; + Console.WriteLine($"-- {name}"); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}"); + } +} diff --git a/tools/DecalBridgeCheckTests/DecalBridgeCheckTests.csproj b/tools/DecalBridgeCheckTests/DecalBridgeCheckTests.csproj new file mode 100644 index 0000000..1acc45a --- /dev/null +++ b/tools/DecalBridgeCheckTests/DecalBridgeCheckTests.csproj @@ -0,0 +1,27 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the "Check Decal bridge" logic (src\RynthCore.App\DecalBridgeCheck.cs, + compiled in): which registry view a Decal client reads its filter list from (per-user + VirtualStore copy vs machine-wide HKLM) for non-elevated / elevated / UAC-off / + manifest / run-as-administrator clients, and every check line, against a fake registry. + Never touches the real registry. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0-windows</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>DecalBridgeCheckTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.App\DecalBridgeCheck.cs" Link="App\DecalBridgeCheck.cs" /> + <Compile Include="..\..\src\RynthCore.App\RealDecalCheckHost.cs" Link="App\RealDecalCheckHost.cs" /> + <Compile Include="..\..\src\RynthCore.App\DecalBridgeRegistration.cs" Link="App\DecalBridgeRegistration.cs" /> + <Compile Include="..\..\src\RynthCore.App\DecalLocator.cs" Link="App\DecalLocator.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/DecalBridgeCheckTests/Program.cs b/tools/DecalBridgeCheckTests/Program.cs new file mode 100644 index 0000000..7793335 --- /dev/null +++ b/tools/DecalBridgeCheckTests/Program.cs @@ -0,0 +1,440 @@ +using RynthCore.App; +using static RynthCore.App.DecalBridgeCheck; + +namespace DecalBridgeCheckTests; + +/// <summary> +/// The Decal bridge check against a fake machine. The scenario that broke on a player's PC +/// (2026-10-03, release 2026.10.3.1) is "elevated client, per-user registration only": +/// Decal reads HKLM, the per-user entry is invisible, the bridge never loads. +/// </summary> +internal static class Program +{ + private static int _checks, _failed; + + private const string Agent = @"C:\Program Files (x86)\Decal 3.0\"; + private const string BridgeDir = @"C:\Games\RynthCore\DecalBridge"; + private const string AcClient = @"C:\Turbine\Asheron's Call\acclient.exe"; + private static readonly string Guid = DecalBridgeRegistration.FilterGuid; + private static readonly string VsFilters = VirtualStoreDecalPath(true, "NetworkFilters"); + private static readonly string HkFilters = MachineDecalPath("NetworkFilters"); + + private static int Main() + { + Scenario("Tom's PC: non-elevated, per-user copy with the bridge", () => + { + FakeHost h = Baseline(); + h.Set(RegRoot.User64, VsFilters, new()); + h.Set(RegRoot.User64, VsFilters + "\\" + Guid, BridgeEntry()); + MirrorStock(h, RegRoot.User64, VsFilters); + h.OwnView = BridgeEntry(); + Result r = Run(h, BridgeDir, AcClient, null); + Check(r.ClientVirtualized, "client virtualized"); + Check(r.ReadsPerUserCopy, "Decal reads the per-user copy"); + Check(r.BridgeVisibleToDecal && !r.Blocking, "bridge visible, not blocking"); + Check(Has(r, Level.Ok, "Read back as AC will see it: bridge listed"), "live read-back agrees"); + Check(!Has(r, Level.Warn, "Hidden from AC"), "no hidden filters (all mirrored)"); + }); + + Scenario("THE PLAYER CASE: launcher (so AC) elevated, bridge only in the per-user copy", () => + { + FakeHost h = Baseline(); + h.LauncherElevated = true; + h.LauncherVirtualized = false; + h.Set(RegRoot.User64, VsFilters, new()); + h.Set(RegRoot.User64, VsFilters + "\\" + Guid, BridgeEntry()); + h.OwnView = null; // the elevated view is the real HKLM: no bridge there + Result r = Run(h, BridgeDir, AcClient, null); + Check(!r.ClientVirtualized, "client not virtualized"); + Check(r.ClientReason.Contains("administrator"), "reason names administrator"); + Check(!r.ReadsPerUserCopy, "Decal reads HKLM"); + Check(r.FiltersReadFrom.Contains(@"HKLM\SOFTWARE\WOW6432Node\Decal\NetworkFilters"), "describes the WOW6432Node key"); + Check(r.Blocking && !r.BridgeVisibleToDecal, "blocking"); + Check(r.NeedsMachineWideRegistration, "needs the machine-wide registration (admin)"); + Check(Has(r, Level.Info, "per-user registration exists, but this AC client doesn't read it"), "explains the invisible per-user entry"); + Check(Has(r, Level.Ok, "Read back as AC will see it: bridge not listed"), "live read-back agrees (not listed)"); + }); + + // ── after the installer / an update (installer\RynthCore.iss RegisterDecalBridge) ── + + Scenario("installer plan: machine always; per-user only into an existing copy", () => + { + FakeHost h = Baseline(); + Check(PlanInstall(h) == (true, false), "no copy: machine only (a copy is never created)"); + h.Set(RegRoot.User64, VsFilters, new()); + Check(PlanInstall(h) == (true, true), "copy exists: machine + per-user"); + h.Remove(RegRoot.Machine32, MachineDecalPath("Agent")); + Check(PlanInstall(h) == (false, false), "no Decal: nothing"); + }); + + foreach (bool elevated in new[] { false, true }) + foreach (bool uacOff in new[] { false, true }) + { + string who = (elevated ? "elevated" : "non-elevated") + (uacOff ? ", UAC off" : ""); + Scenario($"installer wrote both (per-user copy existed): {who} client loads the bridge", () => + { + FakeHost h = InstalledBoth(withCopy: true, elevated, uacOff); + Result r = Run(h, BridgeDir, AcClient, null); + Check(r.BridgeVisibleToDecal && !r.Blocking, "visible, not blocking"); + Check(r.ReadsPerUserCopy == (!elevated && !uacOff), "reads the copy only when virtualized"); + }); + Scenario($"installer wrote machine only (no per-user copy): {who} client loads the bridge", () => + { + FakeHost h = InstalledBoth(withCopy: false, elevated, uacOff); + Result r = Run(h, BridgeDir, AcClient, null); + Check(r.BridgeVisibleToDecal && !r.Blocking && !r.ReadsPerUserCopy, "visible through HKLM, not blocking"); + }); + } + + Scenario("negative control: copy existed but the per-user half didn't run", () => + { + FakeHost h = InstalledBoth(withCopy: true, elevated: false, uacOff: false); + h.Remove(RegRoot.User64, VsFilters + "\\" + Guid); + h.OwnView = null; + Result r = Run(h, BridgeDir, AcClient, null); + Check(r.Blocking && r.ReadsPerUserCopy, "the copy hides the machine entry: why the per-user half is needed"); + }); + + Scenario("elevated, machine-wide entry present", () => + { + FakeHost h = Baseline(); + h.LauncherElevated = true; + h.LauncherVirtualized = false; + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, BridgeEntry()); + h.OwnView = BridgeEntry(); + Result r = Run(h, BridgeDir, AcClient, null); + Check(!r.Blocking && r.BridgeVisibleToDecal && !r.ReadsPerUserCopy, "OK through HKLM"); + }); + + Scenario("non-elevated, no per-user copy, nothing registered", () => + { + FakeHost h = Baseline(); + h.OwnView = null; + Result r = Run(h, BridgeDir, AcClient, null); + Check(r.ClientVirtualized && !r.ReadsPerUserCopy, "virtualized client reads HKLM when no copy exists"); + Check(r.Blocking && r.NeedsMachineWideRegistration, "blocking; the place read is HKLM"); + }); + + Scenario("non-elevated, per-user copy exists without the bridge, HKLM has it", () => + { + FakeHost h = Baseline(); + h.Set(RegRoot.User64, VsFilters, new()); + h.Set(RegRoot.User64, VsFilters + "\\{108ED493-48AD-42A6-AADC-EF773E4F185A}", new() { [""] = "Virindi AutomaticUpdatesFilter", ["Enabled"] = 1 }); + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, BridgeEntry()); + h.OwnView = null; + Result r = Run(h, BridgeDir, AcClient, null); + Check(r.ReadsPerUserCopy && r.Blocking && !r.NeedsMachineWideRegistration, "per-user copy hides the HKLM entry; fixable per-user"); + Check(Has(r, Level.Info, "machine-wide entry exists, but your per-user copy hides it"), "explains the hidden machine entry"); + Check(Has(r, Level.Warn, "World Object Filter"), "warns that World Object Filter is hidden"); + }); + + Scenario("UAC off", () => + { + FakeHost h = Baseline(); + h.Set(RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", new() { ["EnableLUA"] = 0, ["EnableVirtualization"] = 1 }); + h.LauncherVirtualized = false; + h.Set(RegRoot.User64, VsFilters, new()); + h.Set(RegRoot.User64, VsFilters + "\\" + Guid, BridgeEntry()); + Result r = Run(h, BridgeDir, AcClient, null); + Check(!r.ClientVirtualized && r.ClientReason.Contains("UAC is turned off"), "UAC off: not virtualized"); + Check(r.Blocking && r.NeedsMachineWideRegistration, "per-user registration is not enough"); + }); + + Scenario("virtualization off by policy", () => + { + FakeHost h = Baseline(); + h.Set(RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", new() { ["EnableLUA"] = 1, ["EnableVirtualization"] = 0 }); + Check(!PredictClientVirtualized(h, AcClient, out string why) && why.Contains("EnableVirtualization=0"), "policy: not virtualized"); + }); + + Scenario("acclient.exe with a manifest", () => + { + FakeHost h = Baseline(); + h.Levels[AcClient] = "asInvoker"; + Check(!PredictClientVirtualized(h, AcClient, out string why) && why.Contains("asInvoker"), "manifest: not virtualized"); + Check(PredictClientVirtualized(h, @"C:\Other\acclient.exe", out _), "a different exe without manifest is virtualized"); + }); + + Scenario("acclient.exe set to Run as administrator, Decal's COM class only per-user", () => + { + FakeHost h = Baseline(); + h.Set(RegRoot.User64, @"Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers", new() { [AcClient.ToUpperInvariant()] = "~ RUNASADMIN" }); + h.Remove(RegRoot.Machine32, @"SOFTWARE\Classes\CLSID\" + SurrogateClsid + @"\InprocServer32"); + h.Set(RegRoot.User32, @"Software\Classes\CLSID\" + SurrogateClsid + @"\InprocServer32", ComEntry()); + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, BridgeEntry()); + Result r = Run(h, BridgeDir, AcClient, null); + Check(!r.ClientVirtualized && r.ClientReason.Contains("RUNASADMIN"), "RUNASADMIN: not virtualized"); + Check(r.BridgeVisibleToDecal, "bridge visible in HKLM"); + Check(Has(r, Level.Fail, "ignores per-user COM classes"), "per-user-only COM class fails for an elevated client"); + }); + + Scenario("non-elevated client resolves a per-user COM class", () => + { + FakeHost h = Baseline(); + h.Remove(RegRoot.Machine32, @"SOFTWARE\Classes\CLSID\" + SurrogateClsid + @"\InprocServer32"); + h.Set(RegRoot.User32, @"Software\Classes\CLSID\" + SurrogateClsid + @"\InprocServer32", ComEntry()); + Check(SurrogateComProblem(h, clientElevated: false, out string where) == null && where == "per-user", "per-user COM class OK"); + }); + + Scenario("COM class missing / pointing at a missing file", () => + { + FakeHost h = Baseline(); + h.Remove(RegRoot.Machine32, @"SOFTWARE\Classes\CLSID\" + SurrogateClsid + @"\InprocServer32"); + Check(SurrogateComProblem(h, false, out _)?.Contains("not registered") == true, "missing COM class"); + var com = ComEntry(); + com["CodeBase"] = @"file:///D:\Gone\Decal.Adapter.dll"; + h.Set(RegRoot.Machine32, @"SOFTWARE\Classes\CLSID\" + SurrogateClsid + @"\InprocServer32", com); + Check(SurrogateComProblem(h, false, out _)?.Contains("missing file") == true, "CodeBase to a missing file"); + }); + + Scenario("entry problems", () => + { + FakeHost h = Baseline(); + var disabled = BridgeEntry(); disabled["Enabled"] = 0; + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, disabled); + Check(EntryProblem(h, RegRoot.Machine32, HkFilters + "\\" + Guid, out _)?.Contains("disabled") == true, "disabled entry"); + var moved = BridgeEntry(); moved["Path"] = @"D:\Old\DecalBridge"; + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, moved); + Check(EntryProblem(h, RegRoot.Machine32, HkFilters + "\\" + Guid, out _)?.Contains("missing") == true, "DLL missing at the registered path"); + var foreign = BridgeEntry(); foreign["Object"] = "Someone.Else"; + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, foreign); + Check(EntryProblem(h, RegRoot.Machine32, HkFilters + "\\" + Guid, out _)?.Contains("another filter") == true, "foreign entry"); + var badSur = BridgeEntry(); badSur["Surrogate"] = "{00000000-0000-0000-0000-000000000000}"; + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, badSur); + Check(EntryProblem(h, RegRoot.Machine32, HkFilters + "\\" + Guid, out _)?.Contains("Surrogate") == true, "wrong surrogate"); + }); + + Scenario("Decal older than the bridge's reference", () => + { + FakeHost h = Baseline(); + h.AssemblyVersions[Agent + "Decal.Adapter.dll"] = new Version(2, 9, 7, 5); + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, BridgeEntry()); + Result r = Run(h, BridgeDir, AcClient, null); + Check(r.Blocking && Has(r, Level.Fail, "older than the 2.9.8.3"), "old Decal blocks"); + }); + + Scenario("Decal's surrogate disabled / not listed in the per-user Surrogates copy", () => + { + FakeHost h = Baseline(); + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, BridgeEntry()); + h.Set(RegRoot.Machine32, MachineDecalPath("Surrogates") + "\\" + SurrogateClsid, new() { [""] = "Decal.Adapter Surrogate", ["Enabled"] = 0 }); + Check(Has(Run(h, BridgeDir, AcClient, null), Level.Fail, "disabled in Decal"), "disabled surrogate"); + h.Set(RegRoot.Machine32, MachineDecalPath("Surrogates") + "\\" + SurrogateClsid, new() { [""] = "Decal.Adapter Surrogate", ["Enabled"] = 1 }); + h.Set(RegRoot.User64, VirtualStoreDecalPath(true, "Surrogates"), new()); + Check(Has(Run(h, BridgeDir, AcClient, null), Level.Fail, "surrogate is not listed"), "a per-user Surrogates copy without it hides it"); + }); + + Scenario("engine.json DecalBridge Off", () => + { + FakeHost h = Baseline(); + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, BridgeEntry()); + h.Files[@"C:\cfg\engine.json"] = "{ \"DecalBridge\": \"Off\", \"DecalInGameImGui\": false }"; + Result r = Run(h, BridgeDir, AcClient, @"C:\cfg\engine.json"); + Check(Has(r, Level.Fail, "\"DecalBridge\": Off"), "DecalBridge Off fails"); + Check(Has(r, Level.Warn, "DecalInGameImGui"), "DecalInGameImGui false warns"); + }); + + Scenario("live view disagrees with the predicted place", () => + { + FakeHost h = Baseline(); + h.Set(RegRoot.User64, VsFilters, new()); + h.Set(RegRoot.User64, VsFilters + "\\" + Guid, BridgeEntry()); + h.OwnView = null; + Result r = Run(h, BridgeDir, AcClient, null); + Check(r.Blocking && Has(r, Level.Fail, "bridge NOT listed"), "disagreement fails"); + }); + + Scenario("launcher virtualized, client not: no live read-back", () => + { + FakeHost h = Baseline(); + h.Levels[AcClient] = "asInvoker"; + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, BridgeEntry()); + h.OwnView = null; + Result r = Run(h, BridgeDir, AcClient, null); + Check(!r.Blocking && Has(r, Level.Info, "Not read back live"), "skips the live read when views differ"); + }); + + Scenario("bridge DLL downloaded mark, .NET older than 4.8", () => + { + FakeHost h = Baseline(); + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, BridgeEntry()); + h.Zoned.Add(BridgeDir + "\\" + DecalBridgeRegistration.AssemblyFile); + h.OwnView = BridgeEntry(); + h.Set(RegRoot.Machine32, @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", new() { ["Release"] = 461814 }); + Result r = Run(h, BridgeDir, AcClient, null); + Check(Has(r, Level.Warn, "downloaded from the internet") && Has(r, Level.Warn, "4.8"), "both warn"); + Check(!r.Blocking, "warnings don't block"); + }); + + Scenario("Decal not installed", () => + { + FakeHost h = Baseline(); + h.Remove(RegRoot.Machine32, MachineDecalPath("Agent")); + Result r = Run(h, BridgeDir, AcClient, null); + Check(r.Blocking && !r.DecalInstalled && r.Lines.Count == 1, "stops at 'not installed'"); + }); + + Scenario("32-bit Windows paths", () => + { + Check(VirtualStoreDecalPath(false, "NetworkFilters") == @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\Decal\NetworkFilters", "no WOW6432Node in the copy's path"); + Check(Describe(false, RegRoot.Machine32, HkFilters) == @"HKLM\SOFTWARE\Decal\NetworkFilters", "no WOW6432Node in the HKLM description"); + }); + + Scenario("manifest level parsing", () => + { + Check(RealDecalCheckHost.LevelIn("<requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>") == "asInvoker", "double quotes"); + Check(RealDecalCheckHost.LevelIn("<requestedExecutionLevel uiAccess='false' level='requireAdministrator' />") == "requireAdministrator", "single quotes, other order"); + Check(RealDecalCheckHost.LevelIn("<assembly><description>x</description></assembly>") == null, "no element"); + }); + + Console.WriteLine(); + Console.WriteLine(_failed == 0 ? $"PASS: {_checks} checks" : $"FAIL: {_failed} of {_checks} checks failed"); + return _failed == 0 ? 0 : 1; + } + + // ── machine ───────────────────────────────────────────────────────────── + + private static Dictionary<string, object> BridgeEntry() => new() + { + [""] = DecalBridgeRegistration.FilterName, + ["Enabled"] = 1, + ["Assembly"] = DecalBridgeRegistration.AssemblyFile, + ["Path"] = BridgeDir, + ["Object"] = DecalBridgeRegistration.FilterObject, + ["Surrogate"] = SurrogateClsid, + }; + + private static Dictionary<string, object> ComEntry() => new() + { + [""] = "mscoree.dll", + ["Class"] = "Decal.Adapter.Surrogate", + ["Assembly"] = "Decal.Adapter, Version=2.9.8.3, Culture=neutral, PublicKeyToken=bd1c8ce002ce221e", + ["RuntimeVersion"] = "v4.0.30319", + ["CodeBase"] = @"file:///C:\Program Files (x86)\Decal 3.0\Decal.Adapter.dll", + }; + + private static readonly (string Id, string Name)[] Stock = + { + ("{53092D1B-F0B0-46FF-BF11-8F031EC9B137}", "World Object Filter"), + ("{34239EAD-6317-4c40-A405-193BA5232DD8}", "Echo Filter 2"), + }; + + /// <summary>A healthy 64-bit machine with Decal 2.9.8.3, UAC on, a non-elevated launcher, nothing registered.</summary> + private static FakeHost Baseline() + { + var h = new FakeHost(); + h.Set(RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", new() { ["EnableLUA"] = 1, ["EnableVirtualization"] = 1 }); + h.Set(RegRoot.Machine32, MachineDecalPath("Agent"), new() { ["AgentPath"] = Agent, ["PortalPath"] = @"C:\Turbine\Asheron's Call" }); + h.Set(RegRoot.Machine32, HkFilters, new()); + foreach (var f in Stock) + h.Set(RegRoot.Machine32, HkFilters + "\\" + f.Id, new() { [""] = f.Name, ["Enabled"] = 1 }); + h.Set(RegRoot.Machine32, MachineDecalPath("Surrogates") + "\\" + SurrogateClsid, new() { [""] = "Decal.Adapter Surrogate", ["Enabled"] = 1 }); + h.Set(RegRoot.Machine32, @"SOFTWARE\Classes\CLSID\" + SurrogateClsid + @"\InprocServer32", ComEntry()); + h.Set(RegRoot.Machine32, @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", new() { ["Release"] = 533325 }); + h.Files[Agent + "Inject.dll"] = ""; + h.Files[Agent + "Decal.Adapter.dll"] = ""; + h.Files[@"C:\Program Files (x86)\Decal 3.0\Decal.Adapter.dll"] = ""; + h.Files[BridgeDir + "\\" + DecalBridgeRegistration.AssemblyFile] = ""; + h.Files[AcClient] = ""; + h.AssemblyVersions[Agent + "Decal.Adapter.dll"] = new Version(2, 9, 8, 3); + h.ReferenceVersions[BridgeDir + "\\" + DecalBridgeRegistration.AssemblyFile] = new Version(2, 9, 8, 3); + return h; + } + + /// <summary>The machine after the installer: HKLM entry, plus the per-user entry when a copy existed.</summary> + private static FakeHost InstalledBoth(bool withCopy, bool elevated, bool uacOff) + { + FakeHost h = Baseline(); + h.Set(RegRoot.Machine32, HkFilters + "\\" + Guid, BridgeEntry()); + if (withCopy) + { + h.Set(RegRoot.User64, VsFilters, new()); + MirrorStock(h, RegRoot.User64, VsFilters); + h.Set(RegRoot.User64, VsFilters + "\\" + Guid, BridgeEntry()); + } + if (uacOff) + h.Set(RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", new() { ["EnableLUA"] = 0, ["EnableVirtualization"] = 1 }); + h.LauncherElevated = elevated; + h.LauncherVirtualized = !elevated && !uacOff; + h.OwnView = BridgeEntry(); // both views list it + return h; + } + + private static void MirrorStock(FakeHost h, RegRoot root, string path) + { + foreach (var f in Stock) + h.Set(root, path + "\\" + f.Id, new() { [""] = f.Name, ["Enabled"] = 1 }); + } + + // ── harness ───────────────────────────────────────────────────────────── + + private static bool Has(Result r, Level level, string text) => + r.Lines.Any(l => l.Level == level && l.Text.Contains(text, StringComparison.Ordinal)); + + private static void Scenario(string name, Action body) + { + Console.WriteLine($"-- {name}"); + try { body(); } + catch (Exception ex) { _checks++; _failed++; Console.WriteLine($" FAIL threw {ex}"); } + } + + private static void Check(bool ok, string what) + { + _checks++; + if (!ok) _failed++; + Console.WriteLine($" {(ok ? "ok " : "FAIL")} {what}"); + } +} + +internal sealed class FakeHost : IDecalCheckHost +{ + private readonly Dictionary<(RegRoot, string), Dictionary<string, object>> _keys = new(new KeyComparer()); + public Dictionary<string, string> Files { get; } = new(StringComparer.OrdinalIgnoreCase); + public HashSet<string> Zoned { get; } = new(StringComparer.OrdinalIgnoreCase); + public Dictionary<string, string?> Levels { get; } = new(StringComparer.OrdinalIgnoreCase); + public Dictionary<string, Version> AssemblyVersions { get; } = new(StringComparer.OrdinalIgnoreCase); + public Dictionary<string, Version> ReferenceVersions { get; } = new(StringComparer.OrdinalIgnoreCase); + public Dictionary<string, object>? OwnView { get; set; } + + public bool Is64BitOs { get; set; } = true; + public bool LauncherElevated { get; set; } + public bool LauncherVirtualized { get; set; } = true; + + public void Set(RegRoot root, string path, Dictionary<string, object> values) => _keys[(root, path)] = values; + public void Remove(RegRoot root, string path) => _keys.Remove((root, path)); + + public IRegKey? OpenReal(RegRoot root, string subKey) + { + bool exists = _keys.TryGetValue((root, subKey), out var values); + var subs = _keys.Keys + .Where(k => k.Item1 == root && k.Item2.StartsWith(subKey + "\\", StringComparison.OrdinalIgnoreCase)) + .Select(k => k.Item2.Substring(subKey.Length + 1).Split('\\')[0]) + .Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + if (!exists && subs.Count == 0) return null; + return Snap(values, subs); + } + + public IRegKey? OpenOwnViewMachine32(string subKey) => OwnView == null ? null : Snap(OwnView, new List<string>()); + + private static RegSnapshot Snap(Dictionary<string, object>? values, List<string> subs) + { + var s = new RegSnapshot(); + if (values != null) foreach (var kv in values) s.Values[kv.Key] = kv.Value; + s.SubKeys.AddRange(subs); + return s; + } + + public bool FileExists(string path) => Files.ContainsKey(path); + public bool HasZoneIdentifier(string path) => Zoned.Contains(path); + public Version? AssemblyVersionOf(string path) => AssemblyVersions.TryGetValue(path, out var v) ? v : null; + public Version? ReferenceVersionOf(string assemblyPath, string referenceName) => + referenceName == "Decal.Adapter" && ReferenceVersions.TryGetValue(assemblyPath, out var v) ? v : null; + public string? ExecutionLevelOf(string exePath) => Levels.TryGetValue(exePath, out var l) ? l : null; + public string? ReadTextFile(string path) => Files.TryGetValue(path, out var t) ? t : null; + + private sealed class KeyComparer : IEqualityComparer<(RegRoot, string)> + { + public bool Equals((RegRoot, string) a, (RegRoot, string) b) => a.Item1 == b.Item1 && string.Equals(a.Item2, b.Item2, StringComparison.OrdinalIgnoreCase); + public int GetHashCode((RegRoot, string) k) => HashCode.Combine(k.Item1, StringComparer.OrdinalIgnoreCase.GetHashCode(k.Item2)); + } +} diff --git a/tools/DecalBridgeProtocolTests/DecalBridgeProtocolTests.csproj b/tools/DecalBridgeProtocolTests/DecalBridgeProtocolTests.csproj new file mode 100644 index 0000000..0312b55 --- /dev/null +++ b/tools/DecalBridgeProtocolTests/DecalBridgeProtocolTests.csproj @@ -0,0 +1,25 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the Decal bridge's shared-memory protocol (src\RynthCore.DecalBridge\ + BridgeProtocol.cs, compiled in - the same file the engine and the bridge link): both + rings, wrap-around, full rings, the want mask, the version check and resync after a + corrupt record. Two channels on a made-up pid play the bridge and the engine. + Nothing native: no AC, no Decal. See docs\DECAL_BRIDGE_PLAN.md. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0-windows</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>DecalBridgeProtocolTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.DecalBridge\BridgeProtocol.cs" Link="Bridge\BridgeProtocol.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/DecalBridgeProtocolTests/Program.cs b/tools/DecalBridgeProtocolTests/Program.cs new file mode 100644 index 0000000..ad16cc2 --- /dev/null +++ b/tools/DecalBridgeProtocolTests/Program.cs @@ -0,0 +1,272 @@ +using RynthCore.DecalBridge; + +namespace DecalBridgeProtocolTests; + +/// <summary> +/// The bridge (producer of events, consumer of commands) and the engine (the reverse) each +/// open their own view of one mapping, as in a client; every record is checked on arrival. +/// </summary> +internal static unsafe class Program +{ + private static int _checks, _failed; + private static string _case = ""; + private static int _pid = 0x7F000000 + Environment.ProcessId % 0x10000; // not a real client's pid + + private static int Main() + { + Run("hello and the want mask", WantMask); + Run("chat events in order", ChatInOrder); + Run("event ring wrap-around", EventWrap); + Run("event ring full, then recovers", EventFull); + Run("command ring round trip + wrap", Commands); + Run("oversized records are refused", Oversized); + Run("another protocol version is not Valid", VersionMismatch); + Run("corrupt record: reader resyncs at the writer", CorruptResync); + Run("a second engine generation continues where the first stopped", GenerationHandOff); + Run("v2 header fields (Decal device) fit and reach the engine", HeaderFields); + Console.WriteLine(_failed == 0 ? $"PASS: {_checks} checks" : $"FAIL: {_failed} of {_checks} checks"); + return _failed == 0 ? 0 : 1; + } + + private static void Run(string name, Action test) + { + _case = name; + _pid++; // fresh mapping per case + try { test(); } + catch (Exception ex) { Check(false, $"threw {ex.GetType().Name}: {ex.Message}"); } + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" [{_case}] FAILED: {what}"); + } + + private sealed record Rec(BridgeRecordKind Kind, uint A0, uint A1, byte[] Payload) + { + public string Text => System.Text.Encoding.Unicode.GetString(Payload); + } + + private static List<Rec> DrainAll(BridgeChannel ch, bool commands = false, int max = int.MaxValue) + { + var got = new List<Rec>(); + BridgeChannel.RecordHandler h = (k, a0, a1, p, n) => + { + var b = new byte[n]; + for (int i = 0; i < n; i++) b[i] = p[i]; + got.Add(new Rec(k, a0, a1, b)); + }; + if (commands) ch.DrainCommands(h, max); else ch.Drain(h, max); + return got; + } + + private static void Want(BridgeChannel engine, params BridgeRecordKind[] kinds) + { + uint m = 0; + foreach (var k in kinds) m |= BridgeLayout.Bit(k); + engine.WriteInt(BridgeLayout.OffWantMask, unchecked((int)m)); + } + + private static void WantMask() + { + using var bridge = BridgeChannel.OpenOrCreate(_pid); + using var engine = BridgeChannel.OpenOrCreate(_pid); + Check(bridge.Valid && engine.Valid, "both views valid"); + Check(BridgeChannel.Exists(_pid), "Exists sees the mapping"); + Check(bridge.WriteString(BridgeRecordKind.Hello, BridgeLayout.Version, 0, "hi"), "hello always goes"); + Check(!bridge.WriteString(BridgeRecordKind.ChatText, 1, 0, "unwanted"), "chat refused with an empty mask"); + Check(!bridge.Write(BridgeRecordKind.ServerMessage, 0xF7B0, 0, null, 0), "server message refused with an empty mask"); + Want(engine, BridgeRecordKind.ChatText); + Check(bridge.WriteString(BridgeRecordKind.ChatText, 1, 0, "wanted"), "chat accepted once wanted"); + Check(!bridge.Write(BridgeRecordKind.CreateObject, 5, 0, null, 0), "create still refused"); + var got = DrainAll(engine); + Check(got.Count == 2 && got[0].Kind == BridgeRecordKind.Hello && got[1].Text == "wanted", $"drained hello + chat ({got.Count})"); + Check(engine.ReadLong(BridgeLayout.OffDropped) == 0, "refused-by-mask is not counted as dropped"); + } + + private static void ChatInOrder() + { + using var bridge = BridgeChannel.OpenOrCreate(_pid); + using var engine = BridgeChannel.OpenOrCreate(_pid); + Want(engine, BridgeRecordKind.ChatText, BridgeRecordKind.ChatBarEnter); + string[] lines = { "", "a", "ab", "abc", "Welcome to Asheron's Call\n", new string('x', 1000), "ünïcödé ✓" }; + for (int i = 0; i < lines.Length; i++) + Check(bridge.WriteString(i % 2 == 0 ? BridgeRecordKind.ChatText : BridgeRecordKind.ChatBarEnter, (uint)i, 7, lines[i]), $"write {i}"); + var got = DrainAll(engine); + Check(got.Count == lines.Length, $"count {got.Count}"); + for (int i = 0; i < Math.Min(got.Count, lines.Length); i++) + Check(got[i].A0 == i && got[i].A1 == 7 && got[i].Text == lines[i], $"record {i} ('{got[i].Text}')"); + Check(DrainAll(engine).Count == 0, "nothing left"); + Check(bridge.ReadLong(BridgeLayout.OffRecords) == lines.Length, "records counter"); + } + + private static void EventWrap() + { + using var bridge = BridgeChannel.OpenOrCreate(_pid); + using var engine = BridgeChannel.OpenOrCreate(_pid); + Want(engine, BridgeRecordKind.ServerMessage); + var rnd = new Random(1234); + uint next = 0, expect = 0; + long total = 0; + bool orderOk = true, contentOk = true; + // ~3x the ring through it, drained in uneven bites so the writer wraps at odd offsets. + while (total < 3L * BridgeLayout.EventRingSize) + { + int burst = rnd.Next(1, 60); + for (int i = 0; i < burst; i++) + { + int len = rnd.Next(0, 9000); + var data = new byte[len]; + for (int j = 0; j < len; j++) data[j] = (byte)(next + j); + if (!bridge.WriteBytes(BridgeRecordKind.ServerMessage, next, (uint)len, data)) + break; + next++; + total += len + 16; + } + foreach (var r in DrainAll(engine, max: rnd.Next(1, 80))) + { + if (r.A0 != expect) orderOk = false; + if (r.Payload.Length != r.A1) contentOk = false; + for (int j = 0; j < r.Payload.Length && contentOk; j++) + if (r.Payload[j] != (byte)(r.A0 + j)) contentOk = false; + expect++; + } + } + foreach (var r in DrainAll(engine)) { if (r.A0 != expect) orderOk = false; expect++; } + Check(orderOk, "sequence in order across wraps"); + Check(contentOk, "payload bytes intact across wraps"); + Check(expect == next, $"every record arrived ({expect}/{next})"); + Check(bridge.ReadLong(BridgeLayout.OffDropped) == 0, "nothing dropped while drained"); + } + + private static void EventFull() + { + using var bridge = BridgeChannel.OpenOrCreate(_pid); + using var engine = BridgeChannel.OpenOrCreate(_pid); + Want(engine, BridgeRecordKind.ServerMessage); + var data = new byte[200 * 1024]; + int written = 0; + while (bridge.WriteBytes(BridgeRecordKind.ServerMessage, (uint)written, 0, data)) written++; + Check(written == BridgeLayout.EventRingSize / (data.Length + 16), $"filled with {written} records"); + Check(bridge.ReadLong(BridgeLayout.OffDropped) == 1, "one drop counted"); + var got = DrainAll(engine); + Check(got.Count == written, $"all {written} drained ({got.Count})"); + Check(bridge.WriteBytes(BridgeRecordKind.ServerMessage, 999, 0, data), "writes again after the drain"); + got = DrainAll(engine); + Check(got.Count == 1 && got[0].A0 == 999, "the new record arrives"); + } + + private static void Commands() + { + using var bridge = BridgeChannel.OpenOrCreate(_pid); + using var engine = BridgeChannel.OpenOrCreate(_pid); + Check(!bridge.HasCommands, "empty at start"); + Check(engine.WriteCommand(BridgeRecordKind.CmdInvokeChatParser, 0, 0, "/loc"), "chat command"); + Check(engine.WriteCommand(BridgeRecordKind.CmdSalvagePanelAdd, 0x80000123, 0, null), "salvage add"); + Check(engine.WriteCommand(BridgeRecordKind.CmdSalvagePanelSalvage, 0, 0, null), "salvage go"); + Check(bridge.HasCommands, "bridge sees commands"); + var got = DrainAll(bridge, commands: true); + Check(got.Count == 3 && got[0].Text == "/loc" && got[1].A0 == 0x80000123 && got[2].Kind == BridgeRecordKind.CmdSalvagePanelSalvage, "commands in order"); + Check(bridge.ReadLong(BridgeLayout.OffCmdDone) == 3, "done counter"); + Check(!bridge.HasCommands, "empty after drain"); + // The events ring is untouched by commands. + Check(DrainAll(engine).Count == 0, "no command leaks into the event ring"); + // Wrap the 64 KB command ring many times. + int sent = 0, seen = 0; + bool ok = true; + for (int round = 0; round < 400; round++) + { + for (int i = 0; i < 7; i++) + if (engine.WriteCommand(BridgeRecordKind.CmdInvokeChatParser, (uint)sent, 0, "/tell Someone " + new string('z', (sent * 37) % 900))) sent++; + foreach (var r in DrainAll(bridge, commands: true)) + { + if (r.A0 != seen || !r.Text.StartsWith("/tell Someone ")) ok = false; + seen++; + } + } + Check(ok && seen == sent && sent == 2800, $"command wrap ({seen}/{sent})"); + // Full command ring: counted as dropped, never blocks. + int n = 0; + while (engine.WriteCommand(BridgeRecordKind.CmdInvokeChatParser, 0, 0, new string('q', 4000))) n++; + Check(n > 0 && engine.ReadLong(BridgeLayout.OffCmdDropped) == 1, $"full command ring drops ({n} fit)"); + } + + private static void Oversized() + { + using var bridge = BridgeChannel.OpenOrCreate(_pid); + using var engine = BridgeChannel.OpenOrCreate(_pid); + Want(engine, BridgeRecordKind.ServerMessage); + Check(!bridge.WriteBytes(BridgeRecordKind.ServerMessage, 1, 0, new byte[BridgeLayout.MaxRecord + 1]), "event over MaxRecord refused"); + Check(!engine.WriteCommand(BridgeRecordKind.CmdInvokeChatParser, 0, 0, new string('x', BridgeLayout.CommandRingSize)), "command over a quarter of its ring refused"); + Check(bridge.WriteBytes(BridgeRecordKind.ServerMessage, 2, 0, new byte[10]), "a normal one still goes"); + var got = DrainAll(engine); + Check(got.Count == 1 && got[0].A0 == 2, "only the normal one arrives"); + } + + private static void VersionMismatch() + { + using var older = BridgeChannel.OpenOrCreate(_pid); + older.WriteInt(BridgeLayout.OffVersion, 1); // a version-1 (spike) side created it + using var newer = BridgeChannel.OpenOrCreate(_pid); + Check(!newer.Valid, "version 1 mapping is not Valid for version 2"); + } + + private static void CorruptResync() + { + using var bridge = BridgeChannel.OpenOrCreate(_pid); + using var engine = BridgeChannel.OpenOrCreate(_pid); + Want(engine, BridgeRecordKind.ChatText); + bridge.WriteString(BridgeRecordKind.ChatText, 1, 0, "one"); + bridge.WriteString(BridgeRecordKind.ChatText, 2, 0, "two"); + // Stomp the second record's length field (header + command ring + first record of 24 bytes). + byte* ring = engine.Header + BridgeLayout.HeaderSize + BridgeLayout.CommandRingSize; + *(int*)(ring + 24) = 3; + var got = DrainAll(engine); + Check(got.Count == 1 && got[0].Text == "one", "first record read, corrupt one skipped"); + Check(engine.ReadLong(BridgeLayout.OffReadPos) == engine.ReadLong(BridgeLayout.OffWritePos), "reader at the writer"); + bridge.WriteString(BridgeRecordKind.ChatText, 3, 0, "three"); + got = DrainAll(engine); + Check(got.Count == 1 && got[0].Text == "three", "later records flow again"); + } + + private static void GenerationHandOff() + { + using var bridge = BridgeChannel.OpenOrCreate(_pid); + var gen1 = BridgeChannel.OpenOrCreate(_pid); + Want(gen1, BridgeRecordKind.ChatText); + bridge.WriteString(BridgeRecordKind.ChatText, 1, 0, "before reload"); + Check(DrainAll(gen1).Count == 1, "gen 1 reads"); + bridge.WriteString(BridgeRecordKind.ChatText, 2, 0, "during reload"); + gen1.Dispose(); // generation unloads; the bridge keeps the mapping + using var gen2 = BridgeChannel.OpenOrCreate(_pid); + Check(gen2.Valid, "gen 2 attaches to the same mapping"); + var got = DrainAll(gen2); + Check(got.Count == 1 && got[0].Text == "during reload", "gen 2 gets what arrived in between, nothing twice"); + } + + // The header fields added to v2 (the device Decal renders with, for DecalInGameImGui): + // inside the header, clear of every other field and of the prefix area, and a value the + // bridge writes is what the engine reads. + private static void HeaderFields() + { + int[] ints = { BridgeLayout.OffMagic, BridgeLayout.OffVersion, BridgeLayout.OffBridgeState, BridgeLayout.OffBridgeBeats, + BridgeLayout.OffEngineAttached, BridgeLayout.OffEngineGeneration, BridgeLayout.OffBridgePid, BridgeLayout.OffReplayRequest, + BridgeLayout.OffReplayDone, BridgeLayout.OffWantMask, BridgeLayout.OffD3DDevice, BridgeLayout.OffDecalHwnd }; + int[] longs = { BridgeLayout.OffWritePos, BridgeLayout.OffReadPos, BridgeLayout.OffDropped, BridgeLayout.OffRecords, + BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos, BridgeLayout.OffCmdDropped, BridgeLayout.OffCmdDone }; + var used = new System.Collections.Generic.HashSet<int>(); + bool overlap = false; + foreach (int o in ints) for (int b = 0; b < 4; b++) overlap |= !used.Add(o + b); + foreach (int o in longs) for (int b = 0; b < 8; b++) overlap |= !used.Add(o + b); + Check(!overlap, "header fields don't overlap"); + int max = 0; + foreach (int b in used) max = Math.Max(max, b); + Check(max < BridgeLayout.OffPrefixes, "header fields end before the prefix area"); + using var bridge = BridgeChannel.OpenOrCreate(_pid); + bridge.WriteInt(BridgeLayout.OffD3DDevice, 0x12C1B300); + using var engine = BridgeChannel.OpenOrCreate(_pid); + Check(engine.ReadInt(BridgeLayout.OffD3DDevice) == 0x12C1B300, "device field reaches the engine"); + } +} diff --git a/tools/DecalBridgeRepair/Add-RynthCoreDecalBridge-AllUsers.reg b/tools/DecalBridgeRepair/Add-RynthCoreDecalBridge-AllUsers.reg new file mode 100644 index 0000000..5ccf2d1 Binary files /dev/null and b/tools/DecalBridgeRepair/Add-RynthCoreDecalBridge-AllUsers.reg differ diff --git a/tools/DecalBridgeRepair/Remove-RynthCoreDecalBridge-AllUsers.reg b/tools/DecalBridgeRepair/Remove-RynthCoreDecalBridge-AllUsers.reg new file mode 100644 index 0000000..3163f6a Binary files /dev/null and b/tools/DecalBridgeRepair/Remove-RynthCoreDecalBridge-AllUsers.reg differ diff --git a/tools/FloodProbeBench/FloodProbeBench.csproj b/tools/FloodProbeBench/FloodProbeBench.csproj new file mode 100644 index 0000000..26f87b5 --- /dev/null +++ b/tools/FloodProbeBench/FloodProbeBench.csproj @@ -0,0 +1,33 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + The engine's memory probe (src\RynthCore.Engine\Compatibility\MemoryProbe.cs, compiled in) + without AC: (1) it must answer exactly like the old VirtualQuery checks for committed, + untouched, reserved, freed, guard, no-access, read-only and cross-page memory; (2) a + benchmark of the main-thread snapshot walk's probes (CObjectMaint bucket walk + the + per-object position/PWD probes) against a large committed heap like AC's in a crowded + dungeon, old VirtualQuery probes vs MemoryProbe. + + x86 on purpose: the cost that broke the client is VirtualQuery under WOW64 (a 32-bit + process on 64-bit Windows). Needs the x86 .NET runtime (C:\Program Files (x86)\dotnet). + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + dotnet run -c Release, then heap sizes in MB after the usual separator (default 4 16 64) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0-windows</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <RuntimeIdentifier>win-x86</RuntimeIdentifier> + <SelfContained>false</SelfContained> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>FloodProbeBench</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\MemoryProbe.cs" Link="Engine\MemoryProbe.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/FloodProbeBench/Program.cs b/tools/FloodProbeBench/Program.cs new file mode 100644 index 0000000..bbd8e09 --- /dev/null +++ b/tools/FloodProbeBench/Program.cs @@ -0,0 +1,343 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using RynthCore.Engine.Compatibility; + +namespace FloodProbeBench; + +/// <summary> +/// MemoryProbe (the engine's AV-safe memory check) without AC. +/// +/// Part 1 checks it answers like the old VirtualQuery helpers on every kind of page. +/// Part 2 times the probes of the engine's main-thread snapshot walks against a big committed +/// heap, like AC's in a crowded dungeon (working set 1.0-1.4 GB on 2026-10-02): +/// * the CObjectMaint weenie-table walk (EnumerateLiveWeenieObjectIds): old = one probe per +/// hash bucket plus two per chain node; new = one probe over the bucket array plus one per +/// node (id and next are adjacent); +/// * PrefetchPositions' per-object probes (the PublicWeenieDesc copy and the CPhysicsObj +/// head), 10 walks a second; +/// * PrefetchObjectIdentity's per-object probes (qualities pointer, name string, two PWD +/// ints: about 10), and PrefetchAttackable's walk, 2 walks a second each. +/// The AC calls the walks also make (GetWeenieObject, GetObjectName, ObjectIsAttackable) are +/// not modelled - they did not change. Objects are spread over the heap and the bucket array +/// sits in the middle, so the committed run after a probed address averages half the heap. +/// VirtualQuery's cost grows with that run (WOW64), MemoryProbe's does not. +/// </summary> +internal static unsafe class Program +{ + private static int _checks, _failed; + + private static int Main(string[] args) + { + int[] heapSizesMb = args.Length > 0 ? args.Select(int.Parse).ToArray() : new[] { 4, 16, 64 }; + Console.WriteLine($"MemoryProbe: QueryWorkingSetEx fast path {(MemoryProbe.FastPathActive ? "available" : "MISSING")}, IntPtr.Size={IntPtr.Size}"); + + Correctness(); + Benchmark(heapSizesMb); + + Console.WriteLine(); + Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks)"); + return _failed == 0 ? 0 : 1; + } + + // ── Part 1: same answers as the old helpers ─────────────────────────────── + + private static void Correctness() + { + Console.WriteLine("\n=== Correctness: MemoryProbe vs the old VirtualQuery rule ==="); + const int Page = 4096; + + IntPtr touched = Alloc(4 * Page, MemCommit | MemReserve, PageReadWrite); + for (int i = 0; i < 4 * Page; i += Page) *((byte*)touched + i) = 1; + Same("committed, touched (resident)", touched + 16, 1); + Same("committed, touched, span over 3 pages", touched + 100, 3 * Page - 200); + Expect("committed, touched: readable", MemoryProbe.IsReadable(touched, 64), true); + Expect("committed, touched: writable", MemoryProbe.IsWritable(touched, 64), true); + + IntPtr untouched = Alloc(2 * Page, MemCommit | MemReserve, PageReadWrite); + Same("committed, never touched (not resident)", untouched + 8, 1); + Same("committed, never touched, span", untouched, 2 * Page); + + IntPtr reserved = Alloc(4 * Page, MemReserve, PageReadWrite); + Same("reserved only", reserved, 1); + Expect("reserved only: refused", MemoryProbe.IsAccessible(reserved), false); + + IntPtr mixed = Alloc(4 * Page, MemReserve, PageReadWrite); + Alloc(Page, MemCommit, PageReadWrite, mixed); + *(byte*)mixed = 1; + Expect("span from a committed page into a reserved one: refused", + MemoryProbe.IsAccessible(mixed + Page - 8, 16), false); + Same("span from a committed page into a reserved one", mixed + Page - 8, 16); + + IntPtr freed = Alloc(Page, MemCommit | MemReserve, PageReadWrite); + *(byte*)freed = 1; + VirtualFree(freed, UIntPtr.Zero, MemRelease); + Same("freed", freed, 1); + Expect("freed: refused", MemoryProbe.IsAccessible(freed), false); + + IntPtr guard = Alloc(Page, MemCommit | MemReserve, PageReadWrite | PageGuard); + Same("guard page", guard, 1); + Expect("guard page: refused", MemoryProbe.IsAccessible(guard), false); + + IntPtr noAccess = Alloc(Page, MemCommit | MemReserve, PageReadWrite); + *(byte*)noAccess = 1; + VirtualProtect(noAccess, (UIntPtr)Page, PageNoAccess, out _); + Same("no-access page (was resident)", noAccess, 1); + Expect("no-access page: refused", MemoryProbe.IsAccessible(noAccess), false); + + IntPtr readOnly = Alloc(Page, MemCommit | MemReserve, PageReadWrite); + *(byte*)readOnly = 1; + VirtualProtect(readOnly, (UIntPtr)Page, PageReadOnly, out _); + Expect("read-only page: readable", MemoryProbe.IsReadable(readOnly, 32), true); + Expect("read-only page: not writable", MemoryProbe.IsWritable(readOnly, 32), false); + Expect("read-only page: same as old writable rule", MemoryProbe.IsWritable(readOnly), LegacyWritable(readOnly)); + + IntPtr code = NativeLibrary.GetExport(NativeLibrary.Load("kernel32.dll"), "VirtualQuery"); + Same("code page (kernel32!VirtualQuery)", code, 16); + + Expect("null pointer refused", MemoryProbe.IsAccessible(IntPtr.Zero), false); + Expect("zero length refused", MemoryProbe.IsAccessible(touched, 0), false); + Expect("top of the address space refused", MemoryProbe.IsAccessible(new IntPtr(-16), 64), false); + } + + private static void Same(string what, IntPtr p, int len) + { + bool legacy = LegacyAccessible(p, len); + bool probe = MemoryProbe.IsAccessible(p, len); + bool legacyR = LegacyReadable(p, len); + bool probeR = MemoryProbe.IsReadable(p, len); + Expect($"{what}: accessible {probe} (old {legacy})", probe, legacy); + Expect($"{what}: readable {probeR} (old {legacyR})", probeR, legacyR); + } + + private static void Expect(string what, bool got, bool want) + { + _checks++; + if (got == want) Console.WriteLine($" [ok] {what}"); + else { _failed++; Console.WriteLine($" [FAIL] {what}: got {got}, want {want}"); } + } + + // ── Part 2: the snapshot walks ──────────────────────────────────────────── + + private const int TableSize = 4096; // weenie_object_table buckets (AC: 1k-8k) + private const int ObjectSize = 0x400; // an ACCWeenieObject-sized block + private const int PhysOffset = 0x80; // weenie -> CPhysicsObj* (the probed _phys_obj offset) + private const int PwdSize = 0x120; // PwdLayout.Size-like copy + private const int PhysSize = 0x200; + private const int PhysProbe = 0xAC; // CPhysicsObj head through m_state + + private static void Benchmark(int[] heapSizesMb) + { + foreach (int heapMb in heapSizesMb) + { + Console.WriteLine(); + Console.WriteLine($"=== Benchmark: snapshot-walk probes, {heapMb} MB committed heap, {TableSize} buckets ==="); + long size = (long)heapMb << 20; + IntPtr heap = Alloc((int)size, MemCommit | MemReserve, PageReadWrite); + if (heap == IntPtr.Zero) { Console.WriteLine(" could not reserve the heap - pass smaller sizes"); _failed++; continue; } + for (long off = 0; off < size; off += 4096) *((byte*)heap + off) = 1; + + foreach (int objects in new[] { 150, 750 }) + { + var table = BuildTable(heap, size, objects, seed: objects); + MemoryProbe.TakeStats(); + double oldPos = Time(() => WalkOld(table, identity: false), 1); + double newPos = Time(() => WalkNew(table, identity: false), 20); + double oldId = Time(() => WalkOld(table, identity: true), 1); + double newId = Time(() => WalkNew(table, identity: true), 20); + double oldAtk = Time(() => EnumerateOld(table, null), 1); + double newAtk = Time(() => { using var scope = MemoryProbe.BeginWalk(); EnumerateNew(table, null); }, 20); + + // Per second on AC's main thread: positions 10x, identity 2x, attackable 2x. + double oldPerSec = oldPos * 10 + oldId * 2 + oldAtk * 2; + double newPerSec = newPos * 10 + newId * 2 + newAtk * 2; + Console.WriteLine($" {objects,4} objects:"); + Console.WriteLine($" position walk old {oldPos,10:0.00} ms new {newPos,7:0.000} ms"); + Console.WriteLine($" identity walk old {oldId,10:0.00} ms new {newId,7:0.000} ms"); + Console.WriteLine($" attackable walk old {oldAtk,10:0.00} ms new {newAtk,7:0.000} ms"); + Console.WriteLine($" AC main thread per second: old {oldPerSec,8:0} ms new {newPerSec,6:0.0} ms"); + var (fast, slow, slowMs) = MemoryProbe.TakeStats(); + Console.WriteLine($" MemoryProbe: {fast} pages answered by QueryWorkingSetEx, {slow} VirtualQuery fallbacks ({slowMs:0.0} ms)"); + _checks++; + if (oldPerSec > 50 && newPerSec * 10 > oldPerSec) { _failed++; Console.WriteLine(" [FAIL] the new walk is not at least 10x cheaper"); } + if (slow > 0) { _failed++; Console.WriteLine(" [FAIL] resident heap pages fell back to VirtualQuery"); } + } + VirtualFree(heap, UIntPtr.Zero, MemRelease); + } + } + + private sealed class Table + { + public IntPtr Header; // HashBase: +12 buckets, +16 table_size + public readonly Dictionary<uint, IntPtr> ById = new(); + } + + private static Table BuildTable(IntPtr heap, long heapSize, int objects, int seed) + { + var rng = new Random(seed); + var t = new Table { Header = heap + 0x1000 }; + IntPtr buckets = heap + (int)(heapSize / 2); + new Span<byte>((void*)buckets, TableSize * 4).Clear(); + *(IntPtr*)(t.Header + 12) = buckets; + *(int*)(t.Header + 16) = TableSize; + for (int i = 0; i < objects; i++) + { + uint id = 0x80000000u + (uint)(0x2000 + i * 7); + IntPtr obj = heap + (int)(0x10000 + (rng.NextInt64(heapSize / 2 - 0x20000) & ~0xFL)); + IntPtr phys = heap + (int)(heapSize / 2 + 0x10000 + (rng.NextInt64(heapSize / 2 - 0x20000) & ~0xFL)); + *(uint*)(obj + 8) = id; + *(IntPtr*)(obj + PhysOffset) = phys; + IntPtr slot = buckets + (int)((id & (TableSize - 1)) * 4); + *(IntPtr*)(obj + 4) = *(IntPtr*)slot; // hash_next + *(IntPtr*)slot = obj; + t.ById[id] = obj; + } + return t; + } + + private static int _sink; + + // The pre-2026-10-02 walk: SmartBoxLocator.IsMemoryReadable (VirtualQuery) per bucket and + // twice per node, then CapturePositionForId's two IsReadableSpan probes per object; the + // identity walk's ~10 probes per object. + private static int EnumerateOld(Table t, Action<uint>? visit) + { + if (!LegacyReadable(t.Header + 12, 4)) return -1; + IntPtr buckets = *(IntPtr*)(t.Header + 12); + if (!LegacyReadable(t.Header + 16, 4)) return -1; + int size = *(int*)(t.Header + 16); + int count = 0; + for (int i = 0; i < size; i++) + { + IntPtr slot = buckets + i * 4; + if (!LegacyReadable(slot, 4)) break; + IntPtr node = *(IntPtr*)slot; + while (node != IntPtr.Zero) + { + if (!LegacyReadable(node + 8, 4)) break; + uint id = *(uint*)(node + 8); + visit?.Invoke(id); + count++; + if (!LegacyReadable(node + 4, 4)) break; + node = *(IntPtr*)(node + 4); + } + } + return count; + } + + private static void WalkOld(Table t, bool identity) + { + EnumerateOld(t, id => + { + IntPtr w = t.ById[id]; + if (identity) + { + for (int k = 0; k < 10; k++) + if (LegacyAccessible(w + 0x10 + k * 0x20, 4)) _sink++; + return; + } + if (LegacyAccessible(w + PhysOffset + 4, PwdSize)) _sink++; + IntPtr phys = *(IntPtr*)(w + PhysOffset); + if (LegacyAccessible(phys, PhysProbe + 4)) _sink += *(byte*)phys; + }); + } + + // The new walk: one probe over the bucket array, one per node, MemoryProbe everywhere, inside + // a walk scope (each page queried once per walk), as the engine's PrefetchPositions / + // PrefetchObjectIdentity / PrefetchAttackable. + private static int EnumerateNew(Table t, Action<uint>? visit) + { + if (!MemoryProbe.IsReadable(t.Header + 12, 8)) return -1; + IntPtr buckets = *(IntPtr*)(t.Header + 12); + int size = *(int*)(t.Header + 16); + if (!MemoryProbe.IsReadable(buckets, size * 4)) return -1; + int count = 0; + for (int i = 0; i < size; i++) + { + IntPtr node = *(IntPtr*)(buckets + i * 4); + while (node != IntPtr.Zero) + { + if (!MemoryProbe.IsReadable(node + 4, 8)) break; + uint id = *(uint*)(node + 8); + visit?.Invoke(id); + count++; + node = *(IntPtr*)(node + 4); + } + } + return count; + } + + private static void WalkNew(Table t, bool identity) + { + using var scope = MemoryProbe.BeginWalk(); // as the engine's walks + EnumerateNew(t, id => + { + IntPtr w = t.ById[id]; + if (identity) + { + for (int k = 0; k < 10; k++) + if (MemoryProbe.IsAccessible(w + 0x10 + k * 0x20, 4)) _sink++; + return; + } + if (MemoryProbe.IsAccessible(w + PhysOffset + 4, PwdSize)) _sink++; + IntPtr phys = *(IntPtr*)(w + PhysOffset); + if (MemoryProbe.IsAccessible(phys, PhysProbe + 4)) _sink += *(byte*)phys; + }); + } + + private static double Time(Action a, int reps) + { + var sw = Stopwatch.StartNew(); + for (int i = 0; i < reps; i++) a(); + return sw.Elapsed.TotalMilliseconds / reps; + } + + // ── The old helpers, verbatim in behaviour ──────────────────────────────── + + // ClientObjectHooks.IsReadablePointer / IsReadableSpan before 2026-10-02. + private static bool LegacyAccessible(IntPtr ptr, int length) + { + if (ptr == IntPtr.Zero || length <= 0) return false; + if (VirtualQuery(ptr, out var mbi, Marshal.SizeOf<Mbi>()) == 0) return false; + if (mbi.State != MemCommit) return false; + if ((mbi.Protect & (PageNoAccess | PageGuard)) != 0) return false; + if (length <= 1) return true; + ulong regionEnd = (ulong)(nuint)mbi.BaseAddress + (ulong)(nuint)mbi.RegionSize; + return (ulong)(nuint)ptr + (ulong)length <= regionEnd; + } + + // SmartBoxLocator.IsMemoryReadable before 2026-10-02. + private static bool LegacyReadable(IntPtr ptr, int length) + { + if (ptr == IntPtr.Zero || length <= 0) return false; + if (VirtualQuery(ptr, out var mbi, Marshal.SizeOf<Mbi>()) == 0) return false; + if (mbi.State != MemCommit) return false; + if ((mbi.Protect & PageNoAccess) != 0 || (mbi.Protect & PageGuard) != 0) return false; + if ((mbi.Protect & MemoryProbe.ReadableMask) == 0) return false; + long regionEnd = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64(); + return ptr.ToInt64() + length <= regionEnd; + } + + // ClientObjectHooks.IsWritablePointer before 2026-10-02. + private static bool LegacyWritable(IntPtr ptr) + { + if (ptr == IntPtr.Zero) return false; + if (VirtualQuery(ptr, out var mbi, Marshal.SizeOf<Mbi>()) == 0) return false; + if (mbi.State != MemCommit) return false; + if ((mbi.Protect & (PageNoAccess | PageGuard)) != 0) return false; + return (mbi.Protect & MemoryProbe.WritableMask) != 0; + } + + private const uint MemCommit = 0x1000, MemReserve = 0x2000, MemRelease = 0x8000; + private const uint PageNoAccess = 0x01, PageReadOnly = 0x02, PageReadWrite = 0x04, PageGuard = 0x100; + + private static IntPtr Alloc(int size, uint type, uint protect, IntPtr at = default) + => VirtualAlloc(at, (UIntPtr)(uint)size, type, protect); + + [StructLayout(LayoutKind.Sequential)] + private struct Mbi { public IntPtr BaseAddress, AllocationBase; public uint AllocationProtect; public IntPtr RegionSize; public uint State, Protect, Type; } + + [DllImport("kernel32.dll")] private static extern int VirtualQuery(IntPtr a, out Mbi m, int len); + [DllImport("kernel32.dll")] private static extern IntPtr VirtualAlloc(IntPtr a, UIntPtr size, uint type, uint protect); + [DllImport("kernel32.dll")] private static extern bool VirtualFree(IntPtr a, UIntPtr size, uint type); + [DllImport("kernel32.dll")] private static extern bool VirtualProtect(IntPtr a, UIntPtr size, uint protect, out uint old); +} diff --git a/tools/LauncherSettingsTests/LauncherSettingsTests.csproj b/tools/LauncherSettingsTests/LauncherSettingsTests.csproj new file mode 100644 index 0000000..c5fd01b --- /dev/null +++ b/tools/LauncherSettingsTests/LauncherSettingsTests.csproj @@ -0,0 +1,33 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the launcher's shared settings with "Decal + RynthCore" accounts + (src\RynthCore.App\AppSettingsStore.cs and DecalAccountModes.cs, compiled in): the choice + lives in decal-accounts.json, appsettings.json never holds a value an older launcher can't + read, migration of a file that does, and what happens when an older launcher edits the + accounts; and saved account passwords (DPAPI-encrypted, AccountPasswordProtection.cs): round + trip, migration of a plain-text file, undecryptable blobs, nothing leaking into files or notes. + Works in a temp folder, never in %APPDATA%\RynthCore. Windows only (DPAPI). + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>LauncherSettingsTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.App\AppSettings.cs" Link="App\AppSettings.cs" /> + <Compile Include="..\..\src\RynthCore.App\AppSettingsStore.cs" Link="App\AppSettingsStore.cs" /> + <Compile Include="..\..\src\RynthCore.App\DecalAccountModes.cs" Link="App\DecalAccountModes.cs" /> + <Compile Include="..\..\src\RynthCore.App\InjectionMode.cs" Link="App\InjectionMode.cs" /> + <Compile Include="..\..\src\RynthCore.App\LaunchAccountProfile.cs" Link="App\LaunchAccountProfile.cs" /> + <Compile Include="..\..\src\RynthCore.App\AccountPasswordProtection.cs" Link="App\AccountPasswordProtection.cs" /> + <Compile Include="..\..\src\RynthCore.App\LaunchServerProfile.cs" Link="App\LaunchServerProfile.cs" /> + <Compile Include="..\..\src\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="App\AcLaunchArgumentBuilder.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/LauncherSettingsTests/Program.cs b/tools/LauncherSettingsTests/Program.cs new file mode 100644 index 0000000..22c2735 --- /dev/null +++ b/tools/LauncherSettingsTests/Program.cs @@ -0,0 +1,426 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using RynthCore.App; + +namespace LauncherSettingsTests; + +/// <summary> +/// The launcher's shared settings with "Decal + RynthCore" accounts, in a temp folder. +/// "Old launcher" = a launcher released before the Decal bridge: its InjectionMode has only +/// RynthCore and Decal, read with JsonStringEnumConverter, so "DecalBridge" makes the whole +/// appsettings.json unreadable for it. +/// </summary> +internal static class Program +{ + private static int _checks, _failed; + private static string _dir = ""; + + private static string Main_ => Path.Combine(_dir, "appsettings.json"); + private static string Bak => Main_ + ".bak"; + private static string Sidecar => Path.Combine(_dir, DecalAccountModes.FileName); + + private static int Main() + { + string root = Path.Combine(Path.GetTempPath(), "rc-launcher-settings-tests-" + Guid.NewGuid().ToString("N")); + try + { + Scenario("negative control: the old launcher can't read DecalBridge", root, () => + { + File.WriteAllText(Main_, """{ "AccountProfiles": [ { "Id": "b", "InjectionMode": "DecalBridge" } ] }"""); + Check(!OldLauncherCanRead(Main_), "old reader rejects \"DecalBridge\" (so the checks below mean something)"); + }); + + Scenario("save and load", root, () => + { + AppSettings s = Sample(); + AppSettingsStore.Save(s); + AppSettingsStore.Save(s); // second save: a .bak exists too + CheckSharedFilesSafe(); + Check(SharedMode("a") == "RynthCore", "a is RynthCore in appsettings.json"); + Check(SharedMode("b") == "RynthCore", "b (Decal + RynthCore) is written as RynthCore"); + Check(SharedMode("c") == "Decal", "c is Decal in appsettings.json"); + Check(SidecarIds().SequenceEqual(new[] { "b" }), "decal-accounts.json lists only b"); + Check(s.AccountProfiles[1].InjectionMode == InjectionMode.DecalBridge, "save leaves the in-memory mode alone"); + + AppSettings loaded = AppSettingsStore.Load(); + Check(Mode(loaded, "a") == InjectionMode.RynthCore, "load: a RynthCore"); + Check(Mode(loaded, "b") == InjectionMode.DecalBridge, "load: b Decal + RynthCore"); + Check(Mode(loaded, "c") == InjectionMode.Decal, "load: c Decal"); + Check(AppSettingsStore.LastLoadDiagnostic == null && AppSettingsStore.LastMigrationNote == null, "load: no diagnostics"); + }); + + Scenario("switch back to RynthCore", root, () => + { + AppSettings s = Sample(); + AppSettingsStore.Save(s); + s.AccountProfiles[1].InjectionMode = InjectionMode.RynthCore; + AppSettingsStore.Save(s); + Check(!File.Exists(Sidecar), "decal-accounts.json removed when no account uses the mode"); + Check(Mode(AppSettingsStore.Load(), "b") == InjectionMode.RynthCore, "load: b RynthCore"); + }); + + Scenario("migrate a file written by a pre-release bridge build", root, () => + { + string legacy = """ + { "EnginePath": "X", "AccountProfiles": [ + { "Id": "a", "AccountName": "A", "InjectionMode": "RynthCore" }, + { "Id": "b", "AccountName": "B", "InjectionMode": "DecalBridge" }, + { "Id": "d", "AccountName": "D", "InjectionMode": 2 } ] } + """; + File.WriteAllText(Main_, legacy); + File.WriteAllText(Bak, legacy); + AppSettings loaded = AppSettingsStore.Load(); + Check(Mode(loaded, "b") == InjectionMode.DecalBridge, "b kept as Decal + RynthCore"); + Check(Mode(loaded, "d") == InjectionMode.DecalBridge, "d (numeric 2) kept as Decal + RynthCore"); + Check(loaded.EnginePath == "X", "other settings kept"); + Check(AppSettingsStore.LastMigrationNote?.Contains("Moved 2") == true, "migration note: " + AppSettingsStore.LastMigrationNote); + CheckSharedFilesSafe(); + Check(SidecarIds().SequenceEqual(new[] { "b", "d" }), "decal-accounts.json lists b and d"); + + AppSettingsStore.Load(); + Check(AppSettingsStore.LastMigrationNote == null, "second load: nothing left to migrate"); + }); + + Scenario("an old launcher switches the account to Decal", root, () => + { + AppSettingsStore.Save(Sample()); + OldLauncherEdit(accounts => SetMode(accounts, "b", "Decal")); + AppSettings loaded = AppSettingsStore.Load(); + Check(Mode(loaded, "b") == InjectionMode.Decal, "the old launcher's choice wins"); + AppSettingsStore.Save(loaded); + Check(!File.Exists(Sidecar), "the stale entry is dropped at the next save"); + }); + + Scenario("an old launcher deletes the account", root, () => + { + AppSettingsStore.Save(Sample()); + OldLauncherEdit(accounts => + { + for (int i = accounts.Count - 1; i >= 0; i--) + if ((string?)accounts[i]!["Id"] == "b") accounts.RemoveAt(i); + }); + AppSettings loaded = AppSettingsStore.Load(); + Check(loaded.AccountProfiles.All(a => a.Id != "b"), "b is gone"); + AppSettingsStore.Save(loaded); + Check(!File.Exists(Sidecar), "its entry is dropped at the next save"); + }); + + Scenario("an old launcher saves without changes", root, () => + { + AppSettingsStore.Save(Sample()); + OldLauncherEdit(_ => { }); + Check(Mode(AppSettingsStore.Load(), "b") == InjectionMode.DecalBridge, "b is still Decal + RynthCore"); + }); + + Scenario("unreadable decal-accounts.json", root, () => + { + AppSettingsStore.Save(Sample()); + File.WriteAllText(Sidecar, "{ not json"); + AppSettings loaded = AppSettingsStore.Load(); + Check(Mode(loaded, "b") == InjectionMode.RynthCore, "b runs as RynthCore"); + Check(Mode(loaded, "c") == InjectionMode.Decal, "other accounts unchanged"); + Check(AppSettingsStore.LastLoadDiagnostic == null, "appsettings.json not taken for corrupt"); + Check(AppSettingsStore.LastMigrationNote?.Contains("could not be read") == true, "note: " + AppSettingsStore.LastMigrationNote); + loaded.AccountProfiles.First(a => a.Id == "b").InjectionMode = InjectionMode.DecalBridge; + AppSettingsStore.Save(loaded); + Check(SidecarIds().SequenceEqual(new[] { "b" }), "picking the mode again rewrites the file"); + }); + + Scenario("a mode name this build doesn't know", root, () => + { + File.WriteAllText(Main_, """{ "EnginePath": "Y", "AccountProfiles": [ { "Id": "z", "InjectionMode": "SomethingNew" }, { "Id": "y", "InjectionMode": 9 } ] }"""); + AppSettings loaded = AppSettingsStore.Load(); + Check(AppSettingsStore.LastLoadDiagnostic == null && loaded.EnginePath == "Y", "file still loads (not quarantined)"); + Check(Mode(loaded, "z") == InjectionMode.RynthCore && Mode(loaded, "y") == InjectionMode.RynthCore, "unknown modes read as RynthCore"); + }); + + Scenario("unchanged list: decal-accounts.json is not rewritten", root, () => + { + AppSettings s = Sample(); + AppSettingsStore.Save(s); + DateTime old = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + File.SetLastWriteTimeUtc(Sidecar, old); + AppSettingsStore.Save(s); + Check(File.GetLastWriteTimeUtc(Sidecar) == old, "no rewrite when nothing changed"); + s.AccountProfiles[0].InjectionMode = InjectionMode.DecalBridge; + AppSettingsStore.Save(s); + Check(SidecarIds().SequenceEqual(new[] { "a", "b" }), "rewritten when the list changed"); + CheckSharedFilesSafe(); + }); + + // ── saved account passwords (DPAPI) ───────────────────────────────── + // Test-only passwords; nothing here touches the real settings file. + const string Pw = "t3st pw \"quoted\" ü"; + const string Pw2 = "Second-Test-Pw"; + + Scenario("password round trip", root, () => + { + AppSettings s = Sample(); + s.AccountProfiles[0].SetPassword(Pw); + AppSettingsStore.Save(s); + AppSettingsStore.Save(s); // .bak too + CheckNoPlainText(Pw); + CheckNoPlainText("t3st pw"); + Check(!RawAccount("a").ContainsKey("Password"), "no plain \"Password\" field written"); + Check(!string.IsNullOrEmpty((string?)RawAccount("a")["PasswordProtected"]), "PasswordProtected written"); + Check(OldLauncherCanRead(Main_), "the old launcher can still read the file"); + + AppSettings loaded = AppSettingsStore.Load(); + LaunchAccountProfile a = loaded.AccountProfiles.First(x => x.Id == "a"); + Check(a.TryGetPasswordForLaunch(out string got, out _) && got == Pw, "decrypts to the saved password"); + Check(!a.PasswordNeedsReentry && a.HasSavedPassword, "saved, readable"); + Check(AppSettingsStore.LastPasswordMigrationNote == null && AppSettingsStore.LastPasswordProblemNote == null, "no password notes"); + + var builder = new AcLaunchArgumentBuilder(); + LaunchServerProfile ace = Server(AcEmulatorKind.Ace), gdle = Server(AcEmulatorKind.Gdle); + Check(builder.BuildArguments(ace, a).Contains("-v \"t3st pw \\\"quoted\\\" ü\""), "ACE args carry the password (-v)"); + Check(builder.BuildArguments(gdle, a).Contains("-a \"A:t3st pw \\\"quoted\\\" ü\""), "GDLE args carry account:password (-a)"); + string preview = builder.BuildMaskedArguments(ace, a); + Check(!preview.Contains("t3st") && preview.Contains("-v " + AcLaunchArgumentBuilder.PasswordMask), "preview masked: " + preview); + LaunchAccountProfile noPw = loaded.AccountProfiles.First(x => x.Id == "b"); + Check(builder.BuildMaskedArguments(ace, noPw).Contains("-v \"\""), "preview of an account without a password"); + Check(builder.BuildArguments(ace, noPw).Contains("-v \"\""), "no saved password still launches as before (empty)"); + + LaunchAccountProfile copy = a.Clone(); + Check(copy.PasswordProtected == a.PasswordProtected, "Clone keeps the encrypted password"); + copy.SetPassword(Pw2); + Check(copy.TryGetPasswordForLaunch(out string got2, out _) && got2 == Pw2, "a new password replaces it"); + copy.ClearPassword(); + Check(!copy.HasSavedPassword && copy.TryGetPasswordForLaunch(out string none, out _) && none.Length == 0, "clear"); + Check(AccountPasswordProtection.Protect(Pw) != AccountPasswordProtection.Protect(Pw), "each encryption differs (salted blobs)"); + }); + + Scenario("migrate plain-text passwords from an older file", root, () => + { + string legacy = """ + { "EnginePath": "X", "AccountProfiles": [ + { "Id": "a", "AccountName": "A", "Password": "PLAIN-PW-ONE", "InjectionMode": "RynthCore" }, + { "Id": "b", "AccountName": "B", "Password": "PLAIN-PW-TWO", "InjectionMode": "RynthCore" }, + { "Id": "c", "AccountName": "C", "Password": "", "InjectionMode": "Decal" }, + { "Id": "d", "AccountName": "D" } ] } + """; + File.WriteAllText(Main_, legacy); + File.WriteAllText(Bak, legacy); + File.WriteAllText(Sidecar, """{ "DecalBridgeAccountIds": [ "b" ] }"""); + File.WriteAllText(Main_ + ".corrupt-20260101-000000", "{ old quarantined file"); + + AppSettings loaded = AppSettingsStore.Load(); + Check(AppSettingsStore.LastPasswordMigrationNote?.StartsWith("migrated 2 account password(s) to encrypted storage") == true, + "one note: " + AppSettingsStore.LastPasswordMigrationNote); + Check(AppSettingsStore.LastPasswordMigrationNote?.Contains("corrupt-") == true, "note points at the quarantined file"); + Check(PwOf(loaded, "a") == "PLAIN-PW-ONE" && PwOf(loaded, "b") == "PLAIN-PW-TWO", "passwords kept"); + Check(!loaded.AccountProfiles.First(x => x.Id == "c").HasSavedPassword, "empty plain password = none saved"); + Check(loaded.AccountProfiles.All(x => x.LegacyPlainPassword == null), "no plain text left on the profiles"); + CheckNoPlainText("PLAIN-PW-ONE"); + CheckNoPlainText("PLAIN-PW-TWO"); + Check(!File.ReadAllText(Main_).Contains("\"Password\"") && !File.ReadAllText(Bak).Contains("\"Password\""), + "no \"Password\" field in appsettings.json or .bak"); + Check(Mode(loaded, "b") == InjectionMode.DecalBridge && SidecarIds().SequenceEqual(new[] { "b" }), + "decal-accounts.json survives the migration save"); + Check(loaded.EnginePath == "X", "other settings kept"); + CheckNotesClean("PLAIN-PW-ONE", "PLAIN-PW-TWO"); + + AppSettings again = AppSettingsStore.Load(); + Check(AppSettingsStore.LastPasswordMigrationNote == null, "second load: nothing left to migrate"); + Check(PwOf(again, "a") == "PLAIN-PW-ONE", "second load decrypts"); + }); + + Scenario("undecryptable password (copied from another Windows user or PC)", root, () => + { + AppSettings s = Sample(); + s.AccountProfiles[0].SetPassword(Pw); + s.AccountProfiles[1].SetPassword(Pw2); + s.AccountProfiles[2].SetPassword(Pw2); + AppSettingsStore.Save(s); + // Blobs this user can't open: a valid one with a byte changed (DPAPI's integrity + // check fails as it does with another user's key), random bytes, and non-base64. + byte[] blob = Convert.FromBase64String(s.AccountProfiles[0].PasswordProtected); + blob[^5] ^= 0x5A; + SetRaw("a", Convert.ToBase64String(blob)); + SetRaw("b", Convert.ToBase64String(Guid.NewGuid().ToByteArray())); + SetRaw("c", "not base64 !!"); + + AppSettings loaded = AppSettingsStore.Load(); // must not throw + Check(AppSettingsStore.LastLoadDiagnostic == null, "the file is not taken for corrupt"); + Check(loaded.AccountProfiles.All(x => x.PasswordNeedsReentry), "all three marked \"password needs re-entering\""); + Check(AppSettingsStore.LastPasswordProblemNote?.Contains("3 saved account password(s)") == true && + AppSettingsStore.LastPasswordProblemNote.Contains("need re-entering"), + "problem note: " + AppSettingsStore.LastPasswordProblemNote); + + LaunchAccountProfile a = loaded.AccountProfiles.First(x => x.Id == "a"); + var builder = new AcLaunchArgumentBuilder(); + LaunchServerProfile ace = Server(AcEmulatorKind.Ace); + string? error = null; + try { builder.BuildArguments(ace, a); } + catch (InvalidOperationException ex) { error = ex.Message; } + Check(error?.Contains("needs re-entering") == true, "launch refused, not launched with an empty password: " + error); + Check(builder.BuildMaskedArguments(ace, a).Contains("needs re-entering"), "preview says so"); + Check(!a.TryGetPasswordForLaunch(out string empty, out _) && empty.Length == 0, "TryGetPasswordForLaunch false"); + + a.SetPassword(Pw2); // re-entered in the account editor + Check(!a.PasswordNeedsReentry && a.TryGetPasswordForLaunch(out string got, out _) && got == Pw2, "re-entering fixes it"); + AppSettingsStore.Save(loaded); + AppSettings reloaded = AppSettingsStore.Load(); + Check(!reloaded.AccountProfiles.First(x => x.Id == "a").PasswordNeedsReentry, "fixed after reload"); + Check(reloaded.AccountProfiles.First(x => x.Id == "b").PasswordNeedsReentry, "the others still need re-entering"); + CheckNoPlainText(Pw2); + }); + + Scenario("nothing leaks into notes, previews or other files", root, () => + { + File.WriteAllText(Main_, """{ "AccountProfiles": [ { "Id": "a", "AccountName": "A", "Password": "LEAK-CHECK-PW" } ] }"""); + AppSettings loaded = AppSettingsStore.Load(); + CheckNotesClean("LEAK-CHECK-PW"); + Check(!loaded.AccountProfiles[0].ToString().Contains("LEAK-CHECK-PW"), "display name has no password"); + Check(!new AcLaunchArgumentBuilder().BuildMaskedArguments(Server(AcEmulatorKind.Gdle), loaded.AccountProfiles[0]).Contains("LEAK-CHECK-PW"), + "GDLE preview masked"); + AppSettingsStore.Save(loaded); + CheckNoPlainText("LEAK-CHECK-PW"); + }); + } + finally + { + AppSettingsStore.DirectoryOverride = null; + try { Directory.Delete(root, recursive: true); } catch { } + } + + Console.WriteLine(_failed == 0 + ? $"PASS: {_checks} checks" + : $"FAIL: {_failed} of {_checks} checks failed"); + return _failed == 0 ? 0 : 1; + } + + // ── helpers ────────────────────────────────────────────────────────────── + + private static void Scenario(string name, string root, Action body) + { + Console.WriteLine($"-- {name}"); + _dir = Path.Combine(root, Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_dir); + AppSettingsStore.DirectoryOverride = _dir; + try { body(); } + catch (Exception ex) { Check(false, $"threw {ex.GetType().Name}: {ex.Message}"); } + } + + private static AppSettings Sample() => new() + { + EnginePath = @"C:\Games\RynthCore\Runtime\RynthCore.Loader.dll", + AccountProfiles = + [ + new LaunchAccountProfile { Id = "a", AccountName = "A", InjectionMode = InjectionMode.RynthCore }, + new LaunchAccountProfile { Id = "b", AccountName = "B", InjectionMode = InjectionMode.DecalBridge }, + new LaunchAccountProfile { Id = "c", AccountName = "C", InjectionMode = InjectionMode.Decal }, + ], + }; + + private static InjectionMode Mode(AppSettings s, string id) => s.AccountProfiles.First(a => a.Id == id).InjectionMode; + + private static void CheckSharedFilesSafe() + { + foreach (string path in new[] { Main_, Bak }) + { + if (!File.Exists(path)) continue; + string name = Path.GetFileName(path); + Check(!File.ReadAllText(path).Contains("DecalBridge"), $"{name} has no \"DecalBridge\""); + Check(OldLauncherCanRead(path), $"the old launcher can read {name}"); + } + } + + private static string? SharedMode(string id) + { + JsonArray accounts = JsonNode.Parse(File.ReadAllText(Main_))!["AccountProfiles"]!.AsArray(); + return accounts.FirstOrDefault(a => (string?)a!["Id"] == id)?["InjectionMode"]?.ToString(); + } + + private static List<string> SidecarIds() + { + if (!File.Exists(Sidecar)) return new(); + JsonNode node = JsonNode.Parse(File.ReadAllText(Sidecar))!; + return node["DecalBridgeAccountIds"]!.AsArray().Select(n => (string)n!).ToList(); + } + + /// <summary>An old launcher's save: the JSON round-trips with its edit applied.</summary> + private static void OldLauncherEdit(Action<JsonArray> edit) + { + Check(OldLauncherCanRead(Main_), "old launcher loads the file before its edit"); + JsonNode root = JsonNode.Parse(File.ReadAllText(Main_))!; + edit(root["AccountProfiles"]!.AsArray()); + File.Copy(Main_, Bak, overwrite: true); + File.WriteAllText(Main_, root.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); + } + + private static void SetMode(JsonArray accounts, string id, string mode) + { + foreach (JsonNode? a in accounts) + if ((string?)a!["Id"] == id) a["InjectionMode"] = mode; + } + + private enum OldInjectionMode { RynthCore = 0, Decal = 1 } + + private sealed class OldAccount + { + public string Id { get; set; } = ""; + public OldInjectionMode InjectionMode { get; set; } + } + + private sealed class OldSettings + { + public List<OldAccount> AccountProfiles { get; set; } = new(); + } + + private static readonly JsonSerializerOptions OldOptions = new() { Converters = { new JsonStringEnumConverter() } }; + + private static bool OldLauncherCanRead(string path) + { + try { JsonSerializer.Deserialize<OldSettings>(File.ReadAllText(path), OldOptions); return true; } + catch (JsonException) { return false; } + } + + private static LaunchServerProfile Server(AcEmulatorKind kind) => new() + { + Id = "s", Name = "Test", Host = "127.0.0.1", Port = 9000, Emulator = kind + }; + + private static string PwOf(AppSettings s, string id) => + s.AccountProfiles.First(a => a.Id == id).TryGetPasswordForLaunch(out string pw, out _) ? pw : "<unreadable>"; + + private static JsonObject RawAccount(string id) => + JsonNode.Parse(File.ReadAllText(Main_))!["AccountProfiles"]!.AsArray() + .First(a => (string?)a!["Id"] == id)!.AsObject(); + + private static void SetRaw(string id, string passwordProtected) + { + JsonNode root = JsonNode.Parse(File.ReadAllText(Main_))!; + foreach (JsonNode? a in root["AccountProfiles"]!.AsArray()) + if ((string?)a!["Id"] == id) a["PasswordProtected"] = passwordProtected; + File.WriteAllText(Main_, root.ToJsonString()); + } + + /// <summary>No file the store wrote in the test folder (settings, .bak, .tmp, decal-accounts) holds the password.</summary> + private static void CheckNoPlainText(string password) + { + foreach (string file in Directory.GetFiles(_dir)) + { + if (file.Contains(".corrupt-")) continue; // planted by the test itself + Check(!File.ReadAllText(file).Contains(password), $"{Path.GetFileName(file)} has no plain-text password"); + } + } + + /// <summary>The store's notes (what the launcher logs and shows in the activity panel) hold no password.</summary> + private static void CheckNotesClean(params string[] passwords) + { + foreach (string? note in new[] { AppSettingsStore.LastLoadDiagnostic, AppSettingsStore.LastMigrationNote, + AppSettingsStore.LastPasswordMigrationNote, AppSettingsStore.LastPasswordProblemNote }) + foreach (string pw in passwords) + Check(note == null || !note.Contains(pw), "note has no password: " + note); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL: {what}"); + } +} diff --git a/tools/LauncherUpdateTests/LauncherUpdateTests.csproj b/tools/LauncherUpdateTests/LauncherUpdateTests.csproj new file mode 100644 index 0000000..78f3bec --- /dev/null +++ b/tools/LauncherUpdateTests/LauncherUpdateTests.csproj @@ -0,0 +1,28 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline tests for the launcher's Available plugins list, plugin installs with download + progress and Cancel (RynthUpdater.Available.cs, DownloadProgress.cs), and the front page's + update card (UpdateCardModel.cs). A throwaway key signs a feed served by a local + HttpListener; plugins install into temp folders. Never opens the launcher window, never + reads or writes outside %TEMP%. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0-windows</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <RootNamespace>LauncherUpdateTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.cs" Link="Linked\RynthUpdater.cs" /> + <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.NavData.cs" Link="Linked\RynthUpdater.NavData.cs" /> + <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.Available.cs" Link="Linked\RynthUpdater.Available.cs" /> + <Compile Include="..\..\src\RynthCore.App.Avalonia\DownloadProgress.cs" Link="Linked\DownloadProgress.cs" /> + <Compile Include="..\..\src\RynthCore.App.Avalonia\UpdateCardModel.cs" Link="Linked\UpdateCardModel.cs" /> + <Compile Include="..\..\src\RynthCore.App.Avalonia\UpdateTrust.cs" Link="Linked\UpdateTrust.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/LauncherUpdateTests/Program.cs b/tools/LauncherUpdateTests/Program.cs new file mode 100644 index 0000000..ed11764 --- /dev/null +++ b/tools/LauncherUpdateTests/Program.cs @@ -0,0 +1,605 @@ +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using RynthCore.App.Avalonia; + +// Tests for the launcher's Available plugins list, plugin installs (verified, with progress and +// Cancel), Remove, old feeds without descriptions, the download meter, and the front page's +// update card. A throwaway signing key signs feeds served by a local HttpListener. +internal static class Program +{ + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + + private static string _root = ""; + private static string _base = ""; + private static readonly Dictionary<string, byte[]> Served = new(); + private static readonly ECDsa Key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + private static readonly DateTime Published = new(2026, 10, 5, 0, 0, 0, DateTimeKind.Utc); + + private static async Task<int> Main() + { + _root = Path.Combine(Path.GetTempPath(), "rlaunch-upd-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_root); + int port = FreePort(); + _base = $"http://localhost:{port}/rynth/"; + using var http = new HttpListener(); + http.Prefixes.Add(_base); + http.Start(); + _ = Task.Run(() => Serve(http)); + try + { + await Run(nameof(AvailableIsFeedMinusInstalled), AvailableIsFeedMinusInstalled); + await Run(nameof(OnlyRynthLuaIsAutomatic), OnlyRynthLuaIsAutomatic); + await Run(nameof(OldManifestWithoutDescriptions), OldManifestWithoutDescriptions); + await Run(nameof(DescriptionsAreOneShortLine), DescriptionsAreOneShortLine); + await Run(nameof(NewBadgeAndOneAnnouncement), NewBadgeAndOneAnnouncement); + await Run(nameof(NotNewForPlayersWhoHadThem), NotNewForPlayersWhoHadThem); + await Run(nameof(InstallDownloadsVerifiesRegisters), InstallDownloadsVerifiesRegisters); + await Run(nameof(InstallRefusesTamperedFile), InstallRefusesTamperedFile); + await Run(nameof(InstallOnlyFromTheFeed), InstallOnlyFromTheFeed); + await Run(nameof(InstallKeepsGoodCopyReplacesOldOne), InstallKeepsGoodCopyReplacesOldOne); + await Run(nameof(CancelledInstallLeavesNoFile), CancelledInstallLeavesNoFile); + await Run(nameof(RemoveReturnsPluginToAvailable), RemoveReturnsPluginToAvailable); + await Run(nameof(SuiteFolderWithoutRynthAi), SuiteFolderWithoutRynthAi); + await Run(nameof(UnsignedDescriptionBreaksSignature), UnsignedDescriptionBreaksSignature); + await Run(nameof(UrlOutsideFeedStillRefused), UrlOutsideFeedStillRefused); + await Run(nameof(MeterThrottlesAndFinishes), MeterThrottlesAndFinishes); + await Run(nameof(ProgressTextFormats), ProgressTextFormats); + await Run(nameof(UpdateCardStates), UpdateCardStates); + await Run(nameof(UpdateCardDownloading), UpdateCardDownloading); + await Run(nameof(UpdateCardWhatsNew), UpdateCardWhatsNew); + } + finally + { + http.Stop(); + try { Directory.Delete(_root, true); } catch { } + } + Console.WriteLine(); + Console.WriteLine(_fails == 0 && _asserts > 0 ? $"PASS ({_asserts} assertions)" : $"FAIL ({_fails} of {_asserts} assertions failed)"); + return _fails == 0 && _asserts > 0 ? 0 : 1; + } + + private static async Task Run(string name, Func<Task> test) + { + int before = _fails; + try { await test(); } + catch (Exception ex) { _fails++; _asserts++; Console.WriteLine($" [FAIL] {name} threw {ex.GetType().Name}: {ex.Message}"); } + Console.WriteLine($"{(_fails == before ? "ok " : "FAIL")} {name}"); + } + + private static Task Run(string name, Action test) => Run(name, () => { test(); return Task.CompletedTask; }); + + // ── Fixtures ───────────────────────────────────────────────────────────── + + private static int FreePort() + { + var l = new TcpListener(IPAddress.Loopback, 0); + l.Start(); + int p = ((IPEndPoint)l.LocalEndpoint).Port; + l.Stop(); + return p; + } + + private static async Task Serve(HttpListener http) + { + while (http.IsListening) + { + HttpListenerContext ctx; + try { ctx = await http.GetContextAsync(); } catch { return; } + string name = ctx.Request.Url!.AbsolutePath.Replace("/rynth/", ""); + byte[]? body; + lock (Served) Served.TryGetValue(name, out body); + if (body == null) { ctx.Response.StatusCode = 404; ctx.Response.Close(); continue; } + ctx.Response.StatusCode = 200; + ctx.Response.ContentLength64 = body.Length; + HttpListenerContext c = ctx; + byte[] b = body; + // Big files go out in pieces with a pause between them, so a download is still running + // when progress is reported (and can be cancelled half way). + _ = Task.Run(async () => + { + try + { + for (int off = 0; off < b.Length; off += 64 * 1024) + { + await c.Response.OutputStream.WriteAsync(b.AsMemory(off, Math.Min(64 * 1024, b.Length - off))); + if (b.Length > 512 * 1024) await Task.Delay(25); + } + } + catch { } + finally { try { c.Response.Close(); } catch { } } + }); + } + } + + private static string Sha(byte[] b) => Convert.ToHexString(SHA256.HashData(b)).ToLowerInvariant(); + // Names that aren't plain folder names (a test of the folder check) get a plain file name. + private static string FileOf(string name) => + name.All(char.IsLetterOrDigit) ? $"RynthCore.Plugin.{name}.dll" : $"RynthCore.Plugin.Weird{(uint)name.GetHashCode():x}.dll"; + + private static byte[] Body(string name, string version = "v2") + { + if (name == "RynthOracle") + { + // Big enough for several progress reports. + var rnd = new Random(7); + byte[] b = new byte[1_500_000]; + rnd.NextBytes(b); + Encoding.ASCII.GetBytes($"dll {name} {version}").CopyTo(b, 0); + return b; + } + return Encoding.UTF8.GetBytes($"dll {name} {version}"); + } + + private static readonly string[] FeedPlugins = { "RynthAi", "RynthChat", "RynthNav", "RynthLua", "RynthOracle", "RynthInventory" }; + + private sealed record Feed(RynthUpdater Upd, string Dir, string Suite, string State, string RynthAiPath); + + /// <summary> + /// A signed feed in its own folder, a state folder, and RynthAi installed at + /// <tag>\Games\RynthSuite\RynthAi (the installer's layout). + /// </summary> + private static Feed Setup(string tag, bool descriptions = true, IEnumerable<string>? extraPlugins = null, + Dictionary<string, string>? descriptionOverride = null, bool signDescriptions = true, string? badUrlFor = null, + string[]? changes = null) + { + string dir = Path.Combine(_root, tag); + string state = Path.Combine(dir, "state"), app = Path.Combine(dir, "app"), suite = Path.Combine(dir, "Games", "RynthSuite"); + Directory.CreateDirectory(state); Directory.CreateDirectory(app); + string ai = Path.Combine(suite, "RynthAi", FileOf("RynthAi")); + Directory.CreateDirectory(Path.GetDirectoryName(ai)!); + File.WriteAllBytes(ai, Body("RynthAi")); + File.SetLastWriteTimeUtc(ai, Published); + WriteFeed(tag, descriptions, extraPlugins, descriptionOverride, signDescriptions, badUrlFor, changes); + var upd = new RynthUpdater(_base + $"{tag}/update.json", new[] { Convert.ToBase64String(Key.ExportSubjectPublicKeyInfo()) }, state, app); + upd.SetDefaultSuiteDir(Path.Combine(dir, "DefaultSuite")); + return new Feed(upd, dir, suite, state, ai); + } + + private static void WriteFeed(string tag, bool descriptions = true, IEnumerable<string>? extraPlugins = null, + Dictionary<string, string>? descriptionOverride = null, bool signDescriptions = true, string? badUrlFor = null, + string[]? changes = null) + { + var plugins = new List<Dictionary<string, object>>(); + foreach (string name in FeedPlugins.Concat(extraPlugins ?? Array.Empty<string>())) + { + byte[] body = Body(name); + string rel = $"{tag}/releases/1/plugins/{FileOf(name)}"; + lock (Served) Served[rel] = body; + var p = new Dictionary<string, object> + { + ["name"] = name, ["file"] = FileOf(name), + ["url"] = name == badUrlFor ? "http://elsewhere.example/" + FileOf(name) : _base + rel, + ["size"] = body.Length, ["sha256"] = Sha(body), + }; + if (descriptions) p["description"] = descriptionOverride != null && descriptionOverride.TryGetValue(name, out string? d) ? d : $"Feed line for {name}."; + plugins.Add(p); + } + var manifest = new Dictionary<string, object?> + { + ["schema"] = 1, ["release"] = 2026100501, ["version"] = "2026.10.5.1", + ["published"] = Published.ToString("yyyy-MM-ddTHH:mm:ssZ"), ["notes"] = "Release notes for players.", + ["core"] = new Dictionary<string, object> { ["release"] = 2026100501, ["version"] = "2026.10.5.1", ["url"] = _base + $"{tag}/releases/1/RynthCore-Setup.exe", ["size"] = 1, ["sha256"] = "00" }, + ["plugins"] = plugins, + }; + if (changes != null) manifest["changes"] = changes; + byte[] signedPayload; + if (!signDescriptions) + { + // What was signed had no descriptions; what is served does. + var unsigned = plugins.Select(p => p.Where(kv => kv.Key != "description").ToDictionary(kv => kv.Key, kv => kv.Value)).ToList(); + var m2 = new Dictionary<string, object?>(manifest) { ["plugins"] = unsigned }; + signedPayload = JsonSerializer.SerializeToUtf8Bytes(m2); + } + else signedPayload = JsonSerializer.SerializeToUtf8Bytes(manifest); + byte[] payload = JsonSerializer.SerializeToUtf8Bytes(manifest); + byte[] sig = Key.SignData(signedPayload, HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation); + string envelope = JsonSerializer.Serialize(new + { + payload = Convert.ToBase64String(payload), + signatures = new[] { new { key = RynthUpdater.KeyId(Key.ExportSubjectPublicKeyInfo()), sig = Convert.ToBase64String(sig) } }, + }); + lock (Served) Served[$"{tag}/update.json"] = Encoding.UTF8.GetBytes(envelope); + } + + /// <summary>Installs a plugin by hand at the suite layout (as if from the zip or an earlier launcher).</summary> + private static string Place(Feed f, string name) + { + string path = Path.Combine(f.Suite, name, FileOf(name)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllBytes(path, Body(name)); + File.SetLastWriteTimeUtc(path, Published); + return path; + } + + private sealed class SyncProgress(Action<DownloadProgress> onReport) : IProgress<DownloadProgress> + { + public void Report(DownloadProgress value) => onReport(value); + } + + private static List<string> Names(IEnumerable<RynthUpdater.AvailablePlugin> a) => a.Select(x => x.Entry.Name).OrderBy(n => n).ToList(); + + // ── Available list ─────────────────────────────────────────────────────── + + private static async Task AvailableIsFeedMinusInstalled() + { + var f = Setup("avail"); + string chat = Place(f, "RynthChat"); + var paths = new List<string> { f.RynthAiPath, chat }; + var c = await f.Upd.CheckAsync(paths); + Check(Names(c.Available).SequenceEqual(new[] { "RynthInventory", "RynthNav", "RynthOracle" }), + "Available = feed minus installed, minus RynthLua (installed automatically): " + string.Join(",", Names(c.Available))); + var oracle = c.Available.Single(a => a.Entry.Name == "RynthOracle"); + Check(oracle.Path == Path.Combine(f.Suite, "RynthOracle", FileOf("RynthOracle")), "goes beside RynthAi: " + oracle.Path); + Check(oracle.Version == "2026.10.5.1" && oracle.Entry.Size == Body("RynthOracle").Length, "version and size from the feed"); + Check(oracle.Description == "Feed line for RynthOracle.", "description from the feed"); + Check(f.Upd.GetAvailable(c, paths).Count == c.Available.Count, "recomputed against the same list: the same"); + // Disabled (unticked) plugins are still in the list: not available. + Check(!c.Available.Any(a => a.Entry.Name == "RynthChat"), "a listed plugin is never available"); + } + + private static async Task OnlyRynthLuaIsAutomatic() + { + var f = Setup("companions"); + var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath }); + Check(c.Companions.Count == 1 && c.Companions[0].Entry.Name == "RynthLua", "only RynthLua installs itself beside RynthAi"); + var done = await f.Upd.InstallCompanionsAsync(c); + Check(done.Count == 1 && File.Exists(done[0].Path), "RynthLua installed"); + var c2 = await f.Upd.CheckAsync(new[] { f.RynthAiPath }); + Check(c2.Companions.Count == 0, "offered once: removed from the list, it stays removed"); + Check(c2.Available.Any(a => a.Entry.Name == "RynthLua"), "but it is under Available if the player wants it back"); + Check(c2.Available.Any(a => a.Entry.Name == "RynthOracle") && c2.Available.Any(a => a.Entry.Name == "RynthInventory"), + "RynthOracle and RynthInventory are offered, not installed"); + } + + private static async Task OldManifestWithoutDescriptions() + { + var f = Setup("olddesc", descriptions: false, extraPlugins: new[] { "RynthSomethingElse" }); + var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath }); + Check(c.Manifest.Plugins.All(p => p.Description == ""), "an old feed parses with no descriptions"); + Check(c.Available.Single(a => a.Entry.Name == "RynthOracle").Description == "Quests, character, titles and leaderboards.", + "a missing description falls back to the launcher's table"); + Check(c.Available.Single(a => a.Entry.Name == "RynthNav").Description.Contains("540 MB"), "RynthNav's says how big its map is"); + Check(c.Available.Single(a => a.Entry.Name == "RynthSomethingElse").Description == "", "a plugin the table doesn't know: no description, still listed"); + Check(c.Manifest.Changes.Count == 0 && c.Manifest.Notes.Length > 0, "no changes list: the notes are still there"); + } + + private static async Task DescriptionsAreOneShortLine() + { + var f = Setup("longdesc", descriptionOverride: new() + { + ["RynthOracle"] = "Line one\nline two\t\u0007 with spaces " + new string('x', 400), + ["RynthNav"] = " ", + }, changes: new[] { "First change.", " Second\nchange. ", "" }); + var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath }); + string d = c.Available.Single(a => a.Entry.Name == "RynthOracle").Description; + Check(!d.Contains('\n') && !d.Contains('\t') && !d.Contains('\u0007') && d.StartsWith("Line one line two with spaces"), "one line, control characters gone: " + d[..40]); + Check(d.Length <= 160 && d.EndsWith("…"), $"capped at 160 characters ({d.Length})"); + Check(c.Available.Single(a => a.Entry.Name == "RynthNav").Description.Contains("540 MB"), "a blank feed description falls back to the table"); + Check(c.Manifest.Changes.SequenceEqual(new[] { "First change.", "Second change." }), "changes: trimmed, one line each, blanks dropped"); + } + + private static async Task NewBadgeAndOneAnnouncement() + { + var f = Setup("newbadge"); + DateTime now = new(2026, 10, 6, 12, 0, 0, DateTimeKind.Utc); + f.Upd.UtcNow = () => now; + var paths = new[] { f.RynthAiPath }; + var c = await f.Upd.CheckAsync(paths); + Check(c.Available.Where(a => a.IsNew).Select(a => a.Entry.Name).OrderBy(n => n).SequenceEqual(new[] { "RynthInventory", "RynthOracle" }), + "first run: the two recent plugins are New, the rest aren't"); + Check(Names(c.NewlyAnnounced).SequenceEqual(new[] { "RynthInventory", "RynthOracle" }), "and announced"); + Check(c.Available.First().IsNew, "New ones are listed first"); + c = await f.Upd.CheckAsync(paths); + Check(c.NewlyAnnounced.Count == 0, "announced once only"); + Check(c.Available.Count(a => a.IsNew) == 2, "the badge stays"); + now = now.AddDays(31); + c = await f.Upd.CheckAsync(paths); + Check(c.Available.All(a => !a.IsNew), "after a month the badge goes"); + + // A plugin added to the feed later is New and announced, no table needed. + WriteFeed("newbadge", extraPlugins: new[] { "RynthBrandNew" }); + c = await f.Upd.CheckAsync(paths); + Check(c.Available.Single(a => a.Entry.Name == "RynthBrandNew").IsNew && Names(c.NewlyAnnounced).SequenceEqual(new[] { "RynthBrandNew" }), + "a plugin that appears in the feed later is New and announced"); + } + + private static async Task NotNewForPlayersWhoHadThem() + { + var f = Setup("hadthem"); + // 2026.10.4.3 auto-installed both; this player removed RynthInventory afterwards. + File.WriteAllText(Path.Combine(f.State, "update-companions.json"), "[\"RynthInventory\", \"RynthLua\", \"RynthOracle\"]"); + string oracle = Place(f, "RynthOracle"); + var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath, oracle }); + Check(!c.Available.Any(a => a.Entry.Name == "RynthOracle"), "the one they kept is installed, not offered"); + var inv = c.Available.SingleOrDefault(a => a.Entry.Name == "RynthInventory"); + Check(inv != null && !inv.IsNew && c.NewlyAnnounced.Count == 0, "the one they removed is available, without a New badge or an announcement"); + Check(c.Companions.Count == 0, "and nothing installs itself (RynthLua was offered already)"); + } + + // ── Install ────────────────────────────────────────────────────────────── + + private static async Task InstallDownloadsVerifiesRegisters() + { + var f = Setup("install"); + var paths = new List<string> { f.RynthAiPath }; + var c = await f.Upd.CheckAsync(paths); + var reports = new List<DownloadProgress>(); + var r = await f.Upd.InstallPluginAsync(c, "RynthOracle", paths, new SyncProgress(p => { lock (reports) reports.Add(p); })); + string expected = Path.Combine(f.Suite, "RynthOracle", FileOf("RynthOracle")); + Check(r.Path == expected && r.Downloaded, "installed into the suite folder: " + r.Path); + Check(File.Exists(expected) && Sha(File.ReadAllBytes(expected)) == Sha(Body("RynthOracle")), "the file is the signed one"); + Check(File.GetLastWriteTimeUtc(expected) == Published, "stamped with the release time (never taken for a local build)"); + var dl = reports.Where(p => p.Stage == DownloadStage.Downloading).ToList(); + Check(dl.Count >= 2 && dl.Last().Done == dl.Last().Total && dl.Last().Percent == 100, $"progress reaches 100% ({dl.Count} reports)"); + Check(dl.All(p => p.What == "RynthOracle"), "progress names the plugin"); + Check(reports.Any(p => p.Stage == DownloadStage.Verified) && reports.Last().Stage == DownloadStage.Installing, "verified, then installing"); + + Check(PluginListEdits.Add(paths, r.Path), "registered in the plugin list"); + Check(!PluginListEdits.Add(paths, r.Path.ToUpperInvariant()), "only once"); + Check(!f.Upd.GetAvailable(c, paths).Any(a => a.Entry.Name == "RynthOracle"), "no longer available"); + var c2 = await f.Upd.CheckAsync(paths); + Check(c2.Plugins.Any(p => p.Entry.Name == "RynthOracle" && p.State == RynthUpdater.PluginState.UpToDate), "the next check sees it up to date"); + } + + private static async Task InstallRefusesTamperedFile() + { + var f = Setup("tamper"); + var paths = new List<string> { f.RynthAiPath }; + var c = await f.Upd.CheckAsync(paths); + byte[] bad = Body("RynthInventory"); bad[0] ^= 0xFF; + lock (Served) Served[$"tamper/releases/1/plugins/{FileOf("RynthInventory")}"] = bad; + var reports = new List<DownloadProgress>(); + bool threw = false; + try { await f.Upd.InstallPluginAsync(c, "RynthInventory", paths, new SyncProgress(reports.Add)); } + catch (InvalidDataException) { threw = true; } + Check(threw, "a file that doesn't match the signed hash is refused"); + string target = Path.Combine(f.Suite, "RynthInventory", FileOf("RynthInventory")); + Check(!File.Exists(target), "nothing installed"); + Check(!reports.Any(p => p.Stage is DownloadStage.Verified or DownloadStage.Installing), "never reported as verified"); + + // A bigger tampered file, refused at the end of a download with progress on. + byte[] badBig = Body("RynthOracle"); badBig[badBig.Length - 1] ^= 0x01; + lock (Served) Served[$"tamper/releases/1/plugins/{FileOf("RynthOracle")}"] = badBig; + threw = false; + try { await f.Upd.InstallPluginAsync(c, "RynthOracle", paths, new SyncProgress(_ => { })); } + catch (InvalidDataException) { threw = true; } + Check(threw && !File.Exists(Path.Combine(f.Suite, "RynthOracle", FileOf("RynthOracle"))), "with progress on, the hash is still checked"); + } + + private static async Task InstallOnlyFromTheFeed() + { + var f = Setup("feedonly", extraPlugins: new[] { "..", "Bad Name" }); + var paths = new List<string> { f.RynthAiPath }; + var c = await f.Upd.CheckAsync(paths); + Check(!c.Available.Any(a => a.Entry.Name is ".." or "Bad Name"), "a feed name that isn't a plain folder name is never listed"); + bool threw = false; + try { await f.Upd.InstallPluginAsync(c, "..", paths); } catch (InvalidDataException) { threw = true; } + Check(threw, "and can't be installed"); + threw = false; + try { await f.Upd.InstallPluginAsync(c, "RynthNotInFeed", paths); } catch (InvalidOperationException) { threw = true; } + Check(threw, "a plugin the feed doesn't have can't be installed"); + threw = false; + try { await f.Upd.InstallPluginAsync(c, "RynthAi", paths); } catch (InvalidOperationException) { threw = true; } + Check(threw, "one already in the list isn't installed again"); + } + + private static async Task InstallKeepsGoodCopyReplacesOldOne() + { + var f = Setup("existing"); + var paths = new List<string> { f.RynthAiPath }; + var c = await f.Upd.CheckAsync(paths); + string chat = Place(f, "RynthChat"); // the right file already there (from the zip) + var r = await f.Upd.InstallPluginAsync(c, "RynthChat", paths); + Check(r.Path == chat && !r.Downloaded, "a good copy at the target is kept, not downloaded again"); + + string nav = Path.Combine(f.Suite, "RynthNav", FileOf("RynthNav")); + Directory.CreateDirectory(Path.GetDirectoryName(nav)!); + File.WriteAllText(nav, "an old RynthNav"); + File.SetLastWriteTimeUtc(nav, Published.AddDays(-20)); + r = await f.Upd.InstallPluginAsync(c, "RynthNav", paths); + Check(r.Downloaded && Sha(File.ReadAllBytes(nav)) == Sha(Body("RynthNav")), "an older copy is replaced by the release"); + Check(File.ReadAllText(nav + ".previous") == "an old RynthNav", "and kept beside it as .previous"); + + string inv = Path.Combine(f.Suite, "RynthInventory", FileOf("RynthInventory")); + Directory.CreateDirectory(Path.GetDirectoryName(inv)!); + File.WriteAllText(inv, "my own build"); + File.SetLastWriteTimeUtc(inv, Published.AddDays(2)); + r = await f.Upd.InstallPluginAsync(c, "RynthInventory", paths); + Check(!r.Downloaded && File.ReadAllText(inv) == "my own build", "a newer local build is left alone"); + } + + private static async Task CancelledInstallLeavesNoFile() + { + var f = Setup("cancel"); + var paths = new List<string> { f.RynthAiPath }; + var c = await f.Upd.CheckAsync(paths); + using var cts = new CancellationTokenSource(); + bool halfWay = false, threw = false; + string tempBefore = string.Join("|", Directory.GetFiles(Path.GetTempPath(), "rynth-*.dll").OrderBy(x => x)); + try + { + await f.Upd.InstallPluginAsync(c, "RynthOracle", paths, new SyncProgress(p => + { + if (p.Stage == DownloadStage.Downloading && p.Done > 0 && p.Done < p.Total) { halfWay = true; cts.Cancel(); } + }), cts.Token); + } + catch (OperationCanceledException) { threw = true; } + Check(halfWay && threw, "cancelled half way"); + Check(!File.Exists(Path.Combine(f.Suite, "RynthOracle", FileOf("RynthOracle"))), "nothing installed"); + string tempAfter = string.Join("|", Directory.GetFiles(Path.GetTempPath(), "rynth-*.dll").OrderBy(x => x)); + Check(tempAfter == tempBefore, "the partial download is deleted"); + var r = await f.Upd.InstallPluginAsync(c, "RynthOracle", paths); + Check(r.Downloaded && File.Exists(r.Path), "a later Install works"); + } + + // ── Remove ─────────────────────────────────────────────────────────────── + + private static async Task RemoveReturnsPluginToAvailable() + { + var f = Setup("remove"); + string oracle = Place(f, "RynthOracle"); + var paths = new List<string> { f.RynthAiPath, oracle }; + var disabled = new List<string> { oracle.ToUpperInvariant() }; + var c = await f.Upd.CheckAsync(paths); + Check(!c.Available.Any(a => a.Entry.Name == "RynthOracle"), "installed: not available"); + Check(PluginListEdits.Remove(paths, disabled, oracle), "removed from the list"); + Check(!paths.Contains(oracle) && disabled.Count == 0, "and from the disabled list (adding it back starts it ticked)"); + Check(File.Exists(oracle), "the files stay on disk"); + Check(f.Upd.GetAvailable(c, paths).Any(a => a.Entry.Name == "RynthOracle"), "back under Available"); + c = await f.Upd.CheckAsync(paths); + Check(c.Available.Any(a => a.Entry.Name == "RynthOracle") && !c.Companions.Any(x => x.Entry.Name == "RynthOracle"), "the next check agrees, and doesn't reinstall it"); + var r = await f.Upd.InstallPluginAsync(c, "RynthOracle", paths); + Check(!r.Downloaded && r.Path == oracle, "Install again reuses the file that stayed"); + Check(!PluginListEdits.Remove(paths, null, Path.Combine(f.Dir, "never-listed.dll")), "removing something not listed does nothing"); + } + + private static async Task SuiteFolderWithoutRynthAi() + { + var f = Setup("suite"); + // RynthAi not in the list, RynthChat in a folder named after it: install beside that. + string otherSuite = Path.Combine(f.Dir, "Elsewhere", "RynthSuite"); + string chat = Path.Combine(otherSuite, "RynthChat", FileOf("RynthChat")); + Directory.CreateDirectory(Path.GetDirectoryName(chat)!); + File.WriteAllBytes(chat, Body("RynthChat")); + var c = await f.Upd.CheckAsync(new[] { chat }); + Check(c.Available.Single(a => a.Entry.Name == "RynthNav").Path.StartsWith(otherSuite), "beside another suite plugin"); + c = await f.Upd.CheckAsync(new[] { Path.Combine(f.Dir, "loose", "SomeOther.dll") }); + Check(c.Available.Single(a => a.Entry.Name == "RynthNav").Path.StartsWith(Path.Combine(f.Dir, "DefaultSuite")), "else the default folder"); + Check(c.Available.Any(a => a.Entry.Name == "RynthAi"), "RynthAi itself is available when it isn't listed"); + } + + // ── The feed's rules are unchanged ─────────────────────────────────────── + + private static async Task UnsignedDescriptionBreaksSignature() + { + var f = Setup("unsigned", signDescriptions: false); + bool threw = false; + try { await f.Upd.CheckAsync(new[] { f.RynthAiPath }); } catch (InvalidDataException) { threw = true; } + Check(threw, "descriptions are covered by the signature like everything else"); + } + + private static async Task UrlOutsideFeedStillRefused() + { + var f = Setup("badurl", badUrlFor: "RynthOracle"); + bool threw = false; + try { await f.Upd.CheckAsync(new[] { f.RynthAiPath }); } catch (InvalidDataException) { threw = true; } + Check(threw, "a plugin URL outside the feed's folder is refused (so it can never be installed)"); + } + + // ── Download meter and text ────────────────────────────────────────────── + + private static void MeterThrottlesAndFinishes() + { + TimeSpan t = TimeSpan.Zero; + var reports = new List<DownloadProgress>(); + long total = 100L << 20; + var m = new DownloadMeter("RynthNav map", total, new SyncProgress(reports.Add), () => t); + m.Report(0); + for (int i = 1; i <= 9; i++) { t += TimeSpan.FromMilliseconds(20); m.Report(i * (1L << 20)); } + Check(reports.Count == 1, $"reads 20 ms apart are throttled ({reports.Count} reports)"); + t = TimeSpan.FromSeconds(1); m.Report(10L << 20); + Check(reports.Count == 2, "a read after the interval is reported"); + var r = reports.Last(); + Check(Math.Abs(r.BytesPerSecond - (10L << 20)) < (1L << 20), $"speed ~10 MB/s ({r.BytesPerSecond / (1 << 20):0.0})"); + Check(r.Remaining is { } rem && Math.Abs(rem.TotalSeconds - 9) < 1, $"time left ~9 s ({r.Remaining})"); + Check(r.Percent is { } pc && Math.Abs(pc - 10) < 0.01, "10%"); + t = TimeSpan.FromSeconds(1.01); m.Report(total); + Check(reports.Last().Done == total && reports.Last().Percent == 100 && reports.Last().Remaining == TimeSpan.Zero, "the end is always reported, at 100%"); + t = TimeSpan.FromSeconds(130); m.Verified(); + Check(reports.Last().Stage == DownloadStage.Verified && reports.Last().Elapsed == TimeSpan.FromSeconds(130), "Verified carries the time taken"); + Check(new DownloadMeter("x", 10, null).Elapsed >= TimeSpan.Zero, "no progress wanted: no reports, no failure"); + } + + private static void ProgressTextFormats() + { + var done = new DownloadProgress("RynthNav map", DownloadStage.Verified, 565_182_464, 565_182_464, Elapsed: TimeSpan.FromSeconds(130)); + Check(done.Summary == "RynthNav map: 539 MB in 2m10s, verified", "log line: " + done.Summary); + var mid = new DownloadProgress("RynthNav map", DownloadStage.Downloading, 327_155_712, 565_182_464, 4.2 * 1024 * 1024, TimeSpan.FromSeconds(55)); + Check(mid.Detail == "312 of 539 MB · 4.2 MB/s · about 55s left", "detail: " + mid.Detail); + var small = new DownloadProgress("RynthOracle", DownloadStage.Downloading, 524_288, 1_500_000); + Check(small.Detail == "0.5 of 1.4 MB", "small file, no speed yet: " + small.Detail); + var unpack = new DownloadProgress("RynthNav map", DownloadStage.Unpacking, 12345, 40112); + Check(unpack.Detail == "Unpacking 12,345 of 40,112 files…" && unpack.Percent is > 30 and < 31, "unpacking: " + unpack.Detail); + Check(new DownloadProgress("x", DownloadStage.Installing, 0, 0).Percent == null, "installing has no percentage (an indeterminate bar)"); + Check(DownloadProgress.FormatDuration(TimeSpan.FromMinutes(65)) == "1h05m" && DownloadProgress.FormatDuration(TimeSpan.FromSeconds(8.4)) == "8s", "durations"); + } + + // ── Update card ────────────────────────────────────────────────────────── + + private static void UpdateCardStates() + { + var notConfigured = UpdateCardModel.Build(new UpdateCardInput { Configured = false }); + Check(notConfigured.Kind == UpdateCardKind.NotConfigured && !notConfigured.ShowCheckButton, "no signing key: says so, no button"); + + var notChecked = UpdateCardModel.Build(new UpdateCardInput { InstalledVersion = "2026.10.4.3" }); + Check(notChecked.Kind == UpdateCardKind.NotChecked && notChecked.ShowCheckButton && notChecked.ActionButton == null, "before the first check: Check button only"); + + var checking = UpdateCardModel.Build(new UpdateCardInput { Checking = true, InstalledVersion = "2026.10.4.3" }); + Check(checking.Kind == UpdateCardKind.Checking && !checking.ShowCheckButton, "checking: no buttons"); + + DateTime at = DateTime.Now.Date.AddHours(14).AddMinutes(5); + var upToDate = UpdateCardModel.Build(new UpdateCardInput { HasCheck = true, InstalledVersion = "2026.10.4.3", LastChecked = at }); + Check(upToDate.Kind == UpdateCardKind.UpToDate && upToDate.Title == "RynthCore 2026.10.4.3 - up to date", "up to date: " + upToDate.Title); + Check(upToDate.Detail == "Last checked at 14:05." && upToDate.ShowCheckButton && upToDate.ActionButton == null, "with the last check time and Check: " + upToDate.Detail); + Check(upToDate.NewPluginsLine == null, "no new plugins, no line"); + + var error = UpdateCardModel.Build(new UpdateCardInput { HasCheck = true, Error = "No such host is known.", LastChecked = at, InstalledVersion = "2026.10.4.3" }); + Check(error.Kind == UpdateCardKind.Error && error.ShowCheckButton && error.Detail == "No such host is known. Last good check: at 14:05.", "error: " + error.Detail); + + var core = UpdateCardModel.Build(new UpdateCardInput + { + HasCheck = true, InstalledVersion = "2026.10.4.3", CoreUpdateAvailable = true, AvailableVersion = "2026.10.5.1", + ClientsRunning = 2, PendingPluginUpdates = new[] { "RynthAi" }, LastChecked = at, + }); + Check(core.Kind == UpdateCardKind.CoreUpdate && core.Title == "RynthCore 2026.10.5.1 is available" && core.ActionButton == UpdateCardModel.UpdateCoreButton, "RynthCore update: version and Update button"); + Check(core.Detail.Contains("You have 2026.10.4.3") && core.Detail.Contains("installs once every game client is closed"), "says it installs once the game clients are closed"); + Check(core.Detail.Contains("Close your 2 game clients running RynthCore first."), "and how many are still running: " + core.Detail); + Check(core.Detail.Contains("Plugin updates ready too: RynthAi."), "mentions plugin updates as well"); + Check(core.Compact == "Update available: RynthCore 2026.10.5.1", "compact line: " + core.Compact); + var oneClient = UpdateCardModel.Build(new UpdateCardInput { HasCheck = true, CoreUpdateAvailable = true, AvailableVersion = "2026.10.5.1", ClientsRunning = 1 }); + Check(oneClient.Detail.Contains("Close your 1 game client running"), "one client: singular"); + + var plugins = UpdateCardModel.Build(new UpdateCardInput { HasCheck = true, InstalledVersion = "2026.10.5.1", PendingPluginUpdates = new[] { "RynthAi", "RynthNav map (539 MB download)" } }); + Check(plugins.Kind == UpdateCardKind.PluginUpdates && plugins.ActionButton == UpdateCardModel.UpdatePluginsButton && plugins.Detail.StartsWith("RynthAi, RynthNav map (539 MB download)."), "plugin updates: " + plugins.Detail); + + var withNew = UpdateCardModel.Build(new UpdateCardInput { HasCheck = true, InstalledVersion = "2026.10.5.1", NewPlugins = new[] { "RynthOracle", "RynthInventory" } }); + Check(withNew.Kind == UpdateCardKind.UpToDate && withNew.NewPluginsLine == "New plugins available: RynthOracle, RynthInventory. See Available plugins on the Plugins tab.", "new plugins line: " + withNew.NewPluginsLine); + + Check(UpdateCardModel.FormatWhen(new DateTime(2026, 10, 3, 9, 7, 0), new DateTime(2026, 10, 4, 12, 0, 0)) == "Oct 3 at 09:07", "an earlier day shows the date"); + } + + private static void UpdateCardDownloading() + { + var p = new DownloadProgress("RynthNav map", DownloadStage.Downloading, 100L << 20, 400L << 20, 5 << 20, TimeSpan.FromMinutes(1)); + var card = UpdateCardModel.Build(new UpdateCardInput { HasCheck = true, CoreUpdateAvailable = true, AvailableVersion = "x", Download = p, CanCancel = true }); + Check(card.Kind == UpdateCardKind.Downloading && card.Title == "Downloading RynthNav map", "a download takes over the card: " + card.Title); + Check(card.ShowProgress && card.ProgressPercent == 25 && card.ShowCancel && card.ActionButton == null && !card.ShowCheckButton, "bar at 25%, Cancel, no other buttons"); + Check(card.Detail == "100 of 400 MB · 5.0 MB/s · about 1m00s left", "MB, speed, time left: " + card.Detail); + var unpack = UpdateCardModel.Build(new UpdateCardInput { Download = p with { Stage = DownloadStage.Unpacking, Done = 10, Total = 40 } }); + Check(unpack.Title == "Unpacking RynthNav map" && unpack.ProgressPercent == 25, "the step after the download"); + var install = UpdateCardModel.Build(new UpdateCardInput { Download = p with { Stage = DownloadStage.Installing, Done = 0, Total = 0 }, CanCancel = true }); + Check(install.Title == "Installing RynthNav map" && install.ProgressPercent == null && !install.ShowCancel, "installing: indeterminate, no Cancel"); + var verified = UpdateCardModel.Build(new UpdateCardInput { Download = p with { Stage = DownloadStage.Verified } }); + Check(verified.Title == "RynthNav map: verified", "verified step shown"); + } + + private static void UpdateCardWhatsNew() + { + var six = new[] { "One.", "Two.", "Three.", "Four.", "Five.", "Six." }; + var card = UpdateCardModel.Build(new UpdateCardInput { HasCheck = true, CoreUpdateAvailable = true, AvailableVersion = "2026.10.5.1", Changes = six, Notes = "All of it." }); + Check(card.WhatsNew.SequenceEqual(new[] { "One.", "Two.", "Three.", "Four.", "…and 2 more." }), "a few of the changes: " + string.Join(" | ", card.WhatsNew)); + var old = UpdateCardModel.Build(new UpdateCardInput { HasCheck = true, CoreUpdateAvailable = true, AvailableVersion = "2026.10.5.1", Notes = "Old feeds only have notes." }); + Check(old.WhatsNew.SequenceEqual(new[] { "Old feeds only have notes." }), "an old feed shows its notes"); + var upToDate = UpdateCardModel.Build(new UpdateCardInput { HasCheck = true, Changes = six }); + Check(upToDate.WhatsNew.Count == 0, "nothing to install: no what's new"); + Check(UpdateCardModel.WhatsNew(Array.Empty<string>(), new string('n', 500))[0].Length == 300, "long notes are cut"); + } +} diff --git a/tools/NavDataUpdateTests/NavDataUpdateTests.csproj b/tools/NavDataUpdateTests/NavDataUpdateTests.csproj new file mode 100644 index 0000000..fa170e6 --- /dev/null +++ b/tools/NavDataUpdateTests/NavDataUpdateTests.csproj @@ -0,0 +1,25 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline tests for the launcher's RynthNav tile update (RynthUpdater.NavData.cs): a signed + feed with a "navdata" archive, served from a local HttpListener, installed into temp folders. + Nothing outside %TEMP% is read or written. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0-windows</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <RootNamespace>NavDataUpdateTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.cs" Link="Linked\RynthUpdater.cs" /> + <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.NavData.cs" Link="Linked\RynthUpdater.NavData.cs" /> + <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.Available.cs" Link="Linked\RynthUpdater.Available.cs" /> + <Compile Include="..\..\src\RynthCore.App.Avalonia\DownloadProgress.cs" Link="Linked\DownloadProgress.cs" /> + <Compile Include="..\..\src\RynthCore.App.Avalonia\UpdateTrust.cs" Link="Linked\UpdateTrust.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/NavDataUpdateTests/Program.cs b/tools/NavDataUpdateTests/Program.cs new file mode 100644 index 0000000..b4d64dd --- /dev/null +++ b/tools/NavDataUpdateTests/Program.cs @@ -0,0 +1,404 @@ +using System.IO.Compression; +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using RynthCore.App.Avalonia; + +// Tests for the launcher's RynthNav tile update. A throwaway signing key signs a feed served by +// a local HttpListener; the updater installs the archive into a temp NavData folder. +internal static class Program +{ + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + + private static string _root = ""; + private static string _base = ""; + private static readonly Dictionary<string, byte[]> Served = new(); + private static ECDsa _key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + + private static async Task<int> Main() + { + _root = Path.Combine(Path.GetTempPath(), "rnav-upd-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_root); + int port = FreePort(); + _base = $"http://localhost:{port}/rynth/"; + using var http = new HttpListener(); + http.Prefixes.Add(_base); + http.Start(); + _ = Task.Run(() => Serve(http)); + try + { + await Run(nameof(NoNavDataInFeed), NoNavDataInFeed); + await Run(nameof(NotInstalledWithoutRynthNav), NotInstalledWithoutRynthNav); + await Run(nameof(InstallsAndKeepsPlayerFiles), InstallsAndKeepsPlayerFiles); + await Run(nameof(LocalTilesLeftAlone), LocalTilesLeftAlone); + await Run(nameof(SettingsFolderIsUsed), SettingsFolderIsUsed); + await Run(nameof(RejectsBadArchive), RejectsBadArchive); + await Run(nameof(RejectsTamperedArchive), RejectsTamperedArchive); + await Run(nameof(RejectsUnsignedNavData), RejectsUnsignedNavData); + await Run(nameof(ReportsProgressToTheEnd), ReportsProgressToTheEnd); + await Run(nameof(CancelledDownloadLeavesNothing), CancelledDownloadLeavesNothing); + await Run(nameof(CancelledUnpackLeavesTilesAsTheyWere), CancelledUnpackLeavesTilesAsTheyWere); + await Run(nameof(TamperedArchiveRefusedWithProgress), TamperedArchiveRefusedWithProgress); + } + finally + { + http.Stop(); + try { Directory.Delete(_root, true); } catch { } + } + Console.WriteLine(); + Console.WriteLine(_fails == 0 && _asserts > 0 ? $"PASS ({_asserts} assertions)" : $"FAIL ({_fails} of {_asserts} assertions failed)"); + return _fails == 0 && _asserts > 0 ? 0 : 1; + } + + private static async Task Run(string name, Func<Task> test) + { + int before = _fails; + try { await test(); } + catch (Exception ex) { _fails++; _asserts++; Console.WriteLine($" [FAIL] {name} threw {ex.GetType().Name}: {ex.Message}"); } + Console.WriteLine($"{(_fails == before ? "ok " : "FAIL")} {name}"); + } + + // ── Fixtures ───────────────────────────────────────────────────────────── + + private static int FreePort() + { + var l = new TcpListener(IPAddress.Loopback, 0); + l.Start(); + int p = ((IPEndPoint)l.LocalEndpoint).Port; + l.Stop(); + return p; + } + + private static async Task Serve(HttpListener http) + { + while (http.IsListening) + { + HttpListenerContext ctx; + try { ctx = await http.GetContextAsync(); } catch { return; } + string name = ctx.Request.Url!.AbsolutePath.Replace("/rynth/", ""); + byte[]? body; + lock (Served) Served.TryGetValue(name, out body); + if (body == null) { ctx.Response.StatusCode = 404; ctx.Response.Close(); continue; } + ctx.Response.StatusCode = 200; + ctx.Response.ContentLength64 = body.Length; + HttpListenerContext c = ctx; + byte[] b = body; + // Big files go out in pieces with a pause between them, like a real connection, so a + // download is still running when progress is reported (and can be cancelled half way). + _ = Task.Run(async () => + { + try + { + for (int off = 0; off < b.Length; off += 64 * 1024) + { + int n = Math.Min(64 * 1024, b.Length - off); + await c.Response.OutputStream.WriteAsync(b.AsMemory(off, n)); + if (b.Length > 512 * 1024) await Task.Delay(25); + } + } + catch { } + finally { try { c.Response.Close(); } catch { } } + }); + } + } + + private static string Sha(byte[] b) => Convert.ToHexString(SHA256.HashData(b)).ToLowerInvariant(); + + /// <summary>A zip of the given files (name -> content).</summary> + private static byte[] Zip(Dictionary<string, string> files) + { + using var ms = new MemoryStream(); + using (var za = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) + foreach (var (n, c) in files) + { + using var s = za.CreateEntry(n).Open(); + s.Write(Encoding.UTF8.GetBytes(c)); + } + return ms.ToArray(); + } + + private static readonly Dictionary<string, string> TileSet = new() + { + ["nav_A9B4.tile"] = "tile A9B4 v2", + ["nav_A9B5.tile"] = "tile A9B5 v2", + ["nav_AAB4.tile"] = "tile AAB4 v2", + ["portals.tsv"] = "1\t2\t3\t4\tportal", + ["locations.json"] = "{\"locations\":[]}", + ["navgraph.bin"] = "route graph", + ["townnet.json"] = "{\"version\":1}", + }; + + // The feed's URLs must sit in the feed's folder: serve each test's archive under it. + private static (RynthUpdater upd, string nav, string plugin, string state) SetupInFeedFolder(string tag, byte[]? zip, string id = "0123456789abcdef0123456789abcdef", + int? files = null, bool signNavData = true, bool withNavData = true, string? overrideSha = null) + { + string zipName = $"{tag}/releases/1/RynthNav-NavData.zip"; + string dir = Path.Combine(_root, tag); + string state = Path.Combine(dir, "state"), app = Path.Combine(dir, "app"), nav = Path.Combine(dir, "NavData"), cache = Path.Combine(dir, "cache"); + Directory.CreateDirectory(state); Directory.CreateDirectory(app); + string plugin = Path.Combine(dir, "RynthNav", "RynthCore.Plugin.RynthNav.dll"); + Directory.CreateDirectory(Path.GetDirectoryName(plugin)!); + File.WriteAllText(plugin, "not a real dll"); + if (zip != null) lock (Served) Served[zipName] = zip; + var manifest = new Dictionary<string, object?> + { + ["schema"] = 1, ["release"] = 2026100201, ["version"] = "2026.10.2.1", + ["published"] = "2026-10-02T00:00:00Z", ["notes"] = "test", + ["core"] = new Dictionary<string, object> { ["release"] = 2026100201, ["version"] = "2026.10.2.1", ["url"] = _base + $"{tag}/releases/1/RynthCore-Setup.exe", ["size"] = 1, ["sha256"] = "00" }, + ["plugins"] = Array.Empty<object>(), + }; + var nd = zip == null ? null : new Dictionary<string, object> + { + ["id"] = id, ["release"] = 2026100201, ["url"] = _base + zipName, ["size"] = zip.Length, + ["sha256"] = overrideSha ?? Sha(zip), ["files"] = files ?? TileSet.Count, ["bytes"] = 1000, + }; + if (withNavData && nd != null && signNavData) manifest["navdata"] = nd; + byte[] signedPayload = JsonSerializer.SerializeToUtf8Bytes(manifest); + if (withNavData && nd != null && !signNavData) manifest["navdata"] = nd; // served, but not what was signed + byte[] payload = JsonSerializer.SerializeToUtf8Bytes(manifest); + byte[] sig = _key.SignData(signedPayload, HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation); + byte[] spki = _key.ExportSubjectPublicKeyInfo(); + string envelope = JsonSerializer.Serialize(new { payload = Convert.ToBase64String(payload), signatures = new[] { new { key = RynthUpdater.KeyId(spki), sig = Convert.ToBase64String(sig) } } }); + lock (Served) Served[$"{tag}/update.json"] = Encoding.UTF8.GetBytes(envelope); + var upd = new RynthUpdater(_base + $"{tag}/update.json", new[] { Convert.ToBase64String(spki) }, state, app); + upd.SetDefaultNavDataDir(nav); + upd.NavDataCacheDir = cache; + return (upd, nav, plugin, state); + } + + private static void OldNavData(string nav) + { + Directory.CreateDirectory(nav); + File.WriteAllText(Path.Combine(nav, "nav_A9B4.tile"), "tile A9B4 June"); + File.WriteAllText(Path.Combine(nav, "nav_0101.tile"), "a stale June tile not in the new set"); + File.WriteAllText(Path.Combine(nav, "portals.tsv"), "old portals"); + File.WriteAllText(Path.Combine(nav, "atlas.txt"), "my favorites"); + File.WriteAllText(Path.Combine(nav, "recalls.txt"), "my recalls"); + } + + // ── Tests ──────────────────────────────────────────────────────────────── + + private static async Task NoNavDataInFeed() + { + var (upd, nav, plugin, _) = SetupInFeedFolder("none", Zip(TileSet), withNavData: false); + var c = await upd.CheckAsync(new[] { plugin }); + Check(c.Manifest.NavData == null && c.NavData == null && !c.NavDataUpdateAvailable, "a feed without navdata (every feed so far) still parses, nothing to do"); + } + + private static async Task NotInstalledWithoutRynthNav() + { + var (upd, nav, plugin, _) = SetupInFeedFolder("nonav", Zip(TileSet)); + var c = await upd.CheckAsync(new[] { Path.Combine(Path.GetDirectoryName(plugin)!, "RynthCore.Plugin.RynthAi.dll") }); + Check(c.Manifest.NavData != null, "the feed's navdata parses"); + Check(c.NavData == null, "no RynthNav in the plugin list: no tiles"); + } + + private static async Task InstallsAndKeepsPlayerFiles() + { + var (upd, nav, plugin, _) = SetupInFeedFolder("install", Zip(TileSet)); + OldNavData(nav); + var c = await upd.CheckAsync(new[] { plugin }); + Check(c.NavData is { State: RynthUpdater.NavDataState.NeedsUpdate }, "June tiles (no navdata.id): update needed"); + string line = await upd.UpdateNavDataAsync(c); + Check(line.Contains($"{TileSet.Count} files"), "reports what it installed: " + line); + Check(File.ReadAllText(Path.Combine(nav, "navgraph.bin")) == "route graph", "the route graph ships with the tiles"); + Check(File.ReadAllText(Path.Combine(nav, "townnet.json")) == "{\"version\":1}", "the Town Network ships with the tiles"); + Check(File.ReadAllText(Path.Combine(nav, "nav_A9B4.tile")) == "tile A9B4 v2", "the tile is the new one"); + Check(File.Exists(Path.Combine(nav, "nav_AAB4.tile")), "new tiles are there"); + Check(!File.Exists(Path.Combine(nav, "nav_0101.tile")), "a stale tile from the old set is gone (old and new don't link)"); + Check(File.ReadAllText(Path.Combine(nav, "portals.tsv")).Contains("portal"), "portals.tsv replaced"); + Check(File.ReadAllText(Path.Combine(nav, "atlas.txt")) == "my favorites", "atlas.txt kept"); + Check(File.ReadAllText(Path.Combine(nav, "recalls.txt")) == "my recalls", "recalls.txt kept"); + Check(File.ReadAllText(Path.Combine(nav, "navdata.id")) == "0123456789abcdef0123456789abcdef", "navdata.id written"); + Check(File.ReadAllText(Path.Combine(nav + ".previous", "nav_0101.tile")).Contains("June"), "the old folder is kept as NavData.previous"); + Check(!Directory.Exists(nav + ".new"), "no staging folder left behind"); + c = await upd.CheckAsync(new[] { plugin }); + Check(c.NavData is { State: RynthUpdater.NavDataState.UpToDate } && !c.NavDataUpdateAvailable, "a second check: up to date"); + Check(await upd.UpdateNavDataAsync(c) == "", "nothing to do when up to date"); + } + + private static async Task LocalTilesLeftAlone() + { + var (upd, nav, plugin, _) = SetupInFeedFolder("local", Zip(TileSet)); + OldNavData(nav); + File.WriteAllText(Path.Combine(nav, "navdata.local"), ""); + var c = await upd.CheckAsync(new[] { plugin }); + Check(c.NavData is { State: RynthUpdater.NavDataState.LocalTiles } && !c.NavDataUpdateAvailable, "navdata.local: left alone"); + await upd.UpdateNavDataAsync(c); + Check(File.ReadAllText(Path.Combine(nav, "nav_A9B4.tile")) == "tile A9B4 June", "local tiles untouched"); + } + + private static async Task SettingsFolderIsUsed() + { + var (upd, nav, plugin, state) = SetupInFeedFolder("settings", Zip(TileSet)); + string other = Path.Combine(_root, "settings", "Elsewhere", "NavData"); + File.WriteAllText(Path.Combine(state, "rynthnav.json"), JsonSerializer.Serialize(new { navDataDir = other })); + var c = await upd.CheckAsync(new[] { plugin }); + Check(c.NavData != null && c.NavData.Dir == other, "rynthnav.json's navDataDir is where the tiles go"); + await upd.UpdateNavDataAsync(c); + Check(File.Exists(Path.Combine(other, "nav_A9B4.tile")) && !Directory.Exists(nav), "installed there, not in the default"); + } + + private static async Task RejectsBadArchive() + { + var evil = new Dictionary<string, string>(TileSet) { ["../evil.txt"] = "x" }; + var (upd, nav, plugin, _) = SetupInFeedFolder("evil", Zip(evil), files: evil.Count); + OldNavData(nav); + var c = await upd.CheckAsync(new[] { plugin }); + bool threw = false; + try { await upd.UpdateNavDataAsync(c); } catch (InvalidDataException) { threw = true; } + Check(threw, "a path outside the folder is refused"); + Check(!File.Exists(Path.Combine(_root, "evil", "evil.txt")), "nothing written outside"); + Check(File.ReadAllText(Path.Combine(nav, "nav_A9B4.tile")) == "tile A9B4 June" && !Directory.Exists(nav + ".new"), "the installed folder is as it was, no staging left"); + + var odd = new Dictionary<string, string>(TileSet) { ["run.exe"] = "x" }; + (upd, nav, plugin, _) = SetupInFeedFolder("odd", Zip(odd), files: odd.Count); + c = await upd.CheckAsync(new[] { plugin }); + threw = false; + try { await upd.UpdateNavDataAsync(c); } catch (InvalidDataException) { threw = true; } + Check(threw, "a file RynthNav doesn't read is refused"); + + (upd, nav, plugin, _) = SetupInFeedFolder("count", Zip(TileSet), files: TileSet.Count + 1); + c = await upd.CheckAsync(new[] { plugin }); + threw = false; + try { await upd.UpdateNavDataAsync(c); } catch (InvalidDataException) { threw = true; } + Check(threw, "a file count that doesn't match the feed is refused"); + } + + private static async Task RejectsTamperedArchive() + { + byte[] zip = Zip(TileSet); + var (upd, nav, plugin, _) = SetupInFeedFolder("tamper", zip); + OldNavData(nav); + var c = await upd.CheckAsync(new[] { plugin }); + byte[] bad = (byte[])zip.Clone(); bad[bad.Length / 2] ^= 0xFF; + lock (Served) Served["tamper/releases/1/RynthNav-NavData.zip"] = bad; + bool threw = false; + try { await upd.UpdateNavDataAsync(c); } catch (InvalidDataException) { threw = true; } + Check(threw, "an archive that doesn't match the signed hash is refused"); + Check(File.ReadAllText(Path.Combine(nav, "nav_A9B4.tile")) == "tile A9B4 June", "and nothing changes"); + } + + /// <summary>Calls back on the reporting thread (Progress<T> would post to the thread pool).</summary> + private sealed class SyncProgress(Action<DownloadProgress> onReport) : IProgress<DownloadProgress> + { + public void Report(DownloadProgress value) => onReport(value); + } + + /// <summary>The tile set plus an incompressible file, so the archive takes many reads.</summary> + private static Dictionary<string, string> BigTileSet() + { + var rnd = new Random(42); + var sb = new StringBuilder(); + for (int i = 0; i < 1_500_000; i++) sb.Append((char)rnd.Next(0x21, 0x7E)); + return new Dictionary<string, string>(TileSet) { ["navgraph.bin"] = sb.ToString() }; + } + + private static async Task ReportsProgressToTheEnd() + { + var big = BigTileSet(); + byte[] zip = Zip(big); + var (upd, nav, plugin, _) = SetupInFeedFolder("progress", zip); + var c = await upd.CheckAsync(new[] { plugin }); + var reports = new List<DownloadProgress>(); + await upd.UpdateNavDataAsync(c, new SyncProgress(p => { lock (reports) reports.Add(p); })); + var dl = reports.Where(r => r.Stage == DownloadStage.Downloading).ToList(); + Check(dl.Count >= 2, $"download progress reported ({dl.Count} reports)"); + Check(dl.All(r => r.What == RynthUpdater.NavDataDisplayName && r.Total == zip.Length), "each names the map and the signed size"); + Check(dl.Zip(dl.Skip(1)).All(p => p.Second.Done >= p.First.Done), "bytes only go up"); + Check(dl.Last().Done == zip.Length && dl.Last().Percent == 100, "the download reaches 100%"); + var verified = reports.FirstOrDefault(r => r.Stage == DownloadStage.Verified); + Check(verified != null && verified.Summary.StartsWith("RynthNav map: ") && verified.Summary.EndsWith(", verified"), "a Verified step with the log line: " + verified?.Summary); + var unpack = reports.Where(r => r.Stage == DownloadStage.Unpacking).ToList(); + Check(unpack.Count >= 1 && unpack.Last().Done == big.Count && unpack.Last().Total == big.Count, "unpacking counts to every file"); + Check(reports.Last().Stage == DownloadStage.Installing, "installing is the last step"); + int vi = reports.IndexOf(verified!), ui = reports.FindIndex(r => r.Stage == DownloadStage.Unpacking); + Check(vi > 0 && ui > vi, "steps in order: download, verify, unpack, install"); + Check(File.Exists(Path.Combine(nav, "navgraph.bin")), "and it is installed"); + } + + private static async Task CancelledDownloadLeavesNothing() + { + byte[] zip = Zip(BigTileSet()); + var (upd, nav, plugin, _) = SetupInFeedFolder("cancel", zip); + OldNavData(nav); + var c = await upd.CheckAsync(new[] { plugin }); + using var cts = new CancellationTokenSource(); + bool threw = false, halfWay = false; + string cachePart = Path.Combine(_root, "cancel", "cache", "navdata-0123456789abcdef0123456789abcdef.zip.part"); + bool partExisted = false; + try + { + await upd.UpdateNavDataAsync(c, new SyncProgress(p => + { + if (p.Stage == DownloadStage.Downloading && p.Done > 0 && p.Done < p.Total) + { + halfWay = true; + partExisted = File.Exists(cachePart); + cts.Cancel(); + } + }), cts.Token); + } + catch (OperationCanceledException) { threw = true; } + Check(halfWay && partExisted, "cancelled half way, with a partial file on disk at that moment"); + Check(threw, "Cancel during the download stops it"); + string cache = Path.Combine(_root, "cancel", "cache"); + Check(!Directory.Exists(cache) || Directory.GetFiles(cache).Length == 0, "no partial (or any) archive left in the cache"); + Check(File.ReadAllText(Path.Combine(nav, "nav_A9B4.tile")) == "tile A9B4 June" && !Directory.Exists(nav + ".new"), "the installed tiles are as they were, no staging"); + + // The next try downloads and installs normally. + c = await upd.CheckAsync(new[] { plugin }); + await upd.UpdateNavDataAsync(c); + Check(File.ReadAllText(Path.Combine(nav, "nav_A9B4.tile")) == "tile A9B4 v2", "a later try installs"); + } + + private static async Task CancelledUnpackLeavesTilesAsTheyWere() + { + byte[] zip = Zip(BigTileSet()); + var (upd, nav, plugin, _) = SetupInFeedFolder("cancelunpack", zip); + OldNavData(nav); + var c = await upd.CheckAsync(new[] { plugin }); + using var cts = new CancellationTokenSource(); + bool threw = false; + try { await upd.UpdateNavDataAsync(c, new SyncProgress(p => { if (p.Stage == DownloadStage.Unpacking) cts.Cancel(); }), cts.Token); } + catch (OperationCanceledException) { threw = true; } + Check(threw, "Cancel while unpacking stops it"); + Check(File.ReadAllText(Path.Combine(nav, "nav_A9B4.tile")) == "tile A9B4 June" && File.Exists(Path.Combine(nav, "nav_0101.tile")), "the installed tiles are as they were"); + Check(!Directory.Exists(nav + ".new") && !Directory.Exists(nav + ".previous"), "no staging folder, no swap"); + string cache = Path.Combine(_root, "cancelunpack", "cache"); + Check(Directory.GetFiles(cache, "*.part").Length == 0, "no partial file in the cache (the verified archive may stay for the next try)"); + } + + private static async Task TamperedArchiveRefusedWithProgress() + { + byte[] zip = Zip(BigTileSet()); + var (upd, nav, plugin, _) = SetupInFeedFolder("tamperprog", zip); + OldNavData(nav); + var c = await upd.CheckAsync(new[] { plugin }); + byte[] bad = (byte[])zip.Clone(); bad[bad.Length / 3] ^= 0x55; + lock (Served) Served["tamperprog/releases/1/RynthNav-NavData.zip"] = bad; + var reports = new List<DownloadProgress>(); + bool threw = false; + try { await upd.UpdateNavDataAsync(c, new SyncProgress(reports.Add)); } catch (InvalidDataException) { threw = true; } + Check(threw, "with progress on, a wrong hash is still refused"); + Check(!reports.Any(r => r.Stage is DownloadStage.Verified or DownloadStage.Unpacking), "never reported as verified, never unpacked"); + string cache = Path.Combine(_root, "tamperprog", "cache"); + Check(Directory.GetFiles(cache).Length == 0, "the bad download is deleted"); + Check(File.ReadAllText(Path.Combine(nav, "nav_A9B4.tile")) == "tile A9B4 June", "and nothing changes"); + } + + private static async Task RejectsUnsignedNavData() + { + var (upd, nav, plugin, _) = SetupInFeedFolder("unsigned", Zip(TileSet), signNavData: false); + bool threw = false; + try { await upd.CheckAsync(new[] { plugin }); } catch (InvalidDataException) { threw = true; } + Check(threw, "a navdata entry added after signing breaks the signature"); + } +} diff --git a/tools/ProcPatchDiff.py b/tools/ProcPatchDiff.py new file mode 100644 index 0000000..ef11505 --- /dev/null +++ b/tools/ProcPatchDiff.py @@ -0,0 +1,395 @@ +"""ProcPatchDiff - which code in a running 32-bit process was patched, and by whom. + +Read-only. For each module it compares the executable sections in memory with the +on-disk image (relocated to the module's actual base) and lists every changed byte run. +A run that starts with a jump (E9 rel32, EB rel8 -> E9, FF25 [abs], 68 imm32 C3) is +followed - through simple jump stubs only - to the module that owns the destination, +which names the patcher. It also checks acclient.exe's import table (IAT hooks) and the +game window's WndProc. It never disassembles anything beyond reading one jump at a time. + +Spike tool for the Decal-bridge analysis (docs: spikes/decal-bridge). Point it at TEST +clients only. + + python tools/ProcPatchDiff.py <pid> [--all] [--names <RynthCore.<pid>.log>] [--json out.json] + +--all diff every module with a file on disk (default: acclient.exe + the system DLLs + AC and its hookers use) +--names annotate acclient.exe addresses with HookResolver names from an engine log +""" +import ctypes +import ctypes.wintypes as wt +import json +import os +import re +import struct +import sys + +import pefile + +PROCESS_QUERY_INFORMATION = 0x0400 +PROCESS_VM_READ = 0x0010 +LIST_MODULES_32BIT = 0x01 +IMAGE_SCN_MEM_EXECUTE = 0x20000000 + +k32 = ctypes.WinDLL("kernel32", use_last_error=True) +psapi = ctypes.WinDLL("psapi", use_last_error=True) +user32 = ctypes.WinDLL("user32", use_last_error=True) + +k32.OpenProcess.restype = wt.HANDLE +k32.OpenProcess.argtypes = [wt.DWORD, wt.BOOL, wt.DWORD] +k32.ReadProcessMemory.argtypes = [wt.HANDLE, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t)] +k32.VirtualQueryEx.restype = ctypes.c_size_t +k32.VirtualQueryEx.argtypes = [wt.HANDLE, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t] +psapi.EnumProcessModulesEx.argtypes = [wt.HANDLE, ctypes.POINTER(ctypes.c_void_p), wt.DWORD, ctypes.POINTER(wt.DWORD), wt.DWORD] +psapi.GetModuleFileNameExW.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.LPWSTR, wt.DWORD] + + +class MODULEINFO(ctypes.Structure): + _fields_ = [("lpBaseOfDll", ctypes.c_void_p), ("SizeOfImage", wt.DWORD), ("EntryPoint", ctypes.c_void_p)] + + +class MBI(ctypes.Structure): + _fields_ = [("BaseAddress", ctypes.c_ulonglong), ("AllocationBase", ctypes.c_ulonglong), + ("AllocationProtect", wt.DWORD), ("__a1", wt.DWORD), ("RegionSize", ctypes.c_ulonglong), + ("State", wt.DWORD), ("Protect", wt.DWORD), ("Type", wt.DWORD), ("__a2", wt.DWORD)] + + +psapi.GetModuleInformation.argtypes = [wt.HANDLE, ctypes.c_void_p, ctypes.POINTER(MODULEINFO), wt.DWORD] + +DEFAULT_MODULES = { + "acclient.exe", "kernel32.dll", "kernelbase.dll", "ntdll.dll", "user32.dll", "win32u.dll", + "gdi32.dll", "d3d9.dll", "dinput8.dll", "dinput.dll", "ws2_32.dll", "wsock32.dll", + "mswsock.dll", "winmm.dll", "ole32.dll", "combase.dll", "imm32.dll", "dsound.dll", +} + + +class Proc: + def __init__(self, pid): + self.pid = pid + self.h = k32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid) + if not self.h: + raise OSError(f"OpenProcess({pid}) failed: {ctypes.get_last_error()}") + self.mods = self._modules() + + def read(self, addr, size): + buf = ctypes.create_string_buffer(size) + got = ctypes.c_size_t(0) + if not k32.ReadProcessMemory(self.h, ctypes.c_void_p(addr), buf, size, ctypes.byref(got)): + return None + return buf.raw[: got.value] + + def dword(self, addr): + b = self.read(addr, 4) + return struct.unpack("<I", b)[0] if b and len(b) == 4 else None + + def _modules(self): + arr = (ctypes.c_void_p * 1024)() + needed = wt.DWORD(0) + if not psapi.EnumProcessModulesEx(self.h, arr, ctypes.sizeof(arr), ctypes.byref(needed), LIST_MODULES_32BIT): + raise OSError(f"EnumProcessModulesEx failed: {ctypes.get_last_error()}") + mods = [] + for i in range(needed.value // ctypes.sizeof(ctypes.c_void_p)): + hm = arr[i] + name = ctypes.create_unicode_buffer(520) + psapi.GetModuleFileNameExW(self.h, hm, name, 520) + mi = MODULEINFO() + psapi.GetModuleInformation(self.h, hm, ctypes.byref(mi), ctypes.sizeof(mi)) + path = name.value + # A 64-bit reader is told System32 for a WOW64 process's DLLs; the 32-bit + # files it actually loaded live in SysWOW64. + sys32 = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32") + "\\" + if path.lower().startswith(sys32.lower()) and (mi.lpBaseOfDll or 0) < 0x100000000: + wow = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "SysWOW64", path[len(sys32):]) + if os.path.exists(wow): + path = wow + mods.append({"base": mi.lpBaseOfDll or 0, "size": mi.SizeOfImage, "path": path, + "name": os.path.basename(path)}) + return sorted(mods, key=lambda m: m["base"]) + + def module_at(self, addr): + for m in self.mods: + if m["base"] <= addr < m["base"] + m["size"]: + return m + return None + + def alloc_base(self, addr): + mbi = MBI() + if k32.VirtualQueryEx(self.h, ctypes.c_void_p(addr), ctypes.byref(mbi), ctypes.sizeof(mbi)) == 0: + return None + return mbi.AllocationBase + + +def decode_jump(p, addr): + """Destination of a simple jump at addr, or None. Reads only the jump itself.""" + b = p.read(addr, 8) + if not b or len(b) < 6: + return None + if b[0] == 0xE9: + return (addr + 5 + struct.unpack("<i", b[1:5])[0]) & 0xFFFFFFFF, "jmp rel32" + if b[0] == 0xEB: + return (addr + 2 + struct.unpack("<b", b[1:2])[0]) & 0xFFFFFFFF, "jmp rel8" + if b[0] == 0xFF and b[1] == 0x25: + slot = struct.unpack("<I", b[2:6])[0] + dst = p.dword(slot) + return (dst, f"jmp [0x{slot:08X}]") if dst is not None else None + if b[0] == 0x68 and b[5] == 0xC3: + return struct.unpack("<I", b[1:5])[0], "push/ret" + return None + + +def owner_of(p, addr, hops=5): + """Follow simple jump stubs from addr; return (owner description, chain).""" + chain = [] + cur = addr + for _ in range(hops): + m = p.module_at(cur) + if m is not None: + chain.append(f"{m['name']}+0x{cur - m['base']:X}") + return m["name"], chain + j = decode_jump(p, cur) + ab = p.alloc_base(cur) + chain.append(f"private@0x{cur:08X}(alloc 0x{(ab or 0):08X})") + head = p.read(cur, 10) or b"" + if len(head) == 10 and head[0] == 0xB8 and head[5] == 0xE9: + # mov eax, <entry>; jmp <stub>: the .NET Framework reverse-P/Invoke thunk shape, + # i.e. a delegate from managed code (a .NET extension) is the hook. + return "managed thunk (.NET delegate)", chain + if j is None: + return f"private(alloc 0x{(ab or 0):08X})", chain + dst, kind = j + if kind.startswith("jmp [") : + slot = int(re.search(r"0x([0-9A-Fa-f]+)", kind).group(1), 16) + sm = p.module_at(slot) + if sm is not None: + # A stub whose slot lives in a module (e.g. the RynthCore loader's facade). + chain.append(f"slot in {sm['name']}") + dm = p.module_at(dst) + return (f"{sm['name']} stub -> {dm['name'] if dm else 'private'}"), chain + cur = dst + return "unresolved", chain + + +def export_names(pe, base): + names = {} + if hasattr(pe, "DIRECTORY_ENTRY_EXPORT"): + for e in pe.DIRECTORY_ENTRY_EXPORT.symbols: + if e.name: + names[base + e.address] = e.name.decode(errors="replace") + return names + + +def nearest_name(addr, names): + best = None + for a, n in names.items(): + if a <= addr and (best is None or a > best[0]): + best = (a, n) + if best is None or addr - best[0] > 0x40: + return None + return best[1] if best[0] == addr else f"{best[1]}+0x{addr - best[0]:X}" + + +def diff_module(p, m, names_extra=None): + try: + pe = pefile.PE(m["path"], fast_load=True) + except Exception as ex: + return {"module": m["name"], "error": str(ex)} + pe.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_BASERELOC"], + pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_EXPORT"], + pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_IMPORT"]]) + # System DLLs keep their IAT inside .text: name the slots so an IAT hook reads as one. + iat_names = {} + for ent in getattr(pe, "DIRECTORY_ENTRY_IMPORT", []): + for imp in ent.imports: + nm = (imp.name or b"#" + str(imp.ordinal).encode()).decode(errors="replace") + iat_names[imp.address - pe.OPTIONAL_HEADER.ImageBase + m["base"]] = f"{ent.dll.decode()}!{nm}" + if pe.OPTIONAL_HEADER.ImageBase != m["base"]: + pe.relocate_image(m["base"]) + names = export_names(pe, m["base"]) + if names_extra: + names.update(names_extra) + patches = [] + for s in pe.sections: + if not (s.Characteristics & IMAGE_SCN_MEM_EXECUTE): + continue + size = min(s.Misc_VirtualSize or s.SizeOfRawData, s.SizeOfRawData) + disk = pe.get_data(s.VirtualAddress, size) + mem = p.read(m["base"] + s.VirtualAddress, size) + if mem is None or len(mem) != len(disk): + patches.append({"section": s.Name.rstrip(b"\0").decode(), "error": "unreadable"}) + continue + runs = [] + CH = 4096 + for off in range(0, size, CH): + if disk[off:off + CH] == mem[off:off + CH]: + continue + for i in range(off, min(off + CH, size)): + if disk[i] != mem[i]: + if runs and i - runs[-1][1] <= 4: + runs[-1][1] = i + 1 + else: + runs.append([i, i + 1]) + for a, b in runs: + va = m["base"] + s.VirtualAddress + a + # A MinHook-style patch can keep its first byte (rare); start the decode a byte early + # when the run doesn't begin with a known jump opcode. + start = va + j = decode_jump(p, start) + if j is None and a > 0: + j2 = decode_jump(p, va - 1) + if j2 is not None: + start, j = va - 1, j2 + entry = { + "va": f"0x{start:08X}", "rva": f"0x{start - m['base']:X}", "len": b - a, + "name": nearest_name(start, names), + "disk": disk[a:b][:16].hex(), "mem": mem[a:b][:16].hex(), + } + if j is not None: + dst, kind = j + own, chain = owner_of(p, dst) + entry.update({"kind": kind, "dest": f"0x{dst:08X}", "owner": own, "chain": chain}) + elif b - a == 4 and a > 0 and mem[a - 1] in (0xE8, 0xE9) and disk[a - 1] == mem[a - 1]: + # The rel32 of an existing call/jmp was re-pointed: a call-site hook. + site = va - 1 + dst = (va + 4 + struct.unpack("<i", mem[a:b])[0]) & 0xFFFFFFFF + orig = (va + 4 + struct.unpack("<i", disk[a:b])[0]) & 0xFFFFFFFF + own, chain = owner_of(p, dst) + entry.update({"va": f"0x{site:08X}", "kind": "call-site" if mem[a - 1] == 0xE8 else "jmp-site", + "dest": f"0x{dst:08X}", "orig_dest": f"0x{orig:08X}", + "orig_name": nearest_name(orig, names), "owner": own, "chain": chain}) + elif b - a == 4 and iat_names and va in iat_names: + val = struct.unpack("<I", mem[a:b])[0] + own, chain = owner_of(p, val) + entry.update({"kind": f"IAT slot {iat_names[va]}", "dest": f"0x{val:08X}", "owner": own, "chain": chain}) + elif b - a == 4: + val = struct.unpack("<I", mem[a:b])[0] + own, chain = owner_of(p, val) + entry.update({"kind": "pointer?", "dest": f"0x{val:08X}", "owner": own, "chain": chain}) + else: + entry.update({"kind": "data/other", "owner": "?"}) + patches.append(entry) + return {"module": m["name"], "base": f"0x{m['base']:08X}", "patches": patches} + + +def check_iat(p, m): + pe = pefile.PE(m["path"], fast_load=True) + pe.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_IMPORT"]]) + delta = m["base"] - pe.OPTIONAL_HEADER.ImageBase + out = [] + for entry in getattr(pe, "DIRECTORY_ENTRY_IMPORT", []): + dll = entry.dll.decode().lower() + for imp in entry.imports: + slot = imp.address + delta + val = p.dword(slot) + if val is None: + continue + owner = p.module_at(val) + oname = owner["name"].lower() if owner else "private" + system = owner is not None and owner["path"].lower().startswith(r"c:\windows") + if not system and oname != dll: + own, chain = owner_of(p, val) + out.append({"import": f"{dll}!{(imp.name or b'#'+str(imp.ordinal).encode()).decode()}", + "slot": f"0x{slot:08X}", "value": f"0x{val:08X}", "owner": own, "chain": chain}) + return out + + +def check_wndproc(p): + out = [] + GWL_WNDPROC = -4 + EnumWindowsProc = ctypes.WINFUNCTYPE(wt.BOOL, wt.HWND, wt.LPARAM) + hwnds = [] + + def cb(hwnd, _): + pid = wt.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) + if pid.value == p.pid: + hwnds.append(hwnd) + return True + + user32.GetWindowThreadProcessId.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.DWORD)] + user32.GetWindowTextW.argtypes = [ctypes.c_void_p, wt.LPWSTR, ctypes.c_int] + user32.IsWindowVisible.argtypes = [ctypes.c_void_p] + user32.EnumWindows(EnumWindowsProc(cb), 0) + user32.GetClassNameW.argtypes = [ctypes.c_void_p, wt.LPWSTR, ctypes.c_int] + for hw in hwnds: + cls = ctypes.create_unicode_buffer(256) + user32.GetClassNameW(hw, cls, 256) + title = ctypes.create_unicode_buffer(256) + user32.GetWindowTextW(hw, title, 256) + wp = 0 # GWL_WNDPROC is not answered across processes; the engine logs its chain in-process + own, chain = owner_of(p, wp) if wp else ("?", []) + out.append({"hwnd": f"0x{hw:X}", "class": cls.value, "title": title.value, + "wndproc": f"0x{wp:08X}", "owner": own, "chain": chain, + "visible": bool(user32.IsWindowVisible(hw))}) + return out + + +def names_from_log(path): + names = {} + if not path: + return names + rx = re.compile(r"HookResolver\[([^\]]+)\]: RESOLVED via [\w-]+ @ 0x([0-9A-Fa-f]{8})") + rx2 = re.compile(r"(\w+Hooks?): .*?(?:hooked|target=|ready @) ?.*?0x([0-9A-Fa-f]{8})") + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + mm = rx.search(line) + if mm: + names.setdefault(int(mm.group(2), 16), mm.group(1)) + return names + + +def main(): + if len(sys.argv) < 2: + print(__doc__) + return 1 + pid = int(sys.argv[1]) + args = sys.argv[2:] + all_mods = "--all" in args + log = args[args.index("--names") + 1] if "--names" in args else None + js = args[args.index("--json") + 1] if "--json" in args else None + p = Proc(pid) + extra = names_from_log(log) + result = {"pid": pid, "modules": [], "diffs": [], "iat": [], "wndproc": []} + for m in p.mods: + result["modules"].append({"name": m["name"], "base": f"0x{m['base']:08X}", "size": m["size"], "path": m["path"]}) + for m in p.mods: + if not (all_mods or m["name"].lower() in DEFAULT_MODULES): + continue + if not os.path.exists(m["path"]): + continue + d = diff_module(p, m, extra if m["name"].lower() == "acclient.exe" else None) + if d.get("patches") or d.get("error"): + result["diffs"].append(d) + for m in p.mods: + if m["name"].lower() == "acclient.exe": + result["iat"] = check_iat(p, m) + result["wndproc"] = check_wndproc(p) + + print(f"pid {pid}: {len(p.mods)} modules") + interesting = [m["name"] for m in p.mods if not m["path"].lower().startswith(r"c:\windows")] + print("non-system modules: " + ", ".join(interesting)) + for d in result["diffs"]: + if d.get("error"): + print(f"== {d['module']}: {d['error']}") + continue + print(f"== {d['module']} @ {d['base']}: {len(d['patches'])} patched run(s)") + for e in d["patches"]: + if "error" in e: + print(f" {e}") + continue + od = f" (was -> {e['orig_dest']} {e.get('orig_name') or ''})" if e.get('orig_dest') else '' + print(f" {e['va']} {e.get('name') or ''} len={e['len']} {e.get('kind','')} -> {e.get('dest','')}{od} " + f"owner={e.get('owner')} [{' > '.join(e.get('chain', []))}] disk={e['disk']} mem={e['mem']}") + print(f"== IAT (acclient.exe) entries pointing outside system DLLs: {len(result['iat'])}") + for e in result["iat"]: + print(f" {e['import']} slot={e['slot']} -> {e['value']} owner={e['owner']}") + print("== windows") + for w in result["wndproc"]: + print(f" {w['hwnd']} class={w['class']!r} title={w['title']!r} visible={w['visible']} wndproc={w['wndproc']} owner={w['owner']} [{' > '.join(w['chain'])}]") + if js: + with open(js, "w", encoding="utf-8") as f: + json.dump(result, f, indent=1) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/PropertyWireTests/AceWire.cs b/tools/PropertyWireTests/AceWire.cs new file mode 100644 index 0000000..a624ea2 --- /dev/null +++ b/tools/PropertyWireTests/AceWire.cs @@ -0,0 +1,229 @@ +using System.Text; + +namespace PropertyWireTests; + +/// <summary> +/// Builds messages byte for byte the way ACE writes them, from the part the client's +/// UIQueueManager::ProcessNetBlobData hands on: a game event from its event type (the 0xF7B0 +/// header - guid, sequence - is already stripped), a top-level message from its opcode. +/// Each writer below mirrors the ACE.Server code named in its comment. +/// </summary> +internal sealed class AceMessage +{ + private readonly MemoryStream _ms = new(); + public readonly BinaryWriter W; + + private AceMessage(uint first) + { + W = new BinaryWriter(_ms); + W.Write(first); + } + + /// <summary>GameEventMessage: [F7B0][guid][seq][event type] - the client sees the type on.</summary> + public static AceMessage GameEvent(uint eventType) => new(eventType); + + /// <summary>GameMessage: the opcode, then the body.</summary> + public static AceMessage Message(uint opcode) => new(opcode); + + public byte[] ToArray() => _ms.ToArray(); + + private static uint PadMultiple(uint length, uint multiple) => multiple * ((length + multiple - 1u) / multiple) - length; + + /// <summary>ACE Extensions.WriteString16L: u16 length, cp1252 bytes, pad (2 + length) to 4.</summary> + public void String16L(string data) + { + W.Write((ushort)data.Length); + W.Write(Encoding.Latin1.GetBytes(data)); + W.Write(new byte[PadMultiple(2u + (uint)data.Length, 4u)]); + } + + /// <summary>ACE Extensions.Align: pad the stream to a multiple of 4.</summary> + public void Align() => W.Write(new byte[PadMultiple((uint)_ms.Length, 4u)]); + + /// <summary>ACE PackableHashTable.WriteHeader: u16 count, u16 bucket count.</summary> + public void HashHeader(int count, int buckets) + { + W.Write((ushort)count); + W.Write((ushort)buckets); + } + + public void IntTable(Dictionary<uint, int> t) { HashHeader(t.Count, 16); foreach (var kv in t) { W.Write(kv.Key); W.Write(kv.Value); } } + public void Int64Table(Dictionary<uint, long> t) { HashHeader(t.Count, 8); foreach (var kv in t) { W.Write(kv.Key); W.Write(kv.Value); } } + public void BoolTable(Dictionary<uint, bool> t) { HashHeader(t.Count, 8); foreach (var kv in t) { W.Write(kv.Key); W.Write(Convert.ToUInt32(kv.Value)); } } + public void FloatTable(Dictionary<uint, double> t) { HashHeader(t.Count, 8); foreach (var kv in t) { W.Write(kv.Key); W.Write(kv.Value); } } + public void StringTable(Dictionary<uint, string> t) { HashHeader(t.Count, 8); foreach (var kv in t) { W.Write(kv.Key); String16L(kv.Value); } } + public void UIntTable(Dictionary<uint, uint> t) { HashHeader(t.Count, 8); foreach (var kv in t) { W.Write(kv.Key); W.Write(kv.Value); } } +} + +/// <summary>ACE ArmorProfile: slash, pierce, bludgeon, cold, fire, acid, nether, lightning.</summary> +internal sealed record ArmorProfile(float Slash, float Pierce, float Bludgeon, float Cold, float Fire, float Acid, float Nether, float Lightning); + +/// <summary>ACE CreatureProfile (Flags: HasBuffsDebuffs 0x1, ShowAttributes 0x8).</summary> +internal sealed record CreatureProfile(uint Flags, uint Health, uint HealthMax, uint[]? Attributes = null, ushort Highlights = 0, ushort Colors = 0); + +/// <summary>ACE WeaponProfile.</summary> +internal sealed record WeaponProfile(uint DamageType, uint WeaponTime, uint WeaponSkill, uint Damage, + double DamageVariance, double DamageMod, double WeaponLength, double MaxVelocity, double WeaponOffense, uint MaxVelocityEstimated = 0); + +/// <summary>ACE HookProfile (Flags: Inscribable 1, IsHealer 2, IsFood 4, IsLockpick 8).</summary> +internal sealed record HookProfile(uint Flags, uint ValidLocations, uint AmmoType); + +/// <summary>ACE AppraiseInfo: what BuildProfile leaves in it; Write() below mirrors AppraiseInfoExtensions.Write.</summary> +internal sealed class AppraiseInfo +{ + public bool Success = true; + public Dictionary<uint, int> Ints = new(); + public Dictionary<uint, long> Int64s = new(); + public Dictionary<uint, bool> Bools = new(); + public Dictionary<uint, double> Floats = new(); + public Dictionary<uint, string> Strings = new(); + public Dictionary<uint, uint> Dids = new(); + public List<uint> SpellBook = new(); + public ArmorProfile? Armor; + public CreatureProfile? Creature; + public WeaponProfile? Weapon; + public HookProfile? Hook; + public ushort ArmorHighlight, ArmorColor, WeaponHighlight, WeaponColor, ResistHighlight, ResistColor; + public uint[]? ArmorLevels; // 9 values + + // ACE IdentifyResponseFlags + private const uint IntStatsTable = 0x0001, BoolStatsTable = 0x0002, FloatStatsTable = 0x0004, StringStatsTable = 0x0008, + SpellBookF = 0x0010, WeaponProfileF = 0x0020, HookProfileF = 0x0040, ArmorProfileF = 0x0080, CreatureProfileF = 0x0100, + ArmorEnchantmentBitfield = 0x0200, ResistEnchantmentBitfield = 0x0400, WeaponEnchantmentBitfield = 0x0800, + DidStatsTable = 0x1000, Int64StatsTable = 0x2000, ArmorLevelsF = 0x4000; + + /// <summary>ACE AppraiseInfo.BuildFlags.</summary> + public uint Flags + { + get + { + uint f = 0; + if (Ints.Count > 0) f |= IntStatsTable; + if (Int64s.Count > 0) f |= Int64StatsTable; + if (Bools.Count > 0) f |= BoolStatsTable; + if (Floats.Count > 0) f |= FloatStatsTable; + if (Strings.Count > 0) f |= StringStatsTable; + if (Dids.Count > 0) f |= DidStatsTable; + if (SpellBook.Count > 0) f |= SpellBookF; + if (ResistHighlight != 0) f |= ResistEnchantmentBitfield; + if (Armor != null) f |= ArmorProfileF; + if (Creature != null) f |= CreatureProfileF; + if (Weapon != null) f |= WeaponProfileF; + if (Hook != null) f |= HookProfileF; + if (ArmorHighlight != 0) f |= ArmorEnchantmentBitfield; + if (WeaponHighlight != 0) f |= WeaponEnchantmentBitfield; + if (ArmorLevels != null) f |= ArmorLevelsF; + return f; + } + } + + /// <summary>GameEventIdentifyObjectResponse: the object guid, then AppraiseInfoExtensions.Write.</summary> + public byte[] ToIdentifyMessage(uint guid) + { + var m = AceMessage.GameEvent(0x00C9); + var w = m.W; + w.Write(guid); + uint flags = Flags; + w.Write(flags); + w.Write(Convert.ToUInt32(Success)); + if ((flags & IntStatsTable) != 0) m.IntTable(Ints); + if ((flags & Int64StatsTable) != 0) m.Int64Table(Int64s); + if ((flags & BoolStatsTable) != 0) m.BoolTable(Bools); + if ((flags & FloatStatsTable) != 0) m.FloatTable(Floats); + if ((flags & StringStatsTable) != 0) m.StringTable(Strings); + if ((flags & DidStatsTable) != 0) m.UIntTable(Dids); + if ((flags & SpellBookF) != 0) { w.Write(SpellBook.Count); foreach (uint s in SpellBook) w.Write(s); } // PackableList + if (Armor is { } a) + { + w.Write(a.Slash); w.Write(a.Pierce); w.Write(a.Bludgeon); w.Write(a.Cold); + w.Write(a.Fire); w.Write(a.Acid); w.Write(a.Nether); w.Write(a.Lightning); + } + if (Creature is { } c) + { + w.Write(c.Flags); w.Write(c.Health); w.Write(c.HealthMax); + if ((c.Flags & 0x8) != 0) + foreach (uint v in c.Attributes ?? new uint[10]) w.Write(v); + if ((c.Flags & 0x1) != 0) { w.Write(c.Highlights); w.Write(c.Colors); } + } + if (Weapon is { } p) + { + w.Write(p.DamageType); w.Write(p.WeaponTime); w.Write(p.WeaponSkill); w.Write(p.Damage); + w.Write(p.DamageVariance); w.Write(p.DamageMod); w.Write(p.WeaponLength); w.Write(p.MaxVelocity); + w.Write(p.WeaponOffense); w.Write(p.MaxVelocityEstimated); + } + if (Hook is { } h) { w.Write(h.Flags); w.Write(h.ValidLocations); w.Write(h.AmmoType); } + if ((flags & ArmorEnchantmentBitfield) != 0) { w.Write(ArmorHighlight); w.Write(ArmorColor); } + if ((flags & WeaponEnchantmentBitfield) != 0) { w.Write(WeaponHighlight); w.Write(WeaponColor); } + if ((flags & ResistEnchantmentBitfield) != 0) { w.Write(ResistHighlight); w.Write(ResistColor); } + if (ArmorLevels != null) foreach (uint v in ArmorLevels) w.Write(v); + return m.ToArray(); + } +} + +/// <summary>The property part of ACE GameEventPlayerDescription.WriteEventBody (and a tail after it).</summary> +internal sealed class PlayerDescription +{ + public Dictionary<uint, int> Ints = new(); + public Dictionary<uint, long> Int64s = new(); + public Dictionary<uint, bool> Bools = new(); + public Dictionary<uint, double> Floats = new(); + public Dictionary<uint, string> Strings = new(); + public Dictionary<uint, uint> Dids = new(); + public Dictionary<uint, uint> Iids = new(); + + public byte[] ToMessage() + { + var m = AceMessage.GameEvent(0x0013); + var w = m.W; + uint f = 0; + if (Ints.Count > 0) f |= 0x0001; + if (Int64s.Count > 0) f |= 0x0080; + if (Bools.Count > 0) f |= 0x0002; + if (Floats.Count > 0) f |= 0x0004; + if (Strings.Count > 0) f |= 0x0010; + if (Dids.Count > 0) f |= 0x0008; + if (Iids.Count > 0) f |= 0x0040; + f |= 0x0020; // Position (LastOutsideDeath): follows the tables, not read + w.Write(f); + w.Write(1u); // WeenieType.Creature... (Player = 43, the value is skipped) + if (Ints.Count > 0) m.IntTable(Ints); + if (Int64s.Count > 0) m.Int64Table(Int64s); + if (Bools.Count > 0) m.BoolTable(Bools); + if (Floats.Count > 0) m.FloatTable(Floats); + if (Strings.Count > 0) m.StringTable(Strings); + if (Dids.Count > 0) m.UIntTable(Dids); + if (Iids.Count > 0) m.UIntTable(Iids); + // Position table (1 entry, 16 buckets) + the vectors, options and inventory that follow. + m.HashHeader(1, 16); + w.Write(14u); // PositionType.LastOutsideDeath + w.Write(0x7D640013u); w.Write(10f); w.Write(20f); w.Write(30f); w.Write(1f); w.Write(0f); w.Write(0f); w.Write(0f); + w.Write(0x00000303u); // vector flags ... (garbage to the parser) + return m.ToArray(); + } +} + +/// <summary>ACE GameMessage{Private,Public}UpdateProperty* / UpdateDataID / UpdateInstanceID.</summary> +internal static class Updates +{ + private const byte Seq = 0x5A; + + public static byte[] PrivateInt(uint key, int v) { var m = AceMessage.Message(0x02CD); m.W.Write(Seq); m.W.Write(key); m.W.Write(v); return m.ToArray(); } + public static byte[] PublicInt(uint guid, uint key, int v) { var m = AceMessage.Message(0x02CE); m.W.Write(Seq); m.W.Write(guid); m.W.Write(key); m.W.Write(v); return m.ToArray(); } + public static byte[] PrivateInt64(uint key, long v) { var m = AceMessage.Message(0x02CF); m.W.Write(Seq); m.W.Write(key); m.W.Write(v); return m.ToArray(); } + public static byte[] PublicInt64(uint guid, uint key, long v) { var m = AceMessage.Message(0x02D0); m.W.Write(Seq); m.W.Write(guid); m.W.Write(key); m.W.Write(v); return m.ToArray(); } + public static byte[] PrivateBool(uint key, bool v) { var m = AceMessage.Message(0x02D1); m.W.Write(Seq); m.W.Write(key); m.W.Write(Convert.ToUInt32(v)); return m.ToArray(); } + public static byte[] PublicBool(uint guid, uint key, bool v) { var m = AceMessage.Message(0x02D2); m.W.Write(Seq); m.W.Write(guid); m.W.Write(key); m.W.Write(Convert.ToUInt32(v)); return m.ToArray(); } + public static byte[] PrivateFloat(uint key, double v) { var m = AceMessage.Message(0x02D3); m.W.Write(Seq); m.W.Write(key); m.W.Write(v); return m.ToArray(); } + public static byte[] PublicFloat(uint guid, uint key, double v) { var m = AceMessage.Message(0x02D4); m.W.Write(Seq); m.W.Write(guid); m.W.Write(key); m.W.Write(v); return m.ToArray(); } + + /// <summary>GameMessagePrivateUpdatePropertyString: seq, key, Align(), WriteString16L.</summary> + public static byte[] PrivateString(uint key, string v) { var m = AceMessage.Message(0x02D5); m.W.Write(Seq); m.W.Write(key); m.Align(); m.String16L(v); return m.ToArray(); } + + /// <summary>GameMessagePublicUpdatePropertyString: seq, key, THEN guid, Align(), WriteString16L.</summary> + public static byte[] PublicString(uint guid, uint key, string v) { var m = AceMessage.Message(0x02D6); m.W.Write(Seq); m.W.Write(key); m.W.Write(guid); m.Align(); m.String16L(v); return m.ToArray(); } + + public static byte[] PrivateDataId(uint key, uint v) { var m = AceMessage.Message(0x02D7); m.W.Write(Seq); m.W.Write(key); m.W.Write(v); return m.ToArray(); } + public static byte[] PublicDataId(uint guid, uint key, uint v) { var m = AceMessage.Message(0x02D8); m.W.Write(Seq); m.W.Write(guid); m.W.Write(key); m.W.Write(v); return m.ToArray(); } + public static byte[] PrivateInstanceId(uint key, uint v) { var m = AceMessage.Message(0x02D9); m.W.Write(Seq); m.W.Write(key); m.W.Write(v); return m.ToArray(); } + public static byte[] PublicInstanceId(uint guid, uint key, uint v) { var m = AceMessage.Message(0x02DA); m.W.Write(Seq); m.W.Write(guid); m.W.Write(key); m.W.Write(v); return m.ToArray(); } +} diff --git a/tools/PropertyWireTests/Program.cs b/tools/PropertyWireTests/Program.cs new file mode 100644 index 0000000..a23cdc9 --- /dev/null +++ b/tools/PropertyWireTests/Program.cs @@ -0,0 +1,466 @@ +using System.Buffers.Binary; +using RynthCore.Engine.Compatibility; + +namespace PropertyWireTests; + +/// <summary> +/// One identify reply, update set or PublicWeenieDesc per kind of object, built the way ACE +/// writes them, through the engine's parsers; every value the engine would cache is checked. +/// </summary> +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private const uint Me = 0x50000001, Other = 0x50000002, Leggings = 0x80000101, Sword = 0x80000102, + Scroll = 0x80000103, Drudge = 0x80000201, Door = 0x7A9B4001, Portal = 0x7A9B4002, Chest = 0x7A9B4003, + Corpse = 0x80000301, HookObj = 0x7A9B4004; + + private static int Main() + { + PackItemIdentified(); + PackItemNotIdentified(); + WornWeapon(); + CreatureIdentified(); + CreatureFailedRoll(); + CreatureNotIdentified(); + OtherPlayer(); + LandscapeDoorPortalChest(); + CorpseIdentified(); + HouseHook(); + PlayerSelf(); + UpdatesEveryType(); + StringUpdateAlignment(); + TruncatedAndBadInput(); + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL PROPERTY WIRE TESTS PASSED." : $"{_failed} FAILED."); + return _failed == 0 ? 0 : 1; + } + + // ── object kinds ──────────────────────────────────────────────────────── + + /// <summary>Studded Leather Leggings: tables, spells, armour profile + armour highlights, armour levels.</summary> + private static void PackItemIdentified() + { + Case("pack item, identified (armour)"); + var a = new AppraiseInfo + { + Ints = { [1] = 2, [5] = 900, [19] = 1200, [28] = 120, [105] = 6, [106] = 180, [109] = 210, [158] = 7, [159] = 0, [160] = 150, [131] = 42 }, + Bools = { [69] = true }, + Strings = { [16] = "Studded Leather Leggings of Acid Protection" }, + Dids = { [37] = 0x0000002C }, + SpellBook = { 1391, 2092 }, + Armor = new ArmorProfile(1.1f, 0.9f, 0.8f, 0.6f, 0.4f, 1.3f, 0.5f, 0.7f), + ArmorHighlight = 0x0003, ArmorColor = 0x0001, + ArmorLevels = new uint[] { 0, 0, 120, 0, 0, 0, 120, 120, 0 }, + }; + IdentifyRecord r = Identify(a, Leggings); + Check(r.ObjectId == Leggings && r.Success && !r.Truncated, "header"); + Check(r.HasArmorProfile && !r.HasWeaponProfile && !r.HasCreatureProfile && !r.HasHookProfile, "profile flags"); + Eq(r.SpellCount, 2, "spell count"); + // Tables as sent, plus the eight ratings as ArmorModVs* (slash 13 .. acid 18, nether 165, electric 19). + var floats = new Dictionary<uint, double> + { + [13] = 1.1f, [14] = 0.9f, [15] = 0.8f, [16] = 0.6f, [17] = 0.4f, [18] = 1.3f, [165] = 0.5f, [19] = 0.7f, + }; + ExpectBag(r.Properties, ints: a.Ints, bools: a.Bools, floats: floats, strings: a.Strings, dids: a.Dids); + } + + /// <summary>An item never identified: the client knows only its CreateObject (PublicWeenieDesc).</summary> + private static void PackItemNotIdentified() + { + Case("pack item, not identified (PublicWeenieDesc)"); + var pwd = new byte[PwdLayout.Size]; + void U32(int off, uint v) => BinaryPrimitives.WriteUInt32LittleEndian(pwd.AsSpan(off), v); + U32(PwdLayout.Wcid, 20630); U32(PwdLayout.Icon, 0x06001F4A); U32(PwdLayout.IconOverlay, 0x06006C0A); + U32(PwdLayout.Container, Me); U32(PwdLayout.Priority, 0x4000); U32(PwdLayout.ValidLocations, 0x2000); + U32(PwdLayout.Type, 0x2000); U32(PwdLayout.Value, 250); U32(PwdLayout.Useability, 0x10008); + BinaryPrimitives.WriteSingleLittleEndian(pwd.AsSpan(PwdLayout.UseRadius), 2.5f); + U32(PwdLayout.TargetType, 0x10); U32(PwdLayout.Effects, 0x20); U32(PwdLayout.AmmoType, 0); + U32(PwdLayout.CombatUse, 3); U32(PwdLayout.Structure, 50); U32(PwdLayout.MaxStructure, 100); + U32(PwdLayout.StackSize, 10); U32(PwdLayout.MaxStackSize, 100); U32(PwdLayout.BlipColor, 8); + U32(PwdLayout.RadarEnum, 4); U32(PwdLayout.Burden, 30); U32(PwdLayout.SpellId, 1234); + U32(PwdLayout.HouseOwner, 0x50000009); U32(PwdLayout.HookType, 2); U32(PwdLayout.HookItemTypes, 0x80); + U32(PwdLayout.Monarch, Other); U32(PwdLayout.MaterialType, 57); + BinaryPrimitives.WriteSingleLittleEndian(pwd.AsSpan(PwdLayout.Workmanship), 6.5f); + U32(PwdLayout.CooldownId, 5); + BinaryPrimitives.WriteDoubleLittleEndian(pwd.AsSpan(PwdLayout.CooldownDuration), 15.0); + U32(PwdLayout.PetOwner, Me); + + var ints = new Dictionary<uint, int> + { + [1] = 0x2000, [4] = 0x4000, [5] = 30, [9] = 0x2000, [11] = 100, [12] = 10, [16] = 0x10008, [18] = 0x20, + [19] = 250, [51] = 3, [91] = 100, [92] = 50, [94] = 0x10, [95] = 8, [131] = 57, [133] = 4, [151] = 2, + [152] = 0x80, [280] = 5, + }; + foreach (var kv in ints) + Check(PwdLayout.TryGetInt(pwd, kv.Key, out int v) && v == kv.Value, $"PWD int {kv.Key} = {kv.Value}"); + foreach (uint absent in new uint[] { 6, 7, 10, 50, 25, 2 }) // zero (not sent) or not a PWD field + Check(!PwdLayout.TryGetInt(pwd, absent, out _), $"PWD int {absent} absent"); + Check(PwdLayout.TryGetDataId(pwd, 8, out uint d) && d == 0x06001F4A, "PWD Icon"); + Check(PwdLayout.TryGetDataId(pwd, 50, out d) && d == 0x06006C0A, "PWD IconOverlay"); + Check(!PwdLayout.TryGetDataId(pwd, 52, out _), "PWD IconUnderlay absent"); + Check(PwdLayout.TryGetDataId(pwd, 28, out d) && d == 1234, "PWD Spell"); + Check(PwdLayout.TryGetInstanceId(pwd, 2, out uint i) && i == Me, "PWD Container"); + Check(!PwdLayout.TryGetInstanceId(pwd, 3, out _), "PWD Wielder absent"); + Check(PwdLayout.TryGetInstanceId(pwd, 26, out i) && i == Other, "PWD Monarch"); + Check(PwdLayout.TryGetInstanceId(pwd, 32, out i) && i == 0x50000009, "PWD HouseOwner"); + Check(PwdLayout.TryGetInstanceId(pwd, 44, out i) && i == Me, "PWD PetOwner"); + Check(PwdLayout.TryGetFloat(pwd, 54, out double f) && f == 2.5, "PWD UseRadius"); + Check(PwdLayout.TryGetFloat(pwd, 167, out f) && f == 15.0, "PWD CooldownDuration"); + Check(PwdLayout.TryGetFloat(pwd, 280, out f) && f == 6.5, "PWD workmanship (280)"); + Check(!PwdLayout.TryGetFloat(pwd, 22, out _), "PWD has no DamageVariance"); + } + + /// <summary>A wielded sword: tables, weapon profile (buffed values), weapon highlights; then a public update.</summary> + private static void WornWeapon() + { + Case("worn item, identified (weapon)"); + var a = new AppraiseInfo + { + // DamageType (45) is an assessment property: the table's value stays, the profile's doesn't replace it. + Ints = { [1] = 1, [5] = 800, [19] = 5000, [45] = 1, [158] = 2, [159] = 44, [160] = 250, [105] = 8 }, + Int64s = { [4] = 12_000_000_000, [5] = 1_000_000_000 }, // ItemTotalXp, ItemBaseXp + Bools = { [22] = true }, + Floats = { [29] = 1.15, [149] = 1.05, [150] = 1.02, [152] = 0.0 }, + Strings = { [16] = "Tachi", [7] = "Made for Tester", [8] = "Tester" }, + SpellBook = { 2083, 0x80000000u | 1616 }, + Weapon = new WeaponProfile(DamageType: 3, WeaponTime: 35, WeaponSkill: 44, Damage: 38, + DamageVariance: 0.45, DamageMod: 1.1, WeaponLength: 1.5, MaxVelocity: 1.0, WeaponOffense: 1.08, MaxVelocityEstimated: 7), + WeaponHighlight = 0x0005, WeaponColor = 0x0005, + }; + IdentifyRecord r = Identify(a, Sword); + Check(r.HasWeaponProfile && !r.HasArmorProfile && !r.Truncated, "weapon profile read"); + var ints = new Dictionary<uint, int>(a.Ints) { [49] = 35, [48] = 44, [44] = 38 }; // WeaponTime, WeaponSkill, Damage + var floats = new Dictionary<uint, double>(a.Floats) { [22] = 0.45, [63] = 1.1, [21] = 1.5, [26] = 1.0, [62] = 1.08 }; + ExpectBag(r.Properties, ints: ints, int64s: a.Int64s, bools: a.Bools, floats: floats, strings: a.Strings); + + // A caster: ACE sends no weapon profile for one, only the tables. + var wand = new AppraiseInfo { Ints = { [1] = 0x8000 }, Floats = { [144] = 1.2, [152] = 1.1 } }; + IdentifyRecord w = Identify(wand, Sword + 1); + Check(!w.HasWeaponProfile, "caster: no weapon profile"); + ExpectBag(w.Properties, ints: wand.Ints, floats: wand.Floats); + + // Later: the sword's structure changes and its inscription is edited (public updates). + PropertyUpdate u = Update(Updates.PublicInt(Sword, 92, 7)); + Check(u.Kind == PropertyKind.Int && !u.IsPrivate && u.ObjectId == Sword && u.Key == 92 && u.Integer == 7, "public Structure update"); + var bag = r.Properties; + bag.Apply(u); + bag.Apply(Update(Updates.PublicString(Sword, 7, "Made for someone else"))); + Eq(bag.Ints[92], 7, "update folded into the identify record (int)"); + Eq(bag.Strings[7], "Made for someone else", "update folded into the identify record (string)"); + } + + /// <summary>A monster, successful assess: ints, strings, creature profile with attributes and buff highlights.</summary> + private static void CreatureIdentified() + { + Case("creature, identified"); + var a = new AppraiseInfo + { + Ints = { [1] = 0x10, [2] = 3, [25] = 25, [307] = 10, [313] = 5 }, + Strings = { [16] = "A drudge skulker." }, + Creature = new CreatureProfile(0x8 | 0x1, 180, 200, new uint[] { 60, 70, 80, 90, 50, 40, 150, 100, 160, 110 }, 0x0003, 0x0001), + ResistHighlight = 0x0010, ResistColor = 0x0010, + }; + IdentifyRecord r = Identify(a, Drudge); + Check(r.HasCreatureProfile && r.CreatureHealth == 180 && r.CreatureHealthMax == 200 && !r.Truncated, "creature profile read"); + ExpectBag(r.Properties, ints: a.Ints, strings: a.Strings); + } + + /// <summary>A failed assess: Success = 0, the creature profile carries health only; the tables still come.</summary> + private static void CreatureFailedRoll() + { + Case("creature, failed assess"); + var a = new AppraiseInfo + { + Success = false, + Ints = { [1] = 0x10, [2] = 3, [25] = 25 }, + Creature = new CreatureProfile(0x0, 200, 200), + }; + IdentifyRecord r = Identify(a, Drudge); + Check(!r.Success && r.HasCreatureProfile && r.CreatureHealthMax == 200 && !r.Truncated, "failed roll read"); + ExpectBag(r.Properties, ints: a.Ints); + } + + /// <summary>A monster never assessed: CreateObject fields only.</summary> + private static void CreatureNotIdentified() + { + Case("creature, not identified (PublicWeenieDesc)"); + var pwd = new byte[PwdLayout.Size]; + BinaryPrimitives.WriteUInt32LittleEndian(pwd.AsSpan(PwdLayout.Type), 0x10); + BinaryPrimitives.WriteUInt32LittleEndian(pwd.AsSpan(PwdLayout.Useability), 1); + BinaryPrimitives.WriteUInt32LittleEndian(pwd.AsSpan(PwdLayout.BlipColor), 3); + BinaryPrimitives.WriteUInt32LittleEndian(pwd.AsSpan(PwdLayout.RadarEnum), 1); + BinaryPrimitives.WriteUInt32LittleEndian(pwd.AsSpan(PwdLayout.PetOwner), Me); // a summoned pet + Check(PwdLayout.TryGetInt(pwd, 1, out int t) && t == 0x10, "ItemType Creature"); + Check(PwdLayout.TryGetInt(pwd, 16, out int use) && use == 1, "ItemUseable"); + Check(PwdLayout.TryGetInt(pwd, 95, out int blip) && blip == 3, "RadarBlipColor"); + Check(PwdLayout.TryGetInstanceId(pwd, 44, out uint owner) && owner == Me, "PetOwner"); + Check(!PwdLayout.TryGetInt(pwd, 19, out _), "no Value"); + } + + /// <summary>Another player: allegiance strings, ratings, creature profile; then public updates about them.</summary> + private static void OtherPlayer() + { + Case("another player"); + var a = new AppraiseInfo + { + Ints = { [1] = 0x10, [25] = 275, [113] = 1, [188] = 3, [307] = 12, [218] = 9 }, + Strings = { [1] = "Someone Else", [47] = "The Crew", [21] = "High King Boss", [35] = "Lord Patron", [10] = "Hunters" }, + Creature = new CreatureProfile(0x8, 400, 400, new uint[] { 100, 100, 100, 100, 100, 100, 300, 250, 300, 250 }), + ArmorLevels = new uint[] { 300, 310, 320, 330, 340, 350, 360, 370, 380 }, + }; + IdentifyRecord r = Identify(a, Other); + Check(r.HasCreatureProfile && !r.Truncated, "player profile read"); + ExpectBag(r.Properties, ints: a.Ints, strings: a.Strings); + + PropertyUpdate u = Update(Updates.PublicInstanceId(Other, 26, Me)); + Check(u.Kind == PropertyKind.InstanceId && u.ObjectId == Other && u.Key == 26 && u.Integer == Me, "public Monarch update"); + u = Update(Updates.PublicBool(Other, 7, true)); + Check(u.Kind == PropertyKind.Bool && u.ObjectId == Other && u.Key == 7 && u.Integer == 1, "public PlayerKiller-style bool update"); + } + + /// <summary>A locked door (lockpick numbers), a portal (level limits), a chest.</summary> + private static void LandscapeDoorPortalChest() + { + Case("landscape: door, portal, chest"); + var door = new AppraiseInfo { Ints = { [1] = 0x80, [38] = 250, [173] = 67 }, Bools = { [3] = true, [2] = false } }; + IdentifyRecord r = Identify(door, Door); + ExpectBag(r.Properties, ints: door.Ints, bools: door.Bools); + + var portal = new AppraiseInfo + { + Ints = { [1] = 0x10000, [86] = 20, [87] = 80, [111] = 0x31 }, + Strings = { [14] = "Walk through to Town Network.", [16] = "A portal." }, + }; + r = Identify(portal, Portal); + ExpectBag(r.Properties, ints: portal.Ints, strings: portal.Strings); + + var chest = new AppraiseInfo { Ints = { [1] = 0x200, [19] = 0, [38] = 0 }, Bools = { [3] = false } }; + r = Identify(chest, Chest); + ExpectBag(r.Properties, ints: chest.Ints, bools: chest.Bools); + + // The door opens: public bool update for Open. + PropertyUpdate u = Update(Updates.PublicBool(Door, 2, true)); + Check(u.ObjectId == Door && u.Key == 2 && u.Integer == 1, "door Open update"); + } + + /// <summary>ACE strips a corpse to EncumbranceVal, Value = 0 and LongDesc.</summary> + private static void CorpseIdentified() + { + Case("corpse"); + var a = new AppraiseInfo { Ints = { [5] = 2400, [19] = 0 }, Strings = { [16] = "Killed by Tester." } }; + IdentifyRecord r = Identify(a, Corpse); + ExpectBag(r.Properties, ints: a.Ints, strings: a.Strings); + } + + /// <summary>A house hook holding an item: the item's tables, then the hook profile.</summary> + private static void HouseHook() + { + Case("house hook"); + var a = new AppraiseInfo + { + Ints = { [1] = 0x100, [19] = 100 }, + Strings = { [16] = "This hook is owned by Tester. It contains: \nArrows" }, + Hook = new HookProfile(Flags: 0x1 | 0x8, ValidLocations: 0x800000, AmmoType: 1), + }; + IdentifyRecord r = Identify(a, HookObj); + Check(r.HasHookProfile && !r.Truncated, "hook profile read"); + var ints = new Dictionary<uint, int>(a.Ints) { [9] = 0x800000, [50] = 1 }; + ExpectBag(r.Properties, ints: ints, bools: new() { [22] = true }, strings: a.Strings); + + // A hook with an item that isn't inscribable and has no ammo type: only its locations. + var b = new AppraiseInfo { Ints = { [1] = 0x100 }, Hook = new HookProfile(0x2, 0x1, 0) }; + r = Identify(b, HookObj); + ExpectBag(r.Properties, ints: new() { [1] = 0x100, [9] = 0x1 }); + } + + /// <summary>The player: PlayerDescription's seven tables, then a private update of every type.</summary> + private static void PlayerSelf() + { + Case("the player (PlayerDescription + private updates)"); + var pd = new PlayerDescription + { + Ints = { [25] = 275, [5] = 1500, [20] = 250000, [43] = 3, [96] = 4000, [307] = 10, [113] = 1 }, + Int64s = { [1] = 191_226_310_247, [2] = 1_000_000, [6] = 500_000, [7] = 1_500_000 }, + Bools = { [74] = true, [81] = false }, + Floats = { [64] = 1.0, [72] = 0.8, [98] = 1_727_000_000.5 }, + Strings = { [1] = "Tester", [5] = "Adventurer", [47] = "The Crew", [2] = "Sir" }, + Dids = { [1] = 0x02000001, [8] = 0x06001036, [23] = 0x0400007E }, + Iids = { [24] = 0x50000010, [25] = 0x50000011, [26] = 0x50000012 }, + }; + Check(PropertyWire.TryParsePlayerDescription(pd.ToMessage(), out PropertyBag bag, out bool truncated), "PlayerDescription parsed"); + Check(!truncated, "not truncated"); + ExpectBag(bag, ints: pd.Ints, int64s: pd.Int64s, bools: pd.Bools, floats: pd.Floats, strings: pd.Strings, dids: pd.Dids, iids: pd.Iids); + + // Private updates carry no guid; the engine files them in the player's record. + byte[][] msgs = + { + Updates.PrivateInt(5, 1650), Updates.PrivateInt64(1, 191_300_000_000), Updates.PrivateBool(81, true), + Updates.PrivateFloat(72, 0.75), Updates.PrivateString(2, "Lord"), Updates.PrivateDataId(8, 0x06001037), + Updates.PrivateInstanceId(25, 0x50000013), + }; + foreach (byte[] m in msgs) + { + PropertyUpdate u = Update(m); + Check(u.IsPrivate && u.ObjectId == 0, $"private {u.Kind} has no guid"); + bag.Apply(u); + } + Eq(bag.Ints[5], 1650, "EncumbranceVal after update"); + Eq(bag.Int64s[1], 191_300_000_000L, "TotalExperience after update"); + Eq(bag.Bools[81], true, "bool after update"); + Eq(bag.Floats[72], 0.75, "float after update"); + Eq(bag.Strings[2], "Lord", "Title after update"); + Eq(bag.DataIds[8], 0x06001037u, "Icon after update"); + Eq(bag.InstanceIds[25], 0x50000013u, "Patron after update"); + + // A description with no tables at all still parses. + var empty = new PlayerDescription(); + Check(PropertyWire.TryParsePlayerDescription(empty.ToMessage(), out bag, out truncated) && bag.Count == 0 && !truncated, "empty description"); + } + + /// <summary>Every opcode, public and private, round-trips kind, guid, key and value.</summary> + private static void UpdatesEveryType() + { + Case("UpdateProperty* (every type)"); + const uint g = 0x80000555; + Expect(Updates.PublicInt(g, 12, -3), PropertyKind.Int, false, g, 12, -3); + Expect(Updates.PrivateInt(12, int.MaxValue), PropertyKind.Int, true, 0, 12, int.MaxValue); + Expect(Updates.PublicInt64(g, 4, long.MaxValue), PropertyKind.Int64, false, g, 4, long.MaxValue); + Expect(Updates.PrivateInt64(2, -5), PropertyKind.Int64, true, 0, 2, -5); + Expect(Updates.PublicBool(g, 19, false), PropertyKind.Bool, false, g, 19, 0); + Expect(Updates.PrivateBool(19, true), PropertyKind.Bool, true, 0, 19, 1); + Expect(Updates.PublicDataId(g, 8, 0x06004D2A), PropertyKind.DataId, false, g, 8, 0x06004D2A); + Expect(Updates.PrivateDataId(28, 0xFFFFFFFF), PropertyKind.DataId, true, 0, 28, 0xFFFFFFFF); + Expect(Updates.PublicInstanceId(g, 3, Me), PropertyKind.InstanceId, false, g, 3, Me); + Expect(Updates.PrivateInstanceId(26, Other), PropertyKind.InstanceId, true, 0, 26, Other); + + PropertyUpdate f = Update(Updates.PublicFloat(g, 167, 12.25)); + Check(f.Kind == PropertyKind.Float && !f.IsPrivate && f.ObjectId == g && f.Key == 167 && f.Real == 12.25, "public float"); + f = Update(Updates.PrivateFloat(98, 1.5e9)); + Check(f.Kind == PropertyKind.Float && f.IsPrivate && f.Key == 98 && f.Real == 1.5e9, "private float"); + Check(!PropertyWire.TryParsePropertyUpdate(Updates.PrivateFloat(98, double.NaN), out _), "NaN float refused"); + + PropertyUpdate s = Update(Updates.PublicString(g, 16, "A long description.")); + Check(s.Kind == PropertyKind.String && s.ObjectId == g && s.Key == 16 && s.Text == "A long description.", "public string (key before guid)"); + s = Update(Updates.PrivateString(5, "Template")); + Check(s.Kind == PropertyKind.String && s.IsPrivate && s.Key == 5 && s.Text == "Template", "private string"); + } + + /// <summary>Strings of every length mod 4, and a code page 1252 character.</summary> + private static void StringUpdateAlignment() + { + Case("string updates: alignment and padding"); + foreach (string text in new[] { "", "a", "ab", "abc", "abcd", "abcde", "Aelrynth Sword of Æsc" }) + { + PropertyUpdate p = Update(Updates.PrivateString(7, text)); + Check(p.Text == text, $"private \"{text}\""); + PropertyUpdate q = Update(Updates.PublicString(Sword, 7, text)); + Check(q.Text == text && q.ObjectId == Sword, $"public \"{text}\""); + } + // A string table in an identify with the same lengths. + var a = new AppraiseInfo { Strings = { [1] = "", [2] = "a", [3] = "ab", [4] = "abc", [5] = "abcd" }, Ints = { [1] = 1 } }; + a.Dids[8] = 0x06001234; // after the string table: proves the padding was consumed + IdentifyRecord r = Identify(a, Scroll); + ExpectBag(r.Properties, ints: a.Ints, strings: a.Strings, dids: a.Dids); + } + + private static void TruncatedAndBadInput() + { + Case("truncated and bad messages"); + var a = new AppraiseInfo + { + Ints = { [1] = 2, [19] = 5 }, + Bools = { [69] = true }, + Floats = { [5] = -0.03, [29] = 1.1 }, + Strings = { [16] = "Cut short" }, + }; + byte[] full = a.ToIdentifyMessage(Scroll); + // Cut inside the float table: ints and bools kept, the rest dropped, flagged truncated. + int cut = 16 + 4 + 16 + 4 + 8 + 4 + 6; + Check(PropertyWire.TryParseIdentify(full.AsSpan(0, cut), out IdentifyRecord r), "truncated identify still parsed"); + Check(r.Truncated, "flagged truncated"); + ExpectBag(r.Properties, ints: a.Ints, bools: a.Bools); + + Check(!PropertyWire.TryParseIdentify(full.AsSpan(0, 12), out _), "no header, no record"); + byte[] wrongType = (byte[])full.Clone(); + wrongType[0] = 0xC8; + Check(!PropertyWire.TryParseIdentify(wrongType, out _), "not an identify"); + Check(!PropertyWire.TryParsePlayerDescription(full, out _, out _), "an identify is not a PlayerDescription"); + + byte[] upd = Updates.PublicInt(Sword, 92, 1); + Check(!PropertyWire.TryParsePropertyUpdate(upd.AsSpan(0, upd.Length - 1), out _), "short update refused"); + Check(!PropertyWire.TryParsePropertyUpdate(Updates.PrivateString(1, "x").AsSpan(0, 13), out _), "short string refused"); + byte[] other = (byte[])upd.Clone(); + BinaryPrimitives.WriteUInt32LittleEndian(other, 0x02DB); // PrivateUpdatePosition + Check(!PropertyWire.TryParsePropertyUpdate(other, out _), "position update is not a property update"); + Check(PropertyWire.IsPropertyUpdateOpcode(0x02CD) && PropertyWire.IsPropertyUpdateOpcode(0x02DA) + && !PropertyWire.IsPropertyUpdateOpcode(0x02CC) && !PropertyWire.IsPropertyUpdateOpcode(0x02DB), "opcode range"); + } + + // ── helpers ───────────────────────────────────────────────────────────── + + private static IdentifyRecord Identify(AppraiseInfo a, uint guid) + { + bool ok = PropertyWire.TryParseIdentify(a.ToIdentifyMessage(guid), out IdentifyRecord r); + Check(ok, "identify parsed"); + Check(r.ObjectId == guid && r.Flags == a.Flags && r.Success == a.Success, "identify header"); + return r; + } + + private static PropertyUpdate Update(byte[] msg) + { + bool ok = PropertyWire.TryParsePropertyUpdate(msg, out PropertyUpdate u); + Check(ok, $"update 0x{BinaryPrimitives.ReadUInt32LittleEndian(msg):X4} parsed"); + return u; + } + + private static void Expect(byte[] msg, PropertyKind kind, bool isPrivate, uint guid, uint key, long value) + { + PropertyUpdate u = Update(msg); + Check(u.Kind == kind && u.IsPrivate == isPrivate && u.ObjectId == guid && u.Key == key && u.Integer == value, + $"{(isPrivate ? "private" : "public")} {kind} key {key} = {value} (got {u.Kind} {u.IsPrivate} 0x{u.ObjectId:X8} {u.Key} {u.Integer})"); + } + + /// <summary>Every table of the bag must equal the expected one: same keys, same values.</summary> + private static void ExpectBag(PropertyBag bag, + Dictionary<uint, int>? ints = null, Dictionary<uint, long>? int64s = null, Dictionary<uint, bool>? bools = null, + Dictionary<uint, double>? floats = null, Dictionary<uint, string>? strings = null, Dictionary<uint, uint>? dids = null, + Dictionary<uint, uint>? iids = null) + { + Same("int", bag.Ints, ints ?? new()); + Same("int64", bag.Int64s, int64s ?? new()); + Same("bool", bag.Bools, bools ?? new()); + Same("float", bag.Floats, floats ?? new()); + Same("string", bag.Strings, strings ?? new()); + Same("did", bag.DataIds, dids ?? new()); + Same("iid", bag.InstanceIds, iids ?? new()); + } + + private static void Same<T>(string what, Dictionary<uint, T> actual, Dictionary<uint, T> expected) + { + Check(actual.Count == expected.Count, $"{what}: {actual.Count} values, expected {expected.Count}"); + foreach (var kv in expected) + Check(actual.TryGetValue(kv.Key, out T? v) && EqualityComparer<T>.Default.Equals(v, kv.Value), + $"{what}[{kv.Key}] = {kv.Value} (got {(actual.TryGetValue(kv.Key, out T? g) ? g : "nothing")})"); + } + + private static void Case(string name) + { + _case = name; + Console.WriteLine($"- {name}"); + } + + private static void Eq<T>(T actual, T expected, string what) => + Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{what}: expected {expected}, got {actual}"); + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}"); + } +} diff --git a/tools/PropertyWireTests/PropertyWireTests.csproj b/tools/PropertyWireTests/PropertyWireTests.csproj new file mode 100644 index 0000000..ae37f68 --- /dev/null +++ b/tools/PropertyWireTests/PropertyWireTests.csproj @@ -0,0 +1,25 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the engine's property parsers (src\RynthCore.Engine\Compatibility\ + PropertyWire.cs, compiled in): identify replies, PlayerDescription and every + UpdateProperty* message, built byte for byte the way ACE writes them (AceWire.cs mirrors + ACE.Server's writers), one per kind of object, plus the PublicWeenieDesc field map. + Nothing native: no AC, no engine state. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>PropertyWireTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\PropertyWire.cs" Link="Engine\PropertyWire.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/TestClient/Build-TestClient.ps1 b/tools/TestClient/Build-TestClient.ps1 new file mode 100644 index 0000000..3ec44ff --- /dev/null +++ b/tools/TestClient/Build-TestClient.ps1 @@ -0,0 +1,19 @@ +# Builds tools\TestClient\bin\TestClient.exe (x86). +$ErrorActionPreference = "Stop" +$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" ` + -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name +$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer" +$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name +$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer" +$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer" +$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared" +$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86" +$out = Join-Path $PSScriptRoot "bin" +New-Item -ItemType Directory -Force -Path "$out\obj" | Out-Null +Push-Location "$out\obj" +try { + & "$vcBase\bin\Hostx86\x86\cl.exe" /nologo /O2 /MT /W3 "$PSScriptRoot\TestClient.c" /link /MACHINE:X86 /OUT:"$out\TestClient.exe" + if ($LASTEXITCODE -ne 0) { throw "TestClient build failed" } +} finally { Pop-Location } +Write-Host "Built $out\TestClient.exe" diff --git a/tools/TestClient/TestClient.c b/tools/TestClient/TestClient.c new file mode 100644 index 0000000..79869aa --- /dev/null +++ b/tools/TestClient/TestClient.c @@ -0,0 +1,120 @@ +// TestClient: starts acclient.exe suspended, injects a DLL, optionally calls one of its +// exports on a remote thread (like RynthCore.Injector does with RynthCoreInit), resumes +// the client, then waits and (optionally) terminates it. For loader/engine tests that must +// not touch a real account: point the client at a closed port and no login happens. +// +// TestClient.exe <acclient.exe> <dll> <export|-> <seconds> [acclient args...] +// seconds > 0: terminate the client after that many seconds +// seconds = 0: leave it running and exit (prints TEST_PID=<pid>) +// +// Environment variables set here are inherited by the client (e.g. RYNTH_SPIKE_AUTORUN). +#include <windows.h> +#include <stdio.h> +#include <string.h> + +static DWORD RemoteCall(HANDLE process, void* fn, void* arg, DWORD timeoutMs, DWORD* exitCode) +{ + HANDLE t = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)fn, arg, 0, NULL); + if (!t) return GetLastError(); + DWORD r = WaitForSingleObject(t, timeoutMs); + GetExitCodeThread(t, exitCode); + CloseHandle(t); + return r == WAIT_OBJECT_0 ? 0 : WAIT_TIMEOUT; +} + +int main(int argc, char** argv) +{ + if (argc < 5) { + printf("usage: TestClient <acclient.exe> <dll> <export|-> <seconds> [acclient args...]\n"); + return 1; + } + const char* exe = argv[1]; + const char* dll = argv[2]; + const char* exportName = argv[3]; + int seconds = atoi(argv[4]); + + char cmd[4096]; + _snprintf_s(cmd, sizeof cmd, _TRUNCATE, "\"%s\"", exe); + for (int i = 5; i < argc; i++) { strcat_s(cmd, sizeof cmd, " "); strcat_s(cmd, sizeof cmd, argv[i]); } + char dir[MAX_PATH]; + strcpy_s(dir, sizeof dir, exe); + *strrchr(dir, '\\') = 0; + + // The export's RVA, from a local image-only mapping of the DLL. + DWORD exportRva = 0; + if (strcmp(exportName, "-") != 0) { + HMODULE local = LoadLibraryExA(dll, NULL, DONT_RESOLVE_DLL_REFERENCES); + if (!local) { printf("cannot map %s locally (%lu)\n", dll, GetLastError()); return 2; } + FARPROC p = GetProcAddress(local, exportName); + if (!p) { printf("%s has no export %s\n", dll, exportName); return 2; } + exportRva = (DWORD)((char*)p - (char*)local); + FreeLibrary(local); + } + + // Marks the client as a test client in its log (the loader logs "TestClient: ..."). + if (GetEnvironmentVariableA("RYNTHCORE_TEST_CLIENT", NULL, 0) == 0) + SetEnvironmentVariableA("RYNTHCORE_TEST_CLIENT", "tools\\TestClient (no login)"); + STARTUPINFOA si = { sizeof si }; + PROCESS_INFORMATION pi; + if (!CreateProcessA(exe, cmd, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, dir, &si, &pi)) { + printf("CreateProcess failed %lu\n", GetLastError()); + return 3; + } + printf("TEST_PID=%lu\n", pi.dwProcessId); + fflush(stdout); + + // Its own launch context, naming a dummy account and NO character. Without one the engine + // falls back to the shared %APPDATA%\RynthCore\launch_context.json - whatever the launcher + // last launched (a real character) - and arms auto-login for it (2026-09-29). + char ctxPath[MAX_PATH] = ""; + { + char appdata[MAX_PATH]; + if (GetEnvironmentVariableA("APPDATA", appdata, sizeof appdata) > 0) { + char dir[MAX_PATH]; + _snprintf_s(dir, sizeof dir, _TRUNCATE, "%s\\RynthCore\\launch_contexts", appdata); + CreateDirectoryA(dir, NULL); + _snprintf_s(ctxPath, sizeof ctxPath, _TRUNCATE, "%s\\launch_context_%lu.json", dir, pi.dwProcessId); + FILE* f = NULL; + if (fopen_s(&f, ctxPath, "w") == 0 && f) { + fprintf(f, "{\"ProcessId\":%lu,\"AccountName\":\"test-client\",\"ServerName\":\"test-client\"," + "\"TargetCharacter\":\"\",\"SkipLoginLogos\":false,\"OnLoginCommands\":null,\"OnLoginWaitMs\":0}", + pi.dwProcessId); + fclose(f); + } + } + } + + size_t len = strlen(dll) + 1; + void* remote = VirtualAllocEx(pi.hProcess, NULL, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + WriteProcessMemory(pi.hProcess, remote, dll, len, NULL); + DWORD base = 0; + DWORD err = RemoteCall(pi.hProcess, (void*)GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA"), + remote, 30000, &base); + if (err || !base) { + printf("LoadLibrary in the client failed (err %lu, base 0x%08lx)\n", err, base); + TerminateProcess(pi.hProcess, 1); + return 4; + } + printf("loaded at 0x%08lx\n", base); + + if (exportRva) { + DWORD rc = 0; + err = RemoteCall(pi.hProcess, (void*)(ULONG_PTR)(base + exportRva), NULL, 60000, &rc); + printf("%s -> %s rc=%lu\n", exportName, err ? "TIMEOUT" : "returned", rc); + } + ResumeThread(pi.hThread); + fflush(stdout); + + if (seconds <= 0) return 0; + DWORD r = WaitForSingleObject(pi.hProcess, seconds * 1000); + if (r == WAIT_OBJECT_0) { + DWORD code = 0; + GetExitCodeProcess(pi.hProcess, &code); + printf("client exited by itself, code 0x%08lx\n", code); + } else { + TerminateProcess(pi.hProcess, 0); + printf("client terminated after %d s\n", seconds); + } + if (ctxPath[0]) DeleteFileA(ctxPath); + return 0; +} diff --git a/tools/TestClient/ThreadPeek.c b/tools/TestClient/ThreadPeek.c new file mode 100644 index 0000000..b8cd452 --- /dev/null +++ b/tools/TestClient/ThreadPeek.c @@ -0,0 +1,65 @@ +// ThreadPeek: where is a (32-bit) thread right now? Suspends it a few times and prints EIP, +// the module+offset it falls in, and the return-address-looking values on its stack. +// ThreadPeek.exe <pid> <tid> [samples] +#include <windows.h> +#include <psapi.h> +#include <stdio.h> + +static HMODULE g_mods[1024]; +static MODULEINFO g_info[1024]; +static char g_names[1024][64]; +static int g_nmods; + +static void LoadModules(HANDLE p) +{ + DWORD needed = 0; + EnumProcessModulesEx(p, g_mods, sizeof g_mods, &needed, LIST_MODULES_ALL); + g_nmods = (int)(needed / sizeof(HMODULE)); + for (int i = 0; i < g_nmods; i++) { + GetModuleInformation(p, g_mods[i], &g_info[i], sizeof g_info[i]); + GetModuleBaseNameA(p, g_mods[i], g_names[i], sizeof g_names[i]); + } +} + +static const char* Where(DWORD a, char* buf, size_t cap) +{ + for (int i = 0; i < g_nmods; i++) { + DWORD b = (DWORD)(ULONG_PTR)g_info[i].lpBaseOfDll; + if (a >= b && a < b + g_info[i].SizeOfImage) { + _snprintf_s(buf, cap, _TRUNCATE, "%s+0x%lx", g_names[i], a - b); + return buf; + } + } + return NULL; +} + +int main(int argc, char** argv) +{ + if (argc < 3) { printf("usage: ThreadPeek <pid> <tid> [samples]\n"); return 1; } + DWORD pid = strtoul(argv[1], NULL, 0), tid = strtoul(argv[2], NULL, 0); + int samples = argc > 3 ? atoi(argv[3]) : 5; + HANDLE p = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); + HANDLE t = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT, FALSE, tid); + if (!p || !t) { printf("open failed %lu\n", GetLastError()); return 2; } + LoadModules(p); + for (int s = 0; s < samples; s++) { + SuspendThread(t); + CONTEXT c = { 0 }; + c.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER; + GetThreadContext(t, &c); + DWORD stack[256] = { 0 }; + SIZE_T got = 0; + ReadProcessMemory(p, (void*)(ULONG_PTR)c.Esp, stack, sizeof stack, &got); + ResumeThread(t); + char buf[128]; + const char* w = Where(c.Eip, buf, sizeof buf); + printf("sample %d: eip=0x%08lx %s esp=0x%08lx eax=%08lx ecx=%08lx\n", s, c.Eip, w ? w : "(not in a module)", c.Esp, c.Eax, c.Ecx); + int shown = 0; + for (int i = 0; i < (int)(got / 4) && shown < 16; i++) { + const char* m = Where(stack[i], buf, sizeof buf); + if (m) { printf(" [esp+%03x] %s\n", i * 4, m); shown++; } + } + Sleep(200); + } + return 0; +} diff --git a/tools/UsageStatsTests/Program.cs b/tools/UsageStatsTests/Program.cs new file mode 100644 index 0000000..aae647b --- /dev/null +++ b/tools/UsageStatsTests/Program.cs @@ -0,0 +1,327 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using RynthCore.App.Avalonia; + +namespace UsageStatsTests; + +/// <summary> +/// Checks for UsageStats.cs (the launcher's opt-in usage statistics). +/// dotnet run -c Release offline checks, in a temp folder against a local test server +/// dotnet run -c Release -- live then ONE real report to https://aelrynth.com/rynth/ping, built from +/// this PC's enabled plugins (engine.json, read only) and the live +/// update feed's plugin names, with a throwaway install ID (printed) +/// </summary> +internal static class Program +{ + private static int _checks, _failed; + + private static readonly HashSet<string> AllowedKeys = new() { "schema", "install", "version", "windows", "crashes", "plugins", "otherPlugins" }; + + private static async Task<int> Main(string[] args) + { + string root = Path.Combine(Path.GetTempPath(), "rc-usage-stats-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + Versions(); + Payload(); + Plugins(root); + Crashes(root); + OptInOut(root); + await Sending(root); + await FailuresAreSilent(root); + } + finally + { + try { Directory.Delete(root, true); } catch { } + } + + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed"); + if (_failed > 0) return 1; + + if (args.Any(a => a.Equals("live", StringComparison.OrdinalIgnoreCase))) + return await Live(); + return 0; + } + + private static void Versions() + { + Check(UsageStats.ShortVersion("2026.10.2.1+abcdef0123") == "2026.10.2.1", "release version keeps the number, drops the commit"); + Check(UsageStats.ShortVersion("1.0.0+abc") == "dev", "unversioned build is dev"); + Check(UsageStats.ShortVersion("2026.9.28.10 (4e4c4b7)") == "2026.9.28.10", "formatted version"); + Check(UsageStats.ShortVersion(@"C:\Users\Tom\x.dll") == "unknown", "anything else is unknown (no free text)"); + Check(UsageStats.ShortVersion(null) == "unknown", "null is unknown"); + string w = UsageStats.WindowsMajor(); + Check(w is "10" or "11" or "other", $"windows major is 10/11/other (got {w})"); + } + + private static void Payload() + { + var plugins = new List<UsageStats.PluginInfo> + { + new("RynthAi", "2026.10.2.1+abc"), + new("RynthAi", "2026.10.2.1+abc"), // duplicate copy: reported once + new(@"C:\secret\Name", "1.0.0"), // not a safe name: dropped + new("RynthNav", "1.0.0+dev"), + }; + string json = UsageStats.BuildPayload(Guid.NewGuid().ToString("D"), "2026.10.3.1+abc", plugins, 3, 2, "10"); + using var doc = JsonDocument.Parse(json); + var keys = doc.RootElement.EnumerateObject().Select(p => p.Name).ToList(); + Check(keys.All(AllowedKeys.Contains) && keys.Count == AllowedKeys.Count, "payload has exactly the approved keys: " + string.Join(",", keys)); + Check(doc.RootElement.GetProperty("plugins").GetArrayLength() == 2, "plugins deduplicated, unsafe names dropped"); + Check(doc.RootElement.GetProperty("plugins")[0].EnumerateObject().Select(p => p.Name).SequenceEqual(new[] { "name", "version" }), "plugin entries are name+version only"); + Check(!json.Contains('\\') && !json.Contains("C:"), "no file paths in the payload"); + Check(Encoding.UTF8.GetByteCount(json) < 2048, $"payload is small ({Encoding.UTF8.GetByteCount(json)} bytes)"); + string clamped = UsageStats.BuildPayload(Guid.NewGuid().ToString("D"), "dev", Array.Empty<UsageStats.PluginInfo>(), 5000, 99999, "11"); + using var c = JsonDocument.Parse(clamped); + Check(c.RootElement.GetProperty("crashes").GetInt32() == 1000 && c.RootElement.GetProperty("otherPlugins").GetInt32() == 100, "counts are clamped"); + } + + private static void Plugins(string root) + { + string dir = Path.Combine(root, "plugins"); + Directory.CreateDirectory(dir); + string ai = Path.Combine(dir, "RynthCore.Plugin.RynthAi.dll"); + string mine = Path.Combine(dir, "MyPrivatePlugin.dll"); + File.Copy(typeof(Program).Assembly.Location, ai); + File.Copy(typeof(Program).Assembly.Location, mine); + var feed = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { ["RynthCore.Plugin.RynthAi.dll"] = "RynthAi" }; + var (known, other) = UsageStats.DescribePlugins(new[] { ai, mine, ai.ToUpperInvariant(), Path.Combine(dir, "Missing.dll") }, feed); + Check(known.Count == 1 && known[0].Name == "RynthAi", "a feed plugin is reported by its feed name"); + Check(other == 2, $"other plugins (incl. a missing file) only counted (got {other})"); + } + + private static void Crashes(string root) + { + string dumps = Path.Combine(root, "dumps"); + Directory.CreateDirectory(dumps); + DateTime now = DateTime.UtcNow; + void Make(string name, DateTime t) { string p = Path.Combine(dumps, name); File.WriteAllText(p, "x"); File.SetLastWriteTimeUtc(p, t); } + Make("crash_1_old.dmp", now.AddDays(-2)); + Make("crash_2_new.dmp", now.AddMinutes(-10)); + Make("crash_3_new.dmp", now.AddMinutes(-5)); + Make("hang_4_new.dmp", now.AddMinutes(-5)); + Check(UsageStats.CountCrashDumps(dumps, now.AddDays(-1), now) == 2, "only crash_*.dmp newer than the last report count (hangs don't)"); + Check(UsageStats.CountCrashDumps(Path.Combine(root, "nope"), now.AddDays(-1), now) == 0, "missing dump folder = 0"); + } + + private static void OptInOut(string root) + { + string state = Path.Combine(root, "state-optin"); + var s = new UsageStats("http://127.0.0.1:9/", state, Path.Combine(root, "dumps")); + Check(s.InstallId == null, "no install ID before opting in"); + s.OptIn(DateTime.UtcNow); + string? id = s.InstallId; + Check(id != null && Guid.TryParseExact(id, "D", out _), "opting in makes a random GUID"); + s.OptIn(DateTime.UtcNow); + Check(s.InstallId == id, "opting in again keeps the same ID"); + string text = File.ReadAllText(s.StatePath); + Check(!text.Contains(Environment.UserName, StringComparison.OrdinalIgnoreCase) && !text.Contains(Environment.MachineName, StringComparison.OrdinalIgnoreCase), + "the state file holds no user or machine name"); + s.OptOut(); + Check(!File.Exists(s.StatePath) && s.InstallId == null, "opting out deletes the file and the ID"); + s.OptIn(DateTime.UtcNow); + Check(s.InstallId != null && s.InstallId != id, "opting in again later makes a NEW ID"); + } + + private static async Task Sending(string root) + { + using var server = new TestServer(); + string state = Path.Combine(root, "state-send"); + string dumps = Path.Combine(root, "dumps"); + var s = new UsageStats(server.Url, state, dumps); + var plugins = new List<UsageStats.PluginInfo> { new("RynthAi", "2026.10.3.1") }; + DateTime day1 = DateTime.UtcNow; + + bool enabled = false; + Check(!await s.MaybeSendAsync(() => enabled, "2026.10.3.1", plugins, 0, day1) && server.Count == 0, "off: nothing is sent"); + + enabled = true; + s.OptIn(day1.AddDays(-1)); // so the two "new" crash dumps from Crashes() count + Check(await s.MaybeSendAsync(() => enabled, "2026.10.3.1", plugins, 1, day1) && server.Count == 1, "on: one report is sent"); + using (var doc = JsonDocument.Parse(server.LastBody!)) + { + Check(doc.RootElement.GetProperty("install").GetString() == s.InstallId, "the report carries the install ID"); + Check(doc.RootElement.GetProperty("crashes").GetInt32() == 2, "crashes since opting in are counted"); + } + Check(server.LastContentType?.StartsWith("application/json") == true, "sent as application/json"); + Check(server.LastUserAgent == "RynthCore-Launcher", "user agent is the launcher's, nothing more"); + + Check(!await s.MaybeSendAsync(() => enabled, "2026.10.3.1", plugins, 1, day1.AddHours(1)) && server.Count == 1, "a second check the same day sends nothing"); + + DateTime day2 = day1.Date.AddDays(1).AddHours(1); + Check(await s.MaybeSendAsync(() => enabled, "2026.10.3.1", plugins, 1, day2) && server.Count == 2, "next day: one more"); + using (var doc = JsonDocument.Parse(server.LastBody!)) + Check(doc.RootElement.GetProperty("crashes").GetInt32() == 0, "crashes reset after a report"); + + s.OptOut(); + enabled = false; + Check(!await s.MaybeSendAsync(() => enabled, "2026.10.3.1", plugins, 1, day2.AddDays(1)) && server.Count == 2, "after opting out nothing is sent"); + Check(!File.Exists(s.StatePath), "and no ID comes back"); + + // Turned off between building the report and sending it. + enabled = true; + s.OptIn(day2); + int calls = 0; + Check(!await s.MaybeSendAsync(() => ++calls < 2, "2026.10.3.1", plugins, 0, day2.AddDays(2)) && server.Count == 2, "switched off mid-way: not sent"); + + // Server refuses: nothing recorded, so a later check tries again. + server.Status = 400; + DateTime day4 = day2.AddDays(3); + Check(!await s.MaybeSendAsync(() => true, "2026.10.3.1", plugins, 0, day4), "a refused report returns false"); + server.Status = 204; + Check(await s.MaybeSendAsync(() => true, "2026.10.3.1", plugins, 0, day4.AddHours(6)), "and is retried at the next check"); + } + + private static async Task FailuresAreSilent(string root) + { + // A port nothing listens on, and a server that never answers. + var s = new UsageStats("http://127.0.0.1:1/ping", Path.Combine(root, "state-fail"), Path.Combine(root, "dumps")); + s.OptIn(DateTime.UtcNow); + bool threw = false; + try { await s.MaybeSendAsync(() => true, "dev", Array.Empty<UsageStats.PluginInfo>(), 0, DateTime.UtcNow); } + catch { threw = true; } + Check(!threw, "connection refused: no exception"); + + var tcp = new TcpListener(IPAddress.Loopback, 0); + tcp.Start(); + int port = ((IPEndPoint)tcp.LocalEndpoint).Port; + var s2 = new UsageStats($"http://127.0.0.1:{port}/ping", Path.Combine(root, "state-hang"), Path.Combine(root, "dumps")); + s2.OptIn(DateTime.UtcNow); + var sw = Stopwatch.StartNew(); + bool ok = await s2.MaybeSendAsync(() => true, "dev", Array.Empty<UsageStats.PluginInfo>(), 0, DateTime.UtcNow); + sw.Stop(); + tcp.Stop(); + Check(!ok && sw.Elapsed < TimeSpan.FromSeconds(15), $"a server that never answers gives up quietly ({sw.Elapsed.TotalSeconds:0.0} s)"); + } + + // ── Live ────────────────────────────────────────────────────────────────── + + private static async Task<int> Live() + { + Console.WriteLine(); + Console.WriteLine("LIVE: one report to https://aelrynth.com/rynth/ping"); + + var names = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + using (var http = new HttpClient()) + { + byte[] env = await http.GetByteArrayAsync("https://aelrynth.com/downloads/rynth/update.json"); + using var e = JsonDocument.Parse(env); + byte[] payload = Convert.FromBase64String(e.RootElement.GetProperty("payload").GetString()!); + using var m = JsonDocument.Parse(payload); + foreach (JsonElement p in m.RootElement.GetProperty("plugins").EnumerateArray()) + names.TryAdd(p.GetProperty("file").GetString()!, p.GetProperty("name").GetString()!); + } + + var enabled = new List<string>(); + string engineJson = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "engine.json"); + if (File.Exists(engineJson)) + { + using var doc = JsonDocument.Parse(File.ReadAllText(engineJson)); + if (doc.RootElement.TryGetProperty("PluginPaths", out JsonElement paths)) + foreach (JsonElement p in paths.EnumerateArray()) + if (p.GetString() is { Length: > 0 } s) enabled.Add(s); + } + var (known, other) = UsageStats.DescribePlugins(enabled, names); + + // The launcher build in this checkout (dotnet build -c Release of RynthCore.App.Avalonia). + string bin = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", "src", "RynthCore.App.Avalonia", "bin", "Release")); + string? launcher = Directory.Exists(bin) + ? Directory.EnumerateFiles(bin, "RynthCore.App.Avalonia.dll", SearchOption.AllDirectories).FirstOrDefault() + : null; + string version = launcher != null ? FileVersionInfo.GetVersionInfo(launcher).ProductVersion ?? "" : ""; + Console.WriteLine($"Launcher build: {(launcher ?? "not found")} ({version})"); + + string state = Path.Combine(Path.GetTempPath(), "rc-usage-stats-live-" + Guid.NewGuid().ToString("N")); + try + { + var s = new UsageStats(UsageStats.DefaultEndpoint, state); + s.OptIn(DateTime.UtcNow); + Console.WriteLine("Test install ID: " + s.InstallId); + Console.WriteLine(s.Preview(version, known, other, DateTime.UtcNow)); + bool sent = await s.MaybeSendAsync(() => true, version, known, other, DateTime.UtcNow); + Console.WriteLine(sent ? "LIVE: accepted" : "LIVE: NOT accepted"); + return sent ? 0 : 1; + } + finally + { + try { Directory.Delete(state, true); } catch { } + } + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + + private static void Check(bool ok, string what) + { + _checks++; + if (!ok) _failed++; + Console.WriteLine($" {(ok ? "ok " : "FAIL")} {what}"); + } + + /// <summary>A one-route HTTP server on 127.0.0.1 that records each request and answers Status.</summary> + private sealed class TestServer : IDisposable + { + private readonly TcpListener _tcp = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource _cts = new(); + public int Count; + public int Status = 204; + public string? LastBody, LastContentType, LastUserAgent; + + public TestServer() + { + _tcp.Start(); + _ = Task.Run(Loop); + } + + public string Url => $"http://127.0.0.1:{((IPEndPoint)_tcp.LocalEndpoint).Port}/rynth/ping"; + + private async Task Loop() + { + while (!_cts.IsCancellationRequested) + { + TcpClient c; + try { c = await _tcp.AcceptTcpClientAsync(_cts.Token); } catch { return; } + using (c) + { + var stream = c.GetStream(); + var buf = new List<byte>(); + var one = new byte[4096]; + int headerEnd = -1, length = 0; + while (true) + { + int n = await stream.ReadAsync(one); + if (n <= 0) break; + buf.AddRange(one.AsSpan(0, n).ToArray()); + string sofar = Encoding.ASCII.GetString(buf.ToArray()); + if (headerEnd < 0 && (headerEnd = sofar.IndexOf("\r\n\r\n", StringComparison.Ordinal)) >= 0) + { + foreach (string line in sofar[..headerEnd].Split("\r\n")) + { + int colon = line.IndexOf(':'); + if (colon < 0) continue; + string k = line[..colon].Trim(), v = line[(colon + 1)..].Trim(); + if (k.Equals("Content-Length", StringComparison.OrdinalIgnoreCase)) length = int.Parse(v); + if (k.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)) LastContentType = v; + if (k.Equals("User-Agent", StringComparison.OrdinalIgnoreCase)) LastUserAgent = v; + } + } + if (headerEnd >= 0 && buf.Count >= headerEnd + 4 + length) break; + } + LastBody = Encoding.UTF8.GetString(buf.ToArray(), headerEnd + 4, length); + if (Status < 300) Interlocked.Increment(ref Count); + string reason = Status < 300 ? "No Content" : "Bad Request"; + await stream.WriteAsync(Encoding.ASCII.GetBytes($"HTTP/1.1 {Status} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")); + } + } + } + + public void Dispose() + { + _cts.Cancel(); + _tcp.Stop(); + } + } +} diff --git a/tools/UsageStatsTests/UsageStatsTests.csproj b/tools/UsageStatsTests/UsageStatsTests.csproj new file mode 100644 index 0000000..be4bef4 --- /dev/null +++ b/tools/UsageStatsTests/UsageStatsTests.csproj @@ -0,0 +1,26 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Checks for the launcher's opt-in usage statistics (src\RynthCore.App.Avalonia\UsageStats.cs, + compiled in): the payload holds only the approved fields, opting out deletes the install ID, + one report a day, crash counting, silent failures. Works in a temp folder against a local + test server, never in %APPDATA%\RynthCore. + dotnet run -c Release offline checks (exit 0 = pass, 1 = fail) + with the argument "live" (see Program.cs) it also sends ONE real report to aelrynth.com/rynth/ping + with a throwaway install ID (printed, so the test row + can be deleted on the server afterwards) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0-windows</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>UsageStatsTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.App.Avalonia\UsageStats.cs" Link="App\UsageStats.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/VTankWatchTests/Program.cs b/tools/VTankWatchTests/Program.cs new file mode 100644 index 0000000..11abeb5 --- /dev/null +++ b/tools/VTankWatchTests/Program.cs @@ -0,0 +1,81 @@ +using RynthCore.Engine.Compatibility; + +namespace VTankWatchTests; + +/// <summary>VTankSignal (the Decal bridge's VTank signal) without AC, Decal or VTank.</summary> +internal static class Program +{ + private static int _checks, _failed; + + private static int Main() + { + // VTank's documented commands, in the shapes a chat bar or a meta sends them. + Parse("/vt start", VTankSignal.Start); + Parse("/vt stop", VTankSignal.Stop); + Parse("/VT START", VTankSignal.Start); + Parse("/Vt Stop", VTankSignal.Stop); + Parse(" /vt start ", VTankSignal.Start); + Parse("/vt\tstop", VTankSignal.Stop); + Parse("/vt start\r\n", VTankSignal.Start); + Parse("/vt stop now", VTankSignal.Stop); // VTank's own parser decides; the verb matches + + // Not VTank start/stop. + Parse(null, VTankSignal.None); + Parse("", VTankSignal.None); + Parse("/vt", VTankSignal.None); + Parse("/vt ", VTankSignal.None); + Parse("/vt startx", VTankSignal.None); + Parse("/vt starting", VTankSignal.None); + Parse("/vt stopped", VTankSignal.None); + Parse("/vt opt set enablecombat true", VTankSignal.None); + Parse("/vt forcebuff", VTankSignal.None); + Parse("/vt cancelforcebuff", VTankSignal.None); + Parse("/vt meta load start", VTankSignal.None); + Parse("/vt nav load stop", VTankSignal.None); + Parse("/vtank start", VTankSignal.None); + Parse("/vtstart", VTankSignal.None); + Parse("vt start", VTankSignal.None); + Parse("/ra start", VTankSignal.None); + Parse("/ra stop", VTankSignal.None); + Parse("/ub vt start", VTankSignal.None); + Parse("/tell Someone, /vt start", VTankSignal.None); + Parse("/f type /vt stop to stop", VTankSignal.None); + Parse("hello /vt start", VTankSignal.None); + + // Diagnostic chat filter: VTank-looking lines yes, other players' lines no. + Chat("[VTank] Something VTank printed", true); + Chat("Virindi Tank v.1.0.0.0 loaded", true); + Chat("You have entered the General channel.", false); + Chat("Bob tells you, \"is VTank on?\"", false); + Chat("Bob says, \"VTank\"", false); + Chat("[RynthAi] Macro STARTED.", false); + Chat(null, false); + + Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks)"); + return _failed == 0 ? 0 : 1; + } + + private static void Parse(string? line, int expected) + { + _checks++; + int got = VTankSignal.ParseCommand(line); + if (got != expected) + { + _failed++; + Console.WriteLine($"FAIL ParseCommand({Show(line)}) = {got}, expected {expected}"); + } + } + + private static void Chat(string? text, bool expected) + { + _checks++; + bool got = VTankSignal.LooksLikeVTankChat(text); + if (got != expected) + { + _failed++; + Console.WriteLine($"FAIL LooksLikeVTankChat({Show(text)}) = {got}, expected {expected}"); + } + } + + private static string Show(string? s) => s == null ? "null" : "\"" + s.Replace("\r", "\\r").Replace("\n", "\\n").Replace("\t", "\\t") + "\""; +} diff --git a/tools/VTankWatchTests/VTankWatchTests.csproj b/tools/VTankWatchTests/VTankWatchTests.csproj new file mode 100644 index 0000000..a1cfb7b --- /dev/null +++ b/tools/VTankWatchTests/VTankWatchTests.csproj @@ -0,0 +1,23 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the VTank signal the Decal bridge uses (src\RynthCore.Engine\ + Compatibility\VTankSignal.cs, compiled in): which chat-parser lines count as VTank's + documented /vt start and /vt stop, and which chat lines are logged for reference. + Nothing native: no AC, no Decal, no VTank. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>VTankWatchTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\VTankSignal.cs" Link="Engine\VTankSignal.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/WatchPatch.py b/tools/WatchPatch.py new file mode 100644 index 0000000..f8e8ea5 --- /dev/null +++ b/tools/WatchPatch.py @@ -0,0 +1,45 @@ +"""WatchPatch - timeline of who owns the first bytes of some functions in a running process. + +Polls the addresses every few ms and prints a line whenever the bytes change, with the +owner of the jump (see ProcPatchDiff.owner_of). Read-only. Spike tool (Decal bridge). + + python tools/WatchPatch.py <pid> <seconds> 0x005649F0 0x004CBF70 ... +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(__file__)) +import ProcPatchDiff as P # noqa: E402 + + +def main(): + pid, secs = int(sys.argv[1]), float(sys.argv[2]) + addrs = [int(a, 16) for a in sys.argv[3:]] + p = P.Proc(pid) + last = {} + t0 = time.time() + refresh = 0.0 + while time.time() - t0 < secs: + now = time.time() + if now - refresh > 1.0: # modules come and go (Decal loads late) + try: + p.mods = p._modules() + except OSError: + break + refresh = now + for a in addrs: + b = p.read(a, 6) + if b is None: + continue + if last.get(a) != b: + j = P.decode_jump(p, a) + own = P.owner_of(p, j[0])[0] if j else "original bytes" if a not in last else "?" + stamp = time.strftime("%H:%M:%S", time.localtime(now)) + f".{int(now * 1000) % 1000:03d}" + print(f"{stamp} 0x{a:08X} {b.hex()} -> {own}", flush=True) + last[a] = b + time.sleep(0.005) + + +if __name__ == "__main__": + main() diff --git a/tools/check_imgui_calls.py b/tools/check_imgui_calls.py new file mode 100644 index 0000000..324a052 --- /dev/null +++ b/tools/check_imgui_calls.py @@ -0,0 +1,93 @@ +"""Check that every Dear ImGui function the engine calls exists in our cimgui.dll. + +ImGui.NET binds native functions by name and lazily, so a call to a function +the DLL doesn't export (our build compiles out obsolete APIs, e.g. +GetContentRegionMax in 1.91) compiles fine and only fails - on AC's render +thread - the first time that line runs. Run after adding ImGui code: + + python tools/check_imgui_calls.py + +Exit code 1 lists the calls with no matching export. +""" +import re +import struct +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +DLL = ROOT / "src" / "RynthCore.Engine" / "Native" / "cimgui.dll" +SOURCES = ROOT / "src" / "RynthCore.Engine" / "ImGui" +# Old diagnostic shell, FORCE-gated and never run: not held to this check. +SKIP = {"RynthCoreShell.cs"} + +# Wrapper-object calls: variable/field name -> cimgui prefix. +MEMBER_PREFIX = { + "dl": "ImDrawList_", + "clipper": "ImGuiListClipper_", + "io.Fonts": "ImFontAtlas_", + "style": "ImGuiStyle_", +} + + +def pe_exports(path: Path) -> set[str]: + data = path.read_bytes() + pe = struct.unpack_from("<I", data, 0x3C)[0] + nsec = struct.unpack_from("<H", data, pe + 6)[0] + opt = pe + 24 + magic = struct.unpack_from("<H", data, opt)[0] + dd = opt + (96 if magic == 0x10B else 112) + exp_rva = struct.unpack_from("<I", data, dd)[0] + sections = [] + sec = opt + struct.unpack_from("<H", data, pe + 20)[0] + for i in range(nsec): + vsize, va, raw_size, raw_ptr = struct.unpack_from("<IIII", data, sec + i * 40 + 8) + sections.append((va, max(vsize, raw_size), raw_ptr)) + + def off(rva: int) -> int: + for va, size, raw in sections: + if va <= rva < va + size: + return rva - va + raw + raise ValueError(hex(rva)) + + e = off(exp_rva) + count, names_rva = struct.unpack_from("<I", data, e + 24)[0], struct.unpack_from("<I", data, e + 32)[0] + names = set() + for i in range(count): + n = off(struct.unpack_from("<I", data, off(names_rva) + i * 4)[0]) + names.add(data[n:data.index(b"\0", n)].decode()) + return names + + +def main() -> int: + exports = pe_exports(DLL) + + def found(prefix: str, name: str) -> bool: + full = prefix + name + return full in exports or any(x.startswith(full + "_") for x in exports) + + missing = [] + for f in sorted(SOURCES.rglob("*.cs")): + if f.name in SKIP: + continue + text = f.read_text(encoding="utf-8") + for m in re.finditer(r"ImGui(?:NET\.ImGui)?\.(\w+)\(", text): + if not found("ig", m.group(1)): + missing.append(f"{f.relative_to(ROOT)}:{text.count(chr(10), 0, m.start()) + 1}: ImGui.{m.group(1)}") + # Direct native calls name the exact export (overload suffix included). + for m in re.finditer(r"\bImGuiNative\.(\w+)\(", text): + if m.group(1) not in exports: + missing.append(f"{f.relative_to(ROOT)}:{text.count(chr(10), 0, m.start()) + 1}: ImGuiNative.{m.group(1)}") + for m in re.finditer(r"\b(dl|clipper|io\.Fonts|style)\.(\w+)\(", text): + if not found(MEMBER_PREFIX[m.group(1)], m.group(2)): + missing.append(f"{f.relative_to(ROOT)}:{text.count(chr(10), 0, m.start()) + 1}: {m.group(1)}.{m.group(2)}") + + if missing: + print("ImGui calls with no export in cimgui.dll:") + print("\n".join(" " + m for m in missing)) + return 1 + print(f"OK: every ImGui call resolves ({len(exports)} exports).") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/check_offthread_mutators.py b/tools/check_offthread_mutators.py index 25d1136..8e95e8d 100644 --- a/tools/check_offthread_mutators.py +++ b/tools/check_offthread_mutators.py @@ -31,6 +31,12 @@ This tool checks it statically (read-only, stdlib-only, out-of-process): construction). Catches a NEW mutator added with no marshal at all (the SelectItem-before-74f6d8c situation). + CHECK C (raw writes): every method that stores into memory with + `Marshal.Write*(...)` or the `WriteFloat(...)` helper must contain the gate, + or sit in an allow-listed context, or be on RAW_WRITE_ALLOW. CHECK B only + sees native delegate calls, so a raw store into a live AC object (the + SetPlayerHeadingDirect quaternion write, 2026-09-29) slipped past it. + Exit 0 = invariant holds, 1 = a violation (an AC mutator reachable off-thread), 2 = could not read the source tree. Wire into CI next to the golden tests / pe_pattern gate. @@ -54,9 +60,28 @@ MUTATOR_DELEGATES = { "_setSelectedObject", "_useObject", "_useObjectOn", "_useWithTargetEvent", "_useEquippedItem", "_moveItemExternal", "_moveItemInternal", "_eventStackableMerge", "_addTextToScroll", + # CM_Inventory sends (inventory game actions): give, wield, drop (Inventory panel) + "_eventGiveObjectRequest", "_eventGetAndWieldItem", "_eventDropItem", + # CM_Inventory::Event_NoLongerViewingContents (0x0195, close a corpse/chest; v76 CloseContainer) + "_eventNoLongerViewingContents", "_setAutoRun", "_turnToHeading", "_stopCompletely", "_setMotion", "_changeCombatMode", "_sendShopEvent", # VendorTrade: gmVendorUI::SendShopEvent (vendor buy/sell + busy count) + # PlayerTrade (v72): CM_Trade trade actions + ClientTradeSystem accept/decline (Trade object) + "_eventOpenTradeNegotiations", "_eventAddToTrade", "_eventResetTrade", + "_eventCloseTradeNegotiations", "_tradeSystemAcceptTrade", "_tradeSystemDeclineTrade", + # Salvage panel: open notice + gmSalvageUI AddNewItem/Salvage (UIElement tree) + "_sendNoticeOpenSalvagePanel", "_gmSalvageUIAddNewItem", "_gmSalvageUISalvage", + # CombatActionHooks game-action sends (AC heap alloc + send queue; 0xC8 also bumps busy count) + "_requestId", "_queryHealth", "_cancelAttack", + # MovementActionHooks: CM_Movement::Event_AutonomyLevel (0xF752 game-action send) + "_autonomyLevel", + # CharacterManagementHooks: CPlayerSystem::LogOnCharacter (login state + login send); + # the auto-login poll threads marshal it through MainThreadTick's request slot + "_logOnCharacter", + # PlayerTraining: CM_Train raise senders (RaiseAttribute / RaiseVital / RaiseSkill game actions) + "_eventTrainAttribute", "_eventTrainAttribute2nd", "_eventTrainSkill", + "_eventTrainSkillAdvancementClass", # 0x0047 TrainSkill (untrained -> trained with credits) } GATE = "MainThreadGuard.IsOnMainThread" ENQUEUE = "AcMainThreadQueue.Enqueue" @@ -67,6 +92,18 @@ ENQUEUE = "AcMainThreadQueue.Enqueue" # (file, method) pairs, each verified to do no off-thread AC mutation. ENQUEUE_PRODUCER_ALLOW = { ("AutoIdService.cs", "DrainTick"), # appraisal: enqueues 0xC8, sent on main thread in DrainRequestIds + ("RynthCoreChatCommands.cs", "Reply"), # /rc and /rv plates replies: only EnqueueWriteToChat +} + +# CHECK C sinks: raw stores into memory. Comments are stripped before matching. +RAW_WRITE = re.compile(r"\bMarshal\.Write(?:Byte|Int16|Int32|Int64|IntPtr)\s*\(|(?<![\w.])WriteFloat\s*\(") + +# Raw writers that do NOT touch live AC object state, so they need no gate. +# (file, method) pairs, each verified by reading the body. +RAW_WRITE_ALLOW = { + ("PlayerPhysicsHooks.cs", "WriteFloat"), # the helper itself; its callers are checked + ("ThreadStackSampler.cs", "SampleAll"), # writes ContextFlags into its OWN CONTEXT buffer + ("DatFileShareHooks.cs", "WriteIatPointer"), # IAT slot patch under VirtualProtect (hook plumbing, no callers today) } # Methods that run on AC's main thread BY CONSTRUCTION and may call mutators @@ -128,7 +165,7 @@ def main(): return 2 violations = [] - checked_a = checked_b = 0 + checked_a = checked_b = checked_c = 0 deleg_call = re.compile(r"(" + "|".join(re.escape(d) for d in MUTATOR_DELEGATES) + r")\s*\(") @@ -156,6 +193,14 @@ def main(): checked_b += 1 violations.append((fn, line, name, f"invokes AC-mutator delegate {hit}() without a MainThreadGuard gate")) + # CHECK C: raw memory store without the gate. + if not allowed and not gated and (fn, name) not in RAW_WRITE_ALLOW: + code = "\n".join(l.split("//", 1)[0] for l in body.splitlines()) + m = RAW_WRITE.search(code) + if m: + checked_c += 1 + violations.append((fn, line, name, f"raw memory write {m.group(0).rstrip('( ')}() without a MainThreadGuard gate")) + if violations: for fn, line, name, why in violations: print(f" [VIOLATION] {fn}:{line} {name}() - {why}") @@ -165,7 +210,7 @@ def main(): return 1 print(f"PASS: every marshalled helper is gated and every curated AC-mutator " - f"delegate is invoked behind the main-thread gate.") + f"delegate is invoked and every raw memory write sits behind the main-thread gate.") return 0 diff --git a/tools/check_phosphor_icons.py b/tools/check_phosphor_icons.py new file mode 100644 index 0000000..0a92580 --- /dev/null +++ b/tools/check_phosphor_icons.py @@ -0,0 +1,94 @@ +"""Checks src/RynthCore.Engine/ImGui/PhosphorIcons.cs against the Phosphor font. + + - every constant's code point is in the font's cmap; + - its name matches the font's own name for that code point (the font's + ligature table spells each icon's kebab-case name; single-letter names + such as "x" have no ligature and are only checked by code point); + - Baked holds every constant the ImGui code uses (PhosphorIcons.Name), so + no icon draws as nothing because it isn't in the atlas. + +Needs fontTools (pip install fonttools). Exit code 1 on any problem. +Usage: python tools/check_phosphor_icons.py +""" +import os +import re +import sys + +from fontTools.ttLib import TTFont + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +ENGINE = os.path.join(ROOT, 'src', 'RynthCore.Engine') +FONT = os.path.join(ENGINE, 'Assets', 'Fonts', 'Phosphor.ttf') +ICONS = os.path.join(ENGINE, 'ImGui', 'PhosphorIcons.cs') +IMGUI = os.path.join(ENGINE, 'ImGui') + + +def ligature_names(font): + """{kebab-name: code point} from the font's GSUB ligatures.""" + cmap = font.getBestCmap() + by_glyph = {} + for cp, glyph in cmap.items(): + by_glyph.setdefault(glyph, cp) + letters = {g: chr(cp) for g, cp in by_glyph.items() if cp < 0x80} + names = {} + for lookup in font['GSUB'].table.LookupList.Lookup: + for sub in lookup.SubTable: + if sub.LookupType == 7: + sub = sub.ExtSubTable + for first, ligs in getattr(sub, 'ligatures', {}).items(): + for lig in ligs: + name = ''.join(letters.get(g, '?') for g in [first] + list(lig.Component)) + if lig.LigGlyph in by_glyph: + names[name] = by_glyph[lig.LigGlyph] + return names + + +def kebab(pascal): + return re.sub(r'(?<!^)(?=[A-Z])', '-', pascal).lower() + + +def main(): + font = TTFont(FONT) + cmap = font.getBestCmap() + names = ligature_names(font) + src = open(ICONS, encoding='utf-8-sig').read() + consts = {m.group(1): int(m.group(2), 16) + for m in re.finditer(r'public const string (\w+) = "\\u([0-9A-Fa-f]{4})";', src)} + baked_expr = re.search(r'public const string Baked =(.*?);', src, re.S).group(1) + baked = set(re.findall(r'\b([A-Z]\w*)\b', baked_expr)) + + problems = [] + for name, cp in sorted(consts.items()): + if cp not in cmap: + problems.append(f'{name}: U+{cp:04X} is not in the font') + k = kebab(name) + if k in names and names[k] != cp: + problems.append(f'{name}: U+{cp:04X}, but the font has {k} at U+{names[k]:04X}') + elif k not in names: + print(f'note: {name} ({k}) has no ligature name in the font; checked by code point only') + for name in sorted(baked - consts.keys()): + problems.append(f'Baked names {name}, which is not a constant') + + used = set() + for dirpath, _, files in os.walk(IMGUI): + for f in files: + if f.endswith('.cs') and f != 'PhosphorIcons.cs': + text = open(os.path.join(dirpath, f), encoding='utf-8-sig').read() + used |= set(re.findall(r'PhosphorIcons\.(\w+)', text)) + used -= {'Baked', 'DrawCentered'} + for name in sorted(used - consts.keys()): + problems.append(f'PhosphorIcons.{name} is used but not declared') + for name in sorted((used & consts.keys()) - baked): + problems.append(f'PhosphorIcons.{name} is used but not in Baked (it would draw as nothing)') + unused = sorted(baked - used) + if unused: + print('note: in Baked but not used by the ImGui code: ' + ', '.join(unused)) + + print(f'{len(consts)} constants, {len(baked)} baked, {len(used)} used.') + for p in problems: + print('PROBLEM: ' + p) + return 1 if problems else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/navdata/Build-TownNet.ps1 b/tools/navdata/Build-TownNet.ps1 new file mode 100644 index 0000000..cda85c7 --- /dev/null +++ b/tools/navdata/Build-TownNet.ps1 @@ -0,0 +1,47 @@ +<# +.SYNOPSIS + Rebuilds townnet.json: the Town Network's portals (world database) and the walks inside (dats). + +.DESCRIPTION + 1. gen_townnet.py reads the portals from the world database (SELECT only, over ssh; or from a + dump with -FromDump) and writes townnet.json. + 2. RynthSuite's Tools\RynthNav.TownNet adds a checked walk from every arrival point to every + exit portal, from the retail dats (read only), then checks the file again. + + The live NavData folder is refused unless -ForceLive: copy the result there when it ships. + +.EXAMPLE + tools\navdata\Build-TownNet.ps1 + tools\navdata\Build-TownNet.ps1 -FromDump C:\Temp\tndump -Map C:\Temp\townnet.svg +#> +param( + [string]$Out = (Join-Path $PSScriptRoot "NavData"), + [string]$RynthSuite = (Join-Path $PSScriptRoot "..\..\..\RynthSuite"), + [string]$Ac = "C:\Games\ACE\Dats", + [string]$FromDump, + [string]$Dump, + [string]$Map, # also draw the floor plan with the walks (SVG) + [switch]$ForceLive +) +$ErrorActionPreference = "Stop" + +$outFull = [IO.Path]::GetFullPath($Out).TrimEnd('\') +if (-not $ForceLive -and $outFull -ieq "C:\Games\RynthCore\NavData") { + throw "$outFull is the live NavData folder; pass -ForceLive to write there." +} +$tool = Join-Path $RynthSuite "Tools\RynthNav.TownNet\RynthNav.TownNet.csproj" +if (-not (Test-Path $tool)) { throw "RynthNav.TownNet not found at $tool (pass -RynthSuite <checkout>)" } + +$py = @("$PSScriptRoot\gen_townnet.py", "--out", $outFull) +if ($FromDump) { $py += @("--from-dump", $FromDump) } +if ($Dump) { $py += @("--dump", $Dump) } +python @py +if ($LASTEXITCODE -ne 0) { throw "gen_townnet.py failed" } + +$json = Join-Path $outFull "townnet.json" +dotnet run -c Release --project $tool -- build --in $json --ac $Ac +if ($LASTEXITCODE -ne 0) { throw "RynthNav.TownNet build: some walks failed (see above)" } +dotnet run -c Release --no-build --project $tool -- check --in $json --ac $Ac +if ($LASTEXITCODE -ne 0) { throw "RynthNav.TownNet check failed" } +if ($Map) { dotnet run -c Release --no-build --project $tool -- map --in $json --ac $Ac --out $Map } +Write-Host "townnet.json ready: $json" diff --git a/tools/navdata/NavData/locations.json b/tools/navdata/NavData/locations.json new file mode 100644 index 0000000..5c8d57d --- /dev/null +++ b/tools/navdata/NavData/locations.json @@ -0,0 +1,10770 @@ +{ + "version": 1, + "generated": "2026-10-01T09:59:37Z", + "source": "aeshnidae_world", + "counts": {"Bindstone": 25, "Dungeon": 560, "Landmark": 6, "Lifestone": 255, "NPC": 4713, "Portal": 4065, "Town": 50, "Vendor": 1042}, + "locations": [ + {"name":"Underground","type":"Landmark","cell":"01E901AD","place":"dungeon","id":1}, + {"name":"Bandit Castle","type":"Town","cell":"BDD00006","place":"outdoor","ns":64.95,"ew":49.32,"id":2}, + {"name":"Night Club","type":"Landmark","cell":"013A02AE","place":"dungeon","id":3}, + {"name":"Hotel Swank","type":"Landmark","cell":"018A024F","place":"dungeon","id":4}, + {"name":"Storage","type":"Landmark","cell":"01110108","place":"dungeon","id":5}, + {"name":"Ayan Baqur","type":"Town","cell":"1133001F","place":"outdoor","ns":-60.46,"ew":-87.98,"id":6}, + {"name":"Marketplace","type":"Landmark","cell":"016C01BC","place":"dungeon","id":7}, + {"name":"Beach Fort","type":"Town","cell":"42DE000C","place":"outdoor","ns":76.0,"ew":-49.05,"id":8}, + {"name":"Stonehold","type":"Town","cell":"64D5000B","place":"outdoor","ns":68.66,"ew":-21.82,"id":9}, + {"name":"Plateau","type":"Town","cell":"49B70021","place":"outdoor","ns":44.54,"ew":-43.13,"id":10}, + {"name":"Dryreach","type":"Town","cell":"DA75002B","place":"outdoor","ns":-8.1,"ew":73.0,"id":11}, + {"name":"Glenden Wood","type":"Town","cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45,"id":12}, + {"name":"Eastham","type":"Town","cell":"CE940035","place":"outdoor","ns":16.92,"ew":63.48,"id":13}, + {"name":"Lytelthorpe","type":"Town","cell":"C0800007","place":"outdoor","ns":1.1,"ew":51.7,"id":14}, + {"name":"Rithwic","type":"Town","cell":"C98C0028","place":"outdoor","ns":10.84,"ew":59.32,"id":15}, + {"name":"Cragstone","type":"Town","cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36,"id":16}, + {"name":"Arwic","type":"Town","cell":"C6A90009","place":"outdoor","ns":33.27,"ew":56.65,"id":17}, + {"name":"Holtburg","type":"Town","cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6,"id":18}, + {"name":"Uziz","type":"Town","cell":"A260003C","place":"outdoor","ns":-24.78,"ew":28.41,"id":19}, + {"name":"Khayyaban","type":"Town","cell":"9F440012","place":"outdoor","ns":-47.45,"ew":25.62,"id":20}, + {"name":"Al-Arqas","type":"Town","cell":"8F58003B","place":"outdoor","ns":-31.3,"ew":13.22,"id":21}, + {"name":"Yaraq","type":"Town","cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82,"id":22}, + {"name":"Bluespire","type":"Town","cell":"21B00017","place":"outdoor","ns":39.54,"ew":-75.35,"id":23}, + {"name":"Greenspire","type":"Town","cell":"2BB5003C","place":"outdoor","ns":43.21,"ew":-66.8,"id":24}, + {"name":"Ahurenga","type":"Town","cell":"0FB90009","place":"outdoor","ns":46.09,"ew":-89.77,"id":25}, + {"name":"Neydisa","type":"Town","cell":"95D60033","place":"outdoor","ns":69.55,"ew":17.86,"id":26}, + {"name":"Tufa","type":"Town","cell":"876C0008","place":"outdoor","ns":-14.77,"ew":6.06,"id":27}, + {"name":"Al-Jalima","type":"Town","cell":"8588002C","place":"outdoor","ns":7.25,"ew":4.95,"id":28}, + {"name":"Zaikhal","type":"Town","cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72,"id":29}, + {"name":"Xarabydun","type":"Town","cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1,"id":30}, + {"name":"Qalabar","type":"Town","cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55,"id":31}, + {"name":"Samsur","type":"Town","cell":"977B000C","place":"outdoor","ns":-3.24,"ew":18.96,"id":32}, + {"name":"Sanamar","type":"Town","cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9,"id":33}, + {"name":"Redspire","type":"Town","cell":"17B2002A","place":"outdoor","ns":40.56,"ew":-83.0,"id":34}, + {"name":"Westwatch","type":"Town","cell":"23DA002C","place":"outdoor","ns":72.81,"ew":-73.36,"id":35}, + {"name":"Linvak Tukal","type":"Town","cell":"A21E001A","place":"outdoor","ns":-77.79,"ew":28.0,"id":36}, + {"name":"Eastwatch","type":"Town","cell":"49F00013","place":"outdoor","ns":90.34,"ew":-43.26,"id":37}, + {"name":"Shoushi","type":"Town","cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8,"id":38}, + {"name":"Tou-Tou","type":"Town","cell":"F5590034","place":"outdoor","ns":-30.41,"ew":94.69,"id":39}, + {"name":"Mayoi","type":"Town","cell":"E6320021","place":"outdoor","ns":-61.91,"ew":82.5,"id":40}, + {"name":"Nanto","type":"Town","cell":"E63E0022","place":"outdoor","ns":-52.19,"ew":82.45,"id":41}, + {"name":"Lin","type":"Town","cell":"DC3C0011","place":"outdoor","ns":-53.91,"ew":74.3,"id":42}, + {"name":"Baishi","type":"Town","cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9,"id":43}, + {"name":"Hebian-to","type":"Town","cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63,"id":44}, + {"name":"Yanshi","type":"Town","cell":"B46F001E","place":"outdoor","ns":-12.63,"ew":42.36,"id":45}, + {"name":"Kara","type":"Town","cell":"BA170039","place":"outdoor","ns":-83.54,"ew":47.6,"id":46}, + {"name":"Sawato","type":"Town","cell":"C95B0001","place":"outdoor","ns":-29.15,"ew":58.91,"id":47}, + {"name":"Kryst","type":"Town","cell":"E822002A","place":"outdoor","ns":-74.59,"ew":84.2,"id":48}, + {"name":"Silyun","type":"Town","cell":"26EC003D","place":"outdoor","ns":87.31,"ew":-70.82,"id":49}, + {"name":"Fiun","type":"Town","cell":"38F7001B","place":"outdoor","ns":95.88,"ew":-56.77,"id":50}, + {"name":"Timaru","type":"Town","cell":"1DB60016","place":"outdoor","ns":44.21,"ew":-78.45,"id":51}, + {"name":"Fort Tethana","type":"Town","cell":"2681001D","place":"outdoor","ns":1.7,"ew":-71.23,"id":52}, + {"name":"Refuge","type":"Town","cell":"F6820033","place":"outdoor","ns":2.26,"ew":95.46,"id":53}, + {"name":"Outpost","type":"Town","cell":"5A9C0004","place":"outdoor","ns":23.17,"ew":-29.85,"id":54}, + {"name":"Freehold","type":"Town","cell":"F224001A","place":"outdoor","ns":-73.01,"ew":91.99,"id":55}, + {"name":"Town Network","type":"Landmark","cell":"00070143","place":"dungeon","id":56}, + {"name":"Remote Empyrean Vault","type":"Dungeon","ns":81.65,"ew":-71.19,"cell":"26E5001C","place":"outdoor","lb":"0001","desc":"Dungeon, landblock 0001. 1 entrance.","id":57,"minLevel":40}, + {"name":"Viamontian Garrison","type":"Dungeon","ns":75.3,"ew":-73.8,"cell":"23DD000D","place":"outdoor","lb":"0002","desc":"Dungeon, landblock 0002. 1 entrance.","id":58}, + {"name":"Northern Power Forge","type":"Dungeon","ns":18.38,"ew":-22.83,"cell":"62960000","place":"outdoor","lb":"0004","desc":"Dungeon, landblock 0004. 1 entrance.","id":59,"minLevel":40}, + {"name":"Southern Power Forge","type":"Dungeon","ns":-82.27,"ew":-3.87,"cell":"7A180000","place":"outdoor","lb":"0005","desc":"Dungeon, landblock 0005. 1 entrance.","id":60,"minLevel":70}, + {"name":"Western Power Forge","type":"Dungeon","ns":-21.89,"ew":-43.8,"cell":"48640000","place":"outdoor","lb":"0006","desc":"Dungeon, landblock 0006. 1 entrance.","id":61,"minLevel":100}, + {"name":"Town Network","type":"Dungeon","ns":47.07,"ew":-90.26,"cell":"0EBA0023","place":"outdoor","lb":"0007","desc":"Dungeon, landblock 0007. 52 entrances.","id":62}, + {"name":"Defiled Temple Lower Wing","type":"Dungeon","ns":77.61,"ew":32.79,"cell":"A8E00108","place":"building","lb":"0008","desc":"Dungeon, landblock 0008. 1 entrance.","id":63,"minLevel":40}, + {"name":"Defiled Temple Upper Wing","type":"Dungeon","ns":77.69,"ew":32.89,"cell":"A8E0010D","place":"building","lb":"0009","desc":"Dungeon, landblock 0009. 1 entrance.","id":64,"minLevel":80}, + {"name":"Defiled Temple Asylum","type":"Dungeon","ns":77.79,"ew":32.8,"cell":"A8E00112","place":"building","lb":"000A","desc":"Dungeon, landblock 000A. 1 entrance.","id":65,"minLevel":100}, + {"name":"War Room","type":"Dungeon","ns":-11.9,"ew":-92.77,"cell":"0B700000","place":"outdoor","lb":"0010","desc":"Dungeon, landblock 0010. 1 entrance.","id":66,"minLevel":80}, + {"name":"Banished Assembly","type":"Dungeon","ns":-86.99,"ew":-79.59,"cell":"1B120101","place":"building","lb":"0015","desc":"Dungeon, landblock 0015. 1 entrance.","id":67,"minLevel":100}, + {"name":"Ravaged Cathedral","type":"Dungeon","ns":-86.21,"ew":-79.01,"cell":"1C130000","place":"outdoor","lb":"0016","desc":"Dungeon, landblock 0016. 1 entrance.","id":68,"minLevel":100}, + {"name":"Copper Legion Keep","type":"Dungeon","ns":12.1,"ew":0.58,"cell":"808E000D","place":"outdoor","lb":"0018","desc":"Dungeon, landblock 0018. 1 entrance.","id":69,"minLevel":50}, + {"name":"Gold Legion Keep","type":"Dungeon","ns":13.83,"ew":1.98,"cell":"8190003E","place":"outdoor","lb":"0019","desc":"Dungeon, landblock 0019. 1 entrance.","id":70,"minLevel":80}, + {"name":"Platinum Legion Keep","type":"Dungeon","ns":16.52,"ew":0.61,"cell":"80940009","place":"outdoor","lb":"001A","desc":"Dungeon, landblock 001A. 1 entrance.","id":71,"minLevel":100}, + {"name":"Silver Legion Keep","type":"Dungeon","ns":13.55,"ew":-1.52,"cell":"7D900023","place":"outdoor","lb":"001B","desc":"Dungeon, landblock 001B. 1 entrance.","id":72,"minLevel":65}, + {"name":"Lugian Ice Tunnels","type":"Dungeon","ns":93.31,"ew":-50.1,"cell":"40F40031","place":"outdoor","lb":"001C","desc":"Dungeon, landblock 001C. 1 entrance.","id":73,"minLevel":80}, + {"name":"Ruschk Icehold","type":"Dungeon","ns":87.3,"ew":-51.81,"cell":"3EEC002D","place":"outdoor","lb":"001D","desc":"Dungeon, landblock 001D. 1 entrance.","id":74,"minLevel":80}, + {"name":"Viamontian Royal Prison","type":"Dungeon","ns":92.0,"ew":-41.6,"cell":"4BF2001C","place":"outdoor","lb":"001E","desc":"Dungeon, landblock 001E. 1 entrance.","id":75,"minLevel":80}, + {"name":"Hall of Karlun","type":"Dungeon","ns":88.91,"ew":-67.81,"cell":"2AEE002D","place":"outdoor","lb":"0021","desc":"Dungeon, landblock 0021. 1 entrance.","id":76,"minLevel":40}, + {"name":"Thrungus Hole","type":"Dungeon","ns":94.11,"ew":-42.97,"cell":"49F50100","place":"building","lb":"0029","desc":"Dungeon, landblock 0029. 1 entrance.","id":77,"minLevel":126}, + {"name":"Path of the Blind","type":"Dungeon","ns":91.12,"ew":-47.99,"cell":"43F1001B","place":"outdoor","lb":"002A","desc":"Dungeon, landblock 002A. 1 entrance.","id":78,"minLevel":140}, + {"name":"Egg Orchard","type":"Dungeon","ns":96.2,"ew":-48.1,"cell":"43F70016","place":"outdoor","lb":"002B","desc":"Dungeon, landblock 002B. 1 entrance.","id":79,"minLevel":140}, + {"name":"Forgotten Chasm","type":"Dungeon","ns":94.53,"ew":-39.1,"cell":"4EF50025","place":"outdoor","lb":"002C","desc":"Dungeon, landblock 002C. 1 entrance.","id":80,"minLevel":130}, + {"name":"Dark Design","type":"Dungeon","ns":93.81,"ew":-44.91,"cell":"47F40016","place":"outdoor","lb":"002D","desc":"Dungeon, landblock 002D. 1 entrance.","id":81,"minLevel":140}, + {"name":"Feeding Tubes","type":"Dungeon","ns":96.68,"ew":-42.38,"cell":"4AF8001B","place":"outdoor","lb":"002E","desc":"Dungeon, landblock 002E. 1 entrance.","id":82,"minLevel":130}, + {"name":"Renegade Incursion","type":"Dungeon","ns":0.51,"ew":-73.29,"cell":"23800031","place":"outdoor","lb":"0030","desc":"Dungeon, landblock 0030. 1 entrance.","id":83,"minLevel":50}, + {"name":"Creepy Canyons","type":"Dungeon","ns":4.59,"ew":-89.47,"cell":"0F850022","place":"outdoor","lb":"0031","desc":"Dungeon, landblock 0031. 1 entrance.","id":84,"minLevel":100}, + {"name":"Tunnel of Love","type":"Dungeon","ns":-94.41,"ew":-96.56,"cell":"0609002C","place":"outdoor","lb":"0032","desc":"Dungeon, landblock 0032. 1 entrance.","id":85,"minLevel":120}, + {"name":"Icy Hideout","type":"Dungeon","ns":90.49,"ew":-42.46,"cell":"4AF00015","place":"outdoor","lb":"0033","desc":"Dungeon, landblock 0033. 2 entrances.","id":86}, + {"name":"Breached Hive","type":"Dungeon","ns":49.91,"ew":-73.12,"cell":"24BD0007","place":"outdoor","lb":"003E","desc":"Dungeon, landblock 003E. 1 entrance.","id":87,"minLevel":50}, + {"name":"Master Alizari's Dig","type":"Dungeon","ns":19.34,"ew":-43.19,"cell":"4997001D","place":"outdoor","lb":"0040","desc":"Dungeon, landblock 0040. 1 entrance.","id":88,"minLevel":40}, + {"name":"Mistress Halmera's Dig","type":"Dungeon","ns":8.58,"ew":-58.56,"cell":"368A000A","place":"outdoor","lb":"0041","desc":"Dungeon, landblock 0041. 1 entrance.","id":89,"minLevel":60}, + {"name":"Mistress Gabille's Dig","type":"Dungeon","ns":8.49,"ew":-88.91,"cell":"108A0011","place":"outdoor","lb":"0042","desc":"Dungeon, landblock 0042. 1 entrance.","id":90,"minLevel":80}, + {"name":"Master Vaserio's Dig","type":"Dungeon","ns":-54.2,"ew":-78.57,"cell":"1D3B000E","place":"outdoor","lb":"0043","desc":"Dungeon, landblock 0043. 1 entrance.","id":91,"minLevel":100}, + {"name":"Temple of the Stirring Shadow","type":"Dungeon","ns":74.27,"ew":58.67,"cell":"C8DC0033","place":"outdoor","lb":"0045","desc":"Dungeon, landblock 0045. 1 entrance.","id":92,"minLevel":80}, + {"name":"Repository","type":"Dungeon","ns":-89.32,"ew":-93.48,"cell":"0A0F0027","place":"outdoor","lb":"0047","desc":"Dungeon, landblock 0047. 1 entrance.","id":93,"minLevel":125}, + {"name":"Viamontian Direlands Mine","type":"Dungeon","ns":91.3,"ew":-38.41,"cell":"4FF10128","place":"building","lb":"0048","desc":"Dungeon, landblock 0048. 3 entrances.","id":94,"minLevel":100}, + {"name":"Camp Entemarre","type":"Dungeon","ns":-62.96,"ew":-82.57,"cell":"1830000E","place":"outdoor","lb":"0049","desc":"Dungeon, landblock 0049. 1 entrance.","id":95,"minLevel":80}, + {"name":"Creepy Chambers","type":"Dungeon","ns":-80.09,"ew":-60.02,"cell":"341B001B","place":"outdoor","lb":"004A","desc":"Dungeon, landblock 004A. 1 entrance.","id":96}, + {"name":"Path of the Blind West","type":"Dungeon","ns":91.11,"ew":-48.02,"cell":"43F1001B","place":"outdoor","lb":"004B","desc":"Dungeon, landblock 004B. 1 entrance.","id":97,"minLevel":140}, + {"name":"Eastern Temple Catacombs","type":"Dungeon","ns":80.0,"ew":54.57,"cell":"C3E3002C","place":"outdoor","lb":"004D","desc":"Dungeon, landblock 004D. 2 entrances.","id":98,"minLevel":100}, + {"name":"Vault of Eternal Slumber","type":"Dungeon","ns":80.17,"ew":54.4,"cell":"C3E3001E","place":"outdoor","lb":"004E","desc":"Dungeon, landblock 004E. 2 entrances.","id":99,"minLevel":100}, + {"name":"Temple of the Black Spear","type":"Dungeon","ns":95.34,"ew":-52.24,"cell":"3EF6000D","place":"outdoor","lb":"004F","desc":"Dungeon, landblock 004F. 1 entrance.","id":100,"minLevel":130}, + {"name":"Silyun Chapterhouse","type":"Dungeon","ns":85.38,"ew":-70.4,"cell":"27EA001A","place":"outdoor","lb":"0052","desc":"Dungeon, landblock 0052. 1 entrance.","id":101,"minLevel":80}, + {"name":"Shade Iron Mine","type":"Dungeon","ns":-65.06,"ew":-87.6,"cell":"112E0101","place":"building","lb":"0053","desc":"Dungeon, landblock 0053. 1 entrance.","id":102,"minLevel":80}, + {"name":"Deep Mukkir Nest","type":"Dungeon","ns":80.97,"ew":59.3,"cell":"C9E40026","place":"outdoor","lb":"0054","desc":"Dungeon, landblock 0054. 1 entrance.","id":103,"minLevel":150}, + {"name":"Egg Orchard East","type":"Dungeon","ns":96.19,"ew":-48.03,"cell":"43F7001E","place":"outdoor","lb":"0064","desc":"Dungeon, landblock 0064. 1 entrance.","id":104,"minLevel":140}, + {"name":"Thrungal Den","type":"Dungeon","ns":79.36,"ew":-71.63,"cell":"25E2003E","place":"outdoor","lb":"0065","desc":"Dungeon, landblock 0065. 1 entrance.","id":105,"minLevel":100}, + {"name":"Viamontian Laboratory","type":"Dungeon","ns":39.41,"ew":-75.33,"cell":"21B0013B","place":"building","lb":"0068","desc":"Dungeon, landblock 0068. 1 entrance.","id":106,"minLevel":30}, + {"name":"Augmentation Realm Upper Level","type":"Dungeon","ns":94.96,"ew":-47.09,"cell":"44F60022","place":"outdoor","lb":"006D","desc":"Dungeon, landblock 006D. 1 entrance.","id":107,"minLevel":125}, + {"name":"Empyrean Workshop","type":"Dungeon","ns":66.88,"ew":15.89,"cell":"93D30011","place":"outdoor","lb":"006E","desc":"Dungeon, landblock 006E. 1 entrance.","id":108,"minLevel":125}, + {"name":"Black Ferah's Vault","type":"Dungeon","ns":-39.06,"ew":-60.06,"cell":"344E0015","place":"outdoor","lb":"0073","desc":"Dungeon, landblock 0073. 1 entrance.","id":109,"minLevel":151}, + {"name":"Black Spear Temple","type":"Dungeon","ns":74.04,"ew":-28.61,"cell":"5BDB0030","place":"outdoor","lb":"0074","desc":"Dungeon, landblock 0074. 1 entrance.","id":110}, + {"name":"Grael's Chamber","type":"Dungeon","ns":15.9,"ew":-69.94,"cell":"28930003","place":"outdoor","lb":"0075","desc":"Dungeon, landblock 0075. 2 entrances.","id":111,"minLevel":101}, + {"name":"Mukkir-Infested Black Spear Temple","type":"Dungeon","ns":-37.24,"ew":-66.96,"cell":"2B500030","place":"outdoor","lb":"0076","desc":"Dungeon, landblock 0076. 1 entrance.","id":112,"minLevel":151}, + {"name":"Tanada House of Storms","type":"Dungeon","ns":-68.11,"ew":45.53,"cell":"B82A0013","place":"outdoor","lb":"007B","desc":"Dungeon, landblock 007B. 1 entrance.","id":113,"minLevel":80}, + {"name":"Soul Hunter's Lair","type":"Dungeon","ns":-27.67,"ew":55.77,"cell":"C55C000F","place":"outdoor","lb":"007C","desc":"Dungeon, landblock 007C. 1 entrance.","id":114,"minLevel":60}, + {"name":"Dardante's Workshop","type":"Dungeon","ns":69.59,"ew":-62.69,"cell":"31D60154","place":"building","lb":"007F","desc":"Dungeon, landblock 007F. 1 entrance.","id":115,"minLevel":100}, + {"name":"Rossu Morta Chapterhouse","type":"Dungeon","ns":69.66,"ew":-62.33,"cell":"31D60025","place":"outdoor","lb":"0080","desc":"Dungeon, landblock 0080. 1 entrance.","id":116}, + {"name":"Whispering Blade Chapterhouse","type":"Dungeon","ns":-59.92,"ew":-87.22,"cell":"1234001D","place":"outdoor","lb":"0081","desc":"Dungeon, landblock 0081. 1 entrance.","id":117}, + {"name":"Pheraion's Sanctum","type":"Dungeon","ns":-59.75,"ew":-75.11,"cell":"21340027","place":"outdoor","lb":"0083","desc":"Dungeon, landblock 0083. 1 entrance.","id":118,"minLevel":120}, + {"name":"Altar Nest","type":"Dungeon","ns":75.88,"ew":69.39,"cell":"D6DE000B","place":"outdoor","lb":"0085","desc":"Dungeon, landblock 0085. 1 entrance.","id":119,"minLevel":140}, + {"name":"Ikzisik Tika Ri Zikma","type":"Dungeon","ns":70.65,"ew":-14.5,"cell":"6DD70016","place":"outdoor","lb":"0087","desc":"Dungeon, landblock 0087. 1 entrance.","id":120,"minLevel":90}, + {"name":"Ancient Masonry","type":"Dungeon","ns":88.09,"ew":47.6,"cell":"BAED003D","place":"outdoor","lb":"008B","desc":"Dungeon, landblock 008B. 1 entrance.","id":121,"minLevel":100}, + {"name":"Insatiable Vault","type":"Dungeon","ns":97.36,"ew":-48.02,"cell":"43F9001A","place":"outdoor","lb":"0096","desc":"Dungeon, landblock 0096. 1 entrance.","id":122,"minLevel":125}, + {"name":"Tanada House of Water","type":"Dungeon","ns":-85.33,"ew":-5.77,"cell":"7814000F","place":"outdoor","lb":"009E","desc":"Dungeon, landblock 009E. 1 entrance.","id":123,"minLevel":80}, + {"name":"Hidden Laboratory","type":"Dungeon","ns":67.25,"ew":-27.15,"cell":"5DD30024","place":"outdoor","lb":"00A4","desc":"Dungeon, landblock 00A4. 1 entrance.","id":124,"minLevel":150}, + {"name":"Lonely Fortress","type":"Dungeon","ns":-56.7,"ew":-88.42,"cell":"10380100","place":"building","lb":"00A5","desc":"Dungeon, landblock 00A5. 1 entrance.","id":125,"minLevel":80}, + {"name":"Roots of the Deru Tree","type":"Dungeon","ns":-90.27,"ew":87.35,"cell":"EC0E002D","place":"outdoor","lb":"00A8","desc":"Dungeon, landblock 00A8. 1 entrance.","id":126}, + {"name":"Trial of the Deep","type":"Dungeon","ns":85.47,"ew":57.15,"cell":"C6EA003B","place":"outdoor","lb":"00A9","desc":"Dungeon, landblock 00A9. 1 entrance.","id":127}, + {"name":"Olthoi Sanctuary","type":"Dungeon","ns":44.24,"ew":62.79,"cell":"CDB6003E","place":"outdoor","lb":"00AA","desc":"Dungeon, landblock 00AA. 1 entrance.","id":128}, + {"name":"The Colosseum","type":"Dungeon","ns":-11.24,"ew":37.54,"cell":"AE710014","place":"outdoor","lb":"00AF","desc":"Dungeon, landblock 00AF. 1 entrance.","id":129}, + {"name":"Mosswart Worship Cavern","type":"Dungeon","ns":-41.07,"ew":-48.76,"cell":"424C0019","place":"outdoor","lb":"00B5","desc":"Dungeon, landblock 00B5. 1 entrance.","id":130,"minLevel":80}, + {"name":"Celestial Hand Stronghold","type":"Dungeon","ns":-39.71,"ew":83.59,"cell":"E74D003F","place":"outdoor","lb":"00B7","desc":"Dungeon, landblock 00B7. 1 entrance.","id":131,"minLevel":180}, + {"name":"Eldrytch Web Stronghold","type":"Dungeon","ns":26.28,"ew":49.67,"cell":"BDA00023","place":"outdoor","lb":"00B8","desc":"Dungeon, landblock 00B8. 1 entrance.","id":132,"minLevel":180}, + {"name":"Radiant Blood Stronghold","type":"Dungeon","ns":12.78,"ew":0.68,"cell":"808F0014","place":"outdoor","lb":"00B9","desc":"Dungeon, landblock 00B9. 1 entrance.","id":133,"minLevel":180}, + {"name":"Corrupted Catacombs","type":"Dungeon","ns":-23.95,"ew":54.09,"cell":"C3610005","place":"outdoor","lb":"00BA","desc":"Dungeon, landblock 00BA. 1 entrance.","id":134,"minLevel":180}, + {"name":"South Gate","type":"Dungeon","ns":-65.01,"ew":-63.81,"cell":"2F2E002A","place":"outdoor","lb":"00C0","desc":"Dungeon, landblock 00C0. 3 entrances.","id":135}, + {"name":"Blighted Rank Moarsman Tunnels","type":"Dungeon","ns":40.7,"ew":-86.46,"cell":"13B20013","place":"outdoor","lb":"00C1","desc":"Dungeon, landblock 00C1. 1 entrance.","id":136,"minLevel":15}, + {"name":"Blighted Disgusting Moarsman Tunnels","type":"Dungeon","ns":-60.7,"ew":82.96,"cell":"E733000D","place":"outdoor","lb":"00C2","desc":"Dungeon, landblock 00C2. 1 entrance.","id":137,"minLevel":35}, + {"name":"Blighted Putrid Moarsman Tunnels","type":"Dungeon","ns":22.5,"ew":-30.46,"cell":"599B0015","place":"outdoor","lb":"00C3","desc":"Dungeon, landblock 00C3. 1 entrance.","id":138,"minLevel":55}, + {"name":"Blighted Desolation Moarsman Tunnels","type":"Dungeon","ns":75.1,"ew":-49.66,"cell":"41DD0013","place":"outdoor","lb":"00C4","desc":"Dungeon, landblock 00C4. 1 entrance.","id":139,"minLevel":75}, + {"name":"Blighted Grimy Moarsman Tunnels","type":"Dungeon","ns":-60.9,"ew":-89.66,"cell":"0F330013","place":"outdoor","lb":"00C5","desc":"Dungeon, landblock 00C5. 1 entrance.","id":140,"minLevel":95}, + {"name":"Blighted Verdant Moarsman Tunnels","type":"Dungeon","ns":92.7,"ew":-42.36,"cell":"4AF3001B","place":"outdoor","lb":"00C6","desc":"Dungeon, landblock 00C6. 1 entrance.","id":141,"minLevel":125}, + {"name":"Crystalline","type":"Dungeon","ns":-17.0,"ew":-61.26,"cell":"326A0032","place":"outdoor","lb":"00C7","desc":"Dungeon, landblock 00C7. 1 entrance.","id":142,"minLevel":70}, + {"name":"Egg Orchard West","type":"Dungeon","ns":96.19,"ew":-48.15,"cell":"43F7000E","place":"outdoor","lb":"00C8","desc":"Dungeon, landblock 00C8. 1 entrance.","id":143,"minLevel":140}, + {"name":"Chamber of Scrolls","type":"Dungeon","ns":-52.23,"ew":63.23,"cell":"CE3E001A","place":"outdoor","lb":"00C9","desc":"Dungeon, landblock 00C9. 1 entrance.","id":144,"minLevel":100}, + {"name":"Entrance to the pyramid","type":"Dungeon","ns":58.43,"ew":-11.18,"cell":"71C8001C","place":"outdoor","lb":"00CB","desc":"Dungeon, landblock 00CB. 3 entrances.","id":145,"minLevel":125}, + {"name":"The Dark Spiral","type":"Dungeon","ns":15.87,"ew":-68.71,"cell":"29930023","place":"outdoor","lb":"00CF","desc":"Dungeon, landblock 00CF. 1 entrance.","id":146,"minLevel":126}, + {"name":"Rogue Delvings","type":"Dungeon","ns":74.78,"ew":18.36,"cell":"96DC0020","place":"outdoor","lb":"00E0","desc":"Dungeon, landblock 00E0. 1 entrance.","id":147,"minLevel":180}, + {"name":"Path of the Blind East","type":"Dungeon","ns":91.1,"ew":-47.95,"cell":"43F1001B","place":"outdoor","lb":"00E1","desc":"Dungeon, landblock 00E1. 1 entrance.","id":148,"minLevel":140}, + {"name":"Gardens of Menilesh","type":"Dungeon","ns":-64.69,"ew":-43.79,"cell":"482E002D","place":"outdoor","lb":"00E7","desc":"Dungeon, landblock 00E7. 1 entrance.","id":149,"minLevel":150}, + {"name":"Mhoire Armory","type":"Dungeon","ns":-64.81,"ew":-44.28,"cell":"482E0140","place":"building","lb":"00EA","desc":"Dungeon, landblock 00EA. 1 entrance.","id":150,"minLevel":160}, + {"name":"Artifex Collegium","type":"Dungeon","ns":-91.89,"ew":-93.7,"cell":"0A0C0015","place":"outdoor","lb":"00ED","desc":"Dungeon, landblock 00ED. 1 entrance.","id":151}, + {"name":"Cave","type":"Dungeon","ns":25.39,"ew":45.93,"cell":"B89F0102","place":"building","lb":"00EE","desc":"Dungeon, landblock 00EE. 1 entrance.","id":152}, + {"name":"Temple","type":"Dungeon","ns":84.31,"ew":24.67,"cell":"9EE80017","place":"outdoor","lb":"00EF","desc":"Dungeon, landblock 00EF. 1 entrance.","id":153,"minLevel":120}, + {"name":"Upper Sanctum of Xik Minru","type":"Dungeon","ns":72.9,"ew":69.15,"cell":"D5DA0035","place":"outdoor","lb":"00F0","desc":"Dungeon, landblock 00F0. 4 entrances.","id":154,"minLevel":130}, + {"name":"Murk Warrens","type":"Dungeon","ns":-43.2,"ew":67.03,"cell":"D3490000","place":"outdoor","lb":"0100","desc":"Dungeon, landblock 0100. 1 entrance.","id":155}, + {"name":"Murk Warrens","type":"Dungeon","ns":26.3,"ew":1.93,"cell":"81A00000","place":"outdoor","lb":"0101","desc":"Dungeon, landblock 0101. 1 entrance.","id":156}, + {"name":"Murk Warrens","type":"Dungeon","ns":67.49,"ew":-29.33,"cell":"5AD30000","place":"outdoor","lb":"0102","desc":"Dungeon, landblock 0102. 1 entrance.","id":157}, + {"name":"Black Spawn Den","type":"Dungeon","ns":-60.05,"ew":-57.64,"cell":"37340000","place":"outdoor","lb":"0103","desc":"Dungeon, landblock 0103. 1 entrance.","id":158,"minLevel":20}, + {"name":"Black Spawn Den","type":"Dungeon","ns":-56.69,"ew":-86.02,"cell":"13380000","place":"outdoor","lb":"0104","desc":"Dungeon, landblock 0104. 1 entrance.","id":159,"minLevel":20}, + {"name":"Black Spawn Den","type":"Dungeon","ns":13.61,"ew":-79.84,"cell":"1B900000","place":"outdoor","lb":"0105","desc":"Dungeon, landblock 0105. 1 entrance.","id":160,"minLevel":20}, + {"name":"Setab's Barracks","type":"Dungeon","ns":2.73,"ew":53.49,"cell":"C2820000","place":"outdoor","lb":"0106","desc":"Dungeon, landblock 0106. 1 entrance.","id":161}, + {"name":"Nor's Folly","type":"Dungeon","ns":-32.48,"ew":11.86,"cell":"8E560000","place":"outdoor","lb":"0107","desc":"Dungeon, landblock 0107. 1 entrance.","id":162}, + {"name":"Cursed Swamp","type":"Dungeon","ns":-27.31,"ew":69.04,"cell":"D55D0000","place":"outdoor","lb":"0108","desc":"Dungeon, landblock 0108. 1 entrance.","id":163}, + {"name":"Black Dominion","type":"Dungeon","ns":-88.63,"ew":-25.91,"cell":"5F100000","place":"outdoor","lb":"010A","desc":"Dungeon, landblock 010A. 1 entrance.","id":164,"minLevel":25}, + {"name":"Asuger Temple","type":"Dungeon","ns":45.07,"ew":30.37,"cell":"A5B70000","place":"outdoor","lb":"010B","desc":"Dungeon, landblock 010B. 1 entrance.","id":165,"minLevel":20}, + {"name":"Mysterious Tunnels","type":"Dungeon","ns":-52.87,"ew":82.94,"cell":"E73D0000","place":"outdoor","lb":"010C","desc":"Dungeon, landblock 010C. 1 entrance.","id":166,"minLevel":1}, + {"name":"Nexus","type":"Dungeon","ns":-40.14,"ew":-79.14,"cell":"1C4D0000","place":"outdoor","lb":"0110","desc":"Dungeon, landblock 0110. 1 entrance.","id":167,"minLevel":100}, + {"name":"Amiantos Bethel","type":"Dungeon","ns":-16.28,"ew":35.13,"cell":"AB6B0000","place":"outdoor","lb":"0113","desc":"Dungeon, landblock 0113. 1 entrance.","id":168}, + {"name":"Sultry Hovel","type":"Dungeon","ns":74.02,"ew":-61.53,"cell":"32DB0100","place":"building","lb":"0114","desc":"Dungeon, landblock 0114. 1 entrance.","id":169}, + {"name":"Tenkarrdun Foundry","type":"Dungeon","ns":88.9,"ew":42.76,"cell":"B4EE0100","place":"building","lb":"0116","desc":"Dungeon, landblock 0116. 1 entrance.","id":170,"minLevel":40}, + {"name":"Serac Vault","type":"Dungeon","ns":-75.89,"ew":28.98,"cell":"A3200000","place":"outdoor","lb":"0117","desc":"Dungeon, landblock 0117. 2 entrances.","id":171}, + {"name":"Drudge Hovel","type":"Dungeon","ns":-23.7,"ew":-0.2,"cell":"7F61000F","place":"outdoor","lb":"0118","desc":"Dungeon, landblock 0118. 1 entrance.","id":172}, + {"name":"Amperehelion Vault","type":"Dungeon","ns":-56.49,"ew":-72.78,"cell":"24380000","place":"outdoor","lb":"0119","desc":"Dungeon, landblock 0119. 2 entrances.","id":173}, + {"name":"Incunabula Vault","type":"Dungeon","ns":-35.85,"ew":-47.23,"cell":"44520000","place":"outdoor","lb":"011A","desc":"Dungeon, landblock 011A. 2 entrances.","id":174}, + {"name":"Jahannan Vault","type":"Dungeon","ns":-49.77,"ew":14.96,"cell":"92410000","place":"outdoor","lb":"011B","desc":"Dungeon, landblock 011B. 2 entrances.","id":175}, + {"name":"Mountain Fortress","type":"Dungeon","ns":-82.39,"ew":19.87,"cell":"98180000","place":"outdoor","lb":"011C","desc":"Dungeon, landblock 011C. 1 entrance.","id":176,"minLevel":100}, + {"name":"Al-Arqas Meeting Hall","type":"Dungeon","ns":-31.22,"ew":13.82,"cell":"90580152","place":"building","lb":"011D","desc":"Dungeon, landblock 011D. 1 entrance.","id":177}, + {"name":"Al-Jalima Meeting Hall","type":"Dungeon","ns":7.7,"ew":4.9,"cell":"85890101","place":"building","lb":"011E","desc":"Dungeon, landblock 011E. 1 entrance.","id":178}, + {"name":"Arwic Meeting Hall","type":"Dungeon","ns":33.57,"ew":55.78,"cell":"C5A90101","place":"building","lb":"011F","desc":"Dungeon, landblock 011F. 1 entrance.","id":179}, + {"name":"Baishi Meeting Hall","type":"Dungeon","ns":-49.42,"ew":62.28,"cell":"CD41018E","place":"building","lb":"0120","desc":"Dungeon, landblock 0120. 1 entrance.","id":180}, + {"name":"Cragstone Meeting Hall","type":"Dungeon","ns":26.0,"ew":49.1,"cell":"BC9F0169","place":"building","lb":"0121","desc":"Dungeon, landblock 0121. 1 entrance.","id":181}, + {"name":"Eastham Meeting Hall","type":"Dungeon","ns":17.6,"ew":63.52,"cell":"CE950172","place":"building","lb":"0122","desc":"Dungeon, landblock 0122. 1 entrance.","id":182}, + {"name":"Glenden Wood Meeting Hall","type":"Dungeon","ns":29.98,"ew":27.42,"cell":"A1A40167","place":"building","lb":"0123","desc":"Dungeon, landblock 0123. 1 entrance.","id":183}, + {"name":"Hebian-to Meeting Hall","type":"Dungeon","ns":-39.31,"ew":83.3,"cell":"E74E01C9","place":"building","lb":"0124","desc":"Dungeon, landblock 0124. 1 entrance.","id":184}, + {"name":"Holtburg Meeting Hall","type":"Dungeon","ns":42.21,"ew":33.91,"cell":"A9B4017A","place":"building","lb":"0125","desc":"Dungeon, landblock 0125. 2 entrances.","id":185}, + {"name":"Khayyaban Meeting Hall","type":"Dungeon","ns":-48.22,"ew":24.38,"cell":"9D430101","place":"building","lb":"0126","desc":"Dungeon, landblock 0126. 1 entrance.","id":186}, + {"name":"Lin Meeting Hall","type":"Dungeon","ns":-54.8,"ew":73.22,"cell":"DA3A010B","place":"building","lb":"0127","desc":"Dungeon, landblock 0127. 1 entrance.","id":187}, + {"name":"Lytelthorpe Meeting Hall","type":"Dungeon","ns":0.81,"ew":51.6,"cell":"BF800191","place":"building","lb":"0128","desc":"Dungeon, landblock 0128. 1 entrance.","id":188}, + {"name":"Mayoi Meeting Hall","type":"Dungeon","ns":-61.39,"ew":81.79,"cell":"E5320139","place":"building","lb":"0129","desc":"Dungeon, landblock 0129. 1 entrance.","id":189}, + {"name":"Nanto Meeting Hall","type":"Dungeon","ns":-52.51,"ew":82.53,"cell":"E63D0166","place":"building","lb":"012A","desc":"Dungeon, landblock 012A. 1 entrance.","id":190}, + {"name":"Qalaba'r Meeting Hall","type":"Dungeon","ns":-74.2,"ew":19.0,"cell":"97220162","place":"building","lb":"012B","desc":"Dungeon, landblock 012B. 1 entrance.","id":191}, + {"name":"Rithwic Meeting Hall","type":"Dungeon","ns":10.91,"ew":58.2,"cell":"C88D0101","place":"building","lb":"012C","desc":"Dungeon, landblock 012C. 1 entrance.","id":192}, + {"name":"Samsur Meeting Hall","type":"Dungeon","ns":-2.81,"ew":19.71,"cell":"987B0101","place":"building","lb":"012D","desc":"Dungeon, landblock 012D. 1 entrance.","id":193}, + {"name":"Sawato Meeting Hall","type":"Dungeon","ns":-28.48,"ew":59.3,"cell":"C95B0175","place":"building","lb":"012E","desc":"Dungeon, landblock 012E. 1 entrance.","id":194}, + {"name":"Shoushi Meeting Hall","type":"Dungeon","ns":-33.18,"ew":72.88,"cell":"DA5501EB","place":"building","lb":"012F","desc":"Dungeon, landblock 012F. 1 entrance.","id":195}, + {"name":"Tufa Meeting Hall","type":"Dungeon","ns":-14.01,"ew":4.99,"cell":"856D0101","place":"building","lb":"0131","desc":"Dungeon, landblock 0131. 1 entrance.","id":196}, + {"name":"Uziz Meeting Hall","type":"Dungeon","ns":-25.2,"ew":28.19,"cell":"A25F0166","place":"building","lb":"0132","desc":"Dungeon, landblock 0132. 1 entrance.","id":197}, + {"name":"Yanshi Meeting Hall","type":"Dungeon","ns":-12.49,"ew":42.8,"cell":"B46F0106","place":"building","lb":"0133","desc":"Dungeon, landblock 0133. 1 entrance.","id":198}, + {"name":"Yaraq Meeting Hall","type":"Dungeon","ns":-21.8,"ew":-1.8,"cell":"7D640173","place":"building","lb":"0134","desc":"Dungeon, landblock 0134. 1 entrance.","id":199}, + {"name":"Zaikhal Meeting Hall","type":"Dungeon","ns":13.37,"ew":0.69,"cell":"8090015D","place":"building","lb":"0135","desc":"Dungeon, landblock 0135. 1 entrance.","id":200}, + {"name":"Empyrean Foundry","type":"Dungeon","ns":-25.1,"ew":54.13,"cell":"C3600000","place":"outdoor","lb":"0136","desc":"Dungeon, landblock 0136. 1 entrance.","id":201,"minLevel":100}, + {"name":"Artifex Vault","type":"Dungeon","ns":26.48,"ew":-45.77,"cell":"46A00000","place":"outdoor","lb":"0137","desc":"Dungeon, landblock 0137. 2 entrances.","id":202}, + {"name":"Mage Academy","type":"Dungeon","ns":74.72,"ew":18.49,"cell":"96DC0000","place":"outdoor","lb":"0139","desc":"Dungeon, landblock 0139. 1 entrance.","id":203,"minLevel":150}, + {"name":"Underground Forest","type":"Dungeon","ns":31.49,"ew":20.74,"cell":"99A60000","place":"outdoor","lb":"013C","desc":"Dungeon, landblock 013C. 1 entrance.","id":204}, + {"name":"Burial Temple","type":"Dungeon","ns":8.5,"ew":5.93,"cell":"868A0000","place":"outdoor","lb":"013E","desc":"Dungeon, landblock 013E. 1 entrance.","id":205,"minLevel":150}, + {"name":"Saadia's Retreat","type":"Dungeon","ns":-53.6,"ew":76.62,"cell":"DF3C0000","place":"outdoor","lb":"013F","desc":"Dungeon, landblock 013F. 1 entrance.","id":206}, + {"name":"Virindi Fort","type":"Dungeon","ns":-61.62,"ew":-54.13,"cell":"3B320000","place":"outdoor","lb":"0140","desc":"Dungeon, landblock 0140. 1 entrance.","id":207,"minLevel":15}, + {"name":"Enkindled Souls","type":"Dungeon","ns":-49.41,"ew":26.92,"cell":"A1410000","place":"outdoor","lb":"0141","desc":"Dungeon, landblock 0141. 1 entrance.","id":208}, + {"name":"Phyntos Menace","type":"Dungeon","ns":68.1,"ew":-20.04,"cell":"66D40102","place":"building","lb":"0143","desc":"Dungeon, landblock 0143. 1 entrance.","id":209}, + {"name":"Bone Lair","type":"Dungeon","ns":-29.4,"ew":6.98,"cell":"885A0101","place":"building","lb":"0145","desc":"Dungeon, landblock 0145. 1 entrance.","id":210}, + {"name":"Mount Lethe Magma Tubes","type":"Dungeon","ns":-33.89,"ew":-85.2,"cell":"14550100","place":"building","lb":"0146","desc":"Dungeon, landblock 0146. 1 entrance.","id":211,"minLevel":20}, + {"name":"Mount Naipenset Caverns","type":"Dungeon","ns":5.59,"ew":-56.19,"cell":"39860100","place":"building","lb":"0147","desc":"Dungeon, landblock 0147. 1 entrance.","id":212}, + {"name":"A Small Ruin","type":"Dungeon","ns":-53.63,"ew":70.84,"cell":"D73C0000","place":"outdoor","lb":"0148","desc":"Dungeon, landblock 0148. 1 entrance.","id":213,"minLevel":5}, + {"name":"Thieves' Galleries","type":"Dungeon","ns":-57.69,"ew":74.09,"cell":"DC370000","place":"outdoor","lb":"0149","desc":"Dungeon, landblock 0149. 1 entrance.","id":214,"minLevel":5}, + {"name":"Mysterious Cave","type":"Dungeon","ns":7.7,"ew":6.57,"cell":"87890000","place":"outdoor","lb":"014A","desc":"Dungeon, landblock 014A. 1 entrance.","id":215,"minLevel":15}, + {"name":"Winthura's Garden","type":"Dungeon","ns":-43.09,"ew":24.68,"cell":"9E490000","place":"outdoor","lb":"014B","desc":"Dungeon, landblock 014B. 1 entrance.","id":216,"minLevel":8}, + {"name":"Nevius Passage","type":"Dungeon","ns":-45.59,"ew":21.64,"cell":"9A460000","place":"outdoor","lb":"014C","desc":"Dungeon, landblock 014C. 1 entrance.","id":217,"minLevel":8}, + {"name":"Damp Caverns","type":"Dungeon","ns":-31.72,"ew":96.03,"cell":"F7570000","place":"outdoor","lb":"014D","desc":"Dungeon, landblock 014D. 1 entrance.","id":218,"minLevel":5}, + {"name":"Smugglers Hideaway","type":"Dungeon","ns":-29.52,"ew":91.38,"cell":"F15A0000","place":"outdoor","lb":"014E","desc":"Dungeon, landblock 014E. 1 entrance.","id":219}, + {"name":"Dungeon Maggreth","type":"Dungeon","ns":3.73,"ew":52.6,"cell":"C1840000","place":"outdoor","lb":"014F","desc":"Dungeon, landblock 014F. 1 entrance.","id":220}, + {"name":"Shreth Hive","type":"Dungeon","ns":-32.47,"ew":71.0,"cell":"D8560100","place":"building","lb":"0153","desc":"Dungeon, landblock 0153. 1 entrance.","id":221,"minLevel":1}, + {"name":"Stone Cathedral","type":"Dungeon","ns":-34.64,"ew":71.2,"cell":"D8540102","place":"building","lb":"0154","desc":"Dungeon, landblock 0154. 1 entrance.","id":222,"minLevel":1}, + {"name":"Musansayn's Vaults","type":"Dungeon","ns":-0.99,"ew":18.67,"cell":"967E0100","place":"building","lb":"0155","desc":"Dungeon, landblock 0155. 1 entrance.","id":223,"minLevel":40}, + {"name":"Under-Cove Crypt","type":"Dungeon","ns":-21.58,"ew":-4.1,"cell":"7A640102","place":"building","lb":"0157","desc":"Dungeon, landblock 0157. 1 entrance.","id":224}, + {"name":"Unfinished Temple","type":"Dungeon","ns":-30.08,"ew":9.1,"cell":"8A590101","place":"building","lb":"015B","desc":"Dungeon, landblock 015B. 1 entrance.","id":225,"minLevel":1}, + {"name":"Nanto Rat Lair","type":"Dungeon","ns":-54.17,"ew":79.5,"cell":"E23B0100","place":"building","lb":"015C","desc":"Dungeon, landblock 015C. 1 entrance.","id":226}, + {"name":"Mountain Cavern","type":"Dungeon","ns":63.16,"ew":5.51,"cell":"86CE0000","place":"outdoor","lb":"015D","desc":"Dungeon, landblock 015D. 2 entrances.","id":227,"minLevel":20}, + {"name":"Impious Temple","type":"Dungeon","ns":12.19,"ew":2.41,"cell":"828E0100","place":"building","lb":"015E","desc":"Dungeon, landblock 015E. 1 entrance.","id":228,"minLevel":20}, + {"name":"Dericost Ruin","type":"Dungeon","ns":74.18,"ew":-74.18,"cell":"22DC002A","place":"outdoor","lb":"015F","desc":"Dungeon, landblock 015F. 1 entrance.","id":229}, + {"name":"Empyrean Garrison","type":"Dungeon","ns":-54.3,"ew":81.83,"cell":"E53B0102","place":"building","lb":"0161","desc":"Dungeon, landblock 0161. 1 entrance.","id":230}, + {"name":"Holtburg Redoubt","type":"Dungeon","ns":40.4,"ew":34.47,"cell":"AAB10000","place":"outdoor","lb":"0163","desc":"Dungeon, landblock 0163. 1 entrance.","id":231,"minLevel":1}, + {"name":"Muggy Font","type":"Dungeon","ns":-91.5,"ew":89.39,"cell":"EF0D010F","place":"building","lb":"0175","desc":"Dungeon, landblock 0175. 1 entrance.","id":232}, + {"name":"Humid Font","type":"Dungeon","ns":-91.3,"ew":89.81,"cell":"EF0D010B","place":"building","lb":"0176","desc":"Dungeon, landblock 0176. 1 entrance.","id":233}, + {"name":"Mossy Cave","type":"Dungeon","ns":-14.16,"ew":45.98,"cell":"B86D0000","place":"outdoor","lb":"0177","desc":"Dungeon, landblock 0177. 1 entrance.","id":234,"minLevel":20}, + {"name":"Dark Mosswart Halls","type":"Dungeon","ns":-74.21,"ew":83.6,"cell":"E7220100","place":"building","lb":"0178","desc":"Dungeon, landblock 0178. 1 entrance.","id":235,"minLevel":30}, + {"name":"Banderling Hovel","type":"Dungeon","ns":-31.98,"ew":72.81,"cell":"DA570000","place":"outdoor","lb":"017A","desc":"Dungeon, landblock 017A. 1 entrance.","id":236,"minLevel":10}, + {"name":"Hidden","type":"Dungeon","ns":-24.26,"ew":46.25,"cell":"B9610000","place":"outdoor","lb":"017D","desc":"Dungeon, landblock 017D. 1 entrance.","id":237}, + {"name":"Dungeon Nye","type":"Dungeon","ns":6.2,"ew":34.42,"cell":"AA870102","place":"building","lb":"0181","desc":"Dungeon, landblock 0181. 1 entrance.","id":238}, + {"name":"Desert Mine","type":"Dungeon","ns":-4.53,"ew":26.6,"cell":"A0790102","place":"building","lb":"0182","desc":"Dungeon, landblock 0182. 1 entrance.","id":239}, + {"name":"Dungeon Binar","type":"Dungeon","ns":-6.23,"ew":20.12,"cell":"98770000","place":"outdoor","lb":"0183","desc":"Dungeon, landblock 0183. 1 entrance.","id":240}, + {"name":"Dungeon Mei","type":"Dungeon","ns":-36.92,"ew":70.28,"cell":"D7510000","place":"outdoor","lb":"0184","desc":"Dungeon, landblock 0184. 1 entrance.","id":241}, + {"name":"Daiklos Dungeon","type":"Dungeon","ns":33.73,"ew":29.23,"cell":"A3A90000","place":"outdoor","lb":"0185","desc":"Dungeon, landblock 0185. 1 entrance.","id":242}, + {"name":"Sclavus Keep","type":"Dungeon","ns":-38.89,"ew":-48.44,"cell":"424E0102","place":"building","lb":"0186","desc":"Dungeon, landblock 0186. 1 entrance.","id":243,"minLevel":15}, + {"name":"A Ruin","type":"Dungeon","ns":32.97,"ew":54.92,"cell":"C4A80000","place":"outdoor","lb":"0187","desc":"Dungeon, landblock 0187. 1 entrance.","id":244}, + {"name":"Mines of Despair","type":"Dungeon","ns":-75.48,"ew":57.26,"cell":"C7210100","place":"building","lb":"0188","desc":"Dungeon, landblock 0188. 1 entrance.","id":245,"minLevel":14}, + {"name":"Grievous Vault","type":"Dungeon","ns":-25.79,"ew":27.26,"cell":"A15F0000","place":"outdoor","lb":"0189","desc":"Dungeon, landblock 0189. 1 entrance.","id":246,"minLevel":10}, + {"name":"Crater Lair","type":"Dungeon","ns":70.53,"ew":12.69,"cell":"8FD70000","place":"outdoor","lb":"018C","desc":"Dungeon, landblock 018C. 1 entrance.","id":247,"minLevel":15}, + {"name":"Olthoi Tunnels","type":"Dungeon","ns":48.07,"ew":52.98,"cell":"C1BB0000","place":"outdoor","lb":"018D","desc":"Dungeon, landblock 018D. 1 entrance.","id":248,"minLevel":15}, + {"name":"Abayar's Laboratory","type":"Dungeon","ns":92.16,"ew":-46.3,"cell":"45F20026","place":"outdoor","lb":"018E","desc":"Dungeon, landblock 018E. 1 entrance.","id":249}, + {"name":"Carved Cave","type":"Dungeon","ns":7.41,"ew":0.63,"cell":"80880100","place":"building","lb":"018F","desc":"Dungeon, landblock 018F. 1 entrance.","id":250}, + {"name":"Old Mine","type":"Dungeon","ns":-79.18,"ew":26.99,"cell":"A11C0000","place":"outdoor","lb":"0190","desc":"Dungeon, landblock 0190. 1 entrance.","id":251}, + {"name":"Mountain Sewer","type":"Dungeon","ns":-60.86,"ew":82.0,"cell":"E533003B","place":"outdoor","lb":"0191","desc":"Dungeon, landblock 0191. 1 entrance.","id":252,"minLevel":15}, + {"name":"Knath Lair","type":"Dungeon","ns":-49.76,"ew":-56.28,"cell":"39410000","place":"outdoor","lb":"0193","desc":"Dungeon, landblock 0193. 1 entrance.","id":253}, + {"name":"Ruined Empyrean Vault","type":"Dungeon","ns":85.89,"ew":-59.0,"cell":"35EA002F","place":"outdoor","lb":"0194","desc":"Dungeon, landblock 0194. 1 entrance.","id":254,"minLevel":70}, + {"name":"Xi Ru's Chapel","type":"Dungeon","ns":-90.65,"ew":87.5,"cell":"EC0E0000","place":"outdoor","lb":"0195","desc":"Dungeon, landblock 0195. 1 entrance.","id":255}, + {"name":"Steamy Font","type":"Dungeon","ns":-91.1,"ew":89.61,"cell":"EF0D0102","place":"building","lb":"0198","desc":"Dungeon, landblock 0198. 1 entrance.","id":256}, + {"name":"Crater Caves Dungeon","type":"Dungeon","ns":66.68,"ew":12.52,"cell":"8FD20000","place":"outdoor","lb":"019A","desc":"Dungeon, landblock 019A. 1 entrance.","id":257}, + {"name":"Lightless Catacombs","type":"Dungeon","ns":-82.22,"ew":-35.25,"cell":"53180102","place":"building","lb":"019B","desc":"Dungeon, landblock 019B. 1 entrance.","id":258,"minLevel":14}, + {"name":"Simple Tower","type":"Dungeon","ns":17.39,"ew":62.54,"cell":"CD950000","place":"outdoor","lb":"019D","desc":"Dungeon, landblock 019D. 1 entrance.","id":259}, + {"name":"Drudge Hideout","type":"Dungeon","ns":41.37,"ew":33.27,"cell":"A9B30000","place":"outdoor","lb":"019E","desc":"Dungeon, landblock 019E. 1 entrance.","id":260}, + {"name":"Tumerok Post","type":"Dungeon","ns":12.19,"ew":-68.11,"cell":"2A8E0000","place":"outdoor","lb":"019F","desc":"Dungeon, landblock 019F. 1 entrance.","id":261}, + {"name":"Tumerok Dungeon","type":"Dungeon","ns":-9.6,"ew":-62.94,"cell":"30730000","place":"outdoor","lb":"01A0","desc":"Dungeon, landblock 01A0. 1 entrance.","id":262}, + {"name":"Tumerok Base","type":"Dungeon","ns":9.0,"ew":-65.68,"cell":"2D8A010A","place":"building","lb":"01A1","desc":"Dungeon, landblock 01A1. 1 entrance.","id":263}, + {"name":"Mite Tunnels","type":"Dungeon","ns":38.66,"ew":50.0,"cell":"BDAF0100","place":"building","lb":"01A4","desc":"Dungeon, landblock 01A4. 1 entrance.","id":264}, + {"name":"Inner Dungeon","type":"Dungeon","ns":43.53,"ew":-43.36,"cell":"49B50000","place":"outdoor","lb":"01A5","desc":"Dungeon, landblock 01A5. 1 entrance.","id":265}, + {"name":"Disaster Maze","type":"Dungeon","ns":-61.26,"ew":-50.94,"cell":"3F320000","place":"outdoor","lb":"01A6","desc":"Dungeon, landblock 01A6. 1 entrance.","id":266,"minLevel":20}, + {"name":"Crater Pathway","type":"Dungeon","ns":64.8,"ew":13.72,"cell":"90D00104","place":"building","lb":"01A7","desc":"Dungeon, landblock 01A7. 1 entrance.","id":267}, + {"name":"Unstable","type":"Dungeon","ns":-11.28,"ew":37.5,"cell":"AE710000","place":"outdoor","lb":"01A8","desc":"Dungeon, landblock 01A8. 2 entrances.","id":268}, + {"name":"Lair of Death","type":"Dungeon","ns":41.99,"ew":58.11,"cell":"C8B30000","place":"outdoor","lb":"01AA","desc":"Dungeon, landblock 01AA. 1 entrance.","id":269,"minLevel":15}, + {"name":"Forking Trail","type":"Dungeon","ns":-65.59,"ew":16.66,"cell":"942D0000","place":"outdoor","lb":"01AB","desc":"Dungeon, landblock 01AB. 1 entrance.","id":270}, + {"name":"Adventurer's Haven","type":"Dungeon","ns":4.4,"ew":35.52,"cell":"AB840000","place":"outdoor","lb":"01AC","desc":"Dungeon, landblock 01AC. 1 entrance.","id":271}, + {"name":"Dungeon Gallery Tower","type":"Dungeon","ns":10.71,"ew":56.8,"cell":"C68C0000","place":"outdoor","lb":"01AD","desc":"Dungeon, landblock 01AD. 1 entrance.","id":272}, + {"name":"Colier Mine","type":"Dungeon","ns":56.71,"ew":38.48,"cell":"AFC6015C","place":"building","lb":"01AE","desc":"Dungeon, landblock 01AE. 1 entrance.","id":273}, + {"name":"Lakeside Lair","type":"Dungeon","ns":18.98,"ew":48.47,"cell":"BC970000","place":"outdoor","lb":"01AF","desc":"Dungeon, landblock 01AF. 1 entrance.","id":274}, + {"name":"Seaside Lair","type":"Dungeon","ns":17.21,"ew":65.88,"cell":"D1940000","place":"outdoor","lb":"01B0","desc":"Dungeon, landblock 01B0. 1 entrance.","id":275}, + {"name":"Web Maze","type":"Dungeon","ns":-49.41,"ew":65.36,"cell":"D1410000","place":"outdoor","lb":"01B2","desc":"Dungeon, landblock 01B2. 1 entrance.","id":276}, + {"name":"Dungeon Fern","type":"Dungeon","ns":43.33,"ew":37.14,"cell":"ADB50000","place":"outdoor","lb":"01B3","desc":"Dungeon, landblock 01B3. 1 entrance.","id":277}, + {"name":"Golem Burial Ground","type":"Dungeon","ns":-50.93,"ew":67.31,"cell":"D33F0000","place":"outdoor","lb":"01B4","desc":"Dungeon, landblock 01B4. 1 entrance.","id":278,"minLevel":10}, + {"name":"Rocky Crypt","type":"Dungeon","ns":-50.86,"ew":69.27,"cell":"D63F0000","place":"outdoor","lb":"01B5","desc":"Dungeon, landblock 01B5. 1 entrance.","id":279,"minLevel":10}, + {"name":"Dungeon Muddy","type":"Dungeon","ns":-27.03,"ew":70.98,"cell":"D85D0000","place":"outdoor","lb":"01B6","desc":"Dungeon, landblock 01B6. 1 entrance.","id":280,"minLevel":5}, + {"name":"Braid Mansion Ruin","type":"Dungeon","ns":-34.26,"ew":71.97,"cell":"D9540000","place":"outdoor","lb":"01B7","desc":"Dungeon, landblock 01B7. 1 entrance.","id":281}, + {"name":"A Ruin","type":"Dungeon","ns":11.49,"ew":55.04,"cell":"C48D0000","place":"outdoor","lb":"01B8","desc":"Dungeon, landblock 01B8. 1 entrance.","id":282}, + {"name":"A Ruin","type":"Dungeon","ns":-3.26,"ew":20.5,"cell":"997B0000","place":"outdoor","lb":"01B9","desc":"Dungeon, landblock 01B9. 1 entrance.","id":283}, + {"name":"Thief Trail","type":"Dungeon","ns":-39.76,"ew":81.69,"cell":"E54D0000","place":"outdoor","lb":"01BB","desc":"Dungeon, landblock 01BB. 1 entrance.","id":284,"minLevel":7}, + {"name":"Tumerok Chamber","type":"Dungeon","ns":-81.63,"ew":-36.66,"cell":"51190100","place":"building","lb":"01BC","desc":"Dungeon, landblock 01BC. 1 entrance.","id":285}, + {"name":"Cave","type":"Dungeon","ns":-47.77,"ew":-83.68,"cell":"16430000","place":"outdoor","lb":"01BD","desc":"Dungeon, landblock 01BD. 1 entrance.","id":286}, + {"name":"Tumerok Fortress","type":"Dungeon","ns":12.3,"ew":-73.7,"cell":"238E0000","place":"outdoor","lb":"01BE","desc":"Dungeon, landblock 01BE. 1 entrance.","id":287,"minLevel":20}, + {"name":"Tumerok Outpost","type":"Dungeon","ns":23.7,"ew":-36.57,"cell":"519D0100","place":"building","lb":"01BF","desc":"Dungeon, landblock 01BF. 1 entrance.","id":288,"minLevel":15}, + {"name":"Small Complex","type":"Dungeon","ns":-39.07,"ew":-53.38,"cell":"3C4E0000","place":"outdoor","lb":"01C0","desc":"Dungeon, landblock 01C0. 1 entrance.","id":289,"minLevel":40}, + {"name":"Tumerok Mine","type":"Dungeon","ns":7.96,"ew":-61.29,"cell":"32890000","place":"outdoor","lb":"01C1","desc":"Dungeon, landblock 01C1. 1 entrance.","id":290,"minLevel":15}, + {"name":"Underground Passage","type":"Dungeon","ns":-21.0,"ew":-0.8,"cell":"7E650101","place":"building","lb":"01C2","desc":"Dungeon, landblock 01C2. 4 entrances.","id":291,"minLevel":7}, + {"name":"Trialos","type":"Dungeon","ns":-58.68,"ew":55.32,"cell":"C4360000","place":"outdoor","lb":"01C3","desc":"Dungeon, landblock 01C3. 1 entrance.","id":292}, + {"name":"Hunter's Leap","type":"Dungeon","ns":35.72,"ew":32.6,"cell":"A8AC0000","place":"outdoor","lb":"01C6","desc":"Dungeon, landblock 01C6. 1 entrance.","id":293}, + {"name":"Lugian Outpost","type":"Dungeon","ns":-80.6,"ew":18.12,"cell":"961A0000","place":"outdoor","lb":"01C7","desc":"Dungeon, landblock 01C7. 1 entrance.","id":294}, + {"name":"Lugian Post","type":"Dungeon","ns":-71.24,"ew":19.01,"cell":"97260000","place":"outdoor","lb":"01C8","desc":"Dungeon, landblock 01C8. 1 entrance.","id":295}, + {"name":"Abandoned Mine","type":"Dungeon","ns":34.9,"ew":54.51,"cell":"C3AB0000","place":"outdoor","lb":"01C9","desc":"Dungeon, landblock 01C9. 1 entrance.","id":296}, + {"name":"Hebian-to Sewers","type":"Dungeon","ns":-38.77,"ew":83.81,"cell":"E84E0000","place":"outdoor","lb":"01CA","desc":"Dungeon, landblock 01CA. 1 entrance.","id":297,"minLevel":4}, + {"name":"Penguin Cave Hatchery","type":"Dungeon","ns":94.25,"ew":-51.76,"cell":"3EF5002B","place":"outdoor","lb":"01CB","desc":"Dungeon, landblock 01CB. 1 entrance.","id":298,"minLevel":90}, + {"name":"Halls of the Helm","type":"Dungeon","ns":18.71,"ew":1.56,"cell":"81960000","place":"outdoor","lb":"01CC","desc":"Dungeon, landblock 01CC. 1 entrance.","id":299,"minLevel":10}, + {"name":"Rithwic Crypt","type":"Dungeon","ns":14.03,"ew":59.11,"cell":"C9900000","place":"outdoor","lb":"01CD","desc":"Dungeon, landblock 01CD. 1 entrance.","id":300}, + {"name":"Eastham Sewer","type":"Dungeon","ns":18.77,"ew":63.43,"cell":"CE960000","place":"outdoor","lb":"01CF","desc":"Dungeon, landblock 01CF. 1 entrance.","id":301,"minLevel":50}, + {"name":"Yanshi Tunnel","type":"Dungeon","ns":-12.13,"ew":45.53,"cell":"B8700000","place":"outdoor","lb":"01D0","desc":"Dungeon, landblock 01D0. 1 entrance.","id":302}, + {"name":"Balmy Font","type":"Dungeon","ns":-91.51,"ew":89.71,"cell":"EF0D010D","place":"building","lb":"01D1","desc":"Dungeon, landblock 01D1. 1 entrance.","id":303}, + {"name":"Mountain Keep","type":"Dungeon","ns":54.69,"ew":32.89,"cell":"A8C30000","place":"outdoor","lb":"01D2","desc":"Dungeon, landblock 01D2. 1 entrance.","id":304}, + {"name":"Top of Zabool Tower","type":"Dungeon","ns":21.14,"ew":18.47,"cell":"96990000","place":"outdoor","lb":"01D3","desc":"Dungeon, landblock 01D3. 2 entrances.","id":305}, + {"name":"Bellig Tower Base","type":"Dungeon","ns":17.52,"ew":16.08,"cell":"93950000","place":"outdoor","lb":"01D4","desc":"Dungeon, landblock 01D4. 2 entrances.","id":306}, + {"name":"Syliph Tower","type":"Dungeon","ns":12.33,"ew":11.49,"cell":"8D8E0000","place":"outdoor","lb":"01D5","desc":"Dungeon, landblock 01D5. 1 entrance.","id":307}, + {"name":"Alfreth Dungeon","type":"Dungeon","ns":20.48,"ew":13.22,"cell":"8F990000","place":"outdoor","lb":"01D6","desc":"Dungeon, landblock 01D6. 1 entrance.","id":308}, + {"name":"Sylsfear Dungeon","type":"Dungeon","ns":11.0,"ew":14.68,"cell":"918D0000","place":"outdoor","lb":"01D7","desc":"Dungeon, landblock 01D7. 1 entrance.","id":309,"minLevel":10}, + {"name":"A Drudge Nest","type":"Dungeon","ns":10.94,"ew":57.49,"cell":"C78D0000","place":"outdoor","lb":"01D8","desc":"Dungeon, landblock 01D8. 1 entrance.","id":310}, + {"name":"A Red Rat Lair","type":"Dungeon","ns":-21.06,"ew":-2.19,"cell":"7C650000","place":"outdoor","lb":"01D9","desc":"Dungeon, landblock 01D9. 1 entrance.","id":311}, + {"name":"A Ruin","type":"Dungeon","ns":-12.96,"ew":47.33,"cell":"BA6F0000","place":"outdoor","lb":"01DA","desc":"Dungeon, landblock 01DA. 1 entrance.","id":312}, + {"name":"Moss Chamber","type":"Dungeon","ns":14.12,"ew":-0.68,"cell":"7E910000","place":"outdoor","lb":"01DB","desc":"Dungeon, landblock 01DB. 1 entrance.","id":313}, + {"name":"A Drudge Nest","type":"Dungeon","ns":-40.63,"ew":83.58,"cell":"E74C0000","place":"outdoor","lb":"01DC","desc":"Dungeon, landblock 01DC. 1 entrance.","id":314}, + {"name":"A Rat Nest","type":"Dungeon","ns":40.24,"ew":32.46,"cell":"A8B10000","place":"outdoor","lb":"01DD","desc":"Dungeon, landblock 01DD. 1 entrance.","id":315}, + {"name":"A Ruin","type":"Dungeon","ns":-62.64,"ew":81.39,"cell":"E5310000","place":"outdoor","lb":"01DE","desc":"Dungeon, landblock 01DE. 1 entrance.","id":316}, + {"name":"A Mosswart Nest","type":"Dungeon","ns":-36.26,"ew":60.34,"cell":"CA520000","place":"outdoor","lb":"01DF","desc":"Dungeon, landblock 01DF. 3 entrances.","id":317}, + {"name":"Banderling Ruin","type":"Dungeon","ns":36.13,"ew":39.61,"cell":"B0AC0000","place":"outdoor","lb":"01E0","desc":"Dungeon, landblock 01E0. 1 entrance.","id":318}, + {"name":"Thieves' Den","type":"Dungeon","ns":17.76,"ew":64.96,"cell":"D0950000","place":"outdoor","lb":"01E1","desc":"Dungeon, landblock 01E1. 1 entrance.","id":319}, + {"name":"Bandit Castle Prison","type":"Dungeon","ns":66.4,"ew":49.94,"cell":"BDD20128","place":"building","lb":"01E2","desc":"Dungeon, landblock 01E2. 1 entrance.","id":320}, + {"name":"Glenden Wood Dungeon","type":"Dungeon","ns":29.94,"ew":26.37,"cell":"A0A40000","place":"outdoor","lb":"01E3","desc":"Dungeon, landblock 01E3. 1 entrance.","id":321}, + {"name":"North Glenden Prison","type":"Dungeon","ns":31.83,"ew":25.52,"cell":"9FA70000","place":"outdoor","lb":"01E4","desc":"Dungeon, landblock 01E4. 1 entrance.","id":322,"minLevel":80}, + {"name":"Green Mire Grave","type":"Dungeon","ns":-27.83,"ew":71.58,"cell":"D85C0000","place":"outdoor","lb":"01E5","desc":"Dungeon, landblock 01E5. 1 entrance.","id":323}, + {"name":"Small Icecave","type":"Dungeon","ns":67.56,"ew":50.33,"cell":"BED30000","place":"outdoor","lb":"01E6","desc":"Dungeon, landblock 01E6. 1 entrance.","id":324}, + {"name":"A Small Cave","type":"Dungeon","ns":-4.2,"ew":17.32,"cell":"957A0000","place":"outdoor","lb":"01E7","desc":"Dungeon, landblock 01E7. 1 entrance.","id":325}, + {"name":"Dungeon Manor","type":"Dungeon","ns":-1.93,"ew":19.77,"cell":"987D0000","place":"outdoor","lb":"01E8","desc":"Dungeon, landblock 01E8. 1 entrance.","id":326}, + {"name":"Underground City","type":"Dungeon","ns":21.36,"ew":53.94,"cell":"C29A0000","place":"outdoor","lb":"01E9","desc":"Dungeon, landblock 01E9. 1 entrance.","id":327}, + {"name":"Old Talisman Dungeon","type":"Dungeon","ns":-2.3,"ew":-85.61,"cell":"147C0000","place":"outdoor","lb":"01EA","desc":"Dungeon, landblock 01EA. 1 entrance.","id":328}, + {"name":"Lola's Den","type":"Dungeon","ns":91.93,"ew":-69.63,"cell":"28F2001B","place":"outdoor","lb":"01EB","desc":"Dungeon, landblock 01EB. 1 entrance.","id":329}, + {"name":"Defiled Temple Middle Wing","type":"Dungeon","ns":77.7,"ew":32.71,"cell":"A8E00103","place":"building","lb":"01EC","desc":"Dungeon, landblock 01EC. 1 entrance.","id":330,"minLevel":60}, + {"name":"Dungeon of Shadows","type":"Dungeon","ns":21.45,"ew":44.04,"cell":"B69A0000","place":"outdoor","lb":"01ED","desc":"Dungeon, landblock 01ED. 1 entrance.","id":331}, + {"name":"Arwic Mines","type":"Dungeon","ns":33.83,"ew":56.83,"cell":"C6A90000","place":"outdoor","lb":"01EF","desc":"Dungeon, landblock 01EF. 1 entrance.","id":332}, + {"name":"Cave","type":"Dungeon","ns":18.36,"ew":58.11,"cell":"C8960000","place":"outdoor","lb":"01F1","desc":"Dungeon, landblock 01F1. 2 entrances.","id":333}, + {"name":"Holtburg Dungeon","type":"Dungeon","ns":43.57,"ew":32.98,"cell":"A8B50000","place":"outdoor","lb":"01F6","desc":"Dungeon, landblock 01F6. 1 entrance.","id":334}, + {"name":"Shoushi Grotto","type":"Dungeon","ns":-34.46,"ew":72.83,"cell":"DA540000","place":"outdoor","lb":"01F7","desc":"Dungeon, landblock 01F7. 1 entrance.","id":335}, + {"name":"Mite Maze","type":"Dungeon","ns":41.1,"ew":57.24,"cell":"C6B20000","place":"outdoor","lb":"01F8","desc":"Dungeon, landblock 01F8. 1 entrance.","id":336}, + {"name":"Accursed Halls","type":"Dungeon","ns":-24.03,"ew":-57.87,"cell":"37610000","place":"outdoor","lb":"01F9","desc":"Dungeon, landblock 01F9. 1 entrance.","id":337}, + {"name":"Crypt of Ashen Tears","type":"Dungeon","ns":14.64,"ew":3.54,"cell":"83910000","place":"outdoor","lb":"01FA","desc":"Dungeon, landblock 01FA. 1 entrance.","id":338}, + {"name":"Yaraq Tunnels","type":"Dungeon","ns":-24.64,"ew":-1.42,"cell":"7D600000","place":"outdoor","lb":"01FB","desc":"Dungeon, landblock 01FB. 1 entrance.","id":339}, + {"name":"ReedShark Lair","type":"Dungeon","ns":-12.29,"ew":48.28,"cell":"BB700000","place":"outdoor","lb":"01FC","desc":"Dungeon, landblock 01FC. 1 entrance.","id":340,"minLevel":4}, + {"name":"Trothyr's Rest","type":"Dungeon","ns":10.35,"ew":54.89,"cell":"C48C0000","place":"outdoor","lb":"01FD","desc":"Dungeon, landblock 01FD. 1 entrance.","id":341}, + {"name":"Small Empyrean Vault","type":"Dungeon","ns":80.42,"ew":-74.02,"cell":"22E30040","place":"outdoor","lb":"01FE","desc":"Dungeon, landblock 01FE. 1 entrance.","id":342,"minLevel":30}, + {"name":"Vile-Smelling Refuse","type":"Dungeon","ns":-25.54,"ew":46.31,"cell":"B95F0116","place":"building","lb":"0278","desc":"Dungeon, landblock 0278. 1 entrance.","id":343,"minLevel":60}, + {"name":"Vile-Smelling Refuse","type":"Dungeon","ns":-25.6,"ew":46.19,"cell":"B95F0106","place":"building","lb":"0279","desc":"Dungeon, landblock 0279. 1 entrance.","id":344,"minLevel":60}, + {"name":"Vile-Smelling Refuse","type":"Dungeon","ns":-25.5,"ew":46.41,"cell":"B95F0112","place":"building","lb":"027A","desc":"Dungeon, landblock 027A. 1 entrance.","id":345,"minLevel":60}, + {"name":"Vile-Smelling Refuse","type":"Dungeon","ns":-25.5,"ew":46.19,"cell":"B95F010A","place":"building","lb":"027B","desc":"Dungeon, landblock 027B. 1 entrance.","id":346,"minLevel":60}, + {"name":"Ancient Empyrean Grotto","type":"Dungeon","ns":52.57,"ew":-73.05,"cell":"24C10000","place":"outdoor","lb":"027C","desc":"Dungeon, landblock 027C. 1 entrance.","id":347,"minLevel":40}, + {"name":"Lair of the Eviscerators","type":"Dungeon","ns":53.71,"ew":-76.59,"cell":"1FC20000","place":"outdoor","lb":"027D","desc":"Dungeon, landblock 027D. 1 entrance.","id":348,"minLevel":50}, + {"name":"Martinate Holding","type":"Dungeon","ns":59.57,"ew":-77.06,"cell":"1FC90000","place":"outdoor","lb":"027E","desc":"Dungeon, landblock 027E. 1 entrance.","id":349}, + {"name":"East Fork Dam Hive","type":"Dungeon","ns":48.49,"ew":-76.41,"cell":"1FBC0108","place":"building","lb":"027F","desc":"Dungeon, landblock 027F. 1 entrance.","id":350,"minLevel":50}, + {"name":"Vile-Smelling Refuse","type":"Dungeon","ns":-25.6,"ew":46.41,"cell":"B95F010E","place":"building","lb":"0280","desc":"Dungeon, landblock 0280. 1 entrance.","id":351,"minLevel":60}, + {"name":"An Olthoi Soldier Nest","type":"Dungeon","ns":45.19,"ew":-76.27,"cell":"20B70000","place":"outdoor","lb":"0282","desc":"Dungeon, landblock 0282. 1 entrance.","id":352,"minLevel":30}, + {"name":"The Dark Lair","type":"Dungeon","ns":43.8,"ew":-68.41,"cell":"29B60000","place":"outdoor","lb":"0283","desc":"Dungeon, landblock 0283. 1 entrance.","id":353}, + {"name":"Abandoned Tumerok Site","type":"Dungeon","ns":41.98,"ew":-82.17,"cell":"18B30000","place":"outdoor","lb":"0284","desc":"Dungeon, landblock 0284. 1 entrance.","id":354}, + {"name":"Wasteland Hive","type":"Dungeon","ns":50.8,"ew":-79.1,"cell":"1CBE0000","place":"outdoor","lb":"0285","desc":"Dungeon, landblock 0285. 1 entrance.","id":355,"minLevel":70}, + {"name":"Tumerok Cave","type":"Dungeon","ns":41.67,"ew":-82.48,"cell":"18B30000","place":"outdoor","lb":"0286","desc":"Dungeon, landblock 0286. 1 entrance.","id":356}, + {"name":"Aun Papileona's Shrine to Raeta","type":"Dungeon","ns":38.88,"ew":-76.29,"cell":"20B00000","place":"outdoor","lb":"0287","desc":"Dungeon, landblock 0287. 1 entrance.","id":357}, + {"name":"Tiny Hive","type":"Dungeon","ns":49.9,"ew":-72.65,"cell":"24BD002F","place":"outdoor","lb":"0289","desc":"Dungeon, landblock 0289. 1 entrance.","id":358,"minLevel":35}, + {"name":"Palenqual's Caverns","type":"Dungeon","ns":48.9,"ew":-72.54,"cell":"24BC0104","place":"building","lb":"028E","desc":"Dungeon, landblock 028E. 1 entrance.","id":359}, + {"name":"Swamp Gardens","type":"Dungeon","ns":-22.59,"ew":45.78,"cell":"B8630000","place":"outdoor","lb":"028F","desc":"Dungeon, landblock 028F. 1 entrance.","id":360}, + {"name":"Stable Rift","type":"Dungeon","ns":8.01,"ew":50.36,"cell":"BE890000","place":"outdoor","lb":"0290","desc":"Dungeon, landblock 0290. 1 entrance.","id":361,"minLevel":20}, + {"name":"Singularity Bore","type":"Dungeon","ns":-64.1,"ew":-63.83,"cell":"2F2F0000","place":"outdoor","lb":"0291","desc":"Dungeon, landblock 0291. 1 entrance.","id":362,"minLevel":50}, + {"name":"Tumerok Cavern","type":"Dungeon","ns":40.22,"ew":-84.73,"cell":"15B10000","place":"outdoor","lb":"0292","desc":"Dungeon, landblock 0292. 1 entrance.","id":363}, + {"name":"Inculcation Cells","type":"Dungeon","ns":-68.78,"ew":-62.48,"cell":"31290000","place":"outdoor","lb":"0295","desc":"Dungeon, landblock 0295. 1 entrance.","id":364,"minLevel":40}, + {"name":"Land Bridge Staging Complex","type":"Dungeon","ns":-86.05,"ew":-2.52,"cell":"7C130000","place":"outdoor","lb":"0298","desc":"Dungeon, landblock 0298. 1 entrance.","id":365,"minLevel":32}, + {"name":"Gredaline Consulate","type":"Dungeon","ns":-61.6,"ew":29.29,"cell":"A4320000","place":"outdoor","lb":"029B","desc":"Dungeon, landblock 029B. 1 entrance.","id":366,"minLevel":25}, + {"name":"Linvak Tukal Entryway","type":"Dungeon","ns":-76.69,"ew":27.98,"cell":"A21F0000","place":"outdoor","lb":"029C","desc":"Dungeon, landblock 029C. 1 entrance.","id":367}, + {"name":"Mnemosyne Collection Site","type":"Dungeon","ns":-2.54,"ew":16.39,"cell":"937C0000","place":"outdoor","lb":"029D","desc":"Dungeon, landblock 029D. 1 entrance.","id":368}, + {"name":"Aerbax Laboratory","type":"Dungeon","ns":-10.18,"ew":8.12,"cell":"89720000","place":"outdoor","lb":"029E","desc":"Dungeon, landblock 029E. 1 entrance.","id":369}, + {"name":"Sand Shallow","type":"Dungeon","ns":-11.48,"ew":0.68,"cell":"80710000","place":"outdoor","lb":"02A0","desc":"Dungeon, landblock 02A0. 1 entrance.","id":370}, + {"name":"Panopticon","type":"Dungeon","ns":-59.15,"ew":-84.02,"cell":"16350000","place":"outdoor","lb":"02A1","desc":"Dungeon, landblock 02A1. 1 entrance.","id":371,"minLevel":32}, + {"name":"South Tumerok Vanguard Outpost","type":"Dungeon","ns":-45.89,"ew":14.23,"cell":"91460000","place":"outdoor","lb":"02A4","desc":"Dungeon, landblock 02A4. 1 entrance.","id":372,"minLevel":50}, + {"name":"North Tumerok Vanguard Outpost","type":"Dungeon","ns":-7.5,"ew":-0.0,"cell":"7F760000","place":"outdoor","lb":"02A5","desc":"Dungeon, landblock 02A5. 1 entrance.","id":373,"minLevel":50}, + {"name":"Desert March","type":"Dungeon","ns":22.89,"ew":-28.84,"cell":"5B9C0000","place":"outdoor","lb":"02AA","desc":"Dungeon, landblock 02AA. 2 entrances.","id":374}, + {"name":"Empyrean Cloister","type":"Dungeon","ns":-23.47,"ew":5.8,"cell":"86620000","place":"outdoor","lb":"02AD","desc":"Dungeon, landblock 02AD. 1 entrance.","id":375,"minLevel":15}, + {"name":"Chakron Gate","type":"Dungeon","ns":-52.92,"ew":-62.67,"cell":"313D0000","place":"outdoor","lb":"02AE","desc":"Dungeon, landblock 02AE. 1 entrance.","id":376,"minLevel":36}, + {"name":"Upper Shade Stronghold","type":"Dungeon","ns":73.51,"ew":-0.25,"cell":"7FDB0000","place":"outdoor","lb":"02B1","desc":"Dungeon, landblock 02B1. 2 entrances.","id":377,"minLevel":26}, + {"name":"Moars Laboratory","type":"Dungeon","ns":-68.37,"ew":94.4,"cell":"F5290102","place":"building","lb":"02B3","desc":"Dungeon, landblock 02B3. 1 entrance.","id":378}, + {"name":"A Mosswart Hideout","type":"Dungeon","ns":-72.71,"ew":90.72,"cell":"F0240000","place":"outdoor","lb":"02B4","desc":"Dungeon, landblock 02B4. 1 entrance.","id":379}, + {"name":"Moarsmen Spawning Grounds","type":"Dungeon","ns":-69.62,"ew":96.5,"cell":"F8280101","place":"building","lb":"02B5","desc":"Dungeon, landblock 02B5. 1 entrance.","id":380}, + {"name":"Idol Spawning Grounds","type":"Dungeon","ns":-72.27,"ew":87.47,"cell":"EC250000","place":"outdoor","lb":"02B6","desc":"Dungeon, landblock 02B6. 1 entrance.","id":381}, + {"name":"Catacombs of Ithaenc","type":"Dungeon","ns":-82.42,"ew":93.4,"cell":"F4180000","place":"outdoor","lb":"02B7","desc":"Dungeon, landblock 02B7. 1 entrance.","id":382}, + {"name":"Rumuba's Hidey-Hole","type":"Dungeon","ns":-75.88,"ew":89.18,"cell":"EE200000","place":"outdoor","lb":"02B8","desc":"Dungeon, landblock 02B8. 1 entrance.","id":383}, + {"name":"Moist Hovel","type":"Dungeon","ns":73.04,"ew":-62.99,"cell":"30DA0100","place":"building","lb":"02B9","desc":"Dungeon, landblock 02B9. 1 entrance.","id":384}, + {"name":"Mosswart Nest","type":"Dungeon","ns":-77.63,"ew":87.87,"cell":"ED1E0000","place":"outdoor","lb":"02BC","desc":"Dungeon, landblock 02BC. 1 entrance.","id":385}, + {"name":"Small Ruin","type":"Dungeon","ns":-70.11,"ew":91.1,"cell":"F1270100","place":"building","lb":"02BD","desc":"Dungeon, landblock 02BD. 1 entrance.","id":386}, + {"name":"Mud Cave","type":"Dungeon","ns":-73.05,"ew":81.35,"cell":"E5240100","place":"building","lb":"02C1","desc":"Dungeon, landblock 02C1. 1 entrance.","id":387}, + {"name":"Moarsmen Muck","type":"Dungeon","ns":-77.03,"ew":90.95,"cell":"F11F0100","place":"building","lb":"02C2","desc":"Dungeon, landblock 02C2. 1 entrance.","id":388}, + {"name":"Slithis Pit","type":"Dungeon","ns":-70.18,"ew":94.33,"cell":"F5270000","place":"outdoor","lb":"02C3","desc":"Dungeon, landblock 02C3. 1 entrance.","id":389}, + {"name":"Moarsmen Hideout","type":"Dungeon","ns":-69.95,"ew":89.93,"cell":"EF280100","place":"building","lb":"02C4","desc":"Dungeon, landblock 02C4. 1 entrance.","id":390}, + {"name":"Treacherous Tunnels","type":"Dungeon","ns":-75.03,"ew":90.29,"cell":"F0210100","place":"building","lb":"02C5","desc":"Dungeon, landblock 02C5. 1 entrance.","id":391}, + {"name":"Tumideon Fortress","type":"Dungeon","ns":-55.88,"ew":-60.72,"cell":"33390000","place":"outdoor","lb":"02C7","desc":"Dungeon, landblock 02C7. 1 entrance.","id":392,"minLevel":30}, + {"name":"Banderling Conquest Dungeon","type":"Dungeon","ns":-29.03,"ew":50.47,"cell":"BE5B0000","place":"outdoor","lb":"02C8","desc":"Dungeon, landblock 02C8. 1 entrance.","id":393}, + {"name":"Sotiris","type":"Dungeon","ns":-67.98,"ew":-69.24,"cell":"282A0000","place":"outdoor","lb":"02C9","desc":"Dungeon, landblock 02C9. 1 entrance.","id":394,"minLevel":30}, + {"name":"Mosswart Maze","type":"Dungeon","ns":-25.23,"ew":19.38,"cell":"975F0000","place":"outdoor","lb":"02CA","desc":"Dungeon, landblock 02CA. 1 entrance.","id":395}, + {"name":"Abhorrent Vault","type":"Dungeon","ns":88.5,"ew":-50.28,"cell":"40EE0021","place":"outdoor","lb":"02D4","desc":"Dungeon, landblock 02D4. 1 entrance.","id":396,"minLevel":90}, + {"name":"Waterfall Cave","type":"Dungeon","ns":84.0,"ew":-75.41,"cell":"21E8000C","place":"outdoor","lb":"02D5","desc":"Dungeon, landblock 02D5. 1 entrance.","id":397}, + {"name":"Hidden City","type":"Dungeon","ns":94.4,"ew":-70.0,"cell":"27F5003C","place":"outdoor","lb":"02D6","desc":"Dungeon, landblock 02D6. 1 entrance.","id":398,"minLevel":50}, + {"name":"Fenmalain Vestibule","type":"Dungeon","ns":-46.91,"ew":55.24,"cell":"C4440000","place":"outdoor","lb":"02DB","desc":"Dungeon, landblock 02DB. 1 entrance.","id":399,"minLevel":20}, + {"name":"Caulnalain Vestibule","type":"Dungeon","ns":68.54,"ew":5.49,"cell":"86D50000","place":"outdoor","lb":"02DC","desc":"Dungeon, landblock 02DC. 1 entrance.","id":400,"minLevel":40}, + {"name":"Penguin Den","type":"Dungeon","ns":71.7,"ew":-60.38,"cell":"33D90039","place":"outdoor","lb":"02DD","desc":"Dungeon, landblock 02DD. 1 entrance.","id":401}, + {"name":"Ruschk Iceberg","type":"Dungeon","ns":96.33,"ew":-59.99,"cell":"34F7001F","place":"outdoor","lb":"02DE","desc":"Dungeon, landblock 02DE. 1 entrance.","id":402,"minLevel":70}, + {"name":"Shendolain Vestibule","type":"Dungeon","ns":-53.79,"ew":-59.59,"cell":"343C0000","place":"outdoor","lb":"02E0","desc":"Dungeon, landblock 02E0. 2 entrances.","id":403,"minLevel":60}, + {"name":"Arena","type":"Dungeon","ns":-18.51,"ew":3.68,"cell":"84680000","place":"outdoor","lb":"02E2","desc":"Dungeon, landblock 02E2. 1 entrance.","id":404}, + {"name":"Arena","type":"Dungeon","ns":-17.91,"ew":3.88,"cell":"84690000","place":"outdoor","lb":"02E3","desc":"Dungeon, landblock 02E3. 1 entrance.","id":405}, + {"name":"Krau Li's Labyrinth","type":"Dungeon","ns":-35.15,"ew":23.77,"cell":"9D530000","place":"outdoor","lb":"02E5","desc":"Dungeon, landblock 02E5. 1 entrance.","id":406,"minLevel":25}, + {"name":"Catacombs of the Forgotten","type":"Dungeon","ns":17.31,"ew":32.8,"cell":"A8950000","place":"outdoor","lb":"02E6","desc":"Dungeon, landblock 02E6. 1 entrance.","id":407,"minLevel":15}, + {"name":"Lugian Excavations","type":"Dungeon","ns":-77.02,"ew":64.32,"cell":"CF1F0000","place":"outdoor","lb":"02E7","desc":"Dungeon, landblock 02E7. 1 entrance.","id":408}, + {"name":"Lugian Quarry","type":"Dungeon","ns":-64.38,"ew":55.48,"cell":"C42E0000","place":"outdoor","lb":"02E8","desc":"Dungeon, landblock 02E8. 1 entrance.","id":409}, + {"name":"Lugian Mines","type":"Dungeon","ns":-73.87,"ew":38.98,"cell":"B0230000","place":"outdoor","lb":"02E9","desc":"Dungeon, landblock 02E9. 1 entrance.","id":410}, + {"name":"Ishaq's Cellar","type":"Dungeon","ns":-66.12,"ew":-86.57,"cell":"132C0000","place":"outdoor","lb":"02EA","desc":"Dungeon, landblock 02EA. 1 entrance.","id":411,"minLevel":80}, + {"name":"Viamontian Torture Chamber","type":"Dungeon","ns":69.66,"ew":-62.57,"cell":"31D6000D","place":"outdoor","lb":"02EB","desc":"Dungeon, landblock 02EB. 1 entrance.","id":412}, + {"name":"Coral Tunnels","type":"Dungeon","ns":84.2,"ew":46.02,"cell":"B8E80103","place":"building","lb":"02EC","desc":"Dungeon, landblock 02EC. 1 entrance.","id":413,"minLevel":40}, + {"name":"Aerlinthe Reservoir","type":"Dungeon","ns":85.53,"ew":43.4,"cell":"B5EA0102","place":"building","lb":"02EE","desc":"Dungeon, landblock 02EE. 1 entrance.","id":414,"minLevel":40}, + {"name":"Hills Citadel","type":"Dungeon","ns":-56.57,"ew":66.91,"cell":"D3380000","place":"outdoor","lb":"02F0","desc":"Dungeon, landblock 02F0. 1 entrance.","id":415}, + {"name":"Ridge Citadel","type":"Dungeon","ns":-70.19,"ew":24.23,"cell":"9D270000","place":"outdoor","lb":"02F1","desc":"Dungeon, landblock 02F1. 1 entrance.","id":416}, + {"name":"Wilderness Citadel","type":"Dungeon","ns":-67.87,"ew":62.56,"cell":"CD2A0000","place":"outdoor","lb":"02F2","desc":"Dungeon, landblock 02F2. 1 entrance.","id":417}, + {"name":"Halls of Metos","type":"Dungeon","ns":-4.41,"ew":-0.61,"cell":"7E790000","place":"outdoor","lb":"02F3","desc":"Dungeon, landblock 02F3. 1 entrance.","id":418,"minLevel":15}, + {"name":"Halls of Metos","type":"Dungeon","ns":-55.94,"ew":-89.22,"cell":"0F390000","place":"outdoor","lb":"02F4","desc":"Dungeon, landblock 02F4. 2 entrances.","id":419,"minLevel":15}, + {"name":"Halls of Metos","type":"Dungeon","ns":-61.32,"ew":-46.68,"cell":"45320000","place":"outdoor","lb":"02F5","desc":"Dungeon, landblock 02F5. 1 entrance.","id":420,"minLevel":15}, + {"name":"Sclavus Cathedral","type":"Dungeon","ns":-33.44,"ew":-80.12,"cell":"1B550000","place":"outdoor","lb":"02F6","desc":"Dungeon, landblock 02F6. 1 entrance.","id":421}, + {"name":"Sclavus Cathedral","type":"Dungeon","ns":-17.9,"ew":-89.44,"cell":"0F690000","place":"outdoor","lb":"02F7","desc":"Dungeon, landblock 02F7. 1 entrance.","id":422}, + {"name":"Burun Cathedral","type":"Dungeon","ns":-42.31,"ew":-52.6,"cell":"3D4A0000","place":"outdoor","lb":"02F8","desc":"Dungeon, landblock 02F8. 1 entrance.","id":423}, + {"name":"Olthoi Horde Nest","type":"Dungeon","ns":55.78,"ew":43.48,"cell":"B5C50000","place":"outdoor","lb":"02FB","desc":"Dungeon, landblock 02FB. 1 entrance.","id":424,"minLevel":20}, + {"name":"Olthoi Horde Nest","type":"Dungeon","ns":48.9,"ew":-12.94,"cell":"6FBC0000","place":"outdoor","lb":"02FC","desc":"Dungeon, landblock 02FC. 1 entrance.","id":425,"minLevel":30}, + {"name":"Olthoi Horde Nest","type":"Dungeon","ns":64.34,"ew":52.77,"cell":"C1CF0000","place":"outdoor","lb":"02FD","desc":"Dungeon, landblock 02FD. 1 entrance.","id":426,"minLevel":30}, + {"name":"Frozen Library","type":"Dungeon","ns":90.72,"ew":-56.38,"cell":"38F0003F","place":"outdoor","lb":"02FE","desc":"Dungeon, landblock 02FE. 1 entrance.","id":427}, + {"name":"Steaming Hovel","type":"Dungeon","ns":73.14,"ew":-65.6,"cell":"2DDA0100","place":"building","lb":"039B","desc":"Dungeon, landblock 039B. 1 entrance.","id":428}, + {"name":"Hollow Lair near Lytelthorpe","type":"Dungeon","ns":-2.2,"ew":50.75,"cell":"BE7C0000","place":"outdoor","lb":"039C","desc":"Dungeon, landblock 039C. 1 entrance.","id":429,"minLevel":20}, + {"name":"Ravenous Vault","type":"Dungeon","ns":92.83,"ew":-48.92,"cell":"42F30014","place":"outdoor","lb":"039D","desc":"Dungeon, landblock 039D. 1 entrance.","id":430,"minLevel":110}, + {"name":"Singular Obsidian Repository","type":"Dungeon","ns":-55.93,"ew":-64.79,"cell":"2E390000","place":"outdoor","lb":"039F","desc":"Dungeon, landblock 039F. 1 entrance.","id":431,"minLevel":45}, + {"name":"Singular Chorizite Repository","type":"Dungeon","ns":-77.32,"ew":51.6,"cell":"BF1E0000","place":"outdoor","lb":"03A0","desc":"Dungeon, landblock 03A0. 1 entrance.","id":432,"minLevel":35}, + {"name":"Singular Pyreal Repository","type":"Dungeon","ns":-4.2,"ew":8.92,"cell":"8A7A0000","place":"outdoor","lb":"03A1","desc":"Dungeon, landblock 03A1. 1 entrance.","id":433,"minLevel":24}, + {"name":"Southern Infiltrator Keep","type":"Dungeon","ns":-52.28,"ew":24.91,"cell":"9E3E0000","place":"outdoor","lb":"03A2","desc":"Dungeon, landblock 03A2. 1 entrance.","id":434,"minLevel":25}, + {"name":"Northern Infiltrator Keep","type":"Dungeon","ns":15.41,"ew":4.96,"cell":"85920000","place":"outdoor","lb":"03A3","desc":"Dungeon, landblock 03A3. 1 entrance.","id":435,"minLevel":25}, + {"name":"The Asteliary","type":"Dungeon","ns":-10.21,"ew":17.5,"cell":"95720000","place":"outdoor","lb":"03A4","desc":"Dungeon, landblock 03A4. 1 entrance.","id":436,"minLevel":35}, + {"name":"Undead Temple","type":"Dungeon","ns":90.89,"ew":-43.19,"cell":"49F10019","place":"outdoor","lb":"03A5","desc":"Dungeon, landblock 03A5. 1 entrance.","id":437}, + {"name":"North Fork Dam Hive","type":"Dungeon","ns":51.42,"ew":-76.0,"cell":"20BF0125","place":"building","lb":"03A6","desc":"Dungeon, landblock 03A6. 1 entrance.","id":438,"minLevel":70}, + {"name":"Mount Elyrii Hive","type":"Dungeon","ns":48.5,"ew":-81.68,"cell":"19BC0000","place":"outdoor","lb":"03A7","desc":"Dungeon, landblock 03A7. 1 entrance.","id":439,"minLevel":70}, + {"name":"Apostate Citadel Mines","type":"Dungeon","ns":-48.68,"ew":-68.91,"cell":"29420015","place":"outdoor","lb":"2842","desc":"Dungeon, landblock 2842. 1 entrance.","id":440,"minLevel":150}, + {"name":"Massilor's Crypt","type":"Dungeon","ns":-65.38,"ew":-43.6,"cell":"482D003E","place":"outdoor","lb":"472D","desc":"Dungeon, landblock 472D. 1 entrance.","id":441,"minLevel":180}, + {"name":"Wedding Trials Dungeon","type":"Dungeon","ns":32.8,"ew":55.23,"cell":"C4A80000","place":"outdoor","lb":"5269","desc":"Dungeon, landblock 5269. 1 entrance.","id":442}, + {"name":"Entrance to Portal Space","type":"Dungeon","ns":82.77,"ew":21.17,"cell":"99E60000","place":"outdoor","lb":"526C","desc":"Dungeon, landblock 526C. 1 entrance.","id":443,"minLevel":70}, + {"name":"Empyrean Acid Propylaeum","type":"Dungeon","ns":-31.63,"ew":-74.21,"cell":"22570000","place":"outdoor","lb":"526E","desc":"Dungeon, landblock 526E. 1 entrance.","id":444,"minLevel":50}, + {"name":"Empyrean Fire Propylaeum","type":"Dungeon","ns":73.46,"ew":-2.67,"cell":"7CDB0000","place":"outdoor","lb":"5270","desc":"Dungeon, landblock 5270. 1 entrance.","id":445,"minLevel":25}, + {"name":"Empyrean Ice Propylaeum","type":"Dungeon","ns":53.28,"ew":62.48,"cell":"CDC20000","place":"outdoor","lb":"5272","desc":"Dungeon, landblock 5272. 1 entrance.","id":446,"minLevel":25}, + {"name":"Empyrean Lightning Propylaeum","type":"Dungeon","ns":-87.09,"ew":9.51,"cell":"8B120000","place":"outdoor","lb":"5274","desc":"Dungeon, landblock 5274. 1 entrance.","id":447,"minLevel":50}, + {"name":"Convergent Median","type":"Dungeon","ns":-87.04,"ew":-40.26,"cell":"4D120000","place":"outdoor","lb":"536B","desc":"Dungeon, landblock 536B. 1 entrance.","id":448,"minLevel":40}, + {"name":"Malignant Tabernacle","type":"Dungeon","ns":-23.21,"ew":-46.0,"cell":"45620000","place":"outdoor","lb":"536C","desc":"Dungeon, landblock 536C. 1 entrance.","id":449,"minLevel":40}, + {"name":"Venemous Nidus","type":"Dungeon","ns":-13.14,"ew":-91.78,"cell":"0C6F0000","place":"outdoor","lb":"536E","desc":"Dungeon, landblock 536E. 1 entrance.","id":450,"minLevel":40}, + {"name":"Grievver Caves","type":"Dungeon","ns":75.93,"ew":-19.04,"cell":"67DE0103","place":"building","lb":"5456","desc":"Dungeon, landblock 5456. 1 entrance.","id":451}, + {"name":"Colossus Foundry","type":"Dungeon","ns":-59.99,"ew":-87.92,"cell":"11340149","place":"building","lb":"5457","desc":"Dungeon, landblock 5457. 4 entrances.","id":452}, + {"name":"Mammet Foundry","type":"Dungeon","ns":44.25,"ew":-43.38,"cell":"49B6012C","place":"building","lb":"5458","desc":"Dungeon, landblock 5458. 9 entrances.","id":453}, + {"name":"Effigy Foundry","type":"Dungeon","ns":13.78,"ew":0.57,"cell":"80900138","place":"building","lb":"5459","desc":"Dungeon, landblock 5459. 10 entrances.","id":454}, + {"name":"Mannikin Foundry","type":"Dungeon","ns":-21.54,"ew":-1.7,"cell":"7D640150","place":"building","lb":"545A","desc":"Dungeon, landblock 545A. 8 entrances.","id":455}, + {"name":"Arcanum Research Facility","type":"Dungeon","ns":5.85,"ew":6.32,"cell":"87860000","place":"outdoor","lb":"545B","desc":"Dungeon, landblock 545B. 1 entrance.","id":456,"minLevel":20}, + {"name":"Fathomless Chasm","type":"Dungeon","ns":-36.92,"ew":63.36,"cell":"CE510000","place":"outdoor","lb":"545E","desc":"Dungeon, landblock 545E. 1 entrance.","id":457,"minLevel":20}, + {"name":"Sanctum Residential Halls","type":"Dungeon","ns":13.39,"ew":0.58,"cell":"80900000","place":"outdoor","lb":"5465","desc":"Dungeon, landblock 5465. 3 entrances.","id":458}, + {"name":"Gromnie Clan Training Camp","type":"Dungeon","ns":-16.01,"ew":70.02,"cell":"D66B0000","place":"outdoor","lb":"5643","desc":"Dungeon, landblock 5643. 1 entrance.","id":459}, + {"name":"Mask Clan Training Camp","type":"Dungeon","ns":-16.0,"ew":74.99,"cell":"DD6B0000","place":"outdoor","lb":"5644","desc":"Dungeon, landblock 5644. 1 entrance.","id":460}, + {"name":"Abandoned Armory","type":"Dungeon","ns":-83.58,"ew":-14.86,"cell":"6C160000","place":"outdoor","lb":"5645","desc":"Dungeon, landblock 5645. 1 entrance.","id":461}, + {"name":"An Archive","type":"Dungeon","ns":-63.48,"ew":36.83,"cell":"AD300000","place":"outdoor","lb":"5646","desc":"Dungeon, landblock 5646. 1 entrance.","id":462,"minLevel":115}, + {"name":"Tower Base Dungeon","type":"Dungeon","ns":-34.73,"ew":33.6,"cell":"A9540000","place":"outdoor","lb":"5647","desc":"Dungeon, landblock 5647. 1 entrance.","id":463,"minLevel":115}, + {"name":"Dark Tree Crystal Mine","type":"Dungeon","ns":24.79,"ew":-31.27,"cell":"589E0000","place":"outdoor","lb":"5649","desc":"Dungeon, landblock 5649. 1 entrance.","id":464,"minLevel":100}, + {"name":"Spirit Cell","type":"Dungeon","ns":26.49,"ew":-28.52,"cell":"5BA00000","place":"outdoor","lb":"564A","desc":"Dungeon, landblock 564A. 1 entrance.","id":465}, + {"name":"Crystal Mine Extreme","type":"Dungeon","ns":70.44,"ew":-8.1,"cell":"75D70000","place":"outdoor","lb":"564B","desc":"Dungeon, landblock 564B. 1 entrance.","id":466,"minLevel":80}, + {"name":"Crystal Mine High","type":"Dungeon","ns":70.47,"ew":-7.91,"cell":"75D70000","place":"outdoor","lb":"564C","desc":"Dungeon, landblock 564C. 1 entrance.","id":467,"minLevel":60}, + {"name":"Crystal Mine Mid","type":"Dungeon","ns":70.6,"ew":-8.07,"cell":"75D70000","place":"outdoor","lb":"564D","desc":"Dungeon, landblock 564D. 1 entrance.","id":468,"minLevel":40}, + {"name":"Crystal Mine Low","type":"Dungeon","ns":70.54,"ew":-8.2,"cell":"75D70000","place":"outdoor","lb":"564E","desc":"Dungeon, landblock 564E. 1 entrance.","id":469,"minLevel":20}, + {"name":"Crystal Mine New Isparians","type":"Dungeon","ns":70.52,"ew":-7.98,"cell":"75D70000","place":"outdoor","lb":"564F","desc":"Dungeon, landblock 564F. 1 entrance.","id":470,"minLevel":1}, + {"name":"Victory Residential Halls","type":"Dungeon","ns":-3.21,"ew":19.08,"cell":"977B0000","place":"outdoor","lb":"5650","desc":"Dungeon, landblock 5650. 3 entrances.","id":471}, + {"name":"Citadel Library","type":"Dungeon","ns":17.21,"ew":63.0,"cell":"CE940102","place":"building","lb":"5653","desc":"Dungeon, landblock 5653. 1 entrance.","id":472,"minLevel":20}, + {"name":"Virindi Research Facility","type":"Dungeon","ns":43.26,"ew":-43.75,"cell":"48B5002D","place":"outdoor","lb":"5655","desc":"Dungeon, landblock 5655. 1 entrance.","id":473,"minLevel":150}, + {"name":"Haven Residential Halls","type":"Dungeon","ns":-24.93,"ew":28.33,"cell":"A2600000","place":"outdoor","lb":"5656","desc":"Dungeon, landblock 5656. 3 entrances.","id":474}, + {"name":"Oriel Residential Halls","type":"Dungeon","ns":44.01,"ew":-43.11,"cell":"49B60000","place":"outdoor","lb":"565E","desc":"Dungeon, landblock 565E. 3 entrances.","id":475}, + {"name":"Martine's Retreat","type":"Dungeon","ns":10.62,"ew":58.27,"cell":"C88C0000","place":"outdoor","lb":"5660","desc":"Dungeon, landblock 5660. 1 entrance.","id":476}, + {"name":"Atrium Residential Halls","type":"Dungeon","ns":-74.08,"ew":19.16,"cell":"97220000","place":"outdoor","lb":"5661","desc":"Dungeon, landblock 5661. 3 entrances.","id":477}, + {"name":"Frost Guardian Lair","type":"Dungeon","ns":52.75,"ew":62.36,"cell":"CDC10000","place":"outdoor","lb":"5743","desc":"Dungeon, landblock 5743. 1 entrance.","id":478,"minLevel":20}, + {"name":"Proving Grounds Low","type":"Dungeon","ns":17.16,"ew":63.02,"cell":"CE940102","place":"building","lb":"5744","desc":"Dungeon, landblock 5744. 1 entrance.","id":479,"minLevel":20}, + {"name":"Lightning Ziggurat","type":"Dungeon","ns":57.08,"ew":47.7,"cell":"BBC60007","place":"outdoor","lb":"5746","desc":"Dungeon, landblock 5746. 2 entrances.","id":480,"minLevel":20}, + {"name":"Tusker Burrow","type":"Dungeon","ns":2.03,"ew":97.98,"cell":"F9810000","place":"outdoor","lb":"5748","desc":"Dungeon, landblock 5748. 1 entrance.","id":481}, + {"name":"Tusker Lodge","type":"Dungeon","ns":0.15,"ew":98.08,"cell":"FA7F0000","place":"outdoor","lb":"5749","desc":"Dungeon, landblock 5749. 1 entrance.","id":482,"minLevel":5}, + {"name":"Temple","type":"Dungeon","ns":-20.62,"ew":7.93,"cell":"89650016","place":"outdoor","lb":"5756","desc":"Dungeon, landblock 5756. 1 entrance.","id":483}, + {"name":"Sand Caves","type":"Dungeon","ns":-21.46,"ew":6.43,"cell":"8764001D","place":"outdoor","lb":"5760","desc":"Dungeon, landblock 5760. 3 entrances.","id":484}, + {"name":"Lost Ruins","type":"Dungeon","ns":-82.56,"ew":94.83,"cell":"F518003A","place":"outdoor","lb":"5765","desc":"Dungeon, landblock 5765. 1 entrance.","id":485,"minLevel":150}, + {"name":"Nanjou Shou-jen Academy","type":"Dungeon","ns":78.08,"ew":-42.2,"cell":"4AE10118","place":"building","lb":"5766","desc":"Dungeon, landblock 5766. 1 entrance.","id":486,"minLevel":200}, + {"name":"Firey Refuge","type":"Dungeon","ns":-95.33,"ew":-94.17,"cell":"0908002B","place":"outdoor","lb":"5769","desc":"Dungeon, landblock 5769. 1 entrance.","id":487,"minLevel":150}, + {"name":"Charged Refuge","type":"Dungeon","ns":-86.82,"ew":10.54,"cell":"8C120028","place":"outdoor","lb":"576A","desc":"Dungeon, landblock 576A. 1 entrance.","id":488,"minLevel":150}, + {"name":"Acidic Refuge","type":"Dungeon","ns":59.05,"ew":65.76,"cell":"D1C9002B","place":"outdoor","lb":"576C","desc":"Dungeon, landblock 576C. 1 entrance.","id":489,"minLevel":150}, + {"name":"Cavernous Refuge","type":"Dungeon","ns":-7.3,"ew":13.4,"cell":"9076000B","place":"outdoor","lb":"576D","desc":"Dungeon, landblock 576D. 1 entrance.","id":490,"minLevel":150}, + {"name":"Shadowy Refuge","type":"Dungeon","ns":-26.77,"ew":96.01,"cell":"F75D0020","place":"outdoor","lb":"576E","desc":"Dungeon, landblock 576E. 1 entrance.","id":491,"minLevel":150}, + {"name":"Twisted Refuge","type":"Dungeon","ns":-62.77,"ew":-64.8,"cell":"2E300020","place":"outdoor","lb":"576F","desc":"Dungeon, landblock 576F. 1 entrance.","id":492,"minLevel":150}, + {"name":"Frozen Refuge","type":"Dungeon","ns":93.94,"ew":-45.44,"cell":"46F4002F","place":"outdoor","lb":"5770","desc":"Dungeon, landblock 5770. 1 entrance.","id":493,"minLevel":150}, + {"name":"Venerable Mausoleum","type":"Dungeon","ns":78.88,"ew":-41.68,"cell":"4BE20011","place":"outdoor","lb":"5771","desc":"Dungeon, landblock 5771. 1 entrance.","id":494,"minLevel":200}, + {"name":"Olthoi Brood Hive","type":"Dungeon","ns":44.22,"ew":66.18,"cell":"D2B60000","place":"outdoor","lb":"5772","desc":"Dungeon, landblock 5772. 1 entrance.","id":495,"minLevel":20}, + {"name":"Olthoi Brood Hive","type":"Dungeon","ns":51.22,"ew":48.09,"cell":"BBBF0000","place":"outdoor","lb":"5773","desc":"Dungeon, landblock 5773. 1 entrance.","id":496,"minLevel":20}, + {"name":"Secret Putiputi Place","type":"Dungeon","ns":46.25,"ew":-82.05,"cell":"18B90000","place":"outdoor","lb":"5774","desc":"Dungeon, landblock 5774. 1 entrance.","id":497}, + {"name":"Falcon Clan Training Camp","type":"Dungeon","ns":2.01,"ew":74.97,"cell":"DD810000","place":"outdoor","lb":"5777","desc":"Dungeon, landblock 5777. 1 entrance.","id":498}, + {"name":"Serpent Clan Training Camp","type":"Dungeon","ns":-1.02,"ew":70.01,"cell":"D67E0000","place":"outdoor","lb":"5778","desc":"Dungeon, landblock 5778. 1 entrance.","id":499}, + {"name":"Shreth Clan Training Camp","type":"Dungeon","ns":-5.03,"ew":67.97,"cell":"D4790000","place":"outdoor","lb":"5779","desc":"Dungeon, landblock 5779. 1 entrance.","id":500}, + {"name":"Reedshark Clan Training Camp","type":"Dungeon","ns":-13.03,"ew":67.97,"cell":"D46F0000","place":"outdoor","lb":"577A","desc":"Dungeon, landblock 577A. 1 entrance.","id":501}, + {"name":"Fire Guardian Lair","type":"Dungeon","ns":73.51,"ew":-3.15,"cell":"7BDB0000","place":"outdoor","lb":"5843","desc":"Dungeon, landblock 5843. 1 entrance.","id":502,"minLevel":40}, + {"name":"Proving Grounds Mid","type":"Dungeon","ns":17.2,"ew":63.02,"cell":"CE940102","place":"building","lb":"5844","desc":"Dungeon, landblock 5844. 1 entrance.","id":503,"minLevel":40}, + {"name":"Acid Ziggurat","type":"Dungeon","ns":57.08,"ew":47.73,"cell":"BBC60007","place":"outdoor","lb":"5846","desc":"Dungeon, landblock 5846. 2 entrances.","id":504,"minLevel":40}, + {"name":"Tusker Freehold","type":"Dungeon","ns":-1.58,"ew":95.54,"cell":"F67D0000","place":"outdoor","lb":"5848","desc":"Dungeon, landblock 5848. 1 entrance.","id":505,"minLevel":25}, + {"name":"Tusker Assault","type":"Dungeon","ns":-3.89,"ew":84.26,"cell":"E87A0000","place":"outdoor","lb":"5849","desc":"Dungeon, landblock 5849. 1 entrance.","id":506,"minLevel":85}, + {"name":"Olthoi Brood Hive","type":"Dungeon","ns":64.53,"ew":56.2,"cell":"C5D00000","place":"outdoor","lb":"584B","desc":"Dungeon, landblock 584B. 1 entrance.","id":507,"minLevel":80}, + {"name":"Olthoi Brood Hive","type":"Dungeon","ns":57.44,"ew":67.44,"cell":"D3C70000","place":"outdoor","lb":"584C","desc":"Dungeon, landblock 584C. 1 entrance.","id":508,"minLevel":80}, + {"name":"Frigid Grotto","type":"Dungeon","ns":97.09,"ew":-51.78,"cell":"3EF8002F","place":"outdoor","lb":"584D","desc":"Dungeon, landblock 584D. 1 entrance.","id":509,"minLevel":150}, + {"name":"Serpent Burial Grounds","type":"Dungeon","ns":67.58,"ew":-25.37,"cell":"5FD30030","place":"outdoor","lb":"584E","desc":"Dungeon, landblock 584E. 1 entrance.","id":510,"minLevel":150}, + {"name":"Prismatic Guardian Lair","type":"Dungeon","ns":10.9,"ew":-81.18,"cell":"198D0039","place":"outdoor","lb":"5850","desc":"Dungeon, landblock 5850. 1 entrance.","id":511,"minLevel":150}, + {"name":"Prismatic Ziggurat","type":"Dungeon","ns":57.08,"ew":47.82,"cell":"BBC6000F","place":"outdoor","lb":"5851","desc":"Dungeon, landblock 5851. 2 entrances.","id":512,"minLevel":150}, + {"name":"Proving Grounds Uber","type":"Dungeon","ns":17.18,"ew":63.02,"cell":"CE940102","place":"building","lb":"5852","desc":"Dungeon, landblock 5852. 1 entrance.","id":513,"minLevel":150}, + {"name":"Foundry of Izexi","type":"Dungeon","ns":-19.4,"ew":6.71,"cell":"87670032","place":"outdoor","lb":"5856","desc":"Dungeon, landblock 5856. 1 entrance.","id":514,"minLevel":200}, + {"name":"Falatacot Depot","type":"Dungeon","ns":-75.39,"ew":29.31,"cell":"A4210002","place":"outdoor","lb":"585E","desc":"Dungeon, landblock 585E. 1 entrance.","id":515,"minLevel":150}, + {"name":"Colton Reeyan's Sanctuary","type":"Dungeon","ns":22.93,"ew":-37.04,"cell":"519C0009","place":"outdoor","lb":"5860","desc":"Dungeon, landblock 5860. 1 entrance.","id":516,"minLevel":150}, + {"name":"Crystal Core","type":"Dungeon","ns":-66.62,"ew":25.83,"cell":"9F2C002A","place":"outdoor","lb":"5861","desc":"Dungeon, landblock 5861. 1 entrance.","id":517,"minLevel":50}, + {"name":"Count Phainor's Tomb","type":"Dungeon","ns":-65.0,"ew":-44.02,"cell":"482E0131","place":"building","lb":"5862","desc":"Dungeon, landblock 5862. 1 entrance.","id":518,"minLevel":180}, + {"name":"Desert Dwelling","type":"Dungeon","ns":-20.98,"ew":7.63,"cell":"8865003A","place":"outdoor","lb":"5863","desc":"Dungeon, landblock 5863. 1 entrance.","id":519,"minLevel":180}, + {"name":"Samurai Hausu","type":"Dungeon","ns":79.62,"ew":-40.8,"cell":"4CE20102","place":"building","lb":"5864","desc":"Dungeon, landblock 5864. 1 entrance.","id":520,"minLevel":200}, + {"name":"Stinging Corner","type":"Dungeon","ns":-79.07,"ew":90.03,"cell":"EF1C003D","place":"outdoor","lb":"5865","desc":"Dungeon, landblock 5865. 2 entrances.","id":521,"minLevel":180}, + {"name":"Sanctuary of the Recluse","type":"Dungeon","ns":-20.83,"ew":7.48,"cell":"88650034","place":"outdoor","lb":"5866","desc":"Dungeon, landblock 5866. 1 entrance.","id":522,"minLevel":180}, + {"name":"Virindi Edifice","type":"Dungeon","ns":-19.34,"ew":18.18,"cell":"9667000B","place":"outdoor","lb":"5867","desc":"Dungeon, landblock 5867. 1 entrance.","id":523,"minLevel":180}, + {"name":"Chiming","type":"Dungeon","ns":44.96,"ew":-73.51,"cell":"23B70026","place":"outdoor","lb":"5868","desc":"Dungeon, landblock 5868. 1 entrance.","id":524,"minLevel":180}, + {"name":"West Fork Dam Hive","type":"Dungeon","ns":49.07,"ew":-80.05,"cell":"1BBC0017","place":"outdoor","lb":"5869","desc":"Dungeon, landblock 5869. 1 entrance.","id":525,"minLevel":180}, + {"name":"Masked Preface","type":"Dungeon","ns":-48.12,"ew":10.67,"cell":"8C430033","place":"outdoor","lb":"586C","desc":"Dungeon, landblock 586C. 1 entrance.","id":526,"minLevel":180}, + {"name":"Hive Eviscerator Burrow","type":"Dungeon","ns":48.59,"ew":-73.56,"cell":"23BC001A","place":"outdoor","lb":"586D","desc":"Dungeon, landblock 586D. 1 entrance.","id":527,"minLevel":200}, + {"name":"Hive Warrior Mound","type":"Dungeon","ns":49.1,"ew":-81.27,"cell":"19BC0037","place":"outdoor","lb":"586E","desc":"Dungeon, landblock 586E. 1 entrance.","id":528,"minLevel":200}, + {"name":"Tusker Den","type":"Dungeon","ns":84.34,"ew":-6.39,"cell":"77E8001F","place":"outdoor","lb":"586F","desc":"Dungeon, landblock 586F. 1 entrance.","id":529,"minLevel":200}, + {"name":"Curator of Torment's Study","type":"Dungeon","ns":-78.97,"ew":-39.21,"cell":"4E1C001E","place":"outdoor","lb":"5870","desc":"Dungeon, landblock 5870. 1 entrance.","id":530,"minLevel":180}, + {"name":"Seed of Hatred","type":"Dungeon","ns":-63.04,"ew":-65.49,"cell":"2D300026","place":"outdoor","lb":"5871","desc":"Dungeon, landblock 5871. 1 entrance.","id":531,"minLevel":180}, + {"name":"Seed of Misery","type":"Dungeon","ns":-63.13,"ew":-65.44,"cell":"2D30002D","place":"outdoor","lb":"5872","desc":"Dungeon, landblock 5872. 1 entrance.","id":532,"minLevel":180}, + {"name":"Seed of Anger","type":"Dungeon","ns":-63.13,"ew":-65.53,"cell":"2D300025","place":"outdoor","lb":"5873","desc":"Dungeon, landblock 5873. 1 entrance.","id":533,"minLevel":180}, + {"name":"Rynthid Genesis","type":"Dungeon","ns":-62.79,"ew":-66.73,"cell":"2C300008","place":"outdoor","lb":"5875","desc":"Dungeon, landblock 5875. 1 entrance.","id":534,"minLevel":180}, + {"name":"Rynthid Foundry","type":"Dungeon","ns":-62.48,"ew":-65.17,"cell":"2D31003B","place":"outdoor","lb":"5876","desc":"Dungeon, landblock 5876. 1 entrance.","id":535,"minLevel":180}, + {"name":"Fear Factory","type":"Dungeon","ns":-62.11,"ew":-65.37,"cell":"2D31002F","place":"outdoor","lb":"5877","desc":"Dungeon, landblock 5877. 1 entrance.","id":536,"minLevel":180}, + {"name":"Spirited Halls","type":"Dungeon","ns":-63.17,"ew":-66.69,"cell":"2C300004","place":"outdoor","lb":"5878","desc":"Dungeon, landblock 5878. 1 entrance.","id":537,"minLevel":180}, + {"name":"Path of Sorrows","type":"Dungeon","ns":-62.54,"ew":-65.41,"cell":"2D31002B","place":"outdoor","lb":"5879","desc":"Dungeon, landblock 5879. 3 entrances.","id":538,"minLevel":180}, + {"name":"Acid Guardian Lair","type":"Dungeon","ns":-30.49,"ew":-74.31,"cell":"22590000","place":"outdoor","lb":"5943","desc":"Dungeon, landblock 5943. 1 entrance.","id":539,"minLevel":60}, + {"name":"Proving Grounds High","type":"Dungeon","ns":17.2,"ew":62.98,"cell":"CE940102","place":"building","lb":"5944","desc":"Dungeon, landblock 5944. 1 entrance.","id":540,"minLevel":60}, + {"name":"Fire Ziggurat","type":"Dungeon","ns":57.08,"ew":47.75,"cell":"BBC6000F","place":"outdoor","lb":"5946","desc":"Dungeon, landblock 5946. 2 entrances.","id":541,"minLevel":60}, + {"name":"Tusker Armory","type":"Dungeon","ns":0.03,"ew":89.38,"cell":"EF7F0000","place":"outdoor","lb":"5948","desc":"Dungeon, landblock 5948. 1 entrance.","id":542,"minLevel":50}, + {"name":"Tusker Lacuna","type":"Dungeon","ns":-9.9,"ew":90.73,"cell":"F0730000","place":"outdoor","lb":"5949","desc":"Dungeon, landblock 5949. 1 entrance.","id":543,"minLevel":100}, + {"name":"Chapel of Mowen","type":"Dungeon","ns":3.12,"ew":93.61,"cell":"F4830000","place":"outdoor","lb":"594A","desc":"Dungeon, landblock 594A. 1 entrance.","id":544,"minLevel":50}, + {"name":"Aerbax's Holding","type":"Dungeon","ns":-62.4,"ew":-71.1,"cell":"26310000","place":"outdoor","lb":"594B","desc":"Dungeon, landblock 594B. 1 entrance.","id":545,"minLevel":60}, + {"name":"Gerent's Compound","type":"Dungeon","ns":-87.31,"ew":-17.49,"cell":"69120000","place":"outdoor","lb":"594C","desc":"Dungeon, landblock 594C. 1 entrance.","id":546,"minLevel":40}, + {"name":"Ancient Temple","type":"Dungeon","ns":-32.91,"ew":-88.19,"cell":"11560100","place":"building","lb":"594D","desc":"Dungeon, landblock 594D. 1 entrance.","id":547,"minLevel":80}, + {"name":"Deep Caves","type":"Dungeon","ns":-20.69,"ew":8.24,"cell":"8965002D","place":"outdoor","lb":"594E","desc":"Dungeon, landblock 594E. 1 entrance.","id":548}, + {"name":"Frozen Fortress","type":"Dungeon","ns":83.38,"ew":-6.47,"cell":"77E70016","place":"outdoor","lb":"594F","desc":"Dungeon, landblock 594F. 1 entrance.","id":549,"minLevel":180}, + {"name":"Presk's Bunker","type":"Dungeon","ns":-63.58,"ew":-66.35,"cell":"2C2F0020","place":"outdoor","lb":"5951","desc":"Dungeon, landblock 5951. 1 entrance.","id":550,"minLevel":180}, + {"name":"Bah'Ktar's Tower","type":"Dungeon","ns":-62.68,"ew":-66.67,"cell":"2C310001","place":"outdoor","lb":"5952","desc":"Dungeon, landblock 5952. 1 entrance.","id":551,"minLevel":180}, + {"name":"Frozen Recess","type":"Dungeon","ns":91.64,"ew":46.84,"cell":"B9F10040","place":"outdoor","lb":"595E","desc":"Dungeon, landblock 595E. 2 entrances.","id":552,"minLevel":180}, + {"name":"Radiant Blood Gauntlet","type":"Dungeon","ns":-39.74,"ew":83.63,"cell":"E74D003F","place":"outdoor","lb":"596B","desc":"Dungeon, landblock 596B. 4 entrances.","id":553,"minLevel":180}, + {"name":"Lightning Guardian Lair","type":"Dungeon","ns":-86.68,"ew":10.42,"cell":"8C130000","place":"outdoor","lb":"5A43","desc":"Dungeon, landblock 5A43. 1 entrance.","id":554,"minLevel":80}, + {"name":"Proving Grounds Extreme","type":"Dungeon","ns":17.16,"ew":62.98,"cell":"CE940102","place":"building","lb":"5A44","desc":"Dungeon, landblock 5A44. 1 entrance.","id":555,"minLevel":80}, + {"name":"Frost Ziggurat","type":"Dungeon","ns":57.08,"ew":47.78,"cell":"BBC6000F","place":"outdoor","lb":"5A46","desc":"Dungeon, landblock 5A46. 2 entrances.","id":556,"minLevel":80}, + {"name":"Tusker Barracks","type":"Dungeon","ns":-0.28,"ew":90.79,"cell":"F07F0000","place":"outdoor","lb":"5A48","desc":"Dungeon, landblock 5A48. 1 entrance.","id":557,"minLevel":40}, + {"name":"Tusker Honeycombs","type":"Dungeon","ns":-1.24,"ew":86.9,"cell":"EC7D0000","place":"outdoor","lb":"5A49","desc":"Dungeon, landblock 5A49. 1 entrance.","id":558,"minLevel":80}, + {"name":"Tusker Pits","type":"Dungeon","ns":1.21,"ew":91.79,"cell":"F2800000","place":"outdoor","lb":"5A4A","desc":"Dungeon, landblock 5A4A. 1 entrance.","id":559,"minLevel":45}, + {"name":"Olthoi Arcade","type":"Dungeon","ns":39.04,"ew":-81.17,"cell":"19B00000","place":"outdoor","lb":"5B43","desc":"Dungeon, landblock 5B43. 1 entrance.","id":560}, + {"name":"Virindi Complex","type":"Dungeon","ns":73.78,"ew":25.02,"cell":"9EDB0000","place":"outdoor","lb":"5B45","desc":"Dungeon, landblock 5B45. 1 entrance.","id":561}, + {"name":"Tusker Cave","type":"Dungeon","ns":0.4,"ew":97.38,"cell":"F97F0000","place":"outdoor","lb":"5B46","desc":"Dungeon, landblock 5B46. 1 entrance.","id":562,"minLevel":12}, + {"name":"Tusker Habitat","type":"Dungeon","ns":-0.51,"ew":95.87,"cell":"F77E0000","place":"outdoor","lb":"5B47","desc":"Dungeon, landblock 5B47. 1 entrance.","id":563,"minLevel":25}, + {"name":"Tusker Holding","type":"Dungeon","ns":-3.48,"ew":85.32,"cell":"EA7B0000","place":"outdoor","lb":"5B48","desc":"Dungeon, landblock 5B48. 1 entrance.","id":564,"minLevel":60}, + {"name":"Plated Rifts","type":"Dungeon","ns":-0.97,"ew":85.77,"cell":"EA7E0000","place":"outdoor","lb":"5B49","desc":"Dungeon, landblock 5B49. 1 entrance.","id":565,"minLevel":75}, + {"name":"Tusker Quarters","type":"Dungeon","ns":-2.26,"ew":95.6,"cell":"F67C0000","place":"outdoor","lb":"5B4A","desc":"Dungeon, landblock 5B4A. 1 entrance.","id":566,"minLevel":30}, + {"name":"Tusker Cavern","type":"Dungeon","ns":1.01,"ew":96.88,"cell":"F8800000","place":"outdoor","lb":"5C43","desc":"Dungeon, landblock 5C43. 1 entrance.","id":567,"minLevel":15}, + {"name":"Tusker Encampments","type":"Dungeon","ns":-4.0,"ew":93.48,"cell":"F47A0000","place":"outdoor","lb":"5C44","desc":"Dungeon, landblock 5C44. 1 entrance.","id":568,"minLevel":30}, + {"name":"Tusker Abode","type":"Dungeon","ns":-3.16,"ew":94.97,"cell":"F67B0000","place":"outdoor","lb":"5C45","desc":"Dungeon, landblock 5C45. 1 entrance.","id":569,"minLevel":20}, + {"name":"Tusker Gauntlet","type":"Dungeon","ns":-9.83,"ew":86.45,"cell":"EB730000","place":"outdoor","lb":"5C46","desc":"Dungeon, landblock 5C46. 1 entrance.","id":570,"minLevel":100}, + {"name":"Tusker Grotto","type":"Dungeon","ns":-0.92,"ew":98.38,"cell":"FA7E0000","place":"outdoor","lb":"5C47","desc":"Dungeon, landblock 5C47. 1 entrance.","id":571,"minLevel":12}, + {"name":"Rampage Bluff","type":"Dungeon","ns":-1.31,"ew":84.94,"cell":"E97D0000","place":"outdoor","lb":"5C48","desc":"Dungeon, landblock 5C48. 1 entrance.","id":572,"minLevel":80}, + {"name":"Tusker Retreat","type":"Dungeon","ns":-0.67,"ew":97.94,"cell":"F97E0000","place":"outdoor","lb":"5C49","desc":"Dungeon, landblock 5C49. 1 entrance.","id":573,"minLevel":5}, + {"name":"Tusker Temple","type":"Dungeon","ns":0.72,"ew":-68.11,"cell":"2A800000","place":"outdoor","lb":"5C4A","desc":"Dungeon, landblock 5C4A. 1 entrance.","id":574,"minLevel":40}, + {"name":"Tusker Temple","type":"Dungeon","ns":59.79,"ew":28.43,"cell":"A2CA0000","place":"outdoor","lb":"5D43","desc":"Dungeon, landblock 5D43. 1 entrance.","id":575,"minLevel":20}, + {"name":"Tusker Temple","type":"Dungeon","ns":-10.5,"ew":65.58,"cell":"D1720000","place":"outdoor","lb":"5D44","desc":"Dungeon, landblock 5D44. 1 entrance.","id":576}, + {"name":"Tusker Tunnels","type":"Dungeon","ns":0.29,"ew":86.37,"cell":"EB7F0000","place":"outdoor","lb":"5D45","desc":"Dungeon, landblock 5D45. 1 entrance.","id":577,"minLevel":70}, + {"name":"Vengeance Caverns","type":"Dungeon","ns":1.87,"ew":93.64,"cell":"F4810000","place":"outdoor","lb":"5D46","desc":"Dungeon, landblock 5D46. 1 entrance.","id":578,"minLevel":45}, + {"name":"Olthoi Chasm","type":"Dungeon","ns":0.7,"ew":44.71,"cell":"B7800000","place":"outdoor","lb":"5D4A","desc":"Dungeon, landblock 5D4A. 1 entrance.","id":579,"minLevel":20}, + {"name":"Black Death Catacombs","type":"Dungeon","ns":59.93,"ew":71.21,"cell":"D8CA0000","place":"outdoor","lb":"5E45","desc":"Dungeon, landblock 5E45. 1 entrance.","id":580,"minLevel":20}, + {"name":"Asheron's Sanctum","type":"Dungeon","ns":21.18,"ew":69.09,"cell":"D599014C","place":"building","lb":"5E47","desc":"Dungeon, landblock 5E47. 1 entrance.","id":581}, + {"name":"Olthoi Brood Hive","type":"Dungeon","ns":60.18,"ew":61.18,"cell":"CBCA0000","place":"outdoor","lb":"5E48","desc":"Dungeon, landblock 5E48. 1 entrance.","id":582,"minLevel":60}, + {"name":"Olthoi Brood Hive","type":"Dungeon","ns":66.5,"ew":70.67,"cell":"D7D20000","place":"outdoor","lb":"5E49","desc":"Dungeon, landblock 5E49. 1 entrance.","id":583,"minLevel":40}, + {"name":"Olthoi Brood Hive","type":"Dungeon","ns":51.82,"ew":59.78,"cell":"CAC00000","place":"outdoor","lb":"5E4A","desc":"Dungeon, landblock 5E4A. 1 entrance.","id":584,"minLevel":60}, + {"name":"Olthoi Brood Hive","type":"Dungeon","ns":71.2,"ew":60.22,"cell":"CAD80000","place":"outdoor","lb":"5E4B","desc":"Dungeon, landblock 5E4B. 1 entrance.","id":585,"minLevel":40}, + {"name":"Elemental Caverns","type":"Dungeon","ns":-82.56,"ew":-47.54,"cell":"44180000","place":"outdoor","lb":"5F47","desc":"Dungeon, landblock 5F47. 1 entrance.","id":586}, + {"name":"Hidden Cavern","type":"Dungeon","ns":-37.84,"ew":-65.51,"cell":"2D500000","place":"outdoor","lb":"5F48","desc":"Dungeon, landblock 5F48. 1 entrance.","id":587,"minLevel":80}, + {"name":"Behind the Waterfall","type":"Dungeon","ns":-8.66,"ew":85.71,"cell":"EA740000","place":"outdoor","lb":"6044","desc":"Dungeon, landblock 6044. 1 entrance.","id":588,"minLevel":80}, + {"name":"Caul Asylum","type":"Dungeon","ns":-94.8,"ew":-91.03,"cell":"0D080000","place":"outdoor","lb":"6045","desc":"Dungeon, landblock 6045. 1 entrance.","id":589,"minLevel":90}, + {"name":"Renegade Garrison","type":"Dungeon","ns":44.34,"ew":51.94,"cell":"C0B60000","place":"outdoor","lb":"6049","desc":"Dungeon, landblock 6049. 1 entrance.","id":590,"minLevel":40}, + {"name":"Sclavus Temple","type":"Dungeon","ns":-82.5,"ew":-75.19,"cell":"21180100","place":"building","lb":"604A","desc":"Dungeon, landblock 604A. 1 entrance.","id":591,"minLevel":60}, + {"name":"Basement","type":"Dungeon","ns":-94.79,"ew":-9.72,"cell":"73080105","place":"building","lb":"6143","desc":"Dungeon, landblock 6143. 1 entrance.","id":592}, + {"name":"Matron Hive West","type":"Dungeon","ns":-24.95,"ew":28.2,"cell":"A2600000","place":"outdoor","lb":"6145","desc":"Dungeon, landblock 6145. 1 entrance.","id":593,"minLevel":90}, + {"name":"Matron Hive East","type":"Dungeon","ns":-49.78,"ew":61.97,"cell":"CC410000","place":"outdoor","lb":"6146","desc":"Dungeon, landblock 6146. 1 entrance.","id":594,"minLevel":120}, + {"name":"Mountain Citadel","type":"Dungeon","ns":5.36,"ew":-71.83,"cell":"25860000","place":"outdoor","lb":"6147","desc":"Dungeon, landblock 6147. 1 entrance.","id":595}, + {"name":"Desert Citadel","type":"Dungeon","ns":-84.8,"ew":-59.7,"cell":"34150000","place":"outdoor","lb":"6148","desc":"Dungeon, landblock 6148. 1 entrance.","id":596}, + {"name":"Crystal Mine","type":"Dungeon","ns":-49.27,"ew":17.93,"cell":"95410000","place":"outdoor","lb":"6149","desc":"Dungeon, landblock 6149. 1 entrance.","id":597}, + {"name":"Lair of the Ancient Queen","type":"Dungeon","ns":13.2,"ew":0.82,"cell":"808F0000","place":"outdoor","lb":"614A","desc":"Dungeon, landblock 614A. 1 entrance.","id":598}, + {"name":"Renegade Fortress","type":"Dungeon","ns":-29.54,"ew":-65.5,"cell":"2D5A0104","place":"building","lb":"6248","desc":"Dungeon, landblock 6248. 1 entrance.","id":599,"minLevel":60}, + {"name":"Matron Hive South","type":"Dungeon","ns":-52.54,"ew":81.88,"cell":"E53D0000","place":"outdoor","lb":"6346","desc":"Dungeon, landblock 6346. 1 entrance.","id":600,"minLevel":40}, + {"name":"Matron Hive North","type":"Dungeon","ns":-47.49,"ew":24.88,"cell":"9E440000","place":"outdoor","lb":"6347","desc":"Dungeon, landblock 6347. 1 entrance.","id":601,"minLevel":60}, + {"name":"Tainted Grotto","type":"Dungeon","ns":-17.79,"ew":50.6,"cell":"BE690000","place":"outdoor","lb":"634C","desc":"Dungeon, landblock 634C. 1 entrance.","id":602}, + {"name":"Mount Ingot","type":"Dungeon","ns":-67.75,"ew":25.55,"cell":"9F2A0000","place":"outdoor","lb":"6448","desc":"Dungeon, landblock 6448. 1 entrance.","id":603}, + {"name":"Dragon's Power","type":"Dungeon","ns":-82.33,"ew":41.38,"cell":"B3180000","place":"outdoor","lb":"6449","desc":"Dungeon, landblock 6449. 3 entrances.","id":604,"minLevel":35}, + {"name":"Hoshino Tower","type":"Dungeon","ns":80.18,"ew":-42.45,"cell":"4AE30016","place":"outdoor","lb":"6651","desc":"Dungeon, landblock 6651. 2 entrances.","id":605,"minLevel":200}, + {"name":"Falatacot Temple","type":"Dungeon","ns":79.6,"ew":-42.53,"cell":"4AE20018","place":"outdoor","lb":"665E","desc":"Dungeon, landblock 665E. 1 entrance.","id":606,"minLevel":200}, + {"name":"Olthoi Warrior Nest","type":"Dungeon","ns":46.96,"ew":-81.21,"cell":"19BA0000","place":"outdoor","lb":"6678","desc":"Dungeon, landblock 6678. 1 entrance.","id":607,"minLevel":70}, + {"name":"Crumbling Empyrean Mansion","type":"Dungeon","ns":46.8,"ew":-67.88,"cell":"2AB90000","place":"outdoor","lb":"6679","desc":"Dungeon, landblock 6679. 1 entrance.","id":608}, + {"name":"Mutilator Tunnels","type":"Dungeon","ns":52.84,"ew":-78.12,"cell":"1DC10000","place":"outdoor","lb":"667A","desc":"Dungeon, landblock 667A. 1 entrance.","id":609,"minLevel":80}, + {"name":"Tanada Toresen Temple","type":"Dungeon","ns":-42.7,"ew":72.41,"cell":"D94A0039","place":"outdoor","lb":"6757","desc":"Dungeon, landblock 6757. 1 entrance.","id":610,"minLevel":200}, + {"name":"Empyrean Facility Upper Level","type":"Dungeon","ns":-46.21,"ew":-71.81,"cell":"2545002E","place":"outdoor","lb":"8904","desc":"Dungeon, landblock 8904. 1 entrance.","id":611,"minLevel":75}, + {"name":"Hub of Awakening","type":"Dungeon","ns":42.13,"ew":33.56,"cell":"A9B40019","place":"outdoor","lb":"8A02","desc":"Dungeon, landblock 8A02. 1 entrance.","id":612}, + {"name":"Forgotten Tunnels","type":"Dungeon","ns":-93.56,"ew":-56.6,"cell":"380A0102","place":"building","lb":"8B02","desc":"Dungeon, landblock 8B02. 1 entrance.","id":613,"minLevel":180}, + {"name":"Geraine's Study","type":"Dungeon","ns":82.81,"ew":-6.32,"cell":"77E702F7","place":"building","lb":"9302","desc":"Dungeon, landblock 9302. 1 entrance.","id":614,"minLevel":150}, + {"name":"Mainland","type":"Dungeon","ns":-88.04,"ew":48.8,"cell":"BC11015A","place":"building","lb":"BA11","desc":"Dungeon, landblock BA11. 1 entrance.","id":615}, + {"name":"Olthoi Tunnel","type":"Dungeon","ns":69.4,"ew":80.31,"cell":"E3D60032","place":"outdoor","lb":"C7EA","desc":"Dungeon, landblock C7EA. 1 entrance.","id":616}, + {"name":"Surface","type":"Portal","wcid":28783,"cell":"000102C8","place":"dungeon","dest":{"cell":"26E5001D","place":"outdoor","ns":81.68,"ew":-71.16},"desc":"In Remote Empyrean Vault.","id":617}, + {"name":"Surface","type":"Portal","wcid":28783,"cell":"0001011B","place":"dungeon","dest":{"cell":"26E5001D","place":"outdoor","ns":81.68,"ew":-71.16},"desc":"In Remote Empyrean Vault.","id":618}, + {"name":"Destroyed Portal to Sanamar","type":"Portal","wcid":28709,"cell":"00020225","place":"dungeon","dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Viamontian Garrison.","id":619}, + {"name":"Surface","type":"Portal","wcid":28800,"cell":"0002021C","place":"dungeon","dest":{"cell":"23DD000D","place":"outdoor","ns":75.34,"ew":-73.83},"desc":"In Viamontian Garrison.","id":620}, + {"name":"Surface","type":"Portal","wcid":30473,"cell":"0004010E","place":"dungeon","dest":{"cell":"6296003B","place":"outdoor","ns":18.35,"ew":-22.85},"desc":"In Northern Power Forge.","id":621}, + {"name":"Surface","type":"Portal","wcid":30473,"cell":"000402A6","place":"dungeon","dest":{"cell":"6296003B","place":"outdoor","ns":18.35,"ew":-22.85},"desc":"In Northern Power Forge.","id":622}, + {"name":"Surface","type":"Portal","wcid":30469,"cell":"0005010E","place":"dungeon","dest":{"cell":"7A180025","place":"outdoor","ns":-82.29,"ew":-3.89},"desc":"In Southern Power Forge.","id":623}, + {"name":"Surface","type":"Portal","wcid":30469,"cell":"000502A6","place":"dungeon","dest":{"cell":"7A180025","place":"outdoor","ns":-82.29,"ew":-3.89},"desc":"In Southern Power Forge.","id":624}, + {"name":"Surface","type":"Portal","wcid":30471,"cell":"0006010E","place":"dungeon","dest":{"cell":"48640031","place":"outdoor","ns":-21.9,"ew":-43.74},"desc":"In Western Power Forge.","id":625}, + {"name":"Surface","type":"Portal","wcid":30471,"cell":"000602A6","place":"dungeon","dest":{"cell":"48640031","place":"outdoor","ns":-21.9,"ew":-43.74},"desc":"In Western Power Forge.","id":626}, + {"name":"Al-Jalima Portal","type":"Portal","wcid":42830,"cell":"0007010A","place":"dungeon","dest":{"cell":"8588002C","place":"outdoor","ns":7.25,"ew":4.95},"desc":"This portal goes to Al-Jalima, the Gharu'ndim settlement located between the prominent cities of Zaikhal and Samsur. This is a good town for characters over level 20. In Town Network.","id":627}, + {"name":"Tufa Portal","type":"Portal","wcid":42829,"cell":"0007010C","place":"dungeon","dest":{"cell":"876C0008","place":"outdoor","ns":-14.77,"ew":6.06},"desc":"This portal goes to Tufa, the once peaceful desert oasis that was destroyed by Shadows during the Fourth Sending of Darkness. The residents have since regrouped in tents and buildings surrounded the crater of their former homes. This is a good town for characters over level 20. In Town Network.","id":628}, + {"name":"Portal to Zaikhal","type":"Portal","wcid":42831,"cell":"0007010D","place":"dungeon","dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal goes to the Gharu'ndim capital, Zaikhal. This is a good town for characters over level 20. In Town Network.","id":629}, + {"name":"Uziz Portal","type":"Portal","wcid":42821,"cell":"00070111","place":"dungeon","dest":{"cell":"A260003C","place":"outdoor","ns":-24.78,"ew":28.41},"desc":"This portal goes to the town of Uziz in the heart of the Yushad Ridge. This is a good town for characters over level 20. In Town Network.","id":630}, + {"name":"Portal to Xarabydun","type":"Portal","wcid":42832,"cell":"00070112","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"This portal goes to the town of Xarabydun, in the southern reaches of the A'mun desert. This is a good town for characters over level 10, but be careful -- the surrounding area can be a bit rough. In Town Network.","id":631}, + {"name":"Portal to Khayyaban","type":"Portal","wcid":42822,"cell":"00070116","place":"dungeon","dest":{"cell":"9F440012","place":"outdoor","ns":-47.45,"ew":25.62},"desc":"This portal goes to the town of Khayyaban on the Yushad Ridge. This is a good town for characters over level 20. In Town Network.","id":632}, + {"name":"Qalaba'r Portal","type":"Portal","wcid":42833,"cell":"00070117","place":"dungeon","dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"desc":"This portal leads to Qalaba'r, the Gharu'ndim village on the edge of the Linvak Mountain Range. This is a good town for characters over level 30. In Town Network.","id":633}, + {"name":"Portal to Al-Arqas","type":"Portal","wcid":42823,"cell":"0007011B","place":"dungeon","dest":{"cell":"8F58003B","place":"outdoor","ns":-31.3,"ew":13.22},"desc":"This portal goes to the Gharu'ndim town of Al-Arqas in the depths of the A'mun desert. This is a good town for characters over level 10. In Town Network.","id":634}, + {"name":"Portal to Samsur","type":"Portal","wcid":42834,"cell":"0007011C","place":"dungeon","dest":{"cell":"977B000C","place":"outdoor","ns":-3.24,"ew":18.96},"desc":"This portal goes to Samsur, a Gharu'ndim town in the hills behind the Yushad Ridge. This is a good town for characters over level 10. In Town Network.","id":635}, + {"name":"Portal to Yaraq","type":"Portal","wcid":42824,"cell":"00070120","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal goes to Yaraq, a Gharu'ndim town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Town Network.","id":636}, + {"name":"Glenden Wood Portal","type":"Portal","wcid":42814,"cell":"00070121","place":"dungeon","dest":{"cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45},"desc":"This portal goes to Glenden Wood, a village surrounded by the tall trees of the Tiofor Woods. Despite the truce between Queen Elysa and King Varicci, the town is besieged on all sides by Viamontian soldiers. This is a good town for characters over level 40. In Town Network.","id":637}, + {"name":"Lytelthorpe Portal","type":"Portal","wcid":42816,"cell":"00070122","place":"dungeon","dest":{"cell":"C0800007","place":"outdoor","ns":1.1,"ew":51.7},"desc":"This portal goes to the town of Lytelthorpe, an Aluvian settlement surrounded by rich farmlands. This is a good town for characters over level 10. In Town Network.","id":638}, + {"name":"Portal to Cragstone","type":"Portal","wcid":42818,"cell":"00070123","place":"dungeon","dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal goes to the Aluvian capital, Cragstone. This is a good town for characters over level 10. In Town Network.","id":639}, + {"name":"Portal to Holtburg","type":"Portal","wcid":42820,"cell":"00070124","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal goes to Holtburg, an Aluvian town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Town Network.","id":640}, + {"name":"Portal to Facility Hub","type":"Portal","wcid":42851,"cell":"00070126","place":"dungeon","dest":{"cell":"8A020212","place":"dungeon","name":"Hub of Awakening"},"minLevel":10,"desc":"This portal goes to the Facility Hub, a good starting place for new adventurers. In Town Network.","id":641}, + {"name":"Portal to Bluespire","type":"Portal","wcid":42825,"cell":"00070127","place":"dungeon","dest":{"cell":"21B00017","place":"outdoor","ns":39.54,"ew":-75.35},"desc":"This portal goes to the town of Bluespire on the island of Marae Lassel. This is a good town for characters over level 10. In Town Network.","id":642}, + {"name":"Portal to Greenspire","type":"Portal","wcid":42826,"cell":"00070128","place":"dungeon","dest":{"cell":"2BB5003C","place":"outdoor","ns":43.21,"ew":-66.8},"desc":"This portal goes to the town of Greenspire on the island of Marae Lassel. This is a good town for characters over level 10. In Town Network.","id":643}, + {"name":"Ahurenga Portal","type":"Portal","wcid":42827,"cell":"00070129","place":"dungeon","dest":{"cell":"0FB90009","place":"outdoor","ns":46.09,"ew":-89.77},"desc":"This portal goes to Ahurenga, the home of the Hea Tumeroks in the marshes of western Marae Lassel. This is a good town for characters over level 40. In Town Network.","id":644}, + {"name":"Portal to Neydisa Castle","type":"Portal","wcid":42828,"cell":"0007012A","place":"dungeon","dest":{"cell":"95D60033","place":"outdoor","ns":69.55,"ew":17.86},"desc":"This portal goes to Neydisa Castle, northeast of Mt. Esper. This is a good town for characters over level 40. In Town Network.","id":645}, + {"name":"Portal to Silyun","type":"Portal","wcid":42998,"cell":"0007012B","place":"dungeon","dest":{"cell":"26EC003D","place":"outdoor","ns":87.31,"ew":-70.82},"desc":"This portal goes to Silyun, the home of the remnants of the Bellenesse rebels. This is a good town for characters over level 40. In Town Network.","id":646}, + {"name":"Fiun Outpost","type":"Portal","wcid":42999,"cell":"0007012C","place":"dungeon","dest":{"cell":"38F7001B","place":"outdoor","ns":95.88,"ew":-56.77},"desc":"This portal is tied to the Fiun Outpost. This outpost is a good place for characters above level 60. In Town Network.","id":647}, + {"name":"Plateau Portal","type":"Portal","wcid":42812,"cell":"0007012D","place":"dungeon","dest":{"cell":"49B70021","place":"outdoor","ns":44.54,"ew":-43.13},"desc":"This portal goes to the Plateau Village, a remote settlement in the forests of Northwestern Osteth. This is a good town for characters over level 40. In Town Network.","id":648}, + {"name":"Base of the Timaru Plateau Portal","type":"Portal","wcid":43000,"cell":"0007013C","place":"dungeon","dest":{"cell":"1DB60016","place":"outdoor","ns":44.21,"ew":-78.45},"desc":"This portal goes to Timaru, the home of the Aun Tumeroks atop the Marescent Plateau of Marae Lassel. This is a good town for characters over level 40. In Town Network.","id":649}, + {"name":"Fort Tethana Portal","type":"Portal","wcid":43001,"cell":"0007013D","place":"dungeon","dest":{"cell":"2681001D","place":"outdoor","ns":1.7,"ew":-71.23},"desc":"Located in the northern part of the Direlands, Fort Tethana teeters on the brink of outright warfare with the neighboring Renegade encampment. Adventurers may find they need to assist the troops stationed here to keep this important fort under control of the Realm. This town is good for characters over level 50. In Town Network.","id":650}, + {"name":"Stonehold Portal","type":"Portal","wcid":42811,"cell":"00070150","place":"dungeon","dest":{"cell":"64D5000B","place":"outdoor","ns":68.66,"ew":-21.82},"desc":"This portal goes to Stonehold. a remote village found in the westernmost reaches of the Esper mountain range. This is a good town for characters over level 50. In Town Network.","id":651}, + {"name":"Oolutanga's Refuge","type":"Portal","wcid":43002,"cell":"0007015F","place":"dungeon","dest":{"cell":"F6820033","place":"outdoor","ns":2.26,"ew":95.46},"minLevel":10,"desc":"This portal goes to Oolutanga's Refuge, a place where Tuskers rule the land. This is a good town for charaters over level 10. In Town Network.","id":652}, + {"name":"Portal to Dryreach","type":"Portal","wcid":42813,"cell":"00070160","place":"dungeon","dest":{"cell":"DA75002B","place":"outdoor","ns":-8.1,"ew":73.0},"desc":"This fortified town fell under siege in the earlier days of Aluvian settlement to Tumeroks ushered in from the Hea Village of Ahurenga by the Virindi. The townpeople are often in need of donations from traveling adventurers lest they starve. This town is good for characters over level 20. In Town Network.","id":653}, + {"name":"Eastham Portal","type":"Portal","wcid":42815,"cell":"00070161","place":"dungeon","dest":{"cell":"CE940035","place":"outdoor","ns":16.92,"ew":63.48},"desc":"This portal goes to Eastham, a coastal Aluvian town that contains a portal to Asheron's island home. This is a good town for characters over level 20. In Town Network.","id":654}, + {"name":"Portal to Rithwic","type":"Portal","wcid":42817,"cell":"00070162","place":"dungeon","dest":{"cell":"C98C0028","place":"outdoor","ns":10.84,"ew":59.32},"desc":"This portal goes to Rithwic, an Aluvian town on the shores of Lake Blessed. This is a good town for characters over level 10. In Town Network.","id":655}, + {"name":"Portal to Arwic","type":"Portal","wcid":42819,"cell":"00070163","place":"dungeon","dest":{"cell":"C6A90009","place":"outdoor","ns":33.27,"ew":56.65},"desc":"This portal goes to Arwic, a walled Aluvian town that has fully recovered from a devastating attack by a Shadow Spire. This is a good town for characters over level 20. In Town Network.","id":656}, + {"name":"The Marketplace of Dereth","type":"Portal","wcid":23032,"cell":"00070165","place":"dungeon","dest":{"cell":"016C01BC","place":"dungeon"},"desc":"In Town Network.","id":657}, + {"name":"Portal to Sanamar","type":"Portal","wcid":42835,"cell":"00070166","place":"dungeon","dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"desc":"This portal goes to Sanamar, the capital of New Viamont and town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Town Network.","id":658}, + {"name":"Portal to Redspire","type":"Portal","wcid":42836,"cell":"00070167","place":"dungeon","dest":{"cell":"17B2002A","place":"outdoor","ns":40.56,"ew":-83.0},"desc":"This portal goes to the town of Redspire on the island of Marae Lassel. This is a good town for characters over level 10. In Town Network.","id":659}, + {"name":"Portal to Westwatch","type":"Portal","wcid":42837,"cell":"00070168","place":"dungeon","dest":{"cell":"23DA002C","place":"outdoor","ns":72.81,"ew":-73.36},"desc":"This portal is tied to the Viamontian outpost of Westwatch. This outpost is a good place for characters above level 20. In Town Network.","id":660}, + {"name":"Portal to Linvak Tukal","type":"Portal","wcid":42838,"cell":"00070169","place":"dungeon","dest":{"cell":"A21E001A","place":"outdoor","ns":-77.79,"ew":28.0},"desc":"This portal goes to Linvak Tukal, the fortress bastion of our Lugian allies in the Linvak Range. This is a good town for characters over level 40. In Town Network.","id":661}, + {"name":"Danby's Outpost","type":"Portal","wcid":43003,"cell":"0007016A","place":"dungeon","dest":{"cell":"5A9C0004","place":"outdoor","ns":23.17,"ew":-29.85},"desc":"This portal goes to Danby's Outpost, a settlement on the northern edge of the inner sea. This outpost is a good place for characters over level 40. In Town Network.","id":662}, + {"name":"Portal to Eastwatch","type":"Portal","wcid":42839,"cell":"0007016B","place":"dungeon","dest":{"cell":"49F00013","place":"outdoor","ns":90.34,"ew":-43.26},"minLevel":80,"desc":"This portal is tied to the Viamontian outpost of Eastwatch. This outpost is a good place for characters above level 80. In Town Network.","id":663}, + {"name":"Portal to Shoushi","type":"Portal","wcid":42840,"cell":"0007016C","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal goes to Shoushi, a Sho town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Town Network.","id":664}, + {"name":"Portal to Tou-Tou","type":"Portal","wcid":42841,"cell":"00070170","place":"dungeon","dest":{"cell":"F5590034","place":"outdoor","ns":-30.41,"ew":94.69},"desc":"This portal goes to the Sho town of Tou-Tou, perched on the tip of the Tou-Tou peninsula. This is a good town for characters over level 20. In Town Network.","id":665}, + {"name":"Mayoi Portal","type":"Portal","wcid":42842,"cell":"00070171","place":"dungeon","dest":{"cell":"E6320021","place":"outdoor","ns":-61.91,"ew":82.5},"desc":"This portal goes to Mayoi, a coastal settlement renowned for Shoyanen Kenchu, the master mage of the Sho people, who lives in a spire on the outskirts of town. This is a good town for characters over level 30. In Town Network.","id":666}, + {"name":"Portal to Nanto","type":"Portal","wcid":42843,"cell":"00070175","place":"dungeon","dest":{"cell":"E63E0022","place":"outdoor","ns":-52.19,"ew":82.45},"desc":"This portal goes to Nanto, a sleepy Sho town. This is a good town for characters over level 10. In Town Network.","id":667}, + {"name":"Lin Portal","type":"Portal","wcid":42844,"cell":"00070176","place":"dungeon","dest":{"cell":"DC3C0011","place":"outdoor","ns":-53.91,"ew":74.3},"desc":"This portal goes to Lin, a small town nestled in a valley located by the foothills of the Linvak Mountains. This is a good town for characters over level 20. In Town Network.","id":668}, + {"name":"Baishi Portal","type":"Portal","wcid":42845,"cell":"0007017A","place":"dungeon","dest":{"cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9},"desc":"This portal goes to Baishi, a town well-known for its sake and the madman that desires it. This is good town for characters over level 40. In Town Network.","id":669}, + {"name":"Portal to Hebian-To","type":"Portal","wcid":42846,"cell":"0007017B","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal goes to the Sho capital, Hebian-To. This is a good town for characters over level 10. In Town Network.","id":670}, + {"name":"Portal to Yanshi","type":"Portal","wcid":42847,"cell":"0007017F","place":"dungeon","dest":{"cell":"B46F001E","place":"outdoor","ns":-12.63,"ew":42.36},"desc":"This portal goes to the Sho town of Yanshi on the edges of the Blackmire swamp. The original town was devastated by the Harbinger, who still lurks deep beneath the surface. This is a good town for characters over level 10. But stay away from the Harbinger. In Town Network.","id":671}, + {"name":"Portal to Kara","type":"Portal","wcid":42848,"cell":"00070180","place":"dungeon","dest":{"cell":"BA170039","place":"outdoor","ns":-83.54,"ew":47.6},"desc":"This portal goes to the town of Kara, hidden deep in the Linvak range. This is a good town for characters over level 40. In Town Network.","id":672}, + {"name":"Sawato Portal","type":"Portal","wcid":42849,"cell":"00070184","place":"dungeon","dest":{"cell":"C95B0001","place":"outdoor","ns":-29.15,"ew":58.91},"desc":"This portal goes to Sawato, a village surrounded by the wetlands of the Blackmire Swamp. This is a good town for characters over level 30. In Town Network.","id":673}, + {"name":"Portal to Kryst","type":"Portal","wcid":42850,"cell":"00070185","place":"dungeon","dest":{"cell":"E822002A","place":"outdoor","ns":-74.59,"ew":84.2},"desc":"This portal goes to the town of Kryst on the Vesayen archipelago. This is a good town for characters over level 20. In Town Network.","id":674}, + {"name":"Freehold Portal","type":"Portal","wcid":43004,"cell":"00070187","place":"dungeon","dest":{"cell":"F224001A","place":"outdoor","ns":-73.01,"ew":91.99},"desc":"This portal goes to MacNiall's Freehold, a bastion of civilization among the tropical islands of the Vesayen Archipelago. The only law here is to live as you wish, unrestricted by the ideologies of Ispar. This is a good town for characters over level 30. In Town Network.","id":675}, + {"name":"Weakened Vault Sewers","type":"Portal","wcid":30717,"cell":"00080181","place":"dungeon","dest":{"cell":"000C0142","place":"dungeon"},"minLevel":40,"quest":true,"desc":"You must best the spirits of the temple before you may pass through this portal. In Defiled Temple Lower Wing.","id":676}, + {"name":"Surface","type":"Portal","wcid":30753,"cell":"00080155","place":"dungeon","dest":{"cell":"A8DF0010","place":"outdoor","ns":77.18,"ew":32.59},"desc":"In Defiled Temple Lower Wing.","id":677}, + {"name":"Reinforced Vault Sewers","type":"Portal","wcid":30721,"cell":"00090181","place":"dungeon","dest":{"cell":"000E02EE","place":"dungeon"},"minLevel":80,"quest":true,"desc":"You must best the spirits of the temple before you may pass through this portal. In Defiled Temple Upper Wing.","id":678}, + {"name":"Fortified Vault Sewers","type":"Portal","wcid":30723,"cell":"000A0181","place":"dungeon","dest":{"cell":"000F02EE","place":"dungeon"},"minLevel":100,"quest":true,"desc":"You must best the spirits of the temple before you may pass through this portal. In Defiled Temple Asylum.","id":679}, + {"name":"Surface","type":"Portal","wcid":30753,"cell":"000A0155","place":"dungeon","dest":{"cell":"A8DF0010","place":"outdoor","ns":77.18,"ew":32.59},"desc":"In Defiled Temple Asylum.","id":680}, + {"name":"Surface","type":"Portal","wcid":30644,"cell":"000B016D","place":"dungeon","dest":{"cell":"77DA0005","place":"outdoor","ns":72.94,"ew":-6.71},"desc":"In a dungeon (landblock 000B).","id":681}, + {"name":"Surface","type":"Portal","wcid":30644,"cell":"000B031F","place":"dungeon","dest":{"cell":"77DA0005","place":"outdoor","ns":72.94,"ew":-6.71},"desc":"In a dungeon (landblock 000B).","id":682}, + {"name":"Surface","type":"Portal","wcid":30718,"cell":"000C02EB","place":"dungeon","dest":{"cell":"A8DF0010","place":"outdoor","ns":77.18,"ew":32.59},"desc":"In a dungeon (landblock 000C).","id":683}, + {"name":"Weakened Royal Vault","type":"Portal","wcid":30726,"cell":"000C0199","place":"dungeon","dest":{"cell":"001102D6","place":"dungeon"},"minLevel":40,"desc":"In a dungeon (landblock 000C).","id":684}, + {"name":"Secured Royal Vault","type":"Portal","wcid":30728,"cell":"000D0199","place":"dungeon","dest":{"cell":"001202D6","place":"dungeon"},"minLevel":60,"desc":"In a dungeon (landblock 000D).","id":685}, + {"name":"Surface","type":"Portal","wcid":30720,"cell":"000D02EB","place":"dungeon","dest":{"cell":"A8DF0010","place":"outdoor","ns":77.18,"ew":32.59},"desc":"In a dungeon (landblock 000D).","id":686}, + {"name":"Reinforced Royal Vault","type":"Portal","wcid":30730,"cell":"000E0199","place":"dungeon","dest":{"cell":"001302D6","place":"dungeon"},"minLevel":80,"desc":"In a dungeon (landblock 000E).","id":687}, + {"name":"Surface","type":"Portal","wcid":30722,"cell":"000E02EB","place":"dungeon","dest":{"cell":"A8DF0010","place":"outdoor","ns":77.18,"ew":32.59},"desc":"In a dungeon (landblock 000E).","id":688}, + {"name":"Fortified Royal Vault","type":"Portal","wcid":30715,"cell":"000F0199","place":"dungeon","dest":{"cell":"001402D6","place":"dungeon"},"minLevel":100,"desc":"In a dungeon (landblock 000F).","id":689}, + {"name":"Surface","type":"Portal","wcid":30724,"cell":"000F02EB","place":"dungeon","dest":{"cell":"A8DF0010","place":"outdoor","ns":77.18,"ew":32.59},"desc":"In a dungeon (landblock 000F).","id":690}, + {"name":"Escape Route","type":"Portal","wcid":30661,"cell":"00100355","place":"dungeon","dest":{"cell":"0B700118","place":"building","ns":-11.93,"ew":-92.84},"desc":"In War Room.","id":691}, + {"name":"Escape Route","type":"Portal","wcid":30661,"cell":"0010012A","place":"dungeon","dest":{"cell":"0B700118","place":"building","ns":-11.93,"ew":-92.84},"desc":"In War Room.","id":692}, + {"name":"Surface","type":"Portal","wcid":30727,"cell":"00110219","place":"dungeon","dest":{"cell":"A8DF0010","place":"outdoor","ns":77.18,"ew":32.59},"desc":"In a dungeon (landblock 0011).","id":693}, + {"name":"Surface","type":"Portal","wcid":30729,"cell":"00120219","place":"dungeon","dest":{"cell":"A8DF0010","place":"outdoor","ns":77.18,"ew":32.59},"desc":"In a dungeon (landblock 0012).","id":694}, + {"name":"Surface","type":"Portal","wcid":30731,"cell":"00130219","place":"dungeon","dest":{"cell":"A8DF0010","place":"outdoor","ns":77.18,"ew":32.59},"desc":"In a dungeon (landblock 0013).","id":695}, + {"name":"Surface","type":"Portal","wcid":30716,"cell":"00140219","place":"dungeon","dest":{"cell":"A8DF0010","place":"outdoor","ns":77.18,"ew":32.59},"desc":"In a dungeon (landblock 0014).","id":696}, + {"name":"Surface","type":"Portal","wcid":4942,"cell":"001501CE","place":"dungeon","dest":{"cell":"1B12003B","place":"outdoor","ns":-87.33,"ew":-79.62},"desc":"In Banished Assembly.","id":697}, + {"name":"Surface","type":"Portal","wcid":30692,"cell":"001601CE","place":"dungeon","dest":{"cell":"1D140003","place":"outdoor","ns":-85.75,"ew":-78.7},"desc":"In Ravaged Cathedral.","id":698}, + {"name":"Surface","type":"Portal","wcid":30694,"cell":"001701CE","place":"dungeon","dest":{"cell":"1D120040","place":"outdoor","ns":-86.81,"ew":-78.02},"desc":"In a dungeon (landblock 0017).","id":699}, + {"name":"Exit Copper Legion Keep","type":"Portal","wcid":29434,"cell":"001801C6","place":"dungeon","dest":{"cell":"808E000D","place":"outdoor","ns":12.05,"ew":0.58},"desc":"In Copper Legion Keep.","id":700}, + {"name":"Exit Copper Legion Keep","type":"Portal","wcid":29434,"cell":"001802DD","place":"dungeon","dest":{"cell":"808E000D","place":"outdoor","ns":12.05,"ew":0.58},"desc":"In Copper Legion Keep.","id":701}, + {"name":"Exit Gold Legion Keep","type":"Portal","wcid":29436,"cell":"00190103","place":"dungeon","dest":{"cell":"8190003E","place":"outdoor","ns":13.79,"ew":2.02},"desc":"In Gold Legion Keep.","id":702}, + {"name":"Exit Gold Legion Keep","type":"Portal","wcid":29436,"cell":"00190190","place":"dungeon","dest":{"cell":"8190003E","place":"outdoor","ns":13.79,"ew":2.02},"desc":"In Gold Legion Keep.","id":703}, + {"name":"Exit Platinum Legion Keep","type":"Portal","wcid":29438,"cell":"001A02EA","place":"dungeon","dest":{"cell":"80940009","place":"outdoor","ns":16.49,"ew":0.59},"desc":"In Platinum Legion Keep.","id":704}, + {"name":"Exit Platinum Legion Keep","type":"Portal","wcid":29438,"cell":"001A018A","place":"dungeon","dest":{"cell":"80940009","place":"outdoor","ns":16.49,"ew":0.59},"desc":"In Platinum Legion Keep.","id":705}, + {"name":"Exit Silver Legion Keep","type":"Portal","wcid":29440,"cell":"001B016F","place":"dungeon","dest":{"cell":"7D90001C","place":"outdoor","ns":13.59,"ew":-1.57},"desc":"In Silver Legion Keep.","id":706}, + {"name":"Exit Silver Legion Keep","type":"Portal","wcid":29440,"cell":"001B0266","place":"dungeon","dest":{"cell":"7D90001C","place":"outdoor","ns":13.59,"ew":-1.57},"desc":"In Silver Legion Keep.","id":707}, + {"name":"Exit Lugian Ice Tunnels","type":"Portal","wcid":29482,"cell":"001C010A","place":"dungeon","dest":{"cell":"40F40031","place":"outdoor","ns":93.28,"ew":-50.13},"desc":"In Lugian Ice Tunnels.","id":708}, + {"name":"Exit Lugian Ice Tunnels","type":"Portal","wcid":29482,"cell":"001C025C","place":"dungeon","dest":{"cell":"40F40031","place":"outdoor","ns":93.28,"ew":-50.13},"desc":"In Lugian Ice Tunnels.","id":709}, + {"name":"Exit Ruschk Icehold","type":"Portal","wcid":29484,"cell":"001D011D","place":"dungeon","dest":{"cell":"3EEC002D","place":"outdoor","ns":87.3,"ew":-51.85},"desc":"In Ruschk Icehold.","id":710}, + {"name":"Exit Ruschk Icehold","type":"Portal","wcid":29484,"cell":"001D014E","place":"dungeon","dest":{"cell":"3EEC002D","place":"outdoor","ns":87.3,"ew":-51.85},"desc":"In Ruschk Icehold.","id":711}, + {"name":"Exit Viamontian Royal Prison","type":"Portal","wcid":29486,"cell":"001E0299","place":"dungeon","dest":{"cell":"4BF2001C","place":"outdoor","ns":92.0,"ew":-41.56},"desc":"In Viamontian Royal Prison.","id":712}, + {"name":"Surface","type":"Portal","wcid":29497,"cell":"001F0284","place":"dungeon","dest":{"cell":"24EE002C","place":"outdoor","ns":88.8,"ew":-72.57},"desc":"In a dungeon (landblock 001F).","id":713}, + {"name":"Surface","type":"Portal","wcid":29497,"cell":"001F0100","place":"dungeon","dest":{"cell":"24EE002C","place":"outdoor","ns":88.8,"ew":-72.57},"desc":"In a dungeon (landblock 001F).","id":714}, + {"name":"Surface","type":"Portal","wcid":29499,"cell":"002002CD","place":"dungeon","dest":{"cell":"29E9002C","place":"outdoor","ns":84.76,"ew":-68.6},"desc":"In a dungeon (landblock 0020).","id":715}, + {"name":"Surface","type":"Portal","wcid":29499,"cell":"00200101","place":"dungeon","dest":{"cell":"29E9002C","place":"outdoor","ns":84.76,"ew":-68.6},"desc":"In a dungeon (landblock 0020).","id":716}, + {"name":"Karlun's Hall Exit","type":"Portal","wcid":29503,"cell":"0021013E","place":"dungeon","dest":{"cell":"2AEE0024","place":"outdoor","ns":88.81,"ew":-67.88},"desc":"In Hall of Karlun.","id":717}, + {"name":"Surface","type":"Portal","wcid":29513,"cell":"00220101","place":"dungeon","dest":{"cell":"36ED0014","place":"outdoor","ns":88.0,"ew":-58.45},"desc":"In a dungeon (landblock 0022).","id":718}, + {"name":"Surface","type":"Portal","wcid":29513,"cell":"002202F6","place":"dungeon","dest":{"cell":"36ED0014","place":"outdoor","ns":88.0,"ew":-58.45},"desc":"In a dungeon (landblock 0022).","id":719}, + {"name":"Surface","type":"Portal","wcid":30962,"cell":"002902ED","place":"dungeon","dest":{"cell":"49F50100","place":"building","ns":94.13,"ew":-42.97},"desc":"In Thrungus Hole.","id":720}, + {"name":"Surface","type":"Portal","wcid":30962,"cell":"0029011C","place":"dungeon","dest":{"cell":"49F50100","place":"building","ns":94.13,"ew":-42.97},"desc":"In Thrungus Hole.","id":721}, + {"name":"Surface","type":"Portal","wcid":30970,"cell":"002A034E","place":"dungeon","dest":{"cell":"43F1001B","place":"outdoor","ns":91.07,"ew":-47.97},"desc":"In Path of the Blind.","id":722}, + {"name":"Surface","type":"Portal","wcid":30970,"cell":"002A017F","place":"dungeon","dest":{"cell":"43F1001B","place":"outdoor","ns":91.07,"ew":-47.97},"desc":"In Path of the Blind.","id":723}, + {"name":"Surface","type":"Portal","wcid":30965,"cell":"002B036F","place":"dungeon","dest":{"cell":"43F70015","place":"outdoor","ns":96.1,"ew":-48.1},"desc":"In Egg Orchard.","id":724}, + {"name":"Surface","type":"Portal","wcid":30965,"cell":"002B0100","place":"dungeon","dest":{"cell":"43F70015","place":"outdoor","ns":96.1,"ew":-48.1},"desc":"In Egg Orchard.","id":725}, + {"name":"Surface","type":"Portal","wcid":30969,"cell":"002C02A2","place":"dungeon","dest":{"cell":"4EF5002D","place":"outdoor","ns":94.54,"ew":-39.05},"desc":"In Forgotten Chasm.","id":726}, + {"name":"Surface","type":"Portal","wcid":30961,"cell":"002D0372","place":"dungeon","dest":{"cell":"47F4000E","place":"outdoor","ns":93.8,"ew":-45.0},"desc":"In Dark Design.","id":727}, + {"name":"Surface","type":"Portal","wcid":30961,"cell":"002D01B3","place":"dungeon","dest":{"cell":"47F4000E","place":"outdoor","ns":93.8,"ew":-45.0},"desc":"In Dark Design.","id":728}, + {"name":"Surface","type":"Portal","wcid":30967,"cell":"002E02D1","place":"dungeon","dest":{"cell":"4AF80023","place":"outdoor","ns":96.72,"ew":-42.35},"desc":"In Feeding Tubes.","id":729}, + {"name":"Surface","type":"Portal","wcid":30967,"cell":"002E0233","place":"dungeon","dest":{"cell":"4AF80023","place":"outdoor","ns":96.72,"ew":-42.35},"desc":"In Feeding Tubes.","id":730}, + {"name":"Surface","type":"Portal","wcid":31042,"cell":"002F010F","place":"dungeon","dest":{"cell":"44F20008","place":"outdoor","ns":92.4,"ew":-47.5},"desc":"In a dungeon (landblock 002F).","id":731}, + {"name":"Surface","type":"Portal","wcid":31293,"cell":"003001AE","place":"dungeon","dest":{"cell":"23800031","place":"outdoor","ns":0.5,"ew":-73.32},"desc":"In Renegade Incursion.","id":732}, + {"name":"Portal to Fort Tethana","type":"Portal","wcid":19131,"cell":"00300186","place":"dungeon","dest":{"cell":"2681001D","place":"outdoor","ns":1.7,"ew":-71.23},"desc":"In Renegade Incursion.","id":733}, + {"name":"Surface","type":"Portal","wcid":31314,"cell":"00310116","place":"dungeon","dest":{"cell":"0F850022","place":"outdoor","ns":4.6,"ew":-89.48},"desc":"In Creepy Canyons.","id":734}, + {"name":"Surface","type":"Portal","wcid":31314,"cell":"003102FC","place":"dungeon","dest":{"cell":"0F850022","place":"outdoor","ns":4.6,"ew":-89.48},"desc":"In Creepy Canyons.","id":735}, + {"name":"Surface","type":"Portal","wcid":31314,"cell":"00310106","place":"dungeon","dest":{"cell":"0F850022","place":"outdoor","ns":4.6,"ew":-89.48},"desc":"In Creepy Canyons.","id":736}, + {"name":"Surface","type":"Portal","wcid":31515,"cell":"00320100","place":"dungeon","dest":{"cell":"06090034","place":"outdoor","ns":-94.44,"ew":-96.54},"desc":"In Tunnel of Love.","id":737}, + {"name":"Surface","type":"Portal","wcid":31515,"cell":"0032022D","place":"dungeon","dest":{"cell":"06090034","place":"outdoor","ns":-94.44,"ew":-96.54},"desc":"In Tunnel of Love.","id":738}, + {"name":"Surface","type":"Portal","wcid":31327,"cell":"003303CB","place":"dungeon","dest":{"cell":"4AF00015","place":"outdoor","ns":90.52,"ew":-42.46},"desc":"In Icy Hideout.","id":739}, + {"name":"Surface","type":"Portal","wcid":31327,"cell":"003301C2","place":"dungeon","dest":{"cell":"4AF00015","place":"outdoor","ns":90.52,"ew":-42.46},"desc":"In Icy Hideout.","id":740}, + {"name":"Surface","type":"Portal","wcid":70010,"cell":"00330145","place":"dungeon","dest":{"cell":"39EF0003","place":"outdoor","ns":89.53,"ew":-56.27},"desc":"In Icy Hideout.","id":741}, + {"name":"Surface","type":"Portal","wcid":70010,"cell":"00330413","place":"dungeon","dest":{"cell":"39EF0003","place":"outdoor","ns":89.53,"ew":-56.27},"desc":"In Icy Hideout.","id":742}, + {"name":"Surface","type":"Portal","wcid":70059,"cell":"003402A3","place":"dungeon","dest":{"cell":"89BD0006","place":"outdoor","ns":49.84,"ew":7.68},"desc":"In a dungeon (landblock 0034).","id":743}, + {"name":"Surface","type":"Portal","wcid":70059,"cell":"00340101","place":"dungeon","dest":{"cell":"89BD0006","place":"outdoor","ns":49.84,"ew":7.68},"desc":"In a dungeon (landblock 0034).","id":744}, + {"name":"Surface","type":"Portal","wcid":31435,"cell":"003501E2","place":"dungeon","dest":{"cell":"D3AE000A","place":"outdoor","ns":37.36,"ew":67.03},"desc":"In a dungeon (landblock 0035).","id":745}, + {"name":"Surface","type":"Portal","wcid":31435,"cell":"00350136","place":"dungeon","dest":{"cell":"D3AE000A","place":"outdoor","ns":37.36,"ew":67.03},"desc":"In a dungeon (landblock 0035).","id":746}, + {"name":"Surface","type":"Portal","wcid":31437,"cell":"00360139","place":"dungeon","dest":{"cell":"7C84001C","place":"outdoor","ns":3.97,"ew":-2.44},"desc":"In a dungeon (landblock 0036).","id":747}, + {"name":"Surface","type":"Portal","wcid":31437,"cell":"003601BE","place":"dungeon","dest":{"cell":"7C84001C","place":"outdoor","ns":3.97,"ew":-2.44},"desc":"In a dungeon (landblock 0036).","id":748}, + {"name":"Surface","type":"Portal","wcid":31433,"cell":"003701AE","place":"dungeon","dest":{"cell":"2CF00016","place":"outdoor","ns":90.6,"ew":-66.55},"desc":"In a dungeon (landblock 0037).","id":749}, + {"name":"Surface","type":"Portal","wcid":31433,"cell":"00370310","place":"dungeon","dest":{"cell":"2CF00016","place":"outdoor","ns":90.6,"ew":-66.55},"desc":"In a dungeon (landblock 0037).","id":750}, + {"name":"Surface","type":"Portal","wcid":31671,"cell":"00380298","place":"dungeon","dest":{"cell":"454A0105","place":"dungeon"},"desc":"In a dungeon (landblock 0038).","id":751}, + {"name":"Surface","type":"Portal","wcid":31671,"cell":"003802EE","place":"dungeon","dest":{"cell":"454A0105","place":"dungeon"},"desc":"In a dungeon (landblock 0038).","id":752}, + {"name":"Surface","type":"Portal","wcid":70058,"cell":"00390210","place":"dungeon","dest":{"cell":"10BB0036","place":"outdoor","ns":48.2,"ew":-88.55},"desc":"In a dungeon (landblock 0039).","id":753}, + {"name":"Surface","type":"Portal","wcid":70058,"cell":"00390149","place":"dungeon","dest":{"cell":"10BB0036","place":"outdoor","ns":48.2,"ew":-88.55},"desc":"In a dungeon (landblock 0039).","id":754}, + {"name":"Surface","type":"Portal","wcid":31885,"cell":"003A0541","place":"dungeon","dest":{"cell":"B3EC001D","place":"outdoor","ns":87.29,"ew":41.58},"desc":"In a dungeon (landblock 003A).","id":755}, + {"name":"Gatekeepers","type":"Portal","wcid":31892,"cell":"003A05B1","place":"dungeon","dest":{"cell":"79110040","place":"outdoor","ns":-87.62,"ew":-4.42},"minLevel":130,"desc":"In a dungeon (landblock 003A).","id":756}, + {"name":"Gatekeepers","type":"Portal","wcid":31892,"cell":"003B0343","place":"dungeon","dest":{"cell":"79110040","place":"outdoor","ns":-87.62,"ew":-4.42},"minLevel":130,"desc":"In a dungeon (landblock 003B).","id":757}, + {"name":"Gatekeepers","type":"Portal","wcid":31892,"cell":"003B01C0","place":"dungeon","dest":{"cell":"79110040","place":"outdoor","ns":-87.62,"ew":-4.42},"minLevel":130,"desc":"In a dungeon (landblock 003B).","id":758}, + {"name":"Gatekeepers","type":"Portal","wcid":31892,"cell":"003B0309","place":"dungeon","dest":{"cell":"79110040","place":"outdoor","ns":-87.62,"ew":-4.42},"minLevel":130,"desc":"In a dungeon (landblock 003B).","id":759}, + {"name":"Gatekeepers","type":"Portal","wcid":31892,"cell":"003B01F8","place":"dungeon","dest":{"cell":"79110040","place":"outdoor","ns":-87.62,"ew":-4.42},"minLevel":130,"desc":"In a dungeon (landblock 003B).","id":760}, + {"name":"Gatekeepers","type":"Portal","wcid":31892,"cell":"003B0355","place":"dungeon","dest":{"cell":"79110040","place":"outdoor","ns":-87.62,"ew":-4.42},"minLevel":130,"desc":"In a dungeon (landblock 003B).","id":761}, + {"name":"Gatekeepers","type":"Portal","wcid":31892,"cell":"003B023A","place":"dungeon","dest":{"cell":"79110040","place":"outdoor","ns":-87.62,"ew":-4.42},"minLevel":130,"desc":"In a dungeon (landblock 003B).","id":762}, + {"name":"Surface","type":"Portal","wcid":1596,"cell":"003C011F","place":"dungeon","dest":{"cell":"C3AB0021","place":"outdoor","ns":34.88,"ew":54.51},"desc":"In a dungeon (landblock 003C).","id":763}, + {"name":"Surface","type":"Portal","wcid":1596,"cell":"003C0231","place":"dungeon","dest":{"cell":"C3AB0021","place":"outdoor","ns":34.88,"ew":54.51},"desc":"In a dungeon (landblock 003C).","id":764}, + {"name":"Surface","type":"Portal","wcid":31884,"cell":"003D0541","place":"dungeon","dest":{"cell":"BFEC0025","place":"outdoor","ns":87.27,"ew":51.27},"desc":"In a dungeon (landblock 003D).","id":765}, + {"name":"Gatekeepers","type":"Portal","wcid":31892,"cell":"003D05B1","place":"dungeon","dest":{"cell":"79110040","place":"outdoor","ns":-87.62,"ew":-4.42},"minLevel":130,"desc":"In a dungeon (landblock 003D).","id":766}, + {"name":"Surface","type":"Portal","wcid":70086,"cell":"003E02EA","place":"dungeon","dest":{"cell":"24BD0007","place":"outdoor","ns":49.88,"ew":-73.14},"desc":"In Breached Hive.","id":767}, + {"name":"Surface","type":"Portal","wcid":32234,"cell":"004002FE","place":"dungeon","dest":{"cell":"4997000F","place":"outdoor","ns":19.46,"ew":-43.43},"desc":"Portal to 19.5N, 43.4W In Master Alizari's Dig.","id":768}, + {"name":"Surface","type":"Portal","wcid":32234,"cell":"00400108","place":"dungeon","dest":{"cell":"4997000F","place":"outdoor","ns":19.46,"ew":-43.43},"desc":"Portal to 19.5N, 43.4W In Master Alizari's Dig.","id":769}, + {"name":"Surface","type":"Portal","wcid":32236,"cell":"00410190","place":"dungeon","dest":{"cell":"36890008","place":"outdoor","ns":8.45,"ew":-58.75},"desc":"Portal Destination 8.4N, 58.7W In Mistress Halmera's Dig.","id":770}, + {"name":"Surface","type":"Portal","wcid":32238,"cell":"00420282","place":"dungeon","dest":{"cell":"10890008","place":"outdoor","ns":8.45,"ew":-89.15},"desc":"Portal Destination 8.4N, 89.1W In Mistress Gabille's Dig.","id":771}, + {"name":"Surface","type":"Portal","wcid":32238,"cell":"00420100","place":"dungeon","dest":{"cell":"10890008","place":"outdoor","ns":8.45,"ew":-89.15},"desc":"Portal Destination 8.4N, 89.1W In Mistress Gabille's Dig.","id":772}, + {"name":"Surface","type":"Portal","wcid":32240,"cell":"00430101","place":"dungeon","dest":{"cell":"1D3A0008","place":"outdoor","ns":-54.75,"ew":-78.75},"desc":"Portal Destination 54.8S, 78.7W In Master Vaserio's Dig.","id":773}, + {"name":"Surface","type":"Portal","wcid":32240,"cell":"0043031B","place":"dungeon","dest":{"cell":"1D3A0008","place":"outdoor","ns":-54.75,"ew":-78.75},"desc":"Portal Destination 54.8S, 78.7W In Master Vaserio's Dig.","id":774}, + {"name":"Collegium Occultus Portal","type":"Portal","wcid":32282,"cell":"004401FD","place":"dungeon","dest":{"cell":"00440201","place":"dungeon"},"minLevel":130,"quest":true,"desc":"You must gain approval from Balior before entering this portal. In a dungeon (landblock 0044).","id":775}, + {"name":"Exit","type":"Portal","wcid":32283,"cell":"004401FE","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 0044).","id":776}, + {"name":"Exit","type":"Portal","wcid":32283,"cell":"00440150","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 0044).","id":777}, + {"name":"Exit","type":"Portal","wcid":32283,"cell":"004401F9","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 0044).","id":778}, + {"name":"Temple South Wing","type":"Portal","wcid":32505,"cell":"00450329","place":"dungeon","dest":{"cell":"0045032A","place":"dungeon","name":"Temple of the Stirring Shadow"},"minLevel":80,"quest":true,"desc":"In Temple of the Stirring Shadow.","id":779}, + {"name":"Temple East Wing","type":"Portal","wcid":32506,"cell":"004503A8","place":"dungeon","dest":{"cell":"00450415","place":"dungeon","name":"Temple of the Stirring Shadow"},"minLevel":80,"quest":true,"desc":"In Temple of the Stirring Shadow.","id":780}, + {"name":"Temple North Wing","type":"Portal","wcid":32509,"cell":"00450323","place":"dungeon","dest":{"cell":"00450322","place":"dungeon","name":"Temple of the Stirring Shadow"},"minLevel":80,"quest":true,"desc":"In Temple of the Stirring Shadow.","id":781}, + {"name":"Surface","type":"Portal","wcid":32507,"cell":"004502A4","place":"dungeon","dest":{"cell":"C8DC003B","place":"outdoor","ns":74.33,"ew":58.8},"desc":"In Temple of the Stirring Shadow.","id":782}, + {"name":"Temple of the Stirring Shadow","type":"Portal","wcid":32508,"cell":"0045032A","place":"dungeon","dest":{"cell":"004502C2","place":"dungeon","name":"Temple of the Stirring Shadow"},"minLevel":80,"quest":true,"desc":"In Temple of the Stirring Shadow.","id":783}, + {"name":"Surface","type":"Portal","wcid":32507,"cell":"004503A4","place":"dungeon","dest":{"cell":"C8DC003B","place":"outdoor","ns":74.33,"ew":58.8},"desc":"In Temple of the Stirring Shadow.","id":784}, + {"name":"Surface","type":"Portal","wcid":32507,"cell":"00450322","place":"dungeon","dest":{"cell":"C8DC003B","place":"outdoor","ns":74.33,"ew":58.8},"desc":"In Temple of the Stirring Shadow.","id":785}, + {"name":"Surface","type":"Portal","wcid":32507,"cell":"0045010B","place":"dungeon","dest":{"cell":"C8DC003B","place":"outdoor","ns":74.33,"ew":58.8},"desc":"In Temple of the Stirring Shadow.","id":786}, + {"name":"Surface","type":"Portal","wcid":32507,"cell":"00450415","place":"dungeon","dest":{"cell":"C8DC003B","place":"outdoor","ns":74.33,"ew":58.8},"desc":"In Temple of the Stirring Shadow.","id":787}, + {"name":"Surface","type":"Portal","wcid":32507,"cell":"00450285","place":"dungeon","dest":{"cell":"C8DC003B","place":"outdoor","ns":74.33,"ew":58.8},"desc":"In Temple of the Stirring Shadow.","id":788}, + {"name":"Surface","type":"Portal","wcid":32516,"cell":"00460103","place":"dungeon","dest":{"cell":"B070001F","place":"outdoor","ns":-11.7,"ew":39.2},"desc":"In a dungeon (landblock 0046).","id":789}, + {"name":"Yanshi Upper Undermine","type":"Portal","wcid":32517,"cell":"0046023E","place":"dungeon","dest":{"cell":"00460242","place":"dungeon"},"minLevel":100,"desc":"In a dungeon (landblock 0046).","id":790}, + {"name":"Yanshi Lower Undermine","type":"Portal","wcid":32518,"cell":"00460241","place":"dungeon","dest":{"cell":"0046010E","place":"dungeon"},"minLevel":100,"quest":true,"desc":"This portal is quest-restricted. Speak with Adrana the Royal Guard in Yanshi for details. In a dungeon (landblock 0046).","id":791}, + {"name":"Surface","type":"Portal","wcid":70756,"cell":"00470319","place":"dungeon","dest":{"cell":"0A0F0027","place":"outdoor","ns":-89.27,"ew":-93.49},"desc":"In Repository.","id":792}, + {"name":"Surface","type":"Portal","wcid":70756,"cell":"0047039C","place":"dungeon","dest":{"cell":"0A0F0027","place":"outdoor","ns":-89.27,"ew":-93.49},"desc":"In Repository.","id":793}, + {"name":"Surface","type":"Portal","wcid":70756,"cell":"004703A4","place":"dungeon","dest":{"cell":"0A0F0027","place":"outdoor","ns":-89.27,"ew":-93.49},"desc":"In Repository.","id":794}, + {"name":"Surface","type":"Portal","wcid":73060,"cell":"0048051A","place":"dungeon","dest":{"cell":"83D9000E","place":"outdoor","ns":72.23,"ew":3.03},"desc":"In Viamontian Direlands Mine.","id":795}, + {"name":"Surface","type":"Portal","wcid":73060,"cell":"00480345","place":"dungeon","dest":{"cell":"83D9000E","place":"outdoor","ns":72.23,"ew":3.03},"desc":"In Viamontian Direlands Mine.","id":796}, + {"name":"Surface","type":"Portal","wcid":73064,"cell":"00480328","place":"dungeon","dest":{"cell":"1F8A003A","place":"outdoor","ns":8.6,"ew":-76.37},"desc":"In Viamontian Direlands Mine.","id":797}, + {"name":"Surface","type":"Portal","wcid":73064,"cell":"00480100","place":"dungeon","dest":{"cell":"1F8A003A","place":"outdoor","ns":8.6,"ew":-76.37},"desc":"In Viamontian Direlands Mine.","id":798}, + {"name":"Surface","type":"Portal","wcid":73069,"cell":"004805D4","place":"dungeon","dest":{"cell":"4FF1001A","place":"outdoor","ns":91.03,"ew":-38.4},"desc":"In Viamontian Direlands Mine.","id":799}, + {"name":"Surface","type":"Portal","wcid":73069,"cell":"004805EA","place":"dungeon","dest":{"cell":"4FF1001A","place":"outdoor","ns":91.03,"ew":-38.4},"desc":"In Viamontian Direlands Mine.","id":800}, + {"name":"Surface","type":"Portal","wcid":70754,"cell":"00490105","place":"dungeon","dest":{"cell":"18300103","place":"building","ns":-63.0,"ew":-82.6},"desc":"In Camp Entemarre.","id":801}, + {"name":"Surface","type":"Portal","wcid":70754,"cell":"004901AF","place":"dungeon","dest":{"cell":"18300103","place":"building","ns":-63.0,"ew":-82.6},"desc":"In Camp Entemarre.","id":802}, + {"name":"Surface Portal","type":"Portal","wcid":4151,"cell":"004A010C","place":"dungeon","dest":{"cell":"341B001D","place":"outdoor","ns":-79.85,"ew":-60.05},"desc":"In Creepy Chambers.","id":803}, + {"name":"Surface Portal","type":"Portal","wcid":4151,"cell":"004A01F4","place":"dungeon","dest":{"cell":"341B001D","place":"outdoor","ns":-79.85,"ew":-60.05},"desc":"In Creepy Chambers.","id":804}, + {"name":"Surface","type":"Portal","wcid":30970,"cell":"004B034E","place":"dungeon","dest":{"cell":"43F1001B","place":"outdoor","ns":91.07,"ew":-47.97},"desc":"In Path of the Blind West.","id":805}, + {"name":"Surface","type":"Portal","wcid":30970,"cell":"004B017F","place":"dungeon","dest":{"cell":"43F1001B","place":"outdoor","ns":91.07,"ew":-47.97},"desc":"In Path of the Blind West.","id":806}, + {"name":"Temple of N'cthail","type":"Portal","wcid":33295,"cell":"004D06E5","place":"dungeon","dest":{"cell":"C3E30019","place":"outdoor","ns":79.69,"ew":54.4},"minLevel":100,"desc":"In Eastern Temple Catacombs.","id":807}, + {"name":"Temple of N'cthail","type":"Portal","wcid":33295,"cell":"004D0131","place":"dungeon","dest":{"cell":"C3E30019","place":"outdoor","ns":79.69,"ew":54.4},"minLevel":100,"desc":"In Eastern Temple Catacombs.","id":808}, + {"name":"Temple of N'cthail","type":"Portal","wcid":33295,"cell":"004D03D6","place":"dungeon","dest":{"cell":"C3E30019","place":"outdoor","ns":79.69,"ew":54.4},"minLevel":100,"desc":"In Eastern Temple Catacombs.","id":809}, + {"name":"Temple of N'cthail","type":"Portal","wcid":33295,"cell":"004D049E","place":"dungeon","dest":{"cell":"C3E30019","place":"outdoor","ns":79.69,"ew":54.4},"minLevel":100,"desc":"In Eastern Temple Catacombs.","id":810}, + {"name":"Vault of Eternal Slumber","type":"Portal","wcid":87128,"cell":"004E080D","place":"dungeon","dest":{"cell":"004E055A","place":"dungeon","name":"Vault of Eternal Slumber"},"minLevel":100,"desc":"In Vault of Eternal Slumber.","id":811}, + {"name":"Temple of N'cthail","type":"Portal","wcid":33295,"cell":"004E0239","place":"dungeon","dest":{"cell":"C3E30019","place":"outdoor","ns":79.69,"ew":54.4},"minLevel":100,"desc":"In Vault of Eternal Slumber.","id":812}, + {"name":"Temple Exit","type":"Portal","wcid":87631,"cell":"004F030D","place":"dungeon","dest":{"cell":"3EF6000C","place":"outdoor","ns":95.23,"ew":-52.17},"desc":"In Temple of the Black Spear.","id":813}, + {"name":"Temple Exit","type":"Portal","wcid":87631,"cell":"004F0143","place":"dungeon","dest":{"cell":"3EF6000C","place":"outdoor","ns":95.23,"ew":-52.17},"desc":"In Temple of the Black Spear.","id":814}, + {"name":"Surface","type":"Portal","wcid":34541,"cell":"00500174","place":"dungeon","dest":{"cell":"65C80019","place":"outdoor","ns":58.1,"ew":-20.8},"desc":"In a dungeon (landblock 0050).","id":815}, + {"name":"Surface","type":"Portal","wcid":34543,"cell":"005001EB","place":"dungeon","dest":{"cell":"B0C00018","place":"outdoor","ns":52.4,"ew":39.1},"desc":"In a dungeon (landblock 0050).","id":816}, + {"name":"Surface","type":"Portal","wcid":34539,"cell":"005003AA","place":"dungeon","dest":{"cell":"84DE0033","place":"outdoor","ns":75.9,"ew":4.3},"desc":"In a dungeon (landblock 0050).","id":817}, + {"name":"Portal Summoning Site","type":"Portal","wcid":34603,"cell":"005106BC","place":"dungeon","dest":{"cell":"A5D30040","place":"outdoor","ns":67.62,"ew":30.79},"desc":"In a dungeon (landblock 0051).","id":818}, + {"name":"Surface","type":"Portal","wcid":32694,"cell":"005201EF","place":"dungeon","dest":{"cell":"27EA001A","place":"outdoor","ns":85.39,"ew":-70.39},"desc":"In Silyun Chapterhouse.","id":819}, + {"name":"Surface","type":"Portal","wcid":32694,"cell":"0052020C","place":"dungeon","dest":{"cell":"27EA001A","place":"outdoor","ns":85.39,"ew":-70.39},"desc":"In Silyun Chapterhouse.","id":820}, + {"name":"Surface","type":"Portal","wcid":80060,"cell":"005303AF","place":"dungeon","dest":{"cell":"112E0102","place":"building","ns":-65.0,"ew":-87.6},"desc":"In Shade Iron Mine.","id":821}, + {"name":"Surface","type":"Portal","wcid":33544,"cell":"00540103","place":"dungeon","dest":{"cell":"C9E40026","place":"outdoor","ns":80.95,"ew":59.3},"minLevel":150,"desc":"In Deep Mukkir Nest.","id":822}, + {"name":"Surface","type":"Portal","wcid":33544,"cell":"00540579","place":"dungeon","dest":{"cell":"C9E40026","place":"outdoor","ns":80.95,"ew":59.3},"minLevel":150,"desc":"In Deep Mukkir Nest.","id":823}, + {"name":"Surface","type":"Portal","wcid":70088,"cell":"005502BD","place":"dungeon","dest":{"cell":"2BB40028","place":"outdoor","ns":42.78,"ew":-67.09},"desc":"In a dungeon (landblock 0055).","id":824}, + {"name":"Surface","type":"Portal","wcid":70088,"cell":"00550292","place":"dungeon","dest":{"cell":"2BB40028","place":"outdoor","ns":42.78,"ew":-67.09},"desc":"In a dungeon (landblock 0055).","id":825}, + {"name":"Surface","type":"Portal","wcid":28710,"cell":"00560123","place":"dungeon","dest":{"cell":"44F60022","place":"outdoor","ns":94.95,"ew":-47.14},"desc":"In a dungeon (landblock 0056).","id":826}, + {"name":"Surface","type":"Portal","wcid":87672,"cell":"005701AE","place":"dungeon","dest":{"cell":"88D20100","place":"dungeon"},"desc":"In a dungeon (landblock 0057).","id":827}, + {"name":"Surface","type":"Portal","wcid":87672,"cell":"00570166","place":"dungeon","dest":{"cell":"88D20100","place":"dungeon"},"desc":"In a dungeon (landblock 0057).","id":828}, + {"name":"Surface","type":"Portal","wcid":87672,"cell":"0057011E","place":"dungeon","dest":{"cell":"88D20100","place":"dungeon"},"desc":"In a dungeon (landblock 0057).","id":829}, + {"name":"Surface","type":"Portal","wcid":87672,"cell":"005701ED","place":"dungeon","dest":{"cell":"88D20100","place":"dungeon"},"desc":"In a dungeon (landblock 0057).","id":830}, + {"name":"Tanada House of Stone","type":"Portal","wcid":87668,"cell":"00570191","place":"dungeon","dest":{"cell":"00570165","place":"dungeon"},"minLevel":80,"quest":true,"desc":"In a dungeon (landblock 0057).","id":831}, + {"name":"Tanada House of Metal","type":"Portal","wcid":87669,"cell":"00570149","place":"dungeon","dest":{"cell":"0057011D","place":"dungeon"},"minLevel":80,"quest":true,"desc":"In a dungeon (landblock 0057).","id":832}, + {"name":"Enlightened Master's Chambers","type":"Portal","wcid":87663,"cell":"00570101","place":"dungeon","dest":{"cell":"005701EC","place":"dungeon"},"minLevel":80,"quest":true,"desc":"In a dungeon (landblock 0057).","id":833}, + {"name":"Surface Portal","type":"Portal","wcid":80046,"cell":"00580399","place":"dungeon","dest":{"cell":"A4A70016","place":"outdoor","ns":32.24,"ew":29.5},"desc":"In a dungeon (landblock 0058).","id":834}, + {"name":"Surface Portal","type":"Portal","wcid":80046,"cell":"0058010C","place":"dungeon","dest":{"cell":"A4A70016","place":"outdoor","ns":32.24,"ew":29.5},"desc":"In a dungeon (landblock 0058).","id":835}, + {"name":"Surface Portal","type":"Portal","wcid":80045,"cell":"00590399","place":"dungeon","dest":{"cell":"9FA6002E","place":"outdoor","ns":31.44,"ew":25.8},"desc":"In a dungeon (landblock 0059).","id":836}, + {"name":"Surface Portal","type":"Portal","wcid":80045,"cell":"0059010C","place":"dungeon","dest":{"cell":"9FA6002E","place":"outdoor","ns":31.44,"ew":25.8},"desc":"In a dungeon (landblock 0059).","id":837}, + {"name":"Surface Portal","type":"Portal","wcid":32557,"cell":"005A0399","place":"dungeon","dest":{"cell":"A2A10014","place":"outdoor","ns":27.24,"ew":27.9},"desc":"In a dungeon (landblock 005A).","id":838}, + {"name":"Surface Portal","type":"Portal","wcid":32557,"cell":"005A010C","place":"dungeon","dest":{"cell":"A2A10014","place":"outdoor","ns":27.24,"ew":27.9},"desc":"In a dungeon (landblock 005A).","id":839}, + {"name":"Bookcase","type":"Portal","wcid":85002,"cell":"005B0285","place":"dungeon","dest":{"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.06},"desc":"In a dungeon (landblock 005B).","id":840}, + {"name":"Bookcase","type":"Portal","wcid":85002,"cell":"005B02D8","place":"dungeon","dest":{"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.06},"desc":"In a dungeon (landblock 005B).","id":841}, + {"name":"Bookcase","type":"Portal","wcid":85002,"cell":"005B0280","place":"dungeon","dest":{"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.06},"desc":"In a dungeon (landblock 005B).","id":842}, + {"name":"Bookcase","type":"Portal","wcid":85002,"cell":"005B01D9","place":"dungeon","dest":{"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.06},"desc":"In a dungeon (landblock 005B).","id":843}, + {"name":"Bookcase","type":"Portal","wcid":85002,"cell":"005B01A7","place":"dungeon","dest":{"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.06},"desc":"In a dungeon (landblock 005B).","id":844}, + {"name":"Bookcase","type":"Portal","wcid":85002,"cell":"005B019E","place":"dungeon","dest":{"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.06},"desc":"In a dungeon (landblock 005B).","id":845}, + {"name":"Bookcase","type":"Portal","wcid":85002,"cell":"005B01D0","place":"dungeon","dest":{"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.06},"desc":"In a dungeon (landblock 005B).","id":846}, + {"name":"Bookcase","type":"Portal","wcid":85002,"cell":"005B010B","place":"dungeon","dest":{"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.06},"desc":"In a dungeon (landblock 005B).","id":847}, + {"name":"Bookcase","type":"Portal","wcid":85002,"cell":"005B0104","place":"dungeon","dest":{"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.06},"desc":"In a dungeon (landblock 005B).","id":848}, + {"name":"Bookcase","type":"Portal","wcid":85002,"cell":"005B011D","place":"dungeon","dest":{"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.06},"desc":"In a dungeon (landblock 005B).","id":849}, + {"name":"Surface","type":"Portal","wcid":73119,"cell":"005C010A","place":"dungeon","dest":{"cell":"700A0032","place":"outdoor","ns":-93.79,"ew":-11.7},"desc":"In a dungeon (landblock 005C).","id":850}, + {"name":"Essence Chambers","type":"Portal","wcid":33247,"cell":"005E0106","place":"dungeon","dest":{"cell":"008C0121","place":"dungeon"},"desc":"In a dungeon (landblock 005E).","id":851}, + {"name":"Harraag's Lair","type":"Portal","wcid":87339,"cell":"006004BC","place":"dungeon","dest":{"cell":"006004BF","place":"dungeon"},"quest":true,"desc":"This portal seems to be warded against those who are not attuned to it. In a dungeon (landblock 0060).","id":852}, + {"name":"Harraag's Lair","type":"Portal","wcid":87341,"cell":"0060010F","place":"dungeon","dest":{"cell":"006004BF","place":"dungeon"},"desc":"In a dungeon (landblock 0060).","id":853}, + {"name":"Surface","type":"Portal","wcid":87342,"cell":"00600147","place":"dungeon","dest":{"cell":"1B340100","place":"building","ns":-60.22,"ew":-80.17},"desc":"In a dungeon (landblock 0060).","id":854}, + {"name":"Surface","type":"Portal","wcid":87342,"cell":"00600421","place":"dungeon","dest":{"cell":"1B340100","place":"building","ns":-60.22,"ew":-80.17},"desc":"In a dungeon (landblock 0060).","id":855}, + {"name":"Portal Summoning Site","type":"Portal","wcid":34603,"cell":"006106BC","place":"dungeon","dest":{"cell":"A5D30040","place":"outdoor","ns":67.62,"ew":30.79},"desc":"In a dungeon (landblock 0061).","id":856}, + {"name":"Portal Summoning Site","type":"Portal","wcid":34603,"cell":"006306BC","place":"dungeon","dest":{"cell":"A5D30040","place":"outdoor","ns":67.62,"ew":30.79},"desc":"In a dungeon (landblock 0063).","id":857}, + {"name":"Surface","type":"Portal","wcid":30965,"cell":"0064036F","place":"dungeon","dest":{"cell":"43F70015","place":"outdoor","ns":96.1,"ew":-48.1},"desc":"In Egg Orchard East.","id":858}, + {"name":"Surface","type":"Portal","wcid":30965,"cell":"00640100","place":"dungeon","dest":{"cell":"43F70015","place":"outdoor","ns":96.1,"ew":-48.1},"desc":"In Egg Orchard East.","id":859}, + {"name":"Surface","type":"Portal","wcid":73055,"cell":"006502C7","place":"dungeon","dest":{"cell":"25E2003D","place":"outdoor","ns":79.29,"ew":-71.61},"minLevel":100,"desc":"In Thrungal Den.","id":860}, + {"name":"Castle Pietrus","type":"Portal","wcid":32712,"cell":"00680102","place":"dungeon","dest":{"cell":"4198012E","place":"building","ns":19.99,"ew":-49.26},"quest":true,"desc":"In Viamontian Laboratory.","id":861}, + {"name":"Surface","type":"Portal","wcid":32711,"cell":"00680187","place":"dungeon","dest":{"cell":"21B00016","place":"outdoor","ns":39.39,"ew":-75.32},"desc":"In Viamontian Laboratory.","id":862}, + {"name":"Surface","type":"Portal","wcid":28710,"cell":"006D0418","place":"dungeon","dest":{"cell":"44F60022","place":"outdoor","ns":94.95,"ew":-47.14},"desc":"In Augmentation Realm Upper Level.","id":863}, + {"name":"Augmentation Realm Lower Level","type":"Portal","wcid":28711,"cell":"006D021F","place":"dungeon","dest":{"cell":"007D0268","place":"dungeon"},"minLevel":125,"quest":true,"desc":"In Augmentation Realm Upper Level.","id":864}, + {"name":"Surface","type":"Portal","wcid":32656,"cell":"006E0372","place":"dungeon","dest":{"cell":"93D30011","place":"outdoor","ns":66.9,"ew":15.9},"desc":"Surface In Empyrean Workshop.","id":865}, + {"name":"Surface","type":"Portal","wcid":32656,"cell":"006E055E","place":"dungeon","dest":{"cell":"93D30011","place":"outdoor","ns":66.9,"ew":15.9},"desc":"Surface In Empyrean Workshop.","id":866}, + {"name":"Atlan's Laboratory","type":"Portal","wcid":80063,"cell":"006E0384","place":"dungeon","dest":{"cell":"006E054C","place":"dungeon","name":"Empyrean Workshop"},"minLevel":125,"quest":true,"desc":"In Empyrean Workshop.","id":867}, + {"name":"Surface","type":"Portal","wcid":32656,"cell":"006E054B","place":"dungeon","dest":{"cell":"93D30011","place":"outdoor","ns":66.9,"ew":15.9},"desc":"Surface In Empyrean Workshop.","id":868}, + {"name":"Surface","type":"Portal","wcid":32656,"cell":"006E057C","place":"dungeon","dest":{"cell":"93D30011","place":"outdoor","ns":66.9,"ew":15.9},"desc":"Surface In Empyrean Workshop.","id":869}, + {"name":"Surface","type":"Portal","wcid":87592,"cell":"007201FE","place":"dungeon","dest":{"cell":"FA220009","place":"outdoor","ns":-74.7,"ew":98.19},"desc":"In a dungeon (landblock 0072).","id":870}, + {"name":"Surface","type":"Portal","wcid":87592,"cell":"0072014E","place":"dungeon","dest":{"cell":"FA220009","place":"outdoor","ns":-74.7,"ew":98.19},"desc":"In a dungeon (landblock 0072).","id":871}, + {"name":"Surface","type":"Portal","wcid":33791,"cell":"0073016B","place":"dungeon","dest":{"cell":"344E0015","place":"outdoor","ns":-39.07,"ew":-60.06},"desc":"In Black Ferah's Vault.","id":872}, + {"name":"Surface","type":"Portal","wcid":33791,"cell":"0073045E","place":"dungeon","dest":{"cell":"344E0015","place":"outdoor","ns":-39.07,"ew":-60.06},"desc":"In Black Ferah's Vault.","id":873}, + {"name":"Surface","type":"Portal","wcid":87576,"cell":"0074052B","place":"dungeon","dest":{"cell":"5BDB0030","place":"outdoor","ns":74.0,"ew":-28.6},"desc":"In Black Spear Temple.","id":874}, + {"name":"Grael's Chamber","type":"Portal","wcid":87574,"cell":"00740527","place":"dungeon","dest":{"cell":"00740586","place":"dungeon","name":"Black Spear Temple"},"maxLevel":100,"quest":true,"desc":"This portal is warded against those who have not earned the right to access the chamber of the Ruschk Aspect of Grael. In Black Spear Temple.","id":875}, + {"name":"Grael's Chamber","type":"Portal","wcid":87573,"cell":"0074010E","place":"dungeon","dest":{"cell":"00740586","place":"dungeon","name":"Black Spear Temple"},"maxLevel":100,"desc":"This portal is warded against those who have not earned the right to access the chamber of the Ruschk Aspect of Grael. In Black Spear Temple.","id":876}, + {"name":"Trophy Room","type":"Portal","wcid":87575,"cell":"0074054E","place":"dungeon","dest":{"cell":"00740549","place":"dungeon","name":"Black Spear Temple"},"desc":"In Black Spear Temple.","id":877}, + {"name":"Surface","type":"Portal","wcid":87576,"cell":"0074053B","place":"dungeon","dest":{"cell":"5BDB0030","place":"outdoor","ns":74.0,"ew":-28.6},"desc":"In Black Spear Temple.","id":878}, + {"name":"Surface","type":"Portal","wcid":87597,"cell":"00750476","place":"dungeon","dest":{"cell":"F41F002B","place":"outdoor","ns":-76.88,"ew":93.79},"desc":"In Grael's Chamber.","id":879}, + {"name":"Surface","type":"Portal","wcid":87597,"cell":"0075046D","place":"dungeon","dest":{"cell":"F41F002B","place":"outdoor","ns":-76.88,"ew":93.79},"desc":"In Grael's Chamber.","id":880}, + {"name":"Surface","type":"Portal","wcid":87597,"cell":"00750469","place":"dungeon","dest":{"cell":"F41F002B","place":"outdoor","ns":-76.88,"ew":93.79},"desc":"In Grael's Chamber.","id":881}, + {"name":"Surface","type":"Portal","wcid":87597,"cell":"0075046E","place":"dungeon","dest":{"cell":"F41F002B","place":"outdoor","ns":-76.88,"ew":93.79},"desc":"In Grael's Chamber.","id":882}, + {"name":"Surface","type":"Portal","wcid":87597,"cell":"00750470","place":"dungeon","dest":{"cell":"F41F002B","place":"outdoor","ns":-76.88,"ew":93.79},"desc":"In Grael's Chamber.","id":883}, + {"name":"Grael's Chamber","type":"Portal","wcid":33784,"cell":"00750472","place":"dungeon","dest":{"cell":"007504C6","place":"dungeon","name":"Grael's Chamber"},"quest":true,"desc":"This portal is warded against those who have not earned the right to access the chamber of the Shadow Aspect of Grael. In Grael's Chamber.","id":884}, + {"name":"Grael's Chamber","type":"Portal","wcid":87598,"cell":"0075010E","place":"dungeon","dest":{"cell":"007504C6","place":"dungeon","name":"Grael's Chamber"},"desc":"In Grael's Chamber.","id":885}, + {"name":"Trophy Room","type":"Portal","wcid":87600,"cell":"00750481","place":"dungeon","dest":{"cell":"0075047C","place":"dungeon","name":"Grael's Chamber"},"desc":"In Grael's Chamber.","id":886}, + {"name":"Surface","type":"Portal","wcid":33790,"cell":"0076046E","place":"dungeon","dest":{"cell":"2C50000F","place":"outdoor","ns":-37.29,"ew":-66.63},"desc":"In Mukkir-Infested Black Spear Temple.","id":887}, + {"name":"Grael's Chamber","type":"Portal","wcid":33789,"cell":"0076010E","place":"dungeon","dest":{"cell":"007604D0","place":"dungeon","name":"Mukkir-Infested Black Spear Temple"},"minLevel":151,"desc":"In Mukkir-Infested Black Spear Temple.","id":888}, + {"name":"Grael's Chamber","type":"Portal","wcid":33772,"cell":"0076046A","place":"dungeon","dest":{"cell":"007604D0","place":"dungeon","name":"Mukkir-Infested Black Spear Temple"},"minLevel":151,"quest":true,"desc":"This portal is warded against those who have not earned the right to access the chamber of the Mukkir Aspect of Grael. In Mukkir-Infested Black Spear Temple.","id":889}, + {"name":"Surface","type":"Portal","wcid":33790,"cell":"00760486","place":"dungeon","dest":{"cell":"2C50000F","place":"outdoor","ns":-37.29,"ew":-66.63},"desc":"In Mukkir-Infested Black Spear Temple.","id":890}, + {"name":"Trophy Room","type":"Portal","wcid":33874,"cell":"007604A6","place":"dungeon","dest":{"cell":"00760488","place":"dungeon","name":"Mukkir-Infested Black Spear Temple"},"desc":"In Mukkir-Infested Black Spear Temple.","id":891}, + {"name":"Cavern Exit","type":"Portal","wcid":87333,"cell":"00770556","place":"dungeon","dest":{"cell":"009C01D2","place":"dungeon"},"desc":"In a dungeon (landblock 0077).","id":892}, + {"name":"Cavern Exit","type":"Portal","wcid":87333,"cell":"007703B5","place":"dungeon","dest":{"cell":"009C01D2","place":"dungeon"},"desc":"In a dungeon (landblock 0077).","id":893}, + {"name":"Cavern Exit","type":"Portal","wcid":87333,"cell":"0077035F","place":"dungeon","dest":{"cell":"009C01D2","place":"dungeon"},"desc":"In a dungeon (landblock 0077).","id":894}, + {"name":"Cavern Exit","type":"Portal","wcid":87333,"cell":"00770111","place":"dungeon","dest":{"cell":"009C01D2","place":"dungeon"},"desc":"In a dungeon (landblock 0077).","id":895}, + {"name":"Cavern Exit","type":"Portal","wcid":87312,"cell":"00780556","place":"dungeon","dest":{"cell":"00D2015C","place":"dungeon"},"desc":"In a dungeon (landblock 0078).","id":896}, + {"name":"Cavern Exit","type":"Portal","wcid":87312,"cell":"007803B5","place":"dungeon","dest":{"cell":"00D2015C","place":"dungeon"},"desc":"In a dungeon (landblock 0078).","id":897}, + {"name":"Cavern Exit","type":"Portal","wcid":87312,"cell":"0078035F","place":"dungeon","dest":{"cell":"00D2015C","place":"dungeon"},"desc":"In a dungeon (landblock 0078).","id":898}, + {"name":"Cavern Exit","type":"Portal","wcid":87312,"cell":"00780111","place":"dungeon","dest":{"cell":"00D2015C","place":"dungeon"},"desc":"In a dungeon (landblock 0078).","id":899}, + {"name":"Cavern Exit","type":"Portal","wcid":87315,"cell":"00790556","place":"dungeon","dest":{"cell":"00D3015C","place":"dungeon"},"desc":"In a dungeon (landblock 0079).","id":900}, + {"name":"Cavern Exit","type":"Portal","wcid":87315,"cell":"007903B5","place":"dungeon","dest":{"cell":"00D3015C","place":"dungeon"},"desc":"In a dungeon (landblock 0079).","id":901}, + {"name":"Cavern Exit","type":"Portal","wcid":87315,"cell":"0079035F","place":"dungeon","dest":{"cell":"00D3015C","place":"dungeon"},"desc":"In a dungeon (landblock 0079).","id":902}, + {"name":"Cavern Exit","type":"Portal","wcid":87315,"cell":"00790111","place":"dungeon","dest":{"cell":"00D3015C","place":"dungeon"},"desc":"In a dungeon (landblock 0079).","id":903}, + {"name":"Cavern Exit","type":"Portal","wcid":34768,"cell":"007A0111","place":"dungeon","dest":{"cell":"00D4015C","place":"dungeon"},"desc":"In a dungeon (landblock 007A).","id":904}, + {"name":"Cavern Exit","type":"Portal","wcid":34768,"cell":"007A0556","place":"dungeon","dest":{"cell":"00D4015C","place":"dungeon"},"desc":"In a dungeon (landblock 007A).","id":905}, + {"name":"Cavern Exit","type":"Portal","wcid":34768,"cell":"007A03B7","place":"dungeon","dest":{"cell":"00D4015C","place":"dungeon"},"desc":"In a dungeon (landblock 007A).","id":906}, + {"name":"Cavern Exit","type":"Portal","wcid":34768,"cell":"007A035F","place":"dungeon","dest":{"cell":"00D4015C","place":"dungeon"},"desc":"In a dungeon (landblock 007A).","id":907}, + {"name":"Surface","type":"Portal","wcid":87641,"cell":"007B011E","place":"dungeon","dest":{"cell":"B82A0013","place":"outdoor","ns":-68.11,"ew":45.5},"desc":"In Tanada House of Storms.","id":908}, + {"name":"Surface","type":"Portal","wcid":87641,"cell":"007B01AE","place":"dungeon","dest":{"cell":"B82A0013","place":"outdoor","ns":-68.11,"ew":45.5},"desc":"In Tanada House of Storms.","id":909}, + {"name":"Surface","type":"Portal","wcid":87641,"cell":"007B0166","place":"dungeon","dest":{"cell":"B82A0013","place":"outdoor","ns":-68.11,"ew":45.5},"desc":"In Tanada House of Storms.","id":910}, + {"name":"Surface","type":"Portal","wcid":87641,"cell":"007B01ED","place":"dungeon","dest":{"cell":"B82A0013","place":"outdoor","ns":-68.11,"ew":45.5},"desc":"In Tanada House of Storms.","id":911}, + {"name":"Tanada House of Wind","type":"Portal","wcid":87642,"cell":"007B0101","place":"dungeon","dest":{"cell":"007B01AD","place":"dungeon","name":"Tanada House of Storms"},"minLevel":80,"quest":true,"desc":"In Tanada House of Storms.","id":912}, + {"name":"Tanada House of Breath","type":"Portal","wcid":87643,"cell":"007B0191","place":"dungeon","dest":{"cell":"007B0165","place":"dungeon","name":"Tanada House of Storms"},"minLevel":80,"quest":true,"desc":"In Tanada House of Storms.","id":913}, + {"name":"Enlightened Master's Chambers","type":"Portal","wcid":87644,"cell":"007B0149","place":"dungeon","dest":{"cell":"007B01EC","place":"dungeon","name":"Tanada House of Storms"},"minLevel":80,"quest":true,"desc":"In Tanada House of Storms.","id":914}, + {"name":"Soul Hunter's Chambers","type":"Portal","wcid":34319,"cell":"007C0144","place":"dungeon","dest":{"cell":"007C02C1","place":"dungeon","name":"Soul Hunter's Lair"},"minLevel":60,"quest":true,"desc":"This portal offers a direct gateway into the chambers of the Falatacot Soul Hunter, but it seems that you must gain the approval of the nearby altar to enter... In Soul Hunter's Lair.","id":915}, + {"name":"Surface","type":"Portal","wcid":34320,"cell":"007C02B4","place":"dungeon","dest":{"cell":"C55C000F","place":"outdoor","ns":-27.7,"ew":55.8},"desc":"In Soul Hunter's Lair.","id":916}, + {"name":"Surface","type":"Portal","wcid":34320,"cell":"007C02B8","place":"dungeon","dest":{"cell":"C55C000F","place":"outdoor","ns":-27.7,"ew":55.8},"desc":"In Soul Hunter's Lair.","id":917}, + {"name":"Augmentation Realm Main Level","type":"Portal","wcid":30060,"cell":"007D012A","place":"dungeon","dest":{"cell":"0056036D","place":"dungeon"},"minLevel":125,"quest":true,"desc":"You must speak with Fiun Rehlyun before you can use this portal. In a dungeon (landblock 007D).","id":918}, + {"name":"Augmentation Realm Main Level","type":"Portal","wcid":30059,"cell":"007D012E","place":"dungeon","dest":{"cell":"005604AA","place":"dungeon"},"minLevel":125,"quest":true,"desc":"You must speak with Fiun Rehlyun before you can use this portal. In a dungeon (landblock 007D).","id":919}, + {"name":"Augmentation Realm Main Level","type":"Portal","wcid":30058,"cell":"007D012F","place":"dungeon","dest":{"cell":"00560261","place":"dungeon"},"minLevel":125,"quest":true,"desc":"You must speak with Fiun Rehlyun before you can use this portal. In a dungeon (landblock 007D).","id":920}, + {"name":"Augmentation Realm Main Level","type":"Portal","wcid":30057,"cell":"007D012D","place":"dungeon","dest":{"cell":"00560459","place":"dungeon"},"minLevel":125,"quest":true,"desc":"You must speak with Fiun Rehlyun before you can use this portal. In a dungeon (landblock 007D).","id":921}, + {"name":"Augmentation Realm Main Level","type":"Portal","wcid":30056,"cell":"007D011F","place":"dungeon","dest":{"cell":"005601C6","place":"dungeon"},"minLevel":125,"quest":true,"desc":"You must speak with Fiun Rehlyun before you can use this portal. In a dungeon (landblock 007D).","id":922}, + {"name":"Augmentation Realm Main Level","type":"Portal","wcid":30062,"cell":"007D0111","place":"dungeon","dest":{"cell":"0056030F","place":"dungeon"},"minLevel":125,"quest":true,"desc":"You must speak with Fiun Rehlyun before you can use this portal. In a dungeon (landblock 007D).","id":923}, + {"name":"Augmentation Realm Main Level","type":"Portal","wcid":30059,"cell":"007D0101","place":"dungeon","dest":{"cell":"005604AA","place":"dungeon"},"minLevel":125,"quest":true,"desc":"You must speak with Fiun Rehlyun before you can use this portal. In a dungeon (landblock 007D).","id":924}, + {"name":"Augmentation Realm Main Level","type":"Portal","wcid":30057,"cell":"007D0100","place":"dungeon","dest":{"cell":"00560459","place":"dungeon"},"minLevel":125,"quest":true,"desc":"You must speak with Fiun Rehlyun before you can use this portal. In a dungeon (landblock 007D).","id":925}, + {"name":"Augmentation Realm Main Level","type":"Portal","wcid":30056,"cell":"007D010E","place":"dungeon","dest":{"cell":"005601C6","place":"dungeon"},"minLevel":125,"quest":true,"desc":"You must speak with Fiun Rehlyun before you can use this portal. In a dungeon (landblock 007D).","id":926}, + {"name":"Surface","type":"Portal","wcid":33018,"cell":"007E010D","place":"dungeon","dest":{"cell":"2C290037","place":"outdoor","ns":-68.5,"ew":-66.1},"desc":"In a dungeon (landblock 007E).","id":927}, + {"name":"Surface","type":"Portal","wcid":33018,"cell":"007E022A","place":"dungeon","dest":{"cell":"2C290037","place":"outdoor","ns":-68.5,"ew":-66.1},"desc":"In a dungeon (landblock 007E).","id":928}, + {"name":"Surface","type":"Portal","wcid":33018,"cell":"007E0240","place":"dungeon","dest":{"cell":"2C290037","place":"outdoor","ns":-68.5,"ew":-66.1},"desc":"In a dungeon (landblock 007E).","id":929}, + {"name":"Surface","type":"Portal","wcid":33018,"cell":"007E0357","place":"dungeon","dest":{"cell":"2C290037","place":"outdoor","ns":-68.5,"ew":-66.1},"desc":"In a dungeon (landblock 007E).","id":930}, + {"name":"Surface","type":"Portal","wcid":87532,"cell":"007F02EC","place":"dungeon","dest":{"cell":"31D60154","place":"building","ns":69.61,"ew":-62.7},"desc":"In Dardante's Workshop.","id":931}, + {"name":"Surface","type":"Portal","wcid":87532,"cell":"007F0196","place":"dungeon","dest":{"cell":"31D60154","place":"building","ns":69.61,"ew":-62.7},"desc":"In Dardante's Workshop.","id":932}, + {"name":"Summoning Chamber","type":"Portal","wcid":87533,"cell":"007F018B","place":"dungeon","dest":{"cell":"007F018A","place":"dungeon","name":"Dardante's Workshop"},"quest":true,"desc":"In Dardante's Workshop.","id":933}, + {"name":"Surface","type":"Portal","wcid":87532,"cell":"007F0146","place":"dungeon","dest":{"cell":"31D60154","place":"building","ns":69.61,"ew":-62.7},"desc":"In Dardante's Workshop.","id":934}, + {"name":"Binding Realm","type":"Portal","wcid":87534,"cell":"007F0123","place":"dungeon","dest":{"cell":"007F01B5","place":"dungeon","name":"Dardante's Workshop"},"quest":true,"desc":"In Dardante's Workshop.","id":935}, + {"name":"Portal to Hebian-To","type":"Portal","wcid":42846,"cell":"00800141","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal goes to the Sho capital, Hebian-To. This is a good town for characters over level 10. In Rossu Morta Chapterhouse.","id":936}, + {"name":"Ayan Baqur Portal","type":"Portal","wcid":7194,"cell":"00800144","place":"dungeon","dest":{"cell":"1133001F","place":"outdoor","ns":-60.46,"ew":-87.98},"desc":"In Rossu Morta Chapterhouse.","id":937}, + {"name":"Portal to Sanamar","type":"Portal","wcid":42835,"cell":"00800158","place":"dungeon","dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"desc":"This portal goes to Sanamar, the capital of New Viamont and town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Rossu Morta Chapterhouse.","id":938}, + {"name":"Qalaba'r Portal","type":"Portal","wcid":42833,"cell":"00800161","place":"dungeon","dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"desc":"This portal leads to Qalaba'r, the Gharu'ndim village on the edge of the Linvak Mountain Range. This is a good town for characters over level 30. In Rossu Morta Chapterhouse.","id":939}, + {"name":"Portal to Cragstone","type":"Portal","wcid":42818,"cell":"00800164","place":"dungeon","dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal goes to the Aluvian capital, Cragstone. This is a good town for characters over level 10. In Rossu Morta Chapterhouse.","id":940}, + {"name":"Portal to Hebian-To","type":"Portal","wcid":42846,"cell":"00810141","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal goes to the Sho capital, Hebian-To. This is a good town for characters over level 10. In Whispering Blade Chapterhouse.","id":941}, + {"name":"Ayan Baqur Portal","type":"Portal","wcid":7194,"cell":"00810144","place":"dungeon","dest":{"cell":"1133001F","place":"outdoor","ns":-60.46,"ew":-87.98},"desc":"In Whispering Blade Chapterhouse.","id":942}, + {"name":"Portal to Silyun","type":"Portal","wcid":42998,"cell":"00810158","place":"dungeon","dest":{"cell":"26EC003D","place":"outdoor","ns":87.31,"ew":-70.82},"desc":"This portal goes to Silyun, the home of the remnants of the Bellenesse rebels. This is a good town for characters over level 40. In Whispering Blade Chapterhouse.","id":943}, + {"name":"Qalaba'r Portal","type":"Portal","wcid":42833,"cell":"00810161","place":"dungeon","dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"desc":"This portal leads to Qalaba'r, the Gharu'ndim village on the edge of the Linvak Mountain Range. This is a good town for characters over level 30. In Whispering Blade Chapterhouse.","id":944}, + {"name":"Portal to Cragstone","type":"Portal","wcid":42818,"cell":"00810164","place":"dungeon","dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal goes to the Aluvian capital, Cragstone. This is a good town for characters over level 10. In Whispering Blade Chapterhouse.","id":945}, + {"name":"Surface","type":"Portal","wcid":87540,"cell":"00820186","place":"dungeon","dest":{"cell":"1A3B0100","place":"dungeon"},"desc":"In a dungeon (landblock 0082).","id":946}, + {"name":"Surface","type":"Portal","wcid":87540,"cell":"0082022C","place":"dungeon","dest":{"cell":"1A3B0100","place":"dungeon"},"desc":"In a dungeon (landblock 0082).","id":947}, + {"name":"Surface","type":"Portal","wcid":33254,"cell":"00830106","place":"dungeon","dest":{"cell":"2134002E","place":"outdoor","ns":-59.84,"ew":-75.03},"desc":"In Pheraion's Sanctum.","id":948}, + {"name":"Surface","type":"Portal","wcid":33254,"cell":"0083026F","place":"dungeon","dest":{"cell":"2134002E","place":"outdoor","ns":-59.84,"ew":-75.03},"desc":"In Pheraion's Sanctum.","id":949}, + {"name":"Surface","type":"Portal","wcid":33480,"cell":"0084010B","place":"dungeon","dest":{"cell":"D7DE0102","place":"underground","ns":75.8,"ew":70.45},"desc":"In a dungeon (landblock 0084).","id":950}, + {"name":"Surface","type":"Portal","wcid":33480,"cell":"00840212","place":"dungeon","dest":{"cell":"D7DE0102","place":"underground","ns":75.8,"ew":70.45},"desc":"In a dungeon (landblock 0084).","id":951}, + {"name":"Surface","type":"Portal","wcid":33517,"cell":"0085014A","place":"dungeon","dest":{"cell":"D7DE000A","place":"outdoor","ns":75.8,"ew":70.19},"desc":"In Altar Nest.","id":952}, + {"name":"Rix Zilik","type":"Portal","wcid":87635,"cell":"00870353","place":"dungeon","dest":{"cell":"6DD70016","place":"outdoor","ns":70.6,"ew":-14.5},"desc":"In Ikzisik Tika Ri Zikma.","id":953}, + {"name":"Surface","type":"Portal","wcid":1091,"cell":"0088037B","place":"dungeon","dest":{"cell":"D8CA0014","place":"outdoor","ns":60.03,"ew":71.09},"desc":"In a dungeon (landblock 0088).","id":954}, + {"name":"Surface","type":"Portal","wcid":32678,"cell":"00890150","place":"dungeon","dest":{"cell":"BE720015","place":"outdoor","ns":-10.3,"ew":50.3},"desc":"In a dungeon (landblock 0089).","id":955}, + {"name":"Surface","type":"Portal","wcid":32678,"cell":"008901E7","place":"dungeon","dest":{"cell":"BE720015","place":"outdoor","ns":-10.3,"ew":50.3},"desc":"In a dungeon (landblock 0089).","id":956}, + {"name":"Surface","type":"Portal","wcid":32678,"cell":"00890224","place":"dungeon","dest":{"cell":"BE720015","place":"outdoor","ns":-10.3,"ew":50.3},"desc":"In a dungeon (landblock 0089).","id":957}, + {"name":"Surface","type":"Portal","wcid":32678,"cell":"00890113","place":"dungeon","dest":{"cell":"BE720015","place":"outdoor","ns":-10.3,"ew":50.3},"desc":"In a dungeon (landblock 0089).","id":958}, + {"name":"Surface","type":"Portal","wcid":33035,"cell":"008B0190","place":"dungeon","dest":{"cell":"BAED003D","place":"outdoor","ns":88.13,"ew":47.63},"desc":"In Ancient Masonry.","id":959}, + {"name":"Surface","type":"Portal","wcid":33035,"cell":"008B01BC","place":"dungeon","dest":{"cell":"BAED003D","place":"outdoor","ns":88.13,"ew":47.63},"desc":"In Ancient Masonry.","id":960}, + {"name":"Surface","type":"Portal","wcid":35503,"cell":"00950105","place":"dungeon","dest":{"cell":"482E0121","place":"building","ns":-64.68,"ew":-43.9},"desc":"In a dungeon (landblock 0095).","id":961}, + {"name":"Surface","type":"Portal","wcid":28801,"cell":"00960323","place":"dungeon","dest":{"cell":"43F9001A","place":"outdoor","ns":97.39,"ew":-48.03},"desc":"In Insatiable Vault.","id":962}, + {"name":"Surface","type":"Portal","wcid":28801,"cell":"00960326","place":"dungeon","dest":{"cell":"43F9001A","place":"outdoor","ns":97.39,"ew":-48.03},"desc":"In Insatiable Vault.","id":963}, + {"name":"Surface","type":"Portal","wcid":28801,"cell":"00960100","place":"dungeon","dest":{"cell":"43F9001A","place":"outdoor","ns":97.39,"ew":-48.03},"desc":"In Insatiable Vault.","id":964}, + {"name":"Surface","type":"Portal","wcid":33910,"cell":"00980142","place":"dungeon","dest":{"cell":"C7EB000E","place":"outdoor","ns":86.58,"ew":57.39},"desc":"In a dungeon (landblock 0098).","id":965}, + {"name":"Surface","type":"Portal","wcid":33910,"cell":"009801BD","place":"dungeon","dest":{"cell":"C7EB000E","place":"outdoor","ns":86.58,"ew":57.39},"desc":"In a dungeon (landblock 0098).","id":966}, + {"name":"Surface","type":"Portal","wcid":87616,"cell":"0099011C","place":"dungeon","dest":{"cell":"090B0002","place":"outdoor","ns":-93.04,"ew":-94.7},"desc":"In a dungeon (landblock 0099).","id":967}, + {"name":"Surface","type":"Portal","wcid":87616,"cell":"009901E2","place":"dungeon","dest":{"cell":"090B0002","place":"outdoor","ns":-93.04,"ew":-94.7},"desc":"In a dungeon (landblock 0099).","id":968}, + {"name":"Surface","type":"Portal","wcid":87624,"cell":"009A02D1","place":"dungeon","dest":{"cell":"42EC0020","place":"outdoor","ns":87.55,"ew":-48.81},"desc":"In a dungeon (landblock 009A).","id":969}, + {"name":"Surface","type":"Portal","wcid":87624,"cell":"009A0107","place":"dungeon","dest":{"cell":"42EC0020","place":"outdoor","ns":87.55,"ew":-48.81},"desc":"In a dungeon (landblock 009A).","id":970}, + {"name":"Surface","type":"Portal","wcid":70011,"cell":"009B021D","place":"dungeon","dest":{"cell":"898E002E","place":"outdoor","ns":12.2,"ew":8.18},"desc":"In a dungeon (landblock 009B).","id":971}, + {"name":"Surface","type":"Portal","wcid":70011,"cell":"009B010B","place":"dungeon","dest":{"cell":"898E002E","place":"outdoor","ns":12.2,"ew":8.18},"desc":"In a dungeon (landblock 009B).","id":972}, + {"name":"Kor-Gursha","type":"Portal","wcid":34844,"cell":"009C0244","place":"dungeon","dest":{"cell":"009C0247","place":"dungeon"},"desc":"In a dungeon (landblock 009C).","id":973}, + {"name":"Dereth","type":"Portal","wcid":34845,"cell":"009C0330","place":"dungeon","dest":{"cell":"A5D30026","place":"outdoor","ns":67.36,"ew":30.5},"desc":"In a dungeon (landblock 009C).","id":974}, + {"name":"Muggy Guruk Caverns","type":"Portal","wcid":34771,"cell":"009C01D2","place":"dungeon","dest":{"cell":"0077055C","place":"dungeon"},"minLevel":1,"maxLevel":40,"desc":"In a dungeon (landblock 009C).","id":975}, + {"name":"Northern Catacombs","type":"Portal","wcid":34829,"cell":"009C01F4","place":"dungeon","dest":{"cell":"00D20535","place":"dungeon"},"desc":"In a dungeon (landblock 009C).","id":976}, + {"name":"Southern Catacombs","type":"Portal","wcid":34827,"cell":"009C01F9","place":"dungeon","dest":{"cell":"00D40535","place":"dungeon"},"desc":"In a dungeon (landblock 009C).","id":977}, + {"name":"Eastern Catacombs","type":"Portal","wcid":34831,"cell":"009C01FB","place":"dungeon","dest":{"cell":"00D30535","place":"dungeon"},"desc":"In a dungeon (landblock 009C).","id":978}, + {"name":"Dereth","type":"Portal","wcid":34845,"cell":"009C0173","place":"dungeon","dest":{"cell":"A5D30026","place":"outdoor","ns":67.36,"ew":30.5},"desc":"In a dungeon (landblock 009C).","id":979}, + {"name":"Cavern Exit","type":"Portal","wcid":87322,"cell":"009D0147","place":"dungeon","dest":{"cell":"00D3045F","place":"dungeon"},"desc":"In a dungeon (landblock 009D).","id":980}, + {"name":"Cavern Exit","type":"Portal","wcid":87322,"cell":"009D02D2","place":"dungeon","dest":{"cell":"00D3045F","place":"dungeon"},"desc":"In a dungeon (landblock 009D).","id":981}, + {"name":"Surface","type":"Portal","wcid":87677,"cell":"009E021A","place":"dungeon","dest":{"cell":"7814000F","place":"outdoor","ns":-85.31,"ew":-5.83},"desc":"In Tanada House of Water.","id":982}, + {"name":"Surface","type":"Portal","wcid":87677,"cell":"009E0132","place":"dungeon","dest":{"cell":"7814000F","place":"outdoor","ns":-85.31,"ew":-5.83},"desc":"In Tanada House of Water.","id":983}, + {"name":"Return to Linvak Tukal","type":"Portal","wcid":35484,"cell":"009F022E","place":"dungeon","dest":{"cell":"A21E001A","place":"outdoor","ns":-77.78,"ew":28.0},"desc":"In a dungeon (landblock 009F).","id":984}, + {"name":"Return to Linvak Tukal","type":"Portal","wcid":35484,"cell":"009F0201","place":"dungeon","dest":{"cell":"A21E001A","place":"outdoor","ns":-77.78,"ew":28.0},"desc":"In a dungeon (landblock 009F).","id":985}, + {"name":"Return to Linvak Tukal","type":"Portal","wcid":35484,"cell":"009F0100","place":"dungeon","dest":{"cell":"A21E001A","place":"outdoor","ns":-77.78,"ew":28.0},"desc":"In a dungeon (landblock 009F).","id":986}, + {"name":"Trials Graduation Portal","type":"Portal","wcid":36697,"cell":"009F010C","place":"dungeon","dest":{"cell":"009F010B","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 009F).","id":987}, + {"name":"Return to Linvak Tukal","type":"Portal","wcid":35484,"cell":"009F011B","place":"dungeon","dest":{"cell":"A21E001A","place":"outdoor","ns":-77.78,"ew":28.0},"desc":"In a dungeon (landblock 009F).","id":988}, + {"name":"Return to Linvak Tukal","type":"Portal","wcid":35484,"cell":"009F0173","place":"dungeon","dest":{"cell":"A21E001A","place":"outdoor","ns":-77.78,"ew":28.0},"desc":"In a dungeon (landblock 009F).","id":989}, + {"name":"Trial of the Mind","type":"Portal","wcid":36701,"cell":"009F01A8","place":"dungeon","dest":{"cell":"009F017E","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 009F).","id":990}, + {"name":"Return to Linvak Tukal","type":"Portal","wcid":35484,"cell":"009F01CF","place":"dungeon","dest":{"cell":"A21E001A","place":"outdoor","ns":-77.78,"ew":28.0},"desc":"In a dungeon (landblock 009F).","id":991}, + {"name":"Trials of the Arm, Mind and Heart","type":"Portal","wcid":36698,"cell":"009F0217","place":"dungeon","dest":{"cell":"009F0216","place":"dungeon"},"desc":"In a dungeon (landblock 009F).","id":992}, + {"name":"Return to Linvak Tukal","type":"Portal","wcid":35484,"cell":"009F024A","place":"dungeon","dest":{"cell":"A21E001A","place":"outdoor","ns":-77.78,"ew":28.0},"desc":"In a dungeon (landblock 009F).","id":993}, + {"name":"Trial of the Arm","type":"Portal","wcid":36699,"cell":"009F01EC","place":"dungeon","dest":{"cell":"009F01D3","place":"dungeon"},"desc":"In a dungeon (landblock 009F).","id":994}, + {"name":"Surface","type":"Portal","wcid":36612,"cell":"00A4029E","place":"dungeon","dest":{"cell":"5DD30024","place":"outdoor","ns":67.2,"ew":-27.11},"desc":"In Hidden Laboratory.","id":995}, + {"name":"Surface","type":"Portal","wcid":87079,"cell":"00A50242","place":"dungeon","dest":{"cell":"10380100","place":"building","ns":-56.7,"ew":-88.44},"desc":"In Lonely Fortress.","id":996}, + {"name":"Surface","type":"Portal","wcid":87079,"cell":"00A5010B","place":"dungeon","dest":{"cell":"10380100","place":"building","ns":-56.7,"ew":-88.44},"desc":"In Lonely Fortress.","id":997}, + {"name":"Surface Portal","type":"Portal","wcid":8851,"cell":"00A70104","place":"dungeon","dest":{"cell":"7F7F001C","place":"outdoor","ns":-0.01,"ew":-0.01},"desc":"In a dungeon (landblock 00A7).","id":998}, + {"name":"Surface","type":"Portal","wcid":36935,"cell":"00A702AF","place":"dungeon","dest":{"cell":"F4180009","place":"outdoor","ns":-82.72,"ew":93.41},"desc":"In a dungeon (landblock 00A7).","id":999}, + {"name":"Exit","type":"Portal","wcid":73252,"cell":"00A80107","place":"dungeon","dest":{"cell":"EC0E002D","place":"outdoor","ns":-90.29,"ew":87.35},"desc":"In Roots of the Deru Tree.","id":1000}, + {"name":"Exit","type":"Portal","wcid":73248,"cell":"00A9020A","place":"dungeon","dest":{"cell":"C6EA003A","place":"outdoor","ns":85.44,"ew":57.15},"desc":"In Trial of the Deep.","id":1001}, + {"name":"Exit","type":"Portal","wcid":73245,"cell":"00AA0268","place":"dungeon","dest":{"cell":"CDB6003E","place":"outdoor","ns":44.2,"ew":62.8},"desc":"In Olthoi Sanctuary.","id":1002}, + {"name":"Surface","type":"Portal","wcid":80100,"cell":"00AB028A","place":"dungeon","dest":{"cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9},"desc":"In a dungeon (landblock 00AB).","id":1003}, + {"name":"Stone Fists","type":"Portal","wcid":34510,"cell":"00AF011A","place":"dungeon","dest":{"cell":"00B60114","place":"dungeon"},"quest":true,"desc":"In The Colosseum.","id":1004}, + {"name":"Azaxis","type":"Portal","wcid":34511,"cell":"00AF011F","place":"dungeon","dest":{"cell":"00B60126","place":"dungeon"},"quest":true,"desc":"In The Colosseum.","id":1005}, + {"name":"Killagurg","type":"Portal","wcid":34512,"cell":"00AF011F","place":"dungeon","dest":{"cell":"00B6010E","place":"dungeon"},"quest":true,"desc":"In The Colosseum.","id":1006}, + {"name":"Demon Swarm Matron","type":"Portal","wcid":34513,"cell":"00AF0129","place":"dungeon","dest":{"cell":"00B60129","place":"dungeon"},"quest":true,"desc":"In The Colosseum.","id":1007}, + {"name":"Locked Door","type":"Portal","wcid":34535,"cell":"00AF014A","place":"dungeon","dest":{"cell":"00AF0152","place":"dungeon","name":"The Colosseum"},"quest":true,"desc":"In The Colosseum.","id":1008}, + {"name":"Statue","type":"Portal","wcid":34515,"cell":"00AF0153","place":"dungeon","dest":{"cell":"00AF0166","place":"dungeon","name":"The Colosseum"},"quest":true,"desc":"In The Colosseum.","id":1009}, + {"name":"Statue","type":"Portal","wcid":34516,"cell":"00AF0152","place":"dungeon","dest":{"cell":"00AF015D","place":"dungeon","name":"The Colosseum"},"quest":true,"desc":"In The Colosseum.","id":1010}, + {"name":"Surface","type":"Portal","wcid":90273,"cell":"00B50200","place":"dungeon","dest":{"cell":"424C0019","place":"outdoor","ns":-41.1,"ew":-48.8},"minLevel":80,"desc":"In Mosswart Worship Cavern.","id":1011}, + {"name":"Surface","type":"Portal","wcid":37384,"cell":"00B701C7","place":"dungeon","dest":{"cell":"E74D003F","place":"outdoor","ns":-39.7,"ew":83.6},"desc":"In Celestial Hand Stronghold.","id":1012}, + {"name":"Surface","type":"Portal","wcid":37386,"cell":"00B801C7","place":"dungeon","dest":{"cell":"BDA00023","place":"outdoor","ns":26.26,"ew":49.65},"desc":"In Eldrytch Web Stronghold.","id":1013}, + {"name":"Surface","type":"Portal","wcid":37164,"cell":"00B901C7","place":"dungeon","dest":{"cell":"808F0014","place":"outdoor","ns":12.8,"ew":0.68},"desc":"In Radiant Blood Stronghold.","id":1014}, + {"name":"Surface","type":"Portal","wcid":38401,"cell":"00BA0131","place":"dungeon","dest":{"cell":"C3610005","place":"outdoor","ns":-23.9,"ew":54.1},"desc":"In Corrupted Catacombs.","id":1015}, + {"name":"Surface","type":"Portal","wcid":38401,"cell":"00BA0347","place":"dungeon","dest":{"cell":"C3610005","place":"outdoor","ns":-23.9,"ew":54.1},"desc":"In Corrupted Catacombs.","id":1016}, + {"name":"Surface","type":"Portal","wcid":38377,"cell":"00BB0109","place":"dungeon","dest":{"cell":"F9390027","place":"outdoor","ns":-55.71,"ew":97.67},"minLevel":180,"desc":"In a dungeon (landblock 00BB).","id":1017}, + {"name":"Surface","type":"Portal","wcid":38377,"cell":"00BB0114","place":"dungeon","dest":{"cell":"F9390027","place":"outdoor","ns":-55.71,"ew":97.67},"minLevel":180,"desc":"In a dungeon (landblock 00BB).","id":1018}, + {"name":"Surface","type":"Portal","wcid":38377,"cell":"00BB0331","place":"dungeon","dest":{"cell":"F9390027","place":"outdoor","ns":-55.71,"ew":97.67},"minLevel":180,"desc":"In a dungeon (landblock 00BB).","id":1019}, + {"name":"Surface","type":"Portal","wcid":38377,"cell":"00BB0108","place":"dungeon","dest":{"cell":"F9390027","place":"outdoor","ns":-55.71,"ew":97.67},"minLevel":180,"desc":"In a dungeon (landblock 00BB).","id":1020}, + {"name":"Device Room Portal","type":"Portal","wcid":37115,"cell":"00C0023D","place":"dungeon","dest":{"cell":"00C0019C","place":"dungeon","name":"South Gate"},"quest":true,"desc":"In South Gate.","id":1021}, + {"name":"Device Room Portal","type":"Portal","wcid":37115,"cell":"00C00241","place":"dungeon","dest":{"cell":"00C0019C","place":"dungeon","name":"South Gate"},"quest":true,"desc":"In South Gate.","id":1022}, + {"name":"Device Room Portal","type":"Portal","wcid":37115,"cell":"00C0024C","place":"dungeon","dest":{"cell":"00C0019C","place":"dungeon","name":"South Gate"},"quest":true,"desc":"In South Gate.","id":1023}, + {"name":"Moarsmen Priory","type":"Portal","wcid":38365,"cell":"00C60370","place":"dungeon","dest":{"cell":"00DC016C","place":"dungeon"},"minLevel":180,"quest":true,"desc":"In Blighted Verdant Moarsman Tunnels.","id":1024}, + {"name":"Crystalline Portal","type":"Portal","wcid":40440,"cell":"00C70100","place":"dungeon","dest":{"cell":"87040402","place":"dungeon"},"minLevel":90,"desc":"In Crystalline.","id":1025}, + {"name":"Crystalline Portal","type":"Portal","wcid":40157,"cell":"00C70385","place":"dungeon","dest":{"cell":"316D002A","place":"outdoor","ns":-14.6,"ew":-62.2},"minLevel":50,"desc":"In Crystalline.","id":1026}, + {"name":"Surface","type":"Portal","wcid":30965,"cell":"00C8036F","place":"dungeon","dest":{"cell":"43F70015","place":"outdoor","ns":96.1,"ew":-48.1},"desc":"In Egg Orchard West.","id":1027}, + {"name":"Surface","type":"Portal","wcid":30965,"cell":"00C80100","place":"dungeon","dest":{"cell":"43F70015","place":"outdoor","ns":96.1,"ew":-48.1},"desc":"In Egg Orchard West.","id":1028}, + {"name":"Surface","type":"Portal","wcid":87702,"cell":"00C901A3","place":"dungeon","dest":{"cell":"CE3E001A","place":"outdoor","ns":-52.2,"ew":63.2},"desc":"In Chamber of Scrolls.","id":1029}, + {"name":"Chamber of Air","type":"Portal","wcid":87703,"cell":"00C90151","place":"dungeon","dest":{"cell":"00C9010C","place":"dungeon","name":"Chamber of Scrolls"},"minLevel":100,"desc":"In Chamber of Scrolls.","id":1030}, + {"name":"Chamber of Earth","type":"Portal","wcid":87696,"cell":"00C90103","place":"dungeon","dest":{"cell":"00C9014E","place":"dungeon","name":"Chamber of Scrolls"},"minLevel":100,"desc":"In Chamber of Scrolls.","id":1031}, + {"name":"Chamber of Water","type":"Portal","wcid":87699,"cell":"00C90145","place":"dungeon","dest":{"cell":"00C90174","place":"dungeon","name":"Chamber of Scrolls"},"minLevel":100,"desc":"In Chamber of Scrolls.","id":1032}, + {"name":"Surface","type":"Portal","wcid":87702,"cell":"00C9016B","place":"dungeon","dest":{"cell":"CE3E001A","place":"outdoor","ns":-52.2,"ew":63.2},"desc":"In Chamber of Scrolls.","id":1033}, + {"name":"Surface","type":"Portal","wcid":40244,"cell":"00CB0100","place":"dungeon","dest":{"cell":"73C80024","place":"outdoor","ns":58.44,"ew":-9.55},"desc":"In Entrance to the pyramid.","id":1034}, + {"name":"Surface","type":"Portal","wcid":40245,"cell":"00CB016E","place":"dungeon","dest":{"cell":"71C80025","place":"outdoor","ns":58.45,"ew":-11.14},"desc":"In Entrance to the pyramid.","id":1035}, + {"name":"Surface","type":"Portal","wcid":40246,"cell":"00CB01DC","place":"dungeon","dest":{"cell":"72CA0025","place":"outdoor","ns":60.13,"ew":-10.31},"desc":"In Entrance to the pyramid.","id":1036}, + {"name":"Surface","type":"Portal","wcid":88185,"cell":"00CC03B8","place":"dungeon","dest":{"cell":"2D5A010A","place":"underground","ns":-29.47,"ew":-65.61},"desc":"In a dungeon (landblock 00CC).","id":1037}, + {"name":"Surface","type":"Portal","wcid":87691,"cell":"00CD014B","place":"dungeon","dest":{"cell":"C6610022","place":"outdoor","ns":-24.2,"ew":56.9},"desc":"In a dungeon (landblock 00CD).","id":1038}, + {"name":"Surface","type":"Portal","wcid":87691,"cell":"00CD0144","place":"dungeon","dest":{"cell":"C6610022","place":"outdoor","ns":-24.2,"ew":56.9},"desc":"In a dungeon (landblock 00CD).","id":1039}, + {"name":"Surface","type":"Portal","wcid":87691,"cell":"00CD01FC","place":"dungeon","dest":{"cell":"C6610022","place":"outdoor","ns":-24.2,"ew":56.9},"desc":"In a dungeon (landblock 00CD).","id":1040}, + {"name":"Surface","type":"Portal","wcid":87691,"cell":"00CD0198","place":"dungeon","dest":{"cell":"C6610022","place":"outdoor","ns":-24.2,"ew":56.9},"desc":"In a dungeon (landblock 00CD).","id":1041}, + {"name":"Temple of the Three","type":"Portal","wcid":35037,"cell":"00CE0515","place":"dungeon","dest":{"cell":"00E50734","place":"dungeon"},"desc":"In a dungeon (landblock 00CE).","id":1042}, + {"name":"Surface","type":"Portal","wcid":32845,"cell":"00CF055E","place":"dungeon","dest":{"cell":"29910017","place":"outdoor","ns":14.72,"ew":-68.9},"desc":"In The Dark Spiral.","id":1043}, + {"name":"Destroyed Sawato Portal","type":"Portal","wcid":4043,"cell":"00D00104","place":"dungeon","dest":{"cell":"C95B0001","place":"outdoor","ns":-29.15,"ew":58.91},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 00D0).","id":1044}, + {"name":"Bandit Castle Portal","type":"Portal","wcid":1102,"cell":"00D0011E","place":"dungeon","dest":{"cell":"BDD00006","place":"outdoor","ns":64.95,"ew":49.32},"desc":"In a dungeon (landblock 00D0).","id":1045}, + {"name":"Deepest Caves","type":"Portal","wcid":34020,"cell":"00D10B34","place":"dungeon","dest":{"cell":"00D102B7","place":"dungeon"},"desc":"In a dungeon (landblock 00D1).","id":1046}, + {"name":"Deeper Caves","type":"Portal","wcid":34019,"cell":"00D110B8","place":"dungeon","dest":{"cell":"00D109C7","place":"dungeon"},"desc":"In a dungeon (landblock 00D1).","id":1047}, + {"name":"Surface","type":"Portal","wcid":33986,"cell":"00D10198","place":"dungeon","dest":{"cell":"12450100","place":"dungeon"},"desc":"In a dungeon (landblock 00D1).","id":1048}, + {"name":"Surface","type":"Portal","wcid":33986,"cell":"00D10536","place":"dungeon","dest":{"cell":"12450100","place":"dungeon"},"desc":"In a dungeon (landblock 00D1).","id":1049}, + {"name":"Surface","type":"Portal","wcid":33986,"cell":"00D10569","place":"dungeon","dest":{"cell":"12450100","place":"dungeon"},"desc":"In a dungeon (landblock 00D1).","id":1050}, + {"name":"Surface","type":"Portal","wcid":33986,"cell":"00D107B0","place":"dungeon","dest":{"cell":"12450100","place":"dungeon"},"desc":"In a dungeon (landblock 00D1).","id":1051}, + {"name":"Surface","type":"Portal","wcid":33986,"cell":"00D108FA","place":"dungeon","dest":{"cell":"12450100","place":"dungeon"},"desc":"In a dungeon (landblock 00D1).","id":1052}, + {"name":"Surface","type":"Portal","wcid":33986,"cell":"00D10BDD","place":"dungeon","dest":{"cell":"12450100","place":"dungeon"},"desc":"In a dungeon (landblock 00D1).","id":1053}, + {"name":"Surface","type":"Portal","wcid":33986,"cell":"00D10D02","place":"dungeon","dest":{"cell":"12450100","place":"dungeon"},"desc":"In a dungeon (landblock 00D1).","id":1054}, + {"name":"Surface","type":"Portal","wcid":33986,"cell":"00D10E8F","place":"dungeon","dest":{"cell":"12450100","place":"dungeon"},"desc":"In a dungeon (landblock 00D1).","id":1055}, + {"name":"Surface","type":"Portal","wcid":33986,"cell":"00D10F2F","place":"dungeon","dest":{"cell":"12450100","place":"dungeon"},"desc":"In a dungeon (landblock 00D1).","id":1056}, + {"name":"Northern Catacombs Exit","type":"Portal","wcid":34830,"cell":"00D20115","place":"dungeon","dest":{"cell":"009C01F4","place":"dungeon"},"desc":"In a dungeon (landblock 00D2).","id":1057}, + {"name":"Humid Guruk Caverns","type":"Portal","wcid":87291,"cell":"00D2015B","place":"dungeon","dest":{"cell":"0078055C","place":"dungeon"},"minLevel":41,"maxLevel":80,"desc":"In a dungeon (landblock 00D2).","id":1058}, + {"name":"Northern Catacombs Exit","type":"Portal","wcid":34830,"cell":"00D201B8","place":"dungeon","dest":{"cell":"009C01F4","place":"dungeon"},"desc":"In a dungeon (landblock 00D2).","id":1059}, + {"name":"Northern Catacombs Exit","type":"Portal","wcid":34830,"cell":"00D20511","place":"dungeon","dest":{"cell":"009C01F4","place":"dungeon"},"desc":"In a dungeon (landblock 00D2).","id":1060}, + {"name":"Northern Catacombs Exit","type":"Portal","wcid":34830,"cell":"00D20517","place":"dungeon","dest":{"cell":"009C01F4","place":"dungeon"},"desc":"In a dungeon (landblock 00D2).","id":1061}, + {"name":"Northern Catacombs Exit","type":"Portal","wcid":34830,"cell":"00D20539","place":"dungeon","dest":{"cell":"009C01F4","place":"dungeon"},"desc":"In a dungeon (landblock 00D2).","id":1062}, + {"name":"Northern Catacombs Exit","type":"Portal","wcid":34830,"cell":"00D20355","place":"dungeon","dest":{"cell":"009C01F4","place":"dungeon"},"desc":"In a dungeon (landblock 00D2).","id":1063}, + {"name":"Northern Catacombs Exit","type":"Portal","wcid":34830,"cell":"00D201DF","place":"dungeon","dest":{"cell":"009C01F4","place":"dungeon"},"desc":"In a dungeon (landblock 00D2).","id":1064}, + {"name":"Eastern Catacombs Exit","type":"Portal","wcid":34832,"cell":"00D30115","place":"dungeon","dest":{"cell":"009C01FB","place":"dungeon"},"desc":"In a dungeon (landblock 00D3).","id":1065}, + {"name":"Eastern Catacombs Exit","type":"Portal","wcid":34832,"cell":"00D301B8","place":"dungeon","dest":{"cell":"009C01FB","place":"dungeon"},"desc":"In a dungeon (landblock 00D3).","id":1066}, + {"name":"Eastern Catacombs Exit","type":"Portal","wcid":34832,"cell":"00D30511","place":"dungeon","dest":{"cell":"009C01FB","place":"dungeon"},"desc":"In a dungeon (landblock 00D3).","id":1067}, + {"name":"Eastern Catacombs Exit","type":"Portal","wcid":34832,"cell":"00D30517","place":"dungeon","dest":{"cell":"009C01FB","place":"dungeon"},"desc":"In a dungeon (landblock 00D3).","id":1068}, + {"name":"Eastern Catacombs Exit","type":"Portal","wcid":34832,"cell":"00D30539","place":"dungeon","dest":{"cell":"009C01FB","place":"dungeon"},"desc":"In a dungeon (landblock 00D3).","id":1069}, + {"name":"Eastern Catacombs Exit","type":"Portal","wcid":34832,"cell":"00D30355","place":"dungeon","dest":{"cell":"009C01FB","place":"dungeon"},"desc":"In a dungeon (landblock 00D3).","id":1070}, + {"name":"Eastern Catacombs Exit","type":"Portal","wcid":34832,"cell":"00D301DF","place":"dungeon","dest":{"cell":"009C01FB","place":"dungeon"},"desc":"In a dungeon (landblock 00D3).","id":1071}, + {"name":"Swamp Cavern","type":"Portal","wcid":35210,"cell":"00D30448","place":"dungeon","dest":{"cell":"009D02DA","place":"dungeon"},"desc":"In a dungeon (landblock 00D3).","id":1072}, + {"name":"Steamy Guruk Caverns","type":"Portal","wcid":87298,"cell":"00D3015B","place":"dungeon","dest":{"cell":"0079055C","place":"dungeon"},"minLevel":81,"maxLevel":120,"desc":"In a dungeon (landblock 00D3).","id":1073}, + {"name":"Southern Catacombs Exit","type":"Portal","wcid":34828,"cell":"00D40115","place":"dungeon","dest":{"cell":"009C01F9","place":"dungeon"},"desc":"In a dungeon (landblock 00D4).","id":1074}, + {"name":"Deep Guruk Caverns","type":"Portal","wcid":34767,"cell":"00D4015B","place":"dungeon","dest":{"cell":"007A055C","place":"dungeon"},"minLevel":121,"desc":"In a dungeon (landblock 00D4).","id":1075}, + {"name":"Southern Catacombs Exit","type":"Portal","wcid":34828,"cell":"00D401B8","place":"dungeon","dest":{"cell":"009C01F9","place":"dungeon"},"desc":"In a dungeon (landblock 00D4).","id":1076}, + {"name":"Southern Catacombs Exit","type":"Portal","wcid":34828,"cell":"00D40511","place":"dungeon","dest":{"cell":"009C01F9","place":"dungeon"},"desc":"In a dungeon (landblock 00D4).","id":1077}, + {"name":"Southern Catacombs Exit","type":"Portal","wcid":34828,"cell":"00D40517","place":"dungeon","dest":{"cell":"009C01F9","place":"dungeon"},"desc":"In a dungeon (landblock 00D4).","id":1078}, + {"name":"Southern Catacombs Exit","type":"Portal","wcid":34828,"cell":"00D40539","place":"dungeon","dest":{"cell":"009C01F9","place":"dungeon"},"desc":"In a dungeon (landblock 00D4).","id":1079}, + {"name":"Temple of the Three, Ritual Chambers","type":"Portal","wcid":35801,"cell":"00D4060F","place":"dungeon","dest":{"cell":"00E401DE","place":"dungeon"},"quest":true,"desc":"A bypass portal, created by Asheron for those who are helping defend him from the Ritual of the Three Matriarchs. This portal seems to be warded against those who are not attuned to its destination. In a dungeon (landblock 00D4).","id":1080}, + {"name":"Southern Catacombs Exit","type":"Portal","wcid":34828,"cell":"00D40355","place":"dungeon","dest":{"cell":"009C01F9","place":"dungeon"},"desc":"In a dungeon (landblock 00D4).","id":1081}, + {"name":"Southern Catacombs Exit","type":"Portal","wcid":34828,"cell":"00D401DF","place":"dungeon","dest":{"cell":"009C01F9","place":"dungeon"},"desc":"In a dungeon (landblock 00D4).","id":1082}, + {"name":"North Library Conveyance","type":"Portal","wcid":24019,"cell":"00D6010A","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1083}, + {"name":"South Library Conveyance","type":"Portal","wcid":24020,"cell":"00D60117","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1084}, + {"name":"West Library Conveyance","type":"Portal","wcid":24021,"cell":"00D60203","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1085}, + {"name":"Seat of Knorr Conveyance","type":"Portal","wcid":24025,"cell":"00D60210","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1086}, + {"name":"East Library Conveyance","type":"Portal","wcid":24018,"cell":"00D60219","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1087}, + {"name":"Journeyman Portal Studies","type":"Portal","wcid":36937,"cell":"00D6025A","place":"dungeon","dest":{"cell":"00D6029B","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1088}, + {"name":"Master Portal Studies","type":"Portal","wcid":36938,"cell":"00D6029B","place":"dungeon","dest":{"cell":"00D6036A","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1089}, + {"name":"Planar Academy Lecture Hall","type":"Portal","wcid":36939,"cell":"00D6032A","place":"dungeon","dest":{"cell":"00D603F9","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1090}, + {"name":"Planar Academy Lecture Hall","type":"Portal","wcid":36939,"cell":"00D6036A","place":"dungeon","dest":{"cell":"00D603F9","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1091}, + {"name":"Forge Conveyance","type":"Portal","wcid":24015,"cell":"00D603E7","place":"dungeon","dest":{"cell":"644501A1","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1092}, + {"name":"Planar Academy Headmaster's Rooms","type":"Portal","wcid":36940,"cell":"00D603F2","place":"dungeon","dest":{"cell":"00D60430","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1093}, + {"name":"Master Portal Studies","type":"Portal","wcid":36938,"cell":"00D603F9","place":"dungeon","dest":{"cell":"00D6036A","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1094}, + {"name":"Forge Conveyance","type":"Portal","wcid":24015,"cell":"00D60405","place":"dungeon","dest":{"cell":"644501A1","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1095}, + {"name":"Planar Academy Lecture Hall","type":"Portal","wcid":36939,"cell":"00D60430","place":"dungeon","dest":{"cell":"00D603F9","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1096}, + {"name":"Quiddity Seed","type":"Portal","wcid":36769,"cell":"00D6044E","place":"dungeon","dest":{"cell":"00D60492","place":"dungeon"},"desc":"In a dungeon (landblock 00D6).","id":1097}, + {"name":"Return to Graveyard Tomb Portal","type":"Portal","wcid":72671,"cell":"00D70198","place":"dungeon","dest":{"cell":"482E0101","place":"underground","ns":-64.89,"ew":-44.07},"desc":"In a dungeon (landblock 00D7).","id":1098}, + {"name":"Return to Graveyard Tomb Portal","type":"Portal","wcid":72671,"cell":"00D70100","place":"dungeon","dest":{"cell":"482E0101","place":"underground","ns":-64.89,"ew":-44.07},"desc":"In a dungeon (landblock 00D7).","id":1099}, + {"name":"Return to Graveyard Tomb Portal","type":"Portal","wcid":72671,"cell":"00D701C1","place":"dungeon","dest":{"cell":"482E0101","place":"underground","ns":-64.89,"ew":-44.07},"desc":"In a dungeon (landblock 00D7).","id":1100}, + {"name":"Surface","type":"Portal","wcid":87200,"cell":"00D80179","place":"dungeon","dest":{"cell":"96DC0027","place":"outdoor","ns":74.73,"ew":18.45},"minLevel":180,"desc":"In a dungeon (landblock 00D8).","id":1101}, + {"name":"Surface","type":"Portal","wcid":87200,"cell":"00D8022C","place":"dungeon","dest":{"cell":"96DC0027","place":"outdoor","ns":74.73,"ew":18.45},"minLevel":180,"desc":"In a dungeon (landblock 00D8).","id":1102}, + {"name":"Surface","type":"Portal","wcid":87473,"cell":"00D9028A","place":"dungeon","dest":{"cell":"0F38003A","place":"outdoor","ns":-57.0,"ew":-89.2},"desc":"In a dungeon (landblock 00D9).","id":1103}, + {"name":"Surface","type":"Portal","wcid":87473,"cell":"00D90107","place":"dungeon","dest":{"cell":"0F38003A","place":"outdoor","ns":-57.0,"ew":-89.2},"desc":"In a dungeon (landblock 00D9).","id":1104}, + {"name":"Surface","type":"Portal","wcid":38366,"cell":"00DC0274","place":"dungeon","dest":{"cell":"00C6036E","place":"dungeon","name":"Blighted Verdant Moarsman Tunnels"},"desc":"In a dungeon (landblock 00DC).","id":1105}, + {"name":"Surface","type":"Portal","wcid":38366,"cell":"00DC02A2","place":"dungeon","dest":{"cell":"00C6036E","place":"dungeon","name":"Blighted Verdant Moarsman Tunnels"},"desc":"In a dungeon (landblock 00DC).","id":1106}, + {"name":"Surface","type":"Portal","wcid":38653,"cell":"00DE010B","place":"dungeon","dest":{"cell":"3A11001C","place":"outdoor","ns":-88.02,"ew":-55.2},"desc":"In a dungeon (landblock 00DE).","id":1107}, + {"name":"Surface","type":"Portal","wcid":38653,"cell":"00DE0110","place":"dungeon","dest":{"cell":"3A11001C","place":"outdoor","ns":-88.02,"ew":-55.2},"desc":"In a dungeon (landblock 00DE).","id":1108}, + {"name":"Surface","type":"Portal","wcid":38647,"cell":"00E001AF","place":"dungeon","dest":{"cell":"96DC0018","place":"outdoor","ns":74.78,"ew":18.33},"desc":"In Rogue Delvings.","id":1109}, + {"name":"Surface","type":"Portal","wcid":30970,"cell":"00E1034E","place":"dungeon","dest":{"cell":"43F1001B","place":"outdoor","ns":91.07,"ew":-47.97},"desc":"In Path of the Blind East.","id":1110}, + {"name":"Surface","type":"Portal","wcid":30970,"cell":"00E1017F","place":"dungeon","dest":{"cell":"43F1001B","place":"outdoor","ns":91.07,"ew":-47.97},"desc":"In Path of the Blind East.","id":1111}, + {"name":"Surface","type":"Portal","wcid":71301,"cell":"00E2013F","place":"dungeon","dest":{"cell":"29F10010","place":"outdoor","ns":91.63,"ew":-69.03},"desc":"In a dungeon (landblock 00E2).","id":1112}, + {"name":"Surface","type":"Portal","wcid":71301,"cell":"00E202F2","place":"dungeon","dest":{"cell":"29F10010","place":"outdoor","ns":91.63,"ew":-69.03},"desc":"In a dungeon (landblock 00E2).","id":1113}, + {"name":"Surface","type":"Portal","wcid":71301,"cell":"00E20111","place":"dungeon","dest":{"cell":"29F10010","place":"outdoor","ns":91.63,"ew":-69.03},"desc":"In a dungeon (landblock 00E2).","id":1114}, + {"name":"Surface","type":"Portal","wcid":71302,"cell":"00E30410","place":"dungeon","dest":{"cell":"40A90010","place":"outdoor","ns":34.0,"ew":-50.6},"desc":"In a dungeon (landblock 00E3).","id":1115}, + {"name":"Surface","type":"Portal","wcid":71302,"cell":"00E30126","place":"dungeon","dest":{"cell":"40A90010","place":"outdoor","ns":34.0,"ew":-50.6},"desc":"In a dungeon (landblock 00E3).","id":1116}, + {"name":"Temple of the Three","type":"Portal","wcid":35037,"cell":"00E4010A","place":"dungeon","dest":{"cell":"00E50734","place":"dungeon"},"desc":"In a dungeon (landblock 00E4).","id":1117}, + {"name":"Bur Catacombs","type":"Portal","wcid":35038,"cell":"00E40113","place":"dungeon","dest":{"cell":"00D40535","place":"dungeon"},"desc":"In a dungeon (landblock 00E4).","id":1118}, + {"name":"Kor-Gursha","type":"Portal","wcid":34844,"cell":"00E40116","place":"dungeon","dest":{"cell":"009C0247","place":"dungeon"},"desc":"In a dungeon (landblock 00E4).","id":1119}, + {"name":"Bur Catacombs","type":"Portal","wcid":35038,"cell":"00E50182","place":"dungeon","dest":{"cell":"00D40535","place":"dungeon"},"desc":"In a dungeon (landblock 00E5).","id":1120}, + {"name":"Bur Catacombs","type":"Portal","wcid":35038,"cell":"00E506D8","place":"dungeon","dest":{"cell":"00D40535","place":"dungeon"},"desc":"In a dungeon (landblock 00E5).","id":1121}, + {"name":"Ritual Chambers","type":"Portal","wcid":35039,"cell":"00E506D4","place":"dungeon","dest":{"cell":"00E401DE","place":"dungeon"},"quest":true,"desc":"This portal seems to be warded against those who are not attuned to its destination. In a dungeon (landblock 00E5).","id":1122}, + {"name":"Prodigal Shadow Child's Lair","type":"Portal","wcid":36008,"cell":"00E6012F","place":"dungeon","dest":{"cell":"00E60422","place":"dungeon"},"minLevel":140,"desc":"This portal coruscates with strange energies, filling you with an eerie warmth when you get close to it, even though it doesn't seem to radiate any actual heat. In a dungeon (landblock 00E6).","id":1123}, + {"name":"Exit","type":"Portal","wcid":27299,"cell":"00E60429","place":"dungeon","dest":{"cell":"09040008","place":"outdoor","ns":-97.96,"ew":-94.7},"minLevel":90,"desc":"In a dungeon (landblock 00E6).","id":1124}, + {"name":"Surface","type":"Portal","wcid":38087,"cell":"00E70287","place":"dungeon","dest":{"cell":"482E002D","place":"outdoor","ns":-64.73,"ew":-43.83},"desc":"In Gardens of Menilesh.","id":1125}, + {"name":"Graveyard","type":"Portal","wcid":37490,"cell":"00EA0121","place":"dungeon","dest":{"cell":"482E0140","place":"building","ns":-64.8,"ew":-44.26},"desc":"In Mhoire Armory.","id":1126}, + {"name":"Armory","type":"Portal","wcid":37513,"cell":"00EA01E5","place":"dungeon","dest":{"cell":"00EA0303","place":"dungeon","name":"Mhoire Armory"},"desc":"In Mhoire Armory.","id":1127}, + {"name":"Graveyard","type":"Portal","wcid":37490,"cell":"00EA022E","place":"dungeon","dest":{"cell":"482E0140","place":"building","ns":-64.8,"ew":-44.26},"desc":"In Mhoire Armory.","id":1128}, + {"name":"Graveyard","type":"Portal","wcid":37490,"cell":"00EA0268","place":"dungeon","dest":{"cell":"482E0140","place":"building","ns":-64.8,"ew":-44.26},"desc":"In Mhoire Armory.","id":1129}, + {"name":"Forges","type":"Portal","wcid":37514,"cell":"00EA0303","place":"dungeon","dest":{"cell":"00EA01E5","place":"dungeon","name":"Mhoire Armory"},"desc":"In Mhoire Armory.","id":1130}, + {"name":"Graveyard","type":"Portal","wcid":37490,"cell":"00EA0229","place":"dungeon","dest":{"cell":"482E0140","place":"building","ns":-64.8,"ew":-44.26},"desc":"In Mhoire Armory.","id":1131}, + {"name":"Graveyard","type":"Portal","wcid":37490,"cell":"00EA0263","place":"dungeon","dest":{"cell":"482E0140","place":"building","ns":-64.8,"ew":-44.26},"desc":"In Mhoire Armory.","id":1132}, + {"name":"Surface","type":"Portal","wcid":38731,"cell":"00EB014F","place":"dungeon","dest":{"cell":"F7180023","place":"outdoor","ns":-82.51,"ew":96.09},"desc":"In a dungeon (landblock 00EB).","id":1133}, + {"name":"Surface","type":"Portal","wcid":38731,"cell":"00EB0332","place":"dungeon","dest":{"cell":"F7180023","place":"outdoor","ns":-82.51,"ew":96.09},"desc":"In a dungeon (landblock 00EB).","id":1134}, + {"name":"Surface","type":"Portal","wcid":37107,"cell":"00EC014B","place":"dungeon","dest":{"cell":"A8BF0010","place":"outdoor","ns":51.57,"ew":32.57},"desc":"In a dungeon (landblock 00EC).","id":1135}, + {"name":"Surface","type":"Portal","wcid":37107,"cell":"00EC026C","place":"dungeon","dest":{"cell":"A8BF0010","place":"outdoor","ns":51.57,"ew":32.57},"desc":"In a dungeon (landblock 00EC).","id":1136}, + {"name":"Surface","type":"Portal","wcid":87471,"cell":"00EC011A","place":"dungeon","dest":{"cell":"B93D0035","place":"outdoor","ns":-52.66,"ew":46.68},"desc":"In a dungeon (landblock 00EC).","id":1137}, + {"name":"Surface","type":"Portal","wcid":87471,"cell":"00EC0216","place":"dungeon","dest":{"cell":"B93D0035","place":"outdoor","ns":-52.66,"ew":46.68},"desc":"In a dungeon (landblock 00EC).","id":1138}, + {"name":"Surface","type":"Portal","wcid":36218,"cell":"00ED027E","place":"dungeon","dest":{"cell":"0A0C0013","place":"outdoor","ns":-92.11,"ew":-93.7},"desc":"In Artifex Collegium.","id":1139}, + {"name":"Surface","type":"Portal","wcid":36218,"cell":"00ED0351","place":"dungeon","dest":{"cell":"0A0C0013","place":"outdoor","ns":-92.11,"ew":-93.7},"desc":"In Artifex Collegium.","id":1140}, + {"name":"Surface","type":"Portal","wcid":36218,"cell":"00ED0132","place":"dungeon","dest":{"cell":"0A0C0013","place":"outdoor","ns":-92.11,"ew":-93.7},"desc":"In Artifex Collegium.","id":1141}, + {"name":"Surface","type":"Portal","wcid":36218,"cell":"00ED01E2","place":"dungeon","dest":{"cell":"0A0C0013","place":"outdoor","ns":-92.11,"ew":-93.7},"desc":"In Artifex Collegium.","id":1142}, + {"name":"Surface","type":"Portal","wcid":87393,"cell":"00EE0121","place":"dungeon","dest":{"cell":"B89F0025","place":"outdoor","ns":25.7,"ew":45.7},"desc":"In Cave.","id":1143}, + {"name":"Surface","type":"Portal","wcid":34058,"cell":"00EF0113","place":"dungeon","dest":{"cell":"9EE80017","place":"outdoor","ns":84.33,"ew":24.66},"desc":"In Temple.","id":1144}, + {"name":"Exit","type":"Portal","wcid":32037,"cell":"00F00148","place":"dungeon","dest":{"cell":"D6DB0009","place":"outdoor","ns":73.26,"ew":69.36},"minLevel":130,"desc":"In Upper Sanctum of Xik Minru.","id":1145}, + {"name":"Exit","type":"Portal","wcid":32037,"cell":"00F0012E","place":"dungeon","dest":{"cell":"D6DB0009","place":"outdoor","ns":73.26,"ew":69.36},"minLevel":130,"desc":"In Upper Sanctum of Xik Minru.","id":1146}, + {"name":"Temple of Xik Minru","type":"Portal","wcid":32045,"cell":"00F0015E","place":"dungeon","dest":{"cell":"00F00143","place":"dungeon","name":"Upper Sanctum of Xik Minru"},"minLevel":130,"desc":"In Upper Sanctum of Xik Minru.","id":1147}, + {"name":"Sanctum of Xik Minru","type":"Portal","wcid":32039,"cell":"00F00130","place":"dungeon","dest":{"cell":"00F001B2","place":"dungeon","name":"Upper Sanctum of Xik Minru"},"minLevel":130,"desc":"In Upper Sanctum of Xik Minru.","id":1148}, + {"name":"Exit","type":"Portal","wcid":32037,"cell":"00F0033F","place":"dungeon","dest":{"cell":"D6DB0009","place":"outdoor","ns":73.26,"ew":69.36},"minLevel":130,"desc":"In Upper Sanctum of Xik Minru.","id":1149}, + {"name":"Southern Courtyard","type":"Portal","wcid":32043,"cell":"00F006B2","place":"dungeon","dest":{"cell":"D5DA0021","place":"outdoor","ns":72.51,"ew":68.9},"minLevel":130,"desc":"In Upper Sanctum of Xik Minru.","id":1150}, + {"name":"Eastern Courtyard","type":"Portal","wcid":70091,"cell":"00F006E1","place":"dungeon","dest":{"cell":"D6DA0005","place":"outdoor","ns":72.9,"ew":69.28},"minLevel":130,"desc":"In Upper Sanctum of Xik Minru.","id":1151}, + {"name":"Southern Courtyard","type":"Portal","wcid":32043,"cell":"00F006BF","place":"dungeon","dest":{"cell":"D5DA0021","place":"outdoor","ns":72.51,"ew":68.9},"minLevel":130,"desc":"In Upper Sanctum of Xik Minru.","id":1152}, + {"name":"Western Courtyard","type":"Portal","wcid":70092,"cell":"00F00690","place":"dungeon","dest":{"cell":"D5DA0005","place":"outdoor","ns":72.9,"ew":68.52},"minLevel":130,"desc":"In Upper Sanctum of Xik Minru.","id":1153}, + {"name":"Surface","type":"Portal","wcid":31420,"cell":"00F1013F","place":"dungeon","dest":{"cell":"0A0F0033","place":"outdoor","ns":-89.71,"ew":-93.29},"minLevel":150,"desc":"In a dungeon (landblock 00F1).","id":1154}, + {"name":"Surface Portal","type":"Portal","wcid":7253,"cell":"01000115","place":"dungeon","dest":{"cell":"D349001C","place":"outdoor","ns":-43.2,"ew":67.19},"desc":"In Murk Warrens.","id":1155}, + {"name":"Surface Portal","type":"Portal","wcid":7253,"cell":"01000465","place":"dungeon","dest":{"cell":"D349001C","place":"outdoor","ns":-43.2,"ew":67.19},"desc":"In Murk Warrens.","id":1156}, + {"name":"Surface Portal","type":"Portal","wcid":7251,"cell":"01010115","place":"dungeon","dest":{"cell":"81A0002A","place":"outdoor","ns":26.21,"ew":1.84},"desc":"In Murk Warrens.","id":1157}, + {"name":"Surface Portal","type":"Portal","wcid":7251,"cell":"01010465","place":"dungeon","dest":{"cell":"81A0002A","place":"outdoor","ns":26.21,"ew":1.84},"desc":"In Murk Warrens.","id":1158}, + {"name":"Surface Portal","type":"Portal","wcid":7249,"cell":"01020115","place":"dungeon","dest":{"cell":"5AD30040","place":"outdoor","ns":67.56,"ew":-29.24},"desc":"In Murk Warrens.","id":1159}, + {"name":"Surface Portal","type":"Portal","wcid":7249,"cell":"01020465","place":"dungeon","dest":{"cell":"5AD30040","place":"outdoor","ns":67.56,"ew":-29.24},"desc":"In Murk Warrens.","id":1160}, + {"name":"Surface Portal","type":"Portal","wcid":7247,"cell":"01030279","place":"dungeon","dest":{"cell":"37340014","place":"outdoor","ns":-59.97,"ew":-57.72},"desc":"In Black Spawn Den.","id":1161}, + {"name":"Surface Portal","type":"Portal","wcid":7247,"cell":"01030341","place":"dungeon","dest":{"cell":"37340014","place":"outdoor","ns":-59.97,"ew":-57.72},"desc":"In Black Spawn Den.","id":1162}, + {"name":"Surface Portal","type":"Portal","wcid":7245,"cell":"01040279","place":"dungeon","dest":{"cell":"1338003E","place":"outdoor","ns":-56.58,"ew":-86.02},"desc":"In Black Spawn Den.","id":1163}, + {"name":"Surface Portal","type":"Portal","wcid":7245,"cell":"01040341","place":"dungeon","dest":{"cell":"1338003E","place":"outdoor","ns":-56.58,"ew":-86.02},"desc":"In Black Spawn Den.","id":1164}, + {"name":"Surface Portal","type":"Portal","wcid":7243,"cell":"01050279","place":"dungeon","dest":{"cell":"1B90002D","place":"outdoor","ns":13.72,"ew":-79.84},"desc":"In Black Spawn Den.","id":1165}, + {"name":"Surface Portal","type":"Portal","wcid":7243,"cell":"01050341","place":"dungeon","dest":{"cell":"1B90002D","place":"outdoor","ns":13.72,"ew":-79.84},"desc":"In Black Spawn Den.","id":1166}, + {"name":"Surface Portal","type":"Portal","wcid":7209,"cell":"01060164","place":"dungeon","dest":{"cell":"C2820010","place":"outdoor","ns":2.76,"ew":53.45},"desc":"In Setab's Barracks.","id":1167}, + {"name":"Surface Portal","type":"Portal","wcid":7207,"cell":"01070109","place":"dungeon","dest":{"cell":"8E560017","place":"outdoor","ns":-32.46,"ew":11.88},"desc":"In Nor's Folly.","id":1168}, + {"name":"Surface Portal","type":"Portal","wcid":7207,"cell":"01070154","place":"dungeon","dest":{"cell":"8E560017","place":"outdoor","ns":-32.46,"ew":11.88},"desc":"In Nor's Folly.","id":1169}, + {"name":"Surface Portal","type":"Portal","wcid":7205,"cell":"01080123","place":"dungeon","dest":{"cell":"D55D002A","place":"outdoor","ns":-27.36,"ew":69.04},"desc":"In Cursed Swamp.","id":1170}, + {"name":"Surface Portal","type":"Portal","wcid":7205,"cell":"010801E9","place":"dungeon","dest":{"cell":"D55D002A","place":"outdoor","ns":-27.36,"ew":69.04},"desc":"In Cursed Swamp.","id":1171}, + {"name":"Surface Portal","type":"Portal","wcid":7203,"cell":"01090169","place":"dungeon","dest":{"cell":"4139001B","place":"outdoor","ns":-56.06,"ew":-49.62},"desc":"In a dungeon (landblock 0109).","id":1172}, + {"name":"Surface Portal","type":"Portal","wcid":7201,"cell":"010A0107","place":"dungeon","dest":{"cell":"5F100005","place":"outdoor","ns":-88.68,"ew":-25.87},"desc":"In Black Dominion.","id":1173}, + {"name":"Surface Portal","type":"Portal","wcid":7201,"cell":"010A0147","place":"dungeon","dest":{"cell":"5F100005","place":"outdoor","ns":-88.68,"ew":-25.87},"desc":"In Black Dominion.","id":1174}, + {"name":"Surface Portal","type":"Portal","wcid":7201,"cell":"010A0226","place":"dungeon","dest":{"cell":"5F100005","place":"outdoor","ns":-88.68,"ew":-25.87},"desc":"In Black Dominion.","id":1175}, + {"name":"Surface Portal","type":"Portal","wcid":7199,"cell":"010B019E","place":"dungeon","dest":{"cell":"A5B7001E","place":"outdoor","ns":44.95,"ew":30.43},"desc":"In Asuger Temple.","id":1176}, + {"name":"Surface Portal","type":"Portal","wcid":6885,"cell":"010C01D1","place":"dungeon","dest":{"cell":"E73D0003","place":"outdoor","ns":-52.86,"ew":82.92},"desc":"In Mysterious Tunnels.","id":1177}, + {"name":"Surface Portal","type":"Portal","wcid":6796,"cell":"0110025F","place":"dungeon","dest":{"cell":"1C4D0023","place":"outdoor","ns":-40.16,"ew":-79.14},"desc":"In Nexus.","id":1178}, + {"name":"Surface Portal","type":"Portal","wcid":6796,"cell":"011002E2","place":"dungeon","dest":{"cell":"1C4D0023","place":"outdoor","ns":-40.16,"ew":-79.14},"desc":"In Nexus.","id":1179}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"0112010E","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 0112).","id":1180}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"01120145","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 0112).","id":1181}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"0112017B","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 0112).","id":1182}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"011202DD","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 0112).","id":1183}, + {"name":"Surface Portal","type":"Portal","wcid":6780,"cell":"0113021C","place":"dungeon","dest":{"cell":"AB6B0102","place":"building","ns":-16.06,"ew":35.22},"desc":"In Amiantos Bethel.","id":1184}, + {"name":"Surface","type":"Portal","wcid":29096,"cell":"011401A8","place":"dungeon","dest":{"cell":"32DB0028","place":"outdoor","ns":73.99,"ew":-61.46},"desc":"In Sultry Hovel.","id":1185}, + {"name":"Surface","type":"Portal","wcid":29096,"cell":"01140115","place":"dungeon","dest":{"cell":"32DB0028","place":"outdoor","ns":73.99,"ew":-61.46},"desc":"In Sultry Hovel.","id":1186}, + {"name":"Surface","type":"Portal","wcid":29096,"cell":"01140183","place":"dungeon","dest":{"cell":"32DB0028","place":"outdoor","ns":73.99,"ew":-61.46},"desc":"In Sultry Hovel.","id":1187}, + {"name":"Destroyed Portal to Zaikhal","type":"Portal","wcid":1032,"cell":"01150157","place":"dungeon","dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0115).","id":1188}, + {"name":"North Direlands Portal","type":"Portal","wcid":1104,"cell":"0115015A","place":"dungeon","dest":{"cell":"3C9D0010","place":"outdoor","ns":24.45,"ew":-53.85},"minLevel":12,"desc":"In a dungeon (landblock 0115).","id":1189}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"01150173","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0115).","id":1190}, + {"name":"Destroyed Portal to Cragstone","type":"Portal","wcid":1014,"cell":"0115017C","place":"dungeon","dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0115).","id":1191}, + {"name":"South Direlands Portal","type":"Portal","wcid":1107,"cell":"0115017F","place":"dungeon","dest":{"cell":"5416001A","place":"outdoor","ns":-84.2,"ew":-34.44},"minLevel":12,"desc":"In a dungeon (landblock 0115).","id":1192}, + {"name":"Surface Portal","type":"Portal","wcid":7489,"cell":"0116010A","place":"dungeon","dest":{"cell":"B4EE001A","place":"outdoor","ns":88.64,"ew":42.44},"desc":"In Tenkarrdun Foundry.","id":1193}, + {"name":"Surface Portal","type":"Portal","wcid":7478,"cell":"0116013B","place":"dungeon","dest":{"cell":"BBF0000B","place":"outdoor","ns":90.26,"ew":47.78},"desc":"In Tenkarrdun Foundry.","id":1194}, + {"name":"Surface Portal","type":"Portal","wcid":7478,"cell":"011601E9","place":"dungeon","dest":{"cell":"BBF0000B","place":"outdoor","ns":90.26,"ew":47.78},"desc":"In Tenkarrdun Foundry.","id":1195}, + {"name":"Surface Portal","type":"Portal","wcid":7478,"cell":"011602B7","place":"dungeon","dest":{"cell":"BBF0000B","place":"outdoor","ns":90.26,"ew":47.78},"desc":"In Tenkarrdun Foundry.","id":1196}, + {"name":"Surface Portal","type":"Portal","wcid":6633,"cell":"01160367","place":"dungeon","dest":{"cell":"B4EE001A","place":"outdoor","ns":88.64,"ew":42.44},"desc":"In Tenkarrdun Foundry.","id":1197}, + {"name":"Surface Portal","type":"Portal","wcid":6398,"cell":"011702F0","place":"dungeon","dest":{"cell":"A320002D","place":"outdoor","ns":-75.86,"ew":28.96},"desc":"In Serac Vault.","id":1198}, + {"name":"Surface","type":"Portal","wcid":28791,"cell":"01180238","place":"dungeon","dest":{"cell":"7F61000F","place":"outdoor","ns":-23.7,"ew":-0.16},"desc":"In Drudge Hovel.","id":1199}, + {"name":"Surface","type":"Portal","wcid":28791,"cell":"01180103","place":"dungeon","dest":{"cell":"7F61000F","place":"outdoor","ns":-23.7,"ew":-0.16},"desc":"In Drudge Hovel.","id":1200}, + {"name":"Surface Portal","type":"Portal","wcid":6390,"cell":"01190104","place":"dungeon","dest":{"cell":"2438001F","place":"outdoor","ns":-56.51,"ew":-72.78},"desc":"In Amperehelion Vault.","id":1201}, + {"name":"Surface Portal","type":"Portal","wcid":6390,"cell":"01190242","place":"dungeon","dest":{"cell":"2438001F","place":"outdoor","ns":-56.51,"ew":-72.78},"desc":"In Amperehelion Vault.","id":1202}, + {"name":"Surface Portal","type":"Portal","wcid":6390,"cell":"011902E5","place":"dungeon","dest":{"cell":"2438001F","place":"outdoor","ns":-56.51,"ew":-72.78},"desc":"In Amperehelion Vault.","id":1203}, + {"name":"Surface Portal","type":"Portal","wcid":6390,"cell":"0119032E","place":"dungeon","dest":{"cell":"2438001F","place":"outdoor","ns":-56.51,"ew":-72.78},"desc":"In Amperehelion Vault.","id":1204}, + {"name":"Surface Portal","type":"Portal","wcid":6390,"cell":"01190366","place":"dungeon","dest":{"cell":"2438001F","place":"outdoor","ns":-56.51,"ew":-72.78},"desc":"In Amperehelion Vault.","id":1205}, + {"name":"Surface Portal","type":"Portal","wcid":6394,"cell":"011A02FC","place":"dungeon","dest":{"cell":"4452001D","place":"outdoor","ns":-35.86,"ew":-47.2},"desc":"In Incunabula Vault.","id":1206}, + {"name":"Surface Portal","type":"Portal","wcid":6394,"cell":"011A0404","place":"dungeon","dest":{"cell":"4452001D","place":"outdoor","ns":-35.86,"ew":-47.2},"desc":"In Incunabula Vault.","id":1207}, + {"name":"Surface Portal","type":"Portal","wcid":6396,"cell":"011B0145","place":"dungeon","dest":{"cell":"92D30009","place":"outdoor","ns":66.9,"ew":14.98},"desc":"In Jahannan Vault.","id":1208}, + {"name":"Surface Portal","type":"Portal","wcid":6396,"cell":"011B01B8","place":"dungeon","dest":{"cell":"92D30009","place":"outdoor","ns":66.9,"ew":14.98},"desc":"In Jahannan Vault.","id":1209}, + {"name":"Surface","type":"Portal","wcid":6115,"cell":"011C012E","place":"dungeon","dest":{"cell":"98180001","place":"outdoor","ns":-83.15,"ew":19.94},"desc":"In Mountain Fortress.","id":1210}, + {"name":"Surface","type":"Portal","wcid":6115,"cell":"011C0341","place":"dungeon","dest":{"cell":"98180001","place":"outdoor","ns":-83.15,"ew":19.94},"desc":"In Mountain Fortress.","id":1211}, + {"name":"Portal to Al-Arqas","type":"Portal","wcid":42823,"cell":"011D0126","place":"dungeon","dest":{"cell":"8F58003B","place":"outdoor","ns":-31.3,"ew":13.22},"desc":"This portal goes to the Gharu'ndim town of Al-Arqas in the depths of the A'mun desert. This is a good town for characters over level 10. In Al-Arqas Meeting Hall.","id":1212}, + {"name":"Al-Jalima Portal","type":"Portal","wcid":42830,"cell":"011E0126","place":"dungeon","dest":{"cell":"8588002C","place":"outdoor","ns":7.25,"ew":4.95},"desc":"This portal goes to Al-Jalima, the Gharu'ndim settlement located between the prominent cities of Zaikhal and Samsur. This is a good town for characters over level 20. In Al-Jalima Meeting Hall.","id":1213}, + {"name":"Portal to Arwic","type":"Portal","wcid":42819,"cell":"011F0126","place":"dungeon","dest":{"cell":"C6A90009","place":"outdoor","ns":33.27,"ew":56.65},"desc":"This portal goes to Arwic, a walled Aluvian town that has fully recovered from a devastating attack by a Shadow Spire. This is a good town for characters over level 20. In Arwic Meeting Hall.","id":1214}, + {"name":"Baishi Portal","type":"Portal","wcid":42845,"cell":"01200126","place":"dungeon","dest":{"cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9},"desc":"This portal goes to Baishi, a town well-known for its sake and the madman that desires it. This is good town for characters over level 40. In Baishi Meeting Hall.","id":1215}, + {"name":"Portal to Cragstone","type":"Portal","wcid":42818,"cell":"01210126","place":"dungeon","dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal goes to the Aluvian capital, Cragstone. This is a good town for characters over level 10. In Cragstone Meeting Hall.","id":1216}, + {"name":"Eastham Portal","type":"Portal","wcid":42815,"cell":"01220126","place":"dungeon","dest":{"cell":"CE940035","place":"outdoor","ns":16.92,"ew":63.48},"desc":"This portal goes to Eastham, a coastal Aluvian town that contains a portal to Asheron's island home. This is a good town for characters over level 20. In Eastham Meeting Hall.","id":1217}, + {"name":"Glenden Wood Portal","type":"Portal","wcid":42814,"cell":"01230126","place":"dungeon","dest":{"cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45},"desc":"This portal goes to Glenden Wood, a village surrounded by the tall trees of the Tiofor Woods. Despite the truce between Queen Elysa and King Varicci, the town is besieged on all sides by Viamontian soldiers. This is a good town for characters over level 40. In Glenden Wood Meeting Hall.","id":1218}, + {"name":"Portal to Hebian-To","type":"Portal","wcid":42846,"cell":"01240126","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal goes to the Sho capital, Hebian-To. This is a good town for characters over level 10. In Hebian-to Meeting Hall.","id":1219}, + {"name":"Portal to Holtburg","type":"Portal","wcid":42820,"cell":"01250126","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal goes to Holtburg, an Aluvian town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Holtburg Meeting Hall.","id":1220}, + {"name":"Portal to Khayyaban","type":"Portal","wcid":42822,"cell":"01260126","place":"dungeon","dest":{"cell":"9F440012","place":"outdoor","ns":-47.45,"ew":25.62},"desc":"This portal goes to the town of Khayyaban on the Yushad Ridge. This is a good town for characters over level 20. In Khayyaban Meeting Hall.","id":1221}, + {"name":"Lin Portal","type":"Portal","wcid":42844,"cell":"01270126","place":"dungeon","dest":{"cell":"DC3C0011","place":"outdoor","ns":-53.91,"ew":74.3},"desc":"This portal goes to Lin, a small town nestled in a valley located by the foothills of the Linvak Mountains. This is a good town for characters over level 20. In Lin Meeting Hall.","id":1222}, + {"name":"Lytelthorpe Portal","type":"Portal","wcid":42816,"cell":"01280126","place":"dungeon","dest":{"cell":"C0800007","place":"outdoor","ns":1.1,"ew":51.7},"desc":"This portal goes to the town of Lytelthorpe, an Aluvian settlement surrounded by rich farmlands. This is a good town for characters over level 10. In Lytelthorpe Meeting Hall.","id":1223}, + {"name":"Mayoi Portal","type":"Portal","wcid":42842,"cell":"01290126","place":"dungeon","dest":{"cell":"E6320021","place":"outdoor","ns":-61.91,"ew":82.5},"desc":"This portal goes to Mayoi, a coastal settlement renowned for Shoyanen Kenchu, the master mage of the Sho people, who lives in a spire on the outskirts of town. This is a good town for characters over level 30. In Mayoi Meeting Hall.","id":1224}, + {"name":"Portal to Nanto","type":"Portal","wcid":42843,"cell":"012A0126","place":"dungeon","dest":{"cell":"E63E0022","place":"outdoor","ns":-52.19,"ew":82.45},"desc":"This portal goes to Nanto, a sleepy Sho town. This is a good town for characters over level 10. In Nanto Meeting Hall.","id":1225}, + {"name":"Qalaba'r Portal","type":"Portal","wcid":42833,"cell":"012B0126","place":"dungeon","dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"desc":"This portal leads to Qalaba'r, the Gharu'ndim village on the edge of the Linvak Mountain Range. This is a good town for characters over level 30. In Qalaba'r Meeting Hall.","id":1226}, + {"name":"Portal to Rithwic","type":"Portal","wcid":42817,"cell":"012C0126","place":"dungeon","dest":{"cell":"C98C0028","place":"outdoor","ns":10.84,"ew":59.32},"desc":"This portal goes to Rithwic, an Aluvian town on the shores of Lake Blessed. This is a good town for characters over level 10. In Rithwic Meeting Hall.","id":1227}, + {"name":"Portal to Samsur","type":"Portal","wcid":42834,"cell":"012D0126","place":"dungeon","dest":{"cell":"977B000C","place":"outdoor","ns":-3.24,"ew":18.96},"desc":"This portal goes to Samsur, a Gharu'ndim town in the hills behind the Yushad Ridge. This is a good town for characters over level 10. In Samsur Meeting Hall.","id":1228}, + {"name":"Sawato Portal","type":"Portal","wcid":42849,"cell":"012E0126","place":"dungeon","dest":{"cell":"C95B0001","place":"outdoor","ns":-29.15,"ew":58.91},"desc":"This portal goes to Sawato, a village surrounded by the wetlands of the Blackmire Swamp. This is a good town for characters over level 30. In Sawato Meeting Hall.","id":1229}, + {"name":"Portal to Shoushi","type":"Portal","wcid":42840,"cell":"012F0126","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal goes to Shoushi, a Sho town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Shoushi Meeting Hall.","id":1230}, + {"name":"Portal to Tou-Tou","type":"Portal","wcid":42841,"cell":"01300126","place":"dungeon","dest":{"cell":"F5590034","place":"outdoor","ns":-30.41,"ew":94.69},"desc":"This portal goes to the Sho town of Tou-Tou, perched on the tip of the Tou-Tou peninsula. This is a good town for characters over level 20. In a dungeon (landblock 0130).","id":1231}, + {"name":"Tufa Portal","type":"Portal","wcid":42829,"cell":"01310126","place":"dungeon","dest":{"cell":"876C0008","place":"outdoor","ns":-14.77,"ew":6.06},"desc":"This portal goes to Tufa, the once peaceful desert oasis that was destroyed by Shadows during the Fourth Sending of Darkness. The residents have since regrouped in tents and buildings surrounded the crater of their former homes. This is a good town for characters over level 20. In Tufa Meeting Hall.","id":1232}, + {"name":"Uziz Portal","type":"Portal","wcid":42821,"cell":"01320126","place":"dungeon","dest":{"cell":"A260003C","place":"outdoor","ns":-24.78,"ew":28.41},"desc":"This portal goes to the town of Uziz in the heart of the Yushad Ridge. This is a good town for characters over level 20. In Uziz Meeting Hall.","id":1233}, + {"name":"Portal to Yanshi","type":"Portal","wcid":42847,"cell":"01330126","place":"dungeon","dest":{"cell":"B46F001E","place":"outdoor","ns":-12.63,"ew":42.36},"desc":"This portal goes to the Sho town of Yanshi on the edges of the Blackmire swamp. The original town was devastated by the Harbinger, who still lurks deep beneath the surface. This is a good town for characters over level 10. But stay away from the Harbinger. In Yanshi Meeting Hall.","id":1234}, + {"name":"Portal to Yaraq","type":"Portal","wcid":42824,"cell":"01340126","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal goes to Yaraq, a Gharu'ndim town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Yaraq Meeting Hall.","id":1235}, + {"name":"Portal to Zaikhal","type":"Portal","wcid":42831,"cell":"01350126","place":"dungeon","dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal goes to the Gharu'ndim capital, Zaikhal. This is a good town for characters over level 20. In Zaikhal Meeting Hall.","id":1236}, + {"name":"Surface Portal","type":"Portal","wcid":6085,"cell":"01360154","place":"dungeon","dest":{"cell":"C3600001","place":"outdoor","ns":-25.06,"ew":54.07},"desc":"In Empyrean Foundry.","id":1237}, + {"name":"Surface Portal","type":"Portal","wcid":6085,"cell":"0136029F","place":"dungeon","dest":{"cell":"C3600001","place":"outdoor","ns":-25.06,"ew":54.07},"desc":"In Empyrean Foundry.","id":1238}, + {"name":"Surface Portal","type":"Portal","wcid":6392,"cell":"01370136","place":"dungeon","dest":{"cell":"46A0000D","place":"outdoor","ns":26.47,"ew":-45.78},"desc":"In Artifex Vault.","id":1239}, + {"name":"Surface Portal","type":"Portal","wcid":6392,"cell":"0137018D","place":"dungeon","dest":{"cell":"46A0000D","place":"outdoor","ns":26.47,"ew":-45.78},"desc":"In Artifex Vault.","id":1240}, + {"name":"Surface Portal","type":"Portal","wcid":6392,"cell":"013702F4","place":"dungeon","dest":{"cell":"46A0000D","place":"outdoor","ns":26.47,"ew":-45.78},"desc":"In Artifex Vault.","id":1241}, + {"name":"Surface","type":"Portal","wcid":5110,"cell":"01380185","place":"dungeon","dest":{"cell":"86CD0008","place":"outdoor","ns":62.84,"ew":5.33},"desc":"In a dungeon (landblock 0138).","id":1242}, + {"name":"Surface","type":"Portal","wcid":5110,"cell":"013801E1","place":"dungeon","dest":{"cell":"86CD0008","place":"outdoor","ns":62.84,"ew":5.33},"desc":"In a dungeon (landblock 0138).","id":1243}, + {"name":"Surface Portal","type":"Portal","wcid":5668,"cell":"0139038C","place":"dungeon","dest":{"cell":"96DC0027","place":"outdoor","ns":74.74,"ew":18.53},"desc":"In Mage Academy.","id":1244}, + {"name":"Surface Portal","type":"Portal","wcid":5668,"cell":"01390398","place":"dungeon","dest":{"cell":"96DC0027","place":"outdoor","ns":74.74,"ew":18.53},"desc":"In Mage Academy.","id":1245}, + {"name":"Surface Portal","type":"Portal","wcid":5591,"cell":"013A027D","place":"dungeon","dest":{"cell":"3761000C","place":"outdoor","ns":-24.02,"ew":-57.79},"desc":"In a dungeon (landblock 013A).","id":1246}, + {"name":"Surface Portal","type":"Portal","wcid":5607,"cell":"013B0116","place":"dungeon","dest":{"cell":"C1740024","place":"outdoor","ns":-8.79,"ew":52.85},"desc":"In a dungeon (landblock 013B).","id":1247}, + {"name":"Surface Portal","type":"Portal","wcid":5607,"cell":"013B025A","place":"dungeon","dest":{"cell":"C1740024","place":"outdoor","ns":-8.79,"ew":52.85},"desc":"In a dungeon (landblock 013B).","id":1248}, + {"name":"Surface Portal","type":"Portal","wcid":5607,"cell":"013B0328","place":"dungeon","dest":{"cell":"C1740024","place":"outdoor","ns":-8.79,"ew":52.85},"desc":"In a dungeon (landblock 013B).","id":1249}, + {"name":"Surface Portal","type":"Portal","wcid":5605,"cell":"013C01F2","place":"dungeon","dest":{"cell":"99A60017","place":"outdoor","ns":31.5,"ew":20.73},"desc":"In Underground Forest.","id":1250}, + {"name":"Surface Portal","type":"Portal","wcid":5605,"cell":"013C01FD","place":"dungeon","dest":{"cell":"99A60017","place":"outdoor","ns":31.5,"ew":20.73},"desc":"In Underground Forest.","id":1251}, + {"name":"Surface Portal","type":"Portal","wcid":5518,"cell":"013D010B","place":"dungeon","dest":{"cell":"8387000E","place":"outdoor","ns":6.57,"ew":3.0},"desc":"In a dungeon (landblock 013D).","id":1252}, + {"name":"Surface Portal","type":"Portal","wcid":5518,"cell":"013D02D2","place":"dungeon","dest":{"cell":"8387000E","place":"outdoor","ns":6.57,"ew":3.0},"desc":"In a dungeon (landblock 013D).","id":1253}, + {"name":"Surface Portal","type":"Portal","wcid":5516,"cell":"013E0278","place":"dungeon","dest":{"cell":"868A0031","place":"outdoor","ns":8.54,"ew":5.94},"desc":"In Burial Temple.","id":1254}, + {"name":"Surface Portal","type":"Portal","wcid":5516,"cell":"013E0415","place":"dungeon","dest":{"cell":"868A0031","place":"outdoor","ns":8.54,"ew":5.94},"desc":"In Burial Temple.","id":1255}, + {"name":"Surface Portal","type":"Portal","wcid":5516,"cell":"013E028B","place":"dungeon","dest":{"cell":"868A0031","place":"outdoor","ns":8.54,"ew":5.94},"desc":"In Burial Temple.","id":1256}, + {"name":"Surface Portal","type":"Portal","wcid":5516,"cell":"013E01DB","place":"dungeon","dest":{"cell":"868A0031","place":"outdoor","ns":8.54,"ew":5.94},"desc":"In Burial Temple.","id":1257}, + {"name":"Surface Portal","type":"Portal","wcid":5516,"cell":"013E0223","place":"dungeon","dest":{"cell":"868A0031","place":"outdoor","ns":8.54,"ew":5.94},"desc":"In Burial Temple.","id":1258}, + {"name":"Surface","type":"Portal","wcid":5531,"cell":"013F01CA","place":"dungeon","dest":{"cell":"DF3C000C","place":"outdoor","ns":-53.57,"ew":76.58},"desc":"In Saadia's Retreat.","id":1259}, + {"name":"Surface Portal","type":"Portal","wcid":4922,"cell":"01400145","place":"dungeon","dest":{"cell":"3B32003C","place":"outdoor","ns":-61.58,"ew":-54.05},"desc":"In Virindi Fort.","id":1260}, + {"name":"Surface Portal","type":"Portal","wcid":4922,"cell":"014001A2","place":"dungeon","dest":{"cell":"3B32003C","place":"outdoor","ns":-61.58,"ew":-54.05},"desc":"In Virindi Fort.","id":1261}, + {"name":"Surface Portal","type":"Portal","wcid":4922,"cell":"01400205","place":"dungeon","dest":{"cell":"3B32003C","place":"outdoor","ns":-61.58,"ew":-54.05},"desc":"In Virindi Fort.","id":1262}, + {"name":"Surface","type":"Portal","wcid":5506,"cell":"01410113","place":"dungeon","dest":{"cell":"A141000D","place":"outdoor","ns":-49.49,"ew":27.02},"desc":"In Enkindled Souls.","id":1263}, + {"name":"Surface","type":"Portal","wcid":5506,"cell":"01410116","place":"dungeon","dest":{"cell":"A141000D","place":"outdoor","ns":-49.49,"ew":27.02},"desc":"In Enkindled Souls.","id":1264}, + {"name":"Surface","type":"Portal","wcid":5506,"cell":"014101B9","place":"dungeon","dest":{"cell":"A141000D","place":"outdoor","ns":-49.49,"ew":27.02},"desc":"In Enkindled Souls.","id":1265}, + {"name":"Surface Portal","type":"Portal","wcid":4950,"cell":"01420178","place":"dungeon","dest":{"cell":"7D870015","place":"outdoor","ns":6.54,"ew":-1.72},"desc":"In a dungeon (landblock 0142).","id":1266}, + {"name":"Surface","type":"Portal","wcid":4926,"cell":"0143010A","place":"dungeon","dest":{"cell":"66D40015","place":"outdoor","ns":68.1,"ew":-20.14},"desc":"In Phyntos Menace.","id":1267}, + {"name":"Surface Portal","type":"Portal","wcid":4972,"cell":"0144013E","place":"dungeon","dest":{"cell":"80650015","place":"outdoor","ns":-20.74,"ew":0.68},"desc":"In a dungeon (landblock 0144).","id":1268}, + {"name":"Surface Portal","type":"Portal","wcid":4972,"cell":"014401B9","place":"dungeon","dest":{"cell":"80650015","place":"outdoor","ns":-20.74,"ew":0.68},"desc":"In a dungeon (landblock 0144).","id":1269}, + {"name":"Surface","type":"Portal","wcid":4918,"cell":"01450188","place":"dungeon","dest":{"cell":"885A001D","place":"outdoor","ns":-29.53,"ew":7.21},"desc":"In Bone Lair.","id":1270}, + {"name":"Surface","type":"Portal","wcid":4918,"cell":"014501A3","place":"dungeon","dest":{"cell":"885A001D","place":"outdoor","ns":-29.53,"ew":7.21},"desc":"In Bone Lair.","id":1271}, + {"name":"Surface Portal","type":"Portal","wcid":5529,"cell":"01460159","place":"dungeon","dest":{"cell":"1553001F","place":"outdoor","ns":-34.87,"ew":-84.78},"desc":"In Mount Lethe Magma Tubes.","id":1272}, + {"name":"Surface Portal","type":"Portal","wcid":5528,"cell":"014602A4","place":"dungeon","dest":{"cell":"14550032","place":"outdoor","ns":-33.83,"ew":-85.27},"desc":"In Mount Lethe Magma Tubes.","id":1273}, + {"name":"Surface","type":"Portal","wcid":5525,"cell":"01470102","place":"dungeon","dest":{"cell":"3A860023","place":"outdoor","ns":5.45,"ew":-55.14},"desc":"In Mount Naipenset Caverns.","id":1274}, + {"name":"Surface","type":"Portal","wcid":5524,"cell":"01470208","place":"dungeon","dest":{"cell":"3986000C","place":"outdoor","ns":5.59,"ew":-56.15},"desc":"In Mount Naipenset Caverns.","id":1275}, + {"name":"Surface Portal","type":"Portal","wcid":5522,"cell":"0148014A","place":"dungeon","dest":{"cell":"D73C003C","place":"outdoor","ns":-53.62,"ew":70.81},"desc":"In A Small Ruin.","id":1276}, + {"name":"Surface Portal","type":"Portal","wcid":5514,"cell":"01490177","place":"dungeon","dest":{"cell":"DC370003","place":"outdoor","ns":-57.71,"ew":74.08},"desc":"In Thieves' Galleries.","id":1277}, + {"name":"Surface Portal","type":"Portal","wcid":5512,"cell":"014A0147","place":"dungeon","dest":{"cell":"87890029","place":"outdoor","ns":7.67,"ew":6.59},"desc":"In Mysterious Cave.","id":1278}, + {"name":"Surface Portal","type":"Portal","wcid":5510,"cell":"014B013C","place":"dungeon","dest":{"cell":"9D49003C","place":"outdoor","ns":-43.18,"ew":24.45},"desc":"In Winthura's Garden.","id":1279}, + {"name":"Surface Portal","type":"Portal","wcid":5510,"cell":"014B020D","place":"dungeon","dest":{"cell":"9D49003C","place":"outdoor","ns":-43.18,"ew":24.45},"desc":"In Winthura's Garden.","id":1280}, + {"name":"North Desert Edge","type":"Portal","wcid":1905,"cell":"014C0100","place":"dungeon","dest":{"cell":"7B790025","place":"outdoor","ns":-4.69,"ew":-3.07},"desc":"In Nevius Passage.","id":1281}, + {"name":"Surface Portal","type":"Portal","wcid":5508,"cell":"014C0139","place":"dungeon","dest":{"cell":"9A46000D","place":"outdoor","ns":-45.48,"ew":21.41},"desc":"In Nevius Passage.","id":1282}, + {"name":"Surface Portal","type":"Portal","wcid":5508,"cell":"014C020C","place":"dungeon","dest":{"cell":"9A46000D","place":"outdoor","ns":-45.48,"ew":21.41},"desc":"In Nevius Passage.","id":1283}, + {"name":"Surface Portal","type":"Portal","wcid":5504,"cell":"014D0194","place":"dungeon","dest":{"cell":"F757001D","place":"outdoor","ns":-31.88,"ew":96.01},"desc":"In Damp Caverns.","id":1284}, + {"name":"Surface","type":"Portal","wcid":5502,"cell":"014E0116","place":"dungeon","dest":{"cell":"F15A002D","place":"outdoor","ns":-29.54,"ew":91.36},"desc":"In Smugglers Hideaway.","id":1285}, + {"name":"Surface","type":"Portal","wcid":5502,"cell":"014E0259","place":"dungeon","dest":{"cell":"F15A002D","place":"outdoor","ns":-29.54,"ew":91.36},"desc":"In Smugglers Hideaway.","id":1286}, + {"name":"Surface Portal","type":"Portal","wcid":4167,"cell":"014F01B8","place":"dungeon","dest":{"cell":"C1840009","place":"outdoor","ns":3.7,"ew":52.64},"desc":"In Dungeon Maggreth.","id":1287}, + {"name":"Surface","type":"Portal","wcid":4928,"cell":"01500123","place":"dungeon","dest":{"cell":"CD8E000C","place":"outdoor","ns":12.0,"ew":62.17},"desc":"In a dungeon (landblock 0150).","id":1288}, + {"name":"Surface","type":"Portal","wcid":4928,"cell":"0150017D","place":"dungeon","dest":{"cell":"CD8E000C","place":"outdoor","ns":12.0,"ew":62.17},"desc":"In a dungeon (landblock 0150).","id":1289}, + {"name":"Surface Portal","type":"Portal","wcid":4962,"cell":"015101ED","place":"dungeon","dest":{"cell":"C5800005","place":"outdoor","ns":0.9,"ew":55.74},"desc":"In a dungeon (landblock 0151).","id":1290}, + {"name":"Surface Portal","type":"Portal","wcid":4964,"cell":"01520250","place":"dungeon","dest":{"cell":"BB820032","place":"outdoor","ns":2.23,"ew":48.29},"desc":"In a dungeon (landblock 0152).","id":1291}, + {"name":"Surface","type":"Portal","wcid":4966,"cell":"01530111","place":"dungeon","dest":{"cell":"D8560010","place":"outdoor","ns":-32.36,"ew":71.0},"desc":"In Shreth Hive.","id":1292}, + {"name":"Surface","type":"Portal","wcid":4966,"cell":"015302E8","place":"dungeon","dest":{"cell":"D8560010","place":"outdoor","ns":-32.36,"ew":71.0},"desc":"In Shreth Hive.","id":1293}, + {"name":"Surface","type":"Portal","wcid":4956,"cell":"0154017E","place":"dungeon","dest":{"cell":"D8540019","place":"outdoor","ns":-34.74,"ew":71.2},"desc":"In Stone Cathedral.","id":1294}, + {"name":"Surface Portal","type":"Portal","wcid":5203,"cell":"01550195","place":"dungeon","dest":{"cell":"967E003A","place":"outdoor","ns":-1.02,"ew":18.76},"desc":"In Musansayn's Vaults.","id":1295}, + {"name":"Surface","type":"Portal","wcid":5199,"cell":"0156011D","place":"dungeon","dest":{"cell":"7966003A","place":"outdoor","ns":-20.2,"ew":-4.45},"desc":"In a dungeon (landblock 0156).","id":1296}, + {"name":"Surface","type":"Portal","wcid":5199,"cell":"01560183","place":"dungeon","dest":{"cell":"7966003A","place":"outdoor","ns":-20.2,"ew":-4.45},"desc":"In a dungeon (landblock 0156).","id":1297}, + {"name":"Surface","type":"Portal","wcid":5201,"cell":"01570141","place":"dungeon","dest":{"cell":"7A640015","place":"outdoor","ns":-21.46,"ew":-4.1},"desc":"In Under-Cove Crypt.","id":1298}, + {"name":"Surface Portal","type":"Portal","wcid":4954,"cell":"01580127","place":"dungeon","dest":{"cell":"EB3D0035","place":"outdoor","ns":-52.67,"ew":86.67},"desc":"In a dungeon (landblock 0158).","id":1299}, + {"name":"Surface Portal","type":"Portal","wcid":4944,"cell":"01590195","place":"dungeon","dest":{"cell":"8F560018","place":"outdoor","ns":-32.38,"ew":12.74},"desc":"In a dungeon (landblock 0159).","id":1300}, + {"name":"Surface Portal","type":"Portal","wcid":4948,"cell":"015A010F","place":"dungeon","dest":{"cell":"99790022","place":"outdoor","ns":-5.04,"ew":20.9},"desc":"In a dungeon (landblock 015A).","id":1301}, + {"name":"Surface Portal","type":"Portal","wcid":4948,"cell":"015A01A6","place":"dungeon","dest":{"cell":"99790022","place":"outdoor","ns":-5.04,"ew":20.9},"desc":"In a dungeon (landblock 015A).","id":1302}, + {"name":"Surface Portal","type":"Portal","wcid":4940,"cell":"015B0168","place":"dungeon","dest":{"cell":"8A59003E","place":"outdoor","ns":-30.24,"ew":9.17},"desc":"In Unfinished Temple.","id":1303}, + {"name":"Surface Portal","type":"Portal","wcid":5128,"cell":"015C0115","place":"dungeon","dest":{"cell":"E23B0038","place":"outdoor","ns":-54.03,"ew":79.54},"desc":"In Nanto Rat Lair.","id":1304}, + {"name":"Magical Portal","type":"Portal","wcid":5114,"cell":"015D0100","place":"dungeon","dest":{"cell":"015D0187","place":"dungeon","name":"Mountain Cavern"},"desc":"In Mountain Cavern.","id":1305}, + {"name":"Lost City of Frore Portal","type":"Portal","wcid":5900,"cell":"015D0105","place":"dungeon","dest":{"cell":"01380180","place":"dungeon"},"minLevel":20,"desc":"In Mountain Cavern.","id":1306}, + {"name":"Magical Portal","type":"Portal","wcid":5113,"cell":"015D0107","place":"dungeon","dest":{"cell":"015D01EB","place":"dungeon","name":"Mountain Cavern"},"desc":"In Mountain Cavern.","id":1307}, + {"name":"Magical Portal","type":"Portal","wcid":5112,"cell":"015D010A","place":"dungeon","dest":{"cell":"015D022E","place":"dungeon","name":"Mountain Cavern"},"desc":"In Mountain Cavern.","id":1308}, + {"name":"Surface","type":"Portal","wcid":5110,"cell":"015D024C","place":"dungeon","dest":{"cell":"86CD0008","place":"outdoor","ns":62.84,"ew":5.33},"desc":"In Mountain Cavern.","id":1309}, + {"name":"Surface Portal","type":"Portal","wcid":4976,"cell":"015E015C","place":"dungeon","dest":{"cell":"828E001E","place":"outdoor","ns":12.18,"ew":2.35},"desc":"In Impious Temple.","id":1310}, + {"name":"Surface Portal","type":"Portal","wcid":4976,"cell":"015E0266","place":"dungeon","dest":{"cell":"828E001E","place":"outdoor","ns":12.18,"ew":2.35},"desc":"In Impious Temple.","id":1311}, + {"name":"Surface Portal","type":"Portal","wcid":4976,"cell":"015E0329","place":"dungeon","dest":{"cell":"828E001E","place":"outdoor","ns":12.18,"ew":2.35},"desc":"In Impious Temple.","id":1312}, + {"name":"Surface","type":"Portal","wcid":28715,"cell":"015F0220","place":"dungeon","dest":{"cell":"22DC0029","place":"outdoor","ns":74.12,"ew":-74.19},"desc":"In Dericost Ruin.","id":1313}, + {"name":"Surface","type":"Portal","wcid":28715,"cell":"015F0108","place":"dungeon","dest":{"cell":"22DC0029","place":"outdoor","ns":74.12,"ew":-74.19},"desc":"In Dericost Ruin.","id":1314}, + {"name":"Exit","type":"Portal","wcid":29795,"cell":"01600305","place":"dungeon","dest":{"cell":"016B0454","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 0160).","id":1315}, + {"name":"Exit","type":"Portal","wcid":29789,"cell":"0160010B","place":"dungeon","dest":{"cell":"02D80454","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 0160).","id":1316}, + {"name":"Exit","type":"Portal","wcid":29791,"cell":"016001E4","place":"dungeon","dest":{"cell":"01F202B0","place":"dungeon"},"desc":"In a dungeon (landblock 0160).","id":1317}, + {"name":"Exit","type":"Portal","wcid":29799,"cell":"01600270","place":"dungeon","dest":{"cell":"016A02B0","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 0160).","id":1318}, + {"name":"Exit","type":"Portal","wcid":29797,"cell":"0160030C","place":"dungeon","dest":{"cell":"01F00454","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 0160).","id":1319}, + {"name":"Exit","type":"Portal","wcid":29793,"cell":"0160027E","place":"dungeon","dest":{"cell":"02D902B0","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 0160).","id":1320}, + {"name":"Surface","type":"Portal","wcid":4960,"cell":"01610131","place":"dungeon","dest":{"cell":"E53B0038","place":"outdoor","ns":-54.01,"ew":81.88},"desc":"In Empyrean Garrison.","id":1321}, + {"name":"Surface","type":"Portal","wcid":4960,"cell":"01610264","place":"dungeon","dest":{"cell":"E53B0038","place":"outdoor","ns":-54.01,"ew":81.88},"desc":"In Empyrean Garrison.","id":1322}, + {"name":"Surface","type":"Portal","wcid":4938,"cell":"016201EC","place":"dungeon","dest":{"cell":"A7B3001E","place":"outdoor","ns":41.82,"ew":32.03},"desc":"In a dungeon (landblock 0162).","id":1323}, + {"name":"Surface","type":"Portal","wcid":4936,"cell":"016301A9","place":"dungeon","dest":{"cell":"AAB10020","place":"outdoor","ns":40.38,"ew":34.45},"desc":"In Holtburg Redoubt.","id":1324}, + {"name":"Surface Portal","type":"Portal","wcid":4896,"cell":"016401DB","place":"dungeon","dest":{"cell":"BF7E001D","place":"outdoor","ns":-0.67,"ew":51.19},"desc":"In a dungeon (landblock 0164).","id":1325}, + {"name":"Surface Portal","type":"Portal","wcid":4934,"cell":"01650165","place":"dungeon","dest":{"cell":"C88A0003","place":"outdoor","ns":8.74,"ew":58.1},"desc":"In a dungeon (landblock 0165).","id":1326}, + {"name":"Surface Portal","type":"Portal","wcid":4932,"cell":"01660157","place":"dungeon","dest":{"cell":"BA6B0015","place":"outdoor","ns":-15.92,"ew":47.1},"desc":"In a dungeon (landblock 0166).","id":1327}, + {"name":"Surface Portal","type":"Portal","wcid":4930,"cell":"016701A8","place":"dungeon","dest":{"cell":"9257003E","place":"outdoor","ns":-31.78,"ew":15.63},"desc":"In a dungeon (landblock 0167).","id":1328}, + {"name":"Surface Portal","type":"Portal","wcid":4924,"cell":"01680183","place":"dungeon","dest":{"cell":"E33E0033","place":"outdoor","ns":-52.08,"ew":80.3},"desc":"In a dungeon (landblock 0168).","id":1329}, + {"name":"Bandit Castle Portal","type":"Portal","wcid":1102,"cell":"0169012D","place":"dungeon","dest":{"cell":"BDD00006","place":"outdoor","ns":64.95,"ew":49.32},"desc":"In a dungeon (landblock 0169).","id":1330}, + {"name":"Surface Portal","type":"Portal","wcid":4911,"cell":"0169017E","place":"dungeon","dest":{"cell":"94D10012","place":"outdoor","ns":65.43,"ew":16.71},"desc":"In a dungeon (landblock 0169).","id":1331}, + {"name":"Surface","type":"Portal","wcid":29784,"cell":"0175010D","place":"dungeon","dest":{"cell":"EF0D0011","place":"outdoor","ns":-91.48,"ew":89.47},"desc":"In Muggy Font.","id":1332}, + {"name":"Surface","type":"Portal","wcid":29782,"cell":"0176010D","place":"dungeon","dest":{"cell":"EF0D002B","place":"outdoor","ns":-91.3,"ew":89.77},"desc":"In Humid Font.","id":1333}, + {"name":"Exit to Surface","type":"Portal","wcid":28262,"cell":"0177013F","place":"dungeon","dest":{"cell":"B86D003B","place":"outdoor","ns":-14.55,"ew":45.99},"desc":"In Mossy Cave.","id":1334}, + {"name":"Exit to Surface","type":"Portal","wcid":28262,"cell":"01770150","place":"dungeon","dest":{"cell":"B86D003B","place":"outdoor","ns":-14.55,"ew":45.99},"desc":"In Mossy Cave.","id":1335}, + {"name":"Exit to Surface","type":"Portal","wcid":28260,"cell":"01780246","place":"dungeon","dest":{"cell":"E8220007","place":"outdoor","ns":-74.07,"ew":83.7},"desc":"In Dark Mosswart Halls.","id":1336}, + {"name":"Destroyed Stonehold Portal","type":"Portal","wcid":4044,"cell":"0179013E","place":"dungeon","dest":{"cell":"64D5000B","place":"outdoor","ns":68.66,"ew":-21.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1337}, + {"name":"Destroyed Portal to Kryst","type":"Portal","wcid":8554,"cell":"01790140","place":"dungeon","dest":{"cell":"E822002A","place":"outdoor","ns":-74.59,"ew":84.2},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1338}, + {"name":"Destroyed Uziz Portal","type":"Portal","wcid":4036,"cell":"01790141","place":"dungeon","dest":{"cell":"A260003C","place":"outdoor","ns":-24.78,"ew":28.41},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1339}, + {"name":"Destroyed Portal to Tou-Tou","type":"Portal","wcid":4568,"cell":"01790152","place":"dungeon","dest":{"cell":"F5590034","place":"outdoor","ns":-30.41,"ew":94.69},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1340}, + {"name":"Destroyed Portal to Al-Arqas","type":"Portal","wcid":4571,"cell":"01790154","place":"dungeon","dest":{"cell":"8F58003B","place":"outdoor","ns":-31.3,"ew":13.22},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1341}, + {"name":"Destroyed Portal to Nanto","type":"Portal","wcid":4569,"cell":"0179015F","place":"dungeon","dest":{"cell":"E63E0022","place":"outdoor","ns":-52.19,"ew":82.45},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1342}, + {"name":"Destroyed Eastham Portal","type":"Portal","wcid":1016,"cell":"01790160","place":"dungeon","dest":{"cell":"CE940035","place":"outdoor","ns":16.92,"ew":63.48},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1343}, + {"name":"Destroyed Portal to Samsur","type":"Portal","wcid":1026,"cell":"01790161","place":"dungeon","dest":{"cell":"977B000C","place":"outdoor","ns":-3.24,"ew":18.96},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1344}, + {"name":"Destroyed Portal to Kara","type":"Portal","wcid":4041,"cell":"0179017C","place":"dungeon","dest":{"cell":"BA170039","place":"outdoor","ns":-83.54,"ew":47.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1345}, + {"name":"Destroyed Al-Jalima Portal","type":"Portal","wcid":5486,"cell":"01790184","place":"dungeon","dest":{"cell":"8588002C","place":"outdoor","ns":7.25,"ew":4.95},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1346}, + {"name":"Destroyed Portal to Xarabydun","type":"Portal","wcid":26640,"cell":"01790198","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1347}, + {"name":"Destroyed Plateau Portal","type":"Portal","wcid":4042,"cell":"017901A0","place":"dungeon","dest":{"cell":"49B70021","place":"outdoor","ns":44.54,"ew":-43.13},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1348}, + {"name":"Destroyed Lin Portal","type":"Portal","wcid":4567,"cell":"017901C0","place":"dungeon","dest":{"cell":"DC3C0011","place":"outdoor","ns":-53.91,"ew":74.3},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1349}, + {"name":"Destroyed Lytelthorpe Portal","type":"Portal","wcid":4570,"cell":"017901C1","place":"dungeon","dest":{"cell":"C0800007","place":"outdoor","ns":1.1,"ew":51.7},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1350}, + {"name":"Destroyed Portal to Rithwic","type":"Portal","wcid":1025,"cell":"017901C2","place":"dungeon","dest":{"cell":"C98C0028","place":"outdoor","ns":10.84,"ew":59.32},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1351}, + {"name":"Destroyed Sawato Portal","type":"Portal","wcid":4043,"cell":"017901E9","place":"dungeon","dest":{"cell":"C95B0001","place":"outdoor","ns":-29.15,"ew":58.91},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1352}, + {"name":"Destroyed Glenden Wood Portal","type":"Portal","wcid":1017,"cell":"017901EB","place":"dungeon","dest":{"cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1353}, + {"name":"Destroyed Portal to Arwic","type":"Portal","wcid":1013,"cell":"017901FF","place":"dungeon","dest":{"cell":"C6A90009","place":"outdoor","ns":33.27,"ew":56.65},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1354}, + {"name":"Destroyed Portal to Khayyaban","type":"Portal","wcid":4572,"cell":"01790203","place":"dungeon","dest":{"cell":"9F440012","place":"outdoor","ns":-47.45,"ew":25.62},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0179).","id":1355}, + {"name":"Freehold Portal","type":"Portal","wcid":8555,"cell":"01790205","place":"dungeon","dest":{"cell":"F224001A","place":"outdoor","ns":-73.01,"ew":91.99},"desc":"In a dungeon (landblock 0179).","id":1356}, + {"name":"Exit to Surface","type":"Portal","wcid":28264,"cell":"0179021B","place":"dungeon","dest":{"cell":"E720000D","place":"outdoor","ns":-75.89,"ew":83.0},"desc":"In a dungeon (landblock 0179).","id":1357}, + {"name":"Exit to Surface","type":"Portal","wcid":28268,"cell":"017A0136","place":"dungeon","dest":{"cell":"DA57001C","place":"outdoor","ns":-32.02,"ew":72.83},"desc":"In Banderling Hovel.","id":1358}, + {"name":"Destroyed Portal to Shoushi","type":"Portal","wcid":1027,"cell":"017A0141","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Banderling Hovel.","id":1359}, + {"name":"Exit to Surface","type":"Portal","wcid":28266,"cell":"017B01D1","place":"dungeon","dest":{"cell":"BA610004","place":"outdoor","ns":-24.0,"ew":46.89},"desc":"In a dungeon (landblock 017B).","id":1360}, + {"name":"Exit to Surface","type":"Portal","wcid":28099,"cell":"017C02AF","place":"dungeon","dest":{"cell":"3F4E0011","place":"outdoor","ns":-39.52,"ew":-51.28},"desc":"In a dungeon (landblock 017C).","id":1361}, + {"name":"Underway","type":"Portal","wcid":28103,"cell":"017D0100","place":"dungeon","dest":{"cell":"017E019E","place":"dungeon"},"minLevel":40,"desc":"In Hidden.","id":1362}, + {"name":"Portal to Surface","type":"Portal","wcid":28098,"cell":"017D016E","place":"dungeon","dest":{"cell":"B9610013","place":"outdoor","ns":-24.05,"ew":46.26},"desc":"In Hidden.","id":1363}, + {"name":"Tunnels","type":"Portal","wcid":28102,"cell":"017E0123","place":"dungeon","dest":{"cell":"0180019E","place":"dungeon"},"minLevel":60,"desc":"In a dungeon (landblock 017E).","id":1364}, + {"name":"Burun Hold","type":"Portal","wcid":28097,"cell":"017E019F","place":"dungeon","dest":{"cell":"017D016D","place":"dungeon","name":"Hidden"},"minLevel":40,"desc":"In a dungeon (landblock 017E).","id":1365}, + {"name":"Tunnels","type":"Portal","wcid":28102,"cell":"017F0111","place":"dungeon","dest":{"cell":"0180019E","place":"dungeon"},"minLevel":60,"desc":"In a dungeon (landblock 017F).","id":1366}, + {"name":"Exit to Surface","type":"Portal","wcid":28101,"cell":"017F02A7","place":"dungeon","dest":{"cell":"B11F0014","place":"outdoor","ns":-76.79,"ew":39.88},"desc":"In a dungeon (landblock 017F).","id":1367}, + {"name":"Halls","type":"Portal","wcid":28100,"cell":"01800123","place":"dungeon","dest":{"cell":"017F010F","place":"dungeon"},"minLevel":80,"desc":"In a dungeon (landblock 0180).","id":1368}, + {"name":"Underway","type":"Portal","wcid":28103,"cell":"0180019F","place":"dungeon","dest":{"cell":"017E019E","place":"dungeon"},"minLevel":40,"desc":"In a dungeon (landblock 0180).","id":1369}, + {"name":"Surface","type":"Portal","wcid":4157,"cell":"01810111","place":"dungeon","dest":{"cell":"AA870100","place":"building","ns":6.23,"ew":34.39},"desc":"In Dungeon Nye.","id":1370}, + {"name":"Surface","type":"Portal","wcid":4157,"cell":"01810162","place":"dungeon","dest":{"cell":"AA870100","place":"building","ns":6.23,"ew":34.39},"desc":"In Dungeon Nye.","id":1371}, + {"name":"Surface Portal","type":"Portal","wcid":4165,"cell":"01820174","place":"dungeon","dest":{"cell":"A0790025","place":"outdoor","ns":-4.71,"ew":26.49},"desc":"In Desert Mine.","id":1372}, + {"name":"Surface Portal","type":"Portal","wcid":4163,"cell":"018301B0","place":"dungeon","dest":{"cell":"98770026","place":"outdoor","ns":-6.22,"ew":20.06},"desc":"In Dungeon Binar.","id":1373}, + {"name":"Surface Portal","type":"Portal","wcid":4161,"cell":"0184016D","place":"dungeon","dest":{"cell":"D7510013","place":"outdoor","ns":-36.89,"ew":70.34},"desc":"In Dungeon Mei.","id":1374}, + {"name":"Surface Portal","type":"Portal","wcid":4159,"cell":"01850208","place":"dungeon","dest":{"cell":"A3A9003E","place":"outdoor","ns":33.83,"ew":29.2},"desc":"In Daiklos Dungeon.","id":1375}, + {"name":"Surface Portal","type":"Portal","wcid":4141,"cell":"0186012F","place":"dungeon","dest":{"cell":"424E0040","place":"outdoor","ns":-38.81,"ew":-48.37},"desc":"In Sclavus Keep.","id":1376}, + {"name":"Riverbend","type":"Portal","wcid":1906,"cell":"018601DD","place":"dungeon","dest":{"cell":"CE7C0025","place":"outdoor","ns":-2.29,"ew":63.29},"desc":"In Sclavus Keep.","id":1377}, + {"name":"Surface","type":"Portal","wcid":1604,"cell":"0187011A","place":"dungeon","dest":{"cell":"C4A80005","place":"outdoor","ns":32.88,"ew":54.94},"desc":"In A Ruin.","id":1378}, + {"name":"Beyond the Mines of Despair","type":"Portal","wcid":8969,"cell":"01880101","place":"dungeon","dest":{"cell":"02AB0160","place":"dungeon"},"desc":"In Mines of Despair.","id":1379}, + {"name":"Surface","type":"Portal","wcid":4054,"cell":"018802FA","place":"dungeon","dest":{"cell":"C7210100","place":"building","ns":-75.45,"ew":57.28},"desc":"In Mines of Despair.","id":1380}, + {"name":"Surface Portal","type":"Portal","wcid":4205,"cell":"01890125","place":"dungeon","dest":{"cell":"A15F0022","place":"outdoor","ns":-25.84,"ew":27.31},"desc":"In Grievous Vault.","id":1381}, + {"name":"Surface Portal","type":"Portal","wcid":4205,"cell":"0189019C","place":"dungeon","dest":{"cell":"A15F0022","place":"outdoor","ns":-25.84,"ew":27.31},"desc":"In Grievous Vault.","id":1382}, + {"name":"Destroyed Portal to Samsur","type":"Portal","wcid":1026,"cell":"01890302","place":"dungeon","dest":{"cell":"977B000C","place":"outdoor","ns":-3.24,"ew":18.96},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Grievous Vault.","id":1383}, + {"name":"Surface Portal","type":"Portal","wcid":4205,"cell":"0189031A","place":"dungeon","dest":{"cell":"A15F0022","place":"outdoor","ns":-25.84,"ew":27.31},"desc":"In Grievous Vault.","id":1384}, + {"name":"Portal to Bluespire","type":"Portal","wcid":42825,"cell":"018A0100","place":"dungeon","dest":{"cell":"21B00017","place":"outdoor","ns":39.54,"ew":-75.35},"desc":"This portal goes to the town of Bluespire on the island of Marae Lassel. This is a good town for characters over level 10. In a dungeon (landblock 018A).","id":1385}, + {"name":"Portal to Redspire","type":"Portal","wcid":42836,"cell":"018A0101","place":"dungeon","dest":{"cell":"17B2002A","place":"outdoor","ns":40.56,"ew":-83.0},"desc":"This portal goes to the town of Redspire on the island of Marae Lassel. This is a good town for characters over level 10. In a dungeon (landblock 018A).","id":1386}, + {"name":"Ahurenga Portal","type":"Portal","wcid":42827,"cell":"018A0102","place":"dungeon","dest":{"cell":"0FB90009","place":"outdoor","ns":46.09,"ew":-89.77},"desc":"This portal goes to Ahurenga, the home of the Hea Tumeroks in the marshes of western Marae Lassel. This is a good town for characters over level 40. In a dungeon (landblock 018A).","id":1387}, + {"name":"Portal to Linvak Tukal","type":"Portal","wcid":8401,"cell":"018A0103","place":"dungeon","dest":{"cell":"A21E001A","place":"outdoor","ns":-77.79,"ew":28.0},"desc":"This portal goes to Linvak Tukal, the fortress bastion of our Lugian allies in the Linvak Range. This is a good town for characters over level 40. In a dungeon (landblock 018A).","id":1388}, + {"name":"Base of the Timaru Plateau Portal","type":"Portal","wcid":11959,"cell":"018A010C","place":"dungeon","dest":{"cell":"1EB60013","place":"outdoor","ns":43.9,"ew":-77.71},"desc":"In a dungeon (landblock 018A).","id":1389}, + {"name":"Portal to Xarabydun","type":"Portal","wcid":42832,"cell":"018A010F","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"This portal goes to the town of Xarabydun, in the southern reaches of the A'mun desert. This is a good town for characters over level 10, but be careful -- the surrounding area can be a bit rough. In a dungeon (landblock 018A).","id":1390}, + {"name":"Bandit Castle Portal","type":"Portal","wcid":1102,"cell":"018A0117","place":"dungeon","dest":{"cell":"BDD00006","place":"outdoor","ns":64.95,"ew":49.32},"desc":"In a dungeon (landblock 018A).","id":1391}, + {"name":"Abandoned Mine","type":"Portal","wcid":1595,"cell":"018A0121","place":"dungeon","dest":{"cell":"01C9022D","place":"dungeon","name":"Abandoned Mine"},"desc":"In a dungeon (landblock 018A).","id":1392}, + {"name":"Surface","type":"Portal","wcid":2555,"cell":"018A012B","place":"dungeon","dest":{"cell":"90D00107","place":"building","ns":64.8,"ew":13.65},"desc":"In a dungeon (landblock 018A).","id":1393}, + {"name":"Jungle Shadows","type":"Portal","wcid":8497,"cell":"018A0167","place":"dungeon","dest":{"cell":"02BB0197","place":"dungeon"},"desc":"In a dungeon (landblock 018A).","id":1394}, + {"name":"Desert March Portal","type":"Portal","wcid":9005,"cell":"018A0168","place":"dungeon","dest":{"cell":"02AA022F","place":"dungeon","name":"Desert March"},"desc":"In a dungeon (landblock 018A).","id":1395}, + {"name":"The Floating City","type":"Portal","wcid":8190,"cell":"018A0169","place":"dungeon","dest":{"cell":"02D101EE","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 018A).","id":1396}, + {"name":"Portal to Samsur","type":"Portal","wcid":42834,"cell":"018A01E3","place":"dungeon","dest":{"cell":"977B000C","place":"outdoor","ns":-3.24,"ew":18.96},"desc":"This portal goes to Samsur, a Gharu'ndim town in the hills behind the Yushad Ridge. This is a good town for characters over level 10. In a dungeon (landblock 018A).","id":1397}, + {"name":"Portal to Rithwic","type":"Portal","wcid":42817,"cell":"018A01E4","place":"dungeon","dest":{"cell":"C98C0028","place":"outdoor","ns":10.84,"ew":59.32},"desc":"This portal goes to Rithwic, an Aluvian town on the shores of Lake Blessed. This is a good town for characters over level 10. In a dungeon (landblock 018A).","id":1398}, + {"name":"Qalaba'r Portal","type":"Portal","wcid":1024,"cell":"018A01E5","place":"dungeon","dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"desc":"In a dungeon (landblock 018A).","id":1399}, + {"name":"Sawato Portal","type":"Portal","wcid":42849,"cell":"018A01E6","place":"dungeon","dest":{"cell":"C95B0001","place":"outdoor","ns":-29.15,"ew":58.91},"desc":"This portal goes to Sawato, a village surrounded by the wetlands of the Blackmire Swamp. This is a good town for characters over level 30. In a dungeon (landblock 018A).","id":1400}, + {"name":"Portal to Greenspire","type":"Portal","wcid":42826,"cell":"018A01E7","place":"dungeon","dest":{"cell":"2BB5003C","place":"outdoor","ns":43.21,"ew":-66.8},"desc":"This portal goes to the town of Greenspire on the island of Marae Lassel. This is a good town for characters over level 10. In a dungeon (landblock 018A).","id":1401}, + {"name":"Portal to Dryreach","type":"Portal","wcid":5637,"cell":"018A01E9","place":"dungeon","dest":{"cell":"DB75003B","place":"outdoor","ns":-8.08,"ew":74.03},"desc":"This portal goes to the Aluvian town of Dryreach, besieged by renegade Tumeroks. Due to its besieged status, Dryreach is only accessible with the appropriate key. This is a good town for characters over level 40. In a dungeon (landblock 018A).","id":1402}, + {"name":"Candeth Keep Portal","type":"Portal","wcid":24579,"cell":"018A01E9","place":"dungeon","dest":{"cell":"2B120029","place":"outdoor","ns":-87.54,"ew":-67.05},"desc":"In a dungeon (landblock 018A).","id":1403}, + {"name":"Plateau Portal","type":"Portal","wcid":42812,"cell":"018A01EA","place":"dungeon","dest":{"cell":"49B70021","place":"outdoor","ns":44.54,"ew":-43.13},"desc":"This portal goes to the Plateau Village, a remote settlement in the forests of Northwestern Osteth. This is a good town for characters over level 40. In a dungeon (landblock 018A).","id":1404}, + {"name":"Portal to Shoushi","type":"Portal","wcid":42840,"cell":"018A01EC","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal goes to Shoushi, a Sho town where many new adventurers enter Dereth. This is a good town for characters of all levels. In a dungeon (landblock 018A).","id":1405}, + {"name":"Portal to Yaraq","type":"Portal","wcid":42824,"cell":"018A01ED","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal goes to Yaraq, a Gharu'ndim town where many new adventurers enter Dereth. This is a good town for characters of all levels. In a dungeon (landblock 018A).","id":1406}, + {"name":"Portal to Nanto","type":"Portal","wcid":42843,"cell":"018A01F0","place":"dungeon","dest":{"cell":"E63E0022","place":"outdoor","ns":-52.19,"ew":82.45},"desc":"This portal goes to Nanto, a sleepy Sho town. This is a good town for characters over level 10. In a dungeon (landblock 018A).","id":1407}, + {"name":"Stonehold Portal","type":"Portal","wcid":42811,"cell":"018A01F1","place":"dungeon","dest":{"cell":"64D5000B","place":"outdoor","ns":68.66,"ew":-21.82},"desc":"This portal goes to Stonehold. a remote village found in the westernmost reaches of the Esper mountain range. This is a good town for characters over level 50. In a dungeon (landblock 018A).","id":1408}, + {"name":"Portal to Yanshi","type":"Portal","wcid":42847,"cell":"018A01F2","place":"dungeon","dest":{"cell":"B46F001E","place":"outdoor","ns":-12.63,"ew":42.36},"desc":"This portal goes to the Sho town of Yanshi on the edges of the Blackmire swamp. The original town was devastated by the Harbinger, who still lurks deep beneath the surface. This is a good town for characters over level 10. But stay away from the Harbinger. In a dungeon (landblock 018A).","id":1409}, + {"name":"Portal to Zaikhal","type":"Portal","wcid":42831,"cell":"018A01F4","place":"dungeon","dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal goes to the Gharu'ndim capital, Zaikhal. This is a good town for characters over level 20. In a dungeon (landblock 018A).","id":1410}, + {"name":"Wai Jhou Portal","type":"Portal","wcid":4218,"cell":"018A01F5","place":"dungeon","dest":{"cell":"3F310007","place":"outdoor","ns":-62.13,"ew":-51.45},"desc":"In a dungeon (landblock 018A).","id":1411}, + {"name":"Portal to Tou-Tou","type":"Portal","wcid":42841,"cell":"018A01F6","place":"dungeon","dest":{"cell":"F5590034","place":"outdoor","ns":-30.41,"ew":94.69},"desc":"This portal goes to the Sho town of Tou-Tou, perched on the tip of the Tou-Tou peninsula. This is a good town for characters over level 20. In a dungeon (landblock 018A).","id":1412}, + {"name":"Tufa Portal","type":"Portal","wcid":42829,"cell":"018A01F7","place":"dungeon","dest":{"cell":"876C0008","place":"outdoor","ns":-14.77,"ew":6.06},"desc":"This portal goes to Tufa, the once peaceful desert oasis that was destroyed by Shadows during the Fourth Sending of Darkness. The residents have since regrouped in tents and buildings surrounded the crater of their former homes. This is a good town for characters over level 20. In a dungeon (landblock 018A).","id":1413}, + {"name":"Uziz Portal","type":"Portal","wcid":42821,"cell":"018A01F8","place":"dungeon","dest":{"cell":"A260003C","place":"outdoor","ns":-24.78,"ew":28.41},"desc":"This portal goes to the town of Uziz in the heart of the Yushad Ridge. This is a good town for characters over level 20. In a dungeon (landblock 018A).","id":1414}, + {"name":"Surface","type":"Portal","wcid":22756,"cell":"018A0201","place":"dungeon","dest":{"cell":"7F15002E","place":"outdoor","ns":-84.62,"ew":0.22},"desc":"In a dungeon (landblock 018A).","id":1415}, + {"name":"Danby's Outpost","type":"Portal","wcid":9684,"cell":"018A0205","place":"dungeon","dest":{"cell":"5A9C0004","place":"outdoor","ns":23.17,"ew":-29.85},"desc":"In a dungeon (landblock 018A).","id":1416}, + {"name":"Portal to Cragstone","type":"Portal","wcid":42818,"cell":"018A0206","place":"dungeon","dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal goes to the Aluvian capital, Cragstone. This is a good town for characters over level 10. In a dungeon (landblock 018A).","id":1417}, + {"name":"Baishi Portal","type":"Portal","wcid":42845,"cell":"018A0207","place":"dungeon","dest":{"cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9},"desc":"This portal goes to Baishi, a town well-known for its sake and the madman that desires it. This is good town for characters over level 40. In a dungeon (landblock 018A).","id":1418}, + {"name":"Ayan Baqur Portal","type":"Portal","wcid":7194,"cell":"018A0208","place":"dungeon","dest":{"cell":"1133001F","place":"outdoor","ns":-60.46,"ew":-87.98},"desc":"In a dungeon (landblock 018A).","id":1419}, + {"name":"Portal to Arwic","type":"Portal","wcid":42819,"cell":"018A0209","place":"dungeon","dest":{"cell":"C6A90009","place":"outdoor","ns":33.27,"ew":56.65},"desc":"This portal goes to Arwic, a walled Aluvian town that has fully recovered from a devastating attack by a Shadow Spire. This is a good town for characters over level 20. In a dungeon (landblock 018A).","id":1420}, + {"name":"Eastham Portal","type":"Portal","wcid":42815,"cell":"018A0210","place":"dungeon","dest":{"cell":"CE940035","place":"outdoor","ns":16.92,"ew":63.48},"desc":"This portal goes to Eastham, a coastal Aluvian town that contains a portal to Asheron's island home. This is a good town for characters over level 20. In a dungeon (landblock 018A).","id":1421}, + {"name":"Vesayen Isles Portal","type":"Portal","wcid":8618,"cell":"018A0211","place":"dungeon","dest":{"cell":"E5240007","place":"outdoor","ns":-72.51,"ew":81.3},"desc":"In a dungeon (landblock 018A).","id":1422}, + {"name":"Singularity Caul","type":"Portal","wcid":10794,"cell":"018A0215","place":"dungeon","dest":{"cell":"09040008","place":"outdoor","ns":-97.96,"ew":-94.7},"quest":true,"desc":"In a dungeon (landblock 018A).","id":1423}, + {"name":"Al-Jalima Portal","type":"Portal","wcid":42830,"cell":"018A0216","place":"dungeon","dest":{"cell":"8588002C","place":"outdoor","ns":7.25,"ew":4.95},"desc":"This portal goes to Al-Jalima, the Gharu'ndim settlement located between the prominent cities of Zaikhal and Samsur. This is a good town for characters over level 20. In a dungeon (landblock 018A).","id":1424}, + {"name":"Fort Tethana Portal","type":"Portal","wcid":4040,"cell":"018A021E","place":"dungeon","dest":{"cell":"2681001D","place":"outdoor","ns":1.7,"ew":-71.23},"desc":"In a dungeon (landblock 018A).","id":1425}, + {"name":"Portal to Al-Arqas","type":"Portal","wcid":42823,"cell":"018A0224","place":"dungeon","dest":{"cell":"8F58003B","place":"outdoor","ns":-31.3,"ew":13.22},"desc":"This portal goes to the Gharu'ndim town of Al-Arqas in the depths of the A'mun desert. This is a good town for characters over level 10. In a dungeon (landblock 018A).","id":1426}, + {"name":"Freehold Portal","type":"Portal","wcid":8555,"cell":"018A0231","place":"dungeon","dest":{"cell":"F224001A","place":"outdoor","ns":-73.01,"ew":91.99},"desc":"In a dungeon (landblock 018A).","id":1427}, + {"name":"Glenden Wood Portal","type":"Portal","wcid":42814,"cell":"018A0248","place":"dungeon","dest":{"cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45},"desc":"This portal goes to Glenden Wood, a village surrounded by the tall trees of the Tiofor Woods. Despite the truce between Queen Elysa and King Varicci, the town is besieged on all sides by Viamontian soldiers. This is a good town for characters over level 40. In a dungeon (landblock 018A).","id":1428}, + {"name":"Mayoi Portal","type":"Portal","wcid":42842,"cell":"018A024E","place":"dungeon","dest":{"cell":"E6320021","place":"outdoor","ns":-61.91,"ew":82.5},"desc":"This portal goes to Mayoi, a coastal settlement renowned for Shoyanen Kenchu, the master mage of the Sho people, who lives in a spire on the outskirts of town. This is a good town for characters over level 30. In a dungeon (landblock 018A).","id":1429}, + {"name":"Portal to Hebian-To","type":"Portal","wcid":42846,"cell":"018A025A","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal goes to the Sho capital, Hebian-To. This is a good town for characters over level 10. In a dungeon (landblock 018A).","id":1430}, + {"name":"Oolutanga's Refuge","type":"Portal","wcid":22775,"cell":"018A025B","place":"dungeon","dest":{"cell":"F6820033","place":"outdoor","ns":2.26,"ew":95.46},"desc":"In a dungeon (landblock 018A).","id":1431}, + {"name":"Aerlinthe Island Portal","type":"Portal","wcid":7413,"cell":"018A025F","place":"dungeon","dest":{"cell":"BAE8001D","place":"outdoor","ns":84.09,"ew":47.2},"minLevel":40,"desc":"In a dungeon (landblock 018A).","id":1432}, + {"name":"Lytelthorpe Portal","type":"Portal","wcid":42816,"cell":"018A0260","place":"dungeon","dest":{"cell":"C0800007","place":"outdoor","ns":1.1,"ew":51.7},"desc":"This portal goes to the town of Lytelthorpe, an Aluvian settlement surrounded by rich farmlands. This is a good town for characters over level 10. In a dungeon (landblock 018A).","id":1433}, + {"name":"Portal to Holtburg","type":"Portal","wcid":42820,"cell":"018A026C","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal goes to Holtburg, an Aluvian town where many new adventurers enter Dereth. This is a good town for characters of all levels. In a dungeon (landblock 018A).","id":1434}, + {"name":"Portal to Kara","type":"Portal","wcid":42848,"cell":"018A026D","place":"dungeon","dest":{"cell":"BA170039","place":"outdoor","ns":-83.54,"ew":47.6},"desc":"This portal goes to the town of Kara, hidden deep in the Linvak range. This is a good town for characters over level 40. In a dungeon (landblock 018A).","id":1435}, + {"name":"Portal to Khayyaban","type":"Portal","wcid":42822,"cell":"018A026E","place":"dungeon","dest":{"cell":"9F440012","place":"outdoor","ns":-47.45,"ew":25.62},"desc":"This portal goes to the town of Khayyaban on the Yushad Ridge. This is a good town for characters over level 20. In a dungeon (landblock 018A).","id":1436}, + {"name":"Portal to Kryst","type":"Portal","wcid":42850,"cell":"018A026F","place":"dungeon","dest":{"cell":"E822002A","place":"outdoor","ns":-74.59,"ew":84.2},"desc":"This portal goes to the town of Kryst on the Vesayen archipelago. This is a good town for characters over level 20. In a dungeon (landblock 018A).","id":1437}, + {"name":"Lin Portal","type":"Portal","wcid":42844,"cell":"018A0270","place":"dungeon","dest":{"cell":"DC3C0011","place":"outdoor","ns":-53.91,"ew":74.3},"desc":"This portal goes to Lin, a small town nestled in a valley located by the foothills of the Linvak Mountains. This is a good town for characters over level 20. In a dungeon (landblock 018A).","id":1438}, + {"name":"Surface","type":"Portal","wcid":22760,"cell":"018A0274","place":"dungeon","dest":{"cell":"7FEE0024","place":"outdoor","ns":88.76,"ew":0.08},"desc":"In a dungeon (landblock 018A).","id":1439}, + {"name":"Surface","type":"Portal","wcid":3637,"cell":"018B01BF","place":"dungeon","dest":{"cell":"B59D001E","place":"outdoor","ns":24.18,"ew":43.23},"desc":"In a dungeon (landblock 018B).","id":1440}, + {"name":"Surface","type":"Portal","wcid":3652,"cell":"018C0195","place":"dungeon","dest":{"cell":"8FD80011","place":"outdoor","ns":70.86,"ew":12.71},"desc":"In Crater Lair.","id":1441}, + {"name":"Deeper Catacombs","type":"Portal","wcid":24228,"cell":"018C011C","place":"dungeon","dest":{"cell":"57510251","place":"dungeon"},"minLevel":30,"desc":"In Crater Lair.","id":1442}, + {"name":"Surface","type":"Portal","wcid":3650,"cell":"018D01C2","place":"dungeon","dest":{"cell":"C1BB002C","place":"outdoor","ns":48.02,"ew":52.96},"desc":"In Olthoi Tunnels.","id":1443}, + {"name":"Deeper Catacombs","type":"Portal","wcid":24233,"cell":"018D0109","place":"dungeon","dest":{"cell":"57520260","place":"dungeon"},"minLevel":40,"desc":"In Olthoi Tunnels.","id":1444}, + {"name":"Surface","type":"Portal","wcid":28826,"cell":"018E037A","place":"dungeon","dest":{"cell":"45F20024","place":"outdoor","ns":92.0,"ew":-46.3},"desc":"In Abayar's Laboratory.","id":1445}, + {"name":"Abayar's Study","type":"Portal","wcid":28823,"cell":"018E0103","place":"dungeon","dest":{"cell":"01990175","place":"dungeon"},"minLevel":90,"quest":true,"desc":"In Abayar's Laboratory.","id":1446}, + {"name":"Destroyed Qalaba'r Portal","type":"Portal","wcid":1023,"cell":"018F0106","place":"dungeon","dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Carved Cave.","id":1447}, + {"name":"Halls of the Lost Light","type":"Portal","wcid":1430,"cell":"018F010A","place":"dungeon","dest":{"cell":"01CE01C9","place":"dungeon"},"desc":"In Carved Cave.","id":1448}, + {"name":"Direlands Midland Portal","type":"Portal","wcid":3613,"cell":"018F010A","place":"dungeon","dest":{"cell":"2E110031","place":"outdoor","ns":-88.31,"ew":-64.5},"minLevel":21,"desc":"In Carved Cave.","id":1449}, + {"name":"Surface","type":"Portal","wcid":3631,"cell":"018F022B","place":"dungeon","dest":{"cell":"8088000F","place":"outdoor","ns":7.52,"ew":0.59},"desc":"In Carved Cave.","id":1450}, + {"name":"Surface","type":"Portal","wcid":3631,"cell":"018F024B","place":"dungeon","dest":{"cell":"8088000F","place":"outdoor","ns":7.52,"ew":0.59},"desc":"In Carved Cave.","id":1451}, + {"name":"Surface","type":"Portal","wcid":3633,"cell":"019001E4","place":"dungeon","dest":{"cell":"A11C000C","place":"outdoor","ns":-79.16,"ew":27.01},"desc":"In Old Mine.","id":1452}, + {"name":"Surface","type":"Portal","wcid":3633,"cell":"019001F9","place":"dungeon","dest":{"cell":"A11C000C","place":"outdoor","ns":-79.16,"ew":27.01},"desc":"In Old Mine.","id":1453}, + {"name":"Surface","type":"Portal","wcid":3635,"cell":"019101DA","place":"dungeon","dest":{"cell":"F45A0032","place":"outdoor","ns":-29.79,"ew":93.86},"desc":"In Mountain Sewer.","id":1454}, + {"name":"Surface","type":"Portal","wcid":3635,"cell":"01910210","place":"dungeon","dest":{"cell":"F45A0032","place":"outdoor","ns":-29.79,"ew":93.86},"desc":"In Mountain Sewer.","id":1455}, + {"name":"Surface","type":"Portal","wcid":3641,"cell":"01920100","place":"dungeon","dest":{"cell":"388C003A","place":"outdoor","ns":10.24,"ew":-56.41},"desc":"In a dungeon (landblock 0192).","id":1456}, + {"name":"Surface","type":"Portal","wcid":3641,"cell":"019201A9","place":"dungeon","dest":{"cell":"388C003A","place":"outdoor","ns":10.24,"ew":-56.41},"desc":"In a dungeon (landblock 0192).","id":1457}, + {"name":"Surface","type":"Portal","wcid":3639,"cell":"0193014E","place":"dungeon","dest":{"cell":"39410003","place":"outdoor","ns":-49.71,"ew":-56.27},"desc":"In Knath Lair.","id":1458}, + {"name":"Greater K'nath Lair","type":"Portal","wcid":28790,"cell":"0193010D","place":"dungeon","dest":{"cell":"01930187","place":"dungeon","name":"Knath Lair"},"minLevel":50,"desc":"In Knath Lair.","id":1459}, + {"name":"Knath Lair","type":"Portal","wcid":3638,"cell":"01930184","place":"dungeon","dest":{"cell":"0193012A","place":"dungeon","name":"Knath Lair"},"desc":"In Knath Lair.","id":1460}, + {"name":"K'nath Lair","type":"Portal","wcid":28777,"cell":"0193011D","place":"dungeon","dest":{"cell":"01930151","place":"dungeon","name":"Knath Lair"},"desc":"In Knath Lair.","id":1461}, + {"name":"Surface","type":"Portal","wcid":28805,"cell":"01940117","place":"dungeon","dest":{"cell":"35EA002F","place":"outdoor","ns":85.9,"ew":-58.96},"desc":"In Ruined Empyrean Vault.","id":1462}, + {"name":"Surface","type":"Portal","wcid":28805,"cell":"0194010D","place":"dungeon","dest":{"cell":"35EA002F","place":"outdoor","ns":85.9,"ew":-58.96},"desc":"In Ruined Empyrean Vault.","id":1463}, + {"name":"Xi Ru's Library","type":"Portal","wcid":29960,"cell":"019502A0","place":"dungeon","dest":{"cell":"0195020A","place":"dungeon","name":"Xi Ru's Chapel"},"quest":true,"desc":"In Xi Ru's Chapel.","id":1464}, + {"name":"Xi Ru's Crypt","type":"Portal","wcid":29959,"cell":"019502C5","place":"dungeon","dest":{"cell":"0196023D","place":"dungeon"},"quest":true,"desc":"In Xi Ru's Chapel.","id":1465}, + {"name":"Xi Ru's Chapel Exterior","type":"Portal","wcid":28982,"cell":"019502E0","place":"dungeon","dest":{"cell":"EC0D002C","place":"outdoor","ns":-91.16,"ew":87.42},"desc":"In Xi Ru's Chapel.","id":1466}, + {"name":"Xi Ru's Remembrance","type":"Portal","wcid":29961,"cell":"019502F4","place":"dungeon","dest":{"cell":"019602E2","place":"dungeon"},"quest":true,"desc":"In Xi Ru's Chapel.","id":1467}, + {"name":"Xi Ru's Chapel","type":"Portal","wcid":28981,"cell":"01950557","place":"dungeon","dest":{"cell":"019502DF","place":"dungeon","name":"Xi Ru's Chapel"},"quest":true,"desc":"In Xi Ru's Chapel.","id":1468}, + {"name":"Xi Ru's Chapel","type":"Portal","wcid":28981,"cell":"019606FB","place":"dungeon","dest":{"cell":"019502DF","place":"dungeon","name":"Xi Ru's Chapel"},"quest":true,"desc":"In a dungeon (landblock 0196).","id":1469}, + {"name":"Xi Ru's Chapel","type":"Portal","wcid":28981,"cell":"0196010B","place":"dungeon","dest":{"cell":"019502DF","place":"dungeon","name":"Xi Ru's Chapel"},"quest":true,"desc":"In a dungeon (landblock 0196).","id":1470}, + {"name":"Surface","type":"Portal","wcid":29360,"cell":"0197035C","place":"dungeon","dest":{"cell":"2CE8001B","place":"outdoor","ns":83.92,"ew":-66.38},"desc":"In a dungeon (landblock 0197).","id":1471}, + {"name":"Surface","type":"Portal","wcid":29360,"cell":"01970108","place":"dungeon","dest":{"cell":"2CE8001B","place":"outdoor","ns":83.92,"ew":-66.38},"desc":"In a dungeon (landblock 0197).","id":1472}, + {"name":"Surface","type":"Portal","wcid":29787,"cell":"0198010D","place":"dungeon","dest":{"cell":"EF0D001C","place":"outdoor","ns":-91.17,"ew":89.63},"desc":"In Steamy Font.","id":1473}, + {"name":"Surface","type":"Portal","wcid":28824,"cell":"01990175","place":"dungeon","dest":{"cell":"45F20024","place":"outdoor","ns":92.0,"ew":-46.3},"desc":"In a dungeon (landblock 0199).","id":1474}, + {"name":"Surface","type":"Portal","wcid":2388,"cell":"019A0214","place":"dungeon","dest":{"cell":"8FD20007","place":"outdoor","ns":66.72,"ew":12.48},"desc":"In Crater Caves Dungeon.","id":1475}, + {"name":"Surface","type":"Portal","wcid":2388,"cell":"019A02D4","place":"dungeon","dest":{"cell":"8FD20007","place":"outdoor","ns":66.72,"ew":12.48},"desc":"In Crater Caves Dungeon.","id":1476}, + {"name":"Surface","type":"Portal","wcid":2388,"cell":"019A02DE","place":"dungeon","dest":{"cell":"8FD20007","place":"outdoor","ns":66.72,"ew":12.48},"desc":"In Crater Caves Dungeon.","id":1477}, + {"name":"Surface","type":"Portal","wcid":2382,"cell":"019B012E","place":"dungeon","dest":{"cell":"5318003E","place":"outdoor","ns":-82.2,"ew":-34.82},"desc":"In Lightless Catacombs.","id":1478}, + {"name":"Surface","type":"Portal","wcid":2382,"cell":"019B0158","place":"dungeon","dest":{"cell":"5318003E","place":"outdoor","ns":-82.2,"ew":-34.82},"desc":"In Lightless Catacombs.","id":1479}, + {"name":"Surface","type":"Portal","wcid":2557,"cell":"019C011D","place":"dungeon","dest":{"cell":"45500034","place":"outdoor","ns":-37.57,"ew":-46.13},"desc":"In a dungeon (landblock 019C).","id":1480}, + {"name":"Surface","type":"Portal","wcid":2557,"cell":"019C01EF","place":"dungeon","dest":{"cell":"45500034","place":"outdoor","ns":-37.57,"ew":-46.13},"desc":"In a dungeon (landblock 019C).","id":1481}, + {"name":"Surface","type":"Portal","wcid":2557,"cell":"019C02A5","place":"dungeon","dest":{"cell":"45500034","place":"outdoor","ns":-37.57,"ew":-46.13},"desc":"In a dungeon (landblock 019C).","id":1482}, + {"name":"Surface","type":"Portal","wcid":2557,"cell":"019C02A9","place":"dungeon","dest":{"cell":"45500034","place":"outdoor","ns":-37.57,"ew":-46.13},"desc":"In a dungeon (landblock 019C).","id":1483}, + {"name":"Surface","type":"Portal","wcid":2093,"cell":"019D011C","place":"dungeon","dest":{"cell":"CD95002A","place":"outdoor","ns":17.4,"ew":62.57},"desc":"In Simple Tower.","id":1484}, + {"name":"Surface","type":"Portal","wcid":2069,"cell":"019E0121","place":"dungeon","dest":{"cell":"A9B30003","place":"outdoor","ns":41.4,"ew":33.3},"desc":"In Drudge Hideout.","id":1485}, + {"name":"Surface","type":"Portal","wcid":2559,"cell":"019F0130","place":"dungeon","dest":{"cell":"2A8E0016","place":"outdoor","ns":12.23,"ew":-68.11},"desc":"In Tumerok Post.","id":1486}, + {"name":"Surface","type":"Portal","wcid":2563,"cell":"01A00164","place":"dungeon","dest":{"cell":"3073002A","place":"outdoor","ns":-9.84,"ew":-63.02},"desc":"In Tumerok Dungeon.","id":1487}, + {"name":"Surface","type":"Portal","wcid":2561,"cell":"01A1016D","place":"dungeon","dest":{"cell":"2D8A010A","place":"building","ns":9.0,"ew":-65.7},"desc":"In Tumerok Base.","id":1488}, + {"name":"Sho Roadside","type":"Portal","wcid":1907,"cell":"01A20141","place":"dungeon","dest":{"cell":"D45C003D","place":"outdoor","ns":-27.92,"ew":68.38},"desc":"In a dungeon (landblock 01A2).","id":1489}, + {"name":"Surface","type":"Portal","wcid":2384,"cell":"01A20195","place":"dungeon","dest":{"cell":"BB620012","place":"outdoor","ns":-23.36,"ew":47.93},"desc":"In a dungeon (landblock 01A2).","id":1490}, + {"name":"Surface","type":"Portal","wcid":2384,"cell":"01A2042F","place":"dungeon","dest":{"cell":"BB620012","place":"outdoor","ns":-23.36,"ew":47.93},"desc":"In a dungeon (landblock 01A2).","id":1491}, + {"name":"Surface","type":"Portal","wcid":2384,"cell":"01A2043C","place":"dungeon","dest":{"cell":"BB620012","place":"outdoor","ns":-23.36,"ew":47.93},"desc":"In a dungeon (landblock 01A2).","id":1492}, + {"name":"Surface","type":"Portal","wcid":3629,"cell":"01A30100","place":"dungeon","dest":{"cell":"62CF000F","place":"outdoor","ns":64.26,"ew":-23.4},"desc":"In a dungeon (landblock 01A3).","id":1493}, + {"name":"Surface","type":"Portal","wcid":3629,"cell":"01A302ED","place":"dungeon","dest":{"cell":"62CF000F","place":"outdoor","ns":64.26,"ew":-23.4},"desc":"In a dungeon (landblock 01A3).","id":1494}, + {"name":"Portal to the Beach Fort","type":"Portal","wcid":30395,"cell":"01A30103","place":"dungeon","dest":{"cell":"42DE000C","place":"outdoor","ns":76.0,"ew":-49.05},"desc":"In a dungeon (landblock 01A3).","id":1495}, + {"name":"Surface","type":"Portal","wcid":3627,"cell":"01A401E5","place":"dungeon","dest":{"cell":"BDAF003D","place":"outdoor","ns":38.5,"ew":49.96},"desc":"In Mite Tunnels.","id":1496}, + {"name":"Destroyed Eastham Portal","type":"Portal","wcid":1016,"cell":"01A50101","place":"dungeon","dest":{"cell":"CE940035","place":"outdoor","ns":16.92,"ew":63.48},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Inner Dungeon.","id":1497}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"01A50104","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Inner Dungeon.","id":1498}, + {"name":"Destroyed Portal to Zaikhal","type":"Portal","wcid":1032,"cell":"01A50105","place":"dungeon","dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Inner Dungeon.","id":1499}, + {"name":"Plateau Top","type":"Portal","wcid":2549,"cell":"01A501A6","place":"dungeon","dest":{"cell":"49B60008","place":"outdoor","ns":44.41,"ew":-43.5},"desc":"In Inner Dungeon.","id":1500}, + {"name":"Surface","type":"Portal","wcid":2386,"cell":"01A60211","place":"dungeon","dest":{"cell":"3F320037","place":"outdoor","ns":-61.27,"ew":-50.9},"desc":"In Disaster Maze.","id":1501}, + {"name":"Surface","type":"Portal","wcid":2553,"cell":"01A70103","place":"dungeon","dest":{"cell":"93CB0105","place":"dungeon"},"desc":"In Crater Pathway.","id":1502}, + {"name":"Surface","type":"Portal","wcid":2555,"cell":"01A701A7","place":"dungeon","dest":{"cell":"90D00107","place":"building","ns":64.8,"ew":13.65},"desc":"In Crater Pathway.","id":1503}, + {"name":"Surface","type":"Portal","wcid":2392,"cell":"01A80153","place":"dungeon","dest":{"cell":"AE71001B","place":"outdoor","ns":-11.32,"ew":37.55},"desc":"In Unstable.","id":1504}, + {"name":"Surface Portal","type":"Portal","wcid":2358,"cell":"01A90127","place":"dungeon","dest":{"cell":"24840033","place":"outdoor","ns":3.95,"ew":-72.52},"desc":"In a dungeon (landblock 01A9).","id":1505}, + {"name":"Portal to Lighthouse","type":"Portal","wcid":2356,"cell":"01A902D2","place":"dungeon","dest":{"cell":"23840014","place":"outdoor","ns":3.99,"ew":-73.69},"minLevel":18,"desc":"In a dungeon (landblock 01A9).","id":1506}, + {"name":"Surface","type":"Portal","wcid":2087,"cell":"01AA01FA","place":"dungeon","dest":{"cell":"C8B30008","place":"outdoor","ns":41.97,"ew":58.09},"desc":"In Lair of Death.","id":1507}, + {"name":"Deeper Catacombs","type":"Portal","wcid":24230,"cell":"01AA010B","place":"dungeon","dest":{"cell":"57530253","place":"dungeon"},"desc":"In Lair of Death.","id":1508}, + {"name":"Surface","type":"Portal","wcid":2340,"cell":"01AB0150","place":"dungeon","dest":{"cell":"942D001A","place":"outdoor","ns":-65.76,"ew":16.76},"desc":"In Forking Trail.","id":1509}, + {"name":"Destroyed Lytelthorpe Portal","type":"Portal","wcid":4570,"cell":"01AC0100","place":"dungeon","dest":{"cell":"C0800007","place":"outdoor","ns":1.1,"ew":51.7},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Adventurer's Haven.","id":1510}, + {"name":"Destroyed Portal to Samsur","type":"Portal","wcid":1026,"cell":"01AC0104","place":"dungeon","dest":{"cell":"977B000C","place":"outdoor","ns":-3.24,"ew":18.96},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Adventurer's Haven.","id":1511}, + {"name":"Destroyed Portal to Yanshi","type":"Portal","wcid":1029,"cell":"01AC0108","place":"dungeon","dest":{"cell":"B9720021","place":"outdoor","ns":-10.74,"ew":46.55},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Adventurer's Haven.","id":1512}, + {"name":"Surface","type":"Portal","wcid":2081,"cell":"01AC0112","place":"dungeon","dest":{"cell":"AB840038","place":"outdoor","ns":4.4,"ew":35.55},"desc":"In Adventurer's Haven.","id":1513}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"01AC0104","place":"dungeon","dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth. In Adventurer's Haven.","id":1514}, + {"name":"Surface","type":"Portal","wcid":2077,"cell":"01AD0117","place":"dungeon","dest":{"cell":"C68C001F","place":"outdoor","ns":10.67,"ew":56.84},"desc":"In Dungeon Gallery Tower.","id":1515}, + {"name":"Surface Portal","type":"Portal","wcid":1548,"cell":"01AE0117","place":"dungeon","dest":{"cell":"AFC6015C","place":"building","ns":56.69,"ew":38.48},"desc":"In Colier Mine.","id":1516}, + {"name":"Colier Mine Portal","type":"Portal","wcid":1543,"cell":"01AE019B","place":"dungeon","dest":{"cell":"01AE020A","place":"dungeon","name":"Colier Mine"},"desc":"In Colier Mine.","id":1517}, + {"name":"Colier Mine Portal","type":"Portal","wcid":1546,"cell":"01AE01A7","place":"dungeon","dest":{"cell":"01AE0212","place":"dungeon","name":"Colier Mine"},"desc":"In Colier Mine.","id":1518}, + {"name":"Colier Mine Portal","type":"Portal","wcid":1545,"cell":"01AE01AF","place":"dungeon","dest":{"cell":"01AE026F","place":"dungeon","name":"Colier Mine"},"desc":"In Colier Mine.","id":1519}, + {"name":"Colier Mine Portal","type":"Portal","wcid":1544,"cell":"01AE01C0","place":"dungeon","dest":{"cell":"01AE025A","place":"dungeon","name":"Colier Mine"},"desc":"In Colier Mine.","id":1520}, + {"name":"Surface Portal","type":"Portal","wcid":1548,"cell":"01AE02F9","place":"dungeon","dest":{"cell":"AFC6015C","place":"building","ns":56.69,"ew":38.48},"desc":"In Colier Mine.","id":1521}, + {"name":"Surface Portal","type":"Portal","wcid":1548,"cell":"01AE031D","place":"dungeon","dest":{"cell":"AFC6015C","place":"building","ns":56.69,"ew":38.48},"desc":"In Colier Mine.","id":1522}, + {"name":"Surface","type":"Portal","wcid":2085,"cell":"01AF0121","place":"dungeon","dest":{"cell":"BC970002","place":"outdoor","ns":19.01,"ew":48.47},"desc":"In Lakeside Lair.","id":1523}, + {"name":"Destroyed Eastham Portal","type":"Portal","wcid":1016,"cell":"01B0011D","place":"dungeon","dest":{"cell":"CE940035","place":"outdoor","ns":16.92,"ew":63.48},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Seaside Lair.","id":1524}, + {"name":"Surface","type":"Portal","wcid":1602,"cell":"01B102C0","place":"dungeon","dest":{"cell":"C92D0021","place":"outdoor","ns":-65.94,"ew":59.3},"desc":"In a dungeon (landblock 01B1).","id":1525}, + {"name":"Mayoi Portal","type":"Portal","wcid":42842,"cell":"01B20102","place":"dungeon","dest":{"cell":"E6320021","place":"outdoor","ns":-61.91,"ew":82.5},"desc":"This portal goes to Mayoi, a coastal settlement renowned for Shoyanen Kenchu, the master mage of the Sho people, who lives in a spire on the outskirts of town. This is a good town for characters over level 30. In Web Maze.","id":1526}, + {"name":"Portal to Shoushi","type":"Portal","wcid":42840,"cell":"01B2013A","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal goes to Shoushi, a Sho town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Web Maze.","id":1527}, + {"name":"Portal to Hebian-To","type":"Portal","wcid":42846,"cell":"01B20197","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal goes to the Sho capital, Hebian-To. This is a good town for characters over level 10. In Web Maze.","id":1528}, + {"name":"Surface","type":"Portal","wcid":2071,"cell":"01B30120","place":"dungeon","dest":{"cell":"ADB50035","place":"outdoor","ns":43.35,"ew":37.09},"desc":"In Dungeon Fern.","id":1529}, + {"name":"Surface","type":"Portal","wcid":2079,"cell":"01B40136","place":"dungeon","dest":{"cell":"D33F0027","place":"outdoor","ns":-50.92,"ew":67.29},"desc":"In Golem Burial Ground.","id":1530}, + {"name":"Surface","type":"Portal","wcid":2090,"cell":"01B50101","place":"dungeon","dest":{"cell":"D63F0007","place":"outdoor","ns":-50.86,"ew":69.31},"desc":"In Rocky Crypt.","id":1531}, + {"name":"Surface","type":"Portal","wcid":2073,"cell":"01B6010E","place":"dungeon","dest":{"cell":"D85D000D","place":"outdoor","ns":-27.07,"ew":70.99},"desc":"In Dungeon Muddy.","id":1532}, + {"name":"Surface","type":"Portal","wcid":4146,"cell":"01B701AC","place":"dungeon","dest":{"cell":"D954001D","place":"outdoor","ns":-34.27,"ew":71.98},"desc":"In Braid Mansion Ruin.","id":1533}, + {"name":"Surface Portal","type":"Portal","wcid":4168,"cell":"01B80127","place":"dungeon","dest":{"cell":"C48D0010","place":"outdoor","ns":11.58,"ew":55.04},"desc":"In A Ruin.","id":1534}, + {"name":"Destroyed Portal to Samsur","type":"Portal","wcid":1026,"cell":"01B90120","place":"dungeon","dest":{"cell":"977B000C","place":"outdoor","ns":-3.24,"ew":18.96},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In A Ruin.","id":1535}, + {"name":"Ancient Town","type":"Portal","wcid":2075,"cell":"01BA018F","place":"dungeon","dest":{"cell":"B1320012","place":"outdoor","ns":-61.79,"ew":39.93},"desc":"In a dungeon (landblock 01BA).","id":1536}, + {"name":"Surface","type":"Portal","wcid":1598,"cell":"01BB0152","place":"dungeon","dest":{"cell":"E54D0025","place":"outdoor","ns":-39.89,"ew":81.68},"desc":"In Thief Trail.","id":1537}, + {"name":"Surface","type":"Portal","wcid":2334,"cell":"01BC0121","place":"dungeon","dest":{"cell":"5119002C","place":"outdoor","ns":-81.64,"ew":-36.56},"desc":"In Tumerok Chamber.","id":1538}, + {"name":"Surface Portal","type":"Portal","wcid":2361,"cell":"01BD0100","place":"dungeon","dest":{"cell":"1643003F","place":"outdoor","ns":-47.68,"ew":-83.56},"desc":"In Cave.","id":1539}, + {"name":"Surface Portal","type":"Portal","wcid":2365,"cell":"01BE0195","place":"dungeon","dest":{"cell":"228E0026","place":"outdoor","ns":12.2,"ew":-74.33},"desc":"In Tumerok Fortress.","id":1540}, + {"name":"Surface Portal","type":"Portal","wcid":2365,"cell":"01BE01C6","place":"dungeon","dest":{"cell":"228E0026","place":"outdoor","ns":12.2,"ew":-74.33},"desc":"In Tumerok Fortress.","id":1541}, + {"name":"Surface","type":"Portal","wcid":2338,"cell":"01BF01A2","place":"dungeon","dest":{"cell":"519D0032","place":"outdoor","ns":23.82,"ew":-36.53},"desc":"In Tumerok Outpost.","id":1542}, + {"name":"Surface","type":"Portal","wcid":2336,"cell":"01C00123","place":"dungeon","dest":{"cell":"3C4E002D","place":"outdoor","ns":-39.06,"ew":-53.45},"desc":"In Small Complex.","id":1543}, + {"name":"Surface","type":"Portal","wcid":2332,"cell":"01C10234","place":"dungeon","dest":{"cell":"33890002","place":"outdoor","ns":7.8,"ew":-61.14},"desc":"In Tumerok Mine.","id":1544}, + {"name":"Fort Witshire Surface","type":"Portal","wcid":2096,"cell":"01C201BB","place":"dungeon","dest":{"cell":"AE9E0025","place":"outdoor","ns":24.94,"ew":37.73},"desc":"In Underground Passage.","id":1545}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"01C2011F","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Underground Passage.","id":1546}, + {"name":"Surface","type":"Portal","wcid":2342,"cell":"01C30106","place":"dungeon","dest":{"cell":"C4360022","place":"outdoor","ns":-58.63,"ew":55.32},"desc":"In Trialos.","id":1547}, + {"name":"Surface","type":"Portal","wcid":2363,"cell":"01C40110","place":"dungeon","dest":{"cell":"9E5A000F","place":"outdoor","ns":-29.26,"ew":24.57},"desc":"In a dungeon (landblock 01C4).","id":1548}, + {"name":"Surface","type":"Portal","wcid":2345,"cell":"01C50138","place":"dungeon","dest":{"cell":"C0600021","place":"outdoor","ns":-25.14,"ew":52.1},"desc":"In a dungeon (landblock 01C5).","id":1549}, + {"name":"Surface","type":"Portal","wcid":2083,"cell":"01C6017D","place":"dungeon","dest":{"cell":"A8AC0011","place":"outdoor","ns":35.69,"ew":32.66},"desc":"In Hunter's Leap.","id":1550}, + {"name":"Surface","type":"Portal","wcid":1591,"cell":"01C70127","place":"dungeon","dest":{"cell":"961A0005","place":"outdoor","ns":-80.67,"ew":18.15},"desc":"In Lugian Outpost.","id":1551}, + {"name":"Surface","type":"Portal","wcid":1593,"cell":"01C8010B","place":"dungeon","dest":{"cell":"9726000B","place":"outdoor","ns":-71.27,"ew":18.98},"desc":"In Lugian Post.","id":1552}, + {"name":"Destroyed Portal to Zaikhal","type":"Portal","wcid":1032,"cell":"01C90100","place":"dungeon","dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1553}, + {"name":"Destroyed Portal to Samsur","type":"Portal","wcid":1026,"cell":"01C90101","place":"dungeon","dest":{"cell":"977B000C","place":"outdoor","ns":-3.24,"ew":18.96},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1554}, + {"name":"Destroyed Portal to Rithwic","type":"Portal","wcid":1025,"cell":"01C90102","place":"dungeon","dest":{"cell":"C98C0028","place":"outdoor","ns":10.84,"ew":59.32},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1555}, + {"name":"Destroyed Portal to Yaraq","type":"Portal","wcid":1030,"cell":"01C90107","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1556}, + {"name":"Destroyed Glenden Wood Portal","type":"Portal","wcid":1017,"cell":"01C90108","place":"dungeon","dest":{"cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1557}, + {"name":"Destroyed Qalaba'r Portal","type":"Portal","wcid":1023,"cell":"01C9010D","place":"dungeon","dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1558}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"01C9010E","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1559}, + {"name":"Underground City Portal","type":"Portal","wcid":1099,"cell":"01C90119","place":"dungeon","dest":{"cell":"01E901AD","place":"dungeon","name":"Underground City"},"desc":"In Abandoned Mine.","id":1560}, + {"name":"Destroyed Portal to Arwic","type":"Portal","wcid":1013,"cell":"01C9011A","place":"dungeon","dest":{"cell":"C6A90009","place":"outdoor","ns":33.27,"ew":56.65},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1561}, + {"name":"Surface","type":"Portal","wcid":1596,"cell":"01C9011F","place":"dungeon","dest":{"cell":"C3AB0021","place":"outdoor","ns":34.88,"ew":54.51},"desc":"In Abandoned Mine.","id":1562}, + {"name":"Destroyed Portal to Cragstone","type":"Portal","wcid":1014,"cell":"01C90120","place":"dungeon","dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1563}, + {"name":"Destroyed Mayoi Portal","type":"Portal","wcid":1022,"cell":"01C90125","place":"dungeon","dest":{"cell":"E6320021","place":"outdoor","ns":-61.91,"ew":82.5},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1564}, + {"name":"Destroyed Portal to Shoushi","type":"Portal","wcid":1027,"cell":"01C90126","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1565}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"01C90127","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Abandoned Mine.","id":1566}, + {"name":"Surface","type":"Portal","wcid":1596,"cell":"01C90231","place":"dungeon","dest":{"cell":"C3AB0021","place":"outdoor","ns":34.88,"ew":54.51},"desc":"In Abandoned Mine.","id":1567}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"01CA0101","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Hebian-to Sewers.","id":1568}, + {"name":"Surface","type":"Portal","wcid":1600,"cell":"01CA0105","place":"dungeon","dest":{"cell":"E74D0029","place":"outdoor","ns":-40.29,"ew":83.38},"desc":"In Hebian-to Sewers.","id":1569}, + {"name":"Destroyed Portal to Shoushi","type":"Portal","wcid":1027,"cell":"01CA010A","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Hebian-to Sewers.","id":1570}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"01CA0171","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Hebian-to Sewers.","id":1571}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"01CA0186","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Hebian-to Sewers.","id":1572}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"01CA01B3","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Hebian-to Sewers.","id":1573}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"01CA01F2","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Hebian-to Sewers.","id":1574}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"01CA0287","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Hebian-to Sewers.","id":1575}, + {"name":"Surface","type":"Portal","wcid":29049,"cell":"01CB0360","place":"dungeon","dest":{"cell":"3EF5002A","place":"outdoor","ns":94.23,"ew":-51.81},"desc":"In Penguin Cave Hatchery.","id":1576}, + {"name":"Surface","type":"Portal","wcid":29049,"cell":"01CB0106","place":"dungeon","dest":{"cell":"3EF5002A","place":"outdoor","ns":94.23,"ew":-51.81},"desc":"In Penguin Cave Hatchery.","id":1577}, + {"name":"Surface","type":"Portal","wcid":1513,"cell":"01CC01E1","place":"dungeon","dest":{"cell":"8196001F","place":"outdoor","ns":18.69,"ew":1.56},"desc":"In Halls of the Helm.","id":1578}, + {"name":"Surface","type":"Portal","wcid":1513,"cell":"01CC0255","place":"dungeon","dest":{"cell":"8196001F","place":"outdoor","ns":18.69,"ew":1.56},"desc":"In Halls of the Helm.","id":1579}, + {"name":"Surface","type":"Portal","wcid":1433,"cell":"01CD0145","place":"dungeon","dest":{"cell":"C9900018","place":"outdoor","ns":14.0,"ew":59.12},"desc":"In Rithwic Crypt.","id":1580}, + {"name":"Surface","type":"Portal","wcid":1431,"cell":"01CE012C","place":"dungeon","dest":{"cell":"211F0037","place":"outdoor","ns":-76.53,"ew":-74.87},"desc":"In a dungeon (landblock 01CE).","id":1581}, + {"name":"Surface","type":"Portal","wcid":1431,"cell":"01CE0152","place":"dungeon","dest":{"cell":"211F0037","place":"outdoor","ns":-76.53,"ew":-74.87},"desc":"In a dungeon (landblock 01CE).","id":1582}, + {"name":"Surface","type":"Portal","wcid":1431,"cell":"01CE0161","place":"dungeon","dest":{"cell":"211F0037","place":"outdoor","ns":-76.53,"ew":-74.87},"desc":"In a dungeon (landblock 01CE).","id":1583}, + {"name":"Surface","type":"Portal","wcid":1431,"cell":"01CE0170","place":"dungeon","dest":{"cell":"211F0037","place":"outdoor","ns":-76.53,"ew":-74.87},"desc":"In a dungeon (landblock 01CE).","id":1584}, + {"name":"Surface","type":"Portal","wcid":1431,"cell":"01CE017C","place":"dungeon","dest":{"cell":"211F0037","place":"outdoor","ns":-76.53,"ew":-74.87},"desc":"In a dungeon (landblock 01CE).","id":1585}, + {"name":"Surface","type":"Portal","wcid":1431,"cell":"01CE0197","place":"dungeon","dest":{"cell":"211F0037","place":"outdoor","ns":-76.53,"ew":-74.87},"desc":"In a dungeon (landblock 01CE).","id":1586}, + {"name":"Surface","type":"Portal","wcid":1431,"cell":"01CE01AA","place":"dungeon","dest":{"cell":"211F0037","place":"outdoor","ns":-76.53,"ew":-74.87},"desc":"In a dungeon (landblock 01CE).","id":1587}, + {"name":"Surface","type":"Portal","wcid":1431,"cell":"01CE01C6","place":"dungeon","dest":{"cell":"211F0037","place":"outdoor","ns":-76.53,"ew":-74.87},"desc":"In a dungeon (landblock 01CE).","id":1588}, + {"name":"Surface Portal","type":"Portal","wcid":1324,"cell":"01CF023C","place":"dungeon","dest":{"cell":"CE960037","place":"outdoor","ns":18.67,"ew":63.45},"desc":"In Eastham Sewer.","id":1589}, + {"name":"Surface Portal","type":"Portal","wcid":1324,"cell":"01CF0291","place":"dungeon","dest":{"cell":"CE960037","place":"outdoor","ns":18.67,"ew":63.45},"desc":"In Eastham Sewer.","id":1590}, + {"name":"Surface","type":"Portal","wcid":1399,"cell":"01D00124","place":"dungeon","dest":{"cell":"B870001B","place":"outdoor","ns":-12.13,"ew":45.55},"desc":"In Yanshi Tunnel.","id":1591}, + {"name":"Surface","type":"Portal","wcid":29779,"cell":"01D1010D","place":"dungeon","dest":{"cell":"EF0D0021","place":"outdoor","ns":-91.47,"ew":89.66},"desc":"In Balmy Font.","id":1592}, + {"name":"Holtburg","type":"Portal","wcid":1365,"cell":"01D201F7","place":"dungeon","dest":{"cell":"A7B70037","place":"outdoor","ns":45.06,"ew":32.3},"desc":"In Mountain Keep.","id":1593}, + {"name":"Surface","type":"Portal","wcid":1366,"cell":"01D202F4","place":"dungeon","dest":{"cell":"A8C3002F","place":"outdoor","ns":54.7,"ew":33.03},"desc":"In Mountain Keep.","id":1594}, + {"name":"Surface","type":"Portal","wcid":1367,"cell":"01D203A5","place":"dungeon","dest":{"cell":"A7C50019","place":"outdoor","ns":55.65,"ew":32.04},"desc":"In Mountain Keep.","id":1595}, + {"name":"Surface","type":"Portal","wcid":1368,"cell":"01D203A6","place":"dungeon","dest":{"cell":"A7C50012","place":"outdoor","ns":55.78,"ew":31.93},"desc":"In Mountain Keep.","id":1596}, + {"name":"Base of Mt. Zabool","type":"Portal","wcid":1363,"cell":"01D3010C","place":"dungeon","dest":{"cell":"979A0036","place":"outdoor","ns":21.77,"ew":19.47},"desc":"In Top of Zabool Tower.","id":1597}, + {"name":"Top of Mt. Zabool","type":"Portal","wcid":369,"cell":"01D301BC","place":"dungeon","dest":{"cell":"9699002F","place":"outdoor","ns":21.14,"ew":18.56},"desc":"In Top of Zabool Tower.","id":1598}, + {"name":"Surface","type":"Portal","wcid":374,"cell":"01D40100","place":"dungeon","dest":{"cell":"9395001E","place":"outdoor","ns":17.84,"ew":15.98},"desc":"In Bellig Tower Base.","id":1599}, + {"name":"Surface","type":"Portal","wcid":374,"cell":"01D40123","place":"dungeon","dest":{"cell":"9395001E","place":"outdoor","ns":17.84,"ew":15.98},"desc":"In Bellig Tower Base.","id":1600}, + {"name":"Bellig Top","type":"Portal","wcid":376,"cell":"01D4021B","place":"dungeon","dest":{"cell":"93950023","place":"outdoor","ns":17.53,"ew":16.06},"desc":"In Bellig Tower Base.","id":1601}, + {"name":"Exit","type":"Portal","wcid":430,"cell":"01D50102","place":"dungeon","dest":{"cell":"8E8E000C","place":"outdoor","ns":11.96,"ew":11.77},"desc":"In Syliph Tower.","id":1602}, + {"name":"To Top of Mt. Syliph","type":"Portal","wcid":427,"cell":"01D501BF","place":"dungeon","dest":{"cell":"8D8E0037","place":"outdoor","ns":12.34,"ew":11.51},"desc":"In Syliph Tower.","id":1603}, + {"name":"Surface","type":"Portal","wcid":372,"cell":"01D601B0","place":"dungeon","dest":{"cell":"8F990039","place":"outdoor","ns":20.46,"ew":13.25},"desc":"In Alfreth Dungeon.","id":1604}, + {"name":"Surface","type":"Portal","wcid":372,"cell":"01D601B9","place":"dungeon","dest":{"cell":"8F990039","place":"outdoor","ns":20.46,"ew":13.25},"desc":"In Alfreth Dungeon.","id":1605}, + {"name":"Direlands Midland Portal","type":"Portal","wcid":3613,"cell":"01D70193","place":"dungeon","dest":{"cell":"2E110031","place":"outdoor","ns":-88.31,"ew":-64.5},"minLevel":21,"desc":"In Sylsfear Dungeon.","id":1606}, + {"name":"Surface","type":"Portal","wcid":429,"cell":"01D7026E","place":"dungeon","dest":{"cell":"918D0032","place":"outdoor","ns":11.0,"ew":14.7},"desc":"In Sylsfear Dungeon.","id":1607}, + {"name":"Surface","type":"Portal","wcid":1336,"cell":"01D80112","place":"dungeon","dest":{"cell":"C78D0012","place":"outdoor","ns":10.96,"ew":57.52},"desc":"In A Drudge Nest.","id":1608}, + {"name":"Surface","type":"Portal","wcid":1346,"cell":"01D90100","place":"dungeon","dest":{"cell":"7C640040","place":"outdoor","ns":-21.16,"ew":-1.96},"desc":"In A Red Rat Lair.","id":1609}, + {"name":"Sea Temple Catacombs","type":"Portal","wcid":5198,"cell":"01D90114","place":"dungeon","dest":{"cell":"0156018F","place":"dungeon"},"minLevel":1,"maxLevel":20,"desc":"This is a good adventure for someone who is newly arrived in Dereth. In A Red Rat Lair.","id":1610}, + {"name":"Surface","type":"Portal","wcid":1344,"cell":"01DA0111","place":"dungeon","dest":{"cell":"BA6F0022","place":"outdoor","ns":-12.96,"ew":47.28},"desc":"In A Ruin.","id":1611}, + {"name":"Surface","type":"Portal","wcid":1340,"cell":"01DB01DB","place":"dungeon","dest":{"cell":"7E91002A","place":"outdoor","ns":14.16,"ew":-0.65},"desc":"In Moss Chamber.","id":1612}, + {"name":"Moss Chamber","type":"Portal","wcid":9166,"cell":"01DB0139","place":"dungeon","dest":{"cell":"02A30101","place":"dungeon"},"desc":"In Moss Chamber.","id":1613}, + {"name":"Surface","type":"Portal","wcid":1338,"cell":"01DC0155","place":"dungeon","dest":{"cell":"E74C003E","place":"outdoor","ns":-40.6,"ew":83.61},"desc":"In A Drudge Nest.","id":1614}, + {"name":"Surface","type":"Portal","wcid":1348,"cell":"01DD012E","place":"dungeon","dest":{"cell":"A8B10016","place":"outdoor","ns":40.18,"ew":32.7},"desc":"In A Rat Nest.","id":1615}, + {"name":"Destroyed Baishi Portal","type":"Portal","wcid":4037,"cell":"01DE011B","place":"dungeon","dest":{"cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In A Ruin.","id":1616}, + {"name":"Surface","type":"Portal","wcid":1342,"cell":"01DE01A5","place":"dungeon","dest":{"cell":"E531000A","place":"outdoor","ns":-62.61,"ew":81.4},"desc":"In A Ruin.","id":1617}, + {"name":"Surface","type":"Portal","wcid":1342,"cell":"01DE01B2","place":"dungeon","dest":{"cell":"E531000A","place":"outdoor","ns":-62.61,"ew":81.4},"desc":"In A Ruin.","id":1618}, + {"name":"Surface","type":"Portal","wcid":1334,"cell":"01DF0107","place":"dungeon","dest":{"cell":"CC52003A","place":"outdoor","ns":-36.19,"ew":61.96},"desc":"In A Mosswart Nest.","id":1619}, + {"name":"Surface","type":"Portal","wcid":1330,"cell":"01E00114","place":"dungeon","dest":{"cell":"B1AC0016","place":"outdoor","ns":36.17,"ew":39.89},"desc":"In Banderling Ruin.","id":1620}, + {"name":"Surface","type":"Portal","wcid":4034,"cell":"01E1021F","place":"dungeon","dest":{"cell":"D0950036","place":"outdoor","ns":17.85,"ew":65.13},"desc":"In Thieves' Den.","id":1621}, + {"name":"Surface","type":"Portal","wcid":4034,"cell":"01E1027A","place":"dungeon","dest":{"cell":"D0950036","place":"outdoor","ns":17.85,"ew":65.13},"desc":"In Thieves' Den.","id":1622}, + {"name":"Surface Portal","type":"Portal","wcid":4178,"cell":"01E2012E","place":"dungeon","dest":{"cell":"BDD20128","place":"building","ns":66.38,"ew":49.91},"desc":"In Bandit Castle Prison.","id":1623}, + {"name":"Surface Portal","type":"Portal","wcid":4178,"cell":"01E20228","place":"dungeon","dest":{"cell":"BDD20128","place":"building","ns":66.38,"ew":49.91},"desc":"In Bandit Castle Prison.","id":1624}, + {"name":"North Glenden Prison","type":"Portal","wcid":1311,"cell":"01E30105","place":"dungeon","dest":{"cell":"01E401FE","place":"dungeon","name":"North Glenden Prison"},"minLevel":80,"desc":"In Glenden Wood Dungeon.","id":1625}, + {"name":"Surface","type":"Portal","wcid":1308,"cell":"01E30332","place":"dungeon","dest":{"cell":"A0A4001F","place":"outdoor","ns":29.91,"ew":26.37},"desc":"In Glenden Wood Dungeon.","id":1626}, + {"name":"Surface","type":"Portal","wcid":1312,"cell":"01E40206","place":"dungeon","dest":{"cell":"9FA7001A","place":"outdoor","ns":31.78,"ew":25.62},"desc":"In North Glenden Prison.","id":1627}, + {"name":"North Glenden Prison","type":"Portal","wcid":1311,"cell":"01E40157","place":"dungeon","dest":{"cell":"01E401FE","place":"dungeon","name":"North Glenden Prison"},"minLevel":80,"desc":"In North Glenden Prison.","id":1628}, + {"name":"North Glenden Prison","type":"Portal","wcid":1311,"cell":"01E4010D","place":"dungeon","dest":{"cell":"01E401FE","place":"dungeon","name":"North Glenden Prison"},"minLevel":80,"desc":"In North Glenden Prison.","id":1629}, + {"name":"Commander's Quarters","type":"Portal","wcid":32292,"cell":"01E40180","place":"dungeon","dest":{"cell":"01E40157","place":"dungeon","name":"North Glenden Prison"},"minLevel":100,"desc":"In North Glenden Prison.","id":1630}, + {"name":"Surface","type":"Portal","wcid":1310,"cell":"01E50203","place":"dungeon","dest":{"cell":"D85C003E","place":"outdoor","ns":-27.79,"ew":71.59},"desc":"In Green Mire Grave.","id":1631}, + {"name":"Surface","type":"Portal","wcid":1310,"cell":"01E50205","place":"dungeon","dest":{"cell":"D85C003E","place":"outdoor","ns":-27.79,"ew":71.59},"desc":"In Green Mire Grave.","id":1632}, + {"name":"Surface","type":"Portal","wcid":1310,"cell":"01E50214","place":"dungeon","dest":{"cell":"D85C003E","place":"outdoor","ns":-27.79,"ew":71.59},"desc":"In Green Mire Grave.","id":1633}, + {"name":"Surface","type":"Portal","wcid":1310,"cell":"01E50216","place":"dungeon","dest":{"cell":"D85C003E","place":"outdoor","ns":-27.79,"ew":71.59},"desc":"In Green Mire Grave.","id":1634}, + {"name":"Surface","type":"Portal","wcid":1328,"cell":"01E60107","place":"dungeon","dest":{"cell":"BED3003C","place":"outdoor","ns":67.2,"ew":50.77},"desc":"In Small Icecave.","id":1635}, + {"name":"Surface","type":"Portal","wcid":1328,"cell":"01E60255","place":"dungeon","dest":{"cell":"BED3003C","place":"outdoor","ns":67.2,"ew":50.77},"desc":"In Small Icecave.","id":1636}, + {"name":"Surface","type":"Portal","wcid":1326,"cell":"01E7011E","place":"dungeon","dest":{"cell":"957A0002","place":"outdoor","ns":-4.24,"ew":17.32},"desc":"In A Small Cave.","id":1637}, + {"name":"Surface","type":"Portal","wcid":1092,"cell":"01E8016D","place":"dungeon","dest":{"cell":"977C0036","place":"outdoor","ns":-2.2,"ew":19.53},"desc":"In Dungeon Manor.","id":1638}, + {"name":"Surface","type":"Portal","wcid":1100,"cell":"01E90100","place":"dungeon","dest":{"cell":"C29A0031","place":"outdoor","ns":21.35,"ew":53.93},"desc":"In Underground City.","id":1639}, + {"name":"Surface","type":"Portal","wcid":1100,"cell":"01E90193","place":"dungeon","dest":{"cell":"C29A0031","place":"outdoor","ns":21.35,"ew":53.93},"desc":"In Underground City.","id":1640}, + {"name":"Hidden Dungeon Portal","type":"Portal","wcid":15823,"cell":"01E901C2","place":"dungeon","dest":{"cell":"536A0282","place":"dungeon"},"quest":true,"desc":"In Underground City.","id":1641}, + {"name":"Surface","type":"Portal","wcid":1097,"cell":"01EA0419","place":"dungeon","dest":{"cell":"147C0023","place":"outdoor","ns":-2.5,"ew":-85.5},"desc":"In Old Talisman Dungeon.","id":1642}, + {"name":"Surface","type":"Portal","wcid":1097,"cell":"01EA041D","place":"dungeon","dest":{"cell":"147C0023","place":"outdoor","ns":-2.5,"ew":-85.5},"desc":"In Old Talisman Dungeon.","id":1643}, + {"name":"Surface","type":"Portal","wcid":1097,"cell":"01EA041F","place":"dungeon","dest":{"cell":"147C0023","place":"outdoor","ns":-2.5,"ew":-85.5},"desc":"In Old Talisman Dungeon.","id":1644}, + {"name":"Surface","type":"Portal","wcid":1097,"cell":"01EA0423","place":"dungeon","dest":{"cell":"147C0023","place":"outdoor","ns":-2.5,"ew":-85.5},"desc":"In Old Talisman Dungeon.","id":1645}, + {"name":"Surface","type":"Portal","wcid":28799,"cell":"01EB0224","place":"dungeon","dest":{"cell":"28F20013","place":"outdoor","ns":91.9,"ew":-69.7},"desc":"In Lola's Den.","id":1646}, + {"name":"Lola's Den","type":"Portal","wcid":28809,"cell":"01EB010E","place":"dungeon","dest":{"cell":"01EB0118","place":"dungeon","name":"Lola's Den"},"desc":"In Lola's Den.","id":1647}, + {"name":"Lola's Den","type":"Portal","wcid":28810,"cell":"01EB0119","place":"dungeon","dest":{"cell":"01EB0124","place":"dungeon","name":"Lola's Den"},"desc":"In Lola's Den.","id":1648}, + {"name":"Lola's Den","type":"Portal","wcid":28811,"cell":"01EB012C","place":"dungeon","dest":{"cell":"01EB0135","place":"dungeon","name":"Lola's Den"},"desc":"In Lola's Den.","id":1649}, + {"name":"Lola's Den","type":"Portal","wcid":28812,"cell":"01EB0142","place":"dungeon","dest":{"cell":"01EB010D","place":"dungeon","name":"Lola's Den"},"desc":"In Lola's Den.","id":1650}, + {"name":"Secured Vault Sewers","type":"Portal","wcid":30719,"cell":"01EC0181","place":"dungeon","dest":{"cell":"000D02EE","place":"dungeon"},"minLevel":60,"quest":true,"desc":"You must best the spirits of the temple before you may pass through this portal. In Defiled Temple Middle Wing.","id":1651}, + {"name":"Surface","type":"Portal","wcid":30753,"cell":"01EC0155","place":"dungeon","dest":{"cell":"A8DF0010","place":"outdoor","ns":77.18,"ew":32.59},"desc":"In Defiled Temple Middle Wing.","id":1652}, + {"name":"Surface","type":"Portal","wcid":1095,"cell":"01ED014A","place":"dungeon","dest":{"cell":"B69A0023","place":"outdoor","ns":21.49,"ew":44.06},"desc":"In Dungeon of Shadows.","id":1653}, + {"name":"Surface","type":"Portal","wcid":1095,"cell":"01ED032B","place":"dungeon","dest":{"cell":"B69A0023","place":"outdoor","ns":21.49,"ew":44.06},"desc":"In Dungeon of Shadows.","id":1654}, + {"name":"Old Mine","type":"Portal","wcid":3632,"cell":"01EF0177","place":"dungeon","dest":{"cell":"019001F3","place":"dungeon","name":"Old Mine"},"desc":"In Arwic Mines.","id":1655}, + {"name":"Surface","type":"Portal","wcid":1089,"cell":"01EF0187","place":"dungeon","dest":{"cell":"C6A9002A","place":"outdoor","ns":33.38,"ew":57.01},"desc":"In Arwic Mines.","id":1656}, + {"name":"Moss Chamber","type":"Portal","wcid":1339,"cell":"01EF0199","place":"dungeon","dest":{"cell":"01DB01DC","place":"dungeon","name":"Moss Chamber"},"desc":"In Arwic Mines.","id":1657}, + {"name":"Surface","type":"Portal","wcid":1089,"cell":"01EF03DD","place":"dungeon","dest":{"cell":"C6A9002A","place":"outdoor","ns":33.38,"ew":57.01},"desc":"In Arwic Mines.","id":1658}, + {"name":"Surface","type":"Portal","wcid":1332,"cell":"01F10101","place":"dungeon","dest":{"cell":"CD960004","place":"outdoor","ns":18.37,"ew":62.13},"desc":"In Cave.","id":1659}, + {"name":"Surface","type":"Portal","wcid":9189,"cell":"01F30114","place":"dungeon","dest":{"cell":"8B680003","place":"outdoor","ns":-18.51,"ew":9.3},"desc":"In a dungeon (landblock 01F3).","id":1660}, + {"name":"Surface","type":"Portal","wcid":9189,"cell":"01F301C6","place":"dungeon","dest":{"cell":"8B680003","place":"outdoor","ns":-18.51,"ew":9.3},"desc":"In a dungeon (landblock 01F3).","id":1661}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"01F4010E","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 01F4).","id":1662}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"01F40145","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 01F4).","id":1663}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"01F4017B","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 01F4).","id":1664}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"01F402DD","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 01F4).","id":1665}, + {"name":"Surface Portal","type":"Portal","wcid":7627,"cell":"01F50273","place":"dungeon","dest":{"cell":"B7EB0024","place":"outdoor","ns":86.45,"ew":44.91},"desc":"In a dungeon (landblock 01F5).","id":1666}, + {"name":"Surface","type":"Portal","wcid":1093,"cell":"01F60101","place":"dungeon","dest":{"cell":"A8B50040","place":"outdoor","ns":43.58,"ew":33.23},"desc":"In Holtburg Dungeon.","id":1667}, + {"name":"Surface","type":"Portal","wcid":1093,"cell":"01F601DB","place":"dungeon","dest":{"cell":"A8B50040","place":"outdoor","ns":43.58,"ew":33.23},"desc":"In Holtburg Dungeon.","id":1668}, + {"name":"Surface","type":"Portal","wcid":1093,"cell":"01F6022E","place":"dungeon","dest":{"cell":"A8B50040","place":"outdoor","ns":43.58,"ew":33.23},"desc":"In Holtburg Dungeon.","id":1669}, + {"name":"Surface","type":"Portal","wcid":1096,"cell":"01F701C2","place":"dungeon","dest":{"cell":"DA54002A","place":"outdoor","ns":-34.57,"ew":73.01},"desc":"In Shoushi Grotto.","id":1670}, + {"name":"Destroyed Portal to Shoushi","type":"Portal","wcid":1027,"cell":"01F701E5","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Shoushi Grotto.","id":1671}, + {"name":"Surface","type":"Portal","wcid":1094,"cell":"01F801C0","place":"dungeon","dest":{"cell":"C7B20010","place":"outdoor","ns":41.18,"ew":57.41},"desc":"In Mite Maze.","id":1672}, + {"name":"Surface","type":"Portal","wcid":1094,"cell":"01F8031E","place":"dungeon","dest":{"cell":"C7B20010","place":"outdoor","ns":41.18,"ew":57.41},"desc":"In Mite Maze.","id":1673}, + {"name":"Outside Accursed Halls Portal","type":"Portal","wcid":1087,"cell":"01F9010C","place":"dungeon","dest":{"cell":"3761000C","place":"outdoor","ns":-24.02,"ew":-57.79},"desc":"In Accursed Halls.","id":1674}, + {"name":"Outside Accursed Halls Portal","type":"Portal","wcid":1087,"cell":"01F902A0","place":"dungeon","dest":{"cell":"3761000C","place":"outdoor","ns":-24.02,"ew":-57.79},"desc":"In Accursed Halls.","id":1675}, + {"name":"Outside Accursed Halls Portal","type":"Portal","wcid":1087,"cell":"01F90345","place":"dungeon","dest":{"cell":"3761000C","place":"outdoor","ns":-24.02,"ew":-57.79},"desc":"In Accursed Halls.","id":1676}, + {"name":"Surface","type":"Portal","wcid":1090,"cell":"01FA0139","place":"dungeon","dest":{"cell":"8391003B","place":"outdoor","ns":14.32,"ew":3.65},"desc":"In Crypt of Ashen Tears.","id":1677}, + {"name":"Surface","type":"Portal","wcid":1090,"cell":"01FA022B","place":"dungeon","dest":{"cell":"8391003B","place":"outdoor","ns":14.32,"ew":3.65},"desc":"In Crypt of Ashen Tears.","id":1678}, + {"name":"Surface","type":"Portal","wcid":1090,"cell":"01FA0356","place":"dungeon","dest":{"cell":"8391003B","place":"outdoor","ns":14.32,"ew":3.65},"desc":"In Crypt of Ashen Tears.","id":1679}, + {"name":"Surface","type":"Portal","wcid":1101,"cell":"01FB0206","place":"dungeon","dest":{"cell":"7D60003A","place":"outdoor","ns":-25.04,"ew":-1.15},"desc":"In Yaraq Tunnels.","id":1680}, + {"name":"Surface Portal","type":"Portal","wcid":1128,"cell":"01FC0115","place":"dungeon","dest":{"cell":"BB700029","place":"outdoor","ns":-12.27,"ew":48.17},"desc":"In ReedShark Lair.","id":1681}, + {"name":"Surface","type":"Portal","wcid":1098,"cell":"01FD01B1","place":"dungeon","dest":{"cell":"C58C001B","place":"outdoor","ns":10.35,"ew":55.95},"desc":"In Trothyr's Rest.","id":1682}, + {"name":"Surface","type":"Portal","wcid":1098,"cell":"01FD0211","place":"dungeon","dest":{"cell":"C58C001B","place":"outdoor","ns":10.35,"ew":55.95},"desc":"In Trothyr's Rest.","id":1683}, + {"name":"Surface","type":"Portal","wcid":1098,"cell":"01FD02EB","place":"dungeon","dest":{"cell":"C58C001B","place":"outdoor","ns":10.35,"ew":55.95},"desc":"In Trothyr's Rest.","id":1684}, + {"name":"Surface","type":"Portal","wcid":28781,"cell":"01FE02CB","place":"dungeon","dest":{"cell":"22E30040","place":"outdoor","ns":80.4,"ew":-74.0},"desc":"In Small Empyrean Vault.","id":1685}, + {"name":"Surface","type":"Portal","wcid":28781,"cell":"01FE0139","place":"dungeon","dest":{"cell":"22E30040","place":"outdoor","ns":80.4,"ew":-74.0},"desc":"In Small Empyrean Vault.","id":1686}, + {"name":"Portal to Burun Fortress","type":"Portal","wcid":28480,"cell":"02780109","place":"dungeon","dest":{"cell":"B95F001D","place":"outdoor","ns":-25.55,"ew":46.38},"desc":"In Vile-Smelling Refuse.","id":1687}, + {"name":"Portal to Burun Fortress","type":"Portal","wcid":28480,"cell":"027A0122","place":"dungeon","dest":{"cell":"B95F001D","place":"outdoor","ns":-25.55,"ew":46.38},"desc":"In Vile-Smelling Refuse.","id":1688}, + {"name":"Portal to Burun Fortress","type":"Portal","wcid":28480,"cell":"027B0130","place":"dungeon","dest":{"cell":"B95F001D","place":"outdoor","ns":-25.55,"ew":46.38},"desc":"In Vile-Smelling Refuse.","id":1689}, + {"name":"Surface Exit","type":"Portal","wcid":10854,"cell":"027C015B","place":"dungeon","dest":{"cell":"24C10002","place":"outdoor","ns":52.66,"ew":-73.03},"desc":"In Ancient Empyrean Grotto.","id":1690}, + {"name":"Surface Exit","type":"Portal","wcid":10854,"cell":"027C01A0","place":"dungeon","dest":{"cell":"24C10002","place":"outdoor","ns":52.66,"ew":-73.03},"desc":"In Ancient Empyrean Grotto.","id":1691}, + {"name":"Surface Exit","type":"Portal","wcid":10848,"cell":"027D02A6","place":"dungeon","dest":{"cell":"1FC20023","place":"outdoor","ns":53.48,"ew":-76.71},"desc":"In Lair of the Eviscerators.","id":1692}, + {"name":"Surface Exit","type":"Portal","wcid":10848,"cell":"027D0161","place":"dungeon","dest":{"cell":"1FC20023","place":"outdoor","ns":53.48,"ew":-76.71},"desc":"In Lair of the Eviscerators.","id":1693}, + {"name":"Surface Exit","type":"Portal","wcid":10880,"cell":"027E010B","place":"dungeon","dest":{"cell":"1FC90008","place":"outdoor","ns":59.48,"ew":-77.03},"desc":"In Martinate Holding.","id":1694}, + {"name":"Surface Exit","type":"Portal","wcid":10880,"cell":"027E0262","place":"dungeon","dest":{"cell":"1FC90008","place":"outdoor","ns":59.48,"ew":-77.03},"desc":"In Martinate Holding.","id":1695}, + {"name":"Surface Portal","type":"Portal","wcid":11212,"cell":"027F011D","place":"dungeon","dest":{"cell":"1FBB0028","place":"outdoor","ns":48.38,"ew":-76.65},"minLevel":30,"desc":"In East Fork Dam Hive.","id":1696}, + {"name":"Surface Portal","type":"Portal","wcid":11212,"cell":"027F0230","place":"dungeon","dest":{"cell":"1FBB0028","place":"outdoor","ns":48.38,"ew":-76.65},"minLevel":30,"desc":"In East Fork Dam Hive.","id":1697}, + {"name":"Surface Portal","type":"Portal","wcid":11212,"cell":"027F01DC","place":"dungeon","dest":{"cell":"1FBB0028","place":"outdoor","ns":48.38,"ew":-76.65},"minLevel":30,"desc":"In East Fork Dam Hive.","id":1698}, + {"name":"Portal to Burun Fortress","type":"Portal","wcid":28480,"cell":"0280012E","place":"dungeon","dest":{"cell":"B95F001D","place":"outdoor","ns":-25.55,"ew":46.38},"desc":"In Vile-Smelling Refuse.","id":1699}, + {"name":"Surface Exit","type":"Portal","wcid":10856,"cell":"0282010E","place":"dungeon","dest":{"cell":"20B70008","place":"outdoor","ns":45.08,"ew":-76.18},"desc":"In An Olthoi Soldier Nest.","id":1700}, + {"name":"Surface Exit","type":"Portal","wcid":10856,"cell":"02820201","place":"dungeon","dest":{"cell":"20B70008","place":"outdoor","ns":45.08,"ew":-76.18},"desc":"In An Olthoi Soldier Nest.","id":1701}, + {"name":"Surface Exit","type":"Portal","wcid":10850,"cell":"02830106","place":"dungeon","dest":{"cell":"29B6003A","place":"outdoor","ns":43.86,"ew":-68.53},"desc":"In The Dark Lair.","id":1702}, + {"name":"Surface Exit","type":"Portal","wcid":10850,"cell":"02830159","place":"dungeon","dest":{"cell":"29B6003A","place":"outdoor","ns":43.86,"ew":-68.53},"desc":"In The Dark Lair.","id":1703}, + {"name":"Surface Exit","type":"Portal","wcid":10852,"cell":"02840193","place":"dungeon","dest":{"cell":"18B30030","place":"outdoor","ns":42.01,"ew":-82.18},"desc":"In Abandoned Tumerok Site.","id":1704}, + {"name":"Surface Exit","type":"Portal","wcid":10852,"cell":"0284020B","place":"dungeon","dest":{"cell":"18B30030","place":"outdoor","ns":42.01,"ew":-82.18},"desc":"In Abandoned Tumerok Site.","id":1705}, + {"name":"Royal Hive Portal","type":"Portal","wcid":11206,"cell":"02850100","place":"dungeon","dest":{"cell":"02880280","place":"dungeon"},"minLevel":70,"quest":true,"desc":"In Wasteland Hive.","id":1706}, + {"name":"Surface Portal","type":"Portal","wcid":11230,"cell":"0285023F","place":"dungeon","dest":{"cell":"1CBE0028","place":"outdoor","ns":50.78,"ew":-79.09},"minLevel":30,"desc":"In Wasteland Hive.","id":1707}, + {"name":"Surface Portal","type":"Portal","wcid":11230,"cell":"0285024E","place":"dungeon","dest":{"cell":"1CBE0028","place":"outdoor","ns":50.78,"ew":-79.09},"minLevel":30,"desc":"In Wasteland Hive.","id":1708}, + {"name":"Surface Portal","type":"Portal","wcid":11230,"cell":"028502E2","place":"dungeon","dest":{"cell":"1CBE0028","place":"outdoor","ns":50.78,"ew":-79.09},"minLevel":30,"desc":"In Wasteland Hive.","id":1709}, + {"name":"Surface Portal","type":"Portal","wcid":11230,"cell":"02850359","place":"dungeon","dest":{"cell":"1CBE0028","place":"outdoor","ns":50.78,"ew":-79.09},"minLevel":30,"desc":"In Wasteland Hive.","id":1710}, + {"name":"Exit to the Surface","type":"Portal","wcid":11324,"cell":"02860216","place":"dungeon","dest":{"cell":"18B30014","place":"outdoor","ns":41.63,"ew":-82.51},"desc":"In Tumerok Cave.","id":1711}, + {"name":"Exit to the Surface","type":"Portal","wcid":11324,"cell":"028602B7","place":"dungeon","dest":{"cell":"18B30014","place":"outdoor","ns":41.63,"ew":-82.51},"desc":"In Tumerok Cave.","id":1712}, + {"name":"Exit to the Surface","type":"Portal","wcid":11338,"cell":"0287018A","place":"dungeon","dest":{"cell":"20B00001","place":"outdoor","ns":38.9,"ew":-76.32},"desc":"In Aun Papileona's Shrine to Raeta.","id":1713}, + {"name":"Exit to the Surface","type":"Portal","wcid":11338,"cell":"02870215","place":"dungeon","dest":{"cell":"20B00001","place":"outdoor","ns":38.9,"ew":-76.32},"desc":"In Aun Papileona's Shrine to Raeta.","id":1714}, + {"name":"Royal Hive Portal","type":"Portal","wcid":11206,"cell":"02880100","place":"dungeon","dest":{"cell":"02880280","place":"dungeon"},"minLevel":70,"quest":true,"desc":"In a dungeon (landblock 0288).","id":1715}, + {"name":"Mount Elyrii Hive Portal","type":"Portal","wcid":11210,"cell":"02880264","place":"dungeon","dest":{"cell":"03A7010F","place":"dungeon","name":"Mount Elyrii Hive"},"minLevel":30,"desc":"In a dungeon (landblock 0288).","id":1716}, + {"name":"Wasteland Hive Portal","type":"Portal","wcid":11209,"cell":"02880279","place":"dungeon","dest":{"cell":"0285010A","place":"dungeon","name":"Wasteland Hive"},"minLevel":30,"desc":"In a dungeon (landblock 0288).","id":1717}, + {"name":"North Fork Dam Hive Portal","type":"Portal","wcid":11211,"cell":"028802A7","place":"dungeon","dest":{"cell":"03A60102","place":"dungeon","name":"North Fork Dam Hive"},"minLevel":30,"desc":"In a dungeon (landblock 0288).","id":1718}, + {"name":"Surface Portal","type":"Portal","wcid":11218,"cell":"028902BA","place":"dungeon","dest":{"cell":"1DBD0011","place":"outdoor","ns":49.3,"ew":-78.5},"minLevel":30,"desc":"In Tiny Hive.","id":1719}, + {"name":"Surface Portal","type":"Portal","wcid":11220,"cell":"028A01C8","place":"dungeon","dest":{"cell":"1DBE002F","place":"outdoor","ns":50.74,"ew":-78.22},"minLevel":30,"desc":"In a dungeon (landblock 028A).","id":1720}, + {"name":"Surface Portal","type":"Portal","wcid":11222,"cell":"028B0109","place":"dungeon","dest":{"cell":"1EC0003A","place":"outdoor","ns":51.75,"ew":-77.17},"minLevel":30,"desc":"In a dungeon (landblock 028B).","id":1721}, + {"name":"Surface Portal","type":"Portal","wcid":11224,"cell":"028C0134","place":"dungeon","dest":{"cell":"21BC000E","place":"outdoor","ns":48.97,"ew":-75.36},"minLevel":30,"desc":"In a dungeon (landblock 028C).","id":1722}, + {"name":"Surface Portal","type":"Portal","wcid":11224,"cell":"028C021C","place":"dungeon","dest":{"cell":"21BC000E","place":"outdoor","ns":48.97,"ew":-75.36},"minLevel":30,"desc":"In a dungeon (landblock 028C).","id":1723}, + {"name":"Surface Portal","type":"Portal","wcid":11226,"cell":"028D010A","place":"dungeon","dest":{"cell":"24B80037","place":"outdoor","ns":45.89,"ew":-72.54},"minLevel":30,"desc":"In a dungeon (landblock 028D).","id":1724}, + {"name":"Surface Portal","type":"Portal","wcid":11226,"cell":"028D02EF","place":"dungeon","dest":{"cell":"24B80037","place":"outdoor","ns":45.89,"ew":-72.54},"minLevel":30,"desc":"In a dungeon (landblock 028D).","id":1725}, + {"name":"Exit to the Surface","type":"Portal","wcid":11441,"cell":"028E01BF","place":"dungeon","dest":{"cell":"24BC003C","place":"outdoor","ns":48.84,"ew":-72.43},"desc":"In Palenqual's Caverns.","id":1726}, + {"name":"Exit to the Surface","type":"Portal","wcid":11441,"cell":"028E0289","place":"dungeon","dest":{"cell":"24BC003C","place":"outdoor","ns":48.84,"ew":-72.43},"desc":"In Palenqual's Caverns.","id":1727}, + {"name":"Exit to the Surface","type":"Portal","wcid":11441,"cell":"028E0384","place":"dungeon","dest":{"cell":"24BC003C","place":"outdoor","ns":48.84,"ew":-72.43},"desc":"In Palenqual's Caverns.","id":1728}, + {"name":"Exit","type":"Portal","wcid":11685,"cell":"028F018B","place":"dungeon","dest":{"cell":"B7630019","place":"outdoor","ns":-22.66,"ew":44.76},"desc":"In Swamp Gardens.","id":1729}, + {"name":"Exit","type":"Portal","wcid":11685,"cell":"028F014A","place":"dungeon","dest":{"cell":"B7630019","place":"outdoor","ns":-22.66,"ew":44.76},"desc":"In Swamp Gardens.","id":1730}, + {"name":"Exit","type":"Portal","wcid":10793,"cell":"0290010C","place":"dungeon","dest":{"cell":"BE890027","place":"outdoor","ns":8.26,"ew":50.49},"minLevel":20,"desc":"In Stable Rift.","id":1731}, + {"name":"Exit","type":"Portal","wcid":10793,"cell":"029002C2","place":"dungeon","dest":{"cell":"BE890027","place":"outdoor","ns":8.26,"ew":50.49},"minLevel":20,"desc":"In Stable Rift.","id":1732}, + {"name":"Exit","type":"Portal","wcid":10797,"cell":"0291037F","place":"dungeon","dest":{"cell":"2E43000C","place":"outdoor","ns":-48.02,"ew":-65.01},"minLevel":50,"desc":"In Singularity Bore.","id":1733}, + {"name":"Exit","type":"Portal","wcid":10797,"cell":"02910395","place":"dungeon","dest":{"cell":"2E43000C","place":"outdoor","ns":-48.02,"ew":-65.01},"minLevel":50,"desc":"In Singularity Bore.","id":1734}, + {"name":"Singularity Caul","type":"Portal","wcid":10794,"cell":"029103C3","place":"dungeon","dest":{"cell":"09040008","place":"outdoor","ns":-97.96,"ew":-94.7},"quest":true,"desc":"In Singularity Bore.","id":1735}, + {"name":"Exit to the Surface","type":"Portal","wcid":11326,"cell":"0292021E","place":"dungeon","dest":{"cell":"15B10026","place":"outdoor","ns":40.25,"ew":-84.69},"desc":"In Tumerok Cavern.","id":1736}, + {"name":"Exit Portal","type":"Portal","wcid":10984,"cell":"0293029E","place":"dungeon","dest":{"cell":"1DBB0019","place":"outdoor","ns":47.73,"ew":-78.37},"minLevel":30,"desc":"In a dungeon (landblock 0293).","id":1737}, + {"name":"Surface","type":"Portal","wcid":10733,"cell":"02940100","place":"dungeon","dest":{"cell":"7C130008","place":"outdoor","ns":-85.96,"ew":-2.66},"desc":"In a dungeon (landblock 0294).","id":1738}, + {"name":"Surface","type":"Portal","wcid":10735,"cell":"02950104","place":"dungeon","dest":{"cell":"3129000D","place":"outdoor","ns":-68.74,"ew":-62.6},"desc":"In Inculcation Cells.","id":1739}, + {"name":"Surface","type":"Portal","wcid":10735,"cell":"0295026E","place":"dungeon","dest":{"cell":"3129000D","place":"outdoor","ns":-68.74,"ew":-62.6},"desc":"In Inculcation Cells.","id":1740}, + {"name":"Surface Portal","type":"Portal","wcid":10720,"cell":"02960102","place":"dungeon","dest":{"cell":"E0320011","place":"outdoor","ns":-61.89,"ew":77.54},"desc":"In a dungeon (landblock 0296).","id":1741}, + {"name":"Surface Portal","type":"Portal","wcid":10720,"cell":"029601B8","place":"dungeon","dest":{"cell":"E0320011","place":"outdoor","ns":-61.89,"ew":77.54},"desc":"In a dungeon (landblock 0296).","id":1742}, + {"name":"Surface Portal","type":"Portal","wcid":10719,"cell":"02970217","place":"dungeon","dest":{"cell":"BA6F0036","place":"outdoor","ns":-12.61,"ew":47.55},"desc":"In a dungeon (landblock 0297).","id":1743}, + {"name":"Surface Portal","type":"Portal","wcid":10719,"cell":"02970147","place":"dungeon","dest":{"cell":"BA6F0036","place":"outdoor","ns":-12.61,"ew":47.55},"desc":"In a dungeon (landblock 0297).","id":1744}, + {"name":"Surface Portal","type":"Portal","wcid":10721,"cell":"0298010A","place":"dungeon","dest":{"cell":"7C130008","place":"outdoor","ns":-85.96,"ew":-2.66},"desc":"In Land Bridge Staging Complex.","id":1745}, + {"name":"Surface Portal","type":"Portal","wcid":10721,"cell":"0298022C","place":"dungeon","dest":{"cell":"7C130008","place":"outdoor","ns":-85.96,"ew":-2.66},"desc":"In Land Bridge Staging Complex.","id":1746}, + {"name":"Surface Portal","type":"Portal","wcid":10721,"cell":"0298022E","place":"dungeon","dest":{"cell":"7C130008","place":"outdoor","ns":-85.96,"ew":-2.66},"desc":"In Land Bridge Staging Complex.","id":1747}, + {"name":"Surface Portal","type":"Portal","wcid":10721,"cell":"0298023F","place":"dungeon","dest":{"cell":"7C130008","place":"outdoor","ns":-85.96,"ew":-2.66},"desc":"In Land Bridge Staging Complex.","id":1748}, + {"name":"Surface Portal","type":"Portal","wcid":10721,"cell":"02980241","place":"dungeon","dest":{"cell":"7C130008","place":"outdoor","ns":-85.96,"ew":-2.66},"desc":"In Land Bridge Staging Complex.","id":1749}, + {"name":"Surface Portal","type":"Portal","wcid":10721,"cell":"029802A4","place":"dungeon","dest":{"cell":"7C130008","place":"outdoor","ns":-85.96,"ew":-2.66},"desc":"In Land Bridge Staging Complex.","id":1750}, + {"name":"Surface Portal","type":"Portal","wcid":9530,"cell":"02990118","place":"dungeon","dest":{"cell":"B3810020","place":"outdoor","ns":2.04,"ew":41.6},"desc":"In a dungeon (landblock 0299).","id":1751}, + {"name":"Surface Portal","type":"Portal","wcid":9509,"cell":"029A0130","place":"dungeon","dest":{"cell":"A432000C","place":"outdoor","ns":-61.64,"ew":29.41},"desc":"In a dungeon (landblock 029A).","id":1752}, + {"name":"Gredaline Consulate","type":"Portal","wcid":9507,"cell":"029A01F2","place":"dungeon","dest":{"cell":"029B0318","place":"dungeon","name":"Gredaline Consulate"},"minLevel":25,"desc":"In a dungeon (landblock 029A).","id":1753}, + {"name":"Surface Portal","type":"Portal","wcid":9509,"cell":"029B02E3","place":"dungeon","dest":{"cell":"A432000C","place":"outdoor","ns":-61.64,"ew":29.41},"desc":"In Gredaline Consulate.","id":1754}, + {"name":"Surface Portal","type":"Portal","wcid":9509,"cell":"029B02F5","place":"dungeon","dest":{"cell":"A432000C","place":"outdoor","ns":-61.64,"ew":29.41},"desc":"In Gredaline Consulate.","id":1755}, + {"name":"The Envoy's Chamber","type":"Portal","wcid":9388,"cell":"029B0358","place":"dungeon","dest":{"cell":"029A01F1","place":"dungeon"},"minLevel":25,"desc":"In Gredaline Consulate.","id":1756}, + {"name":"Outside Linvak Tukal","type":"Portal","wcid":9410,"cell":"029C0110","place":"dungeon","dest":{"cell":"A220002F","place":"outdoor","ns":-75.74,"ew":28.23},"desc":"In Linvak Tukal Entryway.","id":1757}, + {"name":"Portal to Linvak Tukal","type":"Portal","wcid":8401,"cell":"029C02A7","place":"dungeon","dest":{"cell":"A21E001A","place":"outdoor","ns":-77.79,"ew":28.0},"desc":"This portal goes to Linvak Tukal, the fortress bastion of our Lugian allies in the Linvak Range. This is a good town for characters over level 40. In Linvak Tukal Entryway.","id":1758}, + {"name":"Exit","type":"Portal","wcid":9323,"cell":"029D0103","place":"dungeon","dest":{"cell":"937C003B","place":"outdoor","ns":-2.55,"ew":16.41},"desc":"In Mnemosyne Collection Site.","id":1759}, + {"name":"Small Mnemosyne Collection Site","type":"Portal","wcid":9320,"cell":"029D0105","place":"dungeon","dest":{"cell":"029D0106","place":"dungeon","name":"Mnemosyne Collection Site"},"minLevel":15,"desc":"In Mnemosyne Collection Site.","id":1760}, + {"name":"Exit","type":"Portal","wcid":9323,"cell":"029D0106","place":"dungeon","dest":{"cell":"937C003B","place":"outdoor","ns":-2.55,"ew":16.41},"desc":"In Mnemosyne Collection Site.","id":1761}, + {"name":"Large Mnemosyne Collection Site","type":"Portal","wcid":9321,"cell":"029D010B","place":"dungeon","dest":{"cell":"029D010C","place":"dungeon","name":"Mnemosyne Collection Site"},"minLevel":30,"desc":"In Mnemosyne Collection Site.","id":1762}, + {"name":"Exit","type":"Portal","wcid":9323,"cell":"029D0111","place":"dungeon","dest":{"cell":"937C003B","place":"outdoor","ns":-2.55,"ew":16.41},"desc":"In Mnemosyne Collection Site.","id":1763}, + {"name":"Aerbax Haven","type":"Portal","wcid":9203,"cell":"029E0119","place":"dungeon","dest":{"cell":"029F017E","place":"dungeon"},"desc":"In Aerbax Laboratory.","id":1764}, + {"name":"Surface","type":"Portal","wcid":9202,"cell":"029E0122","place":"dungeon","dest":{"cell":"89720026","place":"outdoor","ns":-10.21,"ew":8.12},"desc":"In Aerbax Laboratory.","id":1765}, + {"name":"Surface","type":"Portal","wcid":9202,"cell":"029E0268","place":"dungeon","dest":{"cell":"89720026","place":"outdoor","ns":-10.21,"ew":8.12},"desc":"In Aerbax Laboratory.","id":1766}, + {"name":"Surface","type":"Portal","wcid":9204,"cell":"029F017F","place":"dungeon","dest":{"cell":"89720026","place":"outdoor","ns":-10.21,"ew":8.12},"desc":"In a dungeon (landblock 029F).","id":1767}, + {"name":"Surface","type":"Portal","wcid":9204,"cell":"029F0303","place":"dungeon","dest":{"cell":"89720026","place":"outdoor","ns":-10.21,"ew":8.12},"desc":"In a dungeon (landblock 029F).","id":1768}, + {"name":"Surface","type":"Portal","wcid":9200,"cell":"02A002FE","place":"dungeon","dest":{"cell":"80710011","place":"outdoor","ns":-11.46,"ew":0.67},"desc":"In Sand Shallow.","id":1769}, + {"name":"Surface Portal","type":"Portal","wcid":9297,"cell":"02A10175","place":"dungeon","dest":{"cell":"16350015","place":"outdoor","ns":-59.08,"ew":-84.14},"desc":"In Panopticon.","id":1770}, + {"name":"Surface Portal","type":"Portal","wcid":9297,"cell":"02A102A2","place":"dungeon","dest":{"cell":"16350015","place":"outdoor","ns":-59.08,"ew":-84.14},"desc":"In Panopticon.","id":1771}, + {"name":"Surface Portal","type":"Portal","wcid":9297,"cell":"02A102A4","place":"dungeon","dest":{"cell":"16350015","place":"outdoor","ns":-59.08,"ew":-84.14},"desc":"In Panopticon.","id":1772}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A2010E","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A2).","id":1773}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A20145","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A2).","id":1774}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A2017B","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A2).","id":1775}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A202DD","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A2).","id":1776}, + {"name":"Surface","type":"Portal","wcid":9167,"cell":"02A30107","place":"dungeon","dest":{"cell":"7E91002A","place":"outdoor","ns":14.16,"ew":-0.65},"desc":"In a dungeon (landblock 02A3).","id":1777}, + {"name":"Surface","type":"Portal","wcid":9144,"cell":"02A40101","place":"dungeon","dest":{"cell":"91460001","place":"outdoor","ns":-45.87,"ew":14.12},"desc":"In South Tumerok Vanguard Outpost.","id":1778}, + {"name":"Surface","type":"Portal","wcid":9144,"cell":"02A4010E","place":"dungeon","dest":{"cell":"91460001","place":"outdoor","ns":-45.87,"ew":14.12},"desc":"In South Tumerok Vanguard Outpost.","id":1779}, + {"name":"Surface","type":"Portal","wcid":9142,"cell":"02A5015B","place":"dungeon","dest":{"cell":"7F760009","place":"outdoor","ns":-7.53,"ew":-0.17},"desc":"In North Tumerok Vanguard Outpost.","id":1780}, + {"name":"Surface","type":"Portal","wcid":9142,"cell":"02A502B3","place":"dungeon","dest":{"cell":"7F760009","place":"outdoor","ns":-7.53,"ew":-0.17},"desc":"In North Tumerok Vanguard Outpost.","id":1781}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A6010E","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A6).","id":1782}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A60145","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A6).","id":1783}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A6017B","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A6).","id":1784}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A602DD","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A6).","id":1785}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A7010E","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A7).","id":1786}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A70145","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A7).","id":1787}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A7017B","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A7).","id":1788}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A702DD","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A7).","id":1789}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A8010E","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A8).","id":1790}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A80145","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A8).","id":1791}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A8017B","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A8).","id":1792}, + {"name":"Surface Portal","type":"Portal","wcid":9073,"cell":"02A802DD","place":"dungeon","dest":{"cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65},"desc":"In a dungeon (landblock 02A8).","id":1793}, + {"name":"South Direlands Portal","type":"Portal","wcid":1107,"cell":"02AA0103","place":"dungeon","dest":{"cell":"5416001A","place":"outdoor","ns":-84.2,"ew":-34.44},"minLevel":12,"desc":"In Desert March.","id":1794}, + {"name":"Southern Mt. Esper","type":"Portal","wcid":8501,"cell":"02AA0119","place":"dungeon","dest":{"cell":"8FC60024","place":"outdoor","ns":56.75,"ew":12.94},"minLevel":12,"desc":"In Desert March.","id":1795}, + {"name":"Bandit Castle Portal","type":"Portal","wcid":1102,"cell":"02AA011A","place":"dungeon","dest":{"cell":"BDD00006","place":"outdoor","ns":64.95,"ew":49.32},"desc":"In Desert March.","id":1796}, + {"name":"Surface Portal","type":"Portal","wcid":9004,"cell":"02AA0128","place":"dungeon","dest":{"cell":"7A870024","place":"outdoor","ns":6.38,"ew":-3.91},"desc":"In Desert March.","id":1797}, + {"name":"Obsidian Rim Portal","type":"Portal","wcid":7210,"cell":"02AA014D","place":"dungeon","dest":{"cell":"2E43000C","place":"outdoor","ns":-48.02,"ew":-65.01},"minLevel":35,"desc":"In Desert March.","id":1798}, + {"name":"North Direlands Portal","type":"Portal","wcid":1104,"cell":"02AA0151","place":"dungeon","dest":{"cell":"3C9D0010","place":"outdoor","ns":24.45,"ew":-53.85},"minLevel":12,"desc":"In Desert March.","id":1799}, + {"name":"Black Hill","type":"Portal","wcid":2328,"cell":"02AA0167","place":"dungeon","dest":{"cell":"3E310004","place":"outdoor","ns":-62.36,"ew":-52.3},"desc":"In Desert March.","id":1800}, + {"name":"Surface Portal","type":"Portal","wcid":9004,"cell":"02AA0231","place":"dungeon","dest":{"cell":"7A870024","place":"outdoor","ns":6.38,"ew":-3.91},"desc":"In Desert March.","id":1801}, + {"name":"Surface","type":"Portal","wcid":4054,"cell":"02AB010B","place":"dungeon","dest":{"cell":"C7210100","place":"building","ns":-75.45,"ew":57.28},"desc":"In a dungeon (landblock 02AB).","id":1802}, + {"name":"Surface","type":"Portal","wcid":4054,"cell":"02AB0147","place":"dungeon","dest":{"cell":"C7210100","place":"building","ns":-75.45,"ew":57.28},"desc":"In a dungeon (landblock 02AB).","id":1803}, + {"name":"Surface","type":"Portal","wcid":4054,"cell":"02AB0161","place":"dungeon","dest":{"cell":"C7210100","place":"building","ns":-75.45,"ew":57.28},"desc":"In a dungeon (landblock 02AB).","id":1804}, + {"name":"Surface Portal","type":"Portal","wcid":8846,"cell":"02AC0127","place":"dungeon","dest":{"cell":"86620029","place":"outdoor","ns":-23.47,"ew":5.84},"desc":"In a dungeon (landblock 02AC).","id":1805}, + {"name":"Surface Portal","type":"Portal","wcid":8846,"cell":"02AC01E0","place":"dungeon","dest":{"cell":"86620029","place":"outdoor","ns":-23.47,"ew":5.84},"desc":"In a dungeon (landblock 02AC).","id":1806}, + {"name":"Surface Portal","type":"Portal","wcid":8844,"cell":"02AC02DD","place":"dungeon","dest":{"cell":"8662002B","place":"outdoor","ns":-23.35,"ew":5.75},"desc":"In a dungeon (landblock 02AC).","id":1807}, + {"name":"Empyrean Cloister","type":"Portal","wcid":8888,"cell":"02AC02E6","place":"dungeon","dest":{"cell":"02AD0108","place":"dungeon","name":"Empyrean Cloister"},"desc":"In a dungeon (landblock 02AC).","id":1808}, + {"name":"Empyrean Cloister","type":"Portal","wcid":8888,"cell":"02AC02E8","place":"dungeon","dest":{"cell":"02AD0108","place":"dungeon","name":"Empyrean Cloister"},"desc":"In a dungeon (landblock 02AC).","id":1809}, + {"name":"Surface Portal","type":"Portal","wcid":8844,"cell":"02AC02F2","place":"dungeon","dest":{"cell":"8662002B","place":"outdoor","ns":-23.35,"ew":5.75},"desc":"In a dungeon (landblock 02AC).","id":1810}, + {"name":"Lower Empyrean Mausoleum Portal","type":"Portal","wcid":8835,"cell":"02AD010A","place":"dungeon","dest":{"cell":"02AC02EF","place":"dungeon"},"minLevel":15,"desc":"In Empyrean Cloister.","id":1811}, + {"name":"Upper Empyrean Mausoleum Portal","type":"Portal","wcid":8834,"cell":"02AD010B","place":"dungeon","dest":{"cell":"02AC02E4","place":"dungeon"},"minLevel":21,"desc":"In Empyrean Cloister.","id":1812}, + {"name":"Surface Portal","type":"Portal","wcid":8844,"cell":"02AD0151","place":"dungeon","dest":{"cell":"8662002B","place":"outdoor","ns":-23.35,"ew":5.75},"desc":"In Empyrean Cloister.","id":1813}, + {"name":"Surface Portal","type":"Portal","wcid":8844,"cell":"02AD0161","place":"dungeon","dest":{"cell":"8662002B","place":"outdoor","ns":-23.35,"ew":5.75},"desc":"In Empyrean Cloister.","id":1814}, + {"name":"Surface Portal","type":"Portal","wcid":8844,"cell":"02AD0207","place":"dungeon","dest":{"cell":"8662002B","place":"outdoor","ns":-23.35,"ew":5.75},"desc":"In Empyrean Cloister.","id":1815}, + {"name":"Upper Chakron Flux Portal","type":"Portal","wcid":8831,"cell":"02AE0107","place":"dungeon","dest":{"cell":"02AF0308","place":"dungeon"},"minLevel":41,"desc":"In Chakron Gate.","id":1816}, + {"name":"Lower Chakron Flux Portal","type":"Portal","wcid":8832,"cell":"02AE010A","place":"dungeon","dest":{"cell":"02AF0345","place":"dungeon"},"minLevel":36,"desc":"In Chakron Gate.","id":1817}, + {"name":"Surface Portal","type":"Portal","wcid":8841,"cell":"02AE02A0","place":"dungeon","dest":{"cell":"313D0004","place":"outdoor","ns":-52.77,"ew":-62.75},"desc":"In Chakron Gate.","id":1818}, + {"name":"Surface Portal","type":"Portal","wcid":8843,"cell":"02AF0107","place":"dungeon","dest":{"cell":"313D0013","place":"outdoor","ns":-52.87,"ew":-62.48},"desc":"In a dungeon (landblock 02AF).","id":1819}, + {"name":"Surface Portal","type":"Portal","wcid":8843,"cell":"02AF0110","place":"dungeon","dest":{"cell":"313D0013","place":"outdoor","ns":-52.87,"ew":-62.48},"desc":"In a dungeon (landblock 02AF).","id":1820}, + {"name":"Lower Chakron Flux Portal","type":"Portal","wcid":8832,"cell":"02AF0118","place":"dungeon","dest":{"cell":"02AF0345","place":"dungeon"},"minLevel":36,"desc":"In a dungeon (landblock 02AF).","id":1821}, + {"name":"Upper Chakron Flux Portal","type":"Portal","wcid":8831,"cell":"02AF011F","place":"dungeon","dest":{"cell":"02AF0308","place":"dungeon"},"minLevel":41,"desc":"In a dungeon (landblock 02AF).","id":1822}, + {"name":"Lower Chakron Flux Portal","type":"Portal","wcid":8832,"cell":"02AF017E","place":"dungeon","dest":{"cell":"02AF0345","place":"dungeon"},"minLevel":36,"desc":"In a dungeon (landblock 02AF).","id":1823}, + {"name":"Lower Chakron Flux Portal","type":"Portal","wcid":8832,"cell":"02AF0180","place":"dungeon","dest":{"cell":"02AF0345","place":"dungeon"},"minLevel":36,"desc":"In a dungeon (landblock 02AF).","id":1824}, + {"name":"Upper Chakron Flux Portal","type":"Portal","wcid":8831,"cell":"02AF01A7","place":"dungeon","dest":{"cell":"02AF0308","place":"dungeon"},"minLevel":41,"desc":"In a dungeon (landblock 02AF).","id":1825}, + {"name":"Upper Chakron Flux Portal","type":"Portal","wcid":8831,"cell":"02AF01A9","place":"dungeon","dest":{"cell":"02AF0308","place":"dungeon"},"minLevel":41,"desc":"In a dungeon (landblock 02AF).","id":1826}, + {"name":"Chakron Gate","type":"Portal","wcid":8889,"cell":"02AF0300","place":"dungeon","dest":{"cell":"02AE0100","place":"dungeon","name":"Chakron Gate"},"desc":"In a dungeon (landblock 02AF).","id":1827}, + {"name":"Surface Portal","type":"Portal","wcid":8841,"cell":"02AF0302","place":"dungeon","dest":{"cell":"313D0004","place":"outdoor","ns":-52.77,"ew":-62.75},"desc":"In a dungeon (landblock 02AF).","id":1828}, + {"name":"Chakron Gate","type":"Portal","wcid":8889,"cell":"02AF034F","place":"dungeon","dest":{"cell":"02AE0100","place":"dungeon","name":"Chakron Gate"},"desc":"In a dungeon (landblock 02AF).","id":1829}, + {"name":"Surface Portal","type":"Portal","wcid":8841,"cell":"02AF0351","place":"dungeon","dest":{"cell":"313D0004","place":"outdoor","ns":-52.77,"ew":-62.75},"desc":"In a dungeon (landblock 02AF).","id":1830}, + {"name":"Surface Portal","type":"Portal","wcid":8851,"cell":"02B00104","place":"dungeon","dest":{"cell":"7F7F001C","place":"outdoor","ns":-0.01,"ew":-0.01},"desc":"In a dungeon (landblock 02B0).","id":1831}, + {"name":"Surface Portal","type":"Portal","wcid":8851,"cell":"02B002A7","place":"dungeon","dest":{"cell":"7F7F001C","place":"outdoor","ns":-0.01,"ew":-0.01},"desc":"In a dungeon (landblock 02B0).","id":1832}, + {"name":"Lower Heart of Darkness Portal","type":"Portal","wcid":8838,"cell":"02B10104","place":"dungeon","dest":{"cell":"02B201FB","place":"dungeon"},"minLevel":31,"desc":"In Upper Shade Stronghold.","id":1833}, + {"name":"Upper Heart of Darkness Portal","type":"Portal","wcid":8837,"cell":"02B1012A","place":"dungeon","dest":{"cell":"02B20251","place":"dungeon"},"minLevel":26,"desc":"In Upper Shade Stronghold.","id":1834}, + {"name":"Surface Portal","type":"Portal","wcid":8848,"cell":"02B10258","place":"dungeon","dest":{"cell":"7FDB000C","place":"outdoor","ns":73.56,"ew":-0.24},"desc":"In Upper Shade Stronghold.","id":1835}, + {"name":"Surface Portal","type":"Portal","wcid":8848,"cell":"02B10283","place":"dungeon","dest":{"cell":"7FDB000C","place":"outdoor","ns":73.56,"ew":-0.24},"desc":"In Upper Shade Stronghold.","id":1836}, + {"name":"Surface Portal","type":"Portal","wcid":8848,"cell":"02B20110","place":"dungeon","dest":{"cell":"7FDB000C","place":"outdoor","ns":73.56,"ew":-0.24},"desc":"In a dungeon (landblock 02B2).","id":1837}, + {"name":"Surface Portal","type":"Portal","wcid":8850,"cell":"02B201EA","place":"dungeon","dest":{"cell":"7FDB000C","place":"outdoor","ns":73.56,"ew":-0.24},"desc":"In a dungeon (landblock 02B2).","id":1838}, + {"name":"Lower Shade Stronghold","type":"Portal","wcid":8886,"cell":"02B201EC","place":"dungeon","dest":{"cell":"02B10138","place":"dungeon","name":"Upper Shade Stronghold"},"desc":"In a dungeon (landblock 02B2).","id":1839}, + {"name":"Surface Portal","type":"Portal","wcid":8850,"cell":"02B2025A","place":"dungeon","dest":{"cell":"7FDB000C","place":"outdoor","ns":73.56,"ew":-0.24},"desc":"In a dungeon (landblock 02B2).","id":1840}, + {"name":"Upper Shade Stronghold","type":"Portal","wcid":8885,"cell":"02B2025C","place":"dungeon","dest":{"cell":"02B10135","place":"dungeon","name":"Upper Shade Stronghold"},"desc":"In a dungeon (landblock 02B2).","id":1841}, + {"name":"Surface Portal","type":"Portal","wcid":8848,"cell":"02B202B7","place":"dungeon","dest":{"cell":"7FDB000C","place":"outdoor","ns":73.56,"ew":-0.24},"desc":"In a dungeon (landblock 02B2).","id":1842}, + {"name":"Surface","type":"Portal","wcid":8601,"cell":"02B301A0","place":"dungeon","dest":{"cell":"F529001F","place":"outdoor","ns":-68.49,"ew":94.39},"desc":"In Moars Laboratory.","id":1843}, + {"name":"Surface","type":"Portal","wcid":8601,"cell":"02B301F8","place":"dungeon","dest":{"cell":"F529001F","place":"outdoor","ns":-68.49,"ew":94.39},"desc":"In Moars Laboratory.","id":1844}, + {"name":"Surface Portal","type":"Portal","wcid":8579,"cell":"02B40249","place":"dungeon","dest":{"cell":"F0240033","place":"outdoor","ns":-72.94,"ew":90.73},"desc":"In A Mosswart Hideout.","id":1845}, + {"name":"Surface","type":"Portal","wcid":8585,"cell":"02B501A8","place":"dungeon","dest":{"cell":"F8270017","place":"outdoor","ns":-70.09,"ew":96.67},"desc":"In Moarsmen Spawning Grounds.","id":1846}, + {"name":"Surface","type":"Portal","wcid":8585,"cell":"02B50224","place":"dungeon","dest":{"cell":"F8270017","place":"outdoor","ns":-70.09,"ew":96.67},"desc":"In Moarsmen Spawning Grounds.","id":1847}, + {"name":"Surface","type":"Portal","wcid":8585,"cell":"02B502AF","place":"dungeon","dest":{"cell":"F8270017","place":"outdoor","ns":-70.09,"ew":96.67},"desc":"In Moarsmen Spawning Grounds.","id":1848}, + {"name":"Surface","type":"Portal","wcid":8587,"cell":"02B6012B","place":"dungeon","dest":{"cell":"EC25003F","place":"outdoor","ns":-71.7,"ew":87.62},"desc":"In Idol Spawning Grounds.","id":1849}, + {"name":"Surface","type":"Portal","wcid":8587,"cell":"02B6015A","place":"dungeon","dest":{"cell":"EC25003F","place":"outdoor","ns":-71.7,"ew":87.62},"desc":"In Idol Spawning Grounds.","id":1850}, + {"name":"Surface","type":"Portal","wcid":8587,"cell":"02B6029B","place":"dungeon","dest":{"cell":"EC25003F","place":"outdoor","ns":-71.7,"ew":87.62},"desc":"In Idol Spawning Grounds.","id":1851}, + {"name":"Cathedral Ruins Portal","type":"Portal","wcid":8533,"cell":"02B70133","place":"dungeon","dest":{"cell":"F418000B","place":"outdoor","ns":-82.5,"ew":93.4},"desc":"In Catacombs of Ithaenc.","id":1852}, + {"name":"Cathedral Ruins Portal","type":"Portal","wcid":8533,"cell":"02B702F6","place":"dungeon","dest":{"cell":"F418000B","place":"outdoor","ns":-82.5,"ew":93.4},"desc":"In Catacombs of Ithaenc.","id":1853}, + {"name":"Surface","type":"Portal","wcid":8577,"cell":"02B801F3","place":"dungeon","dest":{"cell":"EE20002A","place":"outdoor","ns":-76.2,"ew":89.01},"desc":"In Rumuba's Hidey-Hole.","id":1854}, + {"name":"Surface","type":"Portal","wcid":8577,"cell":"02B802B5","place":"dungeon","dest":{"cell":"EE20002A","place":"outdoor","ns":-76.2,"ew":89.01},"desc":"In Rumuba's Hidey-Hole.","id":1855}, + {"name":"Surface","type":"Portal","wcid":29098,"cell":"02B90180","place":"dungeon","dest":{"cell":"30DA002E","place":"outdoor","ns":72.99,"ew":-63.02},"desc":"In Moist Hovel.","id":1856}, + {"name":"Surface","type":"Portal","wcid":29098,"cell":"02B9010E","place":"dungeon","dest":{"cell":"30DA002E","place":"outdoor","ns":72.99,"ew":-63.02},"desc":"In Moist Hovel.","id":1857}, + {"name":"Surface","type":"Portal","wcid":29098,"cell":"02B9011D","place":"dungeon","dest":{"cell":"30DA002E","place":"outdoor","ns":72.99,"ew":-63.02},"desc":"In Moist Hovel.","id":1858}, + {"name":"Surface","type":"Portal","wcid":8599,"cell":"02BA011F","place":"dungeon","dest":{"cell":"F3270035","place":"outdoor","ns":-70.26,"ew":93.12},"desc":"In a dungeon (landblock 02BA).","id":1859}, + {"name":"Surface","type":"Portal","wcid":8599,"cell":"02BA01FD","place":"dungeon","dest":{"cell":"F3270035","place":"outdoor","ns":-70.26,"ew":93.12},"desc":"In a dungeon (landblock 02BA).","id":1860}, + {"name":"North Direlands Portal","type":"Portal","wcid":1104,"cell":"02BB0100","place":"dungeon","dest":{"cell":"3C9D0010","place":"outdoor","ns":24.45,"ew":-53.85},"minLevel":12,"desc":"In a dungeon (landblock 02BB).","id":1861}, + {"name":"Destroyed Plateau Portal","type":"Portal","wcid":4042,"cell":"02BB0101","place":"dungeon","dest":{"cell":"49B70021","place":"outdoor","ns":44.54,"ew":-43.13},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 02BB).","id":1862}, + {"name":"Destroyed Portal to Zaikhal","type":"Portal","wcid":1032,"cell":"02BB0103","place":"dungeon","dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 02BB).","id":1863}, + {"name":"Destroyed Portal to Neydisa Castle","type":"Portal","wcid":6086,"cell":"02BB0104","place":"dungeon","dest":{"cell":"95D60033","place":"outdoor","ns":69.55,"ew":17.86},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 02BB).","id":1864}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"02BB0106","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 02BB).","id":1865}, + {"name":"Destroyed Baishi Portal","type":"Portal","wcid":4037,"cell":"02BB0107","place":"dungeon","dest":{"cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 02BB).","id":1866}, + {"name":"Destroyed Tufa Portal","type":"Portal","wcid":4038,"cell":"02BB0109","place":"dungeon","dest":{"cell":"876C0008","place":"outdoor","ns":-14.77,"ew":6.06},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 02BB).","id":1867}, + {"name":"Destroyed Glenden Wood Portal","type":"Portal","wcid":1017,"cell":"02BB010A","place":"dungeon","dest":{"cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 02BB).","id":1868}, + {"name":"Destroyed Eastham Portal","type":"Portal","wcid":1016,"cell":"02BB010C","place":"dungeon","dest":{"cell":"CE940035","place":"outdoor","ns":16.92,"ew":63.48},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 02BB).","id":1869}, + {"name":"South Direlands Portal","type":"Portal","wcid":1107,"cell":"02BB010D","place":"dungeon","dest":{"cell":"5416001A","place":"outdoor","ns":-84.2,"ew":-34.44},"minLevel":12,"desc":"In a dungeon (landblock 02BB).","id":1870}, + {"name":"Surface","type":"Portal","wcid":8498,"cell":"02BB0150","place":"dungeon","dest":{"cell":"F5280026","place":"outdoor","ns":-69.42,"ew":94.51},"desc":"In a dungeon (landblock 02BB).","id":1871}, + {"name":"Surface","type":"Portal","wcid":8498,"cell":"02BB0191","place":"dungeon","dest":{"cell":"F5280026","place":"outdoor","ns":-69.42,"ew":94.51},"desc":"In a dungeon (landblock 02BB).","id":1872}, + {"name":"Surface","type":"Portal","wcid":8487,"cell":"02BC0147","place":"dungeon","dest":{"cell":"ED1E0013","place":"outdoor","ns":-77.68,"ew":87.88},"desc":"In Mosswart Nest.","id":1873}, + {"name":"Surface","type":"Portal","wcid":8485,"cell":"02BD016B","place":"dungeon","dest":{"cell":"F1270018","place":"outdoor","ns":-70.04,"ew":91.1},"desc":"In Small Ruin.","id":1874}, + {"name":"Surface","type":"Portal","wcid":8483,"cell":"02BE0120","place":"dungeon","dest":{"cell":"F428002F","place":"outdoor","ns":-69.28,"ew":93.78},"desc":"In a dungeon (landblock 02BE).","id":1875}, + {"name":"Surface","type":"Portal","wcid":8481,"cell":"02BF0120","place":"dungeon","dest":{"cell":"F921001D","place":"outdoor","ns":-75.1,"ew":97.57},"desc":"In a dungeon (landblock 02BF).","id":1876}, + {"name":"Surface","type":"Portal","wcid":8479,"cell":"02C00120","place":"dungeon","dest":{"cell":"F8190031","place":"outdoor","ns":-81.9,"ew":97.06},"desc":"In a dungeon (landblock 02C0).","id":1877}, + {"name":"Surface Portal","type":"Portal","wcid":8475,"cell":"02C10175","place":"dungeon","dest":{"cell":"E5240001","place":"outdoor","ns":-73.14,"ew":81.27},"desc":"In Mud Cave.","id":1878}, + {"name":"Surface Portal","type":"Portal","wcid":8477,"cell":"02C201E5","place":"dungeon","dest":{"cell":"F11E0008","place":"outdoor","ns":-77.22,"ew":90.88},"desc":"In Moarsmen Muck.","id":1879}, + {"name":"Surface Portal","type":"Portal","wcid":8459,"cell":"02C30102","place":"dungeon","dest":{"cell":"F5270014","place":"outdoor","ns":-70.41,"ew":94.34},"desc":"In Slithis Pit.","id":1880}, + {"name":"Surface Portal","type":"Portal","wcid":8459,"cell":"02C30184","place":"dungeon","dest":{"cell":"F5270014","place":"outdoor","ns":-70.41,"ew":94.34},"desc":"In Slithis Pit.","id":1881}, + {"name":"Surface Portal","type":"Portal","wcid":8459,"cell":"02C301D7","place":"dungeon","dest":{"cell":"F5270014","place":"outdoor","ns":-70.41,"ew":94.34},"desc":"In Slithis Pit.","id":1882}, + {"name":"Surface Portal","type":"Portal","wcid":8459,"cell":"02C30271","place":"dungeon","dest":{"cell":"F5270014","place":"outdoor","ns":-70.41,"ew":94.34},"desc":"In Slithis Pit.","id":1883}, + {"name":"Surface Portal","type":"Portal","wcid":8457,"cell":"02C401DA","place":"dungeon","dest":{"cell":"EF280100","place":"building","ns":-69.92,"ew":89.91},"desc":"In Moarsmen Hideout.","id":1884}, + {"name":"Surface Portal","type":"Portal","wcid":8457,"cell":"02C40253","place":"dungeon","dest":{"cell":"EF280100","place":"building","ns":-69.92,"ew":89.91},"desc":"In Moarsmen Hideout.","id":1885}, + {"name":"Surface Portal","type":"Portal","wcid":8457,"cell":"02C402F7","place":"dungeon","dest":{"cell":"EF280100","place":"building","ns":-69.92,"ew":89.91},"desc":"In Moarsmen Hideout.","id":1886}, + {"name":"Forsaken Portal","type":"Portal","wcid":8445,"cell":"02C50106","place":"dungeon","dest":{"cell":"F4260102","place":"dungeon"},"desc":"In Treacherous Tunnels.","id":1887}, + {"name":"Surface Portal","type":"Portal","wcid":8443,"cell":"02C502C8","place":"dungeon","dest":{"cell":"F0210100","place":"building","ns":-75.06,"ew":90.28},"desc":"In Treacherous Tunnels.","id":1888}, + {"name":"Mid Direlands Portal","type":"Portal","wcid":5487,"cell":"02C60100","place":"dungeon","dest":{"cell":"2D510001","place":"outdoor","ns":-37.06,"ew":-65.95},"minLevel":18,"desc":"In a dungeon (landblock 02C6).","id":1889}, + {"name":"Surface Portal","type":"Portal","wcid":8219,"cell":"02C6011E","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"In a dungeon (landblock 02C6).","id":1890}, + {"name":"Surface Portal","type":"Portal","wcid":8219,"cell":"02C60160","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"In a dungeon (landblock 02C6).","id":1891}, + {"name":"Uninhabited Area Portal","type":"Portal","wcid":8220,"cell":"02C60210","place":"dungeon","dest":{"cell":"02D2011F","place":"dungeon"},"minLevel":1,"maxLevel":25,"desc":"In a dungeon (landblock 02C6).","id":1892}, + {"name":"Surface Portal","type":"Portal","wcid":8393,"cell":"02C701BD","place":"dungeon","dest":{"cell":"3339002D","place":"outdoor","ns":-55.87,"ew":-60.64},"desc":"In Tumideon Fortress.","id":1893}, + {"name":"Surface Portal","type":"Portal","wcid":8393,"cell":"02C70227","place":"dungeon","dest":{"cell":"3339002D","place":"outdoor","ns":-55.87,"ew":-60.64},"desc":"In Tumideon Fortress.","id":1894}, + {"name":"Surface Portal","type":"Portal","wcid":8380,"cell":"02C80100","place":"dungeon","dest":{"cell":"BE5B0012","place":"outdoor","ns":-28.95,"ew":50.31},"desc":"In Banderling Conquest Dungeon.","id":1895}, + {"name":"Surface Portal","type":"Portal","wcid":8380,"cell":"02C80257","place":"dungeon","dest":{"cell":"BE5B0012","place":"outdoor","ns":-28.95,"ew":50.31},"desc":"In Banderling Conquest Dungeon.","id":1896}, + {"name":"Surface Portal","type":"Portal","wcid":8382,"cell":"02C90103","place":"dungeon","dest":{"cell":"282A0036","place":"outdoor","ns":-67.85,"ew":-69.29},"desc":"In Sotiris.","id":1897}, + {"name":"Surface Portal","type":"Portal","wcid":8382,"cell":"02C90282","place":"dungeon","dest":{"cell":"282A0036","place":"outdoor","ns":-67.85,"ew":-69.29},"desc":"In Sotiris.","id":1898}, + {"name":"Surface Portal","type":"Portal","wcid":8368,"cell":"02CA0223","place":"dungeon","dest":{"cell":"975F0038","place":"outdoor","ns":-25.23,"ew":19.52},"desc":"In Mosswart Maze.","id":1899}, + {"name":"Surface Portal","type":"Portal","wcid":8368,"cell":"02CA02B8","place":"dungeon","dest":{"cell":"975F0038","place":"outdoor","ns":-25.23,"ew":19.52},"desc":"In Mosswart Maze.","id":1900}, + {"name":"The Floating City","type":"Portal","wcid":8199,"cell":"02CB0117","place":"dungeon","dest":{"cell":"02D101FB","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 02CB).","id":1901}, + {"name":"The Floating City","type":"Portal","wcid":8197,"cell":"02CC010E","place":"dungeon","dest":{"cell":"02D10212","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 02CC).","id":1902}, + {"name":"Golem Sanctum Portal","type":"Portal","wcid":7934,"cell":"02CD0181","place":"dungeon","dest":{"cell":"02E10290","place":"dungeon"},"minLevel":25,"desc":"In a dungeon (landblock 02CD).","id":1903}, + {"name":"The Floating City","type":"Portal","wcid":8198,"cell":"02CD0208","place":"dungeon","dest":{"cell":"02CB011F","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 02CD).","id":1904}, + {"name":"The Floating City","type":"Portal","wcid":8192,"cell":"02CD0280","place":"dungeon","dest":{"cell":"02CF019D","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 02CD).","id":1905}, + {"name":"The Floating City","type":"Portal","wcid":8194,"cell":"02CE0146","place":"dungeon","dest":{"cell":"02D10125","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 02CE).","id":1906}, + {"name":"The Floating City","type":"Portal","wcid":8192,"cell":"02CE0195","place":"dungeon","dest":{"cell":"02CF019D","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 02CE).","id":1907}, + {"name":"The Floating City","type":"Portal","wcid":8192,"cell":"02D00157","place":"dungeon","dest":{"cell":"02CF019D","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 02D0).","id":1908}, + {"name":"Floating Spire","type":"Portal","wcid":8189,"cell":"02D0016A","place":"dungeon","dest":{"cell":"287A0100","place":"building","ns":-3.72,"ew":-69.2},"minLevel":25,"desc":"In a dungeon (landblock 02D0).","id":1909}, + {"name":"The Floating City","type":"Portal","wcid":8193,"cell":"02D1012D","place":"dungeon","dest":{"cell":"02CE0140","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 02D1).","id":1910}, + {"name":"The Floating City","type":"Portal","wcid":8198,"cell":"02D10202","place":"dungeon","dest":{"cell":"02CB011F","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 02D1).","id":1911}, + {"name":"The Floating City","type":"Portal","wcid":8196,"cell":"02D10212","place":"dungeon","dest":{"cell":"02CC010A","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 02D1).","id":1912}, + {"name":"Lightless Tunnels Portal","type":"Portal","wcid":8218,"cell":"02D20102","place":"dungeon","dest":{"cell":"02C60200","place":"dungeon"},"minLevel":1,"maxLevel":25,"desc":"In a dungeon (landblock 02D2).","id":1913}, + {"name":"Xarabydun Town Portal","type":"Portal","wcid":8217,"cell":"02D20116","place":"dungeon","dest":{"cell":"934B023E","place":"underground","ns":-41.85,"ew":16.08},"desc":"In a dungeon (landblock 02D2).","id":1914}, + {"name":"Surface Portal","type":"Portal","wcid":8219,"cell":"02D201D5","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"In a dungeon (landblock 02D2).","id":1915}, + {"name":"Xarabydun Town Portal","type":"Portal","wcid":8217,"cell":"02D30107","place":"dungeon","dest":{"cell":"934B023E","place":"underground","ns":-41.85,"ew":16.08},"desc":"In a dungeon (landblock 02D3).","id":1916}, + {"name":"Surface Portal","type":"Portal","wcid":8219,"cell":"02D30135","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"In a dungeon (landblock 02D3).","id":1917}, + {"name":"Surface","type":"Portal","wcid":28807,"cell":"02D4025F","place":"dungeon","dest":{"cell":"40EE0021","place":"outdoor","ns":88.46,"ew":-50.33},"desc":"In Abhorrent Vault.","id":1918}, + {"name":"Surface","type":"Portal","wcid":28807,"cell":"02D40128","place":"dungeon","dest":{"cell":"40EE0021","place":"outdoor","ns":88.46,"ew":-50.33},"desc":"In Abhorrent Vault.","id":1919}, + {"name":"Surface","type":"Portal","wcid":28797,"cell":"02D5023E","place":"dungeon","dest":{"cell":"21E8000C","place":"outdoor","ns":84.04,"ew":-75.42},"desc":"In Waterfall Cave.","id":1920}, + {"name":"Surface","type":"Portal","wcid":28797,"cell":"02D50104","place":"dungeon","dest":{"cell":"21E8000C","place":"outdoor","ns":84.04,"ew":-75.42},"desc":"In Waterfall Cave.","id":1921}, + {"name":"Surface","type":"Portal","wcid":28787,"cell":"02D6025B","place":"dungeon","dest":{"cell":"27F5003C","place":"outdoor","ns":94.44,"ew":-70.01},"desc":"In Hidden City.","id":1922}, + {"name":"Surface","type":"Portal","wcid":28787,"cell":"02D602D1","place":"dungeon","dest":{"cell":"27F5003C","place":"outdoor","ns":94.44,"ew":-70.01},"desc":"In Hidden City.","id":1923}, + {"name":"Surface Portal","type":"Portal","wcid":7952,"cell":"02D70100","place":"dungeon","dest":{"cell":"4E320007","place":"outdoor","ns":-61.27,"ew":-39.54},"desc":"In a dungeon (landblock 02D7).","id":1924}, + {"name":"Surface Portal","type":"Portal","wcid":7952,"cell":"02D7013E","place":"dungeon","dest":{"cell":"4E320007","place":"outdoor","ns":-61.27,"ew":-39.54},"desc":"In a dungeon (landblock 02D7).","id":1925}, + {"name":"Surface Portal","type":"Portal","wcid":7952,"cell":"02D7024F","place":"dungeon","dest":{"cell":"4E320007","place":"outdoor","ns":-61.27,"ew":-39.54},"desc":"In a dungeon (landblock 02D7).","id":1926}, + {"name":"Surface Portal","type":"Portal","wcid":7944,"cell":"02DA0106","place":"dungeon","dest":{"cell":"C4440028","place":"outdoor","ns":-46.84,"ew":55.28},"desc":"In a dungeon (landblock 02DA).","id":1927}, + {"name":"Surface Portal","type":"Portal","wcid":7944,"cell":"02DA0232","place":"dungeon","dest":{"cell":"C4440028","place":"outdoor","ns":-46.84,"ew":55.28},"desc":"In a dungeon (landblock 02DA).","id":1928}, + {"name":"Surface Portal","type":"Portal","wcid":7944,"cell":"02DA0333","place":"dungeon","dest":{"cell":"C4440028","place":"outdoor","ns":-46.84,"ew":55.28},"desc":"In a dungeon (landblock 02DA).","id":1929}, + {"name":"Surface Portal","type":"Portal","wcid":7944,"cell":"02DB0182","place":"dungeon","dest":{"cell":"C4440028","place":"outdoor","ns":-46.84,"ew":55.28},"desc":"In Fenmalain Vestibule.","id":1930}, + {"name":"Surface Portal","type":"Portal","wcid":7944,"cell":"02DB01FC","place":"dungeon","dest":{"cell":"C4440028","place":"outdoor","ns":-46.84,"ew":55.28},"desc":"In Fenmalain Vestibule.","id":1931}, + {"name":"Surface Portal","type":"Portal","wcid":7944,"cell":"02DB030C","place":"dungeon","dest":{"cell":"C4440028","place":"outdoor","ns":-46.84,"ew":55.28},"desc":"In Fenmalain Vestibule.","id":1932}, + {"name":"Surface Portal","type":"Portal","wcid":7946,"cell":"02DC0100","place":"dungeon","dest":{"cell":"86D5000A","place":"outdoor","ns":68.6,"ew":5.43},"desc":"In Caulnalain Vestibule.","id":1933}, + {"name":"Surface Portal","type":"Portal","wcid":7946,"cell":"02DC035F","place":"dungeon","dest":{"cell":"86D5000A","place":"outdoor","ns":68.6,"ew":5.43},"desc":"In Caulnalain Vestibule.","id":1934}, + {"name":"Surface","type":"Portal","wcid":28794,"cell":"02DD019C","place":"dungeon","dest":{"cell":"33D90039","place":"outdoor","ns":71.73,"ew":-60.41},"desc":"In Penguin Den.","id":1935}, + {"name":"Surface","type":"Portal","wcid":28794,"cell":"02DD010C","place":"dungeon","dest":{"cell":"33D90039","place":"outdoor","ns":71.73,"ew":-60.41},"desc":"In Penguin Den.","id":1936}, + {"name":"Surface","type":"Portal","wcid":28785,"cell":"02DE02BF","place":"dungeon","dest":{"cell":"34F7001F","place":"outdoor","ns":96.33,"ew":-60.02},"desc":"In Ruschk Iceberg.","id":1937}, + {"name":"Surface","type":"Portal","wcid":28785,"cell":"02DE015B","place":"dungeon","dest":{"cell":"34F7001F","place":"outdoor","ns":96.33,"ew":-60.02},"desc":"In Ruschk Iceberg.","id":1938}, + {"name":"Surface Portal","type":"Portal","wcid":7948,"cell":"02DF0139","place":"dungeon","dest":{"cell":"86D5000A","place":"outdoor","ns":68.6,"ew":5.43},"desc":"In a dungeon (landblock 02DF).","id":1939}, + {"name":"Surface Portal","type":"Portal","wcid":7948,"cell":"02DF0143","place":"dungeon","dest":{"cell":"86D5000A","place":"outdoor","ns":68.6,"ew":5.43},"desc":"In a dungeon (landblock 02DF).","id":1940}, + {"name":"Surface Portal","type":"Portal","wcid":7948,"cell":"02DF0157","place":"dungeon","dest":{"cell":"86D5000A","place":"outdoor","ns":68.6,"ew":5.43},"desc":"In a dungeon (landblock 02DF).","id":1941}, + {"name":"Surface Portal","type":"Portal","wcid":7948,"cell":"02DF01A0","place":"dungeon","dest":{"cell":"86D5000A","place":"outdoor","ns":68.6,"ew":5.43},"desc":"In a dungeon (landblock 02DF).","id":1942}, + {"name":"Surface Portal","type":"Portal","wcid":7948,"cell":"02DF025D","place":"dungeon","dest":{"cell":"86D5000A","place":"outdoor","ns":68.6,"ew":5.43},"desc":"In a dungeon (landblock 02DF).","id":1943}, + {"name":"Surface Portal","type":"Portal","wcid":7948,"cell":"02DF0374","place":"dungeon","dest":{"cell":"86D5000A","place":"outdoor","ns":68.6,"ew":5.43},"desc":"In a dungeon (landblock 02DF).","id":1944}, + {"name":"Surface Portal","type":"Portal","wcid":7950,"cell":"02E0046A","place":"dungeon","dest":{"cell":"4E320007","place":"outdoor","ns":-61.27,"ew":-39.54},"desc":"In Shendolain Vestibule.","id":1945}, + {"name":"The Floating City","type":"Portal","wcid":7935,"cell":"02E10295","place":"dungeon","dest":{"cell":"02CD014F","place":"dungeon"},"desc":"In a dungeon (landblock 02E1).","id":1946}, + {"name":"Surface Portal","type":"Portal","wcid":7892,"cell":"02E201A3","place":"dungeon","dest":{"cell":"84690011","place":"outdoor","ns":-17.93,"ew":3.86},"desc":"In Arena.","id":1947}, + {"name":"Judging Station","type":"Portal","wcid":7893,"cell":"02E201A6","place":"dungeon","dest":{"cell":"02E3015A","place":"dungeon","name":"Arena"},"desc":"In Arena.","id":1948}, + {"name":"Surface Portal","type":"Portal","wcid":7892,"cell":"02E301A3","place":"dungeon","dest":{"cell":"84690011","place":"outdoor","ns":-17.93,"ew":3.86},"desc":"In Arena.","id":1949}, + {"name":"Judging Station","type":"Portal","wcid":7893,"cell":"02E301A6","place":"dungeon","dest":{"cell":"02E3015A","place":"dungeon","name":"Arena"},"desc":"In Arena.","id":1950}, + {"name":"Surface","type":"Portal","wcid":29097,"cell":"02E40197","place":"dungeon","dest":{"cell":"35DB001C","place":"outdoor","ns":73.64,"ew":-59.21},"desc":"In a dungeon (landblock 02E4).","id":1951}, + {"name":"Surface","type":"Portal","wcid":29097,"cell":"02E40146","place":"dungeon","dest":{"cell":"35DB001C","place":"outdoor","ns":73.64,"ew":-59.21},"desc":"In a dungeon (landblock 02E4).","id":1952}, + {"name":"Surface","type":"Portal","wcid":29097,"cell":"02E40116","place":"dungeon","dest":{"cell":"35DB001C","place":"outdoor","ns":73.64,"ew":-59.21},"desc":"In a dungeon (landblock 02E4).","id":1953}, + {"name":"Surface Portal","type":"Portal","wcid":7617,"cell":"02E50100","place":"dungeon","dest":{"cell":"9D530004","place":"outdoor","ns":-35.21,"ew":23.69},"desc":"In Krau Li's Labyrinth.","id":1954}, + {"name":"Surface Portal","type":"Portal","wcid":7617,"cell":"02E501C1","place":"dungeon","dest":{"cell":"9D530004","place":"outdoor","ns":-35.21,"ew":23.69},"desc":"In Krau Li's Labyrinth.","id":1955}, + {"name":"Surface Portal","type":"Portal","wcid":7617,"cell":"02E50259","place":"dungeon","dest":{"cell":"9D530004","place":"outdoor","ns":-35.21,"ew":23.69},"desc":"In Krau Li's Labyrinth.","id":1956}, + {"name":"Surface Portal","type":"Portal","wcid":7617,"cell":"02E5029B","place":"dungeon","dest":{"cell":"9D530004","place":"outdoor","ns":-35.21,"ew":23.69},"desc":"In Krau Li's Labyrinth.","id":1957}, + {"name":"Surface Portal","type":"Portal","wcid":7617,"cell":"02E50374","place":"dungeon","dest":{"cell":"9D530004","place":"outdoor","ns":-35.21,"ew":23.69},"desc":"In Krau Li's Labyrinth.","id":1958}, + {"name":"Surface Portal","type":"Portal","wcid":7615,"cell":"02E6025A","place":"dungeon","dest":{"cell":"A8950032","place":"outdoor","ns":17.38,"ew":33.07},"desc":"In Catacombs of the Forgotten.","id":1959}, + {"name":"Surface Portal","type":"Portal","wcid":7615,"cell":"02E602B0","place":"dungeon","dest":{"cell":"A8950032","place":"outdoor","ns":17.38,"ew":33.07},"desc":"In Catacombs of the Forgotten.","id":1960}, + {"name":"Surface Portal","type":"Portal","wcid":7613,"cell":"02E70282","place":"dungeon","dest":{"cell":"CF1F0032","place":"outdoor","ns":-76.97,"ew":64.35},"desc":"In Lugian Excavations.","id":1961}, + {"name":"Surface Portal","type":"Portal","wcid":7613,"cell":"02E70286","place":"dungeon","dest":{"cell":"CF1F0032","place":"outdoor","ns":-76.97,"ew":64.35},"desc":"In Lugian Excavations.","id":1962}, + {"name":"Surface Portal","type":"Portal","wcid":7611,"cell":"02E80172","place":"dungeon","dest":{"cell":"C42E003F","place":"outdoor","ns":-64.5,"ew":55.59},"desc":"In Lugian Quarry.","id":1963}, + {"name":"Surface Portal","type":"Portal","wcid":7611,"cell":"02E80238","place":"dungeon","dest":{"cell":"C42E003F","place":"outdoor","ns":-64.5,"ew":55.59},"desc":"In Lugian Quarry.","id":1964}, + {"name":"Surface Portal","type":"Portal","wcid":7609,"cell":"02E9010B","place":"dungeon","dest":{"cell":"B0230012","place":"outdoor","ns":-73.75,"ew":39.07},"desc":"In Lugian Mines.","id":1965}, + {"name":"Surface Portal","type":"Portal","wcid":7609,"cell":"02E901FF","place":"dungeon","dest":{"cell":"B0230012","place":"outdoor","ns":-73.75,"ew":39.07},"desc":"In Lugian Mines.","id":1966}, + {"name":"Surface","type":"Portal","wcid":29236,"cell":"02EA017D","place":"dungeon","dest":{"cell":"132C000F","place":"outdoor","ns":-66.09,"ew":-86.57},"desc":"In Ishaq's Cellar.","id":1967}, + {"name":"Surface","type":"Portal","wcid":28712,"cell":"02EB022C","place":"dungeon","dest":{"cell":"31D6000C","place":"outdoor","ns":69.64,"ew":-62.61},"desc":"In Viamontian Torture Chamber.","id":1968}, + {"name":"Surface","type":"Portal","wcid":28712,"cell":"02EB0100","place":"dungeon","dest":{"cell":"31D6000C","place":"outdoor","ns":69.64,"ew":-62.61},"desc":"In Viamontian Torture Chamber.","id":1969}, + {"name":"Western Aerlinthe Island","type":"Portal","wcid":28064,"cell":"02EC02B9","place":"dungeon","dest":{"cell":"B8E80103","place":"building","ns":84.2,"ew":45.98},"desc":"In Coral Tunnels.","id":1970}, + {"name":"Eastern Aerlinthe Island","type":"Portal","wcid":28062,"cell":"02EC031B","place":"dungeon","dest":{"cell":"BAE80106","place":"underground","ns":84.1,"ew":46.92},"desc":"In Coral Tunnels.","id":1971}, + {"name":"Surface Portal","type":"Portal","wcid":7446,"cell":"02ED0112","place":"dungeon","dest":{"cell":"B6EB003C","place":"outdoor","ns":86.39,"ew":44.4},"desc":"In a dungeon (landblock 02ED).","id":1972}, + {"name":"Aerlinthe Lower Reservoir Portal","type":"Portal","wcid":7508,"cell":"02EE0101","place":"dungeon","dest":{"cell":"02ED01B5","place":"dungeon"},"minLevel":40,"desc":"In Aerlinthe Reservoir.","id":1973}, + {"name":"Surface Portal","type":"Portal","wcid":7290,"cell":"02EE047B","place":"dungeon","dest":{"cell":"B6EA0027","place":"outdoor","ns":85.92,"ew":44.06},"desc":"In Aerlinthe Reservoir.","id":1974}, + {"name":"Surface Portal","type":"Portal","wcid":7342,"cell":"02EF0108","place":"dungeon","dest":{"cell":"72110007","place":"outdoor","ns":-87.71,"ew":-10.7},"desc":"In a dungeon (landblock 02EF).","id":1975}, + {"name":"Surface Portal","type":"Portal","wcid":7342,"cell":"02EF01A9","place":"dungeon","dest":{"cell":"72110007","place":"outdoor","ns":-87.71,"ew":-10.7},"desc":"In a dungeon (landblock 02EF).","id":1976}, + {"name":"Surface Portal","type":"Portal","wcid":7342,"cell":"02EF0247","place":"dungeon","dest":{"cell":"72110007","place":"outdoor","ns":-87.71,"ew":-10.7},"desc":"In a dungeon (landblock 02EF).","id":1977}, + {"name":"Surface Portal","type":"Portal","wcid":7342,"cell":"02EF025D","place":"dungeon","dest":{"cell":"72110007","place":"outdoor","ns":-87.71,"ew":-10.7},"desc":"In a dungeon (landblock 02EF).","id":1978}, + {"name":"Surface Portal","type":"Portal","wcid":7342,"cell":"02EF0271","place":"dungeon","dest":{"cell":"72110007","place":"outdoor","ns":-87.71,"ew":-10.7},"desc":"In a dungeon (landblock 02EF).","id":1979}, + {"name":"Surface Portal","type":"Portal","wcid":7342,"cell":"02EF0287","place":"dungeon","dest":{"cell":"72110007","place":"outdoor","ns":-87.71,"ew":-10.7},"desc":"In a dungeon (landblock 02EF).","id":1980}, + {"name":"Surface Portal","type":"Portal","wcid":7342,"cell":"02EF02B3","place":"dungeon","dest":{"cell":"72110007","place":"outdoor","ns":-87.71,"ew":-10.7},"desc":"In a dungeon (landblock 02EF).","id":1981}, + {"name":"Surface","type":"Portal","wcid":7318,"cell":"02F0015F","place":"dungeon","dest":{"cell":"D3380005","place":"outdoor","ns":-56.69,"ew":66.87},"desc":"In Hills Citadel.","id":1982}, + {"name":"Surface","type":"Portal","wcid":7320,"cell":"02F1015F","place":"dungeon","dest":{"cell":"9D270036","place":"outdoor","ns":-70.17,"ew":24.3},"desc":"In Ridge Citadel.","id":1983}, + {"name":"Surface","type":"Portal","wcid":7322,"cell":"02F2015F","place":"dungeon","dest":{"cell":"CD2A0024","place":"outdoor","ns":-68.03,"ew":62.48},"desc":"In Wilderness Citadel.","id":1984}, + {"name":"Surface Portal","type":"Portal","wcid":7294,"cell":"02F30100","place":"dungeon","dest":{"cell":"7E790038","place":"outdoor","ns":-4.42,"ew":-0.53},"desc":"In Halls of Metos.","id":1985}, + {"name":"Surface Portal","type":"Portal","wcid":7294,"cell":"02F30161","place":"dungeon","dest":{"cell":"7E790038","place":"outdoor","ns":-4.42,"ew":-0.53},"desc":"In Halls of Metos.","id":1986}, + {"name":"Surface Portal","type":"Portal","wcid":7294,"cell":"02F302B3","place":"dungeon","dest":{"cell":"7E790038","place":"outdoor","ns":-4.42,"ew":-0.53},"desc":"In Halls of Metos.","id":1987}, + {"name":"Surface Portal","type":"Portal","wcid":7292,"cell":"02F40100","place":"dungeon","dest":{"cell":"0F390034","place":"outdoor","ns":-55.98,"ew":-89.27},"desc":"In Halls of Metos.","id":1988}, + {"name":"Surface Portal","type":"Portal","wcid":7292,"cell":"02F40161","place":"dungeon","dest":{"cell":"0F390034","place":"outdoor","ns":-55.98,"ew":-89.27},"desc":"In Halls of Metos.","id":1989}, + {"name":"Surface Portal","type":"Portal","wcid":7292,"cell":"02F402B3","place":"dungeon","dest":{"cell":"0F390034","place":"outdoor","ns":-55.98,"ew":-89.27},"desc":"In Halls of Metos.","id":1990}, + {"name":"Surface Portal","type":"Portal","wcid":7296,"cell":"02F50100","place":"dungeon","dest":{"cell":"4532000E","place":"outdoor","ns":-61.42,"ew":-46.63},"desc":"In Halls of Metos.","id":1991}, + {"name":"Surface Portal","type":"Portal","wcid":7296,"cell":"02F50161","place":"dungeon","dest":{"cell":"4532000E","place":"outdoor","ns":-61.42,"ew":-46.63},"desc":"In Halls of Metos.","id":1992}, + {"name":"Surface Portal","type":"Portal","wcid":7296,"cell":"02F502B3","place":"dungeon","dest":{"cell":"4532000E","place":"outdoor","ns":-61.42,"ew":-46.63},"desc":"In Halls of Metos.","id":1993}, + {"name":"Surface Portal","type":"Portal","wcid":7288,"cell":"02F60100","place":"dungeon","dest":{"cell":"1B55001D","place":"outdoor","ns":-33.46,"ew":-79.98},"desc":"In Sclavus Cathedral.","id":1994}, + {"name":"Surface Portal","type":"Portal","wcid":7288,"cell":"02F6041B","place":"dungeon","dest":{"cell":"1B55001D","place":"outdoor","ns":-33.46,"ew":-79.98},"desc":"In Sclavus Cathedral.","id":1995}, + {"name":"Surface Portal","type":"Portal","wcid":7286,"cell":"02F70100","place":"dungeon","dest":{"cell":"0F690019","place":"outdoor","ns":-17.89,"ew":-89.55},"desc":"In Sclavus Cathedral.","id":1996}, + {"name":"Surface Portal","type":"Portal","wcid":7286,"cell":"02F7041B","place":"dungeon","dest":{"cell":"0F690019","place":"outdoor","ns":-17.89,"ew":-89.55},"desc":"In Sclavus Cathedral.","id":1997}, + {"name":"Surface Portal","type":"Portal","wcid":7284,"cell":"02F80100","place":"dungeon","dest":{"cell":"3D4A0024","place":"outdoor","ns":-42.44,"ew":-52.74},"desc":"In Burun Cathedral.","id":1998}, + {"name":"Surface Portal","type":"Portal","wcid":7284,"cell":"02F8041B","place":"dungeon","dest":{"cell":"3D4A0024","place":"outdoor","ns":-42.44,"ew":-52.74},"desc":"In Burun Cathedral.","id":1999}, + {"name":"Surface Portal","type":"Portal","wcid":7259,"cell":"02FB0101","place":"dungeon","dest":{"cell":"B5C50033","place":"outdoor","ns":55.91,"ew":43.48},"desc":"In Olthoi Horde Nest.","id":2000}, + {"name":"Surface Portal","type":"Portal","wcid":7259,"cell":"02FB03DC","place":"dungeon","dest":{"cell":"B5C50033","place":"outdoor","ns":55.91,"ew":43.48},"desc":"In Olthoi Horde Nest.","id":2001}, + {"name":"Deeper Catacombs","type":"Portal","wcid":24232,"cell":"02FB010F","place":"dungeon","dest":{"cell":"5750028A","place":"dungeon"},"desc":"In Olthoi Horde Nest.","id":2002}, + {"name":"Surface Portal","type":"Portal","wcid":7257,"cell":"02FC0101","place":"dungeon","dest":{"cell":"6FBC001F","place":"outdoor","ns":49.12,"ew":-12.72},"desc":"In Olthoi Horde Nest.","id":2003}, + {"name":"Surface Portal","type":"Portal","wcid":7257,"cell":"02FC03CE","place":"dungeon","dest":{"cell":"6FBC001F","place":"outdoor","ns":49.12,"ew":-12.72},"desc":"In Olthoi Horde Nest.","id":2004}, + {"name":"Deeper Catacombs","type":"Portal","wcid":24231,"cell":"02FC010F","place":"dungeon","dest":{"cell":"574F0290","place":"dungeon"},"desc":"In Olthoi Horde Nest.","id":2005}, + {"name":"Surface Portal","type":"Portal","wcid":7255,"cell":"02FD0101","place":"dungeon","dest":{"cell":"C1CF0027","place":"outdoor","ns":64.33,"ew":52.97},"desc":"In Olthoi Horde Nest.","id":2006}, + {"name":"Surface Portal","type":"Portal","wcid":7255,"cell":"02FD03CE","place":"dungeon","dest":{"cell":"C1CF0027","place":"outdoor","ns":64.33,"ew":52.97},"desc":"In Olthoi Horde Nest.","id":2007}, + {"name":"Deeper Catacombs","type":"Portal","wcid":24229,"cell":"02FD010F","place":"dungeon","dest":{"cell":"574E0285","place":"dungeon"},"desc":"In Olthoi Horde Nest.","id":2008}, + {"name":"Surface","type":"Portal","wcid":28779,"cell":"02FE0441","place":"dungeon","dest":{"cell":"38F0003F","place":"outdoor","ns":90.67,"ew":-56.42},"desc":"In Frozen Library.","id":2009}, + {"name":"Surface","type":"Portal","wcid":28779,"cell":"02FE0104","place":"dungeon","dest":{"cell":"38F0003F","place":"outdoor","ns":90.67,"ew":-56.42},"desc":"In Frozen Library.","id":2010}, + {"name":"Surface","type":"Portal","wcid":30965,"cell":"0302036F","place":"dungeon","dest":{"cell":"43F70015","place":"outdoor","ns":96.1,"ew":-48.1},"desc":"In a dungeon (landblock 0302).","id":2011}, + {"name":"Surface","type":"Portal","wcid":30965,"cell":"03020100","place":"dungeon","dest":{"cell":"43F70015","place":"outdoor","ns":96.1,"ew":-48.1},"desc":"In a dungeon (landblock 0302).","id":2012}, + {"name":"Outer Courtyard","type":"Portal","wcid":12770,"cell":"03630299","place":"dungeon","dest":{"cell":"870302C3","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 0363).","id":2013}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"036302E6","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0363).","id":2014}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"036302D7","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0363).","id":2015}, + {"name":"Outer Courtyard Portal","type":"Portal","wcid":12769,"cell":"03640299","place":"dungeon","dest":{"cell":"036402EF","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 0364).","id":2016}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"036402D7","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0364).","id":2017}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"036402E6","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0364).","id":2018}, + {"name":"Outer Courtyard","type":"Portal","wcid":12771,"cell":"03650299","place":"dungeon","dest":{"cell":"800402C3","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 0365).","id":2019}, + {"name":"Destroyed Portal to Shoushi","type":"Portal","wcid":1027,"cell":"036502D7","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0365).","id":2020}, + {"name":"Destroyed Portal to Shoushi","type":"Portal","wcid":1027,"cell":"036502E6","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0365).","id":2021}, + {"name":"Outer Courtyard Portal","type":"Portal","wcid":12768,"cell":"03660299","place":"dungeon","dest":{"cell":"036602EF","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 0366).","id":2022}, + {"name":"Destroyed Portal to Shoushi","type":"Portal","wcid":1027,"cell":"036602D7","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0366).","id":2023}, + {"name":"Destroyed Portal to Shoushi","type":"Portal","wcid":1027,"cell":"036602E6","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0366).","id":2024}, + {"name":"Outer Courtyard","type":"Portal","wcid":12772,"cell":"03670299","place":"dungeon","dest":{"cell":"8C0402C3","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 0367).","id":2025}, + {"name":"Destroyed Portal to Yaraq","type":"Portal","wcid":1030,"cell":"036702D7","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0367).","id":2026}, + {"name":"Destroyed Portal to Yaraq","type":"Portal","wcid":1030,"cell":"036702E6","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0367).","id":2027}, + {"name":"Outer Courtyard Portal","type":"Portal","wcid":12773,"cell":"03680299","place":"dungeon","dest":{"cell":"036802EF","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 0368).","id":2028}, + {"name":"Destroyed Portal to Yaraq","type":"Portal","wcid":1030,"cell":"036802D7","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0368).","id":2029}, + {"name":"Destroyed Portal to Yaraq","type":"Portal","wcid":1030,"cell":"036802E6","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 0368).","id":2030}, + {"name":"Surface","type":"Portal","wcid":29100,"cell":"039B0174","place":"dungeon","dest":{"cell":"2DDA001E","place":"outdoor","ns":73.0,"ew":-65.6},"desc":"In Steaming Hovel.","id":2031}, + {"name":"Surface","type":"Portal","wcid":29100,"cell":"039B015E","place":"dungeon","dest":{"cell":"2DDA001E","place":"outdoor","ns":73.0,"ew":-65.6},"desc":"In Steaming Hovel.","id":2032}, + {"name":"Surface","type":"Portal","wcid":29100,"cell":"039B0109","place":"dungeon","dest":{"cell":"2DDA001E","place":"outdoor","ns":73.0,"ew":-65.6},"desc":"In Steaming Hovel.","id":2033}, + {"name":"Arcanum Furniture Shop","type":"Portal","wcid":12696,"cell":"039C0193","place":"dungeon","dest":{"cell":"039C01F4","place":"dungeon","name":"Hollow Lair near Lytelthorpe"},"quest":true,"desc":"In Hollow Lair near Lytelthorpe.","id":2034}, + {"name":"Surface Portal","type":"Portal","wcid":12697,"cell":"039C01F6","place":"dungeon","dest":{"cell":"BE7C0036","place":"outdoor","ns":-2.29,"ew":50.63},"desc":"In Hollow Lair near Lytelthorpe.","id":2035}, + {"name":"Exit Portal","type":"Portal","wcid":12693,"cell":"039C0200","place":"dungeon","dest":{"cell":"BE7C0036","place":"outdoor","ns":-2.29,"ew":50.63},"desc":"In Hollow Lair near Lytelthorpe.","id":2036}, + {"name":"Surface","type":"Portal","wcid":28803,"cell":"039D02A2","place":"dungeon","dest":{"cell":"42F30014","place":"outdoor","ns":92.79,"ew":-48.94},"desc":"In Ravenous Vault.","id":2037}, + {"name":"Surface","type":"Portal","wcid":28803,"cell":"039D0127","place":"dungeon","dest":{"cell":"42F30014","place":"outdoor","ns":92.79,"ew":-48.94},"desc":"In Ravenous Vault.","id":2038}, + {"name":"Return Portal","type":"Portal","wcid":12293,"cell":"039E0127","place":"dungeon","dest":{"cell":"7F900025","place":"outdoor","ns":13.72,"ew":0.08},"desc":"In a dungeon (landblock 039E).","id":2039}, + {"name":"Return Portal","type":"Portal","wcid":12293,"cell":"039E02FB","place":"dungeon","dest":{"cell":"7F900025","place":"outdoor","ns":13.72,"ew":0.08},"desc":"In a dungeon (landblock 039E).","id":2040}, + {"name":"Surface Portal","type":"Portal","wcid":12295,"cell":"039F0102","place":"dungeon","dest":{"cell":"2E39001D","place":"outdoor","ns":-55.85,"ew":-64.77},"desc":"In Singular Obsidian Repository.","id":2041}, + {"name":"Surface Portal","type":"Portal","wcid":12295,"cell":"039F02E2","place":"dungeon","dest":{"cell":"2E39001D","place":"outdoor","ns":-55.85,"ew":-64.77},"desc":"In Singular Obsidian Repository.","id":2042}, + {"name":"Surface Portal","type":"Portal","wcid":12291,"cell":"03A00188","place":"dungeon","dest":{"cell":"BF1E003F","place":"outdoor","ns":-77.26,"ew":51.57},"desc":"In Singular Chorizite Repository.","id":2043}, + {"name":"Surface Portal","type":"Portal","wcid":12291,"cell":"03A00280","place":"dungeon","dest":{"cell":"BF1E003F","place":"outdoor","ns":-77.26,"ew":51.57},"desc":"In Singular Chorizite Repository.","id":2044}, + {"name":"Surface Portal","type":"Portal","wcid":12297,"cell":"03A1012C","place":"dungeon","dest":{"cell":"8A7A0022","place":"outdoor","ns":-4.23,"ew":8.88},"desc":"In Singular Pyreal Repository.","id":2045}, + {"name":"Surface Portal","type":"Portal","wcid":12297,"cell":"03A102B8","place":"dungeon","dest":{"cell":"8A7A0022","place":"outdoor","ns":-4.23,"ew":8.88},"desc":"In Singular Pyreal Repository.","id":2046}, + {"name":"Surface","type":"Portal","wcid":12153,"cell":"03A20100","place":"dungeon","dest":{"cell":"9E3E002A","place":"outdoor","ns":-52.21,"ew":25.03},"desc":"In Southern Infiltrator Keep.","id":2047}, + {"name":"Surface","type":"Portal","wcid":12153,"cell":"03A20261","place":"dungeon","dest":{"cell":"9E3E002A","place":"outdoor","ns":-52.21,"ew":25.03},"desc":"In Southern Infiltrator Keep.","id":2048}, + {"name":"Surface","type":"Portal","wcid":12151,"cell":"03A30100","place":"dungeon","dest":{"cell":"85920026","place":"outdoor","ns":15.36,"ew":4.91},"desc":"In Northern Infiltrator Keep.","id":2049}, + {"name":"Surface","type":"Portal","wcid":12151,"cell":"03A30204","place":"dungeon","dest":{"cell":"85920026","place":"outdoor","ns":15.36,"ew":4.91},"desc":"In Northern Infiltrator Keep.","id":2050}, + {"name":"Surface","type":"Portal","wcid":12149,"cell":"03A40109","place":"dungeon","dest":{"cell":"9572001E","place":"outdoor","ns":-10.16,"ew":17.6},"desc":"In The Asteliary.","id":2051}, + {"name":"Surface","type":"Portal","wcid":12149,"cell":"03A40129","place":"dungeon","dest":{"cell":"9572001E","place":"outdoor","ns":-10.16,"ew":17.6},"desc":"In The Asteliary.","id":2052}, + {"name":"Surface","type":"Portal","wcid":28789,"cell":"03A502E1","place":"dungeon","dest":{"cell":"49F10019","place":"outdoor","ns":90.92,"ew":-43.19},"desc":"In Undead Temple.","id":2053}, + {"name":"Surface","type":"Portal","wcid":28789,"cell":"03A50108","place":"dungeon","dest":{"cell":"49F10019","place":"outdoor","ns":90.92,"ew":-43.19},"desc":"In Undead Temple.","id":2054}, + {"name":"Royal Hive Portal","type":"Portal","wcid":11208,"cell":"03A60100","place":"dungeon","dest":{"cell":"028802AA","place":"dungeon"},"minLevel":70,"quest":true,"desc":"In North Fork Dam Hive.","id":2055}, + {"name":"Surface Portal","type":"Portal","wcid":11216,"cell":"03A602C8","place":"dungeon","dest":{"cell":"20BF0116","place":"building","ns":51.1,"ew":-76.01},"minLevel":30,"desc":"In North Fork Dam Hive.","id":2056}, + {"name":"Surface Portal","type":"Portal","wcid":11216,"cell":"03A602CD","place":"dungeon","dest":{"cell":"20BF0116","place":"building","ns":51.1,"ew":-76.01},"minLevel":30,"desc":"In North Fork Dam Hive.","id":2057}, + {"name":"Royal Hive Portal","type":"Portal","wcid":11207,"cell":"03A7010E","place":"dungeon","dest":{"cell":"0288026C","place":"dungeon"},"minLevel":70,"quest":true,"desc":"In Mount Elyrii Hive.","id":2058}, + {"name":"Ice Chasm Portal","type":"Portal","wcid":11969,"cell":"03A70181","place":"dungeon","dest":{"cell":"03A702F6","place":"dungeon","name":"Mount Elyrii Hive"},"minLevel":70,"desc":"In Mount Elyrii Hive.","id":2059}, + {"name":"Surface Portal","type":"Portal","wcid":11214,"cell":"03A70244","place":"dungeon","dest":{"cell":"19BC0011","place":"outdoor","ns":48.5,"ew":-81.7},"minLevel":30,"desc":"In Mount Elyrii Hive.","id":2060}, + {"name":"Surface","type":"Portal","wcid":28834,"cell":"03FE010B","place":"dungeon","dest":{"cell":"DD540100","place":"dungeon"},"desc":"In a dungeon (landblock 03FE).","id":2061}, + {"name":"Surface","type":"Portal","wcid":28834,"cell":"03FE0229","place":"dungeon","dest":{"cell":"DD540100","place":"dungeon"},"desc":"In a dungeon (landblock 03FE).","id":2062}, + {"name":"Tunnel of Love","type":"Portal","wcid":31514,"cell":"0609002C","place":"outdoor","ns":-94.41,"ew":-96.56,"dest":{"cell":"00320104","place":"dungeon","name":"Tunnel of Love"},"minLevel":120,"quest":true,"desc":"You must appease the Golem Xireri before you may use this portal.","id":2063}, + {"name":"Obsidian Rim Portal","type":"Portal","wcid":10795,"cell":"09040000","place":"outdoor","ns":-98.01,"ew":-94.7,"dest":{"cell":"2E43000C","place":"outdoor","ns":-48.02,"ew":-65.01},"id":2064}, + {"name":"Firey Refuge","type":"Portal","wcid":45724,"cell":"0908002B","place":"outdoor","ns":-95.33,"ew":-94.17,"dest":{"cell":"576901A9","place":"dungeon","name":"Firey Refuge"},"minLevel":150,"quest":true,"id":2065}, + {"name":"Artifex Collegium","type":"Portal","wcid":36217,"cell":"0A0C0015","place":"outdoor","ns":-91.89,"ew":-93.7,"dest":{"cell":"00ED0350","place":"dungeon","name":"Artifex Collegium"},"id":2066}, + {"name":"Repository","type":"Portal","wcid":32584,"cell":"0A0F0027","place":"outdoor","ns":-89.32,"ew":-93.48,"dest":{"cell":"0047039C","place":"dungeon","name":"Repository"},"minLevel":125,"desc":"Shadow Stone Repository","id":2067}, + {"name":"War Room","type":"Portal","wcid":30660,"cell":"0B700000","place":"outdoor","ns":-11.9,"ew":-92.77,"dest":{"cell":"0010035E","place":"dungeon","name":"War Room"},"minLevel":80,"id":2068}, + {"name":"Venemous Nidus","type":"Portal","wcid":14888,"cell":"0C6F0000","place":"outdoor","ns":-13.14,"ew":-91.78,"dest":{"cell":"536E027C","place":"dungeon","name":"Venemous Nidus"},"minLevel":40,"id":2069}, + {"name":"Caul Asylum","type":"Portal","wcid":22927,"cell":"0D080000","place":"outdoor","ns":-94.8,"ew":-91.03,"dest":{"cell":"6045026F","place":"dungeon","name":"Caul Asylum"},"minLevel":90,"id":2070}, + {"name":"Gatekeepers","type":"Portal","wcid":32125,"cell":"0E340001","place":"outdoor","ns":-60.3,"ew":-90.69,"dest":{"cell":"79110040","place":"outdoor","ns":-87.62,"ew":-4.42},"minLevel":130,"quest":true,"desc":"You must obtain the blessing of the Gatekeepers before using this portal.","id":2071}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"0EBA0023","place":"outdoor","ns":47.07,"ew":-90.26,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2072}, + {"name":"Stinging Corner","type":"Portal","wcid":52223,"cell":"0F080013","place":"outdoor","ns":-95.3,"ew":-89.73,"dest":{"cell":"586503B9","place":"dungeon","name":"Stinging Corner"},"minLevel":180,"id":2073}, + {"name":"Blighted Grimy Moarsman Tunnels","type":"Portal","wcid":38152,"cell":"0F330013","place":"outdoor","ns":-60.9,"ew":-89.66,"dest":{"cell":"00C5037C","place":"dungeon","name":"Blighted Grimy Moarsman Tunnels"},"minLevel":95,"id":2074}, + {"name":"Blightfinger's Warrens","type":"Portal","wcid":87478,"cell":"0F380150","place":"underground","ns":-56.7,"ew":-88.71,"dest":{"cell":"00D90289","place":"dungeon"},"minLevel":70,"id":2075}, + {"name":"Halls of Metos","type":"Portal","wcid":7291,"cell":"0F390000","place":"outdoor","ns":-55.94,"ew":-89.22,"dest":{"cell":"02F40297","place":"dungeon","name":"Halls of Metos"},"minLevel":15,"id":2076}, + {"name":"Sclavus Cathedral","type":"Portal","wcid":7285,"cell":"0F690000","place":"outdoor","ns":-17.9,"ew":-89.44,"dest":{"cell":"02F703FA","place":"dungeon","name":"Sclavus Cathedral"},"id":2077}, + {"name":"Creepy Canyons","type":"Portal","wcid":31315,"cell":"0F850022","place":"outdoor","ns":4.59,"ew":-89.47,"dest":{"cell":"00310338","place":"dungeon","name":"Creepy Canyons"},"minLevel":100,"id":2078}, + {"name":"Destroyed Baishi Portal","type":"Portal","wcid":4037,"cell":"10350040","place":"outdoor","ns":-58.81,"ew":-88.41,"dest":{"cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2079}, + {"name":"Holtburg Casino VIP Portal","type":"Portal","wcid":38998,"cell":"10350027","place":"outdoor","ns":-58.92,"ew":-88.71,"dest":{"cell":"A9B2001D","place":"outdoor","ns":40.88,"ew":33.6},"quest":true,"id":2080}, + {"name":"Shoushi Casino VIP Portal","type":"Portal","wcid":39002,"cell":"10350027","place":"outdoor","ns":-58.9,"ew":-88.71,"dest":{"cell":"DB54001E","place":"outdoor","ns":-34.2,"ew":73.6},"quest":true,"id":2081}, + {"name":"Yaraq Casino VIP Portal","type":"Portal","wcid":39000,"cell":"10350027","place":"outdoor","ns":-58.88,"ew":-88.71,"dest":{"cell":"7E64001D","place":"outdoor","ns":-21.5,"ew":-0.8},"quest":true,"id":2082}, + {"name":"Lonely Fortress","type":"Portal","wcid":36727,"cell":"10380100","place":"building","ns":-56.7,"ew":-88.42,"dest":{"cell":"00A50108","place":"dungeon","name":"Lonely Fortress"},"minLevel":80,"quest":true,"desc":"This dungeon is quest restricted. The Prodigal Hunter Nomea ibn Makar in Qalaba'r would know more.","id":2083}, + {"name":"Mistress Gabille's Dig","type":"Portal","wcid":32237,"cell":"108A0011","place":"outdoor","ns":8.49,"ew":-88.91,"dest":{"cell":"00420292","place":"dungeon","name":"Mistress Gabille's Dig"},"minLevel":80,"maxLevel":99,"quest":true,"desc":"This dungeon is quest-restricted. Speak with Qath al-Haddash in Qalaba'r to learn more.","id":2084}, + {"name":"Destroyed Portal to Bluespire","type":"Portal","wcid":11953,"cell":"10BA0000","place":"outdoor","ns":47.36,"ew":-88.88,"dest":{"cell":"21B00017","place":"outdoor","ns":39.54,"ew":-75.35},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2085}, + {"name":"Hagra's Holdfast","type":"Portal","wcid":31710,"cell":"10BB0100","place":"dungeon","dest":{"cell":"003901E0","place":"dungeon"},"minLevel":35,"quest":true,"desc":"This dungeon is quest restricted. The Hunter Kassoka in Ahurenga might know something about it. In a dungeon (landblock 10BB).","id":2086}, + {"name":"Shade Iron Mine","type":"Portal","wcid":32685,"cell":"112E0101","place":"building","ns":-65.06,"ew":-87.6,"dest":{"cell":"005303B0","place":"dungeon","name":"Shade Iron Mine"},"minLevel":80,"quest":true,"id":2087}, + {"name":"Destroyed Uziz Portal","type":"Portal","wcid":4036,"cell":"11330000","place":"outdoor","ns":-60.57,"ew":-88.09,"dest":{"cell":"A260003C","place":"outdoor","ns":-24.78,"ew":28.41},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2088}, + {"name":"Colossus Foundry Portal","type":"Portal","wcid":19715,"cell":"11340149","place":"building","ns":-59.99,"ew":-87.92,"dest":{"cell":"545701C5","place":"dungeon","name":"Colossus Foundry"},"id":2089}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"11340026","place":"outdoor","ns":-59.79,"ew":-87.91,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2090}, + {"name":"Ancient Temple","type":"Portal","wcid":25396,"cell":"11560100","place":"building","ns":-32.91,"ew":-88.19,"dest":{"cell":"594D03E2","place":"dungeon","name":"Ancient Temple"},"minLevel":80,"id":2091}, + {"name":"Whispering Blade Chapterhouse","type":"Portal","wcid":32993,"cell":"1234001D","place":"outdoor","ns":-59.92,"ew":-87.22,"dest":{"cell":"00810128","place":"dungeon","name":"Whispering Blade Chapterhouse"},"quest":true,"id":2092}, + {"name":"Ancient Caves","type":"Portal","wcid":33985,"cell":"12450100","place":"dungeon","dest":{"cell":"00D10E92","place":"dungeon"},"minLevel":40,"desc":"In a dungeon (landblock 1245).","id":2093}, + {"name":"Obsidian Rim Portal","type":"Portal","wcid":7210,"cell":"12860000","place":"outdoor","ns":5.5,"ew":-87.52,"dest":{"cell":"2E43000C","place":"outdoor","ns":-48.02,"ew":-65.01},"minLevel":35,"id":2094}, + {"name":"Ishaq's Cellar","type":"Portal","wcid":29237,"cell":"132C0000","place":"outdoor","ns":-66.12,"ew":-86.57,"dest":{"cell":"02EA017D","place":"dungeon","name":"Ishaq's Cellar"},"minLevel":80,"id":2095}, + {"name":"Black Spawn Den","type":"Portal","wcid":7244,"cell":"13380000","place":"outdoor","ns":-56.69,"ew":-86.02,"dest":{"cell":"01040375","place":"dungeon","name":"Black Spawn Den"},"minLevel":20,"id":2096}, + {"name":"Blighted Rank Moarsman Tunnels","type":"Portal","wcid":38154,"cell":"13B20013","place":"outdoor","ns":40.7,"ew":-86.46,"dest":{"cell":"00C1037C","place":"dungeon","name":"Blighted Rank Moarsman Tunnels"},"minLevel":15,"id":2097}, + {"name":"Mount Lethe Magma Tubes Portal","type":"Portal","wcid":5526,"cell":"14550100","place":"building","ns":-33.89,"ew":-85.2,"dest":{"cell":"0146029B","place":"dungeon","name":"Mount Lethe Magma Tubes"},"minLevel":20,"id":2098}, + {"name":"Old Talisman Dungeon Portal","type":"Portal","wcid":1116,"cell":"147C0000","place":"outdoor","ns":-2.3,"ew":-85.61,"dest":{"cell":"01EA041E","place":"dungeon","name":"Old Talisman Dungeon"},"id":2099}, + {"name":"Heartland","type":"Portal","wcid":1900,"cell":"147C0000","place":"outdoor","ns":-2.46,"ew":-85.71,"dest":{"cell":"AD9B003E","place":"outdoor","ns":22.58,"ew":37.23},"id":2100}, + {"name":"Isle of Tears Portal","type":"Portal","wcid":1112,"cell":"15680104","place":"underground","ns":-18.75,"ew":-84.53,"dest":{"cell":"C09B0015","place":"outdoor","ns":22.55,"ew":51.92},"id":2101}, + {"name":"Slaughterhouse","type":"Portal","wcid":2359,"cell":"15680105","place":"underground","ns":-18.75,"ew":-84.49,"dest":{"cell":"1B7F0018","place":"outdoor","ns":0.43,"ew":-80.08},"id":2102}, + {"name":"Darktide Festival Stone Portal","type":"Portal","wcid":5447,"cell":"15680106","place":"underground","ns":-18.75,"ew":-84.45,"dest":{"cell":"0E34003F","place":"outdoor","ns":-59.74,"ew":-90.02},"minLevel":65,"id":2103}, + {"name":"Direlands Southeast Shore","type":"Portal","wcid":8385,"cell":"15680107","place":"underground","ns":-18.75,"ew":-84.41,"dest":{"cell":"52260007","place":"outdoor","ns":-70.9,"ew":-36.33},"minLevel":25,"id":2104}, + {"name":"Black Hill","type":"Portal","wcid":2328,"cell":"15680108","place":"underground","ns":-18.73,"ew":-84.56,"dest":{"cell":"3E310004","place":"outdoor","ns":-62.36,"ew":-52.3},"id":2105}, + {"name":"Obsidian Plains","type":"Portal","wcid":4046,"cell":"1568010D","place":"underground","ns":-18.72,"ew":-84.38,"dest":{"cell":"2D2F0034","place":"outdoor","ns":-64.02,"ew":-65.34},"minLevel":65,"id":2106}, + {"name":"Walled Portals","type":"Portal","wcid":4203,"cell":"1568010E","place":"underground","ns":-18.68,"ew":-84.56,"dest":{"cell":"2264000D","place":"outdoor","ns":-21.55,"ew":-74.6},"id":2107}, + {"name":"Obsidian Span Portal","type":"Portal","wcid":6433,"cell":"15680113","place":"underground","ns":-18.68,"ew":-84.38,"dest":{"cell":"B4AA0005","place":"outdoor","ns":34.52,"ew":42.07},"id":2108}, + {"name":"Obsidian Rim Portal","type":"Portal","wcid":7210,"cell":"15680114","place":"underground","ns":-18.64,"ew":-84.56,"dest":{"cell":"2E43000C","place":"outdoor","ns":-48.02,"ew":-65.01},"minLevel":35,"id":2109}, + {"name":"South Shore Heights","type":"Portal","wcid":8502,"cell":"15680119","place":"underground","ns":-18.64,"ew":-84.38,"dest":{"cell":"B013003E","place":"outdoor","ns":-86.19,"ew":39.6},"minLevel":12,"id":2110}, + {"name":"Stonehold Valley Portal","type":"Portal","wcid":5764,"cell":"1568011A","place":"underground","ns":-18.62,"ew":-84.53,"dest":{"cell":"5ED20005","place":"outdoor","ns":66.5,"ew":-26.7},"minLevel":12,"id":2111}, + {"name":"Direlands North Landbridge Portal","type":"Portal","wcid":8389,"cell":"1568011B","place":"underground","ns":-18.61,"ew":-84.49,"dest":{"cell":"36940026","place":"outdoor","ns":17.03,"ew":-58.35},"minLevel":25,"id":2112}, + {"name":"Direlands South Landbridge Portal","type":"Portal","wcid":8390,"cell":"1568011C","place":"underground","ns":-18.62,"ew":-84.45,"dest":{"cell":"6717001B","place":"outdoor","ns":-83.35,"ew":-19.21},"minLevel":25,"id":2113}, + {"name":"Vesayen Isles Portal","type":"Portal","wcid":8618,"cell":"1568011D","place":"underground","ns":-18.62,"ew":-84.41,"dest":{"cell":"E5240007","place":"outdoor","ns":-72.51,"ew":81.3},"id":2114}, + {"name":"Tumerok Cavern","type":"Portal","wcid":11325,"cell":"15B10000","place":"outdoor","ns":40.22,"ew":-84.73,"dest":{"cell":"02920219","place":"dungeon","name":"Tumerok Cavern"},"id":2115}, + {"name":"Panopticon Portal","type":"Portal","wcid":9296,"cell":"16350000","place":"outdoor","ns":-59.15,"ew":-84.02,"dest":{"cell":"02A10166","place":"dungeon","name":"Panopticon"},"minLevel":32,"id":2116}, + {"name":"Cave","type":"Portal","wcid":2360,"cell":"16430000","place":"outdoor","ns":-47.77,"ew":-83.68,"dest":{"cell":"01BD0107","place":"dungeon","name":"Cave"},"id":2117}, + {"name":"Northern Ahurenga Plains Portal","type":"Portal","wcid":11952,"cell":"16B20000","place":"outdoor","ns":40.96,"ew":-83.56,"dest":{"cell":"13C0002D","place":"outdoor","ns":52.12,"ew":-86.16},"id":2118}, + {"name":"Destroyed Portal to Nanto","type":"Portal","wcid":12160,"cell":"16B20000","place":"outdoor","ns":40.5,"ew":-83.71,"dest":{"cell":"E63E0022","place":"outdoor","ns":-52.19,"ew":82.45},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2119}, + {"name":"Destroyed Portal to Cragstone","type":"Portal","wcid":1014,"cell":"17480104","place":"underground","ns":-43.79,"ew":-83.0,"dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2120}, + {"name":"Hieromancers' Halls Portal","type":"Portal","wcid":9106,"cell":"17790101","place":"dungeon","dest":{"cell":"02A90148","place":"dungeon"},"desc":"In a dungeon (landblock 1779).","id":2121}, + {"name":"Exit Portal","type":"Portal","wcid":9070,"cell":"177B0000","place":"outdoor","ns":-2.84,"ew":-82.84,"dest":{"cell":"1579003F","place":"outdoor","ns":-4.5,"ew":-84.4},"id":2122}, + {"name":"Exit Portal","type":"Portal","wcid":9069,"cell":"177B0000","place":"outdoor","ns":-2.84,"ew":-82.76,"dest":{"cell":"1979003F","place":"outdoor","ns":-4.5,"ew":-81.2},"id":2123}, + {"name":"Destroyed Portal to Sanamar","type":"Portal","wcid":28709,"cell":"17B20024","place":"outdoor","ns":40.81,"ew":-83.07,"dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2124}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"17B2001B","place":"outdoor","ns":40.69,"ew":-83.23,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2125}, + {"name":"Camp Entemarre","type":"Portal","wcid":70752,"cell":"1830000E","place":"outdoor","ns":-62.96,"ew":-82.57,"dest":{"cell":"004901B0","place":"dungeon","name":"Camp Entemarre"},"minLevel":80,"quest":true,"desc":"You must speak to Hashina in Silyun before you may use this portal.","id":2126}, + {"name":"Destroyed Portal to Greenspire","type":"Portal","wcid":11954,"cell":"18B20000","place":"outdoor","ns":40.58,"ew":-82.41,"dest":{"cell":"2BB5003C","place":"outdoor","ns":43.21,"ew":-66.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2127}, + {"name":"Tumerok Cave","type":"Portal","wcid":11323,"cell":"18B30000","place":"outdoor","ns":41.67,"ew":-82.48,"dest":{"cell":"028602BF","place":"dungeon","name":"Tumerok Cave"},"id":2128}, + {"name":"Abandoned Tumerok Site","type":"Portal","wcid":10853,"cell":"18B30000","place":"outdoor","ns":41.98,"ew":-82.17,"dest":{"cell":"02840211","place":"dungeon","name":"Abandoned Tumerok Site"},"id":2129}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43567,"cell":"18B40102","place":"dungeon","dest":{"cell":"E4D00018","place":"outdoor","ns":65.16,"ew":80.73},"desc":"In a dungeon (landblock 18B4).","id":2130}, + {"name":"Secret Putiputi Place","type":"Portal","wcid":10925,"cell":"18B90000","place":"outdoor","ns":46.25,"ew":-82.05,"dest":{"cell":"57740112","place":"dungeon","name":"Secret Putiputi Place"},"quest":true,"id":2131}, + {"name":"Archive","type":"Portal","wcid":35563,"cell":"19360140","place":"underground","ns":-58.42,"ew":-81.3,"dest":{"cell":"193604BC","place":"building","ns":-58.79,"ew":-81.34},"minLevel":120,"id":2132}, + {"name":"Surface","type":"Portal","wcid":35564,"cell":"19360163","place":"underground","ns":-58.96,"ew":-81.19,"dest":{"cell":"19360019","place":"outdoor","ns":-58.73,"ew":-81.59},"id":2133}, + {"name":"Prismatic Guardian Lair","type":"Portal","wcid":46922,"cell":"198D0039","place":"outdoor","ns":10.9,"ew":-81.18,"dest":{"cell":"5850014A","place":"dungeon","name":"Prismatic Guardian Lair"},"minLevel":150,"id":2134}, + {"name":"Olthoi Arcade","type":"Portal","wcid":22011,"cell":"19B00000","place":"outdoor","ns":39.04,"ew":-81.17,"dest":{"cell":"5B43041A","place":"dungeon","name":"Olthoi Arcade"},"id":2135}, + {"name":"Olthoi Warrior Nest","type":"Portal","wcid":27585,"cell":"19BA0000","place":"outdoor","ns":46.96,"ew":-81.21,"dest":{"cell":"667801DC","place":"dungeon","name":"Olthoi Warrior Nest"},"minLevel":70,"id":2136}, + {"name":"Mount Elyrii Hive Portal","type":"Portal","wcid":11215,"cell":"19BC0000","place":"outdoor","ns":48.5,"ew":-81.68,"dest":{"cell":"03A703B2","place":"dungeon","name":"Mount Elyrii Hive"},"minLevel":70,"id":2137}, + {"name":"Hive Warrior Mound","type":"Portal","wcid":51325,"cell":"19BC0037","place":"outdoor","ns":49.1,"ew":-81.27,"dest":{"cell":"586E041E","place":"dungeon","name":"Hive Warrior Mound"},"minLevel":200,"id":2138}, + {"name":"Assassins' Hideout","type":"Portal","wcid":33251,"cell":"1A3B0100","place":"dungeon","dest":{"cell":"00820185","place":"dungeon"},"minLevel":120,"quest":true,"desc":"In a dungeon (landblock 1A3B).","id":2139}, + {"name":"Surface","type":"Portal","wcid":35597,"cell":"1A730111","place":"dungeon","dest":{"cell":"1A730009","place":"outdoor","ns":-9.86,"ew":-81.02},"desc":"In a dungeon (landblock 1A73).","id":2140}, + {"name":"Inner Stronghold","type":"Portal","wcid":30846,"cell":"1A8E028D","place":"underground","ns":11.97,"ew":-81.77,"dest":{"cell":"1A8E0262","place":"underground","ns":12.8,"ew":-81.46},"minLevel":80,"id":2141}, + {"name":"Banished Assembly","type":"Portal","wcid":4941,"cell":"1B120101","place":"building","ns":-86.99,"ew":-79.59,"dest":{"cell":"001501CA","place":"dungeon","name":"Banished Assembly"},"minLevel":100,"id":2142}, + {"name":"Sclavus Cathedral","type":"Portal","wcid":7287,"cell":"1B550000","place":"outdoor","ns":-33.44,"ew":-80.12,"dest":{"cell":"02F603FA","place":"dungeon","name":"Sclavus Cathedral"},"id":2143}, + {"name":"Black Spawn Den","type":"Portal","wcid":7242,"cell":"1B900000","place":"outdoor","ns":13.61,"ew":-79.84,"dest":{"cell":"01050375","place":"dungeon","name":"Black Spawn Den"},"minLevel":20,"id":2144}, + {"name":"West Fork Dam Hive","type":"Portal","wcid":51250,"cell":"1BBC0017","place":"outdoor","ns":49.07,"ew":-80.05,"dest":{"cell":"5869026B","place":"dungeon","name":"West Fork Dam Hive"},"minLevel":180,"id":2145}, + {"name":"Ravaged Cathedral","type":"Portal","wcid":30695,"cell":"1C130000","place":"outdoor","ns":-86.21,"ew":-79.01,"dest":{"cell":"001601CA","place":"dungeon","name":"Ravaged Cathedral"},"minLevel":100,"id":2146}, + {"name":"Nexus Portal","type":"Portal","wcid":6795,"cell":"1C4D0000","place":"outdoor","ns":-40.14,"ew":-79.14,"dest":{"cell":"011002E1","place":"dungeon","name":"Nexus"},"minLevel":100,"id":2147}, + {"name":"Wasteland Hive Portal","type":"Portal","wcid":11231,"cell":"1CBE0000","place":"outdoor","ns":50.8,"ew":-79.1,"dest":{"cell":"028503E6","place":"dungeon","name":"Wasteland Hive"},"minLevel":70,"id":2148}, + {"name":"Vile Sanctuary","type":"Portal","wcid":30693,"cell":"1D130115","place":"underground","ns":-86.73,"ew":-78.15,"dest":{"cell":"001701CA","place":"dungeon"},"minLevel":100,"id":2149}, + {"name":"Master Vaserio's Dig","type":"Portal","wcid":32239,"cell":"1D3B000E","place":"outdoor","ns":-54.2,"ew":-78.57,"dest":{"cell":"0043031D","place":"dungeon","name":"Master Vaserio's Dig"},"minLevel":100,"desc":"This dungeon is quest-restricted. Speak with Qath al-Haddash in Qalaba'r to learn more.","id":2150}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"1DB6003C","place":"outdoor","ns":44.04,"ew":-77.99,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2151}, + {"name":"Mutilator Tunnels","type":"Portal","wcid":27583,"cell":"1DC10000","place":"outdoor","ns":52.84,"ew":-78.12,"dest":{"cell":"667A0240","place":"dungeon","name":"Mutilator Tunnels"},"minLevel":80,"id":2152}, + {"name":"Marescent Plateau Portal","type":"Portal","wcid":11958,"cell":"1EB30102","place":"dungeon","dest":{"cell":"1EB4001A","place":"outdoor","ns":42.18,"ew":-77.62},"minLevel":35,"desc":"In a dungeon (landblock 1EB3).","id":2153}, + {"name":"Base of the Cliffs Portal","type":"Portal","wcid":11957,"cell":"1EB40000","place":"outdoor","ns":42.27,"ew":-77.87,"dest":{"cell":"1EB30010","place":"outdoor","ns":42.04,"ew":-77.81},"minLevel":35,"id":2154}, + {"name":"Base of the Timaru Plateau Portal","type":"Portal","wcid":11959,"cell":"1EB60000","place":"outdoor","ns":44.06,"ew":-77.8,"dest":{"cell":"1EB60013","place":"outdoor","ns":43.9,"ew":-77.71},"id":2155}, + {"name":"Viamontian Direlands Mine","type":"Portal","wcid":32621,"cell":"1F8A003A","place":"outdoor","ns":8.64,"ew":-76.44,"dest":{"cell":"00480330","place":"dungeon","name":"Viamontian Direlands Mine"},"minLevel":100,"quest":true,"desc":"This dungeon is quest restricted.","id":2156}, + {"name":"East Fork Dam Hive Portal","type":"Portal","wcid":11213,"cell":"1FBC0108","place":"building","ns":48.49,"ew":-76.41,"dest":{"cell":"027F0234","place":"dungeon","name":"East Fork Dam Hive"},"minLevel":50,"id":2157}, + {"name":"Lair of the Eviscerators","type":"Portal","wcid":10849,"cell":"1FC20000","place":"outdoor","ns":53.71,"ew":-76.59,"dest":{"cell":"027D02AA","place":"dungeon","name":"Lair of the Eviscerators"},"minLevel":50,"id":2158}, + {"name":"Martinate Holding","type":"Portal","wcid":10881,"cell":"1FC90000","place":"outdoor","ns":59.57,"ew":-77.06,"dest":{"cell":"027E0104","place":"dungeon","name":"Martinate Holding"},"id":2159}, + {"name":"Surface","type":"Portal","wcid":42923,"cell":"200F0497","place":"underground","ns":-93.81,"ew":-76.02,"dest":{"cell":"12030120","place":"building","ns":-99.24,"ew":-87.43},"id":2160}, + {"name":"Aun Papileona's Shrine to Raeta","type":"Portal","wcid":11337,"cell":"20B00000","place":"outdoor","ns":38.88,"ew":-76.29,"dest":{"cell":"028701F3","place":"dungeon","name":"Aun Papileona's Shrine to Raeta"},"id":2161}, + {"name":"Destroyed Ahurenga Portal","type":"Portal","wcid":10982,"cell":"20B10000","place":"outdoor","ns":40.13,"ew":-76.07,"dest":{"cell":"0FB90009","place":"outdoor","ns":46.09,"ew":-89.77},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2162}, + {"name":"An Olthoi Soldier Nest","type":"Portal","wcid":10857,"cell":"20B70000","place":"outdoor","ns":45.19,"ew":-76.27,"dest":{"cell":"02820234","place":"dungeon","name":"An Olthoi Soldier Nest"},"minLevel":30,"id":2163}, + {"name":"North Fork Dam Hive Portal","type":"Portal","wcid":11217,"cell":"20BF0125","place":"building","ns":51.42,"ew":-76.0,"dest":{"cell":"03A602C9","place":"dungeon","name":"North Fork Dam Hive"},"minLevel":70,"id":2164}, + {"name":"Sclavus Temple","type":"Portal","wcid":25588,"cell":"21180100","place":"building","ns":-82.5,"ew":-75.19,"dest":{"cell":"604A036C","place":"dungeon","name":"Sclavus Temple"},"minLevel":60,"id":2165}, + {"name":"Halls of the Lost Light","type":"Portal","wcid":1430,"cell":"211F0100","place":"dungeon","dest":{"cell":"01CE01C9","place":"dungeon"},"desc":"In a dungeon (landblock 211F).","id":2166}, + {"name":"Pheraion's Sanctum","type":"Portal","wcid":33255,"cell":"21340027","place":"outdoor","ns":-59.75,"ew":-75.11,"dest":{"cell":"0083026E","place":"dungeon","name":"Pheraion's Sanctum"},"minLevel":120,"quest":true,"id":2167}, + {"name":"Mysterious Portal","type":"Portal","wcid":43201,"cell":"21760110","place":"underground","ns":-6.89,"ew":-75.42,"dest":{"cell":"8B03018F","place":"dungeon"},"minLevel":150,"quest":true,"desc":"A portal crackling with defensive magics. Only those properly protected from its fluxuations may enter.","id":2168}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"21AF0000","place":"outdoor","ns":38.26,"ew":-75.51,"dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2169}, + {"name":"Viamontian Laboratory","type":"Portal","wcid":32710,"cell":"21B0013B","place":"building","ns":39.41,"ew":-75.33,"dest":{"cell":"00680186","place":"dungeon","name":"Viamontian Laboratory"},"minLevel":30,"id":2170}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"21B0000D","place":"outdoor","ns":39.34,"ew":-75.41,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2171}, + {"name":"Karab Delta Portal","type":"Portal","wcid":11955,"cell":"21C50000","place":"outdoor","ns":55.93,"ew":-75.02,"dest":{"cell":"1EAF0011","place":"outdoor","ns":38.11,"ew":-77.72},"id":2172}, + {"name":"Waterfall Cave","type":"Portal","wcid":28796,"cell":"21E8000C","place":"outdoor","ns":84.0,"ew":-75.41,"dest":{"cell":"02D50237","place":"dungeon","name":"Waterfall Cave"},"id":2173}, + {"name":"Empyrean Acid Propylaeum","type":"Portal","wcid":14492,"cell":"22570000","place":"outdoor","ns":-31.63,"ew":-74.21,"dest":{"cell":"526E014B","place":"dungeon","name":"Empyrean Acid Propylaeum"},"minLevel":50,"id":2174}, + {"name":"Acid Guardian Lair","type":"Portal","wcid":21414,"cell":"22590000","place":"outdoor","ns":-30.49,"ew":-74.31,"dest":{"cell":"5943014A","place":"dungeon","name":"Acid Guardian Lair"},"minLevel":60,"maxLevel":79,"id":2175}, + {"name":"Outside Accursed Halls Portal","type":"Portal","wcid":1087,"cell":"22640000","place":"outdoor","ns":-21.56,"ew":-74.52,"dest":{"cell":"3761000C","place":"outdoor","ns":-24.02,"ew":-57.79},"id":2176}, + {"name":"Ridge Tower","type":"Portal","wcid":4147,"cell":"22640000","place":"outdoor","ns":-21.54,"ew":-74.66,"dest":{"cell":"CB3D0032","place":"outdoor","ns":-52.99,"ew":61.06},"id":2177}, + {"name":"Northern Manumet Plains Portal","type":"Portal","wcid":11956,"cell":"22B10000","place":"outdoor","ns":40.03,"ew":-74.51,"dest":{"cell":"2ABE000D","place":"outdoor","ns":50.48,"ew":-68.15},"minLevel":25,"id":2178}, + {"name":"Dericost Ruin","type":"Portal","wcid":28714,"cell":"22DC002A","place":"outdoor","ns":74.18,"ew":-74.18,"dest":{"cell":"015F0223","place":"dungeon","name":"Dericost Ruin"},"id":2179}, + {"name":"Small Empyrean Vault","type":"Portal","wcid":28780,"cell":"22E30040","place":"outdoor","ns":80.42,"ew":-74.02,"dest":{"cell":"01FE02CB","place":"dungeon","name":"Small Empyrean Vault"},"minLevel":30,"id":2180}, + {"name":"Renegade Incursion","type":"Portal","wcid":31294,"cell":"23800031","place":"outdoor","ns":0.51,"ew":-73.29,"dest":{"cell":"003001A7","place":"dungeon","name":"Renegade Incursion"},"minLevel":50,"id":2181}, + {"name":"Ancient Lighthouse Portal","type":"Portal","wcid":2357,"cell":"23840100","place":"dungeon","dest":{"cell":"01A902D5","place":"dungeon"},"minLevel":18,"desc":"In a dungeon (landblock 2384).","id":2182}, + {"name":"Tumerok Fortress Portal","type":"Portal","wcid":2364,"cell":"238E0000","place":"outdoor","ns":12.3,"ew":-73.7,"dest":{"cell":"01BE01C2","place":"dungeon","name":"Tumerok Fortress"},"minLevel":20,"id":2183}, + {"name":"Back Tunnels","type":"Portal","wcid":70087,"cell":"23B6010F","place":"dungeon","dest":{"cell":"005502B8","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 23B6).","id":2184}, + {"name":"Chiming Portal","type":"Portal","wcid":51253,"cell":"23B70026","place":"outdoor","ns":44.96,"ew":-73.51,"dest":{"cell":"5868016E","place":"dungeon","name":"Chiming"},"minLevel":180,"id":2185}, + {"name":"Hive Eviscerator Burrow","type":"Portal","wcid":51321,"cell":"23BC001A","place":"outdoor","ns":48.59,"ew":-73.56,"dest":{"cell":"586D03E2","place":"dungeon","name":"Hive Eviscerator Burrow"},"minLevel":200,"id":2186}, + {"name":"Destroyed Portal to Sanamar","type":"Portal","wcid":28709,"cell":"23DA003D","place":"outdoor","ns":72.86,"ew":-73.23,"dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2187}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"23DA0034","place":"outdoor","ns":72.78,"ew":-73.33,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2188}, + {"name":"Viamontian Garrison","type":"Portal","wcid":28795,"cell":"23DD000D","place":"outdoor","ns":75.3,"ew":-73.8,"dest":{"cell":"00020224","place":"dungeon","name":"Viamontian Garrison"},"id":2189}, + {"name":"Amperehelion Vault Portal","type":"Portal","wcid":6389,"cell":"24380000","place":"outdoor","ns":-56.49,"ew":-72.78,"dest":{"cell":"01190371","place":"dungeon","name":"Amperehelion Vault"},"id":2190}, + {"name":"Portal to Lighthouse","type":"Portal","wcid":2356,"cell":"24840000","place":"outdoor","ns":3.89,"ew":-72.48,"dest":{"cell":"23840014","place":"outdoor","ns":3.99,"ew":-73.69},"minLevel":18,"id":2191}, + {"name":"Palenqual's Caverns","type":"Portal","wcid":11442,"cell":"24BC0104","place":"building","ns":48.9,"ew":-72.54,"dest":{"cell":"028E0330","place":"dungeon","name":"Palenqual's Caverns"},"quest":true,"id":2192}, + {"name":"Breached Hive","type":"Portal","wcid":32104,"cell":"24BD0007","place":"outdoor","ns":49.91,"ew":-73.12,"dest":{"cell":"003E02F7","place":"dungeon","name":"Breached Hive"},"minLevel":50,"id":2193}, + {"name":"Tiny Hive Portal","type":"Portal","wcid":11219,"cell":"24BD002F","place":"outdoor","ns":49.9,"ew":-72.65,"dest":{"cell":"028902A5","place":"dungeon","name":"Tiny Hive"},"minLevel":35,"id":2194}, + {"name":"Surface","type":"Portal","wcid":87831,"cell":"24C00261","place":"building","ns":51.58,"ew":-73.13,"dest":{"cell":"24C00586","place":"building","ns":51.95,"ew":-73.0},"id":2195}, + {"name":"Surface","type":"Portal","wcid":87831,"cell":"24C0067B","place":"building","ns":51.82,"ew":-73.26,"dest":{"cell":"24C00586","place":"building","ns":51.95,"ew":-73.0},"id":2196}, + {"name":"Roots of Skuld, Urd and Verdandi","type":"Portal","wcid":87828,"cell":"24C00582","place":"building","ns":51.99,"ew":-73.0,"dest":{"cell":"24C0067C","place":"building","ns":51.79,"ew":-73.25},"minLevel":150,"quest":true,"id":2197}, + {"name":"Ancient Empyrean Grotto","type":"Portal","wcid":10855,"cell":"24C10000","place":"outdoor","ns":52.57,"ew":-73.05,"dest":{"cell":"027C01B0","place":"dungeon","name":"Ancient Empyrean Grotto"},"minLevel":40,"id":2198}, + {"name":"Eater Pit","type":"Portal","wcid":29496,"cell":"24EE0100","place":"dungeon","dest":{"cell":"001F0286","place":"dungeon"},"minLevel":40,"quest":true,"desc":"In a dungeon (landblock 24EE).","id":2199}, + {"name":"North Direlands Valley Junction","type":"Portal","wcid":8387,"cell":"25250100","place":"dungeon","dest":{"cell":"2E820006","place":"outdoor","ns":2.57,"ew":-65.05},"minLevel":25,"desc":"In a dungeon (landblock 2525).","id":2200}, + {"name":"Empyrean Facility Upper Level","type":"Portal","wcid":42711,"cell":"2545002E","place":"outdoor","ns":-46.21,"ew":-71.81,"dest":{"cell":"890402C4","place":"dungeon","name":"Empyrean Facility Upper Level"},"minLevel":75,"id":2201}, + {"name":"Beachside","type":"Portal","wcid":1899,"cell":"25730105","place":"building","ns":-9.41,"ew":-71.86,"dest":{"cell":"CE9C0038","place":"outdoor","ns":23.56,"ew":63.52},"id":2202}, + {"name":"Colossus Foundry Portal","type":"Portal","wcid":19715,"cell":"2581016A","place":"building","ns":1.6,"ew":-72.05,"dest":{"cell":"545701C5","place":"dungeon","name":"Colossus Foundry"},"id":2203}, + {"name":"Portal to Town Network","type":"Portal","wcid":43065,"cell":"2581002C","place":"outdoor","ns":1.55,"ew":-71.77,"dest":{"cell":"00070143","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2204}, + {"name":"Mountain Citadel Portal","type":"Portal","wcid":25281,"cell":"25860000","place":"outdoor","ns":5.36,"ew":-71.83,"dest":{"cell":"61470152","place":"dungeon","name":"Mountain Citadel"},"id":2205}, + {"name":"Thrungal Den","type":"Portal","wcid":73054,"cell":"25E2003E","place":"outdoor","ns":79.36,"ew":-71.63,"dest":{"cell":"006502BA","place":"dungeon","name":"Thrungal Den"},"minLevel":100,"quest":true,"id":2206}, + {"name":"Aerbax's Holding","type":"Portal","wcid":25392,"cell":"26310000","place":"outdoor","ns":-62.4,"ew":-71.1,"dest":{"cell":"594B012B","place":"dungeon","name":"Aerbax's Holding"},"minLevel":60,"id":2207}, + {"name":"Northwest Direlands Portal","type":"Portal","wcid":7211,"cell":"26410000","place":"outdoor","ns":-49.4,"ew":-70.8,"dest":{"cell":"12860003","place":"outdoor","ns":5.53,"ew":-87.51},"minLevel":35,"id":2208}, + {"name":"Hilltop","type":"Portal","wcid":1902,"cell":"26810000","place":"outdoor","ns":1.72,"ew":-71.47,"dest":{"cell":"AAA80034","place":"outdoor","ns":32.79,"ew":34.68},"id":2209}, + {"name":"Remote Empyrean Vault","type":"Portal","wcid":28782,"cell":"26E5001C","place":"outdoor","ns":81.65,"ew":-71.19,"dest":{"cell":"000102C6","place":"dungeon","name":"Remote Empyrean Vault"},"minLevel":40,"id":2210}, + {"name":"Destroyed Glenden Wood Portal","type":"Portal","wcid":1017,"cell":"27180000","place":"outdoor","ns":-82.6,"ew":-70.18,"dest":{"cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2211}, + {"name":"Silyun Chapterhouse","type":"Portal","wcid":32695,"cell":"27EA001A","place":"outdoor","ns":85.38,"ew":-70.4,"dest":{"cell":"005201C9","place":"dungeon","name":"Silyun Chapterhouse"},"minLevel":80,"quest":true,"desc":"This dungeon is quest restricted. Go see Garmasi in the Royal Hall of Sanamar for more information.","id":2212}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"27EC000C","place":"outdoor","ns":87.25,"ew":-70.6,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2213}, + {"name":"Hidden City","type":"Portal","wcid":28786,"cell":"27F5003C","place":"outdoor","ns":94.4,"ew":-70.0,"dest":{"cell":"02D602CE","place":"dungeon","name":"Hidden City"},"minLevel":50,"id":2214}, + {"name":"Sotiris Portal","type":"Portal","wcid":8381,"cell":"282A0000","place":"outdoor","ns":-67.98,"ew":-69.24,"dest":{"cell":"02C90280","place":"dungeon","name":"Sotiris"},"minLevel":30,"id":2215}, + {"name":"Surface","type":"Portal","wcid":40504,"cell":"28420164","place":"dungeon","dest":{"cell":"2942001C","place":"outdoor","ns":-48.83,"ew":-68.79},"desc":"In Apostate Citadel Mines.","id":2216}, + {"name":"Apostate Citadel Headquarters","type":"Portal","wcid":40503,"cell":"2842018F","place":"dungeon","dest":{"cell":"284201C9","place":"dungeon","name":"Apostate Citadel Mines"},"minLevel":150,"desc":"This portal leads to the headquarters of the Apostate Citadel. In Apostate Citadel Mines.","id":2217}, + {"name":"Surface","type":"Portal","wcid":40504,"cell":"284201E1","place":"dungeon","dest":{"cell":"2942001C","place":"outdoor","ns":-48.83,"ew":-68.79},"desc":"In Apostate Citadel Mines.","id":2218}, + {"name":"Apostate Citadel Barracks","type":"Portal","wcid":40502,"cell":"284201EA","place":"dungeon","dest":{"cell":"284201E0","place":"dungeon","name":"Apostate Citadel Mines"},"minLevel":150,"desc":"This portal leads to the barracks of the Apostate Citadel. In Apostate Citadel Mines.","id":2219}, + {"name":"Surface","type":"Portal","wcid":40504,"cell":"28420183","place":"dungeon","dest":{"cell":"2942001C","place":"outdoor","ns":-48.83,"ew":-68.79},"desc":"In Apostate Citadel Mines.","id":2220}, + {"name":"Grael's Chamber","type":"Portal","wcid":33784,"cell":"28930003","place":"outdoor","ns":15.9,"ew":-69.94,"dest":{"cell":"007504C6","place":"dungeon","name":"Grael's Chamber"},"quest":true,"desc":"This portal is warded against those who have not earned the right to access the chamber of the Shadow Aspect of Grael.","id":2221}, + {"name":"Plains of Ruin","type":"Portal","wcid":30382,"cell":"28EC0018","place":"outdoor","ns":87.6,"ew":-69.68,"dest":{"cell":"3FF00016","place":"outdoor","ns":90.6,"ew":-51.3},"id":2222}, + {"name":"Lola's Den","type":"Portal","wcid":28798,"cell":"28F2001B","place":"outdoor","ns":91.93,"ew":-69.63,"dest":{"cell":"01EB032F","place":"dungeon","name":"Lola's Den"},"id":2223}, + {"name":"Heartland","type":"Portal","wcid":1900,"cell":"29380101","place":"building","ns":-57.12,"ew":-68.9,"dest":{"cell":"AD9B003E","place":"outdoor","ns":22.58,"ew":37.23},"id":2224}, + {"name":"Apostate Citadel Mines","type":"Portal","wcid":40505,"cell":"29420015","place":"outdoor","ns":-48.68,"ew":-68.91,"dest":{"cell":"28420163","place":"dungeon","name":"Apostate Citadel Mines"},"minLevel":150,"quest":true,"desc":"This portal leads to the mines of the Apostate Citadel.","id":2225}, + {"name":"The Dark Spiral","type":"Portal","wcid":32844,"cell":"29930023","place":"outdoor","ns":15.87,"ew":-68.71,"dest":{"cell":"00CF055F","place":"dungeon","name":"The Dark Spiral"},"minLevel":126,"id":2226}, + {"name":"The Dark Lair","type":"Portal","wcid":10851,"cell":"29B60000","place":"outdoor","ns":43.8,"ew":-68.41,"dest":{"cell":"0283015A","place":"dungeon","name":"The Dark Lair"},"id":2227}, + {"name":"Heart of Madness","type":"Portal","wcid":29498,"cell":"29E90100","place":"dungeon","dest":{"cell":"002002D2","place":"dungeon"},"minLevel":40,"quest":true,"desc":"In a dungeon (landblock 29E9).","id":2228}, + {"name":"Ruschk Burial Mound","type":"Portal","wcid":32818,"cell":"29F10100","place":"dungeon","dest":{"cell":"00E202FA","place":"dungeon"},"minLevel":60,"quest":true,"desc":"In a dungeon (landblock 29F1).","id":2229}, + {"name":"Tusker Temple","type":"Portal","wcid":22696,"cell":"2A800000","place":"outdoor","ns":0.72,"ew":-68.11,"dest":{"cell":"5C4A02F9","place":"dungeon","name":"Tusker Temple"},"minLevel":40,"id":2230}, + {"name":"Tumerok Post","type":"Portal","wcid":2558,"cell":"2A8E0000","place":"outdoor","ns":12.19,"ew":-68.11,"dest":{"cell":"019F0133","place":"dungeon","name":"Tumerok Post"},"id":2231}, + {"name":"Destroyed Portal to Redspire","type":"Portal","wcid":11960,"cell":"2AB50000","place":"outdoor","ns":43.26,"ew":-68.16,"dest":{"cell":"17B2002A","place":"outdoor","ns":40.56,"ew":-83.0},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2232}, + {"name":"Crumbling Empyrean Mansion","type":"Portal","wcid":27587,"cell":"2AB90000","place":"outdoor","ns":46.8,"ew":-67.88,"dest":{"cell":"66790275","place":"dungeon","name":"Crumbling Empyrean Mansion"},"id":2233}, + {"name":"Beacon Tower Exit","type":"Portal","wcid":30535,"cell":"2AE2001C","place":"outdoor","ns":79.2,"ew":-68.04,"dest":{"cell":"33D90009","place":"outdoor","ns":71.73,"ew":-60.96},"id":2234}, + {"name":"Beacon Tower Exit","type":"Portal","wcid":30535,"cell":"2AE3000E","place":"outdoor","ns":80.2,"ew":-68.2,"dest":{"cell":"33D90009","place":"outdoor","ns":71.73,"ew":-60.96},"id":2235}, + {"name":"Beacon Tower Exit","type":"Portal","wcid":30535,"cell":"2AE3002E","place":"outdoor","ns":80.2,"ew":-67.8,"dest":{"cell":"33D90009","place":"outdoor","ns":71.73,"ew":-60.96},"id":2236}, + {"name":"Beacon Tower Exit","type":"Portal","wcid":30535,"cell":"2AE30020","place":"outdoor","ns":80.4,"ew":-68.0,"dest":{"cell":"33D90009","place":"outdoor","ns":71.73,"ew":-60.96},"id":2237}, + {"name":"Karlun's Fort","type":"Portal","wcid":29500,"cell":"2AEE003E","place":"outdoor","ns":89.0,"ew":-67.61,"dest":{"cell":"2AEE0024","place":"outdoor","ns":88.81,"ew":-67.88},"minLevel":40,"id":2238}, + {"name":"Exit Karlun's Fort","type":"Portal","wcid":29501,"cell":"2AEE002D","place":"outdoor","ns":88.88,"ew":-67.78,"dest":{"cell":"2AEE0030","place":"outdoor","ns":89.2,"ew":-67.8},"id":2239}, + {"name":"Hall of Karlun","type":"Portal","wcid":29502,"cell":"2AEE002D","place":"outdoor","ns":88.91,"ew":-67.81,"dest":{"cell":"0021013E","place":"dungeon","name":"Hall of Karlun"},"minLevel":40,"quest":true,"id":2240}, + {"name":"South Direlands Portal","type":"Portal","wcid":1107,"cell":"2B100101","place":"underground","ns":-88.48,"ew":-66.8,"dest":{"cell":"5416001A","place":"outdoor","ns":-84.2,"ew":-34.44},"minLevel":12,"id":2241}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"2B110027","place":"outdoor","ns":-87.68,"ew":-67.07,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2242}, + {"name":"Tree Portal","type":"Portal","wcid":24580,"cell":"2B120000","place":"outdoor","ns":-87.51,"ew":-67.19,"dest":{"cell":"2B120019","place":"outdoor","ns":-87.52,"ew":-67.18},"quest":true,"id":2243}, + {"name":"Ground Portal","type":"Portal","wcid":24875,"cell":"2B120000","place":"outdoor","ns":-87.54,"ew":-67.16,"dest":{"cell":"2B110028","place":"outdoor","ns":-87.61,"ew":-67.09},"id":2244}, + {"name":"Bandit Castle","type":"Portal","wcid":31341,"cell":"2B200024","place":"outdoor","ns":-75.99,"ew":-67.1,"dest":{"cell":"BDD00006","place":"outdoor","ns":64.95,"ew":49.32},"id":2245}, + {"name":"Mukkir-Infested Black Spear Temple","type":"Portal","wcid":33774,"cell":"2B500030","place":"outdoor","ns":-37.24,"ew":-66.96,"dest":{"cell":"0076046B","place":"dungeon","name":"Mukkir-Infested Black Spear Temple"},"minLevel":151,"quest":true,"desc":"A Mukkir-infested Ruschk temple, where those who wish to follow the Black Spear prove their worth.","id":2246}, + {"name":"Destroyed Portal to Yaraq","type":"Portal","wcid":1030,"cell":"2BB40000","place":"outdoor","ns":42.51,"ew":-67.49,"dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2247}, + {"name":"Unstable Portal","type":"Portal","wcid":32087,"cell":"2BB40028","place":"outdoor","ns":42.81,"ew":-67.06,"dest":{"cell":"01A80156","place":"dungeon","name":"Unstable"},"closed":true,"desc":"This portal seems to have become unstable. It would be very unwise to use a portal in this state.","id":2248}, + {"name":"Black Spear Temple Upper Levels","type":"Portal","wcid":33017,"cell":"2C290101","place":"dungeon","dest":{"cell":"007E0353","place":"dungeon"},"minLevel":100,"quest":true,"desc":"In a dungeon (landblock 2C29).","id":2249}, + {"name":"Presk's Bunker","type":"Portal","wcid":51906,"cell":"2C2F0020","place":"outdoor","ns":-63.58,"ew":-66.35,"dest":{"cell":"59510139","place":"dungeon","name":"Presk's Bunker"},"minLevel":180,"id":2250}, + {"name":"Path of Sorrows","type":"Portal","wcid":51721,"cell":"2C300021","place":"outdoor","ns":-63.52,"ew":-66.3,"dest":{"cell":"58790255","place":"dungeon","name":"Path of Sorrows"},"minLevel":180,"id":2251}, + {"name":"Rynthid Genesis","type":"Portal","wcid":51615,"cell":"2C300008","place":"outdoor","ns":-62.79,"ew":-66.73,"dest":{"cell":"58750294","place":"dungeon","name":"Rynthid Genesis"},"minLevel":180,"id":2252}, + {"name":"Spirited Halls","type":"Portal","wcid":51763,"cell":"2C300004","place":"outdoor","ns":-63.17,"ew":-66.69,"dest":{"cell":"5878030A","place":"dungeon","name":"Spirited Halls"},"minLevel":180,"id":2253}, + {"name":"Bah'Ktar's Tower","type":"Portal","wcid":51944,"cell":"2C310001","place":"outdoor","ns":-62.68,"ew":-66.67,"dest":{"cell":"59520258","place":"dungeon","name":"Bah'Ktar's Tower"},"minLevel":180,"id":2254}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"2CB50003","place":"outdoor","ns":43.11,"ew":-66.66,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2255}, + {"name":"Marauder's Lair","type":"Portal","wcid":29361,"cell":"2CE80100","place":"dungeon","dest":{"cell":"0197035D","place":"dungeon"},"desc":"In a dungeon (landblock 2CE8).","id":2256}, + {"name":"Frozen Cenotaph","type":"Portal","wcid":31432,"cell":"2CF00100","place":"dungeon","dest":{"cell":"003701CC","place":"dungeon"},"minLevel":40,"quest":true,"desc":"This dungeon is quest restricted. Royal scholars in Cragstone or Sanamar might be interested in the secrets it holds. In a dungeon (landblock 2CF0).","id":2257}, + {"name":"Seed of Misery","type":"Portal","wcid":51569,"cell":"2D30002D","place":"outdoor","ns":-63.13,"ew":-65.44,"dest":{"cell":"58720120","place":"dungeon","name":"Seed of Misery"},"minLevel":180,"id":2258}, + {"name":"Seed of Anger","type":"Portal","wcid":51580,"cell":"2D300025","place":"outdoor","ns":-63.13,"ew":-65.53,"dest":{"cell":"5873019E","place":"dungeon","name":"Seed of Anger"},"minLevel":180,"id":2259}, + {"name":"Seed of Hatred","type":"Portal","wcid":51564,"cell":"2D300026","place":"outdoor","ns":-63.04,"ew":-65.49,"dest":{"cell":"58710202","place":"dungeon","name":"Seed of Hatred"},"minLevel":180,"id":2260}, + {"name":"Path of Torment","type":"Portal","wcid":51717,"cell":"2D31000F","place":"outdoor","ns":-62.09,"ew":-65.85,"dest":{"cell":"5879052B","place":"dungeon","name":"Path of Sorrows"},"minLevel":180,"id":2261}, + {"name":"Fear Factory","type":"Portal","wcid":51690,"cell":"2D31002F","place":"outdoor","ns":-62.11,"ew":-65.37,"dest":{"cell":"587701F7","place":"dungeon","name":"Fear Factory"},"minLevel":180,"id":2262}, + {"name":"Rynthid Foundry","type":"Portal","wcid":51669,"cell":"2D31003B","place":"outdoor","ns":-62.48,"ew":-65.17,"dest":{"cell":"58760207","place":"dungeon","name":"Rynthid Foundry"},"minLevel":180,"id":2263}, + {"name":"Path of Rage","type":"Portal","wcid":51718,"cell":"2D31002B","place":"outdoor","ns":-62.54,"ew":-65.41,"dest":{"cell":"587903EA","place":"dungeon","name":"Path of Sorrows"},"minLevel":180,"id":2264}, + {"name":"Hidden Cavern","type":"Portal","wcid":25570,"cell":"2D500000","place":"outdoor","ns":-37.84,"ew":-65.51,"dest":{"cell":"5F4802CC","place":"dungeon","name":"Hidden Cavern"},"minLevel":80,"id":2265}, + {"name":"Renegade Fortress","type":"Portal","wcid":27479,"cell":"2D5A0104","place":"building","ns":-29.54,"ew":-65.5,"dest":{"cell":"624803E8","place":"dungeon","name":"Renegade Fortress"},"minLevel":60,"id":2266}, + {"name":"Renegade Fortress","type":"Portal","wcid":40349,"cell":"2D5A010A","place":"underground","ns":-29.46,"ew":-65.64,"dest":{"cell":"00CC0101","place":"dungeon"},"minLevel":120,"id":2267}, + {"name":"Facility Entrance","type":"Portal","wcid":40878,"cell":"2D6B0104","place":"underground","ns":-15.66,"ew":-65.38,"dest":{"cell":"2D6B02C4","place":"underground","ns":-15.69,"ew":-65.36},"minLevel":50,"id":2268}, + {"name":"Tumerok Base","type":"Portal","wcid":2560,"cell":"2D8A010A","place":"building","ns":9.0,"ew":-65.68,"dest":{"cell":"01A1016E","place":"dungeon","name":"Tumerok Base"},"id":2269}, + {"name":"Steaming Hovel","type":"Portal","wcid":29099,"cell":"2DDA0100","place":"building","ns":73.14,"ew":-65.6,"dest":{"cell":"039B0177","place":"dungeon","name":"Steaming Hovel"},"maxLevel":20,"desc":"This hovel is home to the thieving Thrungum. Any stolen items found herein should be returned to a Portal Guardian.","id":2270}, + {"name":"Direlands Desert Edge Portal","type":"Portal","wcid":3612,"cell":"2E0E0101","place":"dungeon","dest":{"cell":"231D0029","place":"outdoor","ns":-78.67,"ew":-73.43},"minLevel":23,"desc":"In a dungeon (landblock 2E0E).","id":2271}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"2E110000","place":"outdoor","ns":-88.18,"ew":-64.6,"dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2272}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43559,"cell":"2E110107","place":"building","ns":-87.66,"ew":-65.1,"dest":{"cell":"E3D50001","place":"outdoor","ns":68.5,"ew":79.69},"id":2273}, + {"name":"Twisted Refuge","type":"Portal","wcid":45725,"cell":"2E300020","place":"outdoor","ns":-62.77,"ew":-64.8,"dest":{"cell":"576F01B1","place":"dungeon","name":"Twisted Refuge"},"minLevel":150,"quest":true,"id":2274}, + {"name":"Singular Obsidian Repository","type":"Portal","wcid":12294,"cell":"2E390000","place":"outdoor","ns":-55.93,"ew":-64.79,"dest":{"cell":"039F02F1","place":"dungeon","name":"Singular Obsidian Repository"},"minLevel":45,"id":2275}, + {"name":"South Gate","type":"Portal","wcid":37051,"cell":"2F2E002A","place":"outdoor","ns":-65.01,"ew":-63.81,"dest":{"cell":"00C00242","place":"dungeon","name":"South Gate"},"id":2276}, + {"name":"South Gate","type":"Portal","wcid":37051,"cell":"2F2E002A","place":"outdoor","ns":-64.99,"ew":-63.8,"dest":{"cell":"00C00242","place":"dungeon","name":"South Gate"},"id":2277}, + {"name":"South Gate","type":"Portal","wcid":37051,"cell":"2F2E002A","place":"outdoor","ns":-65.01,"ew":-63.79,"dest":{"cell":"00C00242","place":"dungeon","name":"South Gate"},"id":2278}, + {"name":"Singularity Bore","type":"Portal","wcid":10796,"cell":"2F2F0000","place":"outdoor","ns":-64.1,"ew":-63.83,"dest":{"cell":"02910388","place":"dungeon","name":"Singularity Bore"},"minLevel":50,"id":2279}, + {"name":"Tumerok Dungeon","type":"Portal","wcid":2562,"cell":"30730000","place":"outdoor","ns":-9.6,"ew":-62.94,"dest":{"cell":"01A0013A","place":"dungeon","name":"Tumerok Dungeon"},"id":2280}, + {"name":"Moist Hovel","type":"Portal","wcid":29101,"cell":"30DA0100","place":"building","ns":73.04,"ew":-62.99,"dest":{"cell":"02B90185","place":"dungeon","name":"Moist Hovel"},"maxLevel":20,"desc":"This hovel is home to the thieving Thrungum. Any stolen items found herein should be returned to a Portal Guardian.","id":2281}, + {"name":"Inculcation Cells Portal","type":"Portal","wcid":10734,"cell":"31290000","place":"outdoor","ns":-68.78,"ew":-62.48,"dest":{"cell":"0295026D","place":"dungeon","name":"Inculcation Cells"},"minLevel":40,"id":2282}, + {"name":"Chakron Gate Portal","type":"Portal","wcid":8830,"cell":"313D0000","place":"outdoor","ns":-52.92,"ew":-62.67,"dest":{"cell":"02AE02B3","place":"dungeon","name":"Chakron Gate"},"minLevel":36,"id":2283}, + {"name":"Temple Exit","type":"Portal","wcid":88218,"cell":"31500144","place":"dungeon","dest":{"cell":"3150041D","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 3150).","id":2284}, + {"name":"Temple Exit","type":"Portal","wcid":88218,"cell":"31500338","place":"dungeon","dest":{"cell":"3150041D","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 3150).","id":2285}, + {"name":"Temple Exit","type":"Portal","wcid":88218,"cell":"31500107","place":"dungeon","dest":{"cell":"3150041D","place":"dungeon"},"minLevel":150,"desc":"In a dungeon (landblock 3150).","id":2286}, + {"name":"Viamontian Torture Chamber","type":"Portal","wcid":28713,"cell":"31D6000D","place":"outdoor","ns":69.66,"ew":-62.57,"dest":{"cell":"02EB022F","place":"dungeon","name":"Viamontian Torture Chamber"},"id":2287}, + {"name":"Rossu Morta Chapterhouse","type":"Portal","wcid":33016,"cell":"31D60025","place":"outdoor","ns":69.66,"ew":-62.33,"dest":{"cell":"00800128","place":"dungeon","name":"Rossu Morta Chapterhouse"},"quest":true,"id":2288}, + {"name":"Dardante's Workshop","type":"Portal","wcid":32996,"cell":"31D60154","place":"building","ns":69.59,"ew":-62.69,"dest":{"cell":"007F02EB","place":"dungeon","name":"Dardante's Workshop"},"minLevel":100,"quest":true,"id":2289}, + {"name":"Crystalline Portal","type":"Portal","wcid":40156,"cell":"326A0032","place":"outdoor","ns":-17.0,"ew":-61.26,"dest":{"cell":"00C703A5","place":"dungeon","name":"Crystalline"},"minLevel":70,"id":2290}, + {"name":"Tumerok Mine","type":"Portal","wcid":2331,"cell":"32890000","place":"outdoor","ns":7.96,"ew":-61.29,"dest":{"cell":"01C10234","place":"dungeon","name":"Tumerok Mine"},"minLevel":15,"id":2291}, + {"name":"Destroyed Portal to Redspire","type":"Portal","wcid":11960,"cell":"32D70001","place":"outdoor","ns":70.08,"ew":-61.88,"dest":{"cell":"17B2002A","place":"outdoor","ns":40.56,"ew":-83.0},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2292}, + {"name":"Destroyed Portal to Eastwatch","type":"Portal","wcid":30383,"cell":"32D80034","place":"outdoor","ns":71.24,"ew":-61.33,"dest":{"cell":"49F00013","place":"outdoor","ns":90.34,"ew":-43.26},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2293}, + {"name":"Destroyed Portal to Westwatch","type":"Portal","wcid":30384,"cell":"32D80034","place":"outdoor","ns":71.22,"ew":-61.34,"dest":{"cell":"23DA002C","place":"outdoor","ns":72.83,"ew":-73.37},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2294}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"32D90034","place":"outdoor","ns":72.0,"ew":-61.3,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2295}, + {"name":"Sultry Hovel","type":"Portal","wcid":29095,"cell":"32DB0100","place":"building","ns":74.02,"ew":-61.53,"dest":{"cell":"0114018C","place":"dungeon","name":"Sultry Hovel"},"maxLevel":20,"desc":"This hovel is home to the thieving Thrungum. Any stolen items found herein should be returned to a Portal Guardian.","id":2296}, + {"name":"Cataracts of Sabella","type":"Portal","wcid":30380,"cell":"32DE0033","place":"outdoor","ns":75.9,"ew":-61.34,"dest":{"cell":"22E60029","place":"outdoor","ns":82.1,"ew":-74.2},"id":2297}, + {"name":"Tumideon Fortress Portal","type":"Portal","wcid":8392,"cell":"33390000","place":"outdoor","ns":-55.88,"ew":-60.72,"dest":{"cell":"02C70198","place":"dungeon","name":"Tumideon Fortress"},"minLevel":30,"id":2298}, + {"name":"Penguin Den","type":"Portal","wcid":28793,"cell":"33D90039","place":"outdoor","ns":71.7,"ew":-60.38,"dest":{"cell":"02DD019B","place":"dungeon","name":"Penguin Den"},"id":2299}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"33D90027","place":"outdoor","ns":72.26,"ew":-60.71,"dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2300}, + {"name":"Beacon Tower","type":"Portal","wcid":30536,"cell":"33D90009","place":"outdoor","ns":71.72,"ew":-60.96,"dest":{"cell":"2AE2001C","place":"outdoor","ns":79.2,"ew":-68.0},"id":2301}, + {"name":"Destroyed Portal to Yaraq","type":"Portal","wcid":1030,"cell":"33D90027","place":"outdoor","ns":72.3,"ew":-60.66,"dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2302}, + {"name":"Destroyed Portal to Shoushi","type":"Portal","wcid":1027,"cell":"33D90027","place":"outdoor","ns":72.34,"ew":-60.7,"dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2303}, + {"name":"Yaraq Casino VIP Portal","type":"Portal","wcid":39000,"cell":"33DA002E","place":"outdoor","ns":73.0,"ew":-60.6,"dest":{"cell":"7E64001D","place":"outdoor","ns":-21.5,"ew":-0.8},"quest":true,"id":2304}, + {"name":"Shoushi Casino VIP Portal","type":"Portal","wcid":39002,"cell":"33DA002E","place":"outdoor","ns":73.0,"ew":-60.63,"dest":{"cell":"DB54001E","place":"outdoor","ns":-34.2,"ew":73.6},"quest":true,"id":2305}, + {"name":"Holtburg Casino VIP Portal","type":"Portal","wcid":38998,"cell":"33DA002E","place":"outdoor","ns":73.0,"ew":-60.57,"dest":{"cell":"A9B2001D","place":"outdoor","ns":40.88,"ew":33.6},"quest":true,"id":2306}, + {"name":"Desert Citadel Portal","type":"Portal","wcid":24952,"cell":"34150000","place":"outdoor","ns":-84.8,"ew":-59.7,"dest":{"cell":"61480152","place":"dungeon","name":"Desert Citadel"},"id":2307}, + {"name":"Creepy Chambers Portal","type":"Portal","wcid":4150,"cell":"341B001B","place":"outdoor","ns":-80.09,"ew":-60.02,"dest":{"cell":"004A01F3","place":"dungeon","name":"Creepy Chambers"},"id":2308}, + {"name":"Shendolain Vestibule Portal","type":"Portal","wcid":7949,"cell":"343C0000","place":"outdoor","ns":-53.79,"ew":-59.59,"dest":{"cell":"02E00461","place":"dungeon","name":"Shendolain Vestibule"},"minLevel":60,"id":2309}, + {"name":"Black Ferah's Vault","type":"Portal","wcid":33776,"cell":"344E0015","place":"outdoor","ns":-39.06,"ew":-60.06,"dest":{"cell":"0073045C","place":"dungeon","name":"Black Ferah's Vault"},"minLevel":151,"quest":true,"id":2310}, + {"name":"Precarious Sojourn Exit Portal","type":"Portal","wcid":20626,"cell":"344F0000","place":"outdoor","ns":-38.14,"ew":-60.3,"dest":{"cell":"7E82001B","place":"outdoor","ns":2.33,"ew":-0.83},"id":2311}, + {"name":"Ruschk Iceberg","type":"Portal","wcid":28784,"cell":"34F7001F","place":"outdoor","ns":96.33,"ew":-59.99,"dest":{"cell":"02DE02BE","place":"dungeon","name":"Ruschk Iceberg"},"minLevel":70,"id":2312}, + {"name":"Humid Hovel","type":"Portal","wcid":29102,"cell":"35DB0100","place":"underground","ns":73.57,"ew":-59.2,"dest":{"cell":"02E4017E","place":"dungeon"},"maxLevel":20,"desc":"This hovel is home to the thieving Thrungum. Any stolen items found herein should be returned to a Portal Guardian.","id":2313}, + {"name":"Ruined Empyrean Vault","type":"Portal","wcid":28804,"cell":"35EA002F","place":"outdoor","ns":85.89,"ew":-59.0,"dest":{"cell":"01940119","place":"dungeon","name":"Ruined Empyrean Vault"},"minLevel":70,"id":2314}, + {"name":"Mistress Halmera's Dig","type":"Portal","wcid":32235,"cell":"368A000A","place":"outdoor","ns":8.58,"ew":-58.56,"dest":{"cell":"00410160","place":"dungeon","name":"Mistress Halmera's Dig"},"minLevel":60,"maxLevel":79,"quest":true,"desc":"This dungeon is quest-restricted. Speak with Qath al-Haddash in Qalaba'r to learn more.","id":2315}, + {"name":"Portal to Silyun","type":"Portal","wcid":28708,"cell":"36DF0002","place":"outdoor","ns":76.59,"ew":-58.72,"dest":{"cell":"26EC0035","place":"outdoor","ns":87.3,"ew":-70.9},"id":2316}, + {"name":"Fiun Outpost","type":"Portal","wcid":30381,"cell":"36DF000A","place":"outdoor","ns":76.62,"ew":-58.6,"dest":{"cell":"38F7001B","place":"outdoor","ns":95.88,"ew":-56.77},"desc":"This portal is tied to the Fiun Outpost. This outpost is a good place for characters above level 60.","id":2317}, + {"name":"Cannibal Caverns","type":"Portal","wcid":29512,"cell":"36ED0101","place":"dungeon","dest":{"cell":"002202F2","place":"dungeon"},"minLevel":50,"desc":"In a dungeon (landblock 36ED).","id":2318}, + {"name":"Black Spawn Den","type":"Portal","wcid":7246,"cell":"37340000","place":"outdoor","ns":-60.05,"ew":-57.64,"dest":{"cell":"01030375","place":"dungeon","name":"Black Spawn Den"},"minLevel":20,"id":2319}, + {"name":"Accursed Halls Portal","type":"Portal","wcid":1119,"cell":"37610000","place":"outdoor","ns":-24.03,"ew":-57.87,"dest":{"cell":"01F90101","place":"dungeon","name":"Accursed Halls"},"id":2320}, + {"name":"Walled Portals","type":"Portal","wcid":4203,"cell":"37610000","place":"outdoor","ns":-24.07,"ew":-57.73,"dest":{"cell":"2264000D","place":"outdoor","ns":-21.55,"ew":-74.6},"id":2321}, + {"name":"Forgotten Tunnels","type":"Portal","wcid":43120,"cell":"380A0102","place":"building","ns":-93.56,"ew":-56.6,"dest":{"cell":"8B020292","place":"dungeon","name":"Forgotten Tunnels"},"minLevel":180,"id":2322}, + {"name":"Forgotten Tunnels","type":"Portal","wcid":43118,"cell":"380B0102","place":"dungeon","dest":{"cell":"8B02026B","place":"dungeon","name":"Forgotten Tunnels"},"minLevel":180,"desc":"In a dungeon (landblock 380B).","id":2323}, + {"name":"Forgotten Tunnels","type":"Portal","wcid":43119,"cell":"380B0106","place":"dungeon","dest":{"cell":"8B020282","place":"dungeon","name":"Forgotten Tunnels"},"minLevel":180,"desc":"In a dungeon (landblock 380B).","id":2324}, + {"name":"Mountain Halls","type":"Portal","wcid":3640,"cell":"388C0102","place":"underground","ns":10.11,"ew":-56.7,"dest":{"cell":"019201A8","place":"dungeon"},"minLevel":15,"id":2325}, + {"name":"Frozen Library","type":"Portal","wcid":28778,"cell":"38F0003F","place":"outdoor","ns":90.72,"ew":-56.38,"dest":{"cell":"02FE044E","place":"dungeon","name":"Frozen Library"},"id":2326}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"38F70019","place":"outdoor","ns":95.71,"ew":-56.81,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2327}, + {"name":"Knath Lair","type":"Portal","wcid":3638,"cell":"39410000","place":"outdoor","ns":-49.76,"ew":-56.28,"dest":{"cell":"0193012A","place":"dungeon","name":"Knath Lair"},"id":2328}, + {"name":"Apostate Excavation","type":"Portal","wcid":41195,"cell":"39600105","place":"dungeon","dest":{"cell":"39600107","place":"dungeon"},"minLevel":150,"quest":true,"desc":"This portal leads to the deeper regions of the Apostate Excavation. In a dungeon (landblock 3960).","id":2329}, + {"name":"Surface","type":"Portal","wcid":41196,"cell":"3960018B","place":"dungeon","dest":{"cell":"39600014","place":"outdoor","ns":-24.8,"ew":-56.09},"desc":"In a dungeon (landblock 3960).","id":2330}, + {"name":"Mount Naipenset Caverns","type":"Portal","wcid":5523,"cell":"39860100","place":"building","ns":5.59,"ew":-56.19,"dest":{"cell":"014701E9","place":"dungeon","name":"Mount Naipenset Caverns"},"id":2331}, + {"name":"Icy Hideout","type":"Portal","wcid":70009,"cell":"39EF0003","place":"outdoor","ns":89.5,"ew":-56.3,"dest":{"cell":"0033040F","place":"dungeon","name":"Icy Hideout"},"quest":true,"id":2332}, + {"name":"Portal to Silyun","type":"Portal","wcid":28708,"cell":"39F60010","place":"outdoor","ns":95.63,"ew":-56.21,"dest":{"cell":"26EC0035","place":"outdoor","ns":87.3,"ew":-70.9},"id":2333}, + {"name":"Virindi Fort Portal","type":"Portal","wcid":4921,"cell":"3B320000","place":"outdoor","ns":-61.62,"ew":-54.13,"dest":{"cell":"01400206","place":"dungeon","name":"Virindi Fort"},"minLevel":15,"id":2334}, + {"name":"Town of Dryreach","type":"Portal","wcid":2065,"cell":"3B4D0104","place":"building","ns":-39.81,"ew":-54.59,"dest":{"cell":"DB75003B","place":"outdoor","ns":-8.08,"ew":74.03},"minLevel":12,"id":2335}, + {"name":"Small Complex","type":"Portal","wcid":2335,"cell":"3C4E0000","place":"outdoor","ns":-39.07,"ew":-53.38,"dest":{"cell":"01C00122","place":"dungeon","name":"Small Complex"},"minLevel":40,"id":2336}, + {"name":"Acolyte's Chamber","type":"Portal","wcid":38581,"cell":"3D0B014B","place":"underground","ns":-92.6,"ew":-53.0,"dest":{"cell":"00DD0102","place":"dungeon"},"quest":true,"id":2337}, + {"name":"Chamber of the High Priest's Third","type":"Portal","wcid":38584,"cell":"3D0B0113","place":"underground","ns":-92.6,"ew":-52.6,"dest":{"cell":"00DD0104","place":"dungeon"},"quest":true,"id":2338}, + {"name":"Chamber of the High Priest's First","type":"Portal","wcid":38582,"cell":"3D0B012F","place":"underground","ns":-93.0,"ew":-52.6,"dest":{"cell":"00DD0108","place":"dungeon"},"quest":true,"id":2339}, + {"name":"Chamber of the High Priest's Second","type":"Portal","wcid":38583,"cell":"3D0B0173","place":"underground","ns":-93.0,"ew":-53.0,"dest":{"cell":"00DD0106","place":"dungeon"},"quest":true,"id":2340}, + {"name":"Temple of Tthuun","type":"Portal","wcid":38585,"cell":"3D0B0100","place":"underground","ns":-92.8,"ew":-52.8,"dest":{"cell":"00DF02B9","place":"dungeon"},"minLevel":180,"quest":true,"id":2341}, + {"name":"Direlands Northwest Shore Portal","type":"Portal","wcid":8388,"cell":"3D220000","place":"outdoor","ns":-74.03,"ew":-52.42,"dest":{"cell":"0D86002E","place":"outdoor","ns":5.8,"ew":-91.03},"minLevel":25,"id":2342}, + {"name":"Direlands Valleys Portal","type":"Portal","wcid":8386,"cell":"3D220000","place":"outdoor","ns":-74.16,"ew":-52.39,"dest":{"cell":"30490007","place":"outdoor","ns":-42.91,"ew":-63.53},"minLevel":25,"id":2343}, + {"name":"Burun Cathedral","type":"Portal","wcid":7283,"cell":"3D4A0000","place":"outdoor","ns":-42.31,"ew":-52.6,"dest":{"cell":"02F803FA","place":"dungeon","name":"Burun Cathedral"},"id":2344}, + {"name":"Small Black Hill","type":"Portal","wcid":2329,"cell":"3E310000","place":"outdoor","ns":-62.14,"ew":-52.26,"dest":{"cell":"4031001F","place":"outdoor","ns":-62.12,"ew":-50.45},"id":2345}, + {"name":"Destroyed Glenden Wood Portal","type":"Portal","wcid":1017,"cell":"3E9A0000","place":"outdoor","ns":21.54,"ew":-51.63,"dest":{"cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2346}, + {"name":"Destroyed Plateau Portal","type":"Portal","wcid":4042,"cell":"3EA40000","place":"outdoor","ns":29.34,"ew":-51.96,"dest":{"cell":"49B70021","place":"outdoor","ns":44.54,"ew":-43.13},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2347}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43565,"cell":"3EEB0102","place":"dungeon","dest":{"cell":"E3D10034","place":"outdoor","ns":65.64,"ew":80.28},"desc":"In a dungeon (landblock 3EEB).","id":2348}, + {"name":"Ruschk Icehold","type":"Portal","wcid":29483,"cell":"3EEC002D","place":"outdoor","ns":87.3,"ew":-51.81,"dest":{"cell":"001D012F","place":"dungeon","name":"Ruschk Icehold"},"minLevel":80,"quest":true,"id":2349}, + {"name":"Penguin Cave Hatchery","type":"Portal","wcid":29048,"cell":"3EF5002B","place":"outdoor","ns":94.25,"ew":-51.76,"dest":{"cell":"01CB0360","place":"dungeon","name":"Penguin Cave Hatchery"},"minLevel":90,"id":2350}, + {"name":"Temple of the Black Spear","type":"Portal","wcid":87627,"cell":"3EF6000D","place":"outdoor","ns":95.34,"ew":-52.24,"dest":{"cell":"004F0343","place":"dungeon","name":"Temple of the Black Spear"},"minLevel":130,"quest":true,"id":2351}, + {"name":"Frigid Grotto","type":"Portal","wcid":46304,"cell":"3EF8002F","place":"outdoor","ns":97.09,"ew":-51.78,"dest":{"cell":"584D035A","place":"dungeon","name":"Frigid Grotto"},"minLevel":150,"id":2352}, + {"name":"Colossus Foundry Portal","type":"Portal","wcid":19715,"cell":"3F310100","place":"building","ns":-61.99,"ew":-51.32,"dest":{"cell":"545701C5","place":"dungeon","name":"Colossus Foundry"},"id":2353}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"3F310017","place":"outdoor","ns":-62.06,"ew":-51.3,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2354}, + {"name":"Disaster Maze","type":"Portal","wcid":2385,"cell":"3F320000","place":"outdoor","ns":-61.26,"ew":-50.94,"dest":{"cell":"01A60214","place":"dungeon","name":"Disaster Maze"},"minLevel":20,"id":2355}, + {"name":"Arrival Chamber","type":"Portal","wcid":41234,"cell":"3FB10107","place":"underground","ns":38.45,"ew":-49.98,"dest":{"cell":"3FB10110","place":"underground","ns":38.36,"ew":-49.41},"id":2356}, + {"name":"Surface","type":"Portal","wcid":41235,"cell":"3FB1010D","place":"underground","ns":38.36,"ew":-49.44,"dest":{"cell":"3FB10024","place":"outdoor","ns":39.99,"ew":-51.12},"id":2357}, + {"name":"Reaving Facility","type":"Portal","wcid":41233,"cell":"3FB10159","place":"underground","ns":39.33,"ew":-50.58,"dest":{"cell":"3FB10175","place":"underground","ns":38.7,"ew":-50.4},"minLevel":150,"quest":true,"desc":"This portal leads to the Apostate Reaving Facility.","id":2358}, + {"name":"Surface","type":"Portal","wcid":41235,"cell":"3FB10172","place":"underground","ns":38.74,"ew":-50.4,"dest":{"cell":"3FB10024","place":"outdoor","ns":39.99,"ew":-51.12},"id":2359}, + {"name":"Destroyed Portal to Zaikhal","type":"Portal","wcid":1032,"cell":"3FE7000B","place":"outdoor","ns":83.11,"ew":-51.4,"dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2360}, + {"name":"Portal to Silyun","type":"Portal","wcid":28708,"cell":"3FF00026","place":"outdoor","ns":90.62,"ew":-51.12,"dest":{"cell":"26EC0035","place":"outdoor","ns":87.3,"ew":-70.9},"id":2361}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43577,"cell":"400A0102","place":"dungeon","dest":{"cell":"E3D2002D","place":"outdoor","ns":66.55,"ew":80.21},"desc":"In a dungeon (landblock 400A).","id":2362}, + {"name":"Sho Roadside","type":"Portal","wcid":1907,"cell":"40310000","place":"outdoor","ns":-62.64,"ew":-50.18,"dest":{"cell":"D45C003D","place":"outdoor","ns":-27.92,"ew":68.38},"id":2363}, + {"name":"Black Hill","type":"Portal","wcid":2328,"cell":"40310000","place":"outdoor","ns":-62.21,"ew":-50.54,"dest":{"cell":"3E310004","place":"outdoor","ns":-62.36,"ew":-52.3},"id":2364}, + {"name":"Small Black Hill","type":"Portal","wcid":2329,"cell":"40310000","place":"outdoor","ns":-62.01,"ew":-50.04,"dest":{"cell":"4031001F","place":"outdoor","ns":-62.12,"ew":-50.45},"id":2365}, + {"name":"Small Hill Base","type":"Portal","wcid":2330,"cell":"40310000","place":"outdoor","ns":-62.06,"ew":-50.36,"dest":{"cell":"40310040","place":"outdoor","ns":-62.0,"ew":-50.02},"id":2366}, + {"name":"Sclavus Umbral Forge","type":"Portal","wcid":32830,"cell":"40AA0100","place":"dungeon","dest":{"cell":"00E3040C","place":"dungeon"},"minLevel":60,"quest":true,"desc":"In a dungeon (landblock 40AA).","id":2367}, + {"name":"Destroyed Portal to Zaikhal","type":"Portal","wcid":1032,"cell":"40E6002A","place":"outdoor","ns":82.2,"ew":-50.21,"dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2368}, + {"name":"Destroyed Portal to Zaikhal","type":"Portal","wcid":1032,"cell":"40E8001D","place":"outdoor","ns":84.08,"ew":-50.42,"dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2369}, + {"name":"Abhorrent Vault","type":"Portal","wcid":28806,"cell":"40EE0021","place":"outdoor","ns":88.5,"ew":-50.28,"dest":{"cell":"02D40260","place":"dungeon","name":"Abhorrent Vault"},"minLevel":90,"id":2370}, + {"name":"Lugian Ice Tunnels","type":"Portal","wcid":29481,"cell":"40F40031","place":"outdoor","ns":93.31,"ew":-50.1,"dest":{"cell":"001C0105","place":"dungeon","name":"Lugian Ice Tunnels"},"minLevel":80,"quest":true,"id":2371}, + {"name":"Dungeon of Corpses Portal","type":"Portal","wcid":7202,"cell":"41390100","place":"dungeon","dest":{"cell":"01090160","place":"dungeon"},"minLevel":25,"desc":"In a dungeon (landblock 4139).","id":2372}, + {"name":"Strange Swamp Temple","type":"Portal","wcid":87633,"cell":"414B0103","place":"dungeon","dest":{"cell":"008603AC","place":"dungeon"},"desc":"In a dungeon (landblock 414B).","id":2373}, + {"name":"Blighted Desolation Moarsman Tunnels","type":"Portal","wcid":38157,"cell":"41DD0013","place":"outdoor","ns":75.1,"ew":-49.66,"dest":{"cell":"00C4037C","place":"dungeon","name":"Blighted Desolation Moarsman Tunnels"},"minLevel":75,"id":2374}, + {"name":"Destroyed Portal to Zaikhal","type":"Portal","wcid":1032,"cell":"41E70036","place":"outdoor","ns":83.39,"ew":-49.3,"dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2375}, + {"name":"South Direlands Portal","type":"Portal","wcid":1107,"cell":"421D0000","place":"outdoor","ns":-77.97,"ew":-48.67,"dest":{"cell":"5416001A","place":"outdoor","ns":-84.2,"ew":-34.44},"minLevel":12,"id":2376}, + {"name":"Desert Ridge Border","type":"Portal","wcid":1903,"cell":"421D0000","place":"outdoor","ns":-78.06,"ew":-48.58,"dest":{"cell":"B178001C","place":"outdoor","ns":-5.64,"ew":39.96},"id":2377}, + {"name":"Vesayen Isles Portal","type":"Portal","wcid":8618,"cell":"42490000","place":"outdoor","ns":-43.26,"ew":-49.05,"dest":{"cell":"E5240007","place":"outdoor","ns":-72.51,"ew":81.3},"id":2378}, + {"name":"Mosswart Worship Cavern","type":"Portal","wcid":87735,"cell":"424C0019","place":"outdoor","ns":-41.07,"ew":-48.76,"dest":{"cell":"00B501FF","place":"dungeon","name":"Mosswart Worship Cavern"},"minLevel":80,"id":2379}, + {"name":"Sclavus Keep Portal","type":"Portal","wcid":4140,"cell":"424E0102","place":"building","ns":-38.89,"ew":-48.44,"dest":{"cell":"01860247","place":"dungeon","name":"Sclavus Keep"},"minLevel":15,"id":2380}, + {"name":"Ravenous Vault","type":"Portal","wcid":28802,"cell":"42F30014","place":"outdoor","ns":92.83,"ew":-48.92,"dest":{"cell":"039D02A4","place":"dungeon","name":"Ravenous Vault"},"minLevel":110,"id":2381}, + {"name":"Isle of Tears Portal","type":"Portal","wcid":1112,"cell":"43150103","place":"building","ns":-85.0,"ew":-47.78,"dest":{"cell":"C09B0015","place":"outdoor","ns":22.55,"ew":51.92},"id":2382}, + {"name":"Path of the Blind","type":"Portal","wcid":30971,"cell":"43F1001B","place":"outdoor","ns":91.12,"ew":-47.99,"dest":{"cell":"002A034A","place":"dungeon","name":"Path of the Blind"},"minLevel":140,"id":2383}, + {"name":"Path of the Blind West","type":"Portal","wcid":31924,"cell":"43F1001B","place":"outdoor","ns":91.11,"ew":-48.02,"dest":{"cell":"004B034A","place":"dungeon","name":"Path of the Blind West"},"minLevel":140,"id":2384}, + {"name":"Path of the Blind East","type":"Portal","wcid":31925,"cell":"43F1001B","place":"outdoor","ns":91.1,"ew":-47.95,"dest":{"cell":"00E1034A","place":"dungeon","name":"Path of the Blind East"},"minLevel":140,"id":2385}, + {"name":"Egg Orchard West","type":"Portal","wcid":31928,"cell":"43F7000E","place":"outdoor","ns":96.19,"ew":-48.15,"dest":{"cell":"00C80371","place":"dungeon","name":"Egg Orchard West"},"minLevel":140,"id":2386}, + {"name":"Egg Orchard","type":"Portal","wcid":30964,"cell":"43F70016","place":"outdoor","ns":96.2,"ew":-48.1,"dest":{"cell":"002B0371","place":"dungeon","name":"Egg Orchard"},"minLevel":140,"id":2387}, + {"name":"Egg Orchard East","type":"Portal","wcid":31926,"cell":"43F7001E","place":"outdoor","ns":96.19,"ew":-48.03,"dest":{"cell":"00640371","place":"dungeon","name":"Egg Orchard East"},"minLevel":140,"id":2388}, + {"name":"Insatiable Vault","type":"Portal","wcid":28808,"cell":"43F9001A","place":"outdoor","ns":97.36,"ew":-48.02,"dest":{"cell":"00960321","place":"dungeon","name":"Insatiable Vault"},"minLevel":125,"id":2389}, + {"name":"Elemental Caverns","type":"Portal","wcid":25605,"cell":"44180000","place":"outdoor","ns":-82.56,"ew":-47.54,"dest":{"cell":"5F470412","place":"dungeon","name":"Elemental Caverns"},"quest":true,"id":2390}, + {"name":"Incunabula Vault Portal","type":"Portal","wcid":6393,"cell":"44520000","place":"outdoor","ns":-35.85,"ew":-47.23,"dest":{"cell":"011A03F9","place":"dungeon","name":"Incunabula Vault"},"id":2391}, + {"name":"Augmentation Realm Upper Level","type":"Portal","wcid":30061,"cell":"44F60022","place":"outdoor","ns":94.96,"ew":-47.09,"dest":{"cell":"006D0413","place":"dungeon","name":"Augmentation Realm Upper Level"},"minLevel":125,"quest":true,"id":2392}, + {"name":"Halls of Metos","type":"Portal","wcid":7295,"cell":"45320000","place":"outdoor","ns":-61.32,"ew":-46.68,"dest":{"cell":"02F50297","place":"dungeon","name":"Halls of Metos"},"minLevel":15,"id":2393}, + {"name":"Font of the Eternal Harvester","type":"Portal","wcid":31670,"cell":"454A0102","place":"dungeon","dest":{"cell":"00380285","place":"dungeon"},"minLevel":80,"desc":"In a dungeon (landblock 454A).","id":2394}, + {"name":"Swamp Temple","type":"Portal","wcid":2556,"cell":"4550011F","place":"underground","ns":-37.58,"ew":-46.08,"dest":{"cell":"019C02A7","place":"dungeon"},"minLevel":15,"id":2395}, + {"name":"Malignant Tabernacle","type":"Portal","wcid":14886,"cell":"45620000","place":"outdoor","ns":-23.21,"ew":-46.0,"dest":{"cell":"536C0280","place":"dungeon","name":"Malignant Tabernacle"},"minLevel":40,"id":2396}, + {"name":"Abayar's Laboratory","type":"Portal","wcid":28825,"cell":"45F20026","place":"outdoor","ns":92.16,"ew":-46.3,"dest":{"cell":"018E037B","place":"dungeon","name":"Abayar's Laboratory"},"id":2397}, + {"name":"Destroyed Portal to Zaikhal","type":"Portal","wcid":1032,"cell":"46180105","place":"dungeon","dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 4618).","id":2398}, + {"name":"Artifex Vault Portal","type":"Portal","wcid":6391,"cell":"46A00000","place":"outdoor","ns":26.48,"ew":-45.77,"dest":{"cell":"01370341","place":"dungeon","name":"Artifex Vault"},"id":2399}, + {"name":"Frozen Refuge","type":"Portal","wcid":45727,"cell":"46F4002F","place":"outdoor","ns":93.94,"ew":-45.44,"dest":{"cell":"5770015B","place":"dungeon","name":"Frozen Refuge"},"minLevel":150,"quest":true,"id":2400}, + {"name":"Graveyard","type":"Portal","wcid":38728,"cell":"472D0106","place":"dungeon","dest":{"cell":"482D003E","place":"outdoor","ns":-65.41,"ew":-43.62},"desc":"In Massilor's Crypt.","id":2401}, + {"name":"Sho Roadside","type":"Portal","wcid":1907,"cell":"47E40000","place":"outdoor","ns":80.6,"ew":-44.38,"dest":{"cell":"D45C003D","place":"outdoor","ns":-27.92,"ew":68.38},"id":2402}, + {"name":"Dark Design","type":"Portal","wcid":30960,"cell":"47F40016","place":"outdoor","ns":93.81,"ew":-44.91,"dest":{"cell":"002D0373","place":"dungeon","name":"Dark Design"},"minLevel":140,"id":2403}, + {"name":"Massilor's Crypt","type":"Portal","wcid":38729,"cell":"482D003E","place":"outdoor","ns":-65.38,"ew":-43.6,"dest":{"cell":"472D0107","place":"dungeon","name":"Massilor's Crypt"},"minLevel":180,"quest":true,"id":2404}, + {"name":"Mhoire Armory","type":"Portal","wcid":37489,"cell":"482E0140","place":"building","ns":-64.81,"ew":-44.28,"dest":{"cell":"00EA04DD","place":"dungeon","name":"Mhoire Armory"},"minLevel":160,"quest":true,"id":2405}, + {"name":"Gardens of Menilesh","type":"Portal","wcid":38086,"cell":"482E002D","place":"outdoor","ns":-64.69,"ew":-43.79,"dest":{"cell":"00E70283","place":"dungeon","name":"Gardens of Menilesh"},"minLevel":150,"quest":true,"desc":"This portal leads to the ancient, ruined Gardens of Menilesh.","id":2406}, + {"name":"Count Phainor's Tomb","type":"Portal","wcid":48778,"cell":"482E0131","place":"building","ns":-65.0,"ew":-44.02,"dest":{"cell":"58620396","place":"dungeon","name":"Count Phainor's Tomb"},"minLevel":180,"id":2407}, + {"name":"Western Power Forge","type":"Portal","wcid":30470,"cell":"48640000","place":"outdoor","ns":-21.89,"ew":-43.8,"dest":{"cell":"00060100","place":"dungeon","name":"Western Power Forge"},"minLevel":100,"id":2408}, + {"name":"Virindi Research Facility","type":"Portal","wcid":46012,"cell":"48B5002D","place":"outdoor","ns":43.26,"ew":-43.75,"dest":{"cell":"56550318","place":"dungeon","name":"Virindi Research Facility"},"minLevel":150,"id":2409}, + {"name":"Plateau Top","type":"Portal","wcid":2549,"cell":"48B80000","place":"outdoor","ns":45.26,"ew":-44.23,"dest":{"cell":"49B60008","place":"outdoor","ns":44.41,"ew":-43.5},"id":2410}, + {"name":"South Direlands Portal","type":"Portal","wcid":1107,"cell":"49240000","place":"outdoor","ns":-72.66,"ew":-43.14,"dest":{"cell":"5416001A","place":"outdoor","ns":-84.2,"ew":-34.44},"minLevel":12,"id":2411}, + {"name":"North Desert Edge","type":"Portal","wcid":1905,"cell":"49240000","place":"outdoor","ns":-72.72,"ew":-43.23,"dest":{"cell":"7B790025","place":"outdoor","ns":-4.69,"ew":-3.07},"id":2412}, + {"name":"Up to Arcanum Lookout","type":"Portal","wcid":40919,"cell":"492D0017","place":"outdoor","ns":-65.3,"ew":-43.3,"dest":{"cell":"492D0017","place":"outdoor","ns":-65.3,"ew":-43.3},"minLevel":50,"id":2413}, + {"name":"Down to Surface","type":"Portal","wcid":40920,"cell":"492D0017","place":"outdoor","ns":-65.33,"ew":-43.3,"dest":{"cell":"492D000F","place":"outdoor","ns":-65.28,"ew":-43.39},"id":2414}, + {"name":"Master Alizari's Dig","type":"Portal","wcid":32233,"cell":"4997001D","place":"outdoor","ns":19.34,"ew":-43.19,"dest":{"cell":"004002E0","place":"dungeon","name":"Master Alizari's Dig"},"minLevel":40,"maxLevel":59,"quest":true,"desc":"This dungeon is quest-restricted. Speak with Qath al-Haddash in Qalaba'r to learn more.","id":2415}, + {"name":"Plateau Top","type":"Portal","wcid":2549,"cell":"49B50000","place":"outdoor","ns":43.24,"ew":-43.27,"dest":{"cell":"49B60008","place":"outdoor","ns":44.41,"ew":-43.5},"id":2416}, + {"name":"Inner Dungeon","type":"Portal","wcid":2551,"cell":"49B50000","place":"outdoor","ns":43.53,"ew":-43.36,"dest":{"cell":"01A5019D","place":"dungeon","name":"Inner Dungeon"},"id":2417}, + {"name":"Plateau Base","type":"Portal","wcid":2550,"cell":"49B60000","place":"outdoor","ns":44.37,"ew":-43.5,"dest":{"cell":"48B80001","place":"outdoor","ns":45.3,"ew":-44.26},"id":2418}, + {"name":"Mammet Foundry Portal","type":"Portal","wcid":19716,"cell":"49B6012C","place":"building","ns":44.25,"ew":-43.38,"dest":{"cell":"5458025F","place":"dungeon","name":"Mammet Foundry"},"id":2419}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"49B60000","place":"outdoor","ns":44.01,"ew":-43.11,"dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"id":2420}, + {"name":"Portal to Town Network","type":"Portal","wcid":43065,"cell":"49B60007","place":"outdoor","ns":44.26,"ew":-43.46,"dest":{"cell":"00070143","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2421}, + {"name":"Destroyed Portal to Sanamar","type":"Portal","wcid":28709,"cell":"49F0001B","place":"outdoor","ns":90.28,"ew":-43.2,"dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2422}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"49F0001C","place":"outdoor","ns":90.36,"ew":-43.19,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":2423}, + {"name":"Undead Temple","type":"Portal","wcid":28788,"cell":"49F10019","place":"outdoor","ns":90.89,"ew":-43.19,"dest":{"cell":"03A502E2","place":"dungeon","name":"Undead Temple"},"id":2424}, + {"name":"Thrungus Hole","type":"Portal","wcid":30963,"cell":"49F50100","place":"building","ns":94.11,"ew":-42.97,"dest":{"cell":"002902E7","place":"dungeon","name":"Thrungus Hole"},"minLevel":126,"id":2425}, + {"name":"South Direlands Portal","type":"Portal","wcid":1107,"cell":"4A1B0000","place":"outdoor","ns":-80.08,"ew":-42.43,"dest":{"cell":"5416001A","place":"outdoor","ns":-84.2,"ew":-34.44},"minLevel":12,"id":2426}, + {"name":"North Direlands Portal","type":"Portal","wcid":1104,"cell":"4A1B0000","place":"outdoor","ns":-80.16,"ew":-42.34,"dest":{"cell":"3C9D0010","place":"outdoor","ns":24.45,"ew":-53.85},"minLevel":12,"id":2427}, + {"name":"Adams' Beach Portal","type":"Portal","wcid":12466,"cell":"4AB80000","place":"outdoor","ns":45.43,"ew":-42.27,"dest":{"cell":"3DC7001B","place":"outdoor","ns":57.52,"ew":-52.84},"id":2428}, + {"name":"Lithaenean Cottages Portal","type":"Portal","wcid":12514,"cell":"4AB80000","place":"outdoor","ns":45.4,"ew":-42.26,"dest":{"cell":"52C10010","place":"outdoor","ns":53.17,"ew":-36.2},"id":2429}, + {"name":"Plateau Hollow Settlement Portal","type":"Portal","wcid":12538,"cell":"4AB80000","place":"outdoor","ns":45.36,"ew":-42.26,"dest":{"cell":"4EAC0022","place":"outdoor","ns":35.8,"ew":-39.08},"id":2430}, + {"name":"Rivermouth Villas Portal","type":"Portal","wcid":13123,"cell":"4AB80000","place":"outdoor","ns":45.46,"ew":-42.28,"dest":{"cell":"40BF0030","place":"outdoor","ns":51.58,"ew":-50.22},"id":2431}, + {"name":"Zatara Portal","type":"Portal","wcid":14294,"cell":"4AB80000","place":"outdoor","ns":45.34,"ew":-42.28,"dest":{"cell":"ABDE0024","place":"outdoor","ns":76.0,"ew":35.32},"id":2432}, + {"name":"Auralla Settlement Portal","type":"Portal","wcid":14254,"cell":"4AB80000","place":"outdoor","ns":45.32,"ew":-42.3,"dest":{"cell":"46C0001B","place":"outdoor","ns":51.93,"ew":-45.6},"id":2433}, + {"name":"Dire's Edge Portal","type":"Portal","wcid":13098,"cell":"4AB80000","place":"outdoor","ns":45.48,"ew":-42.3,"dest":{"cell":"3B9C002B","place":"outdoor","ns":23.07,"ew":-54.23},"id":2434}, + {"name":"Rahvard Square Portal","type":"Portal","wcid":14659,"cell":"4AB80000","place":"outdoor","ns":45.33,"ew":-42.33,"dest":{"cell":"4DC00025","place":"outdoor","ns":52.12,"ew":-39.89},"id":2435}, + {"name":"Rhynntal Cottages Portal","type":"Portal","wcid":14661,"cell":"4AB80000","place":"outdoor","ns":45.36,"ew":-42.4,"dest":{"cell":"4EBA0013","place":"outdoor","ns":47.12,"ew":-39.31},"id":2436}, + {"name":"Yee Villas Portal","type":"Portal","wcid":14678,"cell":"4AB80000","place":"outdoor","ns":45.39,"ew":-42.41,"dest":{"cell":"52AB0014","place":"outdoor","ns":35.2,"ew":-36.07},"id":2437}, + {"name":"East Morntide Villas Portal","type":"Portal","wcid":14623,"cell":"4AB80000","place":"outdoor","ns":45.42,"ew":-42.4,"dest":{"cell":"6FAF0025","place":"outdoor","ns":38.46,"ew":-12.7},"id":2438}, + {"name":"Fadsahil Settlement Portal","type":"Portal","wcid":14630,"cell":"4AB80000","place":"outdoor","ns":45.33,"ew":-42.37,"dest":{"cell":"48BC0024","place":"outdoor","ns":48.84,"ew":-43.93},"id":2439}, + {"name":"Aloria Portal","type":"Portal","wcid":15140,"cell":"4AB80000","place":"outdoor","ns":45.45,"ew":-42.43,"dest":{"cell":"5EBE001B","place":"outdoor","ns":50.32,"ew":-26.42},"id":2440}, + {"name":"Stormtree Villas Portal","type":"Portal","wcid":15194,"cell":"4AB80000","place":"outdoor","ns":45.48,"ew":-42.46,"dest":{"cell":"53C50024","place":"outdoor","ns":55.99,"ew":-35.14},"id":2441}, + {"name":"Caerlin Cottages Portal","type":"Portal","wcid":15148,"cell":"4AB80000","place":"outdoor","ns":45.5,"ew":-42.33,"dest":{"cell":"41C4001C","place":"outdoor","ns":55.22,"ew":-49.57},"id":2442}, + {"name":"Last-Stop-Before-Dires Villas Portal","type":"Portal","wcid":15169,"cell":"4AB80000","place":"outdoor","ns":45.53,"ew":-42.37,"dest":{"cell":"459C0024","place":"outdoor","ns":23.17,"ew":-46.25},"id":2443}, + {"name":"Wolfenvale Portal","type":"Portal","wcid":15201,"cell":"4AB80000","place":"outdoor","ns":45.56,"ew":-42.4,"dest":{"cell":"5BA6001B","place":"outdoor","ns":31.09,"ew":-28.76},"id":2444}, + {"name":"Rytheran Dale Portal","type":"Portal","wcid":15681,"cell":"4AB80000","place":"outdoor","ns":45.49,"ew":-42.49,"dest":{"cell":"52B8001C","place":"outdoor","ns":45.56,"ew":-36.04},"id":2445}, + {"name":"Wilomine Villas Portal","type":"Portal","wcid":15686,"cell":"4AB80000","place":"outdoor","ns":45.5,"ew":-42.51,"dest":{"cell":"42AE000C","place":"outdoor","ns":37.62,"ew":-48.96},"id":2446}, + {"name":"Hero's Vale Portal","type":"Portal","wcid":15676,"cell":"4AB80000","place":"outdoor","ns":45.59,"ew":-42.42,"dest":{"cell":"46A5002E","place":"outdoor","ns":30.57,"ew":-45.4},"id":2447}, + {"name":"Two Hills Cottages Portal","type":"Portal","wcid":19163,"cell":"4AB80000","place":"outdoor","ns":45.62,"ew":-42.44,"dest":{"cell":"56B0002C","place":"outdoor","ns":39.24,"ew":-32.62},"id":2448}, + {"name":"Tyrrin Cottages Portal","type":"Portal","wcid":19164,"cell":"4AB80000","place":"outdoor","ns":45.51,"ew":-42.54,"dest":{"cell":"5AB40024","place":"outdoor","ns":42.45,"ew":-29.54},"id":2449}, + {"name":"Nanjou Shou-jen Academy","type":"Portal","wcid":46545,"cell":"4AE10118","place":"building","ns":78.08,"ew":-42.2,"dest":{"cell":"576602B8","place":"dungeon","name":"Nanjou Shou-jen Academy"},"minLevel":200,"quest":true,"id":2450}, + {"name":"Falatacot Temple","type":"Portal","wcid":46597,"cell":"4AE20018","place":"outdoor","ns":79.6,"ew":-42.53,"dest":{"cell":"665E021E","place":"dungeon","name":"Falatacot Temple"},"minLevel":200,"id":2451}, + {"name":"Hoshino Tower","type":"Portal","wcid":46620,"cell":"4AE30016","place":"outdoor","ns":80.18,"ew":-42.45,"dest":{"cell":"66510103","place":"dungeon","name":"Hoshino Tower"},"minLevel":200,"quest":true,"id":2452}, + {"name":"Coral Caves","type":"Portal","wcid":31326,"cell":"4AF00015","place":"outdoor","ns":90.49,"ew":-42.46,"dest":{"cell":"003303D2","place":"dungeon","name":"Icy Hideout"},"id":2453}, + {"name":"Blighted Verdant Moarsman Tunnels","type":"Portal","wcid":38153,"cell":"4AF3001B","place":"outdoor","ns":92.7,"ew":-42.36,"dest":{"cell":"00C6037C","place":"dungeon","name":"Blighted Verdant Moarsman Tunnels"},"minLevel":125,"id":2454}, + {"name":"Feeding Tubes","type":"Portal","wcid":30966,"cell":"4AF8001B","place":"outdoor","ns":96.68,"ew":-42.38,"dest":{"cell":"002E02D1","place":"dungeon","name":"Feeding Tubes"},"minLevel":130,"id":2455}, + {"name":"Northern Manumet Plains Portal","type":"Portal","wcid":11956,"cell":"4BB70000","place":"outdoor","ns":44.5,"ew":-41.78,"dest":{"cell":"2ABE000D","place":"outdoor","ns":50.48,"ew":-68.15},"minLevel":25,"id":2456}, + {"name":"Venerable Mausoleum","type":"Portal","wcid":46440,"cell":"4BE20011","place":"outdoor","ns":78.88,"ew":-41.68,"dest":{"cell":"577103E3","place":"dungeon","name":"Venerable Mausoleum"},"minLevel":200,"id":2457}, + {"name":"Viamontian Royal Prison","type":"Portal","wcid":29485,"cell":"4BF2001C","place":"outdoor","ns":92.0,"ew":-41.6,"dest":{"cell":"001E029B","place":"dungeon","name":"Viamontian Royal Prison"},"minLevel":80,"quest":true,"id":2458}, + {"name":"Hoshino Tower","type":"Portal","wcid":46619,"cell":"4CE2003C","place":"outdoor","ns":79.2,"ew":-40.42,"dest":{"cell":"66510103","place":"dungeon","name":"Hoshino Tower"},"minLevel":200,"quest":true,"id":2459}, + {"name":"Samurai Hausu","type":"Portal","wcid":49449,"cell":"4CE20102","place":"building","ns":79.62,"ew":-40.8,"dest":{"cell":"586401F7","place":"dungeon","name":"Samurai Hausu"},"minLevel":200,"id":2460}, + {"name":"Convergent Median","type":"Portal","wcid":14884,"cell":"4D120000","place":"outdoor","ns":-87.04,"ew":-40.26,"dest":{"cell":"536B0206","place":"dungeon","name":"Convergent Median"},"minLevel":40,"id":2461}, + {"name":"Curator of Torment's Study","type":"Portal","wcid":51402,"cell":"4E1C001E","place":"outdoor","ns":-78.97,"ew":-39.21,"dest":{"cell":"587002FA","place":"dungeon","name":"Curator of Torment's Study"},"minLevel":180,"id":2462}, + {"name":"Shendolain Vestibule Portal","type":"Portal","wcid":7949,"cell":"4E320000","place":"outdoor","ns":-61.31,"ew":-39.49,"dest":{"cell":"02E00461","place":"dungeon","name":"Shendolain Vestibule"},"minLevel":60,"id":2463}, + {"name":"Forgotten Chasm","type":"Portal","wcid":30968,"cell":"4EF50025","place":"outdoor","ns":94.53,"ew":-39.1,"dest":{"cell":"002C029C","place":"dungeon","name":"Forgotten Chasm"},"minLevel":130,"id":2464}, + {"name":"Frozen Recess","type":"Portal","wcid":52221,"cell":"4EF60022","place":"outdoor","ns":95.04,"ew":-39.07,"dest":{"cell":"595E02B4","place":"dungeon","name":"Frozen Recess"},"minLevel":180,"id":2465}, + {"name":"Dardante's Keep","type":"Portal","wcid":73068,"cell":"4FF10128","place":"building","ns":91.3,"ew":-38.41,"dest":{"cell":"004805D4","place":"dungeon","name":"Viamontian Direlands Mine"},"minLevel":100,"id":2466}, + {"name":"Slaughterhouse","type":"Portal","wcid":2359,"cell":"501A0000","place":"outdoor","ns":-80.57,"ew":-37.43,"dest":{"cell":"1B7F0018","place":"outdoor","ns":0.43,"ew":-80.08},"id":2467}, + {"name":"Destroyed Qalaba'r Portal","type":"Portal","wcid":1023,"cell":"51180000","place":"outdoor","ns":-82.19,"ew":-36.52,"dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2468}, + {"name":"Tumerok Chamber","type":"Portal","wcid":2333,"cell":"51190100","place":"building","ns":-81.63,"ew":-36.66,"dest":{"cell":"01BC011D","place":"dungeon","name":"Tumerok Chamber"},"id":2469}, + {"name":"Colton Reeyan's Sanctuary","type":"Portal","wcid":47840,"cell":"519C0009","place":"outdoor","ns":22.93,"ew":-37.04,"dest":{"cell":"58600196","place":"dungeon","name":"Colton Reeyan's Sanctuary"},"minLevel":150,"id":2470}, + {"name":"Tumerok Outpost","type":"Portal","wcid":2337,"cell":"519D0100","place":"building","ns":23.7,"ew":-36.57,"dest":{"cell":"01BF01A3","place":"dungeon","name":"Tumerok Outpost"},"minLevel":15,"id":2471}, + {"name":"Destroyed Sawato Portal","type":"Portal","wcid":4043,"cell":"52230000","place":"outdoor","ns":-73.48,"ew":-36.16,"dest":{"cell":"C95B0001","place":"outdoor","ns":-29.15,"ew":58.91},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2472}, + {"name":"Cold Feet Portal","type":"Portal","wcid":14927,"cell":"52690100","place":"dungeon","dest":{"cell":"C4A80024","place":"outdoor","ns":32.77,"ew":55.25},"desc":"In Wedding Trials Dungeon.","id":2473}, + {"name":"Cold Feet Portal","type":"Portal","wcid":14927,"cell":"52690109","place":"dungeon","dest":{"cell":"C4A80024","place":"outdoor","ns":32.77,"ew":55.25},"desc":"In Wedding Trials Dungeon.","id":2474}, + {"name":"Cold Feet Portal","type":"Portal","wcid":14927,"cell":"5269017A","place":"dungeon","dest":{"cell":"C4A80024","place":"outdoor","ns":32.77,"ew":55.25},"desc":"In Wedding Trials Dungeon.","id":2475}, + {"name":"Cold Feet Portal","type":"Portal","wcid":14927,"cell":"526901A8","place":"dungeon","dest":{"cell":"C4A80024","place":"outdoor","ns":32.77,"ew":55.25},"desc":"In Wedding Trials Dungeon.","id":2476}, + {"name":"Surface Portal","type":"Portal","wcid":14929,"cell":"526901AB","place":"dungeon","dest":{"cell":"C4A80024","place":"outdoor","ns":32.77,"ew":55.25},"desc":"In Wedding Trials Dungeon.","id":2477}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526A0100","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In a dungeon (landblock 526A).","id":2478}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526A0134","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In a dungeon (landblock 526A).","id":2479}, + {"name":"Portal Space","type":"Portal","wcid":14815,"cell":"526A01C7","place":"dungeon","dest":{"cell":"526C025C","place":"dungeon","name":"Entrance to Portal Space"},"desc":"In a dungeon (landblock 526A).","id":2480}, + {"name":"Portal Space","type":"Portal","wcid":14816,"cell":"526A01CF","place":"dungeon","dest":{"cell":"526C02A9","place":"dungeon","name":"Entrance to Portal Space"},"desc":"In a dungeon (landblock 526A).","id":2481}, + {"name":"Portal Space","type":"Portal","wcid":14818,"cell":"526A01DD","place":"dungeon","dest":{"cell":"526C01E8","place":"dungeon","name":"Entrance to Portal Space"},"desc":"In a dungeon (landblock 526A).","id":2482}, + {"name":"Portal Space","type":"Portal","wcid":14817,"cell":"526A01E5","place":"dungeon","dest":{"cell":"526C025F","place":"dungeon","name":"Entrance to Portal Space"},"desc":"In a dungeon (landblock 526A).","id":2483}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526A01EB","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In a dungeon (landblock 526A).","id":2484}, + {"name":"Portal Space","type":"Portal","wcid":14820,"cell":"526A01F7","place":"dungeon","dest":{"cell":"526B029E","place":"dungeon"},"desc":"In a dungeon (landblock 526A).","id":2485}, + {"name":"Portal Space","type":"Portal","wcid":14821,"cell":"526A0223","place":"dungeon","dest":{"cell":"526B0241","place":"dungeon"},"desc":"In a dungeon (landblock 526A).","id":2486}, + {"name":"Portal Space","type":"Portal","wcid":14819,"cell":"526A023E","place":"dungeon","dest":{"cell":"526B02DE","place":"dungeon"},"desc":"In a dungeon (landblock 526A).","id":2487}, + {"name":"Portal Space","type":"Portal","wcid":14822,"cell":"526A025C","place":"dungeon","dest":{"cell":"526B01F7","place":"dungeon"},"desc":"In a dungeon (landblock 526A).","id":2488}, + {"name":"Portal Space","type":"Portal","wcid":14812,"cell":"526A028D","place":"dungeon","dest":{"cell":"526B01E7","place":"dungeon"},"desc":"In a dungeon (landblock 526A).","id":2489}, + {"name":"Portal Space","type":"Portal","wcid":14811,"cell":"526A0290","place":"dungeon","dest":{"cell":"526B01A1","place":"dungeon"},"desc":"In a dungeon (landblock 526A).","id":2490}, + {"name":"Portal Space","type":"Portal","wcid":14813,"cell":"526A02B0","place":"dungeon","dest":{"cell":"526B010E","place":"dungeon"},"desc":"In a dungeon (landblock 526A).","id":2491}, + {"name":"Portal Space","type":"Portal","wcid":14814,"cell":"526A02B4","place":"dungeon","dest":{"cell":"526B0154","place":"dungeon"},"desc":"In a dungeon (landblock 526A).","id":2492}, + {"name":"Portal Hotspot Empyrean Invoking","type":"Portal","wcid":14603,"cell":"526B0122","place":"dungeon","dest":{"cell":"526A0293","place":"dungeon"},"desc":"In a dungeon (landblock 526B).","id":2493}, + {"name":"Portal Hotspot Empyrean Invoking","type":"Portal","wcid":14603,"cell":"526B0159","place":"dungeon","dest":{"cell":"526A0293","place":"dungeon"},"desc":"In a dungeon (landblock 526B).","id":2494}, + {"name":"Portal Hotspot Empyrean Invoking","type":"Portal","wcid":14603,"cell":"526B019D","place":"dungeon","dest":{"cell":"526A0293","place":"dungeon"},"desc":"In a dungeon (landblock 526B).","id":2495}, + {"name":"Portal Hotspot Empyrean Invoking","type":"Portal","wcid":14603,"cell":"526B01D4","place":"dungeon","dest":{"cell":"526A0293","place":"dungeon"},"desc":"In a dungeon (landblock 526B).","id":2496}, + {"name":"Portal Space","type":"Portal","wcid":14609,"cell":"526B0214","place":"dungeon","dest":{"cell":"526A01F2","place":"dungeon"},"desc":"In a dungeon (landblock 526B).","id":2497}, + {"name":"Portal Space","type":"Portal","wcid":14609,"cell":"526B023B","place":"dungeon","dest":{"cell":"526A01F2","place":"dungeon"},"desc":"In a dungeon (landblock 526B).","id":2498}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526B027A","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In a dungeon (landblock 526B).","id":2499}, + {"name":"Portal Space","type":"Portal","wcid":14609,"cell":"526B02A5","place":"dungeon","dest":{"cell":"526A01F2","place":"dungeon"},"desc":"In a dungeon (landblock 526B).","id":2500}, + {"name":"Portal Space","type":"Portal","wcid":14609,"cell":"526B02B5","place":"dungeon","dest":{"cell":"526A01F2","place":"dungeon"},"desc":"In a dungeon (landblock 526B).","id":2501}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526B0322","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In a dungeon (landblock 526B).","id":2502}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526B039C","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In a dungeon (landblock 526B).","id":2503}, + {"name":"Portal Space","type":"Portal","wcid":14807,"cell":"526B0423","place":"dungeon","dest":{"cell":"526C0123","place":"dungeon","name":"Entrance to Portal Space"},"desc":"In a dungeon (landblock 526B).","id":2504}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526B042B","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In a dungeon (landblock 526B).","id":2505}, + {"name":"Portal Space","type":"Portal","wcid":14809,"cell":"526B0435","place":"dungeon","dest":{"cell":"526C01C2","place":"dungeon","name":"Entrance to Portal Space"},"desc":"In a dungeon (landblock 526B).","id":2506}, + {"name":"Portal Space","type":"Portal","wcid":14808,"cell":"526B0452","place":"dungeon","dest":{"cell":"526C01A1","place":"dungeon","name":"Entrance to Portal Space"},"desc":"In a dungeon (landblock 526B).","id":2507}, + {"name":"Portal Space","type":"Portal","wcid":14810,"cell":"526B0456","place":"dungeon","dest":{"cell":"526C0144","place":"dungeon","name":"Entrance to Portal Space"},"desc":"In a dungeon (landblock 526B).","id":2508}, + {"name":"Portal Space","type":"Portal","wcid":14605,"cell":"526C0120","place":"dungeon","dest":{"cell":"526B0425","place":"dungeon"},"desc":"In Entrance to Portal Space.","id":2509}, + {"name":"Portal Space","type":"Portal","wcid":14608,"cell":"526C014D","place":"dungeon","dest":{"cell":"526B0457","place":"dungeon"},"desc":"In Entrance to Portal Space.","id":2510}, + {"name":"Portal Space","type":"Portal","wcid":14606,"cell":"526C0198","place":"dungeon","dest":{"cell":"526B044C","place":"dungeon"},"desc":"In Entrance to Portal Space.","id":2511}, + {"name":"Portal Space","type":"Portal","wcid":14607,"cell":"526C01C5","place":"dungeon","dest":{"cell":"526B0436","place":"dungeon"},"desc":"In Entrance to Portal Space.","id":2512}, + {"name":"Portal Hotspot Lilitha Invoking","type":"Portal","wcid":14604,"cell":"526C0324","place":"dungeon","dest":{"cell":"526A01E8","place":"dungeon"},"desc":"In Entrance to Portal Space.","id":2513}, + {"name":"Portal Hotspot Lilitha Invoking","type":"Portal","wcid":14604,"cell":"526C032B","place":"dungeon","dest":{"cell":"526A01E8","place":"dungeon"},"desc":"In Entrance to Portal Space.","id":2514}, + {"name":"Portal Hotspot Lilitha Invoking","type":"Portal","wcid":14604,"cell":"526C0379","place":"dungeon","dest":{"cell":"526A01E8","place":"dungeon"},"desc":"In Entrance to Portal Space.","id":2515}, + {"name":"Portal Hotspot Lilitha Invoking","type":"Portal","wcid":14604,"cell":"526C03AE","place":"dungeon","dest":{"cell":"526A01E8","place":"dungeon"},"desc":"In Entrance to Portal Space.","id":2516}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526C03FF","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In Entrance to Portal Space.","id":2517}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526C0404","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In Entrance to Portal Space.","id":2518}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526C0416","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In Entrance to Portal Space.","id":2519}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526C041B","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In Entrance to Portal Space.","id":2520}, + {"name":"Return to Dereth","type":"Portal","wcid":14584,"cell":"526C03F0","place":"dungeon","dest":{"cell":"99E7003A","place":"outdoor","ns":83.05,"ew":21.2},"desc":"In Entrance to Portal Space.","id":2521}, + {"name":"Empyrean Acid Propylaeum","type":"Portal","wcid":14492,"cell":"526D0252","place":"dungeon","dest":{"cell":"526E014B","place":"dungeon","name":"Empyrean Acid Propylaeum"},"minLevel":50,"desc":"In a dungeon (landblock 526D).","id":2522}, + {"name":"Empyrean Acid Propylaeum","type":"Portal","wcid":14492,"cell":"526D0257","place":"dungeon","dest":{"cell":"526E014B","place":"dungeon","name":"Empyrean Acid Propylaeum"},"minLevel":50,"desc":"In a dungeon (landblock 526D).","id":2523}, + {"name":"Surface","type":"Portal","wcid":14497,"cell":"526D0150","place":"dungeon","dest":{"cell":"22590025","place":"outdoor","ns":-30.35,"ew":-74.3},"desc":"In a dungeon (landblock 526D).","id":2524}, + {"name":"Surface","type":"Portal","wcid":14497,"cell":"526D0345","place":"dungeon","dest":{"cell":"22590025","place":"outdoor","ns":-30.35,"ew":-74.3},"desc":"In a dungeon (landblock 526D).","id":2525}, + {"name":"Lower Empyrean Acid Cistern","type":"Portal","wcid":14494,"cell":"526E0101","place":"dungeon","dest":{"cell":"526D0251","place":"dungeon"},"minLevel":50,"desc":"In Empyrean Acid Propylaeum.","id":2526}, + {"name":"Upper Empyrean Acid Cistern","type":"Portal","wcid":14495,"cell":"526E010B","place":"dungeon","dest":{"cell":"526D0256","place":"dungeon"},"minLevel":50,"desc":"In Empyrean Acid Propylaeum.","id":2527}, + {"name":"Surface","type":"Portal","wcid":14497,"cell":"526E014C","place":"dungeon","dest":{"cell":"22590025","place":"outdoor","ns":-30.35,"ew":-74.3},"desc":"In Empyrean Acid Propylaeum.","id":2528}, + {"name":"Surface","type":"Portal","wcid":14489,"cell":"526F014E","place":"dungeon","dest":{"cell":"7BDB001B","place":"outdoor","ns":73.54,"ew":-3.19},"desc":"In a dungeon (landblock 526F).","id":2529}, + {"name":"Empyrean Fire Propylaeum","type":"Portal","wcid":14488,"cell":"526F01FB","place":"dungeon","dest":{"cell":"5270014B","place":"dungeon","name":"Empyrean Fire Propylaeum"},"minLevel":25,"desc":"In a dungeon (landblock 526F).","id":2530}, + {"name":"Empyrean Fire Propylaeum","type":"Portal","wcid":14488,"cell":"526F0247","place":"dungeon","dest":{"cell":"5270014B","place":"dungeon","name":"Empyrean Fire Propylaeum"},"minLevel":25,"desc":"In a dungeon (landblock 526F).","id":2531}, + {"name":"Surface","type":"Portal","wcid":14489,"cell":"526F033E","place":"dungeon","dest":{"cell":"7BDB001B","place":"outdoor","ns":73.54,"ew":-3.19},"desc":"In a dungeon (landblock 526F).","id":2532}, + {"name":"Lower Empyrean Fire Cistern","type":"Portal","wcid":14493,"cell":"52700101","place":"dungeon","dest":{"cell":"526F01FD","place":"dungeon"},"minLevel":25,"desc":"In Empyrean Fire Propylaeum.","id":2533}, + {"name":"Upper Empyrean Fire Cistern","type":"Portal","wcid":14496,"cell":"5270010B","place":"dungeon","dest":{"cell":"526F0246","place":"dungeon"},"minLevel":25,"desc":"In Empyrean Fire Propylaeum.","id":2534}, + {"name":"Surface","type":"Portal","wcid":14489,"cell":"5270014C","place":"dungeon","dest":{"cell":"7BDB001B","place":"outdoor","ns":73.54,"ew":-3.19},"desc":"In Empyrean Fire Propylaeum.","id":2535}, + {"name":"Surface","type":"Portal","wcid":14490,"cell":"5271014A","place":"dungeon","dest":{"cell":"CDC10013","place":"outdoor","ns":52.68,"ew":62.27},"desc":"In a dungeon (landblock 5271).","id":2536}, + {"name":"Empyrean Ice Propylaeum","type":"Portal","wcid":14500,"cell":"52710208","place":"dungeon","dest":{"cell":"5272014B","place":"dungeon","name":"Empyrean Ice Propylaeum"},"minLevel":25,"desc":"In a dungeon (landblock 5271).","id":2537}, + {"name":"Empyrean Ice Propylaeum","type":"Portal","wcid":14500,"cell":"52710258","place":"dungeon","dest":{"cell":"5272014B","place":"dungeon","name":"Empyrean Ice Propylaeum"},"minLevel":25,"desc":"In a dungeon (landblock 5271).","id":2538}, + {"name":"Surface","type":"Portal","wcid":14490,"cell":"52710348","place":"dungeon","dest":{"cell":"CDC10013","place":"outdoor","ns":52.68,"ew":62.27},"desc":"In a dungeon (landblock 5271).","id":2539}, + {"name":"Lower Empyrean Ice Cistern","type":"Portal","wcid":14498,"cell":"52720101","place":"dungeon","dest":{"cell":"527101FD","place":"dungeon"},"minLevel":25,"desc":"In Empyrean Ice Propylaeum.","id":2540}, + {"name":"Upper Empyrean Ice Cistern","type":"Portal","wcid":14499,"cell":"5272010B","place":"dungeon","dest":{"cell":"52710257","place":"dungeon"},"minLevel":25,"desc":"In Empyrean Ice Propylaeum.","id":2541}, + {"name":"Surface","type":"Portal","wcid":14490,"cell":"5272014C","place":"dungeon","dest":{"cell":"CDC10013","place":"outdoor","ns":52.68,"ew":62.27},"desc":"In Empyrean Ice Propylaeum.","id":2542}, + {"name":"Surface","type":"Portal","wcid":14491,"cell":"52730157","place":"dungeon","dest":{"cell":"8C130012","place":"outdoor","ns":-86.6,"ew":10.33},"desc":"In a dungeon (landblock 5273).","id":2543}, + {"name":"Empyrean Lightning Propylaeum","type":"Portal","wcid":14503,"cell":"52730245","place":"dungeon","dest":{"cell":"5274014B","place":"dungeon","name":"Empyrean Lightning Propylaeum"},"minLevel":50,"desc":"In a dungeon (landblock 5273).","id":2544}, + {"name":"Empyrean Lightning Propylaeum","type":"Portal","wcid":14503,"cell":"52730277","place":"dungeon","dest":{"cell":"5274014B","place":"dungeon","name":"Empyrean Lightning Propylaeum"},"minLevel":50,"desc":"In a dungeon (landblock 5273).","id":2545}, + {"name":"Surface","type":"Portal","wcid":14491,"cell":"5273037D","place":"dungeon","dest":{"cell":"8C130012","place":"outdoor","ns":-86.6,"ew":10.33},"desc":"In a dungeon (landblock 5273).","id":2546}, + {"name":"Lower Empyrean Lightning Cistern","type":"Portal","wcid":14502,"cell":"52740101","place":"dungeon","dest":{"cell":"52730254","place":"dungeon"},"minLevel":50,"desc":"In Empyrean Lightning Propylaeum.","id":2547}, + {"name":"Upper Empyrean Lightning Cistern","type":"Portal","wcid":14501,"cell":"5274010B","place":"dungeon","dest":{"cell":"52730276","place":"dungeon"},"minLevel":50,"desc":"In Empyrean Lightning Propylaeum.","id":2548}, + {"name":"Surface","type":"Portal","wcid":14491,"cell":"5274014C","place":"dungeon","dest":{"cell":"8C130012","place":"outdoor","ns":-86.6,"ew":10.33},"desc":"In Empyrean Lightning Propylaeum.","id":2549}, + {"name":"Surface Portal","type":"Portal","wcid":14448,"cell":"5276017A","place":"dungeon","dest":{"cell":"AE9E0025","place":"outdoor","ns":24.94,"ew":37.73},"desc":"In a dungeon (landblock 5276).","id":2550}, + {"name":"Surface Portal","type":"Portal","wcid":14448,"cell":"527601EE","place":"dungeon","dest":{"cell":"AE9E0025","place":"outdoor","ns":24.94,"ew":37.73},"desc":"In a dungeon (landblock 5276).","id":2551}, + {"name":"Direlands Midland Portal","type":"Portal","wcid":3613,"cell":"52D90100","place":"building","ns":72.17,"ew":-35.6,"dest":{"cell":"2E110031","place":"outdoor","ns":-88.31,"ew":-64.5},"minLevel":21,"id":2552}, + {"name":"Lightless Catacombs","type":"Portal","wcid":2381,"cell":"53180102","place":"building","ns":-82.22,"ew":-35.25,"dest":{"cell":"019B0161","place":"dungeon","name":"Lightless Catacombs"},"minLevel":14,"id":2553}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"53600221","place":"dungeon","dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"desc":"In a dungeon (landblock 5360).","id":2554}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"53610221","place":"dungeon","dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"desc":"In a dungeon (landblock 5361).","id":2555}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"53620221","place":"dungeon","dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"desc":"In a dungeon (landblock 5362).","id":2556}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"53630221","place":"dungeon","dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"desc":"In a dungeon (landblock 5363).","id":2557}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"53640221","place":"dungeon","dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"desc":"In a dungeon (landblock 5364).","id":2558}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"53650221","place":"dungeon","dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"desc":"In a dungeon (landblock 5365).","id":2559}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"53660221","place":"dungeon","dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"desc":"In a dungeon (landblock 5366).","id":2560}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"53670221","place":"dungeon","dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"desc":"In a dungeon (landblock 5367).","id":2561}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"53680221","place":"dungeon","dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"desc":"In a dungeon (landblock 5368).","id":2562}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"53690221","place":"dungeon","dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"desc":"In a dungeon (landblock 5369).","id":2563}, + {"name":"The Underground City","type":"Portal","wcid":15824,"cell":"536A023C","place":"dungeon","dest":{"cell":"01E901C2","place":"dungeon","name":"Underground City"},"desc":"In a dungeon (landblock 536A).","id":2564}, + {"name":"The Underground City","type":"Portal","wcid":15824,"cell":"536A0103","place":"dungeon","dest":{"cell":"01E901C2","place":"dungeon","name":"Underground City"},"desc":"In a dungeon (landblock 536A).","id":2565}, + {"name":"Surface","type":"Portal","wcid":14885,"cell":"536B0158","place":"dungeon","dest":{"cell":"4D120006","place":"outdoor","ns":-86.99,"ew":-40.26},"desc":"In Convergent Median.","id":2566}, + {"name":"Surface","type":"Portal","wcid":14885,"cell":"536B0206","place":"dungeon","dest":{"cell":"4D120006","place":"outdoor","ns":-86.99,"ew":-40.26},"desc":"In Convergent Median.","id":2567}, + {"name":"Martine's Retreat","type":"Portal","wcid":20919,"cell":"536B0118","place":"dungeon","dest":{"cell":"56600187","place":"dungeon","name":"Martine's Retreat"},"desc":"In Convergent Median.","id":2568}, + {"name":"Surface","type":"Portal","wcid":14887,"cell":"536C0101","place":"dungeon","dest":{"cell":"4562003C","place":"outdoor","ns":-23.2,"ew":-45.97},"desc":"In Malignant Tabernacle.","id":2569}, + {"name":"Surface","type":"Portal","wcid":14887,"cell":"536C0270","place":"dungeon","dest":{"cell":"4562003C","place":"outdoor","ns":-23.2,"ew":-45.97},"desc":"In Malignant Tabernacle.","id":2570}, + {"name":"Nuhmudira's Mansion","type":"Portal","wcid":15276,"cell":"536D0289","place":"dungeon","dest":{"cell":"AC7A0151","place":"underground","ns":-4.03,"ew":35.9},"desc":"In a dungeon (landblock 536D).","id":2571}, + {"name":"Nuhmudira's Mansion","type":"Portal","wcid":15276,"cell":"536D01B2","place":"dungeon","dest":{"cell":"AC7A0151","place":"underground","ns":-4.03,"ew":35.9},"desc":"In a dungeon (landblock 536D).","id":2572}, + {"name":"Bookcase","type":"Portal","wcid":85001,"cell":"536D023C","place":"dungeon","dest":{"cell":"536D023B","place":"dungeon"},"minLevel":120,"desc":"A simple bookcase. In a dungeon (landblock 536D).","id":2573}, + {"name":"Surface","type":"Portal","wcid":14889,"cell":"536E0101","place":"dungeon","dest":{"cell":"0C6F0029","place":"outdoor","ns":-13.12,"ew":-91.81},"desc":"In Venemous Nidus.","id":2574}, + {"name":"Surface","type":"Portal","wcid":14889,"cell":"536E0256","place":"dungeon","dest":{"cell":"0C6F0029","place":"outdoor","ns":-13.12,"ew":-91.81},"desc":"In Venemous Nidus.","id":2575}, + {"name":"Destroyed Mayoi Portal","type":"Portal","wcid":1022,"cell":"54160000","place":"outdoor","ns":-83.6,"ew":-34.63,"dest":{"cell":"E6320021","place":"outdoor","ns":-61.91,"ew":82.5},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2576}, + {"name":"Surface","type":"Portal","wcid":20643,"cell":"5456029F","place":"dungeon","dest":{"cell":"67DE0103","place":"building","ns":75.9,"ew":-19.11},"desc":"In Grievver Caves.","id":2577}, + {"name":"Portal to Fort Tethana","type":"Portal","wcid":19131,"cell":"545701C7","place":"dungeon","dest":{"cell":"2681001D","place":"outdoor","ns":1.7,"ew":-71.23},"desc":"In Colossus Foundry.","id":2578}, + {"name":"Portal to Fort Tethana","type":"Portal","wcid":19131,"cell":"5457030B","place":"dungeon","dest":{"cell":"2681001D","place":"outdoor","ns":1.7,"ew":-71.23},"desc":"In Colossus Foundry.","id":2579}, + {"name":"Portal to Baishi","type":"Portal","wcid":19133,"cell":"54580261","place":"dungeon","dest":{"cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9},"desc":"In Mammet Foundry.","id":2580}, + {"name":"Portal to Cragstone","type":"Portal","wcid":19137,"cell":"545901AE","place":"dungeon","dest":{"cell":"BB9F0030","place":"outdoor","ns":25.99,"ew":48.16},"desc":"In Effigy Foundry.","id":2581}, + {"name":"Portal to Nanto","type":"Portal","wcid":19135,"cell":"545A0134","place":"dungeon","dest":{"cell":"E63E0022","place":"outdoor","ns":-52.19,"ew":82.45},"desc":"In Mannikin Foundry.","id":2582}, + {"name":"Surface","type":"Portal","wcid":19727,"cell":"545B0122","place":"dungeon","dest":{"cell":"87860016","place":"outdoor","ns":5.8,"ew":6.3},"desc":"In Arcanum Research Facility.","id":2583}, + {"name":"Surface","type":"Portal","wcid":19465,"cell":"545C0123","place":"dungeon","dest":{"cell":"DC3A001F","place":"outdoor","ns":-54.85,"ew":74.39},"desc":"In a dungeon (landblock 545C).","id":2584}, + {"name":"Surface","type":"Portal","wcid":19465,"cell":"545C0189","place":"dungeon","dest":{"cell":"DC3A001F","place":"outdoor","ns":-54.85,"ew":74.39},"desc":"In a dungeon (landblock 545C).","id":2585}, + {"name":"Surface","type":"Portal","wcid":19465,"cell":"545C037B","place":"dungeon","dest":{"cell":"DC3A001F","place":"outdoor","ns":-54.85,"ew":74.39},"desc":"In a dungeon (landblock 545C).","id":2586}, + {"name":"Arcanum Storehouse Middle Level","type":"Portal","wcid":19469,"cell":"545C04F7","place":"dungeon","dest":{"cell":"545C0619","place":"dungeon"},"minLevel":30,"quest":true,"desc":"In a dungeon (landblock 545C).","id":2587}, + {"name":"Arcanum Storehouse Lower Level","type":"Portal","wcid":19467,"cell":"545C052F","place":"dungeon","dest":{"cell":"545C0619","place":"dungeon"},"minLevel":45,"quest":true,"desc":"In a dungeon (landblock 545C).","id":2588}, + {"name":"Surface","type":"Portal","wcid":19465,"cell":"545C05F8","place":"dungeon","dest":{"cell":"DC3A001F","place":"outdoor","ns":-54.85,"ew":74.39},"desc":"In a dungeon (landblock 545C).","id":2589}, + {"name":"Surface","type":"Portal","wcid":19465,"cell":"545C0684","place":"dungeon","dest":{"cell":"DC3A001F","place":"outdoor","ns":-54.85,"ew":74.39},"desc":"In a dungeon (landblock 545C).","id":2590}, + {"name":"Arcanum Storehouse Upper Level","type":"Portal","wcid":19468,"cell":"545C0530","place":"dungeon","dest":{"cell":"545C0681","place":"dungeon"},"minLevel":15,"quest":true,"desc":"In a dungeon (landblock 545C).","id":2591}, + {"name":"Surface","type":"Portal","wcid":19470,"cell":"545D0206","place":"dungeon","dest":{"cell":"69D50040","place":"outdoor","ns":69.23,"ew":-17.2},"desc":"In a dungeon (landblock 545D).","id":2592}, + {"name":"The Callous Heart High Grounds","type":"Portal","wcid":19471,"cell":"545D0217","place":"dungeon","dest":{"cell":"545D024F","place":"dungeon"},"minLevel":45,"desc":"In a dungeon (landblock 545D).","id":2593}, + {"name":"The Callous Heart Right Wing","type":"Portal","wcid":19472,"cell":"545D0242","place":"dungeon","dest":{"cell":"545D024D","place":"dungeon"},"minLevel":15,"desc":"In a dungeon (landblock 545D).","id":2594}, + {"name":"The Callous Heart Left Wing","type":"Portal","wcid":19473,"cell":"545D0243","place":"dungeon","dest":{"cell":"545D025A","place":"dungeon"},"minLevel":30,"desc":"In a dungeon (landblock 545D).","id":2595}, + {"name":"Surface","type":"Portal","wcid":19470,"cell":"545D0100","place":"dungeon","dest":{"cell":"69D50040","place":"outdoor","ns":69.23,"ew":-17.2},"desc":"In a dungeon (landblock 545D).","id":2596}, + {"name":"Surface","type":"Portal","wcid":19470,"cell":"545D01D6","place":"dungeon","dest":{"cell":"69D50040","place":"outdoor","ns":69.23,"ew":-17.2},"desc":"In a dungeon (landblock 545D).","id":2597}, + {"name":"Surface","type":"Portal","wcid":19724,"cell":"545E011B","place":"dungeon","dest":{"cell":"CE510023","place":"outdoor","ns":-36.93,"ew":63.32},"desc":"In Fathomless Chasm.","id":2598}, + {"name":"Fathomless Chasm Clough","type":"Portal","wcid":19721,"cell":"545E0175","place":"dungeon","dest":{"cell":"545F0288","place":"dungeon"},"minLevel":40,"maxLevel":49,"desc":"In Fathomless Chasm.","id":2599}, + {"name":"Fathomless Chasm Plummet","type":"Portal","wcid":19725,"cell":"545E0176","place":"dungeon","dest":{"cell":"545F028B","place":"dungeon"},"minLevel":50,"maxLevel":59,"desc":"In Fathomless Chasm.","id":2600}, + {"name":"Fathomless Chasm Descent","type":"Portal","wcid":19722,"cell":"545E0184","place":"dungeon","dest":{"cell":"54600347","place":"dungeon"},"minLevel":60,"maxLevel":79,"desc":"In Fathomless Chasm.","id":2601}, + {"name":"Fathomless Chasm Devex","type":"Portal","wcid":19723,"cell":"545E0195","place":"dungeon","dest":{"cell":"545E0295","place":"dungeon","name":"Fathomless Chasm"},"minLevel":20,"maxLevel":39,"desc":"In Fathomless Chasm.","id":2602}, + {"name":"Surface","type":"Portal","wcid":19724,"cell":"545E01FD","place":"dungeon","dest":{"cell":"CE510023","place":"outdoor","ns":-36.93,"ew":63.32},"desc":"In Fathomless Chasm.","id":2603}, + {"name":"Fathomless Chasm Abyss","type":"Portal","wcid":19720,"cell":"545E0289","place":"dungeon","dest":{"cell":"54600349","place":"dungeon"},"minLevel":80,"desc":"In Fathomless Chasm.","id":2604}, + {"name":"Surface","type":"Portal","wcid":19724,"cell":"545F0108","place":"dungeon","dest":{"cell":"CE510023","place":"outdoor","ns":-36.93,"ew":63.32},"desc":"In a dungeon (landblock 545F).","id":2605}, + {"name":"Surface","type":"Portal","wcid":19724,"cell":"545F0170","place":"dungeon","dest":{"cell":"CE510023","place":"outdoor","ns":-36.93,"ew":63.32},"desc":"In a dungeon (landblock 545F).","id":2606}, + {"name":"Surface","type":"Portal","wcid":19724,"cell":"545F020A","place":"dungeon","dest":{"cell":"CE510023","place":"outdoor","ns":-36.93,"ew":63.32},"desc":"In a dungeon (landblock 545F).","id":2607}, + {"name":"Surface","type":"Portal","wcid":19724,"cell":"545F0160","place":"dungeon","dest":{"cell":"CE510023","place":"outdoor","ns":-36.93,"ew":63.32},"desc":"In a dungeon (landblock 545F).","id":2608}, + {"name":"Surface","type":"Portal","wcid":19724,"cell":"54600107","place":"dungeon","dest":{"cell":"CE510023","place":"outdoor","ns":-36.93,"ew":63.32},"desc":"In a dungeon (landblock 5460).","id":2609}, + {"name":"Surface","type":"Portal","wcid":19724,"cell":"54600128","place":"dungeon","dest":{"cell":"CE510023","place":"outdoor","ns":-36.93,"ew":63.32},"desc":"In a dungeon (landblock 5460).","id":2610}, + {"name":"Surface","type":"Portal","wcid":19724,"cell":"54600156","place":"dungeon","dest":{"cell":"CE510023","place":"outdoor","ns":-36.93,"ew":63.32},"desc":"In a dungeon (landblock 5460).","id":2611}, + {"name":"Surface","type":"Portal","wcid":19724,"cell":"546001DD","place":"dungeon","dest":{"cell":"CE510023","place":"outdoor","ns":-36.93,"ew":63.32},"desc":"In a dungeon (landblock 5460).","id":2612}, + {"name":"Surface","type":"Portal","wcid":19724,"cell":"54600169","place":"dungeon","dest":{"cell":"CE510023","place":"outdoor","ns":-36.93,"ew":63.32},"desc":"In a dungeon (landblock 5460).","id":2613}, + {"name":"Strange Tunnel","type":"Portal","wcid":8906,"cell":"5461013B","place":"dungeon","dest":{"cell":"02AB0160","place":"dungeon"},"desc":"In a dungeon (landblock 5461).","id":2614}, + {"name":"Strange Tunnel","type":"Portal","wcid":8906,"cell":"5461022E","place":"dungeon","dest":{"cell":"02AB0160","place":"dungeon"},"desc":"In a dungeon (landblock 5461).","id":2615}, + {"name":"Oubliette","type":"Portal","wcid":15779,"cell":"546302A5","place":"dungeon","dest":{"cell":"54620104","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 5463).","id":2616}, + {"name":"Surface","type":"Portal","wcid":15777,"cell":"546303DF","place":"dungeon","dest":{"cell":"69D50040","place":"outdoor","ns":69.23,"ew":-17.2},"desc":"In a dungeon (landblock 5463).","id":2617}, + {"name":"Labyrinth","type":"Portal","wcid":15778,"cell":"54640100","place":"dungeon","dest":{"cell":"54630328","place":"dungeon"},"desc":"In a dungeon (landblock 5464).","id":2618}, + {"name":"Surface","type":"Portal","wcid":15777,"cell":"546401AE","place":"dungeon","dest":{"cell":"69D50040","place":"outdoor","ns":69.23,"ew":-17.2},"desc":"In a dungeon (landblock 5464).","id":2619}, + {"name":"Illsin Veranda","type":"Portal","wcid":15834,"cell":"54650100","place":"dungeon","dest":{"cell":"536201D9","place":"dungeon"},"desc":"In Sanctum Residential Halls.","id":2620}, + {"name":"Caerna Dwellings","type":"Portal","wcid":15833,"cell":"54650101","place":"dungeon","dest":{"cell":"536101D9","place":"dungeon"},"desc":"In Sanctum Residential Halls.","id":2621}, + {"name":"Marin Court","type":"Portal","wcid":15835,"cell":"54650103","place":"dungeon","dest":{"cell":"536301D9","place":"dungeon"},"desc":"In Sanctum Residential Halls.","id":2622}, + {"name":"Alvan Court","type":"Portal","wcid":15832,"cell":"5465010F","place":"dungeon","dest":{"cell":"536001D7","place":"dungeon"},"desc":"In Sanctum Residential Halls.","id":2623}, + {"name":"Ruadnar Court","type":"Portal","wcid":15836,"cell":"5465011A","place":"dungeon","dest":{"cell":"536401D9","place":"dungeon"},"desc":"In Sanctum Residential Halls.","id":2624}, + {"name":"Treyval Veranda","type":"Portal","wcid":15842,"cell":"5465017B","place":"dungeon","dest":{"cell":"536901D9","place":"dungeon"},"desc":"In Sanctum Residential Halls.","id":2625}, + {"name":"Senmai Court","type":"Portal","wcid":15838,"cell":"5465017C","place":"dungeon","dest":{"cell":"536501D9","place":"dungeon"},"desc":"In Sanctum Residential Halls.","id":2626}, + {"name":"Sorveya Court","type":"Portal","wcid":15840,"cell":"54650182","place":"dungeon","dest":{"cell":"536701D9","place":"dungeon"},"desc":"In Sanctum Residential Halls.","id":2627}, + {"name":"Sylvan Dwellings","type":"Portal","wcid":15841,"cell":"54650183","place":"dungeon","dest":{"cell":"536801D9","place":"dungeon"},"desc":"In Sanctum Residential Halls.","id":2628}, + {"name":"Sigil Veranda","type":"Portal","wcid":15839,"cell":"54650184","place":"dungeon","dest":{"cell":"536601D9","place":"dungeon"},"desc":"In Sanctum Residential Halls.","id":2629}, + {"name":"Portal to Cragstone","type":"Portal","wcid":42818,"cell":"5465018C","place":"dungeon","dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal goes to the Aluvian capital, Cragstone. This is a good town for characters over level 10. In Sanctum Residential Halls.","id":2630}, + {"name":"Portal to Zaikhal","type":"Portal","wcid":42831,"cell":"5465019B","place":"dungeon","dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal goes to the Gharu'ndim capital, Zaikhal. This is a good town for characters over level 20. In Sanctum Residential Halls.","id":2631}, + {"name":"Portal to Hebian-To","type":"Portal","wcid":42846,"cell":"546501A4","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal goes to the Sho capital, Hebian-To. This is a good town for characters over level 10. In Sanctum Residential Halls.","id":2632}, + {"name":"Destroyed Portal to Cragstone","type":"Portal","wcid":1014,"cell":"54D70000","place":"outdoor","ns":70.39,"ew":-34.45,"dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":2633}, + {"name":"Surface","type":"Portal","wcid":23894,"cell":"564301ED","place":"dungeon","dest":{"cell":"D66B003C","place":"outdoor","ns":-16.0,"ew":70.0},"desc":"In Gromnie Clan Training Camp.","id":2634}, + {"name":"Surface","type":"Portal","wcid":23894,"cell":"564303E5","place":"dungeon","dest":{"cell":"D66B003C","place":"outdoor","ns":-16.0,"ew":70.0},"desc":"In Gromnie Clan Training Camp.","id":2635}, + {"name":"Surface","type":"Portal","wcid":23896,"cell":"56440100","place":"dungeon","dest":{"cell":"DD6B000C","place":"outdoor","ns":-16.0,"ew":75.02},"desc":"In Mask Clan Training Camp.","id":2636}, + {"name":"Surface","type":"Portal","wcid":23896,"cell":"56440305","place":"dungeon","dest":{"cell":"DD6B000C","place":"outdoor","ns":-16.0,"ew":75.02},"desc":"In Mask Clan Training Camp.","id":2637}, + {"name":"Surface","type":"Portal","wcid":23368,"cell":"56450120","place":"dungeon","dest":{"cell":"6D160008","place":"outdoor","ns":-83.65,"ew":-14.74},"desc":"In Abandoned Armory.","id":2638}, + {"name":"Surface","type":"Portal","wcid":23368,"cell":"5645012E","place":"dungeon","dest":{"cell":"6D160008","place":"outdoor","ns":-83.65,"ew":-14.74},"desc":"In Abandoned Armory.","id":2639}, + {"name":"Surface","type":"Portal","wcid":23513,"cell":"5646013D","place":"dungeon","dest":{"cell":"AD30001A","place":"outdoor","ns":-63.45,"ew":36.76},"desc":"In An Archive.","id":2640}, + {"name":"Surface","type":"Portal","wcid":23513,"cell":"564601E0","place":"dungeon","dest":{"cell":"AD30001A","place":"outdoor","ns":-63.45,"ew":36.76},"desc":"In An Archive.","id":2641}, + {"name":"Exit","type":"Portal","wcid":23516,"cell":"56470101","place":"dungeon","dest":{"cell":"A9540018","place":"outdoor","ns":-34.04,"ew":33.48},"desc":"In Tower Base Dungeon.","id":2642}, + {"name":"Upper Tower","type":"Portal","wcid":23514,"cell":"564702B2","place":"dungeon","dest":{"cell":"A9530015","place":"outdoor","ns":-35.12,"ew":33.47},"desc":"In Tower Base Dungeon.","id":2643}, + {"name":"Surface","type":"Portal","wcid":23080,"cell":"56480102","place":"dungeon","dest":{"cell":"81BB000B","place":"outdoor","ns":47.92,"ew":1.42},"desc":"In a dungeon (landblock 5648).","id":2644}, + {"name":"Surface","type":"Portal","wcid":23077,"cell":"5649013F","place":"dungeon","dest":{"cell":"589E001C","place":"outdoor","ns":24.77,"ew":-31.22},"desc":"In Dark Tree Crystal Mine.","id":2645}, + {"name":"Surface","type":"Portal","wcid":23077,"cell":"564901BB","place":"dungeon","dest":{"cell":"589E001C","place":"outdoor","ns":24.77,"ew":-31.22},"desc":"In Dark Tree Crystal Mine.","id":2646}, + {"name":"Surface","type":"Portal","wcid":23077,"cell":"5649024C","place":"dungeon","dest":{"cell":"589E001C","place":"outdoor","ns":24.77,"ew":-31.22},"desc":"In Dark Tree Crystal Mine.","id":2647}, + {"name":"Exit portal","type":"Portal","wcid":22896,"cell":"564A010F","place":"dungeon","dest":{"cell":"5BA0002D","place":"outdoor","ns":26.52,"ew":-28.57},"desc":"In Spirit Cell.","id":2648}, + {"name":"Exit","type":"Portal","wcid":22867,"cell":"564B011C","place":"dungeon","dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"desc":"In Crystal Mine Extreme.","id":2649}, + {"name":"Exit","type":"Portal","wcid":22867,"cell":"564B022F","place":"dungeon","dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"desc":"In Crystal Mine Extreme.","id":2650}, + {"name":"Exit","type":"Portal","wcid":22867,"cell":"564C011C","place":"dungeon","dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"desc":"In Crystal Mine High.","id":2651}, + {"name":"Exit","type":"Portal","wcid":22867,"cell":"564C022F","place":"dungeon","dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"desc":"In Crystal Mine High.","id":2652}, + {"name":"Exit","type":"Portal","wcid":22867,"cell":"564D011C","place":"dungeon","dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"desc":"In Crystal Mine Mid.","id":2653}, + {"name":"Exit","type":"Portal","wcid":22867,"cell":"564D022F","place":"dungeon","dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"desc":"In Crystal Mine Mid.","id":2654}, + {"name":"Exit","type":"Portal","wcid":22867,"cell":"564E011C","place":"dungeon","dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"desc":"In Crystal Mine Low.","id":2655}, + {"name":"Exit","type":"Portal","wcid":22867,"cell":"564E022F","place":"dungeon","dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"desc":"In Crystal Mine Low.","id":2656}, + {"name":"Exit","type":"Portal","wcid":22867,"cell":"564F011C","place":"dungeon","dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"desc":"In Crystal Mine New Isparians.","id":2657}, + {"name":"Exit","type":"Portal","wcid":22867,"cell":"564F022F","place":"dungeon","dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"desc":"In Crystal Mine New Isparians.","id":2658}, + {"name":"Spirit Gate Portal","type":"Portal","wcid":22229,"cell":"56500100","place":"dungeon","dest":{"cell":"97000161","place":"dungeon"},"desc":"In Victory Residential Halls.","id":2659}, + {"name":"Setera Gardens Portal","type":"Portal","wcid":22228,"cell":"56500101","place":"dungeon","dest":{"cell":"96000161","place":"dungeon"},"desc":"In Victory Residential Halls.","id":2660}, + {"name":"Accord Veranda Portal","type":"Portal","wcid":22222,"cell":"56500103","place":"dungeon","dest":{"cell":"90000161","place":"dungeon"},"desc":"In Victory Residential Halls.","id":2661}, + {"name":"Wilamil Court Portal","type":"Portal","wcid":22232,"cell":"5650010F","place":"dungeon","dest":{"cell":"99000161","place":"dungeon"},"desc":"In Victory Residential Halls.","id":2662}, + {"name":"Meditation Gardens Portal","type":"Portal","wcid":22227,"cell":"5650011A","place":"dungeon","dest":{"cell":"95000161","place":"dungeon"},"desc":"In Victory Residential Halls.","id":2663}, + {"name":"Festivus Court Portal","type":"Portal","wcid":22225,"cell":"5650017B","place":"dungeon","dest":{"cell":"93000161","place":"dungeon"},"desc":"In Victory Residential Halls.","id":2664}, + {"name":"Hibiscus Gardens Portal","type":"Portal","wcid":22226,"cell":"5650017C","place":"dungeon","dest":{"cell":"94000161","place":"dungeon"},"desc":"In Victory Residential Halls.","id":2665}, + {"name":"Candeth Court Portal","type":"Portal","wcid":22223,"cell":"56500182","place":"dungeon","dest":{"cell":"91000161","place":"dungeon"},"desc":"In Victory Residential Halls.","id":2666}, + {"name":"Triumphal Gardens Portal","type":"Portal","wcid":22230,"cell":"56500183","place":"dungeon","dest":{"cell":"98000161","place":"dungeon"},"desc":"In Victory Residential Halls.","id":2667}, + {"name":"Celdiseth Court Portal","type":"Portal","wcid":22224,"cell":"56500184","place":"dungeon","dest":{"cell":"92000161","place":"dungeon"},"desc":"In Victory Residential Halls.","id":2668}, + {"name":"Lin Portal","type":"Portal","wcid":42844,"cell":"5650018C","place":"dungeon","dest":{"cell":"DC3C0011","place":"outdoor","ns":-53.91,"ew":74.3},"desc":"This portal goes to Lin, a small town nestled in a valley located by the foothills of the Linvak Mountains. This is a good town for characters over level 20. In Victory Residential Halls.","id":2669}, + {"name":"Portal to Khayyaban","type":"Portal","wcid":42822,"cell":"5650019B","place":"dungeon","dest":{"cell":"9F440012","place":"outdoor","ns":-47.45,"ew":25.62},"desc":"This portal goes to the town of Khayyaban on the Yushad Ridge. This is a good town for characters over level 20. In Victory Residential Halls.","id":2670}, + {"name":"Portal to Samsur","type":"Portal","wcid":42834,"cell":"565001A4","place":"dungeon","dest":{"cell":"977B000C","place":"outdoor","ns":-3.24,"ew":18.96},"desc":"This portal goes to Samsur, a Gharu'ndim town in the hills behind the Yushad Ridge. This is a good town for characters over level 10. In Victory Residential Halls.","id":2671}, + {"name":"House Portal","type":"Portal","wcid":22090,"cell":"5651038E","place":"dungeon","dest":{"cell":"B6870152","place":"underground","ns":6.58,"ew":43.92},"desc":"In a dungeon (landblock 5651).","id":2672}, + {"name":"Surface","type":"Portal","wcid":87184,"cell":"5652038B","place":"dungeon","dest":{"cell":"8B640001","place":"outdoor","ns":-21.9,"ew":9.3},"desc":"In a dungeon (landblock 5652).","id":2673}, + {"name":"Surface","type":"Portal","wcid":87184,"cell":"56520100","place":"dungeon","dest":{"cell":"8B640001","place":"outdoor","ns":-21.9,"ew":9.3},"desc":"In a dungeon (landblock 5652).","id":2674}, + {"name":"Surface","type":"Portal","wcid":87184,"cell":"56520116","place":"dungeon","dest":{"cell":"8B640001","place":"outdoor","ns":-21.9,"ew":9.3},"desc":"In a dungeon (landblock 5652).","id":2675}, + {"name":"Surface","type":"Portal","wcid":87184,"cell":"56520245","place":"dungeon","dest":{"cell":"8B640001","place":"outdoor","ns":-21.9,"ew":9.3},"desc":"In a dungeon (landblock 5652).","id":2676}, + {"name":"Prismatic Devastation","type":"Portal","wcid":46926,"cell":"565301A7","place":"dungeon","dest":{"cell":"58530109","place":"dungeon"},"minLevel":150,"quest":true,"desc":"In Citadel Library.","id":2677}, + {"name":"Fiery Consumption","type":"Portal","wcid":21409,"cell":"565301A4","place":"dungeon","dest":{"cell":"58450147","place":"dungeon"},"minLevel":40,"maxLevel":59,"quest":true,"desc":"In Citadel Library.","id":2678}, + {"name":"Icy Demise","type":"Portal","wcid":21423,"cell":"565301A4","place":"dungeon","dest":{"cell":"57450109","place":"dungeon"},"minLevel":20,"maxLevel":39,"quest":true,"desc":"In Citadel Library.","id":2679}, + {"name":"Electric Destruction","type":"Portal","wcid":21407,"cell":"565301A7","place":"dungeon","dest":{"cell":"5A450109","place":"dungeon"},"minLevel":80,"maxLevel":149,"quest":true,"desc":"In Citadel Library.","id":2680}, + {"name":"Entropic Decay","type":"Portal","wcid":21408,"cell":"565301A7","place":"dungeon","dest":{"cell":"59450147","place":"dungeon"},"minLevel":60,"maxLevel":79,"quest":true,"desc":"In Citadel Library.","id":2681}, + {"name":"Citadel Apex","type":"Portal","wcid":21400,"cell":"5654012A","place":"dungeon","dest":{"cell":"BAC60015","place":"outdoor","ns":56.9,"ew":47.09},"desc":"In a dungeon (landblock 5654).","id":2682}, + {"name":"Surface","type":"Portal","wcid":46013,"cell":"56550100","place":"dungeon","dest":{"cell":"48B5002D","place":"outdoor","ns":43.3,"ew":-43.78},"desc":"In Virindi Research Facility.","id":2683}, + {"name":"Trothyr Hollow Portal","type":"Portal","wcid":21469,"cell":"56560100","place":"dungeon","dest":{"cell":"87000161","place":"dungeon"},"desc":"In Haven Residential Halls.","id":2684}, + {"name":"Xao Wu Gardens Portal","type":"Portal","wcid":21470,"cell":"56560101","place":"dungeon","dest":{"cell":"8F000161","place":"dungeon"},"desc":"In Haven Residential Halls.","id":2685}, + {"name":"Jojii Gardens Portal","type":"Portal","wcid":21467,"cell":"56560103","place":"dungeon","dest":{"cell":"88000161","place":"dungeon"},"desc":"In Haven Residential Halls.","id":2686}, + {"name":"Celcynd Grotto Portal","type":"Portal","wcid":21461,"cell":"5656010F","place":"dungeon","dest":{"cell":"86000161","place":"dungeon"},"desc":"In Haven Residential Halls.","id":2687}, + {"name":"Jade Gate Portal","type":"Portal","wcid":21466,"cell":"5656011A","place":"dungeon","dest":{"cell":"8D000161","place":"dungeon"},"desc":"In Haven Residential Halls.","id":2688}, + {"name":"Ben Ten Lodge Portal","type":"Portal","wcid":21459,"cell":"5656017B","place":"dungeon","dest":{"cell":"8A000161","place":"dungeon"},"desc":"In Haven Residential Halls.","id":2689}, + {"name":"Ispar Yard Portal","type":"Portal","wcid":21465,"cell":"5656017C","place":"dungeon","dest":{"cell":"8E000161","place":"dungeon"},"desc":"In Haven Residential Halls.","id":2690}, + {"name":"Crescent Moon Veranda Portal","type":"Portal","wcid":21462,"cell":"56560182","place":"dungeon","dest":{"cell":"8C000161","place":"dungeon"},"desc":"In Haven Residential Halls.","id":2691}, + {"name":"Cedraic Court Portal","type":"Portal","wcid":21460,"cell":"56560183","place":"dungeon","dest":{"cell":"89000161","place":"dungeon"},"desc":"In Haven Residential Halls.","id":2692}, + {"name":"Dulok Court Portal","type":"Portal","wcid":21463,"cell":"56560184","place":"dungeon","dest":{"cell":"8B000161","place":"dungeon"},"desc":"In Haven Residential Halls.","id":2693}, + {"name":"Uziz Portal","type":"Portal","wcid":42821,"cell":"5656018C","place":"dungeon","dest":{"cell":"A260003C","place":"outdoor","ns":-24.78,"ew":28.41},"desc":"This portal goes to the town of Uziz in the heart of the Yushad Ridge. This is a good town for characters over level 20. In Haven Residential Halls.","id":2694}, + {"name":"Lytelthorpe Portal","type":"Portal","wcid":42816,"cell":"5656019B","place":"dungeon","dest":{"cell":"C0800007","place":"outdoor","ns":1.1,"ew":51.7},"desc":"This portal goes to the town of Lytelthorpe, an Aluvian settlement surrounded by rich farmlands. This is a good town for characters over level 10. In Haven Residential Halls.","id":2695}, + {"name":"Portal to Tou-Tou","type":"Portal","wcid":42841,"cell":"565601A4","place":"dungeon","dest":{"cell":"F5590034","place":"outdoor","ns":-30.41,"ew":94.69},"desc":"This portal goes to the Sho town of Tou-Tou, perched on the tip of the Tou-Tou peninsula. This is a good town for characters over level 20. In Haven Residential Halls.","id":2696}, + {"name":"Endara Gate Portal","type":"Portal","wcid":19360,"cell":"565E0100","place":"dungeon","dest":{"cell":"85000161","place":"dungeon"},"desc":"In Oriel Residential Halls.","id":2697}, + {"name":"Autumn Moon Gardens Portal","type":"Portal","wcid":19359,"cell":"565E0101","place":"dungeon","dest":{"cell":"83000161","place":"dungeon"},"desc":"In Oriel Residential Halls.","id":2698}, + {"name":"Forsythian Gardens Portal","type":"Portal","wcid":19361,"cell":"565E0103","place":"dungeon","dest":{"cell":"7E000161","place":"dungeon"},"desc":"In Oriel Residential Halls.","id":2699}, + {"name":"Allain Court Portal","type":"Portal","wcid":19356,"cell":"565E010F","place":"dungeon","dest":{"cell":"81000161","place":"dungeon"},"desc":"In Oriel Residential Halls.","id":2700}, + {"name":"Maru Veranda Portal","type":"Portal","wcid":19367,"cell":"565E011A","place":"dungeon","dest":{"cell":"7D000161","place":"dungeon"},"desc":"In Oriel Residential Halls.","id":2701}, + {"name":"White Lotus Gate Portal","type":"Portal","wcid":19376,"cell":"565E017B","place":"dungeon","dest":{"cell":"82000161","place":"dungeon"},"desc":"In Oriel Residential Halls.","id":2702}, + {"name":"Sorac Gate Portal","type":"Portal","wcid":19370,"cell":"565E017C","place":"dungeon","dest":{"cell":"7C000161","place":"dungeon"},"desc":"In Oriel Residential Halls.","id":2703}, + {"name":"Trellyn Gardens Portal","type":"Portal","wcid":19372,"cell":"565E0182","place":"dungeon","dest":{"cell":"84000161","place":"dungeon"},"desc":"In Oriel Residential Halls.","id":2704}, + {"name":"Vindalan Dwellings Portal","type":"Portal","wcid":19375,"cell":"565E0183","place":"dungeon","dest":{"cell":"7F000161","place":"dungeon"},"desc":"In Oriel Residential Halls.","id":2705}, + {"name":"Syrah Dwellings Portal","type":"Portal","wcid":19371,"cell":"565E0184","place":"dungeon","dest":{"cell":"80000161","place":"dungeon"},"desc":"In Oriel Residential Halls.","id":2706}, + {"name":"Mayoi Portal","type":"Portal","wcid":42842,"cell":"565E018C","place":"dungeon","dest":{"cell":"E6320021","place":"outdoor","ns":-61.91,"ew":82.5},"desc":"This portal goes to Mayoi, a coastal settlement renowned for Shoyanen Kenchu, the master mage of the Sho people, who lives in a spire on the outskirts of town. This is a good town for characters over level 30. In Oriel Residential Halls.","id":2707}, + {"name":"Plateau Portal","type":"Portal","wcid":42812,"cell":"565E019B","place":"dungeon","dest":{"cell":"49B70021","place":"outdoor","ns":44.54,"ew":-43.13},"desc":"This portal goes to the Plateau Village, a remote settlement in the forests of Northwestern Osteth. This is a good town for characters over level 40. In Oriel Residential Halls.","id":2708}, + {"name":"Portal to Khayyaban","type":"Portal","wcid":42822,"cell":"565E01A4","place":"dungeon","dest":{"cell":"9F440012","place":"outdoor","ns":-47.45,"ew":25.62},"desc":"This portal goes to the town of Khayyaban on the Yushad Ridge. This is a good town for characters over level 20. In Oriel Residential Halls.","id":2709}, + {"name":"Martine's Study","type":"Portal","wcid":20921,"cell":"566001B9","place":"dungeon","dest":{"cell":"56600187","place":"dungeon","name":"Martine's Retreat"},"desc":"In Martine's Retreat.","id":2710}, + {"name":"Martine's Retreat","type":"Portal","wcid":20919,"cell":"566001EE","place":"dungeon","dest":{"cell":"56600187","place":"dungeon","name":"Martine's Retreat"},"desc":"In Martine's Retreat.","id":2711}, + {"name":"Destroyed Portal to Rithwic","type":"Portal","wcid":1025,"cell":"566001EE","place":"dungeon","dest":{"cell":"C98C0028","place":"outdoor","ns":10.84,"ew":59.32},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In Martine's Retreat.","id":2712}, + {"name":"Martine's Throne Room","type":"Portal","wcid":20922,"cell":"56600116","place":"dungeon","dest":{"cell":"56600187","place":"dungeon","name":"Martine's Retreat"},"desc":"In Martine's Retreat.","id":2713}, + {"name":"Martine's Retreat","type":"Portal","wcid":20919,"cell":"5660014C","place":"dungeon","dest":{"cell":"56600187","place":"dungeon","name":"Martine's Retreat"},"desc":"In Martine's Retreat.","id":2714}, + {"name":"Surface","type":"Portal","wcid":20920,"cell":"566001AA","place":"dungeon","dest":{"cell":"C98B0017","place":"outdoor","ns":9.93,"ew":59.14},"desc":"In Martine's Retreat.","id":2715}, + {"name":"Subterannean Farm","type":"Portal","wcid":24471,"cell":"566001B8","place":"dungeon","dest":{"cell":"6345020B","place":"dungeon"},"minLevel":20,"desc":"In Martine's Retreat.","id":2716}, + {"name":"Heartland Yard Portal","type":"Portal","wcid":19364,"cell":"56610100","place":"dungeon","dest":{"cell":"78000161","place":"dungeon"},"desc":"In Atrium Residential Halls.","id":2717}, + {"name":"Gajin Dwellings Portal","type":"Portal","wcid":19362,"cell":"56610101","place":"dungeon","dest":{"cell":"76000161","place":"dungeon"},"desc":"In Atrium Residential Halls.","id":2718}, + {"name":"Ivory Gate Portal","type":"Portal","wcid":19365,"cell":"56610103","place":"dungeon","dest":{"cell":"79000161","place":"dungeon"},"desc":"In Atrium Residential Halls.","id":2719}, + {"name":"Alphus Court Portal","type":"Portal","wcid":19357,"cell":"5661010F","place":"dungeon","dest":{"cell":"7A000161","place":"dungeon"},"desc":"In Atrium Residential Halls.","id":2720}, + {"name":"Larkspur Gardens Portal","type":"Portal","wcid":19366,"cell":"5661011A","place":"dungeon","dest":{"cell":"73000161","place":"dungeon"},"desc":"In Atrium Residential Halls.","id":2721}, + {"name":"Winthur Gate Portal","type":"Portal","wcid":19377,"cell":"5661017B","place":"dungeon","dest":{"cell":"72000161","place":"dungeon"},"desc":"In Atrium Residential Halls.","id":2722}, + {"name":"Mellas Court Portal","type":"Portal","wcid":19368,"cell":"5661017C","place":"dungeon","dest":{"cell":"74000161","place":"dungeon"},"desc":"In Atrium Residential Halls.","id":2723}, + {"name":"Valorya Gate Portal","type":"Portal","wcid":19373,"cell":"56610182","place":"dungeon","dest":{"cell":"77000161","place":"dungeon"},"desc":"In Atrium Residential Halls.","id":2724}, + {"name":"Vesper Gate Portal","type":"Portal","wcid":19374,"cell":"56610183","place":"dungeon","dest":{"cell":"75000161","place":"dungeon"},"desc":"In Atrium Residential Halls.","id":2725}, + {"name":"Hasina Gardens Portal","type":"Portal","wcid":19363,"cell":"56610184","place":"dungeon","dest":{"cell":"7B000161","place":"dungeon"},"desc":"In Atrium Residential Halls.","id":2726}, + {"name":"Glenden Wood Portal","type":"Portal","wcid":42814,"cell":"5661018C","place":"dungeon","dest":{"cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45},"desc":"This portal goes to Glenden Wood, a village surrounded by the tall trees of the Tiofor Woods. Despite the truce between Queen Elysa and King Varicci, the town is besieged on all sides by Viamontian soldiers. This is a good town for characters over level 40. In Atrium Residential Halls.","id":2727}, + {"name":"Qalaba'r Portal","type":"Portal","wcid":42833,"cell":"5661019B","place":"dungeon","dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"desc":"This portal leads to Qalaba'r, the Gharu'ndim village on the edge of the Linvak Mountain Range. This is a good town for characters over level 30. In Atrium Residential Halls.","id":2728}, + {"name":"Baishi Portal","type":"Portal","wcid":42845,"cell":"566101A4","place":"dungeon","dest":{"cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9},"desc":"This portal goes to Baishi, a town well-known for its sake and the madman that desires it. This is good town for characters over level 40. In Atrium Residential Halls.","id":2729}, + {"name":"Trap Floor Walk Low","type":"Portal","wcid":21523,"cell":"574401CE","place":"dungeon","dest":{"cell":"574401DB","place":"dungeon","name":"Proving Grounds Low"},"desc":"In Proving Grounds Low.","id":2730}, + {"name":"Trap Floor Walk Low","type":"Portal","wcid":21523,"cell":"574401CF","place":"dungeon","dest":{"cell":"574401DB","place":"dungeon","name":"Proving Grounds Low"},"desc":"In Proving Grounds Low.","id":2731}, + {"name":"Trap Floor Walk Low","type":"Portal","wcid":21523,"cell":"574401D0","place":"dungeon","dest":{"cell":"574401DB","place":"dungeon","name":"Proving Grounds Low"},"desc":"In Proving Grounds Low.","id":2732}, + {"name":"Trap Floor Walk Low","type":"Portal","wcid":21523,"cell":"574401D7","place":"dungeon","dest":{"cell":"574401DB","place":"dungeon","name":"Proving Grounds Low"},"desc":"In Proving Grounds Low.","id":2733}, + {"name":"Trap Floor Walk Low","type":"Portal","wcid":21523,"cell":"574401D8","place":"dungeon","dest":{"cell":"574401DB","place":"dungeon","name":"Proving Grounds Low"},"desc":"In Proving Grounds Low.","id":2734}, + {"name":"Trap Floor Walk Low","type":"Portal","wcid":21523,"cell":"574401D9","place":"dungeon","dest":{"cell":"574401DB","place":"dungeon","name":"Proving Grounds Low"},"desc":"In Proving Grounds Low.","id":2735}, + {"name":"Trap Floor Walk Low","type":"Portal","wcid":21523,"cell":"574401E2","place":"dungeon","dest":{"cell":"574401DB","place":"dungeon","name":"Proving Grounds Low"},"desc":"In Proving Grounds Low.","id":2736}, + {"name":"Trap Floor Walk Low","type":"Portal","wcid":21523,"cell":"574401E3","place":"dungeon","dest":{"cell":"574401DB","place":"dungeon","name":"Proving Grounds Low"},"desc":"In Proving Grounds Low.","id":2737}, + {"name":"Trap Floor Walk Low","type":"Portal","wcid":21523,"cell":"574401E4","place":"dungeon","dest":{"cell":"574401DB","place":"dungeon","name":"Proving Grounds Low"},"desc":"In Proving Grounds Low.","id":2738}, + {"name":"Citadel Valley","type":"Portal","wcid":21405,"cell":"5744015A","place":"dungeon","dest":{"cell":"BBC60026","place":"outdoor","ns":56.99,"ew":48.09},"desc":"In Proving Grounds Low.","id":2739}, + {"name":"Proving Grounds Low","type":"Portal","wcid":21958,"cell":"574401D4","place":"dungeon","dest":{"cell":"574401E9","place":"dungeon","name":"Proving Grounds Low"},"quest":true,"desc":"In Proving Grounds Low.","id":2740}, + {"name":"Proving Grounds Low","type":"Portal","wcid":21950,"cell":"574401E7","place":"dungeon","dest":{"cell":"574401D5","place":"dungeon","name":"Proving Grounds Low"},"quest":true,"desc":"In Proving Grounds Low.","id":2741}, + {"name":"Proving Grounds Low","type":"Portal","wcid":21749,"cell":"574603BB","place":"dungeon","dest":{"cell":"574401A0","place":"dungeon","name":"Proving Grounds Low"},"minLevel":20,"maxLevel":39,"quest":true,"desc":"In Lightning Ziggurat.","id":2742}, + {"name":"Surface","type":"Portal","wcid":22664,"cell":"57480100","place":"dungeon","dest":{"cell":"F9820039","place":"outdoor","ns":2.06,"ew":98.01},"desc":"In Tusker Burrow.","id":2743}, + {"name":"Surface","type":"Portal","wcid":22689,"cell":"57490282","place":"dungeon","dest":{"cell":"FA7F0006","place":"outdoor","ns":0.16,"ew":98.06},"desc":"In Tusker Lodge.","id":2744}, + {"name":"Surface","type":"Portal","wcid":23075,"cell":"574A010C","place":"dungeon","dest":{"cell":"CDB4001E","place":"outdoor","ns":42.62,"ew":62.42},"desc":"In a dungeon (landblock 574A).","id":2745}, + {"name":"Warehouse Annex Mine","type":"Portal","wcid":23081,"cell":"574A0123","place":"dungeon","dest":{"cell":"574C03E2","place":"dungeon"},"minLevel":40,"quest":true,"desc":"In a dungeon (landblock 574A).","id":2746}, + {"name":"Surface","type":"Portal","wcid":23078,"cell":"574B010C","place":"dungeon","dest":{"cell":"5648014B","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 574B).","id":2747}, + {"name":"Warehouse Annex Mine","type":"Portal","wcid":23079,"cell":"574B0123","place":"dungeon","dest":{"cell":"5648014B","place":"dungeon"},"minLevel":40,"quest":true,"desc":"In a dungeon (landblock 574B).","id":2748}, + {"name":"Warehouse","type":"Portal","wcid":23043,"cell":"574C0170","place":"dungeon","dest":{"cell":"574B010F","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 574C).","id":2749}, + {"name":"Warehouse","type":"Portal","wcid":23043,"cell":"574C02E7","place":"dungeon","dest":{"cell":"574B010F","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock 574C).","id":2750}, + {"name":"Catacombs of Opposition","type":"Portal","wcid":24227,"cell":"574D0100","place":"dungeon","dest":{"cell":"5E4604DD","place":"dungeon"},"desc":"In a dungeon (landblock 574D).","id":2751}, + {"name":"Catacombs of Opposition","type":"Portal","wcid":24227,"cell":"574E0100","place":"dungeon","dest":{"cell":"5E4604DD","place":"dungeon"},"desc":"In a dungeon (landblock 574E).","id":2752}, + {"name":"Catacombs of Opposition","type":"Portal","wcid":24227,"cell":"574F0107","place":"dungeon","dest":{"cell":"5E4604DD","place":"dungeon"},"desc":"In a dungeon (landblock 574F).","id":2753}, + {"name":"Catacombs of Opposition","type":"Portal","wcid":24227,"cell":"57500106","place":"dungeon","dest":{"cell":"5E4604DD","place":"dungeon"},"desc":"In a dungeon (landblock 5750).","id":2754}, + {"name":"Catacombs of Opposition","type":"Portal","wcid":24227,"cell":"57510109","place":"dungeon","dest":{"cell":"5E4604DD","place":"dungeon"},"desc":"In a dungeon (landblock 5751).","id":2755}, + {"name":"Catacombs of Opposition","type":"Portal","wcid":24227,"cell":"5752010A","place":"dungeon","dest":{"cell":"5E4604DD","place":"dungeon"},"desc":"In a dungeon (landblock 5752).","id":2756}, + {"name":"Surface","type":"Portal","wcid":3650,"cell":"57520100","place":"dungeon","dest":{"cell":"C1BB002C","place":"outdoor","ns":48.02,"ew":52.96},"desc":"In a dungeon (landblock 5752).","id":2757}, + {"name":"Catacombs of Opposition","type":"Portal","wcid":24227,"cell":"57530108","place":"dungeon","dest":{"cell":"5E4604DD","place":"dungeon"},"desc":"In a dungeon (landblock 5753).","id":2758}, + {"name":"Exit to Surface","type":"Portal","wcid":44349,"cell":"575401AD","place":"dungeon","dest":{"cell":"88650033","place":"outdoor","ns":-20.87,"ew":7.54},"desc":"In a dungeon (landblock 5754).","id":2759}, + {"name":"Catacombs","type":"Portal","wcid":44350,"cell":"575402B8","place":"dungeon","dest":{"cell":"5754014B","place":"dungeon"},"desc":"In a dungeon (landblock 5754).","id":2760}, + {"name":"Catacombs","type":"Portal","wcid":44450,"cell":"5754014B","place":"dungeon","dest":{"cell":"5754014B","place":"dungeon"},"desc":"In a dungeon (landblock 5754).","id":2761}, + {"name":"Exit to Surface","type":"Portal","wcid":44349,"cell":"5754022E","place":"dungeon","dest":{"cell":"88650033","place":"outdoor","ns":-20.87,"ew":7.54},"desc":"In a dungeon (landblock 5754).","id":2762}, + {"name":"Catacombs","type":"Portal","wcid":71384,"cell":"57540105","place":"dungeon","dest":{"cell":"57540261","place":"dungeon"},"desc":"In a dungeon (landblock 5754).","id":2763}, + {"name":"Catacombs","type":"Portal","wcid":71384,"cell":"5754010E","place":"dungeon","dest":{"cell":"57540261","place":"dungeon"},"desc":"In a dungeon (landblock 5754).","id":2764}, + {"name":"Catacombs","type":"Portal","wcid":71384,"cell":"57540104","place":"dungeon","dest":{"cell":"57540261","place":"dungeon"},"desc":"In a dungeon (landblock 5754).","id":2765}, + {"name":"Exit to Surface","type":"Portal","wcid":44349,"cell":"57540192","place":"dungeon","dest":{"cell":"88650033","place":"outdoor","ns":-20.87,"ew":7.54},"desc":"In a dungeon (landblock 5754).","id":2766}, + {"name":"Catacombs","type":"Portal","wcid":71390,"cell":"5754012D","place":"dungeon","dest":{"cell":"57540264","place":"dungeon"},"desc":"In a dungeon (landblock 5754).","id":2767}, + {"name":"Catacombs","type":"Portal","wcid":71389,"cell":"57540264","place":"dungeon","dest":{"cell":"5754012D","place":"dungeon"},"desc":"In a dungeon (landblock 5754).","id":2768}, + {"name":"Catacombs","type":"Portal","wcid":71393,"cell":"575401D0","place":"dungeon","dest":{"cell":"57540278","place":"dungeon"},"desc":"In a dungeon (landblock 5754).","id":2769}, + {"name":"Catacombs","type":"Portal","wcid":71392,"cell":"57540278","place":"dungeon","dest":{"cell":"575401D0","place":"dungeon"},"desc":"In a dungeon (landblock 5754).","id":2770}, + {"name":"Exit to Surface","type":"Portal","wcid":44349,"cell":"575401C9","place":"dungeon","dest":{"cell":"88650033","place":"outdoor","ns":-20.87,"ew":7.54},"desc":"In a dungeon (landblock 5754).","id":2771}, + {"name":"Surface","type":"Portal","wcid":44118,"cell":"57600133","place":"dungeon","dest":{"cell":"87650034","place":"outdoor","ns":-20.78,"ew":6.68},"desc":"In Sand Caves.","id":2772}, + {"name":"Surface","type":"Portal","wcid":44119,"cell":"5760040E","place":"dungeon","dest":{"cell":"8764001D","place":"outdoor","ns":-21.49,"ew":6.42},"desc":"In Sand Caves.","id":2773}, + {"name":"Surface","type":"Portal","wcid":44114,"cell":"5760047D","place":"dungeon","dest":{"cell":"8765000B","place":"outdoor","ns":-20.9,"ew":6.17},"desc":"In Sand Caves.","id":2774}, + {"name":"Surface","type":"Portal","wcid":46358,"cell":"5765011C","place":"dungeon","dest":{"cell":"F518003A","place":"outdoor","ns":-82.57,"ew":94.78},"desc":"In Lost Ruins.","id":2775}, + {"name":"Surface","type":"Portal","wcid":46358,"cell":"5765031D","place":"dungeon","dest":{"cell":"F518003A","place":"outdoor","ns":-82.57,"ew":94.78},"desc":"In Lost Ruins.","id":2776}, + {"name":"Surface","type":"Portal","wcid":72645,"cell":"57660100","place":"dungeon","dest":{"cell":"4AE10118","place":"building","ns":78.08,"ew":-42.22},"desc":"In Nanjou Shou-jen Academy.","id":2777}, + {"name":"Surface","type":"Portal","wcid":46452,"cell":"577103DF","place":"dungeon","dest":{"cell":"4BE20011","place":"outdoor","ns":78.9,"ew":-41.68},"desc":"In Venerable Mausoleum.","id":2778}, + {"name":"Surface","type":"Portal","wcid":46452,"cell":"577103E8","place":"dungeon","dest":{"cell":"4BE20011","place":"outdoor","ns":78.9,"ew":-41.68},"desc":"In Venerable Mausoleum.","id":2779}, + {"name":"Venerable Mausoleum","type":"Portal","wcid":46440,"cell":"577101DE","place":"dungeon","dest":{"cell":"577103E3","place":"dungeon","name":"Venerable Mausoleum"},"minLevel":200,"desc":"In Venerable Mausoleum.","id":2780}, + {"name":"Venerable Mausoleum","type":"Portal","wcid":46440,"cell":"577102E0","place":"dungeon","dest":{"cell":"577103E3","place":"dungeon","name":"Venerable Mausoleum"},"minLevel":200,"desc":"In Venerable Mausoleum.","id":2781}, + {"name":"Venerable Mausoleum","type":"Portal","wcid":46440,"cell":"57710100","place":"dungeon","dest":{"cell":"577103E3","place":"dungeon","name":"Venerable Mausoleum"},"minLevel":200,"desc":"In Venerable Mausoleum.","id":2782}, + {"name":"Exit portal","type":"Portal","wcid":24918,"cell":"577202DF","place":"dungeon","dest":{"cell":"D2B6000D","place":"outdoor","ns":44.12,"ew":66.18},"desc":"In Olthoi Brood Hive.","id":2783}, + {"name":"Exit portal","type":"Portal","wcid":24918,"cell":"57720436","place":"dungeon","dest":{"cell":"D2B6000D","place":"outdoor","ns":44.12,"ew":66.18},"desc":"In Olthoi Brood Hive.","id":2784}, + {"name":"Exit portal","type":"Portal","wcid":24917,"cell":"577302DF","place":"dungeon","dest":{"cell":"BBBF001C","place":"outdoor","ns":51.17,"ew":47.96},"desc":"In Olthoi Brood Hive.","id":2785}, + {"name":"Exit portal","type":"Portal","wcid":24917,"cell":"57730436","place":"dungeon","dest":{"cell":"BBBF001C","place":"outdoor","ns":51.17,"ew":47.96},"desc":"In Olthoi Brood Hive.","id":2786}, + {"name":"Gateway Portal","type":"Portal","wcid":24344,"cell":"577401CB","place":"dungeon","dest":{"cell":"57740112","place":"dungeon","name":"Secret Putiputi Place"},"desc":"In Secret Putiputi Place.","id":2787}, + {"name":"Gateway Portal","type":"Portal","wcid":24345,"cell":"57750261","place":"dungeon","dest":{"cell":"577401ED","place":"dungeon","name":"Secret Putiputi Place"},"desc":"In a dungeon (landblock 5775).","id":2788}, + {"name":"Way Back to Tekapuapuh's","type":"Portal","wcid":10926,"cell":"577601A8","place":"dungeon","dest":{"cell":"0DB90014","place":"outdoor","ns":46.41,"ew":-91.31},"desc":"In a dungeon (landblock 5776).","id":2789}, + {"name":"Gateway Portal","type":"Portal","wcid":24346,"cell":"577601AA","place":"dungeon","dest":{"cell":"57750270","place":"dungeon"},"desc":"In a dungeon (landblock 5776).","id":2790}, + {"name":"Surface","type":"Portal","wcid":23892,"cell":"577703AD","place":"dungeon","dest":{"cell":"DD810010","place":"outdoor","ns":2.0,"ew":75.0},"desc":"In Falcon Clan Training Camp.","id":2791}, + {"name":"Surface","type":"Portal","wcid":23892,"cell":"577703C6","place":"dungeon","dest":{"cell":"DD810010","place":"outdoor","ns":2.0,"ew":75.0},"desc":"In Falcon Clan Training Camp.","id":2792}, + {"name":"Surface","type":"Portal","wcid":23900,"cell":"577801AF","place":"dungeon","dest":{"cell":"D67E003A","place":"outdoor","ns":-1.0,"ew":70.01},"desc":"In Serpent Clan Training Camp.","id":2793}, + {"name":"Surface","type":"Portal","wcid":23900,"cell":"57780314","place":"dungeon","dest":{"cell":"D67E003A","place":"outdoor","ns":-1.0,"ew":70.01},"desc":"In Serpent Clan Training Camp.","id":2794}, + {"name":"Surface","type":"Portal","wcid":23902,"cell":"57790109","place":"dungeon","dest":{"cell":"D479001A","place":"outdoor","ns":-5.01,"ew":67.98},"desc":"In Shreth Clan Training Camp.","id":2795}, + {"name":"Surface","type":"Portal","wcid":23902,"cell":"577902E0","place":"dungeon","dest":{"cell":"D479001A","place":"outdoor","ns":-5.01,"ew":67.98},"desc":"In Shreth Clan Training Camp.","id":2796}, + {"name":"Surface","type":"Portal","wcid":23898,"cell":"577A0376","place":"dungeon","dest":{"cell":"D46F001A","place":"outdoor","ns":-13.01,"ew":67.97},"desc":"In Reedshark Clan Training Camp.","id":2797}, + {"name":"Surface","type":"Portal","wcid":23898,"cell":"577A03F0","place":"dungeon","dest":{"cell":"D46F001A","place":"outdoor","ns":-13.01,"ew":67.97},"desc":"In Reedshark Clan Training Camp.","id":2798}, + {"name":"Trap Floor Walk Mid","type":"Portal","wcid":21524,"cell":"584401CE","place":"dungeon","dest":{"cell":"584401DB","place":"dungeon","name":"Proving Grounds Mid"},"desc":"In Proving Grounds Mid.","id":2799}, + {"name":"Trap Floor Walk Mid","type":"Portal","wcid":21524,"cell":"584401CF","place":"dungeon","dest":{"cell":"584401DB","place":"dungeon","name":"Proving Grounds Mid"},"desc":"In Proving Grounds Mid.","id":2800}, + {"name":"Trap Floor Walk Mid","type":"Portal","wcid":21524,"cell":"584401D0","place":"dungeon","dest":{"cell":"584401DB","place":"dungeon","name":"Proving Grounds Mid"},"desc":"In Proving Grounds Mid.","id":2801}, + {"name":"Trap Floor Walk Mid","type":"Portal","wcid":21524,"cell":"584401D7","place":"dungeon","dest":{"cell":"584401DB","place":"dungeon","name":"Proving Grounds Mid"},"desc":"In Proving Grounds Mid.","id":2802}, + {"name":"Trap Floor Walk Mid","type":"Portal","wcid":21524,"cell":"584401D8","place":"dungeon","dest":{"cell":"584401DB","place":"dungeon","name":"Proving Grounds Mid"},"desc":"In Proving Grounds Mid.","id":2803}, + {"name":"Trap Floor Walk Mid","type":"Portal","wcid":21524,"cell":"584401D9","place":"dungeon","dest":{"cell":"584401DB","place":"dungeon","name":"Proving Grounds Mid"},"desc":"In Proving Grounds Mid.","id":2804}, + {"name":"Trap Floor Walk Mid","type":"Portal","wcid":21524,"cell":"584401E2","place":"dungeon","dest":{"cell":"584401DB","place":"dungeon","name":"Proving Grounds Mid"},"desc":"In Proving Grounds Mid.","id":2805}, + {"name":"Trap Floor Walk Mid","type":"Portal","wcid":21524,"cell":"584401E3","place":"dungeon","dest":{"cell":"584401DB","place":"dungeon","name":"Proving Grounds Mid"},"desc":"In Proving Grounds Mid.","id":2806}, + {"name":"Trap Floor Walk Mid","type":"Portal","wcid":21524,"cell":"584401E4","place":"dungeon","dest":{"cell":"584401DB","place":"dungeon","name":"Proving Grounds Mid"},"desc":"In Proving Grounds Mid.","id":2807}, + {"name":"Citadel Valley","type":"Portal","wcid":21404,"cell":"5844015A","place":"dungeon","dest":{"cell":"BAC7001A","place":"outdoor","ns":57.43,"ew":47.17},"desc":"In Proving Grounds Mid.","id":2808}, + {"name":"Proving Grounds Mid","type":"Portal","wcid":21959,"cell":"584401D4","place":"dungeon","dest":{"cell":"584401E9","place":"dungeon","name":"Proving Grounds Mid"},"quest":true,"desc":"In Proving Grounds Mid.","id":2809}, + {"name":"Proving Grounds Mid","type":"Portal","wcid":21951,"cell":"584401E7","place":"dungeon","dest":{"cell":"584401D5","place":"dungeon","name":"Proving Grounds Mid"},"quest":true,"desc":"In Proving Grounds Mid.","id":2810}, + {"name":"Proving Grounds Mid","type":"Portal","wcid":21750,"cell":"584603BB","place":"dungeon","dest":{"cell":"584401A0","place":"dungeon","name":"Proving Grounds Mid"},"minLevel":40,"maxLevel":59,"quest":true,"desc":"In Acid Ziggurat.","id":2811}, + {"name":"Surface","type":"Portal","wcid":22673,"cell":"58480177","place":"dungeon","dest":{"cell":"F67D0034","place":"outdoor","ns":-1.56,"ew":95.55},"desc":"In Tusker Freehold.","id":2812}, + {"name":"Surface","type":"Portal","wcid":22660,"cell":"58490196","place":"dungeon","dest":{"cell":"E87A0035","place":"outdoor","ns":-3.88,"ew":84.29},"desc":"In Tusker Assault.","id":2813}, + {"name":"Exit portal","type":"Portal","wcid":24916,"cell":"584B017F","place":"dungeon","dest":{"cell":"C5D00029","place":"outdoor","ns":64.47,"ew":56.19},"desc":"In Olthoi Brood Hive.","id":2814}, + {"name":"Exit portal","type":"Portal","wcid":24916,"cell":"584B04E4","place":"dungeon","dest":{"cell":"C5D00029","place":"outdoor","ns":64.47,"ew":56.19},"desc":"In Olthoi Brood Hive.","id":2815}, + {"name":"Exit portal","type":"Portal","wcid":24915,"cell":"584C017F","place":"dungeon","dest":{"cell":"D3C7002A","place":"outdoor","ns":57.37,"ew":67.45},"desc":"In Olthoi Brood Hive.","id":2816}, + {"name":"Exit portal","type":"Portal","wcid":24915,"cell":"584C04E4","place":"dungeon","dest":{"cell":"D3C7002A","place":"outdoor","ns":57.37,"ew":67.45},"desc":"In Olthoi Brood Hive.","id":2817}, + {"name":"Surface","type":"Portal","wcid":46308,"cell":"584D0132","place":"dungeon","dest":{"cell":"3EF8002F","place":"outdoor","ns":97.11,"ew":-51.82},"minLevel":6,"desc":"In Frigid Grotto.","id":2818}, + {"name":"Surface","type":"Portal","wcid":72809,"cell":"584E0118","place":"dungeon","dest":{"cell":"5FD30038","place":"outdoor","ns":67.62,"ew":-25.33},"desc":"In Serpent Burial Grounds.","id":2819}, + {"name":"Surface","type":"Portal","wcid":72601,"cell":"584F040F","place":"dungeon","dest":{"cell":"4AE00024","place":"outdoor","ns":77.62,"ew":-42.3},"desc":"In a dungeon (landblock 584F).","id":2820}, + {"name":"Proving Grounds Uber","type":"Portal","wcid":46925,"cell":"585103BB","place":"dungeon","dest":{"cell":"5852019F","place":"dungeon","name":"Proving Grounds Uber"},"minLevel":150,"quest":true,"desc":"In Prismatic Ziggurat.","id":2821}, + {"name":"Trap Floor Walk Uber","type":"Portal","wcid":72888,"cell":"585201CE","place":"dungeon","dest":{"cell":"585201DA","place":"dungeon","name":"Proving Grounds Uber"},"desc":"In Proving Grounds Uber.","id":2822}, + {"name":"Trap Floor Walk Uber","type":"Portal","wcid":72888,"cell":"585201CF","place":"dungeon","dest":{"cell":"585201DA","place":"dungeon","name":"Proving Grounds Uber"},"desc":"In Proving Grounds Uber.","id":2823}, + {"name":"Trap Floor Walk Uber","type":"Portal","wcid":72888,"cell":"585201D0","place":"dungeon","dest":{"cell":"585201DA","place":"dungeon","name":"Proving Grounds Uber"},"desc":"In Proving Grounds Uber.","id":2824}, + {"name":"Trap Floor Walk Uber","type":"Portal","wcid":72888,"cell":"585201D7","place":"dungeon","dest":{"cell":"585201DA","place":"dungeon","name":"Proving Grounds Uber"},"desc":"In Proving Grounds Uber.","id":2825}, + {"name":"Trap Floor Walk Uber","type":"Portal","wcid":72888,"cell":"585201D8","place":"dungeon","dest":{"cell":"585201DA","place":"dungeon","name":"Proving Grounds Uber"},"desc":"In Proving Grounds Uber.","id":2826}, + {"name":"Trap Floor Walk Uber","type":"Portal","wcid":72888,"cell":"585201D9","place":"dungeon","dest":{"cell":"585201DA","place":"dungeon","name":"Proving Grounds Uber"},"desc":"In Proving Grounds Uber.","id":2827}, + {"name":"Trap Floor Walk Uber","type":"Portal","wcid":72888,"cell":"585201E2","place":"dungeon","dest":{"cell":"585201DA","place":"dungeon","name":"Proving Grounds Uber"},"desc":"In Proving Grounds Uber.","id":2828}, + {"name":"Trap Floor Walk Uber","type":"Portal","wcid":72888,"cell":"585201E3","place":"dungeon","dest":{"cell":"585201DA","place":"dungeon","name":"Proving Grounds Uber"},"desc":"In Proving Grounds Uber.","id":2829}, + {"name":"Trap Floor Walk Uber","type":"Portal","wcid":72888,"cell":"585201E4","place":"dungeon","dest":{"cell":"585201DA","place":"dungeon","name":"Proving Grounds Uber"},"desc":"In Proving Grounds Uber.","id":2830}, + {"name":"Citadel Valley","type":"Portal","wcid":46923,"cell":"5852015A","place":"dungeon","dest":{"cell":"BBC80003","place":"outdoor","ns":58.3,"ew":47.75},"quest":true,"desc":"In Proving Grounds Uber.","id":2831}, + {"name":"Proving Grounds Uber","type":"Portal","wcid":46955,"cell":"585201D4","place":"dungeon","dest":{"cell":"585201F4","place":"dungeon","name":"Proving Grounds Uber"},"quest":true,"desc":"In Proving Grounds Uber.","id":2832}, + {"name":"Proving Grounds Uber","type":"Portal","wcid":46953,"cell":"585201E7","place":"dungeon","dest":{"cell":"585201DA","place":"dungeon","name":"Proving Grounds Uber"},"quest":true,"desc":"In Proving Grounds Uber.","id":2833}, + {"name":"Citadel Apex","type":"Portal","wcid":21400,"cell":"5854012A","place":"dungeon","dest":{"cell":"BAC60015","place":"outdoor","ns":56.9,"ew":47.09},"desc":"In a dungeon (landblock 5854).","id":2834}, + {"name":"Surface","type":"Portal","wcid":47154,"cell":"58560122","place":"dungeon","dest":{"cell":"87670032","place":"outdoor","ns":-19.37,"ew":6.69},"minLevel":200,"desc":"In Foundry of Izexi.","id":2835}, + {"name":"Surface","type":"Portal","wcid":47209,"cell":"585E0185","place":"dungeon","dest":{"cell":"A4210001","place":"outdoor","ns":-75.5,"ew":29.26},"minLevel":150,"desc":"In Falatacot Depot.","id":2836}, + {"name":"Surface","type":"Portal","wcid":72981,"cell":"586001AC","place":"dungeon","dest":{"cell":"519C0009","place":"outdoor","ns":22.9,"ew":-37.03},"desc":"In Colton Reeyan's Sanctuary.","id":2837}, + {"name":"Surface","type":"Portal","wcid":72981,"cell":"58600173","place":"dungeon","dest":{"cell":"519C0009","place":"outdoor","ns":22.9,"ew":-37.03},"desc":"In Colton Reeyan's Sanctuary.","id":2838}, + {"name":"Surface","type":"Portal","wcid":48735,"cell":"5861012F","place":"dungeon","dest":{"cell":"9F2C002A","place":"outdoor","ns":-66.58,"ew":25.83},"desc":"In Crystal Core.","id":2839}, + {"name":"Surface","type":"Portal","wcid":48735,"cell":"58610179","place":"dungeon","dest":{"cell":"9F2C002A","place":"outdoor","ns":-66.58,"ew":25.83},"desc":"In Crystal Core.","id":2840}, + {"name":"Surface","type":"Portal","wcid":48800,"cell":"5862010D","place":"dungeon","dest":{"cell":"482E0131","place":"building","ns":-65.0,"ew":-44.04},"desc":"In Count Phainor's Tomb.","id":2841}, + {"name":"Surface","type":"Portal","wcid":48901,"cell":"5863010E","place":"dungeon","dest":{"cell":"8865002B","place":"outdoor","ns":-20.89,"ew":7.4},"minLevel":180,"desc":"In Desert Dwelling.","id":2842}, + {"name":"Surface","type":"Portal","wcid":49450,"cell":"58640112","place":"dungeon","dest":{"cell":"4CE2001E","place":"outdoor","ns":79.36,"ew":-40.84},"minLevel":200,"desc":"In Samurai Hausu.","id":2843}, + {"name":"Surface","type":"Portal","wcid":49450,"cell":"58640122","place":"dungeon","dest":{"cell":"4CE2001E","place":"outdoor","ns":79.36,"ew":-40.84},"minLevel":200,"desc":"In Samurai Hausu.","id":2844}, + {"name":"Surface","type":"Portal","wcid":52216,"cell":"58650505","place":"dungeon","dest":{"cell":"EF1C003D","place":"outdoor","ns":-79.09,"ew":89.97},"minLevel":180,"desc":"In Stinging Corner.","id":2845}, + {"name":"Surface","type":"Portal","wcid":52219,"cell":"58650122","place":"dungeon","dest":{"cell":"0F08000C","place":"outdoor","ns":-95.23,"ew":-89.75},"minLevel":180,"desc":"In Stinging Corner.","id":2846}, + {"name":"Surface","type":"Portal","wcid":52215,"cell":"5866010C","place":"dungeon","dest":{"cell":"88650033","place":"outdoor","ns":-20.87,"ew":7.49},"minLevel":180,"desc":"In Sanctuary of the Recluse.","id":2847}, + {"name":"Surface","type":"Portal","wcid":49609,"cell":"5867010A","place":"dungeon","dest":{"cell":"96670004","place":"outdoor","ns":-19.23,"ew":18.12},"minLevel":180,"desc":"In Virindi Edifice.","id":2848}, + {"name":"Surface","type":"Portal","wcid":49609,"cell":"5867010C","place":"dungeon","dest":{"cell":"96670004","place":"outdoor","ns":-19.23,"ew":18.12},"minLevel":180,"desc":"In Virindi Edifice.","id":2849}, + {"name":"Virindi Edifice","type":"Portal","wcid":49608,"cell":"58670214","place":"dungeon","dest":{"cell":"5867026B","place":"dungeon","name":"Virindi Edifice"},"minLevel":180,"desc":"In Virindi Edifice.","id":2850}, + {"name":"Virindi Edifice","type":"Portal","wcid":49608,"cell":"58670183","place":"dungeon","dest":{"cell":"5867026B","place":"dungeon","name":"Virindi Edifice"},"minLevel":180,"desc":"In Virindi Edifice.","id":2851}, + {"name":"Surface","type":"Portal","wcid":72442,"cell":"58680163","place":"dungeon","dest":{"cell":"23B70026","place":"outdoor","ns":45.0,"ew":-73.5},"desc":"In Chiming.","id":2852}, + {"name":"Surface","type":"Portal","wcid":72442,"cell":"58680179","place":"dungeon","dest":{"cell":"23B70026","place":"outdoor","ns":45.0,"ew":-73.5},"desc":"In Chiming.","id":2853}, + {"name":"Surface","type":"Portal","wcid":72684,"cell":"5869010F","place":"dungeon","dest":{"cell":"1BBC0017","place":"outdoor","ns":49.08,"ew":-80.08},"desc":"In West Fork Dam Hive.","id":2854}, + {"name":"Western Royal Hive","type":"Portal","wcid":72434,"cell":"5869010D","place":"dungeon","dest":{"cell":"586A0148","place":"dungeon"},"minLevel":180,"quest":true,"desc":"In West Fork Dam Hive.","id":2855}, + {"name":"Western Royal Hive","type":"Portal","wcid":72434,"cell":"586A010C","place":"dungeon","dest":{"cell":"586A0148","place":"dungeon"},"minLevel":180,"quest":true,"desc":"In a dungeon (landblock 586A).","id":2856}, + {"name":"Western Royal Hive","type":"Portal","wcid":72434,"cell":"586A010D","place":"dungeon","dest":{"cell":"586A0148","place":"dungeon"},"minLevel":180,"quest":true,"desc":"In a dungeon (landblock 586A).","id":2857}, + {"name":"Grub Quarters","type":"Portal","wcid":72436,"cell":"586A011E","place":"dungeon","dest":{"cell":"586A011D","place":"dungeon"},"minLevel":180,"desc":"In a dungeon (landblock 586A).","id":2858}, + {"name":"Master's Quarters","type":"Portal","wcid":72437,"cell":"586A0158","place":"dungeon","dest":{"cell":"586A0157","place":"dungeon"},"minLevel":180,"desc":"In a dungeon (landblock 586A).","id":2859}, + {"name":"Queen's Quarters","type":"Portal","wcid":72454,"cell":"586A018E","place":"dungeon","dest":{"cell":"586B02FC","place":"dungeon"},"minLevel":180,"desc":"In a dungeon (landblock 586A).","id":2860}, + {"name":"Origin Quarters","type":"Portal","wcid":72435,"cell":"586A01A8","place":"dungeon","dest":{"cell":"586A01AA","place":"dungeon"},"minLevel":180,"desc":"In a dungeon (landblock 586A).","id":2861}, + {"name":"Western Royal Hive","type":"Portal","wcid":72434,"cell":"586A0149","place":"dungeon","dest":{"cell":"586A0148","place":"dungeon"},"minLevel":180,"quest":true,"desc":"In a dungeon (landblock 586A).","id":2862}, + {"name":"Western Royal Hive","type":"Portal","wcid":72434,"cell":"586A01AC","place":"dungeon","dest":{"cell":"586A0148","place":"dungeon"},"minLevel":180,"quest":true,"desc":"In a dungeon (landblock 586A).","id":2863}, + {"name":"Queen's Treasury","type":"Portal","wcid":72439,"cell":"586B010F","place":"dungeon","dest":{"cell":"586B0106","place":"dungeon"},"minLevel":180,"quest":true,"desc":"In a dungeon (landblock 586B).","id":2864}, + {"name":"Portal","type":"Portal","wcid":72438,"cell":"586B0169","place":"dungeon","dest":{"cell":"586B0114","place":"dungeon"},"minLevel":180,"desc":"In a dungeon (landblock 586B).","id":2865}, + {"name":"Surface","type":"Portal","wcid":72684,"cell":"586B0107","place":"dungeon","dest":{"cell":"1BBC0017","place":"outdoor","ns":49.08,"ew":-80.08},"desc":"In a dungeon (landblock 586B).","id":2866}, + {"name":"Masked Preface","type":"Portal","wcid":51282,"cell":"586C0105","place":"dungeon","dest":{"cell":"586C0406","place":"dungeon","name":"Masked Preface"},"minLevel":180,"desc":"In Masked Preface.","id":2867}, + {"name":"Portal","type":"Portal","wcid":51296,"cell":"586C01B1","place":"dungeon","dest":{"cell":"586C01D3","place":"dungeon","name":"Masked Preface"},"quest":true,"desc":"In Masked Preface.","id":2868}, + {"name":"Surface","type":"Portal","wcid":51283,"cell":"586C01EE","place":"dungeon","dest":{"cell":"8C430033","place":"outdoor","ns":-48.1,"ew":10.7},"desc":"In Masked Preface.","id":2869}, + {"name":"Masked Preface","type":"Portal","wcid":51282,"cell":"586C02D7","place":"dungeon","dest":{"cell":"586C0406","place":"dungeon","name":"Masked Preface"},"minLevel":180,"desc":"In Masked Preface.","id":2870}, + {"name":"Surface","type":"Portal","wcid":51283,"cell":"586C03E7","place":"dungeon","dest":{"cell":"8C430033","place":"outdoor","ns":-48.1,"ew":10.7},"desc":"In Masked Preface.","id":2871}, + {"name":"Surface","type":"Portal","wcid":51283,"cell":"586C03F4","place":"dungeon","dest":{"cell":"8C430033","place":"outdoor","ns":-48.1,"ew":10.7},"desc":"In Masked Preface.","id":2872}, + {"name":"Surface","type":"Portal","wcid":72740,"cell":"586D0100","place":"dungeon","dest":{"cell":"23BC0022","place":"outdoor","ns":48.63,"ew":-73.54},"desc":"In Hive Eviscerator Burrow.","id":2873}, + {"name":"Surface","type":"Portal","wcid":72740,"cell":"586D0168","place":"dungeon","dest":{"cell":"23BC0022","place":"outdoor","ns":48.63,"ew":-73.54},"desc":"In Hive Eviscerator Burrow.","id":2874}, + {"name":"Surface","type":"Portal","wcid":51326,"cell":"586E0167","place":"dungeon","dest":{"cell":"19BC0038","place":"outdoor","ns":49.16,"ew":-81.27},"minLevel":200,"desc":"In Hive Warrior Mound.","id":2875}, + {"name":"Tusker Den","type":"Portal","wcid":51428,"cell":"586F0103","place":"dungeon","dest":{"cell":"586F029B","place":"dungeon","name":"Tusker Den"},"minLevel":200,"desc":"In Tusker Den.","id":2876}, + {"name":"Surface","type":"Portal","wcid":51426,"cell":"586F017D","place":"dungeon","dest":{"cell":"77E8001F","place":"outdoor","ns":84.26,"ew":-6.36},"minLevel":200,"desc":"In Tusker Den.","id":2877}, + {"name":"Portal","type":"Portal","wcid":51404,"cell":"58700132","place":"dungeon","dest":{"cell":"5870010C","place":"dungeon","name":"Curator of Torment's Study"},"desc":"In Curator of Torment's Study.","id":2878}, + {"name":"Surface","type":"Portal","wcid":51403,"cell":"5870011B","place":"dungeon","dest":{"cell":"4E1C001E","place":"outdoor","ns":-79.0,"ew":-39.2},"desc":"In Curator of Torment's Study.","id":2879}, + {"name":"Surface","type":"Portal","wcid":51565,"cell":"58710164","place":"dungeon","dest":{"cell":"2D30002D","place":"outdoor","ns":-63.06,"ew":-65.39},"minLevel":180,"desc":"In Seed of Hatred.","id":2880}, + {"name":"Surface","type":"Portal","wcid":51570,"cell":"58720191","place":"dungeon","dest":{"cell":"2D30002D","place":"outdoor","ns":-63.06,"ew":-65.39},"minLevel":180,"desc":"In Seed of Misery.","id":2881}, + {"name":"Surface","type":"Portal","wcid":51581,"cell":"5873011F","place":"dungeon","dest":{"cell":"2D30002D","place":"outdoor","ns":-63.06,"ew":-65.39},"minLevel":180,"desc":"In Seed of Anger.","id":2882}, + {"name":"Surface","type":"Portal","wcid":51597,"cell":"587401B1","place":"dungeon","dest":{"cell":"4E1C001E","place":"outdoor","ns":-79.0,"ew":-39.2},"minLevel":180,"desc":"In a dungeon (landblock 5874).","id":2883}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740145","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2884}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740146","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2885}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740147","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2886}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740152","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2887}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740164","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2888}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740153","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2889}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740165","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2890}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740166","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2891}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740155","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2892}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740154","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2893}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740138","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2894}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740139","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2895}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740148","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2896}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740149","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2897}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"5874013A","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2898}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"5874012A","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2899}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740123","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2900}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740122","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2901}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740121","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2902}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740128","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2903}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740137","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2904}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740129","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2905}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"5874012B","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2906}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740124","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2907}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740125","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2908}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740126","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2909}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"5874012C","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2910}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"5874013B","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2911}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"5874012D","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2912}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"5874013C","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2913}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"5874012E","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2914}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740127","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2915}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"5874013D","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2916}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"5874014B","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2917}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740157","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2918}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740169","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2919}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740175","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2920}, + {"name":"Portal Floor Walk","type":"Portal","wcid":72119,"cell":"58740167","place":"dungeon","dest":{"cell":"58740109","place":"dungeon"},"desc":"In a dungeon (landblock 5874).","id":2921}, + {"name":"Surface","type":"Portal","wcid":51616,"cell":"58750267","place":"dungeon","dest":{"cell":"2C32003D","place":"outdoor","ns":-61.52,"ew":-65.96},"desc":"In Rynthid Genesis.","id":2922}, + {"name":"Portal","type":"Portal","wcid":51630,"cell":"58750103","place":"dungeon","dest":{"cell":"5875025C","place":"dungeon","name":"Rynthid Genesis"},"minLevel":180,"desc":"In Rynthid Genesis.","id":2923}, + {"name":"Surface","type":"Portal","wcid":51670,"cell":"587601C9","place":"dungeon","dest":{"cell":"2D310021","place":"outdoor","ns":-62.7,"ew":-65.5},"minLevel":180,"desc":"In Rynthid Foundry.","id":2924}, + {"name":"Surface","type":"Portal","wcid":51670,"cell":"587601C7","place":"dungeon","dest":{"cell":"2D310021","place":"outdoor","ns":-62.7,"ew":-65.5},"minLevel":180,"desc":"In Rynthid Foundry.","id":2925}, + {"name":"Surface","type":"Portal","wcid":51670,"cell":"58760110","place":"dungeon","dest":{"cell":"2D310021","place":"outdoor","ns":-62.7,"ew":-65.5},"minLevel":180,"desc":"In Rynthid Foundry.","id":2926}, + {"name":"Surface","type":"Portal","wcid":51670,"cell":"58760103","place":"dungeon","dest":{"cell":"2D310021","place":"outdoor","ns":-62.7,"ew":-65.5},"minLevel":180,"desc":"In Rynthid Foundry.","id":2927}, + {"name":"Surface","type":"Portal","wcid":51691,"cell":"587701D9","place":"dungeon","dest":{"cell":"2D310021","place":"outdoor","ns":-62.7,"ew":-65.5},"minLevel":180,"desc":"In Fear Factory.","id":2928}, + {"name":"Surface","type":"Portal","wcid":51691,"cell":"58770100","place":"dungeon","dest":{"cell":"2D310021","place":"outdoor","ns":-62.7,"ew":-65.5},"minLevel":180,"desc":"In Fear Factory.","id":2929}, + {"name":"Surface","type":"Portal","wcid":51764,"cell":"587802A0","place":"dungeon","dest":{"cell":"2C300007","place":"outdoor","ns":-62.89,"ew":-66.72},"minLevel":180,"desc":"In Spirited Halls.","id":2930}, + {"name":"Surface","type":"Portal","wcid":51764,"cell":"58780205","place":"dungeon","dest":{"cell":"2C300007","place":"outdoor","ns":-62.89,"ew":-66.72},"minLevel":180,"desc":"In Spirited Halls.","id":2931}, + {"name":"Surface","type":"Portal","wcid":51764,"cell":"58780150","place":"dungeon","dest":{"cell":"2C300007","place":"outdoor","ns":-62.89,"ew":-66.72},"minLevel":180,"desc":"In Spirited Halls.","id":2932}, + {"name":"Surface","type":"Portal","wcid":51764,"cell":"58780100","place":"dungeon","dest":{"cell":"2C300007","place":"outdoor","ns":-62.89,"ew":-66.72},"minLevel":180,"desc":"In Spirited Halls.","id":2933}, + {"name":"Portal","type":"Portal","wcid":51766,"cell":"587802F4","place":"dungeon","dest":{"cell":"587802EF","place":"dungeon","name":"Spirited Halls"},"minLevel":180,"desc":"In Spirited Halls.","id":2934}, + {"name":"Portal","type":"Portal","wcid":51768,"cell":"58780286","place":"dungeon","dest":{"cell":"58780285","place":"dungeon","name":"Spirited Halls"},"minLevel":180,"desc":"In Spirited Halls.","id":2935}, + {"name":"Portal","type":"Portal","wcid":51770,"cell":"587801BC","place":"dungeon","dest":{"cell":"58780204","place":"dungeon","name":"Spirited Halls"},"minLevel":180,"desc":"In Spirited Halls.","id":2936}, + {"name":"Portal","type":"Portal","wcid":51772,"cell":"58780121","place":"dungeon","dest":{"cell":"5878014F","place":"dungeon","name":"Spirited Halls"},"minLevel":180,"desc":"In Spirited Halls.","id":2937}, + {"name":"Surface","type":"Portal","wcid":51822,"cell":"5879052C","place":"dungeon","dest":{"cell":"2D310021","place":"outdoor","ns":-62.7,"ew":-65.5},"minLevel":180,"desc":"In Path of Sorrows.","id":2938}, + {"name":"Platforms of Torment","type":"Portal","wcid":51719,"cell":"587903B7","place":"dungeon","dest":{"cell":"2D31002E","place":"outdoor","ns":-62.17,"ew":-65.42},"minLevel":180,"desc":"In Path of Sorrows.","id":2939}, + {"name":"Platforms of Torment","type":"Portal","wcid":51719,"cell":"587903EC","place":"dungeon","dest":{"cell":"2D31002E","place":"outdoor","ns":-62.17,"ew":-65.42},"minLevel":180,"desc":"In Path of Sorrows.","id":2940}, + {"name":"Platforms of Rage","type":"Portal","wcid":51720,"cell":"587902C3","place":"dungeon","dest":{"cell":"2C300007","place":"outdoor","ns":-62.89,"ew":-66.72},"minLevel":180,"desc":"In Path of Sorrows.","id":2941}, + {"name":"Platforms of Sorrow","type":"Portal","wcid":72103,"cell":"5879019D","place":"dungeon","dest":{"cell":"2C300027","place":"outdoor","ns":-62.93,"ew":-66.32},"minLevel":180,"desc":"In Path of Sorrows.","id":2942}, + {"name":"Platforms of Rage","type":"Portal","wcid":51720,"cell":"5879025A","place":"dungeon","dest":{"cell":"2C300007","place":"outdoor","ns":-62.89,"ew":-66.72},"minLevel":180,"desc":"In Path of Sorrows.","id":2943}, + {"name":"Dark Tree Crystal Mine","type":"Portal","wcid":23076,"cell":"589E0000","place":"outdoor","ns":24.79,"ew":-31.27,"dest":{"cell":"56490196","place":"dungeon","name":"Dark Tree Crystal Mine"},"minLevel":100,"id":2944}, + {"name":"Trap Floor Walk High","type":"Portal","wcid":21522,"cell":"594401CE","place":"dungeon","dest":{"cell":"594401DB","place":"dungeon","name":"Proving Grounds High"},"desc":"In Proving Grounds High.","id":2945}, + {"name":"Trap Floor Walk High","type":"Portal","wcid":21522,"cell":"594401CF","place":"dungeon","dest":{"cell":"594401DB","place":"dungeon","name":"Proving Grounds High"},"desc":"In Proving Grounds High.","id":2946}, + {"name":"Trap Floor Walk High","type":"Portal","wcid":21522,"cell":"594401D0","place":"dungeon","dest":{"cell":"594401DB","place":"dungeon","name":"Proving Grounds High"},"desc":"In Proving Grounds High.","id":2947}, + {"name":"Trap Floor Walk High","type":"Portal","wcid":21522,"cell":"594401D7","place":"dungeon","dest":{"cell":"594401DB","place":"dungeon","name":"Proving Grounds High"},"desc":"In Proving Grounds High.","id":2948}, + {"name":"Trap Floor Walk High","type":"Portal","wcid":21522,"cell":"594401D8","place":"dungeon","dest":{"cell":"594401DB","place":"dungeon","name":"Proving Grounds High"},"desc":"In Proving Grounds High.","id":2949}, + {"name":"Trap Floor Walk High","type":"Portal","wcid":21522,"cell":"594401D9","place":"dungeon","dest":{"cell":"594401DB","place":"dungeon","name":"Proving Grounds High"},"desc":"In Proving Grounds High.","id":2950}, + {"name":"Trap Floor Walk High","type":"Portal","wcid":21522,"cell":"594401E2","place":"dungeon","dest":{"cell":"594401DB","place":"dungeon","name":"Proving Grounds High"},"desc":"In Proving Grounds High.","id":2951}, + {"name":"Trap Floor Walk High","type":"Portal","wcid":21522,"cell":"594401E3","place":"dungeon","dest":{"cell":"594401DB","place":"dungeon","name":"Proving Grounds High"},"desc":"In Proving Grounds High.","id":2952}, + {"name":"Trap Floor Walk High","type":"Portal","wcid":21522,"cell":"594401E4","place":"dungeon","dest":{"cell":"594401DB","place":"dungeon","name":"Proving Grounds High"},"desc":"In Proving Grounds High.","id":2953}, + {"name":"Citadel Valley","type":"Portal","wcid":21403,"cell":"5944015A","place":"dungeon","dest":{"cell":"BCC7000C","place":"outdoor","ns":57.6,"ew":48.6},"desc":"In Proving Grounds High.","id":2954}, + {"name":"Proving Grounds High","type":"Portal","wcid":21957,"cell":"594401D4","place":"dungeon","dest":{"cell":"594401E9","place":"dungeon","name":"Proving Grounds High"},"quest":true,"desc":"In Proving Grounds High.","id":2955}, + {"name":"Proving Grounds High","type":"Portal","wcid":21949,"cell":"594401E7","place":"dungeon","dest":{"cell":"594401D5","place":"dungeon","name":"Proving Grounds High"},"quest":true,"desc":"In Proving Grounds High.","id":2956}, + {"name":"Proving Grounds High","type":"Portal","wcid":21748,"cell":"594603BB","place":"dungeon","dest":{"cell":"594401A0","place":"dungeon","name":"Proving Grounds High"},"minLevel":60,"maxLevel":79,"quest":true,"desc":"In Fire Ziggurat.","id":2957}, + {"name":"Surface","type":"Portal","wcid":22658,"cell":"59480124","place":"dungeon","dest":{"cell":"EF7F000B","place":"outdoor","ns":-0.14,"ew":89.38},"desc":"In Tusker Armory.","id":2958}, + {"name":"Surface","type":"Portal","wcid":22687,"cell":"59490100","place":"dungeon","dest":{"cell":"F0730031","place":"outdoor","ns":-9.9,"ew":90.7},"desc":"In Tusker Lacuna.","id":2959}, + {"name":"Surface","type":"Portal","wcid":22687,"cell":"59490137","place":"dungeon","dest":{"cell":"F0730031","place":"outdoor","ns":-9.9,"ew":90.7},"desc":"In Tusker Lacuna.","id":2960}, + {"name":"Surface","type":"Portal","wcid":22649,"cell":"594A0102","place":"dungeon","dest":{"cell":"F483001B","place":"outdoor","ns":3.14,"ew":93.62},"desc":"In Chapel of Mowen.","id":2961}, + {"name":"Surface","type":"Portal","wcid":22649,"cell":"594A0115","place":"dungeon","dest":{"cell":"F483001B","place":"outdoor","ns":3.14,"ew":93.62},"desc":"In Chapel of Mowen.","id":2962}, + {"name":"Exit to Surface","type":"Portal","wcid":25393,"cell":"594B016E","place":"dungeon","dest":{"cell":"26310024","place":"outdoor","ns":-62.36,"ew":-71.06},"desc":"In Aerbax's Holding.","id":2963}, + {"name":"Exit to Surface","type":"Portal","wcid":25395,"cell":"594C0135","place":"dungeon","dest":{"cell":"69120024","place":"outdoor","ns":-87.23,"ew":-17.49},"desc":"In Gerent's Compound.","id":2964}, + {"name":"Exit to Surface","type":"Portal","wcid":25397,"cell":"594D012B","place":"dungeon","dest":{"cell":"1156000E","place":"outdoor","ns":-32.63,"ew":-88.16},"desc":"In Ancient Temple.","id":2965}, + {"name":"Surface","type":"Portal","wcid":45800,"cell":"594E0125","place":"dungeon","dest":{"cell":"8965002D","place":"outdoor","ns":-20.73,"ew":8.24},"desc":"In Deep Caves.","id":2966}, + {"name":"Surface","type":"Portal","wcid":45800,"cell":"594E0140","place":"dungeon","dest":{"cell":"8965002D","place":"outdoor","ns":-20.73,"ew":8.24},"desc":"In Deep Caves.","id":2967}, + {"name":"Temple Trial","type":"Portal","wcid":45801,"cell":"594E05FB","place":"dungeon","dest":{"cell":"594E0670","place":"dungeon","name":"Deep Caves"},"quest":true,"desc":"In Deep Caves.","id":2968}, + {"name":"Surface","type":"Portal","wcid":45800,"cell":"594E067F","place":"dungeon","dest":{"cell":"8965002D","place":"outdoor","ns":-20.73,"ew":8.24},"desc":"In Deep Caves.","id":2969}, + {"name":"Antechamber","type":"Portal","wcid":51367,"cell":"594F0277","place":"dungeon","dest":{"cell":"594F02C2","place":"dungeon","name":"Frozen Fortress"},"desc":"In Frozen Fortress.","id":2970}, + {"name":"Laboratory","type":"Portal","wcid":51368,"cell":"594F02AE","place":"dungeon","dest":{"cell":"594F0277","place":"dungeon","name":"Frozen Fortress"},"minLevel":180,"quest":true,"desc":"In Frozen Fortress.","id":2971}, + {"name":"Surface","type":"Portal","wcid":51320,"cell":"594F02C2","place":"dungeon","dest":{"cell":"77E70016","place":"outdoor","ns":83.4,"ew":-6.53},"desc":"In Frozen Fortress.","id":2972}, + {"name":"Testing Grounds","type":"Portal","wcid":51369,"cell":"594F02DC","place":"dungeon","dest":{"cell":"594F031E","place":"dungeon","name":"Frozen Fortress"},"minLevel":180,"quest":true,"desc":"In Frozen Fortress.","id":2973}, + {"name":"Antechamber","type":"Portal","wcid":51367,"cell":"594F02FB","place":"dungeon","dest":{"cell":"594F02C2","place":"dungeon","name":"Frozen Fortress"},"desc":"In Frozen Fortress.","id":2974}, + {"name":"Antechamber","type":"Portal","wcid":51367,"cell":"594F031E","place":"dungeon","dest":{"cell":"594F02C2","place":"dungeon","name":"Frozen Fortress"},"desc":"In Frozen Fortress.","id":2975}, + {"name":"Surface","type":"Portal","wcid":51911,"cell":"59510102","place":"dungeon","dest":{"cell":"2C2F0020","place":"outdoor","ns":-63.6,"ew":-66.4},"minLevel":180,"desc":"In Presk's Bunker.","id":2976}, + {"name":"Surface","type":"Portal","wcid":51911,"cell":"5951013E","place":"dungeon","dest":{"cell":"2C2F0020","place":"outdoor","ns":-63.6,"ew":-66.4},"minLevel":180,"desc":"In Presk's Bunker.","id":2977}, + {"name":"Presk's Treasury","type":"Portal","wcid":51912,"cell":"59510161","place":"dungeon","dest":{"cell":"5951010F","place":"dungeon","name":"Presk's Bunker"},"minLevel":180,"desc":"In Presk's Bunker.","id":2978}, + {"name":"Surface","type":"Portal","wcid":51911,"cell":"59510100","place":"dungeon","dest":{"cell":"2C2F0020","place":"outdoor","ns":-63.6,"ew":-66.4},"minLevel":180,"desc":"In Presk's Bunker.","id":2979}, + {"name":"Surface","type":"Portal","wcid":72047,"cell":"595201F4","place":"dungeon","dest":{"cell":"2C310001","place":"outdoor","ns":-62.72,"ew":-66.68},"desc":"In Bah'Ktar's Tower.","id":2980}, + {"name":"Assessment Chamber","type":"Portal","wcid":52079,"cell":"59530174","place":"dungeon","dest":{"cell":"59530182","place":"dungeon"},"minLevel":180,"desc":"In a dungeon (landblock 5953).","id":2981}, + {"name":"Surface","type":"Portal","wcid":52173,"cell":"59530187","place":"dungeon","dest":{"cell":"2C31002D","place":"outdoor","ns":-62.29,"ew":-66.21},"minLevel":180,"desc":"In a dungeon (landblock 5953).","id":2982}, + {"name":"Assessment Chamber","type":"Portal","wcid":52079,"cell":"5953012E","place":"dungeon","dest":{"cell":"59530182","place":"dungeon"},"minLevel":180,"desc":"In a dungeon (landblock 5953).","id":2983}, + {"name":"Assessment Chamber","type":"Portal","wcid":52079,"cell":"5953015A","place":"dungeon","dest":{"cell":"59530182","place":"dungeon"},"minLevel":180,"desc":"In a dungeon (landblock 5953).","id":2984}, + {"name":"Assessment Chamber","type":"Portal","wcid":52079,"cell":"5953012F","place":"dungeon","dest":{"cell":"59530182","place":"dungeon"},"minLevel":180,"desc":"In a dungeon (landblock 5953).","id":2985}, + {"name":"Surface","type":"Portal","wcid":51822,"cell":"59540818","place":"dungeon","dest":{"cell":"2D310021","place":"outdoor","ns":-62.7,"ew":-65.5},"minLevel":180,"desc":"In a dungeon (landblock 5954).","id":2986}, + {"name":"Surface","type":"Portal","wcid":51822,"cell":"5954015D","place":"dungeon","dest":{"cell":"2D310021","place":"outdoor","ns":-62.7,"ew":-65.5},"minLevel":180,"desc":"In a dungeon (landblock 5954).","id":2987}, + {"name":"Surface","type":"Portal","wcid":51822,"cell":"59540145","place":"dungeon","dest":{"cell":"2D310021","place":"outdoor","ns":-62.7,"ew":-65.5},"minLevel":180,"desc":"In a dungeon (landblock 5954).","id":2988}, + {"name":"Surface","type":"Portal","wcid":51822,"cell":"59540125","place":"dungeon","dest":{"cell":"2D310021","place":"outdoor","ns":-62.7,"ew":-65.5},"minLevel":180,"desc":"In a dungeon (landblock 5954).","id":2989}, + {"name":"Inner Sanctum","type":"Portal","wcid":52014,"cell":"5954081A","place":"dungeon","dest":{"cell":"59540144","place":"dungeon"},"minLevel":180,"quest":true,"desc":"In a dungeon (landblock 5954).","id":2990}, + {"name":"Inner Sanctum","type":"Portal","wcid":52013,"cell":"59540164","place":"dungeon","dest":{"cell":"59540144","place":"dungeon"},"minLevel":180,"desc":"In a dungeon (landblock 5954).","id":2991}, + {"name":"Surface","type":"Portal","wcid":52217,"cell":"595E013C","place":"dungeon","dest":{"cell":"4EF60022","place":"outdoor","ns":94.98,"ew":-39.13},"minLevel":180,"desc":"In Frozen Recess.","id":2992}, + {"name":"Surface","type":"Portal","wcid":52218,"cell":"595E026A","place":"dungeon","dest":{"cell":"B9F10040","place":"outdoor","ns":91.58,"ew":46.82},"minLevel":180,"desc":"In Frozen Recess.","id":2993}, + {"name":"Celestial Hand Gauntlet","type":"Portal","wcid":53446,"cell":"59600112","place":"dungeon","dest":{"cell":"596B0118","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5960).","id":2994}, + {"name":"Celestial Hand Gauntlet","type":"Portal","wcid":53446,"cell":"59600117","place":"dungeon","dest":{"cell":"596B0118","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5960).","id":2995}, + {"name":"Celestial Hand Gauntlet","type":"Portal","wcid":53446,"cell":"59610112","place":"dungeon","dest":{"cell":"596B0118","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5961).","id":2996}, + {"name":"Celestial Hand Gauntlet","type":"Portal","wcid":53446,"cell":"59610117","place":"dungeon","dest":{"cell":"596B0118","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5961).","id":2997}, + {"name":"Eldrytch Web Gauntlet","type":"Portal","wcid":53447,"cell":"59620112","place":"dungeon","dest":{"cell":"596B0110","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5962).","id":2998}, + {"name":"Eldrytch Web Gauntlet","type":"Portal","wcid":53447,"cell":"59620117","place":"dungeon","dest":{"cell":"596B0110","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5962).","id":2999}, + {"name":"Eldrytch Web Gauntlet","type":"Portal","wcid":53447,"cell":"59630112","place":"dungeon","dest":{"cell":"596B0110","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5963).","id":3000}, + {"name":"Eldrytch Web Gauntlet","type":"Portal","wcid":53447,"cell":"59630117","place":"dungeon","dest":{"cell":"596B0110","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5963).","id":3001}, + {"name":"Radiant Blood Gauntlet","type":"Portal","wcid":53445,"cell":"59640112","place":"dungeon","dest":{"cell":"596B010F","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5964).","id":3002}, + {"name":"Radiant Blood Gauntlet","type":"Portal","wcid":53445,"cell":"59640117","place":"dungeon","dest":{"cell":"596B010F","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5964).","id":3003}, + {"name":"Radiant Blood Gauntlet","type":"Portal","wcid":53445,"cell":"59650112","place":"dungeon","dest":{"cell":"596B010F","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5965).","id":3004}, + {"name":"Radiant Blood Gauntlet","type":"Portal","wcid":53445,"cell":"59650117","place":"dungeon","dest":{"cell":"596B010F","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"desc":"In a dungeon (landblock 5965).","id":3005}, + {"name":"Surface","type":"Portal","wcid":37164,"cell":"596B011F","place":"dungeon","dest":{"cell":"808F0014","place":"outdoor","ns":12.8,"ew":0.68},"desc":"In Radiant Blood Gauntlet.","id":3006}, + {"name":"Surface","type":"Portal","wcid":37386,"cell":"596B0121","place":"dungeon","dest":{"cell":"BDA00023","place":"outdoor","ns":26.26,"ew":49.65},"desc":"In Radiant Blood Gauntlet.","id":3007}, + {"name":"Surface","type":"Portal","wcid":37384,"cell":"596B0125","place":"dungeon","dest":{"cell":"E74D003F","place":"outdoor","ns":-39.7,"ew":83.6},"desc":"In Radiant Blood Gauntlet.","id":3008}, + {"name":"Portal to Holtburg","type":"Portal","wcid":42820,"cell":"596B0129","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal goes to Holtburg, an Aluvian town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Radiant Blood Gauntlet.","id":3009}, + {"name":"Portal to Yaraq","type":"Portal","wcid":42824,"cell":"596B0129","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal goes to Yaraq, a Gharu'ndim town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Radiant Blood Gauntlet.","id":3010}, + {"name":"Portal to Shoushi","type":"Portal","wcid":42840,"cell":"596B012F","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal goes to Shoushi, a Sho town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Radiant Blood Gauntlet.","id":3011}, + {"name":"Portal to Sanamar","type":"Portal","wcid":42835,"cell":"596B012F","place":"dungeon","dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"desc":"This portal goes to Sanamar, the capital of New Viamont and town where many new adventurers enter Dereth. This is a good town for characters of all levels. In Radiant Blood Gauntlet.","id":3012}, + {"name":"Asheron's Castle","type":"Portal","wcid":35293,"cell":"596B012E","place":"dungeon","dest":{"cell":"D59A0039","place":"outdoor","ns":21.26,"ew":69.19},"desc":"In Radiant Blood Gauntlet.","id":3013}, + {"name":"Blighted Putrid Moarsman Tunnels","type":"Portal","wcid":38156,"cell":"599B0015","place":"outdoor","ns":22.5,"ew":-30.46,"dest":{"cell":"00C3037C","place":"dungeon","name":"Blighted Putrid Moarsman Tunnels"},"minLevel":55,"id":3014}, + {"name":"Trap Floor Walk Extreme","type":"Portal","wcid":21521,"cell":"5A4401CE","place":"dungeon","dest":{"cell":"5A4401DB","place":"dungeon","name":"Proving Grounds Extreme"},"desc":"In Proving Grounds Extreme.","id":3015}, + {"name":"Trap Floor Walk Extreme","type":"Portal","wcid":21521,"cell":"5A4401CF","place":"dungeon","dest":{"cell":"5A4401DB","place":"dungeon","name":"Proving Grounds Extreme"},"desc":"In Proving Grounds Extreme.","id":3016}, + {"name":"Trap Floor Walk Extreme","type":"Portal","wcid":21521,"cell":"5A4401D0","place":"dungeon","dest":{"cell":"5A4401DB","place":"dungeon","name":"Proving Grounds Extreme"},"desc":"In Proving Grounds Extreme.","id":3017}, + {"name":"Trap Floor Walk Extreme","type":"Portal","wcid":21521,"cell":"5A4401D7","place":"dungeon","dest":{"cell":"5A4401DB","place":"dungeon","name":"Proving Grounds Extreme"},"desc":"In Proving Grounds Extreme.","id":3018}, + {"name":"Trap Floor Walk Extreme","type":"Portal","wcid":21521,"cell":"5A4401D8","place":"dungeon","dest":{"cell":"5A4401DB","place":"dungeon","name":"Proving Grounds Extreme"},"desc":"In Proving Grounds Extreme.","id":3019}, + {"name":"Trap Floor Walk Extreme","type":"Portal","wcid":21521,"cell":"5A4401D9","place":"dungeon","dest":{"cell":"5A4401DB","place":"dungeon","name":"Proving Grounds Extreme"},"desc":"In Proving Grounds Extreme.","id":3020}, + {"name":"Trap Floor Walk Extreme","type":"Portal","wcid":21521,"cell":"5A4401E2","place":"dungeon","dest":{"cell":"5A4401DB","place":"dungeon","name":"Proving Grounds Extreme"},"desc":"In Proving Grounds Extreme.","id":3021}, + {"name":"Trap Floor Walk Extreme","type":"Portal","wcid":21521,"cell":"5A4401E3","place":"dungeon","dest":{"cell":"5A4401DB","place":"dungeon","name":"Proving Grounds Extreme"},"desc":"In Proving Grounds Extreme.","id":3022}, + {"name":"Trap Floor Walk Extreme","type":"Portal","wcid":21521,"cell":"5A4401E4","place":"dungeon","dest":{"cell":"5A4401DB","place":"dungeon","name":"Proving Grounds Extreme"},"desc":"In Proving Grounds Extreme.","id":3023}, + {"name":"Citadel Valley","type":"Portal","wcid":21406,"cell":"5A44015A","place":"dungeon","dest":{"cell":"BBC80012","place":"outdoor","ns":58.2,"ew":47.9},"desc":"In Proving Grounds Extreme.","id":3024}, + {"name":"Proving Grounds Extreme","type":"Portal","wcid":21956,"cell":"5A4401D4","place":"dungeon","dest":{"cell":"5A4401E9","place":"dungeon","name":"Proving Grounds Extreme"},"quest":true,"desc":"In Proving Grounds Extreme.","id":3025}, + {"name":"Proving Grounds Extreme","type":"Portal","wcid":21948,"cell":"5A4401E7","place":"dungeon","dest":{"cell":"5A4401D5","place":"dungeon","name":"Proving Grounds Extreme"},"quest":true,"desc":"In Proving Grounds Extreme.","id":3026}, + {"name":"Proving Grounds Extreme","type":"Portal","wcid":21747,"cell":"5A4603BB","place":"dungeon","dest":{"cell":"5A4401A0","place":"dungeon","name":"Proving Grounds Extreme"},"minLevel":80,"maxLevel":149,"quest":true,"desc":"In Frost Ziggurat.","id":3027}, + {"name":"Surface","type":"Portal","wcid":22662,"cell":"5A480124","place":"dungeon","dest":{"cell":"F07F0039","place":"outdoor","ns":-0.27,"ew":90.79},"desc":"In Tusker Barracks.","id":3028}, + {"name":"Surface","type":"Portal","wcid":22683,"cell":"5A490102","place":"dungeon","dest":{"cell":"EC7D0008","place":"outdoor","ns":-1.25,"ew":86.94},"desc":"In Tusker Honeycombs.","id":3029}, + {"name":"Surface","type":"Portal","wcid":22691,"cell":"5A4A0100","place":"dungeon","dest":{"cell":"F2800010","place":"outdoor","ns":1.18,"ew":91.75},"desc":"In Tusker Pits.","id":3030}, + {"name":"Murk Warrens","type":"Portal","wcid":7248,"cell":"5AD30000","place":"outdoor","ns":67.49,"ew":-29.33,"dest":{"cell":"01020121","place":"dungeon","name":"Murk Warrens"},"id":3031}, + {"name":"Exit to the Surface","type":"Portal","wcid":22012,"cell":"5B430419","place":"dungeon","dest":{"cell":"19B0003B","place":"outdoor","ns":39.06,"ew":-81.17},"desc":"In Olthoi Arcade.","id":3032}, + {"name":"Olthoi Arcade Central","type":"Portal","wcid":22189,"cell":"5B43013A","place":"dungeon","dest":{"cell":"5B440379","place":"dungeon"},"minLevel":30,"desc":"In Olthoi Arcade.","id":3033}, + {"name":"Exit to Olthoi Arcade North","type":"Portal","wcid":22190,"cell":"5B440379","place":"dungeon","dest":{"cell":"5B430139","place":"dungeon","name":"Olthoi Arcade"},"desc":"In a dungeon (landblock 5B44).","id":3034}, + {"name":"Olthoi Arcade","type":"Portal","wcid":22191,"cell":"5B44013B","place":"dungeon","dest":{"cell":"5D49014D","place":"dungeon"},"desc":"In a dungeon (landblock 5B44).","id":3035}, + {"name":"Portal","type":"Portal","wcid":24070,"cell":"5B45010C","place":"dungeon","dest":{"cell":"5C4B0371","place":"dungeon"},"desc":"In Virindi Complex.","id":3036}, + {"name":"Portal","type":"Portal","wcid":24070,"cell":"5B450123","place":"dungeon","dest":{"cell":"5C4B0371","place":"dungeon"},"desc":"In Virindi Complex.","id":3037}, + {"name":"Portal","type":"Portal","wcid":24037,"cell":"5B450174","place":"dungeon","dest":{"cell":"5B45020D","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3038}, + {"name":"Surface","type":"Portal","wcid":24050,"cell":"5B450183","place":"dungeon","dest":{"cell":"9EDB002D","place":"outdoor","ns":73.74,"ew":25.03},"desc":"In Virindi Complex.","id":3039}, + {"name":"Portal","type":"Portal","wcid":24043,"cell":"5B450195","place":"dungeon","dest":{"cell":"5B450265","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3040}, + {"name":"Portal","type":"Portal","wcid":24040,"cell":"5B45019C","place":"dungeon","dest":{"cell":"5B4501D7","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3041}, + {"name":"Portal","type":"Portal","wcid":24084,"cell":"5B45019D","place":"dungeon","dest":{"cell":"5B450210","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3042}, + {"name":"Portal","type":"Portal","wcid":24038,"cell":"5B45019F","place":"dungeon","dest":{"cell":"5B450210","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3043}, + {"name":"Portal","type":"Portal","wcid":24077,"cell":"5B4501A1","place":"dungeon","dest":{"cell":"5B45020D","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3044}, + {"name":"Portal","type":"Portal","wcid":24078,"cell":"5B4501A2","place":"dungeon","dest":{"cell":"5B450210","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3045}, + {"name":"Portal","type":"Portal","wcid":24094,"cell":"5B4501A3","place":"dungeon","dest":{"cell":"9CD80009","place":"outdoor","ns":70.87,"ew":22.96},"desc":"In Virindi Complex.","id":3046}, + {"name":"Portal","type":"Portal","wcid":24081,"cell":"5B4501A5","place":"dungeon","dest":{"cell":"5B45019B","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3047}, + {"name":"Portal","type":"Portal","wcid":24074,"cell":"5B4501A7","place":"dungeon","dest":{"cell":"5B4501FA","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3048}, + {"name":"Portal","type":"Portal","wcid":24076,"cell":"5B4501A8","place":"dungeon","dest":{"cell":"5B450265","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3049}, + {"name":"Portal","type":"Portal","wcid":24039,"cell":"5B4501A9","place":"dungeon","dest":{"cell":"5B45019B","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3050}, + {"name":"Portal","type":"Portal","wcid":24080,"cell":"5B4501AA","place":"dungeon","dest":{"cell":"5B450279","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3051}, + {"name":"Portal","type":"Portal","wcid":24082,"cell":"5B4501AC","place":"dungeon","dest":{"cell":"5B45020D","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3052}, + {"name":"Portal","type":"Portal","wcid":24041,"cell":"5B4501AD","place":"dungeon","dest":{"cell":"5B4501E9","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3053}, + {"name":"Portal","type":"Portal","wcid":24075,"cell":"5B4501AF","place":"dungeon","dest":{"cell":"5B4501AA","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3054}, + {"name":"Portal","type":"Portal","wcid":24079,"cell":"5B4501B1","place":"dungeon","dest":{"cell":"5B450265","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3055}, + {"name":"Portal","type":"Portal","wcid":24039,"cell":"5B4501B2","place":"dungeon","dest":{"cell":"5B45019B","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3056}, + {"name":"Portal","type":"Portal","wcid":24095,"cell":"5B4501B3","place":"dungeon","dest":{"cell":"A2DA0019","place":"outdoor","ns":72.47,"ew":27.96},"desc":"In Virindi Complex.","id":3057}, + {"name":"Portal","type":"Portal","wcid":24083,"cell":"5B4501B5","place":"dungeon","dest":{"cell":"5B450279","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3058}, + {"name":"Portal","type":"Portal","wcid":24072,"cell":"5B4501B6","place":"dungeon","dest":{"cell":"5B4501D7","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3059}, + {"name":"Portal","type":"Portal","wcid":24073,"cell":"5B4501B7","place":"dungeon","dest":{"cell":"5B4501FA","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3060}, + {"name":"Portal","type":"Portal","wcid":24098,"cell":"5B4501BA","place":"dungeon","dest":{"cell":"5B450289","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3061}, + {"name":"Portal","type":"Portal","wcid":24085,"cell":"5B4501BC","place":"dungeon","dest":{"cell":"5B45020D","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3062}, + {"name":"Portal","type":"Portal","wcid":24087,"cell":"5B4501BE","place":"dungeon","dest":{"cell":"5B450265","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3063}, + {"name":"Portal","type":"Portal","wcid":24091,"cell":"5B4501BF","place":"dungeon","dest":{"cell":"5B45020D","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3064}, + {"name":"Portal","type":"Portal","wcid":24090,"cell":"5B4501C0","place":"dungeon","dest":{"cell":"5B4501FA","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3065}, + {"name":"Portal","type":"Portal","wcid":24097,"cell":"5B4501C1","place":"dungeon","dest":{"cell":"9CD80009","place":"outdoor","ns":70.87,"ew":22.96},"desc":"In Virindi Complex.","id":3066}, + {"name":"Portal","type":"Portal","wcid":24095,"cell":"5B4501C2","place":"dungeon","dest":{"cell":"A2DA0019","place":"outdoor","ns":72.47,"ew":27.96},"desc":"In Virindi Complex.","id":3067}, + {"name":"Portal","type":"Portal","wcid":24047,"cell":"5B4501C3","place":"dungeon","dest":{"cell":"5B4501E9","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3068}, + {"name":"Portal","type":"Portal","wcid":24044,"cell":"5B4501C4","place":"dungeon","dest":{"cell":"5B4501FA","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3069}, + {"name":"Portal","type":"Portal","wcid":24086,"cell":"5B4501C5","place":"dungeon","dest":{"cell":"5B4501AA","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3070}, + {"name":"Portal","type":"Portal","wcid":24046,"cell":"5B4501CA","place":"dungeon","dest":{"cell":"5B4501FC","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3071}, + {"name":"Portal","type":"Portal","wcid":24096,"cell":"5B4501CD","place":"dungeon","dest":{"cell":"9EDB002D","place":"outdoor","ns":73.74,"ew":25.03},"desc":"In Virindi Complex.","id":3072}, + {"name":"Portal","type":"Portal","wcid":24088,"cell":"5B4501CF","place":"dungeon","dest":{"cell":"5B45019B","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3073}, + {"name":"Portal","type":"Portal","wcid":24045,"cell":"5B4501D0","place":"dungeon","dest":{"cell":"5B450279","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3074}, + {"name":"Portal","type":"Portal","wcid":24097,"cell":"5B4501D1","place":"dungeon","dest":{"cell":"9CD80009","place":"outdoor","ns":70.87,"ew":22.96},"desc":"In Virindi Complex.","id":3075}, + {"name":"Portal","type":"Portal","wcid":24089,"cell":"5B4501D2","place":"dungeon","dest":{"cell":"5B450210","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3076}, + {"name":"Portal","type":"Portal","wcid":24046,"cell":"5B4501D3","place":"dungeon","dest":{"cell":"5B4501FC","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3077}, + {"name":"Portal","type":"Portal","wcid":24093,"cell":"5B4501D4","place":"dungeon","dest":{"cell":"5B450279","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3078}, + {"name":"Portal","type":"Portal","wcid":24092,"cell":"5B4501D5","place":"dungeon","dest":{"cell":"5B4501FA","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3079}, + {"name":"Surface","type":"Portal","wcid":24050,"cell":"5B450308","place":"dungeon","dest":{"cell":"9EDB002D","place":"outdoor","ns":73.74,"ew":25.03},"desc":"In Virindi Complex.","id":3080}, + {"name":"Surface","type":"Portal","wcid":24050,"cell":"5B4502D7","place":"dungeon","dest":{"cell":"9EDB002D","place":"outdoor","ns":73.74,"ew":25.03},"desc":"In Virindi Complex.","id":3081}, + {"name":"Portal","type":"Portal","wcid":24048,"cell":"5B4501B9","place":"dungeon","dest":{"cell":"5B4501FC","place":"dungeon","name":"Virindi Complex"},"desc":"In Virindi Complex.","id":3082}, + {"name":"Surface","type":"Portal","wcid":22666,"cell":"5B460231","place":"dungeon","dest":{"cell":"F97F0010","place":"outdoor","ns":0.44,"ew":97.4},"desc":"In Tusker Cave.","id":3083}, + {"name":"Surface","type":"Portal","wcid":22679,"cell":"5B4701A8","place":"dungeon","dest":{"cell":"F77E0017","place":"outdoor","ns":-0.49,"ew":95.87},"desc":"In Tusker Habitat.","id":3084}, + {"name":"Surface","type":"Portal","wcid":22681,"cell":"5B480150","place":"dungeon","dest":{"cell":"EA7B0001","place":"outdoor","ns":-3.45,"ew":85.29},"desc":"In Tusker Holding.","id":3085}, + {"name":"Surface","type":"Portal","wcid":22653,"cell":"5B49010C","place":"dungeon","dest":{"cell":"EA7E002A","place":"outdoor","ns":-0.96,"ew":85.78},"desc":"In Plated Rifts.","id":3086}, + {"name":"Surface","type":"Portal","wcid":22693,"cell":"5B4A0100","place":"dungeon","dest":{"cell":"F67C003D","place":"outdoor","ns":-2.27,"ew":95.62},"desc":"In Tusker Quarters.","id":3087}, + {"name":"Desert March Portal","type":"Portal","wcid":9685,"cell":"5B9C0000","place":"outdoor","ns":22.89,"ew":-28.84,"dest":{"cell":"02AA022F","place":"dungeon","name":"Desert March"},"id":3088}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"5B9C002E","place":"outdoor","ns":23.37,"ew":-28.63,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3089}, + {"name":"Spirit Cell","type":"Portal","wcid":22895,"cell":"5BA00000","place":"outdoor","ns":26.49,"ew":-28.52,"dest":{"cell":"564A010D","place":"dungeon","name":"Spirit Cell"},"quest":true,"id":3090}, + {"name":"Black Spear Temple","type":"Portal","wcid":33780,"cell":"5BDB0030","place":"outdoor","ns":74.04,"ew":-28.61,"dest":{"cell":"00740528","place":"dungeon","name":"Black Spear Temple"},"maxLevel":100,"quest":true,"desc":"A Ruschk temple, where those who wish to follow the Black Spear prove their worth.","id":3091}, + {"name":"Surface","type":"Portal","wcid":22668,"cell":"5C430100","place":"dungeon","dest":{"cell":"F8800026","place":"outdoor","ns":1.03,"ew":96.89},"desc":"In Tusker Cavern.","id":3092}, + {"name":"Surface","type":"Portal","wcid":22668,"cell":"5C430137","place":"dungeon","dest":{"cell":"F8800026","place":"outdoor","ns":1.03,"ew":96.89},"desc":"In Tusker Cavern.","id":3093}, + {"name":"Surface","type":"Portal","wcid":22670,"cell":"5C4401A9","place":"dungeon","dest":{"cell":"F47A0014","place":"outdoor","ns":-3.98,"ew":93.5},"desc":"In Tusker Encampments.","id":3094}, + {"name":"Oolutanga's Refuge","type":"Portal","wcid":22775,"cell":"584A0105","place":"dungeon","dest":{"cell":"F6820033","place":"outdoor","ns":2.26,"ew":95.46},"desc":"In a dungeon (landblock 584A).","id":3095}, + {"name":"Surface","type":"Portal","wcid":22655,"cell":"5C450150","place":"dungeon","dest":{"cell":"F67B000C","place":"outdoor","ns":-3.16,"ew":95.0},"desc":"In Tusker Abode.","id":3096}, + {"name":"Surface","type":"Portal","wcid":22675,"cell":"5C460105","place":"dungeon","dest":{"cell":"EB730022","place":"outdoor","ns":-9.8,"ew":86.46},"desc":"In Tusker Gauntlet.","id":3097}, + {"name":"Surface","type":"Portal","wcid":22677,"cell":"5C470100","place":"dungeon","dest":{"cell":"FA7E001B","place":"outdoor","ns":-0.9,"ew":98.42},"desc":"In Tusker Grotto.","id":3098}, + {"name":"Surface","type":"Portal","wcid":22751,"cell":"5C480174","place":"dungeon","dest":{"cell":"E97D002F","place":"outdoor","ns":-1.33,"ew":84.95},"desc":"In Rampage Bluff.","id":3099}, + {"name":"Surface","type":"Portal","wcid":22695,"cell":"5C490100","place":"dungeon","dest":{"cell":"F97E0035","place":"outdoor","ns":-0.68,"ew":97.94},"desc":"In Tusker Retreat.","id":3100}, + {"name":"Exit","type":"Portal","wcid":24071,"cell":"5C4B0311","place":"dungeon","dest":{"cell":"5B4502DC","place":"dungeon","name":"Virindi Complex"},"desc":"In a dungeon (landblock 5C4B).","id":3101}, + {"name":"Exit","type":"Portal","wcid":24071,"cell":"5C4B036C","place":"dungeon","dest":{"cell":"5B4502DC","place":"dungeon","name":"Virindi Complex"},"desc":"In a dungeon (landblock 5C4B).","id":3102}, + {"name":"Central Tuatara Plains Portal","type":"Portal","wcid":12161,"cell":"5C9D0000","place":"outdoor","ns":23.93,"ew":-28.03,"dest":{"cell":"21C5001D","place":"outdoor","ns":56.14,"ew":-75.24},"minLevel":35,"id":3103}, + {"name":"Destroyed Stonehold Portal","type":"Portal","wcid":4044,"cell":"5CEA0000","place":"outdoor","ns":85.83,"ew":-27.59,"dest":{"cell":"64D5000B","place":"outdoor","ns":68.66,"ew":-21.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3104}, + {"name":"Surface","type":"Portal","wcid":22703,"cell":"5D450100","place":"dungeon","dest":{"cell":"EB7F0017","place":"outdoor","ns":0.27,"ew":86.34},"desc":"In Tusker Tunnels.","id":3105}, + {"name":"Surface","type":"Portal","wcid":22707,"cell":"5D46010C","place":"dungeon","dest":{"cell":"F481001F","place":"outdoor","ns":1.9,"ew":93.56},"desc":"In Vengeance Caverns.","id":3106}, + {"name":"Surface","type":"Portal","wcid":22707,"cell":"5D460114","place":"dungeon","dest":{"cell":"F481001F","place":"outdoor","ns":1.9,"ew":93.56},"desc":"In Vengeance Caverns.","id":3107}, + {"name":"Inner Sanctum","type":"Portal","wcid":22758,"cell":"5D470102","place":"dungeon","dest":{"cell":"7F15002E","place":"outdoor","ns":-84.62,"ew":0.22},"desc":"In a dungeon (landblock 5D47).","id":3108}, + {"name":"Inner Sanctum","type":"Portal","wcid":22758,"cell":"5D470103","place":"dungeon","dest":{"cell":"7F15002E","place":"outdoor","ns":-84.62,"ew":0.22},"desc":"In a dungeon (landblock 5D47).","id":3109}, + {"name":"Inner Sanctum","type":"Portal","wcid":22758,"cell":"5D470101","place":"dungeon","dest":{"cell":"7F15002E","place":"outdoor","ns":-84.62,"ew":0.22},"desc":"In a dungeon (landblock 5D47).","id":3110}, + {"name":"Inner Sanctum","type":"Portal","wcid":22757,"cell":"5D470100","place":"dungeon","dest":{"cell":"5D470183","place":"dungeon"},"desc":"In a dungeon (landblock 5D47).","id":3111}, + {"name":"Surface","type":"Portal","wcid":22756,"cell":"5D470175","place":"dungeon","dest":{"cell":"7F15002E","place":"outdoor","ns":-84.62,"ew":0.22},"desc":"In a dungeon (landblock 5D47).","id":3112}, + {"name":"Inner Sanctum","type":"Portal","wcid":22758,"cell":"5D470105","place":"dungeon","dest":{"cell":"7F15002E","place":"outdoor","ns":-84.62,"ew":0.22},"desc":"In a dungeon (landblock 5D47).","id":3113}, + {"name":"Inner Sanctum","type":"Portal","wcid":22758,"cell":"5D470104","place":"dungeon","dest":{"cell":"7F15002E","place":"outdoor","ns":-84.62,"ew":0.22},"desc":"In a dungeon (landblock 5D47).","id":3114}, + {"name":"Inner Sanctum","type":"Portal","wcid":22758,"cell":"5D470106","place":"dungeon","dest":{"cell":"7F15002E","place":"outdoor","ns":-84.62,"ew":0.22},"desc":"In a dungeon (landblock 5D47).","id":3115}, + {"name":"Inner Sanctum","type":"Portal","wcid":22757,"cell":"5D470107","place":"dungeon","dest":{"cell":"5D470183","place":"dungeon"},"desc":"In a dungeon (landblock 5D47).","id":3116}, + {"name":"Inner Sanctum","type":"Portal","wcid":22762,"cell":"5D480102","place":"dungeon","dest":{"cell":"7FEE0024","place":"outdoor","ns":88.76,"ew":0.08},"desc":"In a dungeon (landblock 5D48).","id":3117}, + {"name":"Inner Sanctum","type":"Portal","wcid":22762,"cell":"5D480103","place":"dungeon","dest":{"cell":"7FEE0024","place":"outdoor","ns":88.76,"ew":0.08},"desc":"In a dungeon (landblock 5D48).","id":3118}, + {"name":"Inner Sanctum","type":"Portal","wcid":22762,"cell":"5D480101","place":"dungeon","dest":{"cell":"7FEE0024","place":"outdoor","ns":88.76,"ew":0.08},"desc":"In a dungeon (landblock 5D48).","id":3119}, + {"name":"Inner Sanctum","type":"Portal","wcid":22761,"cell":"5D480100","place":"dungeon","dest":{"cell":"5D480183","place":"dungeon"},"desc":"In a dungeon (landblock 5D48).","id":3120}, + {"name":"Surface","type":"Portal","wcid":22760,"cell":"5D480175","place":"dungeon","dest":{"cell":"7FEE0024","place":"outdoor","ns":88.76,"ew":0.08},"desc":"In a dungeon (landblock 5D48).","id":3121}, + {"name":"Inner Sanctum","type":"Portal","wcid":22762,"cell":"5D480105","place":"dungeon","dest":{"cell":"7FEE0024","place":"outdoor","ns":88.76,"ew":0.08},"desc":"In a dungeon (landblock 5D48).","id":3122}, + {"name":"Inner Sanctum","type":"Portal","wcid":22762,"cell":"5D480104","place":"dungeon","dest":{"cell":"7FEE0024","place":"outdoor","ns":88.76,"ew":0.08},"desc":"In a dungeon (landblock 5D48).","id":3123}, + {"name":"Inner Sanctum","type":"Portal","wcid":22762,"cell":"5D480106","place":"dungeon","dest":{"cell":"7FEE0024","place":"outdoor","ns":88.76,"ew":0.08},"desc":"In a dungeon (landblock 5D48).","id":3124}, + {"name":"Inner Sanctum","type":"Portal","wcid":22761,"cell":"5D480107","place":"dungeon","dest":{"cell":"5D480183","place":"dungeon"},"desc":"In a dungeon (landblock 5D48).","id":3125}, + {"name":"Central Olthoi Arcade","type":"Portal","wcid":22192,"cell":"5D49014D","place":"dungeon","dest":{"cell":"5B44013A","place":"dungeon"},"desc":"In a dungeon (landblock 5D49).","id":3126}, + {"name":"Exit to the Surface","type":"Portal","wcid":22193,"cell":"5D490386","place":"dungeon","dest":{"cell":"12930032","place":"outdoor","ns":15.84,"ew":-86.9},"desc":"In a dungeon (landblock 5D49).","id":3127}, + {"name":"Shallow Olthoi Chasm","type":"Portal","wcid":25685,"cell":"5D4A010B","place":"dungeon","dest":{"cell":"5D4B0146","place":"dungeon"},"minLevel":40,"desc":"In Olthoi Chasm.","id":3128}, + {"name":"Deep Olthoi Chasm","type":"Portal","wcid":25686,"cell":"5D4B032F","place":"dungeon","dest":{"cell":"5D4C0251","place":"dungeon"},"minLevel":60,"desc":"In a dungeon (landblock 5D4B).","id":3129}, + {"name":"Cavernous Olthoi Chasm","type":"Portal","wcid":25687,"cell":"5D4C0108","place":"dungeon","dest":{"cell":"5D4D0360","place":"dungeon"},"minLevel":80,"desc":"In a dungeon (landblock 5D4C).","id":3130}, + {"name":"Abyssal Olthoi Chasm","type":"Portal","wcid":25688,"cell":"5D4D013B","place":"dungeon","dest":{"cell":"5D4E02EF","place":"dungeon"},"minLevel":100,"desc":"In a dungeon (landblock 5D4D).","id":3131}, + {"name":"Surface Portal","type":"Portal","wcid":46019,"cell":"5D4E0113","place":"dungeon","dest":{"cell":"B7800013","place":"outdoor","ns":0.68,"ew":44.69},"desc":"In a dungeon (landblock 5D4E).","id":3132}, + {"name":"Hidden Laboratory","type":"Portal","wcid":36611,"cell":"5DD30024","place":"outdoor","ns":67.25,"ew":-27.15,"dest":{"cell":"00A402A1","place":"dungeon","name":"Hidden Laboratory"},"minLevel":150,"id":3133}, + {"name":"Throne of the Tusker King","type":"Portal","wcid":22701,"cell":"5E430109","place":"dungeon","dest":{"cell":"5F4401A7","place":"dungeon"},"desc":"In a dungeon (landblock 5E43).","id":3134}, + {"name":"Legend of the Tusker King","type":"Portal","wcid":22650,"cell":"5E440101","place":"dungeon","dest":{"cell":"5F4301D6","place":"dungeon"},"minLevel":80,"desc":"In a dungeon (landblock 5E44).","id":3135}, + {"name":"Surface","type":"Portal","wcid":1091,"cell":"5E450372","place":"dungeon","dest":{"cell":"D8CA0014","place":"outdoor","ns":60.03,"ew":71.09},"desc":"In Black Death Catacombs.","id":3136}, + {"name":"Lower Corridor","type":"Portal","wcid":24331,"cell":"5E450100","place":"dungeon","dest":{"cell":"614402AD","place":"dungeon"},"desc":"In Black Death Catacombs.","id":3137}, + {"name":"Lower Corridor","type":"Portal","wcid":24332,"cell":"5E450101","place":"dungeon","dest":{"cell":"614402B1","place":"dungeon"},"desc":"In Black Death Catacombs.","id":3138}, + {"name":"Lower Corridor","type":"Portal","wcid":24330,"cell":"5E450143","place":"dungeon","dest":{"cell":"614403A4","place":"dungeon"},"desc":"In Black Death Catacombs.","id":3139}, + {"name":"Lower Corridor","type":"Portal","wcid":24329,"cell":"5E45015E","place":"dungeon","dest":{"cell":"614403B6","place":"dungeon"},"desc":"In Black Death Catacombs.","id":3140}, + {"name":"Lower Corridor","type":"Portal","wcid":24328,"cell":"5E45015F","place":"dungeon","dest":{"cell":"614403B0","place":"dungeon"},"desc":"In Black Death Catacombs.","id":3141}, + {"name":"Asheron's Tower","type":"Portal","wcid":33590,"cell":"5E470105","place":"dungeon","dest":{"cell":"D599014C","place":"building","ns":21.21,"ew":69.09},"desc":"In Asheron's Sanctum.","id":3142}, + {"name":"Exit portal","type":"Portal","wcid":24882,"cell":"5E480178","place":"dungeon","dest":{"cell":"CBCA003F","place":"outdoor","ns":60.26,"ew":61.21},"desc":"In Olthoi Brood Hive.","id":3143}, + {"name":"Exit portal","type":"Portal","wcid":24882,"cell":"5E480446","place":"dungeon","dest":{"cell":"CBCA003F","place":"outdoor","ns":60.26,"ew":61.21},"desc":"In Olthoi Brood Hive.","id":3144}, + {"name":"Exit portal","type":"Portal","wcid":24883,"cell":"5E490122","place":"dungeon","dest":{"cell":"D7D2002D","place":"outdoor","ns":66.54,"ew":70.64},"desc":"In Olthoi Brood Hive.","id":3145}, + {"name":"Exit portal","type":"Portal","wcid":24883,"cell":"5E490420","place":"dungeon","dest":{"cell":"D7D2002D","place":"outdoor","ns":66.54,"ew":70.64},"desc":"In Olthoi Brood Hive.","id":3146}, + {"name":"Exit portal","type":"Portal","wcid":24634,"cell":"5E4A0178","place":"dungeon","dest":{"cell":"CAC00002","place":"outdoor","ns":51.81,"ew":59.71},"desc":"In Olthoi Brood Hive.","id":3147}, + {"name":"Exit portal","type":"Portal","wcid":24634,"cell":"5E4A0446","place":"dungeon","dest":{"cell":"CAC00002","place":"outdoor","ns":51.81,"ew":59.71},"desc":"In Olthoi Brood Hive.","id":3148}, + {"name":"Exit portal","type":"Portal","wcid":24636,"cell":"5E4B0122","place":"dungeon","dest":{"cell":"CAD8002D","place":"outdoor","ns":71.25,"ew":60.18},"desc":"In Olthoi Brood Hive.","id":3149}, + {"name":"Exit portal","type":"Portal","wcid":24636,"cell":"5E4B0420","place":"dungeon","dest":{"cell":"CAD8002D","place":"outdoor","ns":71.25,"ew":60.18},"desc":"In Olthoi Brood Hive.","id":3150}, + {"name":"Undisclosed Location","type":"Portal","wcid":25727,"cell":"5E4D010E","place":"dungeon","dest":{"cell":"C0810017","place":"outdoor","ns":1.92,"ew":51.89},"desc":"In a dungeon (landblock 5E4D).","id":3151}, + {"name":"Black Dominion Portal","type":"Portal","wcid":7200,"cell":"5F100000","place":"outdoor","ns":-88.63,"ew":-25.91,"dest":{"cell":"010A0223","place":"dungeon","name":"Black Dominion"},"minLevel":25,"id":3152}, + {"name":"Throne of the Tusker King","type":"Portal","wcid":22684,"cell":"5F430100","place":"dungeon","dest":{"cell":"5F4401A7","place":"dungeon"},"minLevel":80,"desc":"In a dungeon (landblock 5F43).","id":3153}, + {"name":"Arena of the Tusker Hero","type":"Portal","wcid":22656,"cell":"5F44019D","place":"dungeon","dest":{"cell":"5E430105","place":"dungeon"},"minLevel":80,"desc":"In a dungeon (landblock 5F44).","id":3154}, + {"name":"Idol of Wishes","type":"Portal","wcid":22708,"cell":"5F4401A0","place":"dungeon","dest":{"cell":"5F44014C","place":"dungeon"},"minLevel":80,"quest":true,"desc":"In a dungeon (landblock 5F44).","id":3155}, + {"name":"Surface","type":"Portal","wcid":22685,"cell":"5F4401AA","place":"dungeon","dest":{"cell":"F6820033","place":"outdoor","ns":2.26,"ew":95.46},"desc":"In a dungeon (landblock 5F44).","id":3156}, + {"name":"Throne of the Tusker King","type":"Portal","wcid":22684,"cell":"5F44019A","place":"dungeon","dest":{"cell":"5F4401A7","place":"dungeon"},"minLevel":80,"desc":"In a dungeon (landblock 5F44).","id":3157}, + {"name":"Eagle's Sight","type":"Portal","wcid":24162,"cell":"5F45011F","place":"dungeon","dest":{"cell":"5F45011E","place":"dungeon"},"desc":"In a dungeon (landblock 5F45).","id":3158}, + {"name":"Surface","type":"Portal","wcid":24163,"cell":"5F45013F","place":"dungeon","dest":{"cell":"46E3001C","place":"outdoor","ns":79.96,"ew":-45.55},"desc":"In a dungeon (landblock 5F45).","id":3159}, + {"name":"Surface","type":"Portal","wcid":24186,"cell":"5F46015D","place":"dungeon","dest":{"cell":"B0A9000D","place":"outdoor","ns":33.75,"ew":38.95},"desc":"In a dungeon (landblock 5F46).","id":3160}, + {"name":"Surface Portal","type":"Portal","wcid":25606,"cell":"5F470103","place":"dungeon","dest":{"cell":"43170036","place":"outdoor","ns":-82.96,"ew":-47.65},"desc":"In Elemental Caverns.","id":3161}, + {"name":"Surface Portal","type":"Portal","wcid":25606,"cell":"5F470107","place":"dungeon","dest":{"cell":"43170036","place":"outdoor","ns":-82.96,"ew":-47.65},"desc":"In Elemental Caverns.","id":3162}, + {"name":"Surface Portal","type":"Portal","wcid":25606,"cell":"5F47010B","place":"dungeon","dest":{"cell":"43170036","place":"outdoor","ns":-82.96,"ew":-47.65},"desc":"In Elemental Caverns.","id":3163}, + {"name":"Surface Portal","type":"Portal","wcid":25606,"cell":"5F47010F","place":"dungeon","dest":{"cell":"43170036","place":"outdoor","ns":-82.96,"ew":-47.65},"desc":"In Elemental Caverns.","id":3164}, + {"name":"Exit to Surface","type":"Portal","wcid":25571,"cell":"5F480110","place":"dungeon","dest":{"cell":"2D500022","place":"outdoor","ns":-37.85,"ew":-65.47},"desc":"In Hidden Cavern.","id":3165}, + {"name":"Exit to Surface","type":"Portal","wcid":25571,"cell":"5F480112","place":"dungeon","dest":{"cell":"2D500022","place":"outdoor","ns":-37.85,"ew":-65.47},"desc":"In Hidden Cavern.","id":3166}, + {"name":"Serpent Burial Grounds","type":"Portal","wcid":46336,"cell":"5FD30030","place":"outdoor","ns":67.58,"ew":-25.37,"dest":{"cell":"584E025C","place":"dungeon","name":"Serpent Burial Grounds"},"minLevel":150,"id":3167}, + {"name":"Tusker Food Storage","type":"Portal","wcid":22671,"cell":"60430192","place":"dungeon","dest":{"cell":"5E440367","place":"dungeon"},"minLevel":80,"desc":"In a dungeon (landblock 6043).","id":3168}, + {"name":"Tusker Warrior's Lair","type":"Portal","wcid":22704,"cell":"60440108","place":"dungeon","dest":{"cell":"604304F5","place":"dungeon"},"minLevel":80,"desc":"In Behind the Waterfall.","id":3169}, + {"name":"Caul Athenaeum","type":"Portal","wcid":22928,"cell":"60450106","place":"dungeon","dest":{"cell":"60460103","place":"dungeon"},"desc":"In Caul Asylum.","id":3170}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604602C0","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6046).","id":3171}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"6047011F","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3172}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470149","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3173}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470164","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3174}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470168","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3175}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"6047016B","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3176}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"6047018D","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3177}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470190","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3178}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604701B9","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3179}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604701BC","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3180}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604701CD","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3181}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604701EA","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3182}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604701F2","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3183}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604701F5","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3184}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470214","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3185}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470222","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3186}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470232","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3187}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470242","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3188}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470246","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3189}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470252","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3190}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604702B6","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3191}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604702CB","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3192}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604702D3","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3193}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604702EC","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3194}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"6047033B","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3195}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"6047038C","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3196}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"6047038F","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3197}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604703A0","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3198}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604703A5","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3199}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470422","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3200}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470430","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3201}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"6047045C","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3202}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"60470462","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3203}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"6047046B","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3204}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"6047046F","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3205}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22930,"cell":"604704A1","place":"dungeon","dest":{"cell":"60480225","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3206}, + {"name":"Caul Sanatorium","type":"Portal","wcid":22929,"cell":"604704A4","place":"dungeon","dest":{"cell":"604703D0","place":"dungeon"},"desc":"In a dungeon (landblock 6047).","id":3207}, + {"name":"Surface","type":"Portal","wcid":22931,"cell":"604801D6","place":"dungeon","dest":{"cell":"0D080028","place":"outdoor","ns":-94.78,"ew":-91.07},"desc":"In a dungeon (landblock 6048).","id":3208}, + {"name":"Surface","type":"Portal","wcid":25497,"cell":"60490328","place":"dungeon","dest":{"cell":"C0B6000D","place":"outdoor","ns":44.09,"ew":51.77},"desc":"In Renegade Garrison.","id":3209}, + {"name":"Surface","type":"Portal","wcid":25589,"cell":"604A0135","place":"dungeon","dest":{"cell":"21180106","place":"building","ns":-82.5,"ew":-74.99},"desc":"In Sclavus Temple.","id":3210}, + {"name":"Destroyed Portal to Yaraq","type":"Portal","wcid":1030,"cell":"604B0109","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 604B).","id":3211}, + {"name":"Destroyed Qalaba'r Portal","type":"Portal","wcid":1023,"cell":"604B0114","place":"dungeon","dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 604B).","id":3212}, + {"name":"Destroyed Portal to Nanto","type":"Portal","wcid":4569,"cell":"604B0117","place":"dungeon","dest":{"cell":"E63E0022","place":"outdoor","ns":-52.19,"ew":82.45},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 604B).","id":3213}, + {"name":"Destroyed Portal to Tou-Tou","type":"Portal","wcid":4568,"cell":"604B0122","place":"dungeon","dest":{"cell":"F5590034","place":"outdoor","ns":-30.41,"ew":94.69},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 604B).","id":3214}, + {"name":"Dericost Vault","type":"Portal","wcid":87560,"cell":"60DC0101","place":"dungeon","dest":{"cell":"0071045A","place":"dungeon"},"maxLevel":100,"quest":true,"desc":"In a dungeon (landblock 60DC).","id":3215}, + {"name":"Exit","type":"Portal","wcid":23771,"cell":"61430112","place":"dungeon","dest":{"cell":"73080105","place":"building","ns":-94.78,"ew":-9.72},"desc":"In Basement.","id":3216}, + {"name":"Upper Corridor","type":"Portal","wcid":24336,"cell":"614402AE","place":"dungeon","dest":{"cell":"5E450105","place":"dungeon","name":"Black Death Catacombs"},"desc":"In a dungeon (landblock 6144).","id":3217}, + {"name":"Upper Corridor","type":"Portal","wcid":24337,"cell":"614402B4","place":"dungeon","dest":{"cell":"5E450102","place":"dungeon","name":"Black Death Catacombs"},"desc":"In a dungeon (landblock 6144).","id":3218}, + {"name":"Upper Corridor","type":"Portal","wcid":24335,"cell":"614403AA","place":"dungeon","dest":{"cell":"5E450144","place":"dungeon","name":"Black Death Catacombs"},"desc":"In a dungeon (landblock 6144).","id":3219}, + {"name":"Upper Corridor","type":"Portal","wcid":24334,"cell":"614403B7","place":"dungeon","dest":{"cell":"5E450191","place":"dungeon","name":"Black Death Catacombs"},"desc":"In a dungeon (landblock 6144).","id":3220}, + {"name":"Upper Corridor","type":"Portal","wcid":24333,"cell":"614403B8","place":"dungeon","dest":{"cell":"5E450161","place":"dungeon","name":"Black Death Catacombs"},"desc":"In a dungeon (landblock 6144).","id":3221}, + {"name":"Deeper Catacombs","type":"Portal","wcid":24226,"cell":"61440101","place":"dungeon","dest":{"cell":"574D0160","place":"dungeon"},"minLevel":40,"desc":"In a dungeon (landblock 6144).","id":3222}, + {"name":"Surface","type":"Portal","wcid":25282,"cell":"6147015F","place":"dungeon","dest":{"cell":"2686000A","place":"outdoor","ns":5.39,"ew":-71.41},"desc":"In Mountain Citadel.","id":3223}, + {"name":"Surface","type":"Portal","wcid":24953,"cell":"6148015F","place":"dungeon","dest":{"cell":"34150037","place":"outdoor","ns":-84.49,"ew":-59.7},"desc":"In Desert Citadel.","id":3224}, + {"name":"Surface","type":"Portal","wcid":25511,"cell":"61490124","place":"dungeon","dest":{"cell":"95410037","place":"outdoor","ns":-49.26,"ew":17.88},"desc":"In Crystal Mine.","id":3225}, + {"name":"Surface","type":"Portal","wcid":25511,"cell":"614902DE","place":"dungeon","dest":{"cell":"95410037","place":"outdoor","ns":-49.26,"ew":17.88},"desc":"In Crystal Mine.","id":3226}, + {"name":"Surface portal","type":"Portal","wcid":25512,"cell":"614A045A","place":"dungeon","dest":{"cell":"808F001F","place":"outdoor","ns":13.14,"ew":0.81},"desc":"In Lair of the Ancient Queen.","id":3227}, + {"name":"Portal to the Surface","type":"Portal","wcid":27478,"cell":"62470106","place":"dungeon","dest":{"cell":"C25D0001","place":"outdoor","ns":-27.53,"ew":53.32},"desc":"In a dungeon (landblock 6247).","id":3228}, + {"name":"Portal to the Surface","type":"Portal","wcid":27480,"cell":"624803E9","place":"dungeon","dest":{"cell":"2D5B001E","place":"outdoor","ns":-28.6,"ew":-65.62},"desc":"In Renegade Fortress.","id":3229}, + {"name":"Exit to Surface","type":"Portal","wcid":27693,"cell":"624901DC","place":"dungeon","dest":{"cell":"CE7C0035","place":"outdoor","ns":-2.27,"ew":63.5},"desc":"In a dungeon (landblock 6249).","id":3230}, + {"name":"Exit to Surface","type":"Portal","wcid":27691,"cell":"624A037E","place":"dungeon","dest":{"cell":"BD700035","place":"outdoor","ns":-11.94,"ew":49.91},"desc":"In a dungeon (landblock 624A).","id":3231}, + {"name":"Northern Power Forge","type":"Portal","wcid":30472,"cell":"62960000","place":"outdoor","ns":18.38,"ew":-22.83,"dest":{"cell":"00040100","place":"dungeon","name":"Northern Power Forge"},"minLevel":40,"id":3232}, + {"name":"The Pit Dungeon Portal","type":"Portal","wcid":3628,"cell":"62CF0100","place":"dungeon","dest":{"cell":"01A302F3","place":"dungeon"},"minLevel":60,"desc":"In a dungeon (landblock 62CF).","id":3233}, + {"name":"Westward Portal","type":"Portal","wcid":443,"cell":"62D50000","place":"outdoor","ns":68.63,"ew":-23.28,"dest":{"cell":"5AD80010","place":"outdoor","ns":71.6,"ew":-29.78},"minLevel":15,"id":3234}, + {"name":"Collegium Entropica Conveyance","type":"Portal","wcid":24013,"cell":"6343022C","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3235}, + {"name":"Collegium Prae Auspi Conveyance","type":"Portal","wcid":24008,"cell":"63430233","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3236}, + {"name":"Collegium Ignae Fatae Conveyance","type":"Portal","wcid":24014,"cell":"6343023C","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3237}, + {"name":"Collegium Conjurae Conveyance","type":"Portal","wcid":24006,"cell":"63430243","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3238}, + {"name":"Collegium Geomancy Conveyance","type":"Portal","wcid":24016,"cell":"6343024C","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3239}, + {"name":"Collegium Artificae Conveyance","type":"Portal","wcid":24004,"cell":"63430257","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3240}, + {"name":"Collegium Heiromancy Conveyance","type":"Portal","wcid":24017,"cell":"63430260","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3241}, + {"name":"Collegium Acumen Manim Conveyance","type":"Portal","wcid":24003,"cell":"63430269","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3242}, + {"name":"Collegium Aegis Medi Conveyance","type":"Portal","wcid":24022,"cell":"63430272","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3243}, + {"name":"Collegium Organis Conveyance","type":"Portal","wcid":24023,"cell":"6343027C","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3244}, + {"name":"Collegium Planar Abstraction Conveyance","type":"Portal","wcid":24024,"cell":"6343027F","place":"dungeon","dest":{"cell":"00D60210","place":"dungeon"},"minLevel":130,"desc":"In a dungeon (landblock 6343).","id":3245}, + {"name":"Collegium Tempae Invectae Conveyance","type":"Portal","wcid":24026,"cell":"634302AA","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3246}, + {"name":"West Library Conveyance","type":"Portal","wcid":24021,"cell":"634302B4","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3247}, + {"name":"East Library Conveyance","type":"Portal","wcid":24018,"cell":"634302B7","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3248}, + {"name":"South Library Conveyance","type":"Portal","wcid":24020,"cell":"634302BA","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3249}, + {"name":"North Library Conveyance","type":"Portal","wcid":24019,"cell":"634302BD","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3250}, + {"name":"Forge Conveyance","type":"Portal","wcid":24015,"cell":"634302C6","place":"dungeon","dest":{"cell":"644501A1","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3251}, + {"name":"Research Chambers Conveyance","type":"Portal","wcid":24007,"cell":"634302CF","place":"dungeon","dest":{"cell":"644303AD","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3252}, + {"name":"Alaidain Dormitory Conveyance","type":"Portal","wcid":24009,"cell":"634302E3","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3253}, + {"name":"Atlan Dormitory Conveyance","type":"Portal","wcid":24010,"cell":"634302F3","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3254}, + {"name":"Maila Dormitory Conveyance","type":"Portal","wcid":24012,"cell":"634302FA","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3255}, + {"name":"Caerlin Dormitory Conveyance","type":"Portal","wcid":24011,"cell":"63430303","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3256}, + {"name":"Barracks Conveyance","type":"Portal","wcid":24005,"cell":"63430308","place":"dungeon","dest":{"cell":"6343028E","place":"dungeon"},"desc":"In a dungeon (landblock 6343).","id":3257}, + {"name":"Martine's Retreat","type":"Portal","wcid":20919,"cell":"63450208","place":"dungeon","dest":{"cell":"56600187","place":"dungeon","name":"Martine's Retreat"},"desc":"In a dungeon (landblock 6345).","id":3258}, + {"name":"Caliginous Bethel","type":"Portal","wcid":25674,"cell":"63480135","place":"dungeon","dest":{"cell":"63480313","place":"dungeon"},"minLevel":35,"desc":"In a dungeon (landblock 6348).","id":3259}, + {"name":"Exit","type":"Portal","wcid":25675,"cell":"6348031A","place":"dungeon","dest":{"cell":"22BC003E","place":"outdoor","ns":49.06,"ew":-73.95},"minLevel":35,"desc":"In a dungeon (landblock 6348).","id":3260}, + {"name":"Moarsmen Hideout","type":"Portal","wcid":8456,"cell":"634B036A","place":"dungeon","dest":{"cell":"02C4023F","place":"dungeon","name":"Moarsmen Hideout"},"desc":"In a dungeon (landblock 634B).","id":3261}, + {"name":"Mud Cave","type":"Portal","wcid":8474,"cell":"634B03B1","place":"dungeon","dest":{"cell":"02C1017E","place":"dungeon","name":"Mud Cave"},"desc":"In a dungeon (landblock 634B).","id":3262}, + {"name":"Moarsmen Spawning Grounds","type":"Portal","wcid":8584,"cell":"634B03FF","place":"dungeon","dest":{"cell":"02B502C1","place":"dungeon","name":"Moarsmen Spawning Grounds"},"desc":"In a dungeon (landblock 634B).","id":3263}, + {"name":"Moarsmen Muck","type":"Portal","wcid":8476,"cell":"634B0474","place":"dungeon","dest":{"cell":"02C201E6","place":"dungeon","name":"Moarsmen Muck"},"desc":"In a dungeon (landblock 634B).","id":3264}, + {"name":"Moars Laboratory","type":"Portal","wcid":8600,"cell":"634B048D","place":"dungeon","dest":{"cell":"02B301F6","place":"dungeon","name":"Moars Laboratory"},"desc":"In a dungeon (landblock 634B).","id":3265}, + {"name":"Exit To Surface","type":"Portal","wcid":25228,"cell":"634C03E0","place":"dungeon","dest":{"cell":"BE680008","place":"outdoor","ns":-17.99,"ew":50.12},"desc":"In Tainted Grotto.","id":3266}, + {"name":"Seat of Knorr Conveyance","type":"Portal","wcid":24025,"cell":"6443039B","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6443).","id":3267}, + {"name":"Barracks Conveyance","type":"Portal","wcid":24005,"cell":"644303A3","place":"dungeon","dest":{"cell":"6343028E","place":"dungeon"},"desc":"In a dungeon (landblock 6443).","id":3268}, + {"name":"East Library Conveyance","type":"Portal","wcid":24018,"cell":"644303B3","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6443).","id":3269}, + {"name":"Collegium Planar Abstraction Conveyance","type":"Portal","wcid":24024,"cell":"644303E5","place":"dungeon","dest":{"cell":"00D60210","place":"dungeon"},"minLevel":130,"desc":"In a dungeon (landblock 6443).","id":3270}, + {"name":"West Library Conveyance","type":"Portal","wcid":24021,"cell":"644303ED","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6443).","id":3271}, + {"name":"Collegium Entropica Conveyance","type":"Portal","wcid":24013,"cell":"64440100","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3272}, + {"name":"Collegium Prae Auspi Conveyance","type":"Portal","wcid":24008,"cell":"64440103","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3273}, + {"name":"Collegium Ignae Fatae Conveyance","type":"Portal","wcid":24014,"cell":"6444010C","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3274}, + {"name":"Collegium Conjurae Conveyance","type":"Portal","wcid":24006,"cell":"6444010F","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3275}, + {"name":"Collegium Geomancy Conveyance","type":"Portal","wcid":24016,"cell":"64440118","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3276}, + {"name":"Collegium Artificae Conveyance","type":"Portal","wcid":24004,"cell":"6444011B","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3277}, + {"name":"Collegium Heiromancy Conveyance","type":"Portal","wcid":24017,"cell":"64440124","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3278}, + {"name":"Collegium Acumen Manim Conveyance","type":"Portal","wcid":24003,"cell":"64440127","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3279}, + {"name":"Collegium Aegis Medi Conveyance","type":"Portal","wcid":24022,"cell":"64440130","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3280}, + {"name":"Collegium Organis Conveyance","type":"Portal","wcid":24023,"cell":"64440136","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3281}, + {"name":"Collegium Planar Abstraction Conveyance","type":"Portal","wcid":24024,"cell":"64440139","place":"dungeon","dest":{"cell":"00D60210","place":"dungeon"},"minLevel":130,"desc":"In a dungeon (landblock 6444).","id":3282}, + {"name":"Collegium Tempae Invectae Conveyance","type":"Portal","wcid":24026,"cell":"6444015E","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3283}, + {"name":"West Library Conveyance","type":"Portal","wcid":24021,"cell":"64440164","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3284}, + {"name":"East Library Conveyance","type":"Portal","wcid":24018,"cell":"64440167","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3285}, + {"name":"South Library Conveyance","type":"Portal","wcid":24020,"cell":"6444016A","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3286}, + {"name":"North Library Conveyance","type":"Portal","wcid":24019,"cell":"6444016D","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3287}, + {"name":"Forge Conveyance","type":"Portal","wcid":24015,"cell":"64440170","place":"dungeon","dest":{"cell":"644501A1","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3288}, + {"name":"Research Chambers Conveyance","type":"Portal","wcid":24007,"cell":"64440179","place":"dungeon","dest":{"cell":"644303AD","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3289}, + {"name":"Alaidain Dormitory Conveyance","type":"Portal","wcid":24009,"cell":"64440185","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3290}, + {"name":"Atlan Dormitory Conveyance","type":"Portal","wcid":24010,"cell":"64440191","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3291}, + {"name":"Maila Dormitory Conveyance","type":"Portal","wcid":24012,"cell":"64440194","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3292}, + {"name":"Caerlin Dormitory Conveyance","type":"Portal","wcid":24011,"cell":"6444019D","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3293}, + {"name":"Barracks Conveyance","type":"Portal","wcid":24005,"cell":"644401A0","place":"dungeon","dest":{"cell":"6343028E","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3294}, + {"name":"Collegium Occultus Anteroom","type":"Portal","wcid":32281,"cell":"6444013F","place":"dungeon","dest":{"cell":"004401FA","place":"dungeon"},"desc":"In a dungeon (landblock 6444).","id":3295}, + {"name":"West Library Conveyance","type":"Portal","wcid":24021,"cell":"64450188","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6445).","id":3296}, + {"name":"East Library Conveyance","type":"Portal","wcid":24018,"cell":"6445018B","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6445).","id":3297}, + {"name":"Barracks Conveyance","type":"Portal","wcid":24005,"cell":"64450194","place":"dungeon","dest":{"cell":"6343028E","place":"dungeon"},"desc":"In a dungeon (landblock 6445).","id":3298}, + {"name":"Seat of Knorr Conveyance","type":"Portal","wcid":24025,"cell":"64450198","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6445).","id":3299}, + {"name":"North Library Conveyance","type":"Portal","wcid":24019,"cell":"644501AA","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6445).","id":3300}, + {"name":"Collegium Planar Abstraction Conveyance","type":"Portal","wcid":24024,"cell":"644501B3","place":"dungeon","dest":{"cell":"00D60210","place":"dungeon"},"minLevel":130,"desc":"In a dungeon (landblock 6445).","id":3301}, + {"name":"South Library Conveyance","type":"Portal","wcid":24020,"cell":"644501B7","place":"dungeon","dest":{"cell":"64440144","place":"dungeon"},"desc":"In a dungeon (landblock 6445).","id":3302}, + {"name":"Surface","type":"Portal","wcid":25796,"cell":"64480186","place":"dungeon","dest":{"cell":"9F2A000E","place":"outdoor","ns":-67.79,"ew":25.42},"desc":"In Mount Ingot.","id":3303}, + {"name":"Exit to Surface","type":"Portal","wcid":25838,"cell":"6449022E","place":"dungeon","dest":{"cell":"CA500029","place":"outdoor","ns":-37.87,"ew":60.18},"desc":"In Dragon's Power.","id":3304}, + {"name":"Exit to Surface","type":"Portal","wcid":25836,"cell":"644902C1","place":"dungeon","dest":{"cell":"D23C0034","place":"outdoor","ns":-53.57,"ew":66.72},"desc":"In Dragon's Power.","id":3305}, + {"name":"Exit to Surface","type":"Portal","wcid":25834,"cell":"644901E8","place":"dungeon","dest":{"cell":"B3180005","place":"outdoor","ns":-82.32,"ew":41.35},"desc":"In Dragon's Power.","id":3306}, + {"name":"Surface","type":"Portal","wcid":25976,"cell":"644A018F","place":"dungeon","dest":{"cell":"709D0108","place":"dungeon"},"desc":"In a dungeon (landblock 644A).","id":3307}, + {"name":"Surface","type":"Portal","wcid":25976,"cell":"644A0248","place":"dungeon","dest":{"cell":"709D0108","place":"dungeon"},"desc":"In a dungeon (landblock 644A).","id":3308}, + {"name":"Heartland","type":"Portal","wcid":1900,"cell":"64D50000","place":"outdoor","ns":68.92,"ew":-21.34,"dest":{"cell":"AD9B003E","place":"outdoor","ns":22.58,"ew":37.23},"id":3309}, + {"name":"Mammet Foundry Portal","type":"Portal","wcid":19716,"cell":"64D50130","place":"building","ns":68.85,"ew":-21.6,"dest":{"cell":"5458025F","place":"dungeon","name":"Mammet Foundry"},"id":3310}, + {"name":"Portal to Town Network","type":"Portal","wcid":43065,"cell":"64D50013","place":"outdoor","ns":68.71,"ew":-21.65,"dest":{"cell":"00070143","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3311}, + {"name":"Exit","type":"Portal","wcid":27299,"cell":"65480141","place":"dungeon","dest":{"cell":"09040008","place":"outdoor","ns":-97.96,"ew":-94.7},"minLevel":90,"desc":"In a dungeon (landblock 6548).","id":3312}, + {"name":"Exit to Surface","type":"Portal","wcid":27697,"cell":"65490142","place":"dungeon","dest":{"cell":"5BD8002E","place":"outdoor","ns":71.4,"ew":-28.61},"desc":"In a dungeon (landblock 6549).","id":3313}, + {"name":"Exit to Surface","type":"Portal","wcid":27699,"cell":"654A0142","place":"dungeon","dest":{"cell":"866A0032","place":"outdoor","ns":-17.05,"ew":5.92},"desc":"In a dungeon (landblock 654A).","id":3314}, + {"name":"Exit to Surface","type":"Portal","wcid":27695,"cell":"654B0142","place":"dungeon","dest":{"cell":"D0540028","place":"outdoor","ns":-33.98,"ew":64.86},"desc":"In a dungeon (landblock 654B).","id":3315}, + {"name":"Surface","type":"Portal","wcid":48933,"cell":"654C069C","place":"dungeon","dest":{"cell":"8763000E","place":"outdoor","ns":-22.21,"ew":6.23},"desc":"In a dungeon (landblock 654C).","id":3316}, + {"name":"Surface","type":"Portal","wcid":72496,"cell":"654C0667","place":"dungeon","dest":{"cell":"4CE3010A","place":"building","ns":79.78,"ew":-41.01},"minLevel":200,"desc":"In a dungeon (landblock 654C).","id":3317}, + {"name":"Surface","type":"Portal","wcid":72496,"cell":"654C0675","place":"dungeon","dest":{"cell":"4CE3010A","place":"building","ns":79.78,"ew":-41.01},"minLevel":200,"desc":"In a dungeon (landblock 654C).","id":3318}, + {"name":"Surface","type":"Portal","wcid":72497,"cell":"654C06A8","place":"dungeon","dest":{"cell":"4CE10122","place":"building","ns":78.63,"ew":-40.58},"minLevel":200,"desc":"In a dungeon (landblock 654C).","id":3319}, + {"name":"Surface","type":"Portal","wcid":72497,"cell":"654C06A9","place":"dungeon","dest":{"cell":"4CE10122","place":"building","ns":78.63,"ew":-40.58},"minLevel":200,"desc":"In a dungeon (landblock 654C).","id":3320}, + {"name":"Surface","type":"Portal","wcid":72498,"cell":"654C065B","place":"dungeon","dest":{"cell":"4AE1010F","place":"building","ns":78.22,"ew":-42.3},"minLevel":200,"desc":"In a dungeon (landblock 654C).","id":3321}, + {"name":"Surface","type":"Portal","wcid":72498,"cell":"654C0682","place":"dungeon","dest":{"cell":"4AE1010F","place":"building","ns":78.22,"ew":-42.3},"minLevel":200,"desc":"In a dungeon (landblock 654C).","id":3322}, + {"name":"Private Chambers","type":"Portal","wcid":72536,"cell":"654D0571","place":"dungeon","dest":{"cell":"654D04DA","place":"dungeon"},"minLevel":200,"quest":true,"desc":"In a dungeon (landblock 654D).","id":3323}, + {"name":"Surface","type":"Portal","wcid":72537,"cell":"654D05B5","place":"dungeon","dest":{"cell":"4CE20034","place":"outdoor","ns":79.2,"ew":-40.52},"minLevel":200,"desc":"In a dungeon (landblock 654D).","id":3324}, + {"name":"Private Chambers","type":"Portal","wcid":72527,"cell":"654D0358","place":"dungeon","dest":{"cell":"654D04DA","place":"dungeon"},"minLevel":200,"desc":"In a dungeon (landblock 654D).","id":3325}, + {"name":"Surface","type":"Portal","wcid":72537,"cell":"654D04CE","place":"dungeon","dest":{"cell":"4CE20034","place":"outdoor","ns":79.2,"ew":-40.52},"minLevel":200,"desc":"In a dungeon (landblock 654D).","id":3326}, + {"name":"Surface","type":"Portal","wcid":72537,"cell":"654D04A5","place":"dungeon","dest":{"cell":"4CE20034","place":"outdoor","ns":79.2,"ew":-40.52},"minLevel":200,"desc":"In a dungeon (landblock 654D).","id":3327}, + {"name":"Realaidain Western Vault","type":"Portal","wcid":34540,"cell":"65C70101","place":"dungeon","dest":{"cell":"00500173","place":"dungeon"},"minLevel":80,"quest":true,"desc":"This dungeon is quest-restricted. Go see Shan Zhen in Cragstone for more information. In a dungeon (landblock 65C7).","id":3328}, + {"name":"Destroyed Ahurenga Portal","type":"Portal","wcid":10982,"cell":"65D50000","place":"outdoor","ns":68.57,"ew":-20.73,"dest":{"cell":"0FB90009","place":"outdoor","ns":46.09,"ew":-89.77},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3329}, + {"name":"Surface","type":"Portal","wcid":72475,"cell":"66510118","place":"dungeon","dest":{"cell":"4CE20034","place":"outdoor","ns":79.2,"ew":-40.52},"desc":"In Hoshino Tower.","id":3330}, + {"name":"Great Hall","type":"Portal","wcid":46590,"cell":"665E0137","place":"dungeon","dest":{"cell":"665E01D0","place":"dungeon","name":"Falatacot Temple"},"desc":"In Falatacot Temple.","id":3331}, + {"name":"Surface","type":"Portal","wcid":72485,"cell":"665E01D1","place":"dungeon","dest":{"cell":"4AE20020","place":"outdoor","ns":79.6,"ew":-42.44},"desc":"In Falatacot Temple.","id":3332}, + {"name":"Surface Exit","type":"Portal","wcid":27586,"cell":"6678010E","place":"dungeon","dest":{"cell":"19BA003A","place":"outdoor","ns":46.98,"ew":-81.18},"desc":"In Olthoi Warrior Nest.","id":3333}, + {"name":"Surface Exit","type":"Portal","wcid":27586,"cell":"667801E2","place":"dungeon","dest":{"cell":"19BA003A","place":"outdoor","ns":46.98,"ew":-81.18},"desc":"In Olthoi Warrior Nest.","id":3334}, + {"name":"Surface Exit","type":"Portal","wcid":27588,"cell":"66790276","place":"dungeon","dest":{"cell":"2AB90028","place":"outdoor","ns":46.76,"ew":-67.87},"desc":"In Crumbling Empyrean Mansion.","id":3335}, + {"name":"Surface Exit","type":"Portal","wcid":27584,"cell":"667A015B","place":"dungeon","dest":{"cell":"1DC10035","place":"outdoor","ns":52.86,"ew":-78.12},"desc":"In Mutilator Tunnels.","id":3336}, + {"name":"Surface Exit","type":"Portal","wcid":27584,"cell":"667A0233","place":"dungeon","dest":{"cell":"1DC10035","place":"outdoor","ns":52.86,"ew":-78.12},"desc":"In Mutilator Tunnels.","id":3337}, + {"name":"Phyntos Menace","type":"Portal","wcid":4925,"cell":"66D40102","place":"building","ns":68.1,"ew":-20.04,"dest":{"cell":"0143010A","place":"dungeon","name":"Phyntos Menace"},"id":3338}, + {"name":"Sonel Portal","type":"Portal","wcid":12547,"cell":"66D60000","place":"outdoor","ns":69.6,"ew":-20.16,"dest":{"cell":"52DF0013","place":"outdoor","ns":76.71,"ew":-36.1},"id":3339}, + {"name":"Desolation Beach Portal","type":"Portal","wcid":12486,"cell":"66D60000","place":"outdoor","ns":69.68,"ew":-20.17,"dest":{"cell":"49E60004","place":"outdoor","ns":82.39,"ew":-43.47},"id":3340}, + {"name":"Woodshore Cottages Portal","type":"Portal","wcid":12567,"cell":"66D60000","place":"outdoor","ns":69.63,"ew":-20.16,"dest":{"cell":"48E0000E","place":"outdoor","ns":77.82,"ew":-44.23},"id":3341}, + {"name":"Lake NemuelSettlement Portal","type":"Portal","wcid":12510,"cell":"66D60000","place":"outdoor","ns":69.56,"ew":-20.16,"dest":{"cell":"7FCD0028","place":"outdoor","ns":62.81,"ew":0.08},"id":3342}, + {"name":"Dires' Door Estates Portal","type":"Portal","wcid":13097,"cell":"66D60000","place":"outdoor","ns":69.7,"ew":-20.2,"dest":{"cell":"6AE10011","place":"outdoor","ns":78.1,"ew":-16.89},"id":3343}, + {"name":"Seaview Ridge Cottages Portal","type":"Portal","wcid":13125,"cell":"66D60000","place":"outdoor","ns":69.54,"ew":-20.17,"dest":{"cell":"6EED002E","place":"outdoor","ns":88.24,"ew":-13.44},"id":3344}, + {"name":"Wisp Lake Cottages Portal","type":"Portal","wcid":13141,"cell":"66D60000","place":"outdoor","ns":69.54,"ew":-20.2,"dest":{"cell":"7DE8001C","place":"outdoor","ns":84.01,"ew":-1.58},"id":3345}, + {"name":"Empyrean Shore Villas Portal","type":"Portal","wcid":14627,"cell":"66D60000","place":"outdoor","ns":69.71,"ew":-20.23,"dest":{"cell":"4DE70006","place":"outdoor","ns":83.39,"ew":-40.31},"id":3346}, + {"name":"Laiti's Villa Portal","type":"Portal","wcid":14640,"cell":"66D60000","place":"outdoor","ns":69.69,"ew":-20.26,"dest":{"cell":"6AD3001F","place":"outdoor","ns":67.52,"ew":-16.83},"id":3347}, + {"name":"Lightbringer Dale Cottages Portal","type":"Portal","wcid":14643,"cell":"66D60000","place":"outdoor","ns":69.67,"ew":-20.29,"dest":{"cell":"69E50016","place":"outdoor","ns":81.84,"ew":-17.66},"id":3348}, + {"name":"Verena Portal","type":"Portal","wcid":14674,"cell":"66D60000","place":"outdoor","ns":69.63,"ew":-20.3,"dest":{"cell":"61CA0026","place":"outdoor","ns":60.17,"ew":-23.92},"id":3349}, + {"name":"Hidden Valley Portal","type":"Portal","wcid":14635,"cell":"66D60000","place":"outdoor","ns":69.6,"ew":-20.31,"dest":{"cell":"67C90025","place":"outdoor","ns":59.29,"ew":-19.07},"id":3350}, + {"name":"Lord Cambarth Villas Portal","type":"Portal","wcid":14647,"cell":"66D60000","place":"outdoor","ns":69.57,"ew":-20.32,"dest":{"cell":"71E4001E","place":"outdoor","ns":81.0,"ew":-11.19},"id":3351}, + {"name":"Durglen Portal","type":"Portal","wcid":15155,"cell":"66D60000","place":"outdoor","ns":69.73,"ew":-20.26,"dest":{"cell":"85B40015","place":"outdoor","ns":42.51,"ew":4.72},"id":3352}, + {"name":"Ice's Edge Cottages Portal","type":"Portal","wcid":15161,"cell":"66D60000","place":"outdoor","ns":69.72,"ew":-20.29,"dest":{"cell":"6ACF0024","place":"outdoor","ns":64.03,"ew":-16.73},"id":3353}, + {"name":"Regina Cottages Portal","type":"Portal","wcid":15184,"cell":"66D60000","place":"outdoor","ns":69.74,"ew":-20.23,"dest":{"cell":"66C30024","place":"outdoor","ns":54.45,"ew":-19.94},"id":3354}, + {"name":"Northfire Estates Portal","type":"Portal","wcid":15180,"cell":"66D60000","place":"outdoor","ns":69.73,"ew":-20.18,"dest":{"cell":"5CE7001B","place":"outdoor","ns":83.09,"ew":-27.95},"id":3355}, + {"name":"Thyrinn Cant Cottages Portal","type":"Portal","wcid":15197,"cell":"66D60000","place":"outdoor","ns":69.72,"ew":-20.14,"dest":{"cell":"65E50024","place":"outdoor","ns":81.61,"ew":-20.7},"id":3356}, + {"name":"East Morntide Settlement Portal","type":"Portal","wcid":15157,"cell":"66D60000","place":"outdoor","ns":69.69,"ew":-20.11,"dest":{"cell":"6CAB0025","place":"outdoor","ns":35.25,"ew":-15.08},"id":3357}, + {"name":"Surface","type":"Portal","wcid":72619,"cell":"67570150","place":"dungeon","dest":{"cell":"D94A0039","place":"outdoor","ns":-42.67,"ew":72.43},"desc":"In Tanada Toresen Temple.","id":3358}, + {"name":"Tanada Toresen Temple","type":"Portal","wcid":72615,"cell":"67570116","place":"dungeon","dest":{"cell":"6757027B","place":"dungeon","name":"Tanada Toresen Temple"},"minLevel":200,"quest":true,"desc":"In Tanada Toresen Temple.","id":3359}, + {"name":"Surface","type":"Portal","wcid":72619,"cell":"675702D7","place":"dungeon","dest":{"cell":"D94A0039","place":"outdoor","ns":-42.67,"ew":72.43},"desc":"In Tanada Toresen Temple.","id":3360}, + {"name":"Surface","type":"Portal","wcid":72619,"cell":"6757018A","place":"dungeon","dest":{"cell":"D94A0039","place":"outdoor","ns":-42.67,"ew":72.43},"desc":"In Tanada Toresen Temple.","id":3361}, + {"name":"Grievver Caves Portal","type":"Portal","wcid":20642,"cell":"67DE0103","place":"building","ns":75.93,"ew":-19.04,"dest":{"cell":"545602A0","place":"dungeon","name":"Grievver Caves"},"id":3362}, + {"name":"Gerent's Compound","type":"Portal","wcid":25394,"cell":"69120000","place":"outdoor","ns":-87.31,"ew":-17.49,"dest":{"cell":"594C0143","place":"dungeon","name":"Gerent's Compound"},"minLevel":40,"id":3363}, + {"name":"Gelidite Library","type":"Portal","wcid":15776,"cell":"69D50101","place":"dungeon","dest":{"cell":"546401AE","place":"dungeon"},"desc":"In a dungeon (landblock 69D5).","id":3364}, + {"name":"Abandoned Armory Portal","type":"Portal","wcid":23367,"cell":"6C160000","place":"outdoor","ns":-83.58,"ew":-14.86,"dest":{"cell":"5645023C","place":"dungeon","name":"Abandoned Armory"},"id":3365}, + {"name":"Northwest Direlands Portal","type":"Portal","wcid":7211,"cell":"6CE30000","place":"outdoor","ns":79.93,"ew":-15.22,"dest":{"cell":"12860003","place":"outdoor","ns":5.53,"ew":-87.51},"minLevel":35,"id":3366}, + {"name":"Ikzisik Tika Ri Zikma","type":"Portal","wcid":34272,"cell":"6DD70016","place":"outdoor","ns":70.65,"ew":-14.5,"dest":{"cell":"00870353","place":"dungeon","name":"Ikzisik Tika Ri Zikma"},"minLevel":90,"quest":true,"id":3367}, + {"name":"Olthoi Horde Nest","type":"Portal","wcid":7256,"cell":"6FBC0000","place":"outdoor","ns":48.9,"ew":-12.94,"dest":{"cell":"02FC03A6","place":"dungeon","name":"Olthoi Horde Nest"},"minLevel":30,"id":3368}, + {"name":"Halls of Metos","type":"Portal","wcid":7291,"cell":"708F0015","place":"outdoor","ns":12.86,"ew":-12.14,"dest":{"cell":"02F40297","place":"dungeon","name":"Halls of Metos"},"minLevel":15,"id":3369}, + {"name":"Decrepit Tower","type":"Portal","wcid":25975,"cell":"709D0102","place":"dungeon","dest":{"cell":"644A03AB","place":"dungeon"},"minLevel":40,"desc":"In a dungeon (landblock 709D).","id":3370}, + {"name":"Entrance to the pyramid","type":"Portal","wcid":40248,"cell":"71C8001C","place":"outdoor","ns":58.43,"ew":-11.18,"dest":{"cell":"00CB016E","place":"dungeon","name":"Entrance to the pyramid"},"minLevel":125,"id":3371}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"72000198","place":"dungeon","dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"desc":"In a dungeon (landblock 7200).","id":3372}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"72020273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 7202).","id":3373}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"72020331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 7202).","id":3374}, + {"name":"Exit to Sanamar","type":"Portal","wcid":29339,"cell":"72020169","place":"dungeon","dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 7202).","id":3375}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"72030273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 7203).","id":3376}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"72030331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 7203).","id":3377}, + {"name":"Exit to Sanamar","type":"Portal","wcid":29339,"cell":"72030169","place":"dungeon","dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 7203).","id":3378}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"72040273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 7204).","id":3379}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"72040331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 7204).","id":3380}, + {"name":"Exit to Sanamar","type":"Portal","wcid":29339,"cell":"72040169","place":"dungeon","dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 7204).","id":3381}, + {"name":"Entrance to the pyramid","type":"Portal","wcid":40249,"cell":"72CA0026","place":"outdoor","ns":60.17,"ew":-10.3,"dest":{"cell":"00CB01DC","place":"dungeon","name":"Entrance to the pyramid"},"minLevel":125,"id":3382}, + {"name":"North Direlands Portal","type":"Portal","wcid":1104,"cell":"72CC0000","place":"outdoor","ns":61.38,"ew":-10.2,"dest":{"cell":"3C9D0010","place":"outdoor","ns":24.45,"ew":-53.85},"minLevel":12,"id":3383}, + {"name":"North Desert Edge","type":"Portal","wcid":1905,"cell":"72CC0000","place":"outdoor","ns":61.63,"ew":-10.18,"dest":{"cell":"7B790025","place":"outdoor","ns":-4.69,"ew":-3.07},"id":3384}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"73000198","place":"dungeon","dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"desc":"In a dungeon (landblock 7300).","id":3385}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"73020273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 7302).","id":3386}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"73020331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 7302).","id":3387}, + {"name":"Exit to Sanamar","type":"Portal","wcid":29339,"cell":"73020169","place":"dungeon","dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 7302).","id":3388}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"73030273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 7303).","id":3389}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"73030331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 7303).","id":3390}, + {"name":"Exit to Sanamar","type":"Portal","wcid":29339,"cell":"73030169","place":"dungeon","dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 7303).","id":3391}, + {"name":"Basement","type":"Portal","wcid":23770,"cell":"73080105","place":"building","ns":-94.79,"ew":-9.72,"dest":{"cell":"61430112","place":"dungeon","name":"Basement"},"id":3392}, + {"name":"Entrance to the pyramid","type":"Portal","wcid":40250,"cell":"73C80024","place":"outdoor","ns":58.43,"ew":-9.52,"dest":{"cell":"00CB0100","place":"dungeon","name":"Entrance to the pyramid"},"minLevel":125,"id":3393}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"74000198","place":"dungeon","dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"desc":"In a dungeon (landblock 7400).","id":3394}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"75000198","place":"dungeon","dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"desc":"In a dungeon (landblock 7500).","id":3395}, + {"name":"Destroyed Portal to Zaikhal","type":"Portal","wcid":1032,"cell":"759C0000","place":"outdoor","ns":23.41,"ew":-7.79,"dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3396}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"759C0000","place":"outdoor","ns":23.59,"ew":-7.71,"dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3397}, + {"name":"Bandit Castle Portal","type":"Portal","wcid":1102,"cell":"75B80000","place":"outdoor","ns":45.83,"ew":-7.97,"dest":{"cell":"BDD00006","place":"outdoor","ns":64.95,"ew":49.32},"id":3398}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"75D70000","place":"outdoor","ns":70.47,"ew":-8.09,"dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3399}, + {"name":"Crystal Mine Low","type":"Portal","wcid":22870,"cell":"75D70000","place":"outdoor","ns":70.54,"ew":-8.2,"dest":{"cell":"564E0233","place":"dungeon","name":"Crystal Mine Low"},"minLevel":20,"maxLevel":39,"id":3400}, + {"name":"Crystal Mine New Isparians","type":"Portal","wcid":22871,"cell":"75D70000","place":"outdoor","ns":70.52,"ew":-7.98,"dest":{"cell":"564F0233","place":"dungeon","name":"Crystal Mine New Isparians"},"minLevel":1,"maxLevel":19,"id":3401}, + {"name":"Crystal Mine Mid","type":"Portal","wcid":22872,"cell":"75D70000","place":"outdoor","ns":70.6,"ew":-8.07,"dest":{"cell":"564D0233","place":"dungeon","name":"Crystal Mine Mid"},"minLevel":40,"maxLevel":59,"id":3402}, + {"name":"Crystal Mine Extreme","type":"Portal","wcid":22868,"cell":"75D70000","place":"outdoor","ns":70.44,"ew":-8.1,"dest":{"cell":"564B0233","place":"dungeon","name":"Crystal Mine Extreme"},"minLevel":80,"id":3403}, + {"name":"Crystal Mine High","type":"Portal","wcid":22869,"cell":"75D70000","place":"outdoor","ns":70.47,"ew":-7.91,"dest":{"cell":"564C0233","place":"dungeon","name":"Crystal Mine High"},"minLevel":60,"maxLevel":79,"id":3404}, + {"name":"Access to Crystal Mines","type":"Portal","wcid":22866,"cell":"75D70000","place":"outdoor","ns":70.48,"ew":-8.31,"dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"quest":true,"id":3405}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"76000198","place":"dungeon","dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"desc":"In a dungeon (landblock 7600).","id":3406}, + {"name":"Frozen Tomb","type":"Portal","wcid":43524,"cell":"76E901B1","place":"underground","ns":85.83,"ew":-6.97,"dest":{"cell":"77E702E4","place":"building","ns":82.98,"ew":-6.65},"minLevel":200,"quest":true,"desc":"This portal appears to be warded against intrusion. Perhaps Nalicana, in Asheron's Castle, will know more.","id":3407}, + {"name":"Frozen Wight Lair","type":"Portal","wcid":44992,"cell":"76EA0100","place":"underground","ns":85.25,"ew":-7.52,"dest":{"cell":"8B040173","place":"dungeon"},"minLevel":180,"id":3408}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"77000198","place":"dungeon","dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"desc":"In a dungeon (landblock 7700).","id":3409}, + {"name":"Surface","type":"Portal","wcid":43525,"cell":"77E70128","place":"building","ns":82.52,"ew":-6.47,"dest":{"cell":"77E702FD","place":"building","ns":82.77,"ew":-6.36},"id":3410}, + {"name":"Surface","type":"Portal","wcid":43525,"cell":"77E702E7","place":"building","ns":83.0,"ew":-6.65,"dest":{"cell":"77E702FD","place":"building","ns":82.77,"ew":-6.36},"id":3411}, + {"name":"Geraine's Study","type":"Portal","wcid":45648,"cell":"77E702F7","place":"building","ns":82.81,"ew":-6.32,"dest":{"cell":"93020171","place":"dungeon","name":"Geraine's Study"},"minLevel":150,"id":3412}, + {"name":"Frozen Fortress","type":"Portal","wcid":51319,"cell":"77E70016","place":"outdoor","ns":83.38,"ew":-6.47,"dest":{"cell":"594F02C2","place":"dungeon","name":"Frozen Fortress"},"minLevel":180,"id":3413}, + {"name":"Tusker Den","type":"Portal","wcid":51428,"cell":"77E8001F","place":"outdoor","ns":84.34,"ew":-6.39,"dest":{"cell":"586F029B","place":"dungeon","name":"Tusker Den"},"minLevel":200,"id":3414}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"78000198","place":"dungeon","dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"desc":"In a dungeon (landblock 7800).","id":3415}, + {"name":"Tanada House of Water","type":"Portal","wcid":35318,"cell":"7814000F","place":"outdoor","ns":-85.33,"ew":-5.77,"dest":{"cell":"009E0218","place":"dungeon","name":"Tanada House of Water"},"minLevel":80,"quest":true,"desc":"This portal leads to the Tanada House of Water.","id":3416}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"79000198","place":"dungeon","dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"desc":"In a dungeon (landblock 7900).","id":3417}, + {"name":"Sea Temple Catacombs","type":"Portal","wcid":5198,"cell":"79660101","place":"dungeon","dest":{"cell":"0156018F","place":"dungeon"},"minLevel":1,"maxLevel":20,"desc":"This is a good adventure for someone who is newly arrived in Dereth. In a dungeon (landblock 7966).","id":3418}, + {"name":"Surface","type":"Portal","wcid":72634,"cell":"79E9017F","place":"dungeon","dest":{"cell":"77E702FD","place":"building","ns":82.77,"ew":-6.36},"desc":"In a dungeon (landblock 79E9).","id":3419}, + {"name":"Surface","type":"Portal","wcid":72634,"cell":"79E903AA","place":"dungeon","dest":{"cell":"77E702FD","place":"building","ns":82.77,"ew":-6.36},"desc":"In a dungeon (landblock 79E9).","id":3420}, + {"name":"Surface","type":"Portal","wcid":72634,"cell":"79E9033A","place":"dungeon","dest":{"cell":"77E702FD","place":"building","ns":82.77,"ew":-6.36},"desc":"In a dungeon (landblock 79E9).","id":3421}, + {"name":"Surface","type":"Portal","wcid":72634,"cell":"79E90107","place":"dungeon","dest":{"cell":"77E702FD","place":"building","ns":82.77,"ew":-6.36},"desc":"In a dungeon (landblock 79E9).","id":3422}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"7A000198","place":"dungeon","dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"desc":"In a dungeon (landblock 7A00).","id":3423}, + {"name":"Southern Power Forge","type":"Portal","wcid":30468,"cell":"7A180000","place":"outdoor","ns":-82.27,"ew":-3.87,"dest":{"cell":"00050100","place":"dungeon","name":"Southern Power Forge"},"minLevel":70,"id":3424}, + {"name":"Under-Cove Crypt","type":"Portal","wcid":5200,"cell":"7A640102","place":"building","ns":-21.58,"ew":-4.1,"dest":{"cell":"01570147","place":"dungeon","name":"Under-Cove Crypt"},"id":3425}, + {"name":"Desert March Portal","type":"Portal","wcid":9005,"cell":"7A870000","place":"outdoor","ns":6.47,"ew":-3.64,"dest":{"cell":"02AA022F","place":"dungeon","name":"Desert March"},"id":3426}, + {"name":"Desert Ridge Border","type":"Portal","wcid":1903,"cell":"7AC30000","place":"outdoor","ns":54.34,"ew":-4.2,"dest":{"cell":"B178001C","place":"outdoor","ns":-5.64,"ew":39.96},"id":3427}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"7AC30000","place":"outdoor","ns":54.22,"ew":-4.1,"dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3428}, + {"name":"Destroyed Mayoi Portal","type":"Portal","wcid":1022,"cell":"7AC30000","place":"outdoor","ns":54.4,"ew":-4.13,"dest":{"cell":"E6320021","place":"outdoor","ns":-61.91,"ew":82.5},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3429}, + {"name":"Hilltop","type":"Portal","wcid":1902,"cell":"7ACA0000","place":"outdoor","ns":59.72,"ew":-4.04,"dest":{"cell":"AAA80034","place":"outdoor","ns":32.79,"ew":34.68},"id":3430}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"7B000198","place":"dungeon","dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"desc":"In a dungeon (landblock 7B00).","id":3431}, + {"name":"North Desert Edge","type":"Portal","wcid":1905,"cell":"7B980000","place":"outdoor","ns":19.83,"ew":-3.3,"dest":{"cell":"7B790025","place":"outdoor","ns":-4.69,"ew":-3.07},"id":3432}, + {"name":"Fire Guardian Lair","type":"Portal","wcid":21416,"cell":"7BDB0000","place":"outdoor","ns":73.51,"ew":-3.15,"dest":{"cell":"5843014A","place":"dungeon","name":"Fire Guardian Lair"},"minLevel":40,"maxLevel":59,"id":3433}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"7C000198","place":"dungeon","dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"desc":"In a dungeon (landblock 7C00).","id":3434}, + {"name":"Land Bridge Staging Complex Portal","type":"Portal","wcid":10716,"cell":"7C130000","place":"outdoor","ns":-86.05,"ew":-2.52,"dest":{"cell":"029802A5","place":"dungeon","name":"Land Bridge Staging Complex"},"minLevel":32,"id":3435}, + {"name":"A Red Rat Lair","type":"Portal","wcid":1345,"cell":"7C650000","place":"outdoor","ns":-21.06,"ew":-2.19,"dest":{"cell":"01D90100","place":"dungeon","name":"A Red Rat Lair"},"id":3436}, + {"name":"Lost Desert Archive","type":"Portal","wcid":31436,"cell":"7C840100","place":"dungeon","dest":{"cell":"0036013C","place":"dungeon"},"minLevel":40,"quest":true,"desc":"This dungeon is quest restricted. Royal scholars in Cragstone or Sanamar might be interested in the secrets it holds. In a dungeon (landblock 7C84).","id":3437}, + {"name":"Empyrean Fire Propylaeum","type":"Portal","wcid":14488,"cell":"7CDB0000","place":"outdoor","ns":73.46,"ew":-2.67,"dest":{"cell":"5270014B","place":"dungeon","name":"Empyrean Fire Propylaeum"},"minLevel":25,"id":3438}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"7D000198","place":"dungeon","dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"desc":"In a dungeon (landblock 7D00).","id":3439}, + {"name":"Yaraq Tunnels Portal","type":"Portal","wcid":1126,"cell":"7D600000","place":"outdoor","ns":-24.64,"ew":-1.42,"dest":{"cell":"01FB0206","place":"dungeon","name":"Yaraq Tunnels"},"id":3440}, + {"name":"Destroyed Portal to Sanamar","type":"Portal","wcid":28709,"cell":"7D630027","place":"outdoor","ns":-22.08,"ew":-1.5,"dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3441}, + {"name":"Mannikin Foundry Portal","type":"Portal","wcid":19717,"cell":"7D640150","place":"building","ns":-21.54,"ew":-1.7,"dest":{"cell":"545A013C","place":"dungeon","name":"Mannikin Foundry"},"id":3442}, + {"name":"Yaraq Meeting Hall Portal","type":"Portal","wcid":6111,"cell":"7D640173","place":"building","ns":-21.8,"ew":-1.8,"dest":{"cell":"01340126","place":"dungeon","name":"Yaraq Meeting Hall"},"id":3443}, + {"name":"Destroyed Portal to Greenspire","type":"Portal","wcid":11954,"cell":"7D640000","place":"outdoor","ns":-21.69,"ew":-1.8,"dest":{"cell":"2BB5003C","place":"outdoor","ns":43.21,"ew":-66.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3444}, + {"name":"Portal to Town Network","type":"Portal","wcid":43066,"cell":"7D640025","place":"outdoor","ns":-21.51,"ew":-1.52,"dest":{"cell":"00070133","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3445}, + {"name":"Recovered Temple Portal","type":"Portal","wcid":4949,"cell":"7D870102","place":"dungeon","dest":{"cell":"0142017F","place":"dungeon"},"desc":"In a dungeon (landblock 7D87).","id":3446}, + {"name":"Majestic Hill Cottages Portal","type":"Portal","wcid":12518,"cell":"7D8F0000","place":"outdoor","ns":12.74,"ew":-1.7,"dest":{"cell":"8AA60029","place":"outdoor","ns":30.89,"ew":9.04},"id":3447}, + {"name":"Maitland Portal","type":"Portal","wcid":12517,"cell":"7D8F0000","place":"outdoor","ns":12.74,"ew":-1.66,"dest":{"cell":"879F0033","place":"outdoor","ns":25.48,"ew":6.68},"id":3448}, + {"name":"New Suntik Portal","type":"Portal","wcid":12528,"cell":"7D8F0000","place":"outdoor","ns":12.7,"ew":-1.64,"dest":{"cell":"84960030","place":"outdoor","ns":18.81,"ew":4.21},"id":3449}, + {"name":"Sanai Portal","type":"Portal","wcid":12541,"cell":"7D8F0000","place":"outdoor","ns":12.66,"ew":-1.66,"dest":{"cell":"68970024","place":"outdoor","ns":19.23,"ew":-18.31},"id":3450}, + {"name":"Tiofor Deeps Portal","type":"Portal","wcid":12560,"cell":"7D8F0000","place":"outdoor","ns":12.64,"ew":-1.7,"dest":{"cell":"78B20023","place":"outdoor","ns":40.72,"ew":-5.48},"id":3451}, + {"name":"Helms Villas Portal","type":"Portal","wcid":14264,"cell":"7D8F0000","place":"outdoor","ns":12.74,"ew":-1.73,"dest":{"cell":"809B0011","place":"outdoor","ns":22.11,"ew":0.71},"id":3452}, + {"name":"Sharvale Portal","type":"Portal","wcid":13126,"cell":"7D8F0000","place":"outdoor","ns":12.72,"ew":-1.76,"dest":{"cell":"7792001A","place":"outdoor","ns":15.03,"ew":-6.4},"id":3453}, + {"name":"East Danby Portal","type":"Portal","wcid":13101,"cell":"7D8F0000","place":"outdoor","ns":12.63,"ew":-1.73,"dest":{"cell":"619E0025","place":"outdoor","ns":24.86,"ew":-23.94},"id":3454}, + {"name":"Stonebend Cottages Portal","type":"Portal","wcid":14669,"cell":"7D8F0000","place":"outdoor","ns":12.62,"ew":-1.76,"dest":{"cell":"9B910036","place":"outdoor","ns":14.64,"ew":22.69},"id":3455}, + {"name":"West Zaikhal Freehold Portal","type":"Portal","wcid":14677,"cell":"7D8F0000","place":"outdoor","ns":12.63,"ew":-1.79,"dest":{"cell":"73940025","place":"outdoor","ns":16.93,"ew":-9.49},"id":3456}, + {"name":"Embara Portal","type":"Portal","wcid":14625,"cell":"7D8F0000","place":"outdoor","ns":12.74,"ew":-1.62,"dest":{"cell":"68A1002A","place":"outdoor","ns":27.02,"ew":-18.19},"id":3457}, + {"name":"Loredane Villas Portal","type":"Portal","wcid":14648,"cell":"7D8F0000","place":"outdoor","ns":12.69,"ew":-1.61,"dest":{"cell":"6F8B0021","place":"outdoor","ns":9.31,"ew":-12.7},"id":3458}, + {"name":"Nalib Cavana Settlement Portal","type":"Portal","wcid":15177,"cell":"7D8F0000","place":"outdoor","ns":12.77,"ew":-1.64,"dest":{"cell":"5FA60025","place":"outdoor","ns":31.29,"ew":-25.5},"id":3459}, + {"name":"Bright Blade Cottages Portal","type":"Portal","wcid":15147,"cell":"7D8F0000","place":"outdoor","ns":12.79,"ew":-1.68,"dest":{"cell":"7E9F001D","place":"outdoor","ns":25.68,"ew":-0.79},"id":3460}, + {"name":"Deepvale Cottages Portal","type":"Portal","wcid":15671,"cell":"7D8F0000","place":"outdoor","ns":12.63,"ew":-1.61,"dest":{"cell":"61AC001C","place":"outdoor","ns":35.98,"ew":-24.05},"id":3461}, + {"name":"Gharu'n Victory Villas Portal","type":"Portal","wcid":15674,"cell":"7D8F0000","place":"outdoor","ns":12.59,"ew":-1.62,"dest":{"cell":"6F950024","place":"outdoor","ns":17.64,"ew":-12.73},"id":3462}, + {"name":"Silver Legion Keep","type":"Portal","wcid":29439,"cell":"7D900023","place":"outdoor","ns":13.55,"ew":-1.52,"dest":{"cell":"001B016E","place":"dungeon","name":"Silver Legion Keep"},"minLevel":65,"id":3463}, + {"name":"Danby's Outpost","type":"Portal","wcid":9684,"cell":"7D940000","place":"outdoor","ns":16.64,"ew":-1.62,"dest":{"cell":"5A9C0004","place":"outdoor","ns":23.17,"ew":-29.85},"id":3464}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"7E000198","place":"dungeon","dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"desc":"In a dungeon (landblock 7E00).","id":3465}, + {"name":"Portal","type":"Portal","wcid":43758,"cell":"7E03041E","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3466}, + {"name":"Portal","type":"Portal","wcid":43759,"cell":"7E030425","place":"dungeon","dest":{"cell":"7E030410","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3467}, + {"name":"Portal","type":"Portal","wcid":43764,"cell":"7E030437","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3468}, + {"name":"Portal","type":"Portal","wcid":43768,"cell":"7E0305FF","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3469}, + {"name":"Portal","type":"Portal","wcid":43758,"cell":"7E030600","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3470}, + {"name":"Portal","type":"Portal","wcid":43766,"cell":"7E030601","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3471}, + {"name":"Portal","type":"Portal","wcid":43769,"cell":"7E030602","place":"dungeon","dest":{"cell":"7E030605","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3472}, + {"name":"Portal","type":"Portal","wcid":43770,"cell":"7E030603","place":"dungeon","dest":{"cell":"7E03072B","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3473}, + {"name":"Portal","type":"Portal","wcid":43765,"cell":"7E030604","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3474}, + {"name":"Portal","type":"Portal","wcid":43771,"cell":"7E030605","place":"dungeon","dest":{"cell":"7E030604","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3475}, + {"name":"Portal","type":"Portal","wcid":43768,"cell":"7E030606","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3476}, + {"name":"Portal","type":"Portal","wcid":43764,"cell":"7E030607","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3477}, + {"name":"Portal","type":"Portal","wcid":43772,"cell":"7E030608","place":"dungeon","dest":{"cell":"7E030603","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3478}, + {"name":"Portal","type":"Portal","wcid":43767,"cell":"7E030609","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3479}, + {"name":"Portal","type":"Portal","wcid":43766,"cell":"7E03060A","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3480}, + {"name":"Surface Portal","type":"Portal","wcid":43779,"cell":"7E030767","place":"dungeon","dest":{"cell":"7E030410","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3481}, + {"name":"Portal","type":"Portal","wcid":43758,"cell":"7E0309A6","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3482}, + {"name":"Portal","type":"Portal","wcid":43759,"cell":"7E0309AC","place":"dungeon","dest":{"cell":"7E030410","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3483}, + {"name":"Portal","type":"Portal","wcid":43764,"cell":"7E0309B3","place":"dungeon","dest":{"cell":"7E030606","place":"dungeon"},"desc":"In a dungeon (landblock 7E03).","id":3484}, + {"name":"Surface Portal","type":"Portal","wcid":43790,"cell":"7E03085F","place":"dungeon","dest":{"cell":"73ED0033","place":"outdoor","ns":87.93,"ew":-9.31},"desc":"In a dungeon (landblock 7E03).","id":3485}, + {"name":"End of the Story","type":"Portal","wcid":72953,"cell":"7E04026A","place":"dungeon","dest":{"cell":"CD410105","place":"building","ns":-49.48,"ew":62.7},"minLevel":180,"desc":"In a dungeon (landblock 7E04).","id":3486}, + {"name":"Destroyed Mayoi Portal","type":"Portal","wcid":1022,"cell":"7E130000","place":"outdoor","ns":-86.18,"ew":-0.7,"dest":{"cell":"E6320021","place":"outdoor","ns":-61.91,"ew":82.5},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3487}, + {"name":"Underground Passage","type":"Portal","wcid":14449,"cell":"7E650101","place":"building","ns":-21.0,"ew":-0.8,"dest":{"cell":"01C20123","place":"dungeon","name":"Underground Passage"},"minLevel":20,"quest":true,"id":3488}, + {"name":"Halls of Metos","type":"Portal","wcid":7293,"cell":"7E790000","place":"outdoor","ns":-4.41,"ew":-0.61,"dest":{"cell":"02F30297","place":"dungeon","name":"Halls of Metos"},"minLevel":15,"id":3489}, + {"name":"Precarious Sojourn Portal","type":"Portal","wcid":20625,"cell":"7E820000","place":"outdoor","ns":2.33,"ew":-0.81,"dest":{"cell":"344F0007","place":"outdoor","ns":-38.13,"ew":-60.3},"quest":true,"id":3490}, + {"name":"Destroyed Qalaba'r Portal","type":"Portal","wcid":1023,"cell":"7E910000","place":"outdoor","ns":14.66,"ew":-0.76,"dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3491}, + {"name":"Moss Chamber","type":"Portal","wcid":1339,"cell":"7E910000","place":"outdoor","ns":14.12,"ew":-0.68,"dest":{"cell":"01DB01DC","place":"dungeon","name":"Moss Chamber"},"id":3492}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"7F000198","place":"dungeon","dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"desc":"In a dungeon (landblock 7F00).","id":3493}, + {"name":"Surface Portal","type":"Portal","wcid":6796,"cell":"7F020134","place":"dungeon","dest":{"cell":"1C4D0023","place":"outdoor","ns":-40.16,"ew":-79.14},"desc":"In a dungeon (landblock 7F02).","id":3494}, + {"name":"Surface Portal","type":"Portal","wcid":6796,"cell":"7F0202AA","place":"dungeon","dest":{"cell":"1C4D0023","place":"outdoor","ns":-40.16,"ew":-79.14},"desc":"In a dungeon (landblock 7F02).","id":3495}, + {"name":"Exit to Shoushi","type":"Portal","wcid":29337,"cell":"7F030169","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 7F03).","id":3496}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"7F030273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 7F03).","id":3497}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"7F030331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 7F03).","id":3498}, + {"name":"Exit to Shoushi","type":"Portal","wcid":29337,"cell":"7F040169","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 7F04).","id":3499}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"7F040273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 7F04).","id":3500}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"7F040331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 7F04).","id":3501}, + {"name":"Drudge Hovel","type":"Portal","wcid":28792,"cell":"7F61000F","place":"outdoor","ns":-23.7,"ew":-0.2,"dest":{"cell":"01180237","place":"dungeon","name":"Drudge Hovel"},"id":3502}, + {"name":"South Yaraq Cottages Portal","type":"Portal","wcid":12555,"cell":"7F630000","place":"outdoor","ns":-22.34,"ew":0.22,"dest":{"cell":"815E0012","place":"outdoor","ns":-26.63,"ew":1.51},"id":3503}, + {"name":"Ijaniya Portal","type":"Portal","wcid":12504,"cell":"7F630000","place":"outdoor","ns":-22.37,"ew":0.27,"dest":{"cell":"85560002","place":"outdoor","ns":-32.98,"ew":4.47},"id":3504}, + {"name":"Wi Badlands Settlement Portal","type":"Portal","wcid":12565,"cell":"7F630000","place":"outdoor","ns":-22.43,"ew":0.26,"dest":{"cell":"8C5F001E","place":"outdoor","ns":-25.43,"ew":10.39},"id":3505}, + {"name":"Aqalah Portal","type":"Portal","wcid":12471,"cell":"7F630000","place":"outdoor","ns":-22.47,"ew":0.21,"dest":{"cell":"7C760005","place":"outdoor","ns":-7.07,"ew":-2.67},"id":3506}, + {"name":"North Yaraq Villas Portal","type":"Portal","wcid":13118,"cell":"7F630000","place":"outdoor","ns":-22.34,"ew":0.17,"dest":{"cell":"7C6C0006","place":"outdoor","ns":-15.04,"ew":-2.73},"id":3507}, + {"name":"North Tumerok Vanguard Outpost","type":"Portal","wcid":9141,"cell":"7F760000","place":"outdoor","ns":-7.5,"ew":-0.0,"dest":{"cell":"02A50296","place":"dungeon","name":"North Tumerok Vanguard Outpost"},"minLevel":50,"id":3508}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43563,"cell":"7F8F0123","place":"building","ns":12.54,"ew":-0.0,"dest":{"cell":"E3D30036","place":"outdoor","ns":67.4,"ew":80.3},"id":3509}, + {"name":"Upper Shade Stronghold Portal","type":"Portal","wcid":8847,"cell":"7FDB0000","place":"outdoor","ns":73.49,"ew":-0.27,"dest":{"cell":"02B10268","place":"dungeon","name":"Upper Shade Stronghold"},"minLevel":26,"id":3510}, + {"name":"Shade Stronghold Portal","type":"Portal","wcid":8892,"cell":"7FDB0000","place":"outdoor","ns":73.51,"ew":-0.25,"dest":{"cell":"02B10276","place":"dungeon","name":"Upper Shade Stronghold"},"minLevel":31,"id":3511}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"80000198","place":"dungeon","dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"desc":"In a dungeon (landblock 8000).","id":3512}, + {"name":"Exit to Shoushi","type":"Portal","wcid":29337,"cell":"80020169","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8002).","id":3513}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"80020273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8002).","id":3514}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"80020331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8002).","id":3515}, + {"name":"Exit to Shoushi","type":"Portal","wcid":29337,"cell":"80030169","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8003).","id":3516}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"80030273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8003).","id":3517}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"80030331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8003).","id":3518}, + {"name":"Exit to Shoushi","type":"Portal","wcid":29337,"cell":"80040169","place":"dungeon","dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8004).","id":3519}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"80040273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8004).","id":3520}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"80040331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8004).","id":3521}, + {"name":"Darkened Halls Portal","type":"Portal","wcid":4971,"cell":"80650100","place":"dungeon","dest":{"cell":"014401B4","place":"dungeon"},"minLevel":20,"quest":true,"desc":"In a dungeon (landblock 8065).","id":3522}, + {"name":"Sand Shallow","type":"Portal","wcid":9199,"cell":"80710000","place":"outdoor","ns":-11.48,"ew":0.68,"dest":{"cell":"02A002F5","place":"dungeon","name":"Sand Shallow"},"id":3523}, + {"name":"Carved Cave Portal","type":"Portal","wcid":3630,"cell":"80880100","place":"building","ns":7.41,"ew":0.63,"dest":{"cell":"018F025C","place":"dungeon","name":"Carved Cave"},"id":3524}, + {"name":"Copper Legion Keep","type":"Portal","wcid":29433,"cell":"808E000D","place":"outdoor","ns":12.1,"ew":0.58,"dest":{"cell":"001801C7","place":"dungeon","name":"Copper Legion Keep"},"minLevel":50,"id":3525}, + {"name":"Lair of the Ancient Queen","type":"Portal","wcid":25495,"cell":"808F0000","place":"outdoor","ns":13.2,"ew":0.82,"dest":{"cell":"614A046E","place":"dungeon","name":"Lair of the Ancient Queen"},"quest":true,"id":3526}, + {"name":"Radiant Blood Stronghold","type":"Portal","wcid":37163,"cell":"808F0014","place":"outdoor","ns":12.78,"ew":0.68,"dest":{"cell":"00B90294","place":"dungeon","name":"Radiant Blood Stronghold"},"minLevel":180,"quest":true,"desc":"You must be a member of the Society of the Radiant Blood to enter this Portal.","id":3527}, + {"name":"Radiant Blood Gauntlet","type":"Portal","wcid":53445,"cell":"808F0014","place":"outdoor","ns":12.81,"ew":0.73,"dest":{"cell":"596B010F","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"id":3528}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"80900000","place":"outdoor","ns":13.39,"ew":0.58,"dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"id":3529}, + {"name":"Effigy Foundry Portal","type":"Portal","wcid":19718,"cell":"80900138","place":"building","ns":13.78,"ew":0.57,"dest":{"cell":"545901B0","place":"dungeon","name":"Effigy Foundry"},"id":3530}, + {"name":"Zaikhal Meeting Hall Portal","type":"Portal","wcid":6112,"cell":"8090015D","place":"building","ns":13.37,"ew":0.69,"dest":{"cell":"01350126","place":"dungeon","name":"Zaikhal Meeting Hall"},"id":3531}, + {"name":"Portal to Town Network","type":"Portal","wcid":43066,"cell":"8090000C","place":"outdoor","ns":13.6,"ew":0.61,"dest":{"cell":"00070133","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3532}, + {"name":"Destroyed Portal to Cragstone","type":"Portal","wcid":1014,"cell":"80910000","place":"outdoor","ns":14.82,"ew":0.69,"dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3533}, + {"name":"Platinum Legion Keep","type":"Portal","wcid":29437,"cell":"80940009","place":"outdoor","ns":16.52,"ew":0.61,"dest":{"cell":"001A017A","place":"dungeon","name":"Platinum Legion Keep"},"minLevel":100,"id":3534}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"81000198","place":"dungeon","dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"desc":"In a dungeon (landblock 8100).","id":3535}, + {"name":"Gold Legion Keep","type":"Portal","wcid":29435,"cell":"8190003E","place":"outdoor","ns":13.83,"ew":1.98,"dest":{"cell":"00190105","place":"dungeon","name":"Gold Legion Keep"},"minLevel":80,"id":3536}, + {"name":"Halls of the Helm","type":"Portal","wcid":1512,"cell":"81960000","place":"outdoor","ns":18.71,"ew":1.56,"dest":{"cell":"01CC01E5","place":"dungeon","name":"Halls of the Helm"},"minLevel":10,"id":3537}, + {"name":"Murk Warrens","type":"Portal","wcid":7250,"cell":"81A00000","place":"outdoor","ns":26.3,"ew":1.93,"dest":{"cell":"01010121","place":"dungeon","name":"Murk Warrens"},"id":3538}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"82000198","place":"dungeon","dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"desc":"In a dungeon (landblock 8200).","id":3539}, + {"name":"Four Towers Entrance","type":"Portal","wcid":3956,"cell":"828E0000","place":"outdoor","ns":12.44,"ew":2.33,"dest":{"cell":"828E001E","place":"outdoor","ns":12.16,"ew":2.37},"id":3540}, + {"name":"Exit","type":"Portal","wcid":3957,"cell":"828E0000","place":"outdoor","ns":12.12,"ew":2.34,"dest":{"cell":"828E0008","place":"outdoor","ns":12.36,"ew":2.07},"id":3541}, + {"name":"Impious Temple Portal","type":"Portal","wcid":4975,"cell":"828E0100","place":"building","ns":12.19,"ew":2.41,"dest":{"cell":"015E0165","place":"dungeon","name":"Impious Temple"},"minLevel":20,"id":3542}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"83000198","place":"dungeon","dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"desc":"In a dungeon (landblock 8300).","id":3543}, + {"name":"Forbidden Crypts Portal","type":"Portal","wcid":5517,"cell":"83870100","place":"underground","ns":6.44,"ew":3.0,"dest":{"cell":"013D02D5","place":"dungeon"},"minLevel":15,"id":3544}, + {"name":"Crypt of Ashen Tears","type":"Portal","wcid":1120,"cell":"83910000","place":"outdoor","ns":14.64,"ew":3.54,"dest":{"cell":"01FA034C","place":"dungeon","name":"Crypt of Ashen Tears"},"id":3545}, + {"name":"Destroyed Portal to Cragstone","type":"Portal","wcid":1014,"cell":"83C00000","place":"outdoor","ns":52.16,"ew":3.01,"dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3546}, + {"name":"Viamontian Esper Mine","type":"Portal","wcid":32623,"cell":"83D9000E","place":"outdoor","ns":72.2,"ew":3.02,"dest":{"cell":"0048051A","place":"dungeon","name":"Viamontian Direlands Mine"},"minLevel":100,"quest":true,"desc":"This dungeon is quest restricted.","id":3547}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"84000198","place":"dungeon","dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"desc":"In a dungeon (landblock 8400).","id":3548}, + {"name":"Arena","type":"Portal","wcid":7894,"cell":"84680000","place":"outdoor","ns":-18.51,"ew":3.68,"dest":{"cell":"02E201A3","place":"dungeon","name":"Arena"},"id":3549}, + {"name":"Arena","type":"Portal","wcid":7891,"cell":"84690000","place":"outdoor","ns":-17.91,"ew":3.88,"dest":{"cell":"02E301A3","place":"dungeon","name":"Arena"},"id":3550}, + {"name":"Four Towers Settlement Portal","type":"Portal","wcid":12499,"cell":"84860000","place":"outdoor","ns":5.7,"ew":4.34,"dest":{"cell":"868E0020","place":"outdoor","ns":12.43,"ew":5.64},"id":3551}, + {"name":"Bay of Sands Portal","type":"Portal","wcid":12476,"cell":"84860000","place":"outdoor","ns":5.66,"ew":4.33,"dest":{"cell":"79810005","place":"outdoor","ns":1.71,"ew":-5.08},"id":3552}, + {"name":"Musansayn Portal","type":"Portal","wcid":12525,"cell":"84860000","place":"outdoor","ns":5.66,"ew":4.3,"dest":{"cell":"8E840037","place":"outdoor","ns":4.34,"ew":12.34},"id":3553}, + {"name":"Jackcat Canyon Portal","type":"Portal","wcid":14267,"cell":"84860000","place":"outdoor","ns":5.66,"ew":4.27,"dest":{"cell":"8A7F0003","place":"outdoor","ns":-0.11,"ew":8.54},"id":3554}, + {"name":"Midsong Cottages Portal","type":"Portal","wcid":14272,"cell":"84860000","place":"outdoor","ns":5.74,"ew":4.33,"dest":{"cell":"7D7E003E","place":"outdoor","ns":-0.58,"ew":-1.22},"id":3555}, + {"name":"Alfreth Ridge Cottages Portal","type":"Portal","wcid":14251,"cell":"84860000","place":"outdoor","ns":5.77,"ew":4.32,"dest":{"cell":"8C98001C","place":"outdoor","ns":20.03,"ew":10.39},"id":3556}, + {"name":"Bucolic Villas Portal","type":"Portal","wcid":13095,"cell":"84860000","place":"outdoor","ns":5.78,"ew":4.29,"dest":{"cell":"92B30039","place":"outdoor","ns":41.3,"ew":15.61},"id":3557}, + {"name":"Dillo Butte Settlement Portal","type":"Portal","wcid":14259,"cell":"84860000","place":"outdoor","ns":5.71,"ew":4.21,"dest":{"cell":"9C8D0033","place":"outdoor","ns":11.13,"ew":23.48},"id":3558}, + {"name":"Al-Arqis Cottages Portal","type":"Portal","wcid":14610,"cell":"84860000","place":"outdoor","ns":5.78,"ew":4.26,"dest":{"cell":"7C700003","place":"outdoor","ns":-12.13,"ew":-2.67},"id":3559}, + {"name":"Fearnot Valley Cottages Portal","type":"Portal","wcid":14631,"cell":"84860000","place":"outdoor","ns":5.68,"ew":4.24,"dest":{"cell":"679D0025","place":"outdoor","ns":24.07,"ew":-19.12},"id":3560}, + {"name":"Mirthless Dale Portal","type":"Portal","wcid":15164,"cell":"84860000","place":"outdoor","ns":5.67,"ew":4.37,"dest":{"cell":"4A9C0024","place":"outdoor","ns":23.23,"ew":-42.32},"id":3561}, + {"name":"Mimiana Villas Portal","type":"Portal","wcid":15176,"cell":"84860000","place":"outdoor","ns":5.63,"ew":4.34,"dest":{"cell":"7A9E0026","place":"outdoor","ns":24.99,"ew":-3.93},"id":3562}, + {"name":"Mahara Cottages Portal","type":"Portal","wcid":15171,"cell":"84860000","place":"outdoor","ns":5.61,"ew":4.29,"dest":{"cell":"923B002C","place":"outdoor","ns":-54.44,"ew":15.38},"id":3563}, + {"name":"East Al-Jalima Villas Portal","type":"Portal","wcid":15156,"cell":"84860000","place":"outdoor","ns":5.72,"ew":4.37,"dest":{"cell":"95890021","place":"outdoor","ns":7.71,"ew":17.69},"id":3564}, + {"name":"Nidal-Taraq Villas Portal","type":"Portal","wcid":15678,"cell":"84860000","place":"outdoor","ns":5.6,"ew":4.26,"dest":{"cell":"69920025","place":"outdoor","ns":15.26,"ew":-17.52},"id":3565}, + {"name":"Unified Heart Villas Portal","type":"Portal","wcid":19165,"cell":"84860000","place":"outdoor","ns":5.61,"ew":4.23,"dest":{"cell":"9390002C","place":"outdoor","ns":13.58,"ew":16.16},"id":3566}, + {"name":"Reviled Maw Cottages Portal","type":"Portal","wcid":19156,"cell":"84860000","place":"outdoor","ns":5.67,"ew":4.17,"dest":{"cell":"80AA0014","place":"outdoor","ns":34.44,"ew":0.74},"id":3567}, + {"name":"Tusker Notch Portal","type":"Portal","wcid":19162,"cell":"84860000","place":"outdoor","ns":5.63,"ew":4.2,"dest":{"cell":"84AC0024","place":"outdoor","ns":36.02,"ew":4.1},"id":3568}, + {"name":"Realaidain Northern Vault","type":"Portal","wcid":34544,"cell":"84DE0101","place":"dungeon","dest":{"cell":"005003B5","place":"dungeon"},"minLevel":80,"quest":true,"desc":"This dungeon is quest-restricted. Go see Shan Zhen in Cragstone for more information. In a dungeon (landblock 84DE).","id":3569}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"85000198","place":"dungeon","dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"desc":"In a dungeon (landblock 8500).","id":3570}, + {"name":"Tufa Meeting Hall Portal","type":"Portal","wcid":6108,"cell":"856D0101","place":"building","ns":-14.01,"ew":4.99,"dest":{"cell":"01310126","place":"dungeon","name":"Tufa Meeting Hall"},"id":3571}, + {"name":"Destroyed Portal to Khayyaban","type":"Portal","wcid":4572,"cell":"85880000","place":"outdoor","ns":7.5,"ew":5.06,"dest":{"cell":"9F440012","place":"outdoor","ns":-47.45,"ew":25.62},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3572}, + {"name":"Destroyed Portal to Tou-Tou","type":"Portal","wcid":4568,"cell":"85880000","place":"outdoor","ns":7.09,"ew":4.51,"dest":{"cell":"F5590034","place":"outdoor","ns":-30.41,"ew":94.69},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3573}, + {"name":"Effigy Foundry Portal","type":"Portal","wcid":19718,"cell":"85880128","place":"building","ns":7.44,"ew":4.79,"dest":{"cell":"545901B0","place":"dungeon","name":"Effigy Foundry"},"id":3574}, + {"name":"Portal to Town Network","type":"Portal","wcid":43066,"cell":"8588001E","place":"outdoor","ns":7.44,"ew":4.83,"dest":{"cell":"00070133","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3575}, + {"name":"Al-Jalima Meeting Hall Portal","type":"Portal","wcid":6089,"cell":"85890101","place":"building","ns":7.7,"ew":4.9,"dest":{"cell":"011E0126","place":"dungeon","name":"Al-Jalima Meeting Hall"},"id":3576}, + {"name":"Northern Infiltrator Keep","type":"Portal","wcid":12150,"cell":"85920000","place":"outdoor","ns":15.41,"ew":4.96,"dest":{"cell":"03A30201","place":"dungeon","name":"Northern Infiltrator Keep"},"minLevel":25,"id":3577}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"86000198","place":"dungeon","dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"desc":"In a dungeon (landblock 8600).","id":3578}, + {"name":"Exit to Holtburg","type":"Portal","wcid":29338,"cell":"86020169","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8602).","id":3579}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"86020273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8602).","id":3580}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"86020331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8602).","id":3581}, + {"name":"Exit to Holtburg","type":"Portal","wcid":29338,"cell":"86030169","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8603).","id":3582}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"86030273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8603).","id":3583}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"86030331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8603).","id":3584}, + {"name":"Exit to Holtburg","type":"Portal","wcid":29338,"cell":"86040169","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8604).","id":3585}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"86040273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8604).","id":3586}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"86040331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8604).","id":3587}, + {"name":"Empyrean Cloister Portal","type":"Portal","wcid":8833,"cell":"86620000","place":"outdoor","ns":-23.47,"ew":5.8,"dest":{"cell":"02AD01E4","place":"dungeon","name":"Empyrean Cloister"},"minLevel":15,"id":3588}, + {"name":"Mammet Foundry Portal","type":"Portal","wcid":19716,"cell":"866C010A","place":"building","ns":-14.93,"ew":5.81,"dest":{"cell":"5458025F","place":"dungeon","name":"Mammet Foundry"},"id":3589}, + {"name":"Portal to Town Network","type":"Portal","wcid":43066,"cell":"866C002F","place":"outdoor","ns":-14.87,"ew":5.83,"dest":{"cell":"00070133","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3590}, + {"name":"Burial Temple Portal","type":"Portal","wcid":5515,"cell":"868A0000","place":"outdoor","ns":8.5,"ew":5.93,"dest":{"cell":"013E03FF","place":"dungeon","name":"Burial Temple"},"minLevel":150,"id":3591}, + {"name":"Mountain Cavern Portal","type":"Portal","wcid":5109,"cell":"86CE0000","place":"outdoor","ns":63.16,"ew":5.51,"dest":{"cell":"015D0250","place":"dungeon","name":"Mountain Cavern"},"minLevel":20,"id":3592}, + {"name":"Caulnalain Vestibule Portal","type":"Portal","wcid":7945,"cell":"86D50000","place":"outdoor","ns":68.54,"ew":5.49,"dest":{"cell":"02DC035D","place":"dungeon","name":"Caulnalain Vestibule"},"minLevel":40,"id":3593}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"87000198","place":"dungeon","dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"desc":"In a dungeon (landblock 8700).","id":3594}, + {"name":"Exit to Holtburg","type":"Portal","wcid":29338,"cell":"87020169","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8702).","id":3595}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"87020273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8702).","id":3596}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"87020331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8702).","id":3597}, + {"name":"Exit to Holtburg","type":"Portal","wcid":29338,"cell":"87030169","place":"dungeon","dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8703).","id":3598}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"87030273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8703).","id":3599}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"87030331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8703).","id":3600}, + {"name":"Crystalline Portal","type":"Portal","wcid":40431,"cell":"870403E6","place":"dungeon","dest":{"cell":"00C703A5","place":"dungeon","name":"Crystalline"},"minLevel":70,"desc":"In a dungeon (landblock 8704).","id":3601}, + {"name":"Crystalline Portal","type":"Portal","wcid":40486,"cell":"87040100","place":"dungeon","dest":{"cell":"88030972","place":"dungeon"},"minLevel":110,"desc":"In a dungeon (landblock 8704).","id":3602}, + {"name":"Sand Caves","type":"Portal","wcid":44117,"cell":"8764001D","place":"outdoor","ns":-21.46,"ew":6.43,"dest":{"cell":"5760047D","place":"dungeon","name":"Sand Caves"},"quest":true,"id":3603}, + {"name":"Sand Caves","type":"Portal","wcid":44115,"cell":"87650033","place":"outdoor","ns":-20.86,"ew":6.65,"dest":{"cell":"57600133","place":"dungeon","name":"Sand Caves"},"quest":true,"id":3604}, + {"name":"Sand Caves","type":"Portal","wcid":44116,"cell":"87650003","place":"outdoor","ns":-20.95,"ew":6.14,"dest":{"cell":"5760040E","place":"dungeon","name":"Sand Caves"},"quest":true,"id":3605}, + {"name":"Foundry of Izexi","type":"Portal","wcid":47155,"cell":"87670032","place":"outdoor","ns":-19.4,"ew":6.71,"dest":{"cell":"585604EA","place":"dungeon","name":"Foundry of Izexi"},"minLevel":200,"quest":true,"id":3606}, + {"name":"Southern Mt. Esper","type":"Portal","wcid":8501,"cell":"87680000","place":"outdoor","ns":-18.67,"ew":6.83,"dest":{"cell":"8FC60024","place":"outdoor","ns":56.75,"ew":12.94},"minLevel":12,"id":3607}, + {"name":"Arcanum Research Facility","type":"Portal","wcid":19726,"cell":"87860000","place":"outdoor","ns":5.85,"ew":6.32,"dest":{"cell":"545B0121","place":"dungeon","name":"Arcanum Research Facility"},"minLevel":20,"id":3608}, + {"name":"Mysterious Cave Portal","type":"Portal","wcid":5511,"cell":"87890000","place":"outdoor","ns":7.7,"ew":6.57,"dest":{"cell":"014A0141","place":"dungeon","name":"Mysterious Cave"},"minLevel":15,"id":3609}, + {"name":"River Mouth","type":"Portal","wcid":8500,"cell":"87A30000","place":"outdoor","ns":28.82,"ew":6.68,"dest":{"cell":"3EC5000B","place":"outdoor","ns":55.87,"ew":-52.24},"minLevel":12,"id":3610}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"88000198","place":"dungeon","dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"desc":"In a dungeon (landblock 8800).","id":3611}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"8802027D","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3612}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"8802027E","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3613}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"8802027F","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3614}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"88020281","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3615}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"88020282","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3616}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"88020283","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3617}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"88020286","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3618}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"88020287","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3619}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"88020288","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3620}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"88020293","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3621}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"88020295","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3622}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"88020296","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3623}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"88020299","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3624}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202A4","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3625}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202A7","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3626}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202A8","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3627}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202A9","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3628}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202AB","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3629}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202AC","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3630}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202AD","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3631}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202AE","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3632}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202B3","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3633}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202B4","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3634}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202BB","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3635}, + {"name":"Roost Floor Trap","type":"Portal","wcid":81077,"cell":"880202A3","place":"dungeon","dest":{"cell":"880202CD","place":"dungeon"},"desc":"In a dungeon (landblock 8802).","id":3636}, + {"name":"Portal","type":"Portal","wcid":81089,"cell":"8802036B","place":"dungeon","dest":{"cell":"48230031","place":"outdoor","ns":-73.94,"ew":-43.65},"desc":"In a dungeon (landblock 8802).","id":3637}, + {"name":"Crystalline Portal","type":"Portal","wcid":40485,"cell":"880302CF","place":"dungeon","dest":{"cell":"870401F6","place":"dungeon"},"minLevel":90,"desc":"In a dungeon (landblock 8803).","id":3638}, + {"name":"Crystalline Portal","type":"Portal","wcid":40800,"cell":"88030100","place":"dungeon","dest":{"cell":"2E6C0104","place":"underground","ns":-15.15,"ew":-66.32},"minLevel":130,"desc":"In a dungeon (landblock 8803).","id":3639}, + {"name":"Destroyed Portal to Xarabydun","type":"Portal","wcid":26640,"cell":"880401AB","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 8804).","id":3640}, + {"name":"Surface","type":"Portal","wcid":40280,"cell":"880401E6","place":"dungeon","dest":{"cell":"94720032","place":"outdoor","ns":-10.6,"ew":17.1},"desc":"In a dungeon (landblock 8804).","id":3641}, + {"name":"Destroyed Portal to Xarabydun","type":"Portal","wcid":26640,"cell":"880402C5","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 8804).","id":3642}, + {"name":"Surface","type":"Portal","wcid":40280,"cell":"88040300","place":"dungeon","dest":{"cell":"94720032","place":"outdoor","ns":-10.6,"ew":17.1},"desc":"In a dungeon (landblock 8804).","id":3643}, + {"name":"Destroyed Portal to Xarabydun","type":"Portal","wcid":26640,"cell":"880403DF","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 8804).","id":3644}, + {"name":"Surface","type":"Portal","wcid":40280,"cell":"8804041A","place":"dungeon","dest":{"cell":"94720032","place":"outdoor","ns":-10.6,"ew":17.1},"desc":"In a dungeon (landblock 8804).","id":3645}, + {"name":"Destroyed Portal to Xarabydun","type":"Portal","wcid":26640,"cell":"880404F9","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 8804).","id":3646}, + {"name":"Surface","type":"Portal","wcid":40280,"cell":"88040534","place":"dungeon","dest":{"cell":"94720032","place":"outdoor","ns":-10.6,"ew":17.1},"desc":"In a dungeon (landblock 8804).","id":3647}, + {"name":"Bone Lair","type":"Portal","wcid":4917,"cell":"885A0101","place":"building","ns":-29.4,"ew":6.98,"dest":{"cell":"01450168","place":"dungeon","name":"Bone Lair"},"id":3648}, + {"name":"Desert Dwelling","type":"Portal","wcid":48823,"cell":"8865003A","place":"outdoor","ns":-20.98,"ew":7.63,"dest":{"cell":"58630252","place":"dungeon","name":"Desert Dwelling"},"minLevel":180,"id":3649}, + {"name":"Sanctuary of the Recluse","type":"Portal","wcid":52214,"cell":"88650034","place":"outdoor","ns":-20.83,"ew":7.48,"dest":{"cell":"586601D1","place":"dungeon","name":"Sanctuary of the Recluse"},"minLevel":180,"quest":true,"id":3650}, + {"name":"Tanada House of Earth","type":"Portal","wcid":34374,"cell":"88D20100","place":"dungeon","dest":{"cell":"005701AD","place":"dungeon"},"minLevel":80,"quest":true,"desc":"This portal leads to the House of Earth, the first chamber in the Tanada training school. In a dungeon (landblock 88D2).","id":3651}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"89000198","place":"dungeon","dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"desc":"In a dungeon (landblock 8900).","id":3652}, + {"name":"Destroyed Portal to Xarabydun","type":"Portal","wcid":26640,"cell":"890201AB","place":"dungeon","dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 8902).","id":3653}, + {"name":"Surface","type":"Portal","wcid":40280,"cell":"890201E6","place":"dungeon","dest":{"cell":"94720032","place":"outdoor","ns":-10.6,"ew":17.1},"desc":"In a dungeon (landblock 8902).","id":3654}, + {"name":"Surface","type":"Portal","wcid":42714,"cell":"89040158","place":"dungeon","dest":{"cell":"26450007","place":"outdoor","ns":-46.1,"ew":-71.49},"desc":"In Empyrean Facility Upper Level.","id":3655}, + {"name":"Empyrean Facility Lower Level","type":"Portal","wcid":42712,"cell":"8904024C","place":"dungeon","dest":{"cell":"8904014D","place":"dungeon","name":"Empyrean Facility Upper Level"},"minLevel":225,"desc":"In Empyrean Facility Upper Level.","id":3656}, + {"name":"Empyrean Facility Middle Level","type":"Portal","wcid":42713,"cell":"89040340","place":"dungeon","dest":{"cell":"890401D0","place":"dungeon","name":"Empyrean Facility Upper Level"},"minLevel":150,"desc":"In Empyrean Facility Upper Level.","id":3657}, + {"name":"Temple Exit","type":"Portal","wcid":88227,"cell":"8954041D","place":"dungeon","dest":{"cell":"8954003B","place":"outdoor","ns":-34.48,"ew":8.43},"minLevel":150,"desc":"In a dungeon (landblock 8954).","id":3658}, + {"name":"Temple","type":"Portal","wcid":44136,"cell":"89650016","place":"outdoor","ns":-20.62,"ew":7.93,"dest":{"cell":"57560161","place":"dungeon","name":"Temple"},"quest":true,"id":3659}, + {"name":"Deep Caves","type":"Portal","wcid":45799,"cell":"8965002D","place":"outdoor","ns":-20.69,"ew":8.24,"dest":{"cell":"594E0686","place":"dungeon","name":"Deep Caves"},"quest":true,"id":3660}, + {"name":"Aerbax Laboratory","type":"Portal","wcid":9201,"cell":"89720000","place":"outdoor","ns":-10.18,"ew":8.12,"dest":{"cell":"029E0269","place":"dungeon","name":"Aerbax Laboratory"},"id":3661}, + {"name":"Crypt of Crimson Night","type":"Portal","wcid":34011,"cell":"898E0100","place":"dungeon","dest":{"cell":"009B021C","place":"dungeon"},"minLevel":70,"quest":true,"desc":"In a dungeon (landblock 898E).","id":3662}, + {"name":"Artifex Vault Portal","type":"Portal","wcid":6391,"cell":"899E0000","place":"outdoor","ns":24.52,"ew":8.03,"dest":{"cell":"01370341","place":"dungeon","name":"Artifex Vault"},"id":3663}, + {"name":"The Fazenda Caves","type":"Portal","wcid":31374,"cell":"89BD0100","place":"dungeon","dest":{"cell":"003402A2","place":"dungeon"},"minLevel":40,"desc":"In a dungeon (landblock 89BD).","id":3664}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"8A000198","place":"dungeon","dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"desc":"In a dungeon (landblock 8A00).","id":3665}, + {"name":"An Olthoi Soldier Nest","type":"Portal","wcid":42170,"cell":"8A020102","place":"dungeon","dest":{"cell":"20B70006","place":"outdoor","ns":45.02,"ew":-76.27},"minLevel":35,"desc":"A portal leading to the Marae Lassel Plateau near An Olthoi Soldier Nest where the Soldier Pincer may be found. In Hub of Awakening.","id":3666}, + {"name":"Ancient Empyrean Grotto","type":"Portal","wcid":42148,"cell":"8A020103","place":"dungeon","dest":{"cell":"24C10002","place":"outdoor","ns":52.58,"ew":-73.11},"minLevel":40,"desc":"A portal leading to the Marae Lassel Plateau near An Ancient Empyrean Grotto where the Legionary Pincer may be found. In Hub of Awakening.","id":3667}, + {"name":"Crumbling Empyrean Mansion","type":"Portal","wcid":42154,"cell":"8A020109","place":"dungeon","dest":{"cell":"2AB90030","place":"outdoor","ns":46.8,"ew":-67.84},"minLevel":30,"desc":"A portal leading to near the Crumbling Empyrean Mansion outside Greenspire where the Worker Pincer may be found. In Hub of Awakening.","id":3668}, + {"name":"The Dark Lair","type":"Portal","wcid":42155,"cell":"8A020111","place":"dungeon","dest":{"cell":"29B60039","place":"outdoor","ns":43.75,"ew":-68.42},"minLevel":20,"desc":"A portal leading to near The Dark Lair outside Greenspire where the Gardener Pincer may be found. In Hub of Awakening.","id":3669}, + {"name":"Abandoned Tumerok Site","type":"Portal","wcid":42146,"cell":"8A020112","place":"dungeon","dest":{"cell":"18B3002F","place":"outdoor","ns":41.89,"ew":-82.19},"minLevel":15,"desc":"A portal leading to near the Abandoned Tumerok Site outside Redspire where the Harvester Pincer may be found. In Hub of Awakening.","id":3670}, + {"name":"Tumerok Camps","type":"Portal","wcid":42174,"cell":"8A020115","place":"dungeon","dest":{"cell":"DA75002B","place":"outdoor","ns":-8.09,"ew":73.02},"minLevel":40,"desc":"A portal leading to Dryreach from which you can find the six Tumerok camps. Falcon Clan Training Camp at 2.0N, 75.0E. Serpent Clan Training Camp 1.0S, 70.0E. Shreth Clan Training Camp 5.0S, 68.0E. Reedshark Clan Training Camp 13.0S, 68.0E. Gromnie Clan Training Camp 16.0S, 70.0E. Mask Clan Training Camp 16.0S, 75.0E. In Hub of Awakening.","id":3671}, + {"name":"Tusker Burrow","type":"Portal","wcid":42177,"cell":"8A020118","place":"dungeon","dest":{"cell":"F9810038","place":"outdoor","ns":2.03,"ew":97.9},"minLevel":15,"desc":"A portal leading to Aphus Lassel near the Tusker Burrow where the Female Tusker Tusk may be found. In Hub of Awakening.","id":3672}, + {"name":"Tusker Lodge","type":"Portal","wcid":42181,"cell":"8A020119","place":"dungeon","dest":{"cell":"F97F003E","place":"outdoor","ns":0.16,"ew":98.03},"minLevel":15,"desc":"A portal leading to Aphus Lassel near the Tusker Lodge where the Male Tusker Tusk may be found. In Hub of Awakening.","id":3673}, + {"name":"Tusker Cave","type":"Portal","wcid":42178,"cell":"8A02011A","place":"dungeon","dest":{"cell":"F97F0008","place":"outdoor","ns":0.4,"ew":97.33},"minLevel":15,"desc":"A portal leading to Aphus Lassel near the Tusker Cave where the Tusker Crimsonback Tusk may be found. In Hub of Awakening.","id":3674}, + {"name":"Tusker Barracks","type":"Portal","wcid":42176,"cell":"8A02011E","place":"dungeon","dest":{"cell":"F07E0040","place":"outdoor","ns":-0.36,"ew":90.77},"minLevel":40,"desc":"A portal leading to Aphus Lassel near the Tusker Barracks where the Tusker Guard Tusk may be found. In Hub of Awakening.","id":3675}, + {"name":"Tusker Cavern","type":"Portal","wcid":42179,"cell":"8A02011F","place":"dungeon","dest":{"cell":"F8800027","place":"outdoor","ns":1.06,"ew":96.86},"minLevel":15,"desc":"A portal leading to Aphus Lassel near the Tusker Cavern where the Goldenback Tusker Tusk may be found. In Hub of Awakening.","id":3676}, + {"name":"Tusker Quarters","type":"Portal","wcid":42182,"cell":"8A020121","place":"dungeon","dest":{"cell":"F67C003D","place":"outdoor","ns":-2.28,"ew":95.57},"minLevel":30,"desc":"A portal leading to Aphus Lassel near the Tusker Quarters where the Tusker Slave Tusk may be found. In Hub of Awakening.","id":3677}, + {"name":"Tusker Habitat","type":"Portal","wcid":42180,"cell":"8A020122","place":"dungeon","dest":{"cell":"F77E0017","place":"outdoor","ns":-0.46,"ew":95.89},"minLevel":25,"desc":"A portal leading to Aphus Lassel near the Tusker Habitat where the Tusker Liberator Tusk may be found. In Hub of Awakening.","id":3678}, + {"name":"Tusker Abode","type":"Portal","wcid":42175,"cell":"8A020123","place":"dungeon","dest":{"cell":"F67B000C","place":"outdoor","ns":-3.2,"ew":94.96},"minLevel":20,"desc":"A portal leading to Aphus Lassel near the Tusker Abode where the Tusker Redeemer Tusk may be found. In Hub of Awakening.","id":3679}, + {"name":"Dryreach","type":"Portal","wcid":42156,"cell":"8A020184","place":"dungeon","dest":{"cell":"DB740007","place":"outdoor","ns":-8.46,"ew":73.32},"minLevel":40,"quest":true,"desc":"A portal leading a cottage near Dryreach where Yu Vuo-Ki and her missing sister Dansha-Ki may be found. In Hub of Awakening.","id":3680}, + {"name":"Castle of Baron Nuvillus","type":"Portal","wcid":42153,"cell":"8A020193","place":"dungeon","dest":{"cell":"DF600017","place":"outdoor","ns":-24.51,"ew":76.75},"minLevel":40,"quest":true,"desc":"A portal leading to the Castle of Baron Nuvillus where the Crown of Bone may be found. In Hub of Awakening.","id":3681}, + {"name":"Blackmire Temple","type":"Portal","wcid":42151,"cell":"8A020196","place":"dungeon","dest":{"cell":"BB64001B","place":"outdoor","ns":-21.74,"ew":47.97},"minLevel":45,"quest":true,"desc":"A portal leading a Blackmire Temple where blackmire lore pages may be found. In Hub of Awakening.","id":3682}, + {"name":"Bellig Tower Base","type":"Portal","wcid":42161,"cell":"8A02019A","place":"dungeon","dest":{"cell":"93950015","place":"outdoor","ns":17.68,"ew":15.93},"minLevel":40,"quest":true,"desc":"A portal leading to the Bellig Tower Base where the Hammer of Lightning may be found. In Hub of Awakening.","id":3683}, + {"name":"Suntik","type":"Portal","wcid":42147,"cell":"8A02019D","place":"dungeon","dest":{"cell":"84940011","place":"outdoor","ns":16.48,"ew":3.86},"minLevel":35,"quest":true,"desc":"A portal leading to a location near Suntik where the Acid Axe may be found. In Hub of Awakening.","id":3684}, + {"name":"Haunted Mansion","type":"Portal","wcid":42162,"cell":"8A0201A1","place":"dungeon","dest":{"cell":"B6860008","place":"outdoor","ns":6.02,"ew":43.74},"minLevel":30,"quest":true,"desc":"A portal leading to Frest Greelving's now haunted mansion where Silver Atlatl, Tetsubo Slugger and Ornate Neckode may be found. In Hub of Awakening.","id":3685}, + {"name":"Banderling Camp","type":"Portal","wcid":42149,"cell":"8A0201A4","place":"dungeon","dest":{"cell":"9EB60029","place":"outdoor","ns":43.7,"ew":25.0},"minLevel":35,"quest":true,"desc":"A portal leading to a location near Edelbar where the Quarter Staff of Fire may be found. In Hub of Awakening.","id":3686}, + {"name":"Mite Maze","type":"Portal","wcid":42152,"cell":"8A0201B6","place":"dungeon","dest":{"cell":"C6B2002F","place":"outdoor","ns":41.08,"ew":57.03},"minLevel":30,"quest":true,"desc":"A portal leading to the the Lost Wish Mountains near the Mite Maze where Branith's stolen possessions may be found. In Hub of Awakening.","id":3687}, + {"name":"Skeleton Fort","type":"Portal","wcid":42164,"cell":"8A0201B9","place":"dungeon","dest":{"cell":"D2A70017","place":"outdoor","ns":32.31,"ew":66.32},"minLevel":35,"quest":true,"desc":"A portal leading to a fort where Jacob's Axe may be found. In Hub of Awakening.","id":3688}, + {"name":"Mountain Sewer","type":"Portal","wcid":42169,"cell":"8A0201BD","place":"dungeon","dest":{"cell":"E533003B","place":"outdoor","ns":-60.94,"ew":82.0},"minLevel":30,"quest":true,"desc":"A portal leading to the Mountain Sewer where the Ancient Arbalest may be found. In Hub of Awakening.","id":3689}, + {"name":"Green Mire Grave","type":"Portal","wcid":42160,"cell":"8A0201CA","place":"dungeon","dest":{"cell":"D85C003F","place":"outdoor","ns":-27.74,"ew":71.63},"minLevel":15,"quest":true,"desc":"A portal leading to Green Mire Grave where the Green Mire Warrior artifacts may be found. In Hub of Awakening.","id":3690}, + {"name":"Mosswart Camp","type":"Portal","wcid":42163,"cell":"8A0201CE","place":"dungeon","dest":{"cell":"D75D0029","place":"outdoor","ns":-27.54,"ew":70.58},"minLevel":10,"quest":true,"desc":"A portal leading to a Mosswart Camp where the Ice Tachi will be found. In Hub of Awakening.","id":3691}, + {"name":"Colier","type":"Portal","wcid":42150,"cell":"8A0201D1","place":"dungeon","dest":{"cell":"AEC60027","place":"outdoor","ns":57.14,"ew":37.66},"minLevel":15,"quest":true,"desc":"A portal leading to Colier Mine where the Baron's Amulet of Life Giving may be found. In Hub of Awakening.","id":3692}, + {"name":"Folthid Estate","type":"Portal","wcid":42158,"cell":"8A0201E3","place":"dungeon","dest":{"cell":"C274001C","place":"outdoor","ns":-8.81,"ew":53.64},"minLevel":10,"quest":true,"desc":"A portal leading to the Folthid Estate where the Dull Dagger and Dagger of Tikola may be found. In Hub of Awakening.","id":3693}, + {"name":"Halls of Helm","type":"Portal","wcid":42171,"cell":"8A0201E6","place":"dungeon","dest":{"cell":"8196002F","place":"outdoor","ns":18.73,"ew":1.77},"minLevel":15,"quest":true,"desc":"A portal leading to Halls of Helm where the Superior Helm and Fiery Shield may be found. In Hub of Awakening.","id":3694}, + {"name":"Glenden Wood","type":"Portal","wcid":42159,"cell":"8A0201EA","place":"dungeon","dest":{"cell":"A0A40017","place":"outdoor","ns":29.87,"ew":26.34},"minLevel":10,"quest":true,"desc":"A portal leading to Glendon Wood where the Platemail Hauberk of the Ogre may be found. In Hub of Awakening.","id":3695}, + {"name":"Fledgemaster's Camp","type":"Portal","wcid":42157,"cell":"8A0201ED","place":"dungeon","dest":{"cell":"34E0002A","place":"outdoor","ns":77.43,"ew":-59.8},"minLevel":25,"quest":true,"desc":"A portal leading to the Ruschk Fledgemaster's Camp where a Fledgemaster's Tusk may be found. In Hub of Awakening.","id":3696}, + {"name":"Hunter's Leap","type":"Portal","wcid":42165,"cell":"8A0201F1","place":"dungeon","dest":{"cell":"A9AC0012","place":"outdoor","ns":35.77,"ew":33.48},"minLevel":20,"quest":true,"desc":"A portal leading to the Hunter's Leap where the Lilitha's Bow may be found. In Hub of Awakening.","id":3697}, + {"name":"Banderling Conquest Dungeon","type":"Portal","wcid":42166,"cell":"8A0201F4","place":"dungeon","dest":{"cell":"BE5B0012","place":"outdoor","ns":-28.95,"ew":50.31},"minLevel":25,"quest":true,"desc":"A portal leading to the Banderling Conquest Dungeon where part of the Explorer's Mace may be found. In Hub of Awakening.","id":3698}, + {"name":"Mosswart Maze","type":"Portal","wcid":42167,"cell":"8A0201F4","place":"dungeon","dest":{"cell":"975F002F","place":"outdoor","ns":-25.28,"ew":19.41},"minLevel":25,"quest":true,"desc":"A portal leading to the Mosswart Maze where part of the Explorer's Mace may be found. In Hub of Awakening.","id":3699}, + {"name":"Eastham Portal","type":"Portal","wcid":42815,"cell":"8A0201F4","place":"dungeon","dest":{"cell":"CE940035","place":"outdoor","ns":16.92,"ew":63.48},"desc":"This portal goes to Eastham, a coastal Aluvian town that contains a portal to Asheron's island home. This is a good town for characters over level 20. In Hub of Awakening.","id":3700}, + {"name":"Trothyr's Rest","type":"Portal","wcid":42173,"cell":"8A020205","place":"dungeon","dest":{"cell":"BE900034","place":"outdoor","ns":13.57,"ew":50.67},"minLevel":20,"quest":true,"desc":"A portal leading to Trothyr's Rest where Trothyr's artifacts may be found. In Hub of Awakening.","id":3701}, + {"name":"Catacombs of the Forgotten","type":"Portal","wcid":42168,"cell":"8A020208","place":"dungeon","dest":{"cell":"A895001A","place":"outdoor","ns":17.35,"ew":32.76},"minLevel":25,"quest":true,"desc":"A portal leading to the Catacombs of the Forgotten where Mi Krau-Li's Jitte may be found. In Hub of Awakening.","id":3702}, + {"name":"Dangerous Cave","type":"Portal","wcid":42172,"cell":"8A02020B","place":"dungeon","dest":{"cell":"B59D001F","place":"outdoor","ns":24.29,"ew":43.22},"minLevel":20,"quest":true,"desc":"A portal leading to a Dangerous Cave where the Tibiri's Fire Spear may be found. In Hub of Awakening.","id":3703}, + {"name":"Stronghold","type":"Portal","wcid":42222,"cell":"8A030185","place":"dungeon","dest":{"cell":"00B7010D","place":"dungeon","name":"Celestial Hand Stronghold"},"desc":"In a dungeon (landblock 8A03).","id":3704}, + {"name":"Stronghold","type":"Portal","wcid":42221,"cell":"8A030215","place":"dungeon","dest":{"cell":"00B9010D","place":"dungeon","name":"Radiant Blood Stronghold"},"desc":"In a dungeon (landblock 8A03).","id":3705}, + {"name":"Stronghold","type":"Portal","wcid":42223,"cell":"8A0302A5","place":"dungeon","dest":{"cell":"00B8010D","place":"dungeon","name":"Eldrytch Web Stronghold"},"desc":"In a dungeon (landblock 8A03).","id":3706}, + {"name":"Portal to Cragstone","type":"Portal","wcid":42818,"cell":"8A0401ED","place":"dungeon","dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal goes to the Aluvian capital, Cragstone. This is a good town for characters over level 10. In a dungeon (landblock 8A04).","id":3707}, + {"name":"Portal to Hebian-To","type":"Portal","wcid":42846,"cell":"8A04020F","place":"dungeon","dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal goes to the Sho capital, Hebian-To. This is a good town for characters over level 10. In a dungeon (landblock 8A04).","id":3708}, + {"name":"Portal to Sanamar","type":"Portal","wcid":42835,"cell":"8A040209","place":"dungeon","dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"desc":"This portal goes to Sanamar, the capital of New Viamont and town where many new adventurers enter Dereth. This is a good town for characters of all levels. In a dungeon (landblock 8A04).","id":3709}, + {"name":"Portal to Zaikhal","type":"Portal","wcid":42831,"cell":"8A0401E9","place":"dungeon","dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal goes to the Gharu'ndim capital, Zaikhal. This is a good town for characters over level 20. In a dungeon (landblock 8A04).","id":3710}, + {"name":"Unfinished Temple Portal","type":"Portal","wcid":4939,"cell":"8A590101","place":"building","ns":-30.08,"ew":9.1,"dest":{"cell":"015B016E","place":"dungeon","name":"Unfinished Temple"},"minLevel":1,"maxLevel":20,"id":3711}, + {"name":"Temple of Mornings","type":"Portal","wcid":88200,"cell":"8A63029C","place":"underground","ns":-21.92,"ew":8.32,"dest":{"cell":"8A630290","place":"underground","ns":-22.09,"ew":8.18},"minLevel":150,"quest":true,"id":3712}, + {"name":"Temple Exit","type":"Portal","wcid":88209,"cell":"8A63010A","place":"underground","ns":-21.94,"ew":8.52,"dest":{"cell":"8A63029D","place":"underground","ns":-21.92,"ew":8.34},"minLevel":150,"id":3713}, + {"name":"Singular Pyreal Repository","type":"Portal","wcid":12296,"cell":"8A7A0000","place":"outdoor","ns":-4.2,"ew":8.92,"dest":{"cell":"03A102B6","place":"dungeon","name":"Singular Pyreal Repository"},"minLevel":24,"id":3714}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"8B000198","place":"dungeon","dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"desc":"In a dungeon (landblock 8B00).","id":3715}, + {"name":"Surface","type":"Portal","wcid":43202,"cell":"8B030190","place":"dungeon","dest":{"cell":"21760036","place":"outdoor","ns":-7.0,"ew":-74.9},"desc":"In a dungeon (landblock 8B03).","id":3716}, + {"name":"Surface","type":"Portal","wcid":43202,"cell":"8B030478","place":"dungeon","dest":{"cell":"21760036","place":"outdoor","ns":-7.0,"ew":-74.9},"desc":"In a dungeon (landblock 8B03).","id":3717}, + {"name":"Surface","type":"Portal","wcid":43202,"cell":"8B030400","place":"dungeon","dest":{"cell":"21760036","place":"outdoor","ns":-7.0,"ew":-74.9},"desc":"In a dungeon (landblock 8B03).","id":3718}, + {"name":"Surface","type":"Portal","wcid":43202,"cell":"8B030333","place":"dungeon","dest":{"cell":"21760036","place":"outdoor","ns":-7.0,"ew":-74.9},"desc":"In a dungeon (landblock 8B03).","id":3719}, + {"name":"Surface","type":"Portal","wcid":43202,"cell":"8B030100","place":"dungeon","dest":{"cell":"21760036","place":"outdoor","ns":-7.0,"ew":-74.9},"desc":"In a dungeon (landblock 8B03).","id":3720}, + {"name":"Empyrean Lightning Propylaeum","type":"Portal","wcid":14503,"cell":"8B120000","place":"outdoor","ns":-87.09,"ew":9.51,"dest":{"cell":"5274014B","place":"dungeon","name":"Empyrean Lightning Propylaeum"},"minLevel":50,"id":3721}, + {"name":"Tomb of The Dead","type":"Portal","wcid":9188,"cell":"8B680102","place":"dungeon","dest":{"cell":"01F301C6","place":"dungeon"},"desc":"In a dungeon (landblock 8B68).","id":3722}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"8C000198","place":"dungeon","dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"desc":"In a dungeon (landblock 8C00).","id":3723}, + {"name":"Exit to Yaraq","type":"Portal","wcid":29340,"cell":"8C040169","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8C04).","id":3724}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"8C040273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8C04).","id":3725}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"8C040331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8C04).","id":3726}, + {"name":"Charged Refuge","type":"Portal","wcid":45721,"cell":"8C120028","place":"outdoor","ns":-86.82,"ew":10.54,"dest":{"cell":"576A01B4","place":"dungeon","name":"Charged Refuge"},"minLevel":150,"quest":true,"id":3727}, + {"name":"Lightning Guardian Lair","type":"Portal","wcid":21420,"cell":"8C130000","place":"outdoor","ns":-86.68,"ew":10.42,"dest":{"cell":"5A43014A","place":"dungeon","name":"Lightning Guardian Lair"},"minLevel":80,"maxLevel":149,"id":3728}, + {"name":"Masked Preface","type":"Portal","wcid":51282,"cell":"8C430033","place":"outdoor","ns":-48.12,"ew":10.67,"dest":{"cell":"586C0406","place":"dungeon","name":"Masked Preface"},"minLevel":180,"id":3729}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"8D000198","place":"dungeon","dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"desc":"In a dungeon (landblock 8D00).","id":3730}, + {"name":"Exit to Yaraq","type":"Portal","wcid":29340,"cell":"8D020169","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8D02).","id":3731}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"8D020273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8D02).","id":3732}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"8D020331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8D02).","id":3733}, + {"name":"Exit to Yaraq","type":"Portal","wcid":29340,"cell":"8D030169","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8D03).","id":3734}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"8D030273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8D03).","id":3735}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"8D030331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8D03).","id":3736}, + {"name":"Exit to Yaraq","type":"Portal","wcid":29340,"cell":"8D040169","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8D04).","id":3737}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"8D040273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8D04).","id":3738}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"8D040331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8D04).","id":3739}, + {"name":"Syliph Tower","type":"Portal","wcid":426,"cell":"8D8E0000","place":"outdoor","ns":12.33,"ew":11.49,"dest":{"cell":"01D501C0","place":"dungeon","name":"Syliph Tower"},"id":3740}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"8E000198","place":"dungeon","dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"desc":"In a dungeon (landblock 8E00).","id":3741}, + {"name":"Exit to Yaraq","type":"Portal","wcid":29340,"cell":"8E020169","place":"dungeon","dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"quest":true,"desc":"You must complete the Sentry's quest before you may use this portal. In a dungeon (landblock 8E02).","id":3742}, + {"name":"Central Courtyard","type":"Portal","wcid":31061,"cell":"8E020273","place":"dungeon","quest":true,"desc":"Walk into this portal to enter the Central Courtyard. You must finish the Training Master's task before you can use this portal. In a dungeon (landblock 8E02).","id":3743}, + {"name":"Outer Courtyard","type":"Portal","wcid":29334,"cell":"8E020331","place":"dungeon","desc":"Walk into this portal to enter the Outer Courtyard. In a dungeon (landblock 8E02).","id":3744}, + {"name":"Destroyed Portal to Yanshi","type":"Portal","wcid":1029,"cell":"8E510102","place":"dungeon","dest":{"cell":"B9720021","place":"outdoor","ns":-10.74,"ew":46.55},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans. In a dungeon (landblock 8E51).","id":3745}, + {"name":"Nor's Folly Portal","type":"Portal","wcid":7206,"cell":"8E560000","place":"outdoor","ns":-32.48,"ew":11.86,"dest":{"cell":"01070166","place":"dungeon","name":"Nor's Folly"},"id":3746}, + {"name":"Base of Mt. Syliph","type":"Portal","wcid":441,"cell":"8E8D0000","place":"outdoor","ns":11.23,"ew":12.18,"dest":{"cell":"8E8D0038","place":"outdoor","ns":11.61,"ew":12.28},"id":3747}, + {"name":"Mt. Syliph Plain","type":"Portal","wcid":442,"cell":"8E8D0000","place":"outdoor","ns":11.56,"ew":12.27,"dest":{"cell":"8E8D002C","place":"outdoor","ns":11.21,"ew":12.18},"id":3748}, + {"name":"South Dalt","type":"Portal","wcid":440,"cell":"8E8F0000","place":"outdoor","ns":12.73,"ew":11.85,"dest":{"cell":"8F910011","place":"outdoor","ns":14.07,"ew":12.68},"id":3749}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"8F000198","place":"dungeon","dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"desc":"In a dungeon (landblock 8F00).","id":3750}, + {"name":"Arqasanti Portal","type":"Portal","wcid":12474,"cell":"8F550000","place":"outdoor","ns":-33.48,"ew":13.17,"dest":{"cell":"9260001D","place":"outdoor","ns":-24.67,"ew":15.24},"id":3751}, + {"name":"Al-Hatar Settlement Portal","type":"Portal","wcid":12469,"cell":"8F550000","place":"outdoor","ns":-33.52,"ew":13.17,"dest":{"cell":"96540003","place":"outdoor","ns":-34.52,"ew":18.14},"id":3752}, + {"name":"Monument Sands Settlement Portal","type":"Portal","wcid":12521,"cell":"8F550000","place":"outdoor","ns":-33.57,"ew":13.11,"dest":{"cell":"93500019","place":"outdoor","ns":-37.86,"ew":16.02},"id":3753}, + {"name":"Al-Kasan Settlement Portal","type":"Portal","wcid":12470,"cell":"8F550000","place":"outdoor","ns":-33.57,"ew":13.07,"dest":{"cell":"8B550030","place":"outdoor","ns":-33.22,"ew":9.78},"id":3754}, + {"name":"Dry Bone Manors Portal","type":"Portal","wcid":13099,"cell":"8F550000","place":"outdoor","ns":-33.57,"ew":13.17,"dest":{"cell":"965A003D","place":"outdoor","ns":-29.49,"ew":18.8},"id":3755}, + {"name":"Pillars-on-the-Sea Cottages Portal","type":"Portal","wcid":14277,"cell":"8F550000","place":"outdoor","ns":-33.56,"ew":13.03,"dest":{"cell":"8A480014","place":"outdoor","ns":-44.01,"ew":8.72},"id":3756}, + {"name":"Tarn Vinara Villas Portal","type":"Portal","wcid":14673,"cell":"8F550000","place":"outdoor","ns":-33.44,"ew":13.17,"dest":{"cell":"5FA2002E","place":"outdoor","ns":28.17,"ew":-25.4},"id":3757}, + {"name":"Djinaya Wind Cottages Portal","type":"Portal","wcid":14621,"cell":"8F550000","place":"outdoor","ns":-33.4,"ew":13.16,"dest":{"cell":"8D630015","place":"outdoor","ns":-22.28,"ew":11.1},"id":3758}, + {"name":"Hamud Cottages Portal","type":"Portal","wcid":14633,"cell":"8F550000","place":"outdoor","ns":-33.56,"ew":13.0,"dest":{"cell":"9264001C","place":"outdoor","ns":-21.58,"ew":15.2},"id":3759}, + {"name":"Bleached Skull Wastes Settlement Portal","type":"Portal","wcid":14613,"cell":"8F550000","place":"outdoor","ns":-33.54,"ew":12.97,"dest":{"cell":"8B6D001B","place":"outdoor","ns":-14.51,"ew":9.58},"id":3760}, + {"name":"Desert Mirage Cottages Portal","type":"Portal","wcid":14618,"cell":"8F550000","place":"outdoor","ns":-33.38,"ew":13.13,"dest":{"cell":"906C0024","place":"outdoor","ns":-15.22,"ew":13.74},"id":3761}, + {"name":"Al-Nosaj Portal","type":"Portal","wcid":14611,"cell":"8F550000","place":"outdoor","ns":-33.36,"ew":13.11,"dest":{"cell":"9170001B","place":"outdoor","ns":-12.12,"ew":14.37},"id":3762}, + {"name":"Ahr-Zona Portal","type":"Portal","wcid":15138,"cell":"8F550000","place":"outdoor","ns":-33.51,"ew":12.94,"dest":{"cell":"9664001B","place":"outdoor","ns":-21.66,"ew":18.45},"id":3763}, + {"name":"Abandoned Shops Portal","type":"Portal","wcid":4943,"cell":"8F560102","place":"dungeon","dest":{"cell":"0159018F","place":"dungeon"},"minLevel":40,"desc":"In a dungeon (landblock 8F56).","id":3764}, + {"name":"South Gemm","type":"Portal","wcid":438,"cell":"8F910000","place":"outdoor","ns":14.63,"ew":13.25,"dest":{"cell":"91930009","place":"outdoor","ns":15.66,"ew":14.18},"id":3765}, + {"name":"North Syliph","type":"Portal","wcid":439,"cell":"8F910000","place":"outdoor","ns":14.05,"ew":12.67,"dest":{"cell":"8E8F000B","place":"outdoor","ns":12.72,"ew":11.83},"id":3766}, + {"name":"Alfreth Dungeon","type":"Portal","wcid":371,"cell":"8F990000","place":"outdoor","ns":20.48,"ew":13.22,"dest":{"cell":"01D601B9","place":"dungeon","name":"Alfreth Dungeon"},"id":3767}, + {"name":"Mountain Cavern Portal","type":"Portal","wcid":43531,"cell":"8FCF003D","place":"outdoor","ns":64.07,"ew":13.19,"dest":{"cell":"015D0250","place":"dungeon","name":"Mountain Cavern"},"minLevel":200,"desc":"A portal, created by Liam of Gelid, so that those strong enough to treat with him could reach him more easily.","id":3768}, + {"name":"Crater Caves Dungeon","type":"Portal","wcid":2387,"cell":"8FD20000","place":"outdoor","ns":66.68,"ew":12.52,"dest":{"cell":"019A02CA","place":"dungeon","name":"Crater Caves Dungeon"},"id":3769}, + {"name":"Crater Lair","type":"Portal","wcid":3651,"cell":"8FD70000","place":"outdoor","ns":70.53,"ew":12.69,"dest":{"cell":"018C0191","place":"dungeon","name":"Crater Lair"},"minLevel":15,"id":3770}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"90000198","place":"dungeon","dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"desc":"In a dungeon (landblock 9000).","id":3771}, + {"name":"Desert Ridge Border","type":"Portal","wcid":1903,"cell":"90240000","place":"outdoor","ns":-72.68,"ew":14.01,"dest":{"cell":"B178001C","place":"outdoor","ns":-5.64,"ew":39.96},"id":3772}, + {"name":"Hilltop","type":"Portal","wcid":1902,"cell":"90240000","place":"outdoor","ns":-72.6,"ew":13.79,"dest":{"cell":"AAA80034","place":"outdoor","ns":32.79,"ew":34.68},"id":3773}, + {"name":"Mannikin Foundry Portal","type":"Portal","wcid":19717,"cell":"90580140","place":"building","ns":-31.17,"ew":13.79,"dest":{"cell":"545A013C","place":"dungeon","name":"Mannikin Foundry"},"id":3774}, + {"name":"Al-Arqas Meeting Hall Portal","type":"Portal","wcid":6088,"cell":"90580152","place":"building","ns":-31.22,"ew":13.82,"dest":{"cell":"011D0126","place":"dungeon","name":"Al-Arqas Meeting Hall"},"id":3775}, + {"name":"Portal to Town Network","type":"Portal","wcid":43066,"cell":"90580034","place":"outdoor","ns":-31.17,"ew":13.9,"dest":{"cell":"00070133","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3776}, + {"name":"Destroyed Portal to Bluespire","type":"Portal","wcid":11953,"cell":"905C0000","place":"outdoor","ns":-28.27,"ew":13.63,"dest":{"cell":"21B00017","place":"outdoor","ns":39.54,"ew":-75.35},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3777}, + {"name":"Cavernous Refuge","type":"Portal","wcid":45722,"cell":"9076000B","place":"outdoor","ns":-7.3,"ew":13.4,"dest":{"cell":"576D0154","place":"dungeon","name":"Cavernous Refuge"},"minLevel":150,"quest":true,"id":3778}, + {"name":"Hilltop","type":"Portal","wcid":1902,"cell":"90D00114","place":"building","ns":64.78,"ew":13.5,"dest":{"cell":"AAA80034","place":"outdoor","ns":32.79,"ew":34.68},"id":3779}, + {"name":"Sho Roadside","type":"Portal","wcid":1907,"cell":"90D00116","place":"building","ns":64.92,"ew":13.6,"dest":{"cell":"D45C003D","place":"outdoor","ns":-27.92,"ew":68.38},"id":3780}, + {"name":"Crater Pathway","type":"Portal","wcid":2554,"cell":"90D00104","place":"building","ns":64.8,"ew":13.72,"dest":{"cell":"01A701AA","place":"dungeon","name":"Crater Pathway"},"id":3781}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"90D00014","place":"outdoor","ns":64.79,"ew":13.54,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3782}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"91000198","place":"dungeon","dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"desc":"In a dungeon (landblock 9100).","id":3783}, + {"name":"South Tumerok Vanguard Outpost","type":"Portal","wcid":9143,"cell":"91460000","place":"outdoor","ns":-45.89,"ew":14.23,"dest":{"cell":"02A40110","place":"dungeon","name":"South Tumerok Vanguard Outpost"},"minLevel":50,"id":3784}, + {"name":"Destroyed Portal to Samsur","type":"Portal","wcid":1026,"cell":"91560000","place":"outdoor","ns":-32.64,"ew":14.38,"dest":{"cell":"977B000C","place":"outdoor","ns":-3.24,"ew":18.96},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3785}, + {"name":"Sylsfear Dungeon Portal","type":"Portal","wcid":428,"cell":"918D0000","place":"outdoor","ns":11.0,"ew":14.68,"dest":{"cell":"01D70277","place":"dungeon","name":"Sylsfear Dungeon"},"minLevel":10,"id":3786}, + {"name":"South Bellig","type":"Portal","wcid":436,"cell":"91930000","place":"outdoor","ns":16.34,"ew":14.74,"dest":{"cell":"93950019","place":"outdoor","ns":17.26,"ew":15.98},"id":3787}, + {"name":"North Dalt","type":"Portal","wcid":437,"cell":"91930000","place":"outdoor","ns":15.65,"ew":14.17,"dest":{"cell":"8F91003E","place":"outdoor","ns":14.62,"ew":13.24},"id":3788}, + {"name":"Pavanne Vale Freehold Portal","type":"Portal","wcid":12537,"cell":"91D20000","place":"outdoor","ns":66.4,"ew":14.31,"dest":{"cell":"91EC0028","place":"outdoor","ns":87.56,"ew":14.5},"id":3789}, + {"name":"Celdiseth's Beach Settlement Portal","type":"Portal","wcid":12483,"cell":"91D20000","place":"outdoor","ns":66.37,"ew":14.33,"dest":{"cell":"A4EB000F","place":"outdoor","ns":86.73,"ew":29.4},"id":3790}, + {"name":"East Esper Valley Portal","type":"Portal","wcid":12489,"cell":"91D20000","place":"outdoor","ns":66.33,"ew":14.34,"dest":{"cell":"A2DA0019","place":"outdoor","ns":72.47,"ew":27.96},"id":3791}, + {"name":"Neydisa Village Portal","type":"Portal","wcid":12529,"cell":"91D20000","place":"outdoor","ns":66.3,"ew":14.34,"dest":{"cell":"9CD80009","place":"outdoor","ns":70.87,"ew":22.96},"id":3792}, + {"name":"Prosper River Headwaters Portal","type":"Portal","wcid":12539,"cell":"91D20000","place":"outdoor","ns":66.26,"ew":14.34,"dest":{"cell":"98C6002B","place":"outdoor","ns":56.7,"ew":20.16},"id":3793}, + {"name":"Bandit Road Villas Portal","type":"Portal","wcid":13091,"cell":"91D20000","place":"outdoor","ns":66.23,"ew":14.31,"dest":{"cell":"B6D80003","place":"outdoor","ns":71.14,"ew":43.68},"id":3794}, + {"name":"Stone Triad Dell Portal","type":"Portal","wcid":13135,"cell":"91D20000","place":"outdoor","ns":66.2,"ew":14.29,"dest":{"cell":"80E1002B","place":"outdoor","ns":78.26,"ew":1.01},"id":3795}, + {"name":"Frosty Dale Cottages Portal","type":"Portal","wcid":13106,"cell":"91D20000","place":"outdoor","ns":66.43,"ew":14.28,"dest":{"cell":"87E0001C","place":"outdoor","ns":77.59,"ew":6.44},"id":3796}, + {"name":"Greenvale Settlement Portal","type":"Portal","wcid":13107,"cell":"91D20000","place":"outdoor","ns":66.47,"ew":14.24,"dest":{"cell":"8DE30024","place":"outdoor","ns":79.98,"ew":11.26},"id":3797}, + {"name":"Celcynd Cottages Portal","type":"Portal","wcid":14616,"cell":"91D20000","place":"outdoor","ns":66.48,"ew":14.21,"dest":{"cell":"8BF20036","place":"outdoor","ns":92.2,"ew":9.92},"id":3798}, + {"name":"Bretslef Cottages Portal","type":"Portal","wcid":14615,"cell":"91D20000","place":"outdoor","ns":66.19,"ew":14.26,"dest":{"cell":"ADD40015","place":"outdoor","ns":68.12,"ew":36.67},"id":3799}, + {"name":"Ianna Portal","type":"Portal","wcid":14636,"cell":"91D20000","place":"outdoor","ns":66.47,"ew":14.18,"dest":{"cell":"86C00010","place":"outdoor","ns":52.42,"ew":5.42},"id":3800}, + {"name":"Merak Portal","type":"Portal","wcid":15174,"cell":"91D20000","place":"outdoor","ns":66.47,"ew":14.16,"dest":{"cell":"51A00025","place":"outdoor","ns":26.5,"ew":-36.68},"id":3801}, + {"name":"New Nesortania Portal","type":"Portal","wcid":15179,"cell":"91D20000","place":"outdoor","ns":66.18,"ew":14.22,"dest":{"cell":"8CC2001C","place":"outdoor","ns":53.61,"ew":10.37},"id":3802}, + {"name":"Anadil Portal","type":"Portal","wcid":15141,"cell":"91D20000","place":"outdoor","ns":66.46,"ew":14.14,"dest":{"cell":"7AD6001B","place":"outdoor","ns":69.51,"ew":-3.98},"id":3803}, + {"name":"Sweet Maple Cottages Portal","type":"Portal","wcid":15685,"cell":"91D20000","place":"outdoor","ns":66.46,"ew":14.1,"dest":{"cell":"53E40024","place":"outdoor","ns":80.8,"ew":-35.14},"id":3804}, + {"name":"Adept's Domain Portal","type":"Portal","wcid":15662,"cell":"91D20000","place":"outdoor","ns":66.46,"ew":14.07,"dest":{"cell":"51A3001C","place":"outdoor","ns":28.82,"ew":-36.84},"id":3805}, + {"name":"Patron's Honor Cottages Portal","type":"Portal","wcid":15679,"cell":"91D20000","place":"outdoor","ns":66.17,"ew":14.18,"dest":{"cell":"A1DD001D","place":"outdoor","ns":75.32,"ew":27.23},"id":3806}, + {"name":"Windrune Cottages Portal","type":"Portal","wcid":15687,"cell":"91D20000","place":"outdoor","ns":66.16,"ew":14.14,"dest":{"cell":"83CD001E","place":"outdoor","ns":62.62,"ew":3.23},"id":3807}, + {"name":"Mountain Retreat Cottages Portal","type":"Portal","wcid":15677,"cell":"91D20000","place":"outdoor","ns":66.16,"ew":14.1,"dest":{"cell":"7EC80025","place":"outdoor","ns":58.47,"ew":-0.7},"id":3808}, + {"name":"North Pass Hollow Cottages Portal","type":"Portal","wcid":19154,"cell":"91D20000","place":"outdoor","ns":66.43,"ew":14.31,"dest":{"cell":"85C4001C","place":"outdoor","ns":55.17,"ew":4.84},"id":3809}, + {"name":"Shaky Ledge Cottages Portal","type":"Portal","wcid":19159,"cell":"91D20000","place":"outdoor","ns":66.4,"ew":14.34,"dest":{"cell":"89CD0035","place":"outdoor","ns":62.5,"ew":8.28},"id":3810}, + {"name":"Stonerune Cottages Portal","type":"Portal","wcid":19160,"cell":"91D20000","place":"outdoor","ns":66.34,"ew":14.36,"dest":{"cell":"89C90012","place":"outdoor","ns":59.01,"ew":7.91},"id":3811}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"92000198","place":"dungeon","dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"desc":"In a dungeon (landblock 9200).","id":3812}, + {"name":"Jahannan Vault Portal","type":"Portal","wcid":6395,"cell":"92410000","place":"outdoor","ns":-49.77,"ew":14.96,"dest":{"cell":"011B014B","place":"dungeon","name":"Jahannan Vault"},"id":3813}, + {"name":"Base of Mt. Alphus","type":"Portal","wcid":433,"cell":"92980000","place":"outdoor","ns":20.24,"ew":15.03,"dest":{"cell":"94970030","place":"outdoor","ns":19.56,"ew":17.0},"id":3814}, + {"name":"Jahannan Vault Portal","type":"Portal","wcid":6395,"cell":"92D30000","place":"outdoor","ns":66.9,"ew":15.0,"dest":{"cell":"011B014B","place":"dungeon","name":"Jahannan Vault"},"id":3815}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"93000198","place":"dungeon","dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"desc":"In a dungeon (landblock 9300).","id":3816}, + {"name":"Uninhabited Area Portal","type":"Portal","wcid":8220,"cell":"934B0133","place":"underground","ns":-41.6,"ew":16.3,"dest":{"cell":"02D2011F","place":"dungeon"},"minLevel":1,"maxLevel":25,"id":3817}, + {"name":"Surface Portal","type":"Portal","wcid":8219,"cell":"934B0134","place":"underground","ns":-41.83,"ew":16.43,"dest":{"cell":"934B0021","place":"outdoor","ns":-41.92,"ew":16.1},"id":3818}, + {"name":"Xarabydun Lifestone Portal","type":"Portal","wcid":8221,"cell":"934B021B","place":"underground","ns":-41.95,"ew":15.89,"dest":{"cell":"02D30116","place":"dungeon"},"minLevel":1,"maxLevel":25,"id":3819}, + {"name":"Portal to Town Network","type":"Portal","wcid":43066,"cell":"934B0009","place":"outdoor","ns":-41.87,"ew":15.81,"dest":{"cell":"00070133","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3820}, + {"name":"Bookcase","type":"Portal","wcid":32811,"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.06,"dest":{"cell":"005B02D9","place":"dungeon"},"quest":true,"desc":"A simple bookcase.","id":3821}, + {"name":"Desert Ruin Portal","type":"Portal","wcid":4929,"cell":"93570102","place":"dungeon","dest":{"cell":"016701A7","place":"dungeon"},"desc":"In a dungeon (landblock 9357).","id":3822}, + {"name":"Mnemosyne Collection Site","type":"Portal","wcid":9322,"cell":"937C0000","place":"outdoor","ns":-2.54,"ew":16.39,"dest":{"cell":"029D0100","place":"dungeon","name":"Mnemosyne Collection Site"},"id":3823}, + {"name":"Bellig Tower Base","type":"Portal","wcid":373,"cell":"93950000","place":"outdoor","ns":17.82,"ew":15.99,"dest":{"cell":"01D40115","place":"dungeon","name":"Bellig Tower Base"},"id":3824}, + {"name":"Bellig Tower","type":"Portal","wcid":375,"cell":"93950000","place":"outdoor","ns":17.52,"ew":16.08,"dest":{"cell":"01D401B1","place":"dungeon","name":"Bellig Tower Base"},"id":3825}, + {"name":"North Gemm","type":"Portal","wcid":435,"cell":"93950000","place":"outdoor","ns":17.26,"ew":15.97,"dest":{"cell":"91930037","place":"outdoor","ns":16.33,"ew":14.73},"id":3826}, + {"name":"Crater Pathway","type":"Portal","wcid":2552,"cell":"93CB0102","place":"dungeon","dest":{"cell":"01A70108","place":"dungeon","name":"Crater Pathway"},"desc":"In a dungeon (landblock 93CB).","id":3827}, + {"name":"Empyrean Workshop","type":"Portal","wcid":32655,"cell":"93D30011","place":"outdoor","ns":66.88,"ew":15.89,"dest":{"cell":"006E055E","place":"dungeon","name":"Empyrean Workshop"},"minLevel":125,"quest":true,"desc":"An old Empyrean Workshop","id":3828}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"94000198","place":"dungeon","dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"desc":"In a dungeon (landblock 9400).","id":3829}, + {"name":"Forking Trail","type":"Portal","wcid":2339,"cell":"942D0000","place":"outdoor","ns":-65.59,"ew":16.66,"dest":{"cell":"01AB0137","place":"dungeon","name":"Forking Trail"},"id":3830}, + {"name":"Mt. Alphus Valley","type":"Portal","wcid":434,"cell":"94970000","place":"outdoor","ns":19.54,"ew":16.89,"dest":{"cell":"9398000F","place":"outdoor","ns":20.25,"ew":15.78},"id":3831}, + {"name":"Mattekar Cave","type":"Portal","wcid":4910,"cell":"94D10100","place":"dungeon","dest":{"cell":"01690183","place":"dungeon"},"desc":"In a dungeon (landblock 94D1).","id":3832}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"95000198","place":"dungeon","dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"desc":"In a dungeon (landblock 9500).","id":3833}, + {"name":"Brigands Bay Settlement Portal","type":"Portal","wcid":12479,"cell":"95210000","place":"outdoor","ns":-74.84,"ew":17.79,"dest":{"cell":"A60F000D","place":"outdoor","ns":-89.46,"ew":30.97},"id":3834}, + {"name":"Villalabar Portal","type":"Portal","wcid":14289,"cell":"95210000","place":"outdoor","ns":-74.86,"ew":17.83,"dest":{"cell":"96330027","place":"outdoor","ns":-60.53,"ew":18.48},"id":3835}, + {"name":"Qalabar Oasis Settlement Portal","type":"Portal","wcid":13119,"cell":"95210000","place":"outdoor","ns":-74.83,"ew":17.76,"dest":{"cell":"9A2C002C","place":"outdoor","ns":-66.37,"ew":21.81},"id":3836}, + {"name":"Simda'r Villas Portal","type":"Portal","wcid":13128,"cell":"95210000","place":"outdoor","ns":-74.8,"ew":17.74,"dest":{"cell":"94190031","place":"outdoor","ns":-81.88,"ew":17.12},"id":3837}, + {"name":"Ro-Nan Portal","type":"Portal","wcid":14279,"cell":"95210000","place":"outdoor","ns":-74.83,"ew":17.86,"dest":{"cell":"AB30002D","place":"outdoor","ns":-63.1,"ew":35.37},"id":3838}, + {"name":"Qalaba'r Seaside Villas Portal","type":"Portal","wcid":13120,"cell":"95210000","place":"outdoor","ns":-74.8,"ew":17.86,"dest":{"cell":"912A0030","place":"outdoor","ns":-67.64,"ew":14.63},"id":3839}, + {"name":"Stormbrow Portal","type":"Portal","wcid":14672,"cell":"95210000","place":"outdoor","ns":-74.76,"ew":17.73,"dest":{"cell":"9414002B","place":"outdoor","ns":-85.66,"ew":16.96},"id":3840}, + {"name":"Land Bridge Villas Portal","type":"Portal","wcid":14642,"cell":"95210000","place":"outdoor","ns":-74.88,"ew":17.88,"dest":{"cell":"83120034","place":"outdoor","ns":-87.17,"ew":3.54},"id":3841}, + {"name":"Southern Park Portal","type":"Portal","wcid":14667,"cell":"95210000","place":"outdoor","ns":-74.9,"ew":17.84,"dest":{"cell":"AD20002E","place":"outdoor","ns":-75.77,"ew":36.98},"id":3842}, + {"name":"Linvak Tukal Foothills Settlement Portal","type":"Portal","wcid":14644,"cell":"95210000","place":"outdoor","ns":-74.9,"ew":17.8,"dest":{"cell":"A618002C","place":"outdoor","ns":-82.43,"ew":31.4},"id":3843}, + {"name":"Northreach Portal","type":"Portal","wcid":14653,"cell":"95210000","place":"outdoor","ns":-74.76,"ew":17.86,"dest":{"cell":"ABE7002C","place":"outdoor","ns":83.22,"ew":35.39},"id":3844}, + {"name":"Azaroth Cottages Portal","type":"Portal","wcid":15145,"cell":"95210000","place":"outdoor","ns":-74.84,"ew":17.9,"dest":{"cell":"58E80025","place":"outdoor","ns":84.09,"ew":-31.14},"id":3845}, + {"name":"Scimitar Lake Cottages Portal","type":"Portal","wcid":15188,"cell":"95210000","place":"outdoor","ns":-74.8,"ew":17.92,"dest":{"cell":"AE130024","place":"outdoor","ns":-86.39,"ew":37.66},"id":3846}, + {"name":"Sand Shallow Cottages Portal","type":"Portal","wcid":15187,"cell":"95210000","place":"outdoor","ns":-74.77,"ew":17.93,"dest":{"cell":"806F0026","place":"outdoor","ns":-12.65,"ew":0.87},"id":3847}, + {"name":"Mattekar Slopes Cottages Portal","type":"Portal","wcid":15172,"cell":"95210000","place":"outdoor","ns":-74.88,"ew":17.73,"dest":{"cell":"A529002C","place":"outdoor","ns":-68.78,"ew":30.62},"id":3848}, + {"name":"Axefall Glen Portal","type":"Portal","wcid":15666,"cell":"95210000","place":"outdoor","ns":-74.88,"ew":17.63,"dest":{"cell":"4CA50025","place":"outdoor","ns":30.52,"ew":-40.69},"id":3849}, + {"name":"Gredaline Villas Portal","type":"Portal","wcid":19146,"cell":"95210000","place":"outdoor","ns":-74.86,"ew":17.7,"dest":{"cell":"A7340023","place":"outdoor","ns":-60.1,"ew":32.09},"id":3850}, + {"name":"Ebbing Tide Villas Portal","type":"Portal","wcid":19143,"cell":"95210000","place":"outdoor","ns":-74.83,"ew":17.67,"dest":{"cell":"91320023","place":"outdoor","ns":-61.69,"ew":14.53},"id":3851}, + {"name":"Sanam Batal Villas Portal","type":"Portal","wcid":19157,"cell":"95210000","place":"outdoor","ns":-74.78,"ew":17.64,"dest":{"cell":"70A60024","place":"outdoor","ns":31.17,"ew":-11.94},"id":3852}, + {"name":"Crystal Mine","type":"Portal","wcid":25494,"cell":"95410000","place":"outdoor","ns":-49.27,"ew":17.93,"dest":{"cell":"614902DE","place":"dungeon","name":"Crystal Mine"},"quest":true,"id":3853}, + {"name":"The Asteliary","type":"Portal","wcid":12148,"cell":"95720000","place":"outdoor","ns":-10.21,"ew":17.5,"dest":{"cell":"03A40131","place":"dungeon","name":"The Asteliary"},"minLevel":35,"id":3854}, + {"name":"A Small Cave","type":"Portal","wcid":1325,"cell":"957A0000","place":"outdoor","ns":-4.2,"ew":17.32,"dest":{"cell":"01E70121","place":"dungeon","name":"A Small Cave"},"id":3855}, + {"name":"Base of Mt. Alphus","type":"Portal","wcid":433,"cell":"95970000","place":"outdoor","ns":19.49,"ew":17.47,"dest":{"cell":"94970030","place":"outdoor","ns":19.56,"ew":17.0},"id":3856}, + {"name":"South Zabool","type":"Portal","wcid":432,"cell":"95980000","place":"outdoor","ns":19.73,"ew":17.84,"dest":{"cell":"96990024","place":"outdoor","ns":20.77,"ew":18.47},"id":3857}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"95D6001C","place":"outdoor","ns":69.56,"ew":17.56,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3858}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"96000198","place":"dungeon","dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"desc":"In a dungeon (landblock 9600).","id":3859}, + {"name":"Lugian Outpost","type":"Portal","wcid":1590,"cell":"961A0000","place":"outdoor","ns":-80.6,"ew":18.12,"dest":{"cell":"01C70121","place":"dungeon","name":"Lugian Outpost"},"id":3860}, + {"name":"Hebian-to Portal","type":"Portal","wcid":1019,"cell":"96230000","place":"outdoor","ns":-73.19,"ew":18.13,"dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"id":3861}, + {"name":"Virindi Edifice","type":"Portal","wcid":49608,"cell":"9667000B","place":"outdoor","ns":-19.34,"ew":18.18,"dest":{"cell":"5867026B","place":"dungeon","name":"Virindi Edifice"},"minLevel":180,"id":3862}, + {"name":"Destroyed Portal to Yaraq","type":"Portal","wcid":1030,"cell":"967A0000","place":"outdoor","ns":-3.79,"ew":18.64,"dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3863}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"967D0000","place":"outdoor","ns":-1.57,"ew":18.4,"dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3864}, + {"name":"Musansayn's Vaults Portal","type":"Portal","wcid":5202,"cell":"967E0100","place":"building","ns":-0.99,"ew":18.67,"dest":{"cell":"01550198","place":"dungeon","name":"Musansayn's Vaults"},"minLevel":40,"id":3865}, + {"name":"Mount Alphus","type":"Portal","wcid":431,"cell":"96990000","place":"outdoor","ns":20.75,"ew":18.46,"dest":{"cell":"95980029","place":"outdoor","ns":19.72,"ew":17.83},"id":3866}, + {"name":"Top of Zabool Tower","type":"Portal","wcid":370,"cell":"96990000","place":"outdoor","ns":21.14,"ew":18.47,"dest":{"cell":"01D301BA","place":"dungeon","name":"Top of Zabool Tower"},"id":3867}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43571,"cell":"96D6010A","place":"underground","ns":69.84,"ew":18.8,"dest":{"cell":"E6CF0025","place":"outdoor","ns":64.12,"ew":82.52},"id":3868}, + {"name":"Mage Academy Portal","type":"Portal","wcid":5667,"cell":"96DC0000","place":"outdoor","ns":74.72,"ew":18.49,"dest":{"cell":"01390396","place":"dungeon","name":"Mage Academy"},"minLevel":150,"id":3869}, + {"name":"Rogue Delvings","type":"Portal","wcid":38646,"cell":"96DC0020","place":"outdoor","ns":74.78,"ew":18.36,"dest":{"cell":"00E001A0","place":"dungeon","name":"Rogue Delvings"},"minLevel":180,"quest":true,"id":3870}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"97000198","place":"dungeon","dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"desc":"In a dungeon (landblock 9700).","id":3871}, + {"name":"Portal to Silyun","type":"Portal","wcid":30555,"cell":"97210036","place":"outdoor","ns":-75.02,"ew":19.48,"dest":{"cell":"26EC003D","place":"outdoor","ns":87.31,"ew":-70.82},"id":3872}, + {"name":"Mammet Foundry Portal","type":"Portal","wcid":19716,"cell":"9722015E","place":"building","ns":-74.24,"ew":19.18,"dest":{"cell":"5458025F","place":"dungeon","name":"Mammet Foundry"},"id":3873}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"97220000","place":"outdoor","ns":-74.08,"ew":19.16,"dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"id":3874}, + {"name":"Qalaba'r Meeting Hall Portal","type":"Portal","wcid":6102,"cell":"97220162","place":"building","ns":-74.2,"ew":19.0,"dest":{"cell":"012B0126","place":"dungeon","name":"Qalaba'r Meeting Hall"},"id":3875}, + {"name":"Portal to Town Network","type":"Portal","wcid":43066,"cell":"9722001D","place":"outdoor","ns":-74.34,"ew":19.16,"dest":{"cell":"00070133","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3876}, + {"name":"Lugian Post","type":"Portal","wcid":1592,"cell":"97260000","place":"outdoor","ns":-71.24,"ew":19.01,"dest":{"cell":"01C80111","place":"dungeon","name":"Lugian Post"},"id":3877}, + {"name":"Mosswart Maze Portal","type":"Portal","wcid":8367,"cell":"975F0000","place":"outdoor","ns":-25.23,"ew":19.38,"dest":{"cell":"02CA0247","place":"dungeon","name":"Mosswart Maze"},"id":3878}, + {"name":"Mannikin Foundry Portal","type":"Portal","wcid":19717,"cell":"977B015E","place":"building","ns":-2.88,"ew":19.38,"dest":{"cell":"545A013C","place":"dungeon","name":"Mannikin Foundry"},"id":3879}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"977B0000","place":"outdoor","ns":-3.21,"ew":19.08,"dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"id":3880}, + {"name":"Portal to Town Network","type":"Portal","wcid":43066,"cell":"977B002F","place":"outdoor","ns":-2.93,"ew":19.44,"dest":{"cell":"00070133","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3881}, + {"name":"Adventurer's Haven Cottages Portal","type":"Portal","wcid":12467,"cell":"977E0000","place":"outdoor","ns":-0.87,"ew":19.03,"dest":{"cell":"AC810024","place":"outdoor","ns":1.63,"ew":36.07},"id":3882}, + {"name":"Samsur Butte Cottages Portal","type":"Portal","wcid":12540,"cell":"977E0000","place":"outdoor","ns":-0.9,"ew":19.04,"dest":{"cell":"92770033","place":"outdoor","ns":-6.48,"ew":15.5},"id":3883}, + {"name":"Yushad Ridge Cottages Portal","type":"Portal","wcid":12570,"cell":"977E0000","place":"outdoor","ns":-0.87,"ew":18.99,"dest":{"cell":"9C70003C","place":"outdoor","ns":-12.03,"ew":23.56},"id":3884}, + {"name":"Janaa Ridge Settlement Portal","type":"Portal","wcid":12507,"cell":"977E0000","place":"outdoor","ns":-0.9,"ew":18.96,"dest":{"cell":"9B760016","place":"outdoor","ns":-7.03,"ew":22.26},"id":3885}, + {"name":"Naqut Dreams Villas Portal","type":"Portal","wcid":13113,"cell":"977E0000","place":"outdoor","ns":-0.93,"ew":19.02,"dest":{"cell":"8D73002E","place":"outdoor","ns":-9.38,"ew":11.38},"id":3886}, + {"name":"Yinar Portal","type":"Portal","wcid":14293,"cell":"977E0000","place":"outdoor","ns":-0.93,"ew":18.94,"dest":{"cell":"A9730005","place":"outdoor","ns":-9.48,"ew":33.32},"id":3887}, + {"name":"Stone Scar Settlement Portal","type":"Portal","wcid":14285,"cell":"977E0000","place":"outdoor","ns":-0.97,"ew":19.02,"dest":{"cell":"9385002E","place":"outdoor","ns":4.98,"ew":16.23},"id":3888}, + {"name":"Greenswath Portal","type":"Portal","wcid":14262,"cell":"977E0000","place":"outdoor","ns":-0.96,"ew":18.92,"dest":{"cell":"9E88000E","place":"outdoor","ns":7.39,"ew":24.57},"id":3889}, + {"name":"Nal Wadi Cottages Portal","type":"Portal","wcid":14275,"cell":"977E0000","place":"outdoor","ns":-1.0,"ew":19.0,"dest":{"cell":"99850012","place":"outdoor","ns":4.6,"ew":20.72},"id":3890}, + {"name":"Sand's Edge Portal","type":"Portal","wcid":13124,"cell":"977E0000","place":"outdoor","ns":-1.03,"ew":18.97,"dest":{"cell":"A586003D","place":"outdoor","ns":5.74,"ew":30.78},"id":3891}, + {"name":"Cactus Acres Portal","type":"Portal","wcid":14255,"cell":"977E0000","place":"outdoor","ns":-0.98,"ew":18.89,"dest":{"cell":"9E74001A","place":"outdoor","ns":-8.99,"ew":24.77},"id":3892}, + {"name":"Tharesun Portal","type":"Portal","wcid":15195,"cell":"977E0000","place":"outdoor","ns":-1.06,"ew":18.93,"dest":{"cell":"86F1000D","place":"outdoor","ns":91.35,"ew":5.42},"id":3893}, + {"name":"Dovetail Valley Villas Portal","type":"Portal","wcid":15153,"cell":"977E0000","place":"outdoor","ns":-1.09,"ew":18.9,"dest":{"cell":"8C9D0026","place":"outdoor","ns":24.2,"ew":10.48},"id":3894}, + {"name":"Return of Mumiyah Cottages Portal","type":"Portal","wcid":15186,"cell":"977E0000","place":"outdoor","ns":-1.11,"ew":18.87,"dest":{"cell":"8477002C","place":"outdoor","ns":-6.44,"ew":4.2},"id":3895}, + {"name":"Maythen Geroyu Villas Portal","type":"Portal","wcid":15173,"cell":"977E0000","place":"outdoor","ns":-1.0,"ew":18.87,"dest":{"cell":"A0920015","place":"outdoor","ns":15.26,"ew":26.28},"id":3896}, + {"name":"Palm-of-Stone Villas Portal","type":"Portal","wcid":15182,"cell":"977E0000","place":"outdoor","ns":-0.83,"ew":19.01,"dest":{"cell":"A08D001A","place":"outdoor","ns":11.01,"ew":26.38},"id":3897}, + {"name":"Charnhold Portal","type":"Portal","wcid":19139,"cell":"977E0000","place":"outdoor","ns":-0.84,"ew":19.07,"dest":{"cell":"84B0001D","place":"outdoor","ns":39.32,"ew":4.05},"id":3898}, + {"name":"Darasa Villas Portal","type":"Portal","wcid":19141,"cell":"977E0000","place":"outdoor","ns":-0.87,"ew":19.09,"dest":{"cell":"74AB0025","place":"outdoor","ns":35.3,"ew":-8.73},"id":3899}, + {"name":"Stone Face Oasis Villas Portal","type":"Portal","wcid":14670,"cell":"977E0000","place":"outdoor","ns":-0.92,"ew":19.09,"dest":{"cell":"9A810024","place":"outdoor","ns":1.6,"ew":21.74},"id":3900}, + {"name":"Zabool Tower Base","type":"Portal","wcid":368,"cell":"979A002D","place":"outdoor","ns":21.71,"ew":19.44,"dest":{"cell":"01D3010F","place":"dungeon","name":"Top of Zabool Tower"},"id":3901}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"98000198","place":"dungeon","dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"desc":"In a dungeon (landblock 9800).","id":3902}, + {"name":"Mountain Fortress Portal","type":"Portal","wcid":6114,"cell":"98180000","place":"outdoor","ns":-82.39,"ew":19.87,"dest":{"cell":"011C030A","place":"dungeon","name":"Mountain Fortress"},"minLevel":100,"id":3903}, + {"name":"Zaikhal Portal","type":"Portal","wcid":1033,"cell":"981E0000","place":"outdoor","ns":-77.25,"ew":19.78,"dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"id":3904}, + {"name":"Dungeon Binar Portal","type":"Portal","wcid":4162,"cell":"98770000","place":"outdoor","ns":-6.23,"ew":20.12,"dest":{"cell":"018301AF","place":"dungeon","name":"Dungeon Binar"},"id":3905}, + {"name":"Samsur Meeting Hall Portal","type":"Portal","wcid":6104,"cell":"987B0101","place":"building","ns":-2.81,"ew":19.71,"dest":{"cell":"012D0126","place":"dungeon","name":"Samsur Meeting Hall"},"id":3906}, + {"name":"Dungeon Manor Portal","type":"Portal","wcid":1123,"cell":"987D0000","place":"outdoor","ns":-1.93,"ew":19.77,"dest":{"cell":"01E801BA","place":"dungeon","name":"Dungeon Manor"},"id":3907}, + {"name":"Amperehelion Vault Portal","type":"Portal","wcid":6389,"cell":"98AB0000","place":"outdoor","ns":34.99,"ew":19.98,"dest":{"cell":"01190371","place":"dungeon","name":"Amperehelion Vault"},"id":3908}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"99000198","place":"dungeon","dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"desc":"In a dungeon (landblock 9900).","id":3909}, + {"name":"Dry Well Portal","type":"Portal","wcid":4947,"cell":"99790102","place":"dungeon","dest":{"cell":"015A01AE","place":"dungeon"},"minLevel":1,"maxLevel":20,"desc":"In a dungeon (landblock 9979).","id":3910}, + {"name":"A Ruin","type":"Portal","wcid":2088,"cell":"997B0000","place":"outdoor","ns":-3.26,"ew":20.5,"dest":{"cell":"01B9011F","place":"dungeon","name":"A Ruin"},"id":3911}, + {"name":"Underground Forest Portal","type":"Portal","wcid":5604,"cell":"99A60000","place":"outdoor","ns":31.49,"ew":20.74,"dest":{"cell":"013C0201","place":"dungeon","name":"Underground Forest"},"id":3912}, + {"name":"Entrance to Portal Space","type":"Portal","wcid":14579,"cell":"99E60000","place":"outdoor","ns":82.77,"ew":21.17,"dest":{"cell":"526C040D","place":"dungeon","name":"Entrance to Portal Space"},"minLevel":70,"id":3913}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43573,"cell":"9A210102","place":"dungeon","dest":{"cell":"E7D1003A","place":"outdoor","ns":65.36,"ew":83.6},"desc":"In a dungeon (landblock 9A21).","id":3914}, + {"name":"Nevius Passage Portal","type":"Portal","wcid":5507,"cell":"9A460000","place":"outdoor","ns":-45.59,"ew":21.64,"dest":{"cell":"014C0158","place":"dungeon","name":"Nevius Passage"},"minLevel":8,"id":3915}, + {"name":"Destroyed Portal to Redspire","type":"Portal","wcid":11960,"cell":"9B7B0000","place":"outdoor","ns":-3.48,"ew":22.41,"dest":{"cell":"17B2002A","place":"outdoor","ns":40.56,"ew":-83.0},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3916}, + {"name":"Ridge Citadel Portal","type":"Portal","wcid":7319,"cell":"9D270000","place":"outdoor","ns":-70.19,"ew":24.23,"dest":{"cell":"02F10152","place":"dungeon","name":"Ridge Citadel"},"id":3917}, + {"name":"Khayyaban Meeting Hall Portal","type":"Portal","wcid":6097,"cell":"9D430101","place":"building","ns":-48.22,"ew":24.38,"dest":{"cell":"01260126","place":"dungeon","name":"Khayyaban Meeting Hall"},"id":3918}, + {"name":"Krau Li's Labyrinth Portal","type":"Portal","wcid":7616,"cell":"9D530000","place":"outdoor","ns":-35.15,"ew":23.77,"dest":{"cell":"02E5024A","place":"dungeon","name":"Krau Li's Labyrinth"},"minLevel":25,"id":3919}, + {"name":"Southern Infiltrator Keep","type":"Portal","wcid":12152,"cell":"9E3E0000","place":"outdoor","ns":-52.28,"ew":24.91,"dest":{"cell":"03A2025E","place":"dungeon","name":"Southern Infiltrator Keep"},"minLevel":25,"id":3920}, + {"name":"Destroyed Lin Portal","type":"Portal","wcid":4567,"cell":"9E430000","place":"outdoor","ns":-47.71,"ew":25.02,"dest":{"cell":"DC3C0011","place":"outdoor","ns":-53.91,"ew":74.3},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3921}, + {"name":"Destroyed Al-Jalima Portal","type":"Portal","wcid":5486,"cell":"9E430000","place":"outdoor","ns":-48.13,"ew":24.56,"dest":{"cell":"8588002C","place":"outdoor","ns":7.25,"ew":4.95},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3922}, + {"name":"Effigy Foundry Portal","type":"Portal","wcid":19718,"cell":"9E430131","place":"building","ns":-47.56,"ew":24.71,"dest":{"cell":"545901B0","place":"dungeon","name":"Effigy Foundry"},"id":3923}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"9E430000","place":"outdoor","ns":-48.03,"ew":24.52,"dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"id":3924}, + {"name":"Portal to Town Network","type":"Portal","wcid":43066,"cell":"9E430018","place":"outdoor","ns":-47.55,"ew":24.71,"dest":{"cell":"00070133","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3925}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"9E440000","place":"outdoor","ns":-47.4,"ew":25.11,"dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"id":3926}, + {"name":"Matron Hive North","type":"Portal","wcid":24436,"cell":"9E440000","place":"outdoor","ns":-47.49,"ew":24.88,"dest":{"cell":"6347036E","place":"dungeon","name":"Matron Hive North"},"minLevel":60,"id":3927}, + {"name":"Winthura's Garden Portal","type":"Portal","wcid":5509,"cell":"9E490000","place":"outdoor","ns":-43.09,"ew":24.68,"dest":{"cell":"014B0213","place":"dungeon","name":"Winthura's Garden"},"minLevel":8,"id":3928}, + {"name":"Thasali","type":"Portal","wcid":2362,"cell":"9E5A0100","place":"dungeon","dest":{"cell":"01C40119","place":"dungeon"},"minLevel":5,"desc":"In a dungeon (landblock 9E5A).","id":3929}, + {"name":"Virindi Complex","type":"Portal","wcid":24049,"cell":"9EDB0000","place":"outdoor","ns":73.78,"ew":25.02,"dest":{"cell":"5B450314","place":"dungeon","name":"Virindi Complex"},"quest":true,"id":3930}, + {"name":"Celestial Hand Northwatch Castle Black Market Portal","type":"Portal","wcid":80403,"cell":"9EE50284","place":"underground","ns":81.38,"ew":24.98,"dest":{"cell":"9EE50266","place":"underground","ns":81.34,"ew":24.96},"minLevel":180,"quest":true,"desc":"You must be a member of the Society of the Celestial Hand to enter this Portal.","id":3931}, + {"name":"Eldrytch Web Northwatch Castle Black Market Portal","type":"Portal","wcid":80404,"cell":"9EE50284","place":"underground","ns":81.38,"ew":24.98,"dest":{"cell":"9EE50266","place":"underground","ns":81.34,"ew":24.96},"minLevel":180,"quest":true,"desc":"You must be a member of the Society of the Eldrytch Web to enter this Portal.","id":3932}, + {"name":"Radiant Blood Northwatch Castle Black Market Portal","type":"Portal","wcid":80405,"cell":"9EE50284","place":"underground","ns":81.38,"ew":24.98,"dest":{"cell":"9EE50266","place":"underground","ns":81.34,"ew":24.96},"minLevel":180,"quest":true,"desc":"You must be a member of the Society of the Radiant Blood to enter this Portal.","id":3933}, + {"name":"Northwatch Castle Portal","type":"Portal","wcid":80399,"cell":"9EE5016D","place":"underground","ns":81.17,"ew":25.25,"dest":{"cell":"9EE50293","place":"underground","ns":81.38,"ew":24.88},"minLevel":180,"id":3934}, + {"name":"Temple Entrance","type":"Portal","wcid":34057,"cell":"9EE80017","place":"outdoor","ns":84.31,"ew":24.67,"dest":{"cell":"00EF0236","place":"dungeon","name":"Temple"},"minLevel":120,"quest":true,"id":3935}, + {"name":"Mount Ingot","type":"Portal","wcid":25795,"cell":"9F2A0000","place":"outdoor","ns":-67.75,"ew":25.55,"dest":{"cell":"64480185","place":"dungeon","name":"Mount Ingot"},"id":3936}, + {"name":"Crystal Core","type":"Portal","wcid":48719,"cell":"9F2C002A","place":"outdoor","ns":-66.62,"ew":25.83,"dest":{"cell":"58610166","place":"dungeon","name":"Crystal Core"},"minLevel":50,"id":3937}, + {"name":"Dunes End Cottages Portal","type":"Portal","wcid":12488,"cell":"9F410000","place":"outdoor","ns":-49.46,"ew":26.01,"dest":{"cell":"98440011","place":"outdoor","ns":-47.53,"ew":19.93},"id":3938}, + {"name":"Taklihuan Settlement Portal","type":"Portal","wcid":12559,"cell":"9F410000","place":"outdoor","ns":-49.43,"ew":26.03,"dest":{"cell":"B04F0021","place":"outdoor","ns":-38.67,"ew":39.33},"id":3939}, + {"name":"Spire Hills Settlement Portal","type":"Portal","wcid":12556,"cell":"9F410000","place":"outdoor","ns":-49.46,"ew":25.97,"dest":{"cell":"B13B0029","place":"outdoor","ns":-54.67,"ew":40.16},"id":3940}, + {"name":"South Khayyaban Cottages Portal","type":"Portal","wcid":12551,"cell":"9F410000","place":"outdoor","ns":-49.43,"ew":25.93,"dest":{"cell":"A23D0006","place":"outdoor","ns":-52.64,"ew":27.68},"id":3941}, + {"name":"Serpent Hills Settlement Portal","type":"Portal","wcid":12544,"cell":"9F410000","place":"outdoor","ns":-49.39,"ew":26.04,"dest":{"cell":"8E400003","place":"outdoor","ns":-50.5,"ew":11.68},"id":3942}, + {"name":"Bhah Dhah Villas Portal","type":"Portal","wcid":13093,"cell":"9F410000","place":"outdoor","ns":-49.4,"ew":25.93,"dest":{"cell":"A04B0040","place":"outdoor","ns":-41.19,"ew":26.83},"id":3943}, + {"name":"Kanasa Portal","type":"Portal","wcid":14270,"cell":"9F410000","place":"outdoor","ns":-49.36,"ew":26.04,"dest":{"cell":"AC3F002D","place":"outdoor","ns":-51.13,"ew":36.21},"id":3944}, + {"name":"Plainsview Cottages Portal","type":"Portal","wcid":14278,"cell":"9F410000","place":"outdoor","ns":-49.37,"ew":25.93,"dest":{"cell":"A738002B","place":"outdoor","ns":-56.88,"ew":32.21},"id":3945}, + {"name":"Brigand Sands Cottages Portal","type":"Portal","wcid":13094,"cell":"9F410000","place":"outdoor","ns":-49.33,"ew":26.03,"dest":{"cell":"9E330023","place":"outdoor","ns":-60.94,"ew":24.85},"id":3946}, + {"name":"Sands-of-the-Skull Cottages Portal","type":"Portal","wcid":14664,"cell":"9F410000","place":"outdoor","ns":-49.33,"ew":25.93,"dest":{"cell":"9C4D001D","place":"outdoor","ns":-39.91,"ew":23.22},"id":3947}, + {"name":"Desert Vanguard Cottages Portal","type":"Portal","wcid":14619,"cell":"9F410000","place":"outdoor","ns":-49.3,"ew":25.94,"dest":{"cell":"8E48000D","place":"outdoor","ns":-43.9,"ew":11.78},"id":3948}, + {"name":"Erevana Villas Portal","type":"Portal","wcid":14629,"cell":"9F410000","place":"outdoor","ns":-49.3,"ew":26.02,"dest":{"cell":"AB380023","place":"outdoor","ns":-56.85,"ew":35.32},"id":3949}, + {"name":"Rethux Vale Portal","type":"Portal","wcid":15185,"cell":"9F410000","place":"outdoor","ns":-49.27,"ew":26.02,"dest":{"cell":"68A50024","place":"outdoor","ns":30.39,"ew":-18.25},"id":3950}, + {"name":"Al-Mar Oasis Portal","type":"Portal","wcid":15139,"cell":"9F410000","place":"outdoor","ns":-49.23,"ew":26.03,"dest":{"cell":"94440025","place":"outdoor","ns":-47.09,"ew":16.92},"id":3951}, + {"name":"Avatania Cottages Portal","type":"Portal","wcid":15144,"cell":"9F410000","place":"outdoor","ns":-49.27,"ew":25.94,"dest":{"cell":"9938000B","place":"outdoor","ns":-56.88,"ew":20.62},"id":3952}, + {"name":"Sonpay Portal","type":"Portal","wcid":15192,"cell":"9F410000","place":"outdoor","ns":-49.23,"ew":25.93,"dest":{"cell":"AB48001D","place":"outdoor","ns":-43.91,"ew":35.16},"id":3953}, + {"name":"Ardent Realm Portal","type":"Portal","wcid":15663,"cell":"9F410000","place":"outdoor","ns":-49.47,"ew":25.93,"dest":{"cell":"A84D002D","place":"outdoor","ns":-39.89,"ew":32.99},"id":3954}, + {"name":"Shield of Ispar Villas Portal","type":"Portal","wcid":15682,"cell":"9F410000","place":"outdoor","ns":-49.43,"ew":25.89,"dest":{"cell":"AC4D0024","place":"outdoor","ns":-39.98,"ew":36.08},"id":3955}, + {"name":"Rending Talon Cottages Portal","type":"Portal","wcid":19155,"cell":"9F410000","place":"outdoor","ns":-49.49,"ew":25.97,"dest":{"cell":"5AB0001D","place":"outdoor","ns":39.3,"ew":-29.57},"id":3956}, + {"name":"Stone Scythe Stronghold Portal","type":"Portal","wcid":19161,"cell":"9F410000","place":"outdoor","ns":-49.49,"ew":26.02,"dest":{"cell":"56AC0021","place":"outdoor","ns":35.72,"ew":-32.73},"id":3957}, + {"name":"North Direlands Portal","type":"Portal","wcid":1104,"cell":"9F990000","place":"outdoor","ns":20.92,"ew":25.92,"dest":{"cell":"3C9D0010","place":"outdoor","ns":24.45,"ew":-53.85},"minLevel":12,"id":3958}, + {"name":"North Glenden Prison","type":"Portal","wcid":1311,"cell":"9FA70000","place":"outdoor","ns":31.83,"ew":25.52,"dest":{"cell":"01E401FE","place":"dungeon","name":"North Glenden Prison"},"minLevel":80,"id":3959}, + {"name":"Desert Mine","type":"Portal","wcid":4164,"cell":"A0790102","place":"building","ns":-4.53,"ew":26.6,"dest":{"cell":"0182017B","place":"dungeon","name":"Desert Mine"},"id":3960}, + {"name":"Glenden Wood Dungeon","type":"Portal","wcid":1307,"cell":"A0A40000","place":"outdoor","ns":29.94,"ew":26.37,"dest":{"cell":"01E3033D","place":"dungeon","name":"Glenden Wood Dungeon"},"id":3961}, + {"name":"Old Mine","type":"Portal","wcid":3632,"cell":"A11C0000","place":"outdoor","ns":-79.18,"ew":26.99,"dest":{"cell":"019001F3","place":"dungeon","name":"Old Mine"},"id":3962}, + {"name":"Enkindled Souls","type":"Portal","wcid":5505,"cell":"A1410000","place":"outdoor","ns":-49.41,"ew":26.92,"dest":{"cell":"014101A6","place":"dungeon","name":"Enkindled Souls"},"id":3963}, + {"name":"Grievous Vault","type":"Portal","wcid":4204,"cell":"A15F0000","place":"outdoor","ns":-25.79,"ew":27.26,"dest":{"cell":"01890321","place":"dungeon","name":"Grievous Vault"},"minLevel":10,"id":3964}, + {"name":"Surface","type":"Portal","wcid":44351,"cell":"A1A30102","place":"underground","ns":28.99,"ew":27.47,"dest":{"cell":"A1A30020","place":"outdoor","ns":29.24,"ew":27.22},"id":3965}, + {"name":"Effigy Foundry Portal","type":"Portal","wcid":19718,"cell":"A1A40161","place":"building","ns":29.92,"ew":27.43,"dest":{"cell":"545901B0","place":"dungeon","name":"Effigy Foundry"},"id":3966}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"A1A40000","place":"outdoor","ns":29.68,"ew":27.03,"dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"id":3967}, + {"name":"Glenden Wood Meeting Hall Portal","type":"Portal","wcid":6094,"cell":"A1A40167","place":"building","ns":29.98,"ew":27.42,"dest":{"cell":"01230126","place":"dungeon","name":"Glenden Wood Meeting Hall"},"id":3968}, + {"name":"Portal to Town Network","type":"Portal","wcid":43065,"cell":"A1A40035","place":"outdoor","ns":29.74,"ew":27.46,"dest":{"cell":"00070143","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3969}, + {"name":"Outside Linvak Tukal","type":"Portal","wcid":9410,"cell":"A21E0000","place":"outdoor","ns":-77.41,"ew":27.97,"dest":{"cell":"A220002F","place":"outdoor","ns":-75.74,"ew":28.23},"id":3970}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"A21E0024","place":"outdoor","ns":-77.6,"ew":28.12,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3971}, + {"name":"Linvak Tukal Entryway","type":"Portal","wcid":9411,"cell":"A21F0000","place":"outdoor","ns":-76.69,"ew":27.98,"dest":{"cell":"029C010C","place":"dungeon","name":"Linvak Tukal Entryway"},"id":3972}, + {"name":"Portal to Linvak Tukal","type":"Portal","wcid":8401,"cell":"A2200000","place":"outdoor","ns":-75.71,"ew":28.22,"dest":{"cell":"A21E001A","place":"outdoor","ns":-77.79,"ew":28.0},"desc":"This portal goes to Linvak Tukal, the fortress bastion of our Lugian allies in the Linvak Range. This is a good town for characters over level 40.","id":3973}, + {"name":"Uziz Meeting Hall Portal","type":"Portal","wcid":6109,"cell":"A25F0166","place":"building","ns":-25.2,"ew":28.19,"dest":{"cell":"01320126","place":"dungeon","name":"Uziz Meeting Hall"},"id":3974}, + {"name":"Effigy Foundry Portal","type":"Portal","wcid":19718,"cell":"A2600121","place":"building","ns":-25.06,"ew":28.33,"dest":{"cell":"545901B0","place":"dungeon","name":"Effigy Foundry"},"id":3975}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"A2600000","place":"outdoor","ns":-24.93,"ew":28.33,"dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"id":3976}, + {"name":"Matron Hive West","type":"Portal","wcid":24434,"cell":"A2600000","place":"outdoor","ns":-24.95,"ew":28.2,"dest":{"cell":"6145036E","place":"dungeon","name":"Matron Hive West"},"minLevel":90,"id":3977}, + {"name":"Portal to Town Network","type":"Portal","wcid":43066,"cell":"A2600029","place":"outdoor","ns":-25.14,"ew":28.19,"dest":{"cell":"00070133","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":3978}, + {"name":"Tusker Temple","type":"Portal","wcid":22698,"cell":"A2CA0000","place":"outdoor","ns":59.79,"ew":28.43,"dest":{"cell":"5D4302F9","place":"dungeon","name":"Tusker Temple"},"minLevel":20,"maxLevel":40,"id":3979}, + {"name":"Serac Vault Portal","type":"Portal","wcid":6397,"cell":"A3200000","place":"outdoor","ns":-75.89,"ew":28.98,"dest":{"cell":"01170140","place":"dungeon","name":"Serac Vault"},"id":3980}, + {"name":"Daiklos Dungeon","type":"Portal","wcid":4158,"cell":"A3A90000","place":"outdoor","ns":33.73,"ew":29.23,"dest":{"cell":"0185020F","place":"dungeon","name":"Daiklos Dungeon"},"id":3981}, + {"name":"Destroyed Glenden Wood Portal","type":"Portal","wcid":1017,"cell":"A3AD0000","place":"outdoor","ns":36.68,"ew":29.06,"dest":{"cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":3982}, + {"name":"Falatacot Depot","type":"Portal","wcid":47208,"cell":"A4210002","place":"outdoor","ns":-75.39,"ew":29.31,"dest":{"cell":"585E0101","place":"dungeon","name":"Falatacot Depot"},"minLevel":150,"id":3983}, + {"name":"Gredaline Consulate","type":"Portal","wcid":9508,"cell":"A4320000","place":"outdoor","ns":-61.6,"ew":29.29,"dest":{"cell":"029B0318","place":"dungeon","name":"Gredaline Consulate"},"minLevel":25,"id":3984}, + {"name":"North Uziz Settlement Portal","type":"Portal","wcid":12534,"cell":"A4600000","place":"outdoor","ns":-24.81,"ew":29.67,"dest":{"cell":"A4640031","place":"outdoor","ns":-21.89,"ew":29.91},"id":3985}, + {"name":"Narziz Cottages Portal","type":"Portal","wcid":12526,"cell":"A4600000","place":"outdoor","ns":-24.81,"ew":29.71,"dest":{"cell":"A8670021","place":"outdoor","ns":-19.52,"ew":32.86},"id":3986}, + {"name":"Broken Sword Bethel Settlement Portal","type":"Portal","wcid":12481,"cell":"A4600000","place":"outdoor","ns":-24.82,"ew":29.77,"dest":{"cell":"AD6A003B","place":"outdoor","ns":-16.86,"ew":37.23},"id":3987}, + {"name":"Arida Butte Portal","type":"Portal","wcid":12473,"cell":"A4600000","place":"outdoor","ns":-24.87,"ew":29.8,"dest":{"cell":"AD62003E","place":"outdoor","ns":-23.02,"ew":37.21},"id":3988}, + {"name":"West Uziz Settlement Portal","type":"Portal","wcid":12563,"cell":"A4600000","place":"outdoor","ns":-24.9,"ew":29.81,"dest":{"cell":"9B5F0031","place":"outdoor","ns":-25.9,"ew":22.73},"id":3989}, + {"name":"Charbone Ridge Portal","type":"Portal","wcid":13096,"cell":"A4600000","place":"outdoor","ns":-24.97,"ew":29.81,"dest":{"cell":"A57F001A","place":"outdoor","ns":-0.17,"ew":30.4},"id":3990}, + {"name":"Arrak Portal","type":"Portal","wcid":14253,"cell":"A4600000","place":"outdoor","ns":-24.82,"ew":29.63,"dest":{"cell":"8573000C","place":"outdoor","ns":-9.56,"ew":4.64},"id":3991}, + {"name":"Sand Kings Cottages Portal","type":"Portal","wcid":14663,"cell":"A4600000","place":"outdoor","ns":-24.93,"ew":29.81,"dest":{"cell":"956E0003","place":"outdoor","ns":-13.71,"ew":17.32},"id":3992}, + {"name":"Djebel al-Nar Cottages Portal","type":"Portal","wcid":14620,"cell":"A4600000","place":"outdoor","ns":-25.0,"ew":29.8,"dest":{"cell":"9A6B000B","place":"outdoor","ns":-16.09,"ew":21.45},"id":3993}, + {"name":"Vulture's Eye Villas Portal","type":"Portal","wcid":14675,"cell":"A4600000","place":"outdoor","ns":-24.83,"ew":29.6,"dest":{"cell":"A06E0022","place":"outdoor","ns":-13.84,"ew":26.53},"id":3994}, + {"name":"South Uzis Villas Portal","type":"Portal","wcid":14668,"cell":"A4600000","place":"outdoor","ns":-24.84,"ew":29.57,"dest":{"cell":"A4540005","place":"outdoor","ns":-34.34,"ew":29.34},"id":3995}, + {"name":"Thasali Cottages Portal","type":"Portal","wcid":15196,"cell":"A4600000","place":"outdoor","ns":-25.03,"ew":29.78,"dest":{"cell":"995B0034","place":"outdoor","ns":-28.82,"ew":21.07},"id":3996}, + {"name":"Drytree Settlement Portal","type":"Portal","wcid":15154,"cell":"A4600000","place":"outdoor","ns":-25.06,"ew":29.76,"dest":{"cell":"A274001C","place":"outdoor","ns":-8.81,"ew":27.98},"id":3997}, + {"name":"Demonsbane Cottages Portal","type":"Portal","wcid":15672,"cell":"A4600000","place":"outdoor","ns":-24.87,"ew":29.52,"dest":{"cell":"A78A001D","place":"outdoor","ns":8.92,"ew":32.04},"id":3998}, + {"name":"Morntide Ascent Cottages Portal","type":"Portal","wcid":19153,"cell":"A4600000","place":"outdoor","ns":-25.11,"ew":29.76,"dest":{"cell":"6CA70025","place":"outdoor","ns":32.05,"ew":-15.11},"id":3999}, + {"name":"Hopevale Portal","type":"Portal","wcid":19148,"cell":"A4600000","place":"outdoor","ns":-24.88,"ew":29.49,"dest":{"cell":"54A80024","place":"outdoor","ns":32.78,"ew":-34.32},"id":4000}, + {"name":"Glenden Hills East Settlement Portal","type":"Portal","wcid":12501,"cell":"A4A20000","place":"outdoor","ns":27.9,"ew":29.54,"dest":{"cell":"A6A7000E","place":"outdoor","ns":32.17,"ew":31.02},"id":4001}, + {"name":"Glenden Hills North Settlement Portal","type":"Portal","wcid":12502,"cell":"A4A20000","place":"outdoor","ns":27.93,"ew":29.54,"dest":{"cell":"A0AB003A","place":"outdoor","ns":35.03,"ew":26.79},"id":4002}, + {"name":"Zabool Overlook Settlement Portal","type":"Portal","wcid":12571,"cell":"A4A20000","place":"outdoor","ns":27.86,"ew":29.54,"dest":{"cell":"9B9B0037","place":"outdoor","ns":22.73,"ew":22.74},"id":4003}, + {"name":"Whispering Pines Cottages Portal","type":"Portal","wcid":12564,"cell":"A4A20000","place":"outdoor","ns":27.84,"ew":29.5,"dest":{"cell":"90AA0011","place":"outdoor","ns":34.09,"ew":13.52},"id":4004}, + {"name":"Mountain Ridge Abodes Portal","type":"Portal","wcid":12524,"cell":"A4A20000","place":"outdoor","ns":27.96,"ew":29.5,"dest":{"cell":"9BAA0025","place":"outdoor","ns":34.52,"ew":22.5},"id":4005}, + {"name":"Eaves of Tiofor Settlement Portal","type":"Portal","wcid":12494,"cell":"A4A20000","place":"outdoor","ns":27.84,"ew":29.46,"dest":{"cell":"96A80021","place":"outdoor","ns":32.51,"ew":18.54},"id":4006}, + {"name":"Highland Manors Portal","type":"Portal","wcid":13108,"cell":"A4A20000","place":"outdoor","ns":27.96,"ew":29.47,"dest":{"cell":"94CE0024","place":"outdoor","ns":63.24,"ew":16.92},"id":4007}, + {"name":"West Norstead Portal","type":"Portal","wcid":14290,"cell":"A4A20000","place":"outdoor","ns":27.86,"ew":29.43,"dest":{"cell":"B1DD0026","place":"outdoor","ns":75.44,"ew":40.08},"id":4008}, + {"name":"Iceea Hills Estates Portal","type":"Portal","wcid":13109,"cell":"A4A20000","place":"outdoor","ns":27.94,"ew":29.43,"dest":{"cell":"A49F003E","place":"outdoor","ns":25.81,"ew":30.0},"id":4009}, + {"name":"Auroch Pasture Estates Portal","type":"Portal","wcid":13131,"cell":"A4A20000","place":"outdoor","ns":27.92,"ew":29.57,"dest":{"cell":"A09C0025","place":"outdoor","ns":23.27,"ew":26.53},"id":4010}, + {"name":"Pine Hillock Settlement Portal","type":"Portal","wcid":14657,"cell":"A4A20000","place":"outdoor","ns":27.88,"ew":29.57,"dest":{"cell":"91B8002D","place":"outdoor","ns":45.68,"ew":14.58},"id":4011}, + {"name":"Firedew Portal","type":"Portal","wcid":14632,"cell":"A4A20000","place":"outdoor","ns":27.83,"ew":29.57,"dest":{"cell":"8CB9002D","place":"outdoor","ns":46.47,"ew":10.57},"id":4012}, + {"name":"Mistdweller Villas Portal","type":"Portal","wcid":14652,"cell":"A4A20000","place":"outdoor","ns":27.81,"ew":29.53,"dest":{"cell":"91A5002E","place":"outdoor","ns":30.57,"ew":14.62},"id":4013}, + {"name":"Redrock Cottages Portal","type":"Portal","wcid":14660,"cell":"A4A20000","place":"outdoor","ns":27.97,"ew":29.57,"dest":{"cell":"9B960032","place":"outdoor","ns":18.19,"ew":22.72},"id":4014}, + {"name":"Bellig Mesa Cottages Portal","type":"Portal","wcid":14612,"cell":"A4A20000","place":"outdoor","ns":27.99,"ew":29.54,"dest":{"cell":"9791002F","place":"outdoor","ns":14.66,"ew":19.37},"id":4015}, + {"name":"Genem Causland Portal","type":"Portal","wcid":15158,"cell":"A4A20000","place":"outdoor","ns":28.01,"ew":29.5,"dest":{"cell":"70AA0024","place":"outdoor","ns":34.42,"ew":-11.91},"id":4016}, + {"name":"Howling Wolf Villas Portal","type":"Portal","wcid":15160,"cell":"A4A20000","place":"outdoor","ns":28.02,"ew":29.45,"dest":{"cell":"95A30022","place":"outdoor","ns":28.57,"ew":17.67},"id":4017}, + {"name":"Soltan Villas Portal","type":"Portal","wcid":15191,"cell":"A4A20000","place":"outdoor","ns":27.79,"ew":29.5,"dest":{"cell":"929E0024","place":"outdoor","ns":24.82,"ew":15.35},"id":4018}, + {"name":"Lanadryll Cottages Portal","type":"Portal","wcid":19151,"cell":"A4A20000","place":"outdoor","ns":27.79,"ew":29.47,"dest":{"cell":"80AE0016","place":"outdoor","ns":37.79,"ew":0.72},"id":4019}, + {"name":"Amarand Villas Portal","type":"Portal","wcid":19138,"cell":"A4A20000","place":"outdoor","ns":27.78,"ew":29.43,"dest":{"cell":"73AF001F","place":"outdoor","ns":38.72,"ew":-9.58},"id":4020}, + {"name":"Asuger Temple Portal","type":"Portal","wcid":7198,"cell":"A5B70000","place":"outdoor","ns":45.07,"ew":30.37,"dest":{"cell":"010B0101","place":"dungeon","name":"Asuger Temple"},"minLevel":20,"quest":true,"id":4021}, + {"name":"Access to Crystal Mines","type":"Portal","wcid":22866,"cell":"A5B90000","place":"outdoor","ns":46.79,"ew":30.49,"dest":{"cell":"75D70015","place":"outdoor","ns":70.5,"ew":-8.1},"quest":true,"id":4022}, + {"name":"Cave of Alabree","type":"Portal","wcid":4937,"cell":"A7B30100","place":"underground","ns":41.81,"ew":32.14,"dest":{"cell":"016201D1","place":"dungeon"},"minLevel":1,"maxLevel":20,"desc":"This is a good adventure for someone who is newly arrived in Dereth.","id":4023}, + {"name":"Catacombs of the Forgotten Portal","type":"Portal","wcid":7614,"cell":"A8950000","place":"outdoor","ns":17.31,"ew":32.8,"dest":{"cell":"02E602AF","place":"dungeon","name":"Catacombs of the Forgotten"},"minLevel":15,"id":4024}, + {"name":"Hunter's Leap","type":"Portal","wcid":2082,"cell":"A8AC0000","place":"outdoor","ns":35.72,"ew":32.6,"dest":{"cell":"01C60181","place":"dungeon","name":"Hunter's Leap"},"id":4025}, + {"name":"A Rat Nest","type":"Portal","wcid":1347,"cell":"A8B10000","place":"outdoor","ns":40.24,"ew":32.46,"dest":{"cell":"01DD015F","place":"dungeon","name":"A Rat Nest"},"id":4026}, + {"name":"Holtburg Dungeon","type":"Portal","wcid":1125,"cell":"A8B50000","place":"outdoor","ns":43.57,"ew":32.98,"dest":{"cell":"01F60289","place":"dungeon","name":"Holtburg Dungeon"},"id":4027}, + {"name":"Mountain Keep","type":"Portal","wcid":1364,"cell":"A8C30000","place":"outdoor","ns":54.69,"ew":32.89,"dest":{"cell":"01D202F7","place":"dungeon","name":"Mountain Keep"},"id":4028}, + {"name":"Defiled Temple Lower Wing","type":"Portal","wcid":30749,"cell":"A8E00108","place":"building","ns":77.61,"ew":32.79,"dest":{"cell":"00080164","place":"dungeon","name":"Defiled Temple Lower Wing"},"minLevel":40,"id":4029}, + {"name":"Defiled Temple Middle Wing","type":"Portal","wcid":30750,"cell":"A8E00103","place":"building","ns":77.7,"ew":32.71,"dest":{"cell":"01EC0164","place":"dungeon","name":"Defiled Temple Middle Wing"},"minLevel":60,"id":4030}, + {"name":"Defiled Temple Asylum","type":"Portal","wcid":30752,"cell":"A8E00112","place":"building","ns":77.79,"ew":32.8,"dest":{"cell":"000A0164","place":"dungeon","name":"Defiled Temple Asylum"},"minLevel":100,"id":4031}, + {"name":"Defiled Temple Upper Wing","type":"Portal","wcid":30751,"cell":"A8E0010D","place":"building","ns":77.69,"ew":32.89,"dest":{"cell":"00090164","place":"dungeon","name":"Defiled Temple Upper Wing"},"minLevel":80,"id":4032}, + {"name":"Exit","type":"Portal","wcid":23516,"cell":"A9530000","place":"outdoor","ns":-35.13,"ew":33.73,"dest":{"cell":"A9540018","place":"outdoor","ns":-34.04,"ew":33.48},"id":4033}, + {"name":"Tower Base Dungeon","type":"Portal","wcid":23515,"cell":"A9540000","place":"outdoor","ns":-34.73,"ew":33.6,"dest":{"cell":"56470103","place":"dungeon","name":"Tower Base Dungeon"},"minLevel":115,"quest":true,"id":4034}, + {"name":"Drudge Hideout","type":"Portal","wcid":2068,"cell":"A9B30000","place":"outdoor","ns":41.37,"ew":33.27,"dest":{"cell":"019E0114","place":"dungeon","name":"Drudge Hideout"},"desc":"This is a good adventure for someone who is newly arrived in Dereth.","id":4035}, + {"name":"Mannikin Foundry Portal","type":"Portal","wcid":19717,"cell":"A9B40176","place":"building","ns":42.7,"ew":33.58,"dest":{"cell":"545A013C","place":"dungeon","name":"Mannikin Foundry"},"id":4036}, + {"name":"Holtburg Meeting Hall Portal","type":"Portal","wcid":6096,"cell":"A9B4017A","place":"building","ns":42.21,"ew":33.91,"dest":{"cell":"01250126","place":"dungeon","name":"Holtburg Meeting Hall"},"id":4037}, + {"name":"Destroyed Portal to Redspire","type":"Portal","wcid":11960,"cell":"A9B40000","place":"outdoor","ns":42.62,"ew":33.36,"dest":{"cell":"17B2002A","place":"outdoor","ns":40.56,"ew":-83.0},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4038}, + {"name":"Portal to Town Network","type":"Portal","wcid":43065,"cell":"A9B40003","place":"outdoor","ns":42.28,"ew":33.31,"dest":{"cell":"00070143","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4039}, + {"name":"Hub of Awakening","type":"Portal","wcid":3000008,"cell":"A9B40019","place":"outdoor","ns":42.13,"ew":33.56,"dest":{"cell":"8A020212","place":"dungeon","name":"Hub of Awakening"},"id":4040}, + {"name":"The Trials Hub","type":"Portal","wcid":3000034,"cell":"A9B40019","place":"outdoor","ns":42.11,"ew":33.56,"dest":{"cell":"01250126","place":"dungeon","name":"Holtburg Meeting Hall"},"id":4041}, + {"name":"Aerlinthe Island (Instance)","type":"Portal","wcid":3000120,"cell":"A9B40019","place":"outdoor","ns":42.09,"ew":33.56,"dest":{"cell":"BAE8001D","place":"outdoor","ns":84.09,"ew":47.2},"id":4042}, + {"name":"Aerlinthe Island (Player Killer)","type":"Portal","wcid":3000121,"cell":"A9B40019","place":"outdoor","ns":42.07,"ew":33.56,"dest":{"cell":"BAE8001D","place":"outdoor","ns":84.09,"ew":47.2},"desc":"Beyond this portal lies a second Aerlinthe where everyone is a Player Killer. Anyone there may attack you, and dying to another player drops items. You are yourself again the moment you leave.","id":4043}, + {"name":"Dungeon Nye","type":"Portal","wcid":4156,"cell":"AA870102","place":"building","ns":6.2,"ew":34.42,"dest":{"cell":"01810161","place":"dungeon","name":"Dungeon Nye"},"id":4044}, + {"name":"Holtburg Redoubt","type":"Portal","wcid":4935,"cell":"AAB10000","place":"outdoor","ns":40.4,"ew":34.47,"dest":{"cell":"016301AC","place":"dungeon","name":"Holtburg Redoubt"},"minLevel":1,"maxLevel":20,"desc":"This is a good adventure for someone who is newly arrived in Dereth.","id":4045}, + {"name":"Underground Passage","type":"Portal","wcid":14449,"cell":"AAB30101","place":"building","ns":41.6,"ew":34.2,"dest":{"cell":"01C20123","place":"dungeon","name":"Underground Passage"},"minLevel":20,"quest":true,"id":4046}, + {"name":"Amiantos Bethel Portal","type":"Portal","wcid":6779,"cell":"AB6B0000","place":"outdoor","ns":-16.28,"ew":35.13,"dest":{"cell":"01130211","place":"dungeon","name":"Amiantos Bethel"},"id":4047}, + {"name":"Adventurer's Haven","type":"Portal","wcid":2080,"cell":"AB840000","place":"outdoor","ns":4.4,"ew":35.52,"dest":{"cell":"01AC010C","place":"dungeon","name":"Adventurer's Haven"},"id":4048}, + {"name":"Evensong Settlement Portal","type":"Portal","wcid":12495,"cell":"ABB10000","place":"outdoor","ns":40.16,"ew":35.1,"dest":{"cell":"B2B30014","place":"outdoor","ns":41.63,"ew":40.74},"id":4049}, + {"name":"Lilyglen Cottages Portal","type":"Portal","wcid":12513,"cell":"ABB10000","place":"outdoor","ns":40.17,"ew":35.07,"dest":{"cell":"A3BB003C","place":"outdoor","ns":47.97,"ew":29.21},"id":4050}, + {"name":"Woodsbane Cottages Portal","type":"Portal","wcid":12566,"cell":"ABB10000","place":"outdoor","ns":40.2,"ew":35.06,"dest":{"cell":"96B6001B","place":"outdoor","ns":43.88,"ew":18.43},"id":4051}, + {"name":"Mountain Keep Cottages Portal","type":"Portal","wcid":12523,"cell":"ABB10000","place":"outdoor","ns":40.23,"ew":35.07,"dest":{"cell":"ABBE0023","place":"outdoor","ns":50.29,"ew":35.35},"id":4052}, + {"name":"Holtburg Wilderness Settlement Portal","type":"Portal","wcid":12503,"cell":"ABB10000","place":"outdoor","ns":40.24,"ew":35.11,"dest":{"cell":"BAB2001B","place":"outdoor","ns":40.74,"ew":47.2},"id":4053}, + {"name":"New Colier Portal","type":"Portal","wcid":12527,"cell":"ABB10000","place":"outdoor","ns":40.18,"ew":35.14,"dest":{"cell":"A6CB001F","place":"outdoor","ns":61.09,"ew":31.19},"id":4054}, + {"name":"West Holtburg Villas Portal","type":"Portal","wcid":13138,"cell":"ABB10000","place":"outdoor","ns":40.21,"ew":35.14,"dest":{"cell":"B2B90005","place":"outdoor","ns":46.53,"ew":40.52},"id":4055}, + {"name":"Destroyed Portal to Sanamar","type":"Portal","wcid":28709,"cell":"ABB20036","place":"outdoor","ns":40.98,"ew":35.49,"dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4056}, + {"name":"Nuhmudira's Dungeon","type":"Portal","wcid":15275,"cell":"AC7A0152","place":"underground","ns":-4.02,"ew":35.93,"dest":{"cell":"536D0289","place":"dungeon"},"id":4057}, + {"name":"An Archive","type":"Portal","wcid":23512,"cell":"AD300000","place":"outdoor","ns":-63.48,"ew":36.83,"dest":{"cell":"564601DC","place":"dungeon","name":"An Archive"},"minLevel":115,"quest":true,"id":4058}, + {"name":"Heartland","type":"Portal","wcid":1900,"cell":"AD580000","place":"outdoor","ns":-31.4,"ew":36.98,"dest":{"cell":"AD9B003E","place":"outdoor","ns":22.58,"ew":37.23},"id":4059}, + {"name":"Dungeon Fern","type":"Portal","wcid":2070,"cell":"ADB50000","place":"outdoor","ns":43.33,"ew":37.14,"dest":{"cell":"01B30116","place":"dungeon","name":"Dungeon Fern"},"id":4060}, + {"name":"Desert Ridge Border","type":"Portal","wcid":1903,"cell":"AE710000","place":"outdoor","ns":-11.2,"ew":37.4,"dest":{"cell":"B178001C","place":"outdoor","ns":-5.64,"ew":39.96},"id":4061}, + {"name":"Riverbend","type":"Portal","wcid":1906,"cell":"AE710000","place":"outdoor","ns":-11.38,"ew":37.57,"dest":{"cell":"CE7C0025","place":"outdoor","ns":-2.29,"ew":63.29},"id":4062}, + {"name":"North Desert Edge","type":"Portal","wcid":1905,"cell":"AE710000","place":"outdoor","ns":-11.43,"ew":37.5,"dest":{"cell":"7B790025","place":"outdoor","ns":-4.69,"ew":-3.07},"id":4063}, + {"name":"Abandoned Arena","type":"Portal","wcid":2391,"cell":"AE710000","place":"outdoor","ns":-11.28,"ew":37.5,"dest":{"cell":"01A80156","place":"dungeon","name":"Unstable"},"id":4064}, + {"name":"The Colosseum","type":"Portal","wcid":34508,"cell":"AE710014","place":"outdoor","ns":-11.24,"ew":37.54,"dest":{"cell":"00AF0118","place":"dungeon","name":"The Colosseum"},"id":4065}, + {"name":"Witshire Dungeon Portal","type":"Portal","wcid":2095,"cell":"AE9E0108","place":"building","ns":24.91,"ew":37.69,"dest":{"cell":"01C201BE","place":"dungeon","name":"Underground Passage"},"minLevel":7,"quest":true,"id":4066}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"AEC70000","place":"outdoor","ns":57.57,"ew":37.64,"dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4067}, + {"name":"Colier Mine","type":"Portal","wcid":1547,"cell":"AFC6015C","place":"building","ns":56.71,"ew":38.48,"dest":{"cell":"01AE032C","place":"dungeon","name":"Colier Mine"},"id":4068}, + {"name":"Lugian Mines Portal","type":"Portal","wcid":7608,"cell":"B0230000","place":"outdoor","ns":-73.87,"ew":38.98,"dest":{"cell":"02E9020C","place":"dungeon","name":"Lugian Mines"},"id":4069}, + {"name":"Yanshi Lower Undermine","type":"Portal","wcid":32518,"cell":"B070010C","place":"dungeon","dest":{"cell":"0046010E","place":"dungeon"},"minLevel":100,"quest":true,"desc":"This portal is quest-restricted. Speak with Adrana the Royal Guard in Yanshi for details. In a dungeon (landblock B070).","id":4070}, + {"name":"Banderling Ruin","type":"Portal","wcid":1329,"cell":"B0AC0000","place":"outdoor","ns":36.13,"ew":39.61,"dest":{"cell":"01E00121","place":"dungeon","name":"Banderling Ruin"},"id":4071}, + {"name":"Realaidain Eastern Vault","type":"Portal","wcid":34542,"cell":"B0C10101","place":"dungeon","dest":{"cell":"005001E9","place":"dungeon"},"minLevel":80,"quest":true,"desc":"This dungeon is quest-restricted. Go see Shan Zhen in Cragstone for more information. In a dungeon (landblock B0C1).","id":4072}, + {"name":"Dungeon of Tatters","type":"Portal","wcid":2074,"cell":"B131011D","place":"underground","ns":-62.13,"ew":40.07,"dest":{"cell":"01BA0186","place":"dungeon"},"id":4073}, + {"name":"Heartland","type":"Portal","wcid":1900,"cell":"B1320000","place":"outdoor","ns":-61.8,"ew":40.02,"dest":{"cell":"AD9B003E","place":"outdoor","ns":22.58,"ew":37.23},"id":4074}, + {"name":"High Mountain Valley","type":"Portal","wcid":1901,"cell":"B132010A","place":"building","ns":-61.87,"ew":40.02,"dest":{"cell":"CA2D0038","place":"outdoor","ns":-65.2,"ew":60.32},"id":4075}, + {"name":"Hilltop","type":"Portal","wcid":1902,"cell":"B1320102","place":"underground","ns":-61.92,"ew":40.19,"dest":{"cell":"AAA80034","place":"outdoor","ns":32.79,"ew":34.68},"id":4076}, + {"name":"Dragon's Power","type":"Portal","wcid":25833,"cell":"B3180000","place":"outdoor","ns":-82.33,"ew":41.38,"dest":{"cell":"644901A3","place":"dungeon","name":"Dragon's Power"},"minLevel":35,"quest":true,"id":4077}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700023","place":"outdoor","ns":-12.11,"ew":41.67,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4078}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700023","place":"outdoor","ns":-12.06,"ew":41.68,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4079}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700023","place":"outdoor","ns":-12.11,"ew":41.71,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4080}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700108","place":"building","ns":-12.1,"ew":41.78,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4081}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700117","place":"building","ns":-12.0,"ew":41.72,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4082}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B370002C","place":"outdoor","ns":-12.01,"ew":41.83,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4083}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700103","place":"building","ns":-12.09,"ew":41.82,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4084}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700023","place":"outdoor","ns":-12.1,"ew":41.71,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4085}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700022","place":"outdoor","ns":-12.21,"ew":41.73,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4086}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700022","place":"outdoor","ns":-12.16,"ew":41.73,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4087}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B370002D","place":"outdoor","ns":-11.9,"ew":41.8,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4088}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700025","place":"outdoor","ns":-11.92,"ew":41.69,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4089}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B370002C","place":"outdoor","ns":-12.0,"ew":41.77,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4090}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B370002B","place":"outdoor","ns":-12.1,"ew":41.76,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4091}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B370002B","place":"outdoor","ns":-12.13,"ew":41.76,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4092}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B370002A","place":"outdoor","ns":-12.18,"ew":41.8,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4093}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B370002B","place":"outdoor","ns":-12.1,"ew":41.84,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4094}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700024","place":"outdoor","ns":-11.97,"ew":41.73,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4095}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B370002D","place":"outdoor","ns":-11.92,"ew":41.78,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4096}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B3700024","place":"outdoor","ns":-12.05,"ew":41.72,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4097}, + {"name":"Trap Floor Portal","type":"Portal","wcid":42956,"cell":"B370002B","place":"outdoor","ns":-12.06,"ew":41.81,"dest":{"cell":"B36F0024","place":"outdoor","ns":-12.79,"ew":41.68},"id":4098}, + {"name":"Yanshi Meeting Hall Portal","type":"Portal","wcid":6110,"cell":"B46F0106","place":"building","ns":-12.49,"ew":42.8,"dest":{"cell":"01330126","place":"dungeon","name":"Yanshi Meeting Hall"},"id":4099}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"B470002B","place":"outdoor","ns":-12.13,"ew":42.58,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4100}, + {"name":"Tenkarrdun Foundry Portal","type":"Portal","wcid":7488,"cell":"B4EE0100","place":"building","ns":88.9,"ew":42.76,"dest":{"cell":"0116042F","place":"dungeon","name":"Tenkarrdun Foundry"},"minLevel":40,"id":4101}, + {"name":"Temple of the Font","type":"Portal","wcid":53477,"cell":"B54A002E","place":"outdoor","ns":-42.19,"ew":43.41,"dest":{"cell":"596B012C","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":275,"id":4102}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43575,"cell":"B56D0102","place":"dungeon","dest":{"cell":"E5D00040","place":"outdoor","ns":65.22,"ew":81.98},"desc":"In a dungeon (landblock B56D).","id":4103}, + {"name":"A Cave","type":"Portal","wcid":3636,"cell":"B59D0100","place":"dungeon","dest":{"cell":"018B0191","place":"dungeon"},"desc":"In a dungeon (landblock B59D).","id":4104}, + {"name":"Olthoi Horde Nest","type":"Portal","wcid":7258,"cell":"B5C50000","place":"outdoor","ns":55.78,"ew":43.48,"dest":{"cell":"02FB03B4","place":"dungeon","name":"Olthoi Horde Nest"},"minLevel":20,"id":4105}, + {"name":"Aerlinthe Reservoir Portal","type":"Portal","wcid":7289,"cell":"B5EA0102","place":"building","ns":85.53,"ew":43.4,"dest":{"cell":"02EE03D2","place":"dungeon","name":"Aerlinthe Reservoir"},"minLevel":40,"id":4106}, + {"name":"Eastern Aerlinthe Island","type":"Portal","wcid":28062,"cell":"B5F0010E","place":"underground","ns":89.64,"ew":43.39,"dest":{"cell":"BAE80106","place":"underground","ns":84.1,"ew":46.92},"id":4107}, + {"name":"Western Aerlinthe Island","type":"Portal","wcid":28064,"cell":"B5F00116","place":"underground","ns":89.68,"ew":43.46,"dest":{"cell":"B8E80103","place":"building","ns":84.2,"ew":45.98},"id":4108}, + {"name":"Mansion Dungeon Portal","type":"Portal","wcid":22089,"cell":"B6870152","place":"underground","ns":6.58,"ew":43.93,"dest":{"cell":"5651038E","place":"dungeon"},"quest":true,"id":4109}, + {"name":"Dungeon of Shadows Portal","type":"Portal","wcid":1117,"cell":"B69A0000","place":"outdoor","ns":21.45,"ew":44.04,"dest":{"cell":"01ED0310","place":"dungeon","name":"Dungeon of Shadows"},"id":4110}, + {"name":"Olthoi Chasm","type":"Portal","wcid":25684,"cell":"B7800000","place":"outdoor","ns":0.7,"ew":44.71,"dest":{"cell":"5D4A0342","place":"dungeon","name":"Olthoi Chasm"},"minLevel":20,"id":4111}, + {"name":"Tanada House of Storms","type":"Portal","wcid":87640,"cell":"B82A0013","place":"outdoor","ns":-68.11,"ew":45.53,"dest":{"cell":"007B011D","place":"dungeon","name":"Tanada House of Storms"},"minLevel":80,"quest":true,"id":4112}, + {"name":"Swamp Gardens","type":"Portal","wcid":11686,"cell":"B8630000","place":"outdoor","ns":-22.59,"ew":45.78,"dest":{"cell":"028F013C","place":"dungeon","name":"Swamp Gardens"},"id":4113}, + {"name":"Mossy Cave","type":"Portal","wcid":28261,"cell":"B86D0000","place":"outdoor","ns":-14.16,"ew":45.98,"dest":{"cell":"0177014F","place":"dungeon","name":"Mossy Cave"},"minLevel":20,"id":4114}, + {"name":"Yanshi Tunnel Portal","type":"Portal","wcid":1398,"cell":"B8700000","place":"outdoor","ns":-12.13,"ew":45.53,"dest":{"cell":"01D00117","place":"dungeon","name":"Yanshi Tunnel"},"id":4115}, + {"name":"Liang Chi Settlement Portal","type":"Portal","wcid":12512,"cell":"B8720000","place":"outdoor","ns":-10.4,"ew":45.73,"dest":{"cell":"B374002A","place":"outdoor","ns":-9.02,"ew":41.78},"id":4116}, + {"name":"Broadacre Cottages Portal","type":"Portal","wcid":12480,"cell":"B8720000","place":"outdoor","ns":-10.39,"ew":45.68,"dest":{"cell":"CE700033","place":"outdoor","ns":-12.13,"ew":63.51},"id":4117}, + {"name":"Imuth Maer Cottages Portal","type":"Portal","wcid":12505,"cell":"B8720000","place":"outdoor","ns":-10.37,"ew":45.63,"dest":{"cell":"CB6B0015","place":"outdoor","ns":-15.91,"ew":60.7},"id":4118}, + {"name":"Swamp Temple Place Portal","type":"Portal","wcid":12558,"cell":"B8720000","place":"outdoor","ns":-10.32,"ew":45.62,"dest":{"cell":"B661003D","place":"outdoor","ns":-23.86,"ew":44.42},"id":4119}, + {"name":"Yanshi Namoon North Portal","type":"Portal","wcid":12568,"cell":"B8720000","place":"outdoor","ns":-10.27,"ew":45.61,"dest":{"cell":"B667003E","place":"outdoor","ns":-19.04,"ew":44.39},"id":4120}, + {"name":"Faranar Foothills Portal","type":"Portal","wcid":12496,"cell":"B8720000","place":"outdoor","ns":-10.23,"ew":45.63,"dest":{"cell":"B26C002C","place":"outdoor","ns":-15.16,"ew":41.03},"id":4121}, + {"name":"West Yanshi Namoon Portal","type":"Portal","wcid":14291,"cell":"B8720000","place":"outdoor","ns":-10.21,"ew":45.67,"dest":{"cell":"B2640029","place":"outdoor","ns":-21.88,"ew":40.98},"id":4122}, + {"name":"Snakehead Portal","type":"Portal","wcid":14284,"cell":"B8720000","place":"outdoor","ns":-10.21,"ew":45.71,"dest":{"cell":"C46C003D","place":"outdoor","ns":-15.11,"ew":55.56},"id":4123}, + {"name":"Crescent Lane Cottages Portal","type":"Portal","wcid":14257,"cell":"B8720000","place":"outdoor","ns":-10.38,"ew":45.77,"dest":{"cell":"D26D001A","place":"outdoor","ns":-14.56,"ew":66.37},"id":4124}, + {"name":"Northwater Cottages Portal","type":"Portal","wcid":13117,"cell":"B8720000","place":"outdoor","ns":-10.37,"ew":45.81,"dest":{"cell":"78F40007","place":"outdoor","ns":93.91,"ew":-5.86},"id":4125}, + {"name":"Taralla Portal","type":"Portal","wcid":14286,"cell":"B8720000","place":"outdoor","ns":-10.3,"ew":45.58,"dest":{"cell":"ACA6002D","place":"outdoor","ns":31.27,"ew":36.23},"id":4126}, + {"name":"Li-Po Cottages Portal","type":"Portal","wcid":14645,"cell":"B8720000","place":"outdoor","ns":-10.36,"ew":45.59,"dest":{"cell":"B957002E","place":"outdoor","ns":-31.84,"ew":46.55},"id":4127}, + {"name":"Jenshi Cottages Portal","type":"Portal","wcid":15163,"cell":"B8720000","place":"outdoor","ns":-10.24,"ew":45.58,"dest":{"cell":"B779000D","place":"outdoor","ns":-4.74,"ew":44.64},"id":4128}, + {"name":"Blazing Wand Villas Portal","type":"Portal","wcid":15668,"cell":"B8720000","place":"outdoor","ns":-10.41,"ew":45.63,"dest":{"cell":"7AA2002B","place":"outdoor","ns":27.93,"ew":-3.79},"id":4129}, + {"name":"Firesong Cottages Portal","type":"Portal","wcid":19145,"cell":"B8720000","place":"outdoor","ns":-10.44,"ew":45.67,"dest":{"cell":"5EAF0024","place":"outdoor","ns":38.36,"ew":-26.3},"id":4130}, + {"name":"Cave","type":"Portal","wcid":35595,"cell":"B89F0102","place":"building","ns":25.39,"ew":45.93,"dest":{"cell":"00EE03B4","place":"dungeon","name":"Cave"},"id":4131}, + {"name":"Coral Tunnels","type":"Portal","wcid":28063,"cell":"B8E80103","place":"building","ns":84.2,"ew":46.02,"dest":{"cell":"02EC02BD","place":"dungeon","name":"Coral Tunnels"},"minLevel":40,"id":4132}, + {"name":"Vile-Smelling Refuse","type":"Portal","wcid":28479,"cell":"B95F0112","place":"building","ns":-25.5,"ew":46.41,"dest":{"cell":"027A0325","place":"dungeon","name":"Vile-Smelling Refuse"},"minLevel":60,"quest":true,"id":4133}, + {"name":"Vile-Smelling Refuse","type":"Portal","wcid":28483,"cell":"B95F010A","place":"building","ns":-25.5,"ew":46.19,"dest":{"cell":"027B030C","place":"dungeon","name":"Vile-Smelling Refuse"},"minLevel":60,"quest":true,"id":4134}, + {"name":"Vile-Smelling Refuse","type":"Portal","wcid":28478,"cell":"B95F0106","place":"building","ns":-25.6,"ew":46.19,"dest":{"cell":"0279037B","place":"dungeon","name":"Vile-Smelling Refuse"},"minLevel":60,"quest":true,"id":4135}, + {"name":"Vile-Smelling Refuse","type":"Portal","wcid":28481,"cell":"B95F0116","place":"building","ns":-25.54,"ew":46.31,"dest":{"cell":"02780369","place":"dungeon","name":"Vile-Smelling Refuse"},"minLevel":60,"quest":true,"id":4136}, + {"name":"Vile-Smelling Refuse","type":"Portal","wcid":28482,"cell":"B95F010E","place":"building","ns":-25.6,"ew":46.41,"dest":{"cell":"0280041C","place":"dungeon","name":"Vile-Smelling Refuse"},"minLevel":60,"quest":true,"id":4137}, + {"name":"Hidden Entrance","type":"Portal","wcid":28096,"cell":"B9610000","place":"outdoor","ns":-24.26,"ew":46.25,"dest":{"cell":"017D016D","place":"dungeon","name":"Hidden"},"id":4138}, + {"name":"Destroyed Portal to Redspire","type":"Portal","wcid":11960,"cell":"B96B0000","place":"outdoor","ns":-15.9,"ew":46.7,"dest":{"cell":"17B2002A","place":"outdoor","ns":40.56,"ew":-83.0},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4139}, + {"name":"Destroyed Portal to Shoushi","type":"Portal","wcid":1027,"cell":"B96D0000","place":"outdoor","ns":-14.72,"ew":46.55,"dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4140}, + {"name":"Destroyed Portal to Yaraq","type":"Portal","wcid":1030,"cell":"B9700000","place":"outdoor","ns":-12.11,"ew":46.3,"dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4141}, + {"name":"Cragstone Farms Portal","type":"Portal","wcid":12485,"cell":"B9A00000","place":"outdoor","ns":26.16,"ew":46.3,"dest":{"cell":"B598003D","place":"outdoor","ns":20.14,"ew":43.57},"id":4142}, + {"name":"South Victory Harbor Portal","type":"Portal","wcid":12553,"cell":"B9A00000","place":"outdoor","ns":26.17,"ew":46.26,"dest":{"cell":"BC950012","place":"outdoor","ns":17.44,"ew":48.74},"id":4143}, + {"name":"Forgotten Hills Portal","type":"Portal","wcid":12498,"cell":"B9A00000","place":"outdoor","ns":26.2,"ew":46.26,"dest":{"cell":"AE910029","place":"outdoor","ns":14.1,"ew":37.83},"id":4144}, + {"name":"Haliana Portal","type":"Portal","wcid":14263,"cell":"B9A00000","place":"outdoor","ns":26.23,"ew":46.26,"dest":{"cell":"CBDA002F","place":"outdoor","ns":73.09,"ew":60.99},"id":4145}, + {"name":"Ispan Hill Portal","type":"Portal","wcid":14266,"cell":"B9A00000","place":"outdoor","ns":26.17,"ew":46.33,"dest":{"cell":"A2C1001A","place":"outdoor","ns":52.57,"ew":27.98},"id":4146}, + {"name":"Meerthus Square Portal","type":"Portal","wcid":14651,"cell":"B9A00000","place":"outdoor","ns":26.27,"ew":46.28,"dest":{"cell":"B0980012","place":"outdoor","ns":19.79,"ew":39.14},"id":4147}, + {"name":"Solstice Hill Portal","type":"Portal","wcid":14666,"cell":"B9A00000","place":"outdoor","ns":26.29,"ew":46.31,"dest":{"cell":"A998001D","place":"outdoor","ns":20.11,"ew":33.57},"id":4148}, + {"name":"Lost Realm Cottages Portal","type":"Portal","wcid":14649,"cell":"B9A00000","place":"outdoor","ns":26.19,"ew":46.36,"dest":{"cell":"A097001D","place":"outdoor","ns":19.27,"ew":26.36},"id":4149}, + {"name":"Tinkelo Hold Villas Portal","type":"Portal","wcid":15199,"cell":"B9A00000","place":"outdoor","ns":26.22,"ew":46.39,"dest":{"cell":"AC950021","place":"outdoor","ns":17.34,"ew":36.11},"id":4150}, + {"name":"Colier View Hill Portal","type":"Portal","wcid":15670,"cell":"B9A00000","place":"outdoor","ns":26.31,"ew":46.33,"dest":{"cell":"B2C90025","place":"outdoor","ns":59.32,"ew":40.92},"id":4151}, + {"name":"Far Horizon Cottages Portal","type":"Portal","wcid":15673,"cell":"B9A00000","place":"outdoor","ns":26.13,"ew":46.28,"dest":{"cell":"7CF3001D","place":"outdoor","ns":92.86,"ew":-2.39},"id":4152}, + {"name":"Charged Niche","type":"Portal","wcid":52222,"cell":"B9F10040","place":"outdoor","ns":91.64,"ew":46.84,"dest":{"cell":"595E020F","place":"dungeon","name":"Frozen Recess"},"minLevel":180,"id":4153}, + {"name":"Sho Roadside","type":"Portal","wcid":1907,"cell":"BA170000","place":"outdoor","ns":-83.52,"ew":47.13,"dest":{"cell":"D45C003D","place":"outdoor","ns":-27.92,"ew":68.38},"id":4154}, + {"name":"Colossus Foundry Portal","type":"Portal","wcid":19715,"cell":"BA170142","place":"building","ns":-83.33,"ew":47.13,"dest":{"cell":"545701C5","place":"dungeon","name":"Colossus Foundry"},"id":4155}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"BA170013","place":"outdoor","ns":-83.29,"ew":47.06,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4156}, + {"name":"Watery Grotto","type":"Portal","wcid":28265,"cell":"BA610100","place":"underground","ns":-23.8,"ew":47.17,"dest":{"cell":"017B0154","place":"dungeon"},"minLevel":40,"id":4157}, + {"name":"Deserted Ruin Portal","type":"Portal","wcid":4931,"cell":"BA6B0102","place":"dungeon","dest":{"cell":"0166015A","place":"dungeon"},"minLevel":40,"desc":"In a dungeon (landblock BA6B).","id":4158}, + {"name":"A Ruin","type":"Portal","wcid":1343,"cell":"BA6F0000","place":"outdoor","ns":-12.96,"ew":47.33,"dest":{"cell":"01DA010F","place":"dungeon","name":"A Ruin"},"id":4159}, + {"name":"River Bridge Portal","type":"Portal","wcid":1106,"cell":"BAA10000","place":"outdoor","ns":27.19,"ew":47.32,"dest":{"cell":"BBA30019","place":"outdoor","ns":28.55,"ew":47.95},"id":4160}, + {"name":"Northwest Direlands Portal","type":"Portal","wcid":7211,"cell":"BAE80000","place":"outdoor","ns":84.11,"ew":47.2,"dest":{"cell":"12860003","place":"outdoor","ns":5.53,"ew":-87.51},"minLevel":35,"id":4161}, + {"name":"Coral Tunnels","type":"Portal","wcid":28061,"cell":"BAE80106","place":"underground","ns":84.1,"ew":46.88,"dest":{"cell":"02EC031F","place":"dungeon","name":"Coral Tunnels"},"minLevel":40,"id":4162}, + {"name":"Ancient Masonry","type":"Portal","wcid":33034,"cell":"BAED003D","place":"outdoor","ns":88.09,"ew":47.6,"dest":{"cell":"008B0155","place":"dungeon","name":"Ancient Masonry"},"minLevel":100,"id":4163}, + {"name":"Yukikaze Portal","type":"Portal","wcid":12569,"cell":"BB170000","place":"outdoor","ns":-82.83,"ew":48.07,"dest":{"cell":"BA250026","place":"outdoor","ns":-71.77,"ew":47.26},"id":4164}, + {"name":"North Adjamaer Cottages Portal","type":"Portal","wcid":12531,"cell":"BB170000","place":"outdoor","ns":-82.83,"ew":48.1,"dest":{"cell":"C220001C","place":"outdoor","ns":-75.98,"ew":53.58},"id":4165}, + {"name":"Ishilai Inlet Settlement Portal","type":"Portal","wcid":12506,"cell":"BB170000","place":"outdoor","ns":-82.87,"ew":48.16,"dest":{"cell":"BF19003D","place":"outdoor","ns":-81.47,"ew":51.56},"id":4166}, + {"name":"Norstead Portal","type":"Portal","wcid":12530,"cell":"BB170000","place":"outdoor","ns":-82.9,"ew":48.17,"dest":{"cell":"C0DD0030","place":"outdoor","ns":75.61,"ew":52.18},"id":4167}, + {"name":"South Adjamaer Cottages Portal","type":"Portal","wcid":12548,"cell":"BB170000","place":"outdoor","ns":-82.84,"ew":48.14,"dest":{"cell":"C51A001E","place":"outdoor","ns":-80.57,"ew":56.0},"id":4168}, + {"name":"Ishilai Inlet Villas Portal","type":"Portal","wcid":13110,"cell":"BB170000","place":"outdoor","ns":-82.87,"ew":48.04,"dest":{"cell":"BF150035","place":"outdoor","ns":-84.7,"ew":51.54},"id":4169}, + {"name":"Ikama Cottages Portal","type":"Portal","wcid":14637,"cell":"BB170000","place":"outdoor","ns":-82.93,"ew":48.16,"dest":{"cell":"AB340025","place":"outdoor","ns":-59.9,"ew":35.25},"id":4170}, + {"name":"Lake Thrasyl Cottages Portal","type":"Portal","wcid":14641,"cell":"BB170000","place":"outdoor","ns":-82.91,"ew":48.03,"dest":{"cell":"B425001C","place":"outdoor","ns":-72.01,"ew":42.38},"id":4171}, + {"name":"Brazenn Domain Portal","type":"Portal","wcid":15146,"cell":"BB170000","place":"outdoor","ns":-82.96,"ew":48.14,"dest":{"cell":"4ADB0024","place":"outdoor","ns":73.63,"ew":-42.3},"id":4172}, + {"name":"Direvale Villas Portal","type":"Portal","wcid":15152,"cell":"BB170000","place":"outdoor","ns":-82.99,"ew":48.12,"dest":{"cell":"63A8002D","place":"outdoor","ns":32.95,"ew":-22.25},"id":4173}, + {"name":"Peril's Edge Cottages Portal","type":"Portal","wcid":15680,"cell":"BB170000","place":"outdoor","ns":-82.94,"ew":48.03,"dest":{"cell":"419C001D","place":"outdoor","ns":23.34,"ew":-49.64},"id":4174}, + {"name":"Harmonious Blade Cottages Portal","type":"Portal","wcid":15675,"cell":"BB170000","place":"outdoor","ns":-82.97,"ew":48.01,"dest":{"cell":"63A2001D","place":"outdoor","ns":28.11,"ew":-22.4},"id":4175}, + {"name":"Swamp Temple","type":"Portal","wcid":2383,"cell":"BB62011F","place":"dungeon","dest":{"cell":"01A2045D","place":"dungeon"},"minLevel":10,"desc":"In a dungeon (landblock BB62).","id":4176}, + {"name":"ReedShark Lair Portal","type":"Portal","wcid":1127,"cell":"BB700000","place":"outdoor","ns":-12.29,"ew":48.28,"dest":{"cell":"01FC0114","place":"dungeon","name":"ReedShark Lair"},"minLevel":4,"id":4177}, + {"name":"Ruined Cave Outpost Portal","type":"Portal","wcid":4963,"cell":"BB820100","place":"dungeon","dest":{"cell":"0152024B","place":"dungeon"},"minLevel":1,"maxLevel":20,"desc":"In a dungeon (landblock BB82).","id":4178}, + {"name":"Destroyed Portal to Hebian-To","type":"Portal","wcid":1018,"cell":"BB9F0000","place":"outdoor","ns":25.36,"ew":47.76,"dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4179}, + {"name":"River Bridge Portal","type":"Portal","wcid":1105,"cell":"BBA30000","place":"outdoor","ns":28.51,"ew":47.96,"dest":{"cell":"BAA1002B","place":"outdoor","ns":27.14,"ew":47.36},"id":4180}, + {"name":"Olthoi Brood Hive","type":"Portal","wcid":24911,"cell":"BBBF0000","place":"outdoor","ns":51.22,"ew":48.09,"dest":{"cell":"57730439","place":"dungeon","name":"Olthoi Brood Hive"},"minLevel":20,"id":4181}, + {"name":"Frost Ziggurat","type":"Portal","wcid":21413,"cell":"BBC6000F","place":"outdoor","ns":57.08,"ew":47.78,"dest":{"cell":"5A460104","place":"dungeon","name":"Frost Ziggurat"},"minLevel":80,"maxLevel":149,"quest":true,"id":4182}, + {"name":"Fire Ziggurat","type":"Portal","wcid":21411,"cell":"BBC6000F","place":"outdoor","ns":57.08,"ew":47.75,"dest":{"cell":"59460104","place":"dungeon","name":"Fire Ziggurat"},"minLevel":60,"maxLevel":79,"quest":true,"id":4183}, + {"name":"Acid Ziggurat","type":"Portal","wcid":21399,"cell":"BBC60007","place":"outdoor","ns":57.08,"ew":47.73,"dest":{"cell":"58460104","place":"dungeon","name":"Acid Ziggurat"},"minLevel":40,"maxLevel":59,"quest":true,"id":4184}, + {"name":"Lightning Ziggurat","type":"Portal","wcid":21425,"cell":"BBC60007","place":"outdoor","ns":57.08,"ew":47.7,"dest":{"cell":"57460104","place":"dungeon","name":"Lightning Ziggurat"},"minLevel":20,"maxLevel":39,"quest":true,"id":4185}, + {"name":"Prismatic Ziggurat","type":"Portal","wcid":46924,"cell":"BBC6000F","place":"outdoor","ns":57.08,"ew":47.82,"dest":{"cell":"58510104","place":"dungeon","name":"Prismatic Ziggurat"},"minLevel":150,"quest":true,"id":4186}, + {"name":"Mainland Portal","type":"Portal","wcid":9072,"cell":"BC11015A","place":"building","ns":-88.04,"ew":48.8,"dest":{"cell":"BA110101","place":"dungeon","name":"Mainland"},"id":4187}, + {"name":"Lakeside Lair","type":"Portal","wcid":2084,"cell":"BC970000","place":"outdoor","ns":18.98,"ew":48.47,"dest":{"cell":"01AF012C","place":"dungeon","name":"Lakeside Lair"},"id":4188}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"BC9F0000","place":"outdoor","ns":25.48,"ew":48.72,"dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"id":4189}, + {"name":"Effigy Foundry Portal","type":"Portal","wcid":19718,"cell":"BC9F0165","place":"building","ns":25.73,"ew":49.21,"dest":{"cell":"545901B0","place":"dungeon","name":"Effigy Foundry"},"id":4190}, + {"name":"Cragstone Meeting Hall Portal","type":"Portal","wcid":6092,"cell":"BC9F0169","place":"building","ns":26.0,"ew":49.1,"dest":{"cell":"01210126","place":"dungeon","name":"Cragstone Meeting Hall"},"id":4191}, + {"name":"Portal to Town Network","type":"Portal","wcid":43065,"cell":"BC9F003C","place":"outdoor","ns":25.58,"ew":49.19,"dest":{"cell":"00070143","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4192}, + {"name":"Destroyed Portal to Zaikhal","type":"Portal","wcid":1032,"cell":"BCA00000","place":"outdoor","ns":26.38,"ew":48.57,"dest":{"cell":"80900013","place":"outdoor","ns":13.48,"ew":0.72},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4193}, + {"name":"Vesayen Isles Portal","type":"Portal","wcid":8618,"cell":"BCCC0000","place":"outdoor","ns":61.68,"ew":48.56,"dest":{"cell":"E5240007","place":"outdoor","ns":-72.51,"ew":81.3},"id":4194}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"BD810000","place":"outdoor","ns":1.69,"ew":49.94,"dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4195}, + {"name":"Isle of Tears Portal","type":"Portal","wcid":1112,"cell":"BD9E0000","place":"outdoor","ns":25.23,"ew":49.89,"dest":{"cell":"C09B0015","place":"outdoor","ns":22.55,"ew":51.92},"id":4196}, + {"name":"Eldrytch Web Stronghold","type":"Portal","wcid":37385,"cell":"BDA00023","place":"outdoor","ns":26.28,"ew":49.67,"dest":{"cell":"00B80294","place":"dungeon","name":"Eldrytch Web Stronghold"},"minLevel":180,"quest":true,"desc":"You must be a member of the Society of the Eldrytch Web to enter this Portal.","id":4197}, + {"name":"Eldrytch Web Gauntlet","type":"Portal","wcid":53447,"cell":"BDA00022","place":"outdoor","ns":26.24,"ew":49.72,"dest":{"cell":"596B0110","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"id":4198}, + {"name":"Mite Tunnels","type":"Portal","wcid":3626,"cell":"BDAF0100","place":"building","ns":38.66,"ew":50.0,"dest":{"cell":"01A401E6","place":"dungeon","name":"Mite Tunnels"},"id":4199}, + {"name":"Eotensfang Portal","type":"Portal","wcid":1103,"cell":"BDD00000","place":"outdoor","ns":64.98,"ew":49.3,"dest":{"cell":"CBB40003","place":"outdoor","ns":42.33,"ew":60.48},"id":4200}, + {"name":"Bandit Castle Prison","type":"Portal","wcid":1306,"cell":"BDD20128","place":"building","ns":66.4,"ew":49.94,"dest":{"cell":"01E20231","place":"dungeon","name":"Bandit Castle Prison"},"id":4201}, + {"name":"KEEP OUT!","type":"Portal","wcid":31342,"cell":"BDD20036","place":"outdoor","ns":66.59,"ew":49.89,"dest":{"cell":"2B200024","place":"outdoor","ns":-75.98,"ew":-67.08},"quest":true,"id":4202}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"BDD20033","place":"outdoor","ns":66.29,"ew":49.94,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4203}, + {"name":"Destroyed Portal to Yanshi","type":"Portal","wcid":1029,"cell":"BDF10101","place":"building","ns":91.3,"ew":49.7,"dest":{"cell":"B9720021","place":"outdoor","ns":-10.74,"ew":46.55},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4204}, + {"name":"Banderling Conquest Dungeon","type":"Portal","wcid":8379,"cell":"BE5B0000","place":"outdoor","ns":-29.03,"ew":50.47,"dest":{"cell":"02C80258","place":"dungeon","name":"Banderling Conquest Dungeon"},"id":4205}, + {"name":"Tainted Grotto","type":"Portal","wcid":25227,"cell":"BE690000","place":"outdoor","ns":-17.79,"ew":50.6,"dest":{"cell":"634C03D3","place":"dungeon","name":"Tainted Grotto"},"id":4206}, + {"name":"Cells of the Black Book","type":"Portal","wcid":32674,"cell":"BE72010B","place":"dungeon","dest":{"cell":"008902DC","place":"dungeon"},"minLevel":60,"quest":true,"desc":"This dungeon is quest restricted and PK restricted. Speak with Hassha about gaining entry. In a dungeon (landblock BE72).","id":4207}, + {"name":"Cells of the Black Book","type":"Portal","wcid":32675,"cell":"BE72010B","place":"dungeon","dest":{"cell":"008902F5","place":"dungeon"},"minLevel":60,"quest":true,"desc":"This dungeon is quest restricted and PK restricted. Speak with Hassha about gaining entry. In a dungeon (landblock BE72).","id":4208}, + {"name":"Cells of the Black Book","type":"Portal","wcid":32676,"cell":"BE720108","place":"dungeon","dest":{"cell":"008902FF","place":"dungeon"},"minLevel":60,"quest":true,"desc":"This dungeon is quest restricted and PK restricted. Speak with Hassha about gaining entry. In a dungeon (landblock BE72).","id":4209}, + {"name":"Cells of the Black Book","type":"Portal","wcid":32677,"cell":"BE720108","place":"dungeon","dest":{"cell":"00890318","place":"dungeon"},"minLevel":60,"quest":true,"desc":"This dungeon is quest restricted and PK restricted. Speak with Hassha about gaining entry. In a dungeon (landblock BE72).","id":4210}, + {"name":"Hollow Lair near Lytelthorpe","type":"Portal","wcid":12692,"cell":"BE7C0000","place":"outdoor","ns":-2.2,"ew":50.75,"dest":{"cell":"039C0202","place":"dungeon","name":"Hollow Lair near Lytelthorpe"},"minLevel":20,"id":4211}, + {"name":"Maedew Portal","type":"Portal","wcid":12516,"cell":"BE820000","place":"outdoor","ns":2.2,"ew":50.33,"dest":{"cell":"D0740003","place":"outdoor","ns":-8.87,"ew":64.53},"id":4212}, + {"name":"East Lytelthorpe Settlement Portal","type":"Portal","wcid":12490,"cell":"BE820000","place":"outdoor","ns":2.24,"ew":50.36,"dest":{"cell":"C77F0036","place":"outdoor","ns":0.2,"ew":57.93},"id":4213}, + {"name":"South Lytelthorpe Portal","type":"Portal","wcid":12552,"cell":"BE820000","place":"outdoor","ns":2.26,"ew":50.4,"dest":{"cell":"C27C0035","place":"outdoor","ns":-2.29,"ew":53.9},"id":4214}, + {"name":"North Yanshi Plains Settlement Portal","type":"Portal","wcid":12535,"cell":"BE820000","place":"outdoor","ns":2.17,"ew":50.33,"dest":{"cell":"BB790020","place":"outdoor","ns":-4.4,"ew":48.01},"id":4215}, + {"name":"Neu Gerz Villas Portal","type":"Portal","wcid":13114,"cell":"BE820000","place":"outdoor","ns":2.13,"ew":50.37,"dest":{"cell":"C6760025","place":"outdoor","ns":-7.13,"ew":56.88},"id":4216}, + {"name":"North Lytelthorpe Villas Portal","type":"Portal","wcid":13115,"cell":"BE820000","place":"outdoor","ns":2.24,"ew":50.46,"dest":{"cell":"BC87002C","place":"outdoor","ns":6.38,"ew":48.98},"id":4217}, + {"name":"Enchanter's Meadow Portal","type":"Portal","wcid":13103,"cell":"BE820000","place":"outdoor","ns":2.11,"ew":50.4,"dest":{"cell":"AD860025","place":"outdoor","ns":5.71,"ew":36.88},"id":4218}, + {"name":"Riverbend Cottages Portal","type":"Portal","wcid":13122,"cell":"BE820000","place":"outdoor","ns":2.21,"ew":50.48,"dest":{"cell":"D07B0011","place":"outdoor","ns":-3.5,"ew":64.74},"id":4219}, + {"name":"Jin-Lai Stronghold Portal","type":"Portal","wcid":15165,"cell":"BE820000","place":"outdoor","ns":2.1,"ew":50.43,"dest":{"cell":"CB760004","place":"outdoor","ns":-7.19,"ew":60.51},"id":4220}, + {"name":"Asbel Domain Portal","type":"Portal","wcid":15143,"cell":"BE820000","place":"outdoor","ns":2.07,"ew":50.46,"dest":{"cell":"B17E0013","place":"outdoor","ns":-0.91,"ew":39.88},"id":4221}, + {"name":"Osric Cottages Portal","type":"Portal","wcid":15181,"cell":"BE820000","place":"outdoor","ns":2.18,"ew":50.51,"dest":{"cell":"B286001B","place":"outdoor","ns":5.52,"ew":40.79},"id":4222}, + {"name":"Darawyll Village Portal","type":"Portal","wcid":15150,"cell":"BE820000","place":"outdoor","ns":2.16,"ew":50.54,"dest":{"cell":"B28B0013","place":"outdoor","ns":9.51,"ew":40.7},"id":4223}, + {"name":"Devana Portal","type":"Portal","wcid":15151,"cell":"BE820000","place":"outdoor","ns":2.23,"ew":50.3,"dest":{"cell":"A97D001B","place":"outdoor","ns":-1.66,"ew":33.57},"id":4224}, + {"name":"Stable Rift","type":"Portal","wcid":10792,"cell":"BE890000","place":"outdoor","ns":8.01,"ew":50.36,"dest":{"cell":"029002C9","place":"dungeon","name":"Stable Rift"},"minLevel":20,"quest":true,"id":4225}, + {"name":"Small Icecave","type":"Portal","wcid":1327,"cell":"BED30000","place":"outdoor","ns":67.56,"ew":50.33,"dest":{"cell":"01E60250","place":"dungeon","name":"Small Icecave"},"id":4226}, + {"name":"Temple of N'cthail","type":"Portal","wcid":33295,"cell":"BED70024","place":"outdoor","ns":70.44,"ew":50.54,"dest":{"cell":"C3E30019","place":"outdoor","ns":79.69,"ew":54.4},"minLevel":100,"id":4227}, + {"name":"Singular Chorizite Repository","type":"Portal","wcid":12290,"cell":"BF1E0000","place":"outdoor","ns":-77.32,"ew":51.6,"dest":{"cell":"03A0027F","place":"dungeon","name":"Singular Chorizite Repository"},"minLevel":35,"id":4228}, + {"name":"Lost Distillery Portal","type":"Portal","wcid":4895,"cell":"BF7E0102","place":"dungeon","dest":{"cell":"016401F1","place":"dungeon"},"minLevel":40,"desc":"In a dungeon (landblock BF7E).","id":4229}, + {"name":"Mannikin Foundry Portal","type":"Portal","wcid":19717,"cell":"BF80017C","place":"building","ns":0.66,"ew":51.41,"dest":{"cell":"545A013C","place":"dungeon","name":"Mannikin Foundry"},"id":4230}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"BF800000","place":"outdoor","ns":0.63,"ew":51.61,"dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"id":4231}, + {"name":"Lytelthorpe Meeting Hall Portal","type":"Portal","wcid":6099,"cell":"BF800191","place":"building","ns":0.81,"ew":51.6,"dest":{"cell":"01280126","place":"dungeon","name":"Lytelthorpe Meeting Hall"},"id":4232}, + {"name":"Portal to Town Network","type":"Portal","wcid":43065,"cell":"BF80002B","place":"outdoor","ns":0.74,"ew":51.43,"dest":{"cell":"00070143","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4233}, + {"name":"Destroyed Portal to Yaraq","type":"Portal","wcid":1030,"cell":"C0260101","place":"building","ns":-70.98,"ew":52.3,"dest":{"cell":"7D64000D","place":"outdoor","ns":-21.51,"ew":-1.82},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4234}, + {"name":"Swamp Ruin","type":"Portal","wcid":2344,"cell":"C0600101","place":"dungeon","dest":{"cell":"01C50138","place":"dungeon"},"minLevel":6,"desc":"In a dungeon (landblock C060).","id":4235}, + {"name":"Destroyed Portal to Rithwic","type":"Portal","wcid":1025,"cell":"C0820000","place":"outdoor","ns":2.3,"ew":51.98,"dest":{"cell":"C98C0028","place":"outdoor","ns":10.84,"ew":59.32},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4236}, + {"name":"Cragstone Portal","type":"Portal","wcid":1113,"cell":"C09B0000","place":"outdoor","ns":22.21,"ew":51.91,"dest":{"cell":"BD9F0039","place":"outdoor","ns":25.34,"ew":49.99},"id":4237}, + {"name":"Renegade Garrison","type":"Portal","wcid":25496,"cell":"C0B60000","place":"outdoor","ns":44.34,"ew":51.94,"dest":{"cell":"60490326","place":"dungeon","name":"Renegade Garrison"},"minLevel":40,"quest":true,"id":4238}, + {"name":"Destroyed Baishi Portal","type":"Portal","wcid":4037,"cell":"C1320000","place":"outdoor","ns":-61.53,"ew":52.67,"dest":{"cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4239}, + {"name":"Folthid Cellar Portal","type":"Portal","wcid":5606,"cell":"C1740105","place":"underground","ns":-8.61,"ew":52.83,"dest":{"cell":"013B0333","place":"dungeon"},"minLevel":10,"id":4240}, + {"name":"Dungeon Maggreth Portal","type":"Portal","wcid":4166,"cell":"C1840000","place":"outdoor","ns":3.73,"ew":52.6,"dest":{"cell":"014F01B9","place":"dungeon","name":"Dungeon Maggreth"},"id":4241}, + {"name":"Olthoi Tunnels","type":"Portal","wcid":3649,"cell":"C1BB0000","place":"outdoor","ns":48.07,"ew":52.98,"dest":{"cell":"018D01C5","place":"dungeon","name":"Olthoi Tunnels"},"minLevel":15,"id":4242}, + {"name":"Olthoi Horde Nest","type":"Portal","wcid":7254,"cell":"C1CF0000","place":"outdoor","ns":64.34,"ew":52.77,"dest":{"cell":"02FD03A6","place":"dungeon","name":"Olthoi Horde Nest"},"minLevel":30,"id":4243}, + {"name":"Burun Burrow","type":"Portal","wcid":27477,"cell":"C25D0100","place":"dungeon","dest":{"cell":"624702B3","place":"dungeon"},"quest":true,"desc":"In a dungeon (landblock C25D).","id":4244}, + {"name":"Destroyed Portal to Bluespire","type":"Portal","wcid":11953,"cell":"C2800000","place":"outdoor","ns":1.2,"ew":54.0,"dest":{"cell":"21B00017","place":"outdoor","ns":39.54,"ew":-75.35},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4245}, + {"name":"Setab's Barracks Portal","type":"Portal","wcid":7208,"cell":"C2820000","place":"outdoor","ns":2.73,"ew":53.49,"dest":{"cell":"010601AF","place":"dungeon","name":"Setab's Barracks"},"id":4246}, + {"name":"Underground City Portal","type":"Portal","wcid":1099,"cell":"C29A0000","place":"outdoor","ns":21.36,"ew":53.94,"dest":{"cell":"01E901AD","place":"dungeon","name":"Underground City"},"id":4247}, + {"name":"Empyrean Foundry Portal","type":"Portal","wcid":6084,"cell":"C3600000","place":"outdoor","ns":-25.1,"ew":54.13,"dest":{"cell":"013602B6","place":"dungeon","name":"Empyrean Foundry"},"minLevel":100,"id":4248}, + {"name":"Corrupted Catacombs","type":"Portal","wcid":38400,"cell":"C3610005","place":"outdoor","ns":-23.95,"ew":54.09,"dest":{"cell":"00BA0348","place":"dungeon","name":"Corrupted Catacombs"},"minLevel":180,"id":4249}, + {"name":"Abandoned Mine","type":"Portal","wcid":1595,"cell":"C3AB0000","place":"outdoor","ns":34.9,"ew":54.51,"dest":{"cell":"01C9022D","place":"dungeon","name":"Abandoned Mine"},"id":4250}, + {"name":"Vault of Eternal Slumber","type":"Portal","wcid":33302,"cell":"C3E30128","place":"building","ns":80.0,"ew":54.4,"dest":{"cell":"004E055A","place":"dungeon","name":"Vault of Eternal Slumber"},"minLevel":100,"quest":true,"desc":"This portal is warded against those who have not earned the right to access the sacred Vault of Eternal Slumber.","id":4251}, + {"name":"Eastern Temple Catacombs","type":"Portal","wcid":33303,"cell":"C3E3002C","place":"outdoor","ns":80.0,"ew":54.57,"dest":{"cell":"004D06E5","place":"dungeon","name":"Eastern Temple Catacombs"},"minLevel":100,"quest":true,"id":4252}, + {"name":"Northern Temple Catacombs","type":"Portal","wcid":33305,"cell":"C3E3001E","place":"outdoor","ns":80.17,"ew":54.4,"dest":{"cell":"004E054A","place":"dungeon","name":"Vault of Eternal Slumber"},"minLevel":100,"quest":true,"id":4253}, + {"name":"Western Temple Catacombs","type":"Portal","wcid":33306,"cell":"C3E3000C","place":"outdoor","ns":80.0,"ew":54.23,"dest":{"cell":"004D06E6","place":"dungeon","name":"Eastern Temple Catacombs"},"minLevel":100,"quest":true,"id":4254}, + {"name":"Temple Exit","type":"Portal","wcid":33304,"cell":"C3E3001F","place":"outdoor","ns":80.31,"ew":54.4,"dest":{"cell":"BED70024","place":"outdoor","ns":70.39,"ew":50.49},"id":4255}, + {"name":"Lugian Quarry Portal","type":"Portal","wcid":7610,"cell":"C42E0000","place":"outdoor","ns":-64.38,"ew":55.48,"dest":{"cell":"02E80232","place":"dungeon","name":"Lugian Quarry"},"id":4256}, + {"name":"Serac Vault Portal","type":"Portal","wcid":6397,"cell":"C4340000","place":"outdoor","ns":-59.95,"ew":54.96,"dest":{"cell":"01170140","place":"dungeon","name":"Serac Vault"},"id":4257}, + {"name":"Trialos","type":"Portal","wcid":2341,"cell":"C4360000","place":"outdoor","ns":-58.68,"ew":55.32,"dest":{"cell":"01C30105","place":"dungeon","name":"Trialos"},"id":4258}, + {"name":"Fenmalain Vestibule Portal","type":"Portal","wcid":7941,"cell":"C4440000","place":"outdoor","ns":-46.91,"ew":55.24,"dest":{"cell":"02DB0306","place":"dungeon","name":"Fenmalain Vestibule"},"minLevel":20,"id":4259}, + {"name":"Trothyr's Rest","type":"Portal","wcid":1122,"cell":"C48C0000","place":"outdoor","ns":10.35,"ew":54.89,"dest":{"cell":"01FD02B5","place":"dungeon","name":"Trothyr's Rest"},"id":4260}, + {"name":"A Ruin","type":"Portal","wcid":2067,"cell":"C48D0000","place":"outdoor","ns":11.49,"ew":55.04,"dest":{"cell":"01B8012E","place":"dungeon","name":"A Ruin"},"id":4261}, + {"name":"A Ruin","type":"Portal","wcid":1603,"cell":"C4A80000","place":"outdoor","ns":32.97,"ew":54.92,"dest":{"cell":"0187011D","place":"dungeon","name":"A Ruin"},"id":4262}, + {"name":"Wedding Trials Dungeon","type":"Portal","wcid":14928,"cell":"C4A80000","place":"outdoor","ns":32.8,"ew":55.23,"dest":{"cell":"52690164","place":"dungeon","name":"Wedding Trials Dungeon"},"id":4263}, + {"name":"Soul Hunter's Lair","type":"Portal","wcid":34318,"cell":"C55C000F","place":"outdoor","ns":-27.67,"ew":55.77,"dest":{"cell":"007C02B2","place":"dungeon","name":"Soul Hunter's Lair"},"minLevel":60,"quest":true,"desc":"This dungeon is quest-restricted. See Hasin Lin in Sawato for more information.","id":4264}, + {"name":"Forgotten Temple Portal","type":"Portal","wcid":4961,"cell":"C5800102","place":"dungeon","dest":{"cell":"015101FE","place":"dungeon"},"desc":"In a dungeon (landblock C580).","id":4265}, + {"name":"Mammet Foundry Portal","type":"Portal","wcid":19716,"cell":"C5A6011B","place":"building","ns":30.92,"ew":56.4,"dest":{"cell":"5458025F","place":"dungeon","name":"Mammet Foundry"},"id":4266}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43569,"cell":"C5A70102","place":"dungeon","dest":{"cell":"E5CE0037","place":"outdoor","ns":63.51,"ew":81.86},"desc":"In a dungeon (landblock C5A7).","id":4267}, + {"name":"Arwic Meeting Hall Portal","type":"Portal","wcid":6090,"cell":"C5A90101","place":"building","ns":33.57,"ew":55.78,"dest":{"cell":"011F0126","place":"dungeon","name":"Arwic Meeting Hall"},"id":4268}, + {"name":"Destroyed Portal to Tou-Tou","type":"Portal","wcid":4568,"cell":"C5A90000","place":"outdoor","ns":33.84,"ew":56.42,"dest":{"cell":"F5590034","place":"outdoor","ns":-30.41,"ew":94.69},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4269}, + {"name":"Mountain Shortcut","type":"Portal","wcid":1904,"cell":"C5AB0000","place":"outdoor","ns":34.89,"ew":56.01,"dest":{"cell":"C5B2001E","place":"outdoor","ns":40.98,"ew":56.03},"id":4270}, + {"name":"Destroyed Portal to Arwic","type":"Portal","wcid":1013,"cell":"C5B20000","place":"outdoor","ns":40.93,"ew":55.79,"dest":{"cell":"C6A90009","place":"outdoor","ns":33.27,"ew":56.65},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4271}, + {"name":"Olthoi Brood Hive","type":"Portal","wcid":24914,"cell":"C5D00000","place":"outdoor","ns":64.53,"ew":56.2,"dest":{"cell":"584B04F1","place":"dungeon","name":"Olthoi Brood Hive"},"minLevel":80,"id":4272}, + {"name":"Tanada Temple of Black Water","type":"Portal","wcid":87683,"cell":"C6610128","place":"underground","ns":-23.49,"ew":57.21,"dest":{"cell":"00CD0159","place":"dungeon"},"quest":true,"id":4273}, + {"name":"Dungeon Gallery Tower","type":"Portal","wcid":2076,"cell":"C68C0000","place":"outdoor","ns":10.71,"ew":56.8,"dest":{"cell":"01AD0116","place":"dungeon","name":"Dungeon Gallery Tower"},"id":4274}, + {"name":"Arwic Mines Portal","type":"Portal","wcid":1088,"cell":"C6A90000","place":"outdoor","ns":33.83,"ew":56.83,"dest":{"cell":"01EF03DD","place":"dungeon","name":"Arwic Mines"},"id":4275}, + {"name":"Destroyed Al-Jalima Portal","type":"Portal","wcid":5486,"cell":"C6A90000","place":"outdoor","ns":33.6,"ew":57.18,"dest":{"cell":"8588002C","place":"outdoor","ns":7.25,"ew":4.95},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4276}, + {"name":"Portal to Town Network","type":"Portal","wcid":43065,"cell":"C6A9001B","place":"outdoor","ns":33.49,"ew":56.78,"dest":{"cell":"00070143","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4277}, + {"name":"Mite Maze Portal","type":"Portal","wcid":1121,"cell":"C6B20000","place":"outdoor","ns":41.1,"ew":57.24,"dest":{"cell":"01F801D4","place":"dungeon","name":"Mite Maze"},"id":4278}, + {"name":"Trial of the Deep","type":"Portal","wcid":37070,"cell":"C6EA003B","place":"outdoor","ns":85.47,"ew":57.15,"dest":{"cell":"00A90122","place":"dungeon","name":"Trial of the Deep"},"id":4279}, + {"name":"Mines of Despair","type":"Portal","wcid":4053,"cell":"C7210100","place":"building","ns":-75.48,"ew":57.26,"dest":{"cell":"01880307","place":"dungeon","name":"Mines of Despair"},"minLevel":14,"id":4280}, + {"name":"Gateway to the Halls of Metos","type":"Portal","wcid":34438,"cell":"C770010D","place":"underground","ns":-11.58,"ew":57.96,"dest":{"cell":"02F50297","place":"dungeon","name":"Halls of Metos"},"minLevel":15,"desc":"This portal leads to the Halls of Metos near Wai Jhou. The area surrounding this portal is extremely dangerous for inexperienced adventurers - tread with caution.","id":4281}, + {"name":"Destroyed Portal to Holtburg","type":"Portal","wcid":1020,"cell":"C78C0000","place":"outdoor","ns":10.13,"ew":57.35,"dest":{"cell":"A9B40019","place":"outdoor","ns":42.08,"ew":33.6},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4282}, + {"name":"A Drudge Nest","type":"Portal","wcid":1335,"cell":"C78D0000","place":"outdoor","ns":10.94,"ew":57.49,"dest":{"cell":"01D80108","place":"dungeon","name":"A Drudge Nest"},"id":4283}, + {"name":"Surface","type":"Portal","wcid":1091,"cell":"C7B70455","place":"dungeon","dest":{"cell":"D8CA0014","place":"outdoor","ns":60.03,"ew":71.09},"desc":"In a dungeon (landblock C7B7).","id":4284}, + {"name":"Surface","type":"Portal","wcid":1091,"cell":"C7B70105","place":"dungeon","dest":{"cell":"D8CA0014","place":"outdoor","ns":60.03,"ew":71.09},"desc":"In a dungeon (landblock C7B7).","id":4285}, + {"name":"Paradox-Touched Olthoi Queen's Lair","type":"Portal","wcid":35935,"cell":"C7B703B5","place":"dungeon","dest":{"cell":"C7B7011B","place":"dungeon"},"minLevel":120,"quest":true,"desc":"This portal seems to be warded against those who are not attuned to it. In a dungeon (landblock C7B7).","id":4286}, + {"name":"Paradox Queen's Lair","type":"Portal","wcid":72092,"cell":"C7B70104","place":"dungeon","dest":{"cell":"C7B7011B","place":"dungeon"},"desc":"In a dungeon (landblock C7B7).","id":4287}, + {"name":"Portal to Arwic","type":"Portal","wcid":42819,"cell":"C7E3000A","place":"outdoor","ns":79.8,"ew":57.37,"dest":{"cell":"C6A90009","place":"outdoor","ns":33.27,"ew":56.65},"desc":"This portal goes to Arwic, a walled Aluvian town that has fully recovered from a devastating attack by a Shadow Spire. This is a good town for characters over level 20.","id":4288}, + {"name":"Vissidal Island","type":"Portal","wcid":32127,"cell":"C7E90017","place":"outdoor","ns":85.13,"ew":57.53,"dest":{"cell":"C8E2002A","place":"outdoor","ns":79.03,"ew":58.62},"minLevel":130,"quest":true,"desc":"You must obtain the blessing of the Watcher of the Deep before you may use this portal.","id":4289}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43705,"cell":"C7EA0102","place":"dungeon","dest":{"cell":"E3D60032","place":"outdoor","ns":69.4,"ew":80.31},"desc":"In Olthoi Tunnel.","id":4290}, + {"name":"Old Warehouse","type":"Portal","wcid":4933,"cell":"C88A0100","place":"dungeon","dest":{"cell":"0165015B","place":"dungeon"},"minLevel":40,"desc":"In a dungeon (landblock C88A).","id":4291}, + {"name":"Mannikin Foundry Portal","type":"Portal","wcid":19717,"cell":"C88C0170","place":"building","ns":10.54,"ew":58.27,"dest":{"cell":"545A013C","place":"dungeon","name":"Mannikin Foundry"},"id":4292}, + {"name":"Martine's Retreat","type":"Portal","wcid":20919,"cell":"C88C0000","place":"outdoor","ns":10.62,"ew":58.27,"dest":{"cell":"56600187","place":"dungeon","name":"Martine's Retreat"},"id":4293}, + {"name":"Portal to Town Network","type":"Portal","wcid":43065,"cell":"C88C0016","place":"outdoor","ns":10.55,"ew":58.27,"dest":{"cell":"00070143","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4294}, + {"name":"Rithwic Meeting Hall Portal","type":"Portal","wcid":6103,"cell":"C88D0101","place":"building","ns":10.91,"ew":58.2,"dest":{"cell":"012C0126","place":"dungeon","name":"Rithwic Meeting Hall"},"id":4295}, + {"name":"Cave","type":"Portal","wcid":1331,"cell":"C8960000","place":"outdoor","ns":18.36,"ew":58.11,"dest":{"cell":"01F1010A","place":"dungeon","name":"Cave"},"id":4296}, + {"name":"Lair of Death","type":"Portal","wcid":2086,"cell":"C8B30000","place":"outdoor","ns":41.99,"ew":58.11,"dest":{"cell":"01AA01EC","place":"dungeon","name":"Lair of Death"},"minLevel":15,"id":4297}, + {"name":"Temple of the Stirring Shadow","type":"Portal","wcid":32508,"cell":"C8DC0033","place":"outdoor","ns":74.27,"ew":58.67,"dest":{"cell":"004502C2","place":"dungeon","name":"Temple of the Stirring Shadow"},"minLevel":80,"quest":true,"id":4298}, + {"name":"Lost Garden Ruins","type":"Portal","wcid":1601,"cell":"C92D0100","place":"dungeon","dest":{"cell":"01B102BD","place":"dungeon"},"desc":"In a dungeon (landblock C92D).","id":4299}, + {"name":"Mammet Foundry Portal","type":"Portal","wcid":19716,"cell":"C95B0168","place":"building","ns":-28.64,"ew":59.3,"dest":{"cell":"5458025F","place":"dungeon","name":"Mammet Foundry"},"id":4300}, + {"name":"Sawato Meeting Hall Portal","type":"Portal","wcid":6105,"cell":"C95B0175","place":"building","ns":-28.48,"ew":59.3,"dest":{"cell":"012E0126","place":"dungeon","name":"Sawato Meeting Hall"},"id":4301}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"C95B002D","place":"outdoor","ns":-28.73,"ew":59.39,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4302}, + {"name":"Destroyed Portal to Shoushi","type":"Portal","wcid":1027,"cell":"C98D0000","place":"outdoor","ns":11.04,"ew":59.26,"dest":{"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4303}, + {"name":"Destroyed Portal to Greenspire","type":"Portal","wcid":11954,"cell":"C98D0000","place":"outdoor","ns":11.12,"ew":59.58,"dest":{"cell":"2BB5003C","place":"outdoor","ns":43.21,"ew":-66.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4304}, + {"name":"Rithwic Crypt","type":"Portal","wcid":1432,"cell":"C9900000","place":"outdoor","ns":14.03,"ew":59.11,"dest":{"cell":"01CD0144","place":"dungeon","name":"Rithwic Crypt"},"id":4305}, + {"name":"East Span Way Settlement Portal","type":"Portal","wcid":12493,"cell":"C9A80000","place":"outdoor","ns":32.86,"ew":59.4,"dest":{"cell":"BBA8003D","place":"outdoor","ns":32.87,"ew":48.4},"id":4306}, + {"name":"Southeast Arwic Settlement Portal","type":"Portal","wcid":12549,"cell":"C9A80000","place":"outdoor","ns":32.87,"ew":59.36,"dest":{"cell":"CAA30003","place":"outdoor","ns":28.74,"ew":59.73},"id":4307}, + {"name":"Cape Feirgard Cottages Portal","type":"Portal","wcid":12482,"cell":"C9A80000","place":"outdoor","ns":32.91,"ew":59.36,"dest":{"cell":"D1A50029","place":"outdoor","ns":30.13,"ew":65.81},"id":4308}, + {"name":"Sennon Valley Retreat Portal","type":"Portal","wcid":12543,"cell":"C9A80000","place":"outdoor","ns":32.94,"ew":59.38,"dest":{"cell":"CFC0001C","place":"outdoor","ns":52.0,"ew":64.04},"id":4309}, + {"name":"Far Claw Villas Portal","type":"Portal","wcid":13104,"cell":"C9A80000","place":"outdoor","ns":32.87,"ew":59.43,"dest":{"cell":"C9C30034","place":"outdoor","ns":54.42,"ew":59.52},"id":4310}, + {"name":"South Beach Pass Villas Portal","type":"Portal","wcid":13090,"cell":"C9A80000","place":"outdoor","ns":32.96,"ew":59.41,"dest":{"cell":"D1AB0018","place":"outdoor","ns":35.59,"ew":65.53},"id":4311}, + {"name":"Alvador Portal","type":"Portal","wcid":14252,"cell":"C9A80000","place":"outdoor","ns":32.86,"ew":59.47,"dest":{"cell":"B2D40016","place":"outdoor","ns":68.16,"ew":40.72},"id":4312}, + {"name":"Norvale Portal","type":"Portal","wcid":14654,"cell":"C9A80000","place":"outdoor","ns":32.99,"ew":59.43,"dest":{"cell":"C0D90024","place":"outdoor","ns":71.99,"ew":52.11},"id":4313}, + {"name":"Bleak Valley Portal","type":"Portal","wcid":14614,"cell":"C9A80000","place":"outdoor","ns":33.03,"ew":59.46,"dest":{"cell":"B3C20023","place":"outdoor","ns":53.54,"ew":41.72},"id":4314}, + {"name":"Eotensfang Cottages Portal","type":"Portal","wcid":14628,"cell":"C9A80000","place":"outdoor","ns":32.87,"ew":59.5,"dest":{"cell":"CBB20016","place":"outdoor","ns":41.02,"ew":60.7},"id":4315}, + {"name":"Lost Wish Cottages Portal","type":"Portal","wcid":14650,"cell":"C9A80000","place":"outdoor","ns":33.07,"ew":59.49,"dest":{"cell":"CEB1001C","place":"outdoor","ns":39.98,"ew":63.19},"id":4316}, + {"name":"Dagger Vale Portal","type":"Portal","wcid":15149,"cell":"C9A80000","place":"outdoor","ns":32.87,"ew":59.57,"dest":{"cell":"A3E7001D","place":"outdoor","ns":83.3,"ew":28.77},"id":4317}, + {"name":"Artifice Cottages Portal","type":"Portal","wcid":15665,"cell":"C9A80000","place":"outdoor","ns":32.88,"ew":59.61,"dest":{"cell":"8F15001D","place":"outdoor","ns":-84.71,"ew":12.78},"id":4318}, + {"name":"Baron's Domain Portal","type":"Portal","wcid":15667,"cell":"C9A80000","place":"outdoor","ns":33.1,"ew":59.52,"dest":{"cell":"AED0001D","place":"outdoor","ns":64.87,"ew":37.64},"id":4319}, + {"name":"Broken Haft Vale Portal","type":"Portal","wcid":15669,"cell":"C9A80000","place":"outdoor","ns":33.13,"ew":59.54,"dest":{"cell":"C4D9001D","place":"outdoor","ns":72.14,"ew":55.2},"id":4320}, + {"name":"Secluded Valley Cottages Portal","type":"Portal","wcid":19158,"cell":"C9A80000","place":"outdoor","ns":32.88,"ew":59.33,"dest":{"cell":"D3C0001B","place":"outdoor","ns":51.87,"ew":67.2},"id":4321}, + {"name":"Jeweled Thorn Estates Portal","type":"Portal","wcid":19150,"cell":"C9A80000","place":"outdoor","ns":32.91,"ew":59.32,"dest":{"cell":"D7C2001D","place":"outdoor","ns":53.66,"ew":70.37},"id":4322}, + {"name":"Hand-on-Sword Cottages Portal","type":"Portal","wcid":19147,"cell":"C9A80000","place":"outdoor","ns":32.84,"ew":59.34,"dest":{"cell":"D6BE0024","place":"outdoor","ns":50.44,"ew":69.72},"id":4323}, + {"name":"Defiant Prey Cottages Portal","type":"Portal","wcid":19142,"cell":"C9A80000","place":"outdoor","ns":32.82,"ew":59.36,"dest":{"cell":"82C7001E","place":"outdoor","ns":57.77,"ew":2.4},"id":4324}, + {"name":"Deep Mukkir Nest","type":"Portal","wcid":33543,"cell":"C9E40026","place":"outdoor","ns":80.97,"ew":59.3,"dest":{"cell":"005405C3","place":"dungeon","name":"Deep Mukkir Nest"},"minLevel":150,"quest":true,"id":4325}, + {"name":"Destroyed Mayoi Portal","type":"Portal","wcid":1022,"cell":"CA2C0000","place":"outdoor","ns":-66.42,"ew":60.1,"dest":{"cell":"E6320021","place":"outdoor","ns":-61.91,"ew":82.5},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4326}, + {"name":"Desert Ridge Border","type":"Portal","wcid":1903,"cell":"CA2D0101","place":"dungeon","dest":{"cell":"B178001C","place":"outdoor","ns":-5.64,"ew":39.96},"desc":"In a dungeon (landblock CA2D).","id":4327}, + {"name":"Unicorn's Grace","type":"Portal","wcid":25837,"cell":"CA4F0000","place":"outdoor","ns":-38.02,"ew":60.17,"dest":{"cell":"64490278","place":"dungeon","name":"Dragon's Power"},"minLevel":35,"quest":true,"id":4328}, + {"name":"A Mosswart Nest","type":"Portal","wcid":1333,"cell":"CA520000","place":"outdoor","ns":-36.26,"ew":60.34,"dest":{"cell":"01DF0106","place":"dungeon","name":"A Mosswart Nest"},"id":4329}, + {"name":"East Sawato Settlement Portal","type":"Portal","wcid":12492,"cell":"CA5D0000","place":"outdoor","ns":-27.23,"ew":59.89,"dest":{"cell":"CF5C0018","place":"outdoor","ns":-27.59,"ew":63.94},"id":4330}, + {"name":"Sawato Foothills Settlement Portal","type":"Portal","wcid":12542,"cell":"CA5D0000","place":"outdoor","ns":-27.18,"ew":59.89,"dest":{"cell":"CE570027","place":"outdoor","ns":-31.73,"ew":63.33},"id":4331}, + {"name":"Ayn Tayan Portal","type":"Portal","wcid":12475,"cell":"CA5D0000","place":"outdoor","ns":-27.14,"ew":59.92,"dest":{"cell":"C44E002E","place":"outdoor","ns":-39.03,"ew":55.38},"id":4332}, + {"name":"West Sawato Cottages Portal","type":"Portal","wcid":12491,"cell":"CA5D0000","place":"outdoor","ns":-27.13,"ew":59.97,"dest":{"cell":"C2580018","place":"outdoor","ns":-30.79,"ew":53.54},"id":4333}, + {"name":"Blackmire Edge Cottages Portal","type":"Portal","wcid":12477,"cell":"CA5D0000","place":"outdoor","ns":-27.18,"ew":59.99,"dest":{"cell":"B95C003E","place":"outdoor","ns":-27.84,"ew":46.82},"id":4334}, + {"name":"Jinianshi Portal","type":"Portal","wcid":12508,"cell":"CA5D0000","place":"outdoor","ns":-27.22,"ew":59.99,"dest":{"cell":"B55D0026","place":"outdoor","ns":-27.55,"ew":43.31},"id":4335}, + {"name":"North Sawato Villas Portal","type":"Portal","wcid":13116,"cell":"CA5D0000","place":"outdoor","ns":-27.26,"ew":59.92,"dest":{"cell":"C5660016","place":"outdoor","ns":-19.79,"ew":55.9},"id":4336}, + {"name":"Mire Hill Portal","type":"Portal","wcid":14273,"cell":"CA5D0000","place":"outdoor","ns":-27.27,"ew":59.97,"dest":{"cell":"CB640024","place":"outdoor","ns":-21.63,"ew":60.87},"id":4337}, + {"name":"Sclavavania Portal","type":"Portal","wcid":14281,"cell":"CA5D0000","place":"outdoor","ns":-27.21,"ew":60.03,"dest":{"cell":"D1640019","place":"outdoor","ns":-21.87,"ew":65.57},"id":4338}, + {"name":"Narsys Portal","type":"Portal","wcid":14276,"cell":"CA5D0000","place":"outdoor","ns":-27.14,"ew":59.87,"dest":{"cell":"DA6B0026","place":"outdoor","ns":-15.79,"ew":72.92},"id":4339}, + {"name":"Lo-Han Portal","type":"Portal","wcid":14646,"cell":"CA5D0000","place":"outdoor","ns":-27.26,"ew":59.86,"dest":{"cell":"C1540015","place":"outdoor","ns":-34.33,"ew":52.72},"id":4340}, + {"name":"Zin-Dai Portal","type":"Portal","wcid":14679,"cell":"CA5D0000","place":"outdoor","ns":-27.23,"ew":59.83,"dest":{"cell":"B953002C","place":"outdoor","ns":-35.21,"ew":46.58},"id":4341}, + {"name":"Empyrean Fields Cottages Portal","type":"Portal","wcid":14626,"cell":"CA5D0000","place":"outdoor","ns":-27.09,"ew":59.92,"dest":{"cell":"B54F0026","place":"outdoor","ns":-38.24,"ew":43.27},"id":4342}, + {"name":"Kuyiza Portal","type":"Portal","wcid":15167,"cell":"CA5D0000","place":"outdoor","ns":-27.16,"ew":60.03,"dest":{"cell":"B252001D","place":"outdoor","ns":-35.93,"ew":40.76},"id":4343}, + {"name":"Village Quan Portal","type":"Portal","wcid":15200,"cell":"CA5D0000","place":"outdoor","ns":-27.3,"ew":59.93,"dest":{"cell":"CE680026","place":"outdoor","ns":-18.21,"ew":63.27},"id":4344}, + {"name":"South Siege Villas Portal","type":"Portal","wcid":15193,"cell":"CA5D0000","place":"outdoor","ns":-27.26,"ew":60.01,"dest":{"cell":"DA6F001D","place":"outdoor","ns":-12.7,"ew":72.75},"id":4345}, + {"name":"Explorer's Villas Portal","type":"Portal","wcid":19144,"cell":"CA5D0000","place":"outdoor","ns":-27.08,"ew":59.97,"dest":{"cell":"D1CC001B","place":"outdoor","ns":61.55,"ew":65.65},"id":4346}, + {"name":"Incunabula Vault Portal","type":"Portal","wcid":6393,"cell":"CA620000","place":"outdoor","ns":-23.0,"ew":60.01,"dest":{"cell":"011A03F9","place":"dungeon","name":"Incunabula Vault"},"id":4347}, + {"name":"Destroyed Lytelthorpe Portal","type":"Portal","wcid":4570,"cell":"CA8B0000","place":"outdoor","ns":9.54,"ew":59.96,"dest":{"cell":"C0800007","place":"outdoor","ns":1.1,"ew":51.7},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4348}, + {"name":"Olthoi Brood Hive","type":"Portal","wcid":24633,"cell":"CAC00000","place":"outdoor","ns":51.82,"ew":59.78,"dest":{"cell":"5E4A043D","place":"dungeon","name":"Olthoi Brood Hive"},"minLevel":60,"id":4349}, + {"name":"Olthoi Brood Hive","type":"Portal","wcid":24635,"cell":"CAD80000","place":"outdoor","ns":71.2,"ew":60.22,"dest":{"cell":"5E4B0435","place":"dungeon","name":"Olthoi Brood Hive"},"minLevel":40,"id":4350}, + {"name":"Leafdawning Settlement Portal","type":"Portal","wcid":12511,"cell":"CB8A0000","place":"outdoor","ns":8.66,"ew":60.91,"dest":{"cell":"C18F0025","place":"outdoor","ns":12.94,"ew":52.91},"id":4351}, + {"name":"Meridian Cottages Portal","type":"Portal","wcid":12520,"cell":"CB8A0000","place":"outdoor","ns":8.66,"ew":60.86,"dest":{"cell":"C3870037","place":"outdoor","ns":6.67,"ew":54.68},"id":4352}, + {"name":"Gaerwel Edge Settlement Portal","type":"Portal","wcid":12500,"cell":"CB8A0000","place":"outdoor","ns":8.7,"ew":60.84,"dest":{"cell":"CE870003","place":"outdoor","ns":6.28,"ew":62.87},"id":4353}, + {"name":"Siege Road Settlement Portal","type":"Portal","wcid":12546,"cell":"CB8A0000","place":"outdoor","ns":8.73,"ew":60.84,"dest":{"cell":"D47E0030","place":"outdoor","ns":-0.44,"ew":68.23},"id":4354}, + {"name":"East Rithwic Estates Portal","type":"Portal","wcid":13102,"cell":"CB8A0000","place":"outdoor","ns":8.67,"ew":60.94,"dest":{"cell":"D28C0014","place":"outdoor","ns":10.42,"ew":66.33},"id":4355}, + {"name":"West Rithwic Estates Portal","type":"Portal","wcid":13140,"cell":"CB8A0000","place":"outdoor","ns":8.69,"ew":60.96,"dest":{"cell":"BB8E0023","place":"outdoor","ns":11.93,"ew":48.08},"id":4356}, + {"name":"Slinker Meadows Portal","type":"Portal","wcid":13129,"cell":"CB8A0000","place":"outdoor","ns":8.77,"ew":60.83,"dest":{"cell":"CA830024","place":"outdoor","ns":3.2,"ew":60.1},"id":4357}, + {"name":"Siege Road Villas Portal","type":"Portal","wcid":14282,"cell":"CB8A0000","place":"outdoor","ns":8.8,"ew":60.84,"dest":{"cell":"D1830022","place":"outdoor","ns":3.02,"ew":65.67},"id":4358}, + {"name":"King Pwyll Square Portal","type":"Portal","wcid":14639,"cell":"CB8A0000","place":"outdoor","ns":8.72,"ew":60.99,"dest":{"cell":"AD8B0024","place":"outdoor","ns":9.62,"ew":36.87},"id":4359}, + {"name":"Glystaene Cottages Portal","type":"Portal","wcid":15159,"cell":"CB8A0000","place":"outdoor","ns":8.83,"ew":60.87,"dest":{"cell":"A4CF0015","place":"outdoor","ns":64.09,"ew":29.51},"id":4360}, + {"name":"New Cannthalo Portal","type":"Portal","wcid":15178,"cell":"CB8A0000","place":"outdoor","ns":8.84,"ew":60.9,"dest":{"cell":"C7D2001D","place":"outdoor","ns":66.54,"ew":57.58},"id":4361}, + {"name":"Isparian Flame Estates Portal","type":"Portal","wcid":19149,"cell":"CB8A0000","place":"outdoor","ns":8.66,"ew":60.83,"dest":{"cell":"D1D00026","place":"outdoor","ns":64.97,"ew":65.67},"id":4362}, + {"name":"Bandit Castle Portal","type":"Portal","wcid":1102,"cell":"CBB40000","place":"outdoor","ns":42.46,"ew":60.51,"dest":{"cell":"BDD00006","place":"outdoor","ns":64.95,"ew":49.32},"id":4363}, + {"name":"Olthoi Brood Hive","type":"Portal","wcid":24880,"cell":"CBCA0000","place":"outdoor","ns":60.18,"ew":61.18,"dest":{"cell":"5E48043D","place":"dungeon","name":"Olthoi Brood Hive"},"minLevel":60,"id":4364}, + {"name":"Matron Hive East","type":"Portal","wcid":24433,"cell":"CC410000","place":"outdoor","ns":-49.78,"ew":61.97,"dest":{"cell":"6146036E","place":"dungeon","name":"Matron Hive East"},"minLevel":120,"id":4365}, + {"name":"A Mosswart Nest","type":"Portal","wcid":1333,"cell":"CC520000","place":"outdoor","ns":-36.19,"ew":62.0,"dest":{"cell":"01DF0106","place":"dungeon","name":"A Mosswart Nest"},"id":4366}, + {"name":"A Mosswart Nest","type":"Portal","wcid":1333,"cell":"CC5E0000","place":"outdoor","ns":-26.74,"ew":61.72,"dest":{"cell":"01DF0106","place":"dungeon","name":"A Mosswart Nest"},"id":4367}, + {"name":"North Eastham Meadow Portal","type":"Portal","wcid":12533,"cell":"CC950000","place":"outdoor","ns":17.43,"ew":61.5,"dest":{"cell":"CA9C0031","place":"outdoor","ns":22.88,"ew":60.27},"id":4368}, + {"name":"Strathelar's Watch Cottages Portal","type":"Portal","wcid":12557,"cell":"CC950000","place":"outdoor","ns":17.46,"ew":61.47,"dest":{"cell":"C7980003","place":"outdoor","ns":19.93,"ew":57.3},"id":4369}, + {"name":"Lake Blessed Cottages Portal","type":"Portal","wcid":12509,"cell":"CC950000","place":"outdoor","ns":17.5,"ew":61.44,"dest":{"cell":"C7940003","place":"outdoor","ns":16.71,"ew":57.28},"id":4370}, + {"name":"Filos' Font Cottages Portal","type":"Portal","wcid":12497,"cell":"CC950000","place":"outdoor","ns":17.53,"ew":61.43,"dest":{"cell":"CE90002A","place":"outdoor","ns":13.44,"ew":63.37},"id":4371}, + {"name":"Beach Pass Villas Portal","type":"Portal","wcid":13092,"cell":"CC950000","place":"outdoor","ns":17.58,"ew":61.43,"dest":{"cell":"D6BA001E","place":"outdoor","ns":47.37,"ew":69.64},"id":4372}, + {"name":"Dryreach Beach Manors Portal","type":"Portal","wcid":13100,"cell":"CC950000","place":"outdoor","ns":17.42,"ew":61.54,"dest":{"cell":"DE7A0035","place":"outdoor","ns":-3.87,"ew":76.27},"id":4373}, + {"name":"Desert Boundary Cottages Portal","type":"Portal","wcid":14617,"cell":"CC950000","place":"outdoor","ns":17.43,"ew":61.58,"dest":{"cell":"74880003","place":"outdoor","ns":7.06,"ew":-9.14},"id":4374}, + {"name":"Hermit Hill Cottages Portal","type":"Portal","wcid":14634,"cell":"CC950000","place":"outdoor","ns":17.46,"ew":61.6,"dest":{"cell":"A5910026","place":"outdoor","ns":14.57,"ew":30.51},"id":4375}, + {"name":"Asandra Cottages Portal","type":"Portal","wcid":15142,"cell":"CC950000","place":"outdoor","ns":17.5,"ew":61.62,"dest":{"cell":"5DC60025","place":"outdoor","ns":56.93,"ew":-27.12},"id":4376}, + {"name":"Sliver-of-BlueCottages Portal","type":"Portal","wcid":15190,"cell":"CC950000","place":"outdoor","ns":17.53,"ew":61.64,"dest":{"cell":"42AA000F","place":"outdoor","ns":34.72,"ew":-49.03},"id":4377}, + {"name":"Midhill Cottages Portal","type":"Portal","wcid":15175,"cell":"CC950000","place":"outdoor","ns":17.63,"ew":61.44,"dest":{"cell":"81E9001D","place":"outdoor","ns":84.92,"ew":1.62},"id":4378}, + {"name":"P'rnelle Acres Portal","type":"Portal","wcid":15183,"cell":"CC950000","place":"outdoor","ns":17.67,"ew":61.46,"dest":{"cell":"CBD60024","place":"outdoor","ns":69.63,"ew":60.88},"id":4379}, + {"name":"Wilderness Citadel Portal","type":"Portal","wcid":7321,"cell":"CD2A0000","place":"outdoor","ns":-67.87,"ew":62.56,"dest":{"cell":"02F20152","place":"dungeon","name":"Wilderness Citadel"},"id":4380}, + {"name":"South Shore Heights","type":"Portal","wcid":8502,"cell":"CD3B0000","place":"outdoor","ns":-54.58,"ew":62.7,"dest":{"cell":"B013003E","place":"outdoor","ns":-86.19,"ew":39.6},"minLevel":12,"id":4381}, + {"name":"Mammet Foundry Portal","type":"Portal","wcid":19716,"cell":"CD41018A","place":"building","ns":-49.44,"ew":62.51,"dest":{"cell":"5458025F","place":"dungeon","name":"Mammet Foundry"},"id":4382}, + {"name":"Atrium Residential Halls Portal","type":"Portal","wcid":19358,"cell":"CD410000","place":"outdoor","ns":-49.25,"ew":62.4,"dest":{"cell":"56610140","place":"dungeon","name":"Atrium Residential Halls"},"id":4383}, + {"name":"Baishi Meeting Hall Portal","type":"Portal","wcid":6091,"cell":"CD41018E","place":"building","ns":-49.42,"ew":62.28,"dest":{"cell":"01200126","place":"dungeon","name":"Baishi Meeting Hall"},"id":4384}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"CD410026","place":"outdoor","ns":-49.43,"ew":62.5,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4385}, + {"name":"Filos' Doom","type":"Portal","wcid":4927,"cell":"CD8E0100","place":"dungeon","dest":{"cell":"0150018A","place":"dungeon"},"desc":"In a dungeon (landblock CD8E).","id":4386}, + {"name":"Simple Tower Portal","type":"Portal","wcid":2092,"cell":"CD950000","place":"outdoor","ns":17.39,"ew":62.54,"dest":{"cell":"019D0118","place":"dungeon","name":"Simple Tower"},"id":4387}, + {"name":"Cave","type":"Portal","wcid":1331,"cell":"CD960004","place":"outdoor","ns":18.36,"ew":62.11,"dest":{"cell":"01F1010A","place":"dungeon","name":"Cave"},"id":4388}, + {"name":"Olthoi Sanctuary","type":"Portal","wcid":37066,"cell":"CDB6003E","place":"outdoor","ns":44.24,"ew":62.79,"dest":{"cell":"00AA0269","place":"dungeon","name":"Olthoi Sanctuary"},"id":4389}, + {"name":"Frost Guardian Lair","type":"Portal","wcid":21418,"cell":"CDC10000","place":"outdoor","ns":52.75,"ew":62.36,"dest":{"cell":"5743014A","place":"dungeon","name":"Frost Guardian Lair"},"minLevel":20,"maxLevel":39,"id":4390}, + {"name":"Empyrean Ice Propylaeum","type":"Portal","wcid":14500,"cell":"CDC20000","place":"outdoor","ns":53.28,"ew":62.48,"dest":{"cell":"5272014B","place":"dungeon","name":"Empyrean Ice Propylaeum"},"minLevel":25,"id":4391}, + {"name":"Chamber of Scrolls","type":"Portal","wcid":40331,"cell":"CE3E001A","place":"outdoor","ns":-52.23,"ew":63.23,"dest":{"cell":"00C901A1","place":"dungeon","name":"Chamber of Scrolls"},"minLevel":100,"quest":true,"id":4392}, + {"name":"North Baishi Cottages Portal","type":"Portal","wcid":12532,"cell":"CE400000","place":"outdoor","ns":-50.12,"ew":63.5,"dest":{"cell":"CE470022","place":"outdoor","ns":-44.97,"ew":63.3},"id":4393}, + {"name":"Oboro Portal","type":"Portal","wcid":12536,"cell":"CE400000","place":"outdoor","ns":-50.17,"ew":63.49,"dest":{"cell":"B141002B","place":"outdoor","ns":-49.73,"ew":40.2},"id":4394}, + {"name":"Tanshi Portal","type":"Portal","wcid":13136,"cell":"CE400000","place":"outdoor","ns":-50.2,"ew":63.48,"dest":{"cell":"D346001A","place":"outdoor","ns":-45.83,"ew":67.24},"id":4395}, + {"name":"Jai-Tan Dale Portal","type":"Portal","wcid":14268,"cell":"CE400000","place":"outdoor","ns":-50.08,"ew":63.48,"dest":{"cell":"C946001C","place":"outdoor","ns":-45.59,"ew":59.17},"id":4396}, + {"name":"Ring of Crystals Estates Portal","type":"Portal","wcid":13121,"cell":"CE400000","place":"outdoor","ns":-50.07,"ew":63.43,"dest":{"cell":"BF430015","place":"outdoor","ns":-47.94,"ew":51.13},"id":4397}, + {"name":"Mage's Pass Portal","type":"Portal","wcid":14271,"cell":"CE400000","place":"outdoor","ns":-50.09,"ew":63.4,"dest":{"cell":"C13D0024","place":"outdoor","ns":-52.77,"ew":52.86},"id":4398}, + {"name":"Tattered Ridge Portal","type":"Portal","wcid":14287,"cell":"CE400000","place":"outdoor","ns":-50.23,"ew":63.43,"dest":{"cell":"B634003C","place":"outdoor","ns":-60.01,"ew":44.4},"id":4399}, + {"name":"West Baishi Settlement Portal","type":"Portal","wcid":14261,"cell":"CE400000","place":"outdoor","ns":-50.14,"ew":63.38,"dest":{"cell":"C641001A","place":"outdoor","ns":-49.83,"ew":56.77},"id":4400}, + {"name":"Jasmine Meadow Portal","type":"Portal","wcid":14638,"cell":"CE400000","place":"outdoor","ns":-50.17,"ew":63.36,"dest":{"cell":"BD47001D","place":"outdoor","ns":-44.72,"ew":49.59},"id":4401}, + {"name":"Shara Portal","type":"Portal","wcid":14665,"cell":"CE400000","place":"outdoor","ns":-50.2,"ew":63.36,"dest":{"cell":"B53B0014","place":"outdoor","ns":-54.42,"ew":43.13},"id":4402}, + {"name":"Kelnen Village Portal","type":"Portal","wcid":15166,"cell":"CE400000","place":"outdoor","ns":-50.03,"ew":63.46,"dest":{"cell":"B3450012","place":"outdoor","ns":-46.6,"ew":41.5},"id":4403}, + {"name":"Lin Kiln Park Portal","type":"Portal","wcid":15170,"cell":"CE400000","place":"outdoor","ns":-50.06,"ew":63.51,"dest":{"cell":"D6420024","place":"outdoor","ns":-48.78,"ew":69.65},"id":4404}, + {"name":"Fathomless Chasm","type":"Portal","wcid":19719,"cell":"CE510000","place":"outdoor","ns":-36.92,"ew":63.36,"dest":{"cell":"545E01DD","place":"dungeon","name":"Fathomless Chasm"},"minLevel":20,"id":4405}, + {"name":"Frost Ziggurat","type":"Portal","wcid":21413,"cell":"CE940107","place":"building","ns":17.14,"ew":63.02,"dest":{"cell":"5A460104","place":"dungeon","name":"Frost Ziggurat"},"minLevel":80,"maxLevel":149,"quest":true,"id":4406}, + {"name":"Fire Ziggurat","type":"Portal","wcid":21411,"cell":"CE940107","place":"building","ns":17.1,"ew":63.02,"dest":{"cell":"59460104","place":"dungeon","name":"Fire Ziggurat"},"minLevel":60,"maxLevel":79,"quest":true,"id":4407}, + {"name":"Acid Ziggurat","type":"Portal","wcid":21399,"cell":"CE940107","place":"building","ns":17.1,"ew":62.98,"dest":{"cell":"58460104","place":"dungeon","name":"Acid Ziggurat"},"minLevel":40,"maxLevel":59,"quest":true,"id":4408}, + {"name":"Lightning Ziggurat","type":"Portal","wcid":21425,"cell":"CE940107","place":"building","ns":17.13,"ew":62.98,"dest":{"cell":"57460104","place":"dungeon","name":"Lightning Ziggurat"},"minLevel":20,"maxLevel":39,"quest":true,"id":4409}, + {"name":"Proving Grounds Low","type":"Portal","wcid":21749,"cell":"CE940102","place":"building","ns":17.16,"ew":63.02,"dest":{"cell":"574401A0","place":"dungeon","name":"Proving Grounds Low"},"minLevel":20,"maxLevel":39,"quest":true,"id":4410}, + {"name":"Proving Grounds Mid","type":"Portal","wcid":21750,"cell":"CE940102","place":"building","ns":17.2,"ew":63.02,"dest":{"cell":"584401A0","place":"dungeon","name":"Proving Grounds Mid"},"minLevel":40,"maxLevel":59,"quest":true,"id":4411}, + {"name":"Proving Grounds High","type":"Portal","wcid":21748,"cell":"CE940102","place":"building","ns":17.2,"ew":62.98,"dest":{"cell":"594401A0","place":"dungeon","name":"Proving Grounds High"},"minLevel":60,"maxLevel":79,"quest":true,"id":4412}, + {"name":"Proving Grounds Extreme","type":"Portal","wcid":21747,"cell":"CE940102","place":"building","ns":17.16,"ew":62.98,"dest":{"cell":"5A4401A0","place":"dungeon","name":"Proving Grounds Extreme"},"minLevel":80,"maxLevel":149,"quest":true,"id":4413}, + {"name":"Citadel Library","type":"Portal","wcid":21401,"cell":"CE940102","place":"building","ns":17.21,"ew":63.0,"dest":{"cell":"56530113","place":"dungeon","name":"Citadel Library"},"minLevel":20,"quest":true,"id":4414}, + {"name":"Prismatic Ziggurat","type":"Portal","wcid":46924,"cell":"CE940107","place":"building","ns":17.09,"ew":63.0,"dest":{"cell":"58510104","place":"dungeon","name":"Prismatic Ziggurat"},"minLevel":150,"quest":true,"id":4415}, + {"name":"Proving Grounds Uber","type":"Portal","wcid":46925,"cell":"CE940102","place":"building","ns":17.18,"ew":63.02,"dest":{"cell":"5852019F","place":"dungeon","name":"Proving Grounds Uber"},"minLevel":150,"quest":true,"id":4416}, + {"name":"Effigy Foundry Portal","type":"Portal","wcid":19718,"cell":"CE950169","place":"building","ns":17.65,"ew":63.33,"dest":{"cell":"545901B0","place":"dungeon","name":"Effigy Foundry"},"id":4417}, + {"name":"Eastham Meeting Hall Portal","type":"Portal","wcid":6093,"cell":"CE950172","place":"building","ns":17.6,"ew":63.52,"dest":{"cell":"01220126","place":"dungeon","name":"Eastham Meeting Hall"},"id":4418}, + {"name":"Portal to Town Network","type":"Portal","wcid":43065,"cell":"CE95002D","place":"outdoor","ns":17.73,"ew":63.37,"dest":{"cell":"00070143","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4419}, + {"name":"Patriarch's Valley","type":"Portal","wcid":39409,"cell":"CE950034","place":"outdoor","ns":17.59,"ew":63.47,"dest":{"cell":"72C80025","place":"outdoor","ns":58.5,"ew":-10.3},"id":4420}, + {"name":"Eastham Sewer","type":"Portal","wcid":1323,"cell":"CE960000","place":"outdoor","ns":18.77,"ew":63.43,"dest":{"cell":"01CF0237","place":"dungeon","name":"Eastham Sewer"},"minLevel":50,"id":4421}, + {"name":"Destroyed Sawato Portal","type":"Portal","wcid":4043,"cell":"CF180000","place":"outdoor","ns":-82.46,"ew":63.78,"dest":{"cell":"C95B0001","place":"outdoor","ns":-29.15,"ew":58.91},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4422}, + {"name":"Destroyed Baishi Portal","type":"Portal","wcid":4037,"cell":"CF180000","place":"outdoor","ns":-82.62,"ew":63.77,"dest":{"cell":"CE410007","place":"outdoor","ns":-49.31,"ew":62.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4423}, + {"name":"Lugian Excavations Portal","type":"Portal","wcid":7612,"cell":"CF1F0000","place":"outdoor","ns":-77.02,"ew":64.32,"dest":{"cell":"02E70285","place":"dungeon","name":"Lugian Excavations"},"id":4424}, + {"name":"Asheron's Island","type":"Portal","wcid":33558,"cell":"CF950037","place":"outdoor","ns":17.86,"ew":64.32,"dest":{"cell":"D6930005","place":"outdoor","ns":16.12,"ew":69.33},"id":4425}, + {"name":"Destroyed Portal to Arwic","type":"Portal","wcid":1013,"cell":"CFA0010B","place":"building","ns":26.25,"ew":63.85,"dest":{"cell":"C6A90009","place":"outdoor","ns":33.27,"ew":56.65},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4426}, + {"name":"High Mountain Valley","type":"Portal","wcid":1901,"cell":"CFA00108","place":"building","ns":26.35,"ew":63.85,"dest":{"cell":"CA2D0038","place":"outdoor","ns":-65.2,"ew":60.32},"id":4427}, + {"name":"Destroyed Eastham Portal","type":"Portal","wcid":1016,"cell":"D0540000","place":"outdoor","ns":-34.43,"ew":64.69,"dest":{"cell":"CE940035","place":"outdoor","ns":16.92,"ew":63.48},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4428}, + {"name":"Thieves' Den","type":"Portal","wcid":1219,"cell":"D0950000","place":"outdoor","ns":17.76,"ew":64.96,"dest":{"cell":"01E10272","place":"dungeon","name":"Thieves' Den"},"id":4429}, + {"name":"Web Maze","type":"Portal","wcid":2094,"cell":"D1410000","place":"outdoor","ns":-49.41,"ew":65.36,"dest":{"cell":"01B20101","place":"dungeon","name":"Web Maze"},"id":4430}, + {"name":"Tusker Temple","type":"Portal","wcid":22700,"cell":"D1720000","place":"outdoor","ns":-10.5,"ew":65.58,"dest":{"cell":"5D4402F9","place":"dungeon","name":"Tusker Temple"},"maxLevel":20,"id":4431}, + {"name":"Seaside Lair","type":"Portal","wcid":2091,"cell":"D1940000","place":"outdoor","ns":17.21,"ew":65.88,"dest":{"cell":"01B0011C","place":"dungeon","name":"Seaside Lair"},"id":4432}, + {"name":"Acidic Refuge","type":"Portal","wcid":45723,"cell":"D1C9002B","place":"outdoor","ns":59.05,"ew":65.76,"dest":{"cell":"576C01C1","place":"dungeon","name":"Acidic Refuge"},"minLevel":150,"quest":true,"id":4433}, + {"name":"Vissidal Island","type":"Portal","wcid":32058,"cell":"D1D7001A","place":"outdoor","ns":70.16,"ew":65.63,"dest":{"cell":"C8E2002A","place":"outdoor","ns":79.03,"ew":58.62},"minLevel":130,"quest":true,"desc":"You must obtain the blessing of the Watcher of the Deep before you may use this portal.","id":4434}, + {"name":"Firebird's Splendor","type":"Portal","wcid":25835,"cell":"D23C0000","place":"outdoor","ns":-53.63,"ew":66.72,"dest":{"cell":"644902D1","place":"dungeon","name":"Dragon's Power"},"minLevel":35,"quest":true,"id":4435}, + {"name":"Olthoi Brood Hive","type":"Portal","wcid":24912,"cell":"D2B60000","place":"outdoor","ns":44.22,"ew":66.18,"dest":{"cell":"57720439","place":"dungeon","name":"Olthoi Brood Hive"},"minLevel":20,"id":4436}, + {"name":"Hills Citadel Portal","type":"Portal","wcid":7317,"cell":"D3380000","place":"outdoor","ns":-56.57,"ew":66.91,"dest":{"cell":"02F00152","place":"dungeon","name":"Hills Citadel"},"id":4437}, + {"name":"South Osteth Peak","type":"Portal","wcid":39747,"cell":"D33D0024","place":"outdoor","ns":-52.75,"ew":67.35,"dest":{"cell":"D43E0011","place":"outdoor","ns":-52.3,"ew":67.9},"id":4438}, + {"name":"Golem Burial Ground","type":"Portal","wcid":2078,"cell":"D33F0000","place":"outdoor","ns":-50.93,"ew":67.31,"dest":{"cell":"01B40130","place":"dungeon","name":"Golem Burial Ground"},"minLevel":10,"id":4439}, + {"name":"Murk Warrens","type":"Portal","wcid":7252,"cell":"D3490000","place":"outdoor","ns":-43.2,"ew":67.03,"dest":{"cell":"01000121","place":"dungeon","name":"Murk Warrens"},"id":4440}, + {"name":"Lost Coastal Archive","type":"Portal","wcid":31434,"cell":"D3AE0100","place":"dungeon","dest":{"cell":"003501E5","place":"dungeon"},"minLevel":40,"quest":true,"desc":"This dungeon is quest restricted. Royal scholars in Cragstone or Sanamar might be interested in the secrets it holds. In a dungeon (landblock D3AE).","id":4441}, + {"name":"Olthoi Brood Hive","type":"Portal","wcid":24913,"cell":"D3C70000","place":"outdoor","ns":57.44,"ew":67.44,"dest":{"cell":"584C04F1","place":"dungeon","name":"Olthoi Brood Hive"},"minLevel":80,"id":4442}, + {"name":"Reedshark Clan Training Camp","type":"Portal","wcid":23897,"cell":"D46F0000","place":"outdoor","ns":-13.03,"ew":67.97,"dest":{"cell":"577A036C","place":"dungeon","name":"Reedshark Clan Training Camp"},"id":4443}, + {"name":"Shreth Clan Training Camp","type":"Portal","wcid":23901,"cell":"D4790000","place":"outdoor","ns":-5.03,"ew":67.97,"dest":{"cell":"577902E3","place":"dungeon","name":"Shreth Clan Training Camp"},"id":4444}, + {"name":"The Old Keep","type":"Portal","wcid":5650,"cell":"D53D0000","place":"outdoor","ns":-52.84,"ew":69.14,"dest":{"cell":"D53E0009","place":"outdoor","ns":-52.28,"ew":68.56},"id":4445}, + {"name":"The Lee Side of The Mountain","type":"Portal","wcid":5651,"cell":"D53D0000","place":"outdoor","ns":-52.44,"ew":68.64,"dest":{"cell":"D53F0019","place":"outdoor","ns":-51.49,"ew":68.81},"id":4446}, + {"name":"Cursed Swamp Portal","type":"Portal","wcid":7204,"cell":"D55D0000","place":"outdoor","ns":-27.31,"ew":69.04,"dest":{"cell":"0108020C","place":"dungeon","name":"Cursed Swamp"},"id":4447}, + {"name":"Portal to Cragstone","type":"Portal","wcid":42818,"cell":"D5990117","place":"building","ns":20.99,"ew":69.1,"dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"desc":"This portal goes to the Aluvian capital, Cragstone. This is a good town for characters over level 10.","id":4448}, + {"name":"Asheron's Sanctum","type":"Portal","wcid":24516,"cell":"D599014C","place":"building","ns":21.18,"ew":69.09,"dest":{"cell":"5E470104","place":"dungeon","name":"Asheron's Sanctum"},"quest":true,"id":4449}, + {"name":"Temple of Xik Minru","type":"Portal","wcid":32045,"cell":"D5DA014E","place":"underground","ns":73.22,"ew":69.2,"dest":{"cell":"00F00143","place":"dungeon","name":"Upper Sanctum of Xik Minru"},"minLevel":130,"id":4450}, + {"name":"Upper Sanctum of Xik Minru","type":"Portal","wcid":32044,"cell":"D5DA0035","place":"outdoor","ns":72.9,"ew":69.15,"dest":{"cell":"00F0052C","place":"dungeon","name":"Upper Sanctum of Xik Minru"},"minLevel":130,"id":4451}, + {"name":"Upper Sanctum of Xik Minru","type":"Portal","wcid":32044,"cell":"D5DA0028","place":"outdoor","ns":73.15,"ew":68.9,"dest":{"cell":"00F0052C","place":"dungeon","name":"Upper Sanctum of Xik Minru"},"minLevel":130,"id":4452}, + {"name":"Upper Sanctum of Xik Minru","type":"Portal","wcid":32044,"cell":"D5DA0022","place":"outdoor","ns":72.65,"ew":68.9,"dest":{"cell":"00F0052C","place":"dungeon","name":"Upper Sanctum of Xik Minru"},"minLevel":130,"id":4453}, + {"name":"Upper Sanctum of Xik Minru","type":"Portal","wcid":32044,"cell":"D5DA000D","place":"outdoor","ns":72.9,"ew":68.65,"dest":{"cell":"00F0052C","place":"dungeon","name":"Upper Sanctum of Xik Minru"},"minLevel":130,"id":4454}, + {"name":"Rocky Crypt Portal","type":"Portal","wcid":2089,"cell":"D63F0000","place":"outdoor","ns":-50.86,"ew":69.27,"dest":{"cell":"01B50101","place":"dungeon","name":"Rocky Crypt"},"minLevel":10,"id":4455}, + {"name":"Gromnie Clan Training Camp","type":"Portal","wcid":23893,"cell":"D66B0000","place":"outdoor","ns":-16.01,"ew":70.02,"dest":{"cell":"56430381","place":"dungeon","name":"Gromnie Clan Training Camp"},"id":4456}, + {"name":"Serpent Clan Training Camp","type":"Portal","wcid":23899,"cell":"D67E0000","place":"outdoor","ns":-1.02,"ew":70.01,"dest":{"cell":"5778030A","place":"dungeon","name":"Serpent Clan Training Camp"},"id":4457}, + {"name":"Asheron's Castle","type":"Portal","wcid":35293,"cell":"D6930006","place":"outdoor","ns":16.2,"ew":69.33,"dest":{"cell":"D59A0039","place":"outdoor","ns":21.26,"ew":69.19},"id":4458}, + {"name":"Portal to Hebian-To","type":"Portal","wcid":42846,"cell":"D6990125","place":"building","ns":20.99,"ew":69.3,"dest":{"cell":"E64E002F","place":"outdoor","ns":-38.88,"ew":82.63},"desc":"This portal goes to the Sho capital, Hebian-To. This is a good town for characters over level 10.","id":4459}, + {"name":"Altar Nest","type":"Portal","wcid":33516,"cell":"D6DE000B","place":"outdoor","ns":75.88,"ew":69.39,"dest":{"cell":"00850151","place":"dungeon","name":"Altar Nest"},"minLevel":140,"quest":true,"desc":"This dungeon is quest restricted. The Whispering Blade may be interested in it...","id":4460}, + {"name":"A Small Ruin Portal","type":"Portal","wcid":5521,"cell":"D73C0000","place":"outdoor","ns":-53.63,"ew":70.84,"dest":{"cell":"01480139","place":"dungeon","name":"A Small Ruin"},"minLevel":5,"id":4461}, + {"name":"Dungeon Mei Portal","type":"Portal","wcid":4160,"cell":"D7510000","place":"outdoor","ns":-36.92,"ew":70.28,"dest":{"cell":"0184014B","place":"dungeon","name":"Dungeon Mei"},"id":4462}, + {"name":"Olthoi Brood Hive","type":"Portal","wcid":24881,"cell":"D7D20000","place":"outdoor","ns":66.5,"ew":70.67,"dest":{"cell":"5E490435","place":"dungeon","name":"Olthoi Brood Hive"},"minLevel":40,"id":4463}, + {"name":"Black Spear Summoning Chamber","type":"Portal","wcid":33478,"cell":"D7DE0102","place":"underground","ns":75.8,"ew":70.42,"dest":{"cell":"00840241","place":"dungeon"},"minLevel":140,"quest":true,"id":4464}, + {"name":"Dark Isle","type":"Portal","wcid":33545,"cell":"D7DE000A","place":"outdoor","ns":75.8,"ew":70.23,"dest":{"cell":"C8E9000B","place":"outdoor","ns":84.7,"ew":58.21},"minLevel":150,"quest":true,"desc":"You must bypass the wards of the Mukkir before you may use this portal.","id":4465}, + {"name":"Stone Cathedral","type":"Portal","wcid":4955,"cell":"D8540102","place":"building","ns":-34.64,"ew":71.2,"dest":{"cell":"0154017E","place":"dungeon","name":"Stone Cathedral"},"minLevel":1,"maxLevel":20,"desc":"This is a good adventure for someone who is newly arrived in Dereth.","id":4466}, + {"name":"Shreth Hive Portal","type":"Portal","wcid":4965,"cell":"D8560100","place":"building","ns":-32.47,"ew":71.0,"dest":{"cell":"015302E8","place":"dungeon","name":"Shreth Hive"},"minLevel":1,"maxLevel":20,"id":4467}, + {"name":"Green Mire Grave","type":"Portal","wcid":1309,"cell":"D85C0000","place":"outdoor","ns":-27.83,"ew":71.58,"dest":{"cell":"01E5020E","place":"dungeon","name":"Green Mire Grave"},"id":4468}, + {"name":"Dungeon Muddy","type":"Portal","wcid":2072,"cell":"D85D0000","place":"outdoor","ns":-27.03,"ew":70.98,"dest":{"cell":"01B60100","place":"dungeon","name":"Dungeon Muddy"},"minLevel":5,"id":4469}, + {"name":"Black Death Catacombs Portal","type":"Portal","wcid":1118,"cell":"D8CA0000","place":"outdoor","ns":59.93,"ew":71.21,"dest":{"cell":"5E450377","place":"dungeon","name":"Black Death Catacombs"},"minLevel":20,"id":4470}, + {"name":"Tanada Toresen Temple","type":"Portal","wcid":72615,"cell":"D94A0039","place":"outdoor","ns":-42.7,"ew":72.41,"dest":{"cell":"6757027B","place":"dungeon","name":"Tanada Toresen Temple"},"minLevel":200,"quest":true,"id":4471}, + {"name":"Braid Mansion Ruin","type":"Portal","wcid":2066,"cell":"D9540000","place":"outdoor","ns":-34.26,"ew":71.97,"dest":{"cell":"01B70100","place":"dungeon","name":"Braid Mansion Ruin"},"desc":"This is a good adventure for someone who is newly arrived in Dereth.","id":4472}, + {"name":"Destroyed Portal to Greenspire","type":"Portal","wcid":11954,"cell":"D9550000","place":"outdoor","ns":-33.58,"ew":72.41,"dest":{"cell":"2BB5003C","place":"outdoor","ns":43.21,"ew":-66.8},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4473}, + {"name":"Destroyed Portal to Khayyaban","type":"Portal","wcid":4572,"cell":"DA3A0000","place":"outdoor","ns":-54.9,"ew":73.1,"dest":{"cell":"9F440012","place":"outdoor","ns":-47.45,"ew":25.62},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4474}, + {"name":"Lin Meeting Hall Portal","type":"Portal","wcid":6098,"cell":"DA3A010B","place":"building","ns":-54.8,"ew":73.22,"dest":{"cell":"01270126","place":"dungeon","name":"Lin Meeting Hall"},"id":4475}, + {"name":"Effigy Foundry Portal","type":"Portal","wcid":19718,"cell":"DA3B013B","place":"building","ns":-54.42,"ew":73.2,"dest":{"cell":"545901B0","place":"dungeon","name":"Effigy Foundry"},"id":4476}, + {"name":"Victory Residential Halls Portal","type":"Portal","wcid":22231,"cell":"DA3B0000","place":"outdoor","ns":-54.35,"ew":73.24,"dest":{"cell":"56500140","place":"dungeon","name":"Victory Residential Halls"},"id":4477}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"DA3B003B","place":"outdoor","ns":-54.53,"ew":73.21,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4478}, + {"name":"Shoushi Grotto Portal","type":"Portal","wcid":1124,"cell":"DA540000","place":"outdoor","ns":-34.46,"ew":72.83,"dest":{"cell":"01F701ED","place":"dungeon","name":"Shoushi Grotto"},"id":4479}, + {"name":"Mannikin Foundry Portal","type":"Portal","wcid":19717,"cell":"DA5501E7","place":"building","ns":-33.37,"ew":72.85,"dest":{"cell":"545A013C","place":"dungeon","name":"Mannikin Foundry"},"id":4480}, + {"name":"Shoushi Meeting Hall Portal","type":"Portal","wcid":6106,"cell":"DA5501EB","place":"building","ns":-33.18,"ew":72.88,"dest":{"cell":"012F0126","place":"dungeon","name":"Shoushi Meeting Hall"},"id":4481}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"DA550014","place":"outdoor","ns":-33.57,"ew":72.73,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4482}, + {"name":"Banderling Hovel","type":"Portal","wcid":28267,"cell":"DA570000","place":"outdoor","ns":-31.98,"ew":72.81,"dest":{"cell":"017A0137","place":"dungeon","name":"Banderling Hovel"},"minLevel":10,"id":4483}, + {"name":"Mosswart Place Cottages Portal","type":"Portal","wcid":12522,"cell":"DA580000","place":"outdoor","ns":-31.33,"ew":72.56,"dest":{"cell":"DB630016","place":"outdoor","ns":-22.22,"ew":73.53},"id":4484}, + {"name":"Aimaru Plains Cottages Portal","type":"Portal","wcid":12468,"cell":"DA580000","place":"outdoor","ns":-31.3,"ew":72.56,"dest":{"cell":"DD5C0012","place":"outdoor","ns":-28.16,"ew":75.13},"id":4485}, + {"name":"Chi Zou Cottages Portal","type":"Portal","wcid":12484,"cell":"DA580000","place":"outdoor","ns":-31.27,"ew":72.57,"dest":{"cell":"D65A003F","place":"outdoor","ns":-29.27,"ew":69.95},"id":4486}, + {"name":"Shou-Zin Portal","type":"Portal","wcid":13127,"cell":"DA580000","place":"outdoor","ns":-31.33,"ew":72.6,"dest":{"cell":"D5510005","place":"outdoor","ns":-36.66,"ew":68.54},"id":4487}, + {"name":"Portal to Town Network","type":"Portal","wcid":43065,"cell":"DA75002D","place":"outdoor","ns":-7.9,"ew":72.97,"dest":{"cell":"00070143","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4488}, + {"name":"Destroyed Portal to Tou-Tou","type":"Portal","wcid":4568,"cell":"DB3B0000","place":"outdoor","ns":-53.99,"ew":73.9,"dest":{"cell":"F5590034","place":"outdoor","ns":-30.41,"ew":94.69},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4489}, + {"name":"Destroyed Portal to Sanamar","type":"Portal","wcid":28709,"cell":"DB54000D","place":"outdoor","ns":-34.3,"ew":73.4,"dest":{"cell":"33D90015","place":"outdoor","ns":72.07,"ew":-60.9},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4490}, + {"name":"Underground Passage","type":"Portal","wcid":14449,"cell":"DB560101","place":"building","ns":-32.8,"ew":73.3,"dest":{"cell":"01C20123","place":"dungeon","name":"Underground Passage"},"minLevel":20,"quest":true,"id":4491}, + {"name":"Thieves' Galleries Portal","type":"Portal","wcid":5513,"cell":"DC370000","place":"outdoor","ns":-57.69,"ew":74.09,"dest":{"cell":"0149017B","place":"dungeon","name":"Thieves' Galleries"},"minLevel":5,"id":4492}, + {"name":"Arcanum Storehouse","type":"Portal","wcid":15775,"cell":"DC3A0100","place":"dungeon","dest":{"cell":"545C067B","place":"dungeon"},"desc":"In a dungeon (landblock DC3A).","id":4493}, + {"name":"East Direlands Swamp","type":"Portal","wcid":2064,"cell":"DC750000","place":"outdoor","ns":-8.12,"ew":74.47,"dest":{"cell":"3B4D0037","place":"outdoor","ns":-39.75,"ew":-54.07},"minLevel":12,"id":4494}, + {"name":"Mossy Cave","type":"Portal","wcid":28835,"cell":"DD540100","place":"dungeon","dest":{"cell":"03FE0228","place":"dungeon"},"desc":"In a dungeon (landblock DD54).","id":4495}, + {"name":"Mask Clan Training Camp","type":"Portal","wcid":23895,"cell":"DD6B0000","place":"outdoor","ns":-16.0,"ew":74.99,"dest":{"cell":"56440103","place":"dungeon","name":"Mask Clan Training Camp"},"id":4496}, + {"name":"Falcon Clan Training Camp","type":"Portal","wcid":23891,"cell":"DD810000","place":"outdoor","ns":2.01,"ew":74.97,"dest":{"cell":"5777040D","place":"dungeon","name":"Falcon Clan Training Camp"},"id":4497}, + {"name":"Passage to Olthoi Island","type":"Portal","wcid":43536,"cell":"DDCF0039","place":"outdoor","ns":63.7,"ew":75.58,"dest":{"cell":"E4D60014","place":"outdoor","ns":69.6,"ew":80.7},"id":4498}, + {"name":"Passage to Olthoi Island","type":"Portal","wcid":43580,"cell":"DECE003B","place":"outdoor","ns":63.12,"ew":76.37,"dest":{"cell":"E8D2002B","place":"outdoor","ns":66.3,"ew":84.2},"id":4499}, + {"name":"South Direlands Portal","type":"Portal","wcid":1107,"cell":"DF310000","place":"outdoor","ns":-62.19,"ew":77.09,"dest":{"cell":"5416001A","place":"outdoor","ns":-84.2,"ew":-34.44},"minLevel":12,"id":4500}, + {"name":"Saadia's Retreat","type":"Portal","wcid":5530,"cell":"DF3C0000","place":"outdoor","ns":-53.6,"ew":76.62,"dest":{"cell":"013F01C5","place":"dungeon","name":"Saadia's Retreat"},"id":4501}, + {"name":"Nanto Rat Lair Portal","type":"Portal","wcid":5127,"cell":"E23B0100","place":"building","ns":-54.17,"ew":79.5,"dest":{"cell":"015C0101","place":"dungeon","name":"Nanto Rat Lair"},"id":4502}, + {"name":"Meditation Meadow Portal","type":"Portal","wcid":12519,"cell":"E3330000","place":"outdoor","ns":-60.77,"ew":80.27,"dest":{"cell":"E941001E","place":"outdoor","ns":-49.41,"ew":84.83},"id":4503}, + {"name":"Vesayan Overlook Portal","type":"Portal","wcid":12562,"cell":"E3330000","place":"outdoor","ns":-60.76,"ew":80.3,"dest":{"cell":"E02A003C","place":"outdoor","ns":-68.03,"ew":78.01},"id":4504}, + {"name":"Lugian Meadows Settlement Portal","type":"Portal","wcid":12515,"cell":"E3330000","place":"outdoor","ns":-60.77,"ew":80.34,"dest":{"cell":"D1220033","place":"outdoor","ns":-74.51,"ew":65.91},"id":4505}, + {"name":"West Mayoi Mountain Villas Portal","type":"Portal","wcid":13139,"cell":"E3330000","place":"outdoor","ns":-60.79,"ew":80.36,"dest":{"cell":"DB330021","place":"outdoor","ns":-61.09,"ew":73.72},"id":4506}, + {"name":"Font Alpa Portal","type":"Portal","wcid":13105,"cell":"E3330000","place":"outdoor","ns":-60.79,"ew":80.24,"dest":{"cell":"D5310025","place":"outdoor","ns":-62.32,"ew":68.93},"id":4507}, + {"name":"Xinh Portal","type":"Portal","wcid":14292,"cell":"E3330000","place":"outdoor","ns":-60.82,"ew":80.37,"dest":{"cell":"CA1D002C","place":"outdoor","ns":-78.39,"ew":60.21},"id":4508}, + {"name":"Point Tremblant Portal","type":"Portal","wcid":14658,"cell":"E3330000","place":"outdoor","ns":-60.86,"ew":80.34,"dest":{"cell":"88F70017","place":"outdoor","ns":96.31,"ew":7.09},"id":4509}, + {"name":"Lady Maila Estates Portal","type":"Portal","wcid":15168,"cell":"E3330000","place":"outdoor","ns":-60.89,"ew":80.32,"dest":{"cell":"45DC0024","place":"outdoor","ns":74.44,"ew":-46.33},"id":4510}, + {"name":"Inquisitor's Dale Cottages Portal","type":"Portal","wcid":15162,"cell":"E3330000","place":"outdoor","ns":-60.92,"ew":80.31,"dest":{"cell":"55A0001C","place":"outdoor","ns":26.43,"ew":-33.6},"id":4511}, + {"name":"Shore Vista Cottages Portal","type":"Portal","wcid":15189,"cell":"E3330000","place":"outdoor","ns":-60.82,"ew":80.22,"dest":{"cell":"6B8E0024","place":"outdoor","ns":11.96,"ew":-15.89},"id":4512}, + {"name":"Songview Portal","type":"Portal","wcid":15684,"cell":"E3330000","place":"outdoor","ns":-60.84,"ew":80.2,"dest":{"cell":"97CB0024","place":"outdoor","ns":60.79,"ew":19.28},"id":4513}, + {"name":"Shield of Valor Cottages Portal","type":"Portal","wcid":15683,"cell":"E3330000","place":"outdoor","ns":-60.97,"ew":80.31,"dest":{"cell":"55A40023","place":"outdoor","ns":29.54,"ew":-33.54},"id":4514}, + {"name":"Destroyed Portal to Yanshi","type":"Portal","wcid":1029,"cell":"E33D0000","place":"outdoor","ns":-52.7,"ew":80.32,"dest":{"cell":"B9720021","place":"outdoor","ns":-10.74,"ew":46.55},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4515}, + {"name":"Destroyed Portal to Bluespire","type":"Portal","wcid":11953,"cell":"E33D0000","place":"outdoor","ns":-52.69,"ew":79.79,"dest":{"cell":"21B00017","place":"outdoor","ns":39.54,"ew":-75.35},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4516}, + {"name":"Water Temple Portal","type":"Portal","wcid":4923,"cell":"E33E0100","place":"dungeon","dest":{"cell":"0168012A","place":"dungeon"},"minLevel":40,"desc":"In a dungeon (landblock E33E).","id":4517}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43544,"cell":"E3D10035","place":"outdoor","ns":65.67,"ew":80.29,"dest":{"cell":"3EEB0001","place":"outdoor","ns":86.14,"ew":-52.31},"id":4518}, + {"name":"Queen's Burrow","type":"Portal","wcid":43586,"cell":"E3D20102","place":"building","ns":66.34,"ew":80.4,"dest":{"cell":"E5D40019","place":"outdoor","ns":67.75,"ew":81.6},"id":4519}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43556,"cell":"E3D2002D","place":"outdoor","ns":66.52,"ew":80.18,"dest":{"cell":"400A001E","place":"outdoor","ns":-93.35,"ew":-50.41},"id":4520}, + {"name":"Queen's Burrow","type":"Portal","wcid":43585,"cell":"E3D30102","place":"building","ns":67.64,"ew":80.2,"dest":{"cell":"E5D4002C","place":"outdoor","ns":68.03,"ew":81.8},"id":4521}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43542,"cell":"E3D30036","place":"outdoor","ns":67.39,"ew":80.33,"dest":{"cell":"7F8F0019","place":"outdoor","ns":12.45,"ew":0.02},"id":4522}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43540,"cell":"E3D3000F","place":"outdoor","ns":67.51,"ew":79.81,"dest":{"cell":"F65D0008","place":"outdoor","ns":-26.85,"ew":94.89},"id":4523}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":90131,"cell":"E3D50001","place":"outdoor","ns":68.5,"ew":79.69,"dest":{"cell":"2E110006","place":"outdoor","ns":-87.8,"ew":-65.1},"id":4524}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":90130,"cell":"E3D60032","place":"outdoor","ns":69.4,"ew":80.31,"dest":{"cell":"C7EA0100","place":"dungeon","name":"Olthoi Tunnel"},"id":4525}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43590,"cell":"E4CF000D","place":"outdoor","ns":64.12,"ew":80.58,"dest":{"cell":"F7300030","place":"outdoor","ns":-62.84,"ew":96.17},"id":4526}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43546,"cell":"E4D00018","place":"outdoor","ns":65.19,"ew":80.71,"dest":{"cell":"18B40001","place":"outdoor","ns":42.05,"ew":-82.7},"id":4527}, + {"name":"Mud Cave","type":"Portal","wcid":8474,"cell":"E5240100","place":"building","ns":-73.05,"ew":81.35,"dest":{"cell":"02C1017E","place":"dungeon","name":"Mud Cave"},"id":4528}, + {"name":"A Ruin","type":"Portal","wcid":1341,"cell":"E5310000","place":"outdoor","ns":-62.64,"ew":81.39,"dest":{"cell":"01DE0195","place":"dungeon","name":"A Ruin"},"id":4529}, + {"name":"Mammet Foundry Portal","type":"Portal","wcid":19716,"cell":"E5320135","place":"building","ns":-61.91,"ew":81.97,"dest":{"cell":"5458025F","place":"dungeon","name":"Mammet Foundry"},"id":4530}, + {"name":"Oriel Residential Halls Portal","type":"Portal","wcid":19369,"cell":"E5320000","place":"outdoor","ns":-61.8,"ew":81.6,"dest":{"cell":"565E0140","place":"dungeon","name":"Oriel Residential Halls"},"id":4531}, + {"name":"Mayoi Meeting Hall Portal","type":"Portal","wcid":6100,"cell":"E5320139","place":"building","ns":-61.39,"ew":81.79,"dest":{"cell":"01290126","place":"dungeon","name":"Mayoi Meeting Hall"},"id":4532}, + {"name":"Mountain Sewer Portal","type":"Portal","wcid":3634,"cell":"E533003B","place":"outdoor","ns":-60.86,"ew":82.0,"dest":{"cell":"01910213","place":"dungeon","name":"Mountain Sewer"},"minLevel":15,"id":4533}, + {"name":"Empyrean Garrison","type":"Portal","wcid":4959,"cell":"E53B0102","place":"building","ns":-54.3,"ew":81.83,"dest":{"cell":"01610264","place":"dungeon","name":"Empyrean Garrison"},"id":4534}, + {"name":"Matron Hive South","type":"Portal","wcid":24435,"cell":"E53D0000","place":"outdoor","ns":-52.54,"ew":81.88,"dest":{"cell":"6346036E","place":"dungeon","name":"Matron Hive South"},"minLevel":40,"id":4535}, + {"name":"Qalaba'r Portal","type":"Portal","wcid":1024,"cell":"E54C0000","place":"outdoor","ns":-40.75,"ew":81.86,"dest":{"cell":"9722003A","place":"outdoor","ns":-74.65,"ew":19.55},"id":4536}, + {"name":"Thief Trail","type":"Portal","wcid":1597,"cell":"E54D0000","place":"outdoor","ns":-39.76,"ew":81.69,"dest":{"cell":"01BB0155","place":"dungeon","name":"Thief Trail"},"minLevel":7,"id":4537}, + {"name":"Cragstone Portal","type":"Portal","wcid":1015,"cell":"E54E0000","place":"outdoor","ns":-39.4,"ew":81.35,"dest":{"cell":"BB9F0040","place":"outdoor","ns":25.95,"ew":48.36},"id":4538}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43548,"cell":"E5CE0037","place":"outdoor","ns":63.47,"ew":81.89,"dest":{"cell":"C5A70037","place":"outdoor","ns":32.35,"ew":56.3},"id":4539}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43554,"cell":"E5D00040","place":"outdoor","ns":65.18,"ew":82.01,"dest":{"cell":"B56D0016","place":"outdoor","ns":-14.25,"ew":43.09},"id":4540}, + {"name":"Queen's Burrow","type":"Portal","wcid":43583,"cell":"E5D30143","place":"dungeon","dest":{"cell":"E6CE002A","place":"outdoor","ns":62.96,"ew":82.56},"desc":"In a dungeon (landblock E5D3).","id":4541}, + {"name":"Queen's Burrow","type":"Portal","wcid":43584,"cell":"E5D3013F","place":"dungeon","dest":{"cell":"E6D10020","place":"outdoor","ns":66.05,"ew":82.4},"desc":"In a dungeon (landblock E5D3).","id":4542}, + {"name":"Queen's Burrow","type":"Portal","wcid":43581,"cell":"E5D40102","place":"dungeon","dest":{"cell":"E3D30030","place":"outdoor","ns":67.57,"ew":80.16},"desc":"In a dungeon (landblock E5D4).","id":4543}, + {"name":"Queen's Burrow","type":"Portal","wcid":43582,"cell":"E5D40106","place":"dungeon","dest":{"cell":"E3D2003A","place":"outdoor","ns":66.25,"ew":80.37},"desc":"In a dungeon (landblock E5D4).","id":4544}, + {"name":"Eastham Beach Portal","type":"Portal","wcid":8616,"cell":"E6240000","place":"outdoor","ns":-72.36,"ew":82.17,"dest":{"cell":"D196002D","place":"outdoor","ns":18.47,"ew":65.82},"id":4545}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"E6320002","place":"outdoor","ns":-61.8,"ew":82.09,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4546}, + {"name":"Mannikin Foundry Portal","type":"Portal","wcid":19717,"cell":"E63D0153","place":"building","ns":-52.53,"ew":82.12,"dest":{"cell":"545A013C","place":"dungeon","name":"Mannikin Foundry"},"id":4547}, + {"name":"Nanto Meeting Hall Portal","type":"Portal","wcid":6101,"cell":"E63D0166","place":"building","ns":-52.51,"ew":82.53,"dest":{"cell":"012A0126","place":"dungeon","name":"Nanto Meeting Hall"},"id":4548}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"E63D0015","place":"outdoor","ns":-52.68,"ew":82.27,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4549}, + {"name":"Bluewater Cottages Portal","type":"Portal","wcid":12478,"cell":"E64B0000","place":"outdoor","ns":-41.47,"ew":82.23,"dest":{"cell":"E1660021","place":"outdoor","ns":-20.33,"ew":78.51},"id":4550}, + {"name":"Southwest Hebian-To Settlement Portal","type":"Portal","wcid":12554,"cell":"E64B0000","place":"outdoor","ns":-41.5,"ew":82.24,"dest":{"cell":"EC49001D","place":"outdoor","ns":-43.14,"ew":87.22},"id":4551}, + {"name":"South Hebian-To Cottages Portal","type":"Portal","wcid":12550,"cell":"E64B0000","place":"outdoor","ns":-41.54,"ew":82.24,"dest":{"cell":"E348003C","place":"outdoor","ns":-44.0,"ew":80.41},"id":4552}, + {"name":"Shian-To Cottages Portal","type":"Portal","wcid":12545,"cell":"E64B0000","place":"outdoor","ns":-41.54,"ew":82.2,"dest":{"cell":"DF4C000C","place":"outdoor","ns":-40.8,"ew":76.65},"id":4553}, + {"name":"South Hebian-To Estates Portal","type":"Portal","wcid":13132,"cell":"E64B0000","place":"outdoor","ns":-41.53,"ew":82.17,"dest":{"cell":"E7460016","place":"outdoor","ns":-45.4,"ew":83.07},"id":4554}, + {"name":"Stoneport Villas Portal","type":"Portal","wcid":13134,"cell":"E64B0000","place":"outdoor","ns":-41.44,"ew":82.2,"dest":{"cell":"E25F002B","place":"outdoor","ns":-25.69,"ew":79.44},"id":4555}, + {"name":"Sai-Nan Portal","type":"Portal","wcid":14280,"cell":"E64B0000","place":"outdoor","ns":-41.51,"ew":82.14,"dest":{"cell":"DD470026","place":"outdoor","ns":-44.63,"ew":75.32},"id":4556}, + {"name":"South Shoushi Villas Portal","type":"Portal","wcid":13133,"cell":"E64B0000","place":"outdoor","ns":-41.48,"ew":82.13,"dest":{"cell":"D64C0006","place":"outdoor","ns":-40.62,"ew":69.34},"id":4557}, + {"name":"Pine Deep Portal","type":"Portal","wcid":14656,"cell":"E64B0000","place":"outdoor","ns":-41.43,"ew":82.18,"dest":{"cell":"4BC8001E","place":"outdoor","ns":58.56,"ew":-41.64},"id":4558}, + {"name":"San-Chin Portal","type":"Portal","wcid":14662,"cell":"E64B0000","place":"outdoor","ns":-41.46,"ew":82.11,"dest":{"cell":"D5630014","place":"outdoor","ns":-22.37,"ew":68.74},"id":4559}, + {"name":"Tia-Leh Homestead Portal","type":"Portal","wcid":15198,"cell":"E64B0000","place":"outdoor","ns":-41.44,"ew":82.1,"dest":{"cell":"5BA2001B","place":"outdoor","ns":27.92,"ew":-28.78},"id":4560}, + {"name":"Arrowdale Cottages Portal","type":"Portal","wcid":15664,"cell":"E64B0000","place":"outdoor","ns":-41.4,"ew":82.13,"dest":{"cell":"D9D00024","place":"outdoor","ns":64.81,"ew":72.07},"id":4561}, + {"name":"Majestic Saddle Cottages Portal","type":"Portal","wcid":19152,"cell":"E64B0000","place":"outdoor","ns":-41.57,"ew":82.22,"dest":{"cell":"63B00017","place":"outdoor","ns":39.46,"ew":-22.48},"id":4562}, + {"name":"Queen's Burrow","type":"Portal","wcid":43587,"cell":"E6CE0102","place":"dungeon","dest":{"cell":"E5D30016","place":"outdoor","ns":67.45,"ew":81.49},"desc":"In a dungeon (landblock E6CE).","id":4563}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43550,"cell":"E6CF0025","place":"outdoor","ns":64.08,"ew":82.52,"dest":{"cell":"96D6003E","place":"outdoor","ns":69.75,"ew":18.79},"id":4564}, + {"name":"Queen's Burrow","type":"Portal","wcid":43588,"cell":"E6D20102","place":"dungeon","dest":{"cell":"E5D3001C","place":"outdoor","ns":67.23,"ew":81.62},"desc":"In a dungeon (landblock E6D2).","id":4565}, + {"name":"Umbral Hall","type":"Portal","wcid":28263,"cell":"E7200103","place":"dungeon","dest":{"cell":"0179010D","place":"dungeon"},"minLevel":30,"desc":"In a dungeon (landblock E720).","id":4566}, + {"name":"Dark Mosswart Halls","type":"Portal","wcid":28259,"cell":"E7220100","place":"building","ns":-74.21,"ew":83.6,"dest":{"cell":"017801F5","place":"dungeon","name":"Dark Mosswart Halls"},"minLevel":30,"id":4567}, + {"name":"Blighted Disgusting Moarsman Tunnels","type":"Portal","wcid":38155,"cell":"E733000D","place":"outdoor","ns":-60.7,"ew":82.96,"dest":{"cell":"00C2037C","place":"dungeon","name":"Blighted Disgusting Moarsman Tunnels"},"minLevel":35,"id":4568}, + {"name":"Mysterious Tunnels Portal","type":"Portal","wcid":6884,"cell":"E73D0000","place":"outdoor","ns":-52.87,"ew":82.94,"dest":{"cell":"010C01DB","place":"dungeon","name":"Mysterious Tunnels"},"minLevel":1,"maxLevel":20,"id":4569}, + {"name":"A Drudge Nest","type":"Portal","wcid":1337,"cell":"E74C0000","place":"outdoor","ns":-40.63,"ew":83.58,"dest":{"cell":"01DC015C","place":"dungeon","name":"A Drudge Nest"},"id":4570}, + {"name":"Sanctum Residential Halls Portal","type":"Portal","wcid":15837,"cell":"E74D0000","place":"outdoor","ns":-39.6,"ew":83.49,"dest":{"cell":"54650140","place":"dungeon","name":"Sanctum Residential Halls"},"id":4571}, + {"name":"Celestial Hand Stronghold","type":"Portal","wcid":37387,"cell":"E74D003F","place":"outdoor","ns":-39.71,"ew":83.59,"dest":{"cell":"00B70294","place":"dungeon","name":"Celestial Hand Stronghold"},"minLevel":180,"quest":true,"desc":"You must be a member of the Society of the Celestial Hand to enter this Portal.","id":4572}, + {"name":"Celestial Hand Gauntlet","type":"Portal","wcid":53446,"cell":"E74D003F","place":"outdoor","ns":-39.74,"ew":83.63,"dest":{"cell":"596B0118","place":"dungeon","name":"Radiant Blood Gauntlet"},"minLevel":180,"id":4573}, + {"name":"Effigy Foundry Portal","type":"Portal","wcid":19718,"cell":"E74E01A6","place":"building","ns":-39.41,"ew":83.14,"dest":{"cell":"545901B0","place":"dungeon","name":"Effigy Foundry"},"id":4574}, + {"name":"Hebian-to Meeting Hall Portal","type":"Portal","wcid":6095,"cell":"E74E01C9","place":"building","ns":-39.31,"ew":83.3,"dest":{"cell":"01240126","place":"dungeon","name":"Hebian-to Meeting Hall"},"id":4575}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"E74E0014","place":"outdoor","ns":-39.17,"ew":83.13,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4576}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43552,"cell":"E7D1003A","place":"outdoor","ns":65.39,"ew":83.6,"dest":{"cell":"9A210014","place":"outdoor","ns":-75.15,"ew":21.5},"id":4577}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"E822003D","place":"outdoor","ns":-74.31,"ew":84.41,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4578}, + {"name":"Hebian-to Sewers","type":"Portal","wcid":1599,"cell":"E84E0000","place":"outdoor","ns":-38.77,"ew":83.81,"dest":{"cell":"01CA027F","place":"dungeon","name":"Hebian-to Sewers"},"minLevel":4,"id":4579}, + {"name":"Tusker Assault","type":"Portal","wcid":22659,"cell":"E87A0000","place":"outdoor","ns":-3.89,"ew":84.26,"dest":{"cell":"584902C8","place":"dungeon","name":"Tusker Assault"},"minLevel":85,"id":4580}, + {"name":"Effigy Foundry Portal","type":"Portal","wcid":19718,"cell":"E9220140","place":"building","ns":-74.27,"ew":84.63,"dest":{"cell":"545901B0","place":"dungeon","name":"Effigy Foundry"},"id":4581}, + {"name":"Destroyed Portal to Kryst","type":"Portal","wcid":8554,"cell":"E9270000","place":"outdoor","ns":-70.22,"ew":84.56,"dest":{"cell":"E822002A","place":"outdoor","ns":-74.59,"ew":84.2},"desc":"This portal was destroyed by Asheron's foray into opening a portal to the lost Empyreans.","id":4582}, + {"name":"Vesayen Isles Portal","type":"Portal","wcid":8618,"cell":"E92D0000","place":"outdoor","ns":-65.74,"ew":84.89,"dest":{"cell":"E5240007","place":"outdoor","ns":-72.51,"ew":81.3},"id":4583}, + {"name":"Rampage Bluff","type":"Portal","wcid":22750,"cell":"E97D0000","place":"outdoor","ns":-1.31,"ew":84.94,"dest":{"cell":"5C48011E","place":"dungeon","name":"Rampage Bluff"},"minLevel":80,"id":4584}, + {"name":"Surface","type":"Portal","wcid":35947,"cell":"EA6C0124","place":"dungeon","dest":{"cell":"EA6C015B","place":"dungeon"},"desc":"In a dungeon (landblock EA6C).","id":4585}, + {"name":"Whispering Caverns","type":"Portal","wcid":35946,"cell":"EA6C015B","place":"dungeon","dest":{"cell":"EA6C0156","place":"dungeon"},"minLevel":130,"desc":"In a dungeon (landblock EA6C).","id":4586}, + {"name":"Behind the Waterfall","type":"Portal","wcid":22651,"cell":"EA740000","place":"outdoor","ns":-8.66,"ew":85.71,"dest":{"cell":"604401E4","place":"dungeon","name":"Behind the Waterfall"},"minLevel":80,"quest":true,"id":4587}, + {"name":"Tusker Holding","type":"Portal","wcid":22680,"cell":"EA7B0000","place":"outdoor","ns":-3.48,"ew":85.32,"dest":{"cell":"5B480384","place":"dungeon","name":"Tusker Holding"},"minLevel":60,"id":4588}, + {"name":"Plated Rifts","type":"Portal","wcid":22652,"cell":"EA7E0000","place":"outdoor","ns":-0.97,"ew":85.77,"dest":{"cell":"5B49027E","place":"dungeon","name":"Plated Rifts"},"minLevel":75,"id":4589}, + {"name":"Lytaway Portal","type":"Portal","wcid":4953,"cell":"EB3D0102","place":"dungeon","dest":{"cell":"015801BC","place":"dungeon"},"minLevel":1,"maxLevel":20,"desc":"In a dungeon (landblock EB3D).","id":4590}, + {"name":"Tusker Gauntlet","type":"Portal","wcid":22674,"cell":"EB730000","place":"outdoor","ns":-9.83,"ew":86.45,"dest":{"cell":"5C4601C1","place":"dungeon","name":"Tusker Gauntlet"},"minLevel":100,"id":4591}, + {"name":"Tusker Tunnels","type":"Portal","wcid":22702,"cell":"EB7F0000","place":"outdoor","ns":0.29,"ew":86.37,"dest":{"cell":"5D450231","place":"dungeon","name":"Tusker Tunnels"},"minLevel":70,"id":4592}, + {"name":"Xi Ru's Chapel","type":"Portal","wcid":28981,"cell":"EC0E0000","place":"outdoor","ns":-90.65,"ew":87.5,"dest":{"cell":"019502DF","place":"dungeon","name":"Xi Ru's Chapel"},"quest":true,"id":4593}, + {"name":"Roots of the Deru Tree","type":"Portal","wcid":37068,"cell":"EC0E002D","place":"outdoor","ns":-90.27,"ew":87.35,"dest":{"cell":"00A8010F","place":"dungeon","name":"Roots of the Deru Tree"},"id":4594}, + {"name":"Idol Spawning Grounds","type":"Portal","wcid":8586,"cell":"EC250000","place":"outdoor","ns":-72.27,"ew":87.47,"dest":{"cell":"02B6029E","place":"dungeon","name":"Idol Spawning Grounds"},"id":4595}, + {"name":"Tusker Honeycombs","type":"Portal","wcid":22682,"cell":"EC7D0000","place":"outdoor","ns":-1.24,"ew":86.9,"dest":{"cell":"5A49029F","place":"dungeon","name":"Tusker Honeycombs"},"minLevel":80,"id":4596}, + {"name":"Mosswart Nest","type":"Portal","wcid":8486,"cell":"ED1E0000","place":"outdoor","ns":-77.63,"ew":87.87,"dest":{"cell":"02BC0145","place":"dungeon","name":"Mosswart Nest"},"id":4597}, + {"name":"Rumuba's Hidey-Hole","type":"Portal","wcid":8576,"cell":"EE200000","place":"outdoor","ns":-75.88,"ew":89.18,"dest":{"cell":"02B802B3","place":"dungeon","name":"Rumuba's Hidey-Hole"},"id":4598}, + {"name":"Steamy Font","type":"Portal","wcid":29786,"cell":"EF0D0102","place":"building","ns":-91.1,"ew":89.61,"dest":{"cell":"019803D3","place":"dungeon","name":"Steamy Font"},"quest":true,"id":4599}, + {"name":"Humid Font","type":"Portal","wcid":29781,"cell":"EF0D010B","place":"building","ns":-91.3,"ew":89.81,"dest":{"cell":"017603D3","place":"dungeon","name":"Humid Font"},"quest":true,"id":4600}, + {"name":"Balmy Font","type":"Portal","wcid":29778,"cell":"EF0D010D","place":"building","ns":-91.51,"ew":89.71,"dest":{"cell":"01D103D3","place":"dungeon","name":"Balmy Font"},"quest":true,"id":4601}, + {"name":"Muggy Font","type":"Portal","wcid":29783,"cell":"EF0D010F","place":"building","ns":-91.5,"ew":89.39,"dest":{"cell":"017503D3","place":"dungeon","name":"Muggy Font"},"quest":true,"id":4602}, + {"name":"Portalling Device","type":"Portal","wcid":29958,"cell":"EF170000","place":"outdoor","ns":-83.34,"ew":89.82,"dest":{"cell":"EC0D002C","place":"outdoor","ns":-91.16,"ew":87.42},"quest":true,"id":4603}, + {"name":"Fiery Alcove","type":"Portal","wcid":52220,"cell":"EF1C003D","place":"outdoor","ns":-79.07,"ew":90.03,"dest":{"cell":"586502CF","place":"dungeon","name":"Stinging Corner"},"minLevel":180,"id":4604}, + {"name":"Moarsmen Hideout","type":"Portal","wcid":8456,"cell":"EF280100","place":"building","ns":-69.95,"ew":89.93,"dest":{"cell":"02C4023F","place":"dungeon","name":"Moarsmen Hideout"},"id":4605}, + {"name":"Tusker Armory","type":"Portal","wcid":22657,"cell":"EF7F0000","place":"outdoor","ns":0.03,"ew":89.38,"dest":{"cell":"594801AB","place":"dungeon","name":"Tusker Armory"},"minLevel":50,"id":4606}, + {"name":"Treacherous Tunnels Portal","type":"Portal","wcid":8442,"cell":"F0210100","place":"building","ns":-75.03,"ew":90.29,"dest":{"cell":"02C502CC","place":"dungeon","name":"Treacherous Tunnels"},"id":4607}, + {"name":"A Mosswart Hideout","type":"Portal","wcid":8578,"cell":"F0240000","place":"outdoor","ns":-72.71,"ew":90.72,"dest":{"cell":"02B40245","place":"dungeon","name":"A Mosswart Hideout"},"id":4608}, + {"name":"Desert Northern Edge Portal","type":"Portal","wcid":8615,"cell":"F0250000","place":"outdoor","ns":-72.17,"ew":90.63,"dest":{"cell":"9795003C","place":"outdoor","ns":17.56,"ew":19.6},"id":4609}, + {"name":"Northern Point","type":"Portal","wcid":8499,"cell":"F0460000","place":"outdoor","ns":-45.9,"ew":90.81,"dest":{"cell":"89F40003","place":"outdoor","ns":93.52,"ew":7.7},"minLevel":12,"id":4610}, + {"name":"Tusker Lacuna","type":"Portal","wcid":22686,"cell":"F0730000","place":"outdoor","ns":-9.9,"ew":90.73,"dest":{"cell":"5949029E","place":"dungeon","name":"Tusker Lacuna"},"minLevel":100,"id":4611}, + {"name":"Tusker Barracks","type":"Portal","wcid":22661,"cell":"F07F0000","place":"outdoor","ns":-0.28,"ew":90.79,"dest":{"cell":"5A4801B5","place":"dungeon","name":"Tusker Barracks"},"minLevel":40,"id":4612}, + {"name":"Moarsmen Muck","type":"Portal","wcid":8476,"cell":"F11F0100","place":"building","ns":-77.03,"ew":90.95,"dest":{"cell":"02C201E6","place":"dungeon","name":"Moarsmen Muck"},"id":4613}, + {"name":"Small Ruin","type":"Portal","wcid":8484,"cell":"F1270100","place":"building","ns":-70.11,"ew":91.1,"dest":{"cell":"02BD01A0","place":"dungeon","name":"Small Ruin"},"id":4614}, + {"name":"Exit","type":"Portal","wcid":5520,"cell":"F15A0102","place":"building","ns":-29.6,"ew":91.31,"dest":{"cell":"F25B0002","place":"outdoor","ns":-28.97,"ew":91.7},"id":4615}, + {"name":"Smugglers Hideaway","type":"Portal","wcid":5501,"cell":"F15A0000","place":"outdoor","ns":-29.52,"ew":91.38,"dest":{"cell":"014E025C","place":"dungeon","name":"Smugglers Hideaway"},"id":4616}, + {"name":"Mammet Foundry Portal","type":"Portal","wcid":19716,"cell":"F2220121","place":"building","ns":-74.12,"ew":92.31,"dest":{"cell":"5458025F","place":"dungeon","name":"Mammet Foundry"},"id":4617}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"F2220030","place":"outdoor","ns":-73.96,"ew":92.19,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4618}, + {"name":"Smugglers Fort","type":"Portal","wcid":5519,"cell":"F25B0102","place":"building","ns":-29.08,"ew":91.7,"dest":{"cell":"F15A0024","place":"outdoor","ns":-29.56,"ew":91.32},"id":4619}, + {"name":"Tusker Pits","type":"Portal","wcid":22690,"cell":"F2800000","place":"outdoor","ns":1.21,"ew":91.79,"dest":{"cell":"5A4A0275","place":"dungeon","name":"Tusker Pits"},"minLevel":45,"id":4620}, + {"name":"Moars","type":"Portal","wcid":8598,"cell":"F3270100","place":"dungeon","dest":{"cell":"02BA01F8","place":"dungeon"},"desc":"In a dungeon (landblock F327).","id":4621}, + {"name":"Catacombs of Ithaenc Portal","type":"Portal","wcid":8532,"cell":"F4180000","place":"outdoor","ns":-82.42,"ew":93.4,"dest":{"cell":"02B702F1","place":"dungeon","name":"Catacombs of Ithaenc"},"id":4622}, + {"name":"Shadow-Infested Black Spear Temple","type":"Portal","wcid":33786,"cell":"F41F002C","place":"outdoor","ns":-76.83,"ew":93.79,"dest":{"cell":"00750473","place":"dungeon","name":"Grael's Chamber"},"minLevel":101,"maxLevel":150,"quest":true,"desc":"A Shadow-infested Ruschk temple, where those who wish to follow the Black Spear prove their worth.","id":4623}, + {"name":"Treacherous Tunnels Portal","type":"Portal","wcid":8444,"cell":"F4260102","place":"dungeon","dest":{"cell":"02C50102","place":"dungeon","name":"Treacherous Tunnels"},"desc":"In a dungeon (landblock F426).","id":4624}, + {"name":"Small Temple","type":"Portal","wcid":8482,"cell":"F4280100","place":"underground","ns":-69.22,"ew":93.7,"dest":{"cell":"02BE011D","place":"dungeon"},"id":4625}, + {"name":"Tusker Encampments","type":"Portal","wcid":22669,"cell":"F47A0000","place":"outdoor","ns":-4.0,"ew":93.48,"dest":{"cell":"5C440159","place":"dungeon","name":"Tusker Encampments"},"minLevel":30,"id":4626}, + {"name":"Vengeance Caverns","type":"Portal","wcid":22706,"cell":"F4810000","place":"outdoor","ns":1.87,"ew":93.64,"dest":{"cell":"5D4601E1","place":"dungeon","name":"Vengeance Caverns"},"minLevel":45,"id":4627}, + {"name":"Chapel of Mowen","type":"Portal","wcid":22648,"cell":"F4830000","place":"outdoor","ns":3.12,"ew":93.61,"dest":{"cell":"594A0148","place":"dungeon","name":"Chapel of Mowen"},"minLevel":50,"id":4628}, + {"name":"Lost Ruins","type":"Portal","wcid":46357,"cell":"F518003A","place":"outdoor","ns":-82.56,"ew":94.83,"dest":{"cell":"5765036C","place":"dungeon","name":"Lost Ruins"},"minLevel":150,"id":4629}, + {"name":"Slithis Pit","type":"Portal","wcid":8458,"cell":"F5270000","place":"outdoor","ns":-70.18,"ew":94.33,"dest":{"cell":"02C30289","place":"dungeon","name":"Slithis Pit"},"id":4630}, + {"name":"Jungle Shadows","type":"Portal","wcid":8497,"cell":"F5280102","place":"dungeon","dest":{"cell":"02BB0197","place":"dungeon"},"desc":"In a dungeon (landblock F528).","id":4631}, + {"name":"Moars Laboratory","type":"Portal","wcid":8600,"cell":"F5290102","place":"building","ns":-68.37,"ew":94.4,"dest":{"cell":"02B301F6","place":"dungeon","name":"Moars Laboratory"},"id":4632}, + {"name":"Haven Residential Halls Portal","type":"Portal","wcid":21464,"cell":"F559003B","place":"outdoor","ns":-30.49,"ew":94.79,"dest":{"cell":"56560140","place":"dungeon","name":"Haven Residential Halls"},"id":4633}, + {"name":"Portal to Town Network","type":"Portal","wcid":43067,"cell":"F559003D","place":"outdoor","ns":-30.28,"ew":94.77,"dest":{"cell":"00070156","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4634}, + {"name":"Ong-Hau Village Portal","type":"Portal","wcid":14655,"cell":"F559002C","place":"outdoor","ns":-30.45,"ew":94.56,"dest":{"cell":"EC450025","place":"outdoor","ns":-46.26,"ew":87.3},"id":4635}, + {"name":"Dryreach Beach Cottages Portal","type":"Portal","wcid":12487,"cell":"F559002B","place":"outdoor","ns":-30.49,"ew":94.56,"dest":{"cell":"DF6F003C","place":"outdoor","ns":-12.83,"ew":77.17},"id":4636}, + {"name":"Snowy Valley Portal","type":"Portal","wcid":13130,"cell":"F559002B","place":"outdoor","ns":-30.47,"ew":94.57,"dest":{"cell":"74EA0019","place":"outdoor","ns":85.33,"ew":-8.83},"id":4637}, + {"name":"Dame Tolani Villas Portal","type":"Portal","wcid":19140,"cell":"F5590024","place":"outdoor","ns":-30.44,"ew":94.54,"dest":{"cell":"5EB40025","place":"outdoor","ns":42.49,"ew":-26.3},"id":4638}, + {"name":"Westshore Cottages Portal","type":"Portal","wcid":14676,"cell":"F5590024","place":"outdoor","ns":-30.44,"ew":94.52,"dest":{"cell":"3ECC0003","place":"outdoor","ns":61.51,"ew":-52.26},"id":4639}, + {"name":"Nan-Zari Portal","type":"Portal","wcid":13112,"cell":"F5590023","place":"outdoor","ns":-30.46,"ew":94.51,"dest":{"cell":"EE420003","place":"outdoor","ns":-48.93,"ew":88.51},"id":4640}, + {"name":"Tou-Tou Penninsula Cottages Portal","type":"Portal","wcid":12561,"cell":"F5590023","place":"outdoor","ns":-30.48,"ew":94.51,"dest":{"cell":"F24F0024","place":"outdoor","ns":-38.37,"ew":92.14},"id":4641}, + {"name":"Tou-Tou Road Villas Portal","type":"Portal","wcid":13137,"cell":"F5590023","place":"outdoor","ns":-30.49,"ew":94.52,"dest":{"cell":"F14A0006","place":"outdoor","ns":-42.21,"ew":90.93},"id":4642}, + {"name":"Ariake Portal","type":"Portal","wcid":12472,"cell":"F5590023","place":"outdoor","ns":-30.5,"ew":94.54,"dest":{"cell":"DF6A0035","place":"outdoor","ns":-16.69,"ew":77.07},"id":4643}, + {"name":"The Shadows","type":"Portal","wcid":43865,"cell":"F55A0103","place":"dungeon","dest":{"cell":"7E020325","place":"dungeon"},"minLevel":200,"desc":"In a dungeon (landblock F55A).","id":4644}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43561,"cell":"F65D0102","place":"dungeon","dest":{"cell":"E3D3000F","place":"outdoor","ns":67.46,"ew":79.81},"desc":"In a dungeon (landblock F65D).","id":4645}, + {"name":"Tusker Abode","type":"Portal","wcid":22654,"cell":"F67B0000","place":"outdoor","ns":-3.16,"ew":94.97,"dest":{"cell":"5C450384","place":"dungeon","name":"Tusker Abode"},"minLevel":20,"id":4646}, + {"name":"Tusker Quarters","type":"Portal","wcid":22692,"cell":"F67C0000","place":"outdoor","ns":-2.26,"ew":95.6,"dest":{"cell":"5B4A0210","place":"dungeon","name":"Tusker Quarters"},"minLevel":30,"id":4647}, + {"name":"Tusker Freehold","type":"Portal","wcid":22672,"cell":"F67D0000","place":"outdoor","ns":-1.58,"ew":95.54,"dest":{"cell":"58480128","place":"dungeon","name":"Tusker Freehold"},"minLevel":25,"id":4648}, + {"name":"Portal to Town Network","type":"Portal","wcid":42852,"cell":"F6820033","place":"outdoor","ns":2.31,"ew":95.46,"dest":{"cell":"00070145","place":"dungeon","name":"Town Network"},"desc":"This portal goes to the Town Network, a place which connects many of the towns of Dereth.","id":4649}, + {"name":"Ancient Cloister","type":"Portal","wcid":38730,"cell":"F7180100","place":"dungeon","dest":{"cell":"00EB014E","place":"dungeon"},"minLevel":150,"quest":true,"desc":"In a dungeon (landblock F718).","id":4650}, + {"name":"Ithaenc Archipelago","type":"Portal","wcid":38075,"cell":"F7300104","place":"building","ns":-63.1,"ew":96.0,"dest":{"cell":"EE18001A","place":"outdoor","ns":-82.57,"ew":88.8},"id":4651}, + {"name":"Olthoi Tunnel","type":"Portal","wcid":43591,"cell":"F7300128","place":"building","ns":-62.76,"ew":96.2,"dest":{"cell":"E4CF000D","place":"outdoor","ns":64.1,"ew":80.6},"id":4652}, + {"name":"Damp Caverns Portal","type":"Portal","wcid":5503,"cell":"F7570000","place":"outdoor","ns":-31.72,"ew":96.03,"dest":{"cell":"014D0191","place":"dungeon","name":"Damp Caverns"},"minLevel":5,"id":4653}, + {"name":"Shadowy Refuge","type":"Portal","wcid":45726,"cell":"F75D0020","place":"outdoor","ns":-26.77,"ew":96.01,"dest":{"cell":"576E0187","place":"dungeon","name":"Shadowy Refuge"},"minLevel":150,"quest":true,"id":4654}, + {"name":"Tusker Habitat","type":"Portal","wcid":22678,"cell":"F77E0000","place":"outdoor","ns":-0.51,"ew":95.87,"dest":{"cell":"5B470177","place":"dungeon","name":"Tusker Habitat"},"minLevel":25,"id":4655}, + {"name":"Exit Portal","type":"Portal","wcid":22647,"cell":"F7840396","place":"underground","ns":5.73,"ew":97.1,"dest":{"cell":"F684003D","place":"outdoor","ns":4.13,"ew":95.56},"id":4656}, + {"name":"Small Temple","type":"Portal","wcid":8478,"cell":"F8190100","place":"underground","ns":-81.82,"ew":97.0,"dest":{"cell":"02C0011D","place":"dungeon"},"id":4657}, + {"name":"Mayoi Beach Portal","type":"Portal","wcid":8617,"cell":"F81C0000","place":"outdoor","ns":-79.2,"ew":96.89,"dest":{"cell":"E633003C","place":"outdoor","ns":-60.82,"ew":82.78},"id":4658}, + {"name":"Blessed Cave","type":"Portal","wcid":72782,"cell":"F81E0506","place":"underground","ns":-77.63,"ew":96.75,"dest":{"cell":"F81E04C8","place":"underground","ns":-77.5,"ew":96.82},"minLevel":150,"quest":true,"id":4659}, + {"name":"Surface","type":"Portal","wcid":72783,"cell":"F81E04C9","place":"underground","ns":-77.48,"ew":96.84,"dest":{"cell":"F81E0105","place":"building","ns":-77.58,"ew":96.78},"minLevel":150,"id":4660}, + {"name":"Surface","type":"Portal","wcid":72783,"cell":"F81E0196","place":"underground","ns":-77.38,"ew":96.53,"dest":{"cell":"F81E0105","place":"building","ns":-77.58,"ew":96.78},"minLevel":150,"id":4661}, + {"name":"Surface","type":"Portal","wcid":72783,"cell":"F81E03F3","place":"underground","ns":-77.48,"ew":96.68,"dest":{"cell":"F81E0105","place":"building","ns":-77.58,"ew":96.78},"minLevel":150,"id":4662}, + {"name":"Moarsmen Spawning Grounds","type":"Portal","wcid":8584,"cell":"F8280101","place":"building","ns":-69.62,"ew":96.5,"dest":{"cell":"02B502C1","place":"dungeon","name":"Moarsmen Spawning Grounds"},"id":4663}, + {"name":"Tusker Cavern","type":"Portal","wcid":22667,"cell":"F8800000","place":"outdoor","ns":1.01,"ew":96.88,"dest":{"cell":"5C430272","place":"dungeon","name":"Tusker Cavern"},"minLevel":15,"id":4664}, + {"name":"Small Temple","type":"Portal","wcid":8480,"cell":"F9210100","place":"underground","ns":-75.02,"ew":97.5,"dest":{"cell":"02BF011D","place":"dungeon"},"id":4665}, + {"name":"Celestial Hand Freebooter Keep Black Market Portal","type":"Portal","wcid":80335,"cell":"F92F0284","place":"building","ns":-64.07,"ew":97.42,"dest":{"cell":"F92F0266","place":"building","ns":-64.04,"ew":97.44},"minLevel":180,"quest":true,"desc":"You must be a member of the Society of the Celestial Hand to enter this Portal.","id":4666}, + {"name":"Eldrytch Web Freebooter Keep Black Market Portal","type":"Portal","wcid":80336,"cell":"F92F0284","place":"building","ns":-64.07,"ew":97.42,"dest":{"cell":"F92F0266","place":"building","ns":-64.04,"ew":97.44},"minLevel":180,"quest":true,"desc":"You must be a member of the Society of the Eldrytch Web to enter this Portal.","id":4667}, + {"name":"Radiant Blood Freebooter Keep Black Market Portal","type":"Portal","wcid":80337,"cell":"F92F0284","place":"building","ns":-64.07,"ew":97.42,"dest":{"cell":"F92F0266","place":"building","ns":-64.04,"ew":97.44},"minLevel":180,"quest":true,"desc":"You must be a member of the Society of the Radiant Blood to enter this Portal.","id":4668}, + {"name":"Freebooter Keep","type":"Portal","wcid":80398,"cell":"F92F016D","place":"building","ns":-63.87,"ew":97.15,"dest":{"cell":"F92F0293","place":"building","ns":-64.07,"ew":97.52},"minLevel":180,"id":4669}, + {"name":"Surface","type":"Portal","wcid":43258,"cell":"F93B03C5","place":"dungeon","dest":{"cell":"F93B0020","place":"outdoor","ns":-53.98,"ew":97.6},"desc":"In a dungeon (landblock F93B).","id":4670}, + {"name":"Surface","type":"Portal","wcid":43202,"cell":"F93B03D5","place":"dungeon","dest":{"cell":"21760036","place":"outdoor","ns":-7.0,"ew":-74.9},"desc":"In a dungeon (landblock F93B).","id":4671}, + {"name":"Surface","type":"Portal","wcid":43258,"cell":"F93B0694","place":"dungeon","dest":{"cell":"F93B0020","place":"outdoor","ns":-53.98,"ew":97.6},"desc":"In a dungeon (landblock F93B).","id":4672}, + {"name":"Mysterious Portal","type":"Portal","wcid":43257,"cell":"F93B071B","place":"dungeon","dest":{"cell":"F93B0737","place":"dungeon"},"minLevel":180,"quest":true,"desc":"A portal crackling with defensive magics. Only those properly protected from its fluxuations may enter. In a dungeon (landblock F93B).","id":4673}, + {"name":"Surface","type":"Portal","wcid":43258,"cell":"F93B0740","place":"dungeon","dest":{"cell":"F93B0020","place":"outdoor","ns":-53.98,"ew":97.6},"desc":"In a dungeon (landblock F93B).","id":4674}, + {"name":"Surface","type":"Portal","wcid":43258,"cell":"F93B0131","place":"dungeon","dest":{"cell":"F93B0020","place":"outdoor","ns":-53.98,"ew":97.6},"desc":"In a dungeon (landblock F93B).","id":4675}, + {"name":"Tusker Retreat","type":"Portal","wcid":22694,"cell":"F97E0000","place":"outdoor","ns":-0.67,"ew":97.94,"dest":{"cell":"5C490138","place":"dungeon","name":"Tusker Retreat"},"minLevel":5,"id":4676}, + {"name":"Tusker Cave","type":"Portal","wcid":22665,"cell":"F97F0000","place":"outdoor","ns":0.4,"ew":97.38,"dest":{"cell":"5B460100","place":"dungeon","name":"Tusker Cave"},"minLevel":12,"id":4677}, + {"name":"Tusker Burrow","type":"Portal","wcid":22663,"cell":"F9810000","place":"outdoor","ns":2.03,"ew":97.98,"dest":{"cell":"57480210","place":"dungeon","name":"Tusker Burrow"},"id":4678}, + {"name":"Falatacot Vault","type":"Portal","wcid":33788,"cell":"FA220100","place":"dungeon","dest":{"cell":"007201E4","place":"dungeon"},"minLevel":101,"maxLevel":150,"quest":true,"desc":"In a dungeon (landblock FA22).","id":4679}, + {"name":"Tusker Grotto","type":"Portal","wcid":22676,"cell":"FA7E0000","place":"outdoor","ns":-0.92,"ew":98.38,"dest":{"cell":"5C470183","place":"dungeon","name":"Tusker Grotto"},"minLevel":12,"id":4680}, + {"name":"Tusker Lodge","type":"Portal","wcid":22688,"cell":"FA7F0000","place":"outdoor","ns":0.15,"ew":98.08,"dest":{"cell":"57490102","place":"dungeon","name":"Tusker Lodge"},"minLevel":5,"id":4681}, + {"name":"Reijiri","type":"NPC","wcid":30389,"cell":"00030100","place":"dungeon","id":4682,"desc":"The Littlest Niffis. In a dungeon (landblock 0003)."}, + {"name":"Barkeep Hosaam","type":"Vendor","wcid":42802,"cell":"00070114","place":"dungeon","id":4683,"desc":"Barkeeper. In Town Network."}, + {"name":"Barkeep Devra","type":"Vendor","wcid":42803,"cell":"00070114","place":"dungeon","id":4684,"desc":"Barkeeper. In Town Network."}, + {"name":"Barkeep Jauhar","type":"Vendor","wcid":42804,"cell":"00070114","place":"dungeon","id":4685,"desc":"Barkeeper. In Town Network."}, + {"name":"Barkeeper AmberJill","type":"Vendor","wcid":42799,"cell":"0007013F","place":"dungeon","id":4686,"desc":"Barkeeper. In Town Network."}, + {"name":"Barkeeper Edsel","type":"Vendor","wcid":42800,"cell":"0007013F","place":"dungeon","id":4687,"desc":"Barkeeper. In Town Network."}, + {"name":"Barkeeper Creighton","type":"Vendor","wcid":42801,"cell":"0007013F","place":"dungeon","id":4688,"desc":"Barkeeper. In Town Network."}, + {"name":"Barkeeper Lazzaro","type":"Vendor","wcid":42805,"cell":"0007014B","place":"dungeon","id":4689,"desc":"Barkeeper. In Town Network."}, + {"name":"Barkeeper Benedetta","type":"Vendor","wcid":42806,"cell":"0007014B","place":"dungeon","id":4690,"desc":"Barkeeper. In Town Network."}, + {"name":"Barkeeper Rafaele","type":"Vendor","wcid":42807,"cell":"0007014B","place":"dungeon","id":4691,"desc":"Barkeeper. In Town Network."}, + {"name":"Hanadi the Barkeeper","type":"Vendor","wcid":42808,"cell":"00070178","place":"dungeon","id":4692,"desc":"Barkeeper. In Town Network."}, + {"name":"Junjie the Barkeeper","type":"Vendor","wcid":42809,"cell":"00070178","place":"dungeon","id":4693,"desc":"Barkeeper. In Town Network."}, + {"name":"Xiao Hong the Barkeeper","type":"Vendor","wcid":42810,"cell":"00070178","place":"dungeon","id":4694,"desc":"Barkeeper. In Town Network."}, + {"name":"Royal Guard","type":"NPC","wcid":30758,"cell":"001103A5","place":"dungeon","id":4695,"desc":"In a dungeon (landblock 0011)."}, + {"name":"Royal Guard","type":"NPC","wcid":30760,"cell":"001103A9","place":"dungeon","id":4696,"desc":"In a dungeon (landblock 0011)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001103B7","place":"dungeon","id":4697,"desc":"In a dungeon (landblock 0011)."}, + {"name":"Royal Guard","type":"NPC","wcid":30758,"cell":"001103BC","place":"dungeon","id":4698,"desc":"In a dungeon (landblock 0011)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001103C0","place":"dungeon","id":4699,"desc":"In a dungeon (landblock 0011)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001103C4","place":"dungeon","id":4700,"desc":"In a dungeon (landblock 0011)."}, + {"name":"Royal Guard","type":"NPC","wcid":30758,"cell":"001203A5","place":"dungeon","id":4701,"desc":"In a dungeon (landblock 0012)."}, + {"name":"Royal Guard","type":"NPC","wcid":30760,"cell":"001203A9","place":"dungeon","id":4702,"desc":"In a dungeon (landblock 0012)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001203B7","place":"dungeon","id":4703,"desc":"In a dungeon (landblock 0012)."}, + {"name":"Royal Guard","type":"NPC","wcid":30758,"cell":"001203BC","place":"dungeon","id":4704,"desc":"In a dungeon (landblock 0012)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001203C0","place":"dungeon","id":4705,"desc":"In a dungeon (landblock 0012)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001203C4","place":"dungeon","id":4706,"desc":"In a dungeon (landblock 0012)."}, + {"name":"Royal Guard","type":"NPC","wcid":30758,"cell":"001303A5","place":"dungeon","id":4707,"desc":"In a dungeon (landblock 0013)."}, + {"name":"Royal Guard","type":"NPC","wcid":30760,"cell":"001303A9","place":"dungeon","id":4708,"desc":"In a dungeon (landblock 0013)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001303B7","place":"dungeon","id":4709,"desc":"In a dungeon (landblock 0013)."}, + {"name":"Royal Guard","type":"NPC","wcid":30758,"cell":"001303BC","place":"dungeon","id":4710,"desc":"In a dungeon (landblock 0013)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001303C0","place":"dungeon","id":4711,"desc":"In a dungeon (landblock 0013)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001303C4","place":"dungeon","id":4712,"desc":"In a dungeon (landblock 0013)."}, + {"name":"Royal Guard","type":"NPC","wcid":30758,"cell":"001403A5","place":"dungeon","id":4713,"desc":"In a dungeon (landblock 0014)."}, + {"name":"Royal Guard","type":"NPC","wcid":30760,"cell":"001403A9","place":"dungeon","id":4714,"desc":"In a dungeon (landblock 0014)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001403B7","place":"dungeon","id":4715,"desc":"In a dungeon (landblock 0014)."}, + {"name":"Royal Guard","type":"NPC","wcid":30758,"cell":"001403BC","place":"dungeon","id":4716,"desc":"In a dungeon (landblock 0014)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001403C0","place":"dungeon","id":4717,"desc":"In a dungeon (landblock 0014)."}, + {"name":"Royal Guard","type":"NPC","wcid":30759,"cell":"001403C4","place":"dungeon","id":4718,"desc":"In a dungeon (landblock 0014)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39810,"cell":"001F0131","place":"dungeon","id":4719,"desc":"In a dungeon (landblock 001F)."}, + {"name":"Baby Thrungus","type":"NPC","wcid":30980,"cell":"0029028A","place":"dungeon","id":4720,"desc":"In Thrungus Hole."}, + {"name":"Baby Thrungus","type":"NPC","wcid":30974,"cell":"00290235","place":"dungeon","id":4721,"desc":"In Thrungus Hole."}, + {"name":"Baby Thrungus","type":"NPC","wcid":30975,"cell":"0029028D","place":"dungeon","id":4722,"desc":"In Thrungus Hole."}, + {"name":"Baby Thrungus","type":"NPC","wcid":30976,"cell":"002901AB","place":"dungeon","id":4723,"desc":"In Thrungus Hole."}, + {"name":"Baby Thrungus","type":"NPC","wcid":30977,"cell":"00290101","place":"dungeon","id":4724,"desc":"In Thrungus Hole."}, + {"name":"Baby Thrungus","type":"NPC","wcid":30978,"cell":"0029013A","place":"dungeon","id":4725,"desc":"In Thrungus Hole."}, + {"name":"Exploration Marker","type":"NPC","wcid":39839,"cell":"002B010C","place":"dungeon","id":4726,"desc":"In Egg Orchard."}, + {"name":"Arwyth Margyle","type":"NPC","wcid":70055,"cell":"00300190","place":"dungeon","id":4727,"desc":"Lt. Commander of Fort Tethana. In Renegade Incursion."}, + {"name":"Soldier","type":"NPC","wcid":70035,"cell":"0030019A","place":"dungeon","id":4728,"desc":"Fort Tethana Guardsman. In Renegade Incursion."}, + {"name":"Soldier","type":"NPC","wcid":70036,"cell":"0030019B","place":"dungeon","id":4729,"desc":"Fort Tethana Guardsman. In Renegade Incursion."}, + {"name":"Balior","type":"NPC","wcid":70294,"cell":"004401FC","place":"dungeon","id":4730,"desc":"In a dungeon (landblock 0044)."}, + {"name":"Mana Barrier","type":"NPC","wcid":80028,"cell":"004805E0","place":"dungeon","id":4731,"desc":"In Viamontian Direlands Mine."}, + {"name":"House Golem","type":"NPC","wcid":34504,"cell":"005001E4","place":"dungeon","id":4732,"desc":"Custodian of Artifacts. In a dungeon (landblock 0050)."}, + {"name":"House Golem","type":"NPC","wcid":34498,"cell":"005002A1","place":"dungeon","id":4733,"desc":"Custodian of Artifacts. In a dungeon (landblock 0050)."}, + {"name":"House Golem","type":"NPC","wcid":34503,"cell":"0050018D","place":"dungeon","id":4734,"desc":"Custodian of Artifacts. In a dungeon (landblock 0050)."}, + {"name":"Tanada Shrine of Earth","type":"NPC","wcid":87665,"cell":"00570194","place":"dungeon","id":4735,"desc":"In a dungeon (landblock 0057)."}, + {"name":"Tanada Shrine of Stone","type":"NPC","wcid":87666,"cell":"0057014C","place":"dungeon","id":4736,"desc":"In a dungeon (landblock 0057)."}, + {"name":"Tanada Shrine of Metal","type":"NPC","wcid":87667,"cell":"00570104","place":"dungeon","id":4737,"desc":"In a dungeon (landblock 0057)."}, + {"name":"Master Seijuro","type":"NPC","wcid":87664,"cell":"0057029B","place":"dungeon","id":4738,"desc":"Enlightened Master of the Tanada. In a dungeon (landblock 0057)."}, + {"name":"Captive","type":"NPC","wcid":70382,"cell":"00580100","place":"dungeon","id":4739,"desc":"In a dungeon (landblock 0058)."}, + {"name":"Captive","type":"NPC","wcid":70383,"cell":"00590100","place":"dungeon","id":4740,"desc":"In a dungeon (landblock 0059)."}, + {"name":"Captive","type":"NPC","wcid":70384,"cell":"005A0100","place":"dungeon","id":4741,"desc":"In a dungeon (landblock 005A)."}, + {"name":"Ulgrim the Unquiet","type":"NPC","wcid":70995,"cell":"005C0100","place":"dungeon","id":4742,"desc":"Mini-Ulgrim. In a dungeon (landblock 005C)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E021B","place":"dungeon","id":4743,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E0219","place":"dungeon","id":4744,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E0214","place":"dungeon","id":4745,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E01B4","place":"dungeon","id":4746,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"005E01B4","place":"dungeon","id":4747,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"005E01B6","place":"dungeon","id":4748,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"005E01B6","place":"dungeon","id":4749,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"005E0174","place":"dungeon","id":4750,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E0174","place":"dungeon","id":4751,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"005E0174","place":"dungeon","id":4752,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"005E0174","place":"dungeon","id":4753,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"005E01A9","place":"dungeon","id":4754,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"005E01A9","place":"dungeon","id":4755,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"005E01A7","place":"dungeon","id":4756,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E01A7","place":"dungeon","id":4757,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Harbinger's Lair","type":"NPC","wcid":33246,"cell":"005E010A","place":"dungeon","id":4758,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E020B","place":"dungeon","id":4759,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E020A","place":"dungeon","id":4760,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E0204","place":"dungeon","id":4761,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"005E018F","place":"dungeon","id":4762,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E018F","place":"dungeon","id":4763,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"005E0191","place":"dungeon","id":4764,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"005E0191","place":"dungeon","id":4765,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E0170","place":"dungeon","id":4766,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"005E0170","place":"dungeon","id":4767,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"005E0170","place":"dungeon","id":4768,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"005E0170","place":"dungeon","id":4769,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"005E019E","place":"dungeon","id":4770,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"005E019E","place":"dungeon","id":4771,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E019C","place":"dungeon","id":4772,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"005E019C","place":"dungeon","id":4773,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"005E012E","place":"dungeon","id":4774,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"005E012E","place":"dungeon","id":4775,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"005E012E","place":"dungeon","id":4776,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"005E012E","place":"dungeon","id":4777,"desc":"In a dungeon (landblock 005E)."}, + {"name":"Empty Plate","type":"NPC","wcid":80089,"cell":"005F0216","place":"dungeon","id":4778,"desc":"In a dungeon (landblock 005F)."}, + {"name":"Empty Plate","type":"NPC","wcid":80090,"cell":"005F01C4","place":"dungeon","id":4779,"desc":"In a dungeon (landblock 005F)."}, + {"name":"Empty Plate","type":"NPC","wcid":80091,"cell":"005F020E","place":"dungeon","id":4780,"desc":"In a dungeon (landblock 005F)."}, + {"name":"Gladys the Golem Waitress","type":"NPC","wcid":80092,"cell":"005F01FE","place":"dungeon","id":4781,"desc":"Hostess with the Mostest. In a dungeon (landblock 005F)."}, + {"name":"Corpse of Pon Mi","type":"NPC","wcid":80094,"cell":"005F016E","place":"dungeon","id":4782,"desc":"In a dungeon (landblock 005F)."}, + {"name":"Corpse of Pon Mi","type":"NPC","wcid":80094,"cell":"005F016C","place":"dungeon","id":4783,"desc":"In a dungeon (landblock 005F)."}, + {"name":"Corpse of Pon Mi","type":"NPC","wcid":80094,"cell":"005F016B","place":"dungeon","id":4784,"desc":"In a dungeon (landblock 005F)."}, + {"name":"Corpse of Pon Mi","type":"NPC","wcid":80094,"cell":"005F016D","place":"dungeon","id":4785,"desc":"In a dungeon (landblock 005F)."}, + {"name":"Ley Line","type":"NPC","wcid":34952,"cell":"0062016C","place":"dungeon","id":4786,"desc":"In a dungeon (landblock 0062)."}, + {"name":"Ley Line","type":"NPC","wcid":34952,"cell":"0062016B","place":"dungeon","id":4787,"desc":"In a dungeon (landblock 0062)."}, + {"name":"Ley Line","type":"NPC","wcid":34952,"cell":"0062016A","place":"dungeon","id":4788,"desc":"In a dungeon (landblock 0062)."}, + {"name":"Ley Line","type":"NPC","wcid":34952,"cell":"00620169","place":"dungeon","id":4789,"desc":"In a dungeon (landblock 0062)."}, + {"name":"Ley Line","type":"NPC","wcid":34952,"cell":"00620168","place":"dungeon","id":4790,"desc":"In a dungeon (landblock 0062)."}, + {"name":"Corpse of a Servitor of Asheron","type":"NPC","wcid":35104,"cell":"00620166","place":"dungeon","id":4791,"desc":"In a dungeon (landblock 0062)."}, + {"name":"Corpse of a Servitor of Asheron","type":"NPC","wcid":35104,"cell":"00620165","place":"dungeon","id":4792,"desc":"In a dungeon (landblock 0062)."}, + {"name":"Corpse of a Servitor of Asheron","type":"NPC","wcid":35104,"cell":"00620164","place":"dungeon","id":4793,"desc":"In a dungeon (landblock 0062)."}, + {"name":"Corpse of a Servitor of Asheron","type":"NPC","wcid":35104,"cell":"00620169","place":"dungeon","id":4794,"desc":"In a dungeon (landblock 0062)."}, + {"name":"Corpse of a Servitor of Asheron","type":"NPC","wcid":35103,"cell":"00620167","place":"dungeon","id":4795,"desc":"In a dungeon (landblock 0062)."}, + {"name":"Corpse of a Servitor of Asheron","type":"NPC","wcid":35103,"cell":"00620163","place":"dungeon","id":4796,"desc":"In a dungeon (landblock 0062)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39839,"cell":"0064010C","place":"dungeon","id":4797,"desc":"In Egg Orchard East."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"006C0286","place":"dungeon","id":4798,"desc":"In a dungeon (landblock 006C)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39843,"cell":"00700101","place":"dungeon","id":4799,"desc":"In a dungeon (landblock 0070)."}, + {"name":"Rock","type":"NPC","wcid":87579,"cell":"007404AE","place":"dungeon","id":4800,"desc":"In Black Spear Temple."}, + {"name":"Rock","type":"NPC","wcid":87580,"cell":"0074049A","place":"dungeon","id":4801,"desc":"In Black Spear Temple."}, + {"name":"Rock","type":"NPC","wcid":87581,"cell":"00740499","place":"dungeon","id":4802,"desc":"In Black Spear Temple."}, + {"name":"Rock","type":"NPC","wcid":87582,"cell":"00740415","place":"dungeon","id":4803,"desc":"In Black Spear Temple."}, + {"name":"Rock","type":"NPC","wcid":87583,"cell":"00740417","place":"dungeon","id":4804,"desc":"In Black Spear Temple."}, + {"name":"Rock","type":"NPC","wcid":87584,"cell":"00740419","place":"dungeon","id":4805,"desc":"In Black Spear Temple."}, + {"name":"Rock","type":"NPC","wcid":87585,"cell":"0074040B","place":"dungeon","id":4806,"desc":"In Black Spear Temple."}, + {"name":"Rock","type":"NPC","wcid":87586,"cell":"00740409","place":"dungeon","id":4807,"desc":"In Black Spear Temple."}, + {"name":"Rock","type":"NPC","wcid":87586,"cell":"00740407","place":"dungeon","id":4808,"desc":"In Black Spear Temple."}, + {"name":"Tanada Shrine of Storms","type":"NPC","wcid":87645,"cell":"007B0104","place":"dungeon","id":4809,"desc":"In Tanada House of Storms."}, + {"name":"Tanada Shrine of Wind","type":"NPC","wcid":87646,"cell":"007B0194","place":"dungeon","id":4810,"desc":"In Tanada House of Storms."}, + {"name":"Tanada Shrine of Breath","type":"NPC","wcid":87647,"cell":"007B014C","place":"dungeon","id":4811,"desc":"In Tanada House of Storms."}, + {"name":"Altar of Urdhinivix","type":"NPC","wcid":34306,"cell":"007C0134","place":"dungeon","id":4812,"desc":"In Soul Hunter's Lair."}, + {"name":"Broken Seal of the Elder Spirits","type":"NPC","wcid":33014,"cell":"007E0242","place":"dungeon","id":4813,"desc":"In a dungeon (landblock 007E)."}, + {"name":"Jasopo Bernarri","type":"NPC","wcid":33019,"cell":"00800124","place":"dungeon","id":4814,"desc":"In Rossu Morta Chapterhouse."}, + {"name":"Venara Basalleno","type":"Vendor","wcid":33021,"cell":"0080012D","place":"dungeon","id":4815,"desc":"Shopkeeper. In Rossu Morta Chapterhouse."}, + {"name":"Sandino Montegarre","type":"NPC","wcid":33020,"cell":"00800135","place":"dungeon","id":4816,"desc":"In Rossu Morta Chapterhouse."}, + {"name":"Rossu Morta Quartermaster","type":"Vendor","wcid":41730,"cell":"00800133","place":"dungeon","id":4817,"desc":"Vendor. In Rossu Morta Chapterhouse."}, + {"name":"Meerana du Renari","type":"NPC","wcid":33015,"cell":"00800129","place":"dungeon","id":4818,"desc":"Chapterhouse Chamberlain. In Rossu Morta Chapterhouse."}, + {"name":"Jathaq al-Nishadina","type":"NPC","wcid":33460,"cell":"00800133","place":"dungeon","id":4819,"desc":"In Rossu Morta Chapterhouse."}, + {"name":"Barsinni","type":"NPC","wcid":33194,"cell":"00800110","place":"dungeon","id":4820,"desc":"In Rossu Morta Chapterhouse."}, + {"name":"Crystal of Life Protections","type":"NPC","wcid":33451,"cell":"00800112","place":"dungeon","id":4821,"desc":"In Rossu Morta Chapterhouse."}, + {"name":"Mudris ibn Hadram","type":"Vendor","wcid":33000,"cell":"00810124","place":"dungeon","id":4822,"desc":"Archmage. In Whispering Blade Chapterhouse."}, + {"name":"Bortrom the Thrifty","type":"Vendor","wcid":33002,"cell":"0081012D","place":"dungeon","id":4823,"desc":"Shopkeeper. In Whispering Blade Chapterhouse."}, + {"name":"Koa Chai-La","type":"Vendor","wcid":33001,"cell":"00810135","place":"dungeon","id":4824,"desc":"Bowyer. In Whispering Blade Chapterhouse."}, + {"name":"Whispering Blade Quartermaster","type":"Vendor","wcid":41731,"cell":"00810133","place":"dungeon","id":4825,"desc":"Vendor. In Whispering Blade Chapterhouse."}, + {"name":"Varlanna","type":"NPC","wcid":33499,"cell":"00810133","place":"dungeon","id":4826,"desc":"Tracker. In Whispering Blade Chapterhouse."}, + {"name":"Eddred the Wolf","type":"NPC","wcid":32992,"cell":"00810129","place":"dungeon","id":4827,"desc":"Chapterhouse Chamberlain. In Whispering Blade Chapterhouse."}, + {"name":"Hassim","type":"NPC","wcid":33187,"cell":"00810110","place":"dungeon","id":4828,"desc":"Whispering Blade Factotum. In Whispering Blade Chapterhouse."}, + {"name":"Crystal of Life Protections","type":"NPC","wcid":33451,"cell":"00810112","place":"dungeon","id":4829,"desc":"In Whispering Blade Chapterhouse."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"008701F6","place":"dungeon","id":4830,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"008701FD","place":"dungeon","id":4831,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"00870260","place":"dungeon","id":4832,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"00870259","place":"dungeon","id":4833,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"008701FE","place":"dungeon","id":4834,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"00870261","place":"dungeon","id":4835,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"008703F5","place":"dungeon","id":4836,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"008703D7","place":"dungeon","id":4837,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"00870340","place":"dungeon","id":4838,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"00870341","place":"dungeon","id":4839,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"00870342","place":"dungeon","id":4840,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"008703D9","place":"dungeon","id":4841,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"008703DA","place":"dungeon","id":4842,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"008703DB","place":"dungeon","id":4843,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"008703DE","place":"dungeon","id":4844,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"008703DD","place":"dungeon","id":4845,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Falatacot Trap","type":"NPC","wcid":87636,"cell":"0087033F","place":"dungeon","id":4846,"desc":"In Ikzisik Tika Ri Zikma."}, + {"name":"Sealed Olthoi Passage","type":"NPC","wcid":35827,"cell":"0088012F","place":"dungeon","id":4847,"desc":"In a dungeon (landblock 0088)."}, + {"name":"Black Book of Salt and Ash","type":"NPC","wcid":32751,"cell":"008902FA","place":"dungeon","id":4848,"desc":"In a dungeon (landblock 0089)."}, + {"name":"Black Book of Salt and Ash","type":"NPC","wcid":32751,"cell":"008902B1","place":"dungeon","id":4849,"desc":"In a dungeon (landblock 0089)."}, + {"name":"Black Book of Salt and Ash","type":"NPC","wcid":32751,"cell":"00890256","place":"dungeon","id":4850,"desc":"In a dungeon (landblock 0089)."}, + {"name":"Black Book of Salt and Ash","type":"NPC","wcid":32751,"cell":"008902BD","place":"dungeon","id":4851,"desc":"In a dungeon (landblock 0089)."}, + {"name":"Black Book of Salt and Ash","type":"NPC","wcid":32751,"cell":"00890262","place":"dungeon","id":4852,"desc":"In a dungeon (landblock 0089)."}, + {"name":"Dark Monolith","type":"NPC","wcid":33060,"cell":"008A0291","place":"dungeon","id":4853,"desc":"In a dungeon (landblock 008A)."}, + {"name":"Hollow","type":"NPC","wcid":36204,"cell":"008C0121","place":"dungeon","id":4854,"desc":"In a dungeon (landblock 008C)."}, + {"name":"Hollow","type":"NPC","wcid":36199,"cell":"008C011D","place":"dungeon","id":4855,"desc":"In a dungeon (landblock 008C)."}, + {"name":"Hollow","type":"NPC","wcid":36202,"cell":"008C0145","place":"dungeon","id":4856,"desc":"In a dungeon (landblock 008C)."}, + {"name":"Hollow","type":"NPC","wcid":36203,"cell":"008C0101","place":"dungeon","id":4857,"desc":"In a dungeon (landblock 008C)."}, + {"name":"Hollow","type":"NPC","wcid":36201,"cell":"008C0129","place":"dungeon","id":4858,"desc":"In a dungeon (landblock 008C)."}, + {"name":"Dobblar","type":"Vendor","wcid":34839,"cell":"009C012D","place":"dungeon","id":4859,"desc":"Shopkeeper. In a dungeon (landblock 009C)."}, + {"name":"Brozuu","type":"Vendor","wcid":34840,"cell":"009C012D","place":"dungeon","id":4860,"desc":"Archmage. In a dungeon (landblock 009C)."}, + {"name":"Drogur","type":"NPC","wcid":34841,"cell":"009C0270","place":"dungeon","id":4861,"desc":"Protector of Kor-Gursha. In a dungeon (landblock 009C)."}, + {"name":"Collector Golem","type":"NPC","wcid":34938,"cell":"009C0144","place":"dungeon","id":4862,"desc":"Representative of Asheron. In a dungeon (landblock 009C)."}, + {"name":"Rheegur","type":"NPC","wcid":34842,"cell":"009C0172","place":"dungeon","id":4863,"desc":"Memory of Kor-Gursha. In a dungeon (landblock 009C)."}, + {"name":"Doruuk","type":"NPC","wcid":34849,"cell":"009C0137","place":"dungeon","id":4864,"desc":"Fungus Cutter. In a dungeon (landblock 009C)."}, + {"name":"Nimeruuk","type":"NPC","wcid":34851,"cell":"009C0137","place":"dungeon","id":4865,"desc":"Purveyor of Fine Fungus. In a dungeon (landblock 009C)."}, + {"name":"Furgal","type":"NPC","wcid":34834,"cell":"009C0140","place":"dungeon","id":4866,"desc":"Mushroom Collector. In a dungeon (landblock 009C)."}, + {"name":"Tibik","type":"NPC","wcid":35209,"cell":"009C0143","place":"dungeon","id":4867,"desc":"Gatherer. In a dungeon (landblock 009C)."}, + {"name":"Kuurak","type":"NPC","wcid":34951,"cell":"009C012D","place":"dungeon","id":4868,"desc":"Weaponsmith. In a dungeon (landblock 009C)."}, + {"name":"Torgluuk, High Shaman of Kor-Gursha","type":"NPC","wcid":34950,"cell":"009C0191","place":"dungeon","id":4869,"desc":"In a dungeon (landblock 009C)."}, + {"name":"Scout Leader Tmauruk","type":"NPC","wcid":34956,"cell":"009C0191","place":"dungeon","id":4870,"desc":"Vagabond. In a dungeon (landblock 009C)."}, + {"name":"Gruuk'lar","type":"NPC","wcid":34729,"cell":"009C0191","place":"dungeon","id":4871,"desc":"Village Guardian. In a dungeon (landblock 009C)."}, + {"name":"Kurket","type":"NPC","wcid":34823,"cell":"009C0190","place":"dungeon","id":4872,"desc":"Ranger Ruuk. In a dungeon (landblock 009C)."}, + {"name":"Mohor","type":"NPC","wcid":34822,"cell":"009C0190","place":"dungeon","id":4873,"desc":"Fiendish Huntsman. In a dungeon (landblock 009C)."}, + {"name":"Brogosh","type":"NPC","wcid":34821,"cell":"009C0190","place":"dungeon","id":4874,"desc":"Dead Eye Hunter. In a dungeon (landblock 009C)."}, + {"name":"Shiruuk","type":"NPC","wcid":34820,"cell":"009C0190","place":"dungeon","id":4875,"desc":"Basher Slasher. In a dungeon (landblock 009C)."}, + {"name":"Kuuru","type":"NPC","wcid":34826,"cell":"009C01A5","place":"dungeon","id":4876,"desc":"King Toad Hunter. In a dungeon (landblock 009C)."}, + {"name":"Kushuk","type":"NPC","wcid":34825,"cell":"009C01A3","place":"dungeon","id":4877,"desc":"Guruk Hunter. In a dungeon (landblock 009C)."}, + {"name":"Borsh","type":"NPC","wcid":34824,"cell":"009C01A3","place":"dungeon","id":4878,"desc":"Monster Killer. In a dungeon (landblock 009C)."}, + {"name":"Altar","type":"NPC","wcid":36691,"cell":"009F0214","place":"dungeon","id":4879,"desc":"In a dungeon (landblock 009F)."}, + {"name":"Trial of the Heart Portal","type":"NPC","wcid":36692,"cell":"009F0159","place":"dungeon","id":4880,"desc":"In a dungeon (landblock 009F)."}, + {"name":"Painting of the Building of Linvak Tukal","type":"NPC","wcid":36693,"cell":"009F0138","place":"dungeon","id":4881,"desc":"In a dungeon (landblock 009F)."}, + {"name":"Pillar of the Mind","type":"NPC","wcid":36696,"cell":"009F0161","place":"dungeon","id":4882,"desc":"In a dungeon (landblock 009F)."}, + {"name":"Pillar of the Heart","type":"NPC","wcid":36695,"cell":"009F0158","place":"dungeon","id":4883,"desc":"In a dungeon (landblock 009F)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00A30313","place":"dungeon","id":4884,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00A30310","place":"dungeon","id":4885,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00A302CB","place":"dungeon","id":4886,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00A3028B","place":"dungeon","id":4887,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00A302E7","place":"dungeon","id":4888,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00A30241","place":"dungeon","id":4889,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00A3026C","place":"dungeon","id":4890,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00A30263","place":"dungeon","id":4891,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00A3023A","place":"dungeon","id":4892,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00A3024F","place":"dungeon","id":4893,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00A30261","place":"dungeon","id":4894,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00A302C3","place":"dungeon","id":4895,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00A302DB","place":"dungeon","id":4896,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36115,"cell":"00A3030B","place":"dungeon","id":4897,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36116,"cell":"00A30180","place":"dungeon","id":4898,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36117,"cell":"00A301C6","place":"dungeon","id":4899,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36092,"cell":"00A301E9","place":"dungeon","id":4900,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36107,"cell":"00A3012D","place":"dungeon","id":4901,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00A30253","place":"dungeon","id":4902,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00A3029D","place":"dungeon","id":4903,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00A30272","place":"dungeon","id":4904,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00A302BA","place":"dungeon","id":4905,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Human","type":"NPC","wcid":36080,"cell":"00A301C5","place":"dungeon","id":4906,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Human","type":"NPC","wcid":36077,"cell":"00A30193","place":"dungeon","id":4907,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Human","type":"NPC","wcid":36078,"cell":"00A30190","place":"dungeon","id":4908,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Human","type":"NPC","wcid":36124,"cell":"00A30197","place":"dungeon","id":4909,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Human","type":"NPC","wcid":36075,"cell":"00A30194","place":"dungeon","id":4910,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Human","type":"NPC","wcid":36079,"cell":"00A3018E","place":"dungeon","id":4911,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Human","type":"NPC","wcid":36121,"cell":"00A30195","place":"dungeon","id":4912,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Human","type":"NPC","wcid":36119,"cell":"00A30192","place":"dungeon","id":4913,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Human","type":"NPC","wcid":36082,"cell":"00A301D2","place":"dungeon","id":4914,"desc":"In a dungeon (landblock 00A3)."}, + {"name":"Claude Witnessing History Stopgap","type":"NPC","wcid":72393,"cell":"00A3010C","place":"dungeon","id":4915,"desc":"Stopgap. In a dungeon (landblock 00A3)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00A30194","place":"dungeon","id":4916,"desc":"Vision Quest Booter. In a dungeon (landblock 00A3)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00A3010C","place":"dungeon","id":4917,"desc":"Vision Quest Booter. In a dungeon (landblock 00A3)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00A301A0","place":"dungeon","id":4918,"desc":"Vision Quest Booter. In a dungeon (landblock 00A3)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00A3011F","place":"dungeon","id":4919,"desc":"Vision Quest Booter. In a dungeon (landblock 00A3)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00A30245","place":"dungeon","id":4920,"desc":"Vision Quest Booter. In a dungeon (landblock 00A3)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00A302FF","place":"dungeon","id":4921,"desc":"Vision Quest Booter. In a dungeon (landblock 00A3)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00A302AB","place":"dungeon","id":4922,"desc":"Vision Quest Booter. In a dungeon (landblock 00A3)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00A302F9","place":"dungeon","id":4923,"desc":"Vision Quest Booter. In a dungeon (landblock 00A3)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00A30180","place":"dungeon","id":4924,"desc":"Vision Quest Booter. In a dungeon (landblock 00A3)."}, + {"name":"Dojiro Sangi","type":"NPC","wcid":36608,"cell":"00A40451","place":"dungeon","id":4925,"desc":"Prodigal Isparian. In Hidden Laboratory."}, + {"name":"Shade of Dule","type":"NPC","wcid":36926,"cell":"00A70249","place":"dungeon","id":4926,"desc":"Walker of Dreams. In a dungeon (landblock 00A7)."}, + {"name":"Pool of Water","type":"NPC","wcid":73251,"cell":"00A80112","place":"dungeon","id":4927,"desc":"In Roots of the Deru Tree."}, + {"name":"Well of Blood","type":"NPC","wcid":73247,"cell":"00A9020D","place":"dungeon","id":4928,"desc":"In Trial of the Deep."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"00A90101","place":"dungeon","id":4929,"desc":"In Trial of the Deep."}, + {"name":"Vat of Olthoi Jelly","type":"NPC","wcid":73244,"cell":"00AA010A","place":"dungeon","id":4930,"desc":"In Olthoi Sanctuary."}, + {"name":"Statue of Death","type":"NPC","wcid":80102,"cell":"00AB0109","place":"dungeon","id":4931,"desc":"In a dungeon (landblock 00AB)."}, + {"name":"Statue of Illuminating Death","type":"NPC","wcid":80135,"cell":"00AB0108","place":"dungeon","id":4932,"desc":"In a dungeon (landblock 00AB)."}, + {"name":"Statue of Illuminating Death","type":"NPC","wcid":80136,"cell":"00AB010B","place":"dungeon","id":4933,"desc":"In a dungeon (landblock 00AB)."}, + {"name":"Statue of Illuminating Death","type":"NPC","wcid":80137,"cell":"00AB0118","place":"dungeon","id":4934,"desc":"In a dungeon (landblock 00AB)."}, + {"name":"Statue of Illuminating Death","type":"NPC","wcid":80138,"cell":"00AB013F","place":"dungeon","id":4935,"desc":"In a dungeon (landblock 00AB)."}, + {"name":"Statue of High Illumination","type":"NPC","wcid":80104,"cell":"00AB0103","place":"dungeon","id":4936,"desc":"In a dungeon (landblock 00AB)."}, + {"name":"Statue of Illuminating Death","type":"NPC","wcid":80103,"cell":"00AB0109","place":"dungeon","id":4937,"desc":"In a dungeon (landblock 00AB)."}, + {"name":"Statue of Extreme Illumination","type":"NPC","wcid":80105,"cell":"00AB010A","place":"dungeon","id":4938,"desc":"In a dungeon (landblock 00AB)."}, + {"name":"Statue of High Illumination","type":"NPC","wcid":80139,"cell":"00AB0110","place":"dungeon","id":4939,"desc":"In a dungeon (landblock 00AB)."}, + {"name":"Statue of Death","type":"NPC","wcid":80102,"cell":"00AC0115","place":"dungeon","id":4940,"desc":"In a dungeon (landblock 00AC)."}, + {"name":"Statue of Illuminating Death","type":"NPC","wcid":80103,"cell":"00AC0115","place":"dungeon","id":4941,"desc":"In a dungeon (landblock 00AC)."}, + {"name":"Statue of Illuminating Death","type":"NPC","wcid":80135,"cell":"00AC010F","place":"dungeon","id":4942,"desc":"In a dungeon (landblock 00AC)."}, + {"name":"Statue of Illuminating Death","type":"NPC","wcid":80136,"cell":"00AC011B","place":"dungeon","id":4943,"desc":"In a dungeon (landblock 00AC)."}, + {"name":"Statue of Extreme Illumination","type":"NPC","wcid":80105,"cell":"00AC0115","place":"dungeon","id":4944,"desc":"In a dungeon (landblock 00AC)."}, + {"name":"Statue of High Illumination","type":"NPC","wcid":80104,"cell":"00AC0100","place":"dungeon","id":4945,"desc":"In a dungeon (landblock 00AC)."}, + {"name":"Colosseum Coin Collector","type":"Vendor","wcid":36519,"cell":"00AF0139","place":"dungeon","id":4946,"desc":"Colosseum Vendor. In The Colosseum."}, + {"name":"Garbage Barrel","type":"NPC","wcid":34726,"cell":"00AF0118","place":"dungeon","id":4947,"desc":"In The Colosseum."}, + {"name":"Colosseum Arena","type":"NPC","wcid":34727,"cell":"00AF010F","place":"dungeon","id":4948,"desc":"In The Colosseum."}, + {"name":"Advanced Colosseum Arena","type":"NPC","wcid":34728,"cell":"00AF0138","place":"dungeon","id":4949,"desc":"In The Colosseum."}, + {"name":"Master Arbitrator","type":"NPC","wcid":34441,"cell":"00AF0117","place":"dungeon","id":4950,"desc":"Empyrean Servant. In The Colosseum."}, + {"name":"Colosseum Ticket Vendor","type":"NPC","wcid":34442,"cell":"00AF0139","place":"dungeon","id":4951,"desc":"Ticket Vendor. In The Colosseum."}, + {"name":"Gladiator Diemos","type":"NPC","wcid":35869,"cell":"00AF0142","place":"dungeon","id":4952,"desc":"In The Colosseum."}, + {"name":"The Master","type":"NPC","wcid":35870,"cell":"00AF0133","place":"dungeon","id":4953,"desc":"In The Colosseum."}, + {"name":"Arena of the Pumpkin King","type":"NPC","wcid":36532,"cell":"00AF0152","place":"dungeon","id":4954,"desc":"In The Colosseum."}, + {"name":"Eggsploder","type":"NPC","wcid":80151,"cell":"00AF0165","place":"dungeon","id":4955,"desc":"Stopgap. In The Colosseum."}, + {"name":"Ahumba","type":"NPC","wcid":87733,"cell":"00B50129","place":"dungeon","id":4956,"desc":"Shaman. In Mosswart Worship Cavern."}, + {"name":"Farnor the Archmage","type":"Vendor","wcid":38687,"cell":"00B7026A","place":"dungeon","id":4957,"desc":"Society Archmage. In Celestial Hand Stronghold."}, + {"name":"Shopkeeper Polly","type":"Vendor","wcid":38688,"cell":"00B7026A","place":"dungeon","id":4958,"desc":"Society Shopkeep. In Celestial Hand Stronghold."}, + {"name":"Celestial Hand Quartermaster","type":"Vendor","wcid":38574,"cell":"00B7026B","place":"dungeon","id":4959,"desc":"Society Officer. In Celestial Hand Stronghold."}, + {"name":"Master Statue of 'Moarsman City' Transport","type":"NPC","wcid":41176,"cell":"00B70295","place":"dungeon","id":4960,"desc":"In Celestial Hand Stronghold."}, + {"name":"Master Statue of 'Freebooter Isle' Transport","type":"NPC","wcid":41175,"cell":"00B70295","place":"dungeon","id":4961,"desc":"In Celestial Hand Stronghold."}, + {"name":"Promotions Officer","type":"NPC","wcid":38319,"cell":"00B7011D","place":"dungeon","id":4962,"desc":"Society Officer. In Celestial Hand Stronghold."}, + {"name":"Alderic","type":"NPC","wcid":41823,"cell":"00B7026C","place":"dungeon","id":4963,"desc":"Society Contractor. In Celestial Hand Stronghold."}, + {"name":"Khanldun","type":"NPC","wcid":41824,"cell":"00B7026C","place":"dungeon","id":4964,"desc":"Society Collector. In Celestial Hand Stronghold."}, + {"name":"Giri bint Ashud","type":"NPC","wcid":38418,"cell":"00B7026C","place":"dungeon","id":4965,"desc":"Jungle Flower Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Aldrion of the Celestial Hand","type":"NPC","wcid":38645,"cell":"00B7026C","place":"dungeon","id":4966,"desc":"Inspector of Adepts. In Celestial Hand Stronghold."}, + {"name":"Francesca du Orza","type":"NPC","wcid":38708,"cell":"00B7026C","place":"dungeon","id":4967,"desc":"Inspector of Knights. In Celestial Hand Stronghold."}, + {"name":"Keep Strategic Commander","type":"NPC","wcid":44389,"cell":"00B7025B","place":"dungeon","id":4968,"desc":"Society Officer. In Celestial Hand Stronghold."}, + {"name":"Edweena","type":"NPC","wcid":51269,"cell":"00B7026D","place":"dungeon","id":4969,"desc":"Mana Siphon Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Philonius Porbandar","type":"NPC","wcid":38330,"cell":"00B7026D","place":"dungeon","id":4970,"desc":"Inspector of Lords. In Celestial Hand Stronghold."}, + {"name":"Alicia Bladesworn","type":"NPC","wcid":38371,"cell":"00B7026D","place":"dungeon","id":4971,"desc":"Inspector of Masters. In Celestial Hand Stronghold."}, + {"name":"Society Sollerets Armorsmith","type":"NPC","wcid":38553,"cell":"00B70104","place":"dungeon","id":4972,"desc":"Society Armorsmith. In Celestial Hand Stronghold."}, + {"name":"Shishalti bint Jaffa","type":"NPC","wcid":38227,"cell":"00B7026E","place":"dungeon","id":4973,"desc":"Spawn Pools Task Master. In Celestial Hand Stronghold."}, + {"name":"Turiq al Qorra","type":"NPC","wcid":38703,"cell":"00B7026E","place":"dungeon","id":4974,"desc":"Wall Carving Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Streza du Vorchass","type":"NPC","wcid":38702,"cell":"00B7026E","place":"dungeon","id":4975,"desc":"Delivery Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Boroth Bearhand","type":"NPC","wcid":38603,"cell":"00B7026E","place":"dungeon","id":4976,"desc":"Falatacot Report Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Ali ibn Qasid","type":"NPC","wcid":38604,"cell":"00B7026E","place":"dungeon","id":4977,"desc":"Dark Isle Scout Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Narris","type":"NPC","wcid":41822,"cell":"00B7026E","place":"dungeon","id":4978,"desc":"Society Collector. In Celestial Hand Stronghold."}, + {"name":"Hidoshi Kawara","type":"NPC","wcid":38602,"cell":"00B7026E","place":"dungeon","id":4979,"desc":"Black Coral Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Kieran Stronghammer","type":"NPC","wcid":38421,"cell":"00B7026E","place":"dungeon","id":4980,"desc":"Blessed Moarsman Hunt Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Giovanni di Alduressa","type":"NPC","wcid":38417,"cell":"00B7026E","place":"dungeon","id":4981,"desc":"Bandit Boss Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Aurellia du Cinghalle","type":"NPC","wcid":38420,"cell":"00B7026E","place":"dungeon","id":4982,"desc":"Moar Gland Collection Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Kojina","type":"NPC","wcid":38419,"cell":"00B7026E","place":"dungeon","id":4983,"desc":"Glowing Jungle Lily Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Ladice","type":"NPC","wcid":51268,"cell":"00B7026F","place":"dungeon","id":4984,"desc":"Gearknight Phalanx Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Dark Reshan","type":"NPC","wcid":51276,"cell":"00B7026F","place":"dungeon","id":4985,"desc":"Gearknight Parts Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Kaymor ibn Dumandi","type":"NPC","wcid":38241,"cell":"00B7026F","place":"dungeon","id":4986,"desc":"High Priest Task Master. In Celestial Hand Stronghold."}, + {"name":"Jentha Strongarm","type":"NPC","wcid":38266,"cell":"00B7026F","place":"dungeon","id":4987,"desc":"Magshuth Hunt Task Master. In Celestial Hand Stronghold."}, + {"name":"Gavin Hammerstone","type":"NPC","wcid":38267,"cell":"00B7026F","place":"dungeon","id":4988,"desc":"Shoguth Hunt Task Master. In Celestial Hand Stronghold."}, + {"name":"Marconi di Bellenesse","type":"NPC","wcid":38240,"cell":"00B7026F","place":"dungeon","id":4989,"desc":"Moguth Hunt Task Master. In Celestial Hand Stronghold."}, + {"name":"Kanji Hatashiya","type":"NPC","wcid":38239,"cell":"00B7026F","place":"dungeon","id":4990,"desc":"Artifacts Task Master. In Celestial Hand Stronghold."}, + {"name":"Kiko","type":"NPC","wcid":38238,"cell":"00B7026F","place":"dungeon","id":4991,"desc":"Coral Towers Task Master. In Celestial Hand Stronghold."}, + {"name":"Eccai Marinni","type":"NPC","wcid":38693,"cell":"00B7026F","place":"dungeon","id":4992,"desc":"Bounty Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Mashira bint Tamur","type":"NPC","wcid":38695,"cell":"00B7026F","place":"dungeon","id":4993,"desc":"Wight Mage Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Balon Strongarm","type":"NPC","wcid":38694,"cell":"00B7026F","place":"dungeon","id":4994,"desc":"Jaw Collection Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Erline the Fleet","type":"NPC","wcid":38596,"cell":"00B7026F","place":"dungeon","id":4995,"desc":"Dark Isle Assassin Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Sudeko Nojiri","type":"NPC","wcid":38736,"cell":"00B7026F","place":"dungeon","id":4996,"desc":"Ruschk Boss Taskmaster. In Celestial Hand Stronghold."}, + {"name":"Society Gauntlets Armorsmith","type":"NPC","wcid":38548,"cell":"00B70105","place":"dungeon","id":4997,"desc":"Society Armorsmith. In Celestial Hand Stronghold."}, + {"name":"Society Greaves Armorsmith","type":"NPC","wcid":38550,"cell":"00B70105","place":"dungeon","id":4998,"desc":"Society Armorsmith. In Celestial Hand Stronghold."}, + {"name":"Society Tassets Armorsmith","type":"NPC","wcid":38554,"cell":"00B70105","place":"dungeon","id":4999,"desc":"Society Armorsmith. In Celestial Hand Stronghold."}, + {"name":"Society Vambraces Armorsmith","type":"NPC","wcid":38555,"cell":"00B70105","place":"dungeon","id":5000,"desc":"Society Armorsmith. In Celestial Hand Stronghold."}, + {"name":"Society Pauldrons Armorsmith","type":"NPC","wcid":38552,"cell":"00B70105","place":"dungeon","id":5001,"desc":"Society Armorsmith. In Celestial Hand Stronghold."}, + {"name":"Society Girth Armorsmith","type":"NPC","wcid":38549,"cell":"00B70106","place":"dungeon","id":5002,"desc":"Society Armorsmith. In Celestial Hand Stronghold."}, + {"name":"Society Breastplate Armorsmith","type":"NPC","wcid":38547,"cell":"00B70106","place":"dungeon","id":5003,"desc":"Society Armorsmith. In Celestial Hand Stronghold."}, + {"name":"Society Helm Armorsmith","type":"NPC","wcid":38551,"cell":"00B70106","place":"dungeon","id":5004,"desc":"Society Armorsmith. In Celestial Hand Stronghold."}, + {"name":"Master Tarkor'in","type":"NPC","wcid":45871,"cell":"00B701E5","place":"dungeon","id":5005,"desc":"Society Stipend Officer. In Celestial Hand Stronghold."}, + {"name":"Commendations Officer","type":"NPC","wcid":38231,"cell":"00B701E5","place":"dungeon","id":5006,"desc":"Society Officer. In Celestial Hand Stronghold."}, + {"name":"Narthran Two-Blades","type":"NPC","wcid":39474,"cell":"00B7025E","place":"dungeon","id":5007,"desc":"Society Collector. In Celestial Hand Stronghold."}, + {"name":"Society Vault Keeper","type":"NPC","wcid":38720,"cell":"00B70121","place":"dungeon","id":5008,"desc":"Society Officer. In Celestial Hand Stronghold."}, + {"name":"Operations Aid","type":"NPC","wcid":42335,"cell":"00B7010E","place":"dungeon","id":5009,"desc":"Society Officer. In Celestial Hand Stronghold."}, + {"name":"Eldrytch Web Quartermaster","type":"Vendor","wcid":38575,"cell":"00B8026B","place":"dungeon","id":5010,"desc":"Society Officer. In Eldrytch Web Stronghold."}, + {"name":"Raenholm the Archmage","type":"Vendor","wcid":38689,"cell":"00B8026A","place":"dungeon","id":5011,"desc":"Society Archmage. In Eldrytch Web Stronghold."}, + {"name":"Shopkeep Gunderson","type":"Vendor","wcid":38690,"cell":"00B8026A","place":"dungeon","id":5012,"desc":"Society Shopkeep. In Eldrytch Web Stronghold."}, + {"name":"Master Statue of 'Moarsman City' Transport","type":"NPC","wcid":41176,"cell":"00B80295","place":"dungeon","id":5013,"desc":"In Eldrytch Web Stronghold."}, + {"name":"Master Statue of 'Freebooter Isle' Transport","type":"NPC","wcid":41175,"cell":"00B80295","place":"dungeon","id":5014,"desc":"In Eldrytch Web Stronghold."}, + {"name":"Haruki","type":"NPC","wcid":41826,"cell":"00B8026C","place":"dungeon","id":5015,"desc":"Society Contractor. In Eldrytch Web Stronghold."}, + {"name":"Jonathan","type":"NPC","wcid":41827,"cell":"00B8026C","place":"dungeon","id":5016,"desc":"Society Collector. In Eldrytch Web Stronghold."}, + {"name":"Luciana du Maki","type":"NPC","wcid":38709,"cell":"00B8026C","place":"dungeon","id":5017,"desc":"Inspector of Knights. In Eldrytch Web Stronghold."}, + {"name":"Khadira of the Eldrytch Web","type":"NPC","wcid":38643,"cell":"00B8026C","place":"dungeon","id":5018,"desc":"Inspector of Adepts. In Eldrytch Web Stronghold."}, + {"name":"Leisall bint Jumadd","type":"NPC","wcid":38423,"cell":"00B8026C","place":"dungeon","id":5019,"desc":"Jungle Flower Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Keep Strategic Commander","type":"NPC","wcid":44390,"cell":"00B8025B","place":"dungeon","id":5020,"desc":"Society Officer. In Eldrytch Web Stronghold."}, + {"name":"Aldreda","type":"NPC","wcid":51272,"cell":"00B8026D","place":"dungeon","id":5021,"desc":"Mana Siphon Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Istonia Charson","type":"NPC","wcid":38309,"cell":"00B8026D","place":"dungeon","id":5022,"desc":"Inspector of Lords. In Eldrytch Web Stronghold."}, + {"name":"Hizuki Tama","type":"NPC","wcid":38372,"cell":"00B8026D","place":"dungeon","id":5023,"desc":"Inspector of Masters. In Eldrytch Web Stronghold."}, + {"name":"Society Sollerets Armorsmith","type":"NPC","wcid":38562,"cell":"00B80104","place":"dungeon","id":5024,"desc":"Society Armorsmith. In Eldrytch Web Stronghold."}, + {"name":"Zahid al-Din","type":"NPC","wcid":41825,"cell":"00B8026E","place":"dungeon","id":5025,"desc":"Society Collector. In Eldrytch Web Stronghold."}, + {"name":"Ualya bint Muyzal","type":"NPC","wcid":38273,"cell":"00B8026E","place":"dungeon","id":5026,"desc":"Spawn Pools Task Master. In Eldrytch Web Stronghold."}, + {"name":"Durvush the Dusty","type":"NPC","wcid":38705,"cell":"00B8026E","place":"dungeon","id":5027,"desc":"Wall Carving Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Annelina Fabarin","type":"NPC","wcid":38704,"cell":"00B8026E","place":"dungeon","id":5028,"desc":"Delivery Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Turvald Snorborgson","type":"NPC","wcid":38606,"cell":"00B8026E","place":"dungeon","id":5029,"desc":"Falatacot Report Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Qa'li al-Kesh","type":"NPC","wcid":38607,"cell":"00B8026E","place":"dungeon","id":5030,"desc":"Dark Isle Scout Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Manto Sakara","type":"NPC","wcid":38605,"cell":"00B8026E","place":"dungeon","id":5031,"desc":"Black Coral Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Alexander Bowspeaker","type":"NPC","wcid":38426,"cell":"00B8026E","place":"dungeon","id":5032,"desc":"Blessed Moarsman Hunt Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Corrado Wardun","type":"NPC","wcid":38422,"cell":"00B8026E","place":"dungeon","id":5033,"desc":"Bandit Boss Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Elloisa du Cinghalle","type":"NPC","wcid":38425,"cell":"00B8026E","place":"dungeon","id":5034,"desc":"Moar Gland Collection Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Satsuki","type":"NPC","wcid":38424,"cell":"00B8026E","place":"dungeon","id":5035,"desc":"Glowing Jungle Lily Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Trathium","type":"NPC","wcid":51270,"cell":"00B8026F","place":"dungeon","id":5036,"desc":"Gearknight Parts Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Tressar","type":"NPC","wcid":51271,"cell":"00B8026F","place":"dungeon","id":5037,"desc":"Gearknight Phalanx Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Aisley Swiftfoot","type":"NPC","wcid":38738,"cell":"00B8026F","place":"dungeon","id":5038,"desc":"Dark Isle Assassin Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Milos ibn Ashud","type":"NPC","wcid":38243,"cell":"00B8026F","place":"dungeon","id":5039,"desc":"High Priest Task Master. In Eldrytch Web Stronghold."}, + {"name":"Denada Morningthaw","type":"NPC","wcid":38269,"cell":"00B8026F","place":"dungeon","id":5040,"desc":"Magshuth Hunt Task Master. In Eldrytch Web Stronghold."}, + {"name":"Dorn Bowspeaker","type":"NPC","wcid":38272,"cell":"00B8026F","place":"dungeon","id":5041,"desc":"Shoguth Hunt Task Master. In Eldrytch Web Stronghold."}, + {"name":"Ricaldo di Alduressa","type":"NPC","wcid":38271,"cell":"00B8026F","place":"dungeon","id":5042,"desc":"Moguth Hunt Task Master. In Eldrytch Web Stronghold."}, + {"name":"Boshi Sutadasuto","type":"NPC","wcid":38270,"cell":"00B8026F","place":"dungeon","id":5043,"desc":"Artifacts Task Master. In Eldrytch Web Stronghold."}, + {"name":"Chiyo","type":"NPC","wcid":38268,"cell":"00B8026F","place":"dungeon","id":5044,"desc":"Coral Towers Task Master. In Eldrytch Web Stronghold."}, + {"name":"Garain di Spesi","type":"NPC","wcid":38696,"cell":"00B8026F","place":"dungeon","id":5045,"desc":"Bounty Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Zumaq al-Jaluzi","type":"NPC","wcid":38698,"cell":"00B8026F","place":"dungeon","id":5046,"desc":"Wight Mage Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Hador the Vengeful","type":"NPC","wcid":38697,"cell":"00B8026F","place":"dungeon","id":5047,"desc":"Jaw Collection Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Keiji Sozoji","type":"NPC","wcid":38737,"cell":"00B8026F","place":"dungeon","id":5048,"desc":"Ruschk Boss Taskmaster. In Eldrytch Web Stronghold."}, + {"name":"Society Gauntlets Armorsmith","type":"NPC","wcid":38557,"cell":"00B80105","place":"dungeon","id":5049,"desc":"Society Armorsmith. In Eldrytch Web Stronghold."}, + {"name":"Society Greaves Armorsmith","type":"NPC","wcid":38559,"cell":"00B80105","place":"dungeon","id":5050,"desc":"Society Armorsmith. In Eldrytch Web Stronghold."}, + {"name":"Society Tassets Armorsmith","type":"NPC","wcid":38563,"cell":"00B80105","place":"dungeon","id":5051,"desc":"Society Armorsmith. In Eldrytch Web Stronghold."}, + {"name":"Society Vambraces Armorsmith","type":"NPC","wcid":38564,"cell":"00B80105","place":"dungeon","id":5052,"desc":"Society Armorsmith. In Eldrytch Web Stronghold."}, + {"name":"Society Pauldrons Armorsmith","type":"NPC","wcid":38561,"cell":"00B80106","place":"dungeon","id":5053,"desc":"Society Armorsmith. In Eldrytch Web Stronghold."}, + {"name":"Society Girth Armorsmith","type":"NPC","wcid":38558,"cell":"00B80106","place":"dungeon","id":5054,"desc":"Society Armorsmith. In Eldrytch Web Stronghold."}, + {"name":"Society Breastplate Armorsmith","type":"NPC","wcid":38556,"cell":"00B80106","place":"dungeon","id":5055,"desc":"Society Armorsmith. In Eldrytch Web Stronghold."}, + {"name":"Society Helm Armorsmith","type":"NPC","wcid":38560,"cell":"00B80106","place":"dungeon","id":5056,"desc":"Society Armorsmith. In Eldrytch Web Stronghold."}, + {"name":"Master Mhoire","type":"NPC","wcid":45872,"cell":"00B801E5","place":"dungeon","id":5057,"desc":"Society Stipend Officer. In Eldrytch Web Stronghold."}, + {"name":"Hiro Sawatogo","type":"NPC","wcid":39475,"cell":"00B8025E","place":"dungeon","id":5058,"desc":"Society Collector. In Eldrytch Web Stronghold."}, + {"name":"Society Vault Keeper","type":"NPC","wcid":38720,"cell":"00B80121","place":"dungeon","id":5059,"desc":"Society Officer. In Eldrytch Web Stronghold."}, + {"name":"Operations Aid","type":"NPC","wcid":42336,"cell":"00B8010E","place":"dungeon","id":5060,"desc":"Society Officer. In Eldrytch Web Stronghold."}, + {"name":"Commendations Officer","type":"NPC","wcid":38232,"cell":"00B801E5","place":"dungeon","id":5061,"desc":"Society Officer. In Eldrytch Web Stronghold."}, + {"name":"Promotions Officer","type":"NPC","wcid":38320,"cell":"00B8011D","place":"dungeon","id":5062,"desc":"Society Officer. In Eldrytch Web Stronghold."}, + {"name":"Radiant Blood Quartermaster","type":"Vendor","wcid":38576,"cell":"00B9026B","place":"dungeon","id":5063,"desc":"Society Officer. In Radiant Blood Stronghold."}, + {"name":"Vermilia the Archmage","type":"Vendor","wcid":38691,"cell":"00B9026A","place":"dungeon","id":5064,"desc":"Society Archmage. In Radiant Blood Stronghold."}, + {"name":"Shopkeeper Lazlo","type":"Vendor","wcid":38692,"cell":"00B9026A","place":"dungeon","id":5065,"desc":"Society Shopkeep. In Radiant Blood Stronghold."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"00B90100","place":"dungeon","id":5066,"desc":"In Radiant Blood Stronghold."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"00B90102","place":"dungeon","id":5067,"desc":"In Radiant Blood Stronghold."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"00B90101","place":"dungeon","id":5068,"desc":"In Radiant Blood Stronghold."}, + {"name":"Master Statue of 'Moarsman City' Transport","type":"NPC","wcid":41176,"cell":"00B90295","place":"dungeon","id":5069,"desc":"In Radiant Blood Stronghold."}, + {"name":"Master Statue of 'Freebooter Isle' Transport","type":"NPC","wcid":41175,"cell":"00B90295","place":"dungeon","id":5070,"desc":"In Radiant Blood Stronghold."}, + {"name":"Master Rhan","type":"NPC","wcid":45873,"cell":"00B901E5","place":"dungeon","id":5071,"desc":"Society Stipend Officer. In Radiant Blood Stronghold."}, + {"name":"Commendations Officer","type":"NPC","wcid":38233,"cell":"00B901E5","place":"dungeon","id":5072,"desc":"Society Officer. In Radiant Blood Stronghold."}, + {"name":"Marek al-Evv","type":"NPC","wcid":39476,"cell":"00B9025E","place":"dungeon","id":5073,"desc":"Society Collector. In Radiant Blood Stronghold."}, + {"name":"Society Vault Keeper","type":"NPC","wcid":38720,"cell":"00B90121","place":"dungeon","id":5074,"desc":"Society Officer. In Radiant Blood Stronghold."}, + {"name":"Promotions Officer","type":"NPC","wcid":38321,"cell":"00B9011E","place":"dungeon","id":5075,"desc":"Society Officer. In Radiant Blood Stronghold."}, + {"name":"Keep Strategic Commander","type":"NPC","wcid":44388,"cell":"00B90257","place":"dungeon","id":5076,"desc":"Society Officer. In Radiant Blood Stronghold."}, + {"name":"Society Helm Armorsmith","type":"NPC","wcid":38569,"cell":"00B90106","place":"dungeon","id":5077,"desc":"Society Armorsmith. In Radiant Blood Stronghold."}, + {"name":"Society Breastplate Armorsmith","type":"NPC","wcid":38565,"cell":"00B90106","place":"dungeon","id":5078,"desc":"Society Armorsmith. In Radiant Blood Stronghold."}, + {"name":"Society Girth Armorsmith","type":"NPC","wcid":38567,"cell":"00B90106","place":"dungeon","id":5079,"desc":"Society Armorsmith. In Radiant Blood Stronghold."}, + {"name":"Society Pauldrons Armorsmith","type":"NPC","wcid":38570,"cell":"00B90106","place":"dungeon","id":5080,"desc":"Society Armorsmith. In Radiant Blood Stronghold."}, + {"name":"Kimberleigh","type":"NPC","wcid":51275,"cell":"00B9026D","place":"dungeon","id":5081,"desc":"Mana Siphon Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Gamri Nightshade","type":"NPC","wcid":38331,"cell":"00B9026D","place":"dungeon","id":5082,"desc":"Inspector of Lords. In Radiant Blood Stronghold."}, + {"name":"Brizinna du Corcosi","type":"NPC","wcid":38373,"cell":"00B9026D","place":"dungeon","id":5083,"desc":"Inspector of Masters. In Radiant Blood Stronghold."}, + {"name":"Society Vambraces Armorsmith","type":"NPC","wcid":38573,"cell":"00B90105","place":"dungeon","id":5084,"desc":"Society Armorsmith. In Radiant Blood Stronghold."}, + {"name":"Society Tassets Armorsmith","type":"NPC","wcid":38572,"cell":"00B90105","place":"dungeon","id":5085,"desc":"Society Armorsmith. In Radiant Blood Stronghold."}, + {"name":"Society Greaves Armorsmith","type":"NPC","wcid":38568,"cell":"00B90105","place":"dungeon","id":5086,"desc":"Society Armorsmith. In Radiant Blood Stronghold."}, + {"name":"Society Gauntlets Armorsmith","type":"NPC","wcid":38566,"cell":"00B90105","place":"dungeon","id":5087,"desc":"Society Armorsmith. In Radiant Blood Stronghold."}, + {"name":"Aun Quanah","type":"NPC","wcid":51274,"cell":"00B9026F","place":"dungeon","id":5088,"desc":"Gearknight Phalanx Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Drocogst","type":"NPC","wcid":51273,"cell":"00B9026F","place":"dungeon","id":5089,"desc":"Gearknight Parts Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Kylos Hunterson","type":"NPC","wcid":38278,"cell":"00B9026F","place":"dungeon","id":5090,"desc":"Shoguth Hunt Task Master. In Radiant Blood Stronghold."}, + {"name":"Lunbal Dolicci","type":"NPC","wcid":38242,"cell":"00B9026F","place":"dungeon","id":5091,"desc":"High Priest Task Master. In Radiant Blood Stronghold."}, + {"name":"Elesandra Trembol","type":"NPC","wcid":38275,"cell":"00B9026F","place":"dungeon","id":5092,"desc":"Magshuth Hunt Task Master. In Radiant Blood Stronghold."}, + {"name":"Berrando Piatelli","type":"NPC","wcid":38277,"cell":"00B9026F","place":"dungeon","id":5093,"desc":"Moguth Hunt Task Master. In Radiant Blood Stronghold."}, + {"name":"Kotaro Ueda","type":"NPC","wcid":38276,"cell":"00B9026F","place":"dungeon","id":5094,"desc":"Artifacts Task Master. In Radiant Blood Stronghold."}, + {"name":"Akahana","type":"NPC","wcid":38274,"cell":"00B9026F","place":"dungeon","id":5095,"desc":"Coral Towers Task Master. In Radiant Blood Stronghold."}, + {"name":"Aldoro di Belleforte","type":"NPC","wcid":38699,"cell":"00B9026F","place":"dungeon","id":5096,"desc":"Bounty Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Idaris bint Qumal","type":"NPC","wcid":38701,"cell":"00B9026F","place":"dungeon","id":5097,"desc":"Wight Mage Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Cullum of Celdon","type":"NPC","wcid":38700,"cell":"00B9026F","place":"dungeon","id":5098,"desc":"Jaw Collection Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Rheda the Watcher","type":"NPC","wcid":38600,"cell":"00B9026F","place":"dungeon","id":5099,"desc":"Dark Isle Assassin Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Takahara Masikawa","type":"NPC","wcid":38601,"cell":"00B9026F","place":"dungeon","id":5100,"desc":"Ruschk Boss Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Mik","type":"NPC","wcid":41830,"cell":"00B9026C","place":"dungeon","id":5101,"desc":"Society Collector. In Radiant Blood Stronghold."}, + {"name":"Ghali al-Fariq","type":"NPC","wcid":41829,"cell":"00B9026C","place":"dungeon","id":5102,"desc":"Society Contractor. In Radiant Blood Stronghold."}, + {"name":"Viviana Fortiore","type":"NPC","wcid":38710,"cell":"00B9026C","place":"dungeon","id":5103,"desc":"Inspector of Knights. In Radiant Blood Stronghold."}, + {"name":"Shien Genda of the Radiant Blood","type":"NPC","wcid":38644,"cell":"00B9026C","place":"dungeon","id":5104,"desc":"Inspector of Adepts. In Radiant Blood Stronghold."}, + {"name":"Ti'alla bint Ashud","type":"NPC","wcid":38428,"cell":"00B9026C","place":"dungeon","id":5105,"desc":"Jungle Flower Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Society Sollerets Armorsmith","type":"NPC","wcid":38571,"cell":"00B90104","place":"dungeon","id":5106,"desc":"Society Armorsmith. In Radiant Blood Stronghold."}, + {"name":"Kenji","type":"NPC","wcid":41828,"cell":"00B9026E","place":"dungeon","id":5107,"desc":"Society Collector. In Radiant Blood Stronghold."}, + {"name":"Payla bint Dumandi","type":"NPC","wcid":38279,"cell":"00B9026E","place":"dungeon","id":5108,"desc":"Spawn Pools Task Master. In Radiant Blood Stronghold."}, + {"name":"Kalal ibn Dariz","type":"NPC","wcid":38707,"cell":"00B9026E","place":"dungeon","id":5109,"desc":"Wall Carving Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Saphine Brauno","type":"NPC","wcid":38706,"cell":"00B9026E","place":"dungeon","id":5110,"desc":"Delivery Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Agbeart","type":"NPC","wcid":38609,"cell":"00B9026E","place":"dungeon","id":5111,"desc":"Falatacot Report Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Rafin ibn Fezesh","type":"NPC","wcid":38610,"cell":"00B9026E","place":"dungeon","id":5112,"desc":"Dark Isle Scout Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Daisei Chirana","type":"NPC","wcid":38608,"cell":"00B9026E","place":"dungeon","id":5113,"desc":"Black Coral Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Ian Foefinder","type":"NPC","wcid":38431,"cell":"00B9026E","place":"dungeon","id":5114,"desc":"Blessed Moarsman Hunt Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Armand di Bellenesse","type":"NPC","wcid":38427,"cell":"00B9026E","place":"dungeon","id":5115,"desc":"Bandit Boss Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Pia du Cinghalle","type":"NPC","wcid":38430,"cell":"00B9026E","place":"dungeon","id":5116,"desc":"Moar Gland Collection Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Atsuko","type":"NPC","wcid":38429,"cell":"00B9026E","place":"dungeon","id":5117,"desc":"Glowing Jungle Lily Taskmaster. In Radiant Blood Stronghold."}, + {"name":"Operations Aid","type":"NPC","wcid":42337,"cell":"00B9010E","place":"dungeon","id":5118,"desc":"Society Officer. In Radiant Blood Stronghold."}, + {"name":"Corrupted Mana Shard","type":"NPC","wcid":38387,"cell":"00BA0111","place":"dungeon","id":5119,"desc":"In Corrupted Catacombs."}, + {"name":"Harmonic Transference Field","type":"NPC","wcid":37050,"cell":"00C0019D","place":"dungeon","id":5120,"desc":"In South Gate."}, + {"name":"Guardian","type":"NPC","wcid":37043,"cell":"00C0019B","place":"dungeon","id":5121,"desc":"In South Gate."}, + {"name":"Emissary of Asheron","type":"NPC","wcid":37042,"cell":"00C0019D","place":"dungeon","id":5122,"desc":"Emissary. In South Gate."}, + {"name":"Guardian","type":"NPC","wcid":37043,"cell":"00C0019D","place":"dungeon","id":5123,"desc":"In South Gate."}, + {"name":"Guardian","type":"NPC","wcid":37043,"cell":"00C001AD","place":"dungeon","id":5124,"desc":"In South Gate."}, + {"name":"Crystal","type":"NPC","wcid":40105,"cell":"00C70397","place":"dungeon","id":5125,"desc":"In Crystalline."}, + {"name":"Crystal","type":"NPC","wcid":40108,"cell":"00C702C8","place":"dungeon","id":5126,"desc":"In Crystalline."}, + {"name":"Crystal","type":"NPC","wcid":40106,"cell":"00C70219","place":"dungeon","id":5127,"desc":"In Crystalline."}, + {"name":"Crystal","type":"NPC","wcid":40107,"cell":"00C70100","place":"dungeon","id":5128,"desc":"In Crystalline."}, + {"name":"Exploration Marker","type":"NPC","wcid":39839,"cell":"00C8010C","place":"dungeon","id":5129,"desc":"In Egg Orchard West."}, + {"name":"Tanada Ganza","type":"NPC","wcid":87705,"cell":"00C901A7","place":"dungeon","id":5130,"desc":"Master of Air. In Chamber of Scrolls."}, + {"name":"Tanada Hido","type":"NPC","wcid":87706,"cell":"00C901A7","place":"dungeon","id":5131,"desc":"Master of Earth. In Chamber of Scrolls."}, + {"name":"Tanada Shouka","type":"NPC","wcid":87707,"cell":"00C901A7","place":"dungeon","id":5132,"desc":"Master of Water. In Chamber of Scrolls."}, + {"name":"Tanada Han-Tu","type":"NPC","wcid":87704,"cell":"00C901A8","place":"dungeon","id":5133,"desc":"Scion of Hano. In Chamber of Scrolls."}, + {"name":"Unstable Test Portal","type":"NPC","wcid":40273,"cell":"00CA01A7","place":"dungeon","id":5134,"desc":"In a dungeon (landblock 00CA)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE03DA","place":"dungeon","id":5135,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE03FF","place":"dungeon","id":5136,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE040A","place":"dungeon","id":5137,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0407","place":"dungeon","id":5138,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04D1","place":"dungeon","id":5139,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE040D","place":"dungeon","id":5140,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0410","place":"dungeon","id":5141,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0413","place":"dungeon","id":5142,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE03E0","place":"dungeon","id":5143,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE03D3","place":"dungeon","id":5144,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE03DD","place":"dungeon","id":5145,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04EC","place":"dungeon","id":5146,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE03D0","place":"dungeon","id":5147,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE03CA","place":"dungeon","id":5148,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE03CD","place":"dungeon","id":5149,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE03E3","place":"dungeon","id":5150,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0402","place":"dungeon","id":5151,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE041B","place":"dungeon","id":5152,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE042D","place":"dungeon","id":5153,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04AD","place":"dungeon","id":5154,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04CE","place":"dungeon","id":5155,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0421","place":"dungeon","id":5156,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0433","place":"dungeon","id":5157,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0445","place":"dungeon","id":5158,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE043F","place":"dungeon","id":5159,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0457","place":"dungeon","id":5160,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0451","place":"dungeon","id":5161,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE046F","place":"dungeon","id":5162,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0469","place":"dungeon","id":5163,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0483","place":"dungeon","id":5164,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE047D","place":"dungeon","id":5165,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0493","place":"dungeon","id":5166,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34955,"cell":"00CE0498","place":"dungeon","id":5167,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04D4","place":"dungeon","id":5168,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE049B","place":"dungeon","id":5169,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04D7","place":"dungeon","id":5170,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04DA","place":"dungeon","id":5171,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04DD","place":"dungeon","id":5172,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04E0","place":"dungeon","id":5173,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":38039,"cell":"00CE04E3","place":"dungeon","id":5174,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04A2","place":"dungeon","id":5175,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04E6","place":"dungeon","id":5176,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04A5","place":"dungeon","id":5177,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04E9","place":"dungeon","id":5178,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0418","place":"dungeon","id":5179,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0424","place":"dungeon","id":5180,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE042A","place":"dungeon","id":5181,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0436","place":"dungeon","id":5182,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE043C","place":"dungeon","id":5183,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0448","place":"dungeon","id":5184,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE044E","place":"dungeon","id":5185,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0460","place":"dungeon","id":5186,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0466","place":"dungeon","id":5187,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0474","place":"dungeon","id":5188,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE047A","place":"dungeon","id":5189,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE048A","place":"dungeon","id":5190,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34949,"cell":"00CE0490","place":"dungeon","id":5191,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE04AA","place":"dungeon","id":5192,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0516","place":"dungeon","id":5193,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE051B","place":"dungeon","id":5194,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE0515","place":"dungeon","id":5195,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE051A","place":"dungeon","id":5196,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE051F","place":"dungeon","id":5197,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Statue","type":"NPC","wcid":34946,"cell":"00CE051E","place":"dungeon","id":5198,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Rock","type":"NPC","wcid":34948,"cell":"00CE02AA","place":"dungeon","id":5199,"desc":"In a dungeon (landblock 00CE)."}, + {"name":"Ringleader's Chambers","type":"NPC","wcid":72202,"cell":"00D00110","place":"dungeon","id":5200,"desc":"In a dungeon (landblock 00D0)."}, + {"name":"Cocooned Auroch","type":"NPC","wcid":20017,"cell":"00D10E5A","place":"dungeon","id":5201,"desc":"Dying. In a dungeon (landblock 00D1)."}, + {"name":"Cocooned Auroch","type":"NPC","wcid":20017,"cell":"00D10DBA","place":"dungeon","id":5202,"desc":"Dying. In a dungeon (landblock 00D1)."}, + {"name":"Cocooned Auroch","type":"NPC","wcid":20017,"cell":"00D10B22","place":"dungeon","id":5203,"desc":"Dying. In a dungeon (landblock 00D1)."}, + {"name":"Cocooned Auroch","type":"NPC","wcid":20017,"cell":"00D1083A","place":"dungeon","id":5204,"desc":"Dying. In a dungeon (landblock 00D1)."}, + {"name":"Cocooned Auroch","type":"NPC","wcid":20017,"cell":"00D10153","place":"dungeon","id":5205,"desc":"Dying. In a dungeon (landblock 00D1)."}, + {"name":"Rock","type":"NPC","wcid":34947,"cell":"00D40610","place":"dungeon","id":5206,"desc":"In a dungeon (landblock 00D4)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00D50313","place":"dungeon","id":5207,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00D50310","place":"dungeon","id":5208,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00D502CB","place":"dungeon","id":5209,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00D5028B","place":"dungeon","id":5210,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00D502E7","place":"dungeon","id":5211,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00D50241","place":"dungeon","id":5212,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00D5026C","place":"dungeon","id":5213,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00D50263","place":"dungeon","id":5214,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00D5023A","place":"dungeon","id":5215,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00D5024F","place":"dungeon","id":5216,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00D50261","place":"dungeon","id":5217,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00D502C3","place":"dungeon","id":5218,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00D502DB","place":"dungeon","id":5219,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36115,"cell":"00D5030B","place":"dungeon","id":5220,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36116,"cell":"00D50180","place":"dungeon","id":5221,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36117,"cell":"00D501C6","place":"dungeon","id":5222,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36092,"cell":"00D501E9","place":"dungeon","id":5223,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36107,"cell":"00D5012D","place":"dungeon","id":5224,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00D50253","place":"dungeon","id":5225,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00D5029D","place":"dungeon","id":5226,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00D50272","place":"dungeon","id":5227,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00D502BA","place":"dungeon","id":5228,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Human","type":"NPC","wcid":36080,"cell":"00D501C5","place":"dungeon","id":5229,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Human","type":"NPC","wcid":36077,"cell":"00D50193","place":"dungeon","id":5230,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Human","type":"NPC","wcid":36078,"cell":"00D50190","place":"dungeon","id":5231,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Human","type":"NPC","wcid":36124,"cell":"00D50197","place":"dungeon","id":5232,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Human","type":"NPC","wcid":36075,"cell":"00D50194","place":"dungeon","id":5233,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Human","type":"NPC","wcid":36079,"cell":"00D5018E","place":"dungeon","id":5234,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Human","type":"NPC","wcid":36121,"cell":"00D50195","place":"dungeon","id":5235,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Human","type":"NPC","wcid":36119,"cell":"00D50192","place":"dungeon","id":5236,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Human","type":"NPC","wcid":36082,"cell":"00D501D2","place":"dungeon","id":5237,"desc":"In a dungeon (landblock 00D5)."}, + {"name":"Claude Witnessing History Stopgap","type":"NPC","wcid":72393,"cell":"00D5010C","place":"dungeon","id":5238,"desc":"Stopgap. In a dungeon (landblock 00D5)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00D50194","place":"dungeon","id":5239,"desc":"Vision Quest Booter. In a dungeon (landblock 00D5)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00D5010C","place":"dungeon","id":5240,"desc":"Vision Quest Booter. In a dungeon (landblock 00D5)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00D501A0","place":"dungeon","id":5241,"desc":"Vision Quest Booter. In a dungeon (landblock 00D5)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00D5011F","place":"dungeon","id":5242,"desc":"Vision Quest Booter. In a dungeon (landblock 00D5)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00D50245","place":"dungeon","id":5243,"desc":"Vision Quest Booter. In a dungeon (landblock 00D5)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00D502FF","place":"dungeon","id":5244,"desc":"Vision Quest Booter. In a dungeon (landblock 00D5)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00D502AB","place":"dungeon","id":5245,"desc":"Vision Quest Booter. In a dungeon (landblock 00D5)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00D502F9","place":"dungeon","id":5246,"desc":"Vision Quest Booter. In a dungeon (landblock 00D5)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00D50180","place":"dungeon","id":5247,"desc":"Vision Quest Booter. In a dungeon (landblock 00D5)."}, + {"name":"Wall","type":"NPC","wcid":72258,"cell":"00D701C6","place":"dungeon","id":5248,"desc":"In a dungeon (landblock 00D7)."}, + {"name":"Jester's Cell","type":"NPC","wcid":72256,"cell":"00D7018F","place":"dungeon","id":5249,"desc":"In a dungeon (landblock 00D7)."}, + {"name":"Wall","type":"NPC","wcid":72257,"cell":"00D70101","place":"dungeon","id":5250,"desc":"In a dungeon (landblock 00D7)."}, + {"name":"Jester's Prison Door","type":"NPC","wcid":72255,"cell":"00D70101","place":"dungeon","id":5251,"desc":"In a dungeon (landblock 00D7)."}, + {"name":"Lever","type":"NPC","wcid":72259,"cell":"00D701C6","place":"dungeon","id":5252,"desc":"In a dungeon (landblock 00D7)."}, + {"name":"Arcane Death","type":"NPC","wcid":72675,"cell":"00D70195","place":"dungeon","id":5253,"desc":"In a dungeon (landblock 00D7)."}, + {"name":"Master's Lectern","type":"NPC","wcid":87212,"cell":"00D80182","place":"dungeon","id":5254,"desc":"In a dungeon (landblock 00D8)."}, + {"name":"Falatacot Herald","type":"NPC","wcid":38035,"cell":"00DA0227","place":"dungeon","id":5255,"desc":"Herald. In a dungeon (landblock 00DA)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00DB0313","place":"dungeon","id":5256,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00DB0310","place":"dungeon","id":5257,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00DB02CB","place":"dungeon","id":5258,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00DB028B","place":"dungeon","id":5259,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00DB02E7","place":"dungeon","id":5260,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00DB0241","place":"dungeon","id":5261,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00DB026C","place":"dungeon","id":5262,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00DB0263","place":"dungeon","id":5263,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00DB023A","place":"dungeon","id":5264,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00DB024F","place":"dungeon","id":5265,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00DB0261","place":"dungeon","id":5266,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00DB02C3","place":"dungeon","id":5267,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00DB02DB","place":"dungeon","id":5268,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36115,"cell":"00DB030B","place":"dungeon","id":5269,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36116,"cell":"00DB0180","place":"dungeon","id":5270,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36117,"cell":"00DB01C6","place":"dungeon","id":5271,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36092,"cell":"00DB01E9","place":"dungeon","id":5272,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36107,"cell":"00DB012D","place":"dungeon","id":5273,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00DB0253","place":"dungeon","id":5274,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00DB029D","place":"dungeon","id":5275,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00DB0272","place":"dungeon","id":5276,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00DB02BA","place":"dungeon","id":5277,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Human","type":"NPC","wcid":36080,"cell":"00DB01C5","place":"dungeon","id":5278,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Human","type":"NPC","wcid":36077,"cell":"00DB0193","place":"dungeon","id":5279,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Human","type":"NPC","wcid":36078,"cell":"00DB0190","place":"dungeon","id":5280,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Human","type":"NPC","wcid":36124,"cell":"00DB0197","place":"dungeon","id":5281,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Human","type":"NPC","wcid":36075,"cell":"00DB0194","place":"dungeon","id":5282,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Human","type":"NPC","wcid":36079,"cell":"00DB018E","place":"dungeon","id":5283,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Human","type":"NPC","wcid":36121,"cell":"00DB0195","place":"dungeon","id":5284,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Human","type":"NPC","wcid":36119,"cell":"00DB0192","place":"dungeon","id":5285,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Human","type":"NPC","wcid":36082,"cell":"00DB01D2","place":"dungeon","id":5286,"desc":"In a dungeon (landblock 00DB)."}, + {"name":"Claude Witnessing History Stopgap","type":"NPC","wcid":72393,"cell":"00DB010C","place":"dungeon","id":5287,"desc":"Stopgap. In a dungeon (landblock 00DB)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00DB0194","place":"dungeon","id":5288,"desc":"Vision Quest Booter. In a dungeon (landblock 00DB)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00DB010C","place":"dungeon","id":5289,"desc":"Vision Quest Booter. In a dungeon (landblock 00DB)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00DB01A0","place":"dungeon","id":5290,"desc":"Vision Quest Booter. In a dungeon (landblock 00DB)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00DB011F","place":"dungeon","id":5291,"desc":"Vision Quest Booter. In a dungeon (landblock 00DB)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00DB0245","place":"dungeon","id":5292,"desc":"Vision Quest Booter. In a dungeon (landblock 00DB)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00DB02FF","place":"dungeon","id":5293,"desc":"Vision Quest Booter. In a dungeon (landblock 00DB)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00DB02AB","place":"dungeon","id":5294,"desc":"Vision Quest Booter. In a dungeon (landblock 00DB)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00DB02F9","place":"dungeon","id":5295,"desc":"Vision Quest Booter. In a dungeon (landblock 00DB)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00DB0180","place":"dungeon","id":5296,"desc":"Vision Quest Booter. In a dungeon (landblock 00DB)."}, + {"name":"Crystal Array","type":"NPC","wcid":35177,"cell":"00E5018D","place":"dungeon","id":5297,"desc":"Empyrean Crystal Array. In a dungeon (landblock 00E5)."}, + {"name":"Strange Pillar","type":"NPC","wcid":38024,"cell":"00E70119","place":"dungeon","id":5298,"desc":"In Gardens of Menilesh."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00E90313","place":"dungeon","id":5299,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00E90310","place":"dungeon","id":5300,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00E902CB","place":"dungeon","id":5301,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00E9028B","place":"dungeon","id":5302,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00E902E7","place":"dungeon","id":5303,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00E90241","place":"dungeon","id":5304,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36397,"cell":"00E9026C","place":"dungeon","id":5305,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00E90263","place":"dungeon","id":5306,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00E9023A","place":"dungeon","id":5307,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00E9024F","place":"dungeon","id":5308,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00E90261","place":"dungeon","id":5309,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00E902C3","place":"dungeon","id":5310,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00E902DB","place":"dungeon","id":5311,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36115,"cell":"00E9030B","place":"dungeon","id":5312,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36116,"cell":"00E90180","place":"dungeon","id":5313,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36117,"cell":"00E901C6","place":"dungeon","id":5314,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36092,"cell":"00E901E9","place":"dungeon","id":5315,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Claude the Archmage","type":"NPC","wcid":36107,"cell":"00E9012D","place":"dungeon","id":5316,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00E90253","place":"dungeon","id":5317,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36399,"cell":"00E9029D","place":"dungeon","id":5318,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36396,"cell":"00E90272","place":"dungeon","id":5319,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Dreamwalker","type":"NPC","wcid":36398,"cell":"00E902BA","place":"dungeon","id":5320,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Human","type":"NPC","wcid":36080,"cell":"00E901C5","place":"dungeon","id":5321,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Human","type":"NPC","wcid":36077,"cell":"00E90193","place":"dungeon","id":5322,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Human","type":"NPC","wcid":36078,"cell":"00E90190","place":"dungeon","id":5323,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Human","type":"NPC","wcid":36124,"cell":"00E90197","place":"dungeon","id":5324,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Human","type":"NPC","wcid":36075,"cell":"00E90194","place":"dungeon","id":5325,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Human","type":"NPC","wcid":36079,"cell":"00E9018E","place":"dungeon","id":5326,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Human","type":"NPC","wcid":36121,"cell":"00E90195","place":"dungeon","id":5327,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Human","type":"NPC","wcid":36119,"cell":"00E90192","place":"dungeon","id":5328,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Human","type":"NPC","wcid":36082,"cell":"00E901D2","place":"dungeon","id":5329,"desc":"In a dungeon (landblock 00E9)."}, + {"name":"Claude Witnessing History Stopgap","type":"NPC","wcid":72393,"cell":"00E9010C","place":"dungeon","id":5330,"desc":"Stopgap. In a dungeon (landblock 00E9)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00E90194","place":"dungeon","id":5331,"desc":"Vision Quest Booter. In a dungeon (landblock 00E9)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00E9010C","place":"dungeon","id":5332,"desc":"Vision Quest Booter. In a dungeon (landblock 00E9)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00E901A0","place":"dungeon","id":5333,"desc":"Vision Quest Booter. In a dungeon (landblock 00E9)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00E9011F","place":"dungeon","id":5334,"desc":"Vision Quest Booter. In a dungeon (landblock 00E9)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00E90245","place":"dungeon","id":5335,"desc":"Vision Quest Booter. In a dungeon (landblock 00E9)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00E902FF","place":"dungeon","id":5336,"desc":"Vision Quest Booter. In a dungeon (landblock 00E9)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00E902AB","place":"dungeon","id":5337,"desc":"Vision Quest Booter. In a dungeon (landblock 00E9)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00E902F9","place":"dungeon","id":5338,"desc":"Vision Quest Booter. In a dungeon (landblock 00E9)."}, + {"name":"Aun Kelauri","type":"NPC","wcid":72403,"cell":"00E90180","place":"dungeon","id":5339,"desc":"Vision Quest Booter. In a dungeon (landblock 00E9)."}, + {"name":"Hurnmel the Smith","type":"Vendor","wcid":37477,"cell":"00EA0139","place":"dungeon","id":5340,"desc":"Ghostly Blacksmith. In Mhoire Armory."}, + {"name":"Jester's Marker","type":"NPC","wcid":37485,"cell":"00EA029E","place":"dungeon","id":5341,"desc":"In Mhoire Armory."}, + {"name":"Jester's Marker","type":"NPC","wcid":37486,"cell":"00EA0350","place":"dungeon","id":5342,"desc":"In Mhoire Armory."}, + {"name":"Jester's Marker","type":"NPC","wcid":37480,"cell":"00EA0187","place":"dungeon","id":5343,"desc":"In Mhoire Armory."}, + {"name":"Jester's Marker","type":"NPC","wcid":87110,"cell":"00EA05A5","place":"dungeon","id":5344,"desc":"In Mhoire Armory."}, + {"name":"Jester's Marker","type":"NPC","wcid":87111,"cell":"00EA0393","place":"dungeon","id":5345,"desc":"In Mhoire Armory."}, + {"name":"Jester's Marker","type":"NPC","wcid":87112,"cell":"00EA05FA","place":"dungeon","id":5346,"desc":"In Mhoire Armory."}, + {"name":"Jester's Marker","type":"NPC","wcid":87113,"cell":"00EA04F9","place":"dungeon","id":5347,"desc":"In Mhoire Armory."}, + {"name":"Jester's Marker","type":"NPC","wcid":87114,"cell":"00EA0459","place":"dungeon","id":5348,"desc":"In Mhoire Armory."}, + {"name":"Jester's Marker","type":"NPC","wcid":87115,"cell":"00EA01EF","place":"dungeon","id":5349,"desc":"In Mhoire Armory."}, + {"name":"Jester's Marker","type":"NPC","wcid":87116,"cell":"00EA022A","place":"dungeon","id":5350,"desc":"In Mhoire Armory."}, + {"name":"Causeway Sentinel","type":"NPC","wcid":31974,"cell":"00F00142","place":"dungeon","id":5351,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Skittering Mukkir","type":"NPC","wcid":33522,"cell":"00F0016C","place":"dungeon","id":5352,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Skittering Mukkir","type":"NPC","wcid":33522,"cell":"00F0016B","place":"dungeon","id":5353,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Skittering Mukkir","type":"NPC","wcid":33522,"cell":"00F00169","place":"dungeon","id":5354,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Skittering Mukkir","type":"NPC","wcid":33522,"cell":"00F0016A","place":"dungeon","id":5355,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Geowulf's Ghost","type":"NPC","wcid":32009,"cell":"00F0048A","place":"dungeon","id":5356,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00186","place":"dungeon","id":5357,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00183","place":"dungeon","id":5358,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F001CF","place":"dungeon","id":5359,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F001D2","place":"dungeon","id":5360,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0016C","place":"dungeon","id":5361,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F001A0","place":"dungeon","id":5362,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0027C","place":"dungeon","id":5363,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00297","place":"dungeon","id":5364,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0022F","place":"dungeon","id":5365,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F001F5","place":"dungeon","id":5366,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00201","place":"dungeon","id":5367,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00212","place":"dungeon","id":5368,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00221","place":"dungeon","id":5369,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00227","place":"dungeon","id":5370,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F002A8","place":"dungeon","id":5371,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F002E5","place":"dungeon","id":5372,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00343","place":"dungeon","id":5373,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F002B2","place":"dungeon","id":5374,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F002C5","place":"dungeon","id":5375,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0036C","place":"dungeon","id":5376,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0036A","place":"dungeon","id":5377,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0035F","place":"dungeon","id":5378,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F001C1","place":"dungeon","id":5379,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F001EA","place":"dungeon","id":5380,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F003C0","place":"dungeon","id":5381,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0039E","place":"dungeon","id":5382,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0038A","place":"dungeon","id":5383,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0038E","place":"dungeon","id":5384,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00392","place":"dungeon","id":5385,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F003A4","place":"dungeon","id":5386,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F003CD","place":"dungeon","id":5387,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F003D2","place":"dungeon","id":5388,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F003D6","place":"dungeon","id":5389,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F003C6","place":"dungeon","id":5390,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F003B8","place":"dungeon","id":5391,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00397","place":"dungeon","id":5392,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F004A0","place":"dungeon","id":5393,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F005CB","place":"dungeon","id":5394,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0052C","place":"dungeon","id":5395,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0053D","place":"dungeon","id":5396,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F004C9","place":"dungeon","id":5397,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F004EE","place":"dungeon","id":5398,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F004F9","place":"dungeon","id":5399,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00555","place":"dungeon","id":5400,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0048A","place":"dungeon","id":5401,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0058E","place":"dungeon","id":5402,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0060A","place":"dungeon","id":5403,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00602","place":"dungeon","id":5404,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0063F","place":"dungeon","id":5405,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00637","place":"dungeon","id":5406,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00627","place":"dungeon","id":5407,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0062F","place":"dungeon","id":5408,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00654","place":"dungeon","id":5409,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F005BE","place":"dungeon","id":5410,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0061A","place":"dungeon","id":5411,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00612","place":"dungeon","id":5412,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F005AE","place":"dungeon","id":5413,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00561","place":"dungeon","id":5414,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00427","place":"dungeon","id":5415,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00437","place":"dungeon","id":5416,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F0045E","place":"dungeon","id":5417,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Timid Spirit","type":"NPC","wcid":32010,"cell":"00F00477","place":"dungeon","id":5418,"desc":"In Upper Sanctum of Xik Minru."}, + {"name":"Exploration Marker","type":"NPC","wcid":39808,"cell":"00F1012D","place":"dungeon","id":5419,"desc":"In a dungeon (landblock 00F1)."}, + {"name":"Enchanted Dais","type":"NPC","wcid":29713,"cell":"00F20111","place":"dungeon","id":5420,"desc":"In a dungeon (landblock 00F2)."}, + {"name":"Ensorcelled Dais","type":"NPC","wcid":29712,"cell":"00F20147","place":"dungeon","id":5421,"desc":"In a dungeon (landblock 00F2)."}, + {"name":"Portal Device","type":"NPC","wcid":29727,"cell":"00F30235","place":"dungeon","id":5422,"desc":"In a dungeon (landblock 00F3)."}, + {"name":"Sarcophagus of High Matriarch, Qin Xikit","type":"NPC","wcid":29729,"cell":"00F30236","place":"dungeon","id":5423,"desc":"In a dungeon (landblock 00F3)."}, + {"name":"Guardian","type":"NPC","wcid":29721,"cell":"00F90730","place":"dungeon","id":5424,"desc":"In a dungeon (landblock 00F9)."}, + {"name":"Portal Gateway","type":"NPC","wcid":29753,"cell":"00FA06F4","place":"dungeon","id":5425,"desc":"In a dungeon (landblock 00FA)."}, + {"name":"Portal Gateway","type":"NPC","wcid":29747,"cell":"00FB06DC","place":"dungeon","id":5426,"desc":"In a dungeon (landblock 00FB)."}, + {"name":"Portal Gateway","type":"NPC","wcid":29741,"cell":"00FC06B7","place":"dungeon","id":5427,"desc":"In a dungeon (landblock 00FC)."}, + {"name":"Portal Gateway","type":"NPC","wcid":29735,"cell":"00FD06D4","place":"dungeon","id":5428,"desc":"In a dungeon (landblock 00FD)."}, + {"name":"Portal Gateway","type":"NPC","wcid":29708,"cell":"00FE0739","place":"dungeon","id":5429,"desc":"In a dungeon (landblock 00FE)."}, + {"name":"Virindi Castaway","type":"NPC","wcid":27814,"cell":"010A0108","place":"dungeon","id":5430,"desc":"In Black Dominion."}, + {"name":"Apostate Nexus Gateway","type":"NPC","wcid":40810,"cell":"0110028A","place":"dungeon","id":5431,"desc":"In Nexus."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"01110109","place":"dungeon","id":5432,"desc":"In a dungeon (landblock 0111)."}, + {"name":"Grand Sentinel Muroba","type":"NPC","wcid":14921,"cell":"01150124","place":"dungeon","id":5433,"desc":"Marriage Facilitator. In a dungeon (landblock 0115)."}, + {"name":"Hamud ibn Rafik","type":"NPC","wcid":6025,"cell":"011C010F","place":"dungeon","id":5434,"desc":"In Mountain Fortress."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":43840,"cell":"013801D1","place":"dungeon","id":5435,"desc":"In a dungeon (landblock 0138)."}, + {"name":"Merchant","type":"Vendor","wcid":1387,"cell":"013A023D","place":"dungeon","id":5436,"desc":"In a dungeon (landblock 013A)."}, + {"name":"Merchant","type":"Vendor","wcid":1387,"cell":"013A0293","place":"dungeon","id":5437,"desc":"In a dungeon (landblock 013A)."}, + {"name":"Warded Portal","type":"NPC","wcid":73182,"cell":"013E028F","place":"dungeon","id":5438,"desc":"In Burial Temple."}, + {"name":"Liam of Gelid","type":"NPC","wcid":43403,"cell":"015D0252","place":"dungeon","id":5439,"desc":"Seer of the Dericost. In Mountain Cavern."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":43839,"cell":"015D0112","place":"dungeon","id":5440,"desc":"In Mountain Cavern."}, + {"name":"Arbiter","type":"NPC","wcid":29765,"cell":"01600302","place":"dungeon","id":5441,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Sacrificial Statue","type":"NPC","wcid":29703,"cell":"01600119","place":"dungeon","id":5442,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Sacrificial Statue","type":"NPC","wcid":29702,"cell":"01600121","place":"dungeon","id":5443,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Sacrificial Statue","type":"NPC","wcid":29701,"cell":"01600126","place":"dungeon","id":5444,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Purple Room Arbiter","type":"NPC","wcid":29761,"cell":"01600132","place":"dungeon","id":5445,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Red Room Arbiter","type":"NPC","wcid":29763,"cell":"01600133","place":"dungeon","id":5446,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Green Room Arbiter","type":"NPC","wcid":29759,"cell":"01600134","place":"dungeon","id":5447,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Blue Room Arbiter","type":"NPC","wcid":29757,"cell":"01600135","place":"dungeon","id":5448,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Blue Room Arbiter","type":"NPC","wcid":29758,"cell":"01600191","place":"dungeon","id":5449,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Purple Room Arbiter","type":"NPC","wcid":29762,"cell":"016001A4","place":"dungeon","id":5450,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Red Room Arbiter","type":"NPC","wcid":29764,"cell":"016001B7","place":"dungeon","id":5451,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Green Room Arbiter","type":"NPC","wcid":29760,"cell":"016001CA","place":"dungeon","id":5452,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Statue","type":"NPC","wcid":29756,"cell":"016001E6","place":"dungeon","id":5453,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Bag labeled \"White\"","type":"NPC","wcid":29777,"cell":"01600242","place":"dungeon","id":5454,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Bag labeled \"Black\"","type":"NPC","wcid":29774,"cell":"01600242","place":"dungeon","id":5455,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Bag labeled \"Mixed\"","type":"NPC","wcid":29776,"cell":"01600242","place":"dungeon","id":5456,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Instructions","type":"NPC","wcid":29775,"cell":"016002AC","place":"dungeon","id":5457,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Shell Table","type":"NPC","wcid":29773,"cell":"01600309","place":"dungeon","id":5458,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Shell Table","type":"NPC","wcid":29773,"cell":"0160030A","place":"dungeon","id":5459,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Shell Table","type":"NPC","wcid":29773,"cell":"01600315","place":"dungeon","id":5460,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Shell Table","type":"NPC","wcid":29773,"cell":"01600316","place":"dungeon","id":5461,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Guardian","type":"NPC","wcid":29721,"cell":"01600103","place":"dungeon","id":5462,"desc":"In a dungeon (landblock 0160)."}, + {"name":"Portal Gateway","type":"NPC","wcid":29746,"cell":"016A0101","place":"dungeon","id":5463,"desc":"In a dungeon (landblock 016A)."}, + {"name":"Portal Gateway","type":"NPC","wcid":29740,"cell":"016B0271","place":"dungeon","id":5464,"desc":"In a dungeon (landblock 016B)."}, + {"name":"Guardian","type":"NPC","wcid":29041,"cell":"016D0101","place":"dungeon","id":5465,"desc":"In a dungeon (landblock 016D)."}, + {"name":"Guardian","type":"NPC","wcid":29040,"cell":"016D010A","place":"dungeon","id":5466,"desc":"In a dungeon (landblock 016D)."}, + {"name":"Guardian","type":"NPC","wcid":29039,"cell":"016D0122","place":"dungeon","id":5467,"desc":"In a dungeon (landblock 016D)."}, + {"name":"Scroll of The Soothing Wind","type":"NPC","wcid":29044,"cell":"016D0146","place":"dungeon","id":5468,"desc":"In a dungeon (landblock 016D)."}, + {"name":"Scroll of The Golden Wind","type":"NPC","wcid":29046,"cell":"016D014C","place":"dungeon","id":5469,"desc":"In a dungeon (landblock 016D)."}, + {"name":"Scroll of The Endless Well","type":"NPC","wcid":29045,"cell":"016D014D","place":"dungeon","id":5470,"desc":"In a dungeon (landblock 016D)."}, + {"name":"Portal Gateway","type":"NPC","wcid":29056,"cell":"016D0147","place":"dungeon","id":5471,"desc":"In a dungeon (landblock 016D)."}, + {"name":"Guardian","type":"NPC","wcid":29036,"cell":"016E0103","place":"dungeon","id":5472,"desc":"In a dungeon (landblock 016E)."}, + {"name":"Guardian","type":"NPC","wcid":29037,"cell":"016F0103","place":"dungeon","id":5473,"desc":"In a dungeon (landblock 016F)."}, + {"name":"Guardian","type":"NPC","wcid":29038,"cell":"01700103","place":"dungeon","id":5474,"desc":"In a dungeon (landblock 0170)."}, + {"name":"Guardian","type":"NPC","wcid":29057,"cell":"01710160","place":"dungeon","id":5475,"desc":"In a dungeon (landblock 0171)."}, + {"name":"Guardian","type":"NPC","wcid":29057,"cell":"01720160","place":"dungeon","id":5476,"desc":"In a dungeon (landblock 0172)."}, + {"name":"Guardian","type":"NPC","wcid":29057,"cell":"01730160","place":"dungeon","id":5477,"desc":"In a dungeon (landblock 0173)."}, + {"name":"Portal Beacon","type":"NPC","wcid":29043,"cell":"0174012C","place":"dungeon","id":5478,"desc":"In a dungeon (landblock 0174)."}, + {"name":"Sealed Door","type":"NPC","wcid":29035,"cell":"01740141","place":"dungeon","id":5479,"desc":"In a dungeon (landblock 0174)."}, + {"name":"Sealed Valve","type":"NPC","wcid":29698,"cell":"01750100","place":"dungeon","id":5480,"desc":"In Muggy Font."}, + {"name":"Sealed Valve","type":"NPC","wcid":29697,"cell":"01760100","place":"dungeon","id":5481,"desc":"In Humid Font."}, + {"name":"Mosswart Enchantment Idol","type":"NPC","wcid":27971,"cell":"017C01A9","place":"dungeon","id":5482,"desc":"In a dungeon (landblock 017C)."}, + {"name":"Jeeves","type":"Vendor","wcid":6826,"cell":"018A0225","place":"dungeon","id":5483,"desc":"Humble Servant. In a dungeon (landblock 018A)."}, + {"name":"Master Yado","type":"NPC","wcid":9149,"cell":"018A0225","place":"dungeon","id":5484,"desc":"The Off-White Mage. In a dungeon (landblock 018A)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"018A0261","place":"dungeon","id":5485,"desc":"In a dungeon (landblock 018A)."}, + {"name":"Ulna bint-Fasha the Ivory Crafter","type":"NPC","wcid":24575,"cell":"018A0295","place":"dungeon","id":5486,"desc":"Trophy Crafter. In a dungeon (landblock 018A)."}, + {"name":"Town Crier","type":"NPC","wcid":5773,"cell":"018A029C","place":"dungeon","id":5487,"desc":"Herald. In a dungeon (landblock 018A)."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"018A029F","place":"dungeon","id":5488,"desc":"Mage. In a dungeon (landblock 018A)."}, + {"name":"Aun Xathurea the Leather Crafter","type":"NPC","wcid":24576,"cell":"018A02A7","place":"dungeon","id":5489,"desc":"Trophy Collector. In a dungeon (landblock 018A)."}, + {"name":"Tibri the Cavedweller","type":"NPC","wcid":3607,"cell":"018B01C7","place":"dungeon","id":5490,"desc":"Hermit. In a dungeon (landblock 018B)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"0191013A","place":"dungeon","id":5491,"desc":"In Mountain Sewer."}, + {"name":"Weaponsmith","type":"Vendor","wcid":1394,"cell":"01910104","place":"dungeon","id":5492,"desc":"In Mountain Sewer."}, + {"name":"Archmage","type":"Vendor","wcid":1371,"cell":"0191012F","place":"dungeon","id":5493,"desc":"In Mountain Sewer."}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"01910136","place":"dungeon","id":5494,"desc":"In Mountain Sewer."}, + {"name":"Jif Loz","type":"NPC","wcid":28970,"cell":"019502BE","place":"dungeon","id":5495,"desc":"In Xi Ru's Chapel."}, + {"name":"Bust of Emperor Kellin II","type":"NPC","wcid":28964,"cell":"019502BF","place":"dungeon","id":5496,"desc":"In Xi Ru's Chapel."}, + {"name":"Bust of Nali Valind","type":"NPC","wcid":28965,"cell":"019502BF","place":"dungeon","id":5497,"desc":"In Xi Ru's Chapel."}, + {"name":"Bust of Asheron Realaidain","type":"NPC","wcid":28963,"cell":"019502C4","place":"dungeon","id":5498,"desc":"In Xi Ru's Chapel."}, + {"name":"Kir Loz","type":"NPC","wcid":28971,"cell":"019502DC","place":"dungeon","id":5499,"desc":"In Xi Ru's Chapel."}, + {"name":"Portrait of Avoren Palacost","type":"NPC","wcid":28974,"cell":"019502E5","place":"dungeon","id":5500,"desc":"In Xi Ru's Chapel."}, + {"name":"Hevk Loz","type":"NPC","wcid":28969,"cell":"019502ED","place":"dungeon","id":5501,"desc":"In Xi Ru's Chapel."}, + {"name":"Portrait of Geraine IV","type":"NPC","wcid":28975,"cell":"019502EE","place":"dungeon","id":5502,"desc":"In Xi Ru's Chapel."}, + {"name":"Portrait of Asheron Realaidain","type":"NPC","wcid":28973,"cell":"019502EE","place":"dungeon","id":5503,"desc":"In Xi Ru's Chapel."}, + {"name":"Statue of Lauallana","type":"NPC","wcid":28977,"cell":"019504BA","place":"dungeon","id":5504,"desc":"In Xi Ru's Chapel."}, + {"name":"Door to Xi Ru's Sanctum","type":"NPC","wcid":28967,"cell":"019504CF","place":"dungeon","id":5505,"desc":"In Xi Ru's Chapel."}, + {"name":"Statue of Ualannan","type":"NPC","wcid":28978,"cell":"019504D0","place":"dungeon","id":5506,"desc":"In Xi Ru's Chapel."}, + {"name":"Statue of Aurlanna","type":"NPC","wcid":28976,"cell":"019504E0","place":"dungeon","id":5507,"desc":"In Xi Ru's Chapel."}, + {"name":"Indecipherable Book","type":"NPC","wcid":28962,"cell":"01950557","place":"dungeon","id":5508,"desc":"In Xi Ru's Chapel."}, + {"name":"Sarcophgus of Xi Ru","type":"NPC","wcid":28966,"cell":"01960112","place":"dungeon","id":5509,"desc":"In a dungeon (landblock 0196)."}, + {"name":"Urn","type":"NPC","wcid":28980,"cell":"019606F8","place":"dungeon","id":5510,"desc":"In a dungeon (landblock 0196)."}, + {"name":"Sealed Valve","type":"NPC","wcid":29699,"cell":"01980100","place":"dungeon","id":5511,"desc":"In Steamy Font."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"01A2020B","place":"dungeon","id":5512,"desc":"In a dungeon (landblock 01A2)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39806,"cell":"01A3012B","place":"dungeon","id":5513,"desc":"In a dungeon (landblock 01A3)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"01A80151","place":"dungeon","id":5514,"desc":"In Unstable."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"01A8015E","place":"dungeon","id":5515,"desc":"In Unstable."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"01AC011F","place":"dungeon","id":5516,"desc":"In Adventurer's Haven."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"01CA0106","place":"dungeon","id":5517,"desc":"In Hebian-to Sewers."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"01CA0116","place":"dungeon","id":5518,"desc":"In Hebian-to Sewers."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"01CA011E","place":"dungeon","id":5519,"desc":"In Hebian-to Sewers."}, + {"name":"Sealed Valve","type":"NPC","wcid":29696,"cell":"01D10100","place":"dungeon","id":5520,"desc":"In Balmy Font."}, + {"name":"Gemm the Smith","type":"Vendor","wcid":1354,"cell":"01D50151","place":"dungeon","id":5521,"desc":"Blacksmith. In Syliph Tower."}, + {"name":"Grawalda the Peddler","type":"Vendor","wcid":966,"cell":"01E80126","place":"dungeon","id":5522,"desc":"Peddler. In Dungeon Manor."}, + {"name":"Arina of the Arms","type":"Vendor","wcid":967,"cell":"01E90186","place":"dungeon","id":5523,"desc":"Armorer. In Underground City."}, + {"name":"Grethoric of all Trades","type":"Vendor","wcid":971,"cell":"01E901A0","place":"dungeon","id":5524,"desc":"Shady. In Underground City."}, + {"name":"Henrid the Grocer","type":"Vendor","wcid":968,"cell":"01E901A0","place":"dungeon","id":5525,"desc":"Grocer. In Underground City."}, + {"name":"Archmage Mah bint Dirid","type":"Vendor","wcid":5490,"cell":"01E901AE","place":"dungeon","id":5526,"desc":"Archmage. In Underground City."}, + {"name":"Gailadu the Scribe","type":"Vendor","wcid":970,"cell":"01E901B6","place":"dungeon","id":5527,"desc":"Scribe. In Underground City."}, + {"name":"Shunju Shinjin the Weaponsmith","type":"Vendor","wcid":972,"cell":"01E902AF","place":"dungeon","id":5528,"desc":"Weaponsmith. In Underground City."}, + {"name":"Healer Lithinia of Chiran","type":"Vendor","wcid":969,"cell":"01E902C2","place":"dungeon","id":5529,"desc":"Healer. In Underground City."}, + {"name":"Strange Device","type":"NPC","wcid":36778,"cell":"01E904A7","place":"dungeon","id":5530,"desc":"In Underground City."}, + {"name":"Strange Device","type":"NPC","wcid":36777,"cell":"01E90105","place":"dungeon","id":5531,"desc":"In Underground City."}, + {"name":"Elysa Strathelar","type":"NPC","wcid":36774,"cell":"01EE04D5","place":"dungeon","id":5532,"desc":"Rebel Leader. In a dungeon (landblock 01EE)."}, + {"name":"Elthina the Shady","type":"Vendor","wcid":405,"cell":"01EF0402","place":"dungeon","id":5533,"desc":"Peddler. In Arwic Mines."}, + {"name":"Portal Gateway","type":"NPC","wcid":29734,"cell":"01F00271","place":"dungeon","id":5534,"desc":"In a dungeon (landblock 01F0)."}, + {"name":"Portal Gateway","type":"NPC","wcid":29752,"cell":"01F20101","place":"dungeon","id":5535,"desc":"In a dungeon (landblock 01F2)."}, + {"name":"Jojii Shrine","type":"NPC","wcid":24263,"cell":"01F701A6","place":"dungeon","id":5536,"desc":"In Shoushi Grotto."}, + {"name":"Alia Dunolmad","type":"Vendor","wcid":22082,"cell":"01F803C1","place":"dungeon","id":5537,"desc":"Herbalist. In Mite Maze."}, + {"name":"Roderick","type":"NPC","wcid":38034,"cell":"01F80374","place":"dungeon","id":5538,"desc":"Bodyguard. In Mite Maze."}, + {"name":"Rushiya bint Anruq","type":"Vendor","wcid":1078,"cell":"01F90102","place":"dungeon","id":5539,"desc":"Blacksmith. In Accursed Halls."}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"01F90348","place":"dungeon","id":5540,"desc":"In Accursed Halls."}, + {"name":"Fisana the Jeweler","type":"Vendor","wcid":411,"cell":"01FA02FC","place":"dungeon","id":5541,"desc":"Jeweler. In Crypt of Ashen Tears."}, + {"name":"Shihinden Ran","type":"Vendor","wcid":1079,"cell":"01FA0352","place":"dungeon","id":5542,"desc":"Peddler. In Crypt of Ashen Tears."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":43837,"cell":"01FD0100","place":"dungeon","id":5543,"desc":"In Trothyr's Rest."}, + {"name":"Guardian","type":"NPC","wcid":28424,"cell":"0272012A","place":"dungeon","id":5544,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Guardian","type":"NPC","wcid":28425,"cell":"02720137","place":"dungeon","id":5545,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Guardian","type":"NPC","wcid":28423,"cell":"02720158","place":"dungeon","id":5546,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Guardian","type":"NPC","wcid":28422,"cell":"02720173","place":"dungeon","id":5547,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Scroll of Conveyic Chant","type":"NPC","wcid":28420,"cell":"02720195","place":"dungeon","id":5548,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Scroll of Conjurant Chant","type":"NPC","wcid":28417,"cell":"02720196","place":"dungeon","id":5549,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Scroll of Artificant Chant","type":"NPC","wcid":28418,"cell":"02720196","place":"dungeon","id":5550,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Sarcophagus of High Matriarch, Kivik Lir","type":"NPC","wcid":28416,"cell":"02720197","place":"dungeon","id":5551,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Tears of Jvikti Kheval","type":"NPC","wcid":28412,"cell":"0272019B","place":"dungeon","id":5552,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Manacle of Biting Pain","type":"NPC","wcid":28401,"cell":"0272019B","place":"dungeon","id":5553,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Scroll of Hieromantic Chant","type":"NPC","wcid":28421,"cell":"0272019C","place":"dungeon","id":5554,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Scroll of Vitaeic Chant","type":"NPC","wcid":28419,"cell":"0272019C","place":"dungeon","id":5555,"desc":"In a dungeon (landblock 0272)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027301E1","place":"dungeon","id":5556,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027301FD","place":"dungeon","id":5557,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730249","place":"dungeon","id":5558,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0273025C","place":"dungeon","id":5559,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28404,"cell":"027302AC","place":"dungeon","id":5560,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28402,"cell":"027302AD","place":"dungeon","id":5561,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Strange Device","type":"NPC","wcid":28399,"cell":"027302B9","place":"dungeon","id":5562,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28405,"cell":"027302C8","place":"dungeon","id":5563,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28403,"cell":"027302C9","place":"dungeon","id":5564,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027302E5","place":"dungeon","id":5565,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027302E8","place":"dungeon","id":5566,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027302EE","place":"dungeon","id":5567,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027302F2","place":"dungeon","id":5568,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027302F4","place":"dungeon","id":5569,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027302FB","place":"dungeon","id":5570,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027302FD","place":"dungeon","id":5571,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730301","place":"dungeon","id":5572,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730303","place":"dungeon","id":5573,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"02730306","place":"dungeon","id":5574,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0273030D","place":"dungeon","id":5575,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0273030F","place":"dungeon","id":5576,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730311","place":"dungeon","id":5577,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730336","place":"dungeon","id":5578,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0273037D","place":"dungeon","id":5579,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"02730388","place":"dungeon","id":5580,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0273039E","place":"dungeon","id":5581,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027303B9","place":"dungeon","id":5582,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027303BC","place":"dungeon","id":5583,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027303BE","place":"dungeon","id":5584,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027303C2","place":"dungeon","id":5585,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027303C6","place":"dungeon","id":5586,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027303C8","place":"dungeon","id":5587,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027303CD","place":"dungeon","id":5588,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027303D0","place":"dungeon","id":5589,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027303F3","place":"dungeon","id":5590,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730411","place":"dungeon","id":5591,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730435","place":"dungeon","id":5592,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730438","place":"dungeon","id":5593,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0273043B","place":"dungeon","id":5594,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0273043D","place":"dungeon","id":5595,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730440","place":"dungeon","id":5596,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730445","place":"dungeon","id":5597,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730447","place":"dungeon","id":5598,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730451","place":"dungeon","id":5599,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730458","place":"dungeon","id":5600,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0273045C","place":"dungeon","id":5601,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730465","place":"dungeon","id":5602,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0273046C","place":"dungeon","id":5603,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730473","place":"dungeon","id":5604,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02730478","place":"dungeon","id":5605,"desc":"In a dungeon (landblock 0273)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027401E1","place":"dungeon","id":5606,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027401FD","place":"dungeon","id":5607,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740249","place":"dungeon","id":5608,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0274025C","place":"dungeon","id":5609,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28402,"cell":"027402AC","place":"dungeon","id":5610,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28403,"cell":"027402AD","place":"dungeon","id":5611,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Strange Device","type":"NPC","wcid":28399,"cell":"027402B9","place":"dungeon","id":5612,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28405,"cell":"027402C8","place":"dungeon","id":5613,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28404,"cell":"027402C9","place":"dungeon","id":5614,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027402E5","place":"dungeon","id":5615,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027402E8","place":"dungeon","id":5616,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027402EE","place":"dungeon","id":5617,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027402F2","place":"dungeon","id":5618,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027402F4","place":"dungeon","id":5619,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027402FB","place":"dungeon","id":5620,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027402FD","place":"dungeon","id":5621,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740301","place":"dungeon","id":5622,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740303","place":"dungeon","id":5623,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"02740306","place":"dungeon","id":5624,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0274030D","place":"dungeon","id":5625,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0274030F","place":"dungeon","id":5626,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740311","place":"dungeon","id":5627,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740336","place":"dungeon","id":5628,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0274037D","place":"dungeon","id":5629,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"02740388","place":"dungeon","id":5630,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0274039E","place":"dungeon","id":5631,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027403B9","place":"dungeon","id":5632,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027403BC","place":"dungeon","id":5633,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027403BE","place":"dungeon","id":5634,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027403C2","place":"dungeon","id":5635,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027403C6","place":"dungeon","id":5636,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027403C8","place":"dungeon","id":5637,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027403CD","place":"dungeon","id":5638,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027403D0","place":"dungeon","id":5639,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027403F3","place":"dungeon","id":5640,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740411","place":"dungeon","id":5641,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740435","place":"dungeon","id":5642,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740438","place":"dungeon","id":5643,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0274043B","place":"dungeon","id":5644,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0274043D","place":"dungeon","id":5645,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740440","place":"dungeon","id":5646,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740445","place":"dungeon","id":5647,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740447","place":"dungeon","id":5648,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740451","place":"dungeon","id":5649,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740458","place":"dungeon","id":5650,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0274045C","place":"dungeon","id":5651,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740465","place":"dungeon","id":5652,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0274046C","place":"dungeon","id":5653,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740473","place":"dungeon","id":5654,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02740478","place":"dungeon","id":5655,"desc":"In a dungeon (landblock 0274)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027501E1","place":"dungeon","id":5656,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027501FD","place":"dungeon","id":5657,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750249","place":"dungeon","id":5658,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0275025C","place":"dungeon","id":5659,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28402,"cell":"027502AC","place":"dungeon","id":5660,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28405,"cell":"027502AD","place":"dungeon","id":5661,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Strange Device","type":"NPC","wcid":28399,"cell":"027502B9","place":"dungeon","id":5662,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28403,"cell":"027502C8","place":"dungeon","id":5663,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28404,"cell":"027502C9","place":"dungeon","id":5664,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027502E5","place":"dungeon","id":5665,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027502E8","place":"dungeon","id":5666,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027502EE","place":"dungeon","id":5667,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027502F2","place":"dungeon","id":5668,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027502F4","place":"dungeon","id":5669,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027502FB","place":"dungeon","id":5670,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027502FD","place":"dungeon","id":5671,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750301","place":"dungeon","id":5672,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750303","place":"dungeon","id":5673,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"02750306","place":"dungeon","id":5674,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0275030D","place":"dungeon","id":5675,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0275030F","place":"dungeon","id":5676,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750311","place":"dungeon","id":5677,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750336","place":"dungeon","id":5678,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0275037D","place":"dungeon","id":5679,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"02750388","place":"dungeon","id":5680,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0275039E","place":"dungeon","id":5681,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027503B9","place":"dungeon","id":5682,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027503BC","place":"dungeon","id":5683,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027503BE","place":"dungeon","id":5684,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027503C2","place":"dungeon","id":5685,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027503C4","place":"dungeon","id":5686,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027503C6","place":"dungeon","id":5687,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027503C8","place":"dungeon","id":5688,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027503CD","place":"dungeon","id":5689,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027503D0","place":"dungeon","id":5690,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"027503F3","place":"dungeon","id":5691,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750411","place":"dungeon","id":5692,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750435","place":"dungeon","id":5693,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750438","place":"dungeon","id":5694,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0275043B","place":"dungeon","id":5695,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0275043D","place":"dungeon","id":5696,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750440","place":"dungeon","id":5697,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750445","place":"dungeon","id":5698,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750447","place":"dungeon","id":5699,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750451","place":"dungeon","id":5700,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750458","place":"dungeon","id":5701,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0275045C","place":"dungeon","id":5702,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750465","place":"dungeon","id":5703,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0275046C","place":"dungeon","id":5704,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750473","place":"dungeon","id":5705,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"02750478","place":"dungeon","id":5706,"desc":"In a dungeon (landblock 0275)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"02760104","place":"dungeon","id":5707,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"0276017B","place":"dungeon","id":5708,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"027601A2","place":"dungeon","id":5709,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Conveyor of the Arena","type":"NPC","wcid":28429,"cell":"0276027D","place":"dungeon","id":5710,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Conveyor of the Arena","type":"NPC","wcid":28429,"cell":"02760287","place":"dungeon","id":5711,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Conveyor of the Arena","type":"NPC","wcid":28429,"cell":"02760291","place":"dungeon","id":5712,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Guardian of the Arena","type":"NPC","wcid":28426,"cell":"027602A2","place":"dungeon","id":5713,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Eye of the Heights","type":"NPC","wcid":28410,"cell":"0276036A","place":"dungeon","id":5714,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Guardian of the Trials","type":"NPC","wcid":28428,"cell":"02760371","place":"dungeon","id":5715,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28411,"cell":"0276037E","place":"dungeon","id":5716,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Offering Urn","type":"NPC","wcid":28415,"cell":"0276038C","place":"dungeon","id":5717,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Strange Device","type":"NPC","wcid":28400,"cell":"027607D9","place":"dungeon","id":5718,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":28406,"cell":"027607D9","place":"dungeon","id":5719,"desc":"In a dungeon (landblock 0276)."}, + {"name":"Guardian of the Crypt","type":"NPC","wcid":28427,"cell":"0277020E","place":"dungeon","id":5720,"desc":"In a dungeon (landblock 0277)."}, + {"name":"Guardian of the Crypt","type":"NPC","wcid":28427,"cell":"02770229","place":"dungeon","id":5721,"desc":"In a dungeon (landblock 0277)."}, + {"name":"Guardian of the Crypt","type":"NPC","wcid":28427,"cell":"02770244","place":"dungeon","id":5722,"desc":"In a dungeon (landblock 0277)."}, + {"name":"Executor Assistant","type":"NPC","wcid":10879,"cell":"027E0263","place":"dungeon","id":5723,"desc":"In Martinate Holding."}, + {"name":"Aun Kerehanua","type":"Vendor","wcid":11409,"cell":"028E01C7","place":"dungeon","id":5724,"desc":"In Palenqual's Caverns."}, + {"name":"Terese","type":"NPC","wcid":11637,"cell":"028F0149","place":"dungeon","id":5725,"desc":"Herbalist. In Swamp Gardens."}, + {"name":"Director's Majordomo","type":"NPC","wcid":10737,"cell":"0298010F","place":"dungeon","id":5726,"desc":"In Land Bridge Staging Complex."}, + {"name":"Saelar's Apprentice","type":"NPC","wcid":9309,"cell":"029D0104","place":"dungeon","id":5727,"desc":"In Mnemosyne Collection Site."}, + {"name":"Hahnain's Apprentice","type":"NPC","wcid":9308,"cell":"029D0107","place":"dungeon","id":5728,"desc":"In Mnemosyne Collection Site."}, + {"name":"Renselm's Apprentice","type":"NPC","wcid":9307,"cell":"029D0110","place":"dungeon","id":5729,"desc":"In Mnemosyne Collection Site."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":43843,"cell":"029D010F","place":"dungeon","id":5730,"desc":"In Mnemosyne Collection Site."}, + {"name":"Yoked Virindi","type":"NPC","wcid":41852,"cell":"02A30108","place":"dungeon","id":5731,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Conquered Virindi","type":"NPC","wcid":9133,"cell":"02A30108","place":"dungeon","id":5732,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Leashed Virindi","type":"NPC","wcid":9134,"cell":"02A30109","place":"dungeon","id":5733,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Tamed Virindi","type":"NPC","wcid":9135,"cell":"02A3010A","place":"dungeon","id":5734,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Beaten Virindi","type":"NPC","wcid":9131,"cell":"02A3010B","place":"dungeon","id":5735,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Atlatl Minion","type":"NPC","wcid":23524,"cell":"02A30100","place":"dungeon","id":5736,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Crossbow Minion","type":"NPC","wcid":14470,"cell":"02A30100","place":"dungeon","id":5737,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Broken Virindi","type":"NPC","wcid":9132,"cell":"02A30106","place":"dungeon","id":5738,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"War Magic Minion","type":"NPC","wcid":27813,"cell":"02A30102","place":"dungeon","id":5739,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Life Magic Minion","type":"NPC","wcid":27812,"cell":"02A30102","place":"dungeon","id":5740,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Bow Minion","type":"NPC","wcid":14469,"cell":"02A30100","place":"dungeon","id":5741,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Staff Minion","type":"NPC","wcid":14472,"cell":"02A30100","place":"dungeon","id":5742,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Dagger Minion","type":"NPC","wcid":14471,"cell":"02A30103","place":"dungeon","id":5743,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Unarmed Minion","type":"NPC","wcid":14473,"cell":"02A30103","place":"dungeon","id":5744,"desc":"In a dungeon (landblock 02A3)."}, + {"name":"Rumuba the Mosswart","type":"NPC","wcid":8614,"cell":"02B80101","place":"dungeon","id":5745,"desc":"In Rumuba's Hidey-Hole."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"02D3010A","place":"dungeon","id":5746,"desc":"In a dungeon (landblock 02D3)."}, + {"name":"Guardian","type":"NPC","wcid":29722,"cell":"02D80271","place":"dungeon","id":5747,"desc":"In a dungeon (landblock 02D8)."}, + {"name":"Portal Gateway","type":"NPC","wcid":29707,"cell":"02D90101","place":"dungeon","id":5748,"desc":"In a dungeon (landblock 02D9)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"02E201A4","place":"dungeon","id":5749,"desc":"In Arena."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"02E301A5","place":"dungeon","id":5750,"desc":"In Arena."}, + {"name":"Mi Krau-Li","type":"NPC","wcid":7773,"cell":"02E50151","place":"dungeon","id":5751,"desc":"In Krau Li's Labyrinth."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":43838,"cell":"02E60124","place":"dungeon","id":5752,"desc":"In Catacombs of the Forgotten."}, + {"name":"Klars","type":"NPC","wcid":31960,"cell":"02EB01E3","place":"dungeon","id":5753,"desc":"In Viamontian Torture Chamber."}, + {"name":"Britana","type":"NPC","wcid":31958,"cell":"02EB0204","place":"dungeon","id":5754,"desc":"In Viamontian Torture Chamber."}, + {"name":"Baggs","type":"NPC","wcid":31959,"cell":"02EB01C5","place":"dungeon","id":5755,"desc":"In Viamontian Torture Chamber."}, + {"name":"Sigil Keeper","type":"Vendor","wcid":34915,"cell":"02F30111","place":"dungeon","id":5756,"desc":"Metos Dispenser. In Halls of Metos."}, + {"name":"Golem Constructor","type":"NPC","wcid":34914,"cell":"02F30111","place":"dungeon","id":5757,"desc":"In Halls of Metos."}, + {"name":"Golem Warden of Metos","type":"NPC","wcid":34350,"cell":"02F30111","place":"dungeon","id":5758,"desc":"In Halls of Metos."}, + {"name":"Exploration Marker","type":"NPC","wcid":39839,"cell":"0302010C","place":"dungeon","id":5759,"desc":"In a dungeon (landblock 0302)."}, + {"name":"Greeter","type":"NPC","wcid":12723,"cell":"0363012F","place":"dungeon","id":5760,"desc":"Guard. In a dungeon (landblock 0363)."}, + {"name":"Guard","type":"NPC","wcid":12722,"cell":"0363014E","place":"dungeon","id":5761,"desc":"Soldier. In a dungeon (landblock 0363)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":12719,"cell":"03630173","place":"dungeon","id":5762,"desc":"Trophy Collector. In a dungeon (landblock 0363)."}, + {"name":"Academy Foreman","type":"NPC","wcid":13088,"cell":"0363018C","place":"dungeon","id":5763,"desc":"Trophy Collector. In a dungeon (landblock 0363)."}, + {"name":"Training Master","type":"NPC","wcid":12721,"cell":"036301D6","place":"dungeon","id":5764,"desc":"Soldier. In a dungeon (landblock 0363)."}, + {"name":"Senior Guard","type":"NPC","wcid":12727,"cell":"036301E5","place":"dungeon","id":5765,"desc":"Soldier. In a dungeon (landblock 0363)."}, + {"name":"Guard","type":"NPC","wcid":12724,"cell":"0363021D","place":"dungeon","id":5766,"desc":"Soldier. In a dungeon (landblock 0363)."}, + {"name":"Academy Quartermaster","type":"Vendor","wcid":12720,"cell":"0363023F","place":"dungeon","id":5767,"desc":"Blacksmith. In a dungeon (landblock 0363)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"03630264","place":"dungeon","id":5768,"desc":"Herald. In a dungeon (landblock 0363)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"036302DA","place":"dungeon","id":5769,"desc":"Shopkeeper. In a dungeon (landblock 0363)."}, + {"name":"Sentry","type":"NPC","wcid":12733,"cell":"036302EF","place":"dungeon","id":5770,"desc":"Soldier. In a dungeon (landblock 0363)."}, + {"name":"Greeter","type":"NPC","wcid":12723,"cell":"0364012F","place":"dungeon","id":5771,"desc":"Guard. In a dungeon (landblock 0364)."}, + {"name":"Guard","type":"NPC","wcid":12722,"cell":"0364014E","place":"dungeon","id":5772,"desc":"Soldier. In a dungeon (landblock 0364)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":12719,"cell":"03640173","place":"dungeon","id":5773,"desc":"Trophy Collector. In a dungeon (landblock 0364)."}, + {"name":"Academy Foreman","type":"NPC","wcid":13088,"cell":"0364018C","place":"dungeon","id":5774,"desc":"Trophy Collector. In a dungeon (landblock 0364)."}, + {"name":"Training Master","type":"NPC","wcid":12721,"cell":"036401D6","place":"dungeon","id":5775,"desc":"Soldier. In a dungeon (landblock 0364)."}, + {"name":"Senior Guard","type":"NPC","wcid":12727,"cell":"036401E5","place":"dungeon","id":5776,"desc":"Soldier. In a dungeon (landblock 0364)."}, + {"name":"Guard","type":"NPC","wcid":12724,"cell":"0364021D","place":"dungeon","id":5777,"desc":"Soldier. In a dungeon (landblock 0364)."}, + {"name":"Academy Quartermaster","type":"Vendor","wcid":12720,"cell":"0364023F","place":"dungeon","id":5778,"desc":"Blacksmith. In a dungeon (landblock 0364)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"03640264","place":"dungeon","id":5779,"desc":"Herald. In a dungeon (landblock 0364)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"036402DA","place":"dungeon","id":5780,"desc":"Shopkeeper. In a dungeon (landblock 0364)."}, + {"name":"Sentry","type":"NPC","wcid":12733,"cell":"036402EF","place":"dungeon","id":5781,"desc":"Soldier. In a dungeon (landblock 0364)."}, + {"name":"Greeter","type":"NPC","wcid":12723,"cell":"0365012F","place":"dungeon","id":5782,"desc":"Guard. In a dungeon (landblock 0365)."}, + {"name":"Guard","type":"NPC","wcid":12722,"cell":"0365014E","place":"dungeon","id":5783,"desc":"Soldier. In a dungeon (landblock 0365)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":12719,"cell":"03650173","place":"dungeon","id":5784,"desc":"Trophy Collector. In a dungeon (landblock 0365)."}, + {"name":"Academy Foreman","type":"NPC","wcid":13088,"cell":"0365018C","place":"dungeon","id":5785,"desc":"Trophy Collector. In a dungeon (landblock 0365)."}, + {"name":"Training Master","type":"NPC","wcid":12721,"cell":"036501D6","place":"dungeon","id":5786,"desc":"Soldier. In a dungeon (landblock 0365)."}, + {"name":"Senior Guard","type":"NPC","wcid":12727,"cell":"036501E5","place":"dungeon","id":5787,"desc":"Soldier. In a dungeon (landblock 0365)."}, + {"name":"Guard","type":"NPC","wcid":12724,"cell":"0365021D","place":"dungeon","id":5788,"desc":"Soldier. In a dungeon (landblock 0365)."}, + {"name":"Academy Quartermaster","type":"Vendor","wcid":12720,"cell":"0365023F","place":"dungeon","id":5789,"desc":"Blacksmith. In a dungeon (landblock 0365)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"03650264","place":"dungeon","id":5790,"desc":"Herald. In a dungeon (landblock 0365)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"036502DA","place":"dungeon","id":5791,"desc":"Shopkeeper. In a dungeon (landblock 0365)."}, + {"name":"Sentry","type":"NPC","wcid":12735,"cell":"036502EF","place":"dungeon","id":5792,"desc":"Soldier. In a dungeon (landblock 0365)."}, + {"name":"Greeter","type":"NPC","wcid":12723,"cell":"0366012F","place":"dungeon","id":5793,"desc":"Guard. In a dungeon (landblock 0366)."}, + {"name":"Guard","type":"NPC","wcid":12722,"cell":"0366014E","place":"dungeon","id":5794,"desc":"Soldier. In a dungeon (landblock 0366)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":12719,"cell":"03660173","place":"dungeon","id":5795,"desc":"Trophy Collector. In a dungeon (landblock 0366)."}, + {"name":"Academy Foreman","type":"NPC","wcid":13088,"cell":"0366018C","place":"dungeon","id":5796,"desc":"Trophy Collector. In a dungeon (landblock 0366)."}, + {"name":"Training Master","type":"NPC","wcid":12721,"cell":"036601D6","place":"dungeon","id":5797,"desc":"Soldier. In a dungeon (landblock 0366)."}, + {"name":"Senior Guard","type":"NPC","wcid":12727,"cell":"036601E5","place":"dungeon","id":5798,"desc":"Soldier. In a dungeon (landblock 0366)."}, + {"name":"Guard","type":"NPC","wcid":12724,"cell":"0366021D","place":"dungeon","id":5799,"desc":"Soldier. In a dungeon (landblock 0366)."}, + {"name":"Academy Quartermaster","type":"Vendor","wcid":12720,"cell":"0366023F","place":"dungeon","id":5800,"desc":"Blacksmith. In a dungeon (landblock 0366)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"03660264","place":"dungeon","id":5801,"desc":"Herald. In a dungeon (landblock 0366)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"036602DA","place":"dungeon","id":5802,"desc":"Shopkeeper. In a dungeon (landblock 0366)."}, + {"name":"Sentry","type":"NPC","wcid":12735,"cell":"036602EF","place":"dungeon","id":5803,"desc":"Soldier. In a dungeon (landblock 0366)."}, + {"name":"Greeter","type":"NPC","wcid":12723,"cell":"0367012F","place":"dungeon","id":5804,"desc":"Guard. In a dungeon (landblock 0367)."}, + {"name":"Guard","type":"NPC","wcid":12722,"cell":"0367014E","place":"dungeon","id":5805,"desc":"Soldier. In a dungeon (landblock 0367)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":12719,"cell":"03670173","place":"dungeon","id":5806,"desc":"Trophy Collector. In a dungeon (landblock 0367)."}, + {"name":"Academy Foreman","type":"NPC","wcid":13088,"cell":"0367018C","place":"dungeon","id":5807,"desc":"Trophy Collector. In a dungeon (landblock 0367)."}, + {"name":"Training Master","type":"NPC","wcid":12721,"cell":"036701D6","place":"dungeon","id":5808,"desc":"Soldier. In a dungeon (landblock 0367)."}, + {"name":"Senior Guard","type":"NPC","wcid":12727,"cell":"036701E5","place":"dungeon","id":5809,"desc":"Soldier. In a dungeon (landblock 0367)."}, + {"name":"Guard","type":"NPC","wcid":12724,"cell":"0367021D","place":"dungeon","id":5810,"desc":"Soldier. In a dungeon (landblock 0367)."}, + {"name":"Academy Quartermaster","type":"Vendor","wcid":12720,"cell":"0367023F","place":"dungeon","id":5811,"desc":"Blacksmith. In a dungeon (landblock 0367)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"03670264","place":"dungeon","id":5812,"desc":"Herald. In a dungeon (landblock 0367)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"036702DA","place":"dungeon","id":5813,"desc":"Shopkeeper. In a dungeon (landblock 0367)."}, + {"name":"Sentry","type":"NPC","wcid":12737,"cell":"036702EF","place":"dungeon","id":5814,"desc":"Soldier. In a dungeon (landblock 0367)."}, + {"name":"Greeter","type":"NPC","wcid":12723,"cell":"0368012F","place":"dungeon","id":5815,"desc":"Guard. In a dungeon (landblock 0368)."}, + {"name":"Guard","type":"NPC","wcid":12722,"cell":"0368014E","place":"dungeon","id":5816,"desc":"Soldier. In a dungeon (landblock 0368)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":12719,"cell":"03680173","place":"dungeon","id":5817,"desc":"Trophy Collector. In a dungeon (landblock 0368)."}, + {"name":"Academy Foreman","type":"NPC","wcid":13088,"cell":"0368018C","place":"dungeon","id":5818,"desc":"Trophy Collector. In a dungeon (landblock 0368)."}, + {"name":"Training Master","type":"NPC","wcid":12721,"cell":"036801D6","place":"dungeon","id":5819,"desc":"Soldier. In a dungeon (landblock 0368)."}, + {"name":"Senior Guard","type":"NPC","wcid":12727,"cell":"036801E5","place":"dungeon","id":5820,"desc":"Soldier. In a dungeon (landblock 0368)."}, + {"name":"Guard","type":"NPC","wcid":12724,"cell":"0368021D","place":"dungeon","id":5821,"desc":"Soldier. In a dungeon (landblock 0368)."}, + {"name":"Academy Quartermaster","type":"Vendor","wcid":12720,"cell":"0368023F","place":"dungeon","id":5822,"desc":"Blacksmith. In a dungeon (landblock 0368)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"03680264","place":"dungeon","id":5823,"desc":"Herald. In a dungeon (landblock 0368)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"036802DA","place":"dungeon","id":5824,"desc":"Shopkeeper. In a dungeon (landblock 0368)."}, + {"name":"Sentry","type":"NPC","wcid":12737,"cell":"036802EF","place":"dungeon","id":5825,"desc":"Soldier. In a dungeon (landblock 0368)."}, + {"name":"Arcanum Envoy","type":"NPC","wcid":12686,"cell":"039C018F","place":"dungeon","id":5826,"desc":"Master House Decorator. In Hollow Lair near Lytelthorpe."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"039C0199","place":"dungeon","id":5827,"desc":"In Hollow Lair near Lytelthorpe."}, + {"name":"Jasin of the Arcanum","type":"Vendor","wcid":12687,"cell":"039C01F8","place":"dungeon","id":5828,"desc":"Apprentice. In Hollow Lair near Lytelthorpe."}, + {"name":"Runic Door Guardian","type":"NPC","wcid":31228,"cell":"03A5014A","place":"dungeon","id":5829,"desc":"In Undead Temple."}, + {"name":"Exploration Marker","type":"NPC","wcid":39846,"cell":"050E002B","place":"outdoor","ns":-90.45,"ew":-97.4,"id":5830}, + {"name":"Surloshen Realaidain","type":"NPC","wcid":31602,"cell":"06020100","place":"dungeon","id":5831,"desc":"Unwanted. In a dungeon (landblock 0602)."}, + {"name":"Xireri","type":"NPC","wcid":31509,"cell":"0609002C","place":"outdoor","ns":-94.39,"ew":-96.59,"id":5832,"desc":"Hungry Golem."}, + {"name":"Exploration Marker","type":"NPC","wcid":39784,"cell":"08080040","place":"outdoor","ns":-94.75,"ew":-94.75,"id":5833}, + {"name":"Solange","type":"NPC","wcid":36232,"cell":"09050102","place":"underground","ns":-97.44,"ew":-94.6,"id":5834,"desc":"Rift Walker."}, + {"name":"Statue of Bael'Zharon, the Hopeslayer","type":"NPC","wcid":36012,"cell":"09050003","place":"outdoor","ns":-97.66,"ew":-94.7,"id":5835}, + {"name":"Black Totem Gateway","type":"NPC","wcid":33914,"cell":"090B0002","place":"outdoor","ns":-93.0,"ew":-94.7,"id":5836}, + {"name":"Nightmare Gate","type":"NPC","wcid":31411,"cell":"0A0F0033","place":"outdoor","ns":-89.7,"ew":-93.3,"id":5837}, + {"name":"Drudge Flying Machine","type":"NPC","wcid":30628,"cell":"0B700000","place":"outdoor","ns":-11.94,"ew":-92.88,"id":5838}, + {"name":"Portal Device","type":"NPC","wcid":29728,"cell":"0D4A012D","place":"dungeon","id":5839,"desc":"In a dungeon (landblock 0D4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":29715,"cell":"0D4A010C","place":"dungeon","id":5840,"desc":"In a dungeon (landblock 0D4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"0D4A010C","place":"dungeon","id":5841,"desc":"In a dungeon (landblock 0D4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":29716,"cell":"0D4A010E","place":"dungeon","id":5842,"desc":"In a dungeon (landblock 0D4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":29717,"cell":"0D4A010F","place":"dungeon","id":5843,"desc":"In a dungeon (landblock 0D4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"0D4A010D","place":"dungeon","id":5844,"desc":"In a dungeon (landblock 0D4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"0D4A010F","place":"dungeon","id":5845,"desc":"In a dungeon (landblock 0D4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"0D4A010E","place":"dungeon","id":5846,"desc":"In a dungeon (landblock 0D4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":29718,"cell":"0D4A010D","place":"dungeon","id":5847,"desc":"In a dungeon (landblock 0D4A)."}, + {"name":"Tekapuapuh","type":"NPC","wcid":10923,"cell":"0DB90000","place":"outdoor","ns":46.39,"ew":-91.49,"id":5848,"desc":"Buhka."}, + {"name":"Putiputipuh","type":"NPC","wcid":10924,"cell":"0DB90000","place":"outdoor","ns":46.38,"ew":-91.48,"id":5849}, + {"name":"Hea Arantah","type":"NPC","wcid":10978,"cell":"0EBA0000","place":"outdoor","ns":47.13,"ew":-90.31,"id":5850}, + {"name":"Hea Rangaua the Elder Shaman","type":"Vendor","wcid":11375,"cell":"0EBA0000","place":"outdoor","ns":46.88,"ew":-90.08,"id":5851}, + {"name":"Hea Nyrinua the Armorer","type":"Vendor","wcid":11376,"cell":"0EBA010A","place":"building","ns":47.13,"ew":-90.39,"id":5852}, + {"name":"Hea Timitea the Bowyer","type":"Vendor","wcid":11378,"cell":"0EBA010A","place":"building","ns":47.11,"ew":-90.38,"id":5853}, + {"name":"Hea Camauri the Barkeep","type":"Vendor","wcid":11377,"cell":"0EBA0100","place":"building","ns":47.11,"ew":-90.21,"id":5854}, + {"name":"Hea Nyrenauri the Healer","type":"Vendor","wcid":11379,"cell":"0EBA0000","place":"outdoor","ns":47.21,"ew":-90.43,"id":5855}, + {"name":"Hea Kiriona the Shopkeep","type":"Vendor","wcid":11381,"cell":"0EBA0000","place":"outdoor","ns":47.28,"ew":-90.39,"id":5856}, + {"name":"Hea Palagura the Jeweler","type":"Vendor","wcid":11380,"cell":"0EBA0000","place":"outdoor","ns":46.91,"ew":-90.13,"id":5857}, + {"name":"Hea Riketura the Collector","type":"NPC","wcid":11343,"cell":"0EBA0000","place":"outdoor","ns":47.05,"ew":-90.28,"id":5858}, + {"name":"Hea Ihipura the Crafter","type":"NPC","wcid":11344,"cell":"0EBA0000","place":"outdoor","ns":47.17,"ew":-90.45,"id":5859}, + {"name":"Hea Mutuona","type":"NPC","wcid":10922,"cell":"0EBA0000","place":"outdoor","ns":47.11,"ew":-90.28,"id":5860}, + {"name":"Hea Kassoka","type":"NPC","wcid":31709,"cell":"0EBA0035","place":"outdoor","ns":47.29,"ew":-90.11,"id":5861,"desc":"Hunter."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"0F870000","place":"outdoor","ns":6.72,"ew":-89.88,"id":5862}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"1035003E","place":"outdoor","ns":-59.01,"ew":-88.37,"id":5863}, + {"name":"Carenzi Race Bookie","type":"NPC","wcid":38993,"cell":"1035003C","place":"outdoor","ns":-59.16,"ew":-88.44,"id":5864,"desc":"Cashier."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38976,"cell":"10350034","place":"outdoor","ns":-59.22,"ew":-88.49,"id":5865,"desc":"(8)."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38974,"cell":"10350034","place":"outdoor","ns":-59.21,"ew":-88.48,"id":5866,"desc":"(6)."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38973,"cell":"10350034","place":"outdoor","ns":-59.21,"ew":-88.49,"id":5867,"desc":"(5)."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38972,"cell":"10350034","place":"outdoor","ns":-59.2,"ew":-88.49,"id":5868,"desc":"(4)."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38971,"cell":"10350034","place":"outdoor","ns":-59.19,"ew":-88.48,"id":5869,"desc":"(3)."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38970,"cell":"10350034","place":"outdoor","ns":-59.19,"ew":-88.49,"id":5870,"desc":"(2)."}, + {"name":"Carenzi Race Announcer","type":"NPC","wcid":38978,"cell":"10350034","place":"outdoor","ns":-59.16,"ew":-88.45,"id":5871,"desc":"Master of Ceremonies."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38946,"cell":"10350034","place":"outdoor","ns":-59.16,"ew":-88.52,"id":5872,"desc":"(2)."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38952,"cell":"10350034","place":"outdoor","ns":-59.16,"ew":-88.47,"id":5873,"desc":"(8)."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38947,"cell":"10350034","place":"outdoor","ns":-59.16,"ew":-88.51,"id":5874,"desc":"(3)."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38948,"cell":"10350034","place":"outdoor","ns":-59.16,"ew":-88.5,"id":5875,"desc":"(4)."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38950,"cell":"10350034","place":"outdoor","ns":-59.16,"ew":-88.49,"id":5876,"desc":"(6)."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38951,"cell":"10350034","place":"outdoor","ns":-59.16,"ew":-88.48,"id":5877,"desc":"(7)."}, + {"name":"Carenzi Racer","type":"NPC","wcid":38945,"cell":"10350034","place":"outdoor","ns":-59.16,"ew":-88.53,"id":5878,"desc":"(1)."}, + {"name":"Aun Aukherea","type":"NPC","wcid":27262,"cell":"11330000","place":"outdoor","ns":-60.73,"ew":-88.04,"id":5879,"desc":"Coral Golem Hunter."}, + {"name":"Aun Khekierea","type":"NPC","wcid":27267,"cell":"11330000","place":"outdoor","ns":-60.72,"ew":-88.03,"id":5880,"desc":"Platinum Golem Hunter."}, + {"name":"Aludi al-Jaladh","type":"NPC","wcid":30629,"cell":"11330000","place":"outdoor","ns":-60.69,"ew":-87.98,"id":5881,"desc":"Warrior of the Wastes."}, + {"name":"Aun Javhalrea, the Game Warden","type":"NPC","wcid":36866,"cell":"1133001D","place":"outdoor","ns":-60.73,"ew":-87.97,"id":5882,"desc":"Game Warden."}, + {"name":"Sang Nen-Kai the Weaponsmith","type":"Vendor","wcid":6862,"cell":"11340101","place":"building","ns":-60.09,"ew":-88.03,"id":5883,"desc":"Weaponsmith."}, + {"name":"Jeweler Daryam ibn Zubed","type":"Vendor","wcid":6860,"cell":"11340000","place":"outdoor","ns":-59.81,"ew":-88.07,"id":5884,"desc":"Jeweler."}, + {"name":"Ivory Crafter","type":"NPC","wcid":3926,"cell":"11340000","place":"outdoor","ns":-60.01,"ew":-88.07,"id":5885,"desc":"Trophy Crafter."}, + {"name":"Sung Wenxio the Armorer","type":"Vendor","wcid":6855,"cell":"11340100","place":"building","ns":-60.11,"ew":-88.01,"id":5886,"desc":"Armorer."}, + {"name":"Grocer Nihara bint Umar","type":"Vendor","wcid":6858,"cell":"11340130","place":"building","ns":-59.7,"ew":-88.03,"id":5887,"desc":"Provisioner."}, + {"name":"Berkholt the Burly Barkeep","type":"Vendor","wcid":6856,"cell":"1134013A","place":"building","ns":-59.67,"ew":-88.0,"id":5888,"desc":"Barkeeper."}, + {"name":"Scribe Muhiza bint Murqidh","type":"Vendor","wcid":6861,"cell":"11340111","place":"building","ns":-60.02,"ew":-87.77,"id":5889,"desc":"Scribe."}, + {"name":"Leather Crafter","type":"NPC","wcid":4214,"cell":"11340102","place":"building","ns":-60.13,"ew":-87.99,"id":5890,"desc":"Trophy Collector."}, + {"name":"Thiuda the Sharp-Eyed Bowyer","type":"Vendor","wcid":6857,"cell":"11340000","place":"outdoor","ns":-60.08,"ew":-87.89,"id":5891,"desc":"Bowyer."}, + {"name":"Ellimar Jorning the Healer","type":"Vendor","wcid":6859,"cell":"11340000","place":"outdoor","ns":-59.99,"ew":-87.79,"id":5892,"desc":"Healer."}, + {"name":"Yuan Hanzu","type":"NPC","wcid":7241,"cell":"11340000","place":"outdoor","ns":-60.07,"ew":-87.92,"id":5893,"desc":"Master Bowyer."}, + {"name":"Town Crier","type":"NPC","wcid":5774,"cell":"11340000","place":"outdoor","ns":-59.88,"ew":-87.84,"id":5894,"desc":"Herald."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"11340145","place":"building","ns":-59.78,"ew":-87.79,"id":5895,"desc":"Mage."}, + {"name":"Grand Master Scrivener of War Magic","type":"Vendor","wcid":20224,"cell":"1134014C","place":"building","ns":-59.93,"ew":-88.19,"id":5896,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Creature Magic","type":"Vendor","wcid":20208,"cell":"11340000","place":"outdoor","ns":-59.91,"ew":-88.18,"id":5897,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Item Magic","type":"Vendor","wcid":20212,"cell":"11340000","place":"outdoor","ns":-59.92,"ew":-88.21,"id":5898,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Life Magic","type":"Vendor","wcid":20220,"cell":"11340151","place":"building","ns":-59.87,"ew":-88.23,"id":5899,"desc":"Master Archmage."}, + {"name":"Aaminah","type":"NPC","wcid":24153,"cell":"11340000","place":"outdoor","ns":-60.0,"ew":-87.81,"id":5900,"desc":"Grieving Wife."}, + {"name":"Tanami Kei","type":"NPC","wcid":30509,"cell":"11340131","place":"building","ns":-59.7,"ew":-88.03,"id":5901,"desc":"Natural Philosopher."}, + {"name":"Anfram Mellow","type":"NPC","wcid":41515,"cell":"1134010E","place":"building","ns":-59.97,"ew":-87.79,"id":5902,"desc":"Augmentation Trainer."}, + {"name":"Alishia bint Aldan","type":"NPC","wcid":41526,"cell":"1134010E","place":"building","ns":-59.98,"ew":-87.77,"id":5903,"desc":"Augmentation Trainer."}, + {"name":"Dionaea","type":"NPC","wcid":31690,"cell":"1134001F","place":"outdoor","ns":-59.68,"ew":-87.97,"id":5904,"desc":"Monster Plant Lover."}, + {"name":"Erik Festus","type":"NPC","wcid":28690,"cell":"11340147","place":"building","ns":-59.79,"ew":-87.79,"id":5905,"desc":"Augmentation Trainer."}, + {"name":"Rohula bint Ludun","type":"NPC","wcid":28686,"cell":"11340147","place":"building","ns":-59.8,"ew":-87.79,"id":5906,"desc":"Augmentation Trainer."}, + {"name":"Ulgrim the Unpleasant","type":"NPC","wcid":6873,"cell":"1134001F","place":"outdoor","ns":-59.74,"ew":-88.02,"id":5907,"desc":"Mayor of Ayan Baqur."}, + {"name":"Grand Master Scrivener of Void Magic","type":"Vendor","wcid":43353,"cell":"1134000D","place":"outdoor","ns":-59.9,"ew":-88.22,"id":5908,"desc":"Master Archmage."}, + {"name":"Harkwull the Discreet","type":"NPC","wcid":32991,"cell":"11340138","place":"building","ns":-59.69,"ew":-87.99,"id":5909,"desc":"Linguist."}, + {"name":"Mekhmet","type":"NPC","wcid":32684,"cell":"1134015A","place":"building","ns":-59.71,"ew":-88.19,"id":5910,"desc":"Ore Merchant."}, + {"name":"Soju Bo-Ki","type":"NPC","wcid":33876,"cell":"1134015C","place":"building","ns":-59.6,"ew":-88.0,"id":5911,"desc":"Operative."}, + {"name":"Lamorda Loschi","type":"NPC","wcid":33875,"cell":"1134015C","place":"building","ns":-59.6,"ew":-88.02,"id":5912,"desc":"Operative."}, + {"name":"Hoshar ibn Jalaq","type":"NPC","wcid":33877,"cell":"1134015D","place":"building","ns":-59.6,"ew":-87.99,"id":5913,"desc":"Operative."}, + {"name":"Havala bint Mylos","type":"NPC","wcid":35962,"cell":"11340023","place":"outdoor","ns":-60.07,"ew":-87.94,"id":5914,"desc":"Master Atlatl Crafter."}, + {"name":"Emissary of Asheron","type":"NPC","wcid":43074,"cell":"1134001C","place":"outdoor","ns":-59.97,"ew":-87.98,"id":5915,"desc":"Emissary."}, + {"name":"Guard Q'alia","type":"NPC","wcid":36534,"cell":"1134001C","place":"outdoor","ns":-60.01,"ew":-87.97,"id":5916,"desc":"Soldier."}, + {"name":"Laedron the Geomancer","type":"NPC","wcid":38211,"cell":"1134001D","place":"outdoor","ns":-59.92,"ew":-87.98,"id":5917,"desc":"Royal Land Surveyor."}, + {"name":"Guard Bey","type":"NPC","wcid":37445,"cell":"1134000E","place":"outdoor","ns":-59.79,"ew":-88.24,"id":5918,"desc":"Soldier."}, + {"name":"Shuthoth","type":"NPC","wcid":31970,"cell":"11340033","place":"outdoor","ns":-60.07,"ew":-87.69,"id":5919,"desc":"Servant of the Lady."}, + {"name":"Lydda","type":"NPC","wcid":32813,"cell":"1134001F","place":"outdoor","ns":-59.75,"ew":-87.96,"id":5920,"desc":"Plumber."}, + {"name":"Guard Winterborn","type":"NPC","wcid":35344,"cell":"1134002F","place":"outdoor","ns":-59.66,"ew":-87.76,"id":5921,"desc":"Guard."}, + {"name":"Merwart Mundagurg","type":"NPC","wcid":37400,"cell":"1134000F","place":"outdoor","ns":-59.67,"ew":-88.22,"id":5922,"desc":"Explorer."}, + {"name":"Ennio di Cinghalle","type":"NPC","wcid":35562,"cell":"11340038","place":"outdoor","ns":-59.56,"ew":-87.69,"id":5923,"desc":"Royal Investigator."}, + {"name":"Vierana du Canamorra","type":"NPC","wcid":37600,"cell":"11340111","place":"building","ns":-60.01,"ew":-87.78,"id":5924,"desc":"Blood Recruiter."}, + {"name":"Gaston Shadowbound","type":"NPC","wcid":38462,"cell":"11340133","place":"building","ns":-59.7,"ew":-87.97,"id":5925,"desc":"Vagabond."}, + {"name":"Joku Shunja","type":"NPC","wcid":37599,"cell":"1134001B","place":"outdoor","ns":-60.12,"ew":-87.97,"id":5926,"desc":"Hand Recruiter."}, + {"name":"Qurakh al-Taal","type":"NPC","wcid":37598,"cell":"11340025","place":"outdoor","ns":-59.91,"ew":-87.86,"id":5927,"desc":"Web Recruiter."}, + {"name":"Claude the Archmage","type":"Vendor","wcid":6854,"cell":"11350100","place":"building","ns":-59.2,"ew":-88.29,"id":5928}, + {"name":"Leopold","type":"NPC","wcid":8155,"cell":"11350100","place":"building","ns":-59.2,"ew":-88.31,"id":5929}, + {"name":"Lugian Lifestone","type":"Lifestone","wcid":27096,"cell":"1203001C","place":"outdoor","ns":-99.18,"ew":-87.19,"id":5930}, + {"name":"Exploration Marker","type":"NPC","wcid":39842,"cell":"12460100","place":"dungeon","id":5931,"desc":"In a dungeon (landblock 1246)."}, + {"name":"Ishaq the Philosopher","type":"NPC","wcid":29229,"cell":"132C0102","place":"building","ns":-66.08,"ew":-86.58,"id":5932,"desc":"Natural Philosopher."}, + {"name":"Exploration Marker","type":"NPC","wcid":39805,"cell":"13960024","place":"outdoor","ns":18.37,"ew":-86.25,"id":5933}, + {"name":"An Empyrean device","type":"NPC","wcid":87839,"cell":"152D0024","place":"outdoor","ns":-65.6,"ew":-84.7,"id":5934}, + {"name":"Lost Messenger's Corpse","type":"NPC","wcid":87535,"cell":"173B0036","place":"outdoor","ns":-54.22,"ew":-82.92,"id":5935}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"17480000","place":"outdoor","ns":-43.6,"ew":-83.0,"id":5936}, + {"name":"Micon Stuvis the Barkeep","type":"Vendor","wcid":11395,"cell":"17B20105","place":"building","ns":40.74,"ew":-83.0,"id":5937,"desc":"Barkeeper."}, + {"name":"Ling Xiao the Collector","type":"NPC","wcid":11347,"cell":"17B2010E","place":"building","ns":40.68,"ew":-83.03,"id":5938,"desc":"Trophy Collector."}, + {"name":"Leyrale Shalorn the Tailor","type":"Vendor","wcid":11399,"cell":"17B2011D","place":"building","ns":40.61,"ew":-82.91,"id":5939,"desc":"Tailor."}, + {"name":"Lam Yi the Jeweler","type":"Vendor","wcid":11396,"cell":"17B2011B","place":"building","ns":40.6,"ew":-83.1,"id":5940,"desc":"Jeweler."}, + {"name":"Behdo Yii","type":"NPC","wcid":10842,"cell":"17B20122","place":"building","ns":40.8,"ew":-83.29,"id":5941,"desc":"Researcher."}, + {"name":"Milanna Russmad the Mage","type":"Vendor","wcid":11397,"cell":"17B20126","place":"building","ns":40.78,"ew":-83.32,"id":5942,"desc":"Archmage."}, + {"name":"Ton Ai Yen the Armorer","type":"Vendor","wcid":11394,"cell":"17B2011F","place":"building","ns":40.88,"ew":-83.38,"id":5943,"desc":"Armorer."}, + {"name":"Janus Roma the Shopkeep","type":"Vendor","wcid":31955,"cell":"17B2012A","place":"building","ns":40.78,"ew":-83.13,"id":5944,"desc":"Scribe."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"17B20000","place":"outdoor","ns":40.67,"ew":-83.13,"id":5945}, + {"name":"Town Crier","type":"NPC","wcid":5772,"cell":"17B20000","place":"outdoor","ns":40.59,"ew":-82.99,"id":5946,"desc":"Herald."}, + {"name":"Bachus Flufens","type":"NPC","wcid":11322,"cell":"17B20000","place":"outdoor","ns":40.72,"ew":-83.02,"id":5947,"desc":"Settler."}, + {"name":"Afra bint Abbas","type":"NPC","wcid":31648,"cell":"17B2002B","place":"outdoor","ns":40.74,"ew":-82.98,"id":5948,"desc":"Ebon Gromnie Eradicator."}, + {"name":"Guard Liaza","type":"NPC","wcid":37440,"cell":"17B2012B","place":"building","ns":40.79,"ew":-82.99,"id":5949,"desc":"Soldier."}, + {"name":"Piero Cenizzi","type":"NPC","wcid":32069,"cell":"17B2002C","place":"outdoor","ns":40.79,"ew":-83.01,"id":5950,"desc":"Ferran Knight."}, + {"name":"Susana du Loc","type":"NPC","wcid":32109,"cell":"17B2001B","place":"outdoor","ns":40.74,"ew":-83.22,"id":5951,"desc":"Windreave Stalker."}, + {"name":"Andrea Dilazo","type":"NPC","wcid":32073,"cell":"17B20024","place":"outdoor","ns":40.76,"ew":-83.09,"id":5952,"desc":"Royal Chirurgeon."}, + {"name":"Niccolo Brasi","type":"NPC","wcid":32072,"cell":"17B2000D","place":"outdoor","ns":40.88,"ew":-83.45,"id":5953,"desc":"Ferran Knight."}, + {"name":"Lucio Murrio","type":"NPC","wcid":32074,"cell":"17B2002B","place":"outdoor","ns":40.65,"ew":-82.98,"id":5954,"desc":"Royal Scout."}, + {"name":"Chief Taraash","type":"NPC","wcid":35343,"cell":"19340002","place":"outdoor","ns":-60.17,"ew":-81.93,"id":5955,"desc":"Banderling Chief."}, + {"name":"Banderling Guard Champion","type":"NPC","wcid":35338,"cell":"19340002","place":"outdoor","ns":-60.18,"ew":-81.94,"id":5956,"desc":"Chief's Personal Guard."}, + {"name":"Banderling Guard Champion","type":"NPC","wcid":35338,"cell":"19340002","place":"outdoor","ns":-60.17,"ew":-81.93,"id":5957,"desc":"Chief's Personal Guard."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72173,"cell":"19BC0037","place":"outdoor","ns":49.12,"ew":-81.29,"id":5958}, + {"name":"Lightning Cloud","type":"NPC","wcid":72173,"cell":"19BC0037","place":"outdoor","ns":49.11,"ew":-81.26,"id":5959}, + {"name":"Bell","type":"NPC","wcid":35762,"cell":"1A7302F4","place":"dungeon","id":5960,"desc":"In a dungeon (landblock 1A73)."}, + {"name":"Bell","type":"NPC","wcid":35763,"cell":"1A7302B2","place":"dungeon","id":5961,"desc":"In a dungeon (landblock 1A73)."}, + {"name":"Bell","type":"NPC","wcid":35761,"cell":"1A7302E1","place":"dungeon","id":5962,"desc":"In a dungeon (landblock 1A73)."}, + {"name":"Lugian Prisoner","type":"NPC","wcid":30825,"cell":"1A8E025F","place":"underground","ns":12.71,"ew":-81.5,"id":5963}, + {"name":"Lugian Prisoner","type":"NPC","wcid":30824,"cell":"1A8E0269","place":"underground","ns":12.74,"ew":-81.43,"id":5964}, + {"name":"Lugian Prisoner","type":"NPC","wcid":30827,"cell":"1A8E026D","place":"underground","ns":12.69,"ew":-81.43,"id":5965}, + {"name":"Lugian Prisoner","type":"NPC","wcid":30828,"cell":"1A8E0279","place":"underground","ns":12.71,"ew":-81.36,"id":5966}, + {"name":"Shadow","type":"NPC","wcid":30826,"cell":"1A8E0104","place":"underground","ns":11.59,"ew":-82.61,"id":5967}, + {"name":"Harraag's Hideout","type":"NPC","wcid":35486,"cell":"1B340100","place":"building","ns":-60.24,"ew":-80.14,"id":5968}, + {"name":"Banderling Guard Champion","type":"NPC","wcid":35341,"cell":"1B340100","place":"building","ns":-60.21,"ew":-80.16,"id":5969,"desc":"Elite Champion."}, + {"name":"Banderling Guard Champion","type":"NPC","wcid":35342,"cell":"1B340100","place":"building","ns":-60.23,"ew":-80.18,"id":5970,"desc":"Elite Champion."}, + {"name":"Banderling Guard Champion","type":"NPC","wcid":35341,"cell":"1B34000A","place":"outdoor","ns":-60.17,"ew":-80.23,"id":5971,"desc":"Elite Champion."}, + {"name":"Banderling Guard Champion","type":"NPC","wcid":35342,"cell":"1B34000A","place":"outdoor","ns":-60.21,"ew":-80.16,"id":5972,"desc":"Elite Champion."}, + {"name":"Exploration Marker","type":"NPC","wcid":39753,"cell":"1B7F0006","place":"outdoor","ns":0.21,"ew":-80.31,"id":5973}, + {"name":"Exploration Marker","type":"NPC","wcid":39749,"cell":"1C140021","place":"outdoor","ns":-85.86,"ew":-79.14,"id":5974}, + {"name":"Undead Mechanic","type":"NPC","wcid":25314,"cell":"1CB40101","place":"building","ns":42.13,"ew":-79.11,"id":5975}, + {"name":"Keh Fire","type":"NPC","wcid":36114,"cell":"1CC2002A","place":"outdoor","ns":53.41,"ew":-78.99,"id":5976}, + {"name":"Aun Kelauri","type":"NPC","wcid":36113,"cell":"1CC2002A","place":"outdoor","ns":53.41,"ew":-79.0,"id":5977}, + {"name":"Exploration Marker","type":"NPC","wcid":39769,"cell":"1DB10030","place":"outdoor","ns":40.44,"ew":-78.16,"id":5978}, + {"name":"Aun Firanauri the Gate Keeper","type":"NPC","wcid":11406,"cell":"1DB60000","place":"outdoor","ns":44.21,"ew":-78.43,"id":5979}, + {"name":"Aun Town Crier","type":"NPC","wcid":11940,"cell":"1DB60000","place":"outdoor","ns":44.08,"ew":-78.29,"id":5980,"desc":"Herald."}, + {"name":"Aun Dreganaua the Elder Shaman","type":"Vendor","wcid":11400,"cell":"1DB60000","place":"outdoor","ns":44.2,"ew":-78.12,"id":5981}, + {"name":"Aun Mireona the Shopkeep","type":"Vendor","wcid":11407,"cell":"1DB60000","place":"outdoor","ns":43.93,"ew":-78.07,"id":5982}, + {"name":"Aun Taguauri the Healer","type":"Vendor","wcid":11404,"cell":"1DB60000","place":"outdoor","ns":44.11,"ew":-78.0,"id":5983}, + {"name":"Aun Ngaiona the Jeweler","type":"Vendor","wcid":11405,"cell":"1DB60000","place":"outdoor","ns":43.88,"ew":-78.13,"id":5984}, + {"name":"Aun Laranawa the Barkeep","type":"Vendor","wcid":11402,"cell":"1DB60000","place":"outdoor","ns":44.34,"ew":-78.03,"id":5985}, + {"name":"Aun Mareura the Collector","type":"NPC","wcid":11348,"cell":"1DB60000","place":"outdoor","ns":43.93,"ew":-78.11,"id":5986}, + {"name":"Aun Whethura the Crafter","type":"NPC","wcid":11349,"cell":"1DB60000","place":"outdoor","ns":43.87,"ew":-78.07,"id":5987}, + {"name":"Aun Kiriona","type":"NPC","wcid":24055,"cell":"1DB60106","place":"building","ns":44.17,"ew":-77.97,"id":5988}, + {"name":"Aun Rukuona","type":"NPC","wcid":24054,"cell":"1DB60106","place":"building","ns":44.18,"ew":-77.96,"id":5989}, + {"name":"Aun Ngationa","type":"NPC","wcid":24053,"cell":"1DB60106","place":"building","ns":44.22,"ew":-77.97,"id":5990}, + {"name":"Aun Turiona","type":"NPC","wcid":24052,"cell":"1DB60106","place":"building","ns":44.21,"ew":-77.96,"id":5991}, + {"name":"Aun Faranua","type":"NPC","wcid":28472,"cell":"1DB60000","place":"outdoor","ns":44.17,"ew":-78.26,"id":5992}, + {"name":"Aun Kimintari","type":"NPC","wcid":39054,"cell":"1DB60106","place":"building","ns":44.19,"ew":-78.0,"id":5993,"desc":"Guardian of the Deru."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"1E090007","place":"outdoor","ns":-94.09,"ew":-77.94,"id":5994}, + {"name":"Water Guardian","type":"NPC","wcid":31971,"cell":"1E090007","place":"outdoor","ns":-94.13,"ew":-77.87,"id":5995,"desc":"Warden of the Deep."}, + {"name":"Life Stone","type":"Lifestone","wcid":23618,"cell":"1EB20000","place":"outdoor","ns":41.0,"ew":-77.4,"id":5996}, + {"name":"Aun Maanuawa the Armorer","type":"Vendor","wcid":11401,"cell":"1EB60000","place":"outdoor","ns":44.23,"ew":-77.87,"id":5997}, + {"name":"Aun Paikitea the Bowyer","type":"Vendor","wcid":11403,"cell":"1EB60000","place":"outdoor","ns":44.19,"ew":-77.9,"id":5998}, + {"name":"Aun Ruperea","type":"NPC","wcid":32107,"cell":"1EB60007","place":"outdoor","ns":44.33,"ew":-77.94,"id":5999,"desc":"Voracious Hunter."}, + {"name":"Aun Papileona","type":"NPC","wcid":11330,"cell":"1FB10000","place":"outdoor","ns":39.8,"ew":-76.4,"id":6000}, + {"name":"Life Stone","type":"Lifestone","wcid":23618,"cell":"1FC90000","place":"outdoor","ns":59.2,"ew":-76.9,"id":6001}, + {"name":"Lugian Miner","type":"NPC","wcid":42929,"cell":"200F0A16","place":"underground","ns":-89.87,"ew":-76.17,"id":6002,"desc":"Miner."}, + {"name":"Lugian Miner","type":"NPC","wcid":42929,"cell":"200F0A50","place":"underground","ns":-89.89,"ew":-76.12,"id":6003,"desc":"Miner."}, + {"name":"Lugian Miner","type":"NPC","wcid":42929,"cell":"200F0A50","place":"underground","ns":-89.89,"ew":-76.11,"id":6004,"desc":"Miner."}, + {"name":"Mine Foreman","type":"NPC","wcid":42930,"cell":"200F0A30","place":"underground","ns":-89.93,"ew":-76.16,"id":6005,"desc":"Miner."}, + {"name":"Lugian Miner","type":"NPC","wcid":42929,"cell":"200F0A37","place":"underground","ns":-90.07,"ew":-76.13,"id":6006,"desc":"Miner."}, + {"name":"Lugian Miner","type":"NPC","wcid":42929,"cell":"200F0A3B","place":"underground","ns":-90.07,"ew":-76.16,"id":6007,"desc":"Miner."}, + {"name":"Mine Chamberlain","type":"NPC","wcid":42931,"cell":"200F0A66","place":"underground","ns":-89.91,"ew":-76.07,"id":6008,"desc":"Miner."}, + {"name":"Lugian Miner","type":"NPC","wcid":42929,"cell":"200F09F0","place":"underground","ns":-90.27,"ew":-76.16,"id":6009,"desc":"Miner."}, + {"name":"Lugian Miner","type":"NPC","wcid":42929,"cell":"200F08A9","place":"underground","ns":-90.35,"ew":-76.13,"id":6010,"desc":"Miner."}, + {"name":"Lugian Miner","type":"NPC","wcid":42929,"cell":"200F08A6","place":"underground","ns":-90.36,"ew":-76.13,"id":6011,"desc":"Miner."}, + {"name":"Lugian Miner","type":"NPC","wcid":42929,"cell":"200F0383","place":"underground","ns":-90.45,"ew":-76.16,"id":6012,"desc":"Miner."}, + {"name":"Exploration Marker","type":"NPC","wcid":39800,"cell":"20BF0004","place":"outdoor","ns":51.22,"ew":-76.26,"id":6013}, + {"name":"Lintareal","type":"Vendor","wcid":43144,"cell":"21700031","place":"outdoor","ns":-12.33,"ew":-74.91,"id":6014,"desc":"Gear Knight Quartermaster."}, + {"name":"T'ing Douzen","type":"NPC","wcid":41548,"cell":"21700029","place":"outdoor","ns":-12.27,"ew":-75.01,"id":6015,"desc":"Arcanum Collector."}, + {"name":"Emissary of Asheron","type":"NPC","wcid":43213,"cell":"21700029","place":"outdoor","ns":-12.33,"ew":-74.99,"id":6016,"desc":"Emissary."}, + {"name":"Dame Trielle","type":"NPC","wcid":41546,"cell":"21700029","place":"outdoor","ns":-12.27,"ew":-74.95,"id":6017,"desc":"Royal Knight."}, + {"name":"Squire Tylaen","type":"NPC","wcid":43145,"cell":"21700029","place":"outdoor","ns":-12.29,"ew":-74.97,"id":6018,"desc":"Copper Cog Supply Officer."}, + {"name":"Sir Durnstad","type":"NPC","wcid":42360,"cell":"21700029","place":"outdoor","ns":-12.29,"ew":-74.96,"id":6019,"desc":"Royal Knight."}, + {"name":"Sir Yanov","type":"NPC","wcid":41545,"cell":"21700103","place":"building","ns":-12.29,"ew":-74.9,"id":6020,"desc":"Royal Knight."}, + {"name":"Mana Siphon","type":"NPC","wcid":41547,"cell":"21720026","place":"outdoor","ns":-10.2,"ew":-75.1,"id":6021}, + {"name":"Copper Cog Craftsmaster","type":"NPC","wcid":42616,"cell":"21720283","place":"underground","ns":-10.35,"ew":-75.43,"id":6022,"desc":"Invasion Officer."}, + {"name":"Silver Scope Spymaster","type":"NPC","wcid":70707,"cell":"2172021B","place":"underground","ns":-10.05,"ew":-74.97,"id":6023,"desc":"Invasion Officer."}, + {"name":"Bronze Gauntlet Knight-Commander","type":"NPC","wcid":70708,"cell":"217202F0","place":"underground","ns":-10.61,"ew":-75.07,"id":6024,"desc":"Invasion Officer."}, + {"name":"Apostate Shimmering Stopgap","type":"NPC","wcid":70345,"cell":"217201C8","place":"underground","ns":-10.38,"ew":-75.05,"id":6025,"desc":"Stopgap."}, + {"name":"Apostate Scintillating Stopgap","type":"NPC","wcid":70344,"cell":"2172011B","place":"underground","ns":-10.4,"ew":-75.15,"id":6026,"desc":"Stopgap."}, + {"name":"Apostate Sparkling Stopgap","type":"NPC","wcid":70343,"cell":"21720250","place":"underground","ns":-10.13,"ew":-75.41,"id":6027,"desc":"Stopgap."}, + {"name":"Life Stone","type":"Lifestone","wcid":23618,"cell":"219A0000","place":"outdoor","ns":21.6,"ew":-75.2,"id":6028}, + {"name":"Wahnaqa bint Fayat the Mage","type":"Vendor","wcid":11387,"cell":"21B0010E","place":"building","ns":39.2,"ew":-75.23,"id":6029,"desc":"Archmage."}, + {"name":"Dorlan the Armorer","type":"Vendor","wcid":11382,"cell":"21B0011D","place":"building","ns":39.21,"ew":-75.53,"id":6030,"desc":"Armorer."}, + {"name":"Nathious Agoren the Jeweler","type":"Vendor","wcid":11386,"cell":"21B00133","place":"building","ns":39.03,"ew":-75.27,"id":6031,"desc":"Jeweler."}, + {"name":"Brother Ku-Xao Sutan the Monk","type":"Vendor","wcid":11388,"cell":"21B0012D","place":"building","ns":39.5,"ew":-75.22,"id":6032,"desc":"Scribe."}, + {"name":"Yusnar ibn Lomaq the Grocer","type":"Vendor","wcid":11385,"cell":"21B00114","place":"building","ns":39.48,"ew":-75.53,"id":6033,"desc":"Scribe."}, + {"name":"Merlonna Farel the Collector","type":"NPC","wcid":11345,"cell":"21B00118","place":"building","ns":39.48,"ew":-75.48,"id":6034,"desc":"Trophy Collector."}, + {"name":"Lark Grifanna the Barkeep","type":"Vendor","wcid":11384,"cell":"21B00107","place":"building","ns":39.23,"ew":-74.99,"id":6035,"desc":"Barkeeper."}, + {"name":"Aurten Rhell","type":"NPC","wcid":25672,"cell":"21B00118","place":"building","ns":39.49,"ew":-75.47,"id":6036,"desc":"Royal Guard."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"21B00000","place":"outdoor","ns":39.34,"ew":-75.34,"id":6037}, + {"name":"Town Crier","type":"NPC","wcid":5774,"cell":"21B00000","place":"outdoor","ns":39.43,"ew":-75.38,"id":6038,"desc":"Herald."}, + {"name":"Aun Arenura the Crafter","type":"NPC","wcid":29858,"cell":"21B00102","place":"building","ns":39.2,"ew":-74.99,"id":6039}, + {"name":"Turino Ribini","type":"NPC","wcid":32065,"cell":"21B00109","place":"building","ns":39.2,"ew":-75.19,"id":6040,"desc":"Tax Collector."}, + {"name":"Otto Selino","type":"NPC","wcid":32066,"cell":"21B00016","place":"outdoor","ns":39.4,"ew":-75.3,"id":6041,"desc":"Astronomer."}, + {"name":"Vettorio Bilcone","type":"NPC","wcid":32064,"cell":"21B00016","place":"outdoor","ns":39.41,"ew":-75.31,"id":6042,"desc":"Ferran Knight."}, + {"name":"Salvito di Marden","type":"NPC","wcid":32075,"cell":"21B00013","place":"outdoor","ns":39.15,"ew":-75.32,"id":6043,"desc":"Ferran Knight."}, + {"name":"Lucarus Malloni the Armorer","type":"Vendor","wcid":31956,"cell":"21B0011F","place":"building","ns":39.11,"ew":-75.42,"id":6044,"desc":"Armorer."}, + {"name":"Aun Nireeura","type":"NPC","wcid":29859,"cell":"21B10000","place":"outdoor","ns":39.71,"ew":-75.29,"id":6045,"desc":"Artisan in Pin and Pitch."}, + {"name":"Aun Ihmenaura","type":"NPC","wcid":29860,"cell":"21B10000","place":"outdoor","ns":39.69,"ew":-75.3,"id":6046,"desc":"Artisan in Feather and Claw."}, + {"name":"Aun Kahuiura","type":"NPC","wcid":29861,"cell":"21B10000","place":"outdoor","ns":39.7,"ew":-75.31,"id":6047,"desc":"Artisan in Arcane Ointment."}, + {"name":"Aun Pitamaura","type":"NPC","wcid":29862,"cell":"21B10000","place":"outdoor","ns":39.72,"ew":-75.31,"id":6048,"desc":"Artisan in Spike and Blade."}, + {"name":"Aun Teriona","type":"NPC","wcid":34253,"cell":"21B30011","place":"outdoor","ns":41.26,"ew":-75.29,"id":6049}, + {"name":"Exploration Marker","type":"NPC","wcid":39775,"cell":"21C50039","place":"outdoor","ns":55.66,"ew":-74.76,"id":6050}, + {"name":"Aun Bernawa","type":"NPC","wcid":11372,"cell":"22B20000","place":"outdoor","ns":41.13,"ew":-74.43,"id":6051}, + {"name":"Exploration Marker","type":"NPC","wcid":39825,"cell":"22E30040","place":"outdoor","ns":80.45,"ew":-73.95,"id":6052}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"231C0000","place":"outdoor","ns":-78.92,"ew":-73.37,"id":6053}, + {"name":"Antonia","type":"NPC","wcid":31950,"cell":"23B60123","place":"dungeon","id":6054,"desc":"Carenzi Rebel. In a dungeon (landblock 23B6)."}, + {"name":"Arica","type":"NPC","wcid":31951,"cell":"23B60123","place":"dungeon","id":6055,"desc":"Carenzi Rebel. In a dungeon (landblock 23B6)."}, + {"name":"Count Tenera","type":"NPC","wcid":31949,"cell":"23B6012B","place":"dungeon","id":6056,"desc":"Carenzi Rebel. In a dungeon (landblock 23B6)."}, + {"name":"Daniel","type":"NPC","wcid":31952,"cell":"23B60127","place":"dungeon","id":6057,"desc":"Carenzi Rebel. In a dungeon (landblock 23B6)."}, + {"name":"Dar Rell","type":"NPC","wcid":31941,"cell":"23B60137","place":"dungeon","id":6058,"desc":"Carenzi Rebel. In a dungeon (landblock 23B6)."}, + {"name":"Gromnie","type":"NPC","wcid":31953,"cell":"23B60125","place":"dungeon","id":6059,"desc":"Carenzi Rebel. In a dungeon (landblock 23B6)."}, + {"name":"Jedeth Eckhart","type":"NPC","wcid":31940,"cell":"23B60137","place":"dungeon","id":6060,"desc":"Carenzi Rebel Leader. In a dungeon (landblock 23B6)."}, + {"name":"Matthias Eckhart","type":"NPC","wcid":31954,"cell":"23B6011B","place":"dungeon","id":6061,"desc":"Carenzi Rebel. In a dungeon (landblock 23B6)."}, + {"name":"Robert Gutsmasher","type":"NPC","wcid":32110,"cell":"23B6013A","place":"dungeon","id":6062,"desc":"Man-At-Arms Thrasher. In a dungeon (landblock 23B6)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"23DA002C","place":"outdoor","ns":72.79,"ew":-73.38,"id":6063}, + {"name":"Archmage","type":"Vendor","wcid":30053,"cell":"23DA0102","place":"building","ns":72.81,"ew":-73.48,"id":6064}, + {"name":"Shopkeeper","type":"Vendor","wcid":30051,"cell":"23DA0109","place":"building","ns":72.83,"ew":-73.52,"id":6065}, + {"name":"Healer","type":"Vendor","wcid":30054,"cell":"23DA0103","place":"building","ns":72.81,"ew":-73.46,"id":6066}, + {"name":"Blacksmith","type":"Vendor","wcid":30052,"cell":"23DA0024","place":"outdoor","ns":72.76,"ew":-73.54,"id":6067}, + {"name":"Master Scrivener of Creature Magic","type":"Vendor","wcid":30023,"cell":"23DA0115","place":"building","ns":72.93,"ew":-73.59,"id":6068,"desc":"Master Archmage."}, + {"name":"Master Scrivener of Life Magic","type":"Vendor","wcid":30013,"cell":"23DA0115","place":"building","ns":72.92,"ew":-73.57,"id":6069,"desc":"Master Archmage."}, + {"name":"Master Scrivener of War Magic","type":"Vendor","wcid":30017,"cell":"23DA0115","place":"building","ns":72.9,"ew":-73.58,"id":6070,"desc":"Master Archmage."}, + {"name":"Master Scrivener of Item Magic","type":"Vendor","wcid":30027,"cell":"23DA0115","place":"building","ns":72.91,"ew":-73.57,"id":6071,"desc":"Master Archmage."}, + {"name":"Jiang Li","type":"NPC","wcid":31659,"cell":"23DA0113","place":"building","ns":72.69,"ew":-73.29,"id":6072,"desc":"Deathcap Defeater."}, + {"name":"Clemenza","type":"NPC","wcid":28717,"cell":"23DA002B","place":"outdoor","ns":72.75,"ew":-73.44,"id":6073,"desc":"Collector."}, + {"name":"Zisaha bint Jaidka the Mage","type":"Vendor","wcid":2314,"cell":"24810102","place":"building","ns":1.8,"ew":-72.8,"id":6074,"desc":"Master Archmage."}, + {"name":"Randall the Sponge","type":"Vendor","wcid":31863,"cell":"24860018","place":"outdoor","ns":5.96,"ew":-72.86,"id":6075,"desc":"Wandering Milkman."}, + {"name":"Tall Tree","type":"NPC","wcid":10931,"cell":"24C0001B","place":"outdoor","ns":51.89,"ew":-72.79,"id":6076}, + {"name":"Tall Tree","type":"NPC","wcid":10930,"cell":"24C0001A","place":"outdoor","ns":51.82,"ew":-72.79,"id":6077}, + {"name":"Eye-covered Tentacles of T'thuun","type":"NPC","wcid":38822,"cell":"24C00023","place":"outdoor","ns":51.87,"ew":-72.73,"id":6078}, + {"name":"Tall Tree","type":"NPC","wcid":10932,"cell":"24C00023","place":"outdoor","ns":51.91,"ew":-72.7,"id":6079}, + {"name":"Pool of Goo","type":"NPC","wcid":87822,"cell":"24C00150","place":"building","ns":51.91,"ew":-73.63,"id":6080}, + {"name":"Large Corrupted Mana Shard","type":"NPC","wcid":87825,"cell":"24C00174","place":"building","ns":51.62,"ew":-73.46,"id":6081}, + {"name":"Altar of T'thuun","type":"NPC","wcid":87827,"cell":"24C0011F","place":"underground","ns":51.75,"ew":-73.25,"id":6082}, + {"name":"Healer","type":"Vendor","wcid":1385,"cell":"25730105","place":"building","ns":-9.39,"ew":-71.86,"id":6083}, + {"name":"Peddler","type":"Vendor","wcid":1391,"cell":"25730105","place":"building","ns":-9.4,"ew":-71.87,"id":6084}, + {"name":"Exploration Marker","type":"NPC","wcid":39834,"cell":"25730026","place":"outdoor","ns":-9.35,"ew":-71.95,"id":6085}, + {"name":"Shopkeeper Yoshi Deshi","type":"Vendor","wcid":2317,"cell":"25810144","place":"building","ns":1.51,"ew":-71.69,"id":6086,"desc":"Shopkeeper."}, + {"name":"Mothdor the Bowyer","type":"Vendor","wcid":2316,"cell":"2581013A","place":"building","ns":1.5,"ew":-71.89,"id":6087,"desc":"Bowyer."}, + {"name":"Blacksmith Magarith","type":"Vendor","wcid":2315,"cell":"25810159","place":"building","ns":1.49,"ew":-71.97,"id":6088,"desc":"High Blacksmith."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"25810000","place":"outdoor","ns":1.73,"ew":-71.89,"id":6089,"desc":"Mage."}, + {"name":"Grand Master Scrivener of Life Magic","type":"Vendor","wcid":20220,"cell":"25810170","place":"building","ns":1.62,"ew":-71.88,"id":6090,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Creature Magic","type":"Vendor","wcid":20208,"cell":"25810170","place":"building","ns":1.62,"ew":-71.9,"id":6091,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of War Magic","type":"Vendor","wcid":20224,"cell":"25810175","place":"building","ns":1.61,"ew":-71.87,"id":6092,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Item Magic","type":"Vendor","wcid":20212,"cell":"2581016E","place":"building","ns":1.59,"ew":-71.89,"id":6093,"desc":"Master Archmage."}, + {"name":"Town Crier","type":"NPC","wcid":5772,"cell":"25810000","place":"outdoor","ns":1.58,"ew":-71.65,"id":6094,"desc":"Herald."}, + {"name":"Fort Tethana Sentry","type":"NPC","wcid":24493,"cell":"25810000","place":"outdoor","ns":1.58,"ew":-71.62,"id":6095,"desc":"Sentry."}, + {"name":"Small Creepy Statue","type":"NPC","wcid":25986,"cell":"25810000","place":"outdoor","ns":1.65,"ew":-71.67,"id":6096}, + {"name":"Xsao Lann","type":"NPC","wcid":31308,"cell":"2581003B","place":"outdoor","ns":1.45,"ew":-71.6,"id":6097,"desc":"Beast Tamer."}, + {"name":"Soldier","type":"NPC","wcid":31290,"cell":"25810034","place":"outdoor","ns":1.59,"ew":-71.7,"id":6098,"desc":"Fort Tethana Guardsman."}, + {"name":"Saqr","type":"NPC","wcid":31643,"cell":"2581002B","place":"outdoor","ns":1.55,"ew":-71.81,"id":6099,"desc":"Plate Armoredillo Punisher."}, + {"name":"Lieutenant Durgan","type":"NPC","wcid":32842,"cell":"25810149","place":"building","ns":1.54,"ew":-71.67,"id":6100,"desc":"Intelligence Chief."}, + {"name":"Aun Aemaua","type":"NPC","wcid":36923,"cell":"25810033","place":"outdoor","ns":1.53,"ew":-71.73,"id":6101,"desc":"Seeker of Dreams."}, + {"name":"Aun Tahuirea","type":"NPC","wcid":27280,"cell":"259D0000","place":"outdoor","ns":24.0,"ew":-72.0,"id":6102,"desc":"Elder Hunter."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"263E0000","place":"outdoor","ns":-51.73,"ew":-71.01,"id":6103}, + {"name":"Exploration Marker","type":"NPC","wcid":39804,"cell":"26830024","place":"outdoor","ns":3.2,"ew":-71.15,"id":6104}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"26EC003D","place":"outdoor","ns":87.3,"ew":-70.79,"id":6105}, + {"name":"Fratellodunon Ribellarista","type":"NPC","wcid":30439,"cell":"26EC0036","place":"outdoor","ns":87.42,"ew":-70.92,"id":6106,"desc":"Townsperson."}, + {"name":"Fratellone Ribellarista","type":"NPC","wcid":30438,"cell":"26EC002E","place":"outdoor","ns":87.38,"ew":-70.98,"id":6107,"desc":"Townsperson."}, + {"name":"Armorer","type":"Vendor","wcid":1372,"cell":"27180100","place":"underground","ns":-82.61,"ew":-70.13,"id":6108}, + {"name":"Roaming Bowyer","type":"Vendor","wcid":1378,"cell":"27180100","place":"underground","ns":-82.59,"ew":-70.16,"id":6109,"desc":"Bowyer."}, + {"name":"Exploration Marker","type":"NPC","wcid":39762,"cell":"277A0040","place":"outdoor","ns":-3.6,"ew":-69.96,"id":6110}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"27800000","place":"outdoor","ns":1.02,"ew":-70.67,"id":6111}, + {"name":"Aun Shimauri","type":"NPC","wcid":11410,"cell":"27B90100","place":"dungeon","id":6112,"desc":"In a dungeon (landblock 27B9)."}, + {"name":"Lila Fiori","type":"NPC","wcid":30981,"cell":"27EB0103","place":"building","ns":86.8,"ew":-70.3,"id":6113,"desc":"Flower Girl."}, + {"name":"Calvinne Sporgenzenni the Shopkeeper","type":"Vendor","wcid":30070,"cell":"27EC0132","place":"building","ns":87.31,"ew":-70.29,"id":6114,"desc":"Shopkeeper."}, + {"name":"Aidanan Ignarias the Blacksmith","type":"Vendor","wcid":30065,"cell":"27EC0013","place":"outdoor","ns":87.12,"ew":-70.52,"id":6115,"desc":"Blacksmith."}, + {"name":"Agonno Filleteppe the Tailor","type":"Vendor","wcid":30069,"cell":"27EC0121","place":"building","ns":87.1,"ew":-70.32,"id":6116,"desc":"Tailor."}, + {"name":"Bowyer Cecili Blocconda","type":"Vendor","wcid":30066,"cell":"27EC000A","place":"outdoor","ns":87.03,"ew":-70.64,"id":6117,"desc":"Bowyer."}, + {"name":"Scribe Copiara Parolinnis","type":"Vendor","wcid":30067,"cell":"27EC0109","place":"building","ns":87.42,"ew":-70.52,"id":6118,"desc":"Scribe."}, + {"name":"Benedetta du Lucrezza the Healer","type":"Vendor","wcid":30072,"cell":"27EC0103","place":"building","ns":87.42,"ew":-70.47,"id":6119,"desc":"Healer."}, + {"name":"Aldonti di Soludatis the Jeweler","type":"Vendor","wcid":30068,"cell":"27EC0118","place":"building","ns":87.11,"ew":-70.69,"id":6120,"desc":"Jeweler."}, + {"name":"Archmage Pazzescorios di Frodenci","type":"Vendor","wcid":30071,"cell":"27EC0111","place":"building","ns":87.38,"ew":-70.47,"id":6121,"desc":"Archmage."}, + {"name":"Barkeeper Mallia Quios","type":"Vendor","wcid":31295,"cell":"27EC0131","place":"building","ns":87.28,"ew":-70.28,"id":6122,"desc":"Barkeeper."}, + {"name":"Donatello Linante","type":"NPC","wcid":34259,"cell":"27EC0102","place":"building","ns":87.43,"ew":-70.47,"id":6123,"desc":"Augmentation Trainer."}, + {"name":"Scorus","type":"NPC","wcid":28703,"cell":"27EC011B","place":"building","ns":87.5,"ew":-70.32,"id":6124,"desc":"Fiun Mage."}, + {"name":"Chef Martam","type":"NPC","wcid":28836,"cell":"27EC012D","place":"building","ns":87.43,"ew":-70.58,"id":6125,"desc":"Master Chef."}, + {"name":"Huntsman of Silyun","type":"NPC","wcid":29468,"cell":"27EC0139","place":"building","ns":86.9,"ew":-70.0,"id":6126,"desc":"Chief Tracker."}, + {"name":"Rickard Dumalia","type":"NPC","wcid":28680,"cell":"27EC000E","place":"outdoor","ns":87.38,"ew":-70.62,"id":6127,"desc":"Augmentation Trainer."}, + {"name":"Marlan Nessunello","type":"NPC","wcid":30436,"cell":"27EC0003","place":"outdoor","ns":87.13,"ew":-70.66,"id":6128,"desc":"Townsperson."}, + {"name":"Hashina","type":"NPC","wcid":32628,"cell":"27EC0015","place":"outdoor","ns":87.28,"ew":-70.49,"id":6129,"desc":"Ambassador."}, + {"name":"Sacci Mijob","type":"NPC","wcid":30437,"cell":"27EC0015","place":"outdoor","ns":87.28,"ew":-70.53,"id":6130,"desc":"Philosopher."}, + {"name":"Raimonestes Risolu","type":"NPC","wcid":30434,"cell":"27EC0015","place":"outdoor","ns":87.26,"ew":-70.51,"id":6131}, + {"name":"Raphel Detante","type":"NPC","wcid":41523,"cell":"27EC0016","place":"outdoor","ns":87.41,"ew":-70.48,"id":6132,"desc":"Augmentation Trainer."}, + {"name":"Carlito Gallo","type":"NPC","wcid":41522,"cell":"27EC0016","place":"outdoor","ns":87.41,"ew":-70.48,"id":6133,"desc":"Augmentation Trainer."}, + {"name":"Lucari di Bellenesse","type":"NPC","wcid":32835,"cell":"27EC0016","place":"outdoor","ns":87.35,"ew":-70.48,"id":6134,"desc":"Knight of Bellenesse."}, + {"name":"Enzo Ilario","type":"NPC","wcid":31651,"cell":"27EC0016","place":"outdoor","ns":87.43,"ew":-70.55,"id":6135,"desc":"Arctic Mattekar Annihilator."}, + {"name":"Grand Mother","type":"NPC","wcid":28699,"cell":"27EC0016","place":"outdoor","ns":87.38,"ew":-70.49,"id":6136,"desc":"Mother of Silyun."}, + {"name":"Lord Tyragar","type":"NPC","wcid":43406,"cell":"27EC001E","place":"outdoor","ns":87.44,"ew":-70.45,"id":6137,"desc":"Seer of the Haebraen."}, + {"name":"Mendica Scarsolo","type":"NPC","wcid":30435,"cell":"27EC0025","place":"outdoor","ns":87.32,"ew":-70.34,"id":6138,"desc":"Beggar."}, + {"name":"Mancanza the Wanderer","type":"NPC","wcid":31728,"cell":"27EC001A","place":"outdoor","ns":87.04,"ew":-70.43,"id":6139,"desc":"Wanderer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"281A0000","place":"outdoor","ns":-80.88,"ew":-69.91,"id":6140}, + {"name":"Giant Snowman","type":"Vendor","wcid":5767,"cell":"287A0000","place":"outdoor","ns":-3.65,"ew":-69.72,"id":6141}, + {"name":"Exploration Marker","type":"NPC","wcid":39786,"cell":"29920025","place":"outdoor","ns":15.34,"ew":-68.7,"id":6142}, + {"name":"Exploration Marker","type":"NPC","wcid":39796,"cell":"2A170029","place":"outdoor","ns":-83.45,"ew":-67.78,"id":6143}, + {"name":"Pillar","type":"NPC","wcid":27963,"cell":"2A3F010A","place":"underground","ns":-51.44,"ew":-67.9,"id":6144}, + {"name":"Pillar","type":"NPC","wcid":27965,"cell":"2A3F010A","place":"underground","ns":-51.36,"ew":-67.9,"id":6145}, + {"name":"Pillar","type":"NPC","wcid":27964,"cell":"2A3F010A","place":"underground","ns":-51.4,"ew":-67.94,"id":6146}, + {"name":"Pillar","type":"NPC","wcid":27966,"cell":"2A3F010A","place":"underground","ns":-51.4,"ew":-67.86,"id":6147}, + {"name":"Beacon","type":"NPC","wcid":28702,"cell":"2AE3001E","place":"outdoor","ns":80.2,"ew":-68.0,"id":6148}, + {"name":"Iian di Alduressa","type":"NPC","wcid":32801,"cell":"2AEE003E","place":"outdoor","ns":88.96,"ew":-67.64,"id":6149,"desc":"Master Armorer."}, + {"name":"Guard","type":"NPC","wcid":29487,"cell":"2AEE002D","place":"outdoor","ns":88.86,"ew":-67.8,"id":6150,"desc":"Knight of Karlun."}, + {"name":"Sir Ginazio","type":"NPC","wcid":29488,"cell":"2AEE002C","place":"outdoor","ns":88.82,"ew":-67.82,"id":6151,"desc":"Eyes of Karlun."}, + {"name":"Guard","type":"NPC","wcid":29487,"cell":"2AEE0025","place":"outdoor","ns":88.87,"ew":-67.86,"id":6152,"desc":"Knight of Karlun."}, + {"name":"Exploration Marker","type":"NPC","wcid":39838,"cell":"2AEE003D","place":"outdoor","ns":88.86,"ew":-67.65,"id":6153}, + {"name":"Life Stone","type":"Lifestone","wcid":24572,"cell":"2B100000","place":"outdoor","ns":-88.86,"ew":-67.26,"id":6154}, + {"name":"Aun Xathurea the Leather Crafter","type":"NPC","wcid":24576,"cell":"2B110000","place":"outdoor","ns":-87.83,"ew":-67.2,"id":6155,"desc":"Trophy Collector."}, + {"name":"Tyokai Renjiro the Grocer","type":"Vendor","wcid":24592,"cell":"2B11012C","place":"building","ns":-87.8,"ew":-67.33,"id":6156,"desc":"Grocer."}, + {"name":"Odvik the Inn Keeper","type":"Vendor","wcid":24590,"cell":"2B110112","place":"building","ns":-87.73,"ew":-67.42,"id":6157,"desc":"Inn Keeper."}, + {"name":"Sentry","type":"NPC","wcid":24578,"cell":"2B110000","place":"outdoor","ns":-87.6,"ew":-66.79,"id":6158,"desc":"Candeth Keep Guard."}, + {"name":"Sentry","type":"NPC","wcid":24578,"cell":"2B110000","place":"outdoor","ns":-87.91,"ew":-67.1,"id":6159,"desc":"Candeth Keep Guard."}, + {"name":"Ulna bint-Fasha the Ivory Crafter","type":"NPC","wcid":24575,"cell":"2B110121","place":"building","ns":-87.67,"ew":-66.87,"id":6160,"desc":"Trophy Crafter."}, + {"name":"Yukara Miko the Collector","type":"NPC","wcid":24573,"cell":"2B110112","place":"building","ns":-87.67,"ew":-67.38,"id":6161,"desc":"Trophy Collector."}, + {"name":"Gate Guard","type":"NPC","wcid":24873,"cell":"2B110000","place":"outdoor","ns":-87.87,"ew":-66.81,"id":6162,"desc":"Candeth Keep Guard."}, + {"name":"Sentry","type":"NPC","wcid":24874,"cell":"2B110000","place":"outdoor","ns":-87.79,"ew":-66.77,"id":6163,"desc":"Candeth Keep Guard."}, + {"name":"Sentry","type":"NPC","wcid":24874,"cell":"2B110000","place":"outdoor","ns":-87.93,"ew":-66.92,"id":6164,"desc":"Candeth Keep Guard."}, + {"name":"Small Creepy Statue","type":"NPC","wcid":25985,"cell":"2B110000","place":"outdoor","ns":-87.78,"ew":-66.88,"id":6165}, + {"name":"Finn Skigg","type":"NPC","wcid":27948,"cell":"2B110127","place":"building","ns":-87.83,"ew":-67.32,"id":6166,"desc":"Adventurer."}, + {"name":"Grania the Bold","type":"NPC","wcid":31644,"cell":"2B11000F","place":"outdoor","ns":-87.65,"ew":-67.43,"id":6167,"desc":"Mottled Carenzi Mauler."}, + {"name":"Morathe","type":"NPC","wcid":43410,"cell":"2B11011C","place":"building","ns":-87.63,"ew":-66.86,"id":6168,"desc":"Augmentation Trainer."}, + {"name":"Town Crier","type":"NPC","wcid":5772,"cell":"2B11001E","place":"outdoor","ns":-87.8,"ew":-67.25,"id":6169,"desc":"Herald."}, + {"name":"Guard Alfric","type":"NPC","wcid":36535,"cell":"2B11000D","place":"outdoor","ns":-87.86,"ew":-67.36,"id":6170,"desc":"Soldier."}, + {"name":"Garbage Barrel","type":"NPC","wcid":34726,"cell":"2B110016","place":"outdoor","ns":-87.78,"ew":-67.35,"id":6171}, + {"name":"Ryukai Hiro","type":"NPC","wcid":36609,"cell":"2B110016","place":"outdoor","ns":-87.8,"ew":-67.31,"id":6172,"desc":"Royal Guard."}, + {"name":"Tunlok Weapons Master","type":"Vendor","wcid":24596,"cell":"2B120000","place":"outdoor","ns":-87.48,"ew":-67.16,"id":6173,"desc":"Weapons Master."}, + {"name":"Aun Amanaualuan the Elder Shaman","type":"Vendor","wcid":24594,"cell":"2B120000","place":"outdoor","ns":-87.53,"ew":-67.23,"id":6174,"desc":"Elder Shaman."}, + {"name":"Thimrin Woodsetter","type":"Vendor","wcid":24595,"cell":"2B120000","place":"outdoor","ns":-87.47,"ew":-67.23,"id":6175,"desc":"Tradesman."}, + {"name":"Pagrok the Stone Collector","type":"NPC","wcid":24574,"cell":"2B12011F","place":"building","ns":-87.24,"ew":-67.32,"id":6176,"desc":"Trophy Collector."}, + {"name":"Sentry","type":"NPC","wcid":24578,"cell":"2B120000","place":"outdoor","ns":-87.19,"ew":-67.2,"id":6177,"desc":"Candeth Keep Guard."}, + {"name":"Sentry","type":"NPC","wcid":24578,"cell":"2B120000","place":"outdoor","ns":-87.5,"ew":-67.51,"id":6178,"desc":"Candeth Keep Guard."}, + {"name":"Gilly","type":"Vendor","wcid":24588,"cell":"2B120000","place":"outdoor","ns":-87.23,"ew":-67.46,"id":6179,"desc":"Apprentice Mage."}, + {"name":"Agent Dravos","type":"NPC","wcid":24577,"cell":"2B120134","place":"building","ns":-87.32,"ew":-66.96,"id":6180,"desc":"Arcanum Agent."}, + {"name":"Grand Master Scrivener of War Magic","type":"Vendor","wcid":20224,"cell":"2B12012E","place":"building","ns":-87.27,"ew":-67.02,"id":6181,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Creature Magic","type":"Vendor","wcid":20208,"cell":"2B120131","place":"building","ns":-87.3,"ew":-66.97,"id":6182,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Item Magic","type":"Vendor","wcid":20212,"cell":"2B120131","place":"building","ns":-87.27,"ew":-66.97,"id":6183,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Life Magic","type":"Vendor","wcid":20220,"cell":"2B120000","place":"outdoor","ns":-87.3,"ew":-67.02,"id":6184,"desc":"Master Archmage."}, + {"name":"Aun Gunditealuan the Marksman","type":"Vendor","wcid":24591,"cell":"2B12012A","place":"building","ns":-87.52,"ew":-66.93,"id":6185,"desc":"Master Bowyer."}, + {"name":"Aun Oreilauri the Healer","type":"Vendor","wcid":24593,"cell":"2B12012A","place":"building","ns":-87.48,"ew":-66.88,"id":6186,"desc":"Healer."}, + {"name":"Rkos the Armorer","type":"Vendor","wcid":24589,"cell":"2B120102","place":"building","ns":-87.33,"ew":-67.31,"id":6187,"desc":"Armorer."}, + {"name":"Ry'zir al-Nabit","type":"Vendor","wcid":24597,"cell":"2B120102","place":"building","ns":-87.34,"ew":-67.29,"id":6188,"desc":"Weaponsmith."}, + {"name":"Dalius Kendmar","type":"NPC","wcid":25585,"cell":"2B12013C","place":"building","ns":-87.24,"ew":-67.45,"id":6189,"desc":"Warrior."}, + {"name":"Talira Dain","type":"NPC","wcid":25584,"cell":"2B12013C","place":"building","ns":-87.24,"ew":-67.47,"id":6190,"desc":"Archmage."}, + {"name":"Aun Autuorea","type":"NPC","wcid":27263,"cell":"2B12012A","place":"building","ns":-87.47,"ew":-66.93,"id":6191,"desc":"Magma Golem Hunter."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"2B120000","place":"outdoor","ns":-87.51,"ew":-67.09,"id":6192}, + {"name":"Virindi Delegate","type":"NPC","wcid":51347,"cell":"2B120039","place":"outdoor","ns":-87.46,"ew":-66.8,"id":6193}, + {"name":"Hinkel","type":"NPC","wcid":31842,"cell":"2B20011B","place":"building","ns":-76.03,"ew":-67.14,"id":6194,"desc":"Prisoner."}, + {"name":"Chef Jonus","type":"NPC","wcid":31841,"cell":"2B200121","place":"building","ns":-75.98,"ew":-67.21,"id":6195,"desc":"Prisoner."}, + {"name":"Larnia","type":"NPC","wcid":31840,"cell":"2B20014D","place":"building","ns":-75.96,"ew":-67.19,"id":6196,"desc":"Prisoner."}, + {"name":"Markis","type":"NPC","wcid":31839,"cell":"2B200140","place":"building","ns":-76.03,"ew":-67.22,"id":6197,"desc":"Prisoner."}, + {"name":"Exploration Marker","type":"NPC","wcid":39822,"cell":"2B20001C","place":"outdoor","ns":-76.04,"ew":-67.22,"id":6198}, + {"name":"Exploration Marker","type":"NPC","wcid":39774,"cell":"2B50002F","place":"outdoor","ns":-37.35,"ew":-67.05,"id":6199}, + {"name":"Brother Samir ibn Lomaq the Monk","type":"Vendor","wcid":11393,"cell":"2BB50103","place":"building","ns":42.9,"ew":-67.0,"id":6200,"desc":"Scribe."}, + {"name":"Greygor Stillwise the Armorer","type":"Vendor","wcid":11389,"cell":"2BB5010A","place":"building","ns":42.99,"ew":-66.9,"id":6201,"desc":"Armorer."}, + {"name":"Yen Loc Anh the Mage","type":"Vendor","wcid":11392,"cell":"2BB50100","place":"building","ns":42.9,"ew":-66.9,"id":6202,"desc":"Archmage."}, + {"name":"Misha the Jeweler","type":"Vendor","wcid":11391,"cell":"2BB50111","place":"building","ns":42.9,"ew":-66.8,"id":6203,"desc":"Jeweler."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"2BB50000","place":"outdoor","ns":42.89,"ew":-66.9,"id":6204}, + {"name":"Town Crier","type":"NPC","wcid":5777,"cell":"2BB50000","place":"outdoor","ns":43.19,"ew":-66.79,"id":6205,"desc":"Herald."}, + {"name":"Rico Cellini","type":"NPC","wcid":32108,"cell":"2BB50024","place":"outdoor","ns":43.18,"ew":-67.11,"id":6206,"desc":"Siraluun Slasher."}, + {"name":"Romeo Osemmi","type":"NPC","wcid":32067,"cell":"2BB50024","place":"outdoor","ns":43.21,"ew":-67.11,"id":6207,"desc":"Ferran Knight."}, + {"name":"Tamara du Cinghalle","type":"NPC","wcid":38820,"cell":"2BB50024","place":"outdoor","ns":43.17,"ew":-67.07,"id":6208,"desc":"Royal Hunter."}, + {"name":"Enrico di Bellenesse","type":"NPC","wcid":32084,"cell":"2BB50117","place":"building","ns":43.19,"ew":-67.1,"id":6209,"desc":"Ferran Commander."}, + {"name":"Exploration Marker","type":"NPC","wcid":39831,"cell":"2BB50031","place":"outdoor","ns":42.91,"ew":-66.92,"id":6210}, + {"name":"Hea Toneawa","type":"NPC","wcid":11371,"cell":"2BB60000","place":"outdoor","ns":43.71,"ew":-66.95,"id":6211}, + {"name":"Halaetan Gatestone","type":"NPC","wcid":80154,"cell":"2BF40100","place":"building","ns":93.8,"ew":-67.4,"id":6212}, + {"name":"Halaetan Node Golem","type":"NPC","wcid":80155,"cell":"2BF4000E","place":"outdoor","ns":93.81,"ew":-67.44,"id":6213,"desc":"Node Guardian."}, + {"name":"Aerlinthe Altar","type":"NPC","wcid":88431,"cell":"2BF50115","place":"dungeon","id":6214,"desc":"In a dungeon (landblock 2BF5)."}, + {"name":"A'mun Altar","type":"NPC","wcid":88432,"cell":"2BF50137","place":"dungeon","id":6215,"desc":"In a dungeon (landblock 2BF5)."}, + {"name":"Esper Altar","type":"NPC","wcid":88433,"cell":"2BF5011A","place":"dungeon","id":6216,"desc":"In a dungeon (landblock 2BF5)."}, + {"name":"Halaetan Altar","type":"NPC","wcid":88434,"cell":"2BF5013C","place":"dungeon","id":6217,"desc":"In a dungeon (landblock 2BF5)."}, + {"name":"Linvak Altar","type":"NPC","wcid":88435,"cell":"2BF50110","place":"dungeon","id":6218,"desc":"In a dungeon (landblock 2BF5)."}, + {"name":"Obsidian Altar","type":"NPC","wcid":88436,"cell":"2BF50141","place":"dungeon","id":6219,"desc":"In a dungeon (landblock 2BF5)."}, + {"name":"Rynthid Assessment Crystal","type":"NPC","wcid":52077,"cell":"2C31002D","place":"outdoor","ns":-62.3,"ew":-66.18,"id":6220}, + {"name":"Kasin ibn Sayrak the Barkeep","type":"Vendor","wcid":11390,"cell":"2CB50102","place":"building","ns":43.17,"ew":-66.62,"id":6221,"desc":"Barkeeper."}, + {"name":"Shalon ibn Mayar the Collector","type":"NPC","wcid":11346,"cell":"2CB50106","place":"building","ns":43.23,"ew":-66.62,"id":6222,"desc":"Trophy Collector."}, + {"name":"Mazur ibn Stounis","type":"NPC","wcid":10866,"cell":"2CB50000","place":"outdoor","ns":42.95,"ew":-66.72,"id":6223,"desc":"Blacksmith."}, + {"name":"Balarazo","type":"NPC","wcid":28258,"cell":"2CB50000","place":"outdoor","ns":42.91,"ew":-66.72,"id":6224,"desc":"Tailor."}, + {"name":"Eliza du Curena","type":"NPC","wcid":31957,"cell":"2CB50111","place":"building","ns":43.01,"ew":-66.73,"id":6225,"desc":"Entrepreneur."}, + {"name":"Virindi Delegate","type":"NPC","wcid":51208,"cell":"2CB50005","place":"outdoor","ns":43.27,"ew":-66.69,"id":6226}, + {"name":"Tito Brickicci","type":"NPC","wcid":32068,"cell":"2CB50005","place":"outdoor","ns":43.27,"ew":-66.74,"id":6227,"desc":"Ferran Knight."}, + {"name":"Valentina du Lurio","type":"NPC","wcid":32071,"cell":"2CB50003","place":"outdoor","ns":43.08,"ew":-66.73,"id":6228,"desc":"Lady of the Realm."}, + {"name":"Caprice du Bellenesse","type":"NPC","wcid":32070,"cell":"2CB50003","place":"outdoor","ns":43.08,"ew":-66.72,"id":6229,"desc":"Lady of the Realm."}, + {"name":"Garaena the Emissary","type":"NPC","wcid":7402,"cell":"2D110000","place":"outdoor","ns":-87.64,"ew":-65.61,"id":6230}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":43844,"cell":"2D110100","place":"underground","ns":-87.61,"ew":-65.58,"id":6231}, + {"name":"Exploration Marker","type":"NPC","wcid":39833,"cell":"2D15002C","place":"outdoor","ns":-84.8,"ew":-65.4,"id":6232}, + {"name":"Rynthid Crystal Access Device","type":"NPC","wcid":51604,"cell":"2D300025","place":"outdoor","ns":-63.1,"ew":-65.49,"id":6233}, + {"name":"Toberik","type":"NPC","wcid":28473,"cell":"2D5A0130","place":"underground","ns":-29.46,"ew":-65.45,"id":6234}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"2D5E0000","place":"outdoor","ns":-26.23,"ew":-65.57,"id":6235}, + {"name":"Crystal","type":"NPC","wcid":40092,"cell":"2D6B02D6","place":"underground","ns":-15.63,"ew":-65.29,"id":6236}, + {"name":"Crystal","type":"NPC","wcid":40095,"cell":"2D6B0215","place":"underground","ns":-15.27,"ew":-65.38,"id":6237}, + {"name":"Crystal","type":"NPC","wcid":40094,"cell":"2D6B0149","place":"underground","ns":-15.61,"ew":-65.47,"id":6238}, + {"name":"Crystal","type":"NPC","wcid":40096,"cell":"2D6B0104","place":"underground","ns":-15.65,"ew":-65.38,"id":6239}, + {"name":"Crystal","type":"NPC","wcid":40093,"cell":"2D6B019D","place":"underground","ns":-16.05,"ew":-65.35,"id":6240}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"2DAF000E","place":"outdoor","ns":38.64,"ew":-65.76,"id":6241}, + {"name":"Flame Guardian","type":"NPC","wcid":31972,"cell":"2DAF000E","place":"outdoor","ns":38.56,"ew":-65.76,"id":6242,"desc":"Warden of the Deep."}, + {"name":"Shopkeeper","type":"Vendor","wcid":31224,"cell":"2DDA001D","place":"outdoor","ns":72.89,"ew":-65.57,"id":6243,"desc":"Traveling Salesman."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"2E110000","place":"outdoor","ns":-88.31,"ew":-64.5,"id":6244}, + {"name":"West Gate Stone","type":"NPC","wcid":37041,"cell":"2E2F0023","place":"outdoor","ns":-64.1,"ew":-64.7,"id":6245}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"2E430000","place":"outdoor","ns":-48.0,"ew":-65.12,"id":6246}, + {"name":"Lever","type":"NPC","wcid":40779,"cell":"2E6C018D","place":"underground","ns":-15.15,"ew":-65.89,"id":6247}, + {"name":"Lever","type":"NPC","wcid":40782,"cell":"2E6C02F1","place":"underground","ns":-15.04,"ew":-66.02,"id":6248}, + {"name":"Lever","type":"NPC","wcid":40785,"cell":"2E6C0301","place":"underground","ns":-15.25,"ew":-66.02,"id":6249}, + {"name":"Shade of Ja'qu","type":"NPC","wcid":40799,"cell":"2E6C016F","place":"underground","ns":-15.16,"ew":-66.02,"id":6250,"desc":"Tormented Soul."}, + {"name":"Crystal","type":"NPC","wcid":40123,"cell":"2E6C0302","place":"underground","ns":-15.33,"ew":-66.02,"id":6251}, + {"name":"Crystal","type":"NPC","wcid":40120,"cell":"2E6C016F","place":"underground","ns":-15.14,"ew":-66.02,"id":6252}, + {"name":"Crystal","type":"NPC","wcid":40122,"cell":"2E6C0216","place":"underground","ns":-14.64,"ew":-66.06,"id":6253}, + {"name":"Crystal","type":"NPC","wcid":40121,"cell":"2E6C0135","place":"underground","ns":-15.01,"ew":-66.28,"id":6254}, + {"name":"Crystal","type":"NPC","wcid":40091,"cell":"2E6C0380","place":"underground","ns":-15.16,"ew":-65.21,"id":6255}, + {"name":"Lever","type":"NPC","wcid":40785,"cell":"2E6C02D9","place":"underground","ns":-15.19,"ew":-66.1,"id":6256}, + {"name":"Lever","type":"NPC","wcid":40785,"cell":"2E6C02FA","place":"underground","ns":-15.19,"ew":-66.02,"id":6257}, + {"name":"Lever","type":"NPC","wcid":40785,"cell":"2E6C031B","place":"underground","ns":-15.19,"ew":-65.93,"id":6258}, + {"name":"Lever","type":"NPC","wcid":40782,"cell":"2E6C02F3","place":"underground","ns":-15.1,"ew":-66.02,"id":6259}, + {"name":"Lever","type":"NPC","wcid":40782,"cell":"2E6C02D3","place":"underground","ns":-15.1,"ew":-66.1,"id":6260}, + {"name":"Lever","type":"NPC","wcid":40782,"cell":"2E6C0315","place":"underground","ns":-15.1,"ew":-65.93,"id":6261}, + {"name":"Exploration Marker","type":"NPC","wcid":39787,"cell":"2F2F002C","place":"outdoor","ns":-64.04,"ew":-63.82,"id":6262}, + {"name":"Exploration Marker","type":"NPC","wcid":39840,"cell":"2F2F002B","place":"outdoor","ns":-64.15,"ew":-63.85,"id":6263}, + {"name":"North Gate Stone","type":"NPC","wcid":37033,"cell":"2F30002C","place":"outdoor","ns":-63.2,"ew":-63.8,"id":6264}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"2F840000","place":"outdoor","ns":4.24,"ew":-63.88,"id":6265}, + {"name":"East Gate Stone","type":"NPC","wcid":37027,"cell":"302F0033","place":"outdoor","ns":-64.1,"ew":-62.9,"id":6266}, + {"name":"Lohrn","type":"NPC","wcid":52281,"cell":"30320014","place":"outdoor","ns":-61.64,"ew":-63.29,"id":6267,"desc":"Virindi Steward."}, + {"name":"Morgethais","type":"NPC","wcid":51987,"cell":"30320014","place":"outdoor","ns":-61.63,"ew":-63.34,"id":6268,"desc":"Royal Knight."}, + {"name":"Aun Ol'tra","type":"NPC","wcid":52015,"cell":"30320014","place":"outdoor","ns":-61.56,"ew":-63.34,"id":6269,"desc":"Tribal Advisor."}, + {"name":"Sylvanus","type":"NPC","wcid":51863,"cell":"30320014","place":"outdoor","ns":-61.56,"ew":-63.3,"id":6270,"desc":"Virindi Steward."}, + {"name":"Rhys","type":"NPC","wcid":51866,"cell":"30320014","place":"outdoor","ns":-61.64,"ew":-63.32,"id":6271,"desc":"Virindi Steward."}, + {"name":"Wido","type":"NPC","wcid":51865,"cell":"30320014","place":"outdoor","ns":-61.64,"ew":-63.3,"id":6272,"desc":"Virindi Steward."}, + {"name":"Ranulf","type":"NPC","wcid":51864,"cell":"30320014","place":"outdoor","ns":-61.56,"ew":-63.32,"id":6273,"desc":"Virindi Steward."}, + {"name":"Marcus","type":"NPC","wcid":51862,"cell":"30320014","place":"outdoor","ns":-61.56,"ew":-63.29,"id":6274,"desc":"Virindi Steward."}, + {"name":"Ilte Krongal","type":"NPC","wcid":51654,"cell":"30320014","place":"outdoor","ns":-61.6,"ew":-63.29,"id":6275,"desc":"Silver Scope Explorer."}, + {"name":"Hernd","type":"NPC","wcid":51861,"cell":"30320014","place":"outdoor","ns":-61.64,"ew":-63.27,"id":6276,"desc":"Big Game Hunter."}, + {"name":"Tillahan","type":"NPC","wcid":51860,"cell":"30320014","place":"outdoor","ns":-61.57,"ew":-63.27,"id":6277,"desc":"Wisp Hunter."}, + {"name":"Rinne Gorber","type":"NPC","wcid":51789,"cell":"30320014","place":"outdoor","ns":-61.59,"ew":-63.33,"id":6278,"desc":"Paranormal Scholar."}, + {"name":"Geilla","type":"NPC","wcid":51681,"cell":"30320014","place":"outdoor","ns":-61.62,"ew":-63.32,"id":6279}, + {"name":"Virindi Delegate","type":"NPC","wcid":51592,"cell":"3032001C","place":"outdoor","ns":-61.58,"ew":-63.25,"id":6280}, + {"name":"Vision of Horror","type":"NPC","wcid":51614,"cell":"3032001C","place":"outdoor","ns":-61.63,"ew":-63.25,"id":6281,"desc":"First General."}, + {"name":"Raksaa","type":"NPC","wcid":51923,"cell":"3032001C","place":"outdoor","ns":-61.63,"ew":-63.23,"id":6282,"desc":"Linvak Tukal Envoy."}, + {"name":"The Bringer of Light","type":"NPC","wcid":51888,"cell":"3032001C","place":"outdoor","ns":-61.59,"ew":-63.24,"id":6283,"desc":"Purifier of Corruption."}, + {"name":"Shopkeeper","type":"Vendor","wcid":31224,"cell":"30DA0027","place":"outdoor","ns":73.11,"ew":-63.06,"id":6284,"desc":"Traveling Salesman."}, + {"name":"Obsidian Gatestone","type":"NPC","wcid":39313,"cell":"312A0100","place":"building","ns":-68.0,"ew":-62.2,"id":6285}, + {"name":"Obsidian Node Golem","type":"NPC","wcid":38207,"cell":"312A002C","place":"outdoor","ns":-68.05,"ew":-62.22,"id":6286,"desc":"Node Guardian."}, + {"name":"Exploration Marker","type":"NPC","wcid":39821,"cell":"313D000D","place":"outdoor","ns":-52.66,"ew":-62.63,"id":6287}, + {"name":"Varetha","type":"NPC","wcid":33746,"cell":"31470018","place":"outdoor","ns":-44.35,"ew":-62.45,"id":6288,"desc":"Emissary of Isin Dule."}, + {"name":"Adrenkus","type":"NPC","wcid":47172,"cell":"31500480","place":"dungeon","id":6289,"desc":"Researcher. In a dungeon (landblock 3150)."}, + {"name":"Bulb of Harvests","type":"NPC","wcid":88219,"cell":"3150033A","place":"dungeon","id":6290,"desc":"In a dungeon (landblock 3150)."}, + {"name":"Sanctum Guardian Spirit","type":"NPC","wcid":88215,"cell":"3150041C","place":"dungeon","id":6291,"desc":"Guardian of the Light Falatacot. In a dungeon (landblock 3150)."}, + {"name":"Crystal","type":"NPC","wcid":40109,"cell":"316A002E","place":"outdoor","ns":-16.64,"ew":-62.17,"id":6292}, + {"name":"Bound Wisp","type":"NPC","wcid":40098,"cell":"316A0013","place":"outdoor","ns":-16.92,"ew":-62.52,"id":6293}, + {"name":"Resonant Portal","type":"NPC","wcid":40104,"cell":"316D002A","place":"outdoor","ns":-14.56,"ew":-62.2,"id":6294}, + {"name":"Tokashi Ando","type":"NPC","wcid":40099,"cell":"316D003A","place":"outdoor","ns":-14.58,"ew":-62.03,"id":6295,"desc":"Researcher."}, + {"name":"Jyotsana","type":"NPC","wcid":40097,"cell":"316D003A","place":"outdoor","ns":-14.56,"ew":-62.03,"id":6296,"desc":"Explorer."}, + {"name":"Oorjit","type":"NPC","wcid":40103,"cell":"316D003A","place":"outdoor","ns":-14.56,"ew":-62.01,"id":6297,"desc":"Wisp Hunter."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":30026,"cell":"31D60108","place":"building","ns":69.84,"ew":-62.34,"id":6298,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":30020,"cell":"31D60108","place":"building","ns":69.84,"ew":-62.26,"id":6299,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":30030,"cell":"31D60108","place":"building","ns":69.82,"ew":-62.26,"id":6300,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":30016,"cell":"31D60108","place":"building","ns":69.84,"ew":-62.3,"id":6301,"desc":"Master Archmage."}, + {"name":"Piersanti Linante","type":"NPC","wcid":28679,"cell":"31D60102","place":"building","ns":69.82,"ew":-62.28,"id":6302,"desc":"Augmentation Trainer."}, + {"name":"Lieutenant Dialossa","type":"NPC","wcid":32843,"cell":"31D60109","place":"building","ns":69.76,"ew":-62.27,"id":6303,"desc":"Spymaster."}, + {"name":"Melaverre","type":"NPC","wcid":33013,"cell":"31D60128","place":"building","ns":69.67,"ew":-62.48,"id":6304,"desc":"Experimental Thaumaturgist."}, + {"name":"Garmasi","type":"NPC","wcid":32693,"cell":"31D6012D","place":"building","ns":69.76,"ew":-62.54,"id":6305,"desc":"Royal Agent."}, + {"name":"Gallatria du Ressetta","type":"NPC","wcid":31431,"cell":"31D60134","place":"building","ns":69.85,"ew":-62.53,"id":6306,"desc":"Royal Scholar."}, + {"name":"Grand Knight","type":"NPC","wcid":28700,"cell":"31D60134","place":"building","ns":69.93,"ew":-62.45,"id":6307,"desc":"Protector of Sanamar."}, + {"name":"Skeleton","type":"NPC","wcid":40529,"cell":"31D60109","place":"building","ns":69.76,"ew":-62.28,"id":6308}, + {"name":"Lieutenant Dialossa","type":"NPC","wcid":81090,"cell":"31D60109","place":"building","ns":69.78,"ew":-62.29,"id":6309,"desc":"Activator."}, + {"name":"Town Crier","type":"NPC","wcid":30063,"cell":"31D70011","place":"outdoor","ns":70.13,"ew":-62.45,"id":6310,"desc":"Herald of Sanamar."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":30025,"cell":"32D90121","place":"building","ns":72.23,"ew":-61.43,"id":6311,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":30029,"cell":"32D90123","place":"building","ns":72.18,"ew":-61.43,"id":6312,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":30019,"cell":"32D90120","place":"building","ns":72.21,"ew":-61.42,"id":6313,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":30015,"cell":"32D9012F","place":"building","ns":72.23,"ew":-61.38,"id":6314,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":30009,"cell":"32D9010A","place":"building","ns":72.23,"ew":-61.27,"id":6315,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":30021,"cell":"32D90119","place":"building","ns":72.18,"ew":-61.27,"id":6316,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":30022,"cell":"32D90036","place":"outdoor","ns":72.19,"ew":-61.29,"id":6317,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":30011,"cell":"32D9010D","place":"building","ns":72.22,"ew":-61.31,"id":6318,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":30012,"cell":"32D9010B","place":"building","ns":72.23,"ew":-61.27,"id":6319,"desc":"Master Archmage."}, + {"name":"Scribe Benno di Hergeaux","type":"Vendor","wcid":30032,"cell":"32D90139","place":"building","ns":71.8,"ew":-61.43,"id":6320,"desc":"Scribe."}, + {"name":"Archmage Luchessa du Lamiere","type":"Vendor","wcid":30038,"cell":"32D9013E","place":"building","ns":71.8,"ew":-61.4,"id":6321,"desc":"Archmage."}, + {"name":"Healer Deme du Laur","type":"Vendor","wcid":30039,"cell":"32D90131","place":"building","ns":71.9,"ew":-61.31,"id":6322,"desc":"Healer."}, + {"name":"Blacksmith Karlus Loc","type":"Vendor","wcid":30040,"cell":"32D90032","place":"outdoor","ns":71.78,"ew":-61.3,"id":6323,"desc":"Blacksmith."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":30010,"cell":"32D9010A","place":"building","ns":72.23,"ew":-61.29,"id":6324,"desc":"Master Archmage."}, + {"name":"Scrivener of Void Magic","type":"Vendor","wcid":43354,"cell":"32D9010A","place":"building","ns":72.22,"ew":-61.29,"id":6325,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"32D90120","place":"building","ns":72.22,"ew":-61.43,"id":6326,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"32D90120","place":"building","ns":72.19,"ew":-61.42,"id":6327,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"32D9002E","place":"outdoor","ns":72.22,"ew":-61.39,"id":6328,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"32D9002E","place":"outdoor","ns":72.21,"ew":-61.36,"id":6329,"desc":"Master Archmage."}, + {"name":"Keminub","type":"Vendor","wcid":49519,"cell":"32D9013E","place":"building","ns":71.79,"ew":-61.41,"id":6330,"desc":"Geomancer."}, + {"name":"Town Crier","type":"NPC","wcid":30063,"cell":"32D9003B","place":"outdoor","ns":71.88,"ew":-61.18,"id":6331,"desc":"Herald of Sanamar."}, + {"name":"Trilaine di Ricard","type":"NPC","wcid":34145,"cell":"32D9003D","place":"outdoor","ns":72.07,"ew":-61.22,"id":6332,"desc":"Mask Maker."}, + {"name":"Luressi di Maki","type":"NPC","wcid":30073,"cell":"32D90100","place":"building","ns":72.01,"ew":-61.41,"id":6333,"desc":"Viamontian Guard."}, + {"name":"Alessandro Mardor","type":"NPC","wcid":31655,"cell":"32D9003C","place":"outdoor","ns":72.03,"ew":-61.18,"id":6334,"desc":"Polardillo Pummeler."}, + {"name":"Turien Di Furza","type":"NPC","wcid":32834,"cell":"32D9003A","place":"outdoor","ns":71.84,"ew":-61.17,"id":6335,"desc":"Royal Agent."}, + {"name":"Paissen du Kim","type":"NPC","wcid":30267,"cell":"32D90032","place":"outdoor","ns":71.84,"ew":-61.29,"id":6336,"desc":"Townsperson."}, + {"name":"Stuven di Bonachien","type":"NPC","wcid":30266,"cell":"32D9002D","place":"outdoor","ns":72.11,"ew":-61.42,"id":6337,"desc":"Townsperson."}, + {"name":"Giordonni","type":"NPC","wcid":32820,"cell":"32D9002D","place":"outdoor","ns":72.11,"ew":-61.36,"id":6338,"desc":"Plumber."}, + {"name":"Shopkeeper","type":"Vendor","wcid":31224,"cell":"32DB001C","place":"outdoor","ns":73.59,"ew":-61.58,"id":6339,"desc":"Traveling Salesman."}, + {"name":"Archmage","type":"Vendor","wcid":1371,"cell":"33110000","place":"outdoor","ns":-88.13,"ew":-60.9,"id":6340}, + {"name":"Merchant","type":"Vendor","wcid":1388,"cell":"33110000","place":"outdoor","ns":-88.13,"ew":-60.92,"id":6341}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"33110000","place":"outdoor","ns":-88.29,"ew":-60.88,"id":6342}, + {"name":"Exploration Marker","type":"NPC","wcid":39812,"cell":"3365001B","place":"outdoor","ns":-20.95,"ew":-60.85,"id":6343}, + {"name":"Seneschal Dalmour","type":"NPC","wcid":29051,"cell":"33D80100","place":"dungeon","id":6344,"desc":"King's Seneschal. In a dungeon (landblock 33D8)."}, + {"name":"Fletcher Mikael di Suinn","type":"Vendor","wcid":30031,"cell":"33D90004","place":"outdoor","ns":71.97,"ew":-61.07,"id":6345,"desc":"Fletcher."}, + {"name":"Barkeeper Jean Vaden","type":"Vendor","wcid":30035,"cell":"33D90109","place":"building","ns":71.79,"ew":-60.77,"id":6346,"desc":"Barkeeper."}, + {"name":"Grocer Jaffres Dini","type":"Vendor","wcid":30036,"cell":"33D90101","place":"building","ns":71.81,"ew":-61.02,"id":6347,"desc":"Grocer."}, + {"name":"Shopkeeper Tod Burgni","type":"Vendor","wcid":30037,"cell":"33D90101","place":"building","ns":71.81,"ew":-61.03,"id":6348,"desc":"Shopkeeper."}, + {"name":"Tailor Monique du Bressa","type":"Vendor","wcid":30034,"cell":"33D90106","place":"building","ns":71.79,"ew":-61.1,"id":6349,"desc":"Tailor."}, + {"name":"Jeweler Susana Arlean","type":"Vendor","wcid":30033,"cell":"33D90106","place":"building","ns":71.8,"ew":-61.09,"id":6350,"desc":"Jeweler."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"33D90008","place":"outdoor","ns":72.4,"ew":-61.1,"id":6351}, + {"name":"Ciriaco","type":"Vendor","wcid":42431,"cell":"33D90106","place":"building","ns":71.79,"ew":-61.09,"id":6352,"desc":"Master Tailor."}, + {"name":"Contract Broker","type":"Vendor","wcid":44188,"cell":"33D9001A","place":"outdoor","ns":71.81,"ew":-60.78,"id":6353,"desc":"Armorer."}, + {"name":"Malrin","type":"NPC","wcid":36231,"cell":"33D9010B","place":"building","ns":71.79,"ew":-60.77,"id":6354,"desc":"Reef Builder."}, + {"name":"Bertrand","type":"NPC","wcid":42723,"cell":"33D90106","place":"building","ns":71.8,"ew":-61.1,"id":6355,"desc":"Barber."}, + {"name":"Tailor's Apprentice","type":"NPC","wcid":42739,"cell":"33D90106","place":"building","ns":71.79,"ew":-61.1,"id":6356}, + {"name":"Fiorella","type":"NPC","wcid":44894,"cell":"33D90109","place":"building","ns":71.79,"ew":-60.78,"id":6357,"desc":"Bartender Greeter."}, + {"name":"Pathwarden Thierra Molanti","type":"NPC","wcid":33615,"cell":"33D90014","place":"outdoor","ns":72.03,"ew":-60.93,"id":6358,"desc":"Pathwarden Greeter."}, + {"name":"Rufina","type":"NPC","wcid":44890,"cell":"33D90008","place":"outdoor","ns":72.4,"ew":-61.11,"id":6359,"desc":"Lifestone Greeter."}, + {"name":"Rand","type":"NPC","wcid":28706,"cell":"33D9010A","place":"building","ns":71.76,"ew":-60.77,"id":6360,"desc":"Brewmaster."}, + {"name":"Anton Sillezi","type":"NPC","wcid":28705,"cell":"33D9001B","place":"outdoor","ns":71.88,"ew":-60.8,"id":6361,"desc":"Trade Merchant."}, + {"name":"Giancarlo De Luca","type":"NPC","wcid":44209,"cell":"33D9001A","place":"outdoor","ns":71.81,"ew":-60.77,"id":6362}, + {"name":"Arcanum Refurbisher","type":"NPC","wcid":32085,"cell":"33D90027","place":"outdoor","ns":72.34,"ew":-60.66,"id":6363,"desc":"Renovation Specialist."}, + {"name":"Portal Guardian","type":"NPC","wcid":29094,"cell":"33D90015","place":"outdoor","ns":72.05,"ew":-60.89,"id":6364,"desc":"Knight of Sanamar."}, + {"name":"Collector","type":"NPC","wcid":28707,"cell":"33D9000C","place":"outdoor","ns":71.97,"ew":-61.01,"id":6365,"desc":"Trophy Collector."}, + {"name":"Elena Du Furza","type":"NPC","wcid":28701,"cell":"33D9000A","place":"outdoor","ns":71.76,"ew":-60.96,"id":6366,"desc":"Keeper of the Beacon."}, + {"name":"Town Crier","type":"NPC","wcid":30064,"cell":"33D90008","place":"outdoor","ns":72.43,"ew":-61.07,"id":6367,"desc":"Herald of Sanamar."}, + {"name":"Lorca Sammel","type":"NPC","wcid":28704,"cell":"33D90013","place":"outdoor","ns":71.93,"ew":-60.88,"id":6368,"desc":"Historian."}, + {"name":"Fabian Strinjelli","type":"NPC","wcid":30265,"cell":"33D90004","place":"outdoor","ns":71.98,"ew":-61.11,"id":6369,"desc":"Townsperson."}, + {"name":"Monster Fight Bookie","type":"NPC","wcid":38995,"cell":"33DA0024","place":"outdoor","ns":72.84,"ew":-60.73,"id":6370,"desc":"Cashier."}, + {"name":"Frozen Gearknight","type":"NPC","wcid":87261,"cell":"33F40102","place":"dungeon","id":6371,"desc":"In a dungeon (landblock 33F4)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39814,"cell":"34F7001F","place":"outdoor","ns":96.3,"ew":-59.99,"id":6372}, + {"name":"Alatar Locke","type":"NPC","wcid":20203,"cell":"35500100","place":"building","ns":-37.7,"ew":-59.0,"id":6373,"desc":"Cartographer for the Explorer Society."}, + {"name":"Guardian","type":"NPC","wcid":29217,"cell":"356F010A","place":"underground","ns":-12.83,"ew":-58.9,"id":6374}, + {"name":"Exploration Marker","type":"NPC","wcid":39754,"cell":"356F0034","place":"outdoor","ns":-12.8,"ew":-58.9,"id":6375}, + {"name":"Shrine of the Blood Pearl","type":"NPC","wcid":38263,"cell":"370A002D","place":"outdoor","ns":-93.5,"ew":-57.4,"id":6376}, + {"name":"Faladha the Emissary","type":"NPC","wcid":7403,"cell":"376A0000","place":"outdoor","ns":-16.96,"ew":-57.34,"id":6377}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":43845,"cell":"376A012F","place":"building","ns":-17.05,"ew":-57.4,"id":6378}, + {"name":"Penguin Nest","type":"NPC","wcid":71880,"cell":"37E40102","place":"dungeon","id":6379,"desc":"In a dungeon (landblock 37E4)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"38680000","place":"outdoor","ns":-18.06,"ew":-56.86,"id":6380}, + {"name":"Merchant","type":"Vendor","wcid":1388,"cell":"38680000","place":"outdoor","ns":-18.17,"ew":-56.98,"id":6381}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"388C0000","place":"outdoor","ns":10.22,"ew":-56.38,"id":6382}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"38F7001B","place":"outdoor","ns":95.87,"ew":-56.8,"id":6383}, + {"name":"Fiun Healer","type":"Vendor","wcid":30047,"cell":"38F70021","place":"outdoor","ns":95.72,"ew":-56.72,"id":6384,"desc":"Healer."}, + {"name":"Fiun Archmage","type":"Vendor","wcid":30049,"cell":"38F70100","place":"building","ns":95.69,"ew":-56.72,"id":6385,"desc":"Archmage."}, + {"name":"Fiun Blacksmith","type":"Vendor","wcid":30048,"cell":"38F70103","place":"building","ns":95.69,"ew":-56.89,"id":6386,"desc":"Blacksmith."}, + {"name":"Fiun Shopkeeper","type":"Vendor","wcid":30050,"cell":"38F70103","place":"building","ns":95.7,"ew":-56.91,"id":6387,"desc":"Shopkeeper."}, + {"name":"Fiun Layeel","type":"NPC","wcid":32595,"cell":"38F7001B","place":"outdoor","ns":95.87,"ew":-56.76,"id":6388,"desc":"Speaker."}, + {"name":"Senior Sage Shibak","type":"NPC","wcid":28819,"cell":"38F70019","place":"outdoor","ns":95.7,"ew":-56.84,"id":6389}, + {"name":"Fiun Rehlyun","type":"NPC","wcid":28698,"cell":"38F7000B","place":"outdoor","ns":95.86,"ew":-57.0,"id":6390,"desc":"Augmentation Trainer."}, + {"name":"Fiun Vasherr","type":"NPC","wcid":28696,"cell":"38F70001","place":"outdoor","ns":95.73,"ew":-57.11,"id":6391,"desc":"Augmentation Trainer."}, + {"name":"Fiun Bayaas","type":"NPC","wcid":28694,"cell":"38F70001","place":"outdoor","ns":95.71,"ew":-57.11,"id":6392,"desc":"Augmentation Trainer."}, + {"name":"Gianni Vernice","type":"NPC","wcid":30385,"cell":"38F70022","place":"outdoor","ns":95.76,"ew":-56.69,"id":6393,"desc":"Explorer."}, + {"name":"Fiun Riish","type":"NPC","wcid":28695,"cell":"38F70001","place":"outdoor","ns":95.73,"ew":-57.09,"id":6394,"desc":"Augmentation Trainer."}, + {"name":"Fiun Luunere","type":"NPC","wcid":28692,"cell":"38F70001","place":"outdoor","ns":95.71,"ew":-57.06,"id":6395,"desc":"Augmentation Trainer."}, + {"name":"Fiun Noress","type":"NPC","wcid":28697,"cell":"38F70001","place":"outdoor","ns":95.7,"ew":-57.07,"id":6396,"desc":"Augmentation Trainer."}, + {"name":"Fiun Ruun","type":"NPC","wcid":28693,"cell":"38F70001","place":"outdoor","ns":95.69,"ew":-57.09,"id":6397,"desc":"Augmentation Trainer."}, + {"name":"Coral Hollow","type":"NPC","wcid":38347,"cell":"39110025","place":"outdoor","ns":-87.91,"ew":-55.89,"id":6398}, + {"name":"Coral Hollow","type":"NPC","wcid":38346,"cell":"39110025","place":"outdoor","ns":-87.9,"ew":-55.89,"id":6399}, + {"name":"Coral Hollow","type":"NPC","wcid":38345,"cell":"39110025","place":"outdoor","ns":-87.89,"ew":-55.89,"id":6400}, + {"name":"Statue","type":"NPC","wcid":38340,"cell":"39110025","place":"outdoor","ns":-87.9,"ew":-55.9,"id":6401}, + {"name":"Mariabella Varanese","type":"NPC","wcid":31642,"cell":"39F60100","place":"building","ns":95.59,"ew":-56.29,"id":6402,"desc":"Polar Ursuin Pounder."}, + {"name":"Shrine of the Sacred Deep Water","type":"NPC","wcid":38260,"cell":"3A0B0003","place":"outdoor","ns":-92.9,"ew":-55.5,"id":6403}, + {"name":"Exploration Marker","type":"NPC","wcid":39841,"cell":"3A11012B","place":"underground","ns":-87.86,"ew":-55.19,"id":6404}, + {"name":"Old Lascare","type":"NPC","wcid":29505,"cell":"3AED000B","place":"outdoor","ns":87.89,"ew":-55.42,"id":6405,"desc":"Livestock Handler."}, + {"name":"Shrine of the Spear of Baalforth, the Slayer","type":"NPC","wcid":38261,"cell":"3B0A0025","place":"outdoor","ns":-93.5,"ew":-54.3,"id":6406}, + {"name":"Shrine of the Coral's Heart","type":"NPC","wcid":38264,"cell":"3B0B0036","place":"outdoor","ns":-92.6,"ew":-54.1,"id":6407}, + {"name":"Coral Hollow","type":"NPC","wcid":38344,"cell":"3B110015","place":"outdoor","ns":-87.89,"ew":-54.51,"id":6408}, + {"name":"Coral Hollow","type":"NPC","wcid":38343,"cell":"3B110015","place":"outdoor","ns":-87.9,"ew":-54.51,"id":6409}, + {"name":"Coral Hollow","type":"NPC","wcid":38342,"cell":"3B110015","place":"outdoor","ns":-87.91,"ew":-54.51,"id":6410}, + {"name":"Statue","type":"NPC","wcid":38339,"cell":"3B110015","place":"outdoor","ns":-87.9,"ew":-54.5,"id":6411}, + {"name":"Camp Blacksmith","type":"NPC","wcid":31702,"cell":"3BE70101","place":"building","ns":83.08,"ew":-54.58,"id":6412}, + {"name":"Ruschk Camp Leader","type":"NPC","wcid":32596,"cell":"3BE70103","place":"building","ns":83.19,"ew":-54.59,"id":6413}, + {"name":"Chun Hei","type":"NPC","wcid":43125,"cell":"3C0D0012","place":"outdoor","ns":-91.41,"ew":-53.75,"id":6414,"desc":"Forgotten Tunnels Investigator."}, + {"name":"Fort Commander","type":"NPC","wcid":41840,"cell":"3C0D000A","place":"outdoor","ns":-91.44,"ew":-53.77,"id":6415,"desc":"Palm Fort Commander."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"3C410000","place":"outdoor","ns":-49.87,"ew":-53.67,"id":6416}, + {"name":"Uber P","type":"NPC","wcid":45851,"cell":"3CF5003E","place":"outdoor","ns":94.62,"ew":-53.23,"id":6417}, + {"name":"Shrine of the Scroll of Prophecy","type":"NPC","wcid":38256,"cell":"3D0A0016","place":"outdoor","ns":-93.4,"ew":-52.9,"id":6418}, + {"name":"Exploration Marker","type":"NPC","wcid":39802,"cell":"3D0B001C","place":"outdoor","ns":-92.8,"ew":-52.8,"id":6419}, + {"name":"Shrine of the Temple Horn","type":"NPC","wcid":38257,"cell":"3D0C001A","place":"outdoor","ns":-92.2,"ew":-52.8,"id":6420}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"3D220000","place":"outdoor","ns":-74.09,"ew":-52.4,"id":6421}, + {"name":"Blacksmith","type":"Vendor","wcid":1375,"cell":"3D5F0000","place":"outdoor","ns":-25.21,"ew":-53.11,"id":6422}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"3D5F0000","place":"outdoor","ns":-25.28,"ew":-53.14,"id":6423}, + {"name":"Myung Hee","type":"NPC","wcid":43126,"cell":"3E0A002C","place":"outdoor","ns":-93.62,"ew":-51.82,"id":6424,"desc":"Forgotten Tunnels Investigator."}, + {"name":"Fort Commander","type":"NPC","wcid":41838,"cell":"3E0A002C","place":"outdoor","ns":-93.62,"ew":-51.82,"id":6425,"desc":"Palm Fort Commander."}, + {"name":"Shrine of the Eye of T'thuun","type":"NPC","wcid":38255,"cell":"3E0D0026","place":"outdoor","ns":-91.0,"ew":-51.9,"id":6426}, + {"name":"Devon the Collector","type":"NPC","wcid":40461,"cell":"3E0D000C","place":"outdoor","ns":-91.24,"ew":-52.18,"id":6427,"desc":"Rare Items Collector."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"3EA40000","place":"outdoor","ns":29.41,"ew":-52.2,"id":6428}, + {"name":"Collector","type":"NPC","wcid":3917,"cell":"3EA40102","place":"building","ns":29.4,"ew":-52.0,"id":6429,"desc":"Trophy Collector."}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"3EA40000","place":"outdoor","ns":29.39,"ew":-52.02,"id":6430}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"3EC50000","place":"outdoor","ns":55.93,"ew":-52.22,"id":6431}, + {"name":"Archmage","type":"Vendor","wcid":1370,"cell":"3EC50100","place":"building","ns":55.89,"ew":-52.31,"id":6432}, + {"name":"Blacksmith","type":"Vendor","wcid":1375,"cell":"3EC50100","place":"building","ns":55.91,"ew":-52.31,"id":6433}, + {"name":"Farmer","type":"Vendor","wcid":1381,"cell":"3ED50000","place":"outdoor","ns":68.74,"ew":-51.61,"id":6434}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"3ED50000","place":"outdoor","ns":69.11,"ew":-51.72,"id":6435}, + {"name":"Roaming Bowyer","type":"Vendor","wcid":1378,"cell":"3ED50102","place":"building","ns":68.89,"ew":-51.61,"id":6436,"desc":"Bowyer."}, + {"name":"Peddler","type":"Vendor","wcid":1390,"cell":"3ED50104","place":"building","ns":68.9,"ew":-51.61,"id":6437}, + {"name":"Alchemy Table","type":"NPC","wcid":34038,"cell":"3EF40101","place":"dungeon","id":6438,"desc":"In a dungeon (landblock 3EF4)."}, + {"name":"Shrine of the Finger Bone of Mishfain","type":"NPC","wcid":38258,"cell":"3F0A002F","place":"outdoor","ns":-93.3,"ew":-51.0,"id":6439}, + {"name":"Shrine of Hagrafash's Tooth Necklace","type":"NPC","wcid":38262,"cell":"3F0C001A","place":"outdoor","ns":-92.2,"ew":-51.2,"id":6440}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"3F300000","place":"outdoor","ns":-62.77,"ew":-51.54,"id":6441}, + {"name":"Caelis Renning","type":"NPC","wcid":24212,"cell":"3F310103","place":"building","ns":-62.31,"ew":-51.37,"id":6442,"desc":"Timberman."}, + {"name":"Aun Teverea","type":"NPC","wcid":24214,"cell":"3F310103","place":"building","ns":-62.31,"ew":-51.4,"id":6443,"desc":"Trapper."}, + {"name":"Kreavon","type":"NPC","wcid":24213,"cell":"3F310104","place":"building","ns":-62.31,"ew":-51.42,"id":6444,"desc":"Miner."}, + {"name":"Grand Master Scrivener of Life Magic","type":"Vendor","wcid":20220,"cell":"3F31010C","place":"building","ns":-62.41,"ew":-51.22,"id":6445,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Creature Magic","type":"Vendor","wcid":20208,"cell":"3F310106","place":"building","ns":-62.39,"ew":-51.18,"id":6446,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of War Magic","type":"Vendor","wcid":20224,"cell":"3F310106","place":"building","ns":-62.4,"ew":-51.19,"id":6447,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Item Magic","type":"Vendor","wcid":20212,"cell":"3F310107","place":"building","ns":-62.4,"ew":-51.18,"id":6448,"desc":"Master Archmage."}, + {"name":"Archmage Dou Ran","type":"Vendor","wcid":2543,"cell":"3F320104","place":"building","ns":-61.82,"ew":-51.28,"id":6449,"desc":"Archmage."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"3F320104","place":"building","ns":-61.78,"ew":-51.32,"id":6450,"desc":"Mage."}, + {"name":"Bowyer Xana Bin-Xara","type":"Vendor","wcid":24218,"cell":"3F320000","place":"outdoor","ns":-61.83,"ew":-51.32,"id":6451,"desc":"Bowyer."}, + {"name":"Goku Bai-Akane the Barkeep","type":"Vendor","wcid":24217,"cell":"3F320113","place":"building","ns":-61.82,"ew":-51.31,"id":6452,"desc":"Barkeeper."}, + {"name":"Nakoro Eshii-Shinjo the Provisioner","type":"Vendor","wcid":24219,"cell":"3F320114","place":"building","ns":-61.78,"ew":-51.29,"id":6453,"desc":"Provisioner."}, + {"name":"Ximi Nu the Blacksmith","type":"Vendor","wcid":2541,"cell":"3F320122","place":"building","ns":-61.93,"ew":-51.5,"id":6454,"desc":"Blacksmith."}, + {"name":"Pang Sin-Xiang the Weaponsmith","type":"Vendor","wcid":24220,"cell":"3F320122","place":"building","ns":-61.88,"ew":-51.49,"id":6455,"desc":"Weaponsmith."}, + {"name":"Kan Chi Gai the Healer","type":"Vendor","wcid":2542,"cell":"3F320121","place":"building","ns":-61.88,"ew":-51.52,"id":6456,"desc":"Healer."}, + {"name":"Jojii Shrine","type":"NPC","wcid":24263,"cell":"3F320129","place":"building","ns":-61.9,"ew":-51.48,"id":6457}, + {"name":"Sarkin Killcrane","type":"NPC","wcid":31376,"cell":"3F320129","place":"building","ns":-61.92,"ew":-51.52,"id":6458,"desc":"Shadow Hunter."}, + {"name":"Nona","type":"NPC","wcid":31649,"cell":"3F320012","place":"outdoor","ns":-61.76,"ew":-51.29,"id":6459,"desc":"K'nath An'dras Assassinator."}, + {"name":"Xanda Har","type":"NPC","wcid":32780,"cell":"3F320012","place":"outdoor","ns":-61.77,"ew":-51.26,"id":6460,"desc":"Busybody."}, + {"name":"Riordin Nightbane","type":"NPC","wcid":33277,"cell":"3F320129","place":"building","ns":-61.93,"ew":-51.52,"id":6461,"desc":"Shadow Hunter."}, + {"name":"Guard Li","type":"NPC","wcid":36536,"cell":"3F320012","place":"outdoor","ns":-61.76,"ew":-51.29,"id":6462,"desc":"Soldier."}, + {"name":"Lacarra Avanthi","type":"NPC","wcid":38078,"cell":"3F320012","place":"outdoor","ns":-61.83,"ew":-51.26,"id":6463,"desc":"Blood of Truth."}, + {"name":"Zho Heishan","type":"NPC","wcid":38077,"cell":"3F320009","place":"outdoor","ns":-61.91,"ew":-51.38,"id":6464,"desc":"Hidden Hand."}, + {"name":"Encrusted Scroll Case","type":"NPC","wcid":40527,"cell":"3F320129","place":"building","ns":-61.9,"ew":-51.48,"id":6465}, + {"name":"Riordin Nightbane","type":"NPC","wcid":81081,"cell":"3F320129","place":"building","ns":-61.88,"ew":-51.5,"id":6466,"desc":"Shadow Hunter."}, + {"name":"King Toad Idol","type":"NPC","wcid":28095,"cell":"3F4E0000","place":"outdoor","ns":-39.37,"ew":-51.08,"id":6467}, + {"name":"Jin Kyong","type":"NPC","wcid":43124,"cell":"400C0023","place":"outdoor","ns":-92.08,"ew":-50.28,"id":6468,"desc":"Forgotten Tunnels Investigator."}, + {"name":"Fort Commander","type":"NPC","wcid":41834,"cell":"400C0023","place":"outdoor","ns":-92.07,"ew":-50.29,"id":6469,"desc":"Palm Fort Commander."}, + {"name":"Black Hill Collector","type":"NPC","wcid":24215,"cell":"40310000","place":"outdoor","ns":-62.21,"ew":-50.41,"id":6470,"desc":"Trophy Collector."}, + {"name":"Black Hill Trophy Smith","type":"NPC","wcid":24216,"cell":"40310000","place":"outdoor","ns":-62.19,"ew":-50.41,"id":6471,"desc":"Trophy Collector."}, + {"name":"Shrine of the Skull of Mishfain","type":"NPC","wcid":38259,"cell":"420B002F","place":"outdoor","ns":-92.5,"ew":-48.6,"id":6472}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"42160000","place":"outdoor","ns":-84.2,"ew":-48.8,"id":6473}, + {"name":"Exploration Marker","type":"NPC","wcid":39759,"cell":"421D0027","place":"outdoor","ns":-78.06,"ew":-48.66,"id":6474}, + {"name":"Archmage","type":"Vendor","wcid":1369,"cell":"42DE0000","place":"outdoor","ns":75.93,"ew":-49.08,"id":6475}, + {"name":"Healer","type":"Vendor","wcid":1384,"cell":"42DE0000","place":"outdoor","ns":76.08,"ew":-49.07,"id":6476}, + {"name":"Weaponsmith","type":"Vendor","wcid":1393,"cell":"42DE0000","place":"outdoor","ns":76.02,"ew":-49.02,"id":6477}, + {"name":"Peddler","type":"Vendor","wcid":1390,"cell":"42DE0000","place":"outdoor","ns":75.98,"ew":-49.02,"id":6478}, + {"name":"Feruza ibn Salaq","type":"NPC","wcid":7560,"cell":"42DE0000","place":"outdoor","ns":76.01,"ew":-49.08,"id":6479,"desc":"Researcher."}, + {"name":"Suzuhara Sheshumi","type":"NPC","wcid":30386,"cell":"42DE0000","place":"outdoor","ns":75.96,"ew":-49.1,"id":6480,"desc":"Ailing Adventurer."}, + {"name":"Guard Al'Zira","type":"NPC","wcid":37444,"cell":"42DE0003","place":"outdoor","ns":75.94,"ew":-49.1,"id":6481,"desc":"Soldier."}, + {"name":"Exploration Marker","type":"NPC","wcid":39791,"cell":"42DE000B","place":"outdoor","ns":75.92,"ew":-49.02,"id":6482}, + {"name":"White Totem Gateway","type":"NPC","wcid":33913,"cell":"42EC001F","place":"outdoor","ns":87.5,"ew":-48.8,"id":6483}, + {"name":"Fiun Gaya","type":"NPC","wcid":31296,"cell":"43EE003F","place":"outdoor","ns":89.13,"ew":-47.61,"id":6484,"desc":"Keeper of the Light."}, + {"name":"Commander Rylane di Cinghalle","type":"NPC","wcid":34037,"cell":"43F30010","place":"outdoor","ns":93.22,"ew":-48.19,"id":6485,"desc":"Royal Hunter."}, + {"name":"Arialle du Bellenesse","type":"NPC","wcid":34062,"cell":"43F30010","place":"outdoor","ns":93.23,"ew":-48.21,"id":6486,"desc":"Royal Hunter."}, + {"name":"Odd Looking Vine","type":"NPC","wcid":28430,"cell":"444F010A","place":"underground","ns":-38.14,"ew":-47.44,"id":6487}, + {"name":"Backpack","type":"NPC","wcid":28413,"cell":"444F0100","place":"building","ns":-38.12,"ew":-47.4,"id":6488}, + {"name":"Lighthouse Hermit","type":"NPC","wcid":27806,"cell":"445F0100","place":"building","ns":-25.81,"ew":-46.91,"id":6489,"desc":"Hermit."}, + {"name":"Exploration Marker","type":"NPC","wcid":39832,"cell":"445F0032","place":"outdoor","ns":-25.79,"ew":-46.89,"id":6490}, + {"name":"Ruschk Challenger","type":"NPC","wcid":31036,"cell":"44F20008","place":"outdoor","ns":92.4,"ew":-47.52,"id":6491}, + {"name":"Ruschk Totem","type":"NPC","wcid":31035,"cell":"44F20008","place":"outdoor","ns":92.37,"ew":-47.49,"id":6492,"desc":"Totem Man."}, + {"name":"Exploration Marker","type":"NPC","wcid":39797,"cell":"44F60022","place":"outdoor","ns":94.96,"ew":-47.07,"id":6493}, + {"name":"Mhoire Castle Southwest Tower Portal","type":"NPC","wcid":41953,"cell":"452D002D","place":"outdoor","ns":-65.47,"ew":-46.2,"id":6494}, + {"name":"Mhoire Castle Northwest Tower Portal","type":"NPC","wcid":41951,"cell":"452E0021","place":"outdoor","ns":-65.1,"ew":-46.3,"id":6495}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"45460000","place":"outdoor","ns":-45.26,"ew":-46.19,"id":6496}, + {"name":"Ssavashka the Devoted","type":"NPC","wcid":31663,"cell":"454A0108","place":"dungeon","id":6497,"desc":"Servant of Adhorix. In a dungeon (landblock 454A)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39794,"cell":"45620034","place":"outdoor","ns":-23.15,"ew":-46.05,"id":6498}, + {"name":"Mhoire Castle Southeast Tower Portal","type":"NPC","wcid":41952,"cell":"462D0026","place":"outdoor","ns":-65.39,"ew":-45.53,"id":6499}, + {"name":"Candrus Steady-Hand","type":"NPC","wcid":37602,"cell":"462D0032","place":"outdoor","ns":-65.81,"ew":-45.33,"id":6500,"desc":"Scout of the Hand."}, + {"name":"Mhoire Castle Northeast Tower Portal","type":"NPC","wcid":41950,"cell":"462E0001","place":"outdoor","ns":-65.1,"ew":-45.87,"id":6501}, + {"name":"Ayaname Chiyoko","type":"NPC","wcid":42731,"cell":"462F0101","place":"building","ns":-64.3,"ew":-45.5,"id":6502,"desc":"Hoshino Kei's Handmaiden."}, + {"name":"Floating Tower Ground Stopgap","type":"NPC","wcid":72744,"cell":"462F0021","place":"outdoor","ns":-64.28,"ew":-45.49,"id":6503,"desc":"Stopgap."}, + {"name":"Fir Tree","type":"NPC","wcid":24161,"cell":"46E30000","place":"outdoor","ns":79.96,"ew":-45.58,"id":6504}, + {"name":"Kalakh","type":"NPC","wcid":34063,"cell":"46F40008","place":"outdoor","ns":93.99,"ew":-45.88,"id":6505,"desc":"Frostglaive Hunter."}, + {"name":"Torgash","type":"NPC","wcid":34036,"cell":"46F40008","place":"outdoor","ns":94.0,"ew":-45.87,"id":6506,"desc":"Hunter of Knights."}, + {"name":"Ancient Stones","type":"NPC","wcid":41946,"cell":"472C0023","place":"outdoor","ns":-66.46,"ew":-44.74,"id":6507}, + {"name":"Massilor the Withered","type":"NPC","wcid":38715,"cell":"472D011C","place":"dungeon","id":6508,"desc":"Ancient Scholar. In Massilor's Crypt."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"47B60000","place":"outdoor","ns":43.83,"ew":-44.94,"id":6509}, + {"name":"Creed","type":"Vendor","wcid":40591,"cell":"48230100","place":"building","ns":-73.91,"ew":-43.71,"id":6510}, + {"name":"Exploration Marker","type":"NPC","wcid":39823,"cell":"48230023","place":"outdoor","ns":-73.75,"ew":-43.85,"id":6511}, + {"name":"Apep-tek the Tolerant","type":"NPC","wcid":35109,"cell":"482D001F","place":"outdoor","ns":-65.29,"ew":-44.02,"id":6512,"desc":"Mu-miyah Archmage."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":43842,"cell":"482D0121","place":"building","ns":-65.61,"ew":-44.11,"id":6513}, + {"name":"Summoning Stone","type":"NPC","wcid":38025,"cell":"482D002A","place":"outdoor","ns":-65.77,"ew":-43.8,"id":6514}, + {"name":"Mhoire Soldier","type":"NPC","wcid":45754,"cell":"482D011C","place":"underground","ns":-65.47,"ew":-43.97,"id":6515}, + {"name":"Mhoire Soldier","type":"NPC","wcid":45685,"cell":"482D011C","place":"underground","ns":-65.44,"ew":-43.97,"id":6516}, + {"name":"Yoite","type":"NPC","wcid":51957,"cell":"482D011F","place":"underground","ns":-65.44,"ew":-43.97,"id":6517,"desc":"Skeleton Stomper."}, + {"name":"Gadi","type":"NPC","wcid":51958,"cell":"482D011F","place":"underground","ns":-65.45,"ew":-43.97,"id":6518,"desc":"Wight Wrecker."}, + {"name":"Aethelswith","type":"NPC","wcid":51956,"cell":"482D011F","place":"underground","ns":-65.47,"ew":-43.97,"id":6519,"desc":"Spirit Slayer."}, + {"name":"Renata","type":"NPC","wcid":51955,"cell":"482D011F","place":"underground","ns":-65.42,"ew":-43.97,"id":6520,"desc":"Wisp Wrangler."}, + {"name":"Laylana","type":"NPC","wcid":37146,"cell":"482D0008","place":"outdoor","ns":-65.23,"ew":-44.26,"id":6521,"desc":"Ghostly Maiden."}, + {"name":"Jester's Prison Portal","type":"NPC","wcid":37149,"cell":"482E0100","place":"underground","ns":-64.88,"ew":-44.1,"id":6522}, + {"name":"Summoning Stone","type":"NPC","wcid":38026,"cell":"482E0026","place":"outdoor","ns":-64.63,"ew":-43.85,"id":6523}, + {"name":"Jailer","type":"NPC","wcid":37145,"cell":"482E010F","place":"underground","ns":-64.94,"ew":-44.07,"id":6524,"desc":"Jester's Prison Jailer."}, + {"name":"Guardian Statue","type":"NPC","wcid":43069,"cell":"482E0016","place":"outdoor","ns":-64.62,"ew":-44.12,"id":6525}, + {"name":"Guardian Statue","type":"NPC","wcid":35505,"cell":"482E0016","place":"outdoor","ns":-64.62,"ew":-44.08,"id":6526}, + {"name":"Kousu Temo","type":"NPC","wcid":37603,"cell":"482F001A","place":"outdoor","ns":-64.24,"ew":-43.96,"id":6527,"desc":"Scout of the Web."}, + {"name":"Exploration Marker","type":"NPC","wcid":39824,"cell":"48640029","place":"outdoor","ns":-21.95,"ew":-43.75,"id":6528}, + {"name":"Skettek the Wanderer","type":"Vendor","wcid":35488,"cell":"492D0017","place":"outdoor","ns":-65.31,"ew":-43.33,"id":6529,"desc":"Archmage."}, + {"name":"Lo Shoen","type":"NPC","wcid":36236,"cell":"492D0017","place":"outdoor","ns":-65.3,"ew":-43.28,"id":6530,"desc":"Rat Catcher."}, + {"name":"Slubbley","type":"NPC","wcid":52310,"cell":"492D0017","place":"outdoor","ns":-65.28,"ew":-43.32,"id":6531,"desc":"Caretaker."}, + {"name":"Sharia Blackmist","type":"NPC","wcid":40922,"cell":"492D0017","place":"outdoor","ns":-65.3,"ew":-43.33,"id":6532,"desc":"Ghost Hunter."}, + {"name":"Lo Shoen's Pack","type":"NPC","wcid":36237,"cell":"492D0017","place":"outdoor","ns":-65.31,"ew":-43.28,"id":6533}, + {"name":"Crafter of Axes","type":"NPC","wcid":11636,"cell":"49A70000","place":"outdoor","ns":32.03,"ew":-43.22,"id":6534}, + {"name":"Crafter of Bows","type":"NPC","wcid":11635,"cell":"49A70000","place":"outdoor","ns":32.0,"ew":-43.24,"id":6535}, + {"name":"Crafter of Fists","type":"NPC","wcid":11634,"cell":"49A70000","place":"outdoor","ns":31.98,"ew":-43.24,"id":6536}, + {"name":"Crafter of Arbelests","type":"NPC","wcid":11633,"cell":"49A70000","place":"outdoor","ns":31.97,"ew":-43.22,"id":6537}, + {"name":"Crafter of Knives","type":"NPC","wcid":11632,"cell":"49A70000","place":"outdoor","ns":31.96,"ew":-43.2,"id":6538}, + {"name":"Crafter of Maces","type":"NPC","wcid":11631,"cell":"49A70000","place":"outdoor","ns":31.97,"ew":-43.18,"id":6539}, + {"name":"Crafter of Orbs","type":"NPC","wcid":11630,"cell":"49A70000","place":"outdoor","ns":31.99,"ew":-43.16,"id":6540}, + {"name":"Crafter of Spears","type":"NPC","wcid":11629,"cell":"49A70000","place":"outdoor","ns":32.01,"ew":-43.16,"id":6541}, + {"name":"Crafter of Staves","type":"NPC","wcid":11628,"cell":"49A70000","place":"outdoor","ns":32.03,"ew":-43.18,"id":6542}, + {"name":"Crafter of Blades","type":"NPC","wcid":11627,"cell":"49A70000","place":"outdoor","ns":32.04,"ew":-43.2,"id":6543}, + {"name":"Crafter of Atlatls","type":"NPC","wcid":23523,"cell":"49A70000","place":"outdoor","ns":32.02,"ew":-43.23,"id":6544}, + {"name":"Crafter of Greatblades","type":"NPC","wcid":42037,"cell":"49A70000","place":"outdoor","ns":31.98,"ew":-43.17,"id":6545}, + {"name":"Avorgild the Shopkeeper","type":"Vendor","wcid":2500,"cell":"49B60103","place":"building","ns":44.29,"ew":-43.4,"id":6546,"desc":"Shopkeeper."}, + {"name":"Brenica the Jeweler","type":"Vendor","wcid":2503,"cell":"49B60117","place":"building","ns":44.11,"ew":-43.49,"id":6547,"desc":"Jeweler."}, + {"name":"Scribe Finaver","type":"Vendor","wcid":2501,"cell":"49B60117","place":"building","ns":44.09,"ew":-43.5,"id":6548,"desc":"Archmage."}, + {"name":"Mairisa bint Fuda","type":"NPC","wcid":5874,"cell":"49B60000","place":"outdoor","ns":44.41,"ew":-43.43,"id":6549,"desc":"Planar Mage."}, + {"name":"Plateau Spice Merchant","type":"Vendor","wcid":6113,"cell":"49B60100","place":"building","ns":44.32,"ew":-43.42,"id":6550,"desc":"Spice Merchant."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"49B60126","place":"building","ns":44.23,"ew":-43.19,"id":6551,"desc":"Mage."}, + {"name":"Master Scrivener of Life Magic","type":"Vendor","wcid":20219,"cell":"49B60132","place":"building","ns":44.19,"ew":-43.5,"id":6552,"desc":"Master Archmage."}, + {"name":"Master Scrivener of Creature Magic","type":"Vendor","wcid":20207,"cell":"49B60131","place":"building","ns":44.21,"ew":-43.48,"id":6553,"desc":"Master Archmage."}, + {"name":"Master Scrivener of Item Magic","type":"Vendor","wcid":20211,"cell":"49B60137","place":"building","ns":44.22,"ew":-43.49,"id":6554,"desc":"Master Archmage."}, + {"name":"Master Scrivener of War Magic","type":"Vendor","wcid":20223,"cell":"49B60000","place":"outdoor","ns":44.18,"ew":-43.48,"id":6555,"desc":"Master Archmage."}, + {"name":"Small Creepy Statue","type":"NPC","wcid":25988,"cell":"49B60000","place":"outdoor","ns":44.31,"ew":-43.23,"id":6556}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"49B60000","place":"outdoor","ns":43.94,"ew":-43.3,"id":6557}, + {"name":"Journeyman Fletcher","type":"NPC","wcid":28923,"cell":"49B6011F","place":"building","ns":44.01,"ew":-43.5,"id":6558,"desc":"Apprentice Fletcher."}, + {"name":"Jun Sawashima","type":"NPC","wcid":31692,"cell":"49B6000D","place":"outdoor","ns":44.12,"ew":-43.39,"id":6559,"desc":"Royal Emissary."}, + {"name":"Omarah","type":"NPC","wcid":45865,"cell":"49B60127","place":"building","ns":44.2,"ew":-43.2,"id":6560}, + {"name":"Grand Sentinel Tretia","type":"NPC","wcid":14922,"cell":"49B80000","place":"outdoor","ns":45.65,"ew":-43.32,"id":6561,"desc":"Marriage Facilitator."}, + {"name":"Lieutenant Takamaki","type":"NPC","wcid":46686,"cell":"49E40101","place":"building","ns":80.71,"ew":-43.0,"id":6562,"desc":"Royal Soldier."}, + {"name":"Griffon","type":"NPC","wcid":46682,"cell":"49E40101","place":"building","ns":80.69,"ew":-42.99,"id":6563,"desc":"Agent of the Whispering Blade."}, + {"name":"Corporal Irashi","type":"NPC","wcid":46681,"cell":"49E40101","place":"building","ns":80.71,"ew":-43.0,"id":6564,"desc":"Royal Soldier."}, + {"name":"Lord Eorlinde","type":"NPC","wcid":46680,"cell":"49E40101","place":"building","ns":80.69,"ew":-42.99,"id":6565,"desc":"Royal Knight Mage."}, + {"name":"Royal Guard","type":"NPC","wcid":42945,"cell":"49E4003B","place":"outdoor","ns":80.71,"ew":-42.84,"id":6566,"desc":"Borelean's Royal Guard."}, + {"name":"Lieutenant Roothe","type":"NPC","wcid":48920,"cell":"49E4002B","place":"outdoor","ns":80.72,"ew":-43.03,"id":6567,"desc":"Royal Soldier."}, + {"name":"Sergeant Freng","type":"NPC","wcid":52294,"cell":"49E4002B","place":"outdoor","ns":80.67,"ew":-42.99,"id":6568,"desc":"Royal Knight."}, + {"name":"Lord Brem","type":"NPC","wcid":48853,"cell":"49E4002B","place":"outdoor","ns":80.71,"ew":-43.05,"id":6569,"desc":"Royal Knight Mage."}, + {"name":"Mareeno Donn","type":"NPC","wcid":46445,"cell":"49E4002B","place":"outdoor","ns":80.72,"ew":-42.97,"id":6570,"desc":"Arcanum Researcher."}, + {"name":"Royal Guard","type":"NPC","wcid":42941,"cell":"49E4002B","place":"outdoor","ns":80.7,"ew":-43.03,"id":6571,"desc":"Borelean's Royal Guard."}, + {"name":"Royal Guard","type":"NPC","wcid":42940,"cell":"49E4002B","place":"outdoor","ns":80.71,"ew":-42.98,"id":6572,"desc":"Borelean's Royal Guard."}, + {"name":"Royal Guard","type":"NPC","wcid":42939,"cell":"49E4002B","place":"outdoor","ns":80.69,"ew":-42.98,"id":6573,"desc":"Borelean's Royal Guard."}, + {"name":"Royal Guard","type":"NPC","wcid":42938,"cell":"49E4002B","place":"outdoor","ns":80.71,"ew":-43.03,"id":6574,"desc":"Borelean's Royal Guard."}, + {"name":"Lieutenant Aurin","type":"NPC","wcid":46678,"cell":"49E4002B","place":"outdoor","ns":80.71,"ew":-42.96,"id":6575,"desc":"Royal Soldier."}, + {"name":"Sergeant Trebuus","type":"NPC","wcid":46679,"cell":"49E4002B","place":"outdoor","ns":80.66,"ew":-42.96,"id":6576,"desc":"Royal Knight."}, + {"name":"Aun Kirtal","type":"NPC","wcid":46683,"cell":"49E4002B","place":"outdoor","ns":80.71,"ew":-42.96,"id":6577,"desc":"Royal Soldier."}, + {"name":"Hanamoto Aki'ko","type":"NPC","wcid":46684,"cell":"49E40101","place":"building","ns":80.69,"ew":-43.01,"id":6578,"desc":"Agent of the Whispering Blade."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"49F0001C","place":"outdoor","ns":90.37,"ew":-43.23,"id":6579}, + {"name":"Healer","type":"Vendor","wcid":30054,"cell":"49F0010B","place":"building","ns":90.4,"ew":-43.09,"id":6580}, + {"name":"Archmage","type":"Vendor","wcid":30053,"cell":"49F0010B","place":"building","ns":90.42,"ew":-43.07,"id":6581}, + {"name":"Shopkeeper","type":"Vendor","wcid":30051,"cell":"49F0010B","place":"building","ns":90.41,"ew":-43.07,"id":6582}, + {"name":"Blacksmith","type":"Vendor","wcid":30052,"cell":"49F0010B","place":"building","ns":90.43,"ew":-43.09,"id":6583}, + {"name":"Grand Master Scrivener of Creature Magic","type":"Vendor","wcid":30024,"cell":"49F0010D","place":"building","ns":90.19,"ew":-42.91,"id":6584,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Life Magic","type":"Vendor","wcid":30014,"cell":"49F00032","place":"outdoor","ns":90.21,"ew":-42.91,"id":6585,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of War Magic","type":"Vendor","wcid":30018,"cell":"49F0010E","place":"building","ns":90.29,"ew":-43.31,"id":6586,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Item Magic","type":"Vendor","wcid":30028,"cell":"49F00013","place":"outdoor","ns":90.29,"ew":-43.31,"id":6587,"desc":"Master Archmage."}, + {"name":"Marcello","type":"NPC","wcid":31654,"cell":"49F00022","place":"outdoor","ns":90.18,"ew":-43.12,"id":6588,"desc":"Olthoi Ripper Reducer."}, + {"name":"Claire Artmad","type":"NPC","wcid":31650,"cell":"49F00022","place":"outdoor","ns":90.21,"ew":-43.09,"id":6589,"desc":"Tukora Lieutenant Trouncer."}, + {"name":"Ruqaya al Mubarak","type":"NPC","wcid":31658,"cell":"49F00023","place":"outdoor","ns":90.3,"ew":-43.12,"id":6590,"desc":"Wicked Skeleton Walloper."}, + {"name":"Orfeo Orlando","type":"NPC","wcid":31653,"cell":"49F00022","place":"outdoor","ns":90.17,"ew":-43.1,"id":6591,"desc":"Mosswart Worshipper Whipper."}, + {"name":"Xun Yu","type":"NPC","wcid":31646,"cell":"49F00100","place":"building","ns":90.19,"ew":-43.11,"id":6592,"desc":"Repugnant Eater Ripper."}, + {"name":"Taku Yukio","type":"NPC","wcid":31657,"cell":"49F00023","place":"outdoor","ns":90.3,"ew":-43.13,"id":6593,"desc":"Naughty Skeleton Snuffer."}, + {"name":"Ricardo","type":"NPC","wcid":31316,"cell":"49F00023","place":"outdoor","ns":90.33,"ew":-43.1,"id":6594,"desc":"Traveler."}, + {"name":"Moina","type":"NPC","wcid":31647,"cell":"49F00024","place":"outdoor","ns":90.41,"ew":-43.13,"id":6595,"desc":"Violator Grievver Vetoer."}, + {"name":"Ryuichi Tai","type":"NPC","wcid":31656,"cell":"49F0002B","place":"outdoor","ns":90.32,"ew":-42.98,"id":6596,"desc":"Floeshark Flogger."}, + {"name":"Francisco the Hunter","type":"NPC","wcid":37441,"cell":"49F0002F","place":"outdoor","ns":90.73,"ew":-42.98,"id":6597,"desc":"Hunter."}, + {"name":"Hermit","type":"NPC","wcid":30979,"cell":"49F50100","place":"building","ns":94.14,"ew":-42.99,"id":6598,"desc":"Tormented Soul."}, + {"name":"Exploration Marker","type":"NPC","wcid":39798,"cell":"49F5002A","place":"outdoor","ns":94.17,"ew":-43.01,"id":6599}, + {"name":"Jawaq ibn Janath","type":"NPC","wcid":37607,"cell":"4A2D0027","place":"outdoor","ns":-65.27,"ew":-42.34,"id":6600,"desc":"Scout of the Blood."}, + {"name":"Lieutenant Allandal","type":"NPC","wcid":32841,"cell":"4AB50019","place":"outdoor","ns":42.91,"ew":-42.4,"id":6601,"desc":"Soldier."}, + {"name":"Mysterious Hatch","type":"NPC","wcid":48859,"cell":"4AE1010C","place":"building","ns":78.21,"ew":-42.32,"id":6602}, + {"name":"Darviss","type":"NPC","wcid":46559,"cell":"4AE1011A","place":"building","ns":78.11,"ew":-42.2,"id":6603,"desc":"Recruiter of Souls."}, + {"name":"Lock","type":"NPC","wcid":46456,"cell":"4AE3001A","place":"outdoor","ns":79.85,"ew":-42.4,"id":6604}, + {"name":"Ruschk Ice Totem","type":"NPC","wcid":87221,"cell":"4AF60023","place":"outdoor","ns":95.12,"ew":-42.27,"id":6605}, + {"name":"Ka Ku-To the Tailor","type":"Vendor","wcid":2502,"cell":"4BB2010A","place":"building","ns":40.59,"ew":-41.7,"id":6606,"desc":"Tailor."}, + {"name":"Exploration Marker","type":"NPC","wcid":39755,"cell":"4BB20032","place":"outdoor","ns":40.59,"ew":-41.29,"id":6607}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"4BB60000","place":"outdoor","ns":44.38,"ew":-41.56,"id":6608}, + {"name":"Shorikan","type":"NPC","wcid":46889,"cell":"4BE1010F","place":"building","ns":78.08,"ew":-41.68,"id":6609,"desc":"Spectral Commander."}, + {"name":"Lock","type":"NPC","wcid":46457,"cell":"4BE2002B","place":"outdoor","ns":79.1,"ew":-41.45,"id":6610}, + {"name":"Mysterious Hatch","type":"NPC","wcid":48875,"cell":"4BE20014","place":"outdoor","ns":79.21,"ew":-41.69,"id":6611}, + {"name":"Lock","type":"NPC","wcid":46458,"cell":"4BE2000C","place":"outdoor","ns":79.2,"ew":-41.85,"id":6612}, + {"name":"Mysterious Hatch","type":"NPC","wcid":48858,"cell":"4CE10124","place":"building","ns":78.63,"ew":-40.6,"id":6613}, + {"name":"Kinchou","type":"NPC","wcid":46775,"cell":"4CE10139","place":"building","ns":78.46,"ew":-40.5,"id":6614,"desc":"Recruiter of Souls."}, + {"name":"Kousha","type":"NPC","wcid":46735,"cell":"4CE10139","place":"building","ns":78.46,"ew":-40.52,"id":6615,"desc":"Recruiter of Souls."}, + {"name":"Mysterious Hatch","type":"NPC","wcid":48857,"cell":"4CE30104","place":"building","ns":79.77,"ew":-41.03,"id":6616}, + {"name":"Life Stone","type":"Lifestone","wcid":23618,"cell":"4FA70000","place":"outdoor","ns":32.2,"ew":-38.53,"id":6617}, + {"name":"Healer","type":"Vendor","wcid":1384,"cell":"4FC30000","place":"outdoor","ns":54.39,"ew":-38.28,"id":6618}, + {"name":"Archmage","type":"Vendor","wcid":1369,"cell":"4FC30000","place":"outdoor","ns":54.39,"ew":-38.26,"id":6619}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"4FC30000","place":"outdoor","ns":54.45,"ew":-38.29,"id":6620}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"51180000","place":"outdoor","ns":-82.2,"ew":-36.46,"id":6621}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"52230000","place":"outdoor","ns":-73.43,"ew":-36.11,"id":6622}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"52230000","place":"outdoor","ns":-73.4,"ew":-36.12,"id":6623}, + {"name":"Lilitha","type":"NPC","wcid":14574,"cell":"526A02EA","place":"dungeon","id":6624,"desc":"Bow Master. In a dungeon (landblock 526A)."}, + {"name":"Yalaini Woman","type":"NPC","wcid":14572,"cell":"526A02FD","place":"dungeon","id":6625,"desc":"Yalaini. In a dungeon (landblock 526A)."}, + {"name":"Yalaini Man","type":"NPC","wcid":14573,"cell":"526A0305","place":"dungeon","id":6626,"desc":"Yalaini. In a dungeon (landblock 526A)."}, + {"name":"Aun Tanua","type":"NPC","wcid":14575,"cell":"526A0320","place":"dungeon","id":6627,"desc":"In a dungeon (landblock 526A)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"54180000","place":"outdoor","ns":-82.28,"ew":-34.29,"id":6628}, + {"name":"Merchant","type":"Vendor","wcid":1389,"cell":"54180102","place":"building","ns":-82.4,"ew":-34.3,"id":6629}, + {"name":"Cocooned Auroch","type":"NPC","wcid":20017,"cell":"54560154","place":"dungeon","id":6630,"desc":"Dying. In Grievver Caves."}, + {"name":"Cocooned Auroch","type":"NPC","wcid":20017,"cell":"5456025E","place":"dungeon","id":6631,"desc":"Dying. In Grievver Caves."}, + {"name":"Guen, Royal Guardian","type":"NPC","wcid":19462,"cell":"545C067B","place":"dungeon","id":6632,"desc":"Guard. In a dungeon (landblock 545C)."}, + {"name":"Isabelle, Royal Guardian","type":"NPC","wcid":19463,"cell":"545C067D","place":"dungeon","id":6633,"desc":"Guard. In a dungeon (landblock 545C)."}, + {"name":"Etienne, Royal Guardian","type":"NPC","wcid":19461,"cell":"545C0680","place":"dungeon","id":6634,"desc":"Guard. In a dungeon (landblock 545C)."}, + {"name":"Oubliette Gatekeeper","type":"NPC","wcid":16912,"cell":"546302A5","place":"dungeon","id":6635,"desc":"In a dungeon (landblock 5463)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"54D70000","place":"outdoor","ns":70.37,"ew":-34.52,"id":6636}, + {"name":"Timorous","type":"NPC","wcid":22935,"cell":"5648014B","place":"dungeon","id":6637,"desc":"Student. In a dungeon (landblock 5648)."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":87180,"cell":"56520289","place":"dungeon","id":6638,"desc":"In a dungeon (landblock 5652)."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":87181,"cell":"56520270","place":"dungeon","id":6639,"desc":"In a dungeon (landblock 5652)."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":87182,"cell":"565202B1","place":"dungeon","id":6640,"desc":"In a dungeon (landblock 5652)."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":87183,"cell":"565202CA","place":"dungeon","id":6641,"desc":"In a dungeon (landblock 5652)."}, + {"name":"Bloody Breastplate","type":"NPC","wcid":87186,"cell":"56520109","place":"dungeon","id":6642,"desc":"In a dungeon (landblock 5652)."}, + {"name":"Menhir","type":"NPC","wcid":43987,"cell":"5652024E","place":"dungeon","id":6643,"desc":"In a dungeon (landblock 5652)."}, + {"name":"Bookshelf","type":"NPC","wcid":21485,"cell":"5653012C","place":"dungeon","id":6644,"desc":"In Citadel Library."}, + {"name":"Bookshelf","type":"NPC","wcid":21486,"cell":"56530135","place":"dungeon","id":6645,"desc":"In Citadel Library."}, + {"name":"Bookshelf","type":"NPC","wcid":21487,"cell":"56530192","place":"dungeon","id":6646,"desc":"In Citadel Library."}, + {"name":"Gaerlan's Phylacteric Prison","type":"NPC","wcid":21720,"cell":"56540129","place":"dungeon","id":6647,"desc":"In a dungeon (landblock 5654)."}, + {"name":"Virindi Captive","type":"NPC","wcid":45861,"cell":"5655039E","place":"dungeon","id":6648,"desc":"In Virindi Research Facility."}, + {"name":"Virindi Captive","type":"NPC","wcid":45862,"cell":"565503A0","place":"dungeon","id":6649,"desc":"In Virindi Research Facility."}, + {"name":"Virindi Captive","type":"NPC","wcid":45863,"cell":"565502A8","place":"dungeon","id":6650,"desc":"In Virindi Research Facility."}, + {"name":"Curator of Torment","type":"NPC","wcid":45864,"cell":"56550107","place":"dungeon","id":6651,"desc":"In Virindi Research Facility."}, + {"name":"Virindi Captive","type":"NPC","wcid":46027,"cell":"56550107","place":"dungeon","id":6652,"desc":"In Virindi Research Facility."}, + {"name":"Leandra","type":"NPC","wcid":20916,"cell":"5660012C","place":"dungeon","id":6653,"desc":"Alchemist. In Martine's Retreat."}, + {"name":"Julian Bartok","type":"NPC","wcid":20914,"cell":"56600152","place":"dungeon","id":6654,"desc":"Human Defender. In Martine's Retreat."}, + {"name":"Sialla Jiro","type":"Vendor","wcid":20923,"cell":"56600156","place":"dungeon","id":6655,"desc":"Master Archmage. In Martine's Retreat."}, + {"name":"Riseldor the Bowyer","type":"Vendor","wcid":20924,"cell":"5660015A","place":"dungeon","id":6656,"desc":"Bowyer. In Martine's Retreat."}, + {"name":"Josef","type":"NPC","wcid":20913,"cell":"56600165","place":"dungeon","id":6657,"desc":"Vagabond. In Martine's Retreat."}, + {"name":"Ichi Ji","type":"Vendor","wcid":20926,"cell":"56600176","place":"dungeon","id":6658,"desc":"Shopkeeper. In Martine's Retreat."}, + {"name":"Remmick","type":"NPC","wcid":20918,"cell":"56600186","place":"dungeon","id":6659,"desc":"Farmer. In Martine's Retreat."}, + {"name":"Kira Sojini","type":"NPC","wcid":20915,"cell":"56600186","place":"dungeon","id":6660,"desc":"Blacksmith. In Martine's Retreat."}, + {"name":"Timon Rae","type":"NPC","wcid":20925,"cell":"566001A6","place":"dungeon","id":6661,"desc":"In Martine's Retreat."}, + {"name":"Ambrosia Roe","type":"NPC","wcid":20911,"cell":"566001E7","place":"dungeon","id":6662,"desc":"Bow Hunter. In Martine's Retreat."}, + {"name":"Hibdin Velos","type":"NPC","wcid":20912,"cell":"566001EE","place":"dungeon","id":6663,"desc":"Axe Warrior. In Martine's Retreat."}, + {"name":"Tribunal","type":"NPC","wcid":21496,"cell":"574401A0","place":"dungeon","id":6664,"desc":"In Proving Grounds Low."}, + {"name":"Statue","type":"NPC","wcid":21495,"cell":"574401F4","place":"dungeon","id":6665,"desc":"In Proving Grounds Low."}, + {"name":"E","type":"NPC","wcid":21502,"cell":"5744019C","place":"dungeon","id":6666,"desc":"In Proving Grounds Low."}, + {"name":"Darkness","type":"NPC","wcid":21500,"cell":"5744019C","place":"dungeon","id":6667,"desc":"In Proving Grounds Low."}, + {"name":"Wind","type":"NPC","wcid":21516,"cell":"5744019D","place":"dungeon","id":6668,"desc":"In Proving Grounds Low."}, + {"name":"Sunlight","type":"NPC","wcid":21513,"cell":"5744019D","place":"dungeon","id":6669,"desc":"In Proving Grounds Low."}, + {"name":"Nothing","type":"NPC","wcid":21509,"cell":"5744019E","place":"dungeon","id":6670,"desc":"In Proving Grounds Low."}, + {"name":"Man","type":"NPC","wcid":21507,"cell":"5744019E","place":"dungeon","id":6671,"desc":"In Proving Grounds Low."}, + {"name":"Stars","type":"NPC","wcid":21512,"cell":"5744019E","place":"dungeon","id":6672,"desc":"In Proving Grounds Low."}, + {"name":"Silence","type":"NPC","wcid":21511,"cell":"5744019F","place":"dungeon","id":6673,"desc":"In Proving Grounds Low."}, + {"name":"Coffin","type":"NPC","wcid":21499,"cell":"5744019F","place":"dungeon","id":6674,"desc":"In Proving Grounds Low."}, + {"name":"Tomorrow","type":"NPC","wcid":21515,"cell":"574401A1","place":"dungeon","id":6675,"desc":"In Proving Grounds Low."}, + {"name":"Death","type":"NPC","wcid":21501,"cell":"574401A1","place":"dungeon","id":6676,"desc":"In Proving Grounds Low."}, + {"name":"Bed","type":"NPC","wcid":21497,"cell":"574401A3","place":"dungeon","id":6677,"desc":"In Proving Grounds Low."}, + {"name":"Eyes","type":"NPC","wcid":21503,"cell":"574401A3","place":"dungeon","id":6678,"desc":"In Proving Grounds Low."}, + {"name":"Black","type":"NPC","wcid":21498,"cell":"574401A3","place":"dungeon","id":6679,"desc":"In Proving Grounds Low."}, + {"name":"Hole","type":"NPC","wcid":21505,"cell":"574401A4","place":"dungeon","id":6680,"desc":"In Proving Grounds Low."}, + {"name":"Flame","type":"NPC","wcid":21504,"cell":"574401A4","place":"dungeon","id":6681,"desc":"In Proving Grounds Low."}, + {"name":"Mushroom","type":"NPC","wcid":21508,"cell":"574401A5","place":"dungeon","id":6682,"desc":"In Proving Grounds Low."}, + {"name":"Hope","type":"NPC","wcid":21506,"cell":"574401A5","place":"dungeon","id":6683,"desc":"In Proving Grounds Low."}, + {"name":"Ring","type":"NPC","wcid":21510,"cell":"574401A5","place":"dungeon","id":6684,"desc":"In Proving Grounds Low."}, + {"name":"Time","type":"NPC","wcid":21514,"cell":"574401A5","place":"dungeon","id":6685,"desc":"In Proving Grounds Low."}, + {"name":"Statue","type":"NPC","wcid":21494,"cell":"574401DA","place":"dungeon","id":6686,"desc":"In Proving Grounds Low."}, + {"name":"Platinum Golem","type":"NPC","wcid":21982,"cell":"574603BA","place":"dungeon","id":6687,"desc":"In Lightning Ziggurat."}, + {"name":"Aun Talamura","type":"NPC","wcid":22936,"cell":"574A0126","place":"dungeon","id":6688,"desc":"In a dungeon (landblock 574A)."}, + {"name":"Aun Talamura","type":"NPC","wcid":23040,"cell":"574B0126","place":"dungeon","id":6689,"desc":"In a dungeon (landblock 574B)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39807,"cell":"574D0107","place":"dungeon","id":6690,"desc":"In a dungeon (landblock 574D)."}, + {"name":"Altar of the Black Crystal","type":"NPC","wcid":44307,"cell":"575402C0","place":"dungeon","id":6691,"desc":"In a dungeon (landblock 5754)."}, + {"name":"Altar of the Red Crystal","type":"NPC","wcid":71380,"cell":"575401E4","place":"dungeon","id":6692,"desc":"In a dungeon (landblock 5754)."}, + {"name":"Altar of the White Crystal","type":"NPC","wcid":71354,"cell":"575402A1","place":"dungeon","id":6693,"desc":"In a dungeon (landblock 5754)."}, + {"name":"Altar of the Green Crystal","type":"NPC","wcid":71357,"cell":"5754027B","place":"dungeon","id":6694,"desc":"In a dungeon (landblock 5754)."}, + {"name":"Hatshepsut","type":"NPC","wcid":44104,"cell":"57560285","place":"dungeon","id":6695,"desc":"In Temple."}, + {"name":"Quaron","type":"NPC","wcid":72834,"cell":"575E01C2","place":"dungeon","id":6696,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Gatekeeper","type":"NPC","wcid":72841,"cell":"575E01BB","place":"dungeon","id":6697,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Gatekeeper","type":"NPC","wcid":72845,"cell":"575E01B7","place":"dungeon","id":6698,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Ter Shen","type":"NPC","wcid":72833,"cell":"575E01F0","place":"dungeon","id":6699,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Strange Crystal","type":"NPC","wcid":72851,"cell":"575E0130","place":"dungeon","id":6700,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Strange Crystal","type":"NPC","wcid":72852,"cell":"575E016E","place":"dungeon","id":6701,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Panumbris Shadow","type":"NPC","wcid":72846,"cell":"575E01D7","place":"dungeon","id":6702,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Panumbris Shadow","type":"NPC","wcid":72846,"cell":"575E01C3","place":"dungeon","id":6703,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Panumbris Shadow","type":"NPC","wcid":72846,"cell":"575E01D8","place":"dungeon","id":6704,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Panumbris Shadow","type":"NPC","wcid":72846,"cell":"575E01F9","place":"dungeon","id":6705,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Panumbris Shadow","type":"NPC","wcid":72846,"cell":"575E01CB","place":"dungeon","id":6706,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Panumbris Shadow","type":"NPC","wcid":72846,"cell":"575E01B7","place":"dungeon","id":6707,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Panumbris Shadow","type":"NPC","wcid":72846,"cell":"575E01BB","place":"dungeon","id":6708,"desc":"In a dungeon (landblock 575E)."}, + {"name":"Bael'Zharon Summoner Stopgap","type":"NPC","wcid":72847,"cell":"575E0153","place":"dungeon","id":6709,"desc":"Stopgap. In a dungeon (landblock 575E)."}, + {"name":"Strange Crystal","type":"NPC","wcid":72851,"cell":"57610130","place":"dungeon","id":6710,"desc":"In a dungeon (landblock 5761)."}, + {"name":"Strange Crystal","type":"NPC","wcid":72852,"cell":"5761016E","place":"dungeon","id":6711,"desc":"In a dungeon (landblock 5761)."}, + {"name":"Bael'Zharon Summoner Stopgap","type":"NPC","wcid":72885,"cell":"57610153","place":"dungeon","id":6712,"desc":"Stopgap. In a dungeon (landblock 5761)."}, + {"name":"Exit from the Oubliette","type":"NPC","wcid":45131,"cell":"5764031E","place":"dungeon","id":6713,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Deeper into the Oubliette","type":"NPC","wcid":45125,"cell":"5764034D","place":"dungeon","id":6714,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Up to the Previous Level","type":"NPC","wcid":45132,"cell":"5764030F","place":"dungeon","id":6715,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Deeper into the Oubliette","type":"NPC","wcid":45126,"cell":"576402E0","place":"dungeon","id":6716,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Up to the Previous Level","type":"NPC","wcid":45133,"cell":"576402A2","place":"dungeon","id":6717,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Deeper into the Oubliette","type":"NPC","wcid":45127,"cell":"576402BD","place":"dungeon","id":6718,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Up to the Previous Level","type":"NPC","wcid":45134,"cell":"57640280","place":"dungeon","id":6719,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Deeper into the Oubliette","type":"NPC","wcid":45128,"cell":"57640287","place":"dungeon","id":6720,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Up to the Previous Level","type":"NPC","wcid":45135,"cell":"57640249","place":"dungeon","id":6721,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Deeper into the Oubliette","type":"NPC","wcid":45129,"cell":"5764021A","place":"dungeon","id":6722,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Up to the Previous Level","type":"NPC","wcid":45136,"cell":"576401E0","place":"dungeon","id":6723,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Deeper into the Oubliette","type":"NPC","wcid":45130,"cell":"576401A2","place":"dungeon","id":6724,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Up to the Previous Level","type":"NPC","wcid":45137,"cell":"57640163","place":"dungeon","id":6725,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Lightning Trap","type":"NPC","wcid":72283,"cell":"576402D8","place":"dungeon","id":6726,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Lightning Trap","type":"NPC","wcid":72283,"cell":"576402DC","place":"dungeon","id":6727,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Lightning Trap","type":"NPC","wcid":72283,"cell":"57640303","place":"dungeon","id":6728,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Lightning Trap","type":"NPC","wcid":72283,"cell":"576402F3","place":"dungeon","id":6729,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Lightning Trap","type":"NPC","wcid":72283,"cell":"576402FF","place":"dungeon","id":6730,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Lightning Trap","type":"NPC","wcid":72283,"cell":"576402EF","place":"dungeon","id":6731,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Lightning Trap","type":"NPC","wcid":72283,"cell":"576402E3","place":"dungeon","id":6732,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Lightning Trap","type":"NPC","wcid":72283,"cell":"576402D4","place":"dungeon","id":6733,"desc":"In a dungeon (landblock 5764)."}, + {"name":"Darviss","type":"NPC","wcid":72670,"cell":"57660102","place":"dungeon","id":6734,"desc":"Recruiter of Souls. In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660101","place":"dungeon","id":6735,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660127","place":"dungeon","id":6736,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660102","place":"dungeon","id":6737,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660108","place":"dungeon","id":6738,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660109","place":"dungeon","id":6739,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"5766012B","place":"dungeon","id":6740,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"5766012F","place":"dungeon","id":6741,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660115","place":"dungeon","id":6742,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660113","place":"dungeon","id":6743,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"5766013C","place":"dungeon","id":6744,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660144","place":"dungeon","id":6745,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660164","place":"dungeon","id":6746,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660163","place":"dungeon","id":6747,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660148","place":"dungeon","id":6748,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660175","place":"dungeon","id":6749,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660159","place":"dungeon","id":6750,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660196","place":"dungeon","id":6751,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576601B8","place":"dungeon","id":6752,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576601BB","place":"dungeon","id":6753,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576601C5","place":"dungeon","id":6754,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576601EE","place":"dungeon","id":6755,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576601F1","place":"dungeon","id":6756,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576601D5","place":"dungeon","id":6757,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660204","place":"dungeon","id":6758,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"5766020D","place":"dungeon","id":6759,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"5766023D","place":"dungeon","id":6760,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"5766023B","place":"dungeon","id":6761,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660241","place":"dungeon","id":6762,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"5766024C","place":"dungeon","id":6763,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660274","place":"dungeon","id":6764,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660276","place":"dungeon","id":6765,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660273","place":"dungeon","id":6766,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"5766027E","place":"dungeon","id":6767,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660292","place":"dungeon","id":6768,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660296","place":"dungeon","id":6769,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576602B6","place":"dungeon","id":6770,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576602B7","place":"dungeon","id":6771,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576602BC","place":"dungeon","id":6772,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576602B8","place":"dungeon","id":6773,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576602C0","place":"dungeon","id":6774,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576602E6","place":"dungeon","id":6775,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576602E7","place":"dungeon","id":6776,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576602C9","place":"dungeon","id":6777,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576602CA","place":"dungeon","id":6778,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660158","place":"dungeon","id":6779,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660160","place":"dungeon","id":6780,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660109","place":"dungeon","id":6781,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660108","place":"dungeon","id":6782,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660105","place":"dungeon","id":6783,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660104","place":"dungeon","id":6784,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660107","place":"dungeon","id":6785,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660196","place":"dungeon","id":6786,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"5766015A","place":"dungeon","id":6787,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"5766016F","place":"dungeon","id":6788,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660194","place":"dungeon","id":6789,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660193","place":"dungeon","id":6790,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660170","place":"dungeon","id":6791,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660170","place":"dungeon","id":6792,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"57660190","place":"dungeon","id":6793,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"5766012F","place":"dungeon","id":6794,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660113","place":"dungeon","id":6795,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"57660126","place":"dungeon","id":6796,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Slice and Dice","type":"NPC","wcid":72648,"cell":"5766013C","place":"dungeon","id":6797,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"576601BC","place":"dungeon","id":6798,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"576601BA","place":"dungeon","id":6799,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"576601C2","place":"dungeon","id":6800,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"576601CB","place":"dungeon","id":6801,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"576601BB","place":"dungeon","id":6802,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"576601C4","place":"dungeon","id":6803,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"576601D2","place":"dungeon","id":6804,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"576601D3","place":"dungeon","id":6805,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"576601EE","place":"dungeon","id":6806,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"57660229","place":"dungeon","id":6807,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"5766023B","place":"dungeon","id":6808,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"5766023D","place":"dungeon","id":6809,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Five Finger Death Punch","type":"NPC","wcid":72650,"cell":"5766027E","place":"dungeon","id":6810,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Five Finger Death Punch","type":"NPC","wcid":72650,"cell":"57660274","place":"dungeon","id":6811,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Five Finger Death Punch","type":"NPC","wcid":72650,"cell":"576602E7","place":"dungeon","id":6812,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Five Finger Death Punch","type":"NPC","wcid":72650,"cell":"576602C0","place":"dungeon","id":6813,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Five Finger Death Punch","type":"NPC","wcid":72650,"cell":"57660273","place":"dungeon","id":6814,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Five Finger Death Punch","type":"NPC","wcid":72650,"cell":"5766028F","place":"dungeon","id":6815,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"5766028F","place":"dungeon","id":6816,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576602AC","place":"dungeon","id":6817,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"576602E5","place":"dungeon","id":6818,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Five Finger Death Punch","type":"NPC","wcid":72650,"cell":"576602E5","place":"dungeon","id":6819,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Pin Cushion","type":"NPC","wcid":72649,"cell":"576601D5","place":"dungeon","id":6820,"desc":"In Nanjou Shou-jen Academy."}, + {"name":"Moarself","type":"NPC","wcid":88362,"cell":"57680161","place":"dungeon","id":6821,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88366,"cell":"57680125","place":"dungeon","id":6822,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88367,"cell":"57680124","place":"dungeon","id":6823,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88347,"cell":"57680127","place":"dungeon","id":6824,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88365,"cell":"5768012A","place":"dungeon","id":6825,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88365,"cell":"57680129","place":"dungeon","id":6826,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88366,"cell":"5768012E","place":"dungeon","id":6827,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88347,"cell":"5768012C","place":"dungeon","id":6828,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88365,"cell":"5768012D","place":"dungeon","id":6829,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88347,"cell":"57680206","place":"dungeon","id":6830,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Door","type":"NPC","wcid":88364,"cell":"57680266","place":"dungeon","id":6831,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Santa Sclavus","type":"NPC","wcid":88345,"cell":"57680262","place":"dungeon","id":6832,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88369,"cell":"576802B5","place":"dungeon","id":6833,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88370,"cell":"576802B7","place":"dungeon","id":6834,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88371,"cell":"576802B6","place":"dungeon","id":6835,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88372,"cell":"576802B8","place":"dungeon","id":6836,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88373,"cell":"576802B4","place":"dungeon","id":6837,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Santa Sclavus","type":"NPC","wcid":88346,"cell":"5768044F","place":"dungeon","id":6838,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Moarself","type":"NPC","wcid":88365,"cell":"5768041F","place":"dungeon","id":6839,"desc":"In a dungeon (landblock 5768)."}, + {"name":"A Rolling Snowball of Death","type":"NPC","wcid":88382,"cell":"57680312","place":"dungeon","id":6840,"desc":"In a dungeon (landblock 5768)."}, + {"name":"A Rolling Snowball of Death","type":"NPC","wcid":88382,"cell":"57680317","place":"dungeon","id":6841,"desc":"In a dungeon (landblock 5768)."}, + {"name":"A Rolling Snowball of Death","type":"NPC","wcid":88382,"cell":"57680320","place":"dungeon","id":6842,"desc":"In a dungeon (landblock 5768)."}, + {"name":"A Rolling Snowball of Death","type":"NPC","wcid":88382,"cell":"57680325","place":"dungeon","id":6843,"desc":"In a dungeon (landblock 5768)."}, + {"name":"A Rolling Snowball of Death","type":"NPC","wcid":88382,"cell":"5768032B","place":"dungeon","id":6844,"desc":"In a dungeon (landblock 5768)."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A01AC","place":"dungeon","id":6845,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A0186","place":"dungeon","id":6846,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A01A2","place":"dungeon","id":6847,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A017C","place":"dungeon","id":6848,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A0178","place":"dungeon","id":6849,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A0148","place":"dungeon","id":6850,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A0198","place":"dungeon","id":6851,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A016E","place":"dungeon","id":6852,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A01C5","place":"dungeon","id":6853,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A016A","place":"dungeon","id":6854,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A013D","place":"dungeon","id":6855,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A018E","place":"dungeon","id":6856,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A0160","place":"dungeon","id":6857,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A0208","place":"dungeon","id":6858,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A01C1","place":"dungeon","id":6859,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A0210","place":"dungeon","id":6860,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A01CF","place":"dungeon","id":6861,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A0218","place":"dungeon","id":6862,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A01DD","place":"dungeon","id":6863,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A018A","place":"dungeon","id":6864,"desc":"In Charged Refuge."}, + {"name":"Geraine Bodies Bolt Caster","type":"NPC","wcid":72356,"cell":"576A0153","place":"dungeon","id":6865,"desc":"In Charged Refuge."}, + {"name":"Ancient Altar","type":"NPC","wcid":46443,"cell":"5771039A","place":"dungeon","id":6866,"desc":"In Venerable Mausoleum."}, + {"name":"Tribunal","type":"NPC","wcid":21496,"cell":"584401A0","place":"dungeon","id":6867,"desc":"In Proving Grounds Mid."}, + {"name":"Statue","type":"NPC","wcid":21495,"cell":"584401F4","place":"dungeon","id":6868,"desc":"In Proving Grounds Mid."}, + {"name":"E","type":"NPC","wcid":21502,"cell":"5844019C","place":"dungeon","id":6869,"desc":"In Proving Grounds Mid."}, + {"name":"Darkness","type":"NPC","wcid":21500,"cell":"5844019C","place":"dungeon","id":6870,"desc":"In Proving Grounds Mid."}, + {"name":"Wind","type":"NPC","wcid":21516,"cell":"5844019D","place":"dungeon","id":6871,"desc":"In Proving Grounds Mid."}, + {"name":"Sunlight","type":"NPC","wcid":21513,"cell":"5844019D","place":"dungeon","id":6872,"desc":"In Proving Grounds Mid."}, + {"name":"Nothing","type":"NPC","wcid":21509,"cell":"5844019E","place":"dungeon","id":6873,"desc":"In Proving Grounds Mid."}, + {"name":"Man","type":"NPC","wcid":21507,"cell":"5844019E","place":"dungeon","id":6874,"desc":"In Proving Grounds Mid."}, + {"name":"Stars","type":"NPC","wcid":21512,"cell":"5844019E","place":"dungeon","id":6875,"desc":"In Proving Grounds Mid."}, + {"name":"Silence","type":"NPC","wcid":21511,"cell":"5844019F","place":"dungeon","id":6876,"desc":"In Proving Grounds Mid."}, + {"name":"Coffin","type":"NPC","wcid":21499,"cell":"5844019F","place":"dungeon","id":6877,"desc":"In Proving Grounds Mid."}, + {"name":"Tomorrow","type":"NPC","wcid":21515,"cell":"584401A1","place":"dungeon","id":6878,"desc":"In Proving Grounds Mid."}, + {"name":"Death","type":"NPC","wcid":21501,"cell":"584401A1","place":"dungeon","id":6879,"desc":"In Proving Grounds Mid."}, + {"name":"Bed","type":"NPC","wcid":21497,"cell":"584401A3","place":"dungeon","id":6880,"desc":"In Proving Grounds Mid."}, + {"name":"Eyes","type":"NPC","wcid":21503,"cell":"584401A3","place":"dungeon","id":6881,"desc":"In Proving Grounds Mid."}, + {"name":"Black","type":"NPC","wcid":21498,"cell":"584401A3","place":"dungeon","id":6882,"desc":"In Proving Grounds Mid."}, + {"name":"Hole","type":"NPC","wcid":21505,"cell":"584401A4","place":"dungeon","id":6883,"desc":"In Proving Grounds Mid."}, + {"name":"Flame","type":"NPC","wcid":21504,"cell":"584401A4","place":"dungeon","id":6884,"desc":"In Proving Grounds Mid."}, + {"name":"Mushroom","type":"NPC","wcid":21508,"cell":"584401A5","place":"dungeon","id":6885,"desc":"In Proving Grounds Mid."}, + {"name":"Hope","type":"NPC","wcid":21506,"cell":"584401A5","place":"dungeon","id":6886,"desc":"In Proving Grounds Mid."}, + {"name":"Ring","type":"NPC","wcid":21510,"cell":"584401A5","place":"dungeon","id":6887,"desc":"In Proving Grounds Mid."}, + {"name":"Time","type":"NPC","wcid":21514,"cell":"584401A5","place":"dungeon","id":6888,"desc":"In Proving Grounds Mid."}, + {"name":"Statue","type":"NPC","wcid":21494,"cell":"584401DA","place":"dungeon","id":6889,"desc":"In Proving Grounds Mid."}, + {"name":"Platinum Golem","type":"NPC","wcid":21979,"cell":"584603BA","place":"dungeon","id":6890,"desc":"In Acid Ziggurat."}, + {"name":"Jonas","type":"NPC","wcid":27317,"cell":"58490116","place":"dungeon","id":6891,"desc":"Tusker Captive. In Tusker Assault."}, + {"name":"Security Station","type":"NPC","wcid":46320,"cell":"584D0118","place":"dungeon","id":6892,"desc":"In Frigid Grotto."}, + {"name":"Mouf","type":"NPC","wcid":45853,"cell":"584D012C","place":"dungeon","id":6893,"desc":"In Frigid Grotto."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"584F040D","place":"dungeon","id":6894,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Statue","type":"NPC","wcid":72644,"cell":"584F040B","place":"dungeon","id":6895,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F016B","place":"dungeon","id":6896,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F0197","place":"dungeon","id":6897,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F0132","place":"dungeon","id":6898,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F02C1","place":"dungeon","id":6899,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F0271","place":"dungeon","id":6900,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F0257","place":"dungeon","id":6901,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F02BE","place":"dungeon","id":6902,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F02E0","place":"dungeon","id":6903,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F02E3","place":"dungeon","id":6904,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F02F5","place":"dungeon","id":6905,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F0282","place":"dungeon","id":6906,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Tanada Nanjou Prisoner","type":"NPC","wcid":72678,"cell":"584F025F","place":"dungeon","id":6907,"desc":"In a dungeon (landblock 584F)."}, + {"name":"Platinum Golem","type":"NPC","wcid":46952,"cell":"585103BA","place":"dungeon","id":6908,"desc":"In Prismatic Ziggurat."}, + {"name":"Tribunal","type":"NPC","wcid":21496,"cell":"585201A0","place":"dungeon","id":6909,"desc":"In Proving Grounds Uber."}, + {"name":"Statue","type":"NPC","wcid":21494,"cell":"585201DA","place":"dungeon","id":6910,"desc":"In Proving Grounds Uber."}, + {"name":"Statue","type":"NPC","wcid":21495,"cell":"585201F4","place":"dungeon","id":6911,"desc":"In Proving Grounds Uber."}, + {"name":"E","type":"NPC","wcid":21502,"cell":"5852019C","place":"dungeon","id":6912,"desc":"In Proving Grounds Uber."}, + {"name":"Darkness","type":"NPC","wcid":21500,"cell":"5852019C","place":"dungeon","id":6913,"desc":"In Proving Grounds Uber."}, + {"name":"Wind","type":"NPC","wcid":21516,"cell":"5852019D","place":"dungeon","id":6914,"desc":"In Proving Grounds Uber."}, + {"name":"Sunlight","type":"NPC","wcid":21513,"cell":"5852019D","place":"dungeon","id":6915,"desc":"In Proving Grounds Uber."}, + {"name":"Nothing","type":"NPC","wcid":21509,"cell":"5852019E","place":"dungeon","id":6916,"desc":"In Proving Grounds Uber."}, + {"name":"Man","type":"NPC","wcid":21507,"cell":"5852019E","place":"dungeon","id":6917,"desc":"In Proving Grounds Uber."}, + {"name":"Stars","type":"NPC","wcid":21512,"cell":"5852019E","place":"dungeon","id":6918,"desc":"In Proving Grounds Uber."}, + {"name":"Silence","type":"NPC","wcid":21511,"cell":"5852019F","place":"dungeon","id":6919,"desc":"In Proving Grounds Uber."}, + {"name":"Coffin","type":"NPC","wcid":21499,"cell":"5852019F","place":"dungeon","id":6920,"desc":"In Proving Grounds Uber."}, + {"name":"Tomorrow","type":"NPC","wcid":21515,"cell":"585201A1","place":"dungeon","id":6921,"desc":"In Proving Grounds Uber."}, + {"name":"Death","type":"NPC","wcid":21501,"cell":"585201A1","place":"dungeon","id":6922,"desc":"In Proving Grounds Uber."}, + {"name":"Bed","type":"NPC","wcid":21497,"cell":"585201A3","place":"dungeon","id":6923,"desc":"In Proving Grounds Uber."}, + {"name":"Eyes","type":"NPC","wcid":21503,"cell":"585201A3","place":"dungeon","id":6924,"desc":"In Proving Grounds Uber."}, + {"name":"Black","type":"NPC","wcid":21498,"cell":"585201A3","place":"dungeon","id":6925,"desc":"In Proving Grounds Uber."}, + {"name":"Hole","type":"NPC","wcid":21505,"cell":"585201A4","place":"dungeon","id":6926,"desc":"In Proving Grounds Uber."}, + {"name":"Flame","type":"NPC","wcid":21504,"cell":"585201A4","place":"dungeon","id":6927,"desc":"In Proving Grounds Uber."}, + {"name":"Mushroom","type":"NPC","wcid":21508,"cell":"585201A5","place":"dungeon","id":6928,"desc":"In Proving Grounds Uber."}, + {"name":"Hope","type":"NPC","wcid":21506,"cell":"585201A5","place":"dungeon","id":6929,"desc":"In Proving Grounds Uber."}, + {"name":"Ring","type":"NPC","wcid":21510,"cell":"585201A5","place":"dungeon","id":6930,"desc":"In Proving Grounds Uber."}, + {"name":"Time","type":"NPC","wcid":21514,"cell":"585201A5","place":"dungeon","id":6931,"desc":"In Proving Grounds Uber."}, + {"name":"Gaerlan's Phylacteric Prison","type":"NPC","wcid":46937,"cell":"58540129","place":"dungeon","id":6932,"desc":"In a dungeon (landblock 5854)."}, + {"name":"Mosswart Messenger","type":"NPC","wcid":72970,"cell":"58600195","place":"dungeon","id":6933,"desc":"In Colton Reeyan's Sanctuary."}, + {"name":"Shady's Cage Door","type":"NPC","wcid":72984,"cell":"586002E7","place":"dungeon","id":6934,"desc":"In Colton Reeyan's Sanctuary."}, + {"name":"Shady","type":"NPC","wcid":72974,"cell":"586002DF","place":"dungeon","id":6935,"desc":"In Colton Reeyan's Sanctuary."}, + {"name":"Bubba","type":"NPC","wcid":72976,"cell":"58600197","place":"dungeon","id":6936,"desc":"In Colton Reeyan's Sanctuary."}, + {"name":"Bubba's Cage Door","type":"NPC","wcid":72986,"cell":"5860015C","place":"dungeon","id":6937,"desc":"In Colton Reeyan's Sanctuary."}, + {"name":"Spot's Cage Door","type":"NPC","wcid":72988,"cell":"5860031A","place":"dungeon","id":6938,"desc":"In Colton Reeyan's Sanctuary."}, + {"name":"Spot","type":"NPC","wcid":72978,"cell":"58600321","place":"dungeon","id":6939,"desc":"In Colton Reeyan's Sanctuary."}, + {"name":"Wall of Ice","type":"NPC","wcid":48718,"cell":"58610163","place":"dungeon","id":6940,"desc":"In Crystal Core."}, + {"name":"Wall of Ice","type":"NPC","wcid":48724,"cell":"58610160","place":"dungeon","id":6941,"desc":"In Crystal Core."}, + {"name":"Crystal","type":"NPC","wcid":48717,"cell":"58610164","place":"dungeon","id":6942,"desc":"In Crystal Core."}, + {"name":"Crystal","type":"NPC","wcid":48723,"cell":"5861015C","place":"dungeon","id":6943,"desc":"In Crystal Core."}, + {"name":"Scold","type":"NPC","wcid":48730,"cell":"5861014C","place":"dungeon","id":6944,"desc":"In Crystal Core."}, + {"name":"Grularr Wa'ydo","type":"NPC","wcid":48794,"cell":"58620390","place":"dungeon","id":6945,"desc":"Artifact Collector. In Count Phainor's Tomb."}, + {"name":"Grularr Wa'ydo","type":"NPC","wcid":48795,"cell":"58620187","place":"dungeon","id":6946,"desc":"Artifact Collector. In Count Phainor's Tomb."}, + {"name":"Grularr Wa'ydo","type":"NPC","wcid":48796,"cell":"5862013A","place":"dungeon","id":6947,"desc":"Artifact Collector. In Count Phainor's Tomb."}, + {"name":"Grularr Wa'ydo","type":"NPC","wcid":48797,"cell":"5862010C","place":"dungeon","id":6948,"desc":"Artifact Collector. In Count Phainor's Tomb."}, + {"name":"Statue of Creeping Death","type":"NPC","wcid":48822,"cell":"58630188","place":"dungeon","id":6949,"desc":"In Desert Dwelling."}, + {"name":"Blitzkrieg Statue","type":"NPC","wcid":48821,"cell":"586301A6","place":"dungeon","id":6950,"desc":"In Desert Dwelling."}, + {"name":"Statue of Creeping Death","type":"NPC","wcid":48822,"cell":"586301A7","place":"dungeon","id":6951,"desc":"In Desert Dwelling."}, + {"name":"Statue of Creeping Death","type":"NPC","wcid":48822,"cell":"586301FF","place":"dungeon","id":6952,"desc":"In Desert Dwelling."}, + {"name":"Blitzkrieg Statue","type":"NPC","wcid":48821,"cell":"58630206","place":"dungeon","id":6953,"desc":"In Desert Dwelling."}, + {"name":"Blitzkrieg Statue","type":"NPC","wcid":48821,"cell":"58630227","place":"dungeon","id":6954,"desc":"In Desert Dwelling."}, + {"name":"Blitzkrieg Statue","type":"NPC","wcid":48821,"cell":"58630210","place":"dungeon","id":6955,"desc":"In Desert Dwelling."}, + {"name":"Blitzkrieg Statue","type":"NPC","wcid":48821,"cell":"58630187","place":"dungeon","id":6956,"desc":"In Desert Dwelling."}, + {"name":"Blitzkrieg Statue","type":"NPC","wcid":48821,"cell":"5863019F","place":"dungeon","id":6957,"desc":"In Desert Dwelling."}, + {"name":"Statue of Creeping Death","type":"NPC","wcid":48822,"cell":"586301AF","place":"dungeon","id":6958,"desc":"In Desert Dwelling."}, + {"name":"Statue of Creeping Death","type":"NPC","wcid":48822,"cell":"5863020F","place":"dungeon","id":6959,"desc":"In Desert Dwelling."}, + {"name":"Statue of Creeping Death","type":"NPC","wcid":48822,"cell":"58630215","place":"dungeon","id":6960,"desc":"In Desert Dwelling."}, + {"name":"Blitzkrieg Statue","type":"NPC","wcid":48821,"cell":"58630216","place":"dungeon","id":6961,"desc":"In Desert Dwelling."}, + {"name":"Statue of Creeping Death","type":"NPC","wcid":48822,"cell":"58630233","place":"dungeon","id":6962,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"58630217","place":"dungeon","id":6963,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"58630235","place":"dungeon","id":6964,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"58630225","place":"dungeon","id":6965,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"58630222","place":"dungeon","id":6966,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"5863020E","place":"dungeon","id":6967,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"586301FD","place":"dungeon","id":6968,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"586301EF","place":"dungeon","id":6969,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"586301EB","place":"dungeon","id":6970,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"586301E2","place":"dungeon","id":6971,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"586301DD","place":"dungeon","id":6972,"desc":"In Desert Dwelling."}, + {"name":"Piercing Trap","type":"NPC","wcid":71352,"cell":"586301B5","place":"dungeon","id":6973,"desc":"In Desert Dwelling."}, + {"name":"Piercing Trap","type":"NPC","wcid":71352,"cell":"58630197","place":"dungeon","id":6974,"desc":"In Desert Dwelling."}, + {"name":"Piercing Trap","type":"NPC","wcid":71352,"cell":"5863019A","place":"dungeon","id":6975,"desc":"In Desert Dwelling."}, + {"name":"Piercing Trap","type":"NPC","wcid":71352,"cell":"5863017E","place":"dungeon","id":6976,"desc":"In Desert Dwelling."}, + {"name":"Piercing Trap","type":"NPC","wcid":71352,"cell":"58630193","place":"dungeon","id":6977,"desc":"In Desert Dwelling."}, + {"name":"Piercing Trap","type":"NPC","wcid":71352,"cell":"58630196","place":"dungeon","id":6978,"desc":"In Desert Dwelling."}, + {"name":"Piercing Trap","type":"NPC","wcid":71352,"cell":"5863014E","place":"dungeon","id":6979,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"58630150","place":"dungeon","id":6980,"desc":"In Desert Dwelling."}, + {"name":"Piercing Trap","type":"NPC","wcid":71352,"cell":"58630159","place":"dungeon","id":6981,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"5863015E","place":"dungeon","id":6982,"desc":"In Desert Dwelling."}, + {"name":"Piercing Trap","type":"NPC","wcid":71352,"cell":"58630167","place":"dungeon","id":6983,"desc":"In Desert Dwelling."}, + {"name":"Piercing Trap","type":"NPC","wcid":71352,"cell":"58630128","place":"dungeon","id":6984,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"58630129","place":"dungeon","id":6985,"desc":"In Desert Dwelling."}, + {"name":"Piercing Trap","type":"NPC","wcid":71352,"cell":"58630132","place":"dungeon","id":6986,"desc":"In Desert Dwelling."}, + {"name":"Blade Trap","type":"NPC","wcid":71351,"cell":"58630133","place":"dungeon","id":6987,"desc":"In Desert Dwelling."}, + {"name":"Janthef","type":"NPC","wcid":48814,"cell":"586301D4","place":"dungeon","id":6988,"desc":"In Desert Dwelling."}, + {"name":"Janthef","type":"NPC","wcid":48815,"cell":"5863016F","place":"dungeon","id":6989,"desc":"In Desert Dwelling."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"58640228","place":"dungeon","id":6990,"desc":"In Samurai Hausu."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"586401C5","place":"dungeon","id":6991,"desc":"In Samurai Hausu."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"586401C9","place":"dungeon","id":6992,"desc":"In Samurai Hausu."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"5864022C","place":"dungeon","id":6993,"desc":"In Samurai Hausu."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"586401CC","place":"dungeon","id":6994,"desc":"In Samurai Hausu."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"5864019A","place":"dungeon","id":6995,"desc":"In Samurai Hausu."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"586401D3","place":"dungeon","id":6996,"desc":"In Samurai Hausu."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"5864014B","place":"dungeon","id":6997,"desc":"In Samurai Hausu."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"58640138","place":"dungeon","id":6998,"desc":"In Samurai Hausu."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"5864022F","place":"dungeon","id":6999,"desc":"In Samurai Hausu."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"58640260","place":"dungeon","id":7000,"desc":"In Samurai Hausu."}, + {"name":"Dormant Samurai","type":"NPC","wcid":49522,"cell":"58640236","place":"dungeon","id":7001,"desc":"In Samurai Hausu."}, + {"name":"Lieutenant Karul","type":"NPC","wcid":48921,"cell":"5864011B","place":"dungeon","id":7002,"desc":"Royal Soldier. In Samurai Hausu."}, + {"name":"Altar","type":"NPC","wcid":52259,"cell":"5866012A","place":"dungeon","id":7003,"desc":"In Sanctuary of the Recluse."}, + {"name":"Altar","type":"NPC","wcid":52253,"cell":"58660124","place":"dungeon","id":7004,"desc":"In Sanctuary of the Recluse."}, + {"name":"Lingering Spirit of the Recluse","type":"NPC","wcid":52248,"cell":"58660116","place":"dungeon","id":7005,"desc":"In Sanctuary of the Recluse."}, + {"name":"Maryata bint Daris the Barkeep","type":"NPC","wcid":49648,"cell":"5867010B","place":"dungeon","id":7006,"desc":"Barkeeper. In Virindi Edifice."}, + {"name":"Ruza bint Tinun the Armorer","type":"NPC","wcid":49646,"cell":"5867010B","place":"dungeon","id":7007,"desc":"Armorer. In Virindi Edifice."}, + {"name":"Archmage Sammam al-Ashiz","type":"NPC","wcid":49647,"cell":"5867010B","place":"dungeon","id":7008,"desc":"Archmage. In Virindi Edifice."}, + {"name":"Ulib ibn Ghunir the Weaponsmith","type":"NPC","wcid":49656,"cell":"58670120","place":"dungeon","id":7009,"desc":"Weaponsmith. In Virindi Edifice."}, + {"name":"Tailor Istima al-Mahat","type":"NPC","wcid":49655,"cell":"58670120","place":"dungeon","id":7010,"desc":"Tailor. In Virindi Edifice."}, + {"name":"Waham ibn Fadyat the Shopkeeper","type":"NPC","wcid":49654,"cell":"58670120","place":"dungeon","id":7011,"desc":"Shopkeeper. In Virindi Edifice."}, + {"name":"Barshid al-Juhir the Scribe","type":"NPC","wcid":49653,"cell":"58670120","place":"dungeon","id":7012,"desc":"Scribe. In Virindi Edifice."}, + {"name":"Adraha bint Safsan the Appraiser","type":"NPC","wcid":49652,"cell":"5867011E","place":"dungeon","id":7013,"desc":"Jeweler. In Virindi Edifice."}, + {"name":"Yahr ibn Ajaj the Bowyer","type":"NPC","wcid":49649,"cell":"5867011E","place":"dungeon","id":7014,"desc":"Bowyer. In Virindi Edifice."}, + {"name":"Ziya bint Balun the Grocer","type":"NPC","wcid":49651,"cell":"5867011E","place":"dungeon","id":7015,"desc":"Grocer. In Virindi Edifice."}, + {"name":"Nashima al-Haruq the Healer","type":"NPC","wcid":49650,"cell":"5867011E","place":"dungeon","id":7016,"desc":"Healer. In Virindi Edifice."}, + {"name":"Curator of Torment","type":"NPC","wcid":49639,"cell":"58670140","place":"dungeon","id":7017,"desc":"In Virindi Edifice."}, + {"name":"Town Crier","type":"NPC","wcid":49642,"cell":"58670140","place":"dungeon","id":7018,"desc":"Herald. In Virindi Edifice."}, + {"name":"Virindi Delegate","type":"NPC","wcid":49638,"cell":"58670106","place":"dungeon","id":7019,"desc":"In Virindi Edifice."}, + {"name":"Grub Test Stopgap","type":"NPC","wcid":72450,"cell":"586A0115","place":"dungeon","id":7020,"desc":"Stopgap. In a dungeon (landblock 586A)."}, + {"name":"Virindi Delegate","type":"NPC","wcid":51208,"cell":"586B0107","place":"dungeon","id":7021,"desc":"In a dungeon (landblock 586B)."}, + {"name":"Virindi Delegate","type":"NPC","wcid":51298,"cell":"586C01D2","place":"dungeon","id":7022,"desc":"In Masked Preface."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72173,"cell":"586E0107","place":"dungeon","id":7023,"desc":"In Hive Warrior Mound."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72173,"cell":"586E010A","place":"dungeon","id":7024,"desc":"In Hive Warrior Mound."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72173,"cell":"586E02B9","place":"dungeon","id":7025,"desc":"In Hive Warrior Mound."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72173,"cell":"586E0477","place":"dungeon","id":7026,"desc":"In Hive Warrior Mound."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72173,"cell":"586E0470","place":"dungeon","id":7027,"desc":"In Hive Warrior Mound."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72173,"cell":"586E02B6","place":"dungeon","id":7028,"desc":"In Hive Warrior Mound."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72173,"cell":"586E0379","place":"dungeon","id":7029,"desc":"In Hive Warrior Mound."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72173,"cell":"586E0364","place":"dungeon","id":7030,"desc":"In Hive Warrior Mound."}, + {"name":"Aun Siminua","type":"NPC","wcid":51378,"cell":"58700106","place":"dungeon","id":7031,"desc":"In Curator of Torment's Study."}, + {"name":"Kul Bronzegear","type":"NPC","wcid":51379,"cell":"5870010B","place":"dungeon","id":7032,"desc":"In Curator of Torment's Study."}, + {"name":"Oggma","type":"NPC","wcid":51377,"cell":"58700113","place":"dungeon","id":7033,"desc":"In Curator of Torment's Study."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72166,"cell":"58700197","place":"dungeon","id":7034,"desc":"In Curator of Torment's Study."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72166,"cell":"58700195","place":"dungeon","id":7035,"desc":"In Curator of Torment's Study."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72166,"cell":"58700297","place":"dungeon","id":7036,"desc":"In Curator of Torment's Study."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72166,"cell":"58700295","place":"dungeon","id":7037,"desc":"In Curator of Torment's Study."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72166,"cell":"58700377","place":"dungeon","id":7038,"desc":"In Curator of Torment's Study."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72166,"cell":"5870035B","place":"dungeon","id":7039,"desc":"In Curator of Torment's Study."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72166,"cell":"58700183","place":"dungeon","id":7040,"desc":"In Curator of Torment's Study."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72166,"cell":"58700185","place":"dungeon","id":7041,"desc":"In Curator of Torment's Study."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72166,"cell":"58700290","place":"dungeon","id":7042,"desc":"In Curator of Torment's Study."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72166,"cell":"5870028E","place":"dungeon","id":7043,"desc":"In Curator of Torment's Study."}, + {"name":"Door","type":"NPC","wcid":51575,"cell":"5872017E","place":"dungeon","id":7044,"desc":"In Seed of Misery."}, + {"name":"Mysterious Portal","type":"NPC","wcid":51603,"cell":"58740197","place":"dungeon","id":7045,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Anomaly","type":"NPC","wcid":72120,"cell":"5874015B","place":"dungeon","id":7046,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Anomaly","type":"NPC","wcid":72120,"cell":"58740182","place":"dungeon","id":7047,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Anomaly","type":"NPC","wcid":72120,"cell":"587401A1","place":"dungeon","id":7048,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Anomaly","type":"NPC","wcid":72120,"cell":"587401A5","place":"dungeon","id":7049,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Anomaly","type":"NPC","wcid":72120,"cell":"58740186","place":"dungeon","id":7050,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Anomaly","type":"NPC","wcid":72120,"cell":"5874015F","place":"dungeon","id":7051,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"587401C1","place":"dungeon","id":7052,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"587401BF","place":"dungeon","id":7053,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"587401B2","place":"dungeon","id":7054,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"587401B4","place":"dungeon","id":7055,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"587401A0","place":"dungeon","id":7056,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"5874019E","place":"dungeon","id":7057,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"5874017F","place":"dungeon","id":7058,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"5874016A","place":"dungeon","id":7059,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"5874014C","place":"dungeon","id":7060,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"5874014E","place":"dungeon","id":7061,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"5874016C","place":"dungeon","id":7062,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Lightning Cloud","type":"NPC","wcid":72122,"cell":"58740181","place":"dungeon","id":7063,"desc":"In a dungeon (landblock 5874)."}, + {"name":"Pile of Spare Parts","type":"NPC","wcid":51672,"cell":"58760100","place":"dungeon","id":7064,"desc":"In Rynthid Foundry."}, + {"name":"Aetherium Ore","type":"NPC","wcid":51655,"cell":"5876019E","place":"dungeon","id":7065,"desc":"In Rynthid Foundry."}, + {"name":"Aetherium Ore","type":"NPC","wcid":51656,"cell":"5876015A","place":"dungeon","id":7066,"desc":"In Rynthid Foundry."}, + {"name":"Aetherium Ore","type":"NPC","wcid":51657,"cell":"5876010B","place":"dungeon","id":7067,"desc":"In Rynthid Foundry."}, + {"name":"Dread Figment","type":"NPC","wcid":51693,"cell":"58770252","place":"dungeon","id":7068,"desc":"In Fear Factory."}, + {"name":"Dread Figment","type":"NPC","wcid":51693,"cell":"587702C3","place":"dungeon","id":7069,"desc":"In Fear Factory."}, + {"name":"Dread Figment","type":"NPC","wcid":51693,"cell":"587702F6","place":"dungeon","id":7070,"desc":"In Fear Factory."}, + {"name":"Dread Figment","type":"NPC","wcid":51693,"cell":"587702AF","place":"dungeon","id":7071,"desc":"In Fear Factory."}, + {"name":"Dread Figment","type":"NPC","wcid":51693,"cell":"587701B3","place":"dungeon","id":7072,"desc":"In Fear Factory."}, + {"name":"Dread Figment","type":"NPC","wcid":51693,"cell":"58770152","place":"dungeon","id":7073,"desc":"In Fear Factory."}, + {"name":"Dread Figment","type":"NPC","wcid":51693,"cell":"58770171","place":"dungeon","id":7074,"desc":"In Fear Factory."}, + {"name":"Dread Figment","type":"NPC","wcid":51693,"cell":"5877026A","place":"dungeon","id":7075,"desc":"In Fear Factory."}, + {"name":"Dread Figment","type":"NPC","wcid":51693,"cell":"58770253","place":"dungeon","id":7076,"desc":"In Fear Factory."}, + {"name":"Sapphire Annex","type":"NPC","wcid":51773,"cell":"5878015D","place":"dungeon","id":7077,"desc":"In Spirited Halls."}, + {"name":"Ruby Annex","type":"NPC","wcid":51774,"cell":"58780155","place":"dungeon","id":7078,"desc":"In Spirited Halls."}, + {"name":"Jade Annex","type":"NPC","wcid":51775,"cell":"58780161","place":"dungeon","id":7079,"desc":"In Spirited Halls."}, + {"name":"Amethyst Annex","type":"NPC","wcid":51776,"cell":"58780159","place":"dungeon","id":7080,"desc":"In Spirited Halls."}, + {"name":"Spirit of Anguish","type":"NPC","wcid":72099,"cell":"5878012E","place":"dungeon","id":7081,"desc":"In Spirited Halls."}, + {"name":"Spirit of Anguish","type":"NPC","wcid":72099,"cell":"58780128","place":"dungeon","id":7082,"desc":"In Spirited Halls."}, + {"name":"Spirit of Anguish","type":"NPC","wcid":72099,"cell":"58780120","place":"dungeon","id":7083,"desc":"In Spirited Halls."}, + {"name":"Spirit of Anguish","type":"NPC","wcid":72100,"cell":"5878010F","place":"dungeon","id":7084,"desc":"In Spirited Halls."}, + {"name":"Spirit of Anguish","type":"NPC","wcid":72100,"cell":"58780110","place":"dungeon","id":7085,"desc":"In Spirited Halls."}, + {"name":"Spirit of Anguish","type":"NPC","wcid":72101,"cell":"58780108","place":"dungeon","id":7086,"desc":"In Spirited Halls."}, + {"name":"Spirit of Anguish","type":"NPC","wcid":72102,"cell":"5878011F","place":"dungeon","id":7087,"desc":"In Spirited Halls."}, + {"name":"Spirit of Anguish","type":"NPC","wcid":72102,"cell":"58780127","place":"dungeon","id":7088,"desc":"In Spirited Halls."}, + {"name":"Spirit of Anguish","type":"NPC","wcid":72101,"cell":"5878010C","place":"dungeon","id":7089,"desc":"In Spirited Halls."}, + {"name":"Spirit of Anguish","type":"NPC","wcid":72102,"cell":"5878012D","place":"dungeon","id":7090,"desc":"In Spirited Halls."}, + {"name":"Spirit of Anguish","type":"NPC","wcid":72100,"cell":"58780111","place":"dungeon","id":7091,"desc":"In Spirited Halls."}, + {"name":"Corrupted Crystal of Torments","type":"NPC","wcid":51887,"cell":"587904BE","place":"dungeon","id":7092,"desc":"In Path of Sorrows."}, + {"name":"Corrupted Crystal of Rage","type":"NPC","wcid":72130,"cell":"587902D9","place":"dungeon","id":7093,"desc":"In Path of Sorrows."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A0249","place":"dungeon","id":7094,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A024F","place":"dungeon","id":7095,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A0247","place":"dungeon","id":7096,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52086,"cell":"587A0244","place":"dungeon","id":7097,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A0243","place":"dungeon","id":7098,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A0241","place":"dungeon","id":7099,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A0237","place":"dungeon","id":7100,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52086,"cell":"587A0235","place":"dungeon","id":7101,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A0224","place":"dungeon","id":7102,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A022B","place":"dungeon","id":7103,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A0215","place":"dungeon","id":7104,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A021B","place":"dungeon","id":7105,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52084,"cell":"587A01D1","place":"dungeon","id":7106,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52086,"cell":"587A01C4","place":"dungeon","id":7107,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52084,"cell":"587A01AC","place":"dungeon","id":7108,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A018B","place":"dungeon","id":7109,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52084,"cell":"587A0195","place":"dungeon","id":7110,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52084,"cell":"587A0180","place":"dungeon","id":7111,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A018A","place":"dungeon","id":7112,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A0199","place":"dungeon","id":7113,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52084,"cell":"587A0198","place":"dungeon","id":7114,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52084,"cell":"587A01A0","place":"dungeon","id":7115,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A019F","place":"dungeon","id":7116,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52084,"cell":"587A01B0","place":"dungeon","id":7117,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A01B9","place":"dungeon","id":7118,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52086,"cell":"587A01B3","place":"dungeon","id":7119,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52084,"cell":"587A01C7","place":"dungeon","id":7120,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A01BC","place":"dungeon","id":7121,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52086,"cell":"587A01D3","place":"dungeon","id":7122,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52084,"cell":"587A01D8","place":"dungeon","id":7123,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A0207","place":"dungeon","id":7124,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52086,"cell":"587A0208","place":"dungeon","id":7125,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Training Dummy","type":"NPC","wcid":52085,"cell":"587A0206","place":"dungeon","id":7126,"desc":"In a dungeon (landblock 587A)."}, + {"name":"Tribunal","type":"NPC","wcid":21496,"cell":"594401A0","place":"dungeon","id":7127,"desc":"In Proving Grounds High."}, + {"name":"Wind","type":"NPC","wcid":21516,"cell":"5944019D","place":"dungeon","id":7128,"desc":"In Proving Grounds High."}, + {"name":"Nothing","type":"NPC","wcid":21509,"cell":"5944019E","place":"dungeon","id":7129,"desc":"In Proving Grounds High."}, + {"name":"Man","type":"NPC","wcid":21507,"cell":"5944019E","place":"dungeon","id":7130,"desc":"In Proving Grounds High."}, + {"name":"Stars","type":"NPC","wcid":21512,"cell":"5944019E","place":"dungeon","id":7131,"desc":"In Proving Grounds High."}, + {"name":"Flame","type":"NPC","wcid":21504,"cell":"594401A4","place":"dungeon","id":7132,"desc":"In Proving Grounds High."}, + {"name":"Bed","type":"NPC","wcid":21497,"cell":"594401A3","place":"dungeon","id":7133,"desc":"In Proving Grounds High."}, + {"name":"Eyes","type":"NPC","wcid":21503,"cell":"594401A3","place":"dungeon","id":7134,"desc":"In Proving Grounds High."}, + {"name":"Black","type":"NPC","wcid":21498,"cell":"594401A3","place":"dungeon","id":7135,"desc":"In Proving Grounds High."}, + {"name":"Tomorrow","type":"NPC","wcid":21515,"cell":"594401A1","place":"dungeon","id":7136,"desc":"In Proving Grounds High."}, + {"name":"Death","type":"NPC","wcid":21501,"cell":"594401A1","place":"dungeon","id":7137,"desc":"In Proving Grounds High."}, + {"name":"Mushroom","type":"NPC","wcid":21508,"cell":"594401A5","place":"dungeon","id":7138,"desc":"In Proving Grounds High."}, + {"name":"Hope","type":"NPC","wcid":21506,"cell":"594401A5","place":"dungeon","id":7139,"desc":"In Proving Grounds High."}, + {"name":"Ring","type":"NPC","wcid":21510,"cell":"594401A5","place":"dungeon","id":7140,"desc":"In Proving Grounds High."}, + {"name":"E","type":"NPC","wcid":21502,"cell":"5944019C","place":"dungeon","id":7141,"desc":"In Proving Grounds High."}, + {"name":"Hole","type":"NPC","wcid":21505,"cell":"594401A4","place":"dungeon","id":7142,"desc":"In Proving Grounds High."}, + {"name":"Statue","type":"NPC","wcid":21495,"cell":"594401F4","place":"dungeon","id":7143,"desc":"In Proving Grounds High."}, + {"name":"Darkness","type":"NPC","wcid":21500,"cell":"5944019C","place":"dungeon","id":7144,"desc":"In Proving Grounds High."}, + {"name":"Sunlight","type":"NPC","wcid":21513,"cell":"5944019D","place":"dungeon","id":7145,"desc":"In Proving Grounds High."}, + {"name":"Silence","type":"NPC","wcid":21511,"cell":"5944019F","place":"dungeon","id":7146,"desc":"In Proving Grounds High."}, + {"name":"Coffin","type":"NPC","wcid":21499,"cell":"5944019F","place":"dungeon","id":7147,"desc":"In Proving Grounds High."}, + {"name":"Time","type":"NPC","wcid":21514,"cell":"594401A5","place":"dungeon","id":7148,"desc":"In Proving Grounds High."}, + {"name":"Statue","type":"NPC","wcid":21494,"cell":"594401DA","place":"dungeon","id":7149,"desc":"In Proving Grounds High."}, + {"name":"Platinum Golem","type":"NPC","wcid":21980,"cell":"594603BA","place":"dungeon","id":7150,"desc":"In Fire Ziggurat."}, + {"name":"Magically Sealed Dais","type":"NPC","wcid":25375,"cell":"594B0166","place":"dungeon","id":7151,"desc":"In Aerbax's Holding."}, + {"name":"Representative of the Singularity","type":"NPC","wcid":25388,"cell":"594C0242","place":"dungeon","id":7152,"desc":"In Gerent's Compound."}, + {"name":"Living Tome","type":"NPC","wcid":25387,"cell":"594D0113","place":"dungeon","id":7153,"desc":"In Ancient Temple."}, + {"name":"Apparition of the Book of Eibhil","type":"NPC","wcid":45835,"cell":"594E048D","place":"dungeon","id":7154,"desc":"In Deep Caves."}, + {"name":"Apparition of the Book of Eibhil","type":"NPC","wcid":45835,"cell":"594E0232","place":"dungeon","id":7155,"desc":"In Deep Caves."}, + {"name":"Guardian Spirit","type":"NPC","wcid":44473,"cell":"594E0602","place":"dungeon","id":7156,"desc":"Guardian of the Deru. In Deep Caves."}, + {"name":"Apparition of Lady Daenerah","type":"NPC","wcid":45818,"cell":"594E05A3","place":"dungeon","id":7157,"desc":"Royal Knight Mage. In Deep Caves."}, + {"name":"Apparition of Borelean Strathelar","type":"NPC","wcid":45771,"cell":"594E05A3","place":"dungeon","id":7158,"desc":"Prince of New Aluvia. In Deep Caves."}, + {"name":"Apparition of Hoshino Kei","type":"NPC","wcid":45776,"cell":"594E052E","place":"dungeon","id":7159,"desc":"Princess of New Aluvia. In Deep Caves."}, + {"name":"Apparition of Borelean Strathelar","type":"NPC","wcid":45772,"cell":"594E052E","place":"dungeon","id":7160,"desc":"Prince of New Aluvia. In Deep Caves."}, + {"name":"Apparition of Hoshino Kei","type":"NPC","wcid":45776,"cell":"594E04CA","place":"dungeon","id":7161,"desc":"Princess of New Aluvia. In Deep Caves."}, + {"name":"Apparition of Borelean Strathelar","type":"NPC","wcid":45773,"cell":"594E04CA","place":"dungeon","id":7162,"desc":"Prince of New Aluvia. In Deep Caves."}, + {"name":"Apparition of Hoshino Kei","type":"NPC","wcid":45776,"cell":"594E048D","place":"dungeon","id":7163,"desc":"Princess of New Aluvia. In Deep Caves."}, + {"name":"Apparition of Borelean Strathelar","type":"NPC","wcid":45774,"cell":"594E048D","place":"dungeon","id":7164,"desc":"Prince of New Aluvia. In Deep Caves."}, + {"name":"Apparition of Hoshino Kei","type":"NPC","wcid":45776,"cell":"594E0232","place":"dungeon","id":7165,"desc":"Princess of New Aluvia. In Deep Caves."}, + {"name":"Apparition of Borelean Strathelar","type":"NPC","wcid":45775,"cell":"594E0232","place":"dungeon","id":7166,"desc":"Prince of New Aluvia. In Deep Caves."}, + {"name":"Avatar of the Deru","type":"NPC","wcid":44472,"cell":"594E0104","place":"dungeon","id":7167,"desc":"In Deep Caves."}, + {"name":"Prototype Bloodstone","type":"NPC","wcid":51365,"cell":"594F021C","place":"dungeon","id":7168,"desc":"In Frozen Fortress."}, + {"name":"Commander Presk","type":"NPC","wcid":51897,"cell":"59510107","place":"dungeon","id":7169,"desc":"In Presk's Bunker."}, + {"name":"White Lever","type":"NPC","wcid":52075,"cell":"59530181","place":"dungeon","id":7170,"desc":"In a dungeon (landblock 5953)."}, + {"name":"Green Lever","type":"NPC","wcid":52072,"cell":"59530181","place":"dungeon","id":7171,"desc":"In a dungeon (landblock 5953)."}, + {"name":"Red Lever","type":"NPC","wcid":52088,"cell":"59530185","place":"dungeon","id":7172,"desc":"In a dungeon (landblock 5953)."}, + {"name":"Orange Lever","type":"NPC","wcid":52074,"cell":"59530185","place":"dungeon","id":7173,"desc":"In a dungeon (landblock 5953)."}, + {"name":"Blue Lever","type":"NPC","wcid":52071,"cell":"59530188","place":"dungeon","id":7174,"desc":"In a dungeon (landblock 5953)."}, + {"name":"Yellow Lever","type":"NPC","wcid":52076,"cell":"59530188","place":"dungeon","id":7175,"desc":"In a dungeon (landblock 5953)."}, + {"name":"Rynthid Assessment Crystal","type":"NPC","wcid":52078,"cell":"5953017E","place":"dungeon","id":7176,"desc":"In a dungeon (landblock 5953)."}, + {"name":"Celestial Hand Officer","type":"NPC","wcid":52266,"cell":"5960012D","place":"dungeon","id":7177,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Officer","type":"NPC","wcid":52266,"cell":"5960012A","place":"dungeon","id":7178,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59600145","place":"dungeon","id":7179,"desc":"Society Gauntlet Master. In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"5960012E","place":"dungeon","id":7180,"desc":"Society Gauntlet Master. In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59600146","place":"dungeon","id":7181,"desc":"Society Gauntlet Master. In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59600144","place":"dungeon","id":7182,"desc":"Society Gauntlet Master. In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"5960012C","place":"dungeon","id":7183,"desc":"Society Gauntlet Master. In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59600142","place":"dungeon","id":7184,"desc":"Society Gauntlet Master. In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"5960012B","place":"dungeon","id":7185,"desc":"Society Gauntlet Master. In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59600143","place":"dungeon","id":7186,"desc":"Society Gauntlet Master. In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59600141","place":"dungeon","id":7187,"desc":"Society Gauntlet Master. In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59600129","place":"dungeon","id":7188,"desc":"Society Gauntlet Master. In a dungeon (landblock 5960)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5960011D","place":"dungeon","id":7189,"desc":"In a dungeon (landblock 5960)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5960011A","place":"dungeon","id":7190,"desc":"In a dungeon (landblock 5960)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59600122","place":"dungeon","id":7191,"desc":"In a dungeon (landblock 5960)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5960011F","place":"dungeon","id":7192,"desc":"In a dungeon (landblock 5960)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5960011C","place":"dungeon","id":7193,"desc":"In a dungeon (landblock 5960)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59600124","place":"dungeon","id":7194,"desc":"In a dungeon (landblock 5960)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59600125","place":"dungeon","id":7195,"desc":"In a dungeon (landblock 5960)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"5960011B","place":"dungeon","id":7196,"desc":"In a dungeon (landblock 5960)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59600123","place":"dungeon","id":7197,"desc":"In a dungeon (landblock 5960)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59600120","place":"dungeon","id":7198,"desc":"In a dungeon (landblock 5960)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59600128","place":"dungeon","id":7199,"desc":"In a dungeon (landblock 5960)."}, + {"name":"Celestial Hand Officer","type":"NPC","wcid":52266,"cell":"5961012D","place":"dungeon","id":7200,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5961)."}, + {"name":"Celestial Hand Officer","type":"NPC","wcid":52266,"cell":"5961012A","place":"dungeon","id":7201,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5961)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59610145","place":"dungeon","id":7202,"desc":"Society Gauntlet Master. In a dungeon (landblock 5961)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"5961012E","place":"dungeon","id":7203,"desc":"Society Gauntlet Master. In a dungeon (landblock 5961)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59610146","place":"dungeon","id":7204,"desc":"Society Gauntlet Master. In a dungeon (landblock 5961)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59610144","place":"dungeon","id":7205,"desc":"Society Gauntlet Master. In a dungeon (landblock 5961)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"5961012C","place":"dungeon","id":7206,"desc":"Society Gauntlet Master. In a dungeon (landblock 5961)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59610142","place":"dungeon","id":7207,"desc":"Society Gauntlet Master. In a dungeon (landblock 5961)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"5961012B","place":"dungeon","id":7208,"desc":"Society Gauntlet Master. In a dungeon (landblock 5961)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59610143","place":"dungeon","id":7209,"desc":"Society Gauntlet Master. In a dungeon (landblock 5961)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59610141","place":"dungeon","id":7210,"desc":"Society Gauntlet Master. In a dungeon (landblock 5961)."}, + {"name":"Celestial Hand Warrior","type":"NPC","wcid":52265,"cell":"59610129","place":"dungeon","id":7211,"desc":"Society Gauntlet Master. In a dungeon (landblock 5961)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5961011D","place":"dungeon","id":7212,"desc":"In a dungeon (landblock 5961)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5961011A","place":"dungeon","id":7213,"desc":"In a dungeon (landblock 5961)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59610122","place":"dungeon","id":7214,"desc":"In a dungeon (landblock 5961)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5961011F","place":"dungeon","id":7215,"desc":"In a dungeon (landblock 5961)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5961011C","place":"dungeon","id":7216,"desc":"In a dungeon (landblock 5961)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59610124","place":"dungeon","id":7217,"desc":"In a dungeon (landblock 5961)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59610125","place":"dungeon","id":7218,"desc":"In a dungeon (landblock 5961)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"5961011B","place":"dungeon","id":7219,"desc":"In a dungeon (landblock 5961)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59610123","place":"dungeon","id":7220,"desc":"In a dungeon (landblock 5961)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59610120","place":"dungeon","id":7221,"desc":"In a dungeon (landblock 5961)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59610128","place":"dungeon","id":7222,"desc":"In a dungeon (landblock 5961)."}, + {"name":"Eldrytch Web Officer","type":"NPC","wcid":87994,"cell":"5962012D","place":"dungeon","id":7223,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Officer","type":"NPC","wcid":87994,"cell":"5962012A","place":"dungeon","id":7224,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59620145","place":"dungeon","id":7225,"desc":"Society Gauntlet Master. In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"5962012E","place":"dungeon","id":7226,"desc":"Society Gauntlet Master. In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59620146","place":"dungeon","id":7227,"desc":"Society Gauntlet Master. In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59620144","place":"dungeon","id":7228,"desc":"Society Gauntlet Master. In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"5962012C","place":"dungeon","id":7229,"desc":"Society Gauntlet Master. In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59620142","place":"dungeon","id":7230,"desc":"Society Gauntlet Master. In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"5962012B","place":"dungeon","id":7231,"desc":"Society Gauntlet Master. In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59620143","place":"dungeon","id":7232,"desc":"Society Gauntlet Master. In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59620141","place":"dungeon","id":7233,"desc":"Society Gauntlet Master. In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59620129","place":"dungeon","id":7234,"desc":"Society Gauntlet Master. In a dungeon (landblock 5962)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5962011D","place":"dungeon","id":7235,"desc":"In a dungeon (landblock 5962)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5962011A","place":"dungeon","id":7236,"desc":"In a dungeon (landblock 5962)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59620122","place":"dungeon","id":7237,"desc":"In a dungeon (landblock 5962)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5962011F","place":"dungeon","id":7238,"desc":"In a dungeon (landblock 5962)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5962011C","place":"dungeon","id":7239,"desc":"In a dungeon (landblock 5962)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59620124","place":"dungeon","id":7240,"desc":"In a dungeon (landblock 5962)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59620125","place":"dungeon","id":7241,"desc":"In a dungeon (landblock 5962)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"5962011B","place":"dungeon","id":7242,"desc":"In a dungeon (landblock 5962)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59620123","place":"dungeon","id":7243,"desc":"In a dungeon (landblock 5962)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59620120","place":"dungeon","id":7244,"desc":"In a dungeon (landblock 5962)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59620128","place":"dungeon","id":7245,"desc":"In a dungeon (landblock 5962)."}, + {"name":"Eldrytch Web Officer","type":"NPC","wcid":87994,"cell":"5963012D","place":"dungeon","id":7246,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5963)."}, + {"name":"Eldrytch Web Officer","type":"NPC","wcid":87994,"cell":"5963012A","place":"dungeon","id":7247,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5963)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59630145","place":"dungeon","id":7248,"desc":"Society Gauntlet Master. In a dungeon (landblock 5963)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"5963012E","place":"dungeon","id":7249,"desc":"Society Gauntlet Master. In a dungeon (landblock 5963)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59630146","place":"dungeon","id":7250,"desc":"Society Gauntlet Master. In a dungeon (landblock 5963)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59630144","place":"dungeon","id":7251,"desc":"Society Gauntlet Master. In a dungeon (landblock 5963)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"5963012C","place":"dungeon","id":7252,"desc":"Society Gauntlet Master. In a dungeon (landblock 5963)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59630142","place":"dungeon","id":7253,"desc":"Society Gauntlet Master. In a dungeon (landblock 5963)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"5963012B","place":"dungeon","id":7254,"desc":"Society Gauntlet Master. In a dungeon (landblock 5963)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59630143","place":"dungeon","id":7255,"desc":"Society Gauntlet Master. In a dungeon (landblock 5963)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59630141","place":"dungeon","id":7256,"desc":"Society Gauntlet Master. In a dungeon (landblock 5963)."}, + {"name":"Eldrytch Web Warrior","type":"NPC","wcid":87993,"cell":"59630129","place":"dungeon","id":7257,"desc":"Society Gauntlet Master. In a dungeon (landblock 5963)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5963011D","place":"dungeon","id":7258,"desc":"In a dungeon (landblock 5963)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5963011A","place":"dungeon","id":7259,"desc":"In a dungeon (landblock 5963)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59630122","place":"dungeon","id":7260,"desc":"In a dungeon (landblock 5963)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5963011F","place":"dungeon","id":7261,"desc":"In a dungeon (landblock 5963)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5963011C","place":"dungeon","id":7262,"desc":"In a dungeon (landblock 5963)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59630124","place":"dungeon","id":7263,"desc":"In a dungeon (landblock 5963)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59630125","place":"dungeon","id":7264,"desc":"In a dungeon (landblock 5963)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"5963011B","place":"dungeon","id":7265,"desc":"In a dungeon (landblock 5963)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59630123","place":"dungeon","id":7266,"desc":"In a dungeon (landblock 5963)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59630120","place":"dungeon","id":7267,"desc":"In a dungeon (landblock 5963)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59630128","place":"dungeon","id":7268,"desc":"In a dungeon (landblock 5963)."}, + {"name":"Radiant Blood Officer","type":"NPC","wcid":52960,"cell":"5964012D","place":"dungeon","id":7269,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Officer","type":"NPC","wcid":52960,"cell":"5964012A","place":"dungeon","id":7270,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59640145","place":"dungeon","id":7271,"desc":"Society Gauntlet Master. In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"5964012E","place":"dungeon","id":7272,"desc":"Society Gauntlet Master. In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59640146","place":"dungeon","id":7273,"desc":"Society Gauntlet Master. In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59640144","place":"dungeon","id":7274,"desc":"Society Gauntlet Master. In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"5964012C","place":"dungeon","id":7275,"desc":"Society Gauntlet Master. In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59640142","place":"dungeon","id":7276,"desc":"Society Gauntlet Master. In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"5964012B","place":"dungeon","id":7277,"desc":"Society Gauntlet Master. In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59640143","place":"dungeon","id":7278,"desc":"Society Gauntlet Master. In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59640141","place":"dungeon","id":7279,"desc":"Society Gauntlet Master. In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59640129","place":"dungeon","id":7280,"desc":"Society Gauntlet Master. In a dungeon (landblock 5964)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5964011D","place":"dungeon","id":7281,"desc":"In a dungeon (landblock 5964)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5964011A","place":"dungeon","id":7282,"desc":"In a dungeon (landblock 5964)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59640122","place":"dungeon","id":7283,"desc":"In a dungeon (landblock 5964)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5964011F","place":"dungeon","id":7284,"desc":"In a dungeon (landblock 5964)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5964011C","place":"dungeon","id":7285,"desc":"In a dungeon (landblock 5964)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59640124","place":"dungeon","id":7286,"desc":"In a dungeon (landblock 5964)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59640125","place":"dungeon","id":7287,"desc":"In a dungeon (landblock 5964)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"5964011B","place":"dungeon","id":7288,"desc":"In a dungeon (landblock 5964)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59640123","place":"dungeon","id":7289,"desc":"In a dungeon (landblock 5964)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59640120","place":"dungeon","id":7290,"desc":"In a dungeon (landblock 5964)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59640128","place":"dungeon","id":7291,"desc":"In a dungeon (landblock 5964)."}, + {"name":"Radiant Blood Officer","type":"NPC","wcid":52960,"cell":"5965012D","place":"dungeon","id":7292,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5965)."}, + {"name":"Radiant Blood Officer","type":"NPC","wcid":52960,"cell":"5965012A","place":"dungeon","id":7293,"desc":"Society Gauntlet Officer. In a dungeon (landblock 5965)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59650145","place":"dungeon","id":7294,"desc":"Society Gauntlet Master. In a dungeon (landblock 5965)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"5965012E","place":"dungeon","id":7295,"desc":"Society Gauntlet Master. In a dungeon (landblock 5965)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59650146","place":"dungeon","id":7296,"desc":"Society Gauntlet Master. In a dungeon (landblock 5965)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59650144","place":"dungeon","id":7297,"desc":"Society Gauntlet Master. In a dungeon (landblock 5965)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"5965012C","place":"dungeon","id":7298,"desc":"Society Gauntlet Master. In a dungeon (landblock 5965)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59650142","place":"dungeon","id":7299,"desc":"Society Gauntlet Master. In a dungeon (landblock 5965)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"5965012B","place":"dungeon","id":7300,"desc":"Society Gauntlet Master. In a dungeon (landblock 5965)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59650143","place":"dungeon","id":7301,"desc":"Society Gauntlet Master. In a dungeon (landblock 5965)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59650141","place":"dungeon","id":7302,"desc":"Society Gauntlet Master. In a dungeon (landblock 5965)."}, + {"name":"Radiant Blood Warrior","type":"NPC","wcid":52961,"cell":"59650129","place":"dungeon","id":7303,"desc":"Society Gauntlet Master. In a dungeon (landblock 5965)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5965011D","place":"dungeon","id":7304,"desc":"In a dungeon (landblock 5965)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5965011A","place":"dungeon","id":7305,"desc":"In a dungeon (landblock 5965)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59650122","place":"dungeon","id":7306,"desc":"In a dungeon (landblock 5965)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5965011F","place":"dungeon","id":7307,"desc":"In a dungeon (landblock 5965)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"5965011C","place":"dungeon","id":7308,"desc":"In a dungeon (landblock 5965)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59650124","place":"dungeon","id":7309,"desc":"In a dungeon (landblock 5965)."}, + {"name":"Inferno","type":"NPC","wcid":87882,"cell":"59650125","place":"dungeon","id":7310,"desc":"In a dungeon (landblock 5965)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"5965011B","place":"dungeon","id":7311,"desc":"In a dungeon (landblock 5965)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59650123","place":"dungeon","id":7312,"desc":"In a dungeon (landblock 5965)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59650120","place":"dungeon","id":7313,"desc":"In a dungeon (landblock 5965)."}, + {"name":"Inferno","type":"NPC","wcid":87889,"cell":"59650128","place":"dungeon","id":7314,"desc":"In a dungeon (landblock 5965)."}, + {"name":"Portal Out to Viridian Chasm","type":"NPC","wcid":53246,"cell":"5966010D","place":"dungeon","id":7315,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Corrupted Statue","type":"NPC","wcid":72178,"cell":"596601D9","place":"dungeon","id":7316,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Vvermurgor","type":"NPC","wcid":72179,"cell":"596601CD","place":"dungeon","id":7317,"desc":"Voice of the Shadow. In a dungeon (landblock 5966)."}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":70853,"cell":"5966014C","place":"dungeon","id":7318,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":70853,"cell":"59660119","place":"dungeon","id":7319,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":70853,"cell":"59660265","place":"dungeon","id":7320,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":70853,"cell":"59660272","place":"dungeon","id":7321,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":70856,"cell":"5966024E","place":"dungeon","id":7322,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":70854,"cell":"59660132","place":"dungeon","id":7323,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":53243,"cell":"5966016E","place":"dungeon","id":7324,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":70852,"cell":"596601A7","place":"dungeon","id":7325,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":70855,"cell":"5966015C","place":"dungeon","id":7326,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":70857,"cell":"59660216","place":"dungeon","id":7327,"desc":"In a dungeon (landblock 5966)."}, + {"name":"Zabien","type":"Vendor","wcid":52707,"cell":"596B0106","place":"dungeon","id":7328,"desc":"Vendor of the Blood. In Radiant Blood Gauntlet."}, + {"name":"Gauntlet Ticket Vendor","type":"Vendor","wcid":52858,"cell":"596B0106","place":"dungeon","id":7329,"desc":"Ticket Vendor. In Radiant Blood Gauntlet."}, + {"name":"Gauntlet Ticket Vendor","type":"Vendor","wcid":52857,"cell":"596B0109","place":"dungeon","id":7330,"desc":"Ticket Vendor. In Radiant Blood Gauntlet."}, + {"name":"Vellum","type":"Vendor","wcid":52706,"cell":"596B0109","place":"dungeon","id":7331,"desc":"Vendor of the Web. In Radiant Blood Gauntlet."}, + {"name":"Gauntlet Ticket Vendor","type":"Vendor","wcid":52856,"cell":"596B0111","place":"dungeon","id":7332,"desc":"Ticket Vendor. In Radiant Blood Gauntlet."}, + {"name":"Wreen","type":"Vendor","wcid":52705,"cell":"596B0111","place":"dungeon","id":7333,"desc":"Vendor of the Hand. In Radiant Blood Gauntlet."}, + {"name":"Lair of Holcha","type":"NPC","wcid":53289,"cell":"596B0115","place":"dungeon","id":7334,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Gauntlet Arena","type":"NPC","wcid":53250,"cell":"596B0100","place":"dungeon","id":7335,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Lair of Tremb'Orh","type":"NPC","wcid":53287,"cell":"596B0119","place":"dungeon","id":7336,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Lair of the Gromnus Champion","type":"NPC","wcid":53285,"cell":"596B0120","place":"dungeon","id":7337,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Lair of Holcha","type":"NPC","wcid":52872,"cell":"596B011E","place":"dungeon","id":7338,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Gauntlet Arena","type":"NPC","wcid":53025,"cell":"596B010C","place":"dungeon","id":7339,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Lair of Tremb'Orh","type":"NPC","wcid":52873,"cell":"596B0123","place":"dungeon","id":7340,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Lair of the Gromnus Champion","type":"NPC","wcid":52871,"cell":"596B0126","place":"dungeon","id":7341,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Font of Enlightenment and Rebirth","type":"NPC","wcid":53412,"cell":"596B012A","place":"dungeon","id":7342,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Lair of Holcha","type":"NPC","wcid":53288,"cell":"596B0117","place":"dungeon","id":7343,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Gauntlet Arena","type":"NPC","wcid":53249,"cell":"596B0103","place":"dungeon","id":7344,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Lair of Tremb'Orh","type":"NPC","wcid":53286,"cell":"596B011B","place":"dungeon","id":7345,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Lair of the Gromnus Champion","type":"NPC","wcid":53284,"cell":"596B0122","place":"dungeon","id":7346,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Master of the Gauntlet","type":"NPC","wcid":52802,"cell":"596B0101","place":"dungeon","id":7347,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Master of the Gauntlet","type":"NPC","wcid":52800,"cell":"596B010D","place":"dungeon","id":7348,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Master of the Gauntlet","type":"NPC","wcid":52801,"cell":"596B0104","place":"dungeon","id":7349,"desc":"In Radiant Blood Gauntlet."}, + {"name":"Tribunal","type":"NPC","wcid":21496,"cell":"5A4401A0","place":"dungeon","id":7350,"desc":"In Proving Grounds Extreme."}, + {"name":"Statue","type":"NPC","wcid":21494,"cell":"5A4401DA","place":"dungeon","id":7351,"desc":"In Proving Grounds Extreme."}, + {"name":"Statue","type":"NPC","wcid":21495,"cell":"5A4401F4","place":"dungeon","id":7352,"desc":"In Proving Grounds Extreme."}, + {"name":"E","type":"NPC","wcid":21502,"cell":"5A44019C","place":"dungeon","id":7353,"desc":"In Proving Grounds Extreme."}, + {"name":"Darkness","type":"NPC","wcid":21500,"cell":"5A44019C","place":"dungeon","id":7354,"desc":"In Proving Grounds Extreme."}, + {"name":"Wind","type":"NPC","wcid":21516,"cell":"5A44019D","place":"dungeon","id":7355,"desc":"In Proving Grounds Extreme."}, + {"name":"Sunlight","type":"NPC","wcid":21513,"cell":"5A44019D","place":"dungeon","id":7356,"desc":"In Proving Grounds Extreme."}, + {"name":"Nothing","type":"NPC","wcid":21509,"cell":"5A44019E","place":"dungeon","id":7357,"desc":"In Proving Grounds Extreme."}, + {"name":"Man","type":"NPC","wcid":21507,"cell":"5A44019E","place":"dungeon","id":7358,"desc":"In Proving Grounds Extreme."}, + {"name":"Stars","type":"NPC","wcid":21512,"cell":"5A44019E","place":"dungeon","id":7359,"desc":"In Proving Grounds Extreme."}, + {"name":"Silence","type":"NPC","wcid":21511,"cell":"5A44019F","place":"dungeon","id":7360,"desc":"In Proving Grounds Extreme."}, + {"name":"Coffin","type":"NPC","wcid":21499,"cell":"5A44019F","place":"dungeon","id":7361,"desc":"In Proving Grounds Extreme."}, + {"name":"Tomorrow","type":"NPC","wcid":21515,"cell":"5A4401A1","place":"dungeon","id":7362,"desc":"In Proving Grounds Extreme."}, + {"name":"Death","type":"NPC","wcid":21501,"cell":"5A4401A1","place":"dungeon","id":7363,"desc":"In Proving Grounds Extreme."}, + {"name":"Bed","type":"NPC","wcid":21497,"cell":"5A4401A3","place":"dungeon","id":7364,"desc":"In Proving Grounds Extreme."}, + {"name":"Eyes","type":"NPC","wcid":21503,"cell":"5A4401A3","place":"dungeon","id":7365,"desc":"In Proving Grounds Extreme."}, + {"name":"Black","type":"NPC","wcid":21498,"cell":"5A4401A3","place":"dungeon","id":7366,"desc":"In Proving Grounds Extreme."}, + {"name":"Hole","type":"NPC","wcid":21505,"cell":"5A4401A4","place":"dungeon","id":7367,"desc":"In Proving Grounds Extreme."}, + {"name":"Flame","type":"NPC","wcid":21504,"cell":"5A4401A4","place":"dungeon","id":7368,"desc":"In Proving Grounds Extreme."}, + {"name":"Mushroom","type":"NPC","wcid":21508,"cell":"5A4401A5","place":"dungeon","id":7369,"desc":"In Proving Grounds Extreme."}, + {"name":"Hope","type":"NPC","wcid":21506,"cell":"5A4401A5","place":"dungeon","id":7370,"desc":"In Proving Grounds Extreme."}, + {"name":"Ring","type":"NPC","wcid":21510,"cell":"5A4401A5","place":"dungeon","id":7371,"desc":"In Proving Grounds Extreme."}, + {"name":"Time","type":"NPC","wcid":21514,"cell":"5A4401A5","place":"dungeon","id":7372,"desc":"In Proving Grounds Extreme."}, + {"name":"Platinum Golem","type":"NPC","wcid":21981,"cell":"5A4603BA","place":"dungeon","id":7373,"desc":"In Frost Ziggurat."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"5AD80000","place":"outdoor","ns":71.54,"ew":-29.77,"id":7374}, + {"name":"Abia bint Huda the Archmage","type":"Vendor","wcid":9678,"cell":"5B9C0000","place":"outdoor","ns":23.34,"ew":-28.68,"id":7375,"desc":"Archmage."}, + {"name":"Greta Danby the Bowyer","type":"Vendor","wcid":9677,"cell":"5B9C0000","place":"outdoor","ns":23.43,"ew":-28.67,"id":7376,"desc":"Bowyer."}, + {"name":"Weaponsmith Hideo Sasaki","type":"Vendor","wcid":9679,"cell":"5B9C0000","place":"outdoor","ns":23.51,"ew":-28.8,"id":7377,"desc":"Weaponsmith."}, + {"name":"Gunther Danby","type":"NPC","wcid":9676,"cell":"5B9C0000","place":"outdoor","ns":23.43,"ew":-28.72,"id":7378,"desc":"Cook."}, + {"name":"Leather Crafter","type":"NPC","wcid":4213,"cell":"5B9C0000","place":"outdoor","ns":23.42,"ew":-28.63,"id":7379,"desc":"Trophy Collector."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"5B9C0000","place":"outdoor","ns":23.42,"ew":-28.73,"id":7380,"desc":"Mage."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"5B9C0000","place":"outdoor","ns":23.48,"ew":-28.65,"id":7381}, + {"name":"Pricilla the Healer","type":"Vendor","wcid":27555,"cell":"5B9C0000","place":"outdoor","ns":23.46,"ew":-28.69,"id":7382,"desc":"Healer."}, + {"name":"Journeyman Fletcher","type":"NPC","wcid":28924,"cell":"5B9C0000","place":"outdoor","ns":23.37,"ew":-28.79,"id":7383,"desc":"Apprentice Fletcher."}, + {"name":"Jin Ghao","type":"NPC","wcid":31284,"cell":"5B9C0025","place":"outdoor","ns":23.35,"ew":-28.74,"id":7384,"desc":"Royal Emissary."}, + {"name":"Marcus Danby","type":"NPC","wcid":37443,"cell":"5B9C001E","place":"outdoor","ns":23.36,"ew":-28.79,"id":7385,"desc":"Townsfolk."}, + {"name":"Colton Reeyan","type":"NPC","wcid":47799,"cell":"5B9C001F","place":"outdoor","ns":23.47,"ew":-28.79,"id":7386,"desc":"Aristocrat."}, + {"name":"Barkeep Aliece Landlig","type":"Vendor","wcid":40521,"cell":"5B9C0104","place":"building","ns":23.51,"ew":-28.79,"id":7387,"desc":"Barkeeper."}, + {"name":"Aun Paritea","type":"NPC","wcid":22890,"cell":"5BA00000","place":"outdoor","ns":26.6,"ew":-28.58,"id":7388}, + {"name":"Peddler","type":"Vendor","wcid":1390,"cell":"5BB70000","place":"outdoor","ns":44.62,"ew":-28.49,"id":7389}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"5BB70000","place":"outdoor","ns":44.77,"ew":-28.62,"id":7390}, + {"name":"Exploration Marker","type":"NPC","wcid":39781,"cell":"5BDB0038","place":"outdoor","ns":74.04,"ew":-28.45,"id":7391}, + {"name":"Tusker Shrine Statue","type":"NPC","wcid":22641,"cell":"5C4A017F","place":"dungeon","id":7392,"desc":"In Tusker Temple."}, + {"name":"Guardian","type":"NPC","wcid":27952,"cell":"5C4C0112","place":"dungeon","id":7393,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Guardian","type":"NPC","wcid":27951,"cell":"5C4C01C1","place":"dungeon","id":7394,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Guardian","type":"NPC","wcid":27950,"cell":"5C4C025F","place":"dungeon","id":7395,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Pillar","type":"NPC","wcid":27968,"cell":"5C4C038F","place":"dungeon","id":7396,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Pillar","type":"NPC","wcid":27967,"cell":"5C4C039E","place":"dungeon","id":7397,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Guardian","type":"NPC","wcid":27949,"cell":"5C4C039F","place":"dungeon","id":7398,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Pillar","type":"NPC","wcid":27961,"cell":"5C4C03A0","place":"dungeon","id":7399,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Pillar","type":"NPC","wcid":27962,"cell":"5C4C03A2","place":"dungeon","id":7400,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Biting Ballistae","type":"NPC","wcid":27937,"cell":"5C4C03A5","place":"dungeon","id":7401,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Portal to Izji Qo's Temple","type":"NPC","wcid":27969,"cell":"5C4C03A6","place":"dungeon","id":7402,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Sarcophagus of High Matriarch, Hizk Ri","type":"NPC","wcid":27970,"cell":"5C4C03A7","place":"dungeon","id":7403,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Razorbound Flange","type":"NPC","wcid":27960,"cell":"5C4C03AB","place":"dungeon","id":7404,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Sealed Door","type":"NPC","wcid":27940,"cell":"5C4C032F","place":"dungeon","id":7405,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Sealed Door","type":"NPC","wcid":27939,"cell":"5C4C0355","place":"dungeon","id":7406,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Sealed Door","type":"NPC","wcid":27938,"cell":"5C4C037F","place":"dungeon","id":7407,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Scroll of Lance Warding","type":"NPC","wcid":28317,"cell":"5C4C03A5","place":"dungeon","id":7408,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Scroll of Scythe Warding","type":"NPC","wcid":28312,"cell":"5C4C03A5","place":"dungeon","id":7409,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Scroll of Inferno Warding","type":"NPC","wcid":28315,"cell":"5C4C03A6","place":"dungeon","id":7410,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Scroll of Voltaic Warding","type":"NPC","wcid":28316,"cell":"5C4C03AB","place":"dungeon","id":7411,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Scroll of Flange Warding","type":"NPC","wcid":28313,"cell":"5C4C03AB","place":"dungeon","id":7412,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Scroll of Corrosive Warding","type":"NPC","wcid":28311,"cell":"5C4C03AC","place":"dungeon","id":7413,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Scroll of Frore Warding","type":"NPC","wcid":28314,"cell":"5C4C03AC","place":"dungeon","id":7414,"desc":"In a dungeon (landblock 5C4C)."}, + {"name":"Guardian","type":"NPC","wcid":27956,"cell":"5C4D0605","place":"dungeon","id":7415,"desc":"In a dungeon (landblock 5C4D)."}, + {"name":"Guardian","type":"NPC","wcid":27957,"cell":"5C4E0605","place":"dungeon","id":7416,"desc":"In a dungeon (landblock 5C4E)."}, + {"name":"Guardian","type":"NPC","wcid":27958,"cell":"5C4F0605","place":"dungeon","id":7417,"desc":"In a dungeon (landblock 5C4F)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"5C9D0000","place":"outdoor","ns":24.07,"ew":-28.14,"id":7418}, + {"name":"Roaming Bowyer","type":"Vendor","wcid":1378,"cell":"5CEA0000","place":"outdoor","ns":85.96,"ew":-27.67,"id":7419,"desc":"Bowyer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"5CEA0000","place":"outdoor","ns":86.02,"ew":-27.73,"id":7420}, + {"name":"Tusker Shrine Statue","type":"NPC","wcid":22641,"cell":"5D43017F","place":"dungeon","id":7421,"desc":"In Tusker Temple."}, + {"name":"Tusker Shrine Statue","type":"NPC","wcid":22641,"cell":"5D44017F","place":"dungeon","id":7422,"desc":"In Tusker Temple."}, + {"name":"Warden of Raising Self","type":"NPC","wcid":32476,"cell":"5D470183","place":"dungeon","id":7423,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Servant of Alteration","type":"NPC","wcid":32551,"cell":"5D470176","place":"dungeon","id":7424,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Warden of Raising Strength","type":"NPC","wcid":32473,"cell":"5D470176","place":"dungeon","id":7425,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Warden of Raising Coordination","type":"NPC","wcid":32472,"cell":"5D470175","place":"dungeon","id":7426,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Warden of Raising Endurance","type":"NPC","wcid":32477,"cell":"5D470175","place":"dungeon","id":7427,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Servant of Enlightenment","type":"NPC","wcid":32553,"cell":"5D470182","place":"dungeon","id":7428,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Warden of Raising Focus","type":"NPC","wcid":32475,"cell":"5D470182","place":"dungeon","id":7429,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Warden of Raising Quickness","type":"NPC","wcid":32474,"cell":"5D470182","place":"dungeon","id":7430,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Dirty Fighting Warden of Enlightenment","type":"NPC","wcid":45390,"cell":"5D470192","place":"dungeon","id":7431,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Deception Warden of Enlightenment","type":"NPC","wcid":32461,"cell":"5D470192","place":"dungeon","id":7432,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Alchemy Warden of Enlightenment","type":"NPC","wcid":32451,"cell":"5D470192","place":"dungeon","id":7433,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Assess Person Warden of Enlightenment","type":"NPC","wcid":32442,"cell":"5D470192","place":"dungeon","id":7434,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Creature Enchantment Warden of Enlightenment","type":"NPC","wcid":32458,"cell":"5D470192","place":"dungeon","id":7435,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Assess Creature Warden of Enlightenment","type":"NPC","wcid":32457,"cell":"5D470192","place":"dungeon","id":7436,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Cooking Warden of Enlightenment","type":"NPC","wcid":32456,"cell":"5D470192","place":"dungeon","id":7437,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Arcane Lore Warden of Enlightenment","type":"NPC","wcid":32452,"cell":"5D470192","place":"dungeon","id":7438,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Summoning Warden of Enlightenment","type":"NPC","wcid":49483,"cell":"5D47018D","place":"dungeon","id":7439,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Sneak Attack Warden of Enlightenment","type":"NPC","wcid":45394,"cell":"5D47018D","place":"dungeon","id":7440,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Shield Warden of Enlightenment","type":"NPC","wcid":45393,"cell":"5D47018D","place":"dungeon","id":7441,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Void Magic Warden of Enlightenment","type":"NPC","wcid":43399,"cell":"5D47018D","place":"dungeon","id":7442,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Recklessness Warden of Enlightenment","type":"NPC","wcid":45392,"cell":"5D47018D","place":"dungeon","id":7443,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Two Handed Combat Warden of Enlightenment","type":"NPC","wcid":41741,"cell":"5D47018D","place":"dungeon","id":7444,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"War Magic Warden of Enlightenment","type":"NPC","wcid":32449,"cell":"5D47018D","place":"dungeon","id":7445,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Missile Weapons Warden of Enlightenment","type":"NPC","wcid":32455,"cell":"5D47018D","place":"dungeon","id":7446,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Run Warden of Enlightenment","type":"NPC","wcid":32443,"cell":"5D47018D","place":"dungeon","id":7447,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Jump Warden of Enlightenment","type":"NPC","wcid":32466,"cell":"5D470170","place":"dungeon","id":7448,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Dual Wield Warden of Enlightenment","type":"NPC","wcid":45391,"cell":"5D470170","place":"dungeon","id":7449,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Finesse Weapons Warden of Enlightenment","type":"NPC","wcid":32460,"cell":"5D470170","place":"dungeon","id":7450,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Heavy Weapons Warden of Enlightenment","type":"NPC","wcid":32446,"cell":"5D470170","place":"dungeon","id":7451,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Life Magic Warden of Enlightenment","type":"NPC","wcid":32468,"cell":"5D470170","place":"dungeon","id":7452,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Item Enchantment Warden of Enlightenment","type":"NPC","wcid":32465,"cell":"5D470170","place":"dungeon","id":7453,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Fletching Warden of Enlightenment","type":"NPC","wcid":32462,"cell":"5D470170","place":"dungeon","id":7454,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Healing Warden of Enlightenment","type":"NPC","wcid":32463,"cell":"5D470170","place":"dungeon","id":7455,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Leadership Warden of Enlightenment","type":"NPC","wcid":32467,"cell":"5D47016B","place":"dungeon","id":7456,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Melee Defense Warden of Enlightenment","type":"NPC","wcid":32440,"cell":"5D47016B","place":"dungeon","id":7457,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Light Weapons Warden of Enlightenment","type":"NPC","wcid":32454,"cell":"5D47016B","place":"dungeon","id":7458,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Lockpick Warden of Enlightenment","type":"NPC","wcid":32469,"cell":"5D47016B","place":"dungeon","id":7459,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Loyalty Warden of Enlightenment","type":"NPC","wcid":32470,"cell":"5D47016B","place":"dungeon","id":7460,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Magic Defense Warden of Enlightenment","type":"NPC","wcid":32437,"cell":"5D47016B","place":"dungeon","id":7461,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Missile Defense Warden of Enlightenment","type":"NPC","wcid":32441,"cell":"5D47016B","place":"dungeon","id":7462,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Mana Conversion Warden of Enlightenment","type":"NPC","wcid":32439,"cell":"5D47016B","place":"dungeon","id":7463,"desc":"In a dungeon (landblock 5D47)."}, + {"name":"Warden of Lowering Self","type":"NPC","wcid":32482,"cell":"5D480183","place":"dungeon","id":7464,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Servant of Alteration","type":"NPC","wcid":32551,"cell":"5D480176","place":"dungeon","id":7465,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Warden of Lowering Strength","type":"NPC","wcid":32479,"cell":"5D480176","place":"dungeon","id":7466,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Warden of Lowering Coordination","type":"NPC","wcid":32478,"cell":"5D480175","place":"dungeon","id":7467,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Warden of Lowering Endurance","type":"NPC","wcid":32471,"cell":"5D480175","place":"dungeon","id":7468,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Warden of Lowering Quickness","type":"NPC","wcid":32480,"cell":"5D480182","place":"dungeon","id":7469,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Servant of Forgetfulness","type":"NPC","wcid":32552,"cell":"5D480182","place":"dungeon","id":7470,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Warden of Lowering Focus","type":"NPC","wcid":32481,"cell":"5D480182","place":"dungeon","id":7471,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Dirty Fighting Warden of Forgetfulness","type":"NPC","wcid":45385,"cell":"5D480192","place":"dungeon","id":7472,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Deception Warden of Forgetfulness","type":"NPC","wcid":32419,"cell":"5D480192","place":"dungeon","id":7473,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Assess Person Warden of Forgetfulness","type":"NPC","wcid":32435,"cell":"5D480192","place":"dungeon","id":7474,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Creature Enchantment Warden of Forgetfulness","type":"NPC","wcid":32416,"cell":"5D480192","place":"dungeon","id":7475,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Assess Creature Warden of Forgetfulness","type":"NPC","wcid":32415,"cell":"5D480192","place":"dungeon","id":7476,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Cooking Warden of Forgetfulness","type":"NPC","wcid":32413,"cell":"5D480192","place":"dungeon","id":7477,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Armor Tinkering Warden of Forgetfulness","type":"NPC","wcid":32410,"cell":"5D480192","place":"dungeon","id":7478,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Alchemy Warden of Forgetfulness","type":"NPC","wcid":32398,"cell":"5D480192","place":"dungeon","id":7479,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Arcane Lore Warden of Forgetfulness","type":"NPC","wcid":32409,"cell":"5D480192","place":"dungeon","id":7480,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Summoning Warden of Forgetfulness","type":"NPC","wcid":49482,"cell":"5D48018D","place":"dungeon","id":7481,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Sneak Attack Warden of Forgetfulness","type":"NPC","wcid":45389,"cell":"5D48018D","place":"dungeon","id":7482,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Shield Warden of Forgetfulness","type":"NPC","wcid":45388,"cell":"5D48018D","place":"dungeon","id":7483,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Recklessness Warden of Forgetfulness","type":"NPC","wcid":45387,"cell":"5D48018D","place":"dungeon","id":7484,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Void Magic Warden of Forgetfulness","type":"NPC","wcid":43401,"cell":"5D48018D","place":"dungeon","id":7485,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Two Handed Warden of Forgetfulness","type":"NPC","wcid":41743,"cell":"5D48018D","place":"dungeon","id":7486,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Run Warden of Forgetfulness","type":"NPC","wcid":32400,"cell":"5D48018D","place":"dungeon","id":7487,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Salvaging Warden of Forgetfulness","type":"NPC","wcid":32401,"cell":"5D48018D","place":"dungeon","id":7488,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Weapon Tinkering Warden of Forgetfulness","type":"NPC","wcid":32408,"cell":"5D48018D","place":"dungeon","id":7489,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"War Magic Warden of Forgetfulness","type":"NPC","wcid":32407,"cell":"5D48018D","place":"dungeon","id":7490,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Dual Wield Warden of Forgetfulness","type":"NPC","wcid":45386,"cell":"5D480170","place":"dungeon","id":7491,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Fletching Warden of Forgetfulness","type":"NPC","wcid":32420,"cell":"5D480170","place":"dungeon","id":7492,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Life Magic Warden of Forgetfulness","type":"NPC","wcid":32426,"cell":"5D480170","place":"dungeon","id":7493,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Finesse Weapons Warden of Forgetfulness","type":"NPC","wcid":32418,"cell":"5D480170","place":"dungeon","id":7494,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Jump Warden of Forgetfulness","type":"NPC","wcid":32424,"cell":"5D480170","place":"dungeon","id":7495,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Item Enchantment Warden of Forgetfulness","type":"NPC","wcid":32423,"cell":"5D480170","place":"dungeon","id":7496,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Leadership Warden of Forgetfulness","type":"NPC","wcid":32425,"cell":"5D480170","place":"dungeon","id":7497,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Healing Warden of Forgetfulness","type":"NPC","wcid":32421,"cell":"5D480170","place":"dungeon","id":7498,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Item Tinkering Warden of Forgetfulness","type":"NPC","wcid":32422,"cell":"5D480170","place":"dungeon","id":7499,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Heavy Weapons Warden of Forgetfulness","type":"NPC","wcid":32404,"cell":"5D480170","place":"dungeon","id":7500,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Lockpick Warden of Forgetfulness","type":"NPC","wcid":32427,"cell":"5D48016B","place":"dungeon","id":7501,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Melee Defense Warden of Forgetfulness","type":"NPC","wcid":32433,"cell":"5D48016B","place":"dungeon","id":7502,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Mana Conversion Warden of Forgetfulness","type":"NPC","wcid":32432,"cell":"5D48016B","place":"dungeon","id":7503,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Missile Defense Warden of Forgetfulness","type":"NPC","wcid":32434,"cell":"5D48016B","place":"dungeon","id":7504,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Magic Defense Warden of Forgetfulness","type":"NPC","wcid":32430,"cell":"5D48016B","place":"dungeon","id":7505,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Magic Item Tinkering Warden of Forgetfulness","type":"NPC","wcid":32431,"cell":"5D48016B","place":"dungeon","id":7506,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Loyalty Warden of Forgetfulness","type":"NPC","wcid":32428,"cell":"5D48016B","place":"dungeon","id":7507,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Missile Weapons Warden of Forgetfulness","type":"NPC","wcid":32412,"cell":"5D48016B","place":"dungeon","id":7508,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Light Weapons Warden of Forgetfulness","type":"NPC","wcid":32411,"cell":"5D48016B","place":"dungeon","id":7509,"desc":"In a dungeon (landblock 5D48)."}, + {"name":"Jaenyn, Stone Shaper","type":"NPC","wcid":25683,"cell":"5D4E02F0","place":"dungeon","id":7510,"desc":"In a dungeon (landblock 5D4E)."}, + {"name":"Quiddity Seed","type":"NPC","wcid":36780,"cell":"5E450229","place":"dungeon","id":7511,"desc":"In Black Death Catacombs."}, + {"name":"Rat Nose","type":"NPC","wcid":24245,"cell":"5E460356","place":"dungeon","id":7512,"desc":"Olthoi Fighter. In a dungeon (landblock 5E46)."}, + {"name":"Ripper","type":"NPC","wcid":24246,"cell":"5E460381","place":"dungeon","id":7513,"desc":"Olthoi Fighter. In a dungeon (landblock 5E46)."}, + {"name":"Teela","type":"NPC","wcid":24247,"cell":"5E460445","place":"dungeon","id":7514,"desc":"Olthoi Fighter. In a dungeon (landblock 5E46)."}, + {"name":"Narg","type":"NPC","wcid":24243,"cell":"5E460448","place":"dungeon","id":7515,"desc":"Olthoi Fighter. In a dungeon (landblock 5E46)."}, + {"name":"Scout Nytani Strongbow","type":"NPC","wcid":24251,"cell":"5E460448","place":"dungeon","id":7516,"desc":"Scout. In a dungeon (landblock 5E46)."}, + {"name":"Nanoc, Basher of Bugs","type":"NPC","wcid":24242,"cell":"5E460456","place":"dungeon","id":7517,"desc":"Olthoi Fighter. In a dungeon (landblock 5E46)."}, + {"name":"Pincer Danta","type":"NPC","wcid":24244,"cell":"5E4604AD","place":"dungeon","id":7518,"desc":"Olthoi Fighter. In a dungeon (landblock 5E46)."}, + {"name":"Scout Tel al-Arat","type":"NPC","wcid":24250,"cell":"5E4604AD","place":"dungeon","id":7519,"desc":"Scout. In a dungeon (landblock 5E46)."}, + {"name":"Mandible","type":"NPC","wcid":24327,"cell":"5E4604B5","place":"dungeon","id":7520,"desc":"Olthoi Fighter. In a dungeon (landblock 5E46)."}, + {"name":"Scout Luzumin Abigwei","type":"NPC","wcid":24249,"cell":"5E460446","place":"dungeon","id":7521,"desc":"Scout. In a dungeon (landblock 5E46)."}, + {"name":"Guardian","type":"NPC","wcid":24432,"cell":"5E470103","place":"dungeon","id":7522,"desc":"In Asheron's Sanctum."}, + {"name":"Graven Idol","type":"NPC","wcid":25719,"cell":"5E4C0103","place":"dungeon","id":7523,"desc":"In a dungeon (landblock 5E4C)."}, + {"name":"Bookcase","type":"NPC","wcid":25713,"cell":"5E4C01A5","place":"dungeon","id":7524,"desc":"In a dungeon (landblock 5E4C)."}, + {"name":"Argyle","type":"NPC","wcid":25711,"cell":"5E4D0105","place":"dungeon","id":7525,"desc":"Bandit Heavy. In a dungeon (landblock 5E4D)."}, + {"name":"Encrusted Scroll Case","type":"NPC","wcid":25716,"cell":"5E4D0107","place":"dungeon","id":7526,"desc":"In a dungeon (landblock 5E4D)."}, + {"name":"Klaus","type":"NPC","wcid":25712,"cell":"5E4D0109","place":"dungeon","id":7527,"desc":"Bandit. In a dungeon (landblock 5E4D)."}, + {"name":"Torch","type":"NPC","wcid":25725,"cell":"5E4D01A4","place":"dungeon","id":7528,"desc":"In a dungeon (landblock 5E4D)."}, + {"name":"Torch","type":"NPC","wcid":25725,"cell":"5E4D01A8","place":"dungeon","id":7529,"desc":"In a dungeon (landblock 5E4D)."}, + {"name":"Torch","type":"NPC","wcid":25725,"cell":"5E4D01B8","place":"dungeon","id":7530,"desc":"In a dungeon (landblock 5E4D)."}, + {"name":"Key Ring","type":"NPC","wcid":25718,"cell":"5E4D01BC","place":"dungeon","id":7531,"desc":"In a dungeon (landblock 5E4D)."}, + {"name":"Torch","type":"NPC","wcid":25725,"cell":"5E4D01BC","place":"dungeon","id":7532,"desc":"In a dungeon (landblock 5E4D)."}, + {"name":"Skeleton","type":"NPC","wcid":25724,"cell":"5E4D01C4","place":"dungeon","id":7533,"desc":"In a dungeon (landblock 5E4D)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39837,"cell":"5EB80001","place":"outdoor","ns":45.29,"ew":-26.75,"id":7534}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"5ED20000","place":"outdoor","ns":66.63,"ew":-26.37,"id":7535}, + {"name":"Statue of Swift Duelist's Wish","type":"NPC","wcid":22477,"cell":"5F440101","place":"dungeon","id":7536,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Light Duelist's Wishes","type":"NPC","wcid":22472,"cell":"5F440107","place":"dungeon","id":7537,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Fletcher's Dreams","type":"NPC","wcid":22478,"cell":"5F44010B","place":"dungeon","id":7538,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Lockpicker's Wish","type":"NPC","wcid":22484,"cell":"5F440110","place":"dungeon","id":7539,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Evasive Wishes","type":"NPC","wcid":22489,"cell":"5F440115","place":"dungeon","id":7540,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Scholarly Wishes","type":"NPC","wcid":22469,"cell":"5F440119","place":"dungeon","id":7541,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Missile Specialist's Wish","type":"NPC","wcid":22473,"cell":"5F44011D","place":"dungeon","id":7542,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Healer's Wish","type":"NPC","wcid":22479,"cell":"5F440123","place":"dungeon","id":7543,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Greedy Wishes","type":"NPC","wcid":22491,"cell":"5F440128","place":"dungeon","id":7544,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Swashbuckler's Wish","type":"NPC","wcid":22485,"cell":"5F44012B","place":"dungeon","id":7545,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Dodge Wishes","type":"NPC","wcid":22490,"cell":"5F440130","place":"dungeon","id":7546,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Heavy Soldier's Wish","type":"NPC","wcid":22495,"cell":"5F440136","place":"dungeon","id":7547,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Alchemical Wishes","type":"NPC","wcid":22468,"cell":"5F44013A","place":"dungeon","id":7548,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Armor Tinker's Wish","type":"NPC","wcid":22470,"cell":"5F44013D","place":"dungeon","id":7549,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Cook's Wish","type":"NPC","wcid":22474,"cell":"5F440143","place":"dungeon","id":7550,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Artificer's Wish","type":"NPC","wcid":22480,"cell":"5F440149","place":"dungeon","id":7551,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Resistance Wishes","type":"NPC","wcid":22486,"cell":"5F440152","place":"dungeon","id":7552,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Sprinter's Wish","type":"NPC","wcid":22492,"cell":"5F440155","place":"dungeon","id":7553,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Dirty Fighter's Wish","type":"NPC","wcid":22496,"cell":"5F44015B","place":"dungeon","id":7554,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Weapon Tinker's Wish","type":"NPC","wcid":22498,"cell":"5F440161","place":"dungeon","id":7555,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Berzerker's Wish","type":"NPC","wcid":22471,"cell":"5F440164","place":"dungeon","id":7556,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Enchanter's Wish","type":"NPC","wcid":22475,"cell":"5F440168","place":"dungeon","id":7557,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Item Tinker's Wish","type":"NPC","wcid":22481,"cell":"5F44016E","place":"dungeon","id":7558,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Greedy Wishes","type":"NPC","wcid":22491,"cell":"5F440173","place":"dungeon","id":7559,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Magic Tinker's Wish","type":"NPC","wcid":22487,"cell":"5F440176","place":"dungeon","id":7560,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Shieldbearer's Wish","type":"NPC","wcid":22493,"cell":"5F44017B","place":"dungeon","id":7561,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Sorcerer's Wish","type":"NPC","wcid":22497,"cell":"5F440181","place":"dungeon","id":7562,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Stealther's Wish","type":"NPC","wcid":22476,"cell":"5F440185","place":"dungeon","id":7563,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Leaper's Wish","type":"NPC","wcid":22482,"cell":"5F440189","place":"dungeon","id":7564,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Archmage's Wish","type":"NPC","wcid":22488,"cell":"5F44018E","place":"dungeon","id":7565,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Cleaving Warrior's Wish","type":"NPC","wcid":22494,"cell":"5F440193","place":"dungeon","id":7566,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Life Giver's Wish","type":"NPC","wcid":22483,"cell":"5F440197","place":"dungeon","id":7567,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Oolutanga, the Tusker King","type":"NPC","wcid":22500,"cell":"5F4401A2","place":"dungeon","id":7568,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Statue of Void Caster's Wish","type":"NPC","wcid":45522,"cell":"5F440104","place":"dungeon","id":7569,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Grunter","type":"NPC","wcid":35777,"cell":"5F4401A3","place":"dungeon","id":7570,"desc":"In a dungeon (landblock 5F44)."}, + {"name":"Puzzle Box","type":"NPC","wcid":24159,"cell":"5F45010E","place":"dungeon","id":7571,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Puzzle Box","type":"NPC","wcid":24159,"cell":"5F45010F","place":"dungeon","id":7572,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Puzzle Box","type":"NPC","wcid":24159,"cell":"5F450118","place":"dungeon","id":7573,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Puzzle Box","type":"NPC","wcid":24159,"cell":"5F450135","place":"dungeon","id":7574,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Puzzle Box","type":"NPC","wcid":24159,"cell":"5F450138","place":"dungeon","id":7575,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Puzzle Box","type":"NPC","wcid":24159,"cell":"5F450139","place":"dungeon","id":7576,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Mu Mu","type":"NPC","wcid":22502,"cell":"5F45013D","place":"dungeon","id":7577,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Cao Cao","type":"NPC","wcid":22501,"cell":"5F45013E","place":"dungeon","id":7578,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Judgment Statue","type":"NPC","wcid":22467,"cell":"5F450146","place":"dungeon","id":7579,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Babysitter","type":"NPC","wcid":22499,"cell":"5F450147","place":"dungeon","id":7580,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Shim Shim","type":"NPC","wcid":22504,"cell":"5F45014B","place":"dungeon","id":7581,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Po Po","type":"NPC","wcid":22503,"cell":"5F45014C","place":"dungeon","id":7582,"desc":"In a dungeon (landblock 5F45)."}, + {"name":"Body of Jaleh al-Thani","type":"NPC","wcid":24184,"cell":"5F460154","place":"dungeon","id":7583,"desc":"In a dungeon (landblock 5F46)."}, + {"name":"Acidic Elemental Pool","type":"NPC","wcid":25601,"cell":"5F470101","place":"dungeon","id":7584,"desc":"In Elemental Caverns."}, + {"name":"Freezing Elemental Pool","type":"NPC","wcid":25604,"cell":"5F470105","place":"dungeon","id":7585,"desc":"In Elemental Caverns."}, + {"name":"Electric Elemental Pool","type":"NPC","wcid":25602,"cell":"5F470109","place":"dungeon","id":7586,"desc":"In Elemental Caverns."}, + {"name":"Flaming Elemental Pool","type":"NPC","wcid":25603,"cell":"5F47010D","place":"dungeon","id":7587,"desc":"In Elemental Caverns."}, + {"name":"Harraag, Banderling Champion","type":"NPC","wcid":25568,"cell":"5F480130","place":"dungeon","id":7588,"desc":"In Hidden Cavern."}, + {"name":"Scrum, Drudge Seraph Mystic","type":"NPC","wcid":25569,"cell":"5F4801B5","place":"dungeon","id":7589,"desc":"In Hidden Cavern."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490115","place":"dungeon","id":7590,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490130","place":"dungeon","id":7591,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F49013D","place":"dungeon","id":7592,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490157","place":"dungeon","id":7593,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490175","place":"dungeon","id":7594,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4901A0","place":"dungeon","id":7595,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4901AB","place":"dungeon","id":7596,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4901B7","place":"dungeon","id":7597,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4901BE","place":"dungeon","id":7598,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4901FF","place":"dungeon","id":7599,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490206","place":"dungeon","id":7600,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490217","place":"dungeon","id":7601,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490241","place":"dungeon","id":7602,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490252","place":"dungeon","id":7603,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490259","place":"dungeon","id":7604,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F49029A","place":"dungeon","id":7605,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4902A1","place":"dungeon","id":7606,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4902AD","place":"dungeon","id":7607,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4902B8","place":"dungeon","id":7608,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4902E3","place":"dungeon","id":7609,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F490373","place":"dungeon","id":7610,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F49037A","place":"dungeon","id":7611,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F490389","place":"dungeon","id":7612,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490390","place":"dungeon","id":7613,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F490424","place":"dungeon","id":7614,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F49042B","place":"dungeon","id":7615,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F49043A","place":"dungeon","id":7616,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490441","place":"dungeon","id":7617,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4904E7","place":"dungeon","id":7618,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490509","place":"dungeon","id":7619,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490528","place":"dungeon","id":7620,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F490540","place":"dungeon","id":7621,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F490547","place":"dungeon","id":7622,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27945,"cell":"5F49059E","place":"dungeon","id":7623,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4905AB","place":"dungeon","id":7624,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27945,"cell":"5F4905BB","place":"dungeon","id":7625,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27945,"cell":"5F4905BC","place":"dungeon","id":7626,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27941,"cell":"5F4905BE","place":"dungeon","id":7627,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27942,"cell":"5F4905BF","place":"dungeon","id":7628,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27945,"cell":"5F4905C0","place":"dungeon","id":7629,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27944,"cell":"5F4905C2","place":"dungeon","id":7630,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Strange Device","type":"NPC","wcid":27934,"cell":"5F4905C8","place":"dungeon","id":7631,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27943,"cell":"5F4905CD","place":"dungeon","id":7632,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27945,"cell":"5F4905D4","place":"dungeon","id":7633,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27945,"cell":"5F4905DA","place":"dungeon","id":7634,"desc":"In a dungeon (landblock 5F49)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0115","place":"dungeon","id":7635,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0130","place":"dungeon","id":7636,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A013D","place":"dungeon","id":7637,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0157","place":"dungeon","id":7638,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0175","place":"dungeon","id":7639,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A01A0","place":"dungeon","id":7640,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A01AB","place":"dungeon","id":7641,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A01B7","place":"dungeon","id":7642,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A01BE","place":"dungeon","id":7643,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A01FF","place":"dungeon","id":7644,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0206","place":"dungeon","id":7645,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0217","place":"dungeon","id":7646,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0241","place":"dungeon","id":7647,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0252","place":"dungeon","id":7648,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0259","place":"dungeon","id":7649,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A029A","place":"dungeon","id":7650,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A02A1","place":"dungeon","id":7651,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A02AD","place":"dungeon","id":7652,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A02B8","place":"dungeon","id":7653,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A02E3","place":"dungeon","id":7654,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F4A0373","place":"dungeon","id":7655,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A037A","place":"dungeon","id":7656,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F4A0389","place":"dungeon","id":7657,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0390","place":"dungeon","id":7658,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F4A0424","place":"dungeon","id":7659,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A042B","place":"dungeon","id":7660,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F4A043A","place":"dungeon","id":7661,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0441","place":"dungeon","id":7662,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A04E7","place":"dungeon","id":7663,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0509","place":"dungeon","id":7664,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0528","place":"dungeon","id":7665,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F4A0540","place":"dungeon","id":7666,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A0547","place":"dungeon","id":7667,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27944,"cell":"5F4A059E","place":"dungeon","id":7668,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4A05AB","place":"dungeon","id":7669,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27943,"cell":"5F4A05BB","place":"dungeon","id":7670,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27946,"cell":"5F4A05BC","place":"dungeon","id":7671,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27946,"cell":"5F4A05BE","place":"dungeon","id":7672,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27946,"cell":"5F4A05BF","place":"dungeon","id":7673,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27946,"cell":"5F4A05C0","place":"dungeon","id":7674,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27946,"cell":"5F4A05C2","place":"dungeon","id":7675,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Strange Device","type":"NPC","wcid":27935,"cell":"5F4A05C8","place":"dungeon","id":7676,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27946,"cell":"5F4A05CD","place":"dungeon","id":7677,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27941,"cell":"5F4A05D4","place":"dungeon","id":7678,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27942,"cell":"5F4A05DA","place":"dungeon","id":7679,"desc":"In a dungeon (landblock 5F4A)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0115","place":"dungeon","id":7680,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0130","place":"dungeon","id":7681,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B013D","place":"dungeon","id":7682,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0157","place":"dungeon","id":7683,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0175","place":"dungeon","id":7684,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B01A0","place":"dungeon","id":7685,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B01AB","place":"dungeon","id":7686,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B01B7","place":"dungeon","id":7687,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B01BE","place":"dungeon","id":7688,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B01FF","place":"dungeon","id":7689,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0206","place":"dungeon","id":7690,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0217","place":"dungeon","id":7691,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0241","place":"dungeon","id":7692,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0252","place":"dungeon","id":7693,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0259","place":"dungeon","id":7694,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B029A","place":"dungeon","id":7695,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B02A1","place":"dungeon","id":7696,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B02AD","place":"dungeon","id":7697,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B02B8","place":"dungeon","id":7698,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B02E3","place":"dungeon","id":7699,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F4B0373","place":"dungeon","id":7700,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B037A","place":"dungeon","id":7701,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F4B0389","place":"dungeon","id":7702,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0390","place":"dungeon","id":7703,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F4B0424","place":"dungeon","id":7704,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B042B","place":"dungeon","id":7705,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F4B043A","place":"dungeon","id":7706,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0441","place":"dungeon","id":7707,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B04E7","place":"dungeon","id":7708,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0509","place":"dungeon","id":7709,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0528","place":"dungeon","id":7710,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"5F4B0540","place":"dungeon","id":7711,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B0547","place":"dungeon","id":7712,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27947,"cell":"5F4B059E","place":"dungeon","id":7713,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"5F4B05AB","place":"dungeon","id":7714,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27947,"cell":"5F4B05BB","place":"dungeon","id":7715,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27941,"cell":"5F4B05BC","place":"dungeon","id":7716,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27947,"cell":"5F4B05BE","place":"dungeon","id":7717,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27947,"cell":"5F4B05BF","place":"dungeon","id":7718,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27944,"cell":"5F4B05C0","place":"dungeon","id":7719,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27947,"cell":"5F4B05C2","place":"dungeon","id":7720,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Strange Device","type":"NPC","wcid":27936,"cell":"5F4B05C8","place":"dungeon","id":7721,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27943,"cell":"5F4B05CD","place":"dungeon","id":7722,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27947,"cell":"5F4B05D4","place":"dungeon","id":7723,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27942,"cell":"5F4B05DA","place":"dungeon","id":7724,"desc":"In a dungeon (landblock 5F4B)."}, + {"name":"Guardian","type":"NPC","wcid":27954,"cell":"5F4C0331","place":"dungeon","id":7725,"desc":"In a dungeon (landblock 5F4C)."}, + {"name":"Guardian","type":"NPC","wcid":27953,"cell":"5F4D0331","place":"dungeon","id":7726,"desc":"In a dungeon (landblock 5F4D)."}, + {"name":"Guardian","type":"NPC","wcid":27959,"cell":"5F4E0331","place":"dungeon","id":7727,"desc":"In a dungeon (landblock 5F4E)."}, + {"name":"Guardian","type":"NPC","wcid":27955,"cell":"5F4F027B","place":"dungeon","id":7728,"desc":"In a dungeon (landblock 5F4F)."}, + {"name":"Guardian","type":"NPC","wcid":27955,"cell":"5F50027B","place":"dungeon","id":7729,"desc":"In a dungeon (landblock 5F50)."}, + {"name":"Guardian","type":"NPC","wcid":27955,"cell":"5F51027B","place":"dungeon","id":7730,"desc":"In a dungeon (landblock 5F51)."}, + {"name":"Sergeant Maloth","type":"NPC","wcid":25493,"cell":"60490321","place":"dungeon","id":7731,"desc":"Gotrok Sergeant. In Renegade Garrison."}, + {"name":"Pool of Goo","type":"NPC","wcid":25489,"cell":"60490100","place":"dungeon","id":7732,"desc":"In Renegade Garrison."}, + {"name":"Torch","type":"NPC","wcid":25587,"cell":"604A0121","place":"dungeon","id":7733,"desc":"In Sclavus Temple."}, + {"name":"Snowman","type":"Vendor","wcid":5765,"cell":"60D60000","place":"outdoor","ns":69.9,"ew":-25.05,"id":7734}, + {"name":"Lord Pyrovor","type":"NPC","wcid":88247,"cell":"60DA0100","place":"dungeon","id":7735,"desc":"Dericost Emissionary. In a dungeon (landblock 60DA)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"624306CF","place":"dungeon","id":7736,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"624305A4","place":"dungeon","id":7737,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"624305A5","place":"dungeon","id":7738,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"62430697","place":"dungeon","id":7739,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243059D","place":"dungeon","id":7740,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430597","place":"dungeon","id":7741,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243059C","place":"dungeon","id":7742,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Guardian","type":"NPC","wcid":27239,"cell":"62430126","place":"dungeon","id":7743,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Guardian of the High Matriarch","type":"NPC","wcid":27240,"cell":"6243016B","place":"dungeon","id":7744,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Guardian","type":"NPC","wcid":27241,"cell":"6243021A","place":"dungeon","id":7745,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Guardian","type":"NPC","wcid":27238,"cell":"6243025F","place":"dungeon","id":7746,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430596","place":"dungeon","id":7747,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430598","place":"dungeon","id":7748,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430599","place":"dungeon","id":7749,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243059A","place":"dungeon","id":7750,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243059B","place":"dungeon","id":7751,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243059E","place":"dungeon","id":7752,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243059F","place":"dungeon","id":7753,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"624305A1","place":"dungeon","id":7754,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"624305A2","place":"dungeon","id":7755,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Guardian","type":"NPC","wcid":27161,"cell":"624305A6","place":"dungeon","id":7756,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Guardian","type":"NPC","wcid":27162,"cell":"624305B3","place":"dungeon","id":7757,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Guardian","type":"NPC","wcid":27163,"cell":"624305C0","place":"dungeon","id":7758,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Guardian","type":"NPC","wcid":27164,"cell":"624305CD","place":"dungeon","id":7759,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243063C","place":"dungeon","id":7760,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243063D","place":"dungeon","id":7761,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243063E","place":"dungeon","id":7762,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243063F","place":"dungeon","id":7763,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430640","place":"dungeon","id":7764,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430641","place":"dungeon","id":7765,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430642","place":"dungeon","id":7766,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430643","place":"dungeon","id":7767,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430644","place":"dungeon","id":7768,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430645","place":"dungeon","id":7769,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430647","place":"dungeon","id":7770,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"62430648","place":"dungeon","id":7771,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243064A","place":"dungeon","id":7772,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6243064B","place":"dungeon","id":7773,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"62430665","place":"dungeon","id":7774,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"6243066B","place":"dungeon","id":7775,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"6243067B","place":"dungeon","id":7776,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"6243067D","place":"dungeon","id":7777,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"6243068E","place":"dungeon","id":7778,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"62430690","place":"dungeon","id":7779,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"62430692","place":"dungeon","id":7780,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"62430694","place":"dungeon","id":7781,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"62430695","place":"dungeon","id":7782,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Guardian","type":"NPC","wcid":27160,"cell":"624306AC","place":"dungeon","id":7783,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"624306C9","place":"dungeon","id":7784,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"624306DF","place":"dungeon","id":7785,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"624306E1","place":"dungeon","id":7786,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"624306F2","place":"dungeon","id":7787,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"624306F4","place":"dungeon","id":7788,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"624306F6","place":"dungeon","id":7789,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"624306F8","place":"dungeon","id":7790,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"624306F9","place":"dungeon","id":7791,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"624306FB","place":"dungeon","id":7792,"desc":"In a dungeon (landblock 6243)."}, + {"name":"Guardian","type":"NPC","wcid":27165,"cell":"62440105","place":"dungeon","id":7793,"desc":"In a dungeon (landblock 6244)."}, + {"name":"Guardian of the High Matriarch","type":"NPC","wcid":27166,"cell":"6244010E","place":"dungeon","id":7794,"desc":"In a dungeon (landblock 6244)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27157,"cell":"62440794","place":"dungeon","id":7795,"desc":"In a dungeon (landblock 6244)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27158,"cell":"624407C2","place":"dungeon","id":7796,"desc":"In a dungeon (landblock 6244)."}, + {"name":"Strange Device","type":"NPC","wcid":27170,"cell":"624407D2","place":"dungeon","id":7797,"desc":"In a dungeon (landblock 6244)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27159,"cell":"62440813","place":"dungeon","id":7798,"desc":"In a dungeon (landblock 6244)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27157,"cell":"62440839","place":"dungeon","id":7799,"desc":"In a dungeon (landblock 6244)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27158,"cell":"62440867","place":"dungeon","id":7800,"desc":"In a dungeon (landblock 6244)."}, + {"name":"Strange Device","type":"NPC","wcid":27171,"cell":"62440877","place":"dungeon","id":7801,"desc":"In a dungeon (landblock 6244)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27159,"cell":"624408B8","place":"dungeon","id":7802,"desc":"In a dungeon (landblock 6244)."}, + {"name":"Guardian","type":"NPC","wcid":27167,"cell":"62450105","place":"dungeon","id":7803,"desc":"In a dungeon (landblock 6245)."}, + {"name":"Guardian","type":"NPC","wcid":27168,"cell":"6245010E","place":"dungeon","id":7804,"desc":"In a dungeon (landblock 6245)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27157,"cell":"62450794","place":"dungeon","id":7805,"desc":"In a dungeon (landblock 6245)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27158,"cell":"624507C2","place":"dungeon","id":7806,"desc":"In a dungeon (landblock 6245)."}, + {"name":"Strange Device","type":"NPC","wcid":27172,"cell":"624507D2","place":"dungeon","id":7807,"desc":"In a dungeon (landblock 6245)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27159,"cell":"62450813","place":"dungeon","id":7808,"desc":"In a dungeon (landblock 6245)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27157,"cell":"62450839","place":"dungeon","id":7809,"desc":"In a dungeon (landblock 6245)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27158,"cell":"62450867","place":"dungeon","id":7810,"desc":"In a dungeon (landblock 6245)."}, + {"name":"Strange Device","type":"NPC","wcid":27173,"cell":"62450877","place":"dungeon","id":7811,"desc":"In a dungeon (landblock 6245)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":27159,"cell":"624508B8","place":"dungeon","id":7812,"desc":"In a dungeon (landblock 6245)."}, + {"name":"Defender of Liazk Itzi's Crypt","type":"NPC","wcid":27169,"cell":"62460322","place":"dungeon","id":7813,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Defender of Liazk Itzi's Crypt","type":"NPC","wcid":27169,"cell":"6246044C","place":"dungeon","id":7814,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Fist of Massacre","type":"NPC","wcid":27148,"cell":"624605CC","place":"dungeon","id":7815,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Bladed Bow of Impaling","type":"NPC","wcid":27146,"cell":"624605CD","place":"dungeon","id":7816,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Scroll of Alacrity of the Conclave","type":"NPC","wcid":27151,"cell":"624605CE","place":"dungeon","id":7817,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Scroll of Empowering the Conclave","type":"NPC","wcid":27156,"cell":"624605CE","place":"dungeon","id":7818,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Sarcophagus of High Matriarch, Liazk Itzi","type":"NPC","wcid":27150,"cell":"624605CF","place":"dungeon","id":7819,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Scroll of Vivify the Conclave","type":"NPC","wcid":27152,"cell":"624605D1","place":"dungeon","id":7820,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Scroll of Speed the Conclave","type":"NPC","wcid":27154,"cell":"624605D1","place":"dungeon","id":7821,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Vein-Thirst Kurki","type":"NPC","wcid":27149,"cell":"624605D2","place":"dungeon","id":7822,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Vile Scourge","type":"NPC","wcid":27147,"cell":"624605D3","place":"dungeon","id":7823,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Scroll of Acumen of the Conclave","type":"NPC","wcid":27153,"cell":"624605D4","place":"dungeon","id":7824,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Scroll of Volition of the Conclave","type":"NPC","wcid":27155,"cell":"624605D4","place":"dungeon","id":7825,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Defender of Liazk Itzi's Crypt","type":"NPC","wcid":27169,"cell":"62460312","place":"dungeon","id":7826,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Defender of Liazk Itzi's Crypt","type":"NPC","wcid":27169,"cell":"6246043C","place":"dungeon","id":7827,"desc":"In a dungeon (landblock 6246)."}, + {"name":"Corpse of Lugian Courier","type":"NPC","wcid":27475,"cell":"6247022E","place":"dungeon","id":7828,"desc":"In a dungeon (landblock 6247)."}, + {"name":"A Cluttered Table","type":"NPC","wcid":27476,"cell":"62480107","place":"dungeon","id":7829,"desc":"In Renegade Fortress."}, + {"name":"Diamond Guardian","type":"NPC","wcid":24000,"cell":"6344010A","place":"dungeon","id":7830,"desc":"In a dungeon (landblock 6344)."}, + {"name":"Diamond Guardian","type":"NPC","wcid":23999,"cell":"6344010E","place":"dungeon","id":7831,"desc":"In a dungeon (landblock 6344)."}, + {"name":"Diamond Guardian","type":"NPC","wcid":23998,"cell":"63440112","place":"dungeon","id":7832,"desc":"In a dungeon (landblock 6344)."}, + {"name":"Proselytic Shadow","type":"NPC","wcid":25673,"cell":"6348015A","place":"dungeon","id":7833,"desc":"In a dungeon (landblock 6348)."}, + {"name":"Twitch","type":"NPC","wcid":22749,"cell":"634802F7","place":"dungeon","id":7834,"desc":"Sacrifice. In a dungeon (landblock 6348)."}, + {"name":"Snowman","type":"Vendor","wcid":5765,"cell":"63D80000","place":"outdoor","ns":71.41,"ew":-22.16,"id":7835}, + {"name":"Paul the Monouga","type":"NPC","wcid":8129,"cell":"63E80000","place":"outdoor","ns":84.01,"ew":-22.19,"id":7836}, + {"name":"Arikas, Warden of Knorr","type":"NPC","wcid":24001,"cell":"64440143","place":"dungeon","id":7837,"desc":"In a dungeon (landblock 6444)."}, + {"name":"Bookshelf","type":"NPC","wcid":23996,"cell":"64440361","place":"dungeon","id":7838,"desc":"In a dungeon (landblock 6444)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"64460155","place":"dungeon","id":7839,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"64460155","place":"dungeon","id":7840,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"64460155","place":"dungeon","id":7841,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"64460155","place":"dungeon","id":7842,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"6446016E","place":"dungeon","id":7843,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"6446016E","place":"dungeon","id":7844,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"6446016E","place":"dungeon","id":7845,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"6446016E","place":"dungeon","id":7846,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"6446017E","place":"dungeon","id":7847,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"6446017E","place":"dungeon","id":7848,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"64460180","place":"dungeon","id":7849,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"64460180","place":"dungeon","id":7850,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"6446018B","place":"dungeon","id":7851,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"6446018B","place":"dungeon","id":7852,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"6446018D","place":"dungeon","id":7853,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"6446018D","place":"dungeon","id":7854,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"644601C0","place":"dungeon","id":7855,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"644601C6","place":"dungeon","id":7856,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"644601C7","place":"dungeon","id":7857,"desc":"In a dungeon (landblock 6446)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"64470155","place":"dungeon","id":7858,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"64470155","place":"dungeon","id":7859,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"64470155","place":"dungeon","id":7860,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"64470155","place":"dungeon","id":7861,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"6447016E","place":"dungeon","id":7862,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"6447016E","place":"dungeon","id":7863,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"6447016E","place":"dungeon","id":7864,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"6447016E","place":"dungeon","id":7865,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"6447017E","place":"dungeon","id":7866,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"6447017E","place":"dungeon","id":7867,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"64470180","place":"dungeon","id":7868,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"64470180","place":"dungeon","id":7869,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"6447018B","place":"dungeon","id":7870,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Fiery Tentacle","type":"NPC","wcid":21779,"cell":"6447018B","place":"dungeon","id":7871,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Acidic Tentacle","type":"NPC","wcid":21771,"cell":"6447018D","place":"dungeon","id":7872,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Electric Tentacle","type":"NPC","wcid":21795,"cell":"6447018D","place":"dungeon","id":7873,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"644701C0","place":"dungeon","id":7874,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"644701C6","place":"dungeon","id":7875,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Icy Tentacle","type":"NPC","wcid":21787,"cell":"644701C7","place":"dungeon","id":7876,"desc":"In a dungeon (landblock 6447)."}, + {"name":"Smooth Rocks","type":"NPC","wcid":25831,"cell":"64490116","place":"dungeon","id":7877,"desc":"In Dragon's Power."}, + {"name":"Crystal Formation","type":"NPC","wcid":25825,"cell":"6449010D","place":"dungeon","id":7878,"desc":"In Dragon's Power."}, + {"name":"Smoldering Brazier","type":"NPC","wcid":25824,"cell":"644901EC","place":"dungeon","id":7879,"desc":"In Dragon's Power."}, + {"name":"Yalik Ibn Ujsef","type":"NPC","wcid":25974,"cell":"644A0390","place":"dungeon","id":7880,"desc":"Zharalim Apprentice. In a dungeon (landblock 644A)."}, + {"name":"Archmage Ta Ri","type":"Vendor","wcid":5435,"cell":"64D50100","place":"building","ns":69.01,"ew":-21.69,"id":7881,"desc":"Archmage."}, + {"name":"Healer of Stonehold","type":"Vendor","wcid":2535,"cell":"64D5011B","place":"building","ns":68.81,"ew":-21.51,"id":7882,"desc":"Healer."}, + {"name":"Farmer","type":"Vendor","wcid":1381,"cell":"64D50121","place":"building","ns":68.8,"ew":-21.7,"id":7883}, + {"name":"Gerhi, Bowyer of Stonehold","type":"Vendor","wcid":2533,"cell":"64D50107","place":"building","ns":68.9,"ew":-21.59,"id":7884,"desc":"Bowyer."}, + {"name":"Vivaina, Shopkeep of Stonehold","type":"Vendor","wcid":2534,"cell":"64D50121","place":"building","ns":68.79,"ew":-21.72,"id":7885,"desc":"Shopkeeper."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"64D5012C","place":"building","ns":68.59,"ew":-21.72,"id":7886,"desc":"Mage."}, + {"name":"Olcris, Nuhmudira's Student","type":"NPC","wcid":23997,"cell":"64D50114","place":"building","ns":68.71,"ew":-21.6,"id":7887,"desc":"Noble."}, + {"name":"Corin of Stonehold","type":"Vendor","wcid":27248,"cell":"64D50000","place":"outdoor","ns":68.73,"ew":-21.61,"id":7888,"desc":"Farmer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"64D50000","place":"outdoor","ns":68.87,"ew":-21.83,"id":7889}, + {"name":"Grand Master Scrivener of Life Magic","type":"Vendor","wcid":20220,"cell":"64D50136","place":"building","ns":68.7,"ew":-21.49,"id":7890,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of War Magic","type":"Vendor","wcid":20224,"cell":"64D50134","place":"building","ns":68.72,"ew":-21.5,"id":7891,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Item Magic","type":"Vendor","wcid":20212,"cell":"64D50135","place":"building","ns":68.7,"ew":-21.52,"id":7892,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Creature Magic","type":"Vendor","wcid":20208,"cell":"64D50136","place":"building","ns":68.69,"ew":-21.5,"id":7893,"desc":"Master Archmage."}, + {"name":"Suzuhara Baijin","type":"NPC","wcid":30387,"cell":"64D50000","place":"outdoor","ns":68.88,"ew":-21.76,"id":7894,"desc":"Adventurer."}, + {"name":"Cyphis Suldow","type":"NPC","wcid":30627,"cell":"64D50000","place":"outdoor","ns":68.77,"ew":-21.57,"id":7895,"desc":"Entrepreneur."}, + {"name":"Drozer","type":"NPC","wcid":31689,"cell":"64D5010D","place":"building","ns":68.89,"ew":-21.41,"id":7896,"desc":"Monster Plant Lover."}, + {"name":"Belinda du Loc","type":"NPC","wcid":33966,"cell":"64D50107","place":"building","ns":68.91,"ew":-21.6,"id":7897,"desc":"Trophy Rare Game Hunter."}, + {"name":"Kraytuss Nallah","type":"NPC","wcid":46338,"cell":"64D50014","place":"outdoor","ns":68.83,"ew":-21.68,"id":7898,"desc":"Adventurer."}, + {"name":"Zahir","type":"NPC","wcid":33967,"cell":"64D50023","place":"outdoor","ns":68.72,"ew":-21.51,"id":7899,"desc":"Experimental Alchemist."}, + {"name":"Bael'Zharon","type":"Vendor","wcid":25994,"cell":"6544011A","place":"dungeon","id":7900,"desc":"Wannabe. In a dungeon (landblock 6544)."}, + {"name":"Guardian of the Forbidden","type":"NPC","wcid":27306,"cell":"6544013A","place":"dungeon","id":7901,"desc":"In a dungeon (landblock 6544)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65450100","place":"dungeon","id":7902,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65450106","place":"dungeon","id":7903,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65450116","place":"dungeon","id":7904,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6545011D","place":"dungeon","id":7905,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Matron Arbiter","type":"NPC","wcid":26552,"cell":"65450123","place":"dungeon","id":7906,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65450126","place":"dungeon","id":7907,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65450128","place":"dungeon","id":7908,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65450129","place":"dungeon","id":7909,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65450130","place":"dungeon","id":7910,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65450132","place":"dungeon","id":7911,"desc":"In a dungeon (landblock 6545)."}, + {"name":"High Matron Arbiter","type":"NPC","wcid":26551,"cell":"65450133","place":"dungeon","id":7912,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"6545013C","place":"dungeon","id":7913,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65450147","place":"dungeon","id":7914,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65450149","place":"dungeon","id":7915,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Matron Arbiter","type":"NPC","wcid":26552,"cell":"6545014B","place":"dungeon","id":7916,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"6545014E","place":"dungeon","id":7917,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65450152","place":"dungeon","id":7918,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65450157","place":"dungeon","id":7919,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"6545015E","place":"dungeon","id":7920,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65450163","place":"dungeon","id":7921,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65450164","place":"dungeon","id":7922,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65450167","place":"dungeon","id":7923,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"6545016F","place":"dungeon","id":7924,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65450172","place":"dungeon","id":7925,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Matron Arbiter","type":"NPC","wcid":26552,"cell":"65450176","place":"dungeon","id":7926,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65450180","place":"dungeon","id":7927,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65450182","place":"dungeon","id":7928,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65450185","place":"dungeon","id":7929,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"6545018B","place":"dungeon","id":7930,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65450192","place":"dungeon","id":7931,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65450199","place":"dungeon","id":7932,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"6545019A","place":"dungeon","id":7933,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6545019B","place":"dungeon","id":7934,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654501A0","place":"dungeon","id":7935,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654501AD","place":"dungeon","id":7936,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654501AE","place":"dungeon","id":7937,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654501B4","place":"dungeon","id":7938,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654501B5","place":"dungeon","id":7939,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654501BA","place":"dungeon","id":7940,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654501BB","place":"dungeon","id":7941,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654501CA","place":"dungeon","id":7942,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654501D3","place":"dungeon","id":7943,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654501DD","place":"dungeon","id":7944,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654501DE","place":"dungeon","id":7945,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654501E3","place":"dungeon","id":7946,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654501E6","place":"dungeon","id":7947,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654501EA","place":"dungeon","id":7948,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654501EF","place":"dungeon","id":7949,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654501FD","place":"dungeon","id":7950,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654501FF","place":"dungeon","id":7951,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26577,"cell":"65450206","place":"dungeon","id":7952,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26576,"cell":"65450207","place":"dungeon","id":7953,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65450208","place":"dungeon","id":7954,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65450212","place":"dungeon","id":7955,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Guardian of the Matriarch's Gaze","type":"NPC","wcid":26549,"cell":"65450213","place":"dungeon","id":7956,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26579,"cell":"65450218","place":"dungeon","id":7957,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26578,"cell":"65450219","place":"dungeon","id":7958,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Guardian of Fury","type":"NPC","wcid":26550,"cell":"6545021B","place":"dungeon","id":7959,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Guardian of the Restless Dead","type":"NPC","wcid":26546,"cell":"65450221","place":"dungeon","id":7960,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Arbiter","type":"NPC","wcid":26548,"cell":"65450222","place":"dungeon","id":7961,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Offering Table","type":"NPC","wcid":26635,"cell":"65450225","place":"dungeon","id":7962,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Guardian of the Sacrificial Urns","type":"NPC","wcid":26566,"cell":"65450228","place":"dungeon","id":7963,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Sickle of Writhing Fury","type":"NPC","wcid":26539,"cell":"6545022A","place":"dungeon","id":7964,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Crimson Brace of Pain","type":"NPC","wcid":26533,"cell":"6545022A","place":"dungeon","id":7965,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Lance of the Bloodletter","type":"NPC","wcid":26540,"cell":"6545022A","place":"dungeon","id":7966,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Strange Device","type":"NPC","wcid":26555,"cell":"6545022B","place":"dungeon","id":7967,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Strange Device","type":"NPC","wcid":26554,"cell":"6545022C","place":"dungeon","id":7968,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26572,"cell":"6545022E","place":"dungeon","id":7969,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26571,"cell":"6545022F","place":"dungeon","id":7970,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Judge of the Appeasement","type":"NPC","wcid":26542,"cell":"65450232","place":"dungeon","id":7971,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Offering Table","type":"NPC","wcid":26635,"cell":"65450237","place":"dungeon","id":7972,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Sarcophagus of High Matriarch, Ixir Zi","type":"NPC","wcid":26538,"cell":"6545023D","place":"dungeon","id":7973,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Portal to Kivik Lir's Temple","type":"NPC","wcid":26537,"cell":"6545023F","place":"dungeon","id":7974,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Guardian of the Matriarch's Gaze","type":"NPC","wcid":26547,"cell":"65450240","place":"dungeon","id":7975,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Guardian of the High Matriarch","type":"NPC","wcid":26564,"cell":"65450243","place":"dungeon","id":7976,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Ensorcelled Falchion","type":"NPC","wcid":26569,"cell":"6545024C","place":"dungeon","id":7977,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Ixir Zi's, Staff of Eyes","type":"NPC","wcid":26541,"cell":"6545024C","place":"dungeon","id":7978,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Crown of Anointed Blood","type":"NPC","wcid":26535,"cell":"6545024C","place":"dungeon","id":7979,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Strange Device","type":"NPC","wcid":26557,"cell":"6545024D","place":"dungeon","id":7980,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Strange Device","type":"NPC","wcid":26556,"cell":"6545024E","place":"dungeon","id":7981,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26574,"cell":"65450250","place":"dungeon","id":7982,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26573,"cell":"65450251","place":"dungeon","id":7983,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Offering Urn","type":"NPC","wcid":26586,"cell":"65450255","place":"dungeon","id":7984,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Judge of the Sacrifice","type":"NPC","wcid":26567,"cell":"65450258","place":"dungeon","id":7985,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26583,"cell":"6545025C","place":"dungeon","id":7986,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26582,"cell":"6545025D","place":"dungeon","id":7987,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Guardian of the Matriarch's Gaze","type":"NPC","wcid":26565,"cell":"6545025E","place":"dungeon","id":7988,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26585,"cell":"65450262","place":"dungeon","id":7989,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Eye of the Watcher","type":"NPC","wcid":26584,"cell":"65450263","place":"dungeon","id":7990,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Button","type":"NPC","wcid":26534,"cell":"65450285","place":"dungeon","id":7991,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Guardian of the Outer Ward","type":"NPC","wcid":26545,"cell":"65450286","place":"dungeon","id":7992,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Button","type":"NPC","wcid":26654,"cell":"6545026D","place":"dungeon","id":7993,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Button","type":"NPC","wcid":26653,"cell":"6545026E","place":"dungeon","id":7994,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Button","type":"NPC","wcid":26650,"cell":"65450280","place":"dungeon","id":7995,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Button","type":"NPC","wcid":26651,"cell":"65450287","place":"dungeon","id":7996,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Button","type":"NPC","wcid":26652,"cell":"6545028C","place":"dungeon","id":7997,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Button","type":"NPC","wcid":26655,"cell":"6545029F","place":"dungeon","id":7998,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Button","type":"NPC","wcid":26656,"cell":"654502A0","place":"dungeon","id":7999,"desc":"In a dungeon (landblock 6545)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460100","place":"dungeon","id":8000,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460106","place":"dungeon","id":8001,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460107","place":"dungeon","id":8002,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460111","place":"dungeon","id":8003,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65460121","place":"dungeon","id":8004,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65460128","place":"dungeon","id":8005,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Matron Arbiter","type":"NPC","wcid":26552,"cell":"65460133","place":"dungeon","id":8006,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460134","place":"dungeon","id":8007,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6546013C","place":"dungeon","id":8008,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65460143","place":"dungeon","id":8009,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460144","place":"dungeon","id":8010,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460145","place":"dungeon","id":8011,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"6546014C","place":"dungeon","id":8012,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6546014E","place":"dungeon","id":8013,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Matron Arbiter","type":"NPC","wcid":26552,"cell":"65460154","place":"dungeon","id":8014,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460155","place":"dungeon","id":8015,"desc":"In a dungeon (landblock 6546)."}, + {"name":"High Matron Arbiter","type":"NPC","wcid":26551,"cell":"65460157","place":"dungeon","id":8016,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"6546015C","place":"dungeon","id":8017,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"6546015D","place":"dungeon","id":8018,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460164","place":"dungeon","id":8019,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65460166","place":"dungeon","id":8020,"desc":"In a dungeon (landblock 6546)."}, + {"name":"High Matron Arbiter","type":"NPC","wcid":26551,"cell":"65460167","place":"dungeon","id":8021,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"6546016E","place":"dungeon","id":8022,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460172","place":"dungeon","id":8023,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460182","place":"dungeon","id":8024,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65460184","place":"dungeon","id":8025,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"6546018A","place":"dungeon","id":8026,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6546018C","place":"dungeon","id":8027,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Matron Arbiter","type":"NPC","wcid":26552,"cell":"6546018D","place":"dungeon","id":8028,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Matron Arbiter","type":"NPC","wcid":26552,"cell":"6546018F","place":"dungeon","id":8029,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460190","place":"dungeon","id":8030,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460194","place":"dungeon","id":8031,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460195","place":"dungeon","id":8032,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"6546019A","place":"dungeon","id":8033,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654601A1","place":"dungeon","id":8034,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654601A5","place":"dungeon","id":8035,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654601AE","place":"dungeon","id":8036,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654601B2","place":"dungeon","id":8037,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654601B3","place":"dungeon","id":8038,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654601B6","place":"dungeon","id":8039,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654601BC","place":"dungeon","id":8040,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654601C6","place":"dungeon","id":8041,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654601C9","place":"dungeon","id":8042,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654601CD","place":"dungeon","id":8043,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654601CE","place":"dungeon","id":8044,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654601D1","place":"dungeon","id":8045,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Matron Arbiter","type":"NPC","wcid":26552,"cell":"654601D4","place":"dungeon","id":8046,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654601DC","place":"dungeon","id":8047,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654601DE","place":"dungeon","id":8048,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654601E6","place":"dungeon","id":8049,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654601E9","place":"dungeon","id":8050,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654601ED","place":"dungeon","id":8051,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654601F3","place":"dungeon","id":8052,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654601FA","place":"dungeon","id":8053,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Matron Arbiter","type":"NPC","wcid":26552,"cell":"654601FB","place":"dungeon","id":8054,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460203","place":"dungeon","id":8055,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460205","place":"dungeon","id":8056,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"6546020E","place":"dungeon","id":8057,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"6546020F","place":"dungeon","id":8058,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65460210","place":"dungeon","id":8059,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65460213","place":"dungeon","id":8060,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460219","place":"dungeon","id":8061,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460220","place":"dungeon","id":8062,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460223","place":"dungeon","id":8063,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460230","place":"dungeon","id":8064,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460237","place":"dungeon","id":8065,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460238","place":"dungeon","id":8066,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65460239","place":"dungeon","id":8067,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"6546023C","place":"dungeon","id":8068,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460242","place":"dungeon","id":8069,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460245","place":"dungeon","id":8070,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460252","place":"dungeon","id":8071,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460253","place":"dungeon","id":8072,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460258","place":"dungeon","id":8073,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"65460259","place":"dungeon","id":8074,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"6546025F","place":"dungeon","id":8075,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460260","place":"dungeon","id":8076,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"65460269","place":"dungeon","id":8077,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"6546026E","place":"dungeon","id":8078,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460271","place":"dungeon","id":8079,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"6546027E","place":"dungeon","id":8080,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"6546028D","place":"dungeon","id":8081,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460293","place":"dungeon","id":8082,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654602A0","place":"dungeon","id":8083,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654602A1","place":"dungeon","id":8084,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654602AB","place":"dungeon","id":8085,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654602AC","place":"dungeon","id":8086,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654602B1","place":"dungeon","id":8087,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654602B4","place":"dungeon","id":8088,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654602B8","place":"dungeon","id":8089,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654602BA","place":"dungeon","id":8090,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654602BF","place":"dungeon","id":8091,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654602C6","place":"dungeon","id":8092,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654602C9","place":"dungeon","id":8093,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654602D7","place":"dungeon","id":8094,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654602D8","place":"dungeon","id":8095,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654602DD","place":"dungeon","id":8096,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654602E2","place":"dungeon","id":8097,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"654602F2","place":"dungeon","id":8098,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654602F3","place":"dungeon","id":8099,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"654602FD","place":"dungeon","id":8100,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"654602FF","place":"dungeon","id":8101,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460306","place":"dungeon","id":8102,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"65460310","place":"dungeon","id":8103,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Guardian of Fury","type":"NPC","wcid":26550,"cell":"65460312","place":"dungeon","id":8104,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Guardian of the Restless Dead","type":"NPC","wcid":26546,"cell":"65460319","place":"dungeon","id":8105,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Arbiter","type":"NPC","wcid":26548,"cell":"6546031A","place":"dungeon","id":8106,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Guardian of Fury","type":"NPC","wcid":26550,"cell":"6546031D","place":"dungeon","id":8107,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Offering Table","type":"NPC","wcid":26635,"cell":"65460320","place":"dungeon","id":8108,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Guardian of the Sacrificial Urns","type":"NPC","wcid":26566,"cell":"65460323","place":"dungeon","id":8109,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Guardian of the Restless Dead","type":"NPC","wcid":26546,"cell":"65460329","place":"dungeon","id":8110,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Arbiter","type":"NPC","wcid":26548,"cell":"6546032A","place":"dungeon","id":8111,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Judge of the Appeasement","type":"NPC","wcid":26542,"cell":"6546032C","place":"dungeon","id":8112,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Offering Table","type":"NPC","wcid":26635,"cell":"65460331","place":"dungeon","id":8113,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Offering Table","type":"NPC","wcid":26635,"cell":"65460338","place":"dungeon","id":8114,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Guardian of the Sacrificial Urns","type":"NPC","wcid":26566,"cell":"6546033B","place":"dungeon","id":8115,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Judge of the Appeasement","type":"NPC","wcid":26542,"cell":"65460344","place":"dungeon","id":8116,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Offering Table","type":"NPC","wcid":26635,"cell":"65460349","place":"dungeon","id":8117,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Judge of the Sacrifice","type":"NPC","wcid":26567,"cell":"6546035D","place":"dungeon","id":8118,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Judge of the Sacrifice","type":"NPC","wcid":26567,"cell":"65460361","place":"dungeon","id":8119,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Offering Urn","type":"NPC","wcid":26669,"cell":"65460350","place":"dungeon","id":8120,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Offering Urn","type":"NPC","wcid":26668,"cell":"6546035B","place":"dungeon","id":8121,"desc":"In a dungeon (landblock 6546)."}, + {"name":"Guardian of the Crypt","type":"NPC","wcid":26562,"cell":"65470100","place":"dungeon","id":8122,"desc":"In a dungeon (landblock 6547)."}, + {"name":"Guardian of the Crypt","type":"NPC","wcid":26558,"cell":"65470102","place":"dungeon","id":8123,"desc":"In a dungeon (landblock 6547)."}, + {"name":"Guardian of the Crypt","type":"NPC","wcid":26560,"cell":"65470104","place":"dungeon","id":8124,"desc":"In a dungeon (landblock 6547)."}, + {"name":"Guardian of the Crypt","type":"NPC","wcid":26563,"cell":"6547013C","place":"dungeon","id":8125,"desc":"In a dungeon (landblock 6547)."}, + {"name":"Guardian of the Crypt","type":"NPC","wcid":26561,"cell":"6547016C","place":"dungeon","id":8126,"desc":"In a dungeon (landblock 6547)."}, + {"name":"Guardian of the Crypt","type":"NPC","wcid":26559,"cell":"65470231","place":"dungeon","id":8127,"desc":"In a dungeon (landblock 6547)."}, + {"name":"Statue of Bael'Zharon, the Hopeslayer","type":"NPC","wcid":36007,"cell":"65480140","place":"dungeon","id":8128,"desc":"In a dungeon (landblock 6548)."}, + {"name":"Calitoth","type":"NPC","wcid":48937,"cell":"654C069C","place":"dungeon","id":8129,"desc":"Apprentice Researcher. In a dungeon (landblock 654C)."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":72493,"cell":"654C0676","place":"dungeon","id":8130,"desc":"In a dungeon (landblock 654C)."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":72494,"cell":"654C06AA","place":"dungeon","id":8131,"desc":"In a dungeon (landblock 654C)."}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":72495,"cell":"654C065C","place":"dungeon","id":8132,"desc":"In a dungeon (landblock 654C)."}, + {"name":"Hall of Agony","type":"NPC","wcid":72523,"cell":"654D02CF","place":"dungeon","id":8133,"desc":"In a dungeon (landblock 654D)."}, + {"name":"Large Enchanted Mnemosyne","type":"NPC","wcid":72500,"cell":"654D04D8","place":"dungeon","id":8134,"desc":"In a dungeon (landblock 654D)."}, + {"name":"Spirit of Bist'elle","type":"NPC","wcid":72501,"cell":"654D04BB","place":"dungeon","id":8135,"desc":"The Lady of Mysteries. In a dungeon (landblock 654D)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"65D50000","place":"outdoor","ns":68.46,"ew":-21.04,"id":8136}, + {"name":"Verdentine Magnan","type":"NPC","wcid":19127,"cell":"65DE0000","place":"outdoor","ns":75.75,"ew":-20.35,"id":8137,"desc":"Entomologist."}, + {"name":"Lever Box","type":"NPC","wcid":46573,"cell":"665E011D","place":"dungeon","id":8138,"desc":"In Falatacot Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"675701C7","place":"dungeon","id":8139,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570191","place":"dungeon","id":8140,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"675701DC","place":"dungeon","id":8141,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570181","place":"dungeon","id":8142,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"675701CB","place":"dungeon","id":8143,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570195","place":"dungeon","id":8144,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"675701D1","place":"dungeon","id":8145,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"6757019B","place":"dungeon","id":8146,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"675701BD","place":"dungeon","id":8147,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"675701C1","place":"dungeon","id":8148,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"675701A1","place":"dungeon","id":8149,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570184","place":"dungeon","id":8150,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570175","place":"dungeon","id":8151,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570164","place":"dungeon","id":8152,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570154","place":"dungeon","id":8153,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"6757013F","place":"dungeon","id":8154,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570132","place":"dungeon","id":8155,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570138","place":"dungeon","id":8156,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"6757014B","place":"dungeon","id":8157,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"6757015E","place":"dungeon","id":8158,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"6757016E","place":"dungeon","id":8159,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570182","place":"dungeon","id":8160,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570131","place":"dungeon","id":8161,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"67570183","place":"dungeon","id":8162,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72618,"cell":"675701DD","place":"dungeon","id":8163,"desc":"In Tanada Toresen Temple."}, + {"name":"Tanada Nanjou Kutekei","type":"NPC","wcid":72624,"cell":"6757027A","place":"dungeon","id":8164,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72651,"cell":"6757010B","place":"dungeon","id":8165,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72651,"cell":"67570108","place":"dungeon","id":8166,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72651,"cell":"6757010A","place":"dungeon","id":8167,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72651,"cell":"67570113","place":"dungeon","id":8168,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72651,"cell":"67570115","place":"dungeon","id":8169,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72651,"cell":"67570109","place":"dungeon","id":8170,"desc":"In Tanada Toresen Temple."}, + {"name":"Something","type":"NPC","wcid":72651,"cell":"67570112","place":"dungeon","id":8171,"desc":"In Tanada Toresen Temple."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"68B20000","place":"outdoor","ns":40.76,"ew":-18.69,"id":8172}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"69AB0000","place":"outdoor","ns":35.01,"ew":-17.78,"id":8173}, + {"name":"Kai Mallan, Sho Enchanter","type":"NPC","wcid":15860,"cell":"69D50100","place":"dungeon","id":8174,"desc":"Entrepreneur. In a dungeon (landblock 69D5)."}, + {"name":"Archmage","type":"Vendor","wcid":1369,"cell":"69D70102","place":"building","ns":70.5,"ew":-17.31,"id":8175}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"69D70000","place":"outdoor","ns":70.43,"ew":-17.29,"id":8176}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"6AC30000","place":"outdoor","ns":54.09,"ew":-17.09,"id":8177}, + {"name":"Peddler","type":"Vendor","wcid":1390,"cell":"6AC30000","place":"outdoor","ns":54.09,"ew":-16.99,"id":8178}, + {"name":"Jolly Snowman","type":"Vendor","wcid":7883,"cell":"6ADB0102","place":"building","ns":73.61,"ew":-16.4,"id":8179,"desc":"Purveyor of Ice."}, + {"name":"Archmage","type":"Vendor","wcid":1371,"cell":"6BE20100","place":"building","ns":79.2,"ew":-15.6,"id":8180}, + {"name":"Roaming Bowyer","type":"Vendor","wcid":1378,"cell":"6BE20100","place":"building","ns":79.19,"ew":-15.62,"id":8181,"desc":"Bowyer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"6BE20000","place":"outdoor","ns":79.24,"ew":-15.73,"id":8182}, + {"name":"Snowman","type":"Vendor","wcid":5765,"cell":"6EDB0102","place":"building","ns":73.81,"ew":-13.7,"id":8183}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"70110000","place":"outdoor","ns":-87.61,"ew":-12.27,"id":8184}, + {"name":"Jolly Snowman","type":"Vendor","wcid":7883,"cell":"70B80102","place":"dungeon","id":8185,"desc":"Purveyor of Ice. In a dungeon (landblock 70B8)."}, + {"name":"Mysterious Hatch","type":"NPC","wcid":32807,"cell":"7109001F","place":"outdoor","ns":-94.13,"ew":-11.17,"id":8186}, + {"name":"Exploration Marker","type":"NPC","wcid":39795,"cell":"7109001F","place":"outdoor","ns":-94.06,"ew":-11.16,"id":8187}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"72020134","place":"dungeon","id":8188,"desc":"In a dungeon (landblock 7202)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"72020278","place":"dungeon","id":8189,"desc":"Exploration Society Agent. In a dungeon (landblock 7202)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"7202032A","place":"dungeon","id":8190,"desc":"Shopkeeper. In a dungeon (landblock 7202)."}, + {"name":"Jonathan","type":"NPC","wcid":29325,"cell":"720201B0","place":"dungeon","id":8191,"desc":"Exploration Society Agent. In a dungeon (landblock 7202)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"720201AD","place":"dungeon","id":8192,"desc":"Exploration Society Agent. In a dungeon (landblock 7202)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"720201B1","place":"dungeon","id":8193,"desc":"Exploration Society Agent. In a dungeon (landblock 7202)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"7202023A","place":"dungeon","id":8194,"desc":"Exploration Society Agent. In a dungeon (landblock 7202)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"720201F4","place":"dungeon","id":8195,"desc":"Exploration Society Agent. In a dungeon (landblock 7202)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"720201F6","place":"dungeon","id":8196,"desc":"Exploration Society Agent. In a dungeon (landblock 7202)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"7202032B","place":"dungeon","id":8197,"desc":"Exploration Society Agent. In a dungeon (landblock 7202)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"7202032B","place":"dungeon","id":8198,"desc":"Herald. In a dungeon (landblock 7202)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"7202032C","place":"dungeon","id":8199,"desc":"Exploration Society Agent. In a dungeon (landblock 7202)."}, + {"name":"Sentry","type":"NPC","wcid":30993,"cell":"720202C2","place":"dungeon","id":8200,"desc":"Exploration Society Agent. In a dungeon (landblock 7202)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"72030134","place":"dungeon","id":8201,"desc":"In a dungeon (landblock 7203)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"72030278","place":"dungeon","id":8202,"desc":"Exploration Society Agent. In a dungeon (landblock 7203)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"7203032A","place":"dungeon","id":8203,"desc":"Shopkeeper. In a dungeon (landblock 7203)."}, + {"name":"Jonathan","type":"NPC","wcid":29325,"cell":"720301B0","place":"dungeon","id":8204,"desc":"Exploration Society Agent. In a dungeon (landblock 7203)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"720301AD","place":"dungeon","id":8205,"desc":"Exploration Society Agent. In a dungeon (landblock 7203)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"720301B1","place":"dungeon","id":8206,"desc":"Exploration Society Agent. In a dungeon (landblock 7203)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"7203023A","place":"dungeon","id":8207,"desc":"Exploration Society Agent. In a dungeon (landblock 7203)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"720301F4","place":"dungeon","id":8208,"desc":"Exploration Society Agent. In a dungeon (landblock 7203)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"720301F6","place":"dungeon","id":8209,"desc":"Exploration Society Agent. In a dungeon (landblock 7203)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"7203032B","place":"dungeon","id":8210,"desc":"Exploration Society Agent. In a dungeon (landblock 7203)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"7203032B","place":"dungeon","id":8211,"desc":"Herald. In a dungeon (landblock 7203)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"7203032C","place":"dungeon","id":8212,"desc":"Exploration Society Agent. In a dungeon (landblock 7203)."}, + {"name":"Sentry","type":"NPC","wcid":30993,"cell":"720302C2","place":"dungeon","id":8213,"desc":"Exploration Society Agent. In a dungeon (landblock 7203)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"72040134","place":"dungeon","id":8214,"desc":"In a dungeon (landblock 7204)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"72040278","place":"dungeon","id":8215,"desc":"Exploration Society Agent. In a dungeon (landblock 7204)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"7204032A","place":"dungeon","id":8216,"desc":"Shopkeeper. In a dungeon (landblock 7204)."}, + {"name":"Jonathan","type":"NPC","wcid":29325,"cell":"720401B0","place":"dungeon","id":8217,"desc":"Exploration Society Agent. In a dungeon (landblock 7204)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"720401AD","place":"dungeon","id":8218,"desc":"Exploration Society Agent. In a dungeon (landblock 7204)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"720401B1","place":"dungeon","id":8219,"desc":"Exploration Society Agent. In a dungeon (landblock 7204)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"7204023A","place":"dungeon","id":8220,"desc":"Exploration Society Agent. In a dungeon (landblock 7204)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"720401F4","place":"dungeon","id":8221,"desc":"Exploration Society Agent. In a dungeon (landblock 7204)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"720401F6","place":"dungeon","id":8222,"desc":"Exploration Society Agent. In a dungeon (landblock 7204)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"7204032B","place":"dungeon","id":8223,"desc":"Exploration Society Agent. In a dungeon (landblock 7204)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"7204032B","place":"dungeon","id":8224,"desc":"Herald. In a dungeon (landblock 7204)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"7204032C","place":"dungeon","id":8225,"desc":"Exploration Society Agent. In a dungeon (landblock 7204)."}, + {"name":"Sentry","type":"NPC","wcid":30993,"cell":"720402C2","place":"dungeon","id":8226,"desc":"Exploration Society Agent. In a dungeon (landblock 7204)."}, + {"name":"Archmage","type":"Vendor","wcid":1369,"cell":"72170106","place":"building","ns":-83.09,"ew":-10.6,"id":8227}, + {"name":"Royal Scout","type":"NPC","wcid":40247,"cell":"72C80025","place":"outdoor","ns":58.52,"ew":-10.31,"id":8228,"desc":"Royal Guard."}, + {"name":"Tthuun Counter Stopgap","type":"NPC","wcid":72829,"cell":"72C9001B","place":"outdoor","ns":59.1,"ew":-10.36,"id":8229,"desc":"Stopgap."}, + {"name":"Giant Snowman","type":"Vendor","wcid":5767,"cell":"72D20000","place":"outdoor","ns":66.8,"ew":-10.31,"id":8230}, + {"name":"Roaming Bowyer","type":"Vendor","wcid":1378,"cell":"72D40102","place":"building","ns":68.01,"ew":-9.99,"id":8231,"desc":"Bowyer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"73020134","place":"dungeon","id":8232,"desc":"In a dungeon (landblock 7302)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"73020278","place":"dungeon","id":8233,"desc":"Exploration Society Agent. In a dungeon (landblock 7302)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"7302032A","place":"dungeon","id":8234,"desc":"Shopkeeper. In a dungeon (landblock 7302)."}, + {"name":"Jonathan","type":"NPC","wcid":29325,"cell":"730201B0","place":"dungeon","id":8235,"desc":"Exploration Society Agent. In a dungeon (landblock 7302)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"730201AD","place":"dungeon","id":8236,"desc":"Exploration Society Agent. In a dungeon (landblock 7302)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"730201B1","place":"dungeon","id":8237,"desc":"Exploration Society Agent. In a dungeon (landblock 7302)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"7302023A","place":"dungeon","id":8238,"desc":"Exploration Society Agent. In a dungeon (landblock 7302)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"730201F4","place":"dungeon","id":8239,"desc":"Exploration Society Agent. In a dungeon (landblock 7302)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"730201F6","place":"dungeon","id":8240,"desc":"Exploration Society Agent. In a dungeon (landblock 7302)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"7302032B","place":"dungeon","id":8241,"desc":"Exploration Society Agent. In a dungeon (landblock 7302)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"7302032B","place":"dungeon","id":8242,"desc":"Herald. In a dungeon (landblock 7302)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"7302032C","place":"dungeon","id":8243,"desc":"Exploration Society Agent. In a dungeon (landblock 7302)."}, + {"name":"Sentry","type":"NPC","wcid":30993,"cell":"730202C2","place":"dungeon","id":8244,"desc":"Exploration Society Agent. In a dungeon (landblock 7302)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"73030134","place":"dungeon","id":8245,"desc":"In a dungeon (landblock 7303)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"73030278","place":"dungeon","id":8246,"desc":"Exploration Society Agent. In a dungeon (landblock 7303)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"7303032A","place":"dungeon","id":8247,"desc":"Shopkeeper. In a dungeon (landblock 7303)."}, + {"name":"Jonathan","type":"NPC","wcid":29325,"cell":"730301B0","place":"dungeon","id":8248,"desc":"Exploration Society Agent. In a dungeon (landblock 7303)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"730301AD","place":"dungeon","id":8249,"desc":"Exploration Society Agent. In a dungeon (landblock 7303)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"730301B1","place":"dungeon","id":8250,"desc":"Exploration Society Agent. In a dungeon (landblock 7303)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"7303023A","place":"dungeon","id":8251,"desc":"Exploration Society Agent. In a dungeon (landblock 7303)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"730301F4","place":"dungeon","id":8252,"desc":"Exploration Society Agent. In a dungeon (landblock 7303)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"730301F6","place":"dungeon","id":8253,"desc":"Exploration Society Agent. In a dungeon (landblock 7303)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"7303032B","place":"dungeon","id":8254,"desc":"Exploration Society Agent. In a dungeon (landblock 7303)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"7303032B","place":"dungeon","id":8255,"desc":"Herald. In a dungeon (landblock 7303)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"7303032C","place":"dungeon","id":8256,"desc":"Exploration Society Agent. In a dungeon (landblock 7303)."}, + {"name":"Sentry","type":"NPC","wcid":30993,"cell":"730302C2","place":"dungeon","id":8257,"desc":"Exploration Society Agent. In a dungeon (landblock 7303)."}, + {"name":"Ulgrim the Unappreciated","type":"NPC","wcid":26457,"cell":"73080101","place":"building","ns":-94.81,"ew":-9.73,"id":8258,"desc":"Mini-Ulgrim."}, + {"name":"Dark Cavern","type":"NPC","wcid":43788,"cell":"73ED0101","place":"dungeon","id":8259,"desc":"In a dungeon (landblock 73ED)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"759C0000","place":"outdoor","ns":23.46,"ew":-7.73,"id":8260}, + {"name":"Merchant","type":"Vendor","wcid":1388,"cell":"759C0103","place":"building","ns":23.5,"ew":-7.83,"id":8261}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"75B80000","place":"outdoor","ns":45.97,"ew":-7.97,"id":8262}, + {"name":"Archmage","type":"Vendor","wcid":1369,"cell":"75B80102","place":"building","ns":45.99,"ew":-7.99,"id":8263}, + {"name":"Mortified Soldier","type":"NPC","wcid":70351,"cell":"76E90104","place":"underground","ns":85.38,"ew":-7.07,"id":8264}, + {"name":"Crude Statue","type":"NPC","wcid":30626,"cell":"77DA0000","place":"outdoor","ns":72.98,"ew":-6.57,"id":8265}, + {"name":"Healer","type":"Vendor","wcid":1386,"cell":"77DF0102","place":"dungeon","id":8266,"desc":"In a dungeon (landblock 77DF)."}, + {"name":"Merchant","type":"Vendor","wcid":1389,"cell":"77DF0102","place":"dungeon","id":8267,"desc":"In a dungeon (landblock 77DF)."}, + {"name":"Pillar","type":"NPC","wcid":43805,"cell":"77E701E3","place":"building","ns":82.52,"ew":-6.58,"id":8268}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":43846,"cell":"77E80001","place":"outdoor","ns":83.7,"ew":-6.7,"id":8269}, + {"name":"Shemza","type":"NPC","wcid":31964,"cell":"79110040","place":"outdoor","ns":-87.57,"ew":-4.44,"id":8270}, + {"name":"Lurza","type":"NPC","wcid":31961,"cell":"79110040","place":"outdoor","ns":-87.6,"ew":-4.4,"id":8271}, + {"name":"Dmesne","type":"NPC","wcid":31962,"cell":"79110040","place":"outdoor","ns":-87.64,"ew":-4.36,"id":8272}, + {"name":"Rhujun","type":"NPC","wcid":31963,"cell":"79110040","place":"outdoor","ns":-87.65,"ew":-4.45,"id":8273}, + {"name":"Pillar","type":"NPC","wcid":43806,"cell":"79E903B4","place":"dungeon","id":8274,"desc":"In a dungeon (landblock 79E9)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"7ACA0000","place":"outdoor","ns":59.77,"ew":-4.17,"id":8275}, + {"name":"Merchant","type":"Vendor","wcid":1387,"cell":"7ACA0110","place":"building","ns":59.8,"ew":-4.21,"id":8276}, + {"name":"Archmage","type":"Vendor","wcid":1370,"cell":"7ACA0117","place":"building","ns":59.79,"ew":-4.08,"id":8277}, + {"name":"Wandering Bowyer","type":"Vendor","wcid":1380,"cell":"7ACA013C","place":"building","ns":59.7,"ew":-4.12,"id":8278,"desc":"Bowyer."}, + {"name":"Collector","type":"NPC","wcid":3917,"cell":"7ACA0135","place":"building","ns":59.71,"ew":-4.07,"id":8279,"desc":"Trophy Collector."}, + {"name":"Halvor","type":"NPC","wcid":44989,"cell":"7AE80107","place":"building","ns":83.74,"ew":-4.26,"id":8280}, + {"name":"Leilah","type":"NPC","wcid":51961,"cell":"7AE80002","place":"outdoor","ns":83.76,"ew":-4.27,"id":8281,"desc":"Wight Hunter."}, + {"name":"Lady Daenerah","type":"NPC","wcid":43988,"cell":"7AE80002","place":"outdoor","ns":83.79,"ew":-4.33,"id":8282,"desc":"Royal Knight Mage."}, + {"name":"Sir Learth","type":"NPC","wcid":43847,"cell":"7AE80002","place":"outdoor","ns":83.8,"ew":-4.33,"id":8283,"desc":"Royal Knight Mage."}, + {"name":"Sir Donovan","type":"NPC","wcid":43804,"cell":"7AE80002","place":"outdoor","ns":83.81,"ew":-4.34,"id":8284,"desc":"Royal Knight."}, + {"name":"Hunter","type":"NPC","wcid":43740,"cell":"7AE80002","place":"outdoor","ns":83.78,"ew":-4.29,"id":8285,"desc":"Snow Tusker Annihilator."}, + {"name":"Gregoria, Gurog Destroyer","type":"NPC","wcid":43495,"cell":"7AE80002","place":"outdoor","ns":83.78,"ew":-4.31,"id":8286,"desc":"Gurog Hunter."}, + {"name":"Boone","type":"NPC","wcid":52286,"cell":"7AE80001","place":"outdoor","ns":83.7,"ew":-4.29,"id":8287,"desc":"Crystal Hunter."}, + {"name":"Kumiko","type":"NPC","wcid":51960,"cell":"7AE80001","place":"outdoor","ns":83.71,"ew":-4.27,"id":8288,"desc":"Spirit Hunter."}, + {"name":"George","type":"NPC","wcid":51959,"cell":"7AE80001","place":"outdoor","ns":83.72,"ew":-4.28,"id":8289,"desc":"Frost Golem Hunter."}, + {"name":"Archmage Ichihiri","type":"NPC","wcid":43741,"cell":"7AE80001","place":"outdoor","ns":83.75,"ew":-4.28,"id":8290,"desc":"Arcanum Investigator."}, + {"name":"Stranger in Town","type":"NPC","wcid":14412,"cell":"7B610105","place":"building","ns":-23.67,"ew":-2.82,"id":8291,"desc":"Bandit."}, + {"name":"Peddler","type":"Vendor","wcid":1391,"cell":"7B790000","place":"outdoor","ns":-4.79,"ew":-2.93,"id":8292}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"7B980000","place":"outdoor","ns":19.71,"ew":-3.31,"id":8293}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C630000","place":"outdoor","ns":-22.05,"ew":-2.36,"id":8294}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C630000","place":"outdoor","ns":-21.98,"ew":-2.36,"id":8295}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C630000","place":"outdoor","ns":-22.01,"ew":-2.41,"id":8296}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C630000","place":"outdoor","ns":-22.14,"ew":-2.38,"id":8297}, + {"name":"Tackle Master","type":"NPC","wcid":23336,"cell":"7C630100","place":"building","ns":-22.02,"ew":-2.17,"id":8298,"desc":"Pro Fisherman."}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C630000","place":"outdoor","ns":-22.01,"ew":-2.62,"id":8299}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C630000","place":"outdoor","ns":-21.98,"ew":-2.34,"id":8300}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C630000","place":"outdoor","ns":-21.98,"ew":-2.38,"id":8301}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C630000","place":"outdoor","ns":-22.0,"ew":-2.4,"id":8302}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C630000","place":"outdoor","ns":-22.04,"ew":-2.4,"id":8303}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C630000","place":"outdoor","ns":-22.05,"ew":-2.34,"id":8304}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C630000","place":"outdoor","ns":-22.07,"ew":-2.41,"id":8305}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C640000","place":"outdoor","ns":-21.86,"ew":-2.37,"id":8306}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C640000","place":"outdoor","ns":-21.91,"ew":-2.36,"id":8307}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"7C640000","place":"outdoor","ns":-21.88,"ew":-2.34,"id":8308}, + {"name":"Archmage","type":"Vendor","wcid":1370,"cell":"7C73011B","place":"dungeon","id":8309,"desc":"In a dungeon (landblock 7C73)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"7CD10000","place":"outdoor","ns":65.91,"ew":-2.59,"id":8310}, + {"name":"Exploration Marker","type":"NPC","wcid":39772,"cell":"7CD20108","place":"building","ns":66.17,"ew":-2.29,"id":8311}, + {"name":"Lubziklan al-Luq","type":"NPC","wcid":5178,"cell":"7D630000","place":"outdoor","ns":-22.39,"ew":-1.85,"id":8312,"desc":"Merchant."}, + {"name":"Nuya bint Mulud the Grocer","type":"Vendor","wcid":1040,"cell":"7D640114","place":"building","ns":-21.43,"ew":-1.62,"id":8313,"desc":"Grocer."}, + {"name":"Arlad ibn Mulud the Tailor","type":"Vendor","wcid":1047,"cell":"7D64010E","place":"building","ns":-21.37,"ew":-1.58,"id":8314,"desc":"Tailor."}, + {"name":"Mulud al-Iyar the Healer","type":"Vendor","wcid":1041,"cell":"7D640000","place":"outdoor","ns":-21.37,"ew":-1.59,"id":8315,"desc":"Healer."}, + {"name":"Buray ibn Tamsa the Blacksmith","type":"Vendor","wcid":1038,"cell":"7D640100","place":"building","ns":-21.48,"ew":-1.58,"id":8316,"desc":"Blacksmith."}, + {"name":"Ladim al-Faji the Bowyer","type":"Vendor","wcid":1039,"cell":"7D640100","place":"building","ns":-21.47,"ew":-1.59,"id":8317,"desc":"Bowyer."}, + {"name":"Rahira bint Hisan the Shopkeeper","type":"Vendor","wcid":1045,"cell":"7D64012D","place":"building","ns":-21.58,"ew":-1.59,"id":8318,"desc":"Shopkeeper."}, + {"name":"Wasifa al-Kani the Scribe","type":"Vendor","wcid":1044,"cell":"7D640137","place":"building","ns":-21.6,"ew":-1.57,"id":8319,"desc":"Scribe."}, + {"name":"Tariqana bint Hin the Jeweler","type":"Vendor","wcid":1042,"cell":"7D64012F","place":"building","ns":-21.62,"ew":-1.59,"id":8320,"desc":"Jeweler."}, + {"name":"Barkeep Jubal al-Baljad","type":"Vendor","wcid":1034,"cell":"7D640141","place":"building","ns":-21.72,"ew":-1.56,"id":8321,"desc":"Barkeeper."}, + {"name":"Archmage Inyamkaya bint Ruz","type":"Vendor","wcid":2307,"cell":"7D64012E","place":"building","ns":-21.57,"ew":-1.59,"id":8322,"desc":"Archmage."}, + {"name":"Akyafi ibn Sumwar","type":"NPC","wcid":5365,"cell":"7D640000","place":"outdoor","ns":-21.68,"ew":-1.6,"id":8323,"desc":"Translator."}, + {"name":"Drawohan the Gem Seller","type":"Vendor","wcid":9424,"cell":"7D640000","place":"outdoor","ns":-21.74,"ew":-1.62,"id":8324,"desc":"Gem Seller."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"7D64014C","place":"building","ns":-21.79,"ew":-1.58,"id":8325,"desc":"Mage."}, + {"name":"Wedding Planner","type":"Vendor","wcid":14930,"cell":"7D64014C","place":"building","ns":-21.8,"ew":-1.57,"id":8326,"desc":"Planner of Weddings."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20215,"cell":"7D640164","place":"building","ns":-21.49,"ew":-1.33,"id":8327,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20217,"cell":"7D64016E","place":"building","ns":-21.46,"ew":-1.3,"id":8328,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":20205,"cell":"7D640166","place":"building","ns":-21.49,"ew":-1.28,"id":8329,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":20206,"cell":"7D640165","place":"building","ns":-21.5,"ew":-1.34,"id":8330,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20218,"cell":"7D640171","place":"building","ns":-21.46,"ew":-1.3,"id":8331,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20216,"cell":"7D640167","place":"building","ns":-21.49,"ew":-1.27,"id":8332,"desc":"Master Archmage."}, + {"name":"Small Creepy Statue","type":"NPC","wcid":25992,"cell":"7D640000","place":"outdoor","ns":-21.23,"ew":-1.69,"id":8333}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"7D640000","place":"outdoor","ns":-21.51,"ew":-1.79,"id":8334}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"7D640000","place":"outdoor","ns":-21.81,"ew":-1.72,"id":8335}, + {"name":"Apprentice Alchemist","type":"NPC","wcid":27741,"cell":"7D640000","place":"outdoor","ns":-21.57,"ew":-1.57,"id":8336}, + {"name":"Mara al-Luq","type":"NPC","wcid":5179,"cell":"7D64013E","place":"building","ns":-21.67,"ew":-1.59,"id":8337,"desc":"Society Agent."}, + {"name":"Ma'yad ibn Ibsar","type":"NPC","wcid":5366,"cell":"7D64013E","place":"building","ns":-21.69,"ew":-1.58,"id":8338,"desc":"Merchant."}, + {"name":"Salvaging Forge","type":"NPC","wcid":30461,"cell":"7D640000","place":"outdoor","ns":-21.47,"ew":-1.7,"id":8339}, + {"name":"Alchemy Forge","type":"NPC","wcid":30465,"cell":"7D640000","place":"outdoor","ns":-21.6,"ew":-1.53,"id":8340}, + {"name":"Cooking Forge","type":"NPC","wcid":30466,"cell":"7D640000","place":"outdoor","ns":-21.33,"ew":-1.59,"id":8341}, + {"name":"Fletching Forge","type":"NPC","wcid":30467,"cell":"7D640000","place":"outdoor","ns":-21.48,"ew":-1.55,"id":8342}, + {"name":"Lockpick Forge","type":"NPC","wcid":30460,"cell":"7D640000","place":"outdoor","ns":-21.4,"ew":-1.55,"id":8343}, + {"name":"Ghaziyah","type":"NPC","wcid":44896,"cell":"7D64000D","place":"outdoor","ns":-21.52,"ew":-1.79,"id":8344,"desc":"Lifestone Greeter."}, + {"name":"Pathwarden Qanara bint Qolosh","type":"NPC","wcid":33616,"cell":"7D640015","place":"outdoor","ns":-21.51,"ew":-1.71,"id":8345,"desc":"Pathwarden Greeter."}, + {"name":"A'shadieeyah","type":"NPC","wcid":44892,"cell":"7D640140","place":"building","ns":-21.73,"ew":-1.57,"id":8346,"desc":"Bartender Greeter."}, + {"name":"Iqbal","type":"Vendor","wcid":42429,"cell":"7D64010E","place":"building","ns":-21.37,"ew":-1.6,"id":8347,"desc":"Master Tailor."}, + {"name":"Iaret","type":"Vendor","wcid":49517,"cell":"7D64012E","place":"building","ns":-21.58,"ew":-1.59,"id":8348,"desc":"Geomancer."}, + {"name":"Nawaf","type":"NPC","wcid":42721,"cell":"7D64010E","place":"building","ns":-21.38,"ew":-1.57,"id":8349,"desc":"Barber."}, + {"name":"Scrivener of Void Magic","type":"Vendor","wcid":43354,"cell":"7D640035","place":"outdoor","ns":-21.47,"ew":-1.33,"id":8350,"desc":"Master Archmage."}, + {"name":"Bhravarn ibn Salizim","type":"NPC","wcid":32836,"cell":"7D64001D","place":"outdoor","ns":-21.51,"ew":-1.59,"id":8351,"desc":"Master Weaponsmith."}, + {"name":"Contract Broker","type":"Vendor","wcid":44189,"cell":"7D64001B","place":"outdoor","ns":-21.68,"ew":-1.61,"id":8352,"desc":"Armorer."}, + {"name":"Abd-al-Matin Basshir","type":"NPC","wcid":44207,"cell":"7D64001B","place":"outdoor","ns":-21.68,"ew":-1.62,"id":8353}, + {"name":"Arcanum Refurbisher","type":"NPC","wcid":32085,"cell":"7D64014C","place":"building","ns":-21.79,"ew":-1.57,"id":8354,"desc":"Renovation Specialist."}, + {"name":"Tailor's Apprentice","type":"NPC","wcid":42737,"cell":"7D64010E","place":"building","ns":-21.37,"ew":-1.59,"id":8355}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"7D640018","place":"outdoor","ns":-21.19,"ew":-1.67,"id":8356,"desc":"Soldier."}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"7D64002C","place":"outdoor","ns":-21.58,"ew":-1.36,"id":8357,"desc":"Soldier."}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"7D640019","place":"outdoor","ns":-21.93,"ew":-1.6,"id":8358,"desc":"Soldier."}, + {"name":"Sentry","type":"NPC","wcid":12725,"cell":"7D670000","place":"outdoor","ns":-18.88,"ew":-1.23,"id":8359,"desc":"Soldier."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"7D680000","place":"outdoor","ns":-18.69,"ew":-1.5,"id":8360}, + {"name":"Atqur the Shopkeeper","type":"Vendor","wcid":4708,"cell":"7D680100","place":"building","ns":-18.68,"ew":-1.41,"id":8361,"desc":"Shopkeeper."}, + {"name":"Nasun ibn Tifar","type":"NPC","wcid":5180,"cell":"7D680103","place":"building","ns":-18.61,"ew":-1.41,"id":8362,"desc":"Citizen of Yaraq."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"7D910000","place":"outdoor","ns":14.08,"ew":-1.3,"id":8363}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"7DAE0000","place":"outdoor","ns":37.66,"ew":-1.28,"id":8364}, + {"name":"Archmage","type":"Vendor","wcid":1369,"cell":"7DAE0000","place":"outdoor","ns":37.73,"ew":-1.21,"id":8365}, + {"name":"Strange Crystal","type":"NPC","wcid":43896,"cell":"7E02015E","place":"dungeon","id":8366,"desc":"In a dungeon (landblock 7E02)."}, + {"name":"Ler Rhan","type":"NPC","wcid":43858,"cell":"7E0202D7","place":"dungeon","id":8367,"desc":"In a dungeon (landblock 7E02)."}, + {"name":"Strange Crystal","type":"NPC","wcid":43896,"cell":"7E020217","place":"dungeon","id":8368,"desc":"In a dungeon (landblock 7E02)."}, + {"name":"Falling Stalactite","type":"NPC","wcid":87268,"cell":"7E03090F","place":"dungeon","id":8369,"desc":"In a dungeon (landblock 7E03)."}, + {"name":"Falling Stalactite","type":"NPC","wcid":87268,"cell":"7E03090E","place":"dungeon","id":8370,"desc":"In a dungeon (landblock 7E03)."}, + {"name":"Falling Stalactite","type":"NPC","wcid":87268,"cell":"7E03090D","place":"dungeon","id":8371,"desc":"In a dungeon (landblock 7E03)."}, + {"name":"Cooking Vat","type":"NPC","wcid":72904,"cell":"7E0401D1","place":"dungeon","id":8372,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Cooking Vat","type":"NPC","wcid":72904,"cell":"7E0401D9","place":"dungeon","id":8373,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Lock","type":"NPC","wcid":72906,"cell":"7E040275","place":"dungeon","id":8374,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Mixing Basin","type":"NPC","wcid":72913,"cell":"7E0401D1","place":"dungeon","id":8375,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Lock","type":"NPC","wcid":72906,"cell":"7E040209","place":"dungeon","id":8376,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Lock","type":"NPC","wcid":72906,"cell":"7E040335","place":"dungeon","id":8377,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Lock","type":"NPC","wcid":72906,"cell":"7E04031C","place":"dungeon","id":8378,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Lock","type":"NPC","wcid":72906,"cell":"7E04028B","place":"dungeon","id":8379,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Lock","type":"NPC","wcid":72906,"cell":"7E04029E","place":"dungeon","id":8380,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Thrungus","type":"NPC","wcid":72914,"cell":"7E040335","place":"dungeon","id":8381,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Trapped Townsperson","type":"NPC","wcid":72915,"cell":"7E040209","place":"dungeon","id":8382,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Trapped Townsperson","type":"NPC","wcid":72952,"cell":"7E04028B","place":"dungeon","id":8383,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Trapped Townsperson","type":"NPC","wcid":72915,"cell":"7E04029E","place":"dungeon","id":8384,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Trapped Townsperson","type":"NPC","wcid":72952,"cell":"7E04031C","place":"dungeon","id":8385,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Fiona Woron","type":"NPC","wcid":72918,"cell":"7E040275","place":"dungeon","id":8386,"desc":"In a dungeon (landblock 7E04)."}, + {"name":"Gharu'ndim Mid-Stakes Gamesmaster","type":"NPC","wcid":9502,"cell":"7E64011B","place":"building","ns":-21.5,"ew":-0.68,"id":8387,"desc":"Gamesmaster."}, + {"name":"Gharu'ndim Low-Stakes Gamesmaster","type":"NPC","wcid":9499,"cell":"7E640111","place":"building","ns":-21.48,"ew":-0.7,"id":8388,"desc":"Gamesmaster."}, + {"name":"Gharu'ndim High-Stakes Gamesmaster","type":"NPC","wcid":9496,"cell":"7E640113","place":"building","ns":-21.52,"ew":-0.7,"id":8389,"desc":"Gamesmaster."}, + {"name":"Arshid al-Qiyid","type":"NPC","wcid":9493,"cell":"7E640119","place":"building","ns":-21.5,"ew":-0.71,"id":8390,"desc":"Gambler Boss."}, + {"name":"Pawn Shopkeep","type":"Vendor","wcid":12308,"cell":"7E640119","place":"building","ns":-21.51,"ew":-0.69,"id":8391,"desc":"Fence."}, + {"name":"Ashadi bint Samaq","type":"Vendor","wcid":9505,"cell":"7E640119","place":"building","ns":-21.49,"ew":-0.69,"id":8392,"desc":"Cashier."}, + {"name":"Rare Exchanger","type":"NPC","wcid":40462,"cell":"7E640025","place":"outdoor","ns":-21.47,"ew":-0.68,"id":8393,"desc":"Gamesmaster."}, + {"name":"Dame Tsaya","type":"NPC","wcid":14415,"cell":"7E650100","place":"building","ns":-20.99,"ew":-0.81,"id":8394,"desc":"Senior Guard."}, + {"name":"Sentry","type":"NPC","wcid":14457,"cell":"7E650000","place":"outdoor","ns":-20.93,"ew":-0.87,"id":8395,"desc":"Guard."}, + {"name":"Sentry","type":"NPC","wcid":14459,"cell":"7E650000","place":"outdoor","ns":-21.07,"ew":-0.82,"id":8396,"desc":"Guard."}, + {"name":"Royal Guard","type":"NPC","wcid":33805,"cell":"7E65001A","place":"outdoor","ns":-20.96,"ew":-0.84,"id":8397,"desc":"Guard."}, + {"name":"Apostate Aetherium Deposit","type":"NPC","wcid":40809,"cell":"7F020107","place":"dungeon","id":8398,"desc":"In a dungeon (landblock 7F02)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"7F030134","place":"dungeon","id":8399,"desc":"In a dungeon (landblock 7F03)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"7F030278","place":"dungeon","id":8400,"desc":"Exploration Society Agent. In a dungeon (landblock 7F03)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"7F03032A","place":"dungeon","id":8401,"desc":"Shopkeeper. In a dungeon (landblock 7F03)."}, + {"name":"Jonathan","type":"NPC","wcid":29326,"cell":"7F0301B0","place":"dungeon","id":8402,"desc":"Exploration Society Agent. In a dungeon (landblock 7F03)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"7F0301AD","place":"dungeon","id":8403,"desc":"Exploration Society Agent. In a dungeon (landblock 7F03)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"7F0301B1","place":"dungeon","id":8404,"desc":"Exploration Society Agent. In a dungeon (landblock 7F03)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"7F03023A","place":"dungeon","id":8405,"desc":"Exploration Society Agent. In a dungeon (landblock 7F03)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"7F0301F4","place":"dungeon","id":8406,"desc":"Exploration Society Agent. In a dungeon (landblock 7F03)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"7F0301F6","place":"dungeon","id":8407,"desc":"Exploration Society Agent. In a dungeon (landblock 7F03)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"7F03032B","place":"dungeon","id":8408,"desc":"Exploration Society Agent. In a dungeon (landblock 7F03)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"7F03032B","place":"dungeon","id":8409,"desc":"Herald. In a dungeon (landblock 7F03)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"7F03032C","place":"dungeon","id":8410,"desc":"Exploration Society Agent. In a dungeon (landblock 7F03)."}, + {"name":"Sentry","type":"NPC","wcid":30990,"cell":"7F0302C2","place":"dungeon","id":8411,"desc":"Exploration Society Agent. In a dungeon (landblock 7F03)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"7F040134","place":"dungeon","id":8412,"desc":"In a dungeon (landblock 7F04)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"7F040278","place":"dungeon","id":8413,"desc":"Exploration Society Agent. In a dungeon (landblock 7F04)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"7F04032A","place":"dungeon","id":8414,"desc":"Shopkeeper. In a dungeon (landblock 7F04)."}, + {"name":"Jonathan","type":"NPC","wcid":29326,"cell":"7F0401B0","place":"dungeon","id":8415,"desc":"Exploration Society Agent. In a dungeon (landblock 7F04)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"7F0401AD","place":"dungeon","id":8416,"desc":"Exploration Society Agent. In a dungeon (landblock 7F04)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"7F0401B1","place":"dungeon","id":8417,"desc":"Exploration Society Agent. In a dungeon (landblock 7F04)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"7F04023A","place":"dungeon","id":8418,"desc":"Exploration Society Agent. In a dungeon (landblock 7F04)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"7F0401F4","place":"dungeon","id":8419,"desc":"Exploration Society Agent. In a dungeon (landblock 7F04)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"7F0401F6","place":"dungeon","id":8420,"desc":"Exploration Society Agent. In a dungeon (landblock 7F04)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"7F04032B","place":"dungeon","id":8421,"desc":"Exploration Society Agent. In a dungeon (landblock 7F04)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"7F04032B","place":"dungeon","id":8422,"desc":"Herald. In a dungeon (landblock 7F04)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"7F04032C","place":"dungeon","id":8423,"desc":"Exploration Society Agent. In a dungeon (landblock 7F04)."}, + {"name":"Sentry","type":"NPC","wcid":30990,"cell":"7F0402C2","place":"dungeon","id":8424,"desc":"Exploration Society Agent. In a dungeon (landblock 7F04)."}, + {"name":"Guardian of the Temple of Enlightenment","type":"NPC","wcid":22753,"cell":"7F150000","place":"outdoor","ns":-84.52,"ew":0.01,"id":8425}, + {"name":"Devana bint Hamudi","type":"NPC","wcid":6026,"cell":"7F8F0000","place":"outdoor","ns":12.91,"ew":0.35,"id":8426,"desc":"Blademaster."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"7F8F011D","place":"building","ns":13.22,"ew":0.31,"id":8427,"desc":"Mage."}, + {"name":"Jordan's Apprentice Craftsman","type":"Vendor","wcid":12242,"cell":"7F8F011D","place":"building","ns":13.23,"ew":0.3,"id":8428,"desc":"Apprentice Craftsman."}, + {"name":"Jordan Ibn'Ikia","type":"NPC","wcid":12239,"cell":"7F8F011D","place":"building","ns":13.21,"ew":0.29,"id":8429,"desc":"Wall Hanging Master."}, + {"name":"Absalom Sarraf","type":"Vendor","wcid":43910,"cell":"7F8F010A","place":"building","ns":12.89,"ew":0.26,"id":8430,"desc":"Alternate Currency Exchanger."}, + {"name":"Carlyle Wolnoth","type":"Vendor","wcid":43940,"cell":"7F8F0035","place":"outdoor","ns":12.86,"ew":0.3,"id":8431,"desc":"Augmented Resistance Exchanger."}, + {"name":"Higashiyama Akako","type":"NPC","wcid":43900,"cell":"7F8F010A","place":"building","ns":12.91,"ew":0.27,"id":8432,"desc":"Alternate Currency Exchanger."}, + {"name":"Sakeenah Qureshi","type":"NPC","wcid":43911,"cell":"7F8F0035","place":"outdoor","ns":12.89,"ew":0.3,"id":8433,"desc":"Augmented Resistance Exchanger."}, + {"name":"Healer Hisuf ibn Shudir","type":"Vendor","wcid":990,"cell":"7F900111","place":"building","ns":13.9,"ew":0.07,"id":8434,"desc":"Healer."}, + {"name":"Jizal al-Nurla the Scribe","type":"Vendor","wcid":992,"cell":"7F90011B","place":"building","ns":13.92,"ew":0.1,"id":8435,"desc":"Scribe."}, + {"name":"Archmage Asaina al-Arqis","type":"Vendor","wcid":984,"cell":"7F900113","place":"building","ns":13.9,"ew":0.12,"id":8436,"desc":"Archmage."}, + {"name":"Suma bint Nayn the Librarian","type":"Vendor","wcid":2045,"cell":"7F900114","place":"building","ns":13.9,"ew":0.12,"id":8437,"desc":"Librarian."}, + {"name":"Kuyiza bint Zayi the Translator","type":"NPC","wcid":5695,"cell":"7F900112","place":"building","ns":13.89,"ew":0.07,"id":8438,"desc":"Translator."}, + {"name":"Diyas al-Yat","type":"NPC","wcid":8266,"cell":"7F900000","place":"outdoor","ns":13.84,"ew":0.11,"id":8439,"desc":"Scholar."}, + {"name":"Ecorto the Lost Director","type":"NPC","wcid":12262,"cell":"7F900000","place":"outdoor","ns":13.71,"ew":0.07,"id":8440}, + {"name":"Arcanum Researcher","type":"NPC","wcid":16892,"cell":"7F90011E","place":"building","ns":13.93,"ew":0.1,"id":8441}, + {"name":"Apprentice Alchemist","type":"NPC","wcid":28183,"cell":"7F900000","place":"outdoor","ns":13.86,"ew":0.07,"id":8442}, + {"name":"Danira the Dusty","type":"NPC","wcid":37166,"cell":"7F900119","place":"building","ns":13.9,"ew":0.11,"id":8443,"desc":"Scholar of Dericostian Texts."}, + {"name":"Exploration Marker","type":"NPC","wcid":39750,"cell":"7FE7002D","place":"outdoor","ns":83.3,"ew":0.18,"id":8444}, + {"name":"Guardian of the Temple of Forgetfulness","type":"NPC","wcid":22754,"cell":"7FEE0000","place":"outdoor","ns":88.84,"ew":0.03,"id":8445}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"80020134","place":"dungeon","id":8446,"desc":"In a dungeon (landblock 8002)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"80020278","place":"dungeon","id":8447,"desc":"Exploration Society Agent. In a dungeon (landblock 8002)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8002032A","place":"dungeon","id":8448,"desc":"Shopkeeper. In a dungeon (landblock 8002)."}, + {"name":"Jonathan","type":"NPC","wcid":29326,"cell":"800201B0","place":"dungeon","id":8449,"desc":"Exploration Society Agent. In a dungeon (landblock 8002)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"800201AD","place":"dungeon","id":8450,"desc":"Exploration Society Agent. In a dungeon (landblock 8002)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"800201B1","place":"dungeon","id":8451,"desc":"Exploration Society Agent. In a dungeon (landblock 8002)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8002023A","place":"dungeon","id":8452,"desc":"Exploration Society Agent. In a dungeon (landblock 8002)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"800201F4","place":"dungeon","id":8453,"desc":"Exploration Society Agent. In a dungeon (landblock 8002)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"800201F6","place":"dungeon","id":8454,"desc":"Exploration Society Agent. In a dungeon (landblock 8002)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8002032B","place":"dungeon","id":8455,"desc":"Exploration Society Agent. In a dungeon (landblock 8002)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8002032B","place":"dungeon","id":8456,"desc":"Herald. In a dungeon (landblock 8002)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8002032C","place":"dungeon","id":8457,"desc":"Exploration Society Agent. In a dungeon (landblock 8002)."}, + {"name":"Sentry","type":"NPC","wcid":30990,"cell":"800202C2","place":"dungeon","id":8458,"desc":"Exploration Society Agent. In a dungeon (landblock 8002)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"80030134","place":"dungeon","id":8459,"desc":"In a dungeon (landblock 8003)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"80030278","place":"dungeon","id":8460,"desc":"Exploration Society Agent. In a dungeon (landblock 8003)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8003032A","place":"dungeon","id":8461,"desc":"Shopkeeper. In a dungeon (landblock 8003)."}, + {"name":"Jonathan","type":"NPC","wcid":29326,"cell":"800301B0","place":"dungeon","id":8462,"desc":"Exploration Society Agent. In a dungeon (landblock 8003)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"800301AD","place":"dungeon","id":8463,"desc":"Exploration Society Agent. In a dungeon (landblock 8003)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"800301B1","place":"dungeon","id":8464,"desc":"Exploration Society Agent. In a dungeon (landblock 8003)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8003023A","place":"dungeon","id":8465,"desc":"Exploration Society Agent. In a dungeon (landblock 8003)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"800301F4","place":"dungeon","id":8466,"desc":"Exploration Society Agent. In a dungeon (landblock 8003)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"800301F6","place":"dungeon","id":8467,"desc":"Exploration Society Agent. In a dungeon (landblock 8003)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8003032B","place":"dungeon","id":8468,"desc":"Exploration Society Agent. In a dungeon (landblock 8003)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8003032B","place":"dungeon","id":8469,"desc":"Herald. In a dungeon (landblock 8003)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8003032C","place":"dungeon","id":8470,"desc":"Exploration Society Agent. In a dungeon (landblock 8003)."}, + {"name":"Sentry","type":"NPC","wcid":30990,"cell":"800302C2","place":"dungeon","id":8471,"desc":"Exploration Society Agent. In a dungeon (landblock 8003)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"80040134","place":"dungeon","id":8472,"desc":"In a dungeon (landblock 8004)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"80040278","place":"dungeon","id":8473,"desc":"Exploration Society Agent. In a dungeon (landblock 8004)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8004032A","place":"dungeon","id":8474,"desc":"Shopkeeper. In a dungeon (landblock 8004)."}, + {"name":"Jonathan","type":"NPC","wcid":29326,"cell":"800401B0","place":"dungeon","id":8475,"desc":"Exploration Society Agent. In a dungeon (landblock 8004)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"800401AD","place":"dungeon","id":8476,"desc":"Exploration Society Agent. In a dungeon (landblock 8004)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"800401B1","place":"dungeon","id":8477,"desc":"Exploration Society Agent. In a dungeon (landblock 8004)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8004023A","place":"dungeon","id":8478,"desc":"Exploration Society Agent. In a dungeon (landblock 8004)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"800401F4","place":"dungeon","id":8479,"desc":"Exploration Society Agent. In a dungeon (landblock 8004)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"800401F6","place":"dungeon","id":8480,"desc":"Exploration Society Agent. In a dungeon (landblock 8004)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8004032B","place":"dungeon","id":8481,"desc":"Exploration Society Agent. In a dungeon (landblock 8004)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8004032B","place":"dungeon","id":8482,"desc":"Herald. In a dungeon (landblock 8004)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8004032C","place":"dungeon","id":8483,"desc":"Exploration Society Agent. In a dungeon (landblock 8004)."}, + {"name":"Sentry","type":"NPC","wcid":30990,"cell":"800402C2","place":"dungeon","id":8484,"desc":"Exploration Society Agent. In a dungeon (landblock 8004)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"80120000","place":"outdoor","ns":-86.95,"ew":0.72,"id":8485}, + {"name":"Ahyara","type":"NPC","wcid":5177,"cell":"80640100","place":"building","ns":-21.29,"ew":1.08,"id":8486,"desc":"Citizen of Yaraq."}, + {"name":"Sentry","type":"NPC","wcid":12725,"cell":"80640000","place":"outdoor","ns":-21.71,"ew":0.89,"id":8487,"desc":"Soldier."}, + {"name":"Darhy, Assistant to Nuhmudira","type":"NPC","wcid":25483,"cell":"808F0000","place":"outdoor","ns":13.19,"ew":0.77,"id":8488,"desc":"Assistant to Nuhmudira."}, + {"name":"Maqudh al Nishadina","type":"NPC","wcid":34010,"cell":"808F000E","place":"outdoor","ns":13.03,"ew":0.61,"id":8489,"desc":"Desecrator of Temples."}, + {"name":"Ayesha of the Radiant Blood","type":"NPC","wcid":38390,"cell":"808F0014","place":"outdoor","ns":12.79,"ew":0.7,"id":8490,"desc":"Society Recruiter."}, + {"name":"Djusufa bint Huqis the Jeweler","type":"Vendor","wcid":991,"cell":"8090011C","place":"building","ns":13.72,"ew":0.67,"id":8491,"desc":"Jeweler."}, + {"name":"Shopkeep Yudi ibn Zayrim","type":"Vendor","wcid":993,"cell":"80900122","place":"building","ns":13.68,"ew":0.73,"id":8492,"desc":"Shopkeeper."}, + {"name":"Barkeeper Ghazi al-Barbasin","type":"Vendor","wcid":985,"cell":"8090012A","place":"building","ns":13.8,"ew":0.73,"id":8493,"desc":"Barkeeper."}, + {"name":"Qufana al-Khurti the Blacksmith","type":"Vendor","wcid":987,"cell":"8090010E","place":"building","ns":13.91,"ew":0.71,"id":8494,"desc":"Blacksmith."}, + {"name":"Maftaltub al-Sur the Bowyer","type":"Vendor","wcid":988,"cell":"80900110","place":"building","ns":13.92,"ew":0.69,"id":8495,"desc":"Bowyer."}, + {"name":"Zubid ibn Ifi the Grocer","type":"Vendor","wcid":989,"cell":"80900106","place":"building","ns":13.93,"ew":0.62,"id":8496,"desc":"Grocer."}, + {"name":"Muda bint Qalakh the Tailor","type":"Vendor","wcid":994,"cell":"80900100","place":"building","ns":13.88,"ew":0.58,"id":8497,"desc":"Tailor."}, + {"name":"Ufet, Prophet of Blades","type":"NPC","wcid":11810,"cell":"80900000","place":"outdoor","ns":13.86,"ew":0.7,"id":8498,"desc":"Quartermaster."}, + {"name":"Coron Usgin","type":"NPC","wcid":19464,"cell":"80900000","place":"outdoor","ns":13.72,"ew":0.68,"id":8499,"desc":"Seller for Telk the Addlepated."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20215,"cell":"8090014C","place":"building","ns":13.63,"ew":0.71,"id":8500,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20216,"cell":"8090014C","place":"building","ns":13.63,"ew":0.7,"id":8501,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20217,"cell":"80900156","place":"building","ns":13.59,"ew":0.73,"id":8502,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20218,"cell":"80900156","place":"building","ns":13.6,"ew":0.73,"id":8503,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":20205,"cell":"8090014E","place":"building","ns":13.57,"ew":0.7,"id":8504,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":20221,"cell":"8090014D","place":"building","ns":13.63,"ew":0.7,"id":8505,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"8090014D","place":"building","ns":13.63,"ew":0.71,"id":8506,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"80900159","place":"building","ns":13.6,"ew":0.74,"id":8507,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":20209,"cell":"80900159","place":"building","ns":13.59,"ew":0.73,"id":8508,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":20225,"cell":"8090014F","place":"building","ns":13.57,"ew":0.7,"id":8509,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"8090014F","place":"building","ns":13.57,"ew":0.69,"id":8510,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"80900154","place":"building","ns":13.61,"ew":0.71,"id":8511,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":20213,"cell":"80900154","place":"building","ns":13.59,"ew":0.71,"id":8512,"desc":"Master Archmage."}, + {"name":"Sign","type":"NPC","wcid":25722,"cell":"80900000","place":"outdoor","ns":13.54,"ew":0.7,"id":8513}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"80900000","place":"outdoor","ns":13.83,"ew":0.52,"id":8514}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"80900000","place":"outdoor","ns":13.39,"ew":0.76,"id":8515}, + {"name":"Coman ibn Rashid","type":"NPC","wcid":28476,"cell":"80900000","place":"outdoor","ns":13.57,"ew":0.73,"id":8516,"desc":"Noble Guard."}, + {"name":"Dumida bint Ruminre","type":"NPC","wcid":28685,"cell":"8090000F","place":"outdoor","ns":13.9,"ew":0.57,"id":8517,"desc":"Augmentation Trainer."}, + {"name":"Husoon","type":"NPC","wcid":28689,"cell":"8090000F","place":"outdoor","ns":13.9,"ew":0.6,"id":8518,"desc":"Augmentation Trainer."}, + {"name":"Arcanum Broker","type":"Vendor","wcid":38460,"cell":"80900002","place":"outdoor","ns":13.42,"ew":0.49,"id":8519,"desc":"Mana Forge Vendor."}, + {"name":"Kilaf","type":"NPC","wcid":41524,"cell":"80900015","place":"outdoor","ns":13.73,"ew":0.7,"id":8520,"desc":"Augmentation Trainer."}, + {"name":"Rahina bint Zalanis","type":"NPC","wcid":41525,"cell":"80900015","place":"outdoor","ns":13.73,"ew":0.69,"id":8521,"desc":"Augmentation Trainer."}, + {"name":"Garbage Barrel","type":"NPC","wcid":34726,"cell":"8090015E","place":"underground","ns":13.31,"ew":0.48,"id":8522}, + {"name":"Garbage Barrel","type":"NPC","wcid":34726,"cell":"80900161","place":"building","ns":13.41,"ew":0.49,"id":8523}, + {"name":"Arcanum Mana-smith","type":"NPC","wcid":38461,"cell":"80900002","place":"outdoor","ns":13.42,"ew":0.51,"id":8524,"desc":"Pristine Mana Shard Collector."}, + {"name":"Component Exchanger","type":"NPC","wcid":40770,"cell":"80900161","place":"building","ns":13.41,"ew":0.51,"id":8525,"desc":"Gamesmaster."}, + {"name":"Garbage Barrel","type":"NPC","wcid":34726,"cell":"8090015E","place":"underground","ns":13.31,"ew":0.52,"id":8526}, + {"name":"Jondor Torgren","type":"NPC","wcid":37610,"cell":"80900014","place":"outdoor","ns":13.64,"ew":0.68,"id":8527,"desc":"Arcanum Archivist."}, + {"name":"Zava bint Laurma","type":"NPC","wcid":36233,"cell":"8090000F","place":"outdoor","ns":13.87,"ew":0.6,"id":8528,"desc":"Slithis Slayer."}, + {"name":"Ned the Clever","type":"NPC","wcid":40807,"cell":"80900163","place":"building","ns":13.39,"ew":0.9,"id":8529,"desc":"Geomantic Tracker."}, + {"name":"Aruq ibn Balthar","type":"NPC","wcid":40488,"cell":"80900012","place":"outdoor","ns":13.42,"ew":0.7,"id":8530,"desc":"Geomantic Investigator."}, + {"name":"Meshenq","type":"NPC","wcid":35308,"cell":"8090000E","place":"outdoor","ns":13.83,"ew":0.63,"id":8531,"desc":"Traveling Scholar."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"81640000","place":"outdoor","ns":-21.33,"ew":1.33,"id":8532}, + {"name":"Lu'zura the Shopkeeper","type":"Vendor","wcid":4707,"cell":"81640108","place":"building","ns":-21.31,"ew":1.29,"id":8533,"desc":"Shopkeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"81900000","place":"outdoor","ns":13.49,"ew":1.54,"id":8534}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"828E0000","place":"outdoor","ns":12.13,"ew":2.37,"id":8535}, + {"name":"Dizah ibn Nadqab","type":"NPC","wcid":5636,"cell":"828E0000","place":"outdoor","ns":12.17,"ew":2.38,"id":8536,"desc":"Grounds Keeper."}, + {"name":"Chosen of Asheron","type":"NPC","wcid":8766,"cell":"82910000","place":"outdoor","ns":14.69,"ew":2.33,"id":8537,"desc":"Emissary."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"82930000","place":"outdoor","ns":15.84,"ew":2.15,"id":8538}, + {"name":"Peddler","type":"Vendor","wcid":1391,"cell":"83580100","place":"building","ns":-31.29,"ew":3.61,"id":8539}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"83580000","place":"outdoor","ns":-31.27,"ew":3.58,"id":8540}, + {"name":"Tazal al-Ashfai","type":"NPC","wcid":5763,"cell":"83870000","place":"outdoor","ns":6.06,"ew":3.47,"id":8541,"desc":"Planar Mage."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"83880000","place":"outdoor","ns":7.12,"ew":2.98,"id":8542}, + {"name":"Jibril ibn Rashid","type":"Vendor","wcid":51156,"cell":"83880000","place":"outdoor","ns":7.11,"ew":3.02,"id":8543,"desc":"Master Armorer."}, + {"name":"Exploration Marker","type":"NPC","wcid":39768,"cell":"83880001","place":"outdoor","ns":6.88,"ew":2.86,"id":8544}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"83C00000","place":"outdoor","ns":52.1,"ew":3.06,"id":8545}, + {"name":"Shopkeep Bubtil al-Taywi","type":"Vendor","wcid":1822,"cell":"846C0100","place":"building","ns":-15.1,"ew":4.39,"id":8546,"desc":"Shopkeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"846D0000","place":"outdoor","ns":-14.26,"ew":3.72,"id":8547}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":20213,"cell":"846D0111","place":"underground","ns":-14.2,"ew":4.37,"id":8548,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":20225,"cell":"846D011B","place":"underground","ns":-14.17,"ew":4.4,"id":8549,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":20221,"cell":"846D0113","place":"underground","ns":-14.2,"ew":4.43,"id":8550,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":20209,"cell":"846D011E","place":"building","ns":-14.17,"ew":4.4,"id":8551,"desc":"Master Archmage."}, + {"name":"Town Crier","type":"NPC","wcid":73186,"cell":"8488003B","place":"outdoor","ns":7.14,"ew":4.44,"id":8552,"desc":"Herald."}, + {"name":"Exploration Marker","type":"NPC","wcid":39817,"cell":"84F80008","place":"outdoor","ns":97.25,"ew":3.65,"id":8553}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"856D0000","place":"outdoor","ns":-13.96,"ew":4.99,"id":8554}, + {"name":"Maqura al-Waryah the Blacksmith","type":"Vendor","wcid":1815,"cell":"856E0100","place":"building","ns":-13.89,"ew":4.99,"id":8555,"desc":"Blacksmith."}, + {"name":"Djuyat ibn Fisa the Armorer","type":"Vendor","wcid":1816,"cell":"856E0100","place":"building","ns":-13.87,"ew":4.99,"id":8556,"desc":"Armorer."}, + {"name":"Ya-Bint-Al-Hawa","type":"NPC","wcid":9228,"cell":"856E010E","place":"building","ns":-13.3,"ew":5.09,"id":8557,"desc":"Undead Hunter."}, + {"name":"Anid Al-Fadee","type":"NPC","wcid":9227,"cell":"856E010F","place":"building","ns":-13.29,"ew":5.11,"id":8558,"desc":"Undead Hunter."}, + {"name":"Gabal Feteh","type":"NPC","wcid":9226,"cell":"856E010F","place":"building","ns":-13.31,"ew":5.11,"id":8559,"desc":"Undead Hunter."}, + {"name":"Su'nah bint Arfiz the Shopkeeper","type":"Vendor","wcid":4693,"cell":"8588011E","place":"building","ns":7.6,"ew":4.8,"id":8560,"desc":"Shopkeeper."}, + {"name":"Rah bint Khurdig the Bowyer","type":"Vendor","wcid":4691,"cell":"8588011C","place":"building","ns":7.61,"ew":5.0,"id":8561,"desc":"Bowyer."}, + {"name":"Archmage Marnai ibn Ayyar","type":"Vendor","wcid":4689,"cell":"85880106","place":"building","ns":7.16,"ew":4.58,"id":8562,"desc":"Sage."}, + {"name":"Healer Hansur al-Hirwak","type":"Vendor","wcid":4692,"cell":"85880100","place":"building","ns":7.22,"ew":4.61,"id":8563,"desc":"Healer."}, + {"name":"Busbawasa the Smith","type":"Vendor","wcid":4690,"cell":"8588010E","place":"building","ns":7.41,"ew":4.59,"id":8564,"desc":"Blacksmith."}, + {"name":"Al-Jalima Spice Merchant","type":"Vendor","wcid":6083,"cell":"8588011F","place":"building","ns":7.59,"ew":4.82,"id":8565,"desc":"Spice Merchant."}, + {"name":"Janda Sulifiya","type":"NPC","wcid":8403,"cell":"8588010F","place":"building","ns":7.43,"ew":4.61,"id":8566,"desc":"Mask Maker."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"85880124","place":"building","ns":7.27,"ew":4.47,"id":8567,"desc":"Mage."}, + {"name":"Janda's Apprentice","type":"NPC","wcid":12204,"cell":"8588010F","place":"building","ns":7.42,"ew":4.62,"id":8568,"desc":"Apprentice Mask Maker."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"8588013D","place":"building","ns":7.48,"ew":4.67,"id":8569,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"85880149","place":"building","ns":7.52,"ew":4.67,"id":8570,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"8588013F","place":"building","ns":7.52,"ew":4.72,"id":8571,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"85880144","place":"building","ns":7.52,"ew":4.7,"id":8572,"desc":"Master Archmage."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"85880000","place":"outdoor","ns":7.28,"ew":4.72,"id":8573}, + {"name":"Trevor Shunderson","type":"NPC","wcid":73177,"cell":"8588000C","place":"outdoor","ns":7.2,"ew":4.63,"id":8574,"desc":"Herald."}, + {"name":"Town Crier","type":"NPC","wcid":73186,"cell":"8588002D","place":"outdoor","ns":7.27,"ew":4.97,"id":8575,"desc":"Herald."}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"85890000","place":"outdoor","ns":7.72,"ew":4.96,"id":8576}, + {"name":"Town Crier","type":"NPC","wcid":73186,"cell":"85890029","place":"outdoor","ns":7.74,"ew":5.04,"id":8577,"desc":"Herald."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"86020134","place":"dungeon","id":8578,"desc":"In a dungeon (landblock 8602)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"86020278","place":"dungeon","id":8579,"desc":"Exploration Society Agent. In a dungeon (landblock 8602)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8602032A","place":"dungeon","id":8580,"desc":"Shopkeeper. In a dungeon (landblock 8602)."}, + {"name":"Jonathan","type":"NPC","wcid":29324,"cell":"860201B0","place":"dungeon","id":8581,"desc":"Exploration Society Agent. In a dungeon (landblock 8602)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"860201AD","place":"dungeon","id":8582,"desc":"Exploration Society Agent. In a dungeon (landblock 8602)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"860201B1","place":"dungeon","id":8583,"desc":"Exploration Society Agent. In a dungeon (landblock 8602)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8602023A","place":"dungeon","id":8584,"desc":"Exploration Society Agent. In a dungeon (landblock 8602)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"860201F4","place":"dungeon","id":8585,"desc":"Exploration Society Agent. In a dungeon (landblock 8602)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"860201F6","place":"dungeon","id":8586,"desc":"Exploration Society Agent. In a dungeon (landblock 8602)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8602032B","place":"dungeon","id":8587,"desc":"Exploration Society Agent. In a dungeon (landblock 8602)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8602032B","place":"dungeon","id":8588,"desc":"Herald. In a dungeon (landblock 8602)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8602032C","place":"dungeon","id":8589,"desc":"Exploration Society Agent. In a dungeon (landblock 8602)."}, + {"name":"Sentry","type":"NPC","wcid":30994,"cell":"860202C2","place":"dungeon","id":8590,"desc":"Exploration Society Agent. In a dungeon (landblock 8602)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"86030134","place":"dungeon","id":8591,"desc":"In a dungeon (landblock 8603)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"86030278","place":"dungeon","id":8592,"desc":"Exploration Society Agent. In a dungeon (landblock 8603)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8603032A","place":"dungeon","id":8593,"desc":"Shopkeeper. In a dungeon (landblock 8603)."}, + {"name":"Jonathan","type":"NPC","wcid":29324,"cell":"860301B0","place":"dungeon","id":8594,"desc":"Exploration Society Agent. In a dungeon (landblock 8603)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"860301AD","place":"dungeon","id":8595,"desc":"Exploration Society Agent. In a dungeon (landblock 8603)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"860301B1","place":"dungeon","id":8596,"desc":"Exploration Society Agent. In a dungeon (landblock 8603)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8603023A","place":"dungeon","id":8597,"desc":"Exploration Society Agent. In a dungeon (landblock 8603)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"860301F4","place":"dungeon","id":8598,"desc":"Exploration Society Agent. In a dungeon (landblock 8603)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"860301F6","place":"dungeon","id":8599,"desc":"Exploration Society Agent. In a dungeon (landblock 8603)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8603032B","place":"dungeon","id":8600,"desc":"Exploration Society Agent. In a dungeon (landblock 8603)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8603032B","place":"dungeon","id":8601,"desc":"Herald. In a dungeon (landblock 8603)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8603032C","place":"dungeon","id":8602,"desc":"Exploration Society Agent. In a dungeon (landblock 8603)."}, + {"name":"Sentry","type":"NPC","wcid":30994,"cell":"860302C2","place":"dungeon","id":8603,"desc":"Exploration Society Agent. In a dungeon (landblock 8603)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"86040134","place":"dungeon","id":8604,"desc":"In a dungeon (landblock 8604)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"86040278","place":"dungeon","id":8605,"desc":"Exploration Society Agent. In a dungeon (landblock 8604)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8604032A","place":"dungeon","id":8606,"desc":"Shopkeeper. In a dungeon (landblock 8604)."}, + {"name":"Jonathan","type":"NPC","wcid":29324,"cell":"860401B0","place":"dungeon","id":8607,"desc":"Exploration Society Agent. In a dungeon (landblock 8604)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"860401AD","place":"dungeon","id":8608,"desc":"Exploration Society Agent. In a dungeon (landblock 8604)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"860401B1","place":"dungeon","id":8609,"desc":"Exploration Society Agent. In a dungeon (landblock 8604)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8604023A","place":"dungeon","id":8610,"desc":"Exploration Society Agent. In a dungeon (landblock 8604)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"860401F4","place":"dungeon","id":8611,"desc":"Exploration Society Agent. In a dungeon (landblock 8604)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"860401F6","place":"dungeon","id":8612,"desc":"Exploration Society Agent. In a dungeon (landblock 8604)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8604032B","place":"dungeon","id":8613,"desc":"Exploration Society Agent. In a dungeon (landblock 8604)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8604032B","place":"dungeon","id":8614,"desc":"Herald. In a dungeon (landblock 8604)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8604032C","place":"dungeon","id":8615,"desc":"Exploration Society Agent. In a dungeon (landblock 8604)."}, + {"name":"Sentry","type":"NPC","wcid":30994,"cell":"860402C2","place":"dungeon","id":8616,"desc":"Exploration Society Agent. In a dungeon (landblock 8604)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"86130000","place":"outdoor","ns":-86.48,"ew":5.45,"id":8617}, + {"name":"Archmage","type":"Vendor","wcid":1370,"cell":"86130101","place":"building","ns":-86.51,"ew":5.41,"id":8618}, + {"name":"Weaponsmith","type":"Vendor","wcid":1394,"cell":"86130000","place":"outdoor","ns":-86.41,"ew":5.42,"id":8619}, + {"name":"Archmage Dakila bint Ma'liz","type":"Vendor","wcid":1812,"cell":"866C0106","place":"building","ns":-15.29,"ew":5.39,"id":8620,"desc":"Archmage."}, + {"name":"Grocer Tashhir ibn Najrak","type":"Vendor","wcid":1818,"cell":"866C0103","place":"building","ns":-14.89,"ew":5.91,"id":8621,"desc":"Grocer."}, + {"name":"Tailor Fadnuj ibn Samil","type":"Vendor","wcid":1823,"cell":"866C0101","place":"building","ns":-14.81,"ew":5.9,"id":8622,"desc":"Tailor."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"866C0109","place":"building","ns":-14.79,"ew":5.78,"id":8623,"desc":"Mage."}, + {"name":"Bowyer Shurida bint Zaud","type":"Vendor","wcid":1817,"cell":"866D0101","place":"building","ns":-14.03,"ew":5.47,"id":8624,"desc":"Bowyer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"866D0000","place":"outdoor","ns":-13.97,"ew":5.38,"id":8625}, + {"name":"Afsan ibn Kusain the Barkeep","type":"Vendor","wcid":1813,"cell":"866E0000","place":"outdoor","ns":-13.8,"ew":5.53,"id":8626,"desc":"Barkeeper."}, + {"name":"Lalid al-Jasi the Jeweler","type":"Vendor","wcid":1820,"cell":"866E0000","place":"outdoor","ns":-13.81,"ew":5.51,"id":8627,"desc":"Jeweler."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"866F0000","place":"outdoor","ns":-12.92,"ew":5.83,"id":8628}, + {"name":"Lonely Merchant","type":"Vendor","wcid":28532,"cell":"86900100","place":"dungeon","id":8629,"desc":"Vendor. In a dungeon (landblock 8690)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"87020134","place":"dungeon","id":8630,"desc":"In a dungeon (landblock 8702)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"87020278","place":"dungeon","id":8631,"desc":"Exploration Society Agent. In a dungeon (landblock 8702)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8702032A","place":"dungeon","id":8632,"desc":"Shopkeeper. In a dungeon (landblock 8702)."}, + {"name":"Jonathan","type":"NPC","wcid":29324,"cell":"870201B0","place":"dungeon","id":8633,"desc":"Exploration Society Agent. In a dungeon (landblock 8702)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"870201AD","place":"dungeon","id":8634,"desc":"Exploration Society Agent. In a dungeon (landblock 8702)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"870201B1","place":"dungeon","id":8635,"desc":"Exploration Society Agent. In a dungeon (landblock 8702)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8702023A","place":"dungeon","id":8636,"desc":"Exploration Society Agent. In a dungeon (landblock 8702)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"870201F4","place":"dungeon","id":8637,"desc":"Exploration Society Agent. In a dungeon (landblock 8702)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"870201F6","place":"dungeon","id":8638,"desc":"Exploration Society Agent. In a dungeon (landblock 8702)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8702032B","place":"dungeon","id":8639,"desc":"Exploration Society Agent. In a dungeon (landblock 8702)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8702032B","place":"dungeon","id":8640,"desc":"Herald. In a dungeon (landblock 8702)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8702032C","place":"dungeon","id":8641,"desc":"Exploration Society Agent. In a dungeon (landblock 8702)."}, + {"name":"Sentry","type":"NPC","wcid":30994,"cell":"870202C2","place":"dungeon","id":8642,"desc":"Exploration Society Agent. In a dungeon (landblock 8702)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"87030134","place":"dungeon","id":8643,"desc":"In a dungeon (landblock 8703)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"87030278","place":"dungeon","id":8644,"desc":"Exploration Society Agent. In a dungeon (landblock 8703)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8703032A","place":"dungeon","id":8645,"desc":"Shopkeeper. In a dungeon (landblock 8703)."}, + {"name":"Jonathan","type":"NPC","wcid":29324,"cell":"870301B0","place":"dungeon","id":8646,"desc":"Exploration Society Agent. In a dungeon (landblock 8703)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"870301AD","place":"dungeon","id":8647,"desc":"Exploration Society Agent. In a dungeon (landblock 8703)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"870301B1","place":"dungeon","id":8648,"desc":"Exploration Society Agent. In a dungeon (landblock 8703)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8703023A","place":"dungeon","id":8649,"desc":"Exploration Society Agent. In a dungeon (landblock 8703)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"870301F4","place":"dungeon","id":8650,"desc":"Exploration Society Agent. In a dungeon (landblock 8703)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"870301F6","place":"dungeon","id":8651,"desc":"Exploration Society Agent. In a dungeon (landblock 8703)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8703032B","place":"dungeon","id":8652,"desc":"Exploration Society Agent. In a dungeon (landblock 8703)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8703032B","place":"dungeon","id":8653,"desc":"Herald. In a dungeon (landblock 8703)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8703032C","place":"dungeon","id":8654,"desc":"Exploration Society Agent. In a dungeon (landblock 8703)."}, + {"name":"Sentry","type":"NPC","wcid":30994,"cell":"870302C2","place":"dungeon","id":8655,"desc":"Exploration Society Agent. In a dungeon (landblock 8703)."}, + {"name":"Crystal","type":"NPC","wcid":40110,"cell":"87040390","place":"dungeon","id":8656,"desc":"In a dungeon (landblock 8704)."}, + {"name":"Crystal","type":"NPC","wcid":40113,"cell":"870402B2","place":"dungeon","id":8657,"desc":"In a dungeon (landblock 8704)."}, + {"name":"Crystal","type":"NPC","wcid":40112,"cell":"87040295","place":"dungeon","id":8658,"desc":"In a dungeon (landblock 8704)."}, + {"name":"Crystal","type":"NPC","wcid":40114,"cell":"87040100","place":"dungeon","id":8659,"desc":"In a dungeon (landblock 8704)."}, + {"name":"Crystal","type":"NPC","wcid":40111,"cell":"8704031D","place":"dungeon","id":8660,"desc":"In a dungeon (landblock 8704)."}, + {"name":"Lieutenant Grenlin","type":"NPC","wcid":41567,"cell":"87550016","place":"outdoor","ns":-33.42,"ew":6.31,"id":8661,"desc":"Royal Knight."}, + {"name":"Lieutenant Micham","type":"NPC","wcid":41568,"cell":"87550016","place":"outdoor","ns":-33.43,"ew":6.29,"id":8662,"desc":"Royal Knight."}, + {"name":"Lieutenant Faen","type":"NPC","wcid":41569,"cell":"87550100","place":"building","ns":-33.41,"ew":6.29,"id":8663,"desc":"Royal Knight."}, + {"name":"Lieutenant Zin","type":"NPC","wcid":41570,"cell":"87550100","place":"building","ns":-33.41,"ew":6.31,"id":8664,"desc":"Royal Knight."}, + {"name":"Sir Stavitor","type":"NPC","wcid":41571,"cell":"87550100","place":"building","ns":-33.4,"ew":6.29,"id":8665,"desc":"Royal Knight."}, + {"name":"Sir Oakley","type":"NPC","wcid":42361,"cell":"87550016","place":"outdoor","ns":-33.42,"ew":6.33,"id":8666,"desc":"Royal Knight."}, + {"name":"Dame Alistra","type":"NPC","wcid":41561,"cell":"87550100","place":"building","ns":-33.39,"ew":6.31,"id":8667,"desc":"Royal Knight."}, + {"name":"Jin Ato","type":"NPC","wcid":41562,"cell":"87550100","place":"building","ns":-33.39,"ew":6.3,"id":8668,"desc":"Arcanum Collector."}, + {"name":"Missive","type":"Vendor","wcid":41612,"cell":"87550100","place":"building","ns":-33.39,"ew":6.29,"id":8669,"desc":"Archmage."}, + {"name":"Panhsj","type":"Vendor","wcid":44241,"cell":"87630101","place":"building","ns":-22.22,"ew":6.18,"id":8670}, + {"name":"Nephthys","type":"NPC","wcid":44101,"cell":"87630101","place":"building","ns":-22.2,"ew":6.18,"id":8671}, + {"name":"Bemeth the Gatherer","type":"NPC","wcid":44288,"cell":"87630006","place":"outdoor","ns":-22.19,"ew":6.14,"id":8672,"desc":"A'nekshay Temple Archivist."}, + {"name":"Hammah al Rundik","type":"NPC","wcid":44300,"cell":"8763000E","place":"outdoor","ns":-22.18,"ew":6.16,"id":8673,"desc":"Arcanum Cook."}, + {"name":"Sir Ibreh bin Kassim","type":"NPC","wcid":44261,"cell":"8763000E","place":"outdoor","ns":-22.18,"ew":6.19,"id":8674,"desc":"Royal Knight."}, + {"name":"Royal Guard","type":"NPC","wcid":42941,"cell":"8763000E","place":"outdoor","ns":-22.16,"ew":6.17,"id":8675,"desc":"Borelean's Royal Guard."}, + {"name":"Royal Guard","type":"NPC","wcid":42940,"cell":"8763000E","place":"outdoor","ns":-22.22,"ew":6.2,"id":8676,"desc":"Borelean's Royal Guard."}, + {"name":"Royal Guard","type":"NPC","wcid":42945,"cell":"8763000E","place":"outdoor","ns":-22.2,"ew":6.2,"id":8677,"desc":"Borelean's Royal Guard."}, + {"name":"Taylarn bint Tulani","type":"NPC","wcid":44301,"cell":"8763000E","place":"outdoor","ns":-22.24,"ew":6.2,"id":8678,"desc":"Arcanum Collector."}, + {"name":"T'ing Setsuko","type":"NPC","wcid":44299,"cell":"8763000E","place":"outdoor","ns":-22.24,"ew":6.21,"id":8679,"desc":"Arcanum Collector."}, + {"name":"Sir Hassim bin Tamarek","type":"NPC","wcid":44263,"cell":"87630015","place":"outdoor","ns":-22.28,"ew":6.31,"id":8680,"desc":"Royal Knight."}, + {"name":"Sir Adarl","type":"NPC","wcid":44262,"cell":"87630016","place":"outdoor","ns":-22.2,"ew":6.31,"id":8681,"desc":"Royal Knight."}, + {"name":"Dame Tularin","type":"NPC","wcid":44260,"cell":"87630017","place":"outdoor","ns":-22.14,"ew":6.26,"id":8682,"desc":"Royal Knight."}, + {"name":"Sir Daeglan","type":"NPC","wcid":44999,"cell":"8763000E","place":"outdoor","ns":-22.18,"ew":6.19,"id":8683,"desc":"Royal Investigator."}, + {"name":"Fahneph","type":"NPC","wcid":47052,"cell":"8763000E","place":"outdoor","ns":-22.24,"ew":6.17,"id":8684}, + {"name":"Sir Unell bin Rakke","type":"NPC","wcid":52289,"cell":"87630006","place":"outdoor","ns":-22.18,"ew":6.13,"id":8685,"desc":"Royal Knight."}, + {"name":"Nekshla","type":"NPC","wcid":48907,"cell":"8763000E","place":"outdoor","ns":-22.24,"ew":6.16,"id":8686}, + {"name":"Healer Jilrisi ibn Makhur","type":"Vendor","wcid":1819,"cell":"876D0101","place":"building","ns":-14.6,"ew":6.3,"id":8687,"desc":"Healer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"87880000","place":"outdoor","ns":7.23,"ew":6.14,"id":8688}, + {"name":"Lander","type":"NPC","wcid":81083,"cell":"88020279","place":"dungeon","id":8689,"desc":"Follower. In a dungeon (landblock 8802)."}, + {"name":"Ardenson","type":"NPC","wcid":81084,"cell":"880201E0","place":"dungeon","id":8690,"desc":"Follower. In a dungeon (landblock 8802)."}, + {"name":"Maximas","type":"NPC","wcid":81086,"cell":"880201C5","place":"dungeon","id":8691,"desc":"Follower. In a dungeon (landblock 8802)."}, + {"name":"Maniel","type":"NPC","wcid":81085,"cell":"88020243","place":"dungeon","id":8692,"desc":"Follower. In a dungeon (landblock 8802)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"88020147","place":"dungeon","id":8693,"desc":"In a dungeon (landblock 8802)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"88020158","place":"dungeon","id":8694,"desc":"In a dungeon (landblock 8802)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"8802015B","place":"dungeon","id":8695,"desc":"In a dungeon (landblock 8802)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"88020159","place":"dungeon","id":8696,"desc":"In a dungeon (landblock 8802)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"8802013B","place":"dungeon","id":8697,"desc":"In a dungeon (landblock 8802)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"88020156","place":"dungeon","id":8698,"desc":"In a dungeon (landblock 8802)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"88020154","place":"dungeon","id":8699,"desc":"In a dungeon (landblock 8802)."}, + {"name":"Crystal","type":"NPC","wcid":40115,"cell":"8803063A","place":"dungeon","id":8700,"desc":"In a dungeon (landblock 8803)."}, + {"name":"Crystal","type":"NPC","wcid":40118,"cell":"88030146","place":"dungeon","id":8701,"desc":"In a dungeon (landblock 8803)."}, + {"name":"Crystal","type":"NPC","wcid":40119,"cell":"88030101","place":"dungeon","id":8702,"desc":"In a dungeon (landblock 8803)."}, + {"name":"Crystal","type":"NPC","wcid":40116,"cell":"880307AD","place":"dungeon","id":8703,"desc":"In a dungeon (landblock 8803)."}, + {"name":"Crystal","type":"NPC","wcid":40117,"cell":"8803093D","place":"dungeon","id":8704,"desc":"In a dungeon (landblock 8803)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39809,"cell":"88030119","place":"dungeon","id":8705,"desc":"In a dungeon (landblock 8803)."}, + {"name":"Jinmi al-Evv","type":"Vendor","wcid":40942,"cell":"88040194","place":"dungeon","id":8706,"desc":"Master Alchemist. In a dungeon (landblock 8804)."}, + {"name":"Barkeep Rubin","type":"Vendor","wcid":40946,"cell":"880401AA","place":"dungeon","id":8707,"desc":"Barkeeper. In a dungeon (landblock 8804)."}, + {"name":"Archmage Malak ibn Hern","type":"Vendor","wcid":40947,"cell":"880401C2","place":"dungeon","id":8708,"desc":"Archmage. In a dungeon (landblock 8804)."}, + {"name":"Smith Aisha bint Karal","type":"Vendor","wcid":40948,"cell":"880401D0","place":"dungeon","id":8709,"desc":"Blacksmith. In a dungeon (landblock 8804)."}, + {"name":"Bowyer Ali ibn Mahir","type":"Vendor","wcid":40949,"cell":"880401D0","place":"dungeon","id":8710,"desc":"Bowyer. In a dungeon (landblock 8804)."}, + {"name":"Grocer Khamal al-Rachard","type":"Vendor","wcid":40952,"cell":"880401EF","place":"dungeon","id":8711,"desc":"Farmer. In a dungeon (landblock 8804)."}, + {"name":"Jeweler Jurraf al-Djiqidh","type":"Vendor","wcid":40953,"cell":"88040214","place":"dungeon","id":8712,"desc":"Jeweler. In a dungeon (landblock 8804)."}, + {"name":"Jinmi al-Evv","type":"Vendor","wcid":40954,"cell":"880402AE","place":"dungeon","id":8713,"desc":"Master Alchemist. In a dungeon (landblock 8804)."}, + {"name":"Barkeep Rubin","type":"Vendor","wcid":40958,"cell":"880402C4","place":"dungeon","id":8714,"desc":"Barkeeper. In a dungeon (landblock 8804)."}, + {"name":"Archmage Malak ibn Hern","type":"Vendor","wcid":40959,"cell":"880402DC","place":"dungeon","id":8715,"desc":"Archmage. In a dungeon (landblock 8804)."}, + {"name":"Smith Aisha bint Karal","type":"Vendor","wcid":40960,"cell":"880402EA","place":"dungeon","id":8716,"desc":"Blacksmith. In a dungeon (landblock 8804)."}, + {"name":"Bowyer Ali ibn Mahir","type":"Vendor","wcid":40961,"cell":"880402EA","place":"dungeon","id":8717,"desc":"Bowyer. In a dungeon (landblock 8804)."}, + {"name":"Grocer Khamal al-Rachard","type":"Vendor","wcid":40964,"cell":"88040309","place":"dungeon","id":8718,"desc":"Farmer. In a dungeon (landblock 8804)."}, + {"name":"Jeweler Jurraf al-Djiqidh","type":"Vendor","wcid":40965,"cell":"8804032E","place":"dungeon","id":8719,"desc":"Jeweler. In a dungeon (landblock 8804)."}, + {"name":"Jinmi al-Evv","type":"Vendor","wcid":40966,"cell":"880403C8","place":"dungeon","id":8720,"desc":"Master Alchemist. In a dungeon (landblock 8804)."}, + {"name":"Barkeep Rubin","type":"Vendor","wcid":40970,"cell":"880403DE","place":"dungeon","id":8721,"desc":"Barkeeper. In a dungeon (landblock 8804)."}, + {"name":"Archmage Malak ibn Hern","type":"Vendor","wcid":40971,"cell":"880403F6","place":"dungeon","id":8722,"desc":"Archmage. In a dungeon (landblock 8804)."}, + {"name":"Smith Aisha bint Karal","type":"Vendor","wcid":40972,"cell":"88040404","place":"dungeon","id":8723,"desc":"Blacksmith. In a dungeon (landblock 8804)."}, + {"name":"Bowyer Ali ibn Mahir","type":"Vendor","wcid":40973,"cell":"88040404","place":"dungeon","id":8724,"desc":"Bowyer. In a dungeon (landblock 8804)."}, + {"name":"Grocer Khamal al-Rachard","type":"Vendor","wcid":40974,"cell":"88040423","place":"dungeon","id":8725,"desc":"Farmer. In a dungeon (landblock 8804)."}, + {"name":"Jeweler Jurraf al-Djiqidh","type":"Vendor","wcid":40975,"cell":"88040448","place":"dungeon","id":8726,"desc":"Jeweler. In a dungeon (landblock 8804)."}, + {"name":"Jinmi al-Evv","type":"Vendor","wcid":40977,"cell":"880404E2","place":"dungeon","id":8727,"desc":"Master Alchemist. In a dungeon (landblock 8804)."}, + {"name":"Barkeep Rubin","type":"Vendor","wcid":40981,"cell":"880404F8","place":"dungeon","id":8728,"desc":"Barkeeper. In a dungeon (landblock 8804)."}, + {"name":"Archmage Malak ibn Hern","type":"Vendor","wcid":40982,"cell":"88040510","place":"dungeon","id":8729,"desc":"Archmage. In a dungeon (landblock 8804)."}, + {"name":"Smith Aisha bint Karal","type":"Vendor","wcid":40983,"cell":"8804051E","place":"dungeon","id":8730,"desc":"Blacksmith. In a dungeon (landblock 8804)."}, + {"name":"Bowyer Ali ibn Mahir","type":"Vendor","wcid":40984,"cell":"8804051E","place":"dungeon","id":8731,"desc":"Bowyer. In a dungeon (landblock 8804)."}, + {"name":"Grocer Khamal al-Rachard","type":"Vendor","wcid":40987,"cell":"8804053D","place":"dungeon","id":8732,"desc":"Farmer. In a dungeon (landblock 8804)."}, + {"name":"Jeweler Jurraf al-Djiqidh","type":"Vendor","wcid":40988,"cell":"88040562","place":"dungeon","id":8733,"desc":"Jeweler. In a dungeon (landblock 8804)."}, + {"name":"Test Portal","type":"NPC","wcid":41001,"cell":"880403DB","place":"dungeon","id":8734,"desc":"In a dungeon (landblock 8804)."}, + {"name":"Enhanced Test Portal","type":"NPC","wcid":41002,"cell":"880402C1","place":"dungeon","id":8735,"desc":"In a dungeon (landblock 8804)."}, + {"name":"Enhanced Test Portal","type":"NPC","wcid":41000,"cell":"880401A7","place":"dungeon","id":8736,"desc":"In a dungeon (landblock 8804)."}, + {"name":"Unstable Test Portal","type":"NPC","wcid":41003,"cell":"880404F5","place":"dungeon","id":8737,"desc":"In a dungeon (landblock 8804)."}, + {"name":"Marcus Manfried","type":"NPC","wcid":40997,"cell":"880403DB","place":"dungeon","id":8738,"desc":"Portal Researcher. In a dungeon (landblock 8804)."}, + {"name":"Wren the Curious","type":"NPC","wcid":40993,"cell":"880403DB","place":"dungeon","id":8739,"desc":"Portal Researcher. In a dungeon (landblock 8804)."}, + {"name":"Luc","type":"NPC","wcid":40963,"cell":"880402FF","place":"dungeon","id":8740,"desc":"In a dungeon (landblock 8804)."}, + {"name":"Jean","type":"NPC","wcid":40962,"cell":"880402FF","place":"dungeon","id":8741,"desc":"In a dungeon (landblock 8804)."}, + {"name":"Wren the Curious","type":"NPC","wcid":40994,"cell":"880402C9","place":"dungeon","id":8742,"desc":"Portal Researcher. In a dungeon (landblock 8804)."}, + {"name":"Marcus Manfried","type":"NPC","wcid":40998,"cell":"880402C1","place":"dungeon","id":8743,"desc":"Portal Researcher. In a dungeon (landblock 8804)."}, + {"name":"Luc","type":"NPC","wcid":40951,"cell":"880401E5","place":"dungeon","id":8744,"desc":"In a dungeon (landblock 8804)."}, + {"name":"Jean","type":"NPC","wcid":40950,"cell":"880401E5","place":"dungeon","id":8745,"desc":"In a dungeon (landblock 8804)."}, + {"name":"Marcus Manfried","type":"NPC","wcid":40996,"cell":"880401A7","place":"dungeon","id":8746,"desc":"Portal Researcher. In a dungeon (landblock 8804)."}, + {"name":"Wren the Curious","type":"NPC","wcid":40992,"cell":"880401A7","place":"dungeon","id":8747,"desc":"Portal Researcher. In a dungeon (landblock 8804)."}, + {"name":"Kaywin","type":"NPC","wcid":40941,"cell":"88040182","place":"dungeon","id":8748,"desc":"Machinist. In a dungeon (landblock 8804)."}, + {"name":"Luc","type":"NPC","wcid":40986,"cell":"88040533","place":"dungeon","id":8749,"desc":"In a dungeon (landblock 8804)."}, + {"name":"Jean","type":"NPC","wcid":40985,"cell":"88040533","place":"dungeon","id":8750,"desc":"In a dungeon (landblock 8804)."}, + {"name":"Wren the Curious","type":"NPC","wcid":40995,"cell":"880404F5","place":"dungeon","id":8751,"desc":"Portal Researcher. In a dungeon (landblock 8804)."}, + {"name":"Marcus Manfried","type":"NPC","wcid":40999,"cell":"880404F5","place":"dungeon","id":8752,"desc":"Portal Researcher. In a dungeon (landblock 8804)."}, + {"name":"Kaywin","type":"NPC","wcid":40976,"cell":"880404D0","place":"dungeon","id":8753,"desc":"Machinist. In a dungeon (landblock 8804)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39845,"cell":"88510006","place":"outdoor","ns":-36.65,"ew":6.9,"id":8754}, + {"name":"Ancient Portal","type":"NPC","wcid":44308,"cell":"88650032","place":"outdoor","ns":-21.01,"ew":7.5,"id":8755}, + {"name":"Ancient Portal","type":"NPC","wcid":44309,"cell":"8865003D","place":"outdoor","ns":-20.73,"ew":7.57,"id":8756}, + {"name":"Ancient Portal","type":"NPC","wcid":44310,"cell":"8865003F","place":"outdoor","ns":-20.5,"ew":7.59,"id":8757}, + {"name":"Ancient Portal","type":"NPC","wcid":44311,"cell":"88650035","place":"outdoor","ns":-20.71,"ew":7.51,"id":8758}, + {"name":"Sha-dekanma","type":"NPC","wcid":44637,"cell":"8866001C","place":"outdoor","ns":-19.97,"ew":7.22,"id":8759,"desc":"Mu-miyah."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"886D0000","place":"outdoor","ns":-14.27,"ew":6.98,"id":8760}, + {"name":"Farmer Kao","type":"NPC","wcid":31365,"cell":"88BF0036","place":"outdoor","ns":51.4,"ew":7.52,"id":8761,"desc":"Peasant Farmer."}, + {"name":"Kaywin","type":"NPC","wcid":72748,"cell":"89020182","place":"dungeon","id":8762,"desc":"Machinist. In a dungeon (landblock 8902)."}, + {"name":"Unstable Test Portal","type":"NPC","wcid":40273,"cell":"890201A7","place":"dungeon","id":8763,"desc":"In a dungeon (landblock 8902)."}, + {"name":"Marcus Manfried","type":"NPC","wcid":72747,"cell":"890201A7","place":"dungeon","id":8764,"desc":"Portal Researcher. In a dungeon (landblock 8902)."}, + {"name":"Wren the Curious","type":"NPC","wcid":72749,"cell":"890201A7","place":"dungeon","id":8765,"desc":"Portal Researcher. In a dungeon (landblock 8902)."}, + {"name":"Barkeep Rubin","type":"Vendor","wcid":40981,"cell":"890201AA","place":"dungeon","id":8766,"desc":"Barkeeper. In a dungeon (landblock 8902)."}, + {"name":"Archmage Malak ibn Hern","type":"Vendor","wcid":40982,"cell":"890201C2","place":"dungeon","id":8767,"desc":"Archmage. In a dungeon (landblock 8902)."}, + {"name":"Bowyer Ali ibn Mahir","type":"Vendor","wcid":40984,"cell":"890201D0","place":"dungeon","id":8768,"desc":"Bowyer. In a dungeon (landblock 8902)."}, + {"name":"Smith Aisha bint Karal","type":"Vendor","wcid":40948,"cell":"890201D0","place":"dungeon","id":8769,"desc":"Blacksmith. In a dungeon (landblock 8902)."}, + {"name":"Grocer Khamal al-Rachard","type":"Vendor","wcid":40987,"cell":"890201EF","place":"dungeon","id":8770,"desc":"Farmer. In a dungeon (landblock 8902)."}, + {"name":"Jinmi al-Evv","type":"Vendor","wcid":40977,"cell":"89020194","place":"dungeon","id":8771,"desc":"Master Alchemist. In a dungeon (landblock 8902)."}, + {"name":"Jeweler Jurraf al-Djiqidh","type":"Vendor","wcid":40988,"cell":"89020214","place":"dungeon","id":8772,"desc":"Jeweler. In a dungeon (landblock 8902)."}, + {"name":"Jean","type":"NPC","wcid":72778,"cell":"890201E5","place":"dungeon","id":8773,"desc":"In a dungeon (landblock 8902)."}, + {"name":"Luc","type":"NPC","wcid":72779,"cell":"890201E5","place":"dungeon","id":8774,"desc":"In a dungeon (landblock 8902)."}, + {"name":"Acid Plane Stopgap","type":"NPC","wcid":72751,"cell":"8903012B","place":"dungeon","id":8775,"desc":"Stopgap. In a dungeon (landblock 8903)."}, + {"name":"Fire Plane Stopgap","type":"NPC","wcid":72768,"cell":"8903010A","place":"dungeon","id":8776,"desc":"Stopgap. In a dungeon (landblock 8903)."}, + {"name":"Frost Plane Stopgap","type":"NPC","wcid":72769,"cell":"89030107","place":"dungeon","id":8777,"desc":"Stopgap. In a dungeon (landblock 8903)."}, + {"name":"Electric Plane Stopgap","type":"NPC","wcid":72770,"cell":"89030119","place":"dungeon","id":8778,"desc":"Stopgap. In a dungeon (landblock 8903)."}, + {"name":"Norus","type":"NPC","wcid":88224,"cell":"8954066D","place":"dungeon","id":8779,"desc":"Researcher. In a dungeon (landblock 8954)."}, + {"name":"Sanctum Guardian Spirit","type":"NPC","wcid":88225,"cell":"8954042B","place":"dungeon","id":8780,"desc":"Guardian of the Light Falatacot. In a dungeon (landblock 8954)."}, + {"name":"Bulb of Twilight","type":"NPC","wcid":88226,"cell":"895403B7","place":"dungeon","id":8781,"desc":"In a dungeon (landblock 8954)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"89F40000","place":"outdoor","ns":93.72,"ew":7.71,"id":8782}, + {"name":"Healer","type":"Vendor","wcid":1386,"cell":"89F40100","place":"underground","ns":93.79,"ew":7.76,"id":8783}, + {"name":"Archmage","type":"Vendor","wcid":1371,"cell":"89F40100","place":"underground","ns":93.81,"ew":7.76,"id":8784}, + {"name":"Roaming Bowyer","type":"Vendor","wcid":1378,"cell":"89F40100","place":"underground","ns":93.8,"ew":7.72,"id":8785,"desc":"Bowyer."}, + {"name":"Steward","type":"NPC","wcid":42134,"cell":"8A0201C8","place":"dungeon","id":8786,"desc":"Facility Steward. In Hub of Awakening."}, + {"name":"Curmudgeon the Drudge","type":"NPC","wcid":42131,"cell":"8A02015E","place":"dungeon","id":8787,"desc":"Friendly Drudge. In Hub of Awakening."}, + {"name":"Aun Warden","type":"NPC","wcid":42136,"cell":"8A0201B0","place":"dungeon","id":8788,"desc":"Portal Warden. In Hub of Awakening."}, + {"name":"Warden","type":"NPC","wcid":42143,"cell":"8A0201D4","place":"dungeon","id":8789,"desc":"Portal Warden. In Hub of Awakening."}, + {"name":"Warden","type":"NPC","wcid":42130,"cell":"8A0201DD","place":"dungeon","id":8790,"desc":"Portal Warden. In Hub of Awakening."}, + {"name":"Warden","type":"NPC","wcid":42124,"cell":"8A0201A7","place":"dungeon","id":8791,"desc":"Portal Warden. In Hub of Awakening."}, + {"name":"Warden","type":"NPC","wcid":42142,"cell":"8A0201B0","place":"dungeon","id":8792,"desc":"Portal Warden. In Hub of Awakening."}, + {"name":"Warden","type":"NPC","wcid":42140,"cell":"8A0201F7","place":"dungeon","id":8793,"desc":"Portal Warden. In Hub of Awakening."}, + {"name":"Warden","type":"NPC","wcid":42110,"cell":"8A02018D","place":"dungeon","id":8794,"desc":"Portal Warden. In Hub of Awakening."}, + {"name":"Warden","type":"NPC","wcid":42126,"cell":"8A020187","place":"dungeon","id":8795,"desc":"Portal Warden. In Hub of Awakening."}, + {"name":"Warden","type":"NPC","wcid":42145,"cell":"8A0201FF","place":"dungeon","id":8796,"desc":"Portal Warden. In Hub of Awakening."}, + {"name":"Mosswart Warden","type":"NPC","wcid":42144,"cell":"8A0201FF","place":"dungeon","id":8797,"desc":"Portal Warden. In Hub of Awakening."}, + {"name":"Master Enchanter","type":"Vendor","wcid":42220,"cell":"8A0201C2","place":"dungeon","id":8798,"desc":"In Hub of Awakening."}, + {"name":"Operations Specialist","type":"NPC","wcid":42237,"cell":"8A0302A2","place":"dungeon","id":8799,"desc":"Society Officer. In a dungeon (landblock 8A03)."}, + {"name":"Operations Specialist","type":"NPC","wcid":42246,"cell":"8A030212","place":"dungeon","id":8800,"desc":"Society Officer. In a dungeon (landblock 8A03)."}, + {"name":"Operations Specialist","type":"NPC","wcid":42228,"cell":"8A030182","place":"dungeon","id":8801,"desc":"Society Officer. In a dungeon (landblock 8A03)."}, + {"name":"Merchant","type":"Vendor","wcid":1387,"cell":"8A0401D5","place":"dungeon","id":8802,"desc":"In a dungeon (landblock 8A04)."}, + {"name":"Merchant","type":"Vendor","wcid":1387,"cell":"8A040212","place":"dungeon","id":8803,"desc":"In a dungeon (landblock 8A04)."}, + {"name":"Kaltus","type":"NPC","wcid":47020,"cell":"8A6304C1","place":"building","ns":-22.2,"ew":8.69,"id":8804,"desc":"Researcher."}, + {"name":"Sanctum Guardian Spirit","type":"NPC","wcid":88210,"cell":"8A630438","place":"underground","ns":-21.88,"ew":8.02,"id":8805,"desc":"Guardian of the Light Falatacot."}, + {"name":"Bulb of Mornings","type":"NPC","wcid":88208,"cell":"8A630116","place":"underground","ns":-22.03,"ew":8.59,"id":8806}, + {"name":"Royal Guard","type":"NPC","wcid":42940,"cell":"8A630016","place":"outdoor","ns":-22.17,"ew":8.69,"id":8807,"desc":"Borelean's Royal Guard."}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A630252","place":"underground","ns":-21.89,"ew":8.05,"id":8808}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A63020C","place":"underground","ns":-21.95,"ew":8.04,"id":8809}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A63021E","place":"underground","ns":-22.06,"ew":8.09,"id":8810}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A63022D","place":"underground","ns":-22.1,"ew":8.15,"id":8811}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A630190","place":"underground","ns":-22.09,"ew":7.85,"id":8812}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A6301BB","place":"underground","ns":-22.09,"ew":8.02,"id":8813}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A6301F2","place":"underground","ns":-22.06,"ew":8.25,"id":8814}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A6301F1","place":"underground","ns":-21.99,"ew":8.26,"id":8815}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A630141","place":"underground","ns":-21.88,"ew":8.27,"id":8816}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A630146","place":"underground","ns":-21.81,"ew":8.32,"id":8817}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A630142","place":"underground","ns":-21.94,"ew":8.25,"id":8818}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A630152","place":"underground","ns":-21.83,"ew":8.38,"id":8819}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A630161","place":"underground","ns":-22.22,"ew":8.38,"id":8820}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A630149","place":"underground","ns":-22.18,"ew":8.3,"id":8821}, + {"name":"Large Desert Flower","type":"NPC","wcid":88202,"cell":"8A63013F","place":"underground","ns":-22.15,"ew":8.24,"id":8822}, + {"name":"Royal Guard","type":"NPC","wcid":42939,"cell":"8A630016","place":"outdoor","ns":-22.18,"ew":8.68,"id":8823,"desc":"Borelean's Royal Guard."}, + {"name":"Royal Guard","type":"NPC","wcid":42945,"cell":"8A630016","place":"outdoor","ns":-22.22,"ew":8.72,"id":8824,"desc":"Borelean's Royal Guard."}, + {"name":"Lonely Archmage","type":"Vendor","wcid":28531,"cell":"8A890100","place":"dungeon","id":8825,"desc":"Vendor. In a dungeon (landblock 8A89)."}, + {"name":"Floating Bottle","type":"NPC","wcid":27805,"cell":"8B220000","place":"outdoor","ns":-74.66,"ew":9.89,"id":8826}, + {"name":"Menhir","type":"NPC","wcid":43986,"cell":"8B64000A","place":"outdoor","ns":-21.8,"ew":9.38,"id":8827}, + {"name":"Menhir","type":"NPC","wcid":43987,"cell":"8B64000A","place":"outdoor","ns":-21.8,"ew":9.41,"id":8828}, + {"name":"Exploration Marker","type":"NPC","wcid":39819,"cell":"8B640024","place":"outdoor","ns":-21.6,"ew":9.67,"id":8829}, + {"name":"Mhoire Castle Great Hall Portal","type":"NPC","wcid":41949,"cell":"8C0307CD","place":"dungeon","id":8830,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Exit to Mhoire Castle Courtyard","type":"NPC","wcid":42052,"cell":"8C0307DD","place":"dungeon","id":8831,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Mhoire Castle Northeast Tower Portal","type":"NPC","wcid":41950,"cell":"8C0303AB","place":"dungeon","id":8832,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Entry to the Oubliette","type":"NPC","wcid":45124,"cell":"8C03015F","place":"dungeon","id":8833,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Guardian of Mhoire","type":"NPC","wcid":42020,"cell":"8C0307E3","place":"dungeon","id":8834,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flames of Courage","type":"NPC","wcid":41999,"cell":"8C0307BA","place":"dungeon","id":8835,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flames of Loyalty","type":"NPC","wcid":42003,"cell":"8C0307B1","place":"dungeon","id":8836,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flames of Honor","type":"NPC","wcid":42001,"cell":"8C0307A8","place":"dungeon","id":8837,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Guardian of Mhoire","type":"NPC","wcid":41986,"cell":"8C03079E","place":"dungeon","id":8838,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flames of Humility","type":"NPC","wcid":42002,"cell":"8C0307BB","place":"dungeon","id":8839,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flames of Temperance","type":"NPC","wcid":42005,"cell":"8C0307A9","place":"dungeon","id":8840,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flames of Patience","type":"NPC","wcid":42004,"cell":"8C0307BC","place":"dungeon","id":8841,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flames of Honesty","type":"NPC","wcid":42000,"cell":"8C0307B3","place":"dungeon","id":8842,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flames of Charity","type":"NPC","wcid":41984,"cell":"8C0307AA","place":"dungeon","id":8843,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Shade of Terelev","type":"NPC","wcid":45201,"cell":"8C0307E8","place":"dungeon","id":8844,"desc":"Knight of House Mhoire. In a dungeon (landblock 8C03)."}, + {"name":"Shade of Fordroth","type":"NPC","wcid":42030,"cell":"8C0307E0","place":"dungeon","id":8845,"desc":"Knight of House Mhoire. In a dungeon (landblock 8C03)."}, + {"name":"Shade of Ormend","type":"NPC","wcid":42029,"cell":"8C0307CB","place":"dungeon","id":8846,"desc":"Knight of House Mhoire. In a dungeon (landblock 8C03)."}, + {"name":"Guliant","type":"NPC","wcid":45194,"cell":"8C0307CC","place":"dungeon","id":8847,"desc":"Alchemist of House Mhoire. In a dungeon (landblock 8C03)."}, + {"name":"Shade of Antemy","type":"NPC","wcid":42027,"cell":"8C0307E8","place":"dungeon","id":8848,"desc":"Seneschal of House Mhoire. In a dungeon (landblock 8C03)."}, + {"name":"Ancient Throne","type":"NPC","wcid":42023,"cell":"8C0303A8","place":"dungeon","id":8849,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Guardian of Mhoire","type":"NPC","wcid":72205,"cell":"8C0307A4","place":"dungeon","id":8850,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Guardian of Air","type":"NPC","wcid":72209,"cell":"8C030798","place":"dungeon","id":8851,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Guardian of Fire","type":"NPC","wcid":72206,"cell":"8C0307A3","place":"dungeon","id":8852,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Guardian of Earth","type":"NPC","wcid":72208,"cell":"8C0307AD","place":"dungeon","id":8853,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Guardian of Water","type":"NPC","wcid":72207,"cell":"8C0307A5","place":"dungeon","id":8854,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307D3","place":"dungeon","id":8855,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307D1","place":"dungeon","id":8856,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307E5","place":"dungeon","id":8857,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307DC","place":"dungeon","id":8858,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307D2","place":"dungeon","id":8859,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307EE","place":"dungeon","id":8860,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307F0","place":"dungeon","id":8861,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307F1","place":"dungeon","id":8862,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307B3","place":"dungeon","id":8863,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307B0","place":"dungeon","id":8864,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307B9","place":"dungeon","id":8865,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307BC","place":"dungeon","id":8866,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307BA","place":"dungeon","id":8867,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307A0","place":"dungeon","id":8868,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307AA","place":"dungeon","id":8869,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307A1","place":"dungeon","id":8870,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307BB","place":"dungeon","id":8871,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307A7","place":"dungeon","id":8872,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C03079F","place":"dungeon","id":8873,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307EF","place":"dungeon","id":8874,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Floating Tower Stopgap","type":"NPC","wcid":72742,"cell":"8C03037E","place":"dungeon","id":8875,"desc":"Stopgap. In a dungeon (landblock 8C03)."}, + {"name":"Flaming Skull","type":"NPC","wcid":72238,"cell":"8C0307D0","place":"dungeon","id":8876,"desc":"In a dungeon (landblock 8C03)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"8C040134","place":"dungeon","id":8877,"desc":"In a dungeon (landblock 8C04)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"8C040278","place":"dungeon","id":8878,"desc":"Exploration Society Agent. In a dungeon (landblock 8C04)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8C04032A","place":"dungeon","id":8879,"desc":"Shopkeeper. In a dungeon (landblock 8C04)."}, + {"name":"Jonathan","type":"NPC","wcid":29317,"cell":"8C0401B0","place":"dungeon","id":8880,"desc":"Exploration Society Agent. In a dungeon (landblock 8C04)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"8C0401AD","place":"dungeon","id":8881,"desc":"Exploration Society Agent. In a dungeon (landblock 8C04)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"8C0401B1","place":"dungeon","id":8882,"desc":"Exploration Society Agent. In a dungeon (landblock 8C04)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8C04023A","place":"dungeon","id":8883,"desc":"Exploration Society Agent. In a dungeon (landblock 8C04)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"8C0401F4","place":"dungeon","id":8884,"desc":"Exploration Society Agent. In a dungeon (landblock 8C04)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"8C0401F6","place":"dungeon","id":8885,"desc":"Exploration Society Agent. In a dungeon (landblock 8C04)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8C04032B","place":"dungeon","id":8886,"desc":"Exploration Society Agent. In a dungeon (landblock 8C04)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8C04032B","place":"dungeon","id":8887,"desc":"Herald. In a dungeon (landblock 8C04)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8C04032C","place":"dungeon","id":8888,"desc":"Exploration Society Agent. In a dungeon (landblock 8C04)."}, + {"name":"Sentry","type":"NPC","wcid":30992,"cell":"8C0402C2","place":"dungeon","id":8889,"desc":"Exploration Society Agent. In a dungeon (landblock 8C04)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"8C440000","place":"outdoor","ns":-47.22,"ew":10.64,"id":8890}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"8C580000","place":"outdoor","ns":-31.21,"ew":10.77,"id":8891}, + {"name":"Shopkeeper Tirua","type":"Vendor","wcid":4688,"cell":"8C580110","place":"building","ns":-31.29,"ew":10.77,"id":8892,"desc":"Shopkeeper."}, + {"name":"Nurbaha bint Dah","type":"NPC","wcid":5153,"cell":"8C580119","place":"building","ns":-31.31,"ew":10.82,"id":8893,"desc":"Citizen of Al-Arqas."}, + {"name":"Merchant","type":"Vendor","wcid":31731,"cell":"8CDD0100","place":"building","ns":75.51,"ew":10.51,"id":8894}, + {"name":"Healer","type":"Vendor","wcid":1384,"cell":"8CDD0100","place":"building","ns":75.5,"ew":10.49,"id":8895}, + {"name":"Archmage","type":"Vendor","wcid":1369,"cell":"8CDD0109","place":"building","ns":75.48,"ew":10.5,"id":8896}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"8CDD0000","place":"outdoor","ns":75.49,"ew":10.4,"id":8897}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"8D020134","place":"dungeon","id":8898,"desc":"In a dungeon (landblock 8D02)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"8D020278","place":"dungeon","id":8899,"desc":"Exploration Society Agent. In a dungeon (landblock 8D02)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8D02032A","place":"dungeon","id":8900,"desc":"Shopkeeper. In a dungeon (landblock 8D02)."}, + {"name":"Jonathan","type":"NPC","wcid":29317,"cell":"8D0201B0","place":"dungeon","id":8901,"desc":"Exploration Society Agent. In a dungeon (landblock 8D02)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"8D0201AD","place":"dungeon","id":8902,"desc":"Exploration Society Agent. In a dungeon (landblock 8D02)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"8D0201B1","place":"dungeon","id":8903,"desc":"Exploration Society Agent. In a dungeon (landblock 8D02)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8D02023A","place":"dungeon","id":8904,"desc":"Exploration Society Agent. In a dungeon (landblock 8D02)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"8D0201F4","place":"dungeon","id":8905,"desc":"Exploration Society Agent. In a dungeon (landblock 8D02)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"8D0201F6","place":"dungeon","id":8906,"desc":"Exploration Society Agent. In a dungeon (landblock 8D02)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8D02032B","place":"dungeon","id":8907,"desc":"Exploration Society Agent. In a dungeon (landblock 8D02)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8D02032B","place":"dungeon","id":8908,"desc":"Herald. In a dungeon (landblock 8D02)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8D02032C","place":"dungeon","id":8909,"desc":"Exploration Society Agent. In a dungeon (landblock 8D02)."}, + {"name":"Sentry","type":"NPC","wcid":30992,"cell":"8D0202C2","place":"dungeon","id":8910,"desc":"Exploration Society Agent. In a dungeon (landblock 8D02)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"8D030134","place":"dungeon","id":8911,"desc":"In a dungeon (landblock 8D03)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"8D030278","place":"dungeon","id":8912,"desc":"Exploration Society Agent. In a dungeon (landblock 8D03)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8D03032A","place":"dungeon","id":8913,"desc":"Shopkeeper. In a dungeon (landblock 8D03)."}, + {"name":"Jonathan","type":"NPC","wcid":29317,"cell":"8D0301B0","place":"dungeon","id":8914,"desc":"Exploration Society Agent. In a dungeon (landblock 8D03)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"8D0301AD","place":"dungeon","id":8915,"desc":"Exploration Society Agent. In a dungeon (landblock 8D03)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"8D0301B1","place":"dungeon","id":8916,"desc":"Exploration Society Agent. In a dungeon (landblock 8D03)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8D03023A","place":"dungeon","id":8917,"desc":"Exploration Society Agent. In a dungeon (landblock 8D03)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"8D0301F4","place":"dungeon","id":8918,"desc":"Exploration Society Agent. In a dungeon (landblock 8D03)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"8D0301F6","place":"dungeon","id":8919,"desc":"Exploration Society Agent. In a dungeon (landblock 8D03)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8D03032B","place":"dungeon","id":8920,"desc":"Exploration Society Agent. In a dungeon (landblock 8D03)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8D03032B","place":"dungeon","id":8921,"desc":"Herald. In a dungeon (landblock 8D03)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8D03032C","place":"dungeon","id":8922,"desc":"Exploration Society Agent. In a dungeon (landblock 8D03)."}, + {"name":"Sentry","type":"NPC","wcid":30992,"cell":"8D0302C2","place":"dungeon","id":8923,"desc":"Exploration Society Agent. In a dungeon (landblock 8D03)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"8D040134","place":"dungeon","id":8924,"desc":"In a dungeon (landblock 8D04)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"8D040278","place":"dungeon","id":8925,"desc":"Exploration Society Agent. In a dungeon (landblock 8D04)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8D04032A","place":"dungeon","id":8926,"desc":"Shopkeeper. In a dungeon (landblock 8D04)."}, + {"name":"Jonathan","type":"NPC","wcid":29317,"cell":"8D0401B0","place":"dungeon","id":8927,"desc":"Exploration Society Agent. In a dungeon (landblock 8D04)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"8D0401AD","place":"dungeon","id":8928,"desc":"Exploration Society Agent. In a dungeon (landblock 8D04)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"8D0401B1","place":"dungeon","id":8929,"desc":"Exploration Society Agent. In a dungeon (landblock 8D04)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8D04023A","place":"dungeon","id":8930,"desc":"Exploration Society Agent. In a dungeon (landblock 8D04)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"8D0401F4","place":"dungeon","id":8931,"desc":"Exploration Society Agent. In a dungeon (landblock 8D04)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"8D0401F6","place":"dungeon","id":8932,"desc":"Exploration Society Agent. In a dungeon (landblock 8D04)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8D04032B","place":"dungeon","id":8933,"desc":"Exploration Society Agent. In a dungeon (landblock 8D04)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8D04032B","place":"dungeon","id":8934,"desc":"Herald. In a dungeon (landblock 8D04)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8D04032C","place":"dungeon","id":8935,"desc":"Exploration Society Agent. In a dungeon (landblock 8D04)."}, + {"name":"Sentry","type":"NPC","wcid":30992,"cell":"8D0402C2","place":"dungeon","id":8936,"desc":"Exploration Society Agent. In a dungeon (landblock 8D04)."}, + {"name":"Fadsahil al-Tashbi the Master Archmage","type":"Vendor","wcid":2247,"cell":"8D4D0100","place":"dungeon","id":8937,"desc":"Master Archmage. In a dungeon (landblock 8D4D)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"8E020134","place":"dungeon","id":8938,"desc":"In a dungeon (landblock 8E02)."}, + {"name":"Academy Researcher","type":"Vendor","wcid":30997,"cell":"8E020278","place":"dungeon","id":8939,"desc":"Exploration Society Agent. In a dungeon (landblock 8E02)."}, + {"name":"Academy Shopkeep","type":"Vendor","wcid":12718,"cell":"8E02032A","place":"dungeon","id":8940,"desc":"Shopkeeper. In a dungeon (landblock 8E02)."}, + {"name":"Jonathan","type":"NPC","wcid":29317,"cell":"8E0201B0","place":"dungeon","id":8941,"desc":"Exploration Society Agent. In a dungeon (landblock 8E02)."}, + {"name":"Society Greeter","type":"NPC","wcid":30991,"cell":"8E0201AD","place":"dungeon","id":8942,"desc":"Exploration Society Agent. In a dungeon (landblock 8E02)."}, + {"name":"Samuel","type":"NPC","wcid":29322,"cell":"8E0201B1","place":"dungeon","id":8943,"desc":"Exploration Society Agent. In a dungeon (landblock 8E02)."}, + {"name":"Training Master","type":"NPC","wcid":29320,"cell":"8E02023A","place":"dungeon","id":8944,"desc":"Exploration Society Agent. In a dungeon (landblock 8E02)."}, + {"name":"Academy Foreman","type":"NPC","wcid":30995,"cell":"8E0201F4","place":"dungeon","id":8945,"desc":"Exploration Society Agent. In a dungeon (landblock 8E02)."}, + {"name":"Academy Blacksmith","type":"NPC","wcid":30996,"cell":"8E0201F6","place":"dungeon","id":8946,"desc":"Exploration Society Agent. In a dungeon (landblock 8E02)."}, + {"name":"Wordsmith","type":"NPC","wcid":29321,"cell":"8E02032B","place":"dungeon","id":8947,"desc":"Exploration Society Agent. In a dungeon (landblock 8E02)."}, + {"name":"Academy Crier","type":"NPC","wcid":13242,"cell":"8E02032B","place":"dungeon","id":8948,"desc":"Herald. In a dungeon (landblock 8E02)."}, + {"name":"Senior Guard","type":"NPC","wcid":29318,"cell":"8E02032C","place":"dungeon","id":8949,"desc":"Exploration Society Agent. In a dungeon (landblock 8E02)."}, + {"name":"Sentry","type":"NPC","wcid":30992,"cell":"8E0202C2","place":"dungeon","id":8950,"desc":"Exploration Society Agent. In a dungeon (landblock 8E02)."}, + {"name":"Odd Looking Vine","type":"NPC","wcid":27174,"cell":"8E4C0100","place":"building","ns":-40.8,"ew":11.89,"id":8951}, + {"name":"A'mun Gatestone","type":"NPC","wcid":39309,"cell":"8E4F0100","place":"building","ns":-38.2,"ew":12.0,"id":8952}, + {"name":"A'mun Node Golem","type":"NPC","wcid":80152,"cell":"8E4F001E","place":"outdoor","ns":-38.21,"ew":12.04,"id":8953,"desc":"Node Guardian."}, + {"name":"Lonely Weaponsmith","type":"Vendor","wcid":28533,"cell":"8F880100","place":"building","ns":6.99,"ew":12.6,"id":8954,"desc":"Vendor."}, + {"name":"Life Stone","type":"Lifestone","wcid":23618,"cell":"8FB20000","place":"outdoor","ns":40.6,"ew":12.47,"id":8955}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"8FC60000","place":"outdoor","ns":56.81,"ew":12.9,"id":8956}, + {"name":"Exploration Marker","type":"NPC","wcid":39785,"cell":"8FD10010","place":"outdoor","ns":65.96,"ew":12.64,"id":8957}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"90570103","place":"building","ns":-31.62,"ew":13.52,"id":8958,"desc":"Mage."}, + {"name":"Wedding Planner","type":"Vendor","wcid":14930,"cell":"90570103","place":"building","ns":-31.61,"ew":13.52,"id":8959,"desc":"Planner of Weddings."}, + {"name":"Sidzika the Grocer","type":"Vendor","wcid":4681,"cell":"9058011B","place":"building","ns":-30.98,"ew":14.0,"id":8960,"desc":"Grocer."}, + {"name":"Tailor Najsun","type":"Vendor","wcid":4686,"cell":"90580111","place":"building","ns":-31.0,"ew":13.97,"id":8961,"desc":"Tailor."}, + {"name":"Bashkiya the Scribe","type":"Vendor","wcid":4684,"cell":"90580113","place":"building","ns":-31.0,"ew":14.02,"id":8962,"desc":"Scribe."}, + {"name":"Archmage Jiz ibn Ijfai","type":"Vendor","wcid":4677,"cell":"90580114","place":"building","ns":-31.0,"ew":14.03,"id":8963,"desc":"Adept."}, + {"name":"Hinnabqiq the Jeweler","type":"Vendor","wcid":4683,"cell":"90580133","place":"building","ns":-31.28,"ew":13.46,"id":8964,"desc":"Jeweler."}, + {"name":"Smith Dah bint Nas","type":"Vendor","wcid":4679,"cell":"9058011F","place":"building","ns":-30.99,"ew":13.69,"id":8965,"desc":"Blacksmith."}, + {"name":"Collector","type":"NPC","wcid":3918,"cell":"90580120","place":"building","ns":-30.97,"ew":13.71,"id":8966,"desc":"Trophy Collector."}, + {"name":"Muta al-Mai the Bowyer","type":"Vendor","wcid":4680,"cell":"9058011F","place":"building","ns":-31.0,"ew":13.68,"id":8967,"desc":"Bowyer."}, + {"name":"Healer Sunwi","type":"Vendor","wcid":4682,"cell":"9058013C","place":"building","ns":-31.27,"ew":13.76,"id":8968,"desc":"Healer."}, + {"name":"Jilsaya bint Dah","type":"NPC","wcid":5152,"cell":"90580130","place":"building","ns":-31.32,"ew":13.48,"id":8969,"desc":"Society Agent."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":20221,"cell":"90580149","place":"building","ns":-31.52,"ew":13.74,"id":8970,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":20209,"cell":"90580143","place":"building","ns":-31.47,"ew":13.69,"id":8971,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":20225,"cell":"90580000","place":"outdoor","ns":-31.49,"ew":13.69,"id":8972,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":20213,"cell":"90580000","place":"outdoor","ns":-31.47,"ew":13.71,"id":8973,"desc":"Master Archmage."}, + {"name":"Jalina al-Hajj","type":"NPC","wcid":25951,"cell":"9058013E","place":"building","ns":-31.08,"ew":13.89,"id":8974,"desc":"Seamstress."}, + {"name":"Adara al-Rajin","type":"NPC","wcid":27251,"cell":"90580000","place":"outdoor","ns":-31.03,"ew":13.68,"id":8975,"desc":"Seamstress."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"90580000","place":"outdoor","ns":-31.32,"ew":13.58,"id":8976}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"90580000","place":"outdoor","ns":-31.18,"ew":13.84,"id":8977}, + {"name":"Apprentice Cook","type":"NPC","wcid":27744,"cell":"9058013E","place":"building","ns":-31.07,"ew":13.88,"id":8978}, + {"name":"Gersan the Sureshot","type":"NPC","wcid":8124,"cell":"90580013","place":"outdoor","ns":-31.31,"ew":13.49,"id":8979,"desc":"Trophy Collector."}, + {"name":"Gervena the Oblique","type":"NPC","wcid":8125,"cell":"90580013","place":"outdoor","ns":-31.31,"ew":13.48,"id":8980,"desc":"Trophy Collector."}, + {"name":"Gerloc the Defender","type":"NPC","wcid":8126,"cell":"90580013","place":"outdoor","ns":-31.32,"ew":13.48,"id":8981,"desc":"Trophy Collector."}, + {"name":"Shopkeeper Yasiya","type":"Vendor","wcid":4687,"cell":"905C0103","place":"building","ns":-28.19,"ew":13.8,"id":8982,"desc":"Shopkeeper."}, + {"name":"Sarqah bint Ak","type":"NPC","wcid":5154,"cell":"905C0100","place":"building","ns":-28.09,"ew":13.6,"id":8983,"desc":"Retired Enchanter."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"905C0000","place":"outdoor","ns":-28.13,"ew":13.8,"id":8984}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"90D00000","place":"outdoor","ns":64.82,"ew":13.4,"id":8985}, + {"name":"Silencia the Archmage","type":"Vendor","wcid":2498,"cell":"90D00000","place":"outdoor","ns":64.9,"ew":13.5,"id":8986,"desc":"Archmage."}, + {"name":"Geldeb Finol the Weaponsmith","type":"Vendor","wcid":2499,"cell":"90D00100","place":"building","ns":64.89,"ew":13.49,"id":8987,"desc":"Weaponsmith."}, + {"name":"Weldub Finol the Jeweler","type":"Vendor","wcid":2497,"cell":"90D00100","place":"building","ns":64.89,"ew":13.51,"id":8988,"desc":"Jeweler."}, + {"name":"Silencia's Magma Golem","type":"NPC","wcid":6356,"cell":"90D00000","place":"outdoor","ns":64.9,"ew":13.51,"id":8989}, + {"name":"Caleb Jinor the Healer","type":"Vendor","wcid":27554,"cell":"90D00100","place":"building","ns":64.9,"ew":13.49,"id":8990,"desc":"Jeweler."}, + {"name":"Journeyman Cook","type":"NPC","wcid":28921,"cell":"90D0010D","place":"building","ns":64.85,"ew":13.63,"id":8991,"desc":"Apprentice Cook."}, + {"name":"Exploration Marker","type":"NPC","wcid":39758,"cell":"91460004","place":"outdoor","ns":-45.56,"ew":14.05,"id":8992}, + {"name":"Archmage","type":"Vendor","wcid":1370,"cell":"91540100","place":"dungeon","id":8993,"desc":"In a dungeon (landblock 9154)."}, + {"name":"Shopkeep Qufar ibn Ijtalwa","type":"Vendor","wcid":4685,"cell":"91580106","place":"building","ns":-31.12,"ew":14.14,"id":8994,"desc":"Shopkeeper."}, + {"name":"Itir ibn Ativ the Barkeep","type":"Vendor","wcid":4678,"cell":"91580103","place":"building","ns":-31.08,"ew":14.12,"id":8995,"desc":"Barkeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"92240000","place":"outdoor","ns":-72.71,"ew":15.11,"id":8996}, + {"name":"Exploration Marker","type":"NPC","wcid":39760,"cell":"92D1001F","place":"outdoor","ns":65.95,"ew":15.15,"id":8997}, + {"name":"Altar","type":"NPC","wcid":72288,"cell":"9302015F","place":"dungeon","id":8998,"desc":"In Geraine's Study."}, + {"name":"Altar","type":"NPC","wcid":72289,"cell":"9302016E","place":"dungeon","id":8999,"desc":"In Geraine's Study."}, + {"name":"Altar","type":"NPC","wcid":72290,"cell":"93020184","place":"dungeon","id":9000,"desc":"In Geraine's Study."}, + {"name":"Corpse","type":"NPC","wcid":72311,"cell":"93020118","place":"dungeon","id":9001,"desc":"In Geraine's Study."}, + {"name":"Book","type":"NPC","wcid":72312,"cell":"930201B6","place":"dungeon","id":9002,"desc":"In Geraine's Study."}, + {"name":"Aino Lunnan-Shin","type":"NPC","wcid":8370,"cell":"934B0100","place":"building","ns":-41.71,"ew":16.12,"id":9003,"desc":"Gem Enchanter."}, + {"name":"Bhab, Arcanum Tinkerer","type":"NPC","wcid":19354,"cell":"934B0102","place":"building","ns":-41.6,"ew":15.8,"id":9004,"desc":"Bestower Examiner."}, + {"name":"Ciandra, Arcanum Alchemist","type":"NPC","wcid":19713,"cell":"934B0122","place":"building","ns":-41.81,"ew":15.83,"id":9005,"desc":"Mage."}, + {"name":"Hiro, Arcanum Artificer","type":"NPC","wcid":19460,"cell":"934B0102","place":"building","ns":-41.6,"ew":15.78,"id":9006,"desc":"Mage."}, + {"name":"Barkeep Anarn","type":"Vendor","wcid":8225,"cell":"934B01EA","place":"underground","ns":-41.72,"ew":16.01,"id":9007,"desc":"Barkeeper."}, + {"name":"Sifida bint Naril the Scribe","type":"Vendor","wcid":1821,"cell":"934B01F7","place":"underground","ns":-41.82,"ew":16.04,"id":9008,"desc":"Scribe."}, + {"name":"Jeweler Jurraf al-Djiqidh","type":"Vendor","wcid":8231,"cell":"934B01F8","place":"underground","ns":-41.71,"ew":16.11,"id":9009,"desc":"Jeweler."}, + {"name":"Smith Ashaira bint Maisa","type":"Vendor","wcid":8226,"cell":"934B0210","place":"underground","ns":-41.85,"ew":16.35,"id":9010,"desc":"Blacksmith."}, + {"name":"Archmage Zarri ibn Khaybi","type":"Vendor","wcid":8224,"cell":"934B0232","place":"underground","ns":-41.94,"ew":16.06,"id":9011,"desc":"Archmage."}, + {"name":"Fazyad ibn Raymar","type":"NPC","wcid":8229,"cell":"934B0260","place":"underground","ns":-41.79,"ew":16.2,"id":9012,"desc":"Bey."}, + {"name":"Farmer Khurah al-Rujarkir","type":"Vendor","wcid":8230,"cell":"934B028B","place":"underground","ns":-41.95,"ew":16.25,"id":9013,"desc":"Farmer."}, + {"name":"Bowyer Hanra ibn Zarib","type":"Vendor","wcid":8227,"cell":"934B02B2","place":"underground","ns":-41.73,"ew":16.4,"id":9014,"desc":"Bowyer."}, + {"name":"Alaine the Apprentice","type":"NPC","wcid":24224,"cell":"934B0124","place":"building","ns":-41.79,"ew":15.77,"id":9015,"desc":"Apprentice Alchemist."}, + {"name":"Small Creepy Statue","type":"NPC","wcid":25991,"cell":"934B0000","place":"outdoor","ns":-41.81,"ew":15.89,"id":9016}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"934B0302","place":"building","ns":-41.93,"ew":15.92,"id":9017,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"934B0308","place":"building","ns":-41.88,"ew":15.86,"id":9018,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"934B0000","place":"outdoor","ns":-41.91,"ew":15.9,"id":9019,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"934B0000","place":"outdoor","ns":-41.91,"ew":15.92,"id":9020,"desc":"Master Archmage."}, + {"name":"Cypher the Apprentice","type":"NPC","wcid":42716,"cell":"934B012E","place":"building","ns":-41.83,"ew":15.8,"id":9021,"desc":"Apprentice Alchemist."}, + {"name":"Janier al-Evv","type":"Vendor","wcid":35730,"cell":"934B0121","place":"building","ns":-41.81,"ew":15.82,"id":9022,"desc":"Master Alchemist."}, + {"name":"Talar the Apprentice","type":"NPC","wcid":33244,"cell":"934B012B","place":"building","ns":-41.82,"ew":15.79,"id":9023,"desc":"Apprentice Alchemist."}, + {"name":"Fayza","type":"NPC","wcid":43526,"cell":"934B0305","place":"building","ns":-41.9,"ew":15.87,"id":9024,"desc":"Arcanum Knowledge Seeker."}, + {"name":"Atamarr","type":"NPC","wcid":42112,"cell":"934B000B","place":"outdoor","ns":-41.74,"ew":15.77,"id":9025,"desc":"Gold Gear Primus."}, + {"name":"Kaytin","type":"NPC","wcid":42601,"cell":"934B000B","place":"outdoor","ns":-41.74,"ew":15.78,"id":9026,"desc":"Copper Cog Supply Officer."}, + {"name":"Merkitz ibn'Akadh","type":"NPC","wcid":42618,"cell":"934B000B","place":"outdoor","ns":-41.74,"ew":15.75,"id":9027,"desc":"Arcanum Portalmancer."}, + {"name":"Cara the Apprentice","type":"NPC","wcid":42519,"cell":"934B012E","place":"building","ns":-41.83,"ew":15.79,"id":9028}, + {"name":"Master Craftsman Takahume","type":"NPC","wcid":42116,"cell":"934B000B","place":"outdoor","ns":-41.74,"ew":15.79,"id":9029,"desc":"Arcanum Tinkerer."}, + {"name":"Nurino","type":"NPC","wcid":41208,"cell":"934B000C","place":"outdoor","ns":-41.64,"ew":15.78,"id":9030,"desc":"Arcanum Researcher."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"93560000","place":"outdoor","ns":-32.52,"ew":15.86,"id":9031}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"937A0000","place":"outdoor","ns":-4.27,"ew":15.92,"id":9032}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"937F0000","place":"outdoor","ns":0.13,"ew":16.3,"id":9033}, + {"name":"Nu'nifiba the Shopkeeper","type":"Vendor","wcid":4706,"cell":"937F0103","place":"building","ns":0.19,"ew":16.41,"id":9034,"desc":"Shopkeeper."}, + {"name":"Rubid al-Jurma","type":"NPC","wcid":5137,"cell":"937F0101","place":"building","ns":0.01,"ew":16.3,"id":9035,"desc":"Society Agent."}, + {"name":"Resonant Portal","type":"NPC","wcid":41051,"cell":"94720032","place":"outdoor","ns":-10.57,"ew":17.08,"id":9036}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"94CB0000","place":"outdoor","ns":60.87,"ew":16.56,"id":9037}, + {"name":"Ivory Crafter","type":"NPC","wcid":3925,"cell":"94D60100","place":"building","ns":69.69,"ew":16.49,"id":9038,"desc":"Trophy Crafter."}, + {"name":"Merchant","type":"Vendor","wcid":1388,"cell":"957A0000","place":"outdoor","ns":-4.13,"ew":17.32,"id":9039}, + {"name":"Zalphoos the Shopkeeper","type":"Vendor","wcid":1355,"cell":"95970100","place":"building","ns":19.29,"ew":17.6,"id":9040,"desc":"Shopkeeper."}, + {"name":"Esper Gatestone","type":"NPC","wcid":39310,"cell":"95CC0100","place":"building","ns":62.0,"ew":18.0,"id":9041}, + {"name":"Esper Node Golem","type":"NPC","wcid":80153,"cell":"95CC0040","place":"outdoor","ns":61.99,"ew":17.95,"id":9042,"desc":"Node Guardian."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"95D60000","place":"outdoor","ns":69.66,"ew":17.66,"id":9043}, + {"name":"Lisatha the Bowyer","type":"Vendor","wcid":5649,"cell":"95D60145","place":"building","ns":69.6,"ew":17.5,"id":9044,"desc":"Bowyer."}, + {"name":"Archmage Philomon","type":"Vendor","wcid":5646,"cell":"95D6012B","place":"building","ns":69.52,"ew":17.7,"id":9045,"desc":"Archmage."}, + {"name":"Viamasa the Weaponsmith","type":"Vendor","wcid":5648,"cell":"95D60000","place":"outdoor","ns":69.51,"ew":17.64,"id":9046,"desc":"Weaponsmith."}, + {"name":"Brother Jarviso","type":"Vendor","wcid":5647,"cell":"95D60126","place":"building","ns":69.7,"ew":17.5,"id":9047,"desc":"Healer."}, + {"name":"Lady Tallial","type":"NPC","wcid":5644,"cell":"95D6013E","place":"building","ns":69.69,"ew":17.59,"id":9048,"desc":"Trophy Collector."}, + {"name":"Yi Yo-Jin","type":"NPC","wcid":5898,"cell":"95D60000","place":"outdoor","ns":69.53,"ew":17.61,"id":9049,"desc":"Leather Crafter."}, + {"name":"Nelvaine the Brewer","type":"Vendor","wcid":5861,"cell":"95D60000","place":"outdoor","ns":69.68,"ew":17.55,"id":9050,"desc":"Brewer."}, + {"name":"Gormling the Sneaky Seneschal","type":"NPC","wcid":6889,"cell":"95D60107","place":"building","ns":69.52,"ew":17.6,"id":9051,"desc":"Seneschal of Neydisa."}, + {"name":"Loom","type":"NPC","wcid":19128,"cell":"95D6010A","place":"building","ns":69.53,"ew":17.64,"id":9052}, + {"name":"Journeyman Cook","type":"NPC","wcid":28922,"cell":"95D60000","place":"outdoor","ns":69.54,"ew":17.67,"id":9053,"desc":"Apprentice Cook."}, + {"name":"Emissary of Asheron","type":"NPC","wcid":43073,"cell":"95D6001C","place":"outdoor","ns":69.58,"ew":17.56,"id":9054,"desc":"Emissary."}, + {"name":"An Empyrean device","type":"NPC","wcid":43076,"cell":"95E9001C","place":"outdoor","ns":84.8,"ew":17.6,"id":9055}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"96230000","place":"outdoor","ns":-73.28,"ew":18.1,"id":9056}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"96990000","place":"outdoor","ns":20.96,"ew":18.63,"id":9057}, + {"name":"Master's Sentinel","type":"NPC","wcid":37169,"cell":"96DC001F","place":"outdoor","ns":74.73,"ew":18.44,"id":9058}, + {"name":"Iquba al-Julmud the Barkeeper","type":"Vendor","wcid":1050,"cell":"9722014F","place":"building","ns":-74.28,"ew":19.07,"id":9059,"desc":"Barkeeper."}, + {"name":"Kuyalal al-A'ma the Jeweler","type":"Vendor","wcid":1055,"cell":"9722011F","place":"building","ns":-74.31,"ew":19.28,"id":9060,"desc":"Jeweler."}, + {"name":"Uthab ibn Yafij the Scribe","type":"Vendor","wcid":1056,"cell":"97220129","place":"building","ns":-74.28,"ew":19.3,"id":9061,"desc":"Scribe."}, + {"name":"Suntar al-Tashqat the Shopkeep","type":"Vendor","wcid":1057,"cell":"97220121","place":"building","ns":-74.3,"ew":19.33,"id":9062,"desc":"Shopkeeper."}, + {"name":"Tamara bint Atwab the Armorer","type":"Vendor","wcid":1049,"cell":"9722012D","place":"building","ns":-74.43,"ew":19.2,"id":9063,"desc":"Armorer."}, + {"name":"Almina bint Atwab the Weaponsmith","type":"Vendor","wcid":1059,"cell":"9722012D","place":"building","ns":-74.41,"ew":19.19,"id":9064,"desc":"Weaponsmith."}, + {"name":"Miya bint Atwab the Bowyer","type":"Vendor","wcid":1052,"cell":"9722012F","place":"building","ns":-74.42,"ew":19.22,"id":9065,"desc":"Bowyer."}, + {"name":"Gharuya al-Dhul the Grocer","type":"Vendor","wcid":1053,"cell":"97220106","place":"building","ns":-74.48,"ew":19.28,"id":9066,"desc":"Grocer."}, + {"name":"Fazlim ibn Masay the Tailor","type":"Vendor","wcid":1058,"cell":"97220100","place":"building","ns":-74.52,"ew":19.33,"id":9067,"desc":"Tailor."}, + {"name":"Jumzik al-Budim the Archmage","type":"Vendor","wcid":1048,"cell":"9722013B","place":"building","ns":-74.38,"ew":19.37,"id":9068,"desc":"Archmage."}, + {"name":"Healer Windotha Sofyld","type":"Vendor","wcid":1054,"cell":"97220141","place":"building","ns":-74.42,"ew":19.42,"id":9069,"desc":"Healer."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"9722015A","place":"building","ns":-74.2,"ew":19.18,"id":9070,"desc":"Mage."}, + {"name":"Small Creepy Statue","type":"NPC","wcid":25989,"cell":"97220000","place":"outdoor","ns":-74.55,"ew":19.42,"id":9071}, + {"name":"Aun Maerirea","type":"NPC","wcid":27265,"cell":"97220000","place":"outdoor","ns":-74.51,"ew":19.33,"id":9072,"desc":"Glacial Golem Hunter."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"97220000","place":"outdoor","ns":-74.48,"ew":19.46,"id":9073}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"97220000","place":"outdoor","ns":-74.15,"ew":19.0,"id":9074}, + {"name":"Master Scrivener of Life Magic","type":"Vendor","wcid":20219,"cell":"9722017C","place":"building","ns":-74.01,"ew":18.98,"id":9075,"desc":"Master Archmage."}, + {"name":"Master Scrivener of Item Magic","type":"Vendor","wcid":20211,"cell":"9722017C","place":"building","ns":-73.99,"ew":18.98,"id":9076,"desc":"Master Archmage."}, + {"name":"Master Scrivener of Creature Magic","type":"Vendor","wcid":20207,"cell":"97220175","place":"building","ns":-74.03,"ew":18.99,"id":9077,"desc":"Master Archmage."}, + {"name":"Master Scrivener of War Magic","type":"Vendor","wcid":20223,"cell":"97220181","place":"building","ns":-74.0,"ew":18.96,"id":9078,"desc":"Master Archmage."}, + {"name":"Journeyman Alchemist","type":"NPC","wcid":28918,"cell":"9722012C","place":"building","ns":-74.27,"ew":19.31,"id":9079,"desc":"Apprentice Alchemist."}, + {"name":"Master Scrivener of Void Magic","type":"Vendor","wcid":43352,"cell":"97220177","place":"building","ns":-73.98,"ew":18.99,"id":9080,"desc":"Master Archmage."}, + {"name":"Nomea ibn Makar","type":"NPC","wcid":36720,"cell":"97220149","place":"building","ns":-74.32,"ew":19.12,"id":9081,"desc":"Prodigal Scholar."}, + {"name":"Guard Taziq","type":"NPC","wcid":36533,"cell":"9722014C","place":"building","ns":-74.32,"ew":19.08,"id":9082,"desc":"Soldier."}, + {"name":"Qath al-Haddash","type":"NPC","wcid":32217,"cell":"9722001E","place":"outdoor","ns":-74.22,"ew":19.16,"id":9083,"desc":"Rogue Scholar."}, + {"name":"Darsida al-Qawa","type":"NPC","wcid":9545,"cell":"97230100","place":"dungeon","id":9084,"desc":"Bestower Examiner. In a dungeon (landblock 9723)."}, + {"name":"Nerezi ibn Risad","type":"Vendor","wcid":9616,"cell":"97230100","place":"dungeon","id":9085,"desc":"Bestower Representative. In a dungeon (landblock 9723)."}, + {"name":"Da'hir ibn Khayzur the Archmage","type":"Vendor","wcid":2306,"cell":"977B012C","place":"building","ns":-2.91,"ew":19.27,"id":9086,"desc":"Archmage."}, + {"name":"Ushad al-Fasam the Grocer","type":"Vendor","wcid":978,"cell":"977B0121","place":"building","ns":-2.87,"ew":19.29,"id":9087,"desc":"Grocer."}, + {"name":"Sutaiya bint Yil the Scribe","type":"Vendor","wcid":981,"cell":"977B0129","place":"building","ns":-2.91,"ew":19.28,"id":9088,"desc":"Scribe."}, + {"name":"Nasruya al-Khanjan the Tailor","type":"Vendor","wcid":983,"cell":"977B011F","place":"building","ns":-2.92,"ew":19.3,"id":9089,"desc":"Tailor."}, + {"name":"Jeweler Fathlan ibn Nuril","type":"Vendor","wcid":980,"cell":"977B0106","place":"building","ns":-2.76,"ew":19.52,"id":9090,"desc":"Jeweler."}, + {"name":"Healer Burah bint Fathlan","type":"Vendor","wcid":979,"cell":"977B0100","place":"building","ns":-2.82,"ew":19.48,"id":9091,"desc":"Healer."}, + {"name":"Mishiya al-Abdi the Barkeeper","type":"Vendor","wcid":973,"cell":"977B013B","place":"building","ns":-2.78,"ew":19.6,"id":9092,"desc":"Barkeeper."}, + {"name":"Weaponsmith Ayiz ibn Khayt","type":"Vendor","wcid":976,"cell":"977B012D","place":"building","ns":-2.91,"ew":19.5,"id":9093,"desc":"Weaponsmith."}, + {"name":"Armorer Talam ibn Tarish","type":"Vendor","wcid":975,"cell":"977B012D","place":"building","ns":-2.92,"ew":19.5,"id":9094,"desc":"Armorer."}, + {"name":"Shopkeep Julsama bint Sakim","type":"Vendor","wcid":982,"cell":"977B014F","place":"building","ns":-2.94,"ew":19.59,"id":9095,"desc":"Shopkeeper."}, + {"name":"Thawasa al-La'ud the Bowyer","type":"Vendor","wcid":977,"cell":"977B0149","place":"building","ns":-2.88,"ew":19.62,"id":9096,"desc":"Bowyer."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"977B015A","place":"building","ns":-3.08,"ew":19.22,"id":9097,"desc":"Mage."}, + {"name":"Wedding Planner","type":"Vendor","wcid":14930,"cell":"977B015A","place":"building","ns":-3.07,"ew":19.21,"id":9098,"desc":"Planner of Weddings."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":20209,"cell":"977B0161","place":"building","ns":-2.98,"ew":19.43,"id":9099,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":20221,"cell":"977B0000","place":"outdoor","ns":-2.97,"ew":19.41,"id":9100,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":20225,"cell":"977B0000","place":"outdoor","ns":-3.0,"ew":19.41,"id":9101,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":20213,"cell":"977B0167","place":"building","ns":-3.03,"ew":19.39,"id":9102,"desc":"Master Archmage."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"977B0000","place":"outdoor","ns":-3.02,"ew":19.31,"id":9103}, + {"name":"Apprentice Fletcher","type":"NPC","wcid":27747,"cell":"977B0000","place":"outdoor","ns":-2.9,"ew":19.59,"id":9104}, + {"name":"Royal Quartermaster","type":"Vendor","wcid":37538,"cell":"977B0040","place":"outdoor","ns":-2.81,"ew":19.59,"id":9105,"desc":"Soldier."}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"977B000C","place":"outdoor","ns":-3.17,"ew":18.99,"id":9106,"desc":"Soldier."}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"977B0038","place":"outdoor","ns":-2.79,"ew":19.47,"id":9107,"desc":"Soldier."}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"977B003F","place":"outdoor","ns":-2.91,"ew":19.62,"id":9108,"desc":"Soldier."}, + {"name":"Strange Device","type":"NPC","wcid":36776,"cell":"979A000F","place":"outdoor","ns":21.95,"ew":18.96,"id":9109}, + {"name":"Merchant","type":"Vendor","wcid":1388,"cell":"981A0000","place":"outdoor","ns":-80.73,"ew":19.71,"id":9110}, + {"name":"Healer","type":"Vendor","wcid":1385,"cell":"981A0000","place":"outdoor","ns":-80.66,"ew":19.68,"id":9111}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"98230000","place":"outdoor","ns":-73.21,"ew":20.29,"id":9112}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"98780000","place":"outdoor","ns":-5.56,"ew":19.86,"id":9113}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"987B0000","place":"outdoor","ns":-2.85,"ew":19.72,"id":9114}, + {"name":"Aun Akuarea","type":"NPC","wcid":27266,"cell":"987C0000","place":"outdoor","ns":-2.63,"ew":19.92,"id":9115,"desc":"Mud Golem Hunter."}, + {"name":"Exploration Marker","type":"NPC","wcid":39844,"cell":"987C0039","place":"outdoor","ns":-2.68,"ew":20.41,"id":9116}, + {"name":"Peddler","type":"Vendor","wcid":1390,"cell":"98A60100","place":"building","ns":31.22,"ew":19.78,"id":9117}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"99200000","place":"outdoor","ns":-75.78,"ew":21.18,"id":9118}, + {"name":"A small pile of rocks","type":"NPC","wcid":25450,"cell":"998D0000","place":"outdoor","ns":11.03,"ew":21.1,"id":9119}, + {"name":"A small pile of rocks","type":"NPC","wcid":25450,"cell":"998D0000","place":"outdoor","ns":11.01,"ew":21.04,"id":9120}, + {"name":"A small pile of rocks","type":"NPC","wcid":25450,"cell":"998D0000","place":"outdoor","ns":10.96,"ew":21.14,"id":9121}, + {"name":"A small pile of rocks","type":"NPC","wcid":25450,"cell":"998D0000","place":"outdoor","ns":11.01,"ew":21.13,"id":9122}, + {"name":"A small pile of rocks","type":"NPC","wcid":25450,"cell":"998D0000","place":"outdoor","ns":11.07,"ew":21.03,"id":9123}, + {"name":"A small pile of rocks","type":"NPC","wcid":25450,"cell":"998D0000","place":"outdoor","ns":11.03,"ew":21.18,"id":9124}, + {"name":"Aun Tikakhe","type":"NPC","wcid":14577,"cell":"99E60000","place":"outdoor","ns":82.72,"ew":20.99,"id":9125}, + {"name":"Aun Aulakhe","type":"NPC","wcid":14571,"cell":"99E60000","place":"outdoor","ns":82.69,"ew":21.19,"id":9126}, + {"name":"Aun Saritea","type":"NPC","wcid":14578,"cell":"99E60000","place":"outdoor","ns":82.83,"ew":21.08,"id":9127}, + {"name":"Farmer","type":"Vendor","wcid":1382,"cell":"9A220104","place":"building","ns":-74.5,"ew":21.82,"id":9128}, + {"name":"Roaming Bowyer","type":"Vendor","wcid":1379,"cell":"9A220101","place":"building","ns":-74.58,"ew":21.81,"id":9129,"desc":"Bowyer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"9ABF0000","place":"outdoor","ns":51.06,"ew":21.28,"id":9130}, + {"name":"Master Celdiseth the Archmage","type":"Vendor","wcid":2246,"cell":"9AEB0102","place":"building","ns":86.6,"ew":21.61,"id":9131,"desc":"Master Archmage."}, + {"name":"Open Journal","type":"NPC","wcid":29957,"cell":"9B650109","place":"dungeon","id":9132,"desc":"In a dungeon (landblock 9B65)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"9B7B0000","place":"outdoor","ns":-3.11,"ew":22.17,"id":9133}, + {"name":"Ashqa the Shopkeeper","type":"Vendor","wcid":4705,"cell":"9B7B0104","place":"building","ns":-3.09,"ew":22.13,"id":9134,"desc":"Shopkeeper."}, + {"name":"Saqat","type":"NPC","wcid":5138,"cell":"9B7B0101","place":"building","ns":-3.27,"ew":22.1,"id":9135,"desc":"Citizen of Samsur."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"9C430000","place":"outdoor","ns":-48.07,"ew":23.16,"id":9136}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"9C790000","place":"outdoor","ns":-4.42,"ew":23.5,"id":9137}, + {"name":"Merchant","type":"Vendor","wcid":1388,"cell":"9C790101","place":"building","ns":-4.49,"ew":23.5,"id":9138}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"9D430000","place":"outdoor","ns":-48.17,"ew":24.43,"id":9139}, + {"name":"Cydna Wren","type":"NPC","wcid":25485,"cell":"9D850100","place":"dungeon","id":9140,"desc":"Ex-student. In a dungeon (landblock 9D85)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"9DC20000","place":"outdoor","ns":53.63,"ew":24.16,"id":9141}, + {"name":"Peddler","type":"Vendor","wcid":1390,"cell":"9DC20000","place":"outdoor","ns":53.68,"ew":24.08,"id":9142}, + {"name":"Exploration Marker","type":"NPC","wcid":39836,"cell":"9DC2002D","place":"outdoor","ns":53.65,"ew":24.17,"id":9143}, + {"name":"Barkeep Mausin ibn Hi","type":"Vendor","wcid":4696,"cell":"9E430112","place":"building","ns":-47.62,"ew":24.57,"id":9144,"desc":"Barkeeper."}, + {"name":"Tumina the Healer","type":"Vendor","wcid":4699,"cell":"9E43011F","place":"building","ns":-47.81,"ew":24.63,"id":9145,"desc":"Healer."}, + {"name":"Tailor Zayjah","type":"Vendor","wcid":4703,"cell":"9E43011A","place":"building","ns":-48.0,"ew":24.6,"id":9146,"desc":"Tailor."}, + {"name":"Grocer Sina bint Idnun","type":"Vendor","wcid":4698,"cell":"9E430122","place":"building","ns":-47.83,"ew":24.58,"id":9147,"desc":"Grocer."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"9E43012D","place":"building","ns":-48.01,"ew":24.49,"id":9148,"desc":"Mage."}, + {"name":"Najsuf al-Afan the Shopkeeper","type":"Vendor","wcid":4702,"cell":"9E440111","place":"building","ns":-47.52,"ew":24.6,"id":9149,"desc":"Shopkeeper."}, + {"name":"Weaponsmith Mura bint Mu'ja","type":"Vendor","wcid":4704,"cell":"9E44011F","place":"building","ns":-47.39,"ew":24.98,"id":9150,"desc":"Weaponsmith."}, + {"name":"Najmima the Archmage","type":"Vendor","wcid":4694,"cell":"9E440133","place":"building","ns":-47.24,"ew":24.88,"id":9151,"desc":"Sage."}, + {"name":"Scribe Tashwi ibn Sayat","type":"Vendor","wcid":4701,"cell":"9E44011B","place":"building","ns":-47.5,"ew":24.57,"id":9152,"desc":"Scribe."}, + {"name":"Jeweler Hawtala bint Arsha","type":"Vendor","wcid":4700,"cell":"9E440113","place":"building","ns":-47.47,"ew":24.6,"id":9153,"desc":"Jeweler."}, + {"name":"Bowyer Safruya bint Bilak","type":"Vendor","wcid":4697,"cell":"9E44013B","place":"building","ns":-47.09,"ew":24.69,"id":9154,"desc":"Bowyer."}, + {"name":"Armorer Hinfiya bint Ju","type":"Vendor","wcid":4695,"cell":"9E44011F","place":"building","ns":-47.39,"ew":25.0,"id":9155,"desc":"Armorer."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"9E44013E","place":"building","ns":-47.07,"ew":24.59,"id":9156,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"9E440141","place":"building","ns":-47.07,"ew":24.6,"id":9157,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"9E440143","place":"building","ns":-47.13,"ew":24.63,"id":9158,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"9E440144","place":"building","ns":-47.12,"ew":24.64,"id":9159,"desc":"Master Archmage."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"9E440000","place":"outdoor","ns":-47.4,"ew":24.89,"id":9160}, + {"name":"Apprentice Fletcher","type":"NPC","wcid":28189,"cell":"9E44013B","place":"building","ns":-47.09,"ew":24.67,"id":9161}, + {"name":"Peddler","type":"Vendor","wcid":1391,"cell":"9E580000","place":"outdoor","ns":-31.01,"ew":24.73,"id":9162}, + {"name":"Mage Syltyn Rillon","type":"NPC","wcid":24068,"cell":"9EA20100","place":"building","ns":27.78,"ew":24.71,"id":9163,"desc":"Aluvian Female."}, + {"name":"Creeping Blight Banner of the Courtyard","type":"NPC","wcid":38107,"cell":"9EE50024","place":"outdoor","ns":81.57,"ew":24.87,"id":9164}, + {"name":"Creeping Blight Banner of the Spire","type":"NPC","wcid":38113,"cell":"9EE50022","place":"outdoor","ns":81.42,"ew":24.9,"id":9165}, + {"name":"Creeping Blight Banner of the Tower","type":"NPC","wcid":38119,"cell":"9EE5000B","place":"outdoor","ns":81.49,"ew":24.57,"id":9166}, + {"name":"Exploration Marker","type":"NPC","wcid":39773,"cell":"9EE50002","place":"outdoor","ns":81.45,"ew":24.47,"id":9167}, + {"name":"Celestial Hand Buffing Array","type":"NPC","wcid":40534,"cell":"9EE5001B","place":"outdoor","ns":81.52,"ew":24.81,"id":9168}, + {"name":"Eldrytch Web Buffing Array","type":"NPC","wcid":40535,"cell":"9EE5001B","place":"outdoor","ns":81.52,"ew":24.81,"id":9169}, + {"name":"Radiant Blood Buffing Array","type":"NPC","wcid":40536,"cell":"9EE5001B","place":"outdoor","ns":81.52,"ew":24.81,"id":9170}, + {"name":"Master Mehkar al-Qalam","type":"NPC","wcid":80422,"cell":"9EE501AF","place":"underground","ns":81.24,"ew":25.26,"id":9171,"desc":"Underboss of Northwatch."}, + {"name":"Purser Narissa Pelton","type":"Vendor","wcid":80425,"cell":"9EE501CA","place":"underground","ns":81.29,"ew":25.25,"id":9172,"desc":"Shopkeeper."}, + {"name":"Arqubal the Archmage","type":"Vendor","wcid":80423,"cell":"9EE501CF","place":"underground","ns":81.29,"ew":25.29,"id":9173,"desc":"Black Market Archmage."}, + {"name":"Ilnorra Denasta","type":"NPC","wcid":80429,"cell":"9EE501B5","place":"underground","ns":81.25,"ew":25.33,"id":9174,"desc":"Black Market Gem-Fence."}, + {"name":"Janaris bint Bazheer","type":"NPC","wcid":80432,"cell":"9EE50198","place":"underground","ns":81.21,"ew":25.33,"id":9175,"desc":"Black Market Writ-Finagler."}, + {"name":"Chiriko","type":"NPC","wcid":80434,"cell":"9EE50155","place":"underground","ns":81.12,"ew":25.09,"id":9176,"desc":"Black Golem Hunter."}, + {"name":"Hanzo","type":"NPC","wcid":80436,"cell":"9EE50155","place":"underground","ns":81.12,"ew":25.08,"id":9177,"desc":"Blighted Golem Hunter."}, + {"name":"Consolata","type":"NPC","wcid":80427,"cell":"9EE50172","place":"underground","ns":81.17,"ew":25.3,"id":9178,"desc":"Black Market Gem-Fence."}, + {"name":"Valerian McGreggor","type":"NPC","wcid":80439,"cell":"9EE5018A","place":"underground","ns":81.21,"ew":25.12,"id":9179,"desc":"Deru Researcher."}, + {"name":"Lich Archmage","type":"Vendor","wcid":2540,"cell":"9F150000","place":"outdoor","ns":-84.41,"ew":25.59,"id":9180}, + {"name":"Chef Pleist","type":"NPC","wcid":25788,"cell":"9F290106","place":"building","ns":-68.51,"ew":25.31,"id":9181,"desc":"Chef."}, + {"name":"Elijah","type":"NPC","wcid":25793,"cell":"9F29010A","place":"building","ns":-68.51,"ew":25.49,"id":9182,"desc":"Ice Mechanic."}, + {"name":"Emma","type":"NPC","wcid":25794,"cell":"9F29010E","place":"building","ns":-68.62,"ew":25.3,"id":9183,"desc":"Mother."}, + {"name":"The Mayor","type":"NPC","wcid":25792,"cell":"9F290112","place":"building","ns":-68.7,"ew":25.4,"id":9184,"desc":"Mayor of Frost Haven."}, + {"name":"David","type":"NPC","wcid":48716,"cell":"9F29000D","place":"outdoor","ns":-68.65,"ew":25.37,"id":9185}, + {"name":"Nip","type":"NPC","wcid":25790,"cell":"9F29000E","place":"outdoor","ns":-68.58,"ew":25.4,"id":9186}, + {"name":"Numb","type":"NPC","wcid":25791,"cell":"9F29000E","place":"outdoor","ns":-68.6,"ew":25.4,"id":9187}, + {"name":"Robert","type":"NPC","wcid":25789,"cell":"9F290016","place":"outdoor","ns":-68.64,"ew":25.52,"id":9188,"desc":"Gardener."}, + {"name":"Archmage Cortorl","type":"Vendor","wcid":5425,"cell":"9FA40113","place":"building","ns":29.81,"ew":25.89,"id":9189,"desc":"Archmage."}, + {"name":"Belbeca the Weaponsmith","type":"Vendor","wcid":5428,"cell":"9FA40100","place":"building","ns":29.88,"ew":25.8,"id":9190,"desc":"Weaponsmith."}, + {"name":"Healer Fridroth","type":"Vendor","wcid":5427,"cell":"9FA4011B","place":"building","ns":29.69,"ew":25.9,"id":9191,"desc":"Healer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"9FA40000","place":"outdoor","ns":29.93,"ew":25.93,"id":9192}, + {"name":"Pondenn the Armorer","type":"Vendor","wcid":5426,"cell":"9FA40100","place":"building","ns":29.88,"ew":25.8,"id":9193,"desc":"Armorer."}, + {"name":"Weaponsmith Omaro Nagate","type":"NPC","wcid":24069,"cell":"9FA40104","place":"building","ns":29.93,"ew":25.82,"id":9194,"desc":"Weaponsmith."}, + {"name":"Chunk of Wood","type":"NPC","wcid":24158,"cell":"9FA70000","place":"outdoor","ns":32.1,"ew":25.57,"id":9195}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"9FB50000","place":"outdoor","ns":43.21,"ew":25.91,"id":9196}, + {"name":"Jolly Snowman","type":"Vendor","wcid":7883,"cell":"A0230102","place":"dungeon","id":9197,"desc":"Purveyor of Ice. In a dungeon (landblock A023)."}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"A02F0100","place":"building","ns":-63.71,"ew":26.19,"id":9198}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A02F0000","place":"outdoor","ns":-63.72,"ew":26.13,"id":9199}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A0440000","place":"outdoor","ns":-47.32,"ew":26.47,"id":9200}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A05F0000","place":"outdoor","ns":-25.9,"ew":26.63,"id":9201}, + {"name":"Farmer","type":"Vendor","wcid":1381,"cell":"A0A70100","place":"building","ns":31.82,"ew":26.3,"id":9202}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A1610000","place":"outdoor","ns":-24.14,"ew":27.44,"id":9203}, + {"name":"Jacque the Woodsman","type":"Vendor","wcid":13227,"cell":"A1A30034","place":"outdoor","ns":28.76,"ew":27.54,"id":9204,"desc":"Woodsman."}, + {"name":"Laurana","type":"Vendor","wcid":44076,"cell":"A1A30116","place":"underground","ns":29.11,"ew":27.35,"id":9205,"desc":"Master Fletcher."}, + {"name":"Cavern","type":"NPC","wcid":44075,"cell":"A1A30131","place":"underground","ns":29.07,"ew":27.22,"id":9206}, + {"name":"Fletching Forge","type":"NPC","wcid":30467,"cell":"A1A30118","place":"underground","ns":29.03,"ew":27.31,"id":9207}, + {"name":"Ystig Marson the Barkeeper","type":"Vendor","wcid":731,"cell":"A1A4012C","place":"building","ns":29.4,"ew":27.21,"id":9208,"desc":"Barkeeper."}, + {"name":"Fletcher Peldin Yewbender","type":"Vendor","wcid":733,"cell":"A1A4015B","place":"building","ns":29.9,"ew":26.9,"id":9209,"desc":"Bowyer."}, + {"name":"Fyrdina Ellic the Weaponsmith","type":"Vendor","wcid":739,"cell":"A1A40104","place":"building","ns":29.9,"ew":27.13,"id":9210,"desc":"Weaponsmith."}, + {"name":"Londigul Ellic the Armorer","type":"NPC","wcid":32360,"cell":"A1A40104","place":"building","ns":29.88,"ew":27.12,"id":9211,"desc":"Armorer."}, + {"name":"Arsitha Trell the Grocer","type":"Vendor","wcid":737,"cell":"A1A40118","place":"building","ns":29.81,"ew":27.44,"id":9212,"desc":"Shopkeeper."}, + {"name":"Danifa Gondmad the Healer","type":"Vendor","wcid":735,"cell":"A1A4010E","place":"building","ns":29.93,"ew":27.14,"id":9213,"desc":"Healer."}, + {"name":"Ortun Trell the Jeweler","type":"Vendor","wcid":736,"cell":"A1A4011A","place":"building","ns":29.78,"ew":27.41,"id":9214,"desc":"Jeweler."}, + {"name":"Hunderth the Provisioner","type":"Vendor","wcid":734,"cell":"A1A40144","place":"building","ns":29.61,"ew":27.49,"id":9215,"desc":"Grocer."}, + {"name":"Idenne Sulmad the Seamstress","type":"Vendor","wcid":738,"cell":"A1A40144","place":"building","ns":29.63,"ew":27.5,"id":9216,"desc":"Tailor."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A1A40000","place":"outdoor","ns":29.67,"ew":26.87,"id":9217}, + {"name":"Singud Trell the Archmage","type":"Vendor","wcid":2303,"cell":"A1A40124","place":"building","ns":29.77,"ew":27.4,"id":9218,"desc":"Archmage."}, + {"name":"Tiffany Comfore","type":"NPC","wcid":22074,"cell":"A1A40165","place":"building","ns":29.59,"ew":27.21,"id":9219,"desc":"Alchemical Artist."}, + {"name":"Wils Morrem","type":"NPC","wcid":22076,"cell":"A1A40165","place":"building","ns":29.59,"ew":27.19,"id":9220,"desc":"Artist in Wood and Feathers."}, + {"name":"Copper Vanurp","type":"NPC","wcid":22075,"cell":"A1A40165","place":"building","ns":29.61,"ew":27.21,"id":9221,"desc":"Food Designer."}, + {"name":"Student","type":"NPC","wcid":22893,"cell":"A1A40000","place":"outdoor","ns":29.86,"ew":27.13,"id":9222}, + {"name":"Sword of Frozen Fury","type":"NPC","wcid":24067,"cell":"A1A40000","place":"outdoor","ns":29.58,"ew":27.41,"id":9223}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"A1A40000","place":"outdoor","ns":29.93,"ew":27.44,"id":9224}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"A1A40168","place":"building","ns":29.79,"ew":27.61,"id":9225,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"A1A4016B","place":"building","ns":29.81,"ew":27.6,"id":9226,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"A1A40170","place":"building","ns":29.81,"ew":27.62,"id":9227,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"A1A4016F","place":"building","ns":29.8,"ew":27.58,"id":9228,"desc":"Master Archmage."}, + {"name":"Apprentice Cook","type":"NPC","wcid":28185,"cell":"A1A40000","place":"outdoor","ns":29.63,"ew":27.18,"id":9229}, + {"name":"Tomo Genza","type":"NPC","wcid":32362,"cell":"A1A40104","place":"building","ns":29.88,"ew":27.11,"id":9230,"desc":"Bow Warrior."}, + {"name":"Captain Sovano","type":"NPC","wcid":32394,"cell":"A1A40111","place":"building","ns":29.92,"ew":27.28,"id":9231,"desc":"Captain of the Royal Guard."}, + {"name":"Captain Anrayl","type":"NPC","wcid":32395,"cell":"A1A40111","place":"building","ns":29.91,"ew":27.28,"id":9232,"desc":"Captain of the Royal Guard."}, + {"name":"Captain Nyino","type":"NPC","wcid":32396,"cell":"A1A40111","place":"building","ns":29.92,"ew":27.28,"id":9233,"desc":"Captain of the Royal Guard."}, + {"name":"Ungrim the Unpleasant Smelling","type":"NPC","wcid":73172,"cell":"A1A40139","place":"building","ns":29.38,"ew":27.2,"id":9234,"desc":"Great Zombie Ulgrim."}, + {"name":"Exploration Marker","type":"NPC","wcid":39793,"cell":"A21D002B","place":"outdoor","ns":-78.53,"ew":28.16,"id":9235}, + {"name":"Aurutis","type":"NPC","wcid":9467,"cell":"A21E0000","place":"outdoor","ns":-77.74,"ew":28.18,"id":9236,"desc":"Noble."}, + {"name":"Lubrik the Resupplier","type":"Vendor","wcid":9418,"cell":"A21E0196","place":"building","ns":-77.43,"ew":28.17,"id":9237}, + {"name":"Krage the Blacksmith","type":"Vendor","wcid":9415,"cell":"A21E0129","place":"building","ns":-77.85,"ew":27.81,"id":9238}, + {"name":"Kifandal the Imbuer","type":"Vendor","wcid":9414,"cell":"A21E015F","place":"building","ns":-77.51,"ew":27.88,"id":9239}, + {"name":"Lord Kresovus","type":"NPC","wcid":9406,"cell":"A21E0000","place":"outdoor","ns":-77.59,"ew":28.02,"id":9240}, + {"name":"Omerik the Bowyer","type":"Vendor","wcid":9416,"cell":"A21E01A0","place":"building","ns":-77.47,"ew":28.24,"id":9241}, + {"name":"Myrlat the Physician","type":"Vendor","wcid":9417,"cell":"A21E0102","place":"building","ns":-77.78,"ew":28.26,"id":9242}, + {"name":"Master Ulkas","type":"NPC","wcid":9407,"cell":"A21E014F","place":"building","ns":-77.83,"ew":27.77,"id":9243}, + {"name":"Lugian Lifestone","type":"Lifestone","wcid":27096,"cell":"A21E0199","place":"building","ns":-77.38,"ew":28.22,"id":9244}, + {"name":"Captain K'rank","type":"NPC","wcid":28515,"cell":"A21E0000","place":"outdoor","ns":-77.74,"ew":27.97,"id":9245}, + {"name":"Neelic","type":"NPC","wcid":47191,"cell":"A21E0026","place":"outdoor","ns":-77.4,"ew":28.06,"id":9246}, + {"name":"Kresovus' Lockbox","type":"NPC","wcid":35478,"cell":"A21E001C","place":"outdoor","ns":-77.6,"ew":27.97,"id":9247}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A22B0000","place":"outdoor","ns":-67.3,"ew":28.3,"id":9248}, + {"name":"Healer","type":"Vendor","wcid":1386,"cell":"A22B0106","place":"building","ns":-67.3,"ew":28.15,"id":9249}, + {"name":"Peddler","type":"Vendor","wcid":1391,"cell":"A22B0106","place":"building","ns":-67.31,"ew":28.16,"id":9250}, + {"name":"Ruza bint Tinun the Armorer","type":"Vendor","wcid":1825,"cell":"A25F0119","place":"building","ns":-25.39,"ew":28.19,"id":9251,"desc":"Armorer."}, + {"name":"Ulib ibn Ghunir the Weaponsmith","type":"Vendor","wcid":1835,"cell":"A25F0119","place":"building","ns":-25.4,"ew":28.17,"id":9252,"desc":"Weaponsmith."}, + {"name":"Tailor Istima al-Mahat","type":"Vendor","wcid":1834,"cell":"A25F0114","place":"building","ns":-25.52,"ew":28.19,"id":9253,"desc":"Tailor."}, + {"name":"Maryata bint Daris the Barkeep","type":"Vendor","wcid":1826,"cell":"A25F0108","place":"building","ns":-25.68,"ew":28.16,"id":9254,"desc":"Barkeeper."}, + {"name":"Adraha bint Safsan the Appraiser","type":"Vendor","wcid":1831,"cell":"A25F0138","place":"building","ns":-25.93,"ew":28.2,"id":9255,"desc":"Jeweler."}, + {"name":"Ziya bint Balun the Grocer","type":"Vendor","wcid":1829,"cell":"A25F0111","place":"building","ns":-25.71,"ew":28.3,"id":9256,"desc":"Grocer."}, + {"name":"Yahr ibn Ajaj the Bowyer","type":"Vendor","wcid":1828,"cell":"A25F0100","place":"building","ns":-25.29,"ew":28.31,"id":9257,"desc":"Bowyer."}, + {"name":"Nashima al-Haruq the Healer","type":"Vendor","wcid":1830,"cell":"A25F0117","place":"building","ns":-25.51,"ew":28.31,"id":9258,"desc":"Healer."}, + {"name":"Barshid al-Juhir the Scribe","type":"Vendor","wcid":1832,"cell":"A25F0142","place":"building","ns":-25.9,"ew":28.17,"id":9259,"desc":"Scribe."}, + {"name":"Waham ibn Fadyat the Shopkeeper","type":"Vendor","wcid":1833,"cell":"A25F013A","place":"building","ns":-25.87,"ew":28.2,"id":9260,"desc":"Shopkeeper."}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"A25F0000","place":"outdoor","ns":-25.21,"ew":28.29,"id":9261}, + {"name":"Apprentice Cook","type":"NPC","wcid":49603,"cell":"A25F0111","place":"building","ns":-25.69,"ew":28.3,"id":9262}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":49597,"cell":"A25F0158","place":"building","ns":-25.33,"ew":28.2,"id":9263,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":49599,"cell":"A25F015F","place":"building","ns":-25.31,"ew":28.19,"id":9264,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":49598,"cell":"A25F0164","place":"building","ns":-25.3,"ew":28.17,"id":9265,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":49596,"cell":"A25F015A","place":"building","ns":-25.27,"ew":28.2,"id":9266,"desc":"Master Archmage."}, + {"name":"Leather Crafter","type":"NPC","wcid":49601,"cell":"A25F011A","place":"building","ns":-25.38,"ew":28.21,"id":9267,"desc":"Trophy Collector."}, + {"name":"Archmage Sammam al-Ashiz","type":"Vendor","wcid":1824,"cell":"A2600112","place":"building","ns":-24.98,"ew":28.41,"id":9268,"desc":"Archmage."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":49604,"cell":"A260011D","place":"building","ns":-25.11,"ew":28.18,"id":9269,"desc":"Mage."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A2600000","place":"outdoor","ns":-24.92,"ew":28.21,"id":9270}, + {"name":"Ivory Crafter","type":"NPC","wcid":49600,"cell":"A260010A","place":"building","ns":-25.0,"ew":28.43,"id":9271,"desc":"Trophy Crafter."}, + {"name":"Collector","type":"NPC","wcid":49602,"cell":"A260003A","place":"outdoor","ns":-24.97,"ew":28.42,"id":9272,"desc":"Trophy Collector."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"A2A40103","place":"building","ns":29.69,"ew":27.78,"id":9273,"desc":"Mage."}, + {"name":"Messenger for The Stranger","type":"NPC","wcid":42987,"cell":"A2A40105","place":"building","ns":29.7,"ew":27.79,"id":9274}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A3A40000","place":"outdoor","ns":29.68,"ew":28.94,"id":9275}, + {"name":"Fertroth the Healer","type":"Vendor","wcid":5424,"cell":"A3A40102","place":"building","ns":29.6,"ew":28.7,"id":9276,"desc":"Healer."}, + {"name":"Bowyer Brondig","type":"Vendor","wcid":5423,"cell":"A3A4010F","place":"building","ns":29.69,"ew":28.71,"id":9277,"desc":"Bowyer."}, + {"name":"Collector","type":"NPC","wcid":3917,"cell":"A3A40104","place":"building","ns":29.6,"ew":28.7,"id":9278,"desc":"Trophy Collector."}, + {"name":"Archmage Geltruma","type":"Vendor","wcid":5422,"cell":"A3A40108","place":"building","ns":29.69,"ew":28.9,"id":9279,"desc":"Archmage."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A3E90000","place":"outdoor","ns":85.03,"ew":28.5,"id":9280}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A45F0000","place":"outdoor","ns":-25.66,"ew":29.92,"id":9281}, + {"name":"Reformed Bandit","type":"NPC","wcid":14410,"cell":"A4B40000","place":"outdoor","ns":42.83,"ew":29.54,"id":9282,"desc":"Guard."}, + {"name":"Weaponsmith","type":"Vendor","wcid":1393,"cell":"A5AF0102","place":"building","ns":38.59,"ew":30.41,"id":9283}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A5B40000","place":"outdoor","ns":42.48,"ew":30.78,"id":9284}, + {"name":"Wantorth the Shopkeeper","type":"Vendor","wcid":4434,"cell":"A5B40000","place":"outdoor","ns":42.37,"ew":30.77,"id":9285,"desc":"Shopkeeper."}, + {"name":"Sentry","type":"NPC","wcid":12725,"cell":"A5B40119","place":"building","ns":42.4,"ew":30.41,"id":9286,"desc":"Soldier."}, + {"name":"Tornash","type":"NPC","wcid":22894,"cell":"A5B90000","place":"outdoor","ns":46.78,"ew":30.53,"id":9287,"desc":"Noble."}, + {"name":"Portal to Bur","type":"NPC","wcid":34593,"cell":"A5D30026","place":"outdoor","ns":67.4,"ew":30.5,"id":9288}, + {"name":"Portal Servitor","type":"NPC","wcid":34467,"cell":"A5D30027","place":"outdoor","ns":67.49,"ew":30.54,"id":9289,"desc":"Keeper of the Way."}, + {"name":"Northern Pedestal","type":"NPC","wcid":34743,"cell":"A5D30026","place":"outdoor","ns":67.44,"ew":30.5,"id":9290}, + {"name":"Eastern Pedestal","type":"NPC","wcid":34746,"cell":"A5D30026","place":"outdoor","ns":67.4,"ew":30.52,"id":9291}, + {"name":"Western Pedestal","type":"NPC","wcid":34744,"cell":"A5D30026","place":"outdoor","ns":67.4,"ew":30.47,"id":9292}, + {"name":"Leikotha","type":"NPC","wcid":6771,"cell":"A6720100","place":"underground","ns":-10.11,"ew":31.29,"id":9293,"desc":"Blademaster."}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"A7230000","place":"outdoor","ns":-73.31,"ew":31.89,"id":9294}, + {"name":"Healer","type":"Vendor","wcid":1384,"cell":"A7B40100","place":"building","ns":42.4,"ew":32.2,"id":9295}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"A7B40100","place":"building","ns":42.41,"ew":32.2,"id":9296}, + {"name":"Sentry","type":"NPC","wcid":12725,"cell":"A8B00000","place":"outdoor","ns":39.29,"ew":33.09,"id":9297,"desc":"Soldier."}, + {"name":"Northern Resonating Crystal","type":"NPC","wcid":37095,"cell":"A8BF000F","place":"outdoor","ns":51.5,"ew":32.6,"id":9298}, + {"name":"Exploration Marker","type":"NPC","wcid":39818,"cell":"A9110039","place":"outdoor","ns":-88.35,"ew":34.05,"id":9299}, + {"name":"Farmer","type":"Vendor","wcid":1383,"cell":"A9160104","place":"building","ns":-84.31,"ew":33.59,"id":9300}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A9160000","place":"outdoor","ns":-84.32,"ew":33.65,"id":9301}, + {"name":"Spear of the Given Heart","type":"NPC","wcid":23511,"cell":"A9530100","place":"building","ns":-35.1,"ew":33.6,"id":9302}, + {"name":"Grilhud the Hermit","type":"NPC","wcid":4202,"cell":"A98E0100","place":"underground","ns":11.86,"ew":33.69,"id":9303,"desc":"Enchanter."}, + {"name":"Eldrista the Adventurer","type":"NPC","wcid":22818,"cell":"A9AC0105","place":"building","ns":35.71,"ew":33.4,"id":9304,"desc":"Adventurer."}, + {"name":"Hudriffa the Shopkeeper","type":"Vendor","wcid":4433,"cell":"A9B00102","place":"building","ns":39.48,"ew":33.41,"id":9305,"desc":"Shopkeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A9B00000","place":"outdoor","ns":39.46,"ew":33.34,"id":9306}, + {"name":"Aluvian High-Stakes Gamesmaster","type":"NPC","wcid":9495,"cell":"A9B20106","place":"building","ns":40.81,"ew":33.59,"id":9307,"desc":"Gamesmaster."}, + {"name":"Aluvian High-Stakes Gamesmaster","type":"NPC","wcid":9495,"cell":"A9B20106","place":"building","ns":40.79,"ew":33.59,"id":9308,"desc":"Gamesmaster."}, + {"name":"Aluvian Mid-Stakes Gamesmaster","type":"NPC","wcid":9501,"cell":"A9B20106","place":"building","ns":40.81,"ew":33.6,"id":9309,"desc":"Gamesmaster."}, + {"name":"Aluvian Mid-Stakes Gamesmaster","type":"NPC","wcid":9501,"cell":"A9B20106","place":"building","ns":40.79,"ew":33.6,"id":9310,"desc":"Gamesmaster."}, + {"name":"Aluvian Low-Stakes Gamesmaster","type":"NPC","wcid":9498,"cell":"A9B20106","place":"building","ns":40.81,"ew":33.61,"id":9311,"desc":"Gamesmaster."}, + {"name":"Aluvian Low-Stakes Gamesmaster","type":"NPC","wcid":9498,"cell":"A9B20106","place":"building","ns":40.79,"ew":33.61,"id":9312,"desc":"Gamesmaster."}, + {"name":"Pawn Shopkeep","type":"Vendor","wcid":12308,"cell":"A9B20114","place":"building","ns":40.76,"ew":33.59,"id":9313,"desc":"Fence."}, + {"name":"Monty the Munificent","type":"NPC","wcid":9492,"cell":"A9B20113","place":"building","ns":40.84,"ew":33.61,"id":9314,"desc":"Gambler Boss."}, + {"name":"Boddry the Chancy","type":"Vendor","wcid":9504,"cell":"A9B2010B","place":"building","ns":40.83,"ew":33.63,"id":9315,"desc":"Cashier."}, + {"name":"Rare Exchanger","type":"NPC","wcid":40463,"cell":"A9B20114","place":"building","ns":40.76,"ew":33.61,"id":9316,"desc":"Gamesmaster."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20215,"cell":"A9B30101","place":"building","ns":41.58,"ew":34.02,"id":9317,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20217,"cell":"A9B30102","place":"building","ns":41.61,"ew":34.02,"id":9318,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":20205,"cell":"A9B30103","place":"building","ns":41.61,"ew":33.99,"id":9319,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":20206,"cell":"A9B30108","place":"building","ns":41.6,"ew":34.02,"id":9320,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20218,"cell":"A9B30107","place":"building","ns":41.59,"ew":33.99,"id":9321,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20216,"cell":"A9B30000","place":"outdoor","ns":41.58,"ew":34.02,"id":9322,"desc":"Master Archmage."}, + {"name":"Scrivener of Void Magic","type":"Vendor","wcid":43354,"cell":"A9B30103","place":"building","ns":41.58,"ew":33.99,"id":9323,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":20221,"cell":"A9B30107","place":"building","ns":41.59,"ew":33.99,"id":9324,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"A9B30107","place":"building","ns":41.58,"ew":33.99,"id":9325,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":20209,"cell":"A9B30108","place":"building","ns":41.61,"ew":34.02,"id":9326,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"A9B30108","place":"building","ns":41.62,"ew":34.01,"id":9327,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"A9B30100","place":"building","ns":41.61,"ew":34.01,"id":9328,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":20225,"cell":"A9B30103","place":"building","ns":41.59,"ew":33.98,"id":9329,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":20213,"cell":"A9B3003C","place":"outdoor","ns":41.57,"ew":34.01,"id":9330,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"A9B3003C","place":"outdoor","ns":41.61,"ew":34.03,"id":9331,"desc":"Master Archmage."}, + {"name":"Monyra the Jeweler","type":"Vendor","wcid":716,"cell":"A9B40117","place":"building","ns":42.61,"ew":33.9,"id":9332,"desc":"Jeweler."}, + {"name":"Shopkeeper Renald the Elder","type":"Vendor","wcid":718,"cell":"A9B40141","place":"building","ns":42.13,"ew":33.83,"id":9333,"desc":"Shopkeeper."}, + {"name":"Barkeeper Wilomine","type":"Vendor","wcid":710,"cell":"A9B40155","place":"building","ns":42.2,"ew":33.7,"id":9334,"desc":"Barkeeper."}, + {"name":"Scribe Renald the Younger","type":"Vendor","wcid":717,"cell":"A9B4013F","place":"building","ns":42.1,"ew":33.8,"id":9335,"desc":"Scribe."}, + {"name":"Fispur Ansel the Grocer","type":"Vendor","wcid":714,"cell":"A9B4016A","place":"building","ns":42.21,"ew":33.58,"id":9336,"desc":"Grocer."}, + {"name":"Ecutha the Tailor","type":"Vendor","wcid":719,"cell":"A9B4012A","place":"building","ns":42.6,"ew":33.49,"id":9337,"desc":"Tailor."}, + {"name":"Sedor Wystan the Blacksmith","type":"Vendor","wcid":712,"cell":"A9B40100","place":"building","ns":42.6,"ew":33.61,"id":9338,"desc":"Blacksmith."}, + {"name":"Thelnoth Cort the Healer","type":"Vendor","wcid":715,"cell":"A9B40111","place":"building","ns":42.72,"ew":33.38,"id":9339,"desc":"Healer."}, + {"name":"Sontella Dagroff the Bowyer","type":"Vendor","wcid":713,"cell":"A9B40121","place":"building","ns":42.62,"ew":33.67,"id":9340,"desc":"Bowyer."}, + {"name":"Flinrala Ryndmad","type":"NPC","wcid":5033,"cell":"A9B40169","place":"building","ns":42.24,"ew":33.68,"id":9341,"desc":"Society Agent."}, + {"name":"Archmage Cindrue","type":"Vendor","wcid":2304,"cell":"A9B4011B","place":"building","ns":42.6,"ew":33.88,"id":9342,"desc":"Archmage."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"A9B40172","place":"building","ns":42.07,"ew":33.93,"id":9343,"desc":"Mage."}, + {"name":"Wedding Planner","type":"Vendor","wcid":14930,"cell":"A9B40172","place":"building","ns":42.09,"ew":33.93,"id":9344,"desc":"Planner of Weddings."}, + {"name":"Novedion the Gem Seller","type":"Vendor","wcid":9423,"cell":"A9B40000","place":"outdoor","ns":42.18,"ew":33.77,"id":9345,"desc":"Gem Seller."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"A9B40000","place":"outdoor","ns":42.1,"ew":33.59,"id":9346}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"A9B40000","place":"outdoor","ns":42.22,"ew":33.85,"id":9347}, + {"name":"Apprentice Alchemist","type":"NPC","wcid":27740,"cell":"A9B4014D","place":"building","ns":42.08,"ew":33.83,"id":9348}, + {"name":"Worcer","type":"NPC","wcid":5035,"cell":"A9B40169","place":"building","ns":42.24,"ew":33.7,"id":9349,"desc":"Citizen of Holtburg."}, + {"name":"Alfrin","type":"NPC","wcid":30479,"cell":"A9B40169","place":"building","ns":42.24,"ew":33.7,"id":9350,"desc":"Aspiring Farmer."}, + {"name":"Alchemy Forge","type":"NPC","wcid":30465,"cell":"A9B40000","place":"outdoor","ns":42.64,"ew":33.84,"id":9351}, + {"name":"Fletching Forge","type":"NPC","wcid":30467,"cell":"A9B40000","place":"outdoor","ns":42.59,"ew":33.69,"id":9352}, + {"name":"Cooking Forge","type":"NPC","wcid":30466,"cell":"A9B40000","place":"outdoor","ns":42.21,"ew":33.63,"id":9353}, + {"name":"Lockpick Forge","type":"NPC","wcid":30460,"cell":"A9B40000","place":"outdoor","ns":42.1,"ew":33.76,"id":9354}, + {"name":"Salvaging Forge","type":"NPC","wcid":30461,"cell":"A9B40000","place":"outdoor","ns":42.6,"ew":33.53,"id":9355}, + {"name":"Tirenia","type":"NPC","wcid":30696,"cell":"A9B40000","place":"outdoor","ns":42.14,"ew":33.67,"id":9356,"desc":"Royal Guard."}, + {"name":"Dwennon","type":"NPC","wcid":33970,"cell":"A9B4001E","place":"outdoor","ns":42.63,"ew":33.55,"id":9357,"desc":"Covert Operative."}, + {"name":"Renald the Eldest","type":"NPC","wcid":28856,"cell":"A9B40029","place":"outdoor","ns":42.07,"ew":33.79,"id":9358,"desc":"Wood Carver."}, + {"name":"Alcott","type":"NPC","wcid":44895,"cell":"A9B40019","place":"outdoor","ns":42.11,"ew":33.6,"id":9359,"desc":"Lifestone Greeter."}, + {"name":"Pathwarden Thorolf","type":"NPC","wcid":33596,"cell":"A9B40022","place":"outdoor","ns":42.16,"ew":33.65,"id":9360,"desc":"Pathwarden Greeter."}, + {"name":"Buckminster","type":"NPC","wcid":44891,"cell":"A9B40163","place":"building","ns":42.2,"ew":33.69,"id":9361,"desc":"Bartender Greeter."}, + {"name":"Ianto","type":"Vendor","wcid":42428,"cell":"A9B4012A","place":"building","ns":42.62,"ew":33.5,"id":9362,"desc":"Master Tailor."}, + {"name":"Asenala","type":"Vendor","wcid":49518,"cell":"A9B4011B","place":"building","ns":42.59,"ew":33.9,"id":9363,"desc":"Geomancer."}, + {"name":"Ealdred","type":"NPC","wcid":42720,"cell":"A9B40127","place":"building","ns":42.62,"ew":33.48,"id":9364,"desc":"Barber."}, + {"name":"Exploration Marker","type":"NPC","wcid":39748,"cell":"A9B40022","place":"outdoor","ns":42.24,"ew":33.72,"id":9365}, + {"name":"Sean the Speedy","type":"NPC","wcid":39746,"cell":"A9B40022","place":"outdoor","ns":42.24,"ew":33.73,"id":9366,"desc":"Society Explorer."}, + {"name":"Contract Broker","type":"Vendor","wcid":44186,"cell":"A9B40162","place":"building","ns":42.2,"ew":33.73,"id":9367,"desc":"Armorer."}, + {"name":"Gawain Cooper","type":"NPC","wcid":44190,"cell":"A9B40162","place":"building","ns":42.19,"ew":33.72,"id":9368}, + {"name":"Arcanum Refurbisher","type":"NPC","wcid":32085,"cell":"A9B40172","place":"building","ns":42.07,"ew":33.92,"id":9369,"desc":"Renovation Specialist."}, + {"name":"Tailor's Apprentice","type":"NPC","wcid":42736,"cell":"A9B4012A","place":"building","ns":42.62,"ew":33.5,"id":9370}, + {"name":"Rand, Game Hunter","type":"NPC","wcid":39983,"cell":"A9B40032","place":"outdoor","ns":42.2,"ew":33.89,"id":9371,"desc":"Game Hunter."}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"A9B40021","place":"outdoor","ns":42.08,"ew":33.73,"id":9372,"desc":"Soldier."}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"A9B40005","place":"outdoor","ns":42.53,"ew":33.29,"id":9373,"desc":"Soldier."}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"A9B4003D","place":"outdoor","ns":42.49,"ew":33.99,"id":9374,"desc":"Soldier."}, + {"name":"Bottle","type":"NPC","wcid":40526,"cell":"A9B40155","place":"building","ns":42.21,"ew":33.7,"id":9375}, + {"name":"Aeshnidae Buff Bot","type":"NPC","wcid":90300,"cell":"A9B40019","place":"outdoor","ns":42.13,"ew":33.58,"id":9376,"desc":"Buff Bot."}, + {"name":"Woodsman","type":"Vendor","wcid":13223,"cell":"A9B50000","place":"outdoor","ns":43.41,"ew":33.29,"id":9377}, + {"name":"Exploration Marker","type":"NPC","wcid":39803,"cell":"AA4F0025","place":"outdoor","ns":-38.29,"ew":34.51,"id":9378}, + {"name":"Sir Rylanan","type":"NPC","wcid":14413,"cell":"AAB30100","place":"building","ns":41.62,"ew":34.2,"id":9379,"desc":"Senior Guard."}, + {"name":"Sentry","type":"NPC","wcid":14457,"cell":"AAB30000","place":"outdoor","ns":41.6,"ew":34.12,"id":9380,"desc":"Guard."}, + {"name":"Sentry","type":"NPC","wcid":14458,"cell":"AAB30000","place":"outdoor","ns":41.55,"ew":34.3,"id":9381,"desc":"Guard."}, + {"name":"Sentry","type":"NPC","wcid":12725,"cell":"AAB30000","place":"outdoor","ns":41.5,"ew":34.51,"id":9382,"desc":"Soldier."}, + {"name":"Aun Kielerea","type":"NPC","wcid":27268,"cell":"AAB30000","place":"outdoor","ns":41.59,"ew":34.19,"id":9383,"desc":"Hunter."}, + {"name":"Royal Guard","type":"NPC","wcid":33805,"cell":"AAB3000C","place":"outdoor","ns":41.64,"ew":34.16,"id":9384,"desc":"Guard."}, + {"name":"Tackle Master","type":"NPC","wcid":23336,"cell":"AAB50100","place":"building","ns":42.99,"ew":34.06,"id":9385,"desc":"Pro Fisherman."}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.07,"ew":34.18,"id":9386}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.08,"ew":34.13,"id":9387}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.14,"ew":34.21,"id":9388}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.13,"ew":34.13,"id":9389}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.13,"ew":34.08,"id":9390}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.08,"ew":34.11,"id":9391}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.1,"ew":34.14,"id":9392}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.13,"ew":34.15,"id":9393}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.13,"ew":34.1,"id":9394}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.12,"ew":34.07,"id":9395}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.14,"ew":34.09,"id":9396}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.16,"ew":34.12,"id":9397}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.09,"ew":34.15,"id":9398}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"AAB50000","place":"outdoor","ns":43.07,"ew":34.15,"id":9399}, + {"name":"Merchant","type":"Vendor","wcid":1387,"cell":"ABB30102","place":"building","ns":41.7,"ew":35.19,"id":9400}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"ABB30000","place":"outdoor","ns":42.02,"ew":34.92,"id":9401}, + {"name":"Giant Snowman","type":"Vendor","wcid":5767,"cell":"AC230000","place":"outdoor","ns":-73.66,"ew":35.85,"id":9402}, + {"name":"Healer","type":"Vendor","wcid":1384,"cell":"ACB70100","place":"building","ns":44.9,"ew":36.4,"id":9403}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"AD580000","place":"outdoor","ns":-31.46,"ew":37.06,"id":9404}, + {"name":"Archmage","type":"Vendor","wcid":1371,"cell":"AD580100","place":"building","ns":-31.51,"ew":37.09,"id":9405}, + {"name":"Kayna bint Iswas","type":"NPC","wcid":6770,"cell":"AD7D011E","place":"building","ns":-1.58,"ew":36.59,"id":9406,"desc":"Enchanter."}, + {"name":"Exploration Marker","type":"NPC","wcid":39777,"cell":"AD7D000C","place":"outdoor","ns":-1.58,"ew":36.63,"id":9407}, + {"name":"Farmer","type":"Vendor","wcid":1381,"cell":"AD9B0102","place":"building","ns":22.6,"ew":37.1,"id":9408}, + {"name":"Peddler","type":"Vendor","wcid":1390,"cell":"ADB20102","place":"building","ns":40.8,"ew":36.49,"id":9409}, + {"name":"Exploration Marker","type":"NPC","wcid":39751,"cell":"AE8D0037","place":"outdoor","ns":11.47,"ew":37.93,"id":9410}, + {"name":"Roaming Bowyer","type":"Vendor","wcid":1378,"cell":"AED90102","place":"building","ns":71.77,"ew":37.99,"id":9411,"desc":"Bowyer."}, + {"name":"Archmage","type":"Vendor","wcid":1369,"cell":"AED90104","place":"building","ns":71.78,"ew":38.0,"id":9412}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"AED90000","place":"outdoor","ns":71.92,"ew":37.99,"id":9413}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"AFC70000","place":"outdoor","ns":57.37,"ew":38.62,"id":9414}, + {"name":"Larinne Kerendova","type":"NPC","wcid":33939,"cell":"B0AB0100","place":"building","ns":35.21,"ew":39.3,"id":9415,"desc":"Pet Store Manager."}, + {"name":"Tamara Mistrunner","type":"NPC","wcid":33938,"cell":"B0AB0108","place":"building","ns":35.17,"ew":39.34,"id":9416,"desc":"Pet Ursuin Vendor."}, + {"name":"Gharon al-Bhavarn","type":"NPC","wcid":33935,"cell":"B0AB010C","place":"building","ns":35.18,"ew":39.32,"id":9417,"desc":"Pet Armoredillo Vendor."}, + {"name":"Ma-Kii","type":"NPC","wcid":33936,"cell":"B0AB010C","place":"building","ns":35.21,"ew":39.3,"id":9418,"desc":"Pet Drudge Vendor."}, + {"name":"Elise Du Ricard","type":"NPC","wcid":33937,"cell":"B0AB0104","place":"building","ns":35.2,"ew":39.34,"id":9419,"desc":"Pet Thrungus Vendor."}, + {"name":"Pet Armoredillo Pup","type":"NPC","wcid":33961,"cell":"B0AB010C","place":"building","ns":35.19,"ew":39.33,"id":9420}, + {"name":"Pet Baby Drudge","type":"NPC","wcid":33962,"cell":"B0AB010C","place":"building","ns":35.21,"ew":39.32,"id":9421}, + {"name":"Pet Baby Thrungus","type":"NPC","wcid":33963,"cell":"B0AB0102","place":"building","ns":35.22,"ew":39.34,"id":9422}, + {"name":"Pet Ursuin Cub","type":"NPC","wcid":33964,"cell":"B0AB0109","place":"building","ns":35.19,"ew":39.31,"id":9423}, + {"name":"Pet Baby Thrungus","type":"NPC","wcid":33963,"cell":"B0AB0102","place":"building","ns":35.22,"ew":39.33,"id":9424}, + {"name":"Pet Baby Thrungus","type":"NPC","wcid":33963,"cell":"B0AB0102","place":"building","ns":35.21,"ew":39.34,"id":9425}, + {"name":"Pet Ursuin Cub","type":"NPC","wcid":33964,"cell":"B0AB0109","place":"building","ns":35.17,"ew":39.31,"id":9426}, + {"name":"Pet Baby Drudge","type":"NPC","wcid":33962,"cell":"B0AB010C","place":"building","ns":35.21,"ew":39.31,"id":9427}, + {"name":"Pet Baby Drudge","type":"NPC","wcid":33962,"cell":"B0AB010E","place":"building","ns":35.21,"ew":39.34,"id":9428}, + {"name":"Pet Armoredillo Pup","type":"NPC","wcid":33961,"cell":"B0AB010E","place":"building","ns":35.2,"ew":39.34,"id":9429}, + {"name":"Pet Armoredillo Pup","type":"NPC","wcid":33961,"cell":"B0AB010E","place":"building","ns":35.19,"ew":39.34,"id":9430}, + {"name":"Pet Ursuin Cub","type":"NPC","wcid":33964,"cell":"B0AB0109","place":"building","ns":35.16,"ew":39.31,"id":9431}, + {"name":"Pet Ursuin Cub","type":"NPC","wcid":33964,"cell":"B0AB0109","place":"building","ns":35.16,"ew":39.3,"id":9432}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B1320000","place":"outdoor","ns":-61.8,"ew":39.91,"id":9433}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B1370000","place":"outdoor","ns":-57.88,"ew":40.0,"id":9434}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"B1370112","place":"building","ns":-57.91,"ew":39.99,"id":9435}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B13F0000","place":"outdoor","ns":-51.35,"ew":40.27,"id":9436}, + {"name":"Hemmik the Sly","type":"NPC","wcid":25600,"cell":"B1A90000","place":"outdoor","ns":33.98,"ew":39.7,"id":9437,"desc":"Suspicious Vagabond."}, + {"name":"Swift's Marker","type":"NPC","wcid":53487,"cell":"B3490036","place":"outdoor","ns":-43.02,"ew":41.9,"id":9438}, + {"name":"Scattered Notes","type":"NPC","wcid":53216,"cell":"B349001C","place":"outdoor","ns":-43.18,"ew":41.62,"id":9439}, + {"name":"Guardian of Yew","type":"NPC","wcid":53214,"cell":"B349001B","place":"outdoor","ns":-43.3,"ew":41.59,"id":9440}, + {"name":"Guardian of Willow","type":"NPC","wcid":53213,"cell":"B349001B","place":"outdoor","ns":-43.29,"ew":41.56,"id":9441}, + {"name":"Guardian of Spruce","type":"NPC","wcid":53212,"cell":"B3490013","place":"outdoor","ns":-43.26,"ew":41.52,"id":9442}, + {"name":"Guardian of Pine","type":"NPC","wcid":53211,"cell":"B3490014","place":"outdoor","ns":-43.23,"ew":41.51,"id":9443}, + {"name":"Guardian of Oak","type":"NPC","wcid":53210,"cell":"B3490014","place":"outdoor","ns":-43.19,"ew":41.52,"id":9444}, + {"name":"Guardian of Maple","type":"NPC","wcid":53209,"cell":"B349001C","place":"outdoor","ns":-43.16,"ew":41.55,"id":9445}, + {"name":"Guardian of Hickory","type":"NPC","wcid":53208,"cell":"B349001C","place":"outdoor","ns":-43.15,"ew":41.59,"id":9446}, + {"name":"Guardian of Cedar","type":"NPC","wcid":53207,"cell":"B349001C","place":"outdoor","ns":-43.16,"ew":41.63,"id":9447}, + {"name":"Guardian of Birch","type":"NPC","wcid":53206,"cell":"B3490024","place":"outdoor","ns":-43.19,"ew":41.66,"id":9448}, + {"name":"Guardian of Ash","type":"NPC","wcid":53147,"cell":"B3490024","place":"outdoor","ns":-43.23,"ew":41.68,"id":9449}, + {"name":"Brellegia's Marker","type":"NPC","wcid":53486,"cell":"B349003C","place":"outdoor","ns":-43.21,"ew":41.97,"id":9450}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53130,"cell":"B349001C","place":"outdoor","ns":-43.23,"ew":41.6,"id":9451}, + {"name":"Aangesilus' Marker","type":"NPC","wcid":53488,"cell":"B3490035","place":"outdoor","ns":-43.09,"ew":41.88,"id":9452}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53033,"cell":"B34A0029","place":"outdoor","ns":-42.7,"ew":41.77,"id":9453}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53037,"cell":"B34A003B","place":"outdoor","ns":-42.46,"ew":42.04,"id":9454}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53034,"cell":"B34A0023","place":"outdoor","ns":-42.52,"ew":41.68,"id":9455}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53035,"cell":"B34A0025","place":"outdoor","ns":-42.29,"ew":41.7,"id":9456}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53036,"cell":"B34A0030","place":"outdoor","ns":-41.99,"ew":41.78,"id":9457}, + {"name":"First Enchanted Candle","type":"NPC","wcid":42958,"cell":"B36F003E","place":"outdoor","ns":-12.6,"ew":42.0,"id":9458}, + {"name":"Wedding Fireworks Launcher","type":"NPC","wcid":42955,"cell":"B36F0024","place":"outdoor","ns":-12.77,"ew":41.71,"id":9459}, + {"name":"Wedding Fireworks Launcher","type":"NPC","wcid":42955,"cell":"B36F001C","place":"outdoor","ns":-12.77,"ew":41.64,"id":9460}, + {"name":"Wedding Fireworks Launcher","type":"NPC","wcid":42955,"cell":"B36F0023","place":"outdoor","ns":-12.88,"ew":41.71,"id":9461}, + {"name":"Wedding Fireworks Launcher","type":"NPC","wcid":42955,"cell":"B36F001B","place":"outdoor","ns":-12.88,"ew":41.64,"id":9462}, + {"name":"Third Enchanted Candle","type":"NPC","wcid":42960,"cell":"B36F0003","place":"outdoor","ns":-12.9,"ew":41.3,"id":9463}, + {"name":"Second Enchanted Candle","type":"NPC","wcid":42959,"cell":"B36F0008","place":"outdoor","ns":-12.4,"ew":41.3,"id":9464}, + {"name":"Sir Draithon","type":"NPC","wcid":42734,"cell":"B36F002B","place":"outdoor","ns":-12.88,"ew":41.76,"id":9465,"desc":"Borelean's Royal Guard."}, + {"name":"Hoshino Kiri","type":"NPC","wcid":42957,"cell":"B36F001A","place":"outdoor","ns":-13.01,"ew":41.63,"id":9466,"desc":"Hoshino Kei's Sister."}, + {"name":"Rock Pile","type":"NPC","wcid":42962,"cell":"B3700103","place":"building","ns":-12.11,"ew":41.82,"id":9467}, + {"name":"Rock Pile","type":"NPC","wcid":42969,"cell":"B3700119","place":"building","ns":-11.99,"ew":41.84,"id":9468}, + {"name":"Rock Pile","type":"NPC","wcid":42976,"cell":"B370002A","place":"outdoor","ns":-12.2,"ew":41.78,"id":9469}, + {"name":"Rock Pile","type":"NPC","wcid":42966,"cell":"B370002A","place":"outdoor","ns":-12.22,"ew":41.75,"id":9470}, + {"name":"Rock Pile","type":"NPC","wcid":42965,"cell":"B370002A","place":"outdoor","ns":-12.19,"ew":41.79,"id":9471}, + {"name":"Rock Pile","type":"NPC","wcid":42971,"cell":"B370002B","place":"outdoor","ns":-12.14,"ew":41.81,"id":9472}, + {"name":"Rock Pile","type":"NPC","wcid":42961,"cell":"B3700022","place":"outdoor","ns":-12.21,"ew":41.7,"id":9473}, + {"name":"Rock Pile","type":"NPC","wcid":42974,"cell":"B3700025","place":"outdoor","ns":-11.9,"ew":41.7,"id":9474}, + {"name":"Rock Pile","type":"NPC","wcid":42976,"cell":"B370002B","place":"outdoor","ns":-12.07,"ew":41.8,"id":9475}, + {"name":"Rock Pile","type":"NPC","wcid":42976,"cell":"B370002B","place":"outdoor","ns":-12.1,"ew":41.82,"id":9476}, + {"name":"Rock Pile","type":"NPC","wcid":42976,"cell":"B3700022","place":"outdoor","ns":-12.19,"ew":41.71,"id":9477}, + {"name":"Rock Pile","type":"NPC","wcid":42976,"cell":"B370002B","place":"outdoor","ns":-12.06,"ew":41.83,"id":9478}, + {"name":"Rock Pile","type":"NPC","wcid":42972,"cell":"B370002B","place":"outdoor","ns":-12.09,"ew":41.75,"id":9479}, + {"name":"Rock Pile","type":"NPC","wcid":42970,"cell":"B3700023","place":"outdoor","ns":-12.1,"ew":41.73,"id":9480}, + {"name":"Rock Pile","type":"NPC","wcid":42976,"cell":"B370002C","place":"outdoor","ns":-11.96,"ew":41.81,"id":9481}, + {"name":"Rock Pile","type":"NPC","wcid":42976,"cell":"B3700023","place":"outdoor","ns":-12.09,"ew":41.67,"id":9482}, + {"name":"Rock Pile","type":"NPC","wcid":42976,"cell":"B3700023","place":"outdoor","ns":-12.11,"ew":41.69,"id":9483}, + {"name":"Rock Pile","type":"NPC","wcid":42967,"cell":"B370002C","place":"outdoor","ns":-12.0,"ew":41.78,"id":9484}, + {"name":"Rock Pile","type":"NPC","wcid":42975,"cell":"B370002C","place":"outdoor","ns":-12.0,"ew":41.82,"id":9485}, + {"name":"Rock Pile","type":"NPC","wcid":42976,"cell":"B3700024","place":"outdoor","ns":-12.05,"ew":41.75,"id":9486}, + {"name":"Rock Pile","type":"NPC","wcid":42976,"cell":"B3700024","place":"outdoor","ns":-12.0,"ew":41.67,"id":9487}, + {"name":"Rock Pile","type":"NPC","wcid":42963,"cell":"B3700024","place":"outdoor","ns":-11.97,"ew":41.68,"id":9488}, + {"name":"Rock Pile","type":"NPC","wcid":42968,"cell":"B3700024","place":"outdoor","ns":-12.04,"ew":41.68,"id":9489}, + {"name":"Rock Pile","type":"NPC","wcid":42973,"cell":"B370002D","place":"outdoor","ns":-11.94,"ew":41.76,"id":9490}, + {"name":"Rock Pile","type":"NPC","wcid":42964,"cell":"B3700025","place":"outdoor","ns":-11.89,"ew":41.74,"id":9491}, + {"name":"Game Coordinator","type":"NPC","wcid":42977,"cell":"B3700022","place":"outdoor","ns":-12.24,"ew":41.73,"id":9492,"desc":"Coordinator."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B3810000","place":"outdoor","ns":1.93,"ew":41.72,"id":9493}, + {"name":"Larry the Rabbit Master","type":"NPC","wcid":9527,"cell":"B3810109","place":"building","ns":1.9,"ew":41.59,"id":9494,"desc":"Farmer."}, + {"name":"Exploration Marker","type":"NPC","wcid":39815,"cell":"B3AA001E","place":"outdoor","ns":34.6,"ew":41.6,"id":9495}, + {"name":"Ruined Watcher","type":"NPC","wcid":31968,"cell":"B3EC001D","place":"outdoor","ns":87.31,"ew":41.64,"id":9496}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":53267,"cell":"B4490037","place":"outdoor","ns":-42.86,"ew":42.73,"id":9497}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":53265,"cell":"B4490030","place":"outdoor","ns":-42.8,"ew":42.58,"id":9498}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":53264,"cell":"B4490037","place":"outdoor","ns":-42.92,"ew":42.72,"id":9499}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":53269,"cell":"B4490028","place":"outdoor","ns":-42.84,"ew":42.53,"id":9500}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":53268,"cell":"B4490027","place":"outdoor","ns":-42.88,"ew":42.49,"id":9501}, + {"name":"Ancient Statue of the Viridian Root","type":"NPC","wcid":53263,"cell":"B4490037","place":"outdoor","ns":-42.94,"ew":42.66,"id":9502}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53049,"cell":"B44B0004","place":"outdoor","ns":-41.63,"ew":42.08,"id":9503}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53053,"cell":"B44B0013","place":"outdoor","ns":-41.74,"ew":42.28,"id":9504}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53055,"cell":"B44B001D","place":"outdoor","ns":-41.51,"ew":42.43,"id":9505}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53051,"cell":"B44B0017","place":"outdoor","ns":-41.29,"ew":42.28,"id":9506}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53057,"cell":"B44B0038","place":"outdoor","ns":-41.17,"ew":42.75,"id":9507}, + {"name":"Farmer","type":"Vendor","wcid":1383,"cell":"B46F0101","place":"building","ns":-12.82,"ew":42.59,"id":9508}, + {"name":"Bier of Antius Blackmoor","type":"NPC","wcid":32290,"cell":"B46F0107","place":"building","ns":-12.4,"ew":42.36,"id":9509}, + {"name":"Bromord Morresten","type":"NPC","wcid":32561,"cell":"B46F0018","place":"outdoor","ns":-12.43,"ew":42.3,"id":9510,"desc":"Honor Guard."}, + {"name":"Antius Blackmoor Memorial","type":"NPC","wcid":32397,"cell":"B46F0018","place":"outdoor","ns":-12.4,"ew":42.3,"id":9511}, + {"name":"Shin Ou-Ye the Shopkeep","type":"Vendor","wcid":820,"cell":"B4700127","place":"building","ns":-12.18,"ew":42.3,"id":9512,"desc":"Shopkeeper."}, + {"name":"Grocer Nan-Yu-Yenbuto","type":"Vendor","wcid":815,"cell":"B4700123","place":"building","ns":-12.23,"ew":42.31,"id":9513,"desc":"Grocer."}, + {"name":"Wah Fo-Za the Armorer","type":"Vendor","wcid":812,"cell":"B4700176","place":"building","ns":-12.08,"ew":42.33,"id":9514,"desc":"Blacksmith."}, + {"name":"Nu Sha the Weaponsmith","type":"Vendor","wcid":813,"cell":"B4700176","place":"building","ns":-12.12,"ew":42.33,"id":9515,"desc":"Apprentice Smith."}, + {"name":"Zan Wa-Shabu the Tailor","type":"Vendor","wcid":821,"cell":"B4700130","place":"building","ns":-12.17,"ew":42.61,"id":9516,"desc":"Tailor."}, + {"name":"Healer Kai Tonweh","type":"Vendor","wcid":816,"cell":"B4700103","place":"building","ns":-11.91,"ew":42.41,"id":9517,"desc":"Healer."}, + {"name":"Master Sonji Pan, Archmage","type":"Vendor","wcid":809,"cell":"B470010A","place":"building","ns":-11.91,"ew":42.42,"id":9518,"desc":"Archmage."}, + {"name":"Kai Go-Sou the Scribe","type":"Vendor","wcid":819,"cell":"B470010A","place":"building","ns":-11.91,"ew":42.38,"id":9519,"desc":"Scribe."}, + {"name":"Barkeep Bai Yao Feng","type":"Vendor","wcid":810,"cell":"B4700151","place":"building","ns":-12.0,"ew":42.59,"id":9520,"desc":"Barkeeper."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":20225,"cell":"B470016B","place":"building","ns":-11.79,"ew":42.58,"id":9521,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":20213,"cell":"B470016B","place":"building","ns":-11.8,"ew":42.58,"id":9522,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":20209,"cell":"B470016A","place":"building","ns":-11.81,"ew":42.62,"id":9523,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":20221,"cell":"B470016A","place":"building","ns":-11.8,"ew":42.62,"id":9524,"desc":"Master Archmage."}, + {"name":"Ribusha Sennei the Bowyer","type":"Vendor","wcid":814,"cell":"B470002B","place":"outdoor","ns":-12.09,"ew":42.56,"id":9525,"desc":"Bowyer."}, + {"name":"Jeweler Ryuhan Wu","type":"Vendor","wcid":817,"cell":"B470012F","place":"building","ns":-12.23,"ew":42.59,"id":9526,"desc":"Jeweler."}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"B470002D","place":"outdoor","ns":-11.9,"ew":42.6,"id":9527}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B470001B","place":"outdoor","ns":-12.1,"ew":42.4,"id":9528}, + {"name":"Wedding Planner","type":"Vendor","wcid":21340,"cell":"B470014F","place":"building","ns":-11.98,"ew":42.62,"id":9529,"desc":"Planner of Weddings."}, + {"name":"Ookami Kiri","type":"NPC","wcid":34365,"cell":"B4700154","place":"building","ns":-11.99,"ew":42.62,"id":9530,"desc":"Apprentice of the Blade."}, + {"name":"Collector","type":"NPC","wcid":21338,"cell":"B4700154","place":"building","ns":-12.01,"ew":42.62,"id":9531,"desc":"Trophy Collector."}, + {"name":"Royal Guard Adrana","type":"NPC","wcid":32510,"cell":"B4700019","place":"outdoor","ns":-12.27,"ew":42.39,"id":9532,"desc":"Guard."}, + {"name":"Dai Ya the Scholar","type":"NPC","wcid":5063,"cell":"B470014F","place":"building","ns":-12.03,"ew":42.58,"id":9533,"desc":"Society Agent."}, + {"name":"Ydnew","type":"NPC","wcid":28094,"cell":"B470014F","place":"building","ns":-11.97,"ew":42.57,"id":9534,"desc":"High Queen's Emissary."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"B470014F","place":"building","ns":-11.97,"ew":42.6,"id":9535,"desc":"Mage."}, + {"name":"Bleeargh, Mosswart Swamp Lord","type":"NPC","wcid":27899,"cell":"B470002B","place":"outdoor","ns":-12.06,"ew":42.62,"id":9536}, + {"name":"Apprentice Fletcher","type":"NPC","wcid":27748,"cell":"B470002B","place":"outdoor","ns":-12.07,"ew":42.58,"id":9537}, + {"name":"El'Yst Maggann","type":"NPC","wcid":49584,"cell":"B470002C","place":"outdoor","ns":-12.03,"ew":42.55,"id":9538,"desc":"Seeker of Ancient Knowledge."}, + {"name":"Virindi Delegate","type":"NPC","wcid":51297,"cell":"B470000F","place":"outdoor","ns":-11.73,"ew":42.24,"id":9539}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53114,"cell":"B5490005","place":"outdoor","ns":-43.07,"ew":42.9,"id":9540}, + {"name":"Brellegia","type":"NPC","wcid":53280,"cell":"B54A000C","place":"outdoor","ns":-42.37,"ew":42.98,"id":9541,"desc":"Spirit Speaker."}, + {"name":"Doriathazaar's Horde","type":"NPC","wcid":53275,"cell":"B54A0014","place":"outdoor","ns":-42.42,"ew":43.07,"id":9542}, + {"name":"Doriathazaar's Horde","type":"NPC","wcid":53275,"cell":"B54A0014","place":"outdoor","ns":-42.43,"ew":43.08,"id":9543}, + {"name":"Doriathazaar's Horde","type":"NPC","wcid":53275,"cell":"B54A0014","place":"outdoor","ns":-42.41,"ew":43.08,"id":9544}, + {"name":"Doriathazaar's Horde","type":"NPC","wcid":53274,"cell":"B54A0014","place":"outdoor","ns":-42.41,"ew":43.06,"id":9545}, + {"name":"Doriathazaar's Horde","type":"NPC","wcid":53273,"cell":"B54A0014","place":"outdoor","ns":-42.44,"ew":43.07,"id":9546}, + {"name":"Doriathazaar's Horde","type":"NPC","wcid":53273,"cell":"B54A0014","place":"outdoor","ns":-42.4,"ew":43.07,"id":9547}, + {"name":"Doriathazaar's Horde","type":"NPC","wcid":53276,"cell":"B54A0014","place":"outdoor","ns":-42.4,"ew":43.08,"id":9548}, + {"name":"Doriathazaar","type":"NPC","wcid":53272,"cell":"B54A0014","place":"outdoor","ns":-42.42,"ew":43.08,"id":9549,"desc":"Watcher of the Viridian Aerie."}, + {"name":"Summercrown","type":"NPC","wcid":53451,"cell":"B54A001D","place":"outdoor","ns":-42.29,"ew":43.22,"id":9550,"desc":"Master of the Amber Forge."}, + {"name":"Aangesilus","type":"NPC","wcid":53281,"cell":"B54A0024","place":"outdoor","ns":-42.38,"ew":43.25,"id":9551,"desc":"Viridian Stalker."}, + {"name":"Dridge","type":"NPC","wcid":53306,"cell":"B54A0025","place":"outdoor","ns":-42.34,"ew":43.32,"id":9552,"desc":"Mead Brewer."}, + {"name":"Kervim'telek","type":"NPC","wcid":53271,"cell":"B54A002C","place":"outdoor","ns":-42.38,"ew":43.45,"id":9553,"desc":"Guardian of the Viridian Rise."}, + {"name":"Swift","type":"NPC","wcid":53283,"cell":"B54A0035","place":"outdoor","ns":-42.34,"ew":43.47,"id":9554,"desc":"Viridian Ranger."}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53100,"cell":"B54B001D","place":"outdoor","ns":-41.54,"ew":43.15,"id":9555}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53076,"cell":"B54B0007","place":"outdoor","ns":-41.32,"ew":42.86,"id":9556}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53101,"cell":"B54B003C","place":"outdoor","ns":-41.55,"ew":43.63,"id":9557}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53102,"cell":"B54B0040","place":"outdoor","ns":-41.18,"ew":43.57,"id":9558}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53099,"cell":"B54B0020","place":"outdoor","ns":-41.17,"ew":43.23,"id":9559}, + {"name":"Wandering Bowyer","type":"Vendor","wcid":1380,"cell":"B56E0101","place":"building","ns":-13.21,"ew":43.4,"id":9560,"desc":"Bowyer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B58A0000","place":"outdoor","ns":8.97,"ew":43.41,"id":9561}, + {"name":"Merchant","type":"Vendor","wcid":1389,"cell":"B58A0000","place":"outdoor","ns":8.89,"ew":43.41,"id":9562}, + {"name":"Exploration Marker","type":"NPC","wcid":39763,"cell":"B5A20040","place":"outdoor","ns":28.4,"ew":43.65,"id":9563}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A30000","place":"outdoor","ns":28.96,"ew":43.53,"id":9564}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A30000","place":"outdoor","ns":28.8,"ew":43.53,"id":9565}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A30000","place":"outdoor","ns":29.2,"ew":43.53,"id":9566}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A30000","place":"outdoor","ns":29.14,"ew":43.56,"id":9567}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A30000","place":"outdoor","ns":29.09,"ew":43.56,"id":9568}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A30000","place":"outdoor","ns":29.06,"ew":43.5,"id":9569}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A30000","place":"outdoor","ns":29.01,"ew":43.52,"id":9570}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A30000","place":"outdoor","ns":28.98,"ew":43.59,"id":9571}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A40000","place":"outdoor","ns":29.31,"ew":43.5,"id":9572}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A40000","place":"outdoor","ns":29.36,"ew":43.62,"id":9573}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A40000","place":"outdoor","ns":29.34,"ew":43.6,"id":9574}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A40000","place":"outdoor","ns":29.3,"ew":43.57,"id":9575}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A40000","place":"outdoor","ns":29.33,"ew":43.53,"id":9576}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B5A40000","place":"outdoor","ns":29.25,"ew":43.52,"id":9577}, + {"name":"Jolly Snowman","type":"Vendor","wcid":7883,"cell":"B62D0102","place":"dungeon","id":9578,"desc":"Purveyor of Ice. In a dungeon (landblock B62D)."}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53108,"cell":"B6490031","place":"outdoor","ns":-43.53,"ew":44.32,"id":9579}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53109,"cell":"B6490019","place":"outdoor","ns":-43.53,"ew":44.03,"id":9580}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53107,"cell":"B649003E","place":"outdoor","ns":-42.97,"ew":44.43,"id":9581}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53080,"cell":"B649001D","place":"outdoor","ns":-43.14,"ew":43.97,"id":9582}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53110,"cell":"B6490004","place":"outdoor","ns":-43.17,"ew":43.67,"id":9583}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53105,"cell":"B64A0011","place":"outdoor","ns":-42.74,"ew":43.88,"id":9584}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53078,"cell":"B64A0040","place":"outdoor","ns":-41.98,"ew":44.42,"id":9585}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53106,"cell":"B64A002D","place":"outdoor","ns":-42.34,"ew":44.24,"id":9586}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53104,"cell":"B64A0039","place":"outdoor","ns":-42.74,"ew":44.37,"id":9587}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53103,"cell":"B64A0033","place":"outdoor","ns":-42.53,"ew":44.27,"id":9588}, + {"name":"Ancient Statue of the Viridian Rise","type":"NPC","wcid":53112,"cell":"B64B0030","place":"outdoor","ns":-41.23,"ew":44.18,"id":9589}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B6520000","place":"outdoor","ns":-36.08,"ew":44.3,"id":9590}, + {"name":"Farmer Ri Na","type":"Vendor","wcid":5640,"cell":"B6650106","place":"building","ns":-20.58,"ew":44.19,"id":9591,"desc":"Farmer."}, + {"name":"Ru Shaha the Healer","type":"Vendor","wcid":5638,"cell":"B665010F","place":"building","ns":-20.49,"ew":44.28,"id":9592,"desc":"Healer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B6650000","place":"outdoor","ns":-20.6,"ew":44.3,"id":9593}, + {"name":"Archmage Le-Ai Ren","type":"Vendor","wcid":5639,"cell":"B6650116","place":"building","ns":-20.53,"ew":44.29,"id":9594,"desc":"Archmage."}, + {"name":"Weaponsmith Lun Dou","type":"Vendor","wcid":5641,"cell":"B6650100","place":"building","ns":-20.62,"ew":44.2,"id":9595,"desc":"Weaponsmith."}, + {"name":"Frest Greelving","type":"NPC","wcid":22088,"cell":"B6860000","place":"outdoor","ns":6.03,"ew":43.73,"id":9596,"desc":"Arcanum Functionary."}, + {"name":"Apparition","type":"NPC","wcid":22113,"cell":"B6870167","place":"building","ns":6.54,"ew":43.9,"id":9597}, + {"name":"Peddler","type":"Vendor","wcid":1391,"cell":"B69B0000","place":"outdoor","ns":22.48,"ew":43.92,"id":9598}, + {"name":"Archmage","type":"Vendor","wcid":1370,"cell":"B69B0000","place":"outdoor","ns":22.53,"ew":43.96,"id":9599}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B69C0000","place":"outdoor","ns":23.2,"ew":44.02,"id":9600}, + {"name":"Tackle Master","type":"NPC","wcid":23336,"cell":"B6A30100","place":"building","ns":29.02,"ew":43.86,"id":9601,"desc":"Pro Fisherman."}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":29.04,"ew":44.1,"id":9602}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":28.93,"ew":43.98,"id":9603}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":28.76,"ew":43.87,"id":9604}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":28.62,"ew":43.88,"id":9605}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":28.64,"ew":43.83,"id":9606}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":28.68,"ew":43.88,"id":9607}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":28.8,"ew":43.86,"id":9608}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":28.84,"ew":43.94,"id":9609}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":28.88,"ew":43.88,"id":9610}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":28.91,"ew":43.94,"id":9611}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":28.99,"ew":43.98,"id":9612}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":29.01,"ew":44.04,"id":9613}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":29.08,"ew":44.04,"id":9614}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":29.05,"ew":44.16,"id":9615}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A30000","place":"outdoor","ns":28.95,"ew":44.15,"id":9616}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A40000","place":"outdoor","ns":29.32,"ew":43.92,"id":9617}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A40000","place":"outdoor","ns":29.4,"ew":43.69,"id":9618}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A40000","place":"outdoor","ns":29.31,"ew":43.96,"id":9619}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A40000","place":"outdoor","ns":29.32,"ew":44.02,"id":9620}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A40000","place":"outdoor","ns":29.38,"ew":43.96,"id":9621}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A40000","place":"outdoor","ns":29.36,"ew":43.86,"id":9622}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A40000","place":"outdoor","ns":29.35,"ew":43.75,"id":9623}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"B6A40000","place":"outdoor","ns":29.34,"ew":43.68,"id":9624}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B6B20101","place":"dungeon","id":9625,"desc":"In a dungeon (landblock B6B2)."}, + {"name":"Aerlinthe Gatestone","type":"NPC","wcid":39293,"cell":"B6E80100","place":"building","ns":84.1,"ew":44.11,"id":9626}, + {"name":"Aerlinthe Node Golem","type":"NPC","wcid":38215,"cell":"B6E80025","place":"outdoor","ns":84.06,"ew":44.11,"id":9627,"desc":"Node Guardian."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B76F0000","place":"outdoor","ns":-12.81,"ew":45.08,"id":9628}, + {"name":"Xavier, Royal Guard","type":"NPC","wcid":25682,"cell":"B7800000","place":"outdoor","ns":0.69,"ew":44.7,"id":9629,"desc":"Senior Guard."}, + {"name":"Exploration Marker","type":"NPC","wcid":39835,"cell":"B7800013","place":"outdoor","ns":0.74,"ew":44.69,"id":9630}, + {"name":"Slithe Tradittor","type":"NPC","wcid":20204,"cell":"B7840102","place":"building","ns":3.9,"ew":44.8,"id":9631,"desc":"Explorer."}, + {"name":"Jhen Gau the Souvenir Hawker","type":"Vendor","wcid":7427,"cell":"B7E80101","place":"dungeon","id":9632,"desc":"Souvenir Hawker. In a dungeon (landblock B7E8)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B817003E","place":"outdoor","ns":-82.96,"ew":45.96,"id":9633}, + {"name":"Koga Hideki","type":"Vendor","wcid":51155,"cell":"B817003F","place":"outdoor","ns":-82.86,"ew":45.99,"id":9634,"desc":"Master Armorer."}, + {"name":"Beldin the Gem Dealer","type":"Vendor","wcid":33249,"cell":"B86F003C","place":"outdoor","ns":-12.79,"ew":46.0,"id":9635,"desc":"Arcanum Vendor."}, + {"name":"Withered Banderling","type":"NPC","wcid":35629,"cell":"B89F012D","place":"building","ns":25.3,"ew":46.0,"id":9636}, + {"name":"Withered Banderling","type":"NPC","wcid":35629,"cell":"B89F012D","place":"building","ns":25.31,"ew":45.99,"id":9637}, + {"name":"Hoogan","type":"NPC","wcid":35572,"cell":"B89F012D","place":"building","ns":25.29,"ew":45.99,"id":9638,"desc":"Drudge Prisoner."}, + {"name":"Sergeant Shanks","type":"NPC","wcid":35573,"cell":"B89F0039","place":"outdoor","ns":25.31,"ew":46.01,"id":9639,"desc":"Guard."}, + {"name":"Giant Snowman","type":"Vendor","wcid":5767,"cell":"B8CC0000","place":"outdoor","ns":61.51,"ew":45.7,"id":9640}, + {"name":"Exploration Marker","type":"NPC","wcid":39829,"cell":"B8E80028","place":"outdoor","ns":84.41,"ew":45.69,"id":9641}, + {"name":"Southern Resonating Crystal","type":"NPC","wcid":37094,"cell":"B93D0035","place":"outdoor","ns":-52.7,"ew":46.7,"id":9642}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B96B0000","place":"outdoor","ns":-15.63,"ew":46.51,"id":9643}, + {"name":"Ru Chi the Shopkeeper","type":"Vendor","wcid":4566,"cell":"B96B0104","place":"building","ns":-15.61,"ew":46.42,"id":9644,"desc":"Shopkeeper."}, + {"name":"Te Ven","type":"NPC","wcid":5065,"cell":"B96B0106","place":"building","ns":-15.57,"ew":46.39,"id":9645,"desc":"Citizen of Yanshi."}, + {"name":"Emissary of Asheron","type":"NPC","wcid":21136,"cell":"B96F0000","place":"outdoor","ns":-12.69,"ew":46.45,"id":9646,"desc":"Emissary."}, + {"name":"Vincadi","type":"NPC","wcid":24859,"cell":"B96F0000","place":"outdoor","ns":-12.59,"ew":46.67,"id":9647,"desc":"Inquisitive Creationist."}, + {"name":"Issk","type":"NPC","wcid":24858,"cell":"B96F0000","place":"outdoor","ns":-12.92,"ew":46.5,"id":9648,"desc":"Chomu Priest."}, + {"name":"Tunnels to the Harbinger","type":"NPC","wcid":33238,"cell":"B96F0000","place":"outdoor","ns":-12.92,"ew":46.46,"id":9649}, + {"name":"Tunnels to the Harbinger","type":"NPC","wcid":33239,"cell":"B96F0000","place":"outdoor","ns":-12.62,"ew":46.67,"id":9650}, + {"name":"Stone of Yanshi","type":"NPC","wcid":32966,"cell":"B96F001D","place":"outdoor","ns":-12.7,"ew":46.4,"id":9651}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B9720000","place":"outdoor","ns":-10.36,"ew":46.66,"id":9652}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"B9730000","place":"outdoor","ns":-9.88,"ew":46.68,"id":9653}, + {"name":"Dou In the Shopkeeper","type":"Vendor","wcid":4565,"cell":"B9730106","place":"building","ns":-9.88,"ew":46.59,"id":9654,"desc":"Shopkeeper."}, + {"name":"Lou Ei","type":"NPC","wcid":5064,"cell":"B9730100","place":"building","ns":-9.92,"ew":46.59,"id":9655,"desc":"Citizen of Yanshi."}, + {"name":"Exploration Marker","type":"NPC","wcid":39764,"cell":"B980002A","place":"outdoor","ns":0.63,"ew":46.61,"id":9656}, + {"name":"Roaming Bowyer","type":"Vendor","wcid":1378,"cell":"B99C0105","place":"building","ns":23.49,"ew":46.2,"id":9657,"desc":"Bowyer."}, + {"name":"Farmer Pogget","type":"Vendor","wcid":2042,"cell":"B99C0109","place":"building","ns":23.38,"ew":46.13,"id":9658,"desc":"Farmer."}, + {"name":"Exploration Marker","type":"NPC","wcid":39790,"cell":"B9EF001F","place":"outdoor","ns":89.91,"ew":46.42,"id":9659}, + {"name":"Archmage Kiko of Kara","type":"Vendor","wcid":2537,"cell":"BA17010C","place":"building","ns":-83.22,"ew":47.0,"id":9660,"desc":"Archmage."}, + {"name":"Koro of Kara, Farmer","type":"Vendor","wcid":2539,"cell":"BA170000","place":"outdoor","ns":-83.33,"ew":47.23,"id":9661,"desc":"Farmer."}, + {"name":"Healer Kana of Kara","type":"Vendor","wcid":2538,"cell":"BA170127","place":"building","ns":-83.38,"ew":47.07,"id":9662,"desc":"Healer."}, + {"name":"Shopkeep Kuro of Kara","type":"Vendor","wcid":2536,"cell":"BA170127","place":"building","ns":-83.39,"ew":47.07,"id":9663,"desc":"Shopkeeper."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"BA17013C","place":"building","ns":-82.81,"ew":47.01,"id":9664,"desc":"Mage."}, + {"name":"Grand Master Scrivener of War Magic","type":"Vendor","wcid":20224,"cell":"BA17010C","place":"building","ns":-83.2,"ew":46.98,"id":9665,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Creature Magic","type":"Vendor","wcid":20208,"cell":"BA17010F","place":"building","ns":-83.22,"ew":46.98,"id":9666,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Life Magic","type":"Vendor","wcid":20220,"cell":"BA17010F","place":"building","ns":-83.22,"ew":47.02,"id":9667,"desc":"Master Archmage."}, + {"name":"Grand Master Scrivener of Item Magic","type":"Vendor","wcid":20212,"cell":"BA17010F","place":"building","ns":-83.18,"ew":47.02,"id":9668,"desc":"Master Archmage."}, + {"name":"Miko Li, Jojii Adherent","type":"NPC","wcid":25827,"cell":"BA170131","place":"building","ns":-83.37,"ew":47.18,"id":9669,"desc":"Monk."}, + {"name":"Kuhira of Kara","type":"Vendor","wcid":27246,"cell":"BA170126","place":"building","ns":-83.42,"ew":47.13,"id":9670,"desc":"Armorer."}, + {"name":"Tatuso of Kara","type":"Vendor","wcid":27247,"cell":"BA170106","place":"building","ns":-82.79,"ew":47.22,"id":9671,"desc":"Bowyer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"BA170000","place":"outdoor","ns":-83.33,"ew":46.99,"id":9672}, + {"name":"Journeyman Alchemist","type":"NPC","wcid":28919,"cell":"BA170131","place":"building","ns":-83.38,"ew":47.23,"id":9673,"desc":"Apprentice Alchemist."}, + {"name":"Esmond Fielding","type":"NPC","wcid":43030,"cell":"BA17011C","place":"building","ns":-83.2,"ew":47.22,"id":9674,"desc":"Explorer Society Outreach Officer."}, + {"name":"Ansar El-Kerdany","type":"NPC","wcid":43028,"cell":"BA17011C","place":"building","ns":-83.19,"ew":47.21,"id":9675,"desc":"Explorer Society Outreach Officer."}, + {"name":"Niccolo De Luca","type":"NPC","wcid":43029,"cell":"BA17011C","place":"building","ns":-83.21,"ew":47.21,"id":9676,"desc":"Explorer Society Outreach Officer."}, + {"name":"Grularr Wa'ydo","type":"NPC","wcid":48777,"cell":"BA170136","place":"building","ns":-83.42,"ew":47.19,"id":9677,"desc":"Artifact Collector."}, + {"name":"Farmer","type":"Vendor","wcid":1383,"cell":"BA700000","place":"outdoor","ns":-11.77,"ew":47.52,"id":9678}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"BA9E0108","place":"building","ns":24.59,"ew":47.07,"id":9679,"desc":"Mage."}, + {"name":"Bartholomew Steiner","type":"NPC","wcid":12238,"cell":"BA9E0108","place":"building","ns":24.59,"ew":47.09,"id":9680,"desc":"Master Furniture Maker."}, + {"name":"Steiner's Apprentice Craftsman","type":"Vendor","wcid":12241,"cell":"BA9E0108","place":"building","ns":24.58,"ew":47.08,"id":9681,"desc":"Apprentice Craftsman."}, + {"name":"Minthada the Librarian","type":"Vendor","wcid":2041,"cell":"BA9F0100","place":"building","ns":26.0,"ew":46.99,"id":9682,"desc":"Librarian."}, + {"name":"Bretself the Translator","type":"NPC","wcid":5693,"cell":"BA9F0104","place":"building","ns":26.0,"ew":47.03,"id":9683,"desc":"Translator."}, + {"name":"Arcanum Researcher","type":"NPC","wcid":16892,"cell":"BA9F0100","place":"building","ns":26.02,"ew":47.01,"id":9684}, + {"name":"Edobar the Esoteric","type":"NPC","wcid":31429,"cell":"BA9F0100","place":"building","ns":26.02,"ew":46.98,"id":9685,"desc":"Royal Scholar."}, + {"name":"Popkin of the Gate","type":"NPC","wcid":46356,"cell":"BAA00101","place":"dungeon","id":9686,"desc":"Researcher. In a dungeon (landblock BAA0)."}, + {"name":"Lady Mashal Trianna","type":"NPC","wcid":46296,"cell":"BAA00101","place":"dungeon","id":9687,"desc":"Researcher. In a dungeon (landblock BAA0)."}, + {"name":"Lady Kiara Trianna","type":"NPC","wcid":46297,"cell":"BAA00101","place":"dungeon","id":9688,"desc":"Researcher. In a dungeon (landblock BAA0)."}, + {"name":"Lady Sherath Trianna","type":"NPC","wcid":46295,"cell":"BAA00101","place":"dungeon","id":9689,"desc":"Researcher. In a dungeon (landblock BAA0)."}, + {"name":"Lady Dan'eel Trianna","type":"NPC","wcid":46294,"cell":"BAA00101","place":"dungeon","id":9690,"desc":"Researcher. In a dungeon (landblock BAA0)."}, + {"name":"Blue Coral Reef","type":"NPC","wcid":31329,"cell":"BADD0008","place":"outdoor","ns":75.6,"ew":46.91,"id":9691}, + {"name":"Odd Looking Vine","type":"NPC","wcid":26587,"cell":"BB64010D","place":"building","ns":-21.59,"ew":47.66,"id":9692}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"BB660000","place":"outdoor","ns":-19.82,"ew":47.94,"id":9693}, + {"name":"Tromylda the Shopkeeper","type":"Vendor","wcid":4447,"cell":"BB800109","place":"building","ns":0.99,"ew":48.38,"id":9694,"desc":"Shopkeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"BB800000","place":"outdoor","ns":1.08,"ew":48.36,"id":9695}, + {"name":"Beltslora","type":"NPC","wcid":5047,"cell":"BB80010B","place":"building","ns":0.99,"ew":48.4,"id":9696,"desc":"Citizen of Lytelthorpe."}, + {"name":"Healer","type":"Vendor","wcid":1386,"cell":"BB920100","place":"building","ns":15.19,"ew":47.69,"id":9697}, + {"name":"Farmer","type":"Vendor","wcid":1381,"cell":"BB920000","place":"outdoor","ns":15.27,"ew":47.71,"id":9698}, + {"name":"Exploration Marker","type":"NPC","wcid":39813,"cell":"BB9B001D","place":"outdoor","ns":22.54,"ew":48.05,"id":9699}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"BB9D0000","place":"outdoor","ns":24.44,"ew":48.3,"id":9700}, + {"name":"Emissary of Asheron","type":"NPC","wcid":43249,"cell":"BB9D0038","place":"outdoor","ns":24.42,"ew":48.31,"id":9701,"desc":"Emissary."}, + {"name":"Guardian Golem","type":"NPC","wcid":43247,"cell":"BB9D0038","place":"outdoor","ns":24.41,"ew":48.31,"id":9702}, + {"name":"Guardian Golem","type":"NPC","wcid":43247,"cell":"BB9D0038","place":"outdoor","ns":24.42,"ew":48.3,"id":9703}, + {"name":"Lenor Turk","type":"NPC","wcid":30278,"cell":"BB9F0105","place":"building","ns":25.51,"ew":48.42,"id":9704,"desc":"Augmentation Trainer."}, + {"name":"Robert Crow","type":"NPC","wcid":30269,"cell":"BB9F0106","place":"building","ns":25.48,"ew":48.39,"id":9705,"desc":"Augmentation Trainer."}, + {"name":"Burrell Sammrun","type":"NPC","wcid":30277,"cell":"BB9F0106","place":"building","ns":25.52,"ew":48.39,"id":9706,"desc":"Augmentation Trainer."}, + {"name":"Kris Cennis","type":"NPC","wcid":28687,"cell":"BB9F010A","place":"building","ns":25.48,"ew":48.38,"id":9707,"desc":"Augmentation Trainer."}, + {"name":"Joshun Felden","type":"NPC","wcid":30276,"cell":"BB9F010D","place":"building","ns":25.52,"ew":48.41,"id":9708,"desc":"Augmentation Trainer."}, + {"name":"Brienne Carlus","type":"NPC","wcid":28684,"cell":"BB9F003B","place":"outdoor","ns":25.48,"ew":48.42,"id":9709,"desc":"Augmentation Trainer."}, + {"name":"Arcanum Broker","type":"Vendor","wcid":38460,"cell":"BB9F0035","place":"outdoor","ns":25.71,"ew":48.32,"id":9710,"desc":"Mana Forge Vendor."}, + {"name":"Garbage Barrel","type":"NPC","wcid":34726,"cell":"BB9F0114","place":"building","ns":25.72,"ew":48.21,"id":9711}, + {"name":"Garbage Barrel","type":"NPC","wcid":34726,"cell":"BB9F0117","place":"building","ns":25.71,"ew":48.31,"id":9712}, + {"name":"Arcanum Mana-smith","type":"NPC","wcid":38461,"cell":"BB9F0035","place":"outdoor","ns":25.69,"ew":48.32,"id":9713,"desc":"Pristine Mana Shard Collector."}, + {"name":"Component Exchanger","type":"NPC","wcid":40770,"cell":"BB9F0117","place":"building","ns":25.69,"ew":48.31,"id":9714,"desc":"Gamesmaster."}, + {"name":"Garbage Barrel","type":"NPC","wcid":34726,"cell":"BB9F0114","place":"building","ns":25.68,"ew":48.21,"id":9715}, + {"name":"Asheron's Platinum Golem","type":"NPC","wcid":21489,"cell":"BBC70000","place":"outdoor","ns":57.75,"ew":48.4,"id":9716}, + {"name":"Ornate Pillar","type":"NPC","wcid":21493,"cell":"BBC70000","place":"outdoor","ns":57.62,"ew":47.97,"id":9717}, + {"name":"Ornate Pillar","type":"NPC","wcid":21493,"cell":"BBC70000","place":"outdoor","ns":57.62,"ew":47.82,"id":9718}, + {"name":"Ornate Pillar","type":"NPC","wcid":21493,"cell":"BBC70000","place":"outdoor","ns":57.77,"ew":47.83,"id":9719}, + {"name":"Ornate Pillar","type":"NPC","wcid":21493,"cell":"BBC70000","place":"outdoor","ns":57.77,"ew":47.97,"id":9720}, + {"name":"Eaushi the Trainer","type":"NPC","wcid":9056,"cell":"BC110000","place":"outdoor","ns":-88.02,"ew":48.74,"id":9721}, + {"name":"Exploration Marker","type":"NPC","wcid":39766,"cell":"BC17003E","place":"outdoor","ns":-82.99,"ew":49.19,"id":9722}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"BC1D0000","place":"outdoor","ns":-78.73,"ew":48.64,"id":9723}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"BC340000","place":"outdoor","ns":-59.77,"ew":48.5,"id":9724}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"BC34010B","place":"building","ns":-59.68,"ew":48.53,"id":9725}, + {"name":"Ka'hiri","type":"NPC","wcid":43404,"cell":"BC5D0100","place":"dungeon","id":9726,"desc":"Seer of the Dark Falatacot. In a dungeon (landblock BC5D)."}, + {"name":"Chosen of Asheron","type":"NPC","wcid":8765,"cell":"BC9C0000","place":"outdoor","ns":23.56,"ew":49.09,"id":9727,"desc":"Emissary."}, + {"name":"Emily Yarow","type":"NPC","wcid":41518,"cell":"BC9E0100","place":"dungeon","id":9728,"desc":"Augmentation Trainer. In a dungeon (landblock BC9E)."}, + {"name":"Gustuv Lansdown","type":"NPC","wcid":41519,"cell":"BC9E0100","place":"dungeon","id":9729,"desc":"Augmentation Trainer. In a dungeon (landblock BC9E)."}, + {"name":"Avalenne Hilmad the Healer","type":"Vendor","wcid":673,"cell":"BC9F0103","place":"building","ns":25.68,"ew":48.52,"id":9730,"desc":"Healer."}, + {"name":"Acina Hilmad the Grocer","type":"Vendor","wcid":672,"cell":"BC9F0103","place":"building","ns":25.7,"ew":48.5,"id":9731,"desc":"Grocer."}, + {"name":"Estorl the Ox, Weaponsmith","type":"Vendor","wcid":677,"cell":"BC9F014F","place":"building","ns":25.77,"ew":49.2,"id":9732,"desc":"Weaponsmith."}, + {"name":"Culthea Ironshaper","type":"Vendor","wcid":678,"cell":"BC9F014B","place":"building","ns":25.82,"ew":49.2,"id":9733,"desc":"Armorer."}, + {"name":"Scildith Dyrson the Bowyer","type":"Vendor","wcid":671,"cell":"BC9F011A","place":"building","ns":25.31,"ew":49.07,"id":9734,"desc":"Bowyer."}, + {"name":"Magrom the Red, Barkeeper","type":"Vendor","wcid":669,"cell":"BC9F0136","place":"building","ns":25.7,"ew":48.79,"id":9735,"desc":"Barkeeper."}, + {"name":"Jeweler Suya bint Habil","type":"Vendor","wcid":674,"cell":"BC9F015D","place":"building","ns":25.68,"ew":49.12,"id":9736,"desc":"Jeweler."}, + {"name":"Merchant Ledine","type":"Vendor","wcid":676,"cell":"BC9F0122","place":"building","ns":25.53,"ew":49.18,"id":9737,"desc":"Shopkeeper."}, + {"name":"Lieutenant Kenneth","type":"NPC","wcid":11809,"cell":"BC9F0000","place":"outdoor","ns":25.79,"ew":49.13,"id":9738,"desc":"Quartermaster."}, + {"name":"Glysander Cartoth","type":"NPC","wcid":15810,"cell":"BC9F0108","place":"building","ns":25.72,"ew":48.53,"id":9739,"desc":"Poet."}, + {"name":"Royal Guard","type":"NPC","wcid":24248,"cell":"BC9F0000","place":"outdoor","ns":25.56,"ew":48.83,"id":9740,"desc":"Guard."}, + {"name":"Sign","type":"NPC","wcid":25722,"cell":"BC9F0000","place":"outdoor","ns":25.41,"ew":49.18,"id":9741}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"BC9F0000","place":"outdoor","ns":25.57,"ew":49.07,"id":9742}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"BC9F0000","place":"outdoor","ns":25.96,"ew":49.12,"id":9743}, + {"name":"Alec","type":"NPC","wcid":28475,"cell":"BC9F0150","place":"building","ns":25.78,"ew":49.17,"id":9744,"desc":"Noble Guard."}, + {"name":"Barnar the Tinker","type":"NPC","wcid":7240,"cell":"BC9F011C","place":"building","ns":25.31,"ew":49.08,"id":9745,"desc":"Tinker."}, + {"name":"Guard Hamdyn","type":"NPC","wcid":29766,"cell":"BC9F0139","place":"building","ns":25.69,"ew":48.77,"id":9746,"desc":"Guard."}, + {"name":"Guard Fassel","type":"NPC","wcid":29770,"cell":"BC9F0000","place":"outdoor","ns":25.73,"ew":48.83,"id":9747,"desc":"Guard."}, + {"name":"Guard Sorchia","type":"NPC","wcid":29768,"cell":"BC9F0000","place":"outdoor","ns":25.72,"ew":48.84,"id":9748,"desc":"Guard."}, + {"name":"Guard Ellyon","type":"NPC","wcid":29771,"cell":"BC9F0000","place":"outdoor","ns":25.69,"ew":48.84,"id":9749,"desc":"Guard."}, + {"name":"Guard Lo Pan","type":"NPC","wcid":29772,"cell":"BC9F0140","place":"building","ns":25.69,"ew":48.8,"id":9750,"desc":"Guard."}, + {"name":"Guard Haigh","type":"NPC","wcid":29767,"cell":"BC9F014A","place":"building","ns":25.72,"ew":48.84,"id":9751,"desc":"Guard."}, + {"name":"Guard Devon","type":"NPC","wcid":29769,"cell":"BC9F014A","place":"building","ns":25.7,"ew":48.84,"id":9752,"desc":"Guard."}, + {"name":"Felizio Calmasi","type":"NPC","wcid":41186,"cell":"BC9F001D","place":"outdoor","ns":25.73,"ew":48.77,"id":9753,"desc":"Arcanum Tinker."}, + {"name":"Royal Guard Qumasha","type":"NPC","wcid":32618,"cell":"BC9F0038","place":"outdoor","ns":25.97,"ew":49.06,"id":9754,"desc":"Guard."}, + {"name":"Shan Zhen","type":"NPC","wcid":34499,"cell":"BC9F003E","place":"outdoor","ns":25.84,"ew":49.23,"id":9755,"desc":"Apprentice of the Sword."}, + {"name":"Oswent the Pale","type":"NPC","wcid":35477,"cell":"BC9F003D","place":"outdoor","ns":25.74,"ew":49.23,"id":9756,"desc":"Hidden Hand."}, + {"name":"Blind Snowman","type":"NPC","wcid":22829,"cell":"BCB90000","place":"outdoor","ns":46.67,"ew":48.89,"id":9757}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"BCD10000","place":"outdoor","ns":65.43,"ew":49.0,"id":9758}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"BD9E0000","place":"outdoor","ns":24.69,"ew":49.43,"id":9759}, + {"name":"Magus Gondibyr Langarl","type":"Vendor","wcid":675,"cell":"BD9F0100","place":"building","ns":25.8,"ew":49.4,"id":9760,"desc":"Archmage."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20215,"cell":"BD9F0106","place":"building","ns":25.7,"ew":49.42,"id":9761,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":20205,"cell":"BD9F0108","place":"building","ns":25.71,"ew":49.39,"id":9762,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20217,"cell":"BD9F0107","place":"building","ns":25.72,"ew":49.41,"id":9763,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20218,"cell":"BD9F010D","place":"building","ns":25.72,"ew":49.4,"id":9764,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":20206,"cell":"BD9F010C","place":"building","ns":25.68,"ew":49.4,"id":9765,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20216,"cell":"BD9F0000","place":"outdoor","ns":25.7,"ew":49.42,"id":9766,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":20221,"cell":"BD9F0116","place":"building","ns":25.57,"ew":49.41,"id":9767,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":20209,"cell":"BD9F0116","place":"building","ns":25.58,"ew":49.42,"id":9768,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":20225,"cell":"BD9F011A","place":"building","ns":25.61,"ew":49.38,"id":9769,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":20213,"cell":"BD9F011F","place":"building","ns":25.62,"ew":49.43,"id":9770,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"BD9F0122","place":"building","ns":25.57,"ew":49.41,"id":9771,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"BD9F0124","place":"building","ns":25.63,"ew":49.39,"id":9772,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"BD9F0124","place":"building","ns":25.6,"ew":49.37,"id":9773,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"BD9F011F","place":"building","ns":25.6,"ew":49.42,"id":9774,"desc":"Master Archmage."}, + {"name":"Jarvis Hammerstone","type":"NPC","wcid":35462,"cell":"BD9F000C","place":"outdoor","ns":25.56,"ew":49.36,"id":9775,"desc":"Merchant."}, + {"name":"Corporal Liao Chen","type":"NPC","wcid":35839,"cell":"BD9F000C","place":"outdoor","ns":25.57,"ew":49.36,"id":9776,"desc":"Guard."}, + {"name":"Arturus of the Eldrytch Web","type":"NPC","wcid":38389,"cell":"BDA0001B","place":"outdoor","ns":26.28,"ew":49.64,"id":9777,"desc":"Society Recruiter."}, + {"name":"Tree","type":"NPC","wcid":40530,"cell":"BDD10016","place":"outdoor","ns":65.76,"ew":49.51,"id":9778}, + {"name":"Melia Thorn the Archmage","type":"Vendor","wcid":5834,"cell":"BDD2011E","place":"building","ns":66.41,"ew":49.77,"id":9779,"desc":"Archmage."}, + {"name":"MacDugal","type":"NPC","wcid":5839,"cell":"BDD2012B","place":"building","ns":66.4,"ew":49.94,"id":9780,"desc":"Bandit Captain."}, + {"name":"Barkeep Gorth","type":"Vendor","wcid":5832,"cell":"BDD2012B","place":"building","ns":66.44,"ew":49.92,"id":9781,"desc":"Barkeep."}, + {"name":"Gwillim, the Apprentice","type":"NPC","wcid":5837,"cell":"BDD20128","place":"building","ns":66.4,"ew":49.92,"id":9782,"desc":"Melia's Apprentice."}, + {"name":"Provisioner Murdo","type":"Vendor","wcid":5835,"cell":"BDD20000","place":"outdoor","ns":66.32,"ew":49.81,"id":9783,"desc":"Shifty Provisioner."}, + {"name":"Jourgensson","type":"NPC","wcid":5838,"cell":"BDD20000","place":"outdoor","ns":66.34,"ew":50.01,"id":9784,"desc":"MacDugal's Lieutenant."}, + {"name":"Karwin, the Lunatic","type":"NPC","wcid":5836,"cell":"BDD2010E","place":"building","ns":66.42,"ew":50.02,"id":9785,"desc":"Lunatic."}, + {"name":"Shi Ki-Yong the Armorer","type":"Vendor","wcid":5833,"cell":"BDD20000","place":"outdoor","ns":66.49,"ew":49.81,"id":9786,"desc":"Armorer."}, + {"name":"Gillian the Poacher","type":"NPC","wcid":8654,"cell":"BDD2010D","place":"building","ns":66.34,"ew":49.9,"id":9787,"desc":"Trophy Collector."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"BDD20000","place":"outdoor","ns":66.44,"ew":49.79,"id":9788}, + {"name":"Journeyman Cook","type":"NPC","wcid":28920,"cell":"BDD20000","place":"outdoor","ns":66.49,"ew":49.99,"id":9789,"desc":"Apprentice Cook."}, + {"name":"Alison Dulane","type":"NPC","wcid":28688,"cell":"BDD2002C","place":"outdoor","ns":66.35,"ew":49.79,"id":9790,"desc":"Augmentation Trainer."}, + {"name":"Shanrek the Forger","type":"NPC","wcid":31328,"cell":"BDD20101","place":"building","ns":66.54,"ew":49.89,"id":9791,"desc":"Master Forger."}, + {"name":"Neela Nashua","type":"NPC","wcid":41516,"cell":"BDD2012B","place":"building","ns":66.39,"ew":49.86,"id":9792,"desc":"Augmentation Trainer."}, + {"name":"Arianna the Adept","type":"NPC","wcid":44886,"cell":"BDD20035","place":"outdoor","ns":66.52,"ew":49.86,"id":9793,"desc":"Augmentation Trainer."}, + {"name":"Kiriel Shadowborn","type":"NPC","wcid":33293,"cell":"BDD2003B","place":"outdoor","ns":66.31,"ew":49.99,"id":9794,"desc":"Emissary of Isin Dule."}, + {"name":"Healer","type":"Vendor","wcid":1386,"cell":"BE6C0000","place":"outdoor","ns":-15.12,"ew":50.36,"id":9795}, + {"name":"Hassha","type":"NPC","wcid":32673,"cell":"BE720102","place":"dungeon","id":9796,"desc":"Scholar of Salt and Ash. In a dungeon (landblock BE72)."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"BE80010A","place":"building","ns":0.6,"ew":50.62,"id":9797,"desc":"Mage."}, + {"name":"Wedding Planner","type":"Vendor","wcid":14930,"cell":"BE80010A","place":"building","ns":0.59,"ew":50.61,"id":9798,"desc":"Planner of Weddings."}, + {"name":"Exploration Marker","type":"NPC","wcid":39761,"cell":"BE89003B","place":"outdoor","ns":7.9,"ew":50.81,"id":9799}, + {"name":"Ringoshu the Apple Seller","type":"Vendor","wcid":2047,"cell":"BE900102","place":"building","ns":13.6,"ew":50.7,"id":9800,"desc":"Farmer."}, + {"name":"Lanaith","type":"NPC","wcid":33542,"cell":"BED70024","place":"outdoor","ns":70.36,"ew":50.47,"id":9801,"desc":"Emissary of Isin Dule."}, + {"name":"Archmage","type":"Vendor","wcid":1371,"cell":"BF3E0100","place":"dungeon","id":9802,"desc":"In a dungeon (landblock BF3E)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39799,"cell":"BF5E0009","place":"outdoor","ns":-26.69,"ew":51.04,"id":9803}, + {"name":"Sathagg the Jeweler","type":"Vendor","wcid":4442,"cell":"BF800165","place":"building","ns":0.7,"ew":51.01,"id":9804,"desc":"Jeweler."}, + {"name":"Taryla the Bowyer","type":"Vendor","wcid":4439,"cell":"BF800119","place":"building","ns":0.71,"ew":51.2,"id":9805,"desc":"Bowyer."}, + {"name":"Grocer Cortarn","type":"Vendor","wcid":4440,"cell":"BF800174","place":"building","ns":0.51,"ew":51.0,"id":9806,"desc":"Grocer."}, + {"name":"Cemcera the Shopkeeper","type":"Vendor","wcid":4444,"cell":"BF800137","place":"building","ns":0.5,"ew":51.21,"id":9807,"desc":"Shopkeeper."}, + {"name":"Selflora the Barkeep","type":"Vendor","wcid":4436,"cell":"BF80014D","place":"building","ns":0.5,"ew":51.39,"id":9808,"desc":"Barkeeper."}, + {"name":"Healer Beysta","type":"Vendor","wcid":4441,"cell":"BF800132","place":"building","ns":0.68,"ew":51.42,"id":9809,"desc":"Healer."}, + {"name":"Sitrath the Smith","type":"Vendor","wcid":4437,"cell":"BF800121","place":"building","ns":0.78,"ew":51.5,"id":9810,"desc":"Blacksmith."}, + {"name":"Smith Baltiff","type":"Vendor","wcid":4438,"cell":"BF800125","place":"building","ns":0.82,"ew":51.52,"id":9811,"desc":"Blacksmith."}, + {"name":"Dafrida the Tailor","type":"Vendor","wcid":4445,"cell":"BF80011E","place":"building","ns":0.7,"ew":51.19,"id":9812,"desc":"Tailor."}, + {"name":"Archmage Den Ou","type":"Vendor","wcid":4435,"cell":"BF800000","place":"outdoor","ns":0.68,"ew":51.02,"id":9813,"desc":"Archmage."}, + {"name":"Gylfolma the Scribe","type":"Vendor","wcid":4443,"cell":"BF800178","place":"building","ns":0.5,"ew":50.99,"id":9814,"desc":"Scribe."}, + {"name":"Lord Aleval","type":"NPC","wcid":5046,"cell":"BF800000","place":"outdoor","ns":1.01,"ew":51.11,"id":9815,"desc":"Society Agent."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":20225,"cell":"BF800182","place":"building","ns":0.59,"ew":51.49,"id":9816,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":20221,"cell":"BF800180","place":"building","ns":0.62,"ew":51.5,"id":9817,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":20209,"cell":"BF800187","place":"building","ns":0.6,"ew":51.48,"id":9818,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":20213,"cell":"BF800186","place":"building","ns":0.6,"ew":51.52,"id":9819,"desc":"Master Archmage."}, + {"name":"Guard Chandler Hammett","type":"NPC","wcid":25717,"cell":"BF800000","place":"outdoor","ns":0.9,"ew":51.08,"id":9820,"desc":"Senior Guard."}, + {"name":"Dame Brinna O'Shea","type":"NPC","wcid":25715,"cell":"BF800114","place":"building","ns":1.0,"ew":51.09,"id":9821,"desc":"Senior Guard."}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"BF800000","place":"outdoor","ns":0.82,"ew":51.65,"id":9822}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"BF800000","place":"outdoor","ns":0.56,"ew":51.45,"id":9823}, + {"name":"Apprentice Cook","type":"NPC","wcid":27743,"cell":"BF80011D","place":"building","ns":0.69,"ew":51.21,"id":9824}, + {"name":"Devastated Watcher","type":"NPC","wcid":31967,"cell":"BFEC001C","place":"outdoor","ns":87.24,"ew":51.19,"id":9825}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C0260000","place":"outdoor","ns":-71.03,"ew":52.37,"id":9826}, + {"name":"Wandering Bowyer","type":"Vendor","wcid":1380,"cell":"C0640106","place":"building","ns":-21.72,"ew":52.11,"id":9827,"desc":"Bowyer."}, + {"name":"William Witty","type":"NPC","wcid":12127,"cell":"C07F0102","place":"building","ns":0.28,"ew":51.78,"id":9828,"desc":"Trophy Collector."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C0820000","place":"outdoor","ns":2.3,"ew":51.68,"id":9829}, + {"name":"Peddler","type":"Vendor","wcid":1390,"cell":"C1320000","place":"outdoor","ns":-61.54,"ew":52.77,"id":9830}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C1320000","place":"outdoor","ns":-61.47,"ew":52.87,"id":9831}, + {"name":"Felscuda","type":"NPC","wcid":5020,"cell":"C1740102","place":"building","ns":-8.81,"ew":53.1,"id":9832,"desc":"Groundskeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C2740000","place":"outdoor","ns":-8.69,"ew":53.83,"id":9833}, + {"name":"Raxanza Folthid","type":"NPC","wcid":5024,"cell":"C2740103","place":"building","ns":-8.81,"ew":53.7,"id":9834,"desc":"Lady."}, + {"name":"Farmer","type":"Vendor","wcid":1381,"cell":"C28C0106","place":"building","ns":10.5,"ew":53.49,"id":9835}, + {"name":"Roaming Bowyer","type":"Vendor","wcid":1378,"cell":"C28C0103","place":"building","ns":10.39,"ew":53.49,"id":9836,"desc":"Bowyer."}, + {"name":"Exploration Marker","type":"NPC","wcid":39827,"cell":"C29A003A","place":"outdoor","ns":21.41,"ew":54.0,"id":9837}, + {"name":"Snowman","type":"Vendor","wcid":5765,"cell":"C3270000","place":"outdoor","ns":-70.4,"ew":54.53,"id":9838}, + {"name":"Riflyffa the Shopkeeper","type":"Vendor","wcid":4446,"cell":"C3800101","place":"building","ns":0.99,"ew":54.2,"id":9839,"desc":"Shopkeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C3800000","place":"outdoor","ns":0.97,"ew":54.12,"id":9840}, + {"name":"Ercel","type":"NPC","wcid":5048,"cell":"C3800109","place":"building","ns":1.01,"ew":54.31,"id":9841,"desc":"Citizen of Lytelthorpe."}, + {"name":"Rock","type":"NPC","wcid":38775,"cell":"C3F7002F","place":"outdoor","ns":96.26,"ew":54.61,"id":9842}, + {"name":"Exploration Marker","type":"NPC","wcid":39816,"cell":"C3F7002F","place":"outdoor","ns":96.3,"ew":54.62,"id":9843}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C4370000","place":"outdoor","ns":-57.4,"ew":55.09,"id":9844}, + {"name":"Farmer","type":"Vendor","wcid":1381,"cell":"C4A80000","place":"outdoor","ns":32.59,"ew":55.02,"id":9845}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C4A80000","place":"outdoor","ns":32.5,"ew":55.08,"id":9846}, + {"name":"Tikka","type":"NPC","wcid":35906,"cell":"C4B5037B","place":"underground","ns":43.44,"ew":54.97,"id":9847,"desc":"Olthoi Shield Crafter."}, + {"name":"Thrasher","type":"NPC","wcid":43058,"cell":"C4B5037C","place":"underground","ns":43.41,"ew":54.92,"id":9848,"desc":"Olthoi Mace Crafter."}, + {"name":"Swift-Eye","type":"NPC","wcid":35903,"cell":"C4B5037D","place":"underground","ns":43.45,"ew":54.92,"id":9849,"desc":"Olthoi Atlatl Crafter."}, + {"name":"Slasha","type":"NPC","wcid":43060,"cell":"C4B5037C","place":"underground","ns":43.39,"ew":54.93,"id":9850,"desc":"Olthoi Great Sword Crafter."}, + {"name":"Sasha","type":"NPC","wcid":35908,"cell":"C4B5037A","place":"underground","ns":43.43,"ew":54.95,"id":9851,"desc":"Olthoi Sword Crafter."}, + {"name":"Peda's Assistant","type":"NPC","wcid":43059,"cell":"C4B50379","place":"underground","ns":43.37,"ew":54.96,"id":9852,"desc":"Olthoi Life Wand Crafter."}, + {"name":"Peda","type":"NPC","wcid":43063,"cell":"C4B50379","place":"underground","ns":43.37,"ew":54.96,"id":9853,"desc":"Olthoi War Wand Crafter."}, + {"name":"Miko","type":"NPC","wcid":35907,"cell":"C4B5037B","place":"underground","ns":43.45,"ew":54.96,"id":9854,"desc":"Olthoi Spear Crafter."}, + {"name":"Mac","type":"NPC","wcid":43064,"cell":"C4B5037D","place":"underground","ns":43.43,"ew":54.92,"id":9855,"desc":"Olthoi Staff Crafter."}, + {"name":"Long-Shot","type":"NPC","wcid":43061,"cell":"C4B5037E","place":"underground","ns":43.48,"ew":54.93,"id":9856,"desc":"Olthoi Bow Crafter."}, + {"name":"Lash","type":"NPC","wcid":43057,"cell":"C4B5037B","place":"underground","ns":43.47,"ew":54.97,"id":9857,"desc":"Olthoi Dagger Crafter."}, + {"name":"Deena","type":"NPC","wcid":35905,"cell":"C4B5037D","place":"underground","ns":43.42,"ew":54.94,"id":9858,"desc":"Olthoi Katar Crafter."}, + {"name":"Dead-Eye","type":"NPC","wcid":43062,"cell":"C4B5037E","place":"underground","ns":43.47,"ew":54.95,"id":9859,"desc":"Olthoi Crossbow Crafter."}, + {"name":"Crusher","type":"NPC","wcid":35904,"cell":"C4B50379","place":"underground","ns":43.4,"ew":54.96,"id":9860,"desc":"Olthoi Axe Crafter."}, + {"name":"Hisham al-Evv","type":"Vendor","wcid":36378,"cell":"C4B60002","place":"outdoor","ns":43.83,"ew":54.92,"id":9861,"desc":"Arcanum Collector."}, + {"name":"Tomihino","type":"NPC","wcid":35826,"cell":"C4B60101","place":"building","ns":43.79,"ew":54.9,"id":9862,"desc":"Olthoi Hunter."}, + {"name":"Ethan Wintermaine","type":"NPC","wcid":35909,"cell":"C4B60002","place":"outdoor","ns":43.78,"ew":54.94,"id":9863,"desc":"Royal Guard Captain."}, + {"name":"Alicia Swiftblade","type":"NPC","wcid":35825,"cell":"C4B60101","place":"building","ns":43.79,"ew":54.91,"id":9864,"desc":"Olthoi Hunter."}, + {"name":"Adrien Swiftblade","type":"NPC","wcid":35828,"cell":"C4B60101","place":"building","ns":43.8,"ew":54.92,"id":9865,"desc":"Royal Guard."}, + {"name":"Roaming Bowyer","type":"Vendor","wcid":1378,"cell":"C58D0000","place":"outdoor","ns":11.33,"ew":55.69,"id":9866,"desc":"Bowyer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C59C0000","place":"outdoor","ns":23.31,"ew":56.2,"id":9867}, + {"name":"Laqisha the Scribe","type":"Vendor","wcid":701,"cell":"C5A6011E","place":"building","ns":31.19,"ew":56.31,"id":9868,"desc":"Scribe."}, + {"name":"Harald the Fletcher","type":"Vendor","wcid":403,"cell":"C5A80102","place":"building","ns":32.8,"ew":55.81,"id":9869,"desc":"Bowyer."}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"C5A90000","place":"outdoor","ns":33.62,"ew":55.81,"id":9870}, + {"name":"Surnad the Peddler","type":"Vendor","wcid":5877,"cell":"C5B20102","place":"building","ns":41.1,"ew":56.41,"id":9871,"desc":"Peddler."}, + {"name":"Denterra the Healer","type":"Vendor","wcid":5876,"cell":"C5B20102","place":"building","ns":41.1,"ew":56.39,"id":9872,"desc":"Healer."}, + {"name":"Trap Door","type":"NPC","wcid":33836,"cell":"C65F000F","place":"outdoor","ns":-25.3,"ew":56.57,"id":9873}, + {"name":"Unfriendly Barkeeper","type":"NPC","wcid":33837,"cell":"C65F0100","place":"building","ns":-25.29,"ew":56.59,"id":9874,"desc":"Barkeeper."}, + {"name":"Shrine of Black Water","type":"NPC","wcid":35858,"cell":"C6610103","place":"building","ns":-24.2,"ew":57.1,"id":9875}, + {"name":"Peddler","type":"Vendor","wcid":1390,"cell":"C6880100","place":"building","ns":7.21,"ew":57.11,"id":9876}, + {"name":"Leather Crafter","type":"NPC","wcid":4213,"cell":"C68C0102","place":"building","ns":10.4,"ew":57.09,"id":9877,"desc":"Trophy Collector."}, + {"name":"Magus Guthima the Wise","type":"Vendor","wcid":692,"cell":"C6A80101","place":"building","ns":32.8,"ew":56.7,"id":9878,"desc":"Archmage."}, + {"name":"Cateril Carsmad the Armorer","type":"Vendor","wcid":695,"cell":"C6A90122","place":"building","ns":33.61,"ew":56.58,"id":9879,"desc":"Armorer."}, + {"name":"Carsith the Weaponsmith","type":"Vendor","wcid":400,"cell":"C6A90122","place":"building","ns":33.6,"ew":56.58,"id":9880,"desc":"Weaponsmith."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"C6A9015A","place":"building","ns":33.48,"ew":56.58,"id":9881,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"C6A90158","place":"building","ns":33.51,"ew":56.61,"id":9882,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"C6A9015A","place":"building","ns":33.47,"ew":56.61,"id":9883,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"C6A9015A","place":"building","ns":33.49,"ew":56.58,"id":9884,"desc":"Master Archmage."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"C6A901A2","place":"building","ns":33.51,"ew":56.89,"id":9885,"desc":"Mage."}, + {"name":"Belthew Shearstone the Jeweler","type":"Vendor","wcid":698,"cell":"C6A9011A","place":"building","ns":33.5,"ew":56.73,"id":9886,"desc":"Jeweler."}, + {"name":"Shopkeep Mirinda","type":"Vendor","wcid":702,"cell":"C6A90147","place":"building","ns":33.38,"ew":56.62,"id":9887,"desc":"Shopkeeper."}, + {"name":"Davis the Tailor","type":"Vendor","wcid":703,"cell":"C6A90145","place":"building","ns":33.42,"ew":56.6,"id":9888,"desc":"Tailor."}, + {"name":"Grocer Rodega Tyning","type":"Vendor","wcid":696,"cell":"C6A90135","place":"building","ns":33.58,"ew":56.68,"id":9889,"desc":"Grocer."}, + {"name":"Healer Dragando the Leech","type":"Vendor","wcid":697,"cell":"C6A90133","place":"building","ns":33.59,"ew":56.72,"id":9890,"desc":"Healer."}, + {"name":"Barkeep Mae Lilidag","type":"Vendor","wcid":693,"cell":"C6A90104","place":"building","ns":33.4,"ew":56.7,"id":9891,"desc":"Barkeeper."}, + {"name":"Leather Crafter","type":"NPC","wcid":4213,"cell":"C6A90149","place":"building","ns":33.37,"ew":56.6,"id":9892,"desc":"Trophy Collector."}, + {"name":"Barkeep Lienne","type":"Vendor","wcid":694,"cell":"C6A90104","place":"building","ns":33.41,"ew":56.71,"id":9893,"desc":"Barkeeper."}, + {"name":"Anasha","type":"NPC","wcid":22934,"cell":"C6A901AE","place":"building","ns":33.33,"ew":56.54,"id":9894,"desc":"Student."}, + {"name":"Hiyp the Toad","type":"NPC","wcid":25486,"cell":"C6A90118","place":"building","ns":33.44,"ew":56.71,"id":9895,"desc":"Drunken Miner."}, + {"name":"Translator Aun Laokhe","type":"NPC","wcid":27117,"cell":"C6A90000","place":"outdoor","ns":33.5,"ew":56.84,"id":9896}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C6A90000","place":"outdoor","ns":33.59,"ew":56.79,"id":9897}, + {"name":"Apprentice Alchemist","type":"NPC","wcid":28182,"cell":"C6A90000","place":"outdoor","ns":33.44,"ew":56.76,"id":9898}, + {"name":"Weapon Imbue Vendor","type":"Vendor","wcid":45501,"cell":"C6A9016E","place":"building","ns":33.59,"ew":56.87,"id":9899}, + {"name":"Free Weapon Vendor","type":"Vendor","wcid":45489,"cell":"C6A90175","place":"building","ns":33.61,"ew":56.93,"id":9900}, + {"name":"Melee Rare Vendor","type":"Vendor","wcid":45485,"cell":"C6A90177","place":"building","ns":33.63,"ew":56.94,"id":9901}, + {"name":"Pevilo ibn Djimin","type":"Vendor","wcid":35811,"cell":"C6A901C8","place":"building","ns":33.5,"ew":56.84,"id":9902,"desc":"Arcane Items Vendor."}, + {"name":"Marid","type":"Vendor","wcid":46425,"cell":"C6A9001C","place":"outdoor","ns":33.65,"ew":56.79,"id":9903,"desc":"Stipend Vendor."}, + {"name":"Emissary of Asheron","type":"NPC","wcid":45495,"cell":"C6A9016E","place":"building","ns":33.61,"ew":56.87,"id":9904,"desc":"Emissary."}, + {"name":"Professor of Void Magic","type":"NPC","wcid":53385,"cell":"C6A9000B","place":"outdoor","ns":33.53,"ew":56.56,"id":9905,"desc":"Spell Instructor."}, + {"name":"Professor of War Magic","type":"NPC","wcid":53381,"cell":"C6A9000B","place":"outdoor","ns":33.52,"ew":56.57,"id":9906,"desc":"Spell Instructor."}, + {"name":"Primalist","type":"NPC","wcid":49516,"cell":"C6A90019","place":"outdoor","ns":33.35,"ew":56.78,"id":9907}, + {"name":"Professor of Life Magic","type":"NPC","wcid":53384,"cell":"C6A9000B","place":"outdoor","ns":33.52,"ew":56.58,"id":9908,"desc":"Spell Instructor."}, + {"name":"Professor of Item Magic","type":"NPC","wcid":53383,"cell":"C6A9000B","place":"outdoor","ns":33.52,"ew":56.58,"id":9909,"desc":"Spell Instructor."}, + {"name":"Professor of Creature Magic","type":"NPC","wcid":53382,"cell":"C6A9000B","place":"outdoor","ns":33.52,"ew":56.6,"id":9910,"desc":"Spell Instructor."}, + {"name":"Necromancer","type":"NPC","wcid":49515,"cell":"C6A90019","place":"outdoor","ns":33.35,"ew":56.79,"id":9911}, + {"name":"Naturalist","type":"NPC","wcid":49514,"cell":"C6A90019","place":"outdoor","ns":33.35,"ew":56.77,"id":9912}, + {"name":"Emissary of Asheron","type":"NPC","wcid":45490,"cell":"C6A90175","place":"building","ns":33.63,"ew":56.94,"id":9913,"desc":"Emissary."}, + {"name":"Emissary of Asheron","type":"NPC","wcid":45492,"cell":"C6A90177","place":"building","ns":33.63,"ew":56.92,"id":9914,"desc":"Emissary."}, + {"name":"Isin Dule","type":"NPC","wcid":43861,"cell":"C6A9018A","place":"building","ns":33.42,"ew":56.9,"id":9915,"desc":"Umbral High King."}, + {"name":"Lord Dargeth","type":"NPC","wcid":42984,"cell":"C6A9018A","place":"building","ns":33.43,"ew":56.9,"id":9916,"desc":"Royal Knight."}, + {"name":"Thrown Weapons Mastery","type":"NPC","wcid":45480,"cell":"C6A9001A","place":"outdoor","ns":33.37,"ew":56.82,"id":9917}, + {"name":"Magic Mastery","type":"NPC","wcid":45477,"cell":"C6A9001A","place":"outdoor","ns":33.36,"ew":56.82,"id":9918}, + {"name":"Crossbow Mastery","type":"NPC","wcid":45474,"cell":"C6A9001A","place":"outdoor","ns":33.38,"ew":56.82,"id":9919}, + {"name":"Bow Mastery","type":"NPC","wcid":45473,"cell":"C6A9001A","place":"outdoor","ns":33.39,"ew":56.82,"id":9920}, + {"name":"Two Handed Combat Mastery","type":"NPC","wcid":45481,"cell":"C6A9001A","place":"outdoor","ns":33.43,"ew":56.82,"id":9921}, + {"name":"Unarmed Combat Mastery","type":"NPC","wcid":45482,"cell":"C6A9001A","place":"outdoor","ns":33.44,"ew":56.82,"id":9922}, + {"name":"Sword Mastery","type":"NPC","wcid":45471,"cell":"C6A9001A","place":"outdoor","ns":33.45,"ew":56.82,"id":9923}, + {"name":"Umbral Guard","type":"NPC","wcid":43862,"cell":"C6A90193","place":"building","ns":33.36,"ew":56.91,"id":9924,"desc":"Isin Dule's Personal Guard."}, + {"name":"Royal Guard","type":"NPC","wcid":43009,"cell":"C6A90193","place":"building","ns":33.39,"ew":56.9,"id":9925,"desc":"Borelean's Royal Guard."}, + {"name":"Royal Guard","type":"NPC","wcid":43010,"cell":"C6A90193","place":"building","ns":33.39,"ew":56.91,"id":9926,"desc":"Borelean's Royal Guard."}, + {"name":"Staves Mastery","type":"NPC","wcid":45479,"cell":"C6A9001B","place":"outdoor","ns":33.45,"ew":56.82,"id":9927}, + {"name":"Spears Mastery","type":"NPC","wcid":45478,"cell":"C6A9001B","place":"outdoor","ns":33.46,"ew":56.82,"id":9928}, + {"name":"Mace Mastery","type":"NPC","wcid":45476,"cell":"C6A9001B","place":"outdoor","ns":33.47,"ew":56.82,"id":9929}, + {"name":"Dagger Mastery","type":"NPC","wcid":45475,"cell":"C6A9001B","place":"outdoor","ns":33.48,"ew":56.82,"id":9930}, + {"name":"Axe Mastery","type":"NPC","wcid":45472,"cell":"C6A9001B","place":"outdoor","ns":33.48,"ew":56.82,"id":9931}, + {"name":"John","type":"NPC","wcid":51962,"cell":"C6A90014","place":"outdoor","ns":33.59,"ew":56.74,"id":9932,"desc":"Gold Smith."}, + {"name":"Royal Guard","type":"NPC","wcid":43007,"cell":"C6A90022","place":"outdoor","ns":33.41,"ew":56.88,"id":9933,"desc":"Borelean's Royal Guard."}, + {"name":"Royal Guard","type":"NPC","wcid":43008,"cell":"C6A90022","place":"outdoor","ns":33.4,"ew":56.88,"id":9934,"desc":"Borelean's Royal Guard."}, + {"name":"Varinia","type":"NPC","wcid":52139,"cell":"C6A9001C","place":"outdoor","ns":33.64,"ew":56.81,"id":9935,"desc":"Keeper of Whispered Lore."}, + {"name":"Monroe","type":"NPC","wcid":46424,"cell":"C6A9001C","place":"outdoor","ns":33.65,"ew":56.78,"id":9936,"desc":"Stipend Officer."}, + {"name":"Jacob Durstan","type":"NPC","wcid":31364,"cell":"C6A9001C","place":"outdoor","ns":33.61,"ew":56.82,"id":9937,"desc":"Adventurer."}, + {"name":"Blackmoor's Page","type":"NPC","wcid":46776,"cell":"C6A90024","place":"outdoor","ns":33.56,"ew":56.9,"id":9938}, + {"name":"Exploration Marker","type":"NPC","wcid":39788,"cell":"C6A90008","place":"outdoor","ns":33.95,"ew":56.55,"id":9939}, + {"name":"The Deep","type":"NPC","wcid":33674,"cell":"C6EA0100","place":"building","ns":85.5,"ew":57.18,"id":9940}, + {"name":"Rock","type":"NPC","wcid":38776,"cell":"C6EC0026","place":"outdoor","ns":87.37,"ew":56.89,"id":9941}, + {"name":"Le-Ai Rea","type":"NPC","wcid":4122,"cell":"C7200102","place":"building","ns":-75.91,"ew":57.29,"id":9942,"desc":"Old Man."}, + {"name":"Archmage","type":"Vendor","wcid":1369,"cell":"C75F0000","place":"outdoor","ns":-25.61,"ew":57.59,"id":9943}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C75F0000","place":"outdoor","ns":-25.8,"ew":57.82,"id":9944}, + {"name":"Exploration Marker","type":"NPC","wcid":39820,"cell":"C75F001C","place":"outdoor","ns":-25.58,"ew":57.59,"id":9945}, + {"name":"Brontynn Marshad","type":"NPC","wcid":15809,"cell":"C7720000","place":"outdoor","ns":-10.29,"ew":57.59,"id":9946,"desc":"Historian."}, + {"name":"Branwyn","type":"NPC","wcid":31973,"cell":"C7A30102","place":"building","ns":29.08,"ew":57.92,"id":9947,"desc":"Worried Wife."}, + {"name":"Exploration Marker","type":"NPC","wcid":39771,"cell":"C7B40006","place":"outdoor","ns":42.55,"ew":57.35,"id":9948}, + {"name":"Exploration Marker","type":"NPC","wcid":39811,"cell":"C7B703E2","place":"dungeon","id":9949,"desc":"In a dungeon (landblock C7B7)."}, + {"name":"Life Stone","type":"Lifestone","wcid":23618,"cell":"C7BB0000","place":"outdoor","ns":48.3,"ew":57.4,"id":9950}, + {"name":"Francois di Terli","type":"NPC","wcid":33675,"cell":"C7E90020","place":"outdoor","ns":85.17,"ew":57.6,"id":9951,"desc":"Soldier."}, + {"name":"Abyssal Totem Gateway","type":"NPC","wcid":33915,"cell":"C7EB0005","place":"outdoor","ns":86.5,"ew":57.3,"id":9952}, + {"name":"Grearrk, Mosswart Emissary","type":"NPC","wcid":26536,"cell":"C85B0000","place":"outdoor","ns":-28.99,"ew":58.22,"id":9953}, + {"name":"Ssavish","type":"NPC","wcid":31430,"cell":"C8620100","place":"dungeon","id":9954,"desc":"Scholar. In a dungeon (landblock C862)."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C8790101","place":"dungeon","id":9955,"desc":"In a dungeon (landblock C879)."}, + {"name":"Girdweld the Shopkeeper","type":"Vendor","wcid":4449,"cell":"C8880109","place":"building","ns":7.57,"ew":58.41,"id":9956,"desc":"Shopkeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C8880000","place":"outdoor","ns":7.57,"ew":58.47,"id":9957}, + {"name":"Brentsella","type":"NPC","wcid":4794,"cell":"C8880102","place":"building","ns":7.6,"ew":58.22,"id":9958,"desc":"Citizen of Rithwic."}, + {"name":"Peddler","type":"Vendor","wcid":1390,"cell":"C88B0000","place":"outdoor","ns":9.89,"ew":58.48,"id":9959}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"C88B0103","place":"building","ns":9.97,"ew":58.39,"id":9960,"desc":"Mage."}, + {"name":"Wedding Planner","type":"Vendor","wcid":14930,"cell":"C88B0103","place":"building","ns":9.97,"ew":58.41,"id":9961,"desc":"Planner of Weddings."}, + {"name":"Barkeep Ricetha","type":"Vendor","wcid":659,"cell":"C88C0136","place":"building","ns":10.7,"ew":58.1,"id":9962,"desc":"Barkeeper."}, + {"name":"Luthin the Smith","type":"Vendor","wcid":661,"cell":"C88C011C","place":"building","ns":10.8,"ew":58.62,"id":9963,"desc":"Blacksmith."}, + {"name":"Trothyd Fletcher","type":"Vendor","wcid":662,"cell":"C88C0165","place":"building","ns":10.52,"ew":58.38,"id":9964,"desc":"Bowyer."}, + {"name":"Ynarre the Grocer","type":"Vendor","wcid":663,"cell":"C88C0105","place":"building","ns":10.23,"ew":58.5,"id":9965,"desc":"Grocer."}, + {"name":"Brisin the Healer","type":"Vendor","wcid":664,"cell":"C88C012D","place":"building","ns":10.79,"ew":58.42,"id":9966,"desc":"Healer."}, + {"name":"Urnolt the Jeweler","type":"Vendor","wcid":665,"cell":"C88C0114","place":"building","ns":10.6,"ew":58.38,"id":9967,"desc":"Jeweler."}, + {"name":"Dortold the Tailor","type":"Vendor","wcid":667,"cell":"C88C016B","place":"building","ns":10.38,"ew":58.18,"id":9968,"desc":"Tailor."}, + {"name":"Weaponsmith Baizai En","type":"Vendor","wcid":668,"cell":"C88C0156","place":"building","ns":10.31,"ew":58.28,"id":9969,"desc":"Weaponsmith."}, + {"name":"Wylreda the Scribe","type":"Vendor","wcid":666,"cell":"C88C0114","place":"building","ns":10.62,"ew":58.38,"id":9970,"desc":"Scribe."}, + {"name":"Celcynd the Dour","type":"NPC","wcid":4795,"cell":"C88C014A","place":"building","ns":10.66,"ew":58.12,"id":9971,"desc":"Society Agent."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":20225,"cell":"C88C0176","place":"building","ns":10.39,"ew":58.4,"id":9972,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":20213,"cell":"C88C0173","place":"building","ns":10.41,"ew":58.39,"id":9973,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":20209,"cell":"C88C017B","place":"building","ns":10.39,"ew":58.39,"id":9974,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":20221,"cell":"C88C017A","place":"building","ns":10.41,"ew":58.41,"id":9975,"desc":"Master Archmage."}, + {"name":"Astara Duskshield","type":"NPC","wcid":23348,"cell":"C88C0000","place":"outdoor","ns":10.33,"ew":58.31,"id":9976,"desc":"Aluvian Female."}, + {"name":"Tackle Master","type":"NPC","wcid":23336,"cell":"C88C0184","place":"building","ns":10.68,"ew":58.72,"id":9977,"desc":"Pro Fisherman."}, + {"name":"Apprentice Fletcher","type":"NPC","wcid":27746,"cell":"C88C016B","place":"building","ns":10.38,"ew":58.2,"id":9978}, + {"name":"Royal Guard Gabrielle","type":"NPC","wcid":27689,"cell":"C88C0000","place":"outdoor","ns":10.48,"ew":58.24,"id":9979,"desc":"Guard."}, + {"name":"Mesalina","type":"NPC","wcid":42982,"cell":"C88C010A","place":"building","ns":10.2,"ew":58.47,"id":9980,"desc":"Traitor to the Crown."}, + {"name":"Yuudai","type":"NPC","wcid":42981,"cell":"C88C010A","place":"building","ns":10.2,"ew":58.47,"id":9981}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"C88D0000","place":"outdoor","ns":10.89,"ew":58.24,"id":9982}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C8A90000","place":"outdoor","ns":33.94,"ew":58.17,"id":9983}, + {"name":"Shade of Farelaith","type":"NPC","wcid":32493,"cell":"C8DC002B","place":"outdoor","ns":74.3,"ew":58.6,"id":9984,"desc":"Tormented Soul."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C8E9002A","place":"outdoor","ns":84.61,"ew":58.6,"id":9985}, + {"name":"Tyrina of Arwic","type":"NPC","wcid":33673,"cell":"C8E90100","place":"building","ns":84.71,"ew":58.69,"id":9986,"desc":"Soldier."}, + {"name":"Honshu Takeda","type":"NPC","wcid":25826,"cell":"C91E0000","place":"outdoor","ns":-77.69,"ew":59.23,"id":9987,"desc":"Adherent."}, + {"name":"Linvak Gatestone","type":"NPC","wcid":39312,"cell":"C92E0100","place":"building","ns":-64.8,"ew":59.3,"id":9988}, + {"name":"Linvak Node Golem","type":"NPC","wcid":38206,"cell":"C92E0024","place":"outdoor","ns":-64.84,"ew":59.29,"id":9989,"desc":"Node Guardian."}, + {"name":"Shopkeep Yunen Ye","type":"Vendor","wcid":2300,"cell":"C95B0155","place":"building","ns":-28.62,"ew":59.18,"id":9990,"desc":"Shopkeeper."}, + {"name":"Ite Kenzen the Barkeeper","type":"Vendor","wcid":2291,"cell":"C95B0121","place":"building","ns":-28.8,"ew":59.18,"id":9991,"desc":"Barkeeper."}, + {"name":"Grocer Pon Hau-jo","type":"Vendor","wcid":2296,"cell":"C95B0112","place":"building","ns":-28.5,"ew":59.24,"id":9992,"desc":"Grocer."}, + {"name":"Chueh Kaigin the Jeweler","type":"Vendor","wcid":2298,"cell":"C95B015E","place":"building","ns":-28.78,"ew":59.41,"id":9993,"desc":"Jeweler."}, + {"name":"Hiruhi Fensen the Scribe","type":"Vendor","wcid":2299,"cell":"C95B0146","place":"building","ns":-28.73,"ew":59.5,"id":9994,"desc":"Scribe."}, + {"name":"To-ping Ra the Tailor","type":"Vendor","wcid":2301,"cell":"C95B0113","place":"building","ns":-28.49,"ew":59.16,"id":9995,"desc":"Tailor."}, + {"name":"Bukai Fu-ya the Bowyer","type":"Vendor","wcid":2295,"cell":"C95B0106","place":"building","ns":-28.57,"ew":59.39,"id":9996,"desc":"Bowyer."}, + {"name":"Healer Xidan Fensen","type":"Vendor","wcid":2297,"cell":"C95B0147","place":"building","ns":-28.66,"ew":59.48,"id":9997,"desc":"Healer."}, + {"name":"Archmage Tawa Matema","type":"Vendor","wcid":2290,"cell":"C95B0142","place":"building","ns":-28.4,"ew":59.57,"id":9998,"desc":"Archmage."}, + {"name":"Tong La-chin the Weaponsmith","type":"Vendor","wcid":2293,"cell":"C95B0123","place":"building","ns":-28.87,"ew":59.29,"id":9999,"desc":"Blacksmith."}, + {"name":"Son Jaiken the Armorer","type":"Vendor","wcid":2294,"cell":"C95B0123","place":"building","ns":-28.87,"ew":59.32,"id":10000,"desc":"Blacksmith."}, + {"name":"Tsua Kagemata","type":"NPC","wcid":8402,"cell":"C95B0158","place":"building","ns":-28.78,"ew":59.38,"id":10001,"desc":"Mask Maker."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"C95B0162","place":"building","ns":-28.82,"ew":59.08,"id":10002,"desc":"Mage."}, + {"name":"Tsua's Apprentice","type":"NPC","wcid":12205,"cell":"C95B0158","place":"building","ns":-28.77,"ew":59.38,"id":10003,"desc":"Apprentice Mask Maker."}, + {"name":"Ro Bi-Jor, Apprentice Tailor","type":"NPC","wcid":24160,"cell":"C95B0113","place":"building","ns":-28.53,"ew":59.17,"id":10004,"desc":"Apprentice Tailor."}, + {"name":"Jojii Shrine","type":"NPC","wcid":25830,"cell":"C95B0000","place":"outdoor","ns":-28.68,"ew":59.18,"id":10005}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C95B0000","place":"outdoor","ns":-28.79,"ew":59.31,"id":10006}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"C95B0000","place":"outdoor","ns":-28.51,"ew":59.33,"id":10007}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"C95B016B","place":"building","ns":-29.01,"ew":59.48,"id":10008,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"C95B016B","place":"building","ns":-29.01,"ew":59.51,"id":10009,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"C95B0171","place":"building","ns":-28.98,"ew":59.49,"id":10010,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"C95B016C","place":"building","ns":-29.01,"ew":59.49,"id":10011,"desc":"Master Archmage."}, + {"name":"Apprentice Fletcher","type":"NPC","wcid":28190,"cell":"C95B010D","place":"building","ns":-28.63,"ew":59.41,"id":10012}, + {"name":"Sergeant Huang","type":"NPC","wcid":33839,"cell":"C95B0131","place":"building","ns":-28.92,"ew":59.34,"id":10013,"desc":"Ryu Jou Gai Apprentice."}, + {"name":"Hasin Lin","type":"NPC","wcid":34305,"cell":"C95B0023","place":"outdoor","ns":-28.89,"ew":59.35,"id":10014,"desc":"Tracker."}, + {"name":"Nomendar al-Rakh","type":"NPC","wcid":37089,"cell":"C95B001E","place":"outdoor","ns":-28.65,"ew":59.17,"id":10015,"desc":"Geomancer."}, + {"name":"Pau Yajin","type":"NPC","wcid":35853,"cell":"C95B002C","place":"outdoor","ns":-28.82,"ew":59.41,"id":10016,"desc":"Dowser."}, + {"name":"Sign","type":"NPC","wcid":40528,"cell":"C95B0040","place":"outdoor","ns":-28.4,"ew":59.64,"id":10017}, + {"name":"Erludd the Cur the Barkeeper","type":"Vendor","wcid":1082,"cell":"C98C011B","place":"building","ns":10.79,"ew":59.4,"id":10018,"desc":"Barkeeper."}, + {"name":"Soldona Wotmad the Jeweler","type":"Vendor","wcid":1081,"cell":"C98C0109","place":"building","ns":10.77,"ew":59.32,"id":10019,"desc":"Jeweler."}, + {"name":"Ji Tenxien the Tailor","type":"Vendor","wcid":1080,"cell":"C98C0130","place":"building","ns":10.72,"ew":59.18,"id":10020,"desc":"Tailor."}, + {"name":"Archmage Nulsymber","type":"Vendor","wcid":2305,"cell":"C98C0000","place":"outdoor","ns":10.8,"ew":59.3,"id":10021,"desc":"Archmage."}, + {"name":"Weary-looking Man","type":"Vendor","wcid":2049,"cell":"C98C011D","place":"building","ns":10.8,"ew":59.36,"id":10022,"desc":"Peddler."}, + {"name":"Delton Hardor","type":"NPC","wcid":23349,"cell":"C98C0128","place":"building","ns":10.76,"ew":59.41,"id":10023,"desc":"Dashing Swordsman."}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98C0000","place":"outdoor","ns":10.74,"ew":58.98,"id":10024}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98C0000","place":"outdoor","ns":10.74,"ew":58.92,"id":10025}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98C0000","place":"outdoor","ns":10.47,"ew":58.97,"id":10026}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98C0000","place":"outdoor","ns":10.48,"ew":58.94,"id":10027}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98C0000","place":"outdoor","ns":10.56,"ew":58.98,"id":10028}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98C0000","place":"outdoor","ns":10.49,"ew":59.0,"id":10029}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98C0000","place":"outdoor","ns":10.64,"ew":58.93,"id":10030}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98C0000","place":"outdoor","ns":10.67,"ew":58.97,"id":10031}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98C0000","place":"outdoor","ns":10.73,"ew":58.95,"id":10032}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98C0000","place":"outdoor","ns":10.7,"ew":58.95,"id":10033}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98C0000","place":"outdoor","ns":10.68,"ew":58.92,"id":10034}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C98D0000","place":"outdoor","ns":11.23,"ew":59.41,"id":10035}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":10.86,"ew":58.93,"id":10036}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":10.86,"ew":58.98,"id":10037}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":11.01,"ew":58.95,"id":10038}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":11.04,"ew":58.97,"id":10039}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":11.08,"ew":58.94,"id":10040}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":11.05,"ew":58.93,"id":10041}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":11.13,"ew":58.94,"id":10042}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":11.16,"ew":58.98,"id":10043}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":11.18,"ew":58.91,"id":10044}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":11.21,"ew":58.91,"id":10045}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":11.22,"ew":58.87,"id":10046}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"C98D0000","place":"outdoor","ns":10.87,"ew":58.95,"id":10047}, + {"name":"Merwart Pelagurg","type":"NPC","wcid":32122,"cell":"C9E20007","place":"outdoor","ns":79.53,"ew":58.91,"id":10048,"desc":"Maw Crafter."}, + {"name":"Archmage Moldurg","type":"Vendor","wcid":32056,"cell":"C9E30105","place":"building","ns":79.89,"ew":59.18,"id":10049,"desc":"Archmage."}, + {"name":"Healer Hargurg","type":"Vendor","wcid":32053,"cell":"C9E30105","place":"building","ns":79.91,"ew":59.18,"id":10050,"desc":"Healer."}, + {"name":"Barkeep Guzglurg","type":"Vendor","wcid":32299,"cell":"C9E3000B","place":"outdoor","ns":79.87,"ew":58.97,"id":10051,"desc":"Barkeep."}, + {"name":"Shopkeeper Hulmurg","type":"Vendor","wcid":32054,"cell":"C9E30013","place":"outdoor","ns":79.92,"ew":59.06,"id":10052,"desc":"Shopkeeper."}, + {"name":"Blacksmith Bulidurg","type":"Vendor","wcid":32055,"cell":"C9E30013","place":"outdoor","ns":79.88,"ew":59.09,"id":10053,"desc":"Blacksmith."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"C9E3002E","place":"outdoor","ns":80.2,"ew":59.41,"id":10054}, + {"name":"Merwart Gurglurg","type":"NPC","wcid":32052,"cell":"C9E30015","place":"outdoor","ns":80.06,"ew":59.13,"id":10055,"desc":"Younger Brother."}, + {"name":"Merwart Urglurg","type":"NPC","wcid":32051,"cell":"C9E30015","place":"outdoor","ns":80.06,"ew":59.08,"id":10056,"desc":"Older Brother."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"CA400000","place":"outdoor","ns":-50.51,"ew":59.85,"id":10057}, + {"name":"Blacksmith","type":"Vendor","wcid":1377,"cell":"CA420116","place":"building","ns":-48.58,"ew":60.0,"id":10058}, + {"name":"Merchant","type":"Vendor","wcid":1388,"cell":"CA420114","place":"building","ns":-48.58,"ew":59.98,"id":10059}, + {"name":"Healer","type":"Vendor","wcid":1386,"cell":"CA540000","place":"outdoor","ns":-34.64,"ew":59.72,"id":10060}, + {"name":"Exploration Marker","type":"NPC","wcid":39847,"cell":"CAAC0003","place":"outdoor","ns":35.91,"ew":59.69,"id":10061}, + {"name":"Exploration Marker","type":"NPC","wcid":39756,"cell":"CAC0000A","place":"outdoor","ns":51.8,"ew":59.81,"id":10062}, + {"name":"Rock","type":"NPC","wcid":38777,"cell":"CAEC0009","place":"outdoor","ns":86.91,"ew":59.77,"id":10063}, + {"name":"Exploration Marker","type":"NPC","wcid":39776,"cell":"CAEC0009","place":"outdoor","ns":86.89,"ew":59.82,"id":10064}, + {"name":"Drunken Madman","type":"NPC","wcid":4201,"cell":"CB3D0000","place":"outdoor","ns":-53.04,"ew":61.02,"id":10065,"desc":"Enchanter."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"CB530000","place":"outdoor","ns":-34.81,"ew":60.53,"id":10066}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"CB530000","place":"outdoor","ns":-35.06,"ew":60.54,"id":10067}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"CB5B0000","place":"outdoor","ns":-28.86,"ew":60.58,"id":10068}, + {"name":"Hydeatha the Shopkeeper","type":"Vendor","wcid":4448,"cell":"CC8C0103","place":"building","ns":10.22,"ew":61.42,"id":10069,"desc":"Shopkeeper."}, + {"name":"Mindorla","type":"NPC","wcid":4796,"cell":"CC8C010A","place":"building","ns":10.2,"ew":61.42,"id":10070,"desc":"Citizen of Rithwic."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"CC8C0000","place":"outdoor","ns":10.37,"ew":61.39,"id":10071}, + {"name":"Exploration Marker","type":"NPC","wcid":39767,"cell":"CC97002A","place":"outdoor","ns":19.04,"ew":61.77,"id":10072}, + {"name":"Farmer","type":"Vendor","wcid":1381,"cell":"CC9A0100","place":"building","ns":21.72,"ew":61.61,"id":10073}, + {"name":"Magus Ku Min","type":"Vendor","wcid":2250,"cell":"CD400103","place":"building","ns":-50.02,"ew":62.5,"id":10074,"desc":"Archmage."}, + {"name":"Nuru Misho the Jeweler","type":"Vendor","wcid":2257,"cell":"CD410140","place":"building","ns":-49.57,"ew":62.28,"id":10075,"desc":"Jeweler."}, + {"name":"Shen Ai-Shen the Weaponsmith","type":"Vendor","wcid":2261,"cell":"CD41016A","place":"building","ns":-49.29,"ew":62.33,"id":10076,"desc":"Weaponsmith."}, + {"name":"Lobu Shui the Armorer","type":"Vendor","wcid":2251,"cell":"CD41016A","place":"building","ns":-49.31,"ew":62.33,"id":10077,"desc":"Armorer."}, + {"name":"Kiun Baicho the Barkeeper","type":"Vendor","wcid":2252,"cell":"CD410100","place":"building","ns":-49.48,"ew":62.73,"id":10078,"desc":"Barkeeper."}, + {"name":"Denki Sokuto the Scribe","type":"Vendor","wcid":2258,"cell":"CD410158","place":"building","ns":-49.59,"ew":62.47,"id":10079,"desc":"Scribe."}, + {"name":"Tailor Zhoyong Wa-son","type":"Vendor","wcid":2260,"cell":"CD41012B","place":"building","ns":-49.41,"ew":62.41,"id":10080,"desc":"Tailor."}, + {"name":"Shopkeep Ginan Wah","type":"Vendor","wcid":2259,"cell":"CD41010E","place":"building","ns":-49.39,"ew":62.63,"id":10081,"desc":"Shopkeeper."}, + {"name":"Bowyer Jyi Zhente","type":"Vendor","wcid":2254,"cell":"CD410150","place":"building","ns":-49.68,"ew":62.39,"id":10082,"desc":"Bowyer."}, + {"name":"Muoyen Han the Grocer","type":"Vendor","wcid":2255,"cell":"CD410169","place":"building","ns":-49.29,"ew":62.53,"id":10083,"desc":"Grocer."}, + {"name":"Healer Fan Lun-Kou","type":"Vendor","wcid":2256,"cell":"CD41011E","place":"building","ns":-49.63,"ew":62.58,"id":10084,"desc":"Healer."}, + {"name":"Spice Merchant Chiani","type":"Vendor","wcid":6082,"cell":"CD410168","place":"building","ns":-49.3,"ew":62.47,"id":10085,"desc":"Spice Merchant."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"CD410184","place":"building","ns":-49.72,"ew":62.61,"id":10086,"desc":"Mage."}, + {"name":"Lia Tze","type":"NPC","wcid":15811,"cell":"CD410125","place":"building","ns":-49.39,"ew":62.42,"id":10087,"desc":"Art Historian."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"CD410000","place":"outdoor","ns":-49.6,"ew":62.4,"id":10088}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"CD410000","place":"outdoor","ns":-49.46,"ew":62.3,"id":10089}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"CD410199","place":"building","ns":-49.22,"ew":62.71,"id":10090,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"CD4101A3","place":"building","ns":-49.21,"ew":62.67,"id":10091,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"CD410193","place":"building","ns":-49.23,"ew":62.68,"id":10092,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"CD410193","place":"building","ns":-49.19,"ew":62.72,"id":10093,"desc":"Master Archmage."}, + {"name":"Derethian Combat Arena","type":"NPC","wcid":44823,"cell":"CD41002D","place":"outdoor","ns":-49.52,"ew":62.58,"id":10094}, + {"name":"Worshipper of Bael'Zharon","type":"NPC","wcid":52992,"cell":"CD41002D","place":"outdoor","ns":-49.49,"ew":62.6,"id":10095,"desc":"Crystal of Increasing Pain Trader."}, + {"name":"Worshipper of Bael'Zharon","type":"NPC","wcid":52991,"cell":"CD41002D","place":"outdoor","ns":-49.5,"ew":62.6,"id":10096,"desc":"Crystal of Twisting Wounds Trader."}, + {"name":"Worshipper of Bael'Zharon","type":"NPC","wcid":52990,"cell":"CD41002D","place":"outdoor","ns":-49.5,"ew":62.59,"id":10097,"desc":"Molten Coal Trader."}, + {"name":"Derethian Combat Arena Master","type":"NPC","wcid":40772,"cell":"CD41002D","place":"outdoor","ns":-49.54,"ew":62.59,"id":10098}, + {"name":"Fiona Woron","type":"NPC","wcid":41311,"cell":"CD410105","place":"building","ns":-49.49,"ew":62.71,"id":10099}, + {"name":"Ries Woron","type":"NPC","wcid":40897,"cell":"CD410105","place":"building","ns":-49.49,"ew":62.7,"id":10100}, + {"name":"Carolyn Woron","type":"NPC","wcid":40895,"cell":"CD410105","place":"building","ns":-49.48,"ew":62.7,"id":10101}, + {"name":"Fergal the Dire","type":"NPC","wcid":31652,"cell":"CD41001E","place":"outdoor","ns":-49.42,"ew":62.44,"id":10102,"desc":"Dire Mattekar Dispatcher."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"CD96003E","place":"outdoor","ns":18.58,"ew":62.77,"id":10103}, + {"name":"Alean the Steel Forger","type":"Vendor","wcid":51154,"cell":"CD96003D","place":"outdoor","ns":18.55,"ew":62.8,"id":10104,"desc":"Master Armorer."}, + {"name":"Lartorus","type":"NPC","wcid":23039,"cell":"CDB40000","place":"outdoor","ns":42.6,"ew":62.38,"id":10105,"desc":"Noble."}, + {"name":"Eluard the Namer","type":"NPC","wcid":9544,"cell":"CE940100","place":"building","ns":16.99,"ew":63.31,"id":10106,"desc":"Bestower Examiner."}, + {"name":"Caranis the Dependable","type":"Vendor","wcid":9615,"cell":"CE940100","place":"building","ns":17.01,"ew":63.29,"id":10107,"desc":"Bestower Representative."}, + {"name":"Aun Tiulerea","type":"NPC","wcid":27264,"cell":"CE940000","place":"outdoor","ns":16.48,"ew":63.58,"id":10108,"desc":"Iron Golem Hunter."}, + {"name":"Byrdara the Barkeeper","type":"Vendor","wcid":648,"cell":"CE95012D","place":"building","ns":17.71,"ew":63.23,"id":10109,"desc":"Barkeeper."}, + {"name":"Getram the Armorer","type":"Vendor","wcid":649,"cell":"CE95013E","place":"building","ns":17.41,"ew":63.5,"id":10110,"desc":"Armor Smith."}, + {"name":"Rundiscar the Weaponsmith","type":"Vendor","wcid":650,"cell":"CE950142","place":"building","ns":17.38,"ew":63.5,"id":10111,"desc":"Blacksmith."}, + {"name":"Bowyer Bronwin","type":"Vendor","wcid":651,"cell":"CE950102","place":"building","ns":17.31,"ew":63.22,"id":10112,"desc":"Bowyer."}, + {"name":"Grocer Parsal","type":"Vendor","wcid":652,"cell":"CE950136","place":"building","ns":17.52,"ew":63.49,"id":10113,"desc":"Grocer."}, + {"name":"Cynsela the Tailor","type":"Vendor","wcid":658,"cell":"CE950136","place":"building","ns":17.53,"ew":63.48,"id":10114,"desc":"Tailor."}, + {"name":"Degel Parson the Scrivener","type":"Vendor","wcid":654,"cell":"CE95013A","place":"building","ns":17.52,"ew":63.49,"id":10115,"desc":"Scribe."}, + {"name":"Sodyla Thurmad the Healer","type":"Vendor","wcid":653,"cell":"CE950117","place":"building","ns":17.29,"ew":63.41,"id":10116,"desc":"Healer."}, + {"name":"Farnum the Provisioner","type":"Vendor","wcid":656,"cell":"CE95014F","place":"building","ns":17.8,"ew":63.5,"id":10117,"desc":"Shopkeeper."}, + {"name":"Aderma the Lapidary","type":"Vendor","wcid":655,"cell":"CE950111","place":"building","ns":17.89,"ew":63.32,"id":10118,"desc":"Jeweler."}, + {"name":"Weary-looking Man","type":"Vendor","wcid":2048,"cell":"CE950000","place":"outdoor","ns":17.53,"ew":63.39,"id":10119,"desc":"Peddler."}, + {"name":"Belbeca the Archmage","type":"Vendor","wcid":2302,"cell":"CE950117","place":"building","ns":17.29,"ew":63.44,"id":10120,"desc":"Archmage."}, + {"name":"Alexander the Deft","type":"NPC","wcid":8404,"cell":"CE95013F","place":"building","ns":17.38,"ew":63.49,"id":10121,"desc":"Mask Maker."}, + {"name":"Olivier Rognath","type":"NPC","wcid":8362,"cell":"CE950000","place":"outdoor","ns":17.53,"ew":63.31,"id":10122,"desc":"Trophy Collector."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"CE950163","place":"building","ns":17.37,"ew":62.91,"id":10123,"desc":"Mage."}, + {"name":"Alexander's Apprentice","type":"NPC","wcid":12203,"cell":"CE95013F","place":"building","ns":17.36,"ew":63.5,"id":10124,"desc":"Apprentice Mask Maker."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"CE95016C","place":"building","ns":17.59,"ew":63.09,"id":10125,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"CE95016C","place":"building","ns":17.6,"ew":63.09,"id":10126,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"CE95016C","place":"building","ns":17.6,"ew":63.11,"id":10127,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"CE95016C","place":"building","ns":17.59,"ew":63.11,"id":10128,"desc":"Master Archmage."}, + {"name":"Samuel, Former Guardian","type":"NPC","wcid":25896,"cell":"CE95012E","place":"building","ns":17.69,"ew":63.17,"id":10129,"desc":"Senior Guard."}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"CE950000","place":"outdoor","ns":17.65,"ew":63.51,"id":10130}, + {"name":"Apprentice Fletcher","type":"NPC","wcid":28188,"cell":"CE950102","place":"building","ns":17.31,"ew":63.2,"id":10131}, + {"name":"Asheron's Investigator","type":"NPC","wcid":39288,"cell":"CE950034","place":"outdoor","ns":17.6,"ew":63.48,"id":10132,"desc":"Emissary of Asheron."}, + {"name":"Hei Shou","type":"NPC","wcid":41227,"cell":"CE95013A","place":"building","ns":17.52,"ew":63.47,"id":10133,"desc":"Arcanum Researcher."}, + {"name":"Archmage","type":"Vendor","wcid":1369,"cell":"CE9C0100","place":"building","ns":23.61,"ew":63.3,"id":10134}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"CF180000","place":"outdoor","ns":-82.12,"ew":63.67,"id":10135}, + {"name":"Archmage","type":"Vendor","wcid":1371,"cell":"CF180000","place":"outdoor","ns":-82.07,"ew":63.71,"id":10136}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"CF180000","place":"outdoor","ns":-82.08,"ew":63.71,"id":10137}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"CF950000","place":"outdoor","ns":17.81,"ew":64.26,"id":10138}, + {"name":"Emissary of Asheron","type":"NPC","wcid":19714,"cell":"CF950000","place":"outdoor","ns":17.87,"ew":64.32,"id":10139,"desc":"Emissary."}, + {"name":"Merchant","type":"Vendor","wcid":1387,"cell":"CFA00102","place":"building","ns":26.31,"ew":63.8,"id":10140}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"CFA10000","place":"outdoor","ns":27.39,"ew":63.79,"id":10141}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"D0550000","place":"outdoor","ns":-33.9,"ew":64.88,"id":10142}, + {"name":"Healer","type":"Vendor","wcid":1386,"cell":"D05E0107","place":"dungeon","id":10143,"desc":"In a dungeon (landblock D05E)."}, + {"name":"Life Stone","type":"Lifestone","wcid":23618,"cell":"D1D70012","place":"outdoor","ns":70.18,"ew":65.51,"id":10144}, + {"name":"Watcher of the Deep","type":"NPC","wcid":31966,"cell":"D1D7000B","place":"outdoor","ns":70.28,"ew":65.39,"id":10145}, + {"name":"Enchanted Mnemosyne","type":"NPC","wcid":43841,"cell":"D2A80034","place":"outdoor","ns":32.79,"ew":66.69,"id":10146}, + {"name":"The Deep","type":"NPC","wcid":31933,"cell":"D3E00100","place":"building","ns":77.81,"ew":67.1,"id":10147}, + {"name":"Dayla Bint Kazm","type":"NPC","wcid":31932,"cell":"D3E00016","place":"outdoor","ns":77.79,"ew":67.13,"id":10148,"desc":"Disciple."}, + {"name":"Colista Fluress","type":"NPC","wcid":31934,"cell":"D3E00016","place":"outdoor","ns":77.78,"ew":67.11,"id":10149,"desc":"Disciple."}, + {"name":"Peng-Ya","type":"NPC","wcid":31930,"cell":"D3E00016","place":"outdoor","ns":77.78,"ew":67.08,"id":10150,"desc":"Disciple."}, + {"name":"Algar Oreksun","type":"NPC","wcid":31931,"cell":"D3E00016","place":"outdoor","ns":77.79,"ew":67.07,"id":10151,"desc":"Disciple."}, + {"name":"Exploration Marker","type":"NPC","wcid":39782,"cell":"D43E0009","place":"outdoor","ns":-52.31,"ew":67.84,"id":10152}, + {"name":"Farmer","type":"Vendor","wcid":1383,"cell":"D44F0000","place":"outdoor","ns":-38.12,"ew":68.09,"id":10153}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"D45C0000","place":"outdoor","ns":-27.84,"ew":68.32,"id":10154}, + {"name":"Weapon Tinkering Warden of Enlightenment","type":"NPC","wcid":32450,"cell":"D5990038","place":"outdoor","ns":21.21,"ew":69.15,"id":10155}, + {"name":"War Magic Warden of Enlightenment","type":"NPC","wcid":32449,"cell":"D5990038","place":"outdoor","ns":21.15,"ew":69.09,"id":10156}, + {"name":"Void Magic Warden of Enlightenment","type":"NPC","wcid":43399,"cell":"D5990037","place":"outdoor","ns":21.14,"ew":69.09,"id":10157}, + {"name":"Two Handed Combat Warden of Enlightenment","type":"NPC","wcid":41741,"cell":"D5990037","place":"outdoor","ns":21.13,"ew":69.09,"id":10158}, + {"name":"Summoning Warden of Enlightenment","type":"NPC","wcid":49483,"cell":"D5990037","place":"outdoor","ns":21.11,"ew":69.09,"id":10159}, + {"name":"Shield Warden of Enlightenment","type":"NPC","wcid":45393,"cell":"D5990037","place":"outdoor","ns":21.08,"ew":69.09,"id":10160}, + {"name":"Run Warden of Enlightenment","type":"NPC","wcid":32443,"cell":"D5990037","place":"outdoor","ns":21.07,"ew":69.09,"id":10161}, + {"name":"Recklessness Warden of Enlightenment","type":"NPC","wcid":45392,"cell":"D5990037","place":"outdoor","ns":21.05,"ew":69.09,"id":10162}, + {"name":"Missile Weapons Warden of Enlightenment","type":"NPC","wcid":32455,"cell":"D5990036","place":"outdoor","ns":21.04,"ew":69.09,"id":10163}, + {"name":"Magic Item Tinkering Warden of Enlightenment","type":"NPC","wcid":32438,"cell":"D599003E","place":"outdoor","ns":20.99,"ew":69.16,"id":10164}, + {"name":"Magic Defense Warden of Enlightenment","type":"NPC","wcid":32437,"cell":"D599003E","place":"outdoor","ns":20.99,"ew":69.17,"id":10165}, + {"name":"Missile Defense Warden of Enlightenment","type":"NPC","wcid":32441,"cell":"D5990036","place":"outdoor","ns":21.02,"ew":69.09,"id":10166}, + {"name":"Melee Defense Warden of Enlightenment","type":"NPC","wcid":32440,"cell":"D5990036","place":"outdoor","ns":20.99,"ew":69.13,"id":10167}, + {"name":"Mana Conversion Warden of Enlightenment","type":"NPC","wcid":32439,"cell":"D5990036","place":"outdoor","ns":20.99,"ew":69.14,"id":10168}, + {"name":"Loyalty Warden of Enlightenment","type":"NPC","wcid":32470,"cell":"D599003E","place":"outdoor","ns":20.99,"ew":69.19,"id":10169}, + {"name":"Lockpick Warden of Enlightenment","type":"NPC","wcid":32469,"cell":"D599003E","place":"outdoor","ns":20.99,"ew":69.2,"id":10170}, + {"name":"Light Weapons Warden of Enlightenment","type":"NPC","wcid":32454,"cell":"D599003E","place":"outdoor","ns":20.99,"ew":69.22,"id":10171}, + {"name":"Life Magic Warden of Enlightenment","type":"NPC","wcid":32468,"cell":"D599003E","place":"outdoor","ns":20.99,"ew":69.23,"id":10172}, + {"name":"Leadership Warden of Enlightenment","type":"NPC","wcid":32467,"cell":"D599003E","place":"outdoor","ns":20.99,"ew":69.25,"id":10173}, + {"name":"Arcane Lore Warden of Enlightenment","type":"NPC","wcid":32452,"cell":"D5990040","place":"outdoor","ns":21.21,"ew":69.24,"id":10174}, + {"name":"Alchemy Warden of Enlightenment","type":"NPC","wcid":32451,"cell":"D5990040","place":"outdoor","ns":21.21,"ew":69.22,"id":10175}, + {"name":"Warden of Raising Self","type":"NPC","wcid":44916,"cell":"D5990040","place":"outdoor","ns":21.18,"ew":69.22,"id":10176}, + {"name":"Sneak Attack Warden of Enlightenment","type":"NPC","wcid":45394,"cell":"D5990037","place":"outdoor","ns":21.1,"ew":69.09,"id":10177}, + {"name":"Warden of Raising Focus","type":"NPC","wcid":44914,"cell":"D5990040","place":"outdoor","ns":21.18,"ew":69.23,"id":10178}, + {"name":"Warden of Raising Quickness","type":"NPC","wcid":44915,"cell":"D5990040","place":"outdoor","ns":21.18,"ew":69.24,"id":10179}, + {"name":"Strange Device","type":"NPC","wcid":36779,"cell":"D5990040","place":"outdoor","ns":21.24,"ew":69.23,"id":10180}, + {"name":"Emissary of Asheron","type":"NPC","wcid":45770,"cell":"D599003F","place":"outdoor","ns":21.14,"ew":69.22,"id":10181,"desc":"Emissary."}, + {"name":"Asheron","type":"NPC","wcid":43183,"cell":"D599003F","place":"outdoor","ns":21.13,"ew":69.23,"id":10182,"desc":"Master of the Lyceum."}, + {"name":"Fianhe","type":"NPC","wcid":43941,"cell":"D599003F","place":"outdoor","ns":21.06,"ew":69.15,"id":10183}, + {"name":"Ayaname Kina","type":"NPC","wcid":37074,"cell":"D5990140","place":"building","ns":21.09,"ew":69.12,"id":10184,"desc":"Hoshino Kei's Handmaiden."}, + {"name":"Emissary of Asheron","type":"NPC","wcid":37065,"cell":"D599014C","place":"building","ns":21.22,"ew":69.08,"id":10185,"desc":"Emissary."}, + {"name":"Asheron's Servant","type":"NPC","wcid":33546,"cell":"D599014D","place":"building","ns":21.21,"ew":69.07,"id":10186,"desc":"Guardian of the White Tower."}, + {"name":"Exploration Marker","type":"NPC","wcid":39801,"cell":"D599011F","place":"building","ns":21.22,"ew":69.19,"id":10187}, + {"name":"Shrine to Xik Minru","type":"NPC","wcid":31975,"cell":"D5DA002E","place":"outdoor","ns":73.0,"ew":69.01,"id":10188}, + {"name":"Shrine to Xik Minru","type":"NPC","wcid":31975,"cell":"D5DA001E","place":"outdoor","ns":73.0,"ew":68.8,"id":10189}, + {"name":"Shrine to Xik Minru","type":"NPC","wcid":31975,"cell":"D5DA002C","place":"outdoor","ns":72.79,"ew":69.0,"id":10190}, + {"name":"Shrine to Xik Minru","type":"NPC","wcid":31975,"cell":"D5DA001C","place":"outdoor","ns":72.81,"ew":68.79,"id":10191}, + {"name":"Nen Gou the Shopkeeper","type":"Vendor","wcid":4560,"cell":"D6550000","place":"outdoor","ns":-33.53,"ew":69.89,"id":10192,"desc":"Shopkeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"D6550000","place":"outdoor","ns":-33.61,"ew":69.88,"id":10193}, + {"name":"Sentry","type":"NPC","wcid":12725,"cell":"D6550116","place":"building","ns":-33.81,"ew":69.51,"id":10194,"desc":"Soldier."}, + {"name":"Armor Tinkering Warden of Enlightenment","type":"NPC","wcid":32453,"cell":"D6990008","place":"outdoor","ns":21.21,"ew":69.26,"id":10195}, + {"name":"Assess Person Warden of Enlightenment","type":"NPC","wcid":32442,"cell":"D6990008","place":"outdoor","ns":21.18,"ew":69.31,"id":10196}, + {"name":"Item Tinkering Warden of Enlightenment","type":"NPC","wcid":32464,"cell":"D6990006","place":"outdoor","ns":21.03,"ew":69.31,"id":10197}, + {"name":"Jump Warden of Enlightenment","type":"NPC","wcid":32466,"cell":"D6990006","place":"outdoor","ns":20.99,"ew":69.26,"id":10198}, + {"name":"Heavy Weapons Warden of Enlightenment","type":"NPC","wcid":32446,"cell":"D6990006","place":"outdoor","ns":21.04,"ew":69.31,"id":10199}, + {"name":"Item Enchantment Warden of Enlightenment","type":"NPC","wcid":32465,"cell":"D6990006","place":"outdoor","ns":20.99,"ew":69.27,"id":10200}, + {"name":"Healing Warden of Enlightenment","type":"NPC","wcid":32463,"cell":"D6990007","place":"outdoor","ns":21.06,"ew":69.31,"id":10201}, + {"name":"Fletching Warden of Enlightenment","type":"NPC","wcid":32462,"cell":"D6990007","place":"outdoor","ns":21.07,"ew":69.31,"id":10202}, + {"name":"Finesse Weapons Warden of Enlightenment","type":"NPC","wcid":32460,"cell":"D6990007","place":"outdoor","ns":21.09,"ew":69.31,"id":10203}, + {"name":"Dual Wield Warden of Enlightenment","type":"NPC","wcid":45391,"cell":"D6990007","place":"outdoor","ns":21.1,"ew":69.31,"id":10204}, + {"name":"Dirty Fighting Warden of Enlightenment","type":"NPC","wcid":45390,"cell":"D6990007","place":"outdoor","ns":21.12,"ew":69.31,"id":10205}, + {"name":"Cooking Warden of Enlightenment","type":"NPC","wcid":32456,"cell":"D6990008","place":"outdoor","ns":21.16,"ew":69.31,"id":10206}, + {"name":"Assess Creature Warden of Enlightenment","type":"NPC","wcid":32457,"cell":"D6990008","place":"outdoor","ns":21.21,"ew":69.27,"id":10207}, + {"name":"Warden of Raising Coordination","type":"NPC","wcid":44912,"cell":"D6990008","place":"outdoor","ns":21.18,"ew":69.25,"id":10208}, + {"name":"Deception Warden of Enlightenment","type":"NPC","wcid":32461,"cell":"D6990007","place":"outdoor","ns":21.13,"ew":69.31,"id":10209}, + {"name":"Creature Enchantment Warden of Enlightenment","type":"NPC","wcid":32458,"cell":"D6990007","place":"outdoor","ns":21.15,"ew":69.31,"id":10210}, + {"name":"Warden of Raising Endurance","type":"NPC","wcid":44913,"cell":"D6990008","place":"outdoor","ns":21.18,"ew":69.26,"id":10211}, + {"name":"Warden of Raising Strength","type":"NPC","wcid":44917,"cell":"D6990008","place":"outdoor","ns":21.18,"ew":69.27,"id":10212}, + {"name":"Warden of Lowering Self","type":"NPC","wcid":44910,"cell":"D6990007","place":"outdoor","ns":21.14,"ew":69.27,"id":10213}, + {"name":"Warden of Lowering Focus","type":"NPC","wcid":44908,"cell":"D6990007","place":"outdoor","ns":21.14,"ew":69.28,"id":10214}, + {"name":"Warden of Lowering Endurance","type":"NPC","wcid":44919,"cell":"D6990008","place":"outdoor","ns":21.16,"ew":69.28,"id":10215}, + {"name":"Warden of Lowering Strength","type":"NPC","wcid":44911,"cell":"D6990008","place":"outdoor","ns":21.17,"ew":69.29,"id":10216}, + {"name":"Warden of Lowering Quickness","type":"NPC","wcid":44909,"cell":"D6990007","place":"outdoor","ns":21.14,"ew":69.28,"id":10217}, + {"name":"Warden of Lowering Coordination","type":"NPC","wcid":44918,"cell":"D6990007","place":"outdoor","ns":21.15,"ew":69.28,"id":10218}, + {"name":"Nalicana","type":"NPC","wcid":43398,"cell":"D6990007","place":"outdoor","ns":21.06,"ew":69.27,"id":10219,"desc":"Seer of the Yalain."}, + {"name":"Chafulumisa","type":"NPC","wcid":44950,"cell":"D6990008","place":"outdoor","ns":21.18,"ew":69.28,"id":10220}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"D7690000","place":"outdoor","ns":-17.64,"ew":70.72,"id":10221}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"D7840000","place":"outdoor","ns":3.87,"ew":70.48,"id":10222}, + {"name":"Farmer","type":"Vendor","wcid":1381,"cell":"D7840000","place":"outdoor","ns":3.84,"ew":70.48,"id":10223}, + {"name":"Wandering Bowyer","type":"Vendor","wcid":1380,"cell":"D7840000","place":"outdoor","ns":3.87,"ew":70.42,"id":10224,"desc":"Bowyer."}, + {"name":"Deewain","type":"NPC","wcid":42543,"cell":"D798000D","place":"outdoor","ns":20.06,"ew":70.23,"id":10225}, + {"name":"Nen Ai","type":"NPC","wcid":5197,"cell":"D8530100","place":"building","ns":-34.77,"ew":71.18,"id":10226,"desc":"A Compassionate Woman."}, + {"name":"Wounded Drudge Skulker","type":"NPC","wcid":5196,"cell":"D8530100","place":"building","ns":-34.79,"ew":71.18,"id":10227}, + {"name":"Lo Raen","type":"NPC","wcid":32715,"cell":"D955003D","place":"outdoor","ns":-33.51,"ew":72.38,"id":10228,"desc":"Rat Catcher."}, + {"name":"Merchant","type":"Vendor","wcid":1389,"cell":"D9590100","place":"building","ns":-30.71,"ew":72.09,"id":10229}, + {"name":"Farmer","type":"Vendor","wcid":1381,"cell":"D97D0000","place":"outdoor","ns":-1.42,"ew":71.89,"id":10230}, + {"name":"Exploration Marker","type":"NPC","wcid":39792,"cell":"D97D0016","place":"outdoor","ns":-1.38,"ew":71.88,"id":10231}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"DA3A0000","place":"outdoor","ns":-54.76,"ew":73.2,"id":10232}, + {"name":"Vuo Nin the Barkeep","type":"Vendor","wcid":4541,"cell":"DA3B0133","place":"building","ns":-54.52,"ew":72.72,"id":10233,"desc":"Barkeeper."}, + {"name":"Wing Collector","type":"NPC","wcid":3924,"cell":"DA3B010F","place":"building","ns":-54.38,"ew":72.89,"id":10234,"desc":"Trophy Collector."}, + {"name":"Bu-Chi Long the Armorer","type":"Vendor","wcid":4540,"cell":"DA3B0128","place":"building","ns":-54.63,"ew":73.19,"id":10235,"desc":"Armorer."}, + {"name":"To Za-I the Weaponsmith","type":"Vendor","wcid":4546,"cell":"DA3B0129","place":"building","ns":-54.57,"ew":73.21,"id":10236,"desc":"Weaponsmith."}, + {"name":"Lo Ma the Jeweler","type":"Vendor","wcid":4544,"cell":"DA3B011C","place":"building","ns":-54.43,"ew":73.1,"id":10237,"desc":"Jeweler."}, + {"name":"Tekai Shou the Scribe","type":"Vendor","wcid":4545,"cell":"DA3B011B","place":"building","ns":-54.37,"ew":73.11,"id":10238,"desc":"Scribe."}, + {"name":"Collector","type":"NPC","wcid":3918,"cell":"DA3B0116","place":"building","ns":-54.42,"ew":72.89,"id":10239,"desc":"Trophy Collector."}, + {"name":"Ri-Gau Ro the Bowyer","type":"Vendor","wcid":4542,"cell":"DA3B0106","place":"building","ns":-54.58,"ew":72.93,"id":10240,"desc":"Bowyer."}, + {"name":"Tian Li Quan","type":"NPC","wcid":23350,"cell":"DA3B0120","place":"building","ns":-54.38,"ew":73.11,"id":10241,"desc":"Scribe."}, + {"name":"Jojii Shrine","type":"NPC","wcid":25829,"cell":"DA3B0000","place":"outdoor","ns":-54.26,"ew":73.08,"id":10242}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"DA3B0000","place":"outdoor","ns":-54.51,"ew":73.1,"id":10243}, + {"name":"Shoichi","type":"NPC","wcid":33968,"cell":"DA3B0116","place":"building","ns":-54.43,"ew":72.91,"id":10244,"desc":"Tusker Blight."}, + {"name":"Oi-Tong Ye","type":"NPC","wcid":5193,"cell":"DA550177","place":"building","ns":-33.52,"ew":73.0,"id":10245,"desc":"Society Agent."}, + {"name":"Ai Konaji the Jeweler","type":"Vendor","wcid":839,"cell":"DA550129","place":"building","ns":-33.17,"ew":72.67,"id":10246,"desc":"Jeweler."}, + {"name":"Tailor Ma Shih","type":"Vendor","wcid":843,"cell":"DA550102","place":"building","ns":-33.2,"ew":73.03,"id":10247,"desc":"Tailor."}, + {"name":"Hau Ji Tan the Grocer","type":"Vendor","wcid":837,"cell":"DA550185","place":"building","ns":-33.33,"ew":73.1,"id":10248,"desc":"Grocer."}, + {"name":"Nin Hong the Barkeeper","type":"Vendor","wcid":832,"cell":"DA55017C","place":"building","ns":-33.51,"ew":73.0,"id":10249,"desc":"Barkeeper."}, + {"name":"Brother Gonun the Scribe","type":"Vendor","wcid":840,"cell":"DA550136","place":"building","ns":-33.68,"ew":73.07,"id":10250,"desc":"Scribe."}, + {"name":"Yaohan Tong the Healer","type":"Vendor","wcid":838,"cell":"DA55014B","place":"building","ns":-33.83,"ew":72.99,"id":10251,"desc":"Healer."}, + {"name":"Shopkeeper Gonjoku Ryumi","type":"Vendor","wcid":842,"cell":"DA55019B","place":"building","ns":-33.71,"ew":72.82,"id":10252,"desc":"Shopkeeper."}, + {"name":"Archmage Chen Wah-Ji","type":"Vendor","wcid":831,"cell":"DA55015E","place":"building","ns":-33.82,"ew":72.63,"id":10253,"desc":"Archmage."}, + {"name":"Jaikite Sanzen the Barkeeper","type":"Vendor","wcid":834,"cell":"DA5501A9","place":"building","ns":-33.72,"ew":72.5,"id":10254,"desc":"Barkeeper."}, + {"name":"Ven Ounan the Blacksmith","type":"Vendor","wcid":835,"cell":"DA55010B","place":"building","ns":-33.51,"ew":72.63,"id":10255,"desc":"Blacksmith."}, + {"name":"Zhofon No the Bowyer","type":"Vendor","wcid":836,"cell":"DA550154","place":"building","ns":-33.38,"ew":72.48,"id":10256,"desc":"Bowyer."}, + {"name":"San Ming","type":"NPC","wcid":31641,"cell":"DA55001D","place":"outdoor","ns":-33.54,"ew":72.76,"id":10257,"desc":"Blood Shreth Butcher."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"DA550000","place":"outdoor","ns":-33.52,"ew":72.82,"id":10258}, + {"name":"Oneros the Gem Seller","type":"Vendor","wcid":9422,"cell":"DA550000","place":"outdoor","ns":-33.46,"ew":72.76,"id":10259,"desc":"Gem Seller."}, + {"name":"Apprentice Alchemist","type":"NPC","wcid":27742,"cell":"DA550000","place":"outdoor","ns":-33.31,"ew":72.77,"id":10260}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"DA550000","place":"outdoor","ns":-33.23,"ew":72.84,"id":10261}, + {"name":"Lou Ka","type":"NPC","wcid":5195,"cell":"DA550177","place":"building","ns":-33.49,"ew":73.01,"id":10262,"desc":"Citizen of Shoushi."}, + {"name":"Cooking Forge","type":"NPC","wcid":30466,"cell":"DA550000","place":"outdoor","ns":-33.24,"ew":73.1,"id":10263}, + {"name":"Salvaging Forge","type":"NPC","wcid":30461,"cell":"DA550000","place":"outdoor","ns":-33.61,"ew":72.61,"id":10264}, + {"name":"Fletching Forge","type":"NPC","wcid":30467,"cell":"DA550000","place":"outdoor","ns":-33.32,"ew":72.5,"id":10265}, + {"name":"Alchemy Forge","type":"NPC","wcid":30465,"cell":"DA550000","place":"outdoor","ns":-33.79,"ew":72.68,"id":10266}, + {"name":"Lockpick Forge","type":"NPC","wcid":30460,"cell":"DA550000","place":"outdoor","ns":-33.42,"ew":72.97,"id":10267}, + {"name":"Eiichi","type":"NPC","wcid":44897,"cell":"DA55001D","place":"outdoor","ns":-33.51,"ew":72.81,"id":10268,"desc":"Lifestone Greeter."}, + {"name":"Benjirou","type":"NPC","wcid":44893,"cell":"DA55017C","place":"building","ns":-33.52,"ew":72.99,"id":10269,"desc":"Bartender Greeter."}, + {"name":"Pathwarden Koro Ijida","type":"NPC","wcid":33614,"cell":"DA55001D","place":"outdoor","ns":-33.52,"ew":72.79,"id":10270,"desc":"Pathwarden Greeter."}, + {"name":"Hiro Ishigame","type":"NPC","wcid":38045,"cell":"DA550192","place":"building","ns":-33.69,"ew":72.79,"id":10271,"desc":"Green Mire Scholar."}, + {"name":"Qing","type":"Vendor","wcid":42430,"cell":"DA55019C","place":"building","ns":-33.7,"ew":72.78,"id":10272,"desc":"Master Tailor."}, + {"name":"Sacmisi","type":"Vendor","wcid":49520,"cell":"DA55015E","place":"building","ns":-33.83,"ew":72.63,"id":10273,"desc":"Geomancer."}, + {"name":"Haruko","type":"NPC","wcid":42722,"cell":"DA550192","place":"building","ns":-33.69,"ew":72.8,"id":10274,"desc":"Barber."}, + {"name":"Hadiya bint Anan","type":"NPC","wcid":33969,"cell":"DA550135","place":"building","ns":-33.7,"ew":73.12,"id":10275,"desc":"Zefir Zapper."}, + {"name":"Sayuji Jina","type":"NPC","wcid":34286,"cell":"DA55001F","place":"outdoor","ns":-33.33,"ew":72.84,"id":10276,"desc":"Sage."}, + {"name":"Contract Broker","type":"Vendor","wcid":44187,"cell":"DA550177","place":"building","ns":-33.48,"ew":72.98,"id":10277,"desc":"Armorer."}, + {"name":"Ohayashi Hiroshi","type":"NPC","wcid":44208,"cell":"DA550177","place":"building","ns":-33.48,"ew":72.99,"id":10278}, + {"name":"Tailor's Apprentice","type":"NPC","wcid":42738,"cell":"DA55019C","place":"building","ns":-33.69,"ew":72.78,"id":10279}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"DA550032","place":"outdoor","ns":-33.76,"ew":73.09,"id":10280,"desc":"Soldier."}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"DA550002","place":"outdoor","ns":-33.78,"ew":72.54,"id":10281,"desc":"Soldier."}, + {"name":"Royal Guard","type":"NPC","wcid":37518,"cell":"DA550008","place":"outdoor","ns":-33.23,"ew":72.51,"id":10282,"desc":"Soldier."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"DA56010C","place":"building","ns":-32.58,"ew":72.5,"id":10283,"desc":"Mage."}, + {"name":"Wedding Planner","type":"Vendor","wcid":14930,"cell":"DA56010C","place":"building","ns":-32.59,"ew":72.51,"id":10284,"desc":"Planner of Weddings."}, + {"name":"Arcanum Refurbisher","type":"NPC","wcid":32085,"cell":"DA56010C","place":"building","ns":-32.59,"ew":72.48,"id":10285,"desc":"Renovation Specialist."}, + {"name":"Binthura the Beggar","type":"NPC","wcid":2225,"cell":"DA750000","place":"outdoor","ns":-7.95,"ew":73.05,"id":10286,"desc":"Beggar."}, + {"name":"Esteca the Bowyer","type":"Vendor","wcid":2227,"cell":"DA750139","place":"building","ns":-8.01,"ew":72.97,"id":10287,"desc":"Bowyer."}, + {"name":"Sordan Edelson the Smithy","type":"Vendor","wcid":2226,"cell":"DA750131","place":"building","ns":-7.98,"ew":72.99,"id":10288,"desc":"Blacksmith."}, + {"name":"Barkeep Mordmor","type":"Vendor","wcid":2221,"cell":"DA750146","place":"building","ns":-8.11,"ew":73.1,"id":10289,"desc":"Barkeeper."}, + {"name":"Helford Beldryn the Grocer","type":"Vendor","wcid":2228,"cell":"DA750129","place":"building","ns":-7.9,"ew":73.1,"id":10290,"desc":"Grocer."}, + {"name":"Tilutha Beldryn the Tailor","type":"Vendor","wcid":2233,"cell":"DA750129","place":"building","ns":-7.88,"ew":73.11,"id":10291,"desc":"Tailor."}, + {"name":"Old Wylfed the Scribe","type":"Vendor","wcid":2231,"cell":"DA75012D","place":"building","ns":-7.88,"ew":73.11,"id":10292,"desc":"Scribe."}, + {"name":"Rindelle the Shopkeeper","type":"Vendor","wcid":2232,"cell":"DA75015D","place":"building","ns":-8.19,"ew":73.03,"id":10293,"desc":"Shopkeeper."}, + {"name":"Landeth Colson the Jeweler","type":"Vendor","wcid":2230,"cell":"DA75015F","place":"building","ns":-8.21,"ew":73.03,"id":10294,"desc":"Jeweler."}, + {"name":"Archmage Bendrew Efrith","type":"Vendor","wcid":2220,"cell":"DA75015B","place":"building","ns":-8.2,"ew":72.98,"id":10295,"desc":"Archmage."}, + {"name":"Ludora the Healer","type":"Vendor","wcid":2229,"cell":"DA750000","place":"outdoor","ns":-8.02,"ew":73.19,"id":10296,"desc":"Healer."}, + {"name":"Orcud the Beggar","type":"NPC","wcid":2223,"cell":"DA750000","place":"outdoor","ns":-7.85,"ew":72.93,"id":10297,"desc":"Beggar."}, + {"name":"Dinsmal the Beggar","type":"NPC","wcid":2224,"cell":"DA750000","place":"outdoor","ns":-8.25,"ew":73.17,"id":10298,"desc":"Beggar."}, + {"name":"Master Scrivener of Life Magic","type":"Vendor","wcid":20219,"cell":"DA75016D","place":"building","ns":-8.02,"ew":73.12,"id":10299,"desc":"Master Archmage."}, + {"name":"Master Scrivener of Creature Magic","type":"Vendor","wcid":20207,"cell":"DA75016D","place":"building","ns":-8.01,"ew":73.11,"id":10300,"desc":"Master Archmage."}, + {"name":"Master Scrivener of War Magic","type":"Vendor","wcid":20223,"cell":"DA75016D","place":"building","ns":-7.99,"ew":73.13,"id":10301,"desc":"Master Archmage."}, + {"name":"Master Scrivener of Item Magic","type":"Vendor","wcid":20211,"cell":"DA75016D","place":"building","ns":-7.98,"ew":73.11,"id":10302,"desc":"Master Archmage."}, + {"name":"Royal Guard Tabbeth","type":"NPC","wcid":28414,"cell":"DA75012D","place":"building","ns":-7.89,"ew":73.12,"id":10303,"desc":"Investigator."}, + {"name":"Gorak","type":"NPC","wcid":28516,"cell":"DA750000","place":"outdoor","ns":-7.94,"ew":73.17,"id":10304}, + {"name":"Journeyman Alchemist","type":"NPC","wcid":28917,"cell":"DA75014B","place":"building","ns":-8.06,"ew":73.14,"id":10305,"desc":"Apprentice Alchemist."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"DA750157","place":"building","ns":-8.1,"ew":73.09,"id":10306,"desc":"Mage."}, + {"name":"Lieutenant Rothe","type":"NPC","wcid":32650,"cell":"DA750032","place":"outdoor","ns":-8.21,"ew":73.11,"id":10307,"desc":"Royal Guard."}, + {"name":"Exploration Marker","type":"NPC","wcid":39826,"cell":"DA750035","place":"outdoor","ns":-7.94,"ew":73.09,"id":10308}, + {"name":"Life Stone","type":"Lifestone","wcid":23618,"cell":"DABE0000","place":"outdoor","ns":50.21,"ew":73.1,"id":10309}, + {"name":"Archmage Ta Ban-Yu","type":"Vendor","wcid":4539,"cell":"DB3B010D","place":"building","ns":-54.4,"ew":73.51,"id":10310,"desc":"Archmage."}, + {"name":"Healer Kai Kou","type":"Vendor","wcid":4543,"cell":"DB3B0100","place":"building","ns":-54.22,"ew":74.01,"id":10311,"desc":"Healer."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"DB3B011B","place":"building","ns":-54.28,"ew":73.32,"id":10312,"desc":"Mage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"DB3B012C","place":"building","ns":-54.08,"ew":73.99,"id":10313,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"DB3B0135","place":"building","ns":-54.1,"ew":74.02,"id":10314,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"DB3B0126","place":"building","ns":-54.08,"ew":74.02,"id":10315,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"DB3B0126","place":"building","ns":-54.11,"ew":73.98,"id":10316,"desc":"Master Archmage."}, + {"name":"Apprentice Alchemist","type":"NPC","wcid":28184,"cell":"DB3B010D","place":"building","ns":-54.41,"ew":73.48,"id":10317}, + {"name":"Sho Low-Stakes Gamesmaster","type":"NPC","wcid":9500,"cell":"DB540100","place":"building","ns":-34.17,"ew":73.67,"id":10318,"desc":"Gamesmaster."}, + {"name":"Mi Gan-Zo","type":"NPC","wcid":9494,"cell":"DB540100","place":"building","ns":-34.19,"ew":73.67,"id":10319,"desc":"Gambler Boss."}, + {"name":"Sho High-Stakes Gamesmaster","type":"NPC","wcid":9497,"cell":"DB540100","place":"building","ns":-34.17,"ew":73.72,"id":10320,"desc":"Gamesmaster."}, + {"name":"Sho High-Stakes Gamesmaster","type":"NPC","wcid":9497,"cell":"DB540100","place":"building","ns":-34.17,"ew":73.71,"id":10321,"desc":"Gamesmaster."}, + {"name":"Sho Mid-Stakes Gamesmaster","type":"NPC","wcid":9503,"cell":"DB540100","place":"building","ns":-34.17,"ew":73.7,"id":10322,"desc":"Gamesmaster."}, + {"name":"Sho Mid-Stakes Gamesmaster","type":"NPC","wcid":9503,"cell":"DB540100","place":"building","ns":-34.17,"ew":73.69,"id":10323,"desc":"Gamesmaster."}, + {"name":"Sho Low-Stakes Gamesmaster","type":"NPC","wcid":9500,"cell":"DB540100","place":"building","ns":-34.17,"ew":73.68,"id":10324,"desc":"Gamesmaster."}, + {"name":"Haya Su Ka","type":"Vendor","wcid":9506,"cell":"DB540102","place":"building","ns":-34.2,"ew":73.7,"id":10325,"desc":"Cashier."}, + {"name":"Pawn Shopkeep","type":"Vendor","wcid":12308,"cell":"DB540100","place":"building","ns":-34.22,"ew":73.67,"id":10326,"desc":"Fence."}, + {"name":"Rare Exchanger","type":"NPC","wcid":40464,"cell":"DB540105","place":"building","ns":-34.2,"ew":73.69,"id":10327,"desc":"Gamesmaster."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20215,"cell":"DB550103","place":"building","ns":-33.61,"ew":73.42,"id":10328,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":20205,"cell":"DB550103","place":"building","ns":-33.58,"ew":73.41,"id":10329,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20217,"cell":"DB550103","place":"building","ns":-33.6,"ew":73.38,"id":10330,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20218,"cell":"DB550106","place":"building","ns":-33.61,"ew":73.42,"id":10331,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":20206,"cell":"DB550106","place":"building","ns":-33.57,"ew":73.4,"id":10332,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20216,"cell":"DB550106","place":"building","ns":-33.59,"ew":73.38,"id":10333,"desc":"Master Archmage."}, + {"name":"Gonjoku Den","type":"NPC","wcid":28857,"cell":"DB550006","place":"outdoor","ns":-33.41,"ew":73.27,"id":10334,"desc":"Herbalist."}, + {"name":"Scrivener of Void Magic","type":"Vendor","wcid":43354,"cell":"DB550106","place":"building","ns":-33.61,"ew":73.38,"id":10335,"desc":"Master Archmage."}, + {"name":"Sir Tenshin","type":"NPC","wcid":14414,"cell":"DB560100","place":"building","ns":-32.81,"ew":73.29,"id":10336,"desc":"Senior Guard."}, + {"name":"Sentry","type":"NPC","wcid":14460,"cell":"DB560000","place":"outdoor","ns":-32.89,"ew":73.37,"id":10337,"desc":"Guard."}, + {"name":"Sentry","type":"NPC","wcid":14459,"cell":"DB560000","place":"outdoor","ns":-32.71,"ew":73.36,"id":10338,"desc":"Guard."}, + {"name":"Sentry","type":"NPC","wcid":12725,"cell":"DB560000","place":"outdoor","ns":-32.6,"ew":73.41,"id":10339,"desc":"Soldier."}, + {"name":"Royal Guard","type":"NPC","wcid":33805,"cell":"DB560004","place":"outdoor","ns":-32.84,"ew":73.26,"id":10340,"desc":"Guard."}, + {"name":"Yu Vuo-Ki","type":"NPC","wcid":6847,"cell":"DB740007","place":"outdoor","ns":-8.48,"ew":73.3,"id":10341,"desc":"Adventurer."}, + {"name":"Dansha-Ki","type":"NPC","wcid":6848,"cell":"DB74010A","place":"building","ns":-8.98,"ew":73.71,"id":10342,"desc":"Prisoner."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"DC390000","place":"outdoor","ns":-55.63,"ew":74.07,"id":10343}, + {"name":"Farmer","type":"Vendor","wcid":1383,"cell":"DC390102","place":"building","ns":-55.58,"ew":74.11,"id":10344}, + {"name":"Balthazar, Royal Guardian","type":"NPC","wcid":15774,"cell":"DC3A0100","place":"dungeon","id":10345,"desc":"Guard. In a dungeon (landblock DC3A)."}, + {"name":"Naba Ko-Zin","type":"Vendor","wcid":9617,"cell":"DC3C0100","place":"dungeon","id":10346,"desc":"Bestower Representative. In a dungeon (landblock DC3C)."}, + {"name":"Jaizen Tan","type":"NPC","wcid":9546,"cell":"DC3C0100","place":"dungeon","id":10347,"desc":"Bestower Examiner. In a dungeon (landblock DC3C)."}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-32.13,"ew":74.26,"id":10348}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-32.04,"ew":74.16,"id":10349}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-32.05,"ew":74.25,"id":10350}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-32.17,"ew":74.32,"id":10351}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-31.98,"ew":74.16,"id":10352}, + {"name":"Tackle Master","type":"NPC","wcid":23336,"cell":"DC570100","place":"building","ns":-32.24,"ew":74.17,"id":10353,"desc":"Pro Fisherman."}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-32.03,"ew":74.13,"id":10354}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-32.08,"ew":74.18,"id":10355}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-32.06,"ew":74.21,"id":10356}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-32.11,"ew":74.25,"id":10357}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-32.14,"ew":74.23,"id":10358}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-32.08,"ew":74.26,"id":10359}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"DC570000","place":"outdoor","ns":-32.05,"ew":74.21,"id":10360}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"DC5F0000","place":"outdoor","ns":-25.68,"ew":74.79,"id":10361}, + {"name":"Peddler","type":"Vendor","wcid":1392,"cell":"DC5F0104","place":"building","ns":-25.72,"ew":74.7,"id":10362}, + {"name":"Ostentatious Farmer","type":"Vendor","wcid":14411,"cell":"DD500100","place":"building","ns":-37.42,"ew":75.48,"id":10363,"desc":"Farmer."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"DD740000","place":"outdoor","ns":-8.82,"ew":75.2,"id":10364}, + {"name":"Oi Ra the Shopkeeper","type":"Vendor","wcid":4559,"cell":"DE51010A","place":"building","ns":-36.61,"ew":75.81,"id":10365,"desc":"Shopkeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"DE510000","place":"outdoor","ns":-36.73,"ew":75.76,"id":10366}, + {"name":"Sentry","type":"NPC","wcid":12725,"cell":"DE510000","place":"outdoor","ns":-36.81,"ew":76.11,"id":10367,"desc":"Soldier."}, + {"name":"Exploration Marker","type":"NPC","wcid":39752,"cell":"DF3C000C","place":"outdoor","ns":-53.56,"ew":76.64,"id":10368}, + {"name":"Spinning Wheel","type":"NPC","wcid":19129,"cell":"DF61010F","place":"building","ns":-24.21,"ew":76.78,"id":10369}, + {"name":"Exploration Marker","type":"NPC","wcid":39765,"cell":"E13D0029","place":"outdoor","ns":-53.09,"ew":78.58,"id":10370}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E15B0000","place":"outdoor","ns":-28.59,"ew":78.32,"id":10371}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E3320000","place":"outdoor","ns":-61.47,"ew":80.04,"id":10372}, + {"name":"Healer","type":"Vendor","wcid":1386,"cell":"E337010D","place":"building","ns":-57.39,"ew":80.28,"id":10373}, + {"name":"Archmage","type":"Vendor","wcid":1371,"cell":"E3370108","place":"building","ns":-57.41,"ew":80.27,"id":10374}, + {"name":"Merchant","type":"Vendor","wcid":1389,"cell":"E3370106","place":"building","ns":-57.38,"ew":80.32,"id":10375}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E33D0000","place":"outdoor","ns":-52.7,"ew":80.16,"id":10376}, + {"name":"Archmage","type":"Vendor","wcid":1371,"cell":"E3550100","place":"building","ns":-33.7,"ew":79.91,"id":10377}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E3550000","place":"outdoor","ns":-33.66,"ew":79.86,"id":10378}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43C0000","place":"outdoor","ns":-53.18,"ew":80.95,"id":10379}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43C0000","place":"outdoor","ns":-53.17,"ew":80.97,"id":10380}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-52.57,"ew":80.66,"id":10381}, + {"name":"Tackle Master","type":"NPC","wcid":23336,"cell":"E43D0100","place":"building","ns":-52.57,"ew":80.8,"id":10382,"desc":"Pro Fisherman."}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-52.52,"ew":80.66,"id":10383}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-52.56,"ew":80.59,"id":10384}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-53.03,"ew":80.75,"id":10385}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-53.05,"ew":80.84,"id":10386}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-53.09,"ew":80.95,"id":10387}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-52.52,"ew":80.68,"id":10388}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-52.6,"ew":80.6,"id":10389}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-52.59,"ew":80.57,"id":10390}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-52.55,"ew":80.54,"id":10391}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-52.49,"ew":80.58,"id":10392}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-53.02,"ew":80.84,"id":10393}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-53.01,"ew":80.72,"id":10394}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-53.05,"ew":80.72,"id":10395}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-53.08,"ew":80.75,"id":10396}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-53.08,"ew":80.81,"id":10397}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-53.02,"ew":80.87,"id":10398}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-53.04,"ew":80.96,"id":10399}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"E43D0000","place":"outdoor","ns":-53.09,"ew":81.0,"id":10400}, + {"name":"Farmer Ar'Oyd","type":"NPC","wcid":52181,"cell":"E43D0011","place":"outdoor","ns":-53.14,"ew":80.73,"id":10401,"desc":"Farmer."}, + {"name":"Garbage Barrel","type":"NPC","wcid":34726,"cell":"E44D0100","place":"underground","ns":-39.89,"ew":81.18,"id":10402}, + {"name":"Garbage Barrel","type":"NPC","wcid":34726,"cell":"E44D0103","place":"building","ns":-39.79,"ew":81.21,"id":10403}, + {"name":"Arcanum Broker","type":"Vendor","wcid":38460,"cell":"E44D003E","place":"outdoor","ns":-39.78,"ew":81.19,"id":10404,"desc":"Mana Forge Vendor."}, + {"name":"Arcanum Mana-smith","type":"NPC","wcid":38461,"cell":"E44D003E","place":"outdoor","ns":-39.78,"ew":81.21,"id":10405,"desc":"Pristine Mana Shard Collector."}, + {"name":"Component Exchanger","type":"NPC","wcid":40770,"cell":"E44D0103","place":"building","ns":-39.79,"ew":81.19,"id":10406,"desc":"Gamesmaster."}, + {"name":"Garbage Barrel","type":"NPC","wcid":34726,"cell":"E44D0100","place":"underground","ns":-39.89,"ew":81.22,"id":10407}, + {"name":"Mayor Trenlach","type":"NPC","wcid":43753,"cell":"E4D6010F","place":"building","ns":69.52,"ew":80.6,"id":10408,"desc":"Survivor."}, + {"name":"Kaneth al-Evv","type":"Vendor","wcid":43752,"cell":"E4D6010F","place":"building","ns":69.53,"ew":80.6,"id":10409,"desc":"Olthoi Hunter."}, + {"name":"Tailor Ka Shen-Ku","type":"Vendor","wcid":1145,"cell":"E532010C","place":"building","ns":-61.8,"ew":81.77,"id":10410,"desc":"Tailor."}, + {"name":"Grocer Riku Ryu","type":"Vendor","wcid":799,"cell":"E532010B","place":"building","ns":-61.79,"ew":81.83,"id":10411,"desc":"Grocer."}, + {"name":"Shui Tentou the Bowyer","type":"Vendor","wcid":798,"cell":"E5320106","place":"building","ns":-61.81,"ew":82.03,"id":10412,"desc":"Bowyer."}, + {"name":"Healer Tonsho Ha","type":"Vendor","wcid":800,"cell":"E5320122","place":"building","ns":-61.91,"ew":81.88,"id":10413,"desc":"Healer."}, + {"name":"Te Kenten the Barkeep","type":"Vendor","wcid":796,"cell":"E532011A","place":"building","ns":-61.41,"ew":81.88,"id":10414,"desc":"Barkeeper."}, + {"name":"Nawamara Ujio","type":"NPC","wcid":28682,"cell":"E5320100","place":"building","ns":-61.78,"ew":82.01,"id":10415,"desc":"Augmentation Trainer."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"E532012E","place":"building","ns":-61.18,"ew":81.71,"id":10416,"desc":"Mage."}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"E5320000","place":"outdoor","ns":-61.34,"ew":81.76,"id":10417}, + {"name":"Apprentice Cook","type":"NPC","wcid":28187,"cell":"E532010F","place":"building","ns":-61.8,"ew":81.77,"id":10418}, + {"name":"Wah Chon the Barkeep","type":"Vendor","wcid":4548,"cell":"E53D0100","place":"building","ns":-52.42,"ew":82.01,"id":10419,"desc":"Barkeeper."}, + {"name":"Wuo Ha the Provisioner","type":"Vendor","wcid":4555,"cell":"E53D010E","place":"building","ns":-52.58,"ew":81.99,"id":10420,"desc":"Provisioner."}, + {"name":"Wa Shi","type":"NPC","wcid":5122,"cell":"E53D0100","place":"building","ns":-52.43,"ew":81.98,"id":10421,"desc":"Rat Killer."}, + {"name":"Miyako Nujou-Wah","type":"NPC","wcid":6890,"cell":"E53D0111","place":"building","ns":-52.49,"ew":81.98,"id":10422,"desc":"Poet."}, + {"name":"Apprentice Cook","type":"NPC","wcid":27745,"cell":"E53D0112","place":"building","ns":-52.5,"ew":81.99,"id":10423}, + {"name":"Han Rin-Jo, Jojii Adherent","type":"NPC","wcid":25832,"cell":"E53D0100","place":"building","ns":-52.38,"ew":82.01,"id":10424,"desc":"Monk."}, + {"name":"Ook","type":"NPC","wcid":35776,"cell":"E53D003E","place":"outdoor","ns":-52.64,"ew":81.96,"id":10425}, + {"name":"Archmage Jo Ji-Shen","type":"Vendor","wcid":4547,"cell":"E53E0103","place":"building","ns":-52.31,"ew":81.61,"id":10426,"desc":"Archmage."}, + {"name":"Le Ben the Healer","type":"Vendor","wcid":4552,"cell":"E53E0114","place":"building","ns":-52.29,"ew":81.77,"id":10427,"desc":"Healer."}, + {"name":"Scribe Lashi Oi","type":"Vendor","wcid":4554,"cell":"E53E0113","place":"building","ns":-52.32,"ew":81.83,"id":10428,"desc":"Scribe."}, + {"name":"Shin Ro","type":"NPC","wcid":5121,"cell":"E53E0103","place":"building","ns":-52.33,"ew":81.6,"id":10429,"desc":"Society Agent."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E53E0000","place":"outdoor","ns":-52.18,"ew":81.63,"id":10430}, + {"name":"Yao Lun the Shopkeeper","type":"Vendor","wcid":4558,"cell":"E542010F","place":"building","ns":-49.11,"ew":81.68,"id":10431,"desc":"Shopkeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E5420000","place":"outdoor","ns":-49.04,"ew":81.61,"id":10432}, + {"name":"Ji Ra Ping","type":"NPC","wcid":5120,"cell":"E542010D","place":"building","ns":-49.07,"ew":81.69,"id":10433,"desc":"Enchanter."}, + {"name":"Ikomi Ra, Jojii Adherent","type":"NPC","wcid":25828,"cell":"E5420108","place":"building","ns":-49.08,"ew":81.71,"id":10434,"desc":"Monk."}, + {"name":"Exploration Marker","type":"NPC","wcid":39778,"cell":"E542002B","place":"outdoor","ns":-48.9,"ew":81.75,"id":10435}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E54E0000","place":"outdoor","ns":-39.1,"ew":81.6,"id":10436}, + {"name":"Ran Le the Librarian","type":"Vendor","wcid":2044,"cell":"E54E010A","place":"building","ns":-39.19,"ew":81.59,"id":10437,"desc":"Librarian."}, + {"name":"Fanzen San the Translator","type":"NPC","wcid":5694,"cell":"E54E010A","place":"building","ns":-39.21,"ew":81.59,"id":10438,"desc":"Translator."}, + {"name":"Arcanum Researcher","type":"NPC","wcid":16892,"cell":"E54E0113","place":"building","ns":-39.21,"ew":81.63,"id":10439}, + {"name":"Open Book","type":"NPC","wcid":40525,"cell":"E54E0104","place":"building","ns":-39.22,"ew":81.58,"id":10440}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E6300000","place":"outdoor","ns":-63.09,"ew":82.45,"id":10441}, + {"name":"Jeweler Liman Pon","type":"Vendor","wcid":801,"cell":"E6320115","place":"building","ns":-61.27,"ew":82.1,"id":10442,"desc":"Jeweler."}, + {"name":"Archmage Yuzai Zhen","type":"Vendor","wcid":795,"cell":"E6320103","place":"building","ns":-61.4,"ew":82.52,"id":10443,"desc":"Archmage."}, + {"name":"Xi Hau-Lai the Weaponsmith","type":"Vendor","wcid":802,"cell":"E6320118","place":"building","ns":-61.83,"ew":82.21,"id":10444,"desc":"Weaponsmith."}, + {"name":"Fen Hau-Lai the Armorer","type":"Vendor","wcid":1146,"cell":"E6320118","place":"building","ns":-61.83,"ew":82.19,"id":10445,"desc":"Armorer."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"E632013A","place":"building","ns":-61.92,"ew":82.2,"id":10446,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"E632013F","place":"building","ns":-61.89,"ew":82.18,"id":10447,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"E6320139","place":"building","ns":-61.9,"ew":82.21,"id":10448,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"E6320139","place":"building","ns":-61.92,"ew":82.19,"id":10449,"desc":"Master Archmage."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E6320000","place":"outdoor","ns":-61.9,"ew":82.3,"id":10450}, + {"name":"Sara Sen","type":"NPC","wcid":31691,"cell":"E632001D","place":"outdoor","ns":-61.51,"ew":82.37,"id":10451,"desc":"Monster Plant Lover."}, + {"name":"Master Liao Oazaka","type":"NPC","wcid":34016,"cell":"E6320137","place":"building","ns":-61.77,"ew":82.38,"id":10452,"desc":"Sensei."}, + {"name":"Tai Wo","type":"NPC","wcid":15812,"cell":"E6320133","place":"building","ns":-61.82,"ew":82.42,"id":10453,"desc":"Historian."}, + {"name":"Guard Taizo","type":"NPC","wcid":37442,"cell":"E6320026","place":"outdoor","ns":-61.36,"ew":82.5,"id":10454,"desc":"Soldier."}, + {"name":"Captain Warner","type":"NPC","wcid":38151,"cell":"E6320103","place":"building","ns":-61.38,"ew":82.5,"id":10455,"desc":"Mariner."}, + {"name":"Nun Hong the Jeweler","type":"Vendor","wcid":4553,"cell":"E63D0126","place":"building","ns":-52.59,"ew":82.08,"id":10456,"desc":"Jeweler."}, + {"name":"Tailor Yajyi San","type":"Vendor","wcid":4556,"cell":"E63D0125","place":"building","ns":-52.61,"ew":82.12,"id":10457,"desc":"Tailor."}, + {"name":"Ye Te the Bowyer","type":"Vendor","wcid":4550,"cell":"E63D0106","place":"building","ns":-52.68,"ew":82.39,"id":10458,"desc":"Bowyer."}, + {"name":"Blacksmith Ton Wing","type":"Vendor","wcid":4549,"cell":"E63D0131","place":"building","ns":-52.77,"ew":82.32,"id":10459,"desc":"Blacksmith."}, + {"name":"Jo Gau the Grocer","type":"Vendor","wcid":4551,"cell":"E63D0108","place":"building","ns":-52.5,"ew":82.39,"id":10460,"desc":"Grocer."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"E63D014C","place":"building","ns":-52.9,"ew":82.49,"id":10461,"desc":"Mage."}, + {"name":"Wedding Planner","type":"Vendor","wcid":14930,"cell":"E63D014C","place":"building","ns":-52.89,"ew":82.5,"id":10462,"desc":"Planner of Weddings."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":20225,"cell":"E63D0159","place":"building","ns":-52.71,"ew":82.62,"id":10463,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":20213,"cell":"E63D0159","place":"building","ns":-52.69,"ew":82.58,"id":10464,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":20209,"cell":"E63D015C","place":"building","ns":-52.72,"ew":82.62,"id":10465,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":20221,"cell":"E63D015C","place":"building","ns":-52.68,"ew":82.61,"id":10466,"desc":"Master Archmage."}, + {"name":"Small Creepy Statue","type":"NPC","wcid":25987,"cell":"E63D0000","place":"outdoor","ns":-52.66,"ew":82.31,"id":10467}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"E63D0000","place":"outdoor","ns":-52.55,"ew":82.49,"id":10468}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"E64E0102","place":"building","ns":-39.41,"ew":82.78,"id":10469,"desc":"Mage."}, + {"name":"Jubei's Apprentice Craftsman","type":"Vendor","wcid":12243,"cell":"E64E0102","place":"building","ns":-39.38,"ew":82.81,"id":10470,"desc":"Apprentice Craftsman."}, + {"name":"Jubei Minawoto","type":"NPC","wcid":12240,"cell":"E64E0102","place":"building","ns":-39.4,"ew":82.81,"id":10471,"desc":"Master House Decorator."}, + {"name":"Olthoi Matron","type":"Vendor","wcid":43490,"cell":"E6D30010","place":"outdoor","ns":67.57,"ew":82.17,"id":10472,"desc":"Soldier Vendor."}, + {"name":"Olthoi Matron","type":"Vendor","wcid":43632,"cell":"E6D30005","place":"outdoor","ns":67.33,"ew":82.1,"id":10473,"desc":"Spitter Vendor."}, + {"name":"Acid Pit","type":"NPC","wcid":43631,"cell":"E6D30005","place":"outdoor","ns":67.33,"ew":82.06,"id":10474}, + {"name":"Acid Pit","type":"NPC","wcid":43631,"cell":"E6D30010","place":"outdoor","ns":67.61,"ew":82.17,"id":10475}, + {"name":"Olthoi Queen","type":"NPC","wcid":43530,"cell":"E6D3000E","place":"outdoor","ns":67.41,"ew":82.25,"id":10476}, + {"name":"Olthoi Grub","type":"NPC","wcid":43589,"cell":"E6D30016","place":"outdoor","ns":67.42,"ew":82.26,"id":10477}, + {"name":"Olthoi Grub","type":"NPC","wcid":43589,"cell":"E6D30016","place":"outdoor","ns":67.4,"ew":82.29,"id":10478}, + {"name":"Olthoi Grub","type":"NPC","wcid":43589,"cell":"E6D30016","place":"outdoor","ns":67.38,"ew":82.28,"id":10479}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E7320000","place":"outdoor","ns":-61.58,"ew":83.34,"id":10480}, + {"name":"Tree","type":"NPC","wcid":25723,"cell":"E7440000","place":"outdoor","ns":-47.32,"ew":83.47,"id":10481}, + {"name":"Tree","type":"NPC","wcid":25723,"cell":"E7440000","place":"outdoor","ns":-47.28,"ew":83.46,"id":10482}, + {"name":"Tree","type":"NPC","wcid":25723,"cell":"E7440000","place":"outdoor","ns":-47.21,"ew":83.26,"id":10483}, + {"name":"Tree","type":"NPC","wcid":25723,"cell":"E7440000","place":"outdoor","ns":-47.26,"ew":83.32,"id":10484}, + {"name":"Tree","type":"NPC","wcid":25723,"cell":"E7440000","place":"outdoor","ns":-47.34,"ew":83.35,"id":10485}, + {"name":"Tree","type":"NPC","wcid":25723,"cell":"E7440000","place":"outdoor","ns":-47.42,"ew":83.41,"id":10486}, + {"name":"Tree","type":"NPC","wcid":25720,"cell":"E7440000","place":"outdoor","ns":-47.24,"ew":83.39,"id":10487}, + {"name":"Tree","type":"NPC","wcid":25723,"cell":"E7440000","place":"outdoor","ns":-47.19,"ew":83.36,"id":10488}, + {"name":"Tree","type":"NPC","wcid":25723,"cell":"E7440000","place":"outdoor","ns":-47.17,"ew":83.3,"id":10489}, + {"name":"Tree","type":"NPC","wcid":25723,"cell":"E7440000","place":"outdoor","ns":-47.08,"ew":83.24,"id":10490}, + {"name":"Tree","type":"NPC","wcid":25723,"cell":"E7440000","place":"outdoor","ns":-47.24,"ew":83.2,"id":10491}, + {"name":"Chosen of Asheron","type":"NPC","wcid":8767,"cell":"E74B0000","place":"outdoor","ns":-41.92,"ew":83.04,"id":10492,"desc":"Emissary."}, + {"name":"Kirina of the Celestial Hand","type":"NPC","wcid":38388,"cell":"E74D003F","place":"outdoor","ns":-39.69,"ew":83.63,"id":10493,"desc":"Society Recruiter."}, + {"name":"Barkeeper Chon Nuo","type":"Vendor","wcid":860,"cell":"E74E0178","place":"building","ns":-39.23,"ew":83.4,"id":10494,"desc":"Barkeeper."}, + {"name":"Archmage Shikiru Nohon","type":"Vendor","wcid":856,"cell":"E74E010F","place":"building","ns":-38.87,"ew":83.03,"id":10495,"desc":"Archmage."}, + {"name":"Archmage Anyao Zai","type":"Vendor","wcid":857,"cell":"E74E0103","place":"building","ns":-38.91,"ew":83.21,"id":10496,"desc":"Archmage."}, + {"name":"Barkeeper Fo Ya-Un","type":"Vendor","wcid":859,"cell":"E74E0133","place":"building","ns":-39.11,"ew":83.4,"id":10497,"desc":"Barkeeper."}, + {"name":"Kouxao Ei the Healer","type":"Vendor","wcid":867,"cell":"E74E018C","place":"building","ns":-38.91,"ew":83.41,"id":10498,"desc":"Healer."}, + {"name":"Goro Yu-Ban the Provisioner","type":"Vendor","wcid":865,"cell":"E74E013E","place":"building","ns":-39.38,"ew":83.61,"id":10499,"desc":"Provisioner."}, + {"name":"Kento Do the Grocer","type":"Vendor","wcid":866,"cell":"E74E013D","place":"building","ns":-39.42,"ew":83.61,"id":10500,"desc":"Grocer."}, + {"name":"Tailor Chueh Jian","type":"Vendor","wcid":870,"cell":"E74E012B","place":"building","ns":-39.52,"ew":83.13,"id":10501,"desc":"Tailor."}, + {"name":"Aldera Brunall Weaponsmith","type":"Vendor","wcid":871,"cell":"E74E0175","place":"building","ns":-39.5,"ew":83.32,"id":10502,"desc":"Weaponsmith."}, + {"name":"Muozhen Wa the Jeweler","type":"Vendor","wcid":868,"cell":"E74E011D","place":"building","ns":-39.31,"ew":83.23,"id":10503,"desc":"Jeweler."}, + {"name":"Rayyib al-Afij the Armorer","type":"Vendor","wcid":858,"cell":"E74E0185","place":"building","ns":-39.3,"ew":83.52,"id":10504,"desc":"Armorer."}, + {"name":"Fenza Tan the Scribe","type":"Vendor","wcid":869,"cell":"E74E0164","place":"building","ns":-39.27,"ew":82.91,"id":10505,"desc":"Scribe."}, + {"name":"Lai Konsho the Armorsmith","type":"Vendor","wcid":862,"cell":"E74E0146","place":"building","ns":-39.09,"ew":83.03,"id":10506,"desc":"Armorsmith."}, + {"name":"Yatenyu Zhuong the Bowyer","type":"Vendor","wcid":864,"cell":"E74E019C","place":"building","ns":-39.52,"ew":82.89,"id":10507,"desc":"Bowyer."}, + {"name":"Shosa Kiroji Matanui","type":"NPC","wcid":11811,"cell":"E74E0000","place":"outdoor","ns":-38.99,"ew":83.21,"id":10508,"desc":"Quartermaster."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20215,"cell":"E74E01BC","place":"building","ns":-39.41,"ew":83.02,"id":10509,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Item and War Magic","type":"Vendor","wcid":20216,"cell":"E74E01BC","place":"building","ns":-39.4,"ew":83.02,"id":10510,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":20206,"cell":"E74E01BD","place":"building","ns":-39.39,"ew":82.98,"id":10511,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Creature Magic","type":"Vendor","wcid":20205,"cell":"E74E01BD","place":"building","ns":-39.4,"ew":82.98,"id":10512,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20217,"cell":"E74E01B3","place":"building","ns":-39.39,"ew":82.99,"id":10513,"desc":"Master Archmage."}, + {"name":"Apprentice Scrivener of Life Magic","type":"Vendor","wcid":20218,"cell":"E74E01B3","place":"building","ns":-39.42,"ew":83.02,"id":10514,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Life Magic","type":"Vendor","wcid":20221,"cell":"E74E01AA","place":"building","ns":-39.37,"ew":83.02,"id":10515,"desc":"Master Archmage."}, + {"name":"Scrivener of Life Magic","type":"Vendor","wcid":20222,"cell":"E74E01AD","place":"building","ns":-39.39,"ew":82.98,"id":10516,"desc":"Master Archmage."}, + {"name":"Scrivener of Creature Magic","type":"Vendor","wcid":20210,"cell":"E74E01AD","place":"building","ns":-39.42,"ew":82.98,"id":10517,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Creature Magic","type":"Vendor","wcid":20209,"cell":"E74E01AD","place":"building","ns":-39.41,"ew":83.02,"id":10518,"desc":"Master Archmage."}, + {"name":"Scrivener of War Magic","type":"Vendor","wcid":20226,"cell":"E74E01A9","place":"building","ns":-39.43,"ew":82.98,"id":10519,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of War Magic","type":"Vendor","wcid":20225,"cell":"E74E0000","place":"outdoor","ns":-39.44,"ew":83.04,"id":10520,"desc":"Master Archmage."}, + {"name":"Scrivener of Item Magic","type":"Vendor","wcid":20214,"cell":"E74E01AD","place":"building","ns":-39.39,"ew":83.02,"id":10521,"desc":"Master Archmage."}, + {"name":"Journeyman Scrivener of Item Magic","type":"Vendor","wcid":20213,"cell":"E74E01AD","place":"building","ns":-39.38,"ew":83.01,"id":10522,"desc":"Master Archmage."}, + {"name":"Sign","type":"NPC","wcid":25722,"cell":"E74E0000","place":"outdoor","ns":-38.98,"ew":82.91,"id":10523}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E74E0000","place":"outdoor","ns":-39.03,"ew":83.15,"id":10524}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"E74E0000","place":"outdoor","ns":-39.32,"ew":83.35,"id":10525}, + {"name":"Li Fong","type":"NPC","wcid":28477,"cell":"E74E0103","place":"building","ns":-38.9,"ew":83.18,"id":10526,"desc":"Noble Guard."}, + {"name":"Nawamara Dia","type":"NPC","wcid":28683,"cell":"E74E011E","place":"building","ns":-39.28,"ew":83.17,"id":10527,"desc":"Augmentation Trainer."}, + {"name":"Lu Bao","type":"NPC","wcid":30274,"cell":"E74E0133","place":"building","ns":-39.07,"ew":83.38,"id":10528,"desc":"Augmentation Trainer."}, + {"name":"Rikshen Ri","type":"NPC","wcid":30273,"cell":"E74E0133","place":"building","ns":-39.07,"ew":83.42,"id":10529,"desc":"Augmentation Trainer."}, + {"name":"Ilin Wis","type":"NPC","wcid":30270,"cell":"E74E0170","place":"building","ns":-39.51,"ew":83.33,"id":10530,"desc":"Augmentation Trainer."}, + {"name":"Enli Yuo","type":"NPC","wcid":30272,"cell":"E74E017C","place":"building","ns":-39.17,"ew":83.4,"id":10531,"desc":"Augmentation Trainer."}, + {"name":"Kyujo Rujen","type":"NPC","wcid":30271,"cell":"E74E0184","place":"building","ns":-39.29,"ew":83.47,"id":10532,"desc":"Augmentation Trainer."}, + {"name":"Shujio Milao","type":"NPC","wcid":30275,"cell":"E74E0193","place":"building","ns":-38.9,"ew":83.37,"id":10533,"desc":"Augmentation Trainer."}, + {"name":"Gan Fo","type":"NPC","wcid":41521,"cell":"E74E001F","place":"outdoor","ns":-38.89,"ew":83.23,"id":10534,"desc":"Augmentation Trainer."}, + {"name":"Akemi Fei","type":"NPC","wcid":41520,"cell":"E74E001F","place":"outdoor","ns":-38.91,"ew":83.24,"id":10535,"desc":"Augmentation Trainer."}, + {"name":"Tanada Sajo","type":"NPC","wcid":40322,"cell":"E74E001F","place":"outdoor","ns":-38.88,"ew":83.25,"id":10536,"desc":"Face of the Clan."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"E8210102","place":"building","ns":-74.82,"ew":83.98,"id":10537,"desc":"Mage."}, + {"name":"Vanten the Archmage","type":"Vendor","wcid":8432,"cell":"E822010B","place":"building","ns":-74.47,"ew":83.99,"id":10538,"desc":"Archmage."}, + {"name":"Kamira Mohonoko the Provisioner","type":"Vendor","wcid":8438,"cell":"E822011D","place":"building","ns":-74.28,"ew":84.27,"id":10539,"desc":"Provisioner."}, + {"name":"Barkeep Brita the Boisterous","type":"Vendor","wcid":8434,"cell":"E8220114","place":"building","ns":-74.3,"ew":84.31,"id":10540,"desc":"Barkeeper."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E8220000","place":"outdoor","ns":-74.18,"ew":84.3,"id":10541}, + {"name":"Sharon the Skilled, Bowyer","type":"Vendor","wcid":8435,"cell":"E9220126","place":"building","ns":-74.4,"ew":84.52,"id":10542,"desc":"Bowyer."}, + {"name":"Weaponsmith Illic Ibn'Abulfiq","type":"Vendor","wcid":8440,"cell":"E9220106","place":"building","ns":-74.62,"ew":84.72,"id":10543,"desc":"Weaponsmith."}, + {"name":"Armorer Padira Yukinara","type":"Vendor","wcid":8433,"cell":"E922010D","place":"building","ns":-74.58,"ew":84.69,"id":10544,"desc":"Armorer."}, + {"name":"Jeweler Imad Nedjim","type":"Vendor","wcid":8437,"cell":"E9220116","place":"building","ns":-74.41,"ew":84.8,"id":10545,"desc":"Jeweler."}, + {"name":"Natalie the Scribe","type":"Vendor","wcid":8439,"cell":"E922013D","place":"building","ns":-74.48,"ew":85.0,"id":10546,"desc":"Scribe."}, + {"name":"Healer Sanami Siohiro","type":"Vendor","wcid":8436,"cell":"E9220136","place":"building","ns":-74.52,"ew":85.0,"id":10547,"desc":"Healer."}, + {"name":"Zenzaburou Hensu","type":"NPC","wcid":8441,"cell":"E9220000","place":"outdoor","ns":-74.6,"ew":84.51,"id":10548,"desc":"Noble."}, + {"name":"Leather Crafter","type":"NPC","wcid":4213,"cell":"E9220000","place":"outdoor","ns":-74.3,"ew":84.65,"id":10549,"desc":"Trophy Collector."}, + {"name":"Ivory Crafter","type":"NPC","wcid":3926,"cell":"E9220000","place":"outdoor","ns":-74.72,"ew":84.66,"id":10550,"desc":"Trophy Crafter."}, + {"name":"Corporal Massein","type":"NPC","wcid":35606,"cell":"E922000D","place":"outdoor","ns":-74.35,"ew":84.58,"id":10551,"desc":"Guard."}, + {"name":"Sergeant Brigitta","type":"NPC","wcid":35603,"cell":"E922000D","place":"outdoor","ns":-74.33,"ew":84.57,"id":10552,"desc":"Soldier."}, + {"name":"Aluvian Spearman","type":"NPC","wcid":32705,"cell":"E9220000","place":"outdoor","ns":-74.42,"ew":84.59,"id":10553,"desc":"Soldier."}, + {"name":"Aluvian Spearman","type":"NPC","wcid":32705,"cell":"E9220000","place":"outdoor","ns":-74.33,"ew":84.62,"id":10554,"desc":"Soldier."}, + {"name":"Aluvian Spearman","type":"NPC","wcid":32705,"cell":"E9220000","place":"outdoor","ns":-74.32,"ew":84.58,"id":10555,"desc":"Soldier."}, + {"name":"Aluvian Spearman","type":"NPC","wcid":32705,"cell":"E9220000","place":"outdoor","ns":-74.43,"ew":84.73,"id":10556,"desc":"Soldier."}, + {"name":"Aluvian Spearman","type":"NPC","wcid":32705,"cell":"E9220000","place":"outdoor","ns":-74.44,"ew":84.95,"id":10557,"desc":"Soldier."}, + {"name":"Aluvian Spearman","type":"NPC","wcid":32705,"cell":"E9220000","place":"outdoor","ns":-74.48,"ew":84.85,"id":10558,"desc":"Soldier."}, + {"name":"Gharu'ndim War Mage","type":"NPC","wcid":32706,"cell":"E9220000","place":"outdoor","ns":-74.43,"ew":84.61,"id":10559,"desc":"Soldier."}, + {"name":"Gharu'ndim War Mage","type":"NPC","wcid":32706,"cell":"E9220000","place":"outdoor","ns":-74.34,"ew":84.6,"id":10560,"desc":"Soldier."}, + {"name":"Gharu'ndim War Mage","type":"NPC","wcid":32706,"cell":"E9220000","place":"outdoor","ns":-74.43,"ew":84.65,"id":10561,"desc":"Soldier."}, + {"name":"Gharu'ndim War Mage","type":"NPC","wcid":32706,"cell":"E9220000","place":"outdoor","ns":-74.42,"ew":84.7,"id":10562,"desc":"Soldier."}, + {"name":"Gharu'ndim War Mage","type":"NPC","wcid":32706,"cell":"E9220000","place":"outdoor","ns":-74.45,"ew":84.78,"id":10563,"desc":"Soldier."}, + {"name":"Gharu'ndim War Mage","type":"NPC","wcid":32706,"cell":"E9220000","place":"outdoor","ns":-74.5,"ew":84.88,"id":10564,"desc":"Soldier."}, + {"name":"Gharu'ndim War Mage","type":"NPC","wcid":32706,"cell":"E9220000","place":"outdoor","ns":-74.43,"ew":84.59,"id":10565,"desc":"Soldier."}, + {"name":"Gharu'ndim Warrior","type":"NPC","wcid":32707,"cell":"E9220000","place":"outdoor","ns":-74.41,"ew":84.63,"id":10566,"desc":"Soldier."}, + {"name":"Gharu'ndim Warrior","type":"NPC","wcid":32707,"cell":"E9220000","place":"outdoor","ns":-74.31,"ew":84.57,"id":10567,"desc":"Soldier."}, + {"name":"Gharu'ndim Warrior","type":"NPC","wcid":32707,"cell":"E9220000","place":"outdoor","ns":-74.41,"ew":84.67,"id":10568,"desc":"Soldier."}, + {"name":"Gharu'ndim Warrior","type":"NPC","wcid":32707,"cell":"E9220000","place":"outdoor","ns":-74.41,"ew":84.73,"id":10569,"desc":"Soldier."}, + {"name":"Gharu'ndim Warrior","type":"NPC","wcid":32707,"cell":"E9220000","place":"outdoor","ns":-74.47,"ew":84.83,"id":10570,"desc":"Soldier."}, + {"name":"Gharu'ndim Warrior","type":"NPC","wcid":32707,"cell":"E9220000","place":"outdoor","ns":-74.49,"ew":84.87,"id":10571,"desc":"Soldier."}, + {"name":"Gharu'ndim Warrior","type":"NPC","wcid":32707,"cell":"E9220000","place":"outdoor","ns":-74.5,"ew":84.91,"id":10572,"desc":"Soldier."}, + {"name":"Sho Swordsman","type":"NPC","wcid":32709,"cell":"E9220000","place":"outdoor","ns":-74.42,"ew":84.63,"id":10573,"desc":"Soldier."}, + {"name":"Sho Swordsman","type":"NPC","wcid":32709,"cell":"E9220000","place":"outdoor","ns":-74.42,"ew":84.59,"id":10574,"desc":"Soldier."}, + {"name":"Sho Swordsman","type":"NPC","wcid":32709,"cell":"E9220000","place":"outdoor","ns":-74.3,"ew":84.59,"id":10575,"desc":"Soldier."}, + {"name":"Sho Swordsman","type":"NPC","wcid":32709,"cell":"E9220000","place":"outdoor","ns":-74.42,"ew":84.67,"id":10576,"desc":"Soldier."}, + {"name":"Sho Swordsman","type":"NPC","wcid":32709,"cell":"E9220000","place":"outdoor","ns":-74.42,"ew":84.72,"id":10577,"desc":"Soldier."}, + {"name":"Sho Swordsman","type":"NPC","wcid":32709,"cell":"E9220000","place":"outdoor","ns":-74.46,"ew":84.81,"id":10578,"desc":"Soldier."}, + {"name":"Sho Swordsman","type":"NPC","wcid":32709,"cell":"E9220000","place":"outdoor","ns":-74.49,"ew":84.91,"id":10579,"desc":"Soldier."}, + {"name":"Sho Swordsman","type":"NPC","wcid":32709,"cell":"E9220000","place":"outdoor","ns":-74.45,"ew":84.94,"id":10580,"desc":"Soldier."}, + {"name":"Guard Hrothgar","type":"NPC","wcid":35213,"cell":"E9220000","place":"outdoor","ns":-74.33,"ew":84.59,"id":10581,"desc":"Investigator."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"E94C0000","place":"outdoor","ns":-40.74,"ew":84.9,"id":10582}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"EA1D0000","place":"outdoor","ns":-78.22,"ew":85.29,"id":10583}, + {"name":"Master Shoyanen Kenchu the Archmage","type":"Vendor","wcid":2249,"cell":"EA300103","place":"building","ns":-63.39,"ew":85.88,"id":10584,"desc":"Master Archmage."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"EA3D0000","place":"outdoor","ns":-52.39,"ew":85.38,"id":10585}, + {"name":"Hon Fo the Shopkeeper","type":"Vendor","wcid":4557,"cell":"EA3D0102","place":"building","ns":-52.41,"ew":85.29,"id":10586,"desc":"Shopkeeper."}, + {"name":"Inuo KonKou","type":"NPC","wcid":5119,"cell":"EA3D0100","place":"building","ns":-52.39,"ew":85.29,"id":10587,"desc":"Enchanter."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"EA4E0000","place":"outdoor","ns":-39.18,"ew":85.6,"id":10588}, + {"name":"Dark Tusker Shrine","type":"Vendor","wcid":35948,"cell":"EA6C0159","place":"dungeon","id":10589,"desc":"In a dungeon (landblock EA6C)."}, + {"name":"Dark Tusker Shrine","type":"Vendor","wcid":35948,"cell":"EA6C015A","place":"dungeon","id":10590,"desc":"In a dungeon (landblock EA6C)."}, + {"name":"Exploration Marker","type":"NPC","wcid":39830,"cell":"EB0F0037","place":"outdoor","ns":-89.29,"ew":86.71,"id":10591}, + {"name":"Visiting Shaman","type":"NPC","wcid":87730,"cell":"EB1D017B","place":"underground","ns":-78.35,"ew":86.95,"id":10592,"desc":"Shaman."}, + {"name":"Visiting Shaman","type":"NPC","wcid":87730,"cell":"EB1D017B","place":"underground","ns":-78.34,"ew":86.94,"id":10593,"desc":"Shaman."}, + {"name":"Visiting Shaman","type":"NPC","wcid":87730,"cell":"EB1D017B","place":"underground","ns":-78.34,"ew":86.96,"id":10594,"desc":"Shaman."}, + {"name":"Pile of Stained Papers","type":"NPC","wcid":87731,"cell":"EB1D0123","place":"underground","ns":-77.88,"ew":87.12,"id":10595}, + {"name":"Exploration Marker","type":"NPC","wcid":39757,"cell":"EB730011","place":"outdoor","ns":-9.94,"ew":86.33,"id":10596}, + {"name":"Kleeoh","type":"NPC","wcid":22461,"cell":"EB7C0102","place":"building","ns":-2.51,"ew":86.36,"id":10597,"desc":"Seer."}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"EC120000","place":"outdoor","ns":-87.1,"ew":87.33,"id":10598}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"EC120000","place":"outdoor","ns":-87.06,"ew":87.35,"id":10599}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"EC120000","place":"outdoor","ns":-87.07,"ew":87.3,"id":10600}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"EC120000","place":"outdoor","ns":-87.13,"ew":87.31,"id":10601}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"EC120000","place":"outdoor","ns":-87.0,"ew":87.3,"id":10602}, + {"name":"Fishing Hole","type":"NPC","wcid":22257,"cell":"EC120000","place":"outdoor","ns":-87.03,"ew":87.35,"id":10603}, + {"name":"A Sycophant's Corpse","type":"NPC","wcid":27513,"cell":"ED810000","place":"outdoor","ns":1.5,"ew":87.99,"id":10604,"desc":"Corpse."}, + {"name":"Statue of Transport","type":"NPC","wcid":38074,"cell":"EE18001A","place":"outdoor","ns":-82.6,"ew":88.8,"id":10605}, + {"name":"Font Guardian","type":"NPC","wcid":29730,"cell":"EF0D0000","place":"outdoor","ns":-91.41,"ew":89.5,"id":10606}, + {"name":"Exploration Marker","type":"NPC","wcid":39780,"cell":"EF280031","place":"outdoor","ns":-69.92,"ew":89.89,"id":10607}, + {"name":"Weaponsmith Bornak the Crookblade","type":"Vendor","wcid":8496,"cell":"F2220100","place":"building","ns":-74.17,"ew":92.22,"id":10608,"desc":"Weaponsmith."}, + {"name":"Lin Hanza the Bowyer","type":"Vendor","wcid":8494,"cell":"F2220100","place":"building","ns":-74.17,"ew":92.18,"id":10609,"desc":"Bowyer."}, + {"name":"Jesren the Jolly Barkeep","type":"Vendor","wcid":8493,"cell":"F2220119","place":"building","ns":-73.98,"ew":92.31,"id":10610,"desc":"Barkeep."}, + {"name":"Provisioner Warster the Handy","type":"Vendor","wcid":8495,"cell":"F2220119","place":"building","ns":-74.03,"ew":92.3,"id":10611,"desc":"Shifty Provisioner."}, + {"name":"MacNiall the Unruled","type":"NPC","wcid":8490,"cell":"F2220000","place":"outdoor","ns":-74.02,"ew":92.25,"id":10612,"desc":"Bandit Leader."}, + {"name":"Open Journal","type":"NPC","wcid":25714,"cell":"F2220127","place":"building","ns":-74.39,"ew":92.09,"id":10613}, + {"name":"Gentleman Jake Hawkins","type":"NPC","wcid":25721,"cell":"F2220000","place":"outdoor","ns":-74.53,"ew":92.34,"id":10614,"desc":"Lunatic."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"F2220000","place":"outdoor","ns":-74.36,"ew":92.21,"id":10615}, + {"name":"Journeyman Fletcher","type":"NPC","wcid":28925,"cell":"F2220100","place":"building","ns":-74.2,"ew":92.18,"id":10616,"desc":"Apprentice Fletcher."}, + {"name":"Researcher Tharin","type":"NPC","wcid":35605,"cell":"F2220119","place":"building","ns":-73.98,"ew":92.28,"id":10617,"desc":"Scholar."}, + {"name":"Onda Nakoza","type":"NPC","wcid":8491,"cell":"F2230000","place":"outdoor","ns":-73.91,"ew":92.28,"id":10618,"desc":"Bandit Lieutenant."}, + {"name":"Agent of the Arcanum","type":"NPC","wcid":12050,"cell":"F2230102","place":"building","ns":-73.78,"ew":92.3,"id":10619,"desc":"Mage."}, + {"name":"Exploration Marker","type":"NPC","wcid":39770,"cell":"F317003E","place":"outdoor","ns":-83.03,"ew":93.19,"id":10620}, + {"name":"Kaza Nijina the Archmage","type":"Vendor","wcid":8492,"cell":"F3220000","place":"outdoor","ns":-74.5,"ew":92.49,"id":10621,"desc":"Archmage."}, + {"name":"Mr. P","type":"NPC","wcid":34383,"cell":"F324002C","place":"outdoor","ns":-72.84,"ew":93.04,"id":10622,"desc":"Penguin."}, + {"name":"Shade of Lady Adja","type":"NPC","wcid":43405,"cell":"F4180112","place":"building","ns":-82.67,"ew":93.4,"id":10623,"desc":"Seer of the Light Falatacot."}, + {"name":"Ithaenc Quiddity Seed","type":"NPC","wcid":36925,"cell":"F4180009","place":"outdoor","ns":-82.72,"ew":93.39,"id":10624}, + {"name":"Exploration Marker","type":"NPC","wcid":39783,"cell":"F41F0034","place":"outdoor","ns":-76.84,"ew":93.89,"id":10625}, + {"name":"Grand Sentinel Ehcac","type":"NPC","wcid":14923,"cell":"F5180000","place":"outdoor","ns":-82.0,"ew":94.77,"id":10626,"desc":"Marriage Facilitator."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"F5590035","place":"outdoor","ns":-30.33,"ew":94.73,"id":10627}, + {"name":"Bind Stone","type":"Bindstone","wcid":27547,"cell":"F559003D","place":"outdoor","ns":-30.34,"ew":94.81,"id":10628}, + {"name":"Leather Crafter","type":"NPC","wcid":4214,"cell":"F559010B","place":"building","ns":-30.31,"ew":94.69,"id":10629,"desc":"Trophy Collector."}, + {"name":"Small Creepy Statue","type":"NPC","wcid":25990,"cell":"F559003D","place":"outdoor","ns":-30.31,"ew":94.83,"id":10630}, + {"name":"Royal Guard","type":"NPC","wcid":52272,"cell":"F559003D","place":"outdoor","ns":-30.27,"ew":94.82,"id":10631,"desc":"Shadow Destroyer."}, + {"name":"Royal Guard","type":"NPC","wcid":46015,"cell":"F559003D","place":"outdoor","ns":-30.3,"ew":94.84,"id":10632,"desc":"Grievver Shredder Hunter."}, + {"name":"Royal Guard","type":"NPC","wcid":46018,"cell":"F559003D","place":"outdoor","ns":-30.26,"ew":94.82,"id":10633,"desc":"Void Lord Hunter."}, + {"name":"Royal Guard","type":"NPC","wcid":46017,"cell":"F559003E","place":"outdoor","ns":-30.24,"ew":94.81,"id":10634,"desc":"Tou-Tou Shadow Hunter."}, + {"name":"Umbral Guard","type":"NPC","wcid":46016,"cell":"F559003D","place":"outdoor","ns":-30.29,"ew":94.83,"id":10635,"desc":"Devourer Margul Hunter."}, + {"name":"Umbral Guard","type":"NPC","wcid":46014,"cell":"F559003D","place":"outdoor","ns":-30.28,"ew":94.83,"id":10636,"desc":"Shadow Flyer Hunter."}, + {"name":"Life Stone","type":"Lifestone","wcid":509,"cell":"F6290000","place":"outdoor","ns":-68.6,"ew":94.93,"id":10637}, + {"name":"Shadow Soldier","type":"NPC","wcid":44630,"cell":"F65B0028","place":"outdoor","ns":-28.39,"ew":95.28,"id":10638}, + {"name":"Shadow Captain","type":"NPC","wcid":44631,"cell":"F65C0101","place":"building","ns":-28.3,"ew":95.3,"id":10639}, + {"name":"Shadow Vortex","type":"NPC","wcid":44650,"cell":"F65C0033","place":"outdoor","ns":-28.09,"ew":95.46,"id":10640}, + {"name":"Shadow Soldier","type":"NPC","wcid":44630,"cell":"F65C0024","place":"outdoor","ns":-28.01,"ew":95.33,"id":10641}, + {"name":"Shadow Soldier","type":"NPC","wcid":44630,"cell":"F65C0022","place":"outdoor","ns":-28.24,"ew":95.26,"id":10642}, + {"name":"Healer","type":"Vendor","wcid":22725,"cell":"F6810000","place":"outdoor","ns":1.98,"ew":95.58,"id":10643}, + {"name":"Town Crier","type":"NPC","wcid":22643,"cell":"F6810000","place":"outdoor","ns":1.92,"ew":95.13,"id":10644,"desc":"Ooo oo aaa."}, + {"name":"Aidene","type":"NPC","wcid":31645,"cell":"F6810040","place":"outdoor","ns":2.02,"ew":95.59,"id":10645,"desc":"Iron-Spined Chittick Immolator."}, + {"name":"Jilna Fullgood","type":"NPC","wcid":35772,"cell":"F6810040","place":"outdoor","ns":1.98,"ew":95.62,"id":10646,"desc":"Tusker King's Healer."}, + {"name":"Blacksmith","type":"Vendor","wcid":22722,"cell":"F6820111","place":"building","ns":2.38,"ew":95.43,"id":10647}, + {"name":"Grocer","type":"Vendor","wcid":22724,"cell":"F6820000","place":"outdoor","ns":2.43,"ew":95.21,"id":10648}, + {"name":"Jeweler","type":"Vendor","wcid":22726,"cell":"F6820000","place":"outdoor","ns":2.17,"ew":95.19,"id":10649}, + {"name":"Mage","type":"Vendor","wcid":22721,"cell":"F682011D","place":"building","ns":2.23,"ew":95.59,"id":10650,"desc":"Archmage."}, + {"name":"Bowyer","type":"Vendor","wcid":22723,"cell":"F6820102","place":"building","ns":2.37,"ew":95.58,"id":10651}, + {"name":"Mayor Ko Ko","type":"NPC","wcid":22640,"cell":"F6820000","place":"outdoor","ns":2.3,"ew":95.49,"id":10652,"desc":"Ooo oo aaa."}, + {"name":"Brighteyes, the Tailor","type":"NPC","wcid":22642,"cell":"F682011C","place":"building","ns":2.18,"ew":95.58,"id":10653,"desc":"Underground Resistance Leader."}, + {"name":"Lug","type":"NPC","wcid":28681,"cell":"F682001A","place":"outdoor","ns":2.2,"ew":95.24,"id":10654,"desc":"Augmentation Trainer."}, + {"name":"Exploration Marker","type":"NPC","wcid":39779,"cell":"F682001E","place":"outdoor","ns":2.64,"ew":95.17,"id":10655}, + {"name":"Emissary of Asheron","type":"NPC","wcid":43072,"cell":"F730001E","place":"outdoor","ns":-62.96,"ew":96.0,"id":10656,"desc":"Emissary."}, + {"name":"Jusad the Collector","type":"NPC","wcid":40460,"cell":"F731001A","place":"outdoor","ns":-62.63,"ew":96.03,"id":10657,"desc":"Rare Items Collector."}, + {"name":"Summoning Cave","type":"NPC","wcid":44434,"cell":"F75A0101","place":"building","ns":-29.19,"ew":95.86,"id":10658}, + {"name":"Black Ferah","type":"NPC","wcid":43860,"cell":"F75A0010","place":"outdoor","ns":-29.19,"ew":95.77,"id":10659}, + {"name":"Town Crier","type":"NPC","wcid":22643,"cell":"F7810000","place":"outdoor","ns":2.03,"ew":95.93,"id":10660,"desc":"Ooo oo aaa."}, + {"name":"Ketnan","type":"Vendor","wcid":22720,"cell":"F784039F","place":"underground","ns":5.86,"ew":97.22,"id":10661,"desc":"Entrepreneur."}, + {"name":"Hawker for Ketnan","type":"NPC","wcid":22644,"cell":"F7840000","place":"outdoor","ns":4.26,"ew":95.77,"id":10662,"desc":"Hawker for the Tusker Emporium Dungeon."}, + {"name":"Life Stone","type":"Lifestone","wcid":23618,"cell":"F81B0000","place":"outdoor","ns":-80.1,"ew":96.7,"id":10663}, + {"name":"Lugian Miner","type":"NPC","wcid":46885,"cell":"F81E0100","place":"building","ns":-77.72,"ew":97.0,"id":10664,"desc":"Laborer."}, + {"name":"Lugian Miner","type":"NPC","wcid":46885,"cell":"F81E002B","place":"outdoor","ns":-77.74,"ew":96.96,"id":10665,"desc":"Laborer."}, + {"name":"Lugian Miner","type":"NPC","wcid":46885,"cell":"F81E002B","place":"outdoor","ns":-77.69,"ew":96.99,"id":10666,"desc":"Laborer."}, + {"name":"Shah-hi","type":"NPC","wcid":46806,"cell":"F81E002B","place":"outdoor","ns":-77.74,"ew":96.96,"id":10667,"desc":"Researcher."}, + {"name":"Lugian Miner","type":"NPC","wcid":46885,"cell":"F81E002B","place":"outdoor","ns":-77.66,"ew":96.98,"id":10668,"desc":"Laborer."}, + {"name":"Lugian Miner","type":"NPC","wcid":46885,"cell":"F81E001C","place":"outdoor","ns":-77.56,"ew":96.84,"id":10669,"desc":"Laborer."}, + {"name":"Prison Guard","type":"NPC","wcid":41179,"cell":"F8380020","place":"outdoor","ns":-56.36,"ew":96.8,"id":10670}, + {"name":"Prison Guard","type":"NPC","wcid":41179,"cell":"F8380020","place":"outdoor","ns":-56.44,"ew":96.8,"id":10671}, + {"name":"Prison Guard","type":"NPC","wcid":41179,"cell":"F838001F","place":"outdoor","ns":-56.49,"ew":96.81,"id":10672}, + {"name":"Prison Guard","type":"NPC","wcid":41179,"cell":"F8380027","place":"outdoor","ns":-56.49,"ew":96.87,"id":10673}, + {"name":"Prison Guard","type":"NPC","wcid":41179,"cell":"F8380027","place":"outdoor","ns":-56.49,"ew":96.93,"id":10674}, + {"name":"Prison Guard","type":"NPC","wcid":41179,"cell":"F838002F","place":"outdoor","ns":-56.49,"ew":96.99,"id":10675}, + {"name":"Prison Guard","type":"NPC","wcid":41179,"cell":"F8380030","place":"outdoor","ns":-56.44,"ew":97.0,"id":10676}, + {"name":"Prison Guard","type":"NPC","wcid":41179,"cell":"F8380030","place":"outdoor","ns":-56.36,"ew":97.0,"id":10677}, + {"name":"Avarin","type":"NPC","wcid":41177,"cell":"F8380028","place":"outdoor","ns":-56.43,"ew":96.93,"id":10678,"desc":"Prison Guard."}, + {"name":"Gate Warden Kris","type":"NPC","wcid":41178,"cell":"F8380028","place":"outdoor","ns":-56.42,"ew":96.89,"id":10679,"desc":"Gate Warden."}, + {"name":"Dark Rock","type":"NPC","wcid":44580,"cell":"F85C0004","place":"outdoor","ns":-28.0,"ew":96.47,"id":10680}, + {"name":"Dark Rock","type":"NPC","wcid":44576,"cell":"F85D000C","place":"outdoor","ns":-27.2,"ew":96.6,"id":10681}, + {"name":"Exploration Marker","type":"NPC","wcid":39828,"cell":"F85E002C","place":"outdoor","ns":-26.41,"ew":97.01,"id":10682}, + {"name":"Abbess Zik'Lir","type":"NPC","wcid":87590,"cell":"F9170002","place":"outdoor","ns":-83.44,"ew":97.25,"id":10683,"desc":"Falatacot Emissionary."}, + {"name":"Creeping Blight Banner of the Courtyard","type":"NPC","wcid":37544,"cell":"F92F0011","place":"outdoor","ns":-64.27,"ew":97.53,"id":10684}, + {"name":"Creeping Blight Banner of the Spire","type":"NPC","wcid":37547,"cell":"F92F0013","place":"outdoor","ns":-64.12,"ew":97.5,"id":10685}, + {"name":"Creeping Blight Banner of the Tower","type":"NPC","wcid":37550,"cell":"F92F002A","place":"outdoor","ns":-64.19,"ew":97.83,"id":10686}, + {"name":"Celestial Hand Buffing Array","type":"NPC","wcid":40534,"cell":"F92F001A","place":"outdoor","ns":-64.23,"ew":97.59,"id":10687}, + {"name":"Eldrytch Web Buffing Array","type":"NPC","wcid":40535,"cell":"F92F001A","place":"outdoor","ns":-64.23,"ew":97.59,"id":10688}, + {"name":"Radiant Blood Buffing Array","type":"NPC","wcid":40536,"cell":"F92F001A","place":"outdoor","ns":-64.23,"ew":97.59,"id":10689}, + {"name":"Master MacTavish","type":"NPC","wcid":80421,"cell":"F92F01AF","place":"building","ns":-63.94,"ew":97.14,"id":10690,"desc":"Laird of the Freebooters."}, + {"name":"Purser Jak Halftoes","type":"Vendor","wcid":80426,"cell":"F92F01CA","place":"building","ns":-63.99,"ew":97.15,"id":10691,"desc":"Shopkeeper."}, + {"name":"Hacha Jien the Archmage","type":"Vendor","wcid":80424,"cell":"F92F01CF","place":"building","ns":-63.99,"ew":97.11,"id":10692,"desc":"Black Market Archmage."}, + {"name":"Lormish Littlefinger","type":"NPC","wcid":80430,"cell":"F92F01B5","place":"building","ns":-63.95,"ew":97.07,"id":10693,"desc":"Black Market Gem-Fence."}, + {"name":"Pak Li-Shung","type":"NPC","wcid":80433,"cell":"F92F0198","place":"building","ns":-63.91,"ew":97.07,"id":10694,"desc":"Black Market Writ-Finagler."}, + {"name":"Digby","type":"NPC","wcid":80428,"cell":"F92F0172","place":"building","ns":-63.87,"ew":97.1,"id":10695,"desc":"Black Market Key-Fence."}, + {"name":"Calhoun","type":"NPC","wcid":80431,"cell":"F92F0172","place":"building","ns":-63.87,"ew":97.12,"id":10696,"desc":"Black Market Luminance Gem-Fence."}, + {"name":"Kagami","type":"NPC","wcid":80435,"cell":"F92F0155","place":"building","ns":-63.81,"ew":97.31,"id":10697,"desc":"Moarsman Hunter."}, + {"name":"Bayani","type":"NPC","wcid":80437,"cell":"F92F0155","place":"building","ns":-63.82,"ew":97.33,"id":10698,"desc":"Sclavus Hunter."}, + {"name":"Valerian McGreggor","type":"NPC","wcid":80439,"cell":"F92F018A","place":"building","ns":-63.9,"ew":97.28,"id":10699,"desc":"Deru Researcher."}, + {"name":"Exploration Marker","type":"NPC","wcid":39789,"cell":"F92F0032","place":"outdoor","ns":-64.24,"ew":97.86,"id":10700}, + {"name":"Corpse of Radiant Blood Agent","type":"NPC","wcid":41805,"cell":"F930011C","place":"underground","ns":-62.9,"ew":97.49,"id":10701}, + {"name":"Corpse of Radiant Blood Agent","type":"NPC","wcid":41805,"cell":"F9300005","place":"outdoor","ns":-63.09,"ew":97.3,"id":10702}, + {"name":"Corpse of Eldrytch Web Agent","type":"NPC","wcid":41804,"cell":"F9300010","place":"outdoor","ns":-62.82,"ew":97.41,"id":10703}, + {"name":"Corpse of Eldrytch Web Agent","type":"NPC","wcid":41804,"cell":"F930001C","place":"outdoor","ns":-63.25,"ew":97.63,"id":10704}, + {"name":"Corpse of Celestial Hand Agent","type":"NPC","wcid":41803,"cell":"F9300135","place":"underground","ns":-62.93,"ew":97.72,"id":10705}, + {"name":"Corpse of Celestial Hand Agent","type":"NPC","wcid":41803,"cell":"F930000E","place":"outdoor","ns":-63.01,"ew":97.37,"id":10706}, + {"name":"Corpse of Celestial Hand Agent","type":"NPC","wcid":41803,"cell":"F9300026","place":"outdoor","ns":-62.96,"ew":97.65,"id":10707}, + {"name":"Statue of Transport","type":"NPC","wcid":38370,"cell":"F9390027","place":"outdoor","ns":-55.71,"ew":97.7,"id":10708}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"F93B0236","place":"dungeon","id":10709,"desc":"In a dungeon (landblock F93B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"F93B0225","place":"dungeon","id":10710,"desc":"In a dungeon (landblock F93B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26543,"cell":"F93B0249","place":"dungeon","id":10711,"desc":"In a dungeon (landblock F93B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26544,"cell":"F93B0255","place":"dungeon","id":10712,"desc":"In a dungeon (landblock F93B)."}, + {"name":"Wailing Statue","type":"NPC","wcid":26568,"cell":"F93B0258","place":"dungeon","id":10713,"desc":"In a dungeon (landblock F93B)."}, + {"name":"Thick Rock Wall","type":"NPC","wcid":51646,"cell":"F93B0127","place":"dungeon","id":10714,"desc":"In a dungeon (landblock F93B)."}, + {"name":"Jester Hall Trap","type":"NPC","wcid":87496,"cell":"F93B03BF","place":"dungeon","id":10715,"desc":"In a dungeon (landblock F93B)."}, + {"name":"An Empyrean device","type":"NPC","wcid":43075,"cell":"FA34001C","place":"outdoor","ns":-60.01,"ew":98.4,"id":10716} + ], + "recalls": [ + {"spell":2020,"name":"Recall Asmolum 1","cell":"F3170036","place":"outdoor","ns":-82.96,"ew":93.06}, + {"spell":2023,"name":"Recall the Sanctuary","cell":"F4180104","place":"building","ns":-82.55,"ew":93.4}, + {"spell":2024,"name":"Recall Asmolum 2","cell":"F3170032","place":"outdoor","ns":-83.4,"ew":93.1}, + {"spell":2025,"name":"RecallAsmolum 3","cell":"F3170004","place":"outdoor","ns":-83.24,"ew":92.54}, + {"spell":2041,"name":"Aerlinthe Recall","cell":"BAE8001D","place":"outdoor","ns":84.09,"ew":47.2}, + {"spell":2358,"name":"Lyceum Recall","cell":"BC110014","place":"outdoor","ns":-88.05,"ew":48.65}, + {"spell":2478,"name":"Cragstone Reinforcements camp recall","cell":"02750158","place":"dungeon"}, + {"spell":2479,"name":"Advance Camp Recall","cell":"027B0200","place":"dungeon","in":"Vile-Smelling Refuse"}, + {"spell":2481,"name":"Zaikhal Reinforcement Camp Recall","cell":"02740158","place":"dungeon"}, + {"spell":2482,"name":"Zaikhal Advance Camp Recall","cell":"027A0200","place":"dungeon","in":"Vile-Smelling Refuse"}, + {"spell":2485,"name":"Hebian-to Advance Camp Recall","cell":"02790200","place":"dungeon","in":"Vile-Smelling Refuse"}, + {"spell":2813,"name":"Mount Lethe Recall","cell":"14550032","place":"outdoor","ns":-33.83,"ew":-85.26}, + {"spell":2931,"name":"Recall Aphus Lassel","cell":"F6820033","place":"outdoor","ns":2.26,"ew":95.46}, + {"spell":2941,"name":"Ulgrim's Recall","cell":"1134001F","place":"outdoor","ns":-59.7,"ew":-88.0}, + {"spell":2943,"name":"Recall to the Singularity Caul","cell":"09040008","place":"outdoor","ns":-97.96,"ew":-94.7}, + {"spell":3856,"name":"Ulgrim's Recall","cell":"1134001F","place":"outdoor","ns":-59.7,"ew":-88.0}, + {"spell":3865,"name":"Glenden Wood Recall","cell":"A0A40025","place":"outdoor","ns":29.75,"ew":26.45}, + {"spell":3929,"name":"Rossu Morta Chapterhouse Recall","cell":"00800128","place":"dungeon","in":"Rossu Morta Chapterhouse"}, + {"spell":3930,"name":"Whispering Blade Chapterhouse Recall","cell":"00810128","place":"dungeon","in":"Whispering Blade Chapterhouse"}, + {"spell":4084,"name":"Bur Recall","cell":"009C0247","place":"dungeon"}, + {"spell":4198,"name":"Paradox-touched Olthoi Infested Area Recall","cell":"C4B60002","place":"outdoor","ns":43.76,"ew":54.94}, + {"spell":4213,"name":"Colosseum Recall","cell":"00AF0118","place":"dungeon","in":"The Colosseum"}, + {"spell":4233,"name":"Aerbax Recall Center Platform","cell":"2F2F002A","place":"outdoor","ns":-64.16,"ew":-63.8}, + {"spell":4234,"name":"Aerbax Recall East Platform","cell":"302F0033","place":"outdoor","ns":-64.1,"ew":-62.9}, + {"spell":4235,"name":"Aerbax Recall North Platform","cell":"2F30002C","place":"outdoor","ns":-63.2,"ew":-63.8}, + {"spell":4236,"name":"Aerbax Recall South Platform","cell":"2F2E002A","place":"outdoor","ns":-65.0,"ew":-63.8}, + {"spell":4237,"name":"Aerbax Recall West Platform","cell":"2E2F0023","place":"outdoor","ns":-64.1,"ew":-64.7}, + {"spell":4256,"name":"Jester Recall 1","cell":"00D70225","place":"dungeon"}, + {"spell":4257,"name":"Jester Recall 2","cell":"00D70226","place":"dungeon"}, + {"spell":4258,"name":"Jester Recall 3","cell":"00D70223","place":"dungeon"}, + {"spell":4259,"name":"Jester Recall 4","cell":"00D70220","place":"dungeon"}, + {"spell":4260,"name":"Jester Recall 5","cell":"00D7021F","place":"dungeon"}, + {"spell":4261,"name":"Jester Recall 6","cell":"00D7021E","place":"dungeon"}, + {"spell":4262,"name":"Jester Recall 7","cell":"00D70221","place":"dungeon"}, + {"spell":4263,"name":"Jester Recall 8","cell":"00D70224","place":"dungeon"}, + {"spell":5175,"name":"Facility Hub Recall","cell":"8A020212","place":"dungeon","in":"Hub of Awakening"}, + {"spell":5330,"name":"Gear Knight Invasion Area Camp Recall","cell":"21700031","place":"outdoor","ns":-12.29,"ew":-74.94}, + {"spell":5541,"name":"Lost City of Neftet Recall","cell":"8763000E","place":"outdoor","ns":-22.21,"ew":6.22}, + {"spell":6150,"name":"Rynthid Recall","cell":"3032001C","place":"outdoor","ns":-61.58,"ew":-63.2}, + {"spell":6321,"name":"Viridian Rise Recall","cell":"B3490013","place":"outdoor","ns":-43.28,"ew":41.53}, + {"spell":6322,"name":"Viridian Rise Great Tree Recall","cell":"B44A0039","place":"outdoor","ns":-42.7,"ew":42.85}, + {"spell":6325,"name":"Celestial Hand Stronghold Recall","cell":"E74D003F","place":"outdoor","ns":-39.67,"ew":83.63}, + {"spell":6326,"name":"Eldrytch Web Stronghold Recall","cell":"BDA00023","place":"outdoor","ns":26.27,"ew":49.66}, + {"spell":6327,"name":"Radiant Blood Stronghold Recall","cell":"808F0014","place":"outdoor","ns":12.8,"ew":0.68} + ] +} diff --git a/tools/navdata/NavData/portals.tsv b/tools/navdata/NavData/portals.tsv new file mode 100644 index 0000000..37a7154 --- /dev/null +++ b/tools/navdata/NavData/portals.tsv @@ -0,0 +1,648 @@ +45.4 -42.3 57.5 -52.8 Adams' Beach Portal +66.5 14.1 28.8 -36.8 Adept's Domain Portal +-0.9 19.0 1.6 36.1 Adventurer's Haven Cottages Portal +42.1 33.6 84.1 47.2 Aerlinthe Island (Instance) +42.1 33.6 84.1 47.2 Aerlinthe Island (Player Killer) +-33.5 12.9 -21.7 18.4 Ahr-Zona Portal +-31.3 72.6 -28.2 75.1 Aimaru Plains Cottages Portal +5.8 4.3 -12.1 -2.7 Al-Arqis Cottages Portal +-33.5 13.2 -34.5 18.1 Al-Hatar Settlement Portal +-33.6 13.1 -33.2 9.8 Al-Kasan Settlement Portal +-49.2 26.0 -47.1 16.9 Al-Mar Oasis Portal +-33.4 13.1 -12.1 14.4 Al-Nosaj Portal +5.8 4.3 20.0 10.4 Alfreth Ridge Cottages Portal +45.5 -42.4 50.3 -26.4 Aloria Portal +32.9 59.5 68.2 40.7 Alvador Portal +27.8 29.4 38.7 -9.6 Amarand Villas Portal +66.5 14.1 69.5 -4.0 Anadil Portal +-22.5 0.2 -7.1 -2.7 Aqalah Portal +-49.5 25.9 -39.9 33.0 Ardent Realm Portal +-30.5 94.5 -16.7 77.1 Ariake Portal +-24.9 29.8 -23.0 37.2 Arida Butte Portal +-33.5 13.2 -24.7 15.2 Arqasanti Portal +-24.8 29.6 -9.6 4.6 Arrak Portal +-41.4 82.1 64.8 72.1 Arrowdale Cottages Portal +32.9 59.6 -84.7 12.8 Artifice Cottages Portal +17.5 61.6 56.9 -27.1 Asandra Cottages Portal +2.1 50.5 -0.9 39.9 Asbel Domain Portal +16.2 69.3 21.3 69.2 Asheron's Castle +17.9 64.3 16.1 69.3 Asheron's Island +45.3 -42.3 51.9 -45.6 Auralla Settlement Portal +27.9 29.6 23.3 26.5 Auroch Pasture Estates Portal +-49.3 25.9 -56.9 20.6 Avatania Cottages Portal +-74.9 17.6 30.5 -40.7 Axefall Glen Portal +-27.1 59.9 -39.0 55.4 Ayn Tayan Portal +-74.8 17.9 84.1 -31.1 Azaroth Cottages Portal +-76.0 -67.1 65.0 49.3 Bandit Castle +42.5 60.5 65.0 49.3 Bandit Castle Portal +45.8 -8.0 65.0 49.3 Bandit Castle Portal +66.2 14.3 71.1 43.7 Bandit Road Villas Portal +33.1 59.5 64.9 37.6 Baron's Domain Portal +19.5 17.5 19.6 17.0 Base of Mt. Alphus +20.2 15.0 19.6 17.0 Base of Mt. Alphus +11.2 12.2 11.6 12.3 Base of Mt. Syliph +42.3 -77.9 42.0 -77.8 Base of the Cliffs Portal +44.1 -77.8 43.9 -77.7 Base of the Timaru Plateau Portal +5.7 4.3 1.7 -5.1 Bay of Sands Portal +17.6 61.4 47.4 69.6 Beach Pass Villas Portal +-9.4 -71.9 23.6 63.5 Beachside +71.7 -61.0 79.2 -68.0 Beacon Tower +79.2 -68.0 71.7 -61.0 Beacon Tower Exit +80.2 -68.2 71.7 -61.0 Beacon Tower Exit +80.2 -67.8 71.7 -61.0 Beacon Tower Exit +80.4 -68.0 71.7 -61.0 Beacon Tower Exit +28.0 29.5 14.7 19.4 Bellig Mesa Cottages Portal +-49.4 25.9 -41.2 26.8 Bhah Dhah Villas Portal +-62.2 -50.5 -62.4 -52.3 Black Hill +-27.2 60.0 -27.8 46.8 Blackmire Edge Cottages Portal +-10.4 45.6 27.9 -3.8 Blazing Wand Villas Portal +-33.5 13.0 -14.5 9.6 Bleached Skull Wastes Settlement Portal +33.0 59.5 53.5 41.7 Bleak Valley Portal +-41.5 82.2 -20.3 78.5 Bluewater Cottages Portal +-83.0 48.1 73.6 -42.3 Brazenn Domain Portal +66.2 14.3 68.1 36.7 Bretslef Cottages Portal +-49.3 26.0 -60.9 24.9 Brigand Sands Cottages Portal +-74.8 17.8 -89.5 31.0 Brigands Bay Settlement Portal +12.8 -1.7 25.7 -0.8 Bright Blade Cottages Portal +-10.4 45.7 -12.1 63.5 Broadacre Cottages Portal +33.1 59.5 72.1 55.2 Broken Haft Vale Portal +-24.8 29.8 -16.9 37.2 Broken Sword Bethel Settlement Portal +5.8 4.3 41.3 15.6 Bucolic Villas Portal +-1.0 18.9 -9.0 24.8 Cactus Acres Portal +45.5 -42.3 55.2 -49.6 Caerlin Cottages Portal +32.9 59.4 30.1 65.8 Cape Feirgard Cottages Portal +75.9 -61.3 82.1 -74.2 Cataracts of Sabella +66.5 14.2 92.2 9.9 Celcynd Cottages Portal +66.4 14.3 86.7 29.4 Celdiseth's Beach Settlement Portal +23.9 -28.0 56.1 -75.2 Central Tuatara Plains Portal +-25.0 29.8 -0.2 30.4 Charbone Ridge Portal +-0.8 19.1 39.3 4.0 Charnhold Portal +-31.3 72.6 -29.3 70.0 Chi Zou Cottages Portal +26.3 46.3 59.3 40.9 Colier View Hill Portal +26.2 46.3 20.1 43.6 Cragstone Farms Portal +-39.4 81.3 25.9 48.4 Cragstone Portal +22.2 51.9 25.3 50.0 Cragstone Portal +-10.4 45.8 -14.6 66.4 Crescent Lane Cottages Portal +32.9 59.6 83.3 28.8 Dagger Vale Portal +-30.4 94.5 42.5 -26.3 Dame Tolani Villas Portal +16.6 -1.6 23.2 -29.9 Danby's Outpost +-0.9 19.1 35.3 -8.7 Darasa Villas Portal +2.2 50.5 9.5 40.7 Darawyll Village Portal +12.6 -1.6 36.0 -24.1 Deepvale Cottages Portal +32.8 59.4 57.8 2.4 Defiant Prey Cottages Portal +-24.9 29.5 8.9 32.0 Demonsbane Cottages Portal +17.4 61.6 7.1 -9.1 Desert Boundary Cottages Portal +-33.4 13.1 -15.2 13.7 Desert Mirage Cottages Portal +-72.2 90.6 17.6 19.6 Desert Northern Edge Portal +-78.1 -48.6 -5.6 40.0 Desert Ridge Border +-72.7 14.0 -5.6 40.0 Desert Ridge Border +-11.2 37.4 -5.6 40.0 Desert Ridge Border +54.3 -4.2 -5.6 40.0 Desert Ridge Border +-49.3 25.9 -43.9 11.8 Desert Vanguard Cottages Portal +69.7 -20.2 82.4 -43.5 Desolation Beach Portal +40.1 -76.1 46.1 -89.8 Destroyed Ahurenga Portal +68.6 -20.7 46.1 -89.8 Destroyed Ahurenga Portal +-48.1 24.6 7.2 5.0 Destroyed Al-Jalima Portal +33.6 57.2 7.2 5.0 Destroyed Al-Jalima Portal +-82.6 63.8 -49.3 62.9 Destroyed Baishi Portal +-61.5 52.7 -49.3 62.9 Destroyed Baishi Portal +-58.8 -88.4 -49.3 62.9 Destroyed Baishi Portal +-34.4 64.7 16.9 63.5 Destroyed Eastham Portal +-82.6 -70.2 29.8 26.4 Destroyed Glenden Wood Portal +21.5 -51.6 29.8 26.4 Destroyed Glenden Wood Portal +36.7 29.1 29.8 26.4 Destroyed Glenden Wood Portal +-47.7 25.0 -53.9 74.3 Destroyed Lin Portal +9.5 60.0 1.1 51.7 Destroyed Lytelthorpe Portal +-86.2 -0.7 -61.9 82.5 Destroyed Mayoi Portal +-83.6 -34.6 -61.9 82.5 Destroyed Mayoi Portal +-66.4 60.1 -61.9 82.5 Destroyed Mayoi Portal +54.4 -4.1 -61.9 82.5 Destroyed Mayoi Portal +29.3 -52.0 44.5 -43.1 Destroyed Plateau Portal +26.2 63.9 33.3 56.6 Destroyed Portal to Arwic +40.9 55.8 33.3 56.6 Destroyed Portal to Arwic +-52.7 79.8 39.5 -75.3 Destroyed Portal to Bluespire +-28.3 13.6 39.5 -75.3 Destroyed Portal to Bluespire +1.2 54.0 39.5 -75.3 Destroyed Portal to Bluespire +47.4 -88.9 39.5 -75.3 Destroyed Portal to Bluespire +14.8 0.7 25.9 48.4 Destroyed Portal to Cragstone +52.2 3.0 25.9 48.4 Destroyed Portal to Cragstone +70.4 -34.5 25.9 48.4 Destroyed Portal to Cragstone +71.2 -61.3 90.3 -43.3 Destroyed Portal to Eastwatch +-33.6 72.4 43.2 -66.8 Destroyed Portal to Greenspire +-21.7 -1.8 43.2 -66.8 Destroyed Portal to Greenspire +11.1 59.6 43.2 -66.8 Destroyed Portal to Greenspire +40.6 -82.4 43.2 -66.8 Destroyed Portal to Greenspire +-88.2 -64.6 -38.9 82.6 Destroyed Portal to Hebian-To +23.6 -7.7 -38.9 82.6 Destroyed Portal to Hebian-To +25.4 47.8 -38.9 82.6 Destroyed Portal to Hebian-To +-1.6 18.4 42.1 33.6 Destroyed Portal to Holtburg +1.7 49.9 42.1 33.6 Destroyed Portal to Holtburg +10.1 57.4 42.1 33.6 Destroyed Portal to Holtburg +38.3 -75.5 42.1 33.6 Destroyed Portal to Holtburg +54.2 -4.1 42.1 33.6 Destroyed Portal to Holtburg +57.6 37.6 42.1 33.6 Destroyed Portal to Holtburg +70.5 -8.1 42.1 33.6 Destroyed Portal to Holtburg +72.3 -60.7 42.1 33.6 Destroyed Portal to Holtburg +-54.9 73.1 -47.5 25.6 Destroyed Portal to Khayyaban +7.5 5.1 -47.5 25.6 Destroyed Portal to Khayyaban +-70.2 84.6 -74.6 84.2 Destroyed Portal to Kryst +40.5 -83.7 -52.2 82.5 Destroyed Portal to Nanto +-15.9 46.7 40.6 -83.0 Destroyed Portal to Redspire +-3.5 22.4 40.6 -83.0 Destroyed Portal to Redspire +42.6 33.4 40.6 -83.0 Destroyed Portal to Redspire +43.3 -68.2 40.6 -83.0 Destroyed Portal to Redspire +70.1 -61.9 40.6 -83.0 Destroyed Portal to Redspire +2.3 52.0 10.8 59.3 Destroyed Portal to Rithwic +-32.6 14.4 -3.2 19.0 Destroyed Portal to Samsur +-34.3 73.4 72.1 -60.9 Destroyed Portal to Sanamar +-22.1 -1.5 72.1 -60.9 Destroyed Portal to Sanamar +40.8 -83.1 72.1 -60.9 Destroyed Portal to Sanamar +41.0 35.5 72.1 -60.9 Destroyed Portal to Sanamar +72.9 -73.2 72.1 -60.9 Destroyed Portal to Sanamar +90.3 -43.2 72.1 -60.9 Destroyed Portal to Sanamar +-14.7 46.5 -33.5 72.8 Destroyed Portal to Shoushi +11.0 59.3 -33.5 72.8 Destroyed Portal to Shoushi +72.3 -60.7 -33.5 72.8 Destroyed Portal to Shoushi +-54.0 73.9 -30.4 94.7 Destroyed Portal to Tou-Tou +7.1 4.5 -30.4 94.7 Destroyed Portal to Tou-Tou +33.8 56.4 -30.4 94.7 Destroyed Portal to Tou-Tou +71.2 -61.3 72.8 -73.4 Destroyed Portal to Westwatch +-52.7 80.3 -10.7 46.5 Destroyed Portal to Yanshi +91.3 49.7 -10.7 46.5 Destroyed Portal to Yanshi +-71.0 52.3 -21.5 -1.8 Destroyed Portal to Yaraq +-12.1 46.3 -21.5 -1.8 Destroyed Portal to Yaraq +-3.8 18.6 -21.5 -1.8 Destroyed Portal to Yaraq +42.5 -67.5 -21.5 -1.8 Destroyed Portal to Yaraq +72.3 -60.7 -21.5 -1.8 Destroyed Portal to Yaraq +23.4 -7.8 13.5 0.7 Destroyed Portal to Zaikhal +26.4 48.6 13.5 0.7 Destroyed Portal to Zaikhal +82.2 -50.2 13.5 0.7 Destroyed Portal to Zaikhal +83.1 -51.4 13.5 0.7 Destroyed Portal to Zaikhal +83.4 -49.3 13.5 0.7 Destroyed Portal to Zaikhal +84.1 -50.4 13.5 0.7 Destroyed Portal to Zaikhal +-82.2 -36.5 -74.7 19.6 Destroyed Qalaba'r Portal +14.7 -0.8 -74.7 19.6 Destroyed Qalaba'r Portal +-82.5 63.8 -29.1 58.9 Destroyed Sawato Portal +-73.5 -36.2 -29.1 58.9 Destroyed Sawato Portal +85.8 -27.6 68.7 -21.8 Destroyed Stonehold Portal +-60.6 -88.1 -24.8 28.4 Destroyed Uziz Portal +2.2 50.3 -1.7 33.6 Devana Portal +5.7 4.2 11.1 23.5 Dillo Butte Settlement Portal +45.5 -42.3 23.1 -54.2 Dire's Edge Portal +72.2 -35.6 -88.3 -64.5 Direlands Midland Portal +-74.0 -52.4 5.8 -91.0 Direlands Northwest Shore Portal +-74.2 -52.4 -42.9 -63.5 Direlands Valleys Portal +69.7 -20.2 78.1 -16.9 Dires' Door Estates Portal +-83.0 48.1 33.0 -22.2 Direvale Villas Portal +-25.0 29.8 -16.1 21.4 Djebel al-Nar Cottages Portal +-33.4 13.2 -22.3 11.1 Djinaya Wind Cottages Portal +-1.1 18.9 24.2 10.5 Dovetail Valley Villas Portal +-65.3 -43.3 -65.3 -43.4 Down to Surface +-33.6 13.2 -29.5 18.8 Dry Bone Manors Portal +-30.5 94.6 -12.8 77.2 Dryreach Beach Cottages Portal +17.4 61.5 -3.9 76.3 Dryreach Beach Manors Portal +-25.1 29.8 -8.8 28.0 Drytree Settlement Portal +-49.5 26.0 -47.5 19.9 Dunes End Cottages Portal +69.7 -20.3 42.5 4.7 Durglen Portal +5.7 4.4 7.7 17.7 East Al-Jalima Villas Portal +12.6 -1.7 24.9 -23.9 East Danby Portal +-8.1 74.5 -39.8 -54.1 East Direlands Swamp +66.3 14.3 72.5 28.0 East Esper Valley Portal +2.2 50.4 0.2 57.9 East Lytelthorpe Settlement Portal +69.7 -20.1 35.2 -15.1 East Morntide Settlement Portal +45.4 -42.4 38.5 -12.7 East Morntide Villas Portal +8.7 60.9 10.4 66.3 East Rithwic Estates Portal +-27.2 59.9 -27.6 63.9 East Sawato Settlement Portal +32.9 59.4 32.9 48.4 East Span Way Settlement Portal +-72.4 82.2 18.5 65.8 Eastham Beach Portal +27.8 29.5 32.5 18.5 Eaves of Tiofor Settlement Portal +-74.8 17.7 -61.7 14.5 Ebbing Tide Villas Portal +12.7 -1.6 27.0 -18.2 Embara Portal +-27.1 59.9 -38.2 43.3 Empyrean Fields Cottages Portal +69.7 -20.2 83.4 -40.3 Empyrean Shore Villas Portal +2.1 50.4 5.7 36.9 Enchanter's Meadow Portal +32.9 59.5 41.0 60.7 Eotensfang Cottages Portal +65.0 49.3 42.3 60.5 Eotensfang Portal +-49.3 26.0 -56.9 35.3 Erevana Villas Portal +40.2 35.1 41.6 40.7 Evensong Settlement Portal +-35.1 33.7 -34.0 33.5 Exit +-29.6 91.3 -29.0 91.7 Exit +12.1 2.3 12.4 2.1 Exit +88.9 -67.8 89.2 -67.8 Exit Karlun's Fort +-2.8 -82.8 -4.5 -84.4 Exit Portal +-2.8 -82.8 -4.5 -81.2 Exit Portal +-27.1 60.0 61.5 65.7 Explorer's Villas Portal +45.3 -42.4 48.8 -43.9 Fadsahil Settlement Portal +32.9 59.4 54.4 59.5 Far Claw Villas Portal +26.1 46.3 92.9 -2.4 Far Horizon Cottages Portal +-10.2 45.6 -15.2 41.0 Faranar Foothills Portal +5.7 4.2 24.1 -19.1 Fearnot Valley Cottages Portal +17.5 61.4 13.4 63.4 Filos' Font Cottages Portal +27.8 29.6 46.5 10.6 Firedew Portal +-10.4 45.7 38.4 -26.3 Firesong Cottages Portal +76.6 -58.6 95.9 -56.8 Fiun Outpost +-60.8 80.2 -62.3 68.9 Font Alpa Portal +26.2 46.3 14.1 37.8 Forgotten Hills Portal +12.4 2.3 12.2 2.4 Four Towers Entrance +5.7 4.3 12.4 5.6 Four Towers Settlement Portal +-63.9 97.2 -64.1 97.5 Freebooter Keep +66.4 14.3 77.6 6.4 Frosty Dale Cottages Portal +8.7 60.8 6.3 62.9 Gaerwel Edge Settlement Portal +28.0 29.5 34.4 -11.9 Genem Causland Portal +12.6 -1.6 17.6 -12.7 Gharu'n Victory Villas Portal +27.9 29.5 32.2 31.0 Glenden Hills East Settlement Portal +27.9 29.5 35.0 26.8 Glenden Hills North Settlement Portal +8.8 60.9 64.1 29.5 Glystaene Cottages Portal +-74.9 17.7 -60.1 32.1 Gredaline Villas Portal +-1.0 18.9 7.4 24.6 Greenswath Portal +66.5 14.2 80.0 11.3 Greenvale Settlement Portal +-87.5 -67.2 -87.6 -67.1 Ground Portal +26.2 46.3 73.1 61.0 Haliana Portal +-33.6 13.0 -21.6 15.2 Hamud Cottages Portal +32.8 59.3 50.4 69.7 Hand-on-Sword Cottages Portal +-83.0 48.0 28.1 -22.4 Harmonious Blade Cottages Portal +-61.8 40.0 22.6 37.2 Heartland +-57.1 -68.9 22.6 37.2 Heartland +-31.4 37.0 22.6 37.2 Heartland +-2.5 -85.7 22.6 37.2 Heartland +68.9 -21.3 22.6 37.2 Heartland +-73.2 18.1 -38.9 82.6 Hebian-to Portal +12.7 -1.7 22.1 0.7 Helms Villas Portal +17.5 61.6 14.6 30.5 Hermit Hill Cottages Portal +45.6 -42.4 30.6 -45.4 Hero's Vale Portal +69.6 -20.3 59.3 -19.1 Hidden Valley Portal +-61.9 40.0 -65.2 60.3 High Mountain Valley +26.4 63.9 -65.2 60.3 High Mountain Valley +28.0 29.5 63.2 16.9 Highland Manors Portal +-72.6 13.8 32.8 34.7 Hilltop +1.7 -71.5 32.8 34.7 Hilltop +59.7 -4.0 32.8 34.7 Hilltop +64.8 13.5 32.8 34.7 Hilltop +40.2 35.1 40.7 47.2 Holtburg Wilderness Settlement Portal +-24.9 29.5 32.8 -34.3 Hopevale Portal +28.0 29.4 28.6 17.7 Howling Wolf Villas Portal +66.5 14.2 52.4 5.4 Ianna Portal +69.7 -20.3 64.0 -16.7 Ice's Edge Cottages Portal +27.9 29.4 25.8 30.0 Iceea Hills Estates Portal +-22.4 0.3 -33.0 4.5 Ijaniya Portal +-82.9 48.2 -59.9 35.2 Ikama Cottages Portal +-10.4 45.6 -15.9 60.7 Imuth Maer Cottages Portal +-60.9 80.3 26.4 -33.6 Inquisitor's Dale Cottages Portal +-82.9 48.2 -81.5 51.6 Ishilai Inlet Settlement Portal +-82.9 48.0 -84.7 51.5 Ishilai Inlet Villas Portal +-85.0 -47.8 22.6 51.9 Isle of Tears Portal +25.2 49.9 22.6 51.9 Isle of Tears Portal +26.2 46.3 52.6 28.0 Ispan Hill Portal +8.7 60.8 65.0 65.7 Isparian Flame Estates Portal +-63.1 96.0 -82.6 88.8 Ithaenc Archipelago +5.7 4.3 -0.1 8.5 Jackcat Canyon Portal +-50.1 63.5 -45.6 59.2 Jai-Tan Dale Portal +-0.9 19.0 -7.0 22.3 Janaa Ridge Settlement Portal +-50.2 63.4 -44.7 49.6 Jasmine Meadow Portal +-10.2 45.6 -4.7 44.6 Jenshi Cottages Portal +32.9 59.3 53.7 70.4 Jeweled Thorn Estates Portal +2.1 50.4 -7.2 60.5 Jin-Lai Stronghold Portal +-27.2 60.0 -27.6 43.3 Jinianshi Portal +-49.4 26.0 -51.1 36.2 Kanasa Portal +55.9 -75.0 38.1 -77.7 Karab Delta Portal +89.0 -67.6 88.8 -67.9 Karlun's Fort +-50.0 63.5 -46.6 41.5 Kelnen Village Portal +8.7 61.0 9.6 36.9 King Pwyll Square Portal +-27.2 60.0 -35.9 40.8 Kuyiza Portal +-60.9 80.3 74.4 -46.3 Lady Maila Estates Portal +69.7 -20.3 67.5 -16.8 Laiti's Villa Portal +17.5 61.4 16.7 57.3 Lake Blessed Cottages Portal +69.6 -20.2 62.8 0.1 Lake NemuelSettlement Portal +-82.9 48.0 -72.0 42.4 Lake Thrasyl Cottages Portal +27.8 29.5 37.8 0.7 Lanadryll Cottages Portal +-74.9 17.9 -87.2 3.5 Land Bridge Villas Portal +45.5 -42.4 23.2 -46.2 Last-Stop-Before-Dires Villas Portal +8.7 60.9 12.9 52.9 Leafdawning Settlement Portal +-10.4 45.6 -31.8 46.5 Li-Po Cottages Portal +-10.4 45.7 -9.0 41.8 Liang Chi Settlement Portal +69.7 -20.3 81.8 -17.7 Lightbringer Dale Cottages Portal +40.2 35.1 48.0 29.2 Lilyglen Cottages Portal +-50.1 63.5 -48.8 69.7 Lin Kiln Park Portal +-74.9 17.8 -82.4 31.4 Linvak Tukal Foothills Settlement Portal +45.4 -42.3 53.2 -36.2 Lithaenean Cottages Portal +-27.3 59.9 -34.3 52.7 Lo-Han Portal +69.6 -20.3 81.0 -11.2 Lord Cambarth Villas Portal +12.7 -1.6 9.3 -12.7 Loredane Villas Portal +26.2 46.4 19.3 26.4 Lost Realm Cottages Portal +33.1 59.5 40.0 63.2 Lost Wish Cottages Portal +-60.8 80.3 -74.5 65.9 Lugian Meadows Settlement Portal +2.2 50.3 -8.9 64.5 Maedew Portal +-50.1 63.4 -52.8 52.9 Mage's Pass Portal +5.6 4.3 -54.4 15.4 Mahara Cottages Portal +12.7 -1.7 25.5 6.7 Maitland Portal +12.7 -1.7 30.9 9.0 Majestic Hill Cottages Portal +-41.6 82.2 39.5 -22.5 Majestic Saddle Cottages Portal +-74.9 17.7 -68.8 30.6 Mattekar Slopes Cottages Portal +-79.2 96.9 -60.8 82.8 Mayoi Beach Portal +-1.0 18.9 15.3 26.3 Maythen Geroyu Villas Portal +-60.8 80.3 -49.4 84.8 Meditation Meadow Portal +26.3 46.3 19.8 39.1 Meerthus Square Portal +66.5 14.2 26.5 -36.7 Merak Portal +8.7 60.9 6.7 54.7 Meridian Cottages Portal +17.6 61.4 84.9 1.6 Midhill Cottages Portal +5.7 4.3 -0.6 -1.2 Midsong Cottages Portal +5.6 4.3 25.0 -3.9 Mimiana Villas Portal +-27.3 60.0 -21.6 60.9 Mire Hill Portal +5.7 4.4 23.2 -42.3 Mirthless Dale Portal +27.8 29.5 30.6 14.6 Mistdweller Villas Portal +-33.6 13.1 -37.9 16.0 Monument Sands Settlement Portal +-25.1 29.8 32.0 -15.1 Morntide Ascent Cottages Portal +-31.3 72.6 -22.2 73.5 Mosswart Place Cottages Portal +20.8 18.5 19.7 17.8 Mount Alphus +40.2 35.1 50.3 35.4 Mountain Keep Cottages Portal +66.2 14.1 58.5 -0.7 Mountain Retreat Cottages Portal +28.0 29.5 34.5 22.5 Mountain Ridge Abodes Portal +34.9 56.0 41.0 56.0 Mountain Shortcut +19.5 16.9 20.2 15.8 Mt. Alphus Valley +11.6 12.3 11.2 12.2 Mt. Syliph Plain +5.7 4.3 4.3 12.3 Musansayn Portal +-1.0 19.0 4.6 20.7 Nal Wadi Cottages Portal +12.8 -1.6 31.3 -25.5 Nalib Cavana Settlement Portal +-30.5 94.5 -48.9 88.5 Nan-Zari Portal +-0.9 19.0 -9.4 11.4 Naqut Dreams Villas Portal +-27.1 59.9 -15.8 72.9 Narsys Portal +-24.8 29.7 -19.5 32.9 Narziz Cottages Portal +2.1 50.4 -7.1 56.9 Neu Gerz Villas Portal +8.8 60.9 66.5 57.6 New Cannthalo Portal +40.2 35.1 61.1 31.2 New Colier Portal +66.2 14.2 53.6 10.4 New Nesortania Portal +12.7 -1.6 18.8 4.2 New Suntik Portal +66.3 14.3 70.9 23.0 Neydisa Village Portal +5.6 4.3 15.3 -17.5 Nidal-Taraq Villas Portal +-82.9 48.2 75.6 52.2 Norstead Portal +-82.8 48.1 -76.0 53.6 North Adjamaer Cottages Portal +-50.1 63.5 -45.0 63.3 North Baishi Cottages Portal +15.7 14.2 14.6 13.2 North Dalt +-72.7 -43.2 -4.7 -3.1 North Desert Edge +-11.4 37.5 -4.7 -3.1 North Desert Edge +19.8 -3.3 -4.7 -3.1 North Desert Edge +61.6 -10.2 -4.7 -3.1 North Desert Edge +-80.2 -42.3 24.4 -53.9 North Direlands Portal +20.9 25.9 24.4 -53.9 North Direlands Portal +61.4 -10.2 24.4 -53.9 North Direlands Portal +17.4 61.5 22.9 60.3 North Eastham Meadow Portal +17.3 16.0 16.3 14.7 North Gemm +2.2 50.5 6.4 49.0 North Lytelthorpe Villas Portal +66.4 14.3 55.2 4.8 North Pass Hollow Cottages Portal +-27.3 59.9 -19.8 55.9 North Sawato Villas Portal +14.1 12.7 12.7 11.8 North Syliph +-24.8 29.7 -21.9 29.9 North Uziz Settlement Portal +2.2 50.3 -4.4 48.0 North Yanshi Plains Settlement Portal +-22.3 0.2 -15.0 -2.7 North Yaraq Villas Portal +41.0 -83.6 52.1 -86.2 Northern Ahurenga Plains Portal +40.0 -74.5 50.5 -68.2 Northern Manumet Plains Portal +44.5 -41.8 50.5 -68.2 Northern Manumet Plains Portal +-45.9 90.8 93.5 7.7 Northern Point +69.7 -20.2 83.1 -27.9 Northfire Estates Portal +-74.8 17.9 83.2 35.4 Northreach Portal +-10.4 45.8 93.9 -5.9 Northwater Cottages Portal +-49.4 -70.8 5.5 -87.5 Northwest Direlands Portal +79.9 -15.2 5.5 -87.5 Northwest Direlands Portal +84.1 47.2 5.5 -87.5 Northwest Direlands Portal +33.0 59.4 72.0 52.1 Norvale Portal +-50.2 63.5 -49.7 40.2 Oboro Portal +-98.0 -94.7 -48.0 -65.0 Obsidian Rim Portal +5.5 -87.5 -48.0 -65.0 Obsidian Rim Portal +-87.7 -65.1 68.5 79.7 Olthoi Tunnel +-62.8 96.2 64.1 80.6 Olthoi Tunnel +12.5 -0.0 67.4 80.3 Olthoi Tunnel +63.5 81.9 32.4 56.3 Olthoi Tunnel +64.1 82.5 69.8 18.8 Olthoi Tunnel +64.1 80.6 -62.8 96.2 Olthoi Tunnel +65.2 82.0 -14.2 43.1 Olthoi Tunnel +65.2 80.7 42.0 -82.7 Olthoi Tunnel +65.4 83.6 -75.2 21.5 Olthoi Tunnel +65.7 80.3 86.1 -52.3 Olthoi Tunnel +66.5 80.2 -93.3 -50.4 Olthoi Tunnel +67.4 80.3 12.4 0.0 Olthoi Tunnel +67.5 79.8 -26.9 94.9 Olthoi Tunnel +68.5 79.7 -87.8 -65.1 Olthoi Tunnel +-30.4 94.6 -46.3 87.3 Ong-Hau Village Portal +2.2 50.5 5.5 40.8 Osric Cottages Portal +-21.6 -74.5 -24.0 -57.8 Outside Accursed Halls Portal +-77.4 28.0 -75.7 28.2 Outside Linvak Tukal +17.7 61.5 69.6 60.9 P'rnelle Acres Portal +-0.8 19.0 11.0 26.4 Palm-of-Stone Villas Portal +63.1 76.4 66.3 84.2 Passage to Olthoi Island +63.7 75.6 69.6 80.7 Passage to Olthoi Island +17.6 63.5 58.5 -10.3 Patriarch's Valley +66.2 14.2 75.3 27.2 Patron's Honor Cottages Portal +66.4 14.3 87.6 14.5 Pavanne Vale Freehold Portal +-82.9 48.0 23.3 -49.6 Peril's Edge Cottages Portal +-33.6 13.0 -44.0 8.7 Pillars-on-the-Sea Cottages Portal +-41.4 82.2 58.6 -41.6 Pine Deep Portal +27.9 29.6 45.7 14.6 Pine Hillock Settlement Portal +87.6 -69.7 90.6 -51.3 Plains of Ruin +-49.4 25.9 -56.9 32.2 Plainsview Cottages Portal +44.4 -43.5 45.3 -44.3 Plateau Base +45.4 -42.3 35.8 -39.1 Plateau Hollow Settlement Portal +43.2 -43.3 44.4 -43.5 Plateau Top +45.3 -44.2 44.4 -43.5 Plateau Top +-60.9 80.3 96.3 7.1 Point Tremblant Portal +79.8 57.4 33.3 56.6 Portal to Arwic +21.0 69.1 25.9 48.4 Portal to Cragstone +21.0 69.3 -38.9 82.6 Portal to Hebian-To +3.9 -72.5 4.0 -73.7 Portal to Lighthouse +-75.7 28.2 -77.8 28.0 Portal to Linvak Tukal +-75.0 19.5 87.3 -70.8 Portal to Silyun +76.6 -58.7 87.3 -70.9 Portal to Silyun +90.6 -51.1 87.3 -70.9 Portal to Silyun +95.6 -56.2 87.3 -70.9 Portal to Silyun +-38.1 -60.3 2.3 -0.8 Precarious Sojourn Exit Portal +66.3 14.3 56.7 20.2 Prosper River Headwaters Portal +-40.8 81.9 -74.7 19.6 Qalaba'r Portal +-74.8 17.9 -67.6 14.6 Qalaba'r Seaside Villas Portal +-74.8 17.8 -66.4 21.8 Qalabar Oasis Settlement Portal +66.3 80.4 67.8 81.6 Queen's Burrow +67.6 80.2 68.0 81.8 Queen's Burrow +45.3 -42.3 52.1 -39.9 Rahvard Square Portal +28.0 29.6 18.2 22.7 Redrock Cottages Portal +69.7 -20.2 54.5 -19.9 Regina Cottages Portal +-49.5 26.0 39.3 -29.6 Rending Talon Cottages Portal +-49.3 26.0 30.4 -18.2 Rethux Vale Portal +-1.1 18.9 -6.4 4.2 Return of Mumiyah Cottages Portal +5.7 4.2 34.4 0.7 Reviled Maw Cottages Portal +45.4 -42.4 47.1 -39.3 Rhynntal Cottages Portal +-21.5 -74.7 -53.0 61.1 Ridge Tower +-50.1 63.4 -47.9 51.1 Ring of Crystals Estates Portal +27.2 47.3 28.6 48.0 River Bridge Portal +28.5 48.0 27.1 47.4 River Bridge Portal +28.8 6.7 55.9 -52.2 River Mouth +-11.4 37.6 -2.3 63.3 Riverbend +2.2 50.5 -3.5 64.7 Riverbend Cottages Portal +45.5 -42.3 51.6 -50.2 Rivermouth Villas Portal +-74.8 17.9 -63.1 35.4 Ro-Nan Portal +45.5 -42.5 45.6 -36.0 Rytheran Dale Portal +-41.5 82.1 -44.6 75.3 Sai-Nan Portal +-0.9 19.0 -6.5 15.5 Samsur Butte Cottages Portal +-41.5 82.1 -22.4 68.7 San-Chin Portal +12.7 -1.7 19.2 -18.3 Sanai Portal +-74.8 17.6 31.2 -11.9 Sanam Batal Villas Portal +-24.9 29.8 -13.7 17.3 Sand Kings Cottages Portal +-74.8 17.9 -12.7 0.9 Sand Shallow Cottages Portal +-1.0 19.0 5.7 30.8 Sand's Edge Portal +-49.3 25.9 -39.9 23.2 Sands-of-the-Skull Cottages Portal +-27.2 59.9 -31.7 63.3 Sawato Foothills Settlement Portal +-74.8 17.9 -86.4 37.7 Scimitar Lake Cottages Portal +-27.2 60.0 -21.9 65.6 Sclavavania Portal +69.5 -20.2 88.2 -13.4 Seaview Ridge Cottages Portal +32.9 59.3 51.9 67.2 Secluded Valley Cottages Portal +32.9 59.4 52.0 64.0 Sennon Valley Retreat Portal +-49.4 26.0 -50.5 11.7 Serpent Hills Settlement Portal +66.4 14.3 62.5 8.3 Shaky Ledge Cottages Portal +-50.2 63.4 -54.4 43.1 Shara Portal +12.7 -1.8 15.0 -6.4 Sharvale Portal +-41.5 82.2 -40.8 76.7 Shian-To Cottages Portal +-49.4 25.9 -40.0 36.1 Shield of Ispar Villas Portal +-61.0 80.3 29.5 -33.5 Shield of Valor Cottages Portal +-83.5 47.1 -27.9 68.4 Sho Roadside +-62.6 -50.2 -27.9 68.4 Sho Roadside +64.9 13.6 -27.9 68.4 Sho Roadside +80.6 -44.4 -27.9 68.4 Sho Roadside +-60.8 80.2 12.0 -15.9 Shore Vista Cottages Portal +-31.3 72.6 -36.7 68.5 Shou-Zin Portal +8.7 60.8 -0.4 68.2 Siege Road Settlement Portal +8.8 60.8 3.0 65.7 Siege Road Villas Portal +-74.8 17.7 -81.9 17.1 Simda'r Villas Portal +-80.6 -37.4 0.4 -80.1 Slaughterhouse +8.8 60.8 3.2 60.1 Slinker Meadows Portal +17.5 61.6 34.7 -49.0 Sliver-of-BlueCottages Portal +-62.1 -52.3 -62.1 -50.5 Small Black Hill +-62.0 -50.0 -62.1 -50.5 Small Black Hill +-62.1 -50.4 -62.0 -50.0 Small Hill Base +-29.1 91.7 -29.6 91.3 Smugglers Fort +-10.2 45.7 -15.1 55.6 Snakehead Portal +-30.5 94.6 85.3 -8.8 Snowy Valley Portal +26.3 46.3 20.1 33.6 Solstice Hill Portal +27.8 29.5 24.8 15.3 Soltan Villas Portal +69.6 -20.2 76.7 -36.1 Sonel Portal +-60.8 80.2 60.8 19.3 Songview Portal +-49.2 25.9 -43.9 35.2 Sonpay Portal +-82.8 48.1 -80.6 56.0 South Adjamaer Cottages Portal +33.0 59.4 35.6 65.5 South Beach Pass Villas Portal +16.3 14.7 17.3 16.0 South Bellig +12.7 11.8 14.1 12.7 South Dalt +-80.1 -42.4 -84.2 -34.4 South Direlands Portal +-78.0 -48.7 -84.2 -34.4 South Direlands Portal +-72.7 -43.1 -84.2 -34.4 South Direlands Portal +-62.2 77.1 -84.2 -34.4 South Direlands Portal +14.6 13.2 15.7 14.2 South Gemm +-41.5 82.2 -44.0 80.4 South Hebian-To Cottages Portal +-41.5 82.2 -45.4 83.1 South Hebian-To Estates Portal +-49.4 25.9 -52.6 27.7 South Khayyaban Cottages Portal +2.3 50.4 -2.3 53.9 South Lytelthorpe Portal +-52.8 67.3 -52.3 67.9 South Osteth Peak +-54.6 62.7 -86.2 39.6 South Shore Heights +-41.5 82.1 -40.6 69.3 South Shoushi Villas Portal +-27.3 60.0 -12.7 72.8 South Siege Villas Portal +-24.8 29.6 -34.3 29.3 South Uzis Villas Portal +26.2 46.3 17.4 48.7 South Victory Harbor Portal +-22.3 0.2 -26.6 1.5 South Yaraq Cottages Portal +19.7 17.8 20.8 18.5 South Zabool +32.9 59.4 28.7 59.7 Southeast Arwic Settlement Portal +-18.7 6.8 56.8 12.9 Southern Mt. Esper +-74.9 17.8 -75.8 37.0 Southern Park Portal +-41.5 82.2 -43.1 87.2 Southwest Hebian-To Settlement Portal +-49.5 26.0 -54.7 40.2 Spire Hills Settlement Portal +-0.9 19.1 1.6 21.7 Stone Face Oasis Villas Portal +-1.0 19.0 5.0 16.2 Stone Scar Settlement Portal +-49.5 26.0 35.7 -32.7 Stone Scythe Stronghold Portal +66.2 14.3 78.3 1.0 Stone Triad Dell Portal +12.6 -1.8 14.6 22.7 Stonebend Cottages Portal +-41.4 82.2 -25.7 79.4 Stoneport Villas Portal +66.3 14.4 59.0 7.9 Stonerune Cottages Portal +-74.8 17.7 -85.7 17.0 Stormbrow Portal +45.5 -42.5 56.0 -35.1 Stormtree Villas Portal +17.5 61.5 19.9 57.3 Strathelar's Watch Cottages Portal +51.6 -73.1 52.0 -73.0 Surface +51.8 -73.3 52.0 -73.0 Surface +82.5 -6.5 82.8 -6.4 Surface +83.0 -6.7 82.8 -6.4 Surface +-10.3 45.6 -23.9 44.4 Swamp Temple Place Portal +66.5 14.1 80.8 -35.1 Sweet Maple Cottages Portal +-49.4 26.0 -38.7 39.3 Taklihuan Settlement Portal +-50.2 63.5 -45.8 67.2 Tanshi Portal +-10.3 45.6 31.3 36.2 Taralla Portal +-33.4 13.2 28.2 -25.4 Tarn Vinara Villas Portal +-50.2 63.4 -60.0 44.4 Tattered Ridge Portal +80.3 54.4 70.4 50.5 Temple Exit +70.4 50.5 79.7 54.4 Temple of N'cthail +-1.1 18.9 91.3 5.4 Tharesun Portal +-25.0 29.8 -28.8 21.1 Thasali Cottages Portal +-52.4 68.6 -51.5 68.8 The Lee Side of The Mountain +-52.8 69.1 -52.3 68.6 The Old Keep +69.7 -20.1 81.6 -20.7 Thyrinn Cant Cottages Portal +-41.4 82.1 27.9 -28.8 Tia-Leh Homestead Portal +26.2 46.4 17.3 36.1 Tinkelo Hold Villas Portal +12.6 -1.7 40.7 -5.5 Tiofor Deeps Portal +-30.5 94.5 -38.4 92.1 Tou-Tou Penninsula Cottages Portal +-30.5 94.5 -42.2 90.9 Tou-Tou Road Villas Portal +-39.8 -54.6 -8.1 74.0 Town of Dryreach +-12.2 41.7 -12.8 41.7 Trap Floor Portal +-12.2 41.8 -12.8 41.7 Trap Floor Portal +-12.2 41.7 -12.8 41.7 Trap Floor Portal +-12.1 41.8 -12.8 41.7 Trap Floor Portal +-12.1 41.7 -12.8 41.7 Trap Floor Portal +-12.1 41.7 -12.8 41.7 Trap Floor Portal +-12.1 41.7 -12.8 41.7 Trap Floor Portal +-12.1 41.8 -12.8 41.7 Trap Floor Portal +-12.1 41.8 -12.8 41.7 Trap Floor Portal +-12.1 41.8 -12.8 41.7 Trap Floor Portal +-12.1 41.8 -12.8 41.7 Trap Floor Portal +-12.1 41.7 -12.8 41.7 Trap Floor Portal +-12.1 41.8 -12.8 41.7 Trap Floor Portal +-12.1 41.7 -12.8 41.7 Trap Floor Portal +-12.0 41.8 -12.8 41.7 Trap Floor Portal +-12.0 41.7 -12.8 41.7 Trap Floor Portal +-12.0 41.8 -12.8 41.7 Trap Floor Portal +-12.0 41.7 -12.8 41.7 Trap Floor Portal +-11.9 41.7 -12.8 41.7 Trap Floor Portal +-11.9 41.8 -12.8 41.7 Trap Floor Portal +-11.9 41.8 -12.8 41.7 Trap Floor Portal +5.6 4.2 36.0 4.1 Tusker Notch Portal +45.6 -42.4 39.2 -32.6 Two Hills Cottages Portal +45.5 -42.5 42.5 -29.5 Tyrrin Cottages Portal +5.6 4.2 13.6 16.2 Unified Heart Villas Portal +69.6 -20.3 60.2 -23.9 Verena Portal +-60.8 80.3 -68.0 78.0 Vesayan Overlook Portal +-65.7 84.9 -72.5 81.3 Vesayen Isles Portal +-43.3 -49.0 -72.5 81.3 Vesayen Isles Portal +61.7 48.6 -72.5 81.3 Vesayen Isles Portal +-27.3 59.9 -18.2 63.3 Village Quan Portal +-74.9 17.8 -60.5 18.5 Villalabar Portal +-24.8 29.6 -13.8 26.5 Vulture's Eye Villas Portal +-24.1 -57.7 -21.6 -74.6 Walled Portals +-50.1 63.4 -49.8 56.8 West Baishi Settlement Portal +40.2 35.1 46.5 40.5 West Holtburg Villas Portal +-60.8 80.4 -61.1 73.7 West Mayoi Mountain Villas Portal +27.9 29.4 75.4 40.1 West Norstead Portal +8.7 61.0 11.9 48.1 West Rithwic Estates Portal +-27.1 60.0 -30.8 53.5 West Sawato Cottages Portal +-24.9 29.8 -25.9 22.7 West Uziz Settlement Portal +-10.2 45.7 -21.9 41.0 West Yanshi Namoon Portal +12.6 -1.8 16.9 -9.5 West Zaikhal Freehold Portal +-30.4 94.5 61.5 -52.3 Westshore Cottages Portal +68.6 -23.3 71.6 -29.8 Westward Portal +27.8 29.5 34.1 13.5 Whispering Pines Cottages Portal +-22.4 0.3 -25.4 10.4 Wi Badlands Settlement Portal +45.5 -42.5 37.6 -49.0 Wilomine Villas Portal +66.2 14.1 62.6 3.2 Windrune Cottages Portal +69.5 -20.2 84.0 -1.6 Wisp Lake Cottages Portal +45.6 -42.4 31.1 -28.8 Wolfenvale Portal +40.2 35.1 43.9 18.4 Woodsbane Cottages Portal +69.6 -20.2 77.8 -44.2 Woodshore Cottages Portal +-60.8 80.4 -78.4 60.2 Xinh Portal +-10.3 45.6 -19.0 44.4 Yanshi Namoon North Portal +45.4 -42.4 35.2 -36.1 Yee Villas Portal +-0.9 18.9 -9.5 33.3 Yinar Portal +-82.8 48.1 -71.8 47.3 Yukikaze Portal +-0.9 19.0 -12.0 23.6 Yushad Ridge Cottages Portal +27.9 29.5 22.7 22.7 Zabool Overlook Settlement Portal +-77.2 19.8 13.5 0.7 Zaikhal Portal +45.3 -42.3 76.0 35.3 Zatara Portal +-27.2 59.8 -35.2 46.6 Zin-Dai Portal diff --git a/tools/navdata/NavData/townnet.json b/tools/navdata/NavData/townnet.json new file mode 100644 index 0000000..86d2632 --- /dev/null +++ b/tools/navdata/NavData/townnet.json @@ -0,0 +1,334 @@ +{ + "version": 1, + "setId": "d03cd2b18f461392", + "generated": "2026-10-01T19:19:40Z", + "source": "aeshnidae_world", + "landblocks": ["0007"], + "counts": {"arrivals": 4, "entries": 53, "exits": 49, "npcs": 12}, + "notes": [], + "walkInfo": {"tool": "RynthNav.TownNet build", "dats": ["client_cell_1.dat 348127232 bytes 2026-04-19", "client_portal.dat 926941184 bytes 2026-04-19"], "grid": 0.25, "walkerRadius": 0.48, "clearance": 0.48, "portalClearance": 0.73, "cells": 205, "walks": 196, "walkable": 196, "lengthMin": 31.83, "lengthMax": 120.69, "lengthAvg": 67.46}, + "arrivals": [ + {"id":"A1","cell":"00070133","x":60.0,"y":-70.0,"z":0.005,"entries":10}, + {"id":"A2","cell":"00070143","x":70.0,"y":-60.0,"z":0.005,"entries":11}, + {"id":"A3","cell":"00070145","x":70.0,"y":-80.0,"z":0.005,"entries":20}, + {"id":"A4","cell":"00070156","x":80.0,"y":-70.0,"z":0.005,"entries":12} + ], + "entries": [ + {"guid":"701AC00F","wcid":42852,"name":"Portal to Town Network","cell":"01AC0104","x":-1.612,"y":-21.362,"z":0.198,"place":"dungeon","noOlthoi":true,"arrival":"A3"}, + {"guid":"70EBA013","wcid":42852,"name":"Portal to Town Network","cell":"0EBA0023","x":118.522,"y":52.621,"z":2.198,"place":"outdoor","ns":47.07,"ew":-90.26,"town":{"name":"Ahurenga","dist":1.1},"noOlthoi":true,"arrival":"A3"}, + {"guid":"7113406D","wcid":42852,"name":"Portal to Town Network","cell":"11340026","x":105.754,"y":133.537,"z":42.198,"place":"outdoor","ns":-59.79,"ew":-87.91,"town":{"name":"Ayan Baqur","dist":0.67},"noOlthoi":true,"arrival":"A3"}, + {"guid":"717B201B","wcid":42852,"name":"Portal to Town Network","cell":"17B2001B","x":77.595,"y":58.692,"z":45.165,"place":"outdoor","ns":40.69,"ew":-83.23,"town":{"name":"Redspire","dist":0.27},"noOlthoi":true,"arrival":"A3"}, + {"guid":"71DB6034","wcid":42852,"name":"Portal to Town Network","cell":"1DB6003C","x":181.401,"y":93.589,"z":120.198,"place":"outdoor","ns":44.04,"ew":-77.99,"town":{"name":"Timaru","dist":0.49},"noOlthoi":true,"arrival":"A3"}, + {"guid":"721B0025","wcid":42852,"name":"Portal to Town Network","cell":"21B0000D","x":34.702,"y":118.221,"z":0.198,"place":"outdoor","ns":39.34,"ew":-75.41,"town":{"name":"Bluespire","dist":0.21},"noOlthoi":true,"arrival":"A3"}, + {"guid":"723DA018","wcid":42852,"name":"Portal to Town Network","cell":"23DA0034","x":149.813,"y":78.94,"z":2.198,"place":"outdoor","ns":72.78,"ew":-73.33,"town":{"name":"Westwatch","dist":0.04},"noOlthoi":true,"arrival":"A3"}, + {"guid":"7258104B","wcid":43065,"name":"Portal to Town Network","cell":"2581002C","x":138.929,"y":72.689,"z":220.198,"place":"outdoor","ns":1.55,"ew":-71.77,"town":{"name":"Fort Tethana","dist":0.56},"noOlthoi":true,"arrival":"A2"}, + {"guid":"727EC037","wcid":42852,"name":"Portal to Town Network","cell":"27EC000C","x":36.813,"y":95.737,"z":80.198,"place":"outdoor","ns":87.25,"ew":-70.6,"town":{"name":"Silyun","dist":0.23},"noOlthoi":true,"arrival":"A3"}, + {"guid":"72B1104C","wcid":42852,"name":"Portal to Town Network","cell":"2B110027","x":114.677,"y":160.92,"z":48.198,"place":"outdoor","ns":-87.68,"ew":-67.07,"noOlthoi":true,"arrival":"A3"}, + {"guid":"72CB5012","wcid":42852,"name":"Portal to Town Network","cell":"2CB50003","x":21.117,"y":63.188,"z":0.198,"place":"outdoor","ns":43.11,"ew":-66.66,"town":{"name":"Greenspire","dist":0.18},"noOlthoi":true,"arrival":"A3"}, + {"guid":"732D9057","wcid":42852,"name":"Portal to Town Network","cell":"32D90034","x":155.562,"y":83.545,"z":52.198,"place":"outdoor","ns":72.0,"ew":-61.3,"town":{"name":"Sanamar","dist":0.4},"noOlthoi":true,"arrival":"A3"}, + {"guid":"738F7012","wcid":42852,"name":"Portal to Town Network","cell":"38F70019","x":82.741,"y":15.578,"z":2.198,"place":"outdoor","ns":95.71,"ew":-56.81,"town":{"name":"Fiun","dist":0.17},"noOlthoi":true,"arrival":"A3"}, + {"guid":"73F3101D","wcid":42852,"name":"Portal to Town Network","cell":"3F310017","x":59.639,"y":165.407,"z":0.098,"place":"outdoor","ns":-62.06,"ew":-51.3,"noOlthoi":true,"arrival":"A3"}, + {"guid":"749B6043","wcid":43065,"name":"Portal to Town Network","cell":"49B60007","x":20.637,"y":147.066,"z":240.198,"place":"outdoor","ns":44.26,"ew":-43.46,"town":{"name":"Plateau","dist":0.43},"noOlthoi":true,"arrival":"A2"}, + {"guid":"749F0019","wcid":42852,"name":"Portal to Town Network","cell":"49F0001C","x":87.531,"y":74.792,"z":170.198,"place":"outdoor","ns":90.36,"ew":-43.19,"town":{"name":"Eastwatch","dist":0.07},"noOlthoi":true,"arrival":"A3"}, + {"guid":"75B9C011","wcid":42852,"name":"Portal to Town Network","cell":"5B9C002E","x":123.944,"y":124.93,"z":14.198,"place":"outdoor","ns":23.37,"ew":-28.63,"town":{"name":"Outpost","dist":1.24},"noOlthoi":true,"arrival":"A3"}, + {"guid":"764D504A","wcid":43065,"name":"Portal to Town Network","cell":"64D50013","x":71.74,"y":62.396,"z":78.198,"place":"outdoor","ns":68.71,"ew":-21.65,"town":{"name":"Stonehold","dist":0.18},"noOlthoi":true,"arrival":"A2"}, + {"guid":"77D6406A","wcid":43066,"name":"Portal to Town Network","cell":"7D640025","x":102.999,"y":106.787,"z":12.198,"place":"outdoor","ns":-21.51,"ew":-1.52,"town":{"name":"Yaraq","dist":0.3},"noOlthoi":true,"arrival":"A1"}, + {"guid":"78090080","wcid":43066,"name":"Portal to Town Network","cell":"8090000C","x":37.543,"y":83.632,"z":124.198,"place":"outdoor","ns":13.6,"ew":0.61,"town":{"name":"Zaikhal","dist":0.16},"noOlthoi":true,"arrival":"A1"}, + {"guid":"78588050","wcid":43066,"name":"Portal to Town Network","cell":"8588001E","x":91.613,"y":141.56,"z":86.198,"place":"outdoor","ns":7.44,"ew":4.83,"town":{"name":"Al-Jalima","dist":0.23},"noOlthoi":true,"arrival":"A1"}, + {"guid":"7866C023","wcid":43066,"name":"Portal to Town Network","cell":"866C002F","x":139.232,"y":162.06,"z":10.198,"place":"outdoor","ns":-14.87,"ew":5.83,"town":{"name":"Tufa","dist":0.25},"noOlthoi":true,"arrival":"A1"}, + {"guid":"79058035","wcid":43066,"name":"Portal to Town Network","cell":"90580034","x":156.021,"y":92.105,"z":0.198,"place":"outdoor","ns":-31.17,"ew":13.9,"town":{"name":"Al-Arqas","dist":0.7},"noOlthoi":true,"arrival":"A1"}, + {"guid":"790D000D","wcid":42852,"name":"Portal to Town Network","cell":"90D00014","x":69.171,"y":82.679,"z":282.198,"place":"outdoor","ns":64.79,"ew":13.54,"noOlthoi":true,"arrival":"A3"}, + {"guid":"7934B07B","wcid":43066,"name":"Portal to Town Network","cell":"934B0009","x":38.723,"y":18.452,"z":14.198,"place":"outdoor","ns":-41.87,"ew":15.81,"town":{"name":"Xarabydun","dist":0.3},"noOlthoi":true,"arrival":"A1"}, + {"guid":"795D6014","wcid":42852,"name":"Portal to Town Network","cell":"95D6001C","x":73.934,"y":74.993,"z":100.198,"place":"outdoor","ns":69.56,"ew":17.56,"town":{"name":"Neydisa","dist":0.3},"noOlthoi":true,"arrival":"A3"}, + {"guid":"79722051","wcid":43066,"name":"Portal to Town Network","cell":"9722001D","x":74.298,"y":99.234,"z":102.198,"place":"outdoor","ns":-74.34,"ew":19.16,"town":{"name":"Qalabar","dist":0.5},"noOlthoi":true,"arrival":"A1"}, + {"guid":"7977B04E","wcid":43066,"name":"Portal to Town Network","cell":"977B002F","x":140.431,"y":149.259,"z":0.198,"place":"outdoor","ns":-2.93,"ew":19.44,"town":{"name":"Samsur","dist":0.57},"noOlthoi":true,"arrival":"A1"}, + {"guid":"79E43035","wcid":43066,"name":"Portal to Town Network","cell":"9E430018","x":62.332,"y":191.224,"z":46.198,"place":"outdoor","ns":-47.55,"ew":24.71,"town":{"name":"Khayyaban","dist":0.92},"noOlthoi":true,"arrival":"A1"}, + {"guid":"7A1A408B","wcid":43065,"name":"Portal to Town Network","cell":"A1A40035","x":146.419,"y":118.794,"z":50.198,"place":"outdoor","ns":29.74,"ew":27.46,"town":{"name":"Glenden Wood","dist":1.01},"noOlthoi":true,"arrival":"A2"}, + {"guid":"7A21E011","wcid":42852,"name":"Portal to Town Network","cell":"A21E0024","x":111.676,"y":84.065,"z":590.198,"place":"outdoor","ns":-77.6,"ew":28.12,"town":{"name":"Linvak Tukal","dist":0.23},"noOlthoi":true,"arrival":"A3"}, + {"guid":"7A260022","wcid":43066,"name":"Portal to Town Network","cell":"A2600029","x":129.741,"y":1.408,"z":20.198,"place":"outdoor","ns":-25.14,"ew":28.19,"town":{"name":"Uziz","dist":0.42},"noOlthoi":true,"arrival":"A1"}, + {"guid":"7A9B4080","wcid":43065,"name":"Portal to Town Network","cell":"A9B40003","x":14.393,"y":55.612,"z":78.198,"place":"outdoor","ns":42.28,"ew":33.31,"town":{"name":"Holtburg","dist":0.35},"noOlthoi":true,"arrival":"A2"}, + {"guid":"7B470038","wcid":43067,"name":"Portal to Town Network","cell":"B470002B","x":127.436,"y":51.658,"z":42.198,"place":"outdoor","ns":-12.13,"ew":42.58,"town":{"name":"Yanshi","dist":0.55},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7BA17033","wcid":43067,"name":"Portal to Town Network","cell":"BA170013","x":49.324,"y":62.227,"z":132.198,"place":"outdoor","ns":-83.29,"ew":47.06,"town":{"name":"Kara","dist":0.6},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7BC9F075","guids":["7BC9F075","7BC9F435"],"wcid":43065,"name":"Portal to Town Network","cell":"BC9F003C","x":178.418,"y":78.801,"z":32.198,"place":"outdoor","ns":25.58,"ew":49.19,"town":{"name":"Cragstone","dist":0.91},"noOlthoi":true,"arrival":"A2"}, + {"guid":"7BDD2016","wcid":42852,"name":"Portal to Town Network","cell":"BDD20033","x":164.757,"y":58.764,"z":186.198,"place":"outdoor","ns":66.29,"ew":49.94,"town":{"name":"Bandit Castle","dist":1.47},"noOlthoi":true,"arrival":"A3"}, + {"guid":"7BF8005C","wcid":43065,"name":"Portal to Town Network","cell":"BF80002B","x":139.167,"y":70.662,"z":34.198,"place":"outdoor","ns":0.74,"ew":51.43,"town":{"name":"Lytelthorpe","dist":0.45},"noOlthoi":true,"arrival":"A2"}, + {"guid":"7C6A9074","wcid":43065,"name":"Portal to Town Network","cell":"C6A9001B","x":78.341,"y":58.225,"z":42.198,"place":"outdoor","ns":33.49,"ew":56.78,"town":{"name":"Arwic","dist":0.26},"noOlthoi":true,"arrival":"A2"}, + {"guid":"7C88C066","wcid":43065,"name":"Portal to Town Network","cell":"C88C0016","x":52.266,"y":120.75,"z":22.198,"place":"outdoor","ns":10.55,"ew":58.27,"town":{"name":"Rithwic","dist":1.09},"noOlthoi":true,"arrival":"A2"}, + {"guid":"7C95B06B","wcid":43067,"name":"Portal to Town Network","cell":"C95B002D","x":130.475,"y":101.854,"z":12.198,"place":"outdoor","ns":-28.73,"ew":59.39,"town":{"name":"Sawato","dist":0.64},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7CD4106C","wcid":43067,"name":"Portal to Town Network","cell":"CD410026","x":108.321,"y":125.145,"z":54.198,"place":"outdoor","ns":-49.43,"ew":62.5,"town":{"name":"Baishi","dist":0.42},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7CE95089","wcid":43065,"name":"Portal to Town Network","cell":"CE95002D","x":123.797,"y":114.757,"z":20.198,"place":"outdoor","ns":17.73,"ew":63.37,"town":{"name":"Eastham","dist":0.82},"noOlthoi":true,"arrival":"A2"}, + {"guid":"7DA3B039","wcid":43067,"name":"Portal to Town Network","cell":"DA3B003B","x":181.605,"y":52.809,"z":0.198,"place":"outdoor","ns":-54.53,"ew":73.21,"town":{"name":"Lin","dist":1.26},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7DA55094","wcid":43067,"name":"Portal to Town Network","cell":"DA550014","x":66.182,"y":92.269,"z":20.198,"place":"outdoor","ns":-33.57,"ew":72.73,"town":{"name":"Shoushi","dist":0.08},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7DA75040","wcid":43065,"name":"Portal to Town Network","cell":"DA75002D","x":125.225,"y":108.214,"z":18.198,"place":"outdoor","ns":-7.9,"ew":72.97,"town":{"name":"Dryreach","dist":0.2},"noOlthoi":true,"arrival":"A2"}, + {"guid":"7E63201F","wcid":43067,"name":"Portal to Town Network","cell":"E6320002","x":10.424,"y":36.066,"z":28.198,"place":"outdoor","ns":-61.8,"ew":82.09,"town":{"name":"Mayoi","dist":0.42},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7E63D043","wcid":43067,"name":"Portal to Town Network","cell":"E63D0015","x":53.19,"y":113.003,"z":86.198,"place":"outdoor","ns":-52.68,"ew":82.27,"town":{"name":"Nanto","dist":0.52},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7E74E0EF","wcid":43067,"name":"Portal to Town Network","cell":"E74E0014","x":68.302,"y":92.186,"z":32.198,"place":"outdoor","ns":-39.17,"ew":83.13,"town":{"name":"Hebian-to","dist":0.58},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7E82200F","wcid":43067,"name":"Portal to Town Network","cell":"E822003D","x":181.692,"y":104.404,"z":0.198,"place":"outdoor","ns":-74.31,"ew":84.41,"town":{"name":"Kryst","dist":0.35},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7F222022","wcid":43067,"name":"Portal to Town Network","cell":"F2220030","x":129.227,"y":190.397,"z":18.198,"place":"outdoor","ns":-73.96,"ew":92.19,"town":{"name":"Freehold","dist":0.97},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7F559011","wcid":43067,"name":"Portal to Town Network","cell":"F559003D","x":171.6,"y":113.397,"z":20.198,"place":"outdoor","ns":-30.28,"ew":94.77,"town":{"name":"Tou-Tou","dist":0.16},"noOlthoi":true,"arrival":"A4"}, + {"guid":"7F682018","wcid":42852,"name":"Portal to Town Network","cell":"F6820033","x":145.337,"y":63.357,"z":58.198,"place":"outdoor","ns":2.31,"ew":95.46,"town":{"name":"Refuge","dist":0.05},"noOlthoi":true,"arrival":"A3"} + ], + "exits": [ + {"guid":"70007000","wcid":42830,"name":"Al-Jalima Portal","label":"Al-Jalima","cell":"0007010A","x":3.993,"y":-60.0,"z":-0.063,"heading":270.0,"dest":{"cell":"8588002C","x":120.359,"y":95.47,"z":90.049,"place":"outdoor","ns":7.25,"ew":4.95,"town":{"name":"Al-Jalima","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007001","wcid":42829,"name":"Tufa Portal","label":"Tufa","cell":"0007010C","x":4.089,"y":-80.0,"z":-0.063,"heading":270.0,"dest":{"cell":"876C0008","x":2.0,"y":186.9,"z":18.0,"place":"outdoor","ns":-14.77,"ew":6.06,"town":{"name":"Tufa","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007002","wcid":42831,"name":"Portal to Zaikhal","label":"Zaikhal","cell":"0007010D","x":9.939,"y":-53.813,"z":-0.063,"heading":0.0,"dest":{"cell":"80900013","x":64.863,"y":55.687,"z":124.005,"place":"outdoor","ns":13.48,"ew":0.72,"town":{"name":"Zaikhal","dist":0.0}},"into":false,"setup":"020005D3"}, + {"guid":"7000700A","wcid":42821,"name":"Uziz Portal","label":"Uziz","cell":"00070111","x":9.864,"y":-86.531,"z":-0.063,"heading":180.0,"dest":{"cell":"A260003C","x":182.919,"y":87.934,"z":20.005,"place":"outdoor","ns":-24.78,"ew":28.41,"town":{"name":"Uziz","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"7000700B","wcid":42832,"name":"Portal to Xarabydun","label":"Xarabydun","cell":"00070112","x":20.071,"y":-53.861,"z":-0.063,"heading":0.0,"dest":{"cell":"934B0021","x":108.3,"y":6.1,"z":18.1,"place":"outdoor","ns":-41.92,"ew":16.1,"town":{"name":"Xarabydun","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007013","wcid":42822,"name":"Portal to Khayyaban","label":"Khayyaban","cell":"00070116","x":19.982,"y":-86.444,"z":-0.063,"heading":180.0,"dest":{"cell":"9F440012","x":90.0,"y":24.553,"z":31.885,"place":"outdoor","ns":-47.45,"ew":25.62,"town":{"name":"Khayyaban","dist":0.01}},"into":false,"setup":"020005D3"}, + {"guid":"70007014","wcid":42833,"name":"Qalaba'r Portal","label":"Qalaba'r","cell":"00070117","x":30.011,"y":-53.7,"z":-0.063,"heading":0.0,"dest":{"cell":"9722003A","x":168.354,"y":24.618,"z":102.005,"place":"outdoor","ns":-74.65,"ew":19.55,"town":{"name":"Qalabar","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007018","wcid":42823,"name":"Portal to Al-Arqas","label":"Al-Arqas","cell":"0007011B","x":29.943,"y":-86.341,"z":-0.063,"heading":180.0,"dest":{"cell":"8F58003B","x":183.851,"y":60.183,"z":9.326,"place":"outdoor","ns":-31.3,"ew":13.22,"town":{"name":"Al-Arqas","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007019","wcid":42834,"name":"Portal to Samsur","label":"Samsur","cell":"0007011C","x":39.967,"y":-53.6,"z":-0.063,"heading":0.0,"dest":{"cell":"977B000C","x":25.811,"y":73.853,"z":0.005,"place":"outdoor","ns":-3.24,"ew":18.96,"town":{"name":"Samsur","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007024","wcid":42824,"name":"Portal to Yaraq","label":"Yaraq","cell":"00070120","x":39.996,"y":-86.178,"z":-0.063,"heading":180.0,"dest":{"cell":"7D64000D","x":31.9,"y":104.6,"z":11.9,"place":"outdoor","ns":-21.51,"ew":-1.82,"town":{"name":"Yaraq","dist":0.01}},"into":false,"setup":"020001B3"}, + {"guid":"70007025","wcid":42814,"name":"Glenden Wood Portal","label":"Glenden Wood","cell":"00070121","x":53.5,"y":-10.0,"z":-0.063,"heading":270.0,"dest":{"cell":"A0A40025","x":96.302,"y":119.847,"z":59.955,"place":"outdoor","ns":29.75,"ew":26.45,"town":{"name":"Glenden Wood","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007026","wcid":42816,"name":"Lytelthorpe Portal","label":"Lytelthorpe","cell":"00070122","x":53.404,"y":-20.0,"z":-0.063,"heading":270.0,"dest":{"cell":"C0800007","x":11.723,"y":155.56,"z":33.028,"place":"outdoor","ns":1.1,"ew":51.7,"town":{"name":"Lytelthorpe","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007027","wcid":42818,"name":"Portal to Cragstone","label":"Cragstone","cell":"00070123","x":53.436,"y":-30.01,"z":-0.063,"heading":270.0,"dest":{"cell":"BB9F0040","x":169.358,"y":168.251,"z":54.005,"place":"outdoor","ns":25.95,"ew":48.36,"town":{"name":"Cragstone","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007028","wcid":42820,"name":"Portal to Holtburg","label":"Holtburg","cell":"00070124","x":53.906,"y":-39.953,"z":-0.063,"heading":270.0,"dest":{"cell":"A9B40019","x":84.0,"y":7.1,"z":94.0,"place":"outdoor","ns":42.08,"ew":33.6,"town":{"name":"Holtburg","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007029","wcid":42851,"name":"Portal to Facility Hub","label":"Facility Hub","cell":"00070126","x":53.554,"y":-99.995,"z":-0.063,"heading":270.0,"dest":{"cell":"8A020212","x":58.639,"y":-89.923,"z":6.005,"place":"dungeon"},"into":false,"setup":"020001B3","minLevel":10}, + {"guid":"7000702A","wcid":42825,"name":"Portal to Bluespire","label":"Bluespire","cell":"00070127","x":53.501,"y":-120.015,"z":-0.063,"heading":270.0,"dest":{"cell":"21B00017","x":48.19,"y":165.89,"z":0.005,"place":"outdoor","ns":39.54,"ew":-75.35,"town":{"name":"Bluespire","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"7000702B","wcid":42826,"name":"Portal to Greenspire","label":"Greenspire","cell":"00070128","x":53.545,"y":-129.945,"z":-0.063,"heading":270.0,"dest":{"cell":"2BB5003C","x":178.958,"y":86.57,"z":0.005,"place":"outdoor","ns":43.21,"ew":-66.8,"town":{"name":"Greenspire","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"7000702C","wcid":42827,"name":"Ahurenga Portal","label":"Ahurenga","cell":"00070129","x":53.807,"y":-139.943,"z":-0.063,"heading":270.0,"dest":{"cell":"0FB90009","x":43.0,"y":8.6,"z":0.005,"place":"outdoor","ns":46.09,"ew":-89.77,"town":{"name":"Ahurenga","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"7000702D","wcid":42828,"name":"Portal to Neydisa Castle","label":"Neydisa Castle","cell":"0007012A","x":54.052,"y":-149.981,"z":-0.063,"heading":270.0,"dest":{"cell":"95D60033","x":146.9,"y":71.3,"z":99.8,"place":"outdoor","ns":69.55,"ew":17.86,"town":{"name":"Neydisa","dist":0.0}},"into":false,"setup":"020005D6"}, + {"guid":"7000702E","wcid":42998,"name":"Portal to Silyun","label":"Silyun","cell":"0007012B","x":53.599,"y":-159.971,"z":-0.063,"heading":270.0,"dest":{"cell":"26EC003D","x":175.927,"y":110.334,"z":80.005,"place":"outdoor","ns":87.31,"ew":-70.82,"town":{"name":"Silyun","dist":0.0}},"into":false,"setup":"020001B3","accountRequirements":1}, + {"guid":"7000702F","wcid":42999,"name":"Fiun Outpost","label":"Fiun Outpost","cell":"0007012C","x":53.8,"y":-170.018,"z":-0.063,"heading":270.0,"dest":{"cell":"38F7001B","x":91.0,"y":54.0,"z":-0.095,"place":"outdoor","ns":95.88,"ew":-56.77,"town":{"name":"Fiun","dist":0.01}},"into":false,"setup":"020005D4"}, + {"guid":"70007030","wcid":42812,"name":"Plateau Portal","label":"Plateau","cell":"0007012D","x":60.0,"y":-3.482,"z":-0.063,"heading":0.0,"dest":{"cell":"49B70021","x":100.1,"y":20.8,"z":238.6,"place":"outdoor","ns":44.54,"ew":-43.13,"town":{"name":"Plateau","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"7000704D","wcid":43000,"name":"Base of the Timaru Plateau Portal","label":"Base of the Timaru Plateau","cell":"0007013C","x":60.019,"y":-176.447,"z":-0.063,"heading":180.0,"dest":{"cell":"1DB60016","x":71.387,"y":134.291,"z":90.005,"place":"outdoor","ns":44.21,"ew":-78.45,"town":{"name":"Timaru","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"7000704E","wcid":43001,"name":"Fort Tethana Portal","label":"Fort Tethana","cell":"0007013D","x":69.989,"y":-3.562,"z":-0.063,"heading":0.0,"dest":{"cell":"2681001D","x":77.7,"y":108.1,"z":240.0,"place":"outdoor","ns":1.7,"ew":-71.23,"town":{"name":"Fort Tethana","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"7000705A","wcid":42811,"name":"Stonehold Portal","label":"Stonehold","cell":"00070150","x":79.939,"y":-3.349,"z":-0.063,"heading":0.0,"dest":{"cell":"64D5000B","x":30.0,"y":50.0,"z":78.0,"place":"outdoor","ns":68.66,"ew":-21.82,"town":{"name":"Stonehold","dist":0.01}},"into":false,"setup":"020001B3"}, + {"guid":"70007079","wcid":43002,"name":"Oolutanga's Refuge","label":"Oolutanga's Refuge","cell":"0007015F","x":79.991,"y":-176.283,"z":-0.05,"heading":180.0,"dest":{"cell":"F6820033","x":145.7,"y":49.855,"z":58.005,"place":"outdoor","ns":2.26,"ew":95.46,"town":{"name":"Refuge","dist":0.0}},"into":false,"setup":"020001B3","scale":0.8,"minLevel":10}, + {"guid":"7000707A","wcid":42813,"name":"Portal to Dryreach","label":"Dryreach","cell":"00070160","x":86.415,"y":-10.0,"z":-0.063,"heading":90.0,"dest":{"cell":"DA75002B","x":132.0,"y":60.0,"z":18.005,"place":"outdoor","ns":-8.1,"ew":73.0,"town":{"name":"Dryreach","dist":0.0}},"into":false,"setup":"020005D6"}, + {"guid":"7000707B","wcid":42815,"name":"Eastham Portal","label":"Eastham","cell":"00070161","x":86.491,"y":-20.03,"z":-0.063,"heading":90.0,"dest":{"cell":"CE940035","x":151.053,"y":112.61,"z":17.417,"place":"outdoor","ns":16.92,"ew":63.48,"town":{"name":"Eastham","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"7000707C","wcid":42817,"name":"Portal to Rithwic","label":"Rithwic","cell":"00070162","x":86.241,"y":-30.0,"z":-0.063,"heading":90.0,"dest":{"cell":"C98C0028","x":113.666,"y":190.259,"z":22.005,"place":"outdoor","ns":10.84,"ew":59.32,"town":{"name":"Rithwic","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"7000707D","wcid":42819,"name":"Portal to Arwic","label":"Arwic","cell":"00070163","x":86.856,"y":-39.997,"z":-0.063,"heading":90.0,"dest":{"cell":"C6A90009","x":46.805,"y":4.219,"z":42.005,"place":"outdoor","ns":33.27,"ew":56.65,"town":{"name":"Arwic","dist":0.01}},"into":false,"setup":"020005D3"}, + {"guid":"7000707E","wcid":23032,"name":"The Marketplace of Dereth","label":"The Marketplace of Dereth","cell":"00070165","x":86.129,"y":-99.982,"z":-0.063,"heading":89.2,"dest":{"cell":"016C01BC","x":49.206,"y":-31.935,"z":0.005,"place":"dungeon"},"into":false,"setup":"020001B3","noOlthoi":true}, + {"guid":"7000707F","wcid":42835,"name":"Portal to Sanamar","label":"Sanamar","cell":"00070166","x":86.184,"y":-120.035,"z":-0.063,"heading":90.0,"dest":{"cell":"33D90015","x":59.1,"y":100.3,"z":52.005,"place":"outdoor","ns":72.07,"ew":-60.9,"town":{"name":"Sanamar","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007080","wcid":42836,"name":"Portal to Redspire","label":"Redspire","cell":"00070167","x":86.613,"y":-130.036,"z":-0.063,"heading":90.0,"dest":{"cell":"17B2002A","x":132.623,"y":25.809,"z":44.005,"place":"outdoor","ns":40.56,"ew":-83.0,"town":{"name":"Redspire","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007081","wcid":42837,"name":"Portal to Westwatch","label":"Westwatch","cell":"00070168","x":86.277,"y":-139.953,"z":-0.063,"heading":90.0,"dest":{"cell":"23DA002C","x":140.9,"y":86.0,"z":2.005,"place":"outdoor","ns":72.81,"ew":-73.36,"town":{"name":"Westwatch","dist":0.0}},"into":false,"setup":"020005D3"}, + {"guid":"70007082","wcid":42838,"name":"Portal to Linvak Tukal","label":"Linvak Tukal","cell":"00070169","x":86.243,"y":-149.991,"z":-0.063,"heading":90.0,"dest":{"cell":"A21E001A","x":83.0,"y":38.0,"z":560.4,"place":"outdoor","ns":-77.79,"ew":28.0,"town":{"name":"Linvak Tukal","dist":0.0}},"into":false,"setup":"020005D6"}, + {"guid":"70007083","wcid":43003,"name":"Danby's Outpost","label":"Danby's Outpost","cell":"0007016A","x":86.419,"y":-160.001,"z":-0.063,"heading":90.0,"dest":{"cell":"5A9C0004","x":23.5,"y":77.1,"z":6.0,"place":"outdoor","ns":23.17,"ew":-29.85,"town":{"name":"Outpost","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007084","wcid":42839,"name":"Portal to Eastwatch","label":"Eastwatch","cell":"0007016B","x":86.513,"y":-170.055,"z":-0.063,"heading":90.0,"dest":{"cell":"49F00013","x":70.0,"y":70.0,"z":170.005,"place":"outdoor","ns":90.34,"ew":-43.26,"town":{"name":"Eastwatch","dist":0.0}},"into":false,"setup":"020005D5","minLevel":80}, + {"guid":"70007085","wcid":42840,"name":"Portal to Shoushi","label":"Shoushi","cell":"0007016C","x":100.0,"y":-53.624,"z":-0.063,"heading":0.0,"dest":{"cell":"DA55001D","x":84.8,"y":99.0,"z":20.0,"place":"outdoor","ns":-33.54,"ew":72.8,"town":{"name":"Shoushi","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"7000708F","wcid":42841,"name":"Portal to Tou-Tou","label":"Tou-Tou","cell":"00070170","x":99.979,"y":-86.304,"z":-0.063,"heading":180.0,"dest":{"cell":"F5590034","x":152.59,"y":80.8,"z":20.005,"place":"outdoor","ns":-30.41,"ew":94.69,"town":{"name":"Tou-Tou","dist":0.01}},"into":false,"setup":"020005D3"}, + {"guid":"70007090","wcid":42842,"name":"Mayoi Portal","label":"Mayoi","cell":"00070171","x":110.0,"y":-53.369,"z":-0.063,"heading":0.0,"dest":{"cell":"E6320021","x":107.417,"y":10.763,"z":29.908,"place":"outdoor","ns":-61.91,"ew":82.5,"town":{"name":"Mayoi","dist":0.01}},"into":false,"setup":"020001B3"}, + {"guid":"70007095","wcid":42843,"name":"Portal to Nanto","label":"Nanto","cell":"00070175","x":109.982,"y":-86.004,"z":-0.063,"heading":180.0,"dest":{"cell":"E63E0022","x":96.96,"y":37.722,"z":74.542,"place":"outdoor","ns":-52.19,"ew":82.45,"town":{"name":"Nanto","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"70007096","wcid":42844,"name":"Lin Portal","label":"Lin","cell":"00070176","x":120.0,"y":-53.43,"z":-0.063,"heading":0.0,"dest":{"cell":"DC3C0011","x":59.72,"y":10.774,"z":18.958,"place":"outdoor","ns":-53.91,"ew":74.3,"town":{"name":"Lin","dist":0.01}},"into":false,"setup":"020001B3"}, + {"guid":"7000709E","wcid":42845,"name":"Baishi Portal","label":"Baishi","cell":"0007017A","x":119.974,"y":-86.439,"z":-0.063,"heading":180.0,"dest":{"cell":"CE410007","x":12.6,"y":152.8,"z":55.1,"place":"outdoor","ns":-49.31,"ew":62.9,"town":{"name":"Baishi","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"7000709F","wcid":42846,"name":"Portal to Hebian-To","label":"Hebian-To","cell":"0007017B","x":130.0,"y":-53.623,"z":-0.063,"heading":0.0,"dest":{"cell":"E64E002F","x":138.304,"y":161.905,"z":20.04,"place":"outdoor","ns":-38.88,"ew":82.63,"town":{"name":"Hebian-to","dist":0.01}},"into":false,"setup":"020001B3"}, + {"guid":"700070A4","wcid":42847,"name":"Portal to Yanshi","label":"Yanshi","cell":"0007017F","x":129.947,"y":-86.357,"z":-0.063,"heading":180.0,"dest":{"cell":"B46F001E","x":75.2,"y":124.1,"z":34.69,"place":"outdoor","ns":-12.63,"ew":42.36,"town":{"name":"Yanshi","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"700070A5","wcid":42848,"name":"Portal to Kara","label":"Kara","cell":"00070180","x":140.044,"y":-53.796,"z":-0.063,"heading":0.0,"dest":{"cell":"BA170039","x":181.2,"y":3.2,"z":167.7,"place":"outdoor","ns":-83.54,"ew":47.6,"town":{"name":"Kara","dist":0.01}},"into":false,"setup":"020005D6"}, + {"guid":"700070AD","wcid":42849,"name":"Sawato Portal","label":"Sawato","cell":"00070184","x":139.937,"y":-86.358,"z":-0.063,"heading":180.0,"dest":{"cell":"C95B0001","x":14.8,"y":0.3,"z":12.0,"place":"outdoor","ns":-29.15,"ew":58.91,"town":{"name":"Sawato","dist":0.0}},"into":false,"setup":"020001B3"}, + {"guid":"700070AE","wcid":42850,"name":"Portal to Kryst","label":"Kryst","cell":"00070185","x":146.522,"y":-59.965,"z":-0.063,"heading":90.0,"dest":{"cell":"E822002A","x":132.7,"y":37.9,"z":20.1,"place":"outdoor","ns":-74.59,"ew":84.2,"town":{"name":"Kryst","dist":0.0}},"into":false,"setup":"020005D3"}, + {"guid":"700070AF","wcid":43004,"name":"Freehold Portal","label":"Freehold","cell":"00070187","x":146.565,"y":-80.047,"z":-0.063,"heading":90.0,"dest":{"cell":"F224001A","x":81.8,"y":33.0,"z":0.0,"place":"outdoor","ns":-73.01,"ew":91.99,"town":{"name":"Freehold","dist":0.0}},"into":false,"setup":"020001B3"} + ], + "npcs": [ + {"guid":"7000700E","wcid":42802,"name":"Barkeep Hosaam","cell":"00070114","x":17.572,"y":-69.471,"z":0.005,"setup":"02000001"}, + {"guid":"7000700F","wcid":42803,"name":"Barkeep Devra","cell":"00070114","x":16.873,"y":-70.612,"z":0.005,"setup":"0200004E"}, + {"guid":"70007010","wcid":42804,"name":"Barkeep Jauhar","cell":"00070114","x":15.186,"y":-69.912,"z":0.005,"setup":"02000001"}, + {"guid":"70007051","wcid":42799,"name":"Barkeeper AmberJill","cell":"0007013F","x":70.514,"y":-17.596,"z":0.005,"setup":"0200004E"}, + {"guid":"70007052","wcid":42800,"name":"Barkeeper Edsel","cell":"0007013F","x":69.457,"y":-16.815,"z":0.005,"setup":"0200004E"}, + {"guid":"70007053","wcid":42801,"name":"Barkeeper Creighton","cell":"0007013F","x":70.085,"y":-15.466,"z":0.005,"setup":"02000001"}, + {"guid":"70007057","wcid":42805,"name":"Barkeeper Lazzaro","cell":"0007014B","x":69.447,"y":-142.381,"z":0.005,"setup":"02000001"}, + {"guid":"70007058","wcid":42806,"name":"Barkeeper Benedetta","cell":"0007014B","x":70.602,"y":-143.072,"z":0.005,"setup":"0200004E"}, + {"guid":"70007059","wcid":42807,"name":"Barkeeper Rafaele","cell":"0007014B","x":69.925,"y":-144.73,"z":0.005,"setup":"02000001"}, + {"guid":"70007099","wcid":42808,"name":"Hanadi the Barkeeper","cell":"00070178","x":122.302,"y":-70.52,"z":0.005,"setup":"0200004E"}, + {"guid":"7000709A","wcid":42809,"name":"Junjie the Barkeeper","cell":"00070178","x":123.057,"y":-69.343,"z":0.005,"setup":"02000001"}, + {"guid":"7000709B","wcid":42810,"name":"Xiao Hong the Barkeeper","cell":"00070178","x":124.867,"y":-70.095,"z":0.005,"setup":"0200004E"} + ], + "walks": [ + {"from":"A1","to":"70007000","exit":"Al-Jalima Portal","length":57.59,"minClear":0.64,"cells":8,"points":[["00070133",60,-70,0],["00070114",21.62,-67.38,0],["0007010E",12.88,-63.38,0],["0007010A",3.99,-60,0]]}, + {"from":"A1","to":"70007001","exit":"Tufa Portal","length":57.52,"minClear":0.65,"cells":8,"points":[["00070133",60,-70,0],["00070114",21.38,-72.62,0],["00070110",12.88,-76.62,0],["0007010C",4.09,-80,0]]}, + {"from":"A1","to":"70007002","exit":"Portal to Zaikhal","length":56.07,"minClear":0.64,"cells":8,"points":[["00070133",60,-70,0],["00070114",23.12,-67.62,0],["0007010E",12.12,-56.62,0],["0007010D",9.94,-53.81,0]]}, + {"from":"A1","to":"7000700A","exit":"Uziz Portal","length":56.49,"minClear":0.66,"cells":8,"points":[["00070133",60,-70,0],["00070114",22.88,-72.38,0],["00070110",12.12,-83.12,0],["00070111",9.86,-86.53,0]]}, + {"from":"A1","to":"7000700B","exit":"Portal to Xarabydun","length":47.43,"minClear":0.71,"cells":7,"points":[["00070133",60,-70,0],["00070119",30.38,-68.12,0],["00070113",22.38,-58.88,0],["00070112",20.07,-53.86,0]]}, + {"from":"A1","to":"70007013","exit":"Portal to Khayyaban","length":46.28,"minClear":0.64,"cells":7,"points":[["00070133",60,-70,0],["0007011E",43.62,-71.12,0],["0007011F",39.38,-75.12,0],["0007011F",35.62,-77.38,0],["0007011A",33.88,-80.62,0],["00070115",22.12,-83.12,0],["00070116",19.98,-86.44,0]]}, + {"from":"A1","to":"70007014","exit":"Qalaba'r Portal","length":37.71,"minClear":0.64,"cells":6,"points":[["00070133",60,-70,0],["0007011E",43.62,-68.88,0],["0007011D",38.38,-59.62,0],["00070118",32.12,-56.88,0],["00070117",30.01,-53.7,0]]}, + {"from":"A1","to":"70007018","exit":"Portal to Al-Arqas","length":37.25,"minClear":0.64,"cells":6,"points":[["00070133",60,-70,0],["0007011E",43.62,-71.12,0],["0007011F",39.38,-75.12,0],["0007011F",35.62,-77.38,0],["0007011A",32.88,-82.12,0],["0007011B",29.94,-86.34,0]]}, + {"from":"A1","to":"70007019","exit":"Portal to Samsur","length":32.13,"minClear":0.64,"cells":5,"points":[["00070133",60,-70,0],["0007011E",43.62,-68.88,0],["0007011C",39.97,-53.6,0]]}, + {"from":"A1","to":"70007024","exit":"Portal to Yaraq","length":31.91,"minClear":0.64,"cells":5,"points":[["00070133",60,-70,0],["0007011E",43.62,-71.12,0],["00070120",40,-86.18,0]]}, + {"from":"A1","to":"70007025","exit":"Glenden Wood Portal","length":68.95,"minClear":0.65,"cells":10,"points":[["00070133",60,-70,0],["00070142",69.88,-53.88,0],["0007013F",66.88,-22.12,0],["0007012E",56.62,-11.88,0],["00070121",53.5,-10,0]]}, + {"from":"A1","to":"70007026","exit":"Lytelthorpe Portal","length":59.15,"minClear":0.63,"cells":9,"points":[["00070133",60,-70,0],["00070142",69.88,-53.88,0],["00070141",68.88,-43.62,0],["00070131",64.88,-39.38,0],["00070131",62.62,-35.62,0],["00070130",59.38,-33.88,0],["0007012F",56.62,-21.88,0],["00070122",53.4,-20,0]]}, + {"from":"A1","to":"70007027","exit":"Portal to Cragstone","length":50.21,"minClear":0.64,"cells":8,"points":[["00070133",60,-70,0],["00070142",69.88,-53.88,0],["00070141",68.88,-43.62,0],["00070131",64.88,-39.38,0],["00070131",62.62,-35.62,0],["00070130",57.62,-32.62,0],["00070130",57.12,-32.12,0],["00070123",53.44,-30.01,0]]}, + {"from":"A1","to":"70007028","exit":"Portal to Holtburg","length":44.63,"minClear":0.68,"cells":7,"points":[["00070133",60,-70,0],["00070142",69.88,-53.88,0],["00070141",68.88,-43.62,0],["00070124",53.91,-39.95,0]]}, + {"from":"A1","to":"70007029","exit":"Portal to Facility Hub","length":44.97,"minClear":0.68,"cells":7,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["00070147",68.88,-96.38,0],["00070126",53.55,-100,0]]}, + {"from":"A1","to":"7000702A","exit":"Portal to Bluespire","length":65.02,"minClear":0.73,"cells":9,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["00070149",69.12,-116.12,0],["00070127",53.5,-120.02,0]]}, + {"from":"A1","to":"7000702B","exit":"Portal to Greenspire","length":70.64,"minClear":0.64,"cells":10,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["00070149",69.12,-116.12,0],["00070136",59.62,-121.62,0],["00070137",56.62,-128.12,0],["00070128",53.54,-129.95,0]]}, + {"from":"A1","to":"7000702C","exit":"Ahurenga Portal","length":80.35,"minClear":0.7,"cells":11,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["0007014A",68.62,-128.88,0],["00070138",58.88,-137.62,0],["00070129",53.81,-139.94,0]]}, + {"from":"A1","to":"7000702D","exit":"Portal to Neydisa Castle","length":88.88,"minClear":0.63,"cells":12,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["0007014B",68.38,-136.12,0],["00070139",57.38,-147.12,0],["0007012A",54.05,-149.98,0]]}, + {"from":"A1","to":"7000702E","exit":"Portal to Silyun","length":97.58,"minClear":0.66,"cells":13,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["0007014B",68.38,-137.38,0],["00070139",63.38,-146.88,0],["0007013A",56.62,-158.12,0],["0007012B",53.6,-159.97,0]]}, + {"from":"A1","to":"7000702F","exit":"Fiun Outpost","length":106.49,"minClear":0.65,"cells":14,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["0007014B",68.38,-137.38,0],["00070139",63.38,-146.88,0],["0007013B",56.38,-168.12,0],["0007012C",53.8,-170.02,0]]}, + {"from":"A1","to":"70007030","exit":"Plateau Portal","length":70.72,"minClear":0.67,"cells":10,"points":[["00070133",60,-70,0],["00070142",69.88,-53.88,0],["0007013F",66.62,-20.62,0],["0007012E",63.38,-13.38,0],["0007012D",60,-3.48,0]]}, + {"from":"A1","to":"7000704D","exit":"Base of the Timaru Plateau Portal","length":110.68,"minClear":0.7,"cells":14,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["0007014B",68.38,-137.38,0],["00070139",63.38,-146.88,0],["0007013C",60.02,-176.45,0]]}, + {"from":"A1","to":"7000704E","exit":"Fort Tethana Portal","length":70.09,"minClear":0.67,"cells":9,"points":[["00070133",60,-70,0],["00070142",69.88,-53.88,0],["0007013F",66.62,-20.62,0],["0007013E",67.12,-9.12,0],["0007013D",69.99,-3.56,0]]}, + {"from":"A1","to":"7000705A","exit":"Stonehold Portal","length":70.75,"minClear":0.67,"cells":10,"points":[["00070133",60,-70,0],["00070142",69.88,-53.88,0],["0007013F",74.38,-17.88,0],["00070151",76.62,-12.62,0],["00070150",79.94,-3.35,0]]}, + {"from":"A1","to":"70007079","exit":"Oolutanga's Refuge","length":110.47,"minClear":0.67,"cells":14,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["0007014B",71.88,-137.88,0],["0007015C",76.62,-146.88,0],["0007015F",79.99,-176.28,0]]}, + {"from":"A1","to":"7000707A","exit":"Portal to Dryreach","length":68.59,"minClear":0.63,"cells":10,"points":[["00070133",60,-70,0],["00070142",69.88,-53.88,0],["0007013F",74.12,-21.12,0],["00070151",83.12,-12.12,0],["00070160",86.42,-10,0]]}, + {"from":"A1","to":"7000707B","exit":"Eastham Portal","length":60.14,"minClear":0.68,"cells":9,"points":[["00070133",60,-70,0],["00070142",69.88,-53.88,0],["00070140",72.88,-29.62,0],["00070152",81.38,-22.38,0],["00070161",86.49,-20.03,0]]}, + {"from":"A1","to":"7000707C","exit":"Portal to Rithwic","length":50.37,"minClear":0.63,"cells":8,"points":[["00070133",60,-70,0],["00070142",69.88,-53.88,0],["00070141",71.12,-43.62,0],["00070154",80.38,-38.38,0],["00070153",83.62,-31.88,0],["00070162",86.24,-30,0]]}, + {"from":"A1","to":"7000707D","exit":"Portal to Arwic","length":45.39,"minClear":0.71,"cells":7,"points":[["00070133",60,-70,0],["00070142",69.88,-53.88,0],["00070141",71.12,-43.62,0],["00070163",86.86,-40,0]]}, + {"from":"A1","to":"7000707E","exit":"The Marketplace of Dereth","length":44.68,"minClear":0.71,"cells":7,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["00070147",71.12,-96.38,0],["00070165",86.13,-99.98,0]]}, + {"from":"A1","to":"7000707F","exit":"Portal to Sanamar","length":64.72,"minClear":0.73,"cells":9,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["00070149",70.88,-116.12,0],["00070166",86.18,-120.04,0]]}, + {"from":"A1","to":"70007080","exit":"Portal to Redspire","length":70.54,"minClear":0.67,"cells":10,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["00070149",70.88,-116.12,0],["00070159",75.12,-120.62,0],["00070159",77.38,-124.38,0],["0007015A",80.12,-125.12,0],["0007015A",82.88,-127.88,0],["00070167",86.61,-130.04,0]]}, + {"from":"A1","to":"70007081","exit":"Portal to Westwatch","length":79.22,"minClear":0.65,"cells":11,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["00070149",70.88,-116.12,0],["00070159",75.12,-120.62,0],["00070159",77.38,-124.38,0],["0007015A",80.12,-125.12,0],["0007015B",83.12,-137.88,0],["00070168",86.28,-139.95,0]]}, + {"from":"A1","to":"70007082","exit":"Portal to Linvak Tukal","length":89.11,"minClear":0.64,"cells":12,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["0007014B",71.88,-136.62,0],["0007015C",82.88,-147.62,0],["00070169",86.24,-149.99,0]]}, + {"from":"A1","to":"70007083","exit":"Danby's Outpost","length":97.58,"minClear":0.63,"cells":13,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["0007014B",71.88,-137.88,0],["0007015C",76.62,-146.88,0],["0007015D",83.12,-157.88,0],["0007016A",86.42,-160,0]]}, + {"from":"A1","to":"70007084","exit":"Portal to Eastwatch","length":106.89,"minClear":0.64,"cells":14,"points":[["00070133",60,-70,0],["00070146",69.88,-86.12,0],["0007014B",71.88,-137.88,0],["0007015C",76.62,-146.88,0],["0007015E",83.12,-167.88,0],["0007016B",86.51,-170.06,0]]}, + {"from":"A1","to":"70007085","exit":"Portal to Shoushi","length":55.67,"minClear":0.67,"cells":9,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070157",79.38,-75.12,0],["00070164",85.88,-70.12,0],["0007016E",96.38,-68.88,0],["0007016C",100,-53.62,0]]}, + {"from":"A1","to":"7000708F","exit":"Portal to Tou-Tou","length":55.56,"minClear":0.67,"cells":9,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070157",79.38,-75.12,0],["00070164",85.88,-70.12,0],["0007016E",96.38,-71.12,0],["00070170",99.98,-86.3,0]]}, + {"from":"A1","to":"70007090","exit":"Mayoi Portal","length":61.25,"minClear":0.65,"cells":10,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070157",79.38,-75.12,0],["00070164",85.88,-70.12,0],["0007016E",96.38,-68.88,0],["0007016D",100.62,-64.88,0],["0007016D",104.38,-62.62,0],["00070172",105.12,-59.88,0],["00070172",107.88,-57.12,0],["00070171",110,-53.37,0]]}, + {"from":"A1","to":"70007095","exit":"Portal to Nanto","length":60.92,"minClear":0.64,"cells":10,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070157",79.38,-75.12,0],["00070164",85.88,-70.12,0],["0007016E",96.38,-71.12,0],["0007016F",101.62,-80.38,0],["00070174",107.62,-83.12,0],["00070175",109.98,-86,0]]}, + {"from":"A1","to":"70007096","exit":"Lin Portal","length":70.15,"minClear":0.64,"cells":11,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070157",79.38,-75.12,0],["00070164",85.88,-70.12,0],["0007016E",96.38,-68.88,0],["0007016D",100.62,-64.88,0],["0007016D",104.38,-62.62,0],["00070172",105.12,-59.88,0],["00070177",118.12,-56.62,0],["00070176",120,-53.43,0]]}, + {"from":"A1","to":"7000709E","exit":"Baishi Portal","length":70.97,"minClear":0.67,"cells":11,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070157",79.38,-75.12,0],["00070164",85.88,-70.12,0],["00070173",109.88,-72.38,0],["00070179",117.62,-81.38,0],["0007017A",119.97,-86.44,0]]}, + {"from":"A1","to":"7000709F","exit":"Portal to Hebian-To","length":78.84,"minClear":0.63,"cells":11,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070164",85.88,-70.12,0],["00070178",118.12,-66.62,0],["0007017C",127.88,-56.88,0],["0007017B",130,-53.62,0]]}, + {"from":"A1","to":"700070A4","exit":"Portal to Yanshi","length":78.87,"minClear":0.67,"cells":11,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070164",85.88,-70.12,0],["00070178",117.88,-73.12,0],["0007017E",128.12,-83.38,0],["0007017F",129.95,-86.36,0]]}, + {"from":"A1","to":"700070A5","exit":"Portal to Kara","length":87,"minClear":0.63,"cells":12,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070164",87.62,-70.12,0],["00070178",119.62,-66.38,0],["0007017C",127.88,-63.38,0],["00070181",138.12,-56.38,0],["00070180",140.04,-53.8,0]]}, + {"from":"A1","to":"700070AD","exit":"Sawato Portal","length":87.08,"minClear":0.64,"cells":12,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070164",87.62,-70.12,0],["00070178",121.88,-74.12,0],["0007017E",127.12,-76.62,0],["00070183",138.12,-83.38,0],["00070184",139.94,-86.36,0]]}, + {"from":"A1","to":"700070AE","exit":"Portal to Kryst","length":91.22,"minClear":0.67,"cells":13,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070157",79.38,-75.12,0],["00070164",85.88,-70.12,0],["00070178",119.38,-66.62,0],["0007017C",126.62,-63.38,0],["00070185",146.52,-59.96,0]]}, + {"from":"A1","to":"700070AF","exit":"Freehold Portal","length":91.24,"minClear":0.66,"cells":13,"points":[["00070133",60,-70,0],["00070145",69.62,-76.12,0],["00070157",79.38,-75.12,0],["00070164",85.88,-70.12,0],["00070178",119.38,-73.38,0],["0007017E",126.62,-76.62,0],["00070187",146.56,-80.05,0]]}, + {"from":"A2","to":"70007000","exit":"Al-Jalima Portal","length":70.23,"minClear":0.67,"cells":10,"points":[["00070143",70,-60,0],["00070125",53.88,-69.88,0],["00070114",20.62,-66.62,0],["0007010A",3.99,-60,0]]}, + {"from":"A2","to":"70007001","exit":"Tufa Portal","length":70.16,"minClear":0.73,"cells":10,"points":[["00070143",70,-60,0],["00070125",53.88,-69.88,0],["00070114",20.62,-73.38,0],["0007010C",4.09,-80,0]]}, + {"from":"A2","to":"70007002","exit":"Portal to Zaikhal","length":68.62,"minClear":0.64,"cells":10,"points":[["00070143",70,-60,0],["00070125",53.88,-69.88,0],["00070114",22.38,-66.88,0],["0007010E",12.12,-56.62,0],["0007010D",9.94,-53.81,0]]}, + {"from":"A2","to":"7000700A","exit":"Uziz Portal","length":68.98,"minClear":0.64,"cells":10,"points":[["00070143",70,-60,0],["00070125",53.88,-69.88,0],["00070114",21.88,-73.38,0],["00070110",12.12,-83.12,0],["00070111",9.86,-86.53,0]]}, + {"from":"A2","to":"7000700B","exit":"Portal to Xarabydun","length":59.91,"minClear":0.64,"cells":9,"points":[["00070143",70,-60,0],["00070125",53.88,-69.88,0],["00070119",29.88,-67.62,0],["00070112",20.07,-53.86,0]]}, + {"from":"A2","to":"70007013","exit":"Portal to Khayyaban","length":59.11,"minClear":0.64,"cells":9,"points":[["00070143",70,-60,0],["00070125",53.88,-69.88,0],["0007011E",43.62,-71.12,0],["0007011F",39.38,-75.12,0],["0007011F",35.62,-77.38,0],["0007011A",33.88,-80.62,0],["00070115",22.12,-83.12,0],["00070116",19.98,-86.44,0]]}, + {"from":"A2","to":"70007014","exit":"Qalaba'r Portal","length":50.5,"minClear":0.66,"cells":8,"points":[["00070143",70,-60,0],["00070125",53.88,-69.88,0],["0007011E",43.62,-68.88,0],["0007011D",38.38,-59.62,0],["00070118",32.12,-56.88,0],["00070117",30.01,-53.7,0]]}, + {"from":"A2","to":"70007018","exit":"Portal to Al-Arqas","length":50.08,"minClear":0.65,"cells":8,"points":[["00070143",70,-60,0],["00070125",53.88,-69.88,0],["0007011E",43.62,-71.12,0],["0007011F",39.38,-75.12,0],["0007011F",35.62,-77.38,0],["0007011A",32.88,-82.12,0],["0007011B",29.94,-86.34,0]]}, + {"from":"A2","to":"70007019","exit":"Portal to Samsur","length":44.93,"minClear":0.68,"cells":7,"points":[["00070143",70,-60,0],["00070125",53.88,-69.88,0],["0007011E",43.62,-68.88,0],["0007011C",39.97,-53.6,0]]}, + {"from":"A2","to":"70007024","exit":"Portal to Yaraq","length":44.73,"minClear":0.71,"cells":7,"points":[["00070143",70,-60,0],["00070125",53.88,-69.88,0],["0007011E",43.62,-71.12,0],["00070120",40,-86.18,0]]}, + {"from":"A2","to":"70007025","exit":"Glenden Wood Portal","length":56.4,"minClear":0.65,"cells":8,"points":[["00070143",70,-60,0],["0007013F",67.62,-22.88,0],["0007012E",56.62,-11.88,0],["00070121",53.5,-10,0]]}, + {"from":"A2","to":"70007026","exit":"Lytelthorpe Portal","length":46.35,"minClear":0.63,"cells":7,"points":[["00070143",70,-60,0],["00070141",68.88,-43.62,0],["00070131",64.88,-39.38,0],["00070131",62.62,-35.62,0],["00070130",59.38,-33.88,0],["0007012F",56.62,-21.88,0],["00070122",53.4,-20,0]]}, + {"from":"A2","to":"70007027","exit":"Portal to Cragstone","length":37.41,"minClear":0.64,"cells":6,"points":[["00070143",70,-60,0],["00070141",68.88,-43.62,0],["00070131",64.88,-39.38,0],["00070131",62.62,-35.62,0],["00070130",57.62,-32.62,0],["00070130",57.12,-32.12,0],["00070123",53.44,-30.01,0]]}, + {"from":"A2","to":"70007028","exit":"Portal to Holtburg","length":31.83,"minClear":0.64,"cells":5,"points":[["00070143",70,-60,0],["00070141",68.88,-43.62,0],["00070124",53.91,-39.95,0]]}, + {"from":"A2","to":"70007029","exit":"Portal to Facility Hub","length":55.71,"minClear":0.68,"cells":9,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070134",64.88,-79.38,0],["00070146",69.88,-85.88,0],["00070147",68.88,-96.38,0],["00070126",53.55,-100,0]]}, + {"from":"A2","to":"7000702A","exit":"Portal to Bluespire","length":75.08,"minClear":0.68,"cells":10,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070146",69.88,-85.88,0],["00070149",69.12,-116.12,0],["00070127",53.5,-120.02,0]]}, + {"from":"A2","to":"7000702B","exit":"Portal to Greenspire","length":80.7,"minClear":0.64,"cells":11,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070146",69.88,-85.88,0],["00070149",69.12,-116.12,0],["00070136",59.62,-121.62,0],["00070137",56.62,-128.12,0],["00070128",53.54,-129.95,0]]}, + {"from":"A2","to":"7000702C","exit":"Ahurenga Portal","length":90.32,"minClear":0.64,"cells":12,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070146",69.88,-87.62,0],["0007014A",68.62,-128.88,0],["00070138",58.88,-137.62,0],["00070129",53.81,-139.94,0]]}, + {"from":"A2","to":"7000702D","exit":"Portal to Neydisa Castle","length":99.62,"minClear":0.63,"cells":14,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070134",64.88,-79.38,0],["00070146",69.88,-85.88,0],["0007014B",68.38,-136.12,0],["00070139",57.38,-147.12,0],["0007012A",54.05,-149.98,0]]}, + {"from":"A2","to":"7000702E","exit":"Portal to Silyun","length":108.33,"minClear":0.66,"cells":15,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070134",64.88,-79.38,0],["00070146",69.88,-85.88,0],["0007014B",68.38,-137.38,0],["00070139",63.38,-146.88,0],["0007013A",56.62,-158.12,0],["0007012B",53.6,-159.97,0]]}, + {"from":"A2","to":"7000702F","exit":"Fiun Outpost","length":117.24,"minClear":0.65,"cells":16,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070134",64.88,-79.38,0],["00070146",69.88,-85.88,0],["0007014B",68.38,-137.38,0],["00070139",63.38,-146.88,0],["0007013B",56.38,-168.12,0],["0007012C",53.8,-170.02,0]]}, + {"from":"A2","to":"70007030","exit":"Plateau Portal","length":58.09,"minClear":0.65,"cells":8,"points":[["00070143",70,-60,0],["0007013F",67.38,-21.38,0],["0007012E",63.38,-12.88,0],["0007012D",60,-3.48,0]]}, + {"from":"A2","to":"7000704D","exit":"Base of the Timaru Plateau Portal","length":120.69,"minClear":0.67,"cells":15,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070145",68.12,-82.62,0],["00070146",69.88,-87.12,0],["0007014B",68.38,-137.38,0],["00070139",63.38,-146.88,0],["0007013C",60.02,-176.45,0]]}, + {"from":"A2","to":"7000704E","exit":"Fort Tethana Portal","length":57.3,"minClear":0.64,"cells":7,"points":[["00070143",70,-60,0],["0007013F",67.38,-21.38,0],["0007013E",66.12,-14.62,0],["0007013D",69.99,-3.56,0]]}, + {"from":"A2","to":"7000705A","exit":"Stonehold Portal","length":58.17,"minClear":0.64,"cells":8,"points":[["00070143",70,-60,0],["0007013F",72.62,-21.62,0],["00070151",76.62,-12.88,0],["00070150",79.94,-3.35,0]]}, + {"from":"A2","to":"70007079","exit":"Oolutanga's Refuge","length":120.47,"minClear":0.67,"cells":15,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070145",68.12,-82.62,0],["00070146",69.88,-87.12,0],["0007014B",71.88,-137.88,0],["0007015C",76.62,-146.88,0],["0007015F",79.99,-176.28,0]]}, + {"from":"A2","to":"7000707A","exit":"Portal to Dryreach","length":56.32,"minClear":0.63,"cells":8,"points":[["00070143",70,-60,0],["0007013F",72.38,-22.88,0],["00070151",83.12,-12.12,0],["00070160",86.42,-10,0]]}, + {"from":"A2","to":"7000707B","exit":"Eastham Portal","length":47.64,"minClear":0.71,"cells":7,"points":[["00070143",70,-60,0],["00070140",71.88,-30.62,0],["00070152",81.38,-22.38,0],["00070161",86.49,-20.03,0]]}, + {"from":"A2","to":"7000707C","exit":"Portal to Rithwic","length":37.55,"minClear":0.63,"cells":6,"points":[["00070143",70,-60,0],["00070141",71.12,-43.62,0],["00070154",80.38,-38.38,0],["00070153",83.62,-31.88,0],["00070162",86.24,-30,0]]}, + {"from":"A2","to":"7000707D","exit":"Portal to Arwic","length":32.57,"minClear":0.64,"cells":5,"points":[["00070143",70,-60,0],["00070141",71.12,-43.62,0],["00070163",86.86,-40,0]]}, + {"from":"A2","to":"7000707E","exit":"The Marketplace of Dereth","length":55.42,"minClear":0.68,"cells":9,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070134",64.88,-79.38,0],["00070146",69.88,-85.88,0],["00070147",71.12,-96.38,0],["00070165",86.13,-99.98,0]]}, + {"from":"A2","to":"7000707F","exit":"Portal to Sanamar","length":74.78,"minClear":0.68,"cells":10,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070146",69.88,-85.88,0],["00070149",70.88,-116.12,0],["00070166",86.18,-120.04,0]]}, + {"from":"A2","to":"70007080","exit":"Portal to Redspire","length":80.61,"minClear":0.67,"cells":11,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070146",69.88,-85.88,0],["00070149",70.88,-116.12,0],["00070159",75.12,-120.62,0],["00070159",77.38,-124.38,0],["0007015A",80.12,-125.12,0],["0007015A",82.88,-127.88,0],["00070167",86.61,-130.04,0]]}, + {"from":"A2","to":"70007081","exit":"Portal to Westwatch","length":89.96,"minClear":0.65,"cells":13,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070134",64.88,-79.38,0],["00070146",69.88,-85.88,0],["00070149",70.88,-116.12,0],["00070159",75.12,-120.62,0],["00070159",77.38,-124.38,0],["0007015A",80.12,-125.12,0],["0007015B",83.12,-137.88,0],["00070168",86.28,-139.95,0]]}, + {"from":"A2","to":"70007082","exit":"Portal to Linvak Tukal","length":99.86,"minClear":0.64,"cells":14,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070134",64.88,-79.38,0],["00070146",69.88,-85.88,0],["0007014B",71.88,-136.62,0],["0007015C",82.88,-147.62,0],["00070169",86.24,-149.99,0]]}, + {"from":"A2","to":"70007083","exit":"Danby's Outpost","length":108.32,"minClear":0.63,"cells":15,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070134",64.88,-79.38,0],["00070146",69.88,-85.88,0],["0007014B",71.88,-137.88,0],["0007015C",76.62,-146.88,0],["0007015D",83.12,-157.88,0],["0007016A",86.42,-160,0]]}, + {"from":"A2","to":"70007084","exit":"Portal to Eastwatch","length":117.64,"minClear":0.64,"cells":16,"points":[["00070143",70,-60,0],["00070133",63.88,-69.62,0],["00070134",64.88,-79.38,0],["00070146",69.88,-85.88,0],["0007014B",71.88,-137.88,0],["0007015C",76.62,-146.88,0],["0007015E",83.12,-167.88,0],["0007016B",86.51,-170.06,0]]}, + {"from":"A2","to":"70007085","exit":"Portal to Shoushi","length":44.9,"minClear":0.68,"cells":7,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["0007016E",96.38,-68.88,0],["0007016C",100,-53.62,0]]}, + {"from":"A2","to":"7000708F","exit":"Portal to Tou-Tou","length":44.84,"minClear":0.71,"cells":7,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["0007016E",96.38,-71.12,0],["00070170",99.98,-86.3,0]]}, + {"from":"A2","to":"70007090","exit":"Mayoi Portal","length":50.48,"minClear":0.65,"cells":8,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["0007016E",96.38,-68.88,0],["0007016D",100.62,-64.88,0],["0007016D",104.38,-62.62,0],["00070172",105.12,-59.88,0],["00070172",107.88,-57.12,0],["00070171",110,-53.37,0]]}, + {"from":"A2","to":"70007095","exit":"Portal to Nanto","length":50.2,"minClear":0.64,"cells":8,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["0007016E",96.38,-71.12,0],["0007016F",101.62,-80.38,0],["00070174",107.62,-83.12,0],["00070175",109.98,-86,0]]}, + {"from":"A2","to":"70007096","exit":"Lin Portal","length":59.37,"minClear":0.64,"cells":9,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["0007016E",96.38,-68.88,0],["0007016D",100.62,-64.88,0],["0007016D",104.38,-62.62,0],["00070172",105.12,-59.88,0],["00070177",118.12,-56.62,0],["00070176",120,-53.43,0]]}, + {"from":"A2","to":"7000709E","exit":"Baishi Portal","length":60.1,"minClear":0.68,"cells":9,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["00070173",110.38,-72.88,0],["00070179",117.62,-81.38,0],["0007017A",119.97,-86.44,0]]}, + {"from":"A2","to":"7000709F","exit":"Portal to Hebian-To","length":68.84,"minClear":0.65,"cells":10,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["00070178",117.88,-66.88,0],["0007017C",127.88,-56.88,0],["0007017B",130,-53.62,0]]}, + {"from":"A2","to":"700070A4","exit":"Portal to Yanshi","length":68.52,"minClear":0.63,"cells":10,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["00070178",118.88,-74.12,0],["0007017E",128.12,-83.38,0],["0007017F",129.95,-86.36,0]]}, + {"from":"A2","to":"700070A5","exit":"Portal to Kara","length":76.94,"minClear":0.65,"cells":11,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["00070178",119.38,-66.62,0],["0007017C",126.62,-63.38,0],["00070181",138.12,-56.38,0],["00070180",140.04,-53.8,0]]}, + {"from":"A2","to":"700070AD","exit":"Sawato Portal","length":77.07,"minClear":0.66,"cells":11,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["00070178",122.12,-74.38,0],["0007017E",127.12,-76.62,0],["00070183",138.12,-83.38,0],["00070184",139.94,-86.36,0]]}, + {"from":"A2","to":"700070AE","exit":"Portal to Kryst","length":80.45,"minClear":0.67,"cells":11,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["00070178",119.38,-66.62,0],["0007017C",126.62,-63.38,0],["00070185",146.52,-59.96,0]]}, + {"from":"A2","to":"700070AF","exit":"Freehold Portal","length":80.41,"minClear":0.67,"cells":11,"points":[["00070143",70,-60,0],["00070164",86.12,-69.88,0],["00070178",122.12,-74.38,0],["0007017E",127.12,-76.62,0],["00070187",146.56,-80.05,0]]}, + {"from":"A3","to":"70007000","exit":"Al-Jalima Portal","length":70.17,"minClear":0.67,"cells":10,"points":[["00070145",70,-80,0],["00070125",53.88,-70.12,0],["00070114",17.88,-65.62,0],["0007010E",12.62,-63.38,0],["0007010A",3.99,-60,0]]}, + {"from":"A3","to":"70007001","exit":"Tufa Portal","length":70.13,"minClear":0.67,"cells":10,"points":[["00070145",70,-80,0],["00070125",53.88,-70.12,0],["00070114",20.62,-73.38,0],["0007010C",4.09,-80,0]]}, + {"from":"A3","to":"70007002","exit":"Portal to Zaikhal","length":68.41,"minClear":0.64,"cells":10,"points":[["00070145",70,-80,0],["00070125",53.88,-70.12,0],["00070114",21.62,-66.12,0],["0007010E",12.12,-56.62,0],["0007010D",9.94,-53.81,0]]}, + {"from":"A3","to":"7000700A","exit":"Uziz Portal","length":69.04,"minClear":0.66,"cells":10,"points":[["00070145",70,-80,0],["00070125",53.88,-70.12,0],["00070114",22.12,-73.12,0],["00070110",12.12,-83.12,0],["00070111",9.86,-86.53,0]]}, + {"from":"A3","to":"7000700B","exit":"Portal to Xarabydun","length":59.79,"minClear":0.65,"cells":9,"points":[["00070145",70,-80,0],["00070125",53.88,-70.12,0],["00070119",29.38,-67.12,0],["00070112",20.07,-53.86,0]]}, + {"from":"A3","to":"70007013","exit":"Portal to Khayyaban","length":59.08,"minClear":0.64,"cells":9,"points":[["00070145",70,-80,0],["00070125",53.88,-70.12,0],["0007011E",43.62,-71.12,0],["0007011F",39.38,-75.12,0],["0007011F",35.62,-77.38,0],["0007011A",33.88,-80.62,0],["00070115",22.12,-83.12,0],["00070116",19.98,-86.44,0]]}, + {"from":"A3","to":"70007014","exit":"Qalaba'r Portal","length":50.53,"minClear":0.66,"cells":8,"points":[["00070145",70,-80,0],["00070125",53.88,-70.12,0],["0007011E",43.62,-68.88,0],["0007011D",38.38,-59.62,0],["00070118",32.12,-56.88,0],["00070117",30.01,-53.7,0]]}, + {"from":"A3","to":"70007018","exit":"Portal to Al-Arqas","length":50.05,"minClear":0.65,"cells":8,"points":[["00070145",70,-80,0],["00070125",53.88,-70.12,0],["0007011E",43.62,-71.12,0],["0007011F",39.38,-75.12,0],["0007011F",35.62,-77.38,0],["0007011A",32.88,-82.12,0],["0007011B",29.94,-86.34,0]]}, + {"from":"A3","to":"70007019","exit":"Portal to Samsur","length":44.95,"minClear":0.71,"cells":7,"points":[["00070145",70,-80,0],["00070125",53.88,-70.12,0],["0007011E",43.62,-68.88,0],["0007011C",39.97,-53.6,0]]}, + {"from":"A3","to":"70007024","exit":"Portal to Yaraq","length":44.7,"minClear":0.68,"cells":7,"points":[["00070145",70,-80,0],["00070125",53.88,-70.12,0],["0007011E",43.62,-71.12,0],["00070120",40,-86.18,0]]}, + {"from":"A3","to":"70007025","exit":"Glenden Wood Portal","length":78.81,"minClear":0.65,"cells":11,"points":[["00070145",70,-80,0],["00070133",64.12,-70.88,0],["00070133",64.88,-66.88,0],["00070143",66.62,-62.38,0],["00070142",69.88,-52.38,0],["0007013F",66.88,-22.12,0],["0007012E",56.62,-11.88,0],["00070121",53.5,-10,0]]}, + {"from":"A3","to":"70007026","exit":"Lytelthorpe Portal","length":69.07,"minClear":0.63,"cells":10,"points":[["00070145",70,-80,0],["00070133",64.12,-70.88,0],["00070133",64.88,-66.88,0],["00070142",69.88,-53.38,0],["00070141",68.88,-43.62,0],["00070131",64.88,-39.38,0],["00070131",62.62,-35.62,0],["00070130",59.38,-33.88,0],["0007012F",56.62,-21.88,0],["00070122",53.4,-20,0]]}, + {"from":"A3","to":"70007027","exit":"Portal to Cragstone","length":60.08,"minClear":0.64,"cells":9,"points":[["00070145",70,-80,0],["00070133",64.12,-70.88,0],["00070133",64.88,-66.88,0],["00070143",66.62,-62.38,0],["00070142",69.88,-52.38,0],["00070141",68.88,-43.62,0],["00070131",64.88,-39.38,0],["00070131",62.62,-35.62,0],["00070130",57.62,-32.62,0],["00070130",57.12,-32.12,0],["00070123",53.44,-30.01,0]]}, + {"from":"A3","to":"70007028","exit":"Portal to Holtburg","length":54.56,"minClear":0.67,"cells":8,"points":[["00070145",70,-80,0],["00070133",64.12,-70.88,0],["00070143",66.62,-60.62,0],["00070142",69.88,-53.12,0],["00070141",68.88,-43.62,0],["00070124",53.91,-39.95,0]]}, + {"from":"A3","to":"70007029","exit":"Portal to Facility Hub","length":32.17,"minClear":0.64,"cells":5,"points":[["00070145",70,-80,0],["00070147",68.88,-96.38,0],["00070126",53.55,-100,0]]}, + {"from":"A3","to":"7000702A","exit":"Portal to Bluespire","length":52.23,"minClear":0.81,"cells":7,"points":[["00070145",70,-80,0],["00070149",69.12,-116.12,0],["00070127",53.5,-120.02,0]]}, + {"from":"A3","to":"7000702B","exit":"Portal to Greenspire","length":57.85,"minClear":0.64,"cells":8,"points":[["00070145",70,-80,0],["00070149",69.12,-116.12,0],["00070136",59.62,-121.62,0],["00070137",56.62,-128.12,0],["00070128",53.54,-129.95,0]]}, + {"from":"A3","to":"7000702C","exit":"Ahurenga Portal","length":67.56,"minClear":0.68,"cells":9,"points":[["00070145",70,-80,0],["0007014A",68.62,-128.88,0],["00070138",58.88,-137.62,0],["00070129",53.81,-139.94,0]]}, + {"from":"A3","to":"7000702D","exit":"Portal to Neydisa Castle","length":76.09,"minClear":0.63,"cells":10,"points":[["00070145",70,-80,0],["0007014B",68.38,-136.12,0],["00070139",57.38,-147.12,0],["0007012A",54.05,-149.98,0]]}, + {"from":"A3","to":"7000702E","exit":"Portal to Silyun","length":84.8,"minClear":0.66,"cells":11,"points":[["00070145",70,-80,0],["0007014B",68.38,-137.38,0],["00070139",63.38,-146.88,0],["0007013A",56.62,-158.12,0],["0007012B",53.6,-159.97,0]]}, + {"from":"A3","to":"7000702F","exit":"Fiun Outpost","length":93.71,"minClear":0.65,"cells":12,"points":[["00070145",70,-80,0],["0007014B",68.38,-137.38,0],["00070139",63.38,-146.88,0],["0007013B",56.38,-168.12,0],["0007012C",53.8,-170.02,0]]}, + {"from":"A3","to":"70007030","exit":"Plateau Portal","length":80.59,"minClear":0.66,"cells":11,"points":[["00070145",70,-80,0],["00070133",64.12,-70.88,0],["00070133",64.88,-66.88,0],["00070143",66.62,-62.38,0],["00070142",69.88,-52.38,0],["0007013F",66.62,-20.62,0],["0007012E",63.38,-13.38,0],["0007012D",60,-3.48,0]]}, + {"from":"A3","to":"7000704D","exit":"Base of the Timaru Plateau Portal","length":97.9,"minClear":0.68,"cells":12,"points":[["00070145",70,-80,0],["0007014B",68.38,-137.38,0],["00070139",63.38,-146.88,0],["0007013C",60.02,-176.45,0]]}, + {"from":"A3","to":"7000704E","exit":"Fort Tethana Portal","length":79.96,"minClear":0.66,"cells":10,"points":[["00070145",70,-80,0],["00070133",64.12,-70.88,0],["00070133",64.88,-66.88,0],["00070143",66.62,-62.38,0],["00070142",69.88,-52.38,0],["0007013F",66.62,-20.62,0],["0007013E",67.12,-9.12,0],["0007013D",69.99,-3.56,0]]}, + {"from":"A3","to":"7000705A","exit":"Stonehold Portal","length":80.47,"minClear":0.64,"cells":11,"points":[["00070145",70,-80,0],["00070133",64.12,-70.88,0],["00070133",64.88,-66.88,0],["00070143",66.62,-62.38,0],["00070142",69.88,-52.38,0],["00070152",75.38,-16.88,0],["00070150",79.94,-3.35,0]]}, + {"from":"A3","to":"70007079","exit":"Oolutanga's Refuge","length":97.79,"minClear":0.68,"cells":12,"points":[["00070145",70,-80,0],["0007014B",71.62,-137.62,0],["0007015C",76.62,-146.62,0],["0007015F",79.99,-176.28,0]]}, + {"from":"A3","to":"7000707A","exit":"Portal to Dryreach","length":78.24,"minClear":0.63,"cells":11,"points":[["00070145",70,-80,0],["00070133",64.12,-70.88,0],["00070133",64.88,-66.88,0],["00070143",66.62,-62.38,0],["00070142",69.88,-52.38,0],["0007013F",74.88,-20.38,0],["00070151",83.12,-12.12,0],["00070160",86.42,-10,0]]}, + {"from":"A3","to":"7000707B","exit":"Eastham Portal","length":69.97,"minClear":0.65,"cells":10,"points":[["00070145",70,-80,0],["00070133",64.12,-70.88,0],["00070143",67.88,-57.62,0],["00070142",69.88,-53.12,0],["00070140",73.12,-29.38,0],["00070152",81.38,-22.38,0],["00070161",86.49,-20.03,0]]}, + {"from":"A3","to":"7000707C","exit":"Portal to Rithwic","length":60.28,"minClear":0.63,"cells":9,"points":[["00070145",70,-80,0],["00070133",64.12,-70.88,0],["00070133",64.88,-66.88,0],["00070142",69.88,-53.38,0],["00070141",71.12,-43.62,0],["00070154",80.38,-38.38,0],["00070153",83.62,-31.88,0],["00070162",86.24,-30,0]]}, + {"from":"A3","to":"7000707D","exit":"Portal to Arwic","length":55.32,"minClear":0.67,"cells":8,"points":[["00070145",70,-80,0],["00070133",64.12,-70.88,0],["00070143",66.62,-60.62,0],["00070142",69.88,-53.12,0],["00070141",71.12,-43.62,0],["00070163",86.86,-40,0]]}, + {"from":"A3","to":"7000707E","exit":"The Marketplace of Dereth","length":31.85,"minClear":0.64,"cells":5,"points":[["00070145",70,-80,0],["00070147",71.12,-96.38,0],["00070165",86.13,-99.98,0]]}, + {"from":"A3","to":"7000707F","exit":"Portal to Sanamar","length":51.92,"minClear":0.81,"cells":7,"points":[["00070145",70,-80,0],["00070149",70.88,-116.12,0],["00070166",86.18,-120.04,0]]}, + {"from":"A3","to":"70007080","exit":"Portal to Redspire","length":57.75,"minClear":0.67,"cells":8,"points":[["00070145",70,-80,0],["00070149",70.88,-116.12,0],["00070159",75.12,-120.62,0],["00070159",77.38,-124.38,0],["0007015A",80.12,-125.12,0],["0007015A",82.88,-127.88,0],["00070167",86.61,-130.04,0]]}, + {"from":"A3","to":"70007081","exit":"Portal to Westwatch","length":66.42,"minClear":0.65,"cells":9,"points":[["00070145",70,-80,0],["00070149",70.88,-116.12,0],["00070159",75.12,-120.62,0],["00070159",77.38,-124.38,0],["0007015A",80.12,-125.12,0],["0007015B",83.12,-137.88,0],["00070168",86.28,-139.95,0]]}, + {"from":"A3","to":"70007082","exit":"Portal to Linvak Tukal","length":76.42,"minClear":0.64,"cells":10,"points":[["00070145",70,-80,0],["0007014B",71.62,-136.38,0],["0007015C",82.88,-147.62,0],["00070169",86.24,-149.99,0]]}, + {"from":"A3","to":"70007083","exit":"Danby's Outpost","length":84.86,"minClear":0.63,"cells":11,"points":[["00070145",70,-80,0],["0007014B",71.62,-137.62,0],["0007015C",76.62,-146.62,0],["0007015D",83.12,-157.88,0],["0007016A",86.42,-160,0]]}, + {"from":"A3","to":"70007084","exit":"Portal to Eastwatch","length":94.2,"minClear":0.64,"cells":12,"points":[["00070145",70,-80,0],["0007014B",71.62,-137.62,0],["0007015C",76.62,-146.62,0],["0007015E",83.12,-167.88,0],["0007016B",86.51,-170.06,0]]}, + {"from":"A3","to":"70007085","exit":"Portal to Shoushi","length":44.92,"minClear":0.71,"cells":7,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["0007016E",96.38,-68.88,0],["0007016C",100,-53.62,0]]}, + {"from":"A3","to":"7000708F","exit":"Portal to Tou-Tou","length":44.82,"minClear":0.68,"cells":7,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["0007016E",96.38,-71.12,0],["00070170",99.98,-86.3,0]]}, + {"from":"A3","to":"70007090","exit":"Mayoi Portal","length":50.51,"minClear":0.65,"cells":8,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["0007016E",96.38,-68.88,0],["0007016D",100.62,-64.88,0],["0007016D",104.38,-62.62,0],["00070172",105.12,-59.88,0],["00070172",107.88,-57.12,0],["00070171",110,-53.37,0]]}, + {"from":"A3","to":"70007095","exit":"Portal to Nanto","length":50.17,"minClear":0.64,"cells":8,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["0007016E",96.38,-71.12,0],["0007016F",101.62,-80.38,0],["00070174",107.62,-83.12,0],["00070175",109.98,-86,0]]}, + {"from":"A3","to":"70007096","exit":"Lin Portal","length":59.4,"minClear":0.64,"cells":9,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["0007016E",96.38,-68.88,0],["0007016D",100.62,-64.88,0],["0007016D",104.38,-62.62,0],["00070172",105.12,-59.88,0],["00070177",118.12,-56.62,0],["00070176",120,-53.43,0]]}, + {"from":"A3","to":"7000709E","exit":"Baishi Portal","length":60.22,"minClear":0.7,"cells":9,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["00070173",109.88,-72.38,0],["00070179",117.62,-81.38,0],["0007017A",119.97,-86.44,0]]}, + {"from":"A3","to":"7000709F","exit":"Portal to Hebian-To","length":68.77,"minClear":0.64,"cells":10,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["00070178",118.12,-66.62,0],["0007017C",127.88,-56.88,0],["0007017B",130,-53.62,0]]}, + {"from":"A3","to":"700070A4","exit":"Portal to Yanshi","length":68.71,"minClear":0.64,"cells":10,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["00070178",118.12,-73.38,0],["0007017E",128.12,-83.38,0],["0007017F",129.95,-86.36,0]]}, + {"from":"A3","to":"700070A5","exit":"Portal to Kara","length":76.96,"minClear":0.65,"cells":11,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["00070178",119.38,-66.62,0],["0007017C",126.62,-63.38,0],["00070181",138.12,-56.38,0],["00070180",140.04,-53.8,0]]}, + {"from":"A3","to":"700070AD","exit":"Sawato Portal","length":77.09,"minClear":0.66,"cells":11,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["00070178",119.38,-73.38,0],["0007017E",126.62,-76.62,0],["00070183",138.12,-83.38,0],["00070184",139.94,-86.36,0]]}, + {"from":"A3","to":"700070AE","exit":"Portal to Kryst","length":80.47,"minClear":0.73,"cells":11,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["00070178",119.38,-66.62,0],["0007017C",126.62,-63.38,0],["00070185",146.52,-59.96,0]]}, + {"from":"A3","to":"700070AF","exit":"Freehold Portal","length":80.49,"minClear":0.67,"cells":11,"points":[["00070145",70,-80,0],["00070164",86.12,-70.12,0],["00070178",119.38,-73.38,0],["0007017E",126.62,-76.62,0],["00070187",146.56,-80.05,0]]}, + {"from":"A4","to":"70007000","exit":"Al-Jalima Portal","length":79.88,"minClear":0.64,"cells":11,"points":[["00070156",80,-70,0],["00070145",70.88,-75.88,0],["00070145",66.88,-75.12,0],["00070133",62.38,-73.38,0],["00070125",52.38,-70.12,0],["00070113",16.88,-64.62,0],["0007010A",3.99,-60,0]]}, + {"from":"A4","to":"70007001","exit":"Tufa Portal","length":80,"minClear":0.65,"cells":11,"points":[["00070156",80,-70,0],["00070145",70.88,-75.88,0],["00070145",66.88,-75.12,0],["00070133",62.38,-73.38,0],["00070125",52.38,-70.12,0],["00070114",20.62,-73.38,0],["0007010C",4.09,-80,0]]}, + {"from":"A4","to":"70007002","exit":"Portal to Zaikhal","length":78.07,"minClear":0.64,"cells":11,"points":[["00070156",80,-70,0],["00070145",70.88,-75.88,0],["00070145",66.88,-75.12,0],["00070133",62.38,-73.38,0],["00070125",52.38,-70.12,0],["00070114",20.88,-65.38,0],["0007010E",12.12,-56.62,0],["0007010D",9.94,-53.81,0]]}, + {"from":"A4","to":"7000700A","exit":"Uziz Portal","length":78.91,"minClear":0.65,"cells":11,"points":[["00070156",80,-70,0],["00070145",70.88,-75.88,0],["00070145",66.88,-75.12,0],["00070133",62.38,-73.38,0],["00070125",52.38,-70.12,0],["00070114",22.12,-73.12,0],["00070110",12.12,-83.12,0],["00070111",9.86,-86.53,0]]}, + {"from":"A4","to":"7000700B","exit":"Portal to Xarabydun","length":69.52,"minClear":0.63,"cells":10,"points":[["00070156",80,-70,0],["00070145",70.88,-75.88,0],["00070133",57.38,-71.88,0],["00070125",52.88,-70.12,0],["00070119",28.88,-66.62,0],["00070112",20.07,-53.86,0]]}, + {"from":"A4","to":"70007013","exit":"Portal to Khayyaban","length":68.94,"minClear":0.64,"cells":10,"points":[["00070156",80,-70,0],["00070145",70.88,-75.88,0],["00070133",57.38,-71.88,0],["00070125",52.88,-70.12,0],["0007011E",43.62,-71.12,0],["0007011F",39.38,-75.12,0],["0007011F",35.62,-77.38,0],["0007011A",33.88,-80.62,0],["00070115",22.12,-83.12,0],["00070116",19.98,-86.44,0]]}, + {"from":"A4","to":"70007014","exit":"Qalaba'r Portal","length":60.45,"minClear":0.65,"cells":9,"points":[["00070156",80,-70,0],["00070145",70.88,-75.88,0],["00070145",66.88,-75.12,0],["00070125",53.38,-70.12,0],["0007011E",43.62,-68.88,0],["0007011D",38.38,-59.62,0],["00070118",32.12,-56.88,0],["00070117",30.01,-53.7,0]]}, + {"from":"A4","to":"70007018","exit":"Portal to Al-Arqas","length":59.92,"minClear":0.65,"cells":9,"points":[["00070156",80,-70,0],["00070145",70.88,-75.88,0],["00070145",66.88,-75.12,0],["00070133",62.38,-73.38,0],["00070125",52.38,-70.12,0],["0007011E",43.62,-71.12,0],["0007011F",39.38,-75.12,0],["0007011F",35.62,-77.38,0],["0007011A",32.88,-82.12,0],["0007011B",29.94,-86.34,0]]}, + {"from":"A4","to":"70007019","exit":"Portal to Samsur","length":54.88,"minClear":0.65,"cells":8,"points":[["00070156",80,-70,0],["00070145",70.88,-75.88,0],["00070133",60.62,-73.38,0],["00070125",53.12,-70.12,0],["0007011E",43.62,-68.88,0],["0007011C",39.97,-53.6,0]]}, + {"from":"A4","to":"70007024","exit":"Portal to Yaraq","length":54.63,"minClear":0.65,"cells":8,"points":[["00070156",80,-70,0],["00070145",70.88,-75.88,0],["00070133",60.62,-73.38,0],["00070125",53.12,-70.12,0],["0007011E",43.62,-71.12,0],["00070120",40,-86.18,0]]}, + {"from":"A4","to":"70007025","exit":"Glenden Wood Portal","length":68.88,"minClear":0.64,"cells":10,"points":[["00070156",80,-70,0],["00070142",70.12,-53.88,0],["0007013F",66.62,-21.88,0],["0007012E",56.62,-11.88,0],["00070121",53.5,-10,0]]}, + {"from":"A4","to":"70007026","exit":"Lytelthorpe Portal","length":59.18,"minClear":0.63,"cells":9,"points":[["00070156",80,-70,0],["00070142",70.12,-53.88,0],["00070141",68.88,-43.62,0],["00070131",64.88,-39.38,0],["00070131",62.62,-35.62,0],["00070130",59.38,-33.88,0],["0007012F",56.62,-21.88,0],["00070122",53.4,-20,0]]}, + {"from":"A4","to":"70007027","exit":"Portal to Cragstone","length":50.24,"minClear":0.64,"cells":8,"points":[["00070156",80,-70,0],["00070142",70.12,-53.88,0],["00070141",68.88,-43.62,0],["00070131",64.88,-39.38,0],["00070131",62.62,-35.62,0],["00070130",57.62,-32.62,0],["00070130",57.12,-32.12,0],["00070123",53.44,-30.01,0]]}, + {"from":"A4","to":"70007028","exit":"Portal to Holtburg","length":44.65,"minClear":0.71,"cells":7,"points":[["00070156",80,-70,0],["00070142",70.12,-53.88,0],["00070141",68.88,-43.62,0],["00070124",53.91,-39.95,0]]}, + {"from":"A4","to":"70007029","exit":"Portal to Facility Hub","length":44.99,"minClear":0.71,"cells":7,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["00070147",68.88,-96.38,0],["00070126",53.55,-100,0]]}, + {"from":"A4","to":"7000702A","exit":"Portal to Bluespire","length":65.02,"minClear":0.73,"cells":9,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["00070149",69.12,-116.12,0],["00070127",53.5,-120.02,0]]}, + {"from":"A4","to":"7000702B","exit":"Portal to Greenspire","length":70.64,"minClear":0.64,"cells":10,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["00070149",69.12,-116.12,0],["00070136",59.62,-121.62,0],["00070137",56.62,-128.12,0],["00070128",53.54,-129.95,0]]}, + {"from":"A4","to":"7000702C","exit":"Ahurenga Portal","length":80.36,"minClear":0.73,"cells":11,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["0007014A",68.62,-128.88,0],["00070138",58.88,-137.62,0],["00070129",53.81,-139.94,0]]}, + {"from":"A4","to":"7000702D","exit":"Portal to Neydisa Castle","length":88.78,"minClear":0.63,"cells":12,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["0007014B",68.12,-136.38,0],["00070139",57.38,-147.12,0],["0007012A",54.05,-149.98,0]]}, + {"from":"A4","to":"7000702E","exit":"Portal to Silyun","length":97.51,"minClear":0.66,"cells":13,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["0007014B",68.12,-137.62,0],["00070139",63.38,-146.88,0],["0007013A",56.62,-158.12,0],["0007012B",53.6,-159.97,0]]}, + {"from":"A4","to":"7000702F","exit":"Fiun Outpost","length":106.42,"minClear":0.65,"cells":14,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["0007014B",68.12,-137.62,0],["00070139",63.38,-146.88,0],["0007013B",56.38,-168.12,0],["0007012C",53.8,-170.02,0]]}, + {"from":"A4","to":"70007030","exit":"Plateau Portal","length":70.74,"minClear":0.73,"cells":10,"points":[["00070156",80,-70,0],["00070142",70.12,-53.88,0],["0007013F",66.62,-20.62,0],["0007012E",63.38,-13.38,0],["0007012D",60,-3.48,0]]}, + {"from":"A4","to":"7000704D","exit":"Base of the Timaru Plateau Portal","length":110.61,"minClear":0.66,"cells":14,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["0007014B",68.12,-137.62,0],["00070139",63.38,-146.88,0],["0007013C",60.02,-176.45,0]]}, + {"from":"A4","to":"7000704E","exit":"Fort Tethana Portal","length":70.12,"minClear":0.71,"cells":9,"points":[["00070156",80,-70,0],["00070142",70.12,-53.88,0],["0007013F",66.62,-20.62,0],["0007013E",67.12,-9.12,0],["0007013D",69.99,-3.56,0]]}, + {"from":"A4","to":"7000705A","exit":"Stonehold Portal","length":70.82,"minClear":0.67,"cells":10,"points":[["00070156",80,-70,0],["00070142",70.12,-53.88,0],["0007013F",73.38,-20.62,0],["00070151",76.62,-13.38,0],["00070150",79.94,-3.35,0]]}, + {"from":"A4","to":"70007079","exit":"Oolutanga's Refuge","length":110.58,"minClear":0.71,"cells":14,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["0007014B",71.62,-137.62,0],["0007015C",76.62,-146.62,0],["0007015F",79.99,-176.28,0]]}, + {"from":"A4","to":"7000707A","exit":"Portal to Dryreach","length":68.78,"minClear":0.63,"cells":10,"points":[["00070156",80,-70,0],["00070142",70.12,-53.88,0],["0007013F",73.38,-21.88,0],["00070151",83.12,-12.12,0],["00070160",86.42,-10,0]]}, + {"from":"A4","to":"7000707B","exit":"Eastham Portal","length":60.27,"minClear":0.7,"cells":9,"points":[["00070156",80,-70,0],["00070142",70.12,-53.88,0],["00070140",72.38,-30.12,0],["00070152",81.38,-22.38,0],["00070161",86.49,-20.03,0]]}, + {"from":"A4","to":"7000707C","exit":"Portal to Rithwic","length":50.34,"minClear":0.63,"cells":8,"points":[["00070156",80,-70,0],["00070142",70.12,-53.88,0],["00070141",71.12,-43.62,0],["00070154",80.38,-38.38,0],["00070153",83.62,-31.88,0],["00070162",86.24,-30,0]]}, + {"from":"A4","to":"7000707D","exit":"Portal to Arwic","length":45.37,"minClear":0.68,"cells":7,"points":[["00070156",80,-70,0],["00070142",70.12,-53.88,0],["00070141",71.12,-43.62,0],["00070163",86.86,-40,0]]}, + {"from":"A4","to":"7000707E","exit":"The Marketplace of Dereth","length":44.65,"minClear":0.68,"cells":7,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["00070147",71.12,-96.38,0],["00070165",86.13,-99.98,0]]}, + {"from":"A4","to":"7000707F","exit":"Portal to Sanamar","length":64.71,"minClear":0.73,"cells":9,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["00070149",70.88,-116.12,0],["00070166",86.18,-120.04,0]]}, + {"from":"A4","to":"70007080","exit":"Portal to Redspire","length":70.54,"minClear":0.67,"cells":10,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["00070149",70.88,-116.12,0],["00070159",75.12,-120.62,0],["00070159",77.38,-124.38,0],["0007015A",80.12,-125.12,0],["0007015A",82.88,-127.88,0],["00070167",86.61,-130.04,0]]}, + {"from":"A4","to":"70007081","exit":"Portal to Westwatch","length":79.21,"minClear":0.65,"cells":11,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["00070149",70.88,-116.12,0],["00070159",75.12,-120.62,0],["00070159",77.38,-124.38,0],["0007015A",80.12,-125.12,0],["0007015B",83.12,-137.88,0],["00070168",86.28,-139.95,0]]}, + {"from":"A4","to":"70007082","exit":"Portal to Linvak Tukal","length":89.21,"minClear":0.64,"cells":12,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["0007014B",71.62,-136.38,0],["0007015C",82.88,-147.62,0],["00070169",86.24,-149.99,0]]}, + {"from":"A4","to":"70007083","exit":"Danby's Outpost","length":97.65,"minClear":0.63,"cells":13,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["0007014B",71.62,-137.62,0],["0007015C",76.62,-146.62,0],["0007015D",83.12,-157.88,0],["0007016A",86.42,-160,0]]}, + {"from":"A4","to":"70007084","exit":"Portal to Eastwatch","length":106.99,"minClear":0.64,"cells":14,"points":[["00070156",80,-70,0],["00070146",70.12,-86.12,0],["0007014B",71.62,-137.62,0],["0007015C",76.62,-146.62,0],["0007015E",83.12,-167.88,0],["0007016B",86.51,-170.06,0]]}, + {"from":"A4","to":"70007085","exit":"Portal to Shoushi","length":32.1,"minClear":0.64,"cells":5,"points":[["00070156",80,-70,0],["0007016E",96.38,-68.88,0],["0007016C",100,-53.62,0]]}, + {"from":"A4","to":"7000708F","exit":"Portal to Tou-Tou","length":32.02,"minClear":0.64,"cells":5,"points":[["00070156",80,-70,0],["0007016E",96.38,-71.12,0],["00070170",99.98,-86.3,0]]}, + {"from":"A4","to":"70007090","exit":"Mayoi Portal","length":37.68,"minClear":0.64,"cells":6,"points":[["00070156",80,-70,0],["0007016E",96.38,-68.88,0],["0007016D",100.62,-64.88,0],["0007016D",104.38,-62.62,0],["00070172",105.12,-59.88,0],["00070172",107.88,-57.12,0],["00070171",110,-53.37,0]]}, + {"from":"A4","to":"70007095","exit":"Portal to Nanto","length":37.38,"minClear":0.64,"cells":6,"points":[["00070156",80,-70,0],["0007016E",96.38,-71.12,0],["0007016F",101.62,-80.38,0],["00070174",107.62,-83.12,0],["00070175",109.98,-86,0]]}, + {"from":"A4","to":"70007096","exit":"Lin Portal","length":46.58,"minClear":0.64,"cells":7,"points":[["00070156",80,-70,0],["0007016E",96.38,-68.88,0],["0007016D",100.62,-64.88,0],["0007016D",104.38,-62.62,0],["00070172",105.12,-59.88,0],["00070177",118.12,-56.62,0],["00070176",120,-53.43,0]]}, + {"from":"A4","to":"7000709E","exit":"Baishi Portal","length":47.59,"minClear":0.71,"cells":7,"points":[["00070156",80,-70,0],["00070173",109.38,-71.88,0],["00070179",117.62,-81.38,0],["0007017A",119.97,-86.44,0]]}, + {"from":"A4","to":"7000709F","exit":"Portal to Hebian-To","length":56.29,"minClear":0.65,"cells":8,"points":[["00070156",80,-70,0],["00070178",117.12,-67.62,0],["0007017C",127.88,-56.88,0],["0007017B",130,-53.62,0]]}, + {"from":"A4","to":"700070A4","exit":"Portal to Yanshi","length":56.25,"minClear":0.67,"cells":8,"points":[["00070156",80,-70,0],["00070178",117.12,-72.38,0],["0007017E",128.12,-83.38,0],["0007017F",129.95,-86.36,0]]}, + {"from":"A4","to":"700070A5","exit":"Portal to Kara","length":64.36,"minClear":0.65,"cells":9,"points":[["00070156",80,-70,0],["00070178",118.62,-67.38,0],["0007017C",127.12,-63.38,0],["00070181",138.12,-56.38,0],["00070180",140.04,-53.8,0]]}, + {"from":"A4","to":"700070AD","exit":"Sawato Portal","length":64.48,"minClear":0.64,"cells":9,"points":[["00070156",80,-70,0],["00070178",118.38,-72.62,0],["0007017E",127.12,-76.62,0],["00070183",138.12,-83.38,0],["00070184",139.94,-86.36,0]]}, + {"from":"A4","to":"700070AE","exit":"Portal to Kryst","length":67.58,"minClear":0.65,"cells":9,"points":[["00070156",80,-70,0],["00070178",118.62,-67.38,0],["00070185",146.52,-59.96,0]]}, + {"from":"A4","to":"700070AF","exit":"Freehold Portal","length":67.61,"minClear":0.64,"cells":9,"points":[["00070156",80,-70,0],["00070178",118.38,-72.62,0],["00070187",146.56,-80.05,0]]} + ] +} diff --git a/tools/navdata/gen_townnet.py b/tools/navdata/gen_townnet.py new file mode 100644 index 0000000..af7918e --- /dev/null +++ b/tools/navdata/gen_townnet.py @@ -0,0 +1,354 @@ +"""Builds townnet.json: the Town Network's portals, for RynthNav's route planner. + +The Town Network is the indoor hub (landblock 0x0007 on retail data) with a +"Portal to Town Network" in many towns and, inside, an exit portal to each town. +This script writes what the world database knows about it: + + arrivals each place an entry portal lands you, inside the network + entries every placed portal (outdoors, in a building, or in a dungeon) whose + destination is inside the network: where it stands on the map, the + nearest town, and which arrival it lands at + exits every placed portal inside the network: where it stands, where it + goes (cell, position, map coordinates, nearest town) + npcs the vendors and other creatures standing inside, as obstacles + +Every portal carries the restrictions the server checks before it lets a +character through (ACE Portal.CheckUseRequirements): minLevel, maxLevel, quest +(the QuestRestriction flag name), closed (PortalBitmask 0: nobody may use it), +noPk / noPkLite / noNpk / onlyOlthoi / noOlthoi / noVitae / noNewAccounts (the +PortalBitmask bits) and accountRequirements (a SubscriptionStatus; ACE gives +every player 1, so 1 restricts nobody). + +The walking paths inside (from every arrival to every exit portal) need the +dats; RynthSuite's Tools/RynthNav.TownNet adds them to the same file: + dotnet run -c Release --project <RynthSuite>/Tools/RynthNav.TownNet -- build --in townnet.json +Build-TownNet.ps1 (next to this script) runs both steps. + +Usage (same options as gen_locations.py; SELECT only, the password stays on the server): + python tools/navdata/gen_townnet.py --out <dir> [--dump <dir> | --from-dump <dir>] + --lb 0007,... the network's landblocks, instead of finding them from the + "Town Network" portals' destinations + +Only our own world database is read; no GoArrow or Crossroads of Dereth data. +""" + +import argparse +import datetime +import hashlib +import json +import os +import re +import sys +from collections import defaultdict + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gen_locations as g # noqa: E402 + +FORMAT_VERSION = 1 + +# Portal weenies named like this lead into the network; their destinations name its landblocks. +TOWN_NETWORK_NAME = re.compile(r'town\s*network', re.I) + +# A portal counts as "in" (or going to) the nearest town within this many map units (0.1 = 24 yd). +TOWN_RADIUS = 3.0 + +# PortalBitmask (ACE.Entity.Enum.PortalBitmask) bits a planner must respect. +PORTAL_BITS = [(0x02, 'noPk'), (0x04, 'noPkLite'), (0x08, 'noNpk'), (0x40, 'onlyOlthoi'), + (0x80, 'noOlthoi'), (0x100, 'noVitae'), (0x200, 'noNewAccounts')] + +_PORTAL_FIELDS = """ + li.guid, li.weenie_Class_Id, li.obj_Cell_Id, li.origin_X, li.origin_Y, li.origin_Z, + li.angles_W, li.angles_X, li.angles_Y, li.angles_Z, + (select s.value from weenie_properties_string s where s.object_Id=li.weenie_Class_Id and s.type=1 limit 1), + pp.obj_Cell_Id, pp.origin_X, pp.origin_Y, pp.origin_Z, + (select i.value from weenie_properties_int i where i.object_Id=li.weenie_Class_Id and i.type=86 limit 1), + (select i.value from weenie_properties_int i where i.object_Id=li.weenie_Class_Id and i.type=87 limit 1), + (select s.value from weenie_properties_string s where s.object_Id=li.weenie_Class_Id and s.type=37 limit 1), + (select i.value from weenie_properties_int i where i.object_Id=li.weenie_Class_Id and i.type=111 limit 1), + (select i.value from weenie_properties_int i where i.object_Id=li.weenie_Class_Id and i.type=26 limit 1), + (select b.value+0 from weenie_properties_bool b where b.object_Id=li.weenie_Class_Id and b.type=43 limit 1), + (select d.value from weenie_properties_d_i_d d where d.object_Id=li.weenie_Class_Id and d.type=1 limit 1), + (select f.value from weenie_properties_float f where f.object_Id=li.weenie_Class_Id and f.type=39 limit 1) +from landblock_instance li +join weenie w on w.class_Id=li.weenie_Class_Id and w.type=7 +left join weenie_properties_position pp on pp.object_Id=li.weenie_Class_Id and pp.position_Type=2""" + +QUERIES = { + # Portal weenies whose name says Town Network, and where they go. + 'tn_weenies': """ +select s.object_Id, s.value, pp.obj_Cell_Id +from weenie_properties_string s +join weenie w on w.class_Id=s.object_Id and w.type=7 +join weenie_properties_position pp on pp.object_Id=s.object_Id and pp.position_Type=2 +where s.type=1 and s.value like '%Town Network%' +order by s.object_Id""", + # Every placed portal with a destination: filtered to the network here, so the query + # does not depend on the landblock list (and one dump serves any --lb). + 'tn_portals': 'select' + _PORTAL_FIELDS + """ +where pp.obj_Cell_Id is not null +order by li.guid""", + # Vendors and other creatures standing in the network (obstacles for the walks). + 'tn_npcs': """ +select li.guid, li.weenie_Class_Id, w.type, li.obj_Cell_Id, li.origin_X, li.origin_Y, li.origin_Z, + (select s.value from weenie_properties_string s where s.object_Id=li.weenie_Class_Id and s.type=1 limit 1), + (select d.value from weenie_properties_d_i_d d where d.object_Id=li.weenie_Class_Id and d.type=1 limit 1) +from landblock_instance li +join weenie w on w.class_Id=li.weenie_Class_Id and w.type in (10,12) +where (li.obj_Cell_Id & 65535) >= 256 +order by li.guid""", + 'poi': g.QUERIES['poi'], + 'surface': g.QUERIES['surface'], +} + + +def fetch(args): + raw = {} + for name, sql in QUERIES.items(): + if args.from_dump: + with open(os.path.join(args.from_dump, name + '.tsv'), encoding='utf-8') as f: + raw[name] = f.read() + else: + raw[name] = g.run_query(args.host, args.db, sql) + if args.dump: + os.makedirs(args.dump, exist_ok=True) + with open(os.path.join(args.dump, name + '.tsv'), 'w', encoding='utf-8', newline='\n') as f: + f.write(raw[name]) + return {k: g.parse_rows(v) for k, v in raw.items()} + + +def r3(v): + return round(v, 3) + + +def lb_of(cell): + return (cell >> 16) & 0xFFFF + + +def restrictions(minlvl, maxlvl, quest, bitmask, acct, advocate): + """The fields a planner checks before it routes a character through a portal.""" + out = {} + if minlvl is not None and int(minlvl) > 0: + out['minLevel'] = int(minlvl) + if maxlvl is not None and int(maxlvl) > 0: + out['maxLevel'] = int(maxlvl) + if quest: + out['quest'] = quest.strip() + if bitmask is not None: + b = int(bitmask) + if b == 0: + out['closed'] = True + for bit, name in PORTAL_BITS: + if b & bit: + out[name] = True + if acct is not None and int(acct) > 0: + out['accountRequirements'] = int(acct) + if advocate == '1': + out['advocateOnly'] = True + return out + + +def build(rows, lbs_override=None): + world = g.World([(int(a), float(b), float(c), int(d)) for a, b, c, d in rows['surface']]) + + # The network's landblocks: where the "Town Network" portals lead. + named = [(int(w), n, int(c)) for w, n, c in rows['tn_weenies'] if TOWN_NETWORK_NAME.search(n or '')] + found = sorted({lb_of(c) for _, _, c in named}) + lbs = sorted(lbs_override) if lbs_override else found + + # Towns (as gen_locations names them), for "which town is this portal in / does it go to". + towns = [] + by_wcid = defaultdict(list) + for name, wcid, cell, x, y, z in rows['poi']: + if cell is not None: + by_wcid[int(wcid)].append((name, int(cell), float(x), float(y), float(z))) + for _wcid, names in by_wcid.items(): + name, cell, x, y, z = max(names, key=lambda n: (n[0].count(' '), len(n[0]))) + if world.place(cell, z) in ('outdoor', 'building'): + ns, ew = g.cell_to_map(cell, x, y) + towns.append((name, ns, ew)) + + def nearest_town(ns, ew): + if not towns: + return None + name, tns, tew = min(towns, key=lambda t: (t[1] - ns) ** 2 + (t[2] - ew) ** 2) + dist = ((tns - ns) ** 2 + (tew - ew) ** 2) ** 0.5 + return {'name': name, 'dist': round(dist, 2)} if dist <= TOWN_RADIUS else None + + def position(cell, x, y, z): + place = world.place(cell, z) + out = {'cell': '%08X' % cell, 'x': r3(x), 'y': r3(y), 'z': r3(z), 'place': place} + if place != 'dungeon': + ns, ew = g.cell_to_map(cell, x, y) + out['ns'], out['ew'] = round(ns, 2), round(ew, 2) + return out + + entries, exits = [], [] + arrivals = {} # (cell, x, y, z) -> arrival dict + seen_entries = {} + for (guid, wcid, cell, x, y, z, aw, ax, ay, az, name, dcell, dx, dy, dz, + minlvl, maxlvl, quest, bitmask, acct, advocate, setup, scale) in rows['tn_portals']: + cell, dcell = int(cell), int(dcell) + x, y, z, dx, dy, dz = float(x), float(y), float(z), float(dx), float(dy), float(dz) + name = (name or 'Portal').strip() + rest = restrictions(minlvl, maxlvl, quest, bitmask, acct, advocate) + inside, into = lb_of(cell) in lbs, lb_of(dcell) in lbs + if inside: + dest = position(dcell, dx, dy, dz) + town = nearest_town(dest['ns'], dest['ew']) if 'ns' in dest else None + if town: + dest['town'] = town + ex = {'guid': '%08X' % int(guid), 'wcid': int(wcid), 'name': name, 'label': g.dungeon_name(name), + 'cell': '%08X' % cell, 'x': r3(x), 'y': r3(y), 'z': r3(z), + 'heading': heading(aw, az), 'dest': dest, 'into': into} + if setup is not None: + ex['setup'] = '%08X' % int(setup) + if scale is not None: + ex['scale'] = float(scale) + ex.update(rest) + exits.append(ex) + elif into: + key = (dcell, r3(dx), r3(dy), r3(dz)) + if key not in arrivals: + arrivals[key] = {'cell': '%08X' % dcell, 'x': r3(dx), 'y': r3(dy), 'z': r3(dz)} + pos = position(cell, x, y, z) + dedupe = (int(wcid), pos['cell'], pos['x'], pos['y'], pos['z']) + if dedupe in seen_entries: # two placements of one portal at one spot + seen_entries[dedupe]['guids'].append('%08X' % int(guid)) + continue + en = {'guid': '%08X' % int(guid), 'guids': ['%08X' % int(guid)], 'wcid': int(wcid), 'name': name, **pos, + 'arrivalKey': key} + town = nearest_town(pos['ns'], pos['ew']) if 'ns' in pos else None + if town: + en['town'] = town + en.update(rest) + seen_entries[dedupe] = en + entries.append(en) + + # Arrival ids in a stable order (by cell, then position). + arr_list = sorted(arrivals.items(), key=lambda kv: kv[0]) + arr_ids = {} + out_arrivals = [] + for i, (key, a) in enumerate(arr_list, 1): + a = dict(id='A%d' % i, **a) + a['entries'] = sum(1 for e in entries if e['arrivalKey'] == key) + arr_ids[key] = a['id'] + out_arrivals.append(a) + for e in entries: + e['arrival'] = arr_ids[e.pop('arrivalKey')] + if len(e['guids']) == 1: + del e['guids'] + entries.sort(key=lambda e: (e['name'].lower(), e['cell'], e['x'], e['y'])) + exits.sort(key=lambda e: (e['cell'], e['name'].lower())) + + npcs = [] + for guid, wcid, wtype, cell, x, y, z, name, setup in rows['tn_npcs']: + cell = int(cell) + if lb_of(cell) not in lbs: + continue + n = {'guid': '%08X' % int(guid), 'wcid': int(wcid), 'name': (name or '').strip(), 'cell': '%08X' % cell, + 'x': r3(float(x)), 'y': r3(float(y)), 'z': r3(float(z))} + if setup is not None: + n['setup'] = '%08X' % int(setup) + npcs.append(n) + + notes = [] + if found != lbs: + notes.append('landblocks given with --lb (%s); the Town Network portals lead to %s' + % (', '.join('%04X' % l for l in lbs), ', '.join('%04X' % l for l in found) or 'none')) + for a in out_arrivals: + if a['entries'] == 0: + notes.append('arrival %s has no entry portal' % a['id']) + return {'landblocks': ['%04X' % l for l in lbs], 'arrivals': out_arrivals, 'entries': entries, + 'exits': exits, 'npcs': npcs, 'notes': notes, 'townNetworkWeenies': [w for w, _, _ in named]} + + +def heading(w, z): + """Compass heading (degrees, 0 = north, clockwise) of a yaw-only rotation, or None.""" + if w is None or z is None: + return None + import math + yaw = 2.0 * math.atan2(float(z), float(w)) # counter-clockwise from +y (north) in AC + return round((-math.degrees(yaw)) % 360.0, 1) + + +def set_id(text): + """The set id: SHA-256 of the file text without its "setId" and "generated" lines (and without + carriage returns, so a CRLF checkout gives the same id), first 16 hex digits. RynthNav.TownNet + computes it the same way. Equal ids mean equal data.""" + kept = [l.rstrip('\r') for l in text.split('\n') if not l.startswith(' "setId":') and not l.startswith(' "generated":')] + return hashlib.sha256('\n'.join(kept).encode('utf-8')).hexdigest()[:16] + + +def serialize(doc): + """One item per line (small diffs when the world changes); RynthNav.TownNet writes the same layout.""" + keys = ['version', 'setId', 'generated', 'source', 'landblocks', 'counts', 'notes', 'walkInfo'] + lists = ['arrivals', 'entries', 'exits', 'npcs', 'walks'] + items = [k for k in keys if k in doc] + [k for k in lists if k in doc] + \ + [k for k in doc if k not in keys and k not in lists] + out = ['{\n'] + for i, k in enumerate(items): + last = i == len(items) - 1 + v = doc[k] + if k in lists: + out.append(' %s: [\n' % json.dumps(k)) + for j, item in enumerate(v): + out.append(' ' + json.dumps(item, ensure_ascii=False, separators=(',', ':')) + + (',' if j < len(v) - 1 else '') + '\n') + out.append(' ]%s\n' % ('' if last else ',')) + else: + out.append(' %s: %s%s\n' % (json.dumps(k), json.dumps(v, ensure_ascii=False), '' if last else ',')) + out.append('}\n') + return ''.join(out) + + +def write(path, doc): + doc['setId'] = '' + doc['setId'] = set_id(serialize(doc)) + with open(path, 'w', encoding='utf-8', newline='\n') as f: + f.write(serialize(doc)) + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument('--out', required=True, help='output folder for townnet.json') + ap.add_argument('--host', default='aelrynth-vps') + ap.add_argument('--db', default='aeshnidae_world') + ap.add_argument('--dump', help='also save the raw query results here') + ap.add_argument('--from-dump', help='read the raw query results from here instead of the server') + ap.add_argument('--lb', help='the network landblocks, hex, comma separated (default: found from the portals)') + args = ap.parse_args(argv) + + rows = fetch(args) + lbs = [int(s, 16) for s in args.lb.split(',')] if args.lb else None + net = build(rows, lbs) + doc = { + 'version': FORMAT_VERSION, + 'setId': '', + 'generated': datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), + 'source': args.db, + 'landblocks': net['landblocks'], + 'counts': {'arrivals': len(net['arrivals']), 'entries': len(net['entries']), 'exits': len(net['exits']), + 'npcs': len(net['npcs'])}, + 'notes': net['notes'], + 'arrivals': net['arrivals'], 'entries': net['entries'], 'exits': net['exits'], 'npcs': net['npcs'], + } + os.makedirs(args.out, exist_ok=True) + path = os.path.join(args.out, 'townnet.json') + write(path, doc) + print('Town Network landblocks: %s (portals named Town Network: weenies %s)' + % (', '.join(net['landblocks']), ', '.join(map(str, net['townNetworkWeenies'])))) + print('arrivals %d, entry portals %d, exit portals %d, npcs %d' + % (len(net['arrivals']), len(net['entries']), len(net['exits']), len(net['npcs']))) + restricted = [e for e in net['entries'] + net['exits'] + if any(k in e for k in ('minLevel', 'maxLevel', 'quest', 'closed', 'onlyOlthoi', 'noPk', 'noNpk'))] + for e in restricted: + print(' restricted: %s (%s)' % (e['name'], ', '.join('%s=%s' % (k, e[k]) for k in + ('minLevel', 'maxLevel', 'quest', 'closed', 'onlyOlthoi', 'noPk', 'noNpk') if k in e))) + for n in net['notes']: + print(' note: ' + n) + print('wrote %s (set %s); the walks inside come from RynthNav.TownNet build' % (path, doc['setId'])) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/navdata/test_gen_townnet.py b/tools/navdata/test_gen_townnet.py new file mode 100644 index 0000000..24ec16d --- /dev/null +++ b/tools/navdata/test_gen_townnet.py @@ -0,0 +1,139 @@ +"""Offline tests for gen_townnet.py: a small made-up world through build(), the +restriction fields, and the file's set id. No server needed. + +Run: python tools/navdata/test_gen_townnet.py +""" + +import json +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gen_townnet as t # noqa: E402 + +TN = 0x0007 +HOLT = 0xA9B4 + + +def portal(guid, wcid, cell, x, y, z, name, dcell, dx, dy, dz, minlvl=None, maxlvl=None, quest=None, + bitmask='1', acct=None, advocate=None, setup='33554867', scale=None): + """A row of the tn_portals query, as parse_rows returns it (strings, None for NULL).""" + s = lambda v: None if v is None else str(v) # noqa: E731 + return [str(guid), str(wcid), str(cell), s(x), s(y), s(z), '1', '0', '0', '0', name, + str(dcell), s(dx), s(dy), s(dz), s(minlvl), s(maxlvl), quest, s(bitmask), s(acct), s(advocate), setup, s(scale)] + + +def world_rows(): + return { + 'tn_weenies': [['42852', 'Portal to Town Network', str((TN << 16) | 0x0145)], + ['30000', 'Some Other Portal', str((0x0123 << 16) | 0x0100)]], + 'tn_portals': [ + # Two entries outdoors in Holtburg landing at one arrival point, one placed twice. + portal(0x7A9B4001, 42852, (HOLT << 16) | 0x0019, 84.0, 9.0, 94.2, 'Portal to Town Network', + (TN << 16) | 0x0145, 70.0, -80.0, 0.005, bitmask='129'), + portal(0x7A9B4002, 42852, (HOLT << 16) | 0x0019, 84.0, 9.0, 94.2, 'Portal to Town Network', + (TN << 16) | 0x0145, 70.0, -80.0, 0.005, bitmask='129'), + # A custom entry with a different name, landing elsewhere inside. + portal(0x7A9B4003, 99001, (HOLT << 16) | 0x0020, 90.0, 20.0, 94.2, 'Aelrynth Gate', + (TN << 16) | 0x0143, 70.0, -60.0, 0.005), + # Exits inside: an open one, a level-gated one, a quest one, a closed one. + portal(0x70007028, 42820, (TN << 16) | 0x0124, 53.91, -39.95, -0.063, 'Portal to Holtburg', + (HOLT << 16) | 0x0019, 84.0, 7.1, 94.0), + portal(0x70007084, 42839, (TN << 16) | 0x016B, 86.51, -170.05, -0.063, 'Portal to Eastwatch', + (0x49F0 << 16) | 0x0013, 70.0, 70.0, 170.0, minlvl=80), + portal(0x70007090, 50001, (TN << 16) | 0x0171, 110.0, -53.37, -0.063, 'Secret Portal', + (HOLT << 16) | 0x0019, 84.0, 7.1, 94.0, quest='SecretFlag', acct=1), + portal(0x70007091, 50002, (TN << 16) | 0x0172, 110.0, -60.0, -0.063, 'Shut Portal', + (HOLT << 16) | 0x0019, 84.0, 7.1, 94.0, bitmask='0'), + # A portal elsewhere that has nothing to do with the network. + portal(0x7A9B4009, 30001, (HOLT << 16) | 0x0021, 10.0, 10.0, 94.0, 'Portal to Somewhere', + (0x0123 << 16) | 0x0100, 1.0, 1.0, 0.0), + ], + 'tn_npcs': [['1879076865', '42799', '12', str((TN << 16) | 0x0200), '10.0', '-20.0', '12.0', 'Barkeeper', '33554510'], + ['1879076866', '1', '10', str((HOLT << 16) | 0x0100), '1.0', '1.0', '1.0', 'Elsewhere', None]], + 'poi': [['Holtburg', '42820', str((HOLT << 16) | 0x0019), '84.0', '7.1', '94.0']], + 'surface': [[str(HOLT), '90.0', '100.0', '40']], + } + + +class BuildTests(unittest.TestCase): + def setUp(self): + self.net = t.build(world_rows()) + + def test_landblocks_from_portal_names(self): + self.assertEqual(self.net['landblocks'], ['0007']) + + def test_arrivals(self): + arr = self.net['arrivals'] + self.assertEqual([a['id'] for a in arr], ['A1', 'A2']) + self.assertEqual(arr[0]['cell'], '00070143') # sorted by cell + self.assertEqual(arr[1]['entries'], 1) # the doubled portal counts once + + def test_entries(self): + en = self.net['entries'] + self.assertEqual(len(en), 2) + holt = [e for e in en if e['name'] == 'Portal to Town Network'][0] + self.assertEqual(holt['guids'], ['7A9B4001', '7A9B4002']) + self.assertEqual(holt['arrival'], 'A2') + self.assertEqual(holt['place'], 'outdoor') + self.assertEqual(holt['town']['name'], 'Holtburg') + self.assertTrue(holt['noOlthoi']) + custom = [e for e in en if e['name'] == 'Aelrynth Gate'][0] + self.assertEqual(custom['arrival'], 'A1') + self.assertNotIn('guids', custom) + + def test_exits_and_restrictions(self): + ex = {e['name']: e for e in self.net['exits']} + self.assertEqual(len(ex), 4) + self.assertEqual(ex['Portal to Holtburg']['label'], 'Holtburg') + self.assertEqual(ex['Portal to Holtburg']['dest']['town']['name'], 'Holtburg') + self.assertNotIn('minLevel', ex['Portal to Holtburg']) + self.assertEqual(ex['Portal to Eastwatch']['minLevel'], 80) + self.assertNotIn('town', ex['Portal to Eastwatch']['dest']) # no town that close + self.assertEqual(ex['Secret Portal']['quest'], 'SecretFlag') + self.assertEqual(ex['Secret Portal']['accountRequirements'], 1) + self.assertTrue(ex['Shut Portal']['closed']) + self.assertEqual(ex['Portal to Holtburg']['setup'], '020001B3') + + def test_npcs_inside_only(self): + self.assertEqual([n['name'] for n in self.net['npcs']], ['Barkeeper']) + + def test_lb_override_is_noted(self): + net = t.build(world_rows(), [0x0007, 0x0008]) + self.assertEqual(net['landblocks'], ['0007', '0008']) + self.assertTrue(any('--lb' in n for n in net['notes'])) + + +def read(path): + with open(path, encoding='utf-8') as f: + return f.read() + + +class FileTests(unittest.TestCase): + def test_set_id_ignores_timestamp(self): + doc = {'version': 1, 'setId': '', 'generated': 'a', 'arrivals': [{'id': 'A1'}]} + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, 'townnet.json') + t.write(p, dict(doc)) + first = json.loads(read(p))['setId'] + t.write(p, dict(doc, generated='b')) + second = json.loads(read(p))['setId'] + t.write(p, dict(doc, arrivals=[{'id': 'A2'}])) + third = json.loads(read(p))['setId'] + text = read(p) + self.assertEqual(first, second) + self.assertNotEqual(first, third) + self.assertEqual(len(first), 16) + self.assertIn(' {"id":"A2"}\n', text) + self.assertEqual(t.set_id(text), json.loads(text)['setId']) + self.assertEqual(t.set_id(text.replace('\n', '\r\n')), json.loads(text)['setId']) # a CRLF checkout + + def test_heading(self): + self.assertEqual(t.heading('1', '0'), 0.0) + self.assertEqual(t.heading('0.70710678', '-0.70710678'), 90.0) # yaw -90 = facing east + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/pe_pattern.py b/tools/pe_pattern.py index d268162..75583cb 100644 --- a/tools/pe_pattern.py +++ b/tools/pe_pattern.py @@ -165,6 +165,11 @@ GROUPS = { "TimeSyncHooks": [ ("ClientNet_HandleTimeSynch", 0x005448F0), ], + "PlayerTrade": [ + ("Event_OpenTradeNegotiations", 0x006AE260), ("Event_AddToTrade", 0x006AE030), + ("Event_ResetTrade", 0x006AE330), ("Event_CloseTradeNegotiations", 0x006AE140), + ("ClientTradeSystem_AcceptTrade", 0x0056E7A0), ("ClientTradeSystem_DeclineTrade", 0x0056E7C0), + ], } def best_pattern(text_b, text_base, va, off): @@ -188,6 +193,7 @@ GROUPS_DATA = [ ("s_selected_id", 0x00871E54), ("s_previous_selected_id", 0x00871E58), ("split_amount", 0x0081D7EC), ("total_stack", 0x0081D7F0), ("PStringChar_s_NullBuffer", 0x008EF11C), ("PStringWide_s_NullBuffer", 0x00818340), + ("ClientTradeSystem_s_pTradeSystem", 0x0087174C), ("RecvFrom_slot", 0x007935AC), ] @@ -297,7 +303,10 @@ def _compat_dir(): def parse_engine_patterns(): srcs = {} - for f in glob.glob(os.path.join(_compat_dir(), "*.cs")): + # Compatibility/ holds nearly every hook; D3D9/AcUiPassHook.cs (RenderUI::RenderObjects) + # is the one function hook that lives with the render code. + engine_dir = os.path.dirname(_compat_dir()) + for f in glob.glob(os.path.join(_compat_dir(), "*.cs")) + glob.glob(os.path.join(engine_dir, "D3D9", "*.cs")): with open(f, "r", encoding="utf-8") as fh: # Strip // line comments so commas / brackets inside an inline disasm # comment (e.g. `0x84, 0xC0 // MOV AL,[ESP+4]; TEST AL,AL`) can't corrupt