diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c4a7c68..7421c81 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -50,9 +50,12 @@ jobs: $override = "${{ github.event.inputs.rynthsuite_ref }}" if ($override) { $want = $override } Write-Host "Cloning RynthSuite to: $dest (pin target: $want)" + # Sibling fork on the same GitHub owner (BlankenshipG in this environment). + # Canonical public source is https://aelrynth.com/git/RynthSuite.git — CI uses + # the GitHub sibling so the release build matches this fork pair. # If RynthSuite is private, set a GH_PAT secret and use the token URL: - # git clone https://x-access-token:${{ secrets.GH_PAT }}@github.com/tombohar/RynthSuite.git $dest - git clone https://github.com/tombohar/RynthSuite.git $dest + # git clone https://x-access-token:${{ secrets.GH_PAT }}@github.com/${{ github.repository_owner }}/RynthSuite.git $dest + git clone "https://github.com/${{ github.repository_owner }}/RynthSuite.git" $dest if ($LASTEXITCODE -ne 0) { throw "git clone RynthSuite failed" } git -C $dest fetch --tags --quiet if ($want -and (git -C $dest rev-parse --verify --quiet "$want^{commit}")) { diff --git a/.gitignore b/.gitignore index 97871b1..36bf792 100644 --- a/.gitignore +++ b/.gitignore @@ -49,4 +49,10 @@ installer/Releases/ # Process Monitor / debug log dumps (session junk) *.PML Logfile*.XML +# Archived installers (Build-Installer.ps1 keeps the previous release here; only the version marker is tracked) +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/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..37f53e3 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,133 @@ +# RynthCore — Codex Context + +A modern .NET 9 NativeAOT framework for Asheron's Call client modding. Replaces Decal + UBService with a self-contained injection system. Hooks D3D9 EndScene to render an ImGui overlay inside the AC client process. + +--- + +## ⚠ Active Focus: RynthAi ImGui Plugin + +**Do NOT work on `src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs` (the Avalonia version of RynthAi).** +The Avalonia RynthAi panel is disabled (`EntryPoint.cs` registration is commented out) and parked until the ImGui plugin is feature-complete. All RynthAi work goes in `Plugins/RynthCore.Plugin.RynthAi/` which uses ImGui via `RynthCore.PluginCore`. + +--- + +## Project Layout + +``` +C:\Projects\RynthCore\ +└── src\ + ├── RynthCore.Injector\ Console app — injects Engine into acclient.exe + │ └── Program.cs LoadLibrary + CreateRemoteThread injection + └── RynthCore.Engine\ NativeAOT x86 DLL — lives inside acclient.exe + ├── EntryPoint.cs Exported RynthCoreInit, preloads native DLLs, spawns init thread + ├── D3D9\ + │ ├── D3D9VTable.cs Temp device to harvest vtable pointers + │ ├── EndSceneHook.cs MinHook detour on EndScene + │ └── TestRenderer.cs v0.1 proof-of-life, kept for reference + └── ImGui\ + ├── ImGuiController.cs Context creation, frame loop orchestration + ├── DX9Backend.cs Renders ImGui draw data via raw D3D9 vtable calls + └── Win32Backend.cs WndProc subclass for mouse/keyboard input +``` + +Deploy folder: `C:\Games\RynthCore\` + +--- + +## Build + +```bash +# Engine (NativeAOT — slow first build, ~2 min) +cd src\RynthCore.Engine +dotnet publish -c Release + +# Injector +cd src\RynthCore.Injector +dotnet publish -c Release +``` + +Both projects target **x86** only. The Engine is NativeAOT (`PublishAot=true`) — it has no .NET runtime dependency and injects as a plain native DLL. + +Deploy output: +``` +C:\Games\RynthCore\ +├── RynthCore.Engine.dll ← Engine publish output +├── RynthCore.Injector.exe ← Injector publish output +├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint +└── cimgui.dll ← ImGui C bindings (x86, docking branch) +``` + +Log file: `%USERPROFILE%\Desktop\RynthCore.log` + +--- + +## Key Technical Facts + +### NativeAOT / x86 +- .NET 9, `net9.0-windows`, `PlatformTarget=x86`, `RuntimeIdentifier=win-x86` +- `AllowUnsafeBlocks=true`, `PublishAot=true`, `TrimMode=link` +- `ImGui.NET` assembly is trim-rooted to preserve P/Invoke bindings +- `SetWindowLongA` not `SetWindowLongPtrA` — the Ptr variant doesn't exist on x86 + +### Injection flow +1. `RynthCore.Injector.exe` calls `CreateRemoteThread(LoadLibrary, "RynthCore.Engine.dll")` +2. `RynthCoreInit` export fires under loader lock — immediately spawns background thread +3. Init thread sleeps 2s (lets AC finish D3D9 init), preloads minhook + cimgui, then installs EndScene hook + +### D3D9 hook +- Vtable discovery: creates a throwaway device via `D3D9VTable.cs`, captures 119 vtable entries +- Hook installed via MinHook on `EndScene` (vtable index 42) +- All D3D9 calls go through cached delegates (stdcall, `this` as first param) — never via COM wrappers +- State save/restore is manual (get/set each render state) — D3D9 state blocks don't work reliably inside EndScene + +### ImGui / cimgui version situation +- ImGui.NET NuGet: **1.91.6.1** +- cimgui.dll must match: use `%USERPROFILE%\.nuget\packages\imgui.net\1.91.6.1\runtimes\win-x86\native\cimgui.dll` +- Post-1.90 struct layout: `ImDrawData.CmdLists` is an **ImVector (12 bytes)**, not a raw pointer (4 bytes) +- `DX9Backend.cs` reads `ImDrawData` fields from native memory at confirmed offsets as a safety fallback: + - `+4` = CmdListsCount + - `+16` = CmdLists array pointer + - `+20/24` = DisplayPos (X, Y) + - `+28/32` = DisplaySize (X, Y) + +### ImGui input API +- Uses the **modern** API: `AddKeyEvent` / `AddMouseButtonEvent` / `AddMousePosEvent` +- `KeyMap` / `KeysDown` / `MouseDown` arrays were removed in ImGui 1.87 — do not use them +- WndProc subclass via `SetWindowLongA` (not Ptr) in `Win32Backend.cs` + +### DX9Backend render notes +- `DrawIndexedPrimitiveUP` takes user-memory pointers directly — **do not** call `SetStreamSource(null)` before it, this crashes the driver +- Vertex format: `D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1` — xyz (3 floats) + BGRA color (uint) + uv (2 floats) +- ImGui gives RGBA pixel data; D3D9 `A8R8G8B8` is BGRA in memory — swizzle R↔B on upload +- Color conversion per vertex: `(c & 0xFF00FF00) | ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16)` +- Font texture: `POOL_MANAGED`, created once in `Init`, `TexID` set via `io.Fonts.SetTexID` + +### Multi-viewport (docking/undocking outside AC window) +- `DockingEnable` is on +- `ViewportsEnable` is commented out — requires cimgui built with `IMGUI_ENABLE_VIEWPORTS` + +--- + +## Common Pitfalls + +| Symptom | Cause | +|---------|-------| +| `DisplaySize = <1, 1>` | cimgui.dll version mismatch (pre/post 1.90 layout) | +| Font cache crash on frame 2 | `io.Fonts.TexID` was zero after init (usually fixed by matching cimgui) | +| Crash in `SetupRenderStateNative` | Do not call `SetStreamSource(null, 0)` — invalid for UP drawing | +| Duplicate `vtxCount` compile error | Was present in early source — remove the second declaration | +| Hook not firing | acclient.exe must be running and past login before injection | +| `ChangePortalMode` event (future) | Crashes Decal — never use (RynthCore note carried from NexTank) | + +--- + +## Current Status (v0.2) + +- [x] D3D9 EndScene hook stable +- [x] ImGui context, font texture, WndProc subclass working +- [x] ImGui demo window + RynthCore info panel rendering +- [x] Mouse/keyboard input forwarded; ImGui captures input when hovered +- [ ] Multi-viewport (needs IMGUI_ENABLE_VIEWPORTS cimgui build) +- [ ] NexTank UI panels ported to RynthCore +- [ ] Network message hooks +- [ ] World state / actions API diff --git a/BUILD.md b/BUILD.md index 43fae17..15776e1 100644 --- a/BUILD.md +++ b/BUILD.md @@ -213,6 +213,10 @@ cd C:\Projects\RynthCore\installer This runs `dotnet publish` for the Launcher, Loader, Engine, and RynthAi plugin (from RynthSuite), stages everything under `installer\staging\app\`, then invokes `ISCC.exe` to produce the installer. +It also publishes the **experimental plugins** — RynthChat, RynthJuice, RynthNav, RynthTracker, RynthVision and **ub-Rythai** (`RynthSuite\Plugins\ub-Rythai\RynthCore.Plugin.UbRythai`) — as optional installer components (unchecked by default) that install to `\\RynthCore.Plugin..dll`. + +`..\Build-Release-All.ps1 -Version ` builds `RynthCore.sln` first and then runs `Build-Installer.ps1`. + Output: `installer\Output\RynthCore-Setup.exe` ### Options diff --git a/Build-Release-All.ps1 b/Build-Release-All.ps1 new file mode 100644 index 0000000..2c680ff --- /dev/null +++ b/Build-Release-All.ps1 @@ -0,0 +1,73 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Builds a full Release of RynthCore + RynthSuite and produces the Windows installer. + +.DESCRIPTION + 1. Compiles RynthCore.sln in Release (validates all SDK projects before the slow publishes). + 2. Invokes installer\Build-Installer.ps1, which publishes the launcher, engine, loader, + RynthAi, the Loot/Monster editors and the experimental plugins (incl. ub-Rythai), stages + them, archives the previous installer when -Version changes, and compiles RynthCore.iss + into installer\Output\RynthCore-Setup-.exe (requires Inno Setup 6). + 3. With -Version, Build-Installer.ps1 also assembles the deployment package + installer\Output\Release-\ and installer\Output\RynthCore--deploy.zip + (installer + SHA256SUMS.txt + release-manifest.json + RELEASE-NOTES.md, hash-verified). + +.PARAMETER Version + Installer version (e.g. 2026.10.4.7). Passed through to Build-Installer.ps1. + +.PARAMETER RynthSuiteRoot + RynthSuite checkout. Default (empty): the sibling ..\RynthSuite folder. + +.PARAMETER IsccPath + ISCC.exe location. Default (empty): Build-Installer.ps1 searches the usual Inno Setup paths. + +.EXAMPLE + .\Build-Release-All.ps1 -Version 2026.10.4.7 +#> +param( + [string]$Version = "", + [string]$RynthSuiteRoot = "", + [string]$IsccPath = "" +) + +$ErrorActionPreference = "Stop" +# This script lives at the RynthCore repository root. +$RepoRoot = $PSScriptRoot + +$sln = Join-Path $RepoRoot "RynthCore.sln" +if (-not (Test-Path $sln)) { + throw "RynthCore.sln not found at: $sln" +} + +# Plugin API delegates must be cdecl. On x86 a delegate without +# [UnmanagedFunctionPointer(CallingConvention.Cdecl)] marshals as stdcall, and every cdecl call +# from a plugin then pops its arguments twice and corrupts the plugin's stack. +$contract = Join-Path $RepoRoot "src\RynthCore.Engine\Plugins\PluginContract.cs" +$contractLines = [IO.File]::ReadAllLines($contract) +$badDelegates = @() +for ($i = 0; $i -lt $contractLines.Length; $i++) { + if ($contractLines[$i] -notmatch '^\s*(internal|public)\s+(unsafe\s+)?delegate\s') { continue } + # Nearest previous line that is not blank and not a // comment must carry the attribute. + $j = $i - 1 + while ($j -ge 0 -and ($contractLines[$j].Trim() -eq '' -or $contractLines[$j].Trim().StartsWith('//'))) { $j-- } + if ($j -lt 0 -or $contractLines[$j] -notmatch 'UnmanagedFunctionPointer\(CallingConvention\.Cdecl\)') { + $badDelegates += " line $($i + 1): $($contractLines[$i].Trim())" + } +} +if ($badDelegates.Count -gt 0) { + throw "PluginContract.cs delegate(s) missing [UnmanagedFunctionPointer(CallingConvention.Cdecl)]:`n$($badDelegates -join "`n")" +} + +Write-Host "Building solution: $sln" -ForegroundColor Cyan +dotnet build $sln -c Release +if ($LASTEXITCODE -ne 0) { throw "Solution build failed (exit $LASTEXITCODE)" } + +# Only forward parameters Build-Installer.ps1 actually declares. +$invokeArgs = @{ Configuration = "Release" } +if ($Version) { $invokeArgs.Version = $Version } +if ($RynthSuiteRoot) { $invokeArgs.RynthSuiteRoot = $RynthSuiteRoot } +if ($IsccPath) { $invokeArgs.IsccPath = $IsccPath } + +& (Join-Path $RepoRoot "installer\Build-Installer.ps1") @invokeArgs +if ($LASTEXITCODE -ne 0) { throw "Build-Installer.ps1 failed (exit $LASTEXITCODE)" } diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..b1e83fa --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,133 @@ +# RynthCore — Claude Context + +A modern .NET 9 NativeAOT framework for Asheron's Call client modding. Replaces Decal + UBService with a self-contained injection system. Hooks D3D9 EndScene to render an ImGui overlay inside the AC client process. + +--- + +## ⚠ Active Focus: RynthAi ImGui Plugin + +**Do NOT work on `src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs` (the Avalonia version of RynthAi).** +The Avalonia RynthAi panel is disabled (`EntryPoint.cs` registration is commented out) and parked until the ImGui plugin is feature-complete. All RynthAi work goes in `Plugins/RynthCore.Plugin.RynthAi/` which uses ImGui via `RynthCore.PluginCore`. + +--- + +## Project Layout + +``` +C:\Projects\RynthCore\ +└── src\ + ├── RynthCore.Injector\ Console app — injects Engine into acclient.exe + │ └── Program.cs LoadLibrary + CreateRemoteThread injection + └── RynthCore.Engine\ NativeAOT x86 DLL — lives inside acclient.exe + ├── EntryPoint.cs Exported RynthCoreInit, preloads native DLLs, spawns init thread + ├── D3D9\ + │ ├── D3D9VTable.cs Temp device to harvest vtable pointers + │ ├── EndSceneHook.cs MinHook detour on EndScene + │ └── TestRenderer.cs v0.1 proof-of-life, kept for reference + └── ImGui\ + ├── ImGuiController.cs Context creation, frame loop orchestration + ├── DX9Backend.cs Renders ImGui draw data via raw D3D9 vtable calls + └── Win32Backend.cs WndProc subclass for mouse/keyboard input +``` + +Deploy folder: `C:\Games\RynthCore\` + +--- + +## Build + +```bash +# Engine (NativeAOT — slow first build, ~2 min) +cd src\RynthCore.Engine +dotnet publish -c Release + +# Injector +cd src\RynthCore.Injector +dotnet publish -c Release +``` + +Both projects target **x86** only. The Engine is NativeAOT (`PublishAot=true`) — it has no .NET runtime dependency and injects as a plain native DLL. + +Deploy output: +``` +C:\Games\RynthCore\ +├── RynthCore.Engine.dll ← Engine publish output +├── RynthCore.Injector.exe ← Injector publish output +├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint +└── cimgui.dll ← ImGui C bindings (x86, docking branch) +``` + +Log file: `%USERPROFILE%\Desktop\RynthCore.log` + +--- + +## Key Technical Facts + +### NativeAOT / x86 +- .NET 9, `net9.0-windows`, `PlatformTarget=x86`, `RuntimeIdentifier=win-x86` +- `AllowUnsafeBlocks=true`, `PublishAot=true`, `TrimMode=link` +- `ImGui.NET` assembly is trim-rooted to preserve P/Invoke bindings +- `SetWindowLongA` not `SetWindowLongPtrA` — the Ptr variant doesn't exist on x86 + +### Injection flow +1. `RynthCore.Injector.exe` calls `CreateRemoteThread(LoadLibrary, "RynthCore.Engine.dll")` +2. `RynthCoreInit` export fires under loader lock — immediately spawns background thread +3. Init thread sleeps 2s (lets AC finish D3D9 init), preloads minhook + cimgui, then installs EndScene hook + +### D3D9 hook +- Vtable discovery: creates a throwaway device via `D3D9VTable.cs`, captures 119 vtable entries +- Hook installed via MinHook on `EndScene` (vtable index 42) +- All D3D9 calls go through cached delegates (stdcall, `this` as first param) — never via COM wrappers +- State save/restore is manual (get/set each render state) — D3D9 state blocks don't work reliably inside EndScene + +### ImGui / cimgui version situation +- ImGui.NET NuGet: **1.91.6.1** +- cimgui.dll must match: use `%USERPROFILE%\.nuget\packages\imgui.net\1.91.6.1\runtimes\win-x86\native\cimgui.dll` +- Post-1.90 struct layout: `ImDrawData.CmdLists` is an **ImVector (12 bytes)**, not a raw pointer (4 bytes) +- `DX9Backend.cs` reads `ImDrawData` fields from native memory at confirmed offsets as a safety fallback: + - `+4` = CmdListsCount + - `+16` = CmdLists array pointer + - `+20/24` = DisplayPos (X, Y) + - `+28/32` = DisplaySize (X, Y) + +### ImGui input API +- Uses the **modern** API: `AddKeyEvent` / `AddMouseButtonEvent` / `AddMousePosEvent` +- `KeyMap` / `KeysDown` / `MouseDown` arrays were removed in ImGui 1.87 — do not use them +- WndProc subclass via `SetWindowLongA` (not Ptr) in `Win32Backend.cs` + +### DX9Backend render notes +- `DrawIndexedPrimitiveUP` takes user-memory pointers directly — **do not** call `SetStreamSource(null)` before it, this crashes the driver +- Vertex format: `D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1` — xyz (3 floats) + BGRA color (uint) + uv (2 floats) +- ImGui gives RGBA pixel data; D3D9 `A8R8G8B8` is BGRA in memory — swizzle R↔B on upload +- Color conversion per vertex: `(c & 0xFF00FF00) | ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16)` +- Font texture: `POOL_MANAGED`, created once in `Init`, `TexID` set via `io.Fonts.SetTexID` + +### Multi-viewport (docking/undocking outside AC window) +- `DockingEnable` is on +- `ViewportsEnable` is commented out — requires cimgui built with `IMGUI_ENABLE_VIEWPORTS` + +--- + +## Common Pitfalls + +| Symptom | Cause | +|---------|-------| +| `DisplaySize = <1, 1>` | cimgui.dll version mismatch (pre/post 1.90 layout) | +| Font cache crash on frame 2 | `io.Fonts.TexID` was zero after init (usually fixed by matching cimgui) | +| Crash in `SetupRenderStateNative` | Do not call `SetStreamSource(null, 0)` — invalid for UP drawing | +| Duplicate `vtxCount` compile error | Was present in early source — remove the second declaration | +| Hook not firing | acclient.exe must be running and past login before injection | +| `ChangePortalMode` event (future) | Crashes Decal — never use (RynthCore note carried from NexTank) | + +--- + +## Current Status (v0.2) + +- [x] D3D9 EndScene hook stable +- [x] ImGui context, font texture, WndProc subclass working +- [x] ImGui demo window + RynthCore info panel rendering +- [x] Mouse/keyboard input forwarded; ImGui captures input when hovered +- [ ] Multi-viewport (needs IMGUI_ENABLE_VIEWPORTS cimgui build) +- [ ] NexTank UI panels ported to RynthCore +- [ ] Network message hooks +- [ ] World state / actions API diff --git a/Changelog/2026-04-22-inno-installer-prereq-dotnet-x64.md b/Changelog/2026-04-22-inno-installer-prereq-dotnet-x64.md new file mode 100644 index 0000000..bc0dbcc --- /dev/null +++ b/Changelog/2026-04-22-inno-installer-prereq-dotnet-x64.md @@ -0,0 +1,15 @@ +# Inno Setup — .NET 10+ Desktop (x64) prerequisite page (2026-04-22) + +## Summary + +`installer/RynthCore.iss` now includes a custom wizard page (after **Welcome**) that: + +- Detects .NET 10 in the 64-bit registry in **either** way: + - `HKLM\SOFTWARE\dotnet\shared\Microsoft.WindowsDesktop.App\` (version folder major ≥ 10), or + - `HKLM\SOFTWARE\Microsoft\dotnet\InstalledManifests\x64\` — any subkey name containing `Manifest-10.` (e.g. `...Manifest-10.0.100` under **InstalledManifests\x64** in `regedit`). +- Offers **Open download page** (Microsoft .NET 10 download hub) and **Check again** after the user installs. +- **Disables Next** on 64-bit Windows until the runtime is present, so file copy cannot start without it. +- On **32-bit** Windows, skips the requirement (tools are x64-only; `RynthCore.exe` still installs). +- On **silent** install (`/SILENT`, `/VERYSILENT`), **skips** the page so automation is not blocked; the admin must pre-provision the x64 runtime for the editors. + +RynthCore.exe / Injector remain self-contained; this check is only for the bundled **x64** tool exes. diff --git a/Changelog/2026-04-22-installer-prereq-sharedhost-and-bundled-runtime-fallback.md b/Changelog/2026-04-22-installer-prereq-sharedhost-and-bundled-runtime-fallback.md new file mode 100644 index 0000000..5bd24ea --- /dev/null +++ b/Changelog/2026-04-22-installer-prereq-sharedhost-and-bundled-runtime-fallback.md @@ -0,0 +1,18 @@ +# Changelog — Installer .NET 10 check + self-contained host fallback (2026-04-22) + +## Summary + +- **Inno (`RynthCore.iss`):** The prerequisite page for the x64 .NET 10+ Desktop/Loot-Monster tool chain now also treats a valid install as **HKLM64\SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost** (and the parallel `SOFTWARE\Microsoft\dotnet\Setup\...` key when present) when **Version** is **10+**. This matches how the runtime advertises the shared host, not only `...\shared\Microsoft.WindowsDesktop.App\...` or `InstalledManifests` (SDK) entries. +- **Build-Installer (`Build-Installer.ps1`):** Launcher and Injector `dotnet publish` for the bundle add **`-p:SelfContained=true -p:PublishSelfContained=true -p:RollForward=Disable`**. Self-contained apphosts should not roll forward to **%ProgramFiles%\dotnet\shared\...** when a matching **major** is bundled next to the executable. + +## Reason + +Users reported the app (or the installer) still “checking for .NET in the wrong place.” The registry under **Setup\InstalledVersions\x64\sharedhost** is a primary signal for a machine .NET host install. Separately, a self-contained build can still consult global locations unless **RollForward** is set to not roll to a **shared** host install. + +## Follow-up + +Rebuild the bundle with `Build-Installer.ps1 -Version ` and verify on a machine **without** a user-visible **WindowsDesktop.App** shared folder but **with** a normal .NET 10+ runtime (sharedhost) install. + +--- + +**Related assembly:** `RynthCore.App.Avalonia` **0.1.2** (Informational: `0.1.2-scd-rollforward-disable`). diff --git a/Changelog/2026-04-22-installer-previous-release-folder.md b/Changelog/2026-04-22-installer-previous-release-folder.md new file mode 100644 index 0000000..ca599b1 --- /dev/null +++ b/Changelog/2026-04-22-installer-previous-release-folder.md @@ -0,0 +1,12 @@ +# Changelog — Installer previous-release archive (2026-04-22) + +## Summary + +- **`installer\Build-Installer.ps1`:** When **`-Version`** is supplied and Inno Setup is about to run, if **`installer\previous-release\last-built-version.txt`** differs from that version and **`installer\Output\RynthBundle-Setup.exe`** exists, the existing setup is copied to **`installer\previous-release\RynthBundle-Setup-.exe`** before the new compile overwrites `Output\`. +- After a **successful** `ISCC` run, **`last-built-version.txt`** is rewritten to the new `-Version` string. +- **`.gitignore`:** `installer/previous-release/*.exe` so archived installers stay local; **`last-built-version.txt`** remains tracked (seeded at **0.4.1**). +- **`BUILD.md`:** Documents the behavior under the installer section. + +## Reason + +Keeps the last shipping bundle installer on disk when bumping **`-Version`**, without manual copies. diff --git a/Changelog/2026-04-22-launcher-injector-self-contained.md b/Changelog/2026-04-22-launcher-injector-self-contained.md new file mode 100644 index 0000000..d37979e --- /dev/null +++ b/Changelog/2026-04-22-launcher-injector-self-contained.md @@ -0,0 +1,17 @@ +# Launcher + Injector: self-contained publish (2026-04-22) + +## Problem + +`RynthCore.exe` and `RynthCore.Injector.exe` were built **framework-dependent**. On PCs without a global **.NET Desktop Runtime 10 (x86)**, Windows shows the standard apphost dialog (“You must install .NET to run this application”) — that is the OS host, not C# code in the app. + +## Change + +- **`installer/Build-Installer.ps1`:** `dotnet publish` for `RynthCore.App.Avalonia` and `RynthCore.Injector` now uses **`--self-contained true`** (still **win-x86**). The install layout carries the .NET host + runtime next to the apphosts; **no separate x86 runtime install** is required to run the launcher or injector from the game folder. +- **`installer/staging` prerequisites text:** `RynthCore-Prerequisites.txt` updated — x64 **only** for optional **LootEditor** / **MonsterEditor** (still FDD). +- **`installer/RynthCore.iss`:** Removed the Start Menu shortcut **“Install .NET Desktop Runtime (Download)”** so the primary experience does not push a global .NET install for the main app. +- **`BUILD.md`:** Aligned with the same story. +- **`RynthCore.App.Avalonia`:** Version **0.1.0 → 0.1.1** (informational tag `0.1.1-launcher-scd-installer`). + +## Tradeoff + +Installer and on-disk size grow (bundled .NET 10 x86 for two executables). This matches the request that the **app** not depend on a preinstalled runtime; only the **optional** x64 tools still document a separate download. diff --git a/Changelog/2026-04-22-minhook-preload-before-multiclient.md b/Changelog/2026-04-22-minhook-preload-before-multiclient.md new file mode 100644 index 0000000..76b9d38 --- /dev/null +++ b/Changelog/2026-04-22-minhook-preload-before-multiclient.md @@ -0,0 +1,12 @@ +# Changelog — MinHook preload before multi-client init (2026-04-22) + +## Summary + +- **EntryPoint:** `RynthCoreInit` now preloads `minhook.x86.dll` from the resolved engine directory **before** `MultiClientHooks.Initialize()` runs. +- **Reason:** Multi-client hooks call MinHook P/Invokes immediately; without an explicit `LoadLibrary` on the full path, Windows often searches from the **AC client** directory first, producing `Unable to load DLL 'minhook.x86.dll'` even when the file exists under `Runtime\`. The init thread’s later preload was too late for that first hook pass. +- **Build stamp:** `EntryPoint.BuildStamp` bumped to `2026-04-22-v55-minhook-before-multiclient`. + +## User-visible effect + +- Fewer spurious **“multi-client hook failed - Unable to load DLL 'minhook.x86.dll'”** lines when `minhook.x86.dll` is deployed next to the engine. +- Init thread still preloads MinHook (harmless duplicate load if already mapped). diff --git a/Changelog/2026-04-22-net-prereq-launcher-matches-inno.md b/Changelog/2026-04-22-net-prereq-launcher-matches-inno.md new file mode 100644 index 0000000..fb186ce --- /dev/null +++ b/Changelog/2026-04-22-net-prereq-launcher-matches-inno.md @@ -0,0 +1,16 @@ +# Changelog — Launcher .NET 10+ x64 probe matches Inno (2026-04-22) + +## Problem + +The installer’s prerequisite page used specific **HKLM64** rules for the **Loot/Monster** x64 FDD tools, while the launcher only reported **x86** self-contained **sidecar** files (`RynthCore.runtimeconfig.json` / `deps.json`). That was a different notion of “runtime” and was easy to confuse with the setup’s **registry** check. + +## Change + +- **`src/RynthCore.DesktopLog/NetDesktopX64Prerequisite.cs`:** Implements the same three registry paths as **`installer/RynthCore.iss`**: `Microsoft.WindowsDesktop.App` 10+ folders, `InstalledManifests\x64` **manifest-10.**, and **`sharedhost` Version** 10+ under `dotnet\Setup` and `Microsoft\dotnet\Setup`. Uses **`RegistryView.Registry64`**. On 32-bit OS, returns “satisfied” (N/A) like Inno. +- **`LauncherHostDiagnostics`:** The activity line and `RynthCore-Launcher.log` now include a clear **x64 suite tools** line with the same result as setup, plus the official download URL when not detected. +- **`RynthCore.iss`:** Comment points maintainers to **`NetDesktopX64Prerequisite.cs`**. + +## Versions + +- **RynthCore.DesktopLog** `1.0.0` → **`1.0.1`** +- **RynthCore.App.Avalonia** `0.1.2` → **`0.1.3`** diff --git a/Changelog/2026-04-22-plugin-extra-path-dedupe-hot-reload.md b/Changelog/2026-04-22-plugin-extra-path-dedupe-hot-reload.md new file mode 100644 index 0000000..8c1e79d --- /dev/null +++ b/Changelog/2026-04-22-plugin-extra-path-dedupe-hot-reload.md @@ -0,0 +1,16 @@ +# RynthCore Engine v57 — plugin extra path dedupe and unload cleanup + +**Build stamp:** `2026-04-22-v57-plugin-extra-path-dedupe` + +## Problem + +When the same logical DLL appeared twice — typically `RynthCore.Plugin.RynthAi.dll` under `Runtime\Plugins\` and again as an **extra plugin path** (e.g. `C:\Games\Rynthcore\RynthCore.Plugin.RynthAi.dll`) — the loader staged both copies into the same per-session shadow directory using the **same file name**. The second `File.Copy(..., overwrite: true)` failed with *The process cannot access the file ... because it is being used by another process*, which cluttered logs and could confuse hot-reload behavior for plugins loaded afterward (e.g. **ub-Rythai** / `RynthCore.Plugin.UbRythai.dll`). + +## Changes + +1. **`PluginManager.LoadPluginsFromDisk`** — Skips an extra path when its file name (or canonical full path) was already loaded from the default plugins directory or from an earlier extra entry. +2. **`LoadedPlugin.ClearResolvedDelegates`** / **`PluginLoader.Unload`** — Clears resolved managed delegates before `FreeLibrary` so the native module reference count can drop cleanly on rescan. + +## User action + +If you intentionally need two different builds under the **same** DLL file name, remove the duplicate path from the launcher list or rename one DLL; the engine now loads at most one instance per file name per session. diff --git a/Changelog/2026-04-22-release-0.4.1.md b/Changelog/2026-04-22-release-0.4.1.md new file mode 100644 index 0000000..e2864ac --- /dev/null +++ b/Changelog/2026-04-22-release-0.4.1.md @@ -0,0 +1,37 @@ +# Release notes — RynthBundle **0.4.1** (2026-04-22) + +## Installer + +- **Output:** `installer\Output\RynthBundle-Setup.exe` +- **App version (Inno Setup):** `0.4.1` (passed to `Build-Release-All.ps1` / `Build-Installer.ps1` via `-Version`). +- **Full pipeline:** `RynthCore.sln` **Release** build, then publish (launcher self-contained x86, engine NativeAOT x86, injector x86, RynthSuite plugins, LootEditor + MonsterEditor self-contained x64), staging, **ISCC** compile — completed successfully on this date. + +## Previous release (archived version label) + +- **Prior documented bundle version:** **0.4.0** (examples in `BUILD.md` before this release). Use **0.4.1** for new builds and release tagging going forward. + +## Highlights in this bundle + +### Security + +- **Tmds.DBus.Protocol** pinned to **0.21.3** where Avalonia pulled vulnerable **0.20.x** (versions below **0.21.3** on that package line; **NU1903**, [GHSA-xrw6-gwf8-vvr9](https://github.com/tmds/Tmds.DBus/security/advisories/GHSA-xrw6-gwf8-vvr9)). See `Changelog/2026-04-22-tmds-dbus-protocol-security.md`. + +### Engine build stamp + +- **`EntryPoint.BuildStamp`:** `2026-04-22-v56-tmds-dbus-protocol-0213` (identifies injected engine build at runtime). + +### Related detailed changelogs + +- `Changelog/2026-04-22-rynth-bundle-installer.md` — unified installer layout and staging behavior. +- `Changelog/2026-04-22-minhook-preload-before-multiclient.md` — MinHook preload ordering for multi-client hooks. + +## RynthSuite repo + +- Tools and plugins staged from sibling **`RynthSuite`** (or `-RynthSuiteRoot`). Suite-side dependency notes: `..\RynthSuite\Changelog\2026-04-22-tmds-dbus-protocol-security.md`. + +## Build command used + +```powershell +cd +.\Build-Release-All.ps1 -Version 0.4.1 -RynthSuiteRoot "\RynthSuite" +``` diff --git a/Changelog/2026-04-22-release-0.4.3-bundle.md b/Changelog/2026-04-22-release-0.4.3-bundle.md new file mode 100644 index 0000000..48dfd31 --- /dev/null +++ b/Changelog/2026-04-22-release-0.4.3-bundle.md @@ -0,0 +1,6 @@ +# RynthBundle 0.4.3 (2026-04-22) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.3.exe` (copy also at `RynthBundle-Setup.exe` when the copy step succeeds). +- **Prior installer archived:** `installer\previous-release\RynthBundle-Setup-0.4.2.exe` (from last-built version **0.4.2** before this build). +- **Components:** RynthCore (launcher, engine, injector, `Runtime\` layout), RynthSuite plugins (e.g. RynthAi) + **LootEditor** and **MonsterEditor** under `Tools\`, and **ub-Rythai** (`RynthCore.Plugin.UbRythai`) in `Runtime\Plugins\` when the sibling `ub-Rythai` repo is present. +- **Build:** `Build-Release-All.ps1 -Version 0.4.3` at repo root (runs `dotnet build` then `installer\Build-Installer.ps1`). diff --git a/Changelog/2026-04-22-release-0.4.7-bundle.md b/Changelog/2026-04-22-release-0.4.7-bundle.md new file mode 100644 index 0000000..2c65117 --- /dev/null +++ b/Changelog/2026-04-22-release-0.4.7-bundle.md @@ -0,0 +1,14 @@ +# RynthBundle 0.4.7 (2026-04-22) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.7.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Version bump:** from **0.4.6**; prior bundle archived under `installer\previous-release\` when present; `last-built-version.txt` → **0.4.7** after a successful ISCC run with `-Version`. +- **Bundle:** RynthCore (launcher, engine, injector), RynthSuite plugins + tools, **ub-Rythai** when the sibling repo is present next to RynthCore. +- **Notable RynthAi in this line:** **0.6.8** — assembly / informational version bump for this distribution build (previous plugin line: **0.6.7**). +- **Launcher:** `LauncherHostDiagnostics.cs` — add missing `using System;` so `dotnet publish` of the Avalonia host succeeds (`AppContext`, `Environment`). +- **Build:** From the RynthCore repo root: + + ```powershell + .\Build-Release-All.ps1 -Version 0.4.7 + ``` + + With a non-default layout, pass **`-RynthSuiteRoot`** (and optionally **`-UbRythaiPluginProject`** / **`-SkipUbRythai`**) as documented in `Build-Release-All.ps1`. diff --git a/Changelog/2026-04-22-release-0.4.8.md b/Changelog/2026-04-22-release-0.4.8.md new file mode 100644 index 0000000..7fabe6a --- /dev/null +++ b/Changelog/2026-04-22-release-0.4.8.md @@ -0,0 +1,28 @@ +# Release notes — RynthBundle **0.4.8** (2026-04-22) + +## Installer + +- **Primary output:** `installer\Output\RynthBundle-Setup-0.4.8.exe` (Inno **`OutputBaseFilename`** is versioned when **`-Version 0.4.8`** is passed to **`Build-Installer.ps1`**). +- **App version (Inno Setup):** `0.4.8`. +- **Pipeline:** launcher self-contained x86 (with **`RollForward=Disable`** on publish), engine NativeAOT x86, injector self-contained x86, **RynthSuite** `Plugins\RynthCore.Plugin.*`, **ub-Rythai** when present, LootEditor + MonsterEditor x64, staging, Inno Setup. + +## Highlights in this bundle + +- **.NET 10+ prerequisite (Loot/Monster tools):** `RynthCore.iss` also accepts **`HKLM\SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost`** (and the parallel **`SOFTWARE\Microsoft\dotnet\Setup\...`** key) when **`Version`** is **10+**. See `Changelog/2026-04-22-installer-prereq-sharedhost-and-bundled-runtime-fallback.md`. +- **Launcher / injector publish:** `Build-Installer.ps1` passes **`-p:SelfContained=true -p:PublishSelfContained=true -p:RollForward=Disable`** for the bundled apphosts. +- **Launcher assembly:** `RynthCore.App.Avalonia` **0.1.2** (Informational: `0.1.2-scd-rollforward-disable`). + +## Build command used + +```powershell +cd "D:\asherons call-int code\RynthCore\installer" +.\Build-Installer.ps1 -Version 0.4.8 +``` + +## Previous bundle + +- **0.4.7** — prior **`last-built-version.txt`** before this build; see `installer\previous-release\` for archived **`RynthBundle-Setup.exe`** when the script bumps the version and the unversioned file was present. + +## Notes + +- Inno may emit: *Architecture identifier "x64" is deprecated* (harmless; substitute **`x64os`** / **`x64compatible`** is a follow-up for the **.iss** if desired). diff --git a/Changelog/2026-04-22-release-0.4.9.md b/Changelog/2026-04-22-release-0.4.9.md new file mode 100644 index 0000000..2e3e08f --- /dev/null +++ b/Changelog/2026-04-22-release-0.4.9.md @@ -0,0 +1,27 @@ +# Release notes — RynthBundle **0.4.9** (2026-04-22) + +## Installer + +- **Primary output:** `installer\Output\RynthBundle-Setup-0.4.9.exe` +- **App version (Inno Setup):** `0.4.9` +- **Pipeline:** `Build-Installer.ps1 -Version 0.4.9` — self-contained launcher/injector, NativeAOT engine + plugins, Loot/Monster x64 FDD, staging, Inno (same as **0.4.8**). + +## Highlights in this bundle + +- **x64 .NET 10+ probe parity:** Launcher uses **`RynthCore.DesktopLog.NetDesktopX64Prerequisite`** (registry checks aligned with `RynthCore.iss`); see `Changelog/2026-04-22-net-prereq-launcher-matches-inno.md`. +- **RynthCore.App.Avalonia** **0.1.3** · **RynthCore.DesktopLog** **1.0.1** + +## Build command used + +```powershell +cd "D:\asherons call-int code\RynthCore\installer" +.\Build-Installer.ps1 -Version 0.4.9 +``` + +## Previous bundle + +- **0.4.8** — `Changelog/2026-04-22-release-0.4.8.md` + +## Notes + +- Inno may show the **deprecated “x64”** architecture warning (see **0.4.8** release notes). diff --git a/Changelog/2026-04-22-rynth-bundle-installer.md b/Changelog/2026-04-22-rynth-bundle-installer.md new file mode 100644 index 0000000..224544d --- /dev/null +++ b/Changelog/2026-04-22-rynth-bundle-installer.md @@ -0,0 +1,27 @@ +# Changelog — RynthBundle unified installer (2026-04-22) + +## Summary + +- **Single installer output:** `installer\Output\RynthBundle-Setup.exe` (Inno Setup 6). +- **Build entry point:** repository root script `Build-Release-All.ps1` builds `RynthCore.sln` in Release, then runs `installer\Build-Installer.ps1`. +- **Bundled components:** + - RynthCore Avalonia launcher (self-contained x86), renamed to `RynthCore.exe` + - RynthCore Engine (NativeAOT x86) and native dependencies under `Runtime\` + - **RynthCore.Injector** (framework-dependent x86 publish) under `Runtime\` for manual CLI injection + - All RynthSuite `Plugins\RynthCore.Plugin.*` projects discovered under the sibling `RynthSuite` repo — published to `Runtime\Plugins\` and RynthAi DLL mirrored under `Suite\RynthAi\` + - **LootEditor** and **MonsterEditor** (self-contained x64) under `Tools\` with full publish trees (including `runtimes\` subfolders) + +## Installer script fixes + +- **Recursive staging:** self-contained and framework-dependent publish outputs that include subdirectories are now copied in full; previously only top-level files were copied, which broke tool publishing. +- **Injector:** included in the publish and staging steps so the bundle matches a full RynthCore deployment. + +## Documentation + +- `BUILD.md` updated to reference `RynthBundle-Setup.exe` and the root `Build-Release-All.ps1` flow. + +## Prerequisites (unchanged) + +- .NET SDK (matching project `TargetFramework`, e.g. .NET 10) and Visual Studio build prerequisites for NativeAOT where applicable +- [Inno Setup 6](https://jrsoftware.org/isdl.php) for compiling `installer\RynthCore.iss` +- `RynthSuite` as a **sibling** of `RynthCore` (same parent folder), or pass `-RynthSuiteRoot` to `Build-Installer.ps1` diff --git a/Changelog/2026-04-22-tmds-dbus-protocol-security.md b/Changelog/2026-04-22-tmds-dbus-protocol-security.md new file mode 100644 index 0000000..890c433 --- /dev/null +++ b/Changelog/2026-04-22-tmds-dbus-protocol-security.md @@ -0,0 +1,12 @@ +# Changelog — Tmds.DBus.Protocol security bump (2026-04-22) + +## Summary + +- **Packages:** Pinned **Tmds.DBus.Protocol** to **0.21.3** on projects that pull it transitively through Avalonia (Avalonia UI stack / FreeDesktop). +- **Reason:** NuGet audit **NU1903** — high severity [GHSA-xrw6-gwf8-vvr9](https://github.com/tmds/Tmds.DBus/security/advisories/GHSA-xrw6-gwf8-vvr9). Versions below **0.21.3** on this package line are affected; **0.21.3** is the maintained backport compatible with Avalonia 11.2.x. +- **Projects:** `RynthCore.App.Avalonia`, `RynthCore.Engine`. +- **Build stamp:** `EntryPoint.BuildStamp` set to `2026-04-22-v56-tmds-dbus-protocol-0213`. + +## User-visible effect + +- No functional change expected for normal Windows desktop use; dependency graph uses a patched protocol assembly and restores without the NU1903 advisory for these projects. diff --git a/Changelog/2026-04-23-installer-dotnet-prereq-advisory-only.md b/Changelog/2026-04-23-installer-dotnet-prereq-advisory-only.md new file mode 100644 index 0000000..9302462 --- /dev/null +++ b/Changelog/2026-04-23-installer-dotnet-prereq-advisory-only.md @@ -0,0 +1,13 @@ +# Changelog — Rynth bundle installer: .NET x64 prereq advisory only (2026-04-23) + +## Summary + +**`installer/RynthCore.iss`:** The post-Welcome **.NET 10+ (x64)** page for Loot/Monster tools is now **informational only**. **Next** stays enabled regardless of registry detection; copy and install always proceed. Copy and button text clarify that **`RynthCore.exe` / injector** remain self-contained. + +## Scope + +This policy applies to the **Rynth client / bundle installer** only. **UB-ILT / UBLoader** retains its own **UtilityBelt** net10 registry gate in **`FilterCore.LoadPluginAssembly`** (unchanged). + +## Related + +- **`RynthCore.DesktopLog.NetDesktopX64Prerequisite`** — unchanged; still mirrors the same registry paths for launcher log / activity alignment. diff --git a/Changelog/2026-04-23-launcher-host-diagnostics.md b/Changelog/2026-04-23-launcher-host-diagnostics.md new file mode 100644 index 0000000..57b202f --- /dev/null +++ b/Changelog/2026-04-23-launcher-host-diagnostics.md @@ -0,0 +1,18 @@ +# RynthCore launcher — host / runtime diagnostics + +Date: 2026-04-23 + +## Summary + +The Avalonia launcher (`RynthCore.App.Avalonia`, shipped as `RynthCore.exe` in the bundle) now logs **host resolution** details at startup: + +- **Activity panel:** one short line (`Host: … runtimeconfig=… deps=…`) so operators see sidecar status without opening log files. +- **Desktop log** (`RynthCore-Launcher.log`): multi-line block with `ProcessPath`, base directory, framework/OS/arch, CLR version, and presence of `RynthCore*.runtimeconfig.json` / `RynthCore*.deps.json` (including legacy `RynthCore.App.Avalonia.*` names for mismatch triage). + +## Why + +After renaming the published apphost to `RynthCore.exe`, mismatched host metadata filenames can cause false “install .NET” prompts. Sidecar logging makes that state obvious in the field. + +## Version + +- `RynthCore.App.Avalonia` NuGet-style `Version`: **0.1.0** (`InformationalVersion`: `0.1.0-launcher-host-diagnostics`). diff --git a/Changelog/2026-04-23-release-0.4.10-bundle-ub-rythai-ilt-banking.md b/Changelog/2026-04-23-release-0.4.10-bundle-ub-rythai-ilt-banking.md new file mode 100644 index 0000000..0615400 --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.10-bundle-ub-rythai-ilt-banking.md @@ -0,0 +1,19 @@ +# RynthBundle 0.4.10 + +Date: 2026-04-23 + +## Summary + +Bundle refresh to ship **ub-Rythai 3.1.9** with UB-ILT-style **ILT mode** (`Auto` / `On` / `Off`), world-name auto list, manual banking override, and **banking** helpers (`/bank` refresh, balance parsing, transfers, optional auto-transfer). + +## Engine + +- `RynthCore.Engine` build stamp: `2026-04-23-v60-bundle-0410-ub-rythai-ilt-banking`. + +## Plugins + +- **RynthCore.Plugin.UbRythai** `3.1.9` — see `ub-Rythai/Changelog/Changelog-3.1.9-ilt-mode-and-banking.md`. + +## Installer + +- Run `installer\Build-Installer.ps1 -Version 0.4.10` to produce `RynthBundle-Setup-0.4.10.exe` (and canonical `RynthBundle-Setup.exe` copy when not locked). diff --git a/Changelog/2026-04-23-release-0.4.10.md b/Changelog/2026-04-23-release-0.4.10.md new file mode 100644 index 0000000..cc0770c --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.10.md @@ -0,0 +1,20 @@ +# Release notes — RynthBundle **0.4.10** (2026-04-23) + +## Installer + +- **Output:** `installer\Output\RynthBundle-Setup-0.4.10.exe` +- **Inno app version:** `0.4.10` +- **Command:** `Build-Installer.ps1 -Version 0.4.10` + +## Highlights + +- **RynthAi** **0.6.9** (staged under `Runtime\Plugins\`) — VirindiTank dashboard import activates copied loot and merges text **MyMonsters** `.usd` for the current character; see `RynthSuite/Changelog/2026-04-23-rynthai-vt-import-active-character.md`. +- **RynthCore installer:** .NET x64 prerequisite page remains **advisory** (Next never blocked); see `Changelog/2026-04-23-installer-dotnet-prereq-advisory-only.md`. + +## Previous bundle + +- **0.4.9** — `Changelog/2026-04-22-release-0.4.9.md` + +## Notes + +- Inno may emit the **deprecated “x64”** architecture warning (non-fatal). diff --git a/Changelog/2026-04-23-release-0.4.11-runtimeconfig-rename-fix.md b/Changelog/2026-04-23-release-0.4.11-runtimeconfig-rename-fix.md new file mode 100644 index 0000000..5db22dd --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.11-runtimeconfig-rename-fix.md @@ -0,0 +1,32 @@ +# RynthBundle 0.4.11 + +Date: 2026-04-23 + +## Summary + +Fix launcher runtime detection so an installed .NET 10 runtime is correctly used instead of repeatedly showing a runtime-install prompt. + +## Root Cause + +The installer staging step renamed `RynthCore.App.Avalonia.exe` to `RynthCore.exe`, but did not rename: + +- `RynthCore.App.Avalonia.runtimeconfig.json` +- `RynthCore.App.Avalonia.deps.json` + +That mismatch can break host runtime resolution for the renamed apphost. + +## Fix + +Updated `installer/Build-Installer.ps1` so staging now renames launcher host metadata with the apphost: + +- `RynthCore.App.Avalonia.runtimeconfig.json` -> `RynthCore.runtimeconfig.json` +- `RynthCore.App.Avalonia.deps.json` -> `RynthCore.deps.json` + +## Build Stamp + +- `RynthCore.Engine` build stamp: `2026-04-23-v61-bundle-0411-runtime-detection-fix` + +## Build + +- `Build-Installer.ps1 -Version 0.4.11` +- Output: `installer/Output/RynthBundle-Setup-0.4.11.exe` diff --git a/Changelog/2026-04-23-release-0.4.2.md b/Changelog/2026-04-23-release-0.4.2.md new file mode 100644 index 0000000..8cc4c32 --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.2.md @@ -0,0 +1,41 @@ +# Release notes — RynthBundle **0.4.2** (2026-04-23) + +## Installer + +- **Primary output:** `installer\Output\RynthBundle-Setup-0.4.2.exe` (when `-Version 0.4.2` is passed, `Build-Installer.ps1` sets Inno **`OutputBaseFilename`** to a versioned name so the compile succeeds even if `RynthBundle-Setup.exe` is locked by another process). +- **Canonical copy:** the script **best-effort** copies that file to `installer\Output\RynthBundle-Setup.exe` when possible (skip if the destination is open). +- **App version (Inno Setup):** `0.4.2` (pass `-Version 0.4.2` to `Build-Release-All.ps1` / `Build-Installer.ps1`). +- **Pipeline:** `RynthCore.sln` **Release**, then publish (launcher self-contained x86, engine NativeAOT x86, injector x86, **RynthSuite** `Plugins\RynthCore.Plugin.*`, **ub-Rythai** `RynthCore.Plugin.UbRythai` when the sibling `ub-Rythai` repo is present, LootEditor + MonsterEditor x64), staging, Inno Setup. + +## Highlights in this bundle + +### ub-Rythai (Utility Belt–style RynthCore plugin) + +- **`installer\Build-Installer.ps1`** now discovers **`..\ub-Rythai\RynthCore.Plugin.UbRythai\RynthCore.Plugin.UbRythai.csproj`** (same parent folder as `RynthCore` and `RynthSuite`), publishes it with the other NativeAOT plugins, and stages **`RynthCore.Plugin.UbRythai.dll`** into **`Runtime\Plugins\`**. +- **`-SkipUbRythai`** omits that step (for environments without the checkout). **`-UbRythaiPluginProject`** overrides the project path. +- Plugin assembly version for this release line: **3.1.8** (`ub-Rythai/RynthCore.Plugin.UbRythai/RynthCore.Plugin.UbRythai.csproj`). + +### RynthCore engine + +- **Build stamp:** `2026-04-22-v57-plugin-extra-path-dedupe` — skips duplicate extra plugin paths that would re-stage the same DLL name and break hot reload; clears export delegates before `FreeLibrary` on unload. See `Changelog/2026-04-22-plugin-extra-path-dedupe-hot-reload.md`. + +## Build command used + +```powershell +cd +.\Build-Release-All.ps1 -Version 0.4.2 +``` + +With a non-default RynthSuite or ub-Rythai layout: + +```powershell +.\Build-Release-All.ps1 -Version 0.4.2 -RynthSuiteRoot "D:\src\RynthSuite" -UbRythaiPluginProject "D:\src\ub-Rythai\RynthCore.Plugin.UbRythai\RynthCore.Plugin.UbRythai.csproj" +``` + +## Previous bundle + +- **0.4.1** — `Changelog/2026-04-22-release-0.4.1.md`. When `-Version` bumps, `Build-Installer.ps1` may archive the prior `RynthBundle-Setup.exe` under `installer\previous-release\` (see `Changelog/2026-04-22-installer-previous-release-folder.md`). + +## GitHub Actions + +- **`.github/workflows/release.yml`** passes **`-SkipUbRythai`** until the workflow clones the **ub-Rythai** repo alongside RynthSuite (local `Build-Release-All.ps1` includes ub-Rythai when `..\ub-Rythai\` is present). Release artifact filename is **`RynthBundle-Setup-.exe`**. diff --git a/Changelog/2026-04-23-release-0.4.7-bundle.md b/Changelog/2026-04-23-release-0.4.7-bundle.md new file mode 100644 index 0000000..0103817 --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.7-bundle.md @@ -0,0 +1,7 @@ +# RynthBundle 0.4.7 (2026-04-23) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.7.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Version bump:** from **0.4.6**; prior bundle **0.4.6** archived under `installer\previous-release\`; `last-built-version.txt` → **0.4.7**. +- **Bundle:** RynthCore (launcher, engine, injector), RynthSuite plugins + tools, **ub-Rythai** when the sibling repo is present. +- **Notable RynthAi in this line:** **0.6.7** — missile auto-combat: correct launcher vs ammo detection (crossbow name no longer matches “bolt” ammo heuristic), skip loose ammo when resolving wielded launcher kind, wield slot fallback via `CurrentWieldedLocation`. +- **Build:** `Build-Release-All.ps1 -Version 0.4.7` from the RynthCore repo root. diff --git a/Changelog/2026-04-23-release-0.4.8-bundle-installer-streamline.md b/Changelog/2026-04-23-release-0.4.8-bundle-installer-streamline.md new file mode 100644 index 0000000..a58cebd --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.8-bundle-installer-streamline.md @@ -0,0 +1,8 @@ +# RynthBundle 0.4.8 (2026-04-23) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.8.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Version bump:** from **0.4.7**; prior bundle archived under `installer\previous-release\` when `-Version` differs; `last-built-version.txt` → **0.4.8**. +- **Installer streamlining:** + - Removed the duplicate **`Suite\RynthAi\RynthCore.Plugin.RynthAi.dll`** mirror; the plugin ships only under **`Runtime\Plugins\`**. User data and optional manual DLL copies remain under **`C:\Games\RynthSuite\RynthAi\`** (`[Dirs]` in `RynthCore.iss`). + - **Engine `cimgui`:** one shipped native next to `RynthCore.Engine.dll` — **`RynthCore.cimgui.dll`** only. MSBuild copies the prefixed name, then deletes redundant **`cimgui.dll`** / **`Native\*.cimgui*`** drops from ImGui.NET / ILC so the publish folder is not bloated. +- **Build:** `Build-Release-All.ps1 -Version 0.4.8` from the RynthCore repo root. diff --git a/Changelog/2026-04-23-release-0.4.9-runtime-fdd-bundle.md b/Changelog/2026-04-23-release-0.4.9-runtime-fdd-bundle.md new file mode 100644 index 0000000..20996b3 --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.9-runtime-fdd-bundle.md @@ -0,0 +1,9 @@ +# RynthBundle 0.4.9 (2026-04-23) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.9.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Version bump:** from **0.4.8**; prior bundle archived under `installer\previous-release\`; `last-built-version.txt` -> **0.4.9**. +- **Size reduction (major):** launcher and Suite tools are now **framework-dependent** instead of self-contained: + - `RynthCore.App.Avalonia` published `win-x86 --self-contained false` + - `RynthCore.LootEditor` and `RynthCore.MonsterEditor` published `win-x64 --self-contained false` +- **Runtime link only (no bundled download):** installer now includes a Start Menu shortcut to the official .NET runtime page and ships `RynthCore-Prerequisites.txt` in the install root with direct runtime guidance. +- **Build:** `Build-Release-All.ps1 -Version 0.4.9` from the RynthCore repo root. diff --git a/Changelog/2026-04-24-release-0.4.4-bundle.md b/Changelog/2026-04-24-release-0.4.4-bundle.md new file mode 100644 index 0000000..38aab8e --- /dev/null +++ b/Changelog/2026-04-24-release-0.4.4-bundle.md @@ -0,0 +1,6 @@ +# RynthBundle 0.4.4 (2026-04-24) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.4.exe` (and `RynthBundle-Setup.exe` when the canonical copy step succeeds). +- **Prior version archived:** the previous `installer\Output\RynthBundle-Setup.exe` (**0.4.3**) was copied to `installer\previous-release\RynthBundle-Setup-0.4.3.exe` at build time; `last-built-version.txt` now records **0.4.4**. +- **Bundle contents (same as prior full bundles):** RynthCore (launcher, engine, injector, `Runtime\` tree); all **RynthSuite** `Plugins\RynthCore.Plugin.*` (e.g. RynthAi) plus **LootEditor** and **MonsterEditor** under `Tools\`; **ub-Rythai** (`RynthCore.Plugin.UbRythai`) from the sibling `ub-Rythai` repository. +- **Notable in this line:** RynthSuite **RynthCore.Plugin.RynthAi** is built at the current **0.6.4** line (suite tool path + IL3000 handling). Build entry point: `Build-Release-All.ps1 -Version 0.4.4`. diff --git a/Changelog/2026-04-25-desktop-rolling-logs.md b/Changelog/2026-04-25-desktop-rolling-logs.md new file mode 100644 index 0000000..49d4699 --- /dev/null +++ b/Changelog/2026-04-25-desktop-rolling-logs.md @@ -0,0 +1,8 @@ +# Desktop log rotation (2026-04-25) + +- New library **`RynthCore.DesktopLog`** with **`DesktopRollingLog`**: all lines append to **`Desktop\\{fileStem}.log`**. When a file would exceed **10 MB**, the current file is moved to **`Desktop\\RynthLogs\\`**, named **`{fileStem}-roll-yyyyMMdd-HHmmssfff.log`**, then a new active file is created. For each **file stem** and each **local calendar day**, at most **10** such rolled files are kept (oldest for that day deleted first so the new segment fits the cap). +- **Three log stems in use** + - **`RynthCore`** (was `RynthCore.log` only) — in-process engine output, same path as before. + - **`RynthCore-Launcher`** — one line on Avalonia app startup; writes **`RynthCore-Launcher.log`**, same rotation. + - **`RynthCore-Injector`** — injector console lines to **`RynthCore-Injector.log`**, same rotation; success message references all three and the `RynthLogs` archive folder. +- **Build stamp** updated to `2026-04-25-v58-desktop-log-rotate`. diff --git a/Changelog/2026-04-25-release-0.4.5-bundle.md b/Changelog/2026-04-25-release-0.4.5-bundle.md new file mode 100644 index 0000000..313fda3 --- /dev/null +++ b/Changelog/2026-04-25-release-0.4.5-bundle.md @@ -0,0 +1,7 @@ +# RynthBundle 0.4.5 (2026-04-25) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.5.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Prior bundle:** `installer\previous-release\` archives the previous `RynthBundle-Setup.exe` when the version bumps; `last-built-version.txt` records **0.4.5**. +- **Contents:** Same bundle layout as prior releases — RynthCore (launcher, engine, injector), RynthSuite plugins + tools, **ub-Rythai** when the sibling repo is present. +- **Notable engine / host changes in this line:** desktop **log rotation** (10 MB active, up to 10 rolled files per day per log under `Desktop\RynthLogs`), three stems (`RynthCore.log`, `RynthCore-Launcher.log`, `RynthCore-Injector.log`), build stamp **v58**. +- **Build:** `Build-Release-All.ps1 -Version 0.4.5` from the RynthCore repo root. diff --git a/Changelog/2026-04-26-release-0.4.6-bundle.md b/Changelog/2026-04-26-release-0.4.6-bundle.md new file mode 100644 index 0000000..2c03da3 --- /dev/null +++ b/Changelog/2026-04-26-release-0.4.6-bundle.md @@ -0,0 +1,7 @@ +# RynthBundle 0.4.6 (2026-04-26) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.6.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Version bump:** from **0.4.5**; prior bundle archived under `installer\previous-release\`; `last-built-version.txt` → **0.4.6**. +- **Bundle:** RynthCore (launcher, engine, injector), RynthSuite plugins + tools, **ub-Rythai** when the sibling repo is present. +- **Notable RynthAi in this line:** **0.6.6** — ImGui Monsters table `WidthFixed | NoResize` fix (assert when opening RynthAi UI). +- **Build:** `Build-Release-All.ps1 -Version 0.4.6` from the RynthCore repo root. diff --git a/Changelog/2026-10-04-aelrynth-sync.md b/Changelog/2026-10-04-aelrynth-sync.md new file mode 100644 index 0000000..eea0256 --- /dev/null +++ b/Changelog/2026-10-04-aelrynth-sync.md @@ -0,0 +1,12 @@ +# Changelog — 2026-10-04 (upstream snapshot) + +## feat: port aelrynth git snapshot onto GitHub history + +Applied `upstream/main` (`9b5e276`, RynthCore as of 2026-09-27, release 2026.9.27.2) as a new commit on top of BlankenshipG `main`. Histories are unrelated, so this is a tree overlay — not a fast-forward or force-replace. + +- Added aelrynth-only product code: Loader, StatusAgent, HookManifest/HookResolver, DComp overlay, SEH trampoline, signed updater, vendor/trade API (PluginContract +16 functions) +- Overlapping engine/launcher files taken from aelrynth (newer than origin 2026-04-25) +- Kept unique origin-only trees: `Plugins/RynthAi/` (Decal-era), `Plugins/RynthCore.Plugin.RynthAi/` stub, `AGENTS.md`/`CLAUDE.md`, `ImGuiController.cs`, `OverlayFrameBuffer.cs` +- Re-applied dead-link fixes: installer + CI clone URLs point at aelrynth.com / `${{ github.repository_owner }}` siblings + +No PluginSdk version bump (still 0.2.0 on both trees). Packaged aelrynth installer (2026.10.4.3) is newer than this git tip. diff --git a/Changelog/2026-10-04-aelrynth-urls.md b/Changelog/2026-10-04-aelrynth-urls.md new file mode 100644 index 0000000..8670c97 --- /dev/null +++ b/Changelog/2026-10-04-aelrynth-urls.md @@ -0,0 +1,9 @@ +# Changelog — 2026-10-04 (docs/CI) + +## fix: point dead tombohar URLs at aelrynth / sibling fork + +- `installer/RynthCore.iss` `AppPublisherURL` → https://aelrynth.com/rynth.html +- `.github/workflows/release.yml` sibling clone → `github.com/${{ github.repository_owner }}/RynthSuite` +- Canonical public git remains https://aelrynth.com/git/RynthCore.git (see product page) + +No engine/SDK version bump (docs and CI URL-only). diff --git a/Changelog/2026-10-04-char-and-hub-launcher-buttons.md b/Changelog/2026-10-04-char-and-hub-launcher-buttons.md new file mode 100644 index 0000000..dbda06e --- /dev/null +++ b/Changelog/2026-10-04-char-and-hub-launcher-buttons.md @@ -0,0 +1,26 @@ +# Launcher buttons: "ILT Hub" renamed to "Char", new "Hub" button (2026-10-04) + +RynthAi 0.6.25, plus an engine change to the Avalonia RynthAi panel. + +## What changed + +The floating HUDs were hard to find: they start hidden and were only reachable through +Settings > Inventory Management or chat commands. Both dashboards now have a launcher for them. + +| Dashboard | Char | Hub | +|-----------|------|-----| +| Avalonia RynthAi panel | Opens the ILT Hub (`/ra hub show`) | Left-click shows/hides the Mini Remote (`/ra remote`). Right-click opens the Inventory HUDs setup window (`/ra huds`). | +| ImGui dashboard launcher grid | Toggles the ILT Hub window. Only shown on ILT/ACECustom worlds, as before. | Toggles the Mini Remote. Lit while it is shown. Shown on every world. | + +- Only the button labels changed. The ILT Hub window title, `/ra hub` and the `[ILT Hub]` chat + messages are unchanged. +- In the ImGui grid, Hub uses the third cell of the last row, which was empty. + +## Files + +- Engine `UI/Panels/RynthAiPanel.cs`: "ILT Hub" launcher renamed to "Char"; new "Hub" launcher + (row 3, column 2) with a right-click handler. +- `LegacyUi/LegacyDashboardRenderer.cs`: "Char" label, "Hub" grid button, and the + `MiniRemoteVisible` / `SetMiniRemoteVisible` hooks. +- `RynthAiPlugin.cs`: wires the hooks to the HUD state at login and clears them at logout. +- Version 0.6.24 → 0.6.25. diff --git a/Changelog/2026-10-04-create-seeds-and-fatal-only-crash-logger.md b/Changelog/2026-10-04-create-seeds-and-fatal-only-crash-logger.md new file mode 100644 index 0000000..1f5444a --- /dev/null +++ b/Changelog/2026-10-04-create-seeds-and-fatal-only-crash-logger.md @@ -0,0 +1,70 @@ +# Engine: object identity seeded at create, native crash logger made fatal-only + +**Date:** 2026-10-04 +**Branch:** `SK-local` +**Ships in:** next installer (2026.10.4.10; previous 2026.10.4.9) + +## 1. Names and types readable from the moment an object is created + +### Problem +Off-thread plugin reads (`TryGetObjectName` / `TryGetItemType`) are served only from the +main-thread identity snapshot, rebuilt every 500 ms. For about 10 s after login that snapshot +resolves almost no names (`[SnapshotDiag] ... names=1`) because qualities aren't populated yet. +The plugin's quick classify retries finish in about 10 ms, so every login-burst object without a +position (pack contents) gave up: about 200 `CLASSIFY-GIVEUP` lines per login, and items stayed +unclassified until a slow retry caught them. + +### Fix +- `CreateObjectHooks` now passes the server's `PublicWeenieDesc` to the new + `ClientObjectHooks.SeedIdentityFromCreate`. It runs on AC's main thread before the plugin is + told about the object. + - It reads `_name` (PWD +4) and `_type` (PWD +56). These are the same offsets the existing + PWD-direct fallbacks use on the embedded copy. + - Every read is validated: the descriptor must start with an acclient.exe vtable, and the + string read is page-checked and length-capped. +- Off-thread lookups use these create seeds when the snapshot has no entry. For types, the seed + is also used when the snapshot says `0` (qualities not loaded yet). The snapshot still wins + whenever it has a real value. +- Seeds are removed in `DeleteObjectHooks`. A 16,384-entry cap clears them if a delete is ever + missed. +- Diagnostics: `[CreateSeed] #1..5` sample lines, plus one + `create-descriptor identity seeds active` summary, so the first in-game log confirms the + offsets. +- Position is unchanged: the position snapshot is taken every 100 ms and already worked at login. + +## 2. Native crash logger: fatal crashes only (`RynthCore.SehTrampoline.dll` v2) + +### Problem +`CrashVeh` logged **every** first-chance access violation, including ones AC or our own `SEH_*` +wrappers catch. Its stack sweep then read 4,096 slots past ESP regardless of where the stack +ended, faulted off the top of the stack, and logged that fault too +(`SehTrampoline.dll+0x13E8`, dataAddr on a page boundary). Every run began with 3–4 noise +entries, and with the 24-entry cap a real fatal crash could find the log already full. + +### Fix (`native/SehTrampoline/SehTrampoline.c`) +- **Stack sweep bounded** to `[Esp, NtCurrentTeb()->NtTib.StackBase)`, and skipped when ESP + isn't inside the thread's stack. +- **Per-thread guards:** + - `t_inLogger`: faults raised while the logger runs are never logged. + - `t_sehDepth`: every `SEH_*` wrapper brackets its call, so AVs those wrappers catch are + ignored. +- **Fatal-only routing:** + - **Unhandled-exception filter** (`SetUnhandledExceptionFilter`, chained to the previous + filter, with a re-entry guard): an unhandled exception is written immediately as FATAL. + - **AVs inside NativeAOT code** (engine/plugins, detected via the `DotNetRuntimeDebugHeader` + export) are written immediately. The runtime fail-fasts on these through + `RaiseFailFastException`, which bypasses every filter. 0xC0000602 / 0xC0000409 are also + written immediately. + - **Every other first-chance AV** (acclient.exe, drivers, DINPUT8…) is formatted into an + 8-slot in-memory ring. It is written only if the process then dies: through the filter, or + at `ExitProcess` (DllMain detach) if it happened within the last 30 s. That keeps + crashes AC's own handler swallows. AVs AC handles and survives never reach the file. +- Separate caps: 16 immediate records and 8 fatal records per run. Formatting is now + bounds-checked (8 KB per record). +- New export `RC_SehTrampolineVersion()` returns 2. The engine logs + `native crash logger installed (v2, fatal-only)` at startup. + +## Build +- `Build-SehTrampoline.ps1`: compiles clean (MSVC 14.50, x86, /W3). +- `RynthCore.Engine` Release build succeeds (no new warnings). +- Not yet verified in game. diff --git a/Changelog/2026-10-04-dashboard-map-and-lua-buttons.md b/Changelog/2026-10-04-dashboard-map-and-lua-buttons.md new file mode 100644 index 0000000..48f25dc --- /dev/null +++ b/Changelog/2026-10-04-dashboard-map-and-lua-buttons.md @@ -0,0 +1,34 @@ +# Avalonia RynthAi panel: Map and Lua buttons (2026-10-04) + +Engine `RynthAiPanel` plus RynthAi 0.6.21. Ships in the next installer after 2026.10.4.16. + +## Problem + +The right halves of the split launcher buttons, **Lua** (next to Meta) and **Map** (next to +Nav), had no click handler, so they did nothing. Both windows are ImGui windows inside +RynthAi, and in Avalonia mode RynthAi's overlay render path never drew either of them. + +There is no separate RynthLua plugin: the Lua Scripts editor is RynthAi's `LegacyLuaUi`, +controlled by `DashWindows.ShowLua`. So the Lua button follows the same pattern as Map and +the ILT Hub button. + +## Engine (`UI/Panels/RynthAiPanel.cs`) + +- **Map** sends the remote command `map toggle`, and **Lua** sends `lua toggle`. Both go through + `RynthPluginApplyRemoteCommand`, the same path as the ILT Hub button. Both buttons have tooltips. +- `AddSplitLauncher` now returns its two half buttons. + +## RynthAi 0.6.21 + +- New remote commands and chat commands `/ra map [show|hide]` and `/ra lua [show|hide]`. With no + argument they toggle. They go through `HandleWindowCommand` to `LegacyDashboardRenderer.SetDungeonMapVisible` / + `SetLuaWindowVisible`, which persist the choice and print a chat confirmation. Turning the map on + while outdoors says it will appear indoors. Both commands are listed in the `/ra` help. +- `OnRenderOverlay` (Avalonia mode) now calls `RenderMapWindow(includeRadarAndChat: false)`. + It draws only the dungeon map, because the Avalonia Radar panel and RynthChat already exist. + ImGui-shell mode still draws all three. +- `RenderOverlayWindows` now also draws the Lua Scripts editor. Opening it rescans the + `LuaScripts` folder. +- Fix: the dungeon map would not reopen after being closed with its title-bar X (its own `_open` + flag stayed false and closed it again on the same frame) until you went outdoors and back. + `DungeonMapUi.Render` now reopens whenever `ShowDungeonMap` is set. diff --git a/Changelog/2026-10-04-floating-huds.md b/Changelog/2026-10-04-floating-huds.md new file mode 100644 index 0000000..f29351f --- /dev/null +++ b/Changelog/2026-10-04-floating-huds.md @@ -0,0 +1,93 @@ +# Floating HUDs: item count HUD, Mini Remote, quest favorites (2026-10-04) + +RynthAi 0.6.23, plus an engine Settings button. Ships in the next installer after 2026.10.4.17. + +## What changed + +Four new floating windows, modelled on UtilityBelt's Item Hud, Mini Remote and quest +favorites. They are ordinary ImGui windows. You can dock them, undock them, or drag them +outside the AC window, because the engine has docking and multi-viewport enabled. Each HUD +remembers its own position. + +| Window | Controlled from | Command | +|--------|-----------------|---------| +| Inventory HUDs (setup) | Advanced Settings > Inventory Management > **Inventory HUDs...**, and the same button in the Avalonia Settings panel | `/ra huds [show\|hide]` | +| Item count HUD | Inventory HUDs setup window | `/ra itemhud [show\|hide]` | +| Mini Remote | Inventory HUDs setup window | `/ra remote [show\|hide]` | +| Quest favorites HUD | ILT Hub > Character > Quest tracker | `/ra quests favhud [show\|hide]` | +| Quests (pop-out tracker) | ILT Hub quest tracker **Pop out** button | `/ra quests window [show\|hide]` | + +Running a command without `show` or `hide` toggles the window. + +### Item count HUD + +- Shows one row per pinned item: the item's icon (read from portal.dat) and how many you + carry, with stacks added up across all packs. The count turns red at 0. Names are optional. +- Right-click the HUD to show names, lock its position, change the icon size (12–48 px), + open the setup window, or hide it. + +### Mini Remote + +- **Stats** (ILT-like worlds): session time, plus XP, Luminance, kills, coins and pyreals per hour. + **Reset XP** restarts the session rates. **Report** prints a summary to local chat. +- **Pet**: the essence that is out ("Out" / "Healing"), or the next combat essence + ("Ready" / "Empty"). +- **Item gems**: a 5×6 grid of item slots. Click a slot to use that item; the slot dims when + you carry none. Right-click a slot to assign the selected item or clear it. +- **Toggles**: Macro, Combat, Buff, Nav, Loot, Meta, Pet (summon pets). +- **Bank** (ILT-like worlds): P, Lum, LK, MK, EC, WE from the ILT Hub bank tracker. +- **Rebuff**: FB (force rebuff) and CFB (cancel force rebuff). +- Right-click the window background to hide sections, lock its position, open the setup + window, or hide it. + +### Inventory HUDs setup window + +- Show/hide the item HUD (with or without names) and the Mini Remote. +- **Scan pack**, **Add from inventory** (pins the selected item), **Drop missing** (unpins + items you no longer carry). +- An **On HUD** list (Up/Down to reorder) and a filterable **Not on HUD** list of everything in + your pack, with `<` / `>` to move items between them. Double-click an item in Not on HUD to + pin it. +- Mini Remote slot picker with **Set** (from the selected item), **Clear** and **Refresh**. + +Item HUD and Mini Remote settings are saved per character in `huds.json`. + +### Quest favorites + +- The ILT Hub quest tracker has a new star column. Click `*` to favourite a quest. + **Favorites only** filters the table to starred quests. +- **Show floating favorites HUD** opens a small HUD listing starred quests, with ready / + time-left. Right-click it to lock it, open the quest tracker, refresh `/myquests`, or hide it. +- **Pop out** moves the quest tracker into its own "Quests" window. Closing that window docks + it back into the Hub. +- Favorites and HUD flags are saved per character in `ilt-hub.json` (`Character.QuestFavorites`). + +## Not carried over from UtilityBelt + +These UtilityBelt Mini Remote and Quests features were left out: + +- Storm, Chat XL, Guardian/Translate, the profile combos and the Fellow toggle. RynthAi has no + equivalent systems for these yet. +- The L / LumS / KillL / PassL / C / Conv stat cells. +- The quest rewards editor. + +## Files + +- New `Huds/` folder: + - `HudController.cs`: pack scan, pump-thread actions, commands. + - `HudState.cs`: settings and `huds.json` store. + - `HudIconCache.cs`: decodes portal.dat icons and uploads D3D9 textures. + - `DxtUtil.cs`: DXT decoder. + - `HudDraw.cs`, `ItemCountHud.cs`, `MiniRemoteHud.cs`, `HudSetupUi.cs`. +- `IltHub/IltQuests.cs`: favorites, favorites HUD, pop-out window. +- `IltHub/IltHubState.cs`, `IltHubStore.cs`: quest favorite fields. +- `IltHub/IltHubUi.cs`, `IltHubController.cs`: floating window rendering and the `quests` verbs. +- `IltHub/IltSessionRates.cs`: `RateSummary` for the Mini Remote. +- `IltHub/IltPets.cs`: Mini Remote pet line. +- `LegacyUi/LegacyAdvancedSettingsUi.cs`, `LegacyDashboardRenderer.cs`: Inventory HUDs button. +- `RynthAiPlugin.cs`, `RynthAiCommands.cs`: wiring and `/ra` help. +- `Diagnostics/RynthLog.cs`: new `Huds` log category. +- Engine: + - `UI/Panels/SettingsPanel.cs`: Inventory HUDs button in Inventory Management. + - `UI/Panels/RynthAiPanel.cs`: `SendRynthAiCommand` helper. +- RynthAi version 0.6.22 → 0.6.23. diff --git a/Changelog/2026-10-04-full-installer-2026.10.4.2.md b/Changelog/2026-10-04-full-installer-2026.10.4.2.md new file mode 100644 index 0000000..7c63ef3 --- /dev/null +++ b/Changelog/2026-10-04-full-installer-2026.10.4.2.md @@ -0,0 +1,68 @@ +# RynthCore 2026.10.4.2: full RynthCore + RynthSuite installer + +**Release date:** 2026-10-04 +**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.2.exe` (also copied to `RynthCore-Setup.exe`) +**Previous release:** `2026.10.4.1` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.1.exe`) +**Branch:** `feat/full-installer` (local test build, not on `main`), based on `fix/tmds-dbus-advisory` +**Bundled RynthSuite:** RynthAi `0.5.3`, Loot Editor, Monster Editor (from RynthSuite `feat/ilt-hub`) + +## Why: the launcher would not start + +On 2026-10-04 an old **RynthBundle 0.4.7** installer was run over the 2026.10.3.4 install. It replaced +`RynthCore.App.Avalonia.dll` with the 0.4.x build, which needs `RynthCore.DesktopLog.dll`, but left the newer +`RynthCore.App.Avalonia.deps.json`, which does not list it. The renamed apphost (`RynthCore.exe`) loads exactly +what the deps.json lists, so .NET failed at startup with `FileNotFoundException: RynthCore.DesktopLog` +(Event Log, .NET Runtime 1026). The new installer fixes such an install in place (see **Cleanup** below). + +## One installer, two folders you choose + +- **Wizard pages:** + - **Select Destination Location** picks the RynthCore folder (default `C:\Games\RynthCore`). + - **Select Components** offers Full, RynthCore only, or Custom. RynthCore is always installed; RynthAi and the + Monster Editor are optional. + - **Select RynthSuite Location** picks the RynthSuite folder. It defaults to a `RynthSuite` folder next to + the RynthCore folder you picked, or the folder used last time. The page is skipped when no Suite component is selected. +- **Silent installs:** `RynthCore-Setup-2026.10.4.2.exe /SILENT /DIR="D:\Games\RynthCore" /SUITEDIR="D:\Games\RynthSuite"`. + Without `/SUITEDIR` the Suite goes next to `/DIR`, or to the previously used folder. +- **Registry:** both folders are written to `Software\Rynth` (`CoreDir`, `SuiteDir`). That is HKCU for per-user installs + and HKLM for all-users installs. All of RynthCore and RynthSuite now read them. +- **Plugin auto-registration:** the installer leaves `PendingPluginRegistration` with the RynthAi DLL path. On the next + start the launcher adds it to the Plugins list (replacing any stale entry with the same file name whose file is gone), + syncs `engine.json` and clears the value. A fresh install therefore loads RynthAi with no manual setup. +- **Shortcuts:** RynthCore, Loot Editor, Monster Editor, RynthSuite folder, Uninstall, and an optional desktop icon. + +### Cleanup of older layouts +Before copying, the installer deletes leftovers from 0.4.x and RynthBundle installs in the RynthCore folder: +root `*.dll`/`*.json`/`*.pdb`, `RynthCore.App.Avalonia.exe`, old `Runtime\*.dll`/`*.json`, `Runtime\RynthCore.Injector.exe` +and `Runtime\Plugins\`. Then it lays down a complete, matching set. User data (`Logs`, settings in `%APPDATA%\RynthCore`, +everything under `\RynthAi`) is never touched, and the RynthSuite data folders survive an uninstall. + +## Code: no more hard-coded `C:\Games\...` + +New `src/RynthCore.App/RynthInstallPaths.cs`, linked into the launcher, engine, loader, injector and status agent. +It resolves the folders in this order: `RYNTHCORE_DIR`/`RYNTHSUITE_DIR` environment variables, then HKCU, then HKLM +(32-bit view), then the old `C:\Games\...` defaults. It uses a direct `RegGetValueW` P/Invoke, so it is NativeAOT-safe. +The engine resolves it on its init worker, never under the loader lock. + +| Was | Now | +|---|---| +| `C:\Games\RynthCore\Logs` (launcher, loader, injector, engine) | `\Logs` | +| `C:\Games\RynthCore\AcClient\acclient.exe` (injector) | `\AcClient\acclient.exe` | +| `C:\Games\RynthSuite\RynthAi\imgui.ini`, MetaFiles | `\RynthAi\...` | +| Status agent defaults | derived from the resolved folders | + +## Build script (`installer\Build-Installer.ps1`) +- **Publishes:** launcher, Engine, Loader, the RynthAi plugin, the Loot Editor, and now the **Monster Editor** + (self-contained win-x86). +- **Staging:** RynthCore goes to `staging\core`, RynthSuite to `staging\suite\RynthAi` (plugin plus `MonsterEditor\`). +- **Versions:** the RynthAi plugin is no longer stamped with the installer version. It keeps its own semantic version + (0.5.3), and everything else gets `-p:Version=`. +- **New check:** every project assembly listed in the launcher's `deps.json` must be staged next to it. This guards + directly against the DesktopLog failure above. +- **Previous release:** `installer\previous-release\last-built-version.txt` tracks the last build. When the version + changes, that build's installer is archived to `previous-release\` (git-ignored) before the new one is built. +- **Output:** `RynthCore-Setup-.exe`, plus a `RynthCore-Setup.exe` copy. + +## Not included +RynthChat, RynthJuice, RynthNav, RynthTracker and RynthVision are experimental and stay out of the installer. +RynthNav and RynthJuice still hard-code `C:\Games\RynthCore`. diff --git a/Changelog/2026-10-04-ilt-hub-button-imgui-on-top-live-logging.md b/Changelog/2026-10-04-ilt-hub-button-imgui-on-top-live-logging.md new file mode 100644 index 0000000..6229a91 --- /dev/null +++ b/Changelog/2026-10-04-ilt-hub-button-imgui-on-top-live-logging.md @@ -0,0 +1,60 @@ +# 2026-10-04 — ILT Hub panel button, ImGui windows on top, live logging levels + +Launcher 0.1.5. Needs RynthAi 0.6.18 for the RynthAi logging rows. + +## ILT Hub button (Avalonia RynthAi panel) + +* New **ILT Hub** launcher button (third row of the RynthAi panel launcher grid). + Sends `hub show` through the plugin's `RynthPluginApplyRemoteCommand` export — + the same path as typing `/ra hub show`. +* New `SendRemoteCmd(action, value)` helper marshals both strings, calls the + export and frees them (the plugin copies them and applies on its pump thread). + +## Plugin ImGui windows draw on top of the Avalonia layer + +* `EngineFrameController.RunImGuiFrame` still builds the ImGui frame at the same + point, but no longer submits the draw data. `EndSceneHook` now calls the new + `EngineFrameController.RenderDeferredImGui()` **after** + `OverlayTextureRenderer.Render`, so the plugin overlay windows (ILT Hub, Item + Info, ...) are drawn over the Avalonia panels. +* Input follows the new stacking: when ImGui is hovered or has an active widget, + mouse messages go to ImGui instead of the Avalonia panel underneath + (`Win32Backend.ImGuiOwnsMouseOverAvalonia`). An Avalonia drag/resize already + in progress keeps its capture so the release is never lost. +* Nothing is submitted twice: the pending draw is cleared at the start of each + ImGui frame and after submission. + +## Live, per-category logging (engine + launcher) + +### Engine + +* New `LogSettings` reads engine.json: + * `"LoggingLevel"`: global threshold, now including **Off** + (Off, Error, Warning, Info, Debug, Trace; `Verbose`/`Warn` accepted). + * `"LogCategories"`: per-category emit level (Off, Trace, Debug, Info) for + General, D3D9, Compat, Render, Plugin, UI, Verbose. A category's lines are + written at its level, so a Trace/Debug category set to **Info** shows in the + normal log, and **Off** silences it. +* A background thread polls engine.json once a second and reloads on change + (logs `LogSettings: engine.json changed - logging reloaded (...)`). Stopped in + `EngineLifecycle.Shutdown` before unload. +* `RynthLog` category methods route through the category levels (the hard-coded + `*Enabled` booleans are gone; defaults are unchanged: Render Off, Verbose Debug, + everything else Info). +* Lines are tagged with their real level: `[DBG]` and `[TRC]` instead of `[INF]`. +* `Warn` is now hidden at level Error/Off; `Error` is always written. + `LastIssue` is still recorded for filtered warnings. +* `EngineSettings.Save()` now copies through engine.json fields it doesn't own + (e.g. `LogCategories`, `EnableDcompOverlay`) instead of dropping them. + +### Launcher (Runtime tab) + +* **Logging level** box gains **Off**, and applies immediately (writes + engine.json on change; no Save needed). Unknown saved values fall back to Info. +* New **Logging** card, every change saved immediately and applied live: + * Engine categories: Off / Trace / Debug / Info per category. + * RynthAi categories: Off / Trace / Info per category (diagnostics.json). + * RynthAi key events: Off / Trace / Info per event (diagnostics.json). + * Reload button re-reads both files. +* New `LoggingSettingsStore` does the read-modify-write of both files + (atomic temp-file swap for diagnostics.json, every other field preserved). diff --git a/Changelog/2026-10-04-ilt-hub-pet-roster.md b/Changelog/2026-10-04-ilt-hub-pet-roster.md new file mode 100644 index 0000000..d1a7aeb --- /dev/null +++ b/Changelog/2026-10-04-ilt-hub-pet-roster.md @@ -0,0 +1,65 @@ +# ILT Hub Pet tab: UtilityBelt-style pet roster (2026-10-04) + +RynthAi 0.6.22. Ships in the next installer after 2026.10.4.17. + +## What changed + +The ILT Hub **Pet** tab's flat "Carried essences" table (name / uses / order) is replaced +by a roster modelled on UtilityBelt's Pets tab. + +### Three stat lines per pet + +| Line | Contents | +|------|----------| +| 1 | Name, Bond, Lvl, Craft (coloured by damage type) | +| 2 | Sex (M/F, `n` neutered, `j` juvenile), growth, mutations, stored potency (active level and +damage %), mastery, damage type | +| 3 | Ratings `[D, DR, C, CD, CR, CDR]`, uses (red when empty), breeding status, "ID pending" until appraised | + +Stats come from the ACECustom pet properties UtilityBelt reads (bond 9053, potency 9056, +mutations 9070–9075, maturity 9077, mastery 362, gear ratings 370–375 falling back to the +base rating ids). Active potency follows ACE: `min(stored, ceil(bond / 10))`, minimum 1, +capped at 150, +2% damage per level. Sex uses the server's GUID hash unless an override +bool is set. + +Un-appraised essences are appraised automatically, two per 2-second scan. **Scan pack** +re-appraises every pet essence to refresh bond and potency after fights. + +### Type and sort + +- **Type**: Combat, Healing or Cosmetic. Combat essences and Healing Buddy / Dule box pets + are classified automatically. Any essence can be re-typed: select it in your pack and press + **Add sel.**, or right-click a row ("Move to …", "Clear type override"). Overrides are + saved per character in `ilt-hub.json` (`Pet.Assignments`). +- **Sort**: Priority, Bond, Potency, Breed ready, Level, Uses, Name. + +### Selecting and summoning by type + +- **Combat**: the tick list is still the `ConsumableRules` Pet list that PetManager summons + from, so there is no second summoner. With Sort = Priority, the arrows set the summon order. +- **Healing**: the tick picks the heal pet used by the healing helper. The old free-text + "Heal-pet essence" field is replaced by this tick. No tick means the first Healing Buddy / + Dule box, as before. The healing settings moved into a collapsible "Healing pet settings" header. +- **Cosmetic** (new): tick one display pet. **Keep cosmetic pet out** summons it in peace + mode when no other pet is out and the combat summoner isn't hunting, re-summoning after a + configurable delay (default 15 s). +- **Summon** uses the highlighted row, or the type's ticked pet. **Despawn** dismisses + whatever pet is out by using the essence that summoned it again (matched by name, else the + last essence summoned from the Hub). An **Active summon** line shows the pet that is out. + +## Combat pet hand-off + +`PetManager` has a new optional hook, `YieldPetForCombat`. When a pet already holds the slot +and monsters are near, PetManager asks the ILT Hub. If the pet is the cosmetic pet, the Hub +dismisses it, and PetManager waits 3 seconds and then summons a combat pet as usual. Other +pets (combat or heal) are never dismissed by this hook. + +## Files + +- New `IltHub/IltPetStats.cs`: stat model, property reader, 3-line formatter and sorter. +- `IltHub/IltPets.cs`: roster snapshot, classification, Summon/Despawn/Scan pack/Add sel., + cosmetic keep-out, new UI. +- `IltHub/IltHubState.cs`: `RosterKind`, `RosterSort`, `Assignments`, `CosmeticPetName`, + `KeepCosmeticOut`, `CosmeticRespawnSeconds`, plus the new `IltPetAssignment` class. The values + are normalized on load (`IltHubStore`). +- `Combat/PetManager.cs`: `YieldPetForCombat` hook. `IltHubController` wires it at login. +- Version 0.6.21 → 0.6.22. diff --git a/Changelog/2026-10-04-installer-2026.10.4.1.md b/Changelog/2026-10-04-installer-2026.10.4.1.md new file mode 100644 index 0000000..5f2c2e7 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.1.md @@ -0,0 +1,42 @@ +# RynthCore installer — release 2026.10.4.1 + +**Build date:** 2026-10-04 +**Previous release:** 2026.10.3.4 (the version currently installed in `C:\Games\RynthCore`) +**Output:** `installer\Output\RynthCore-Setup.exe`, with a versioned copy at +`installer\Output\RynthCore-Setup-2026.10.4.1.exe` (72.9 MB) + +## What's inside + +Built with `installer\Build-Installer.ps1 -Version 2026.10.4.1` from: + +- **RynthCore** `main` @ `eda3cdf` (GitHub BlankenshipG/RynthCore). This includes the + aelrynth 2026.9.27.2 snapshot port and the URL fix. +- **RynthSuite** `feat/ilt-hub` @ `ad61194` (GitHub BlankenshipG/RynthSuite). This adds the + RynthAi 0.5.1 plugin with the ILT Hub. It's a local test build and is not on `main`. + +| Component | Notes | +|---|---| +| Launcher (`RynthCore.exe`) | Self-contained Avalonia, x86 | +| `Runtime\RynthCore.Engine.dll` | NativeAOT x86, 33 MB | +| `Runtime\RynthCore.Loader.dll` | NativeAOT x86 (hot-reload loader) | +| `Runtime\RynthCore.SehTrampoline.dll` | Rebuilt from `native\SehTrampoline\SehTrampoline.c` (MSVC 14.50, x86) | +| `C:\Games\RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` | 0.5.1-legacy-ui (ILT Hub) | +| `Tools\LootEditor` | Self-contained, x86 | + +`release.txt` reads `2026100401 / 2026.10.4.1`, so the launcher updater treats this build +as newer than 2026.10.3.4. + +## Security + +- Code review (diff since `8260c60`, which covers the signed updater, StatusAgent, the + release CI and the deploy scripts): no medium, high or critical findings. +- Dependency advisory: NuGet reports `Tmds.DBus.Protocol` 0.20.0 + ([GHSA-xrw6-gwf8-vvr9](https://github.com/advisories/GHSA-xrw6-gwf8-vvr9), high). + Avalonia pulls it in for the launcher, the engine and the Loot Editor. It's the Linux + D-Bus transport and isn't used on Windows. It should still be upgraded through an + Avalonia bump or a direct package pin. + +## Not done + +- The installer is unsigned (no Authenticode) and wasn't published to the update feed. +- Nothing was installed over `C:\Games\RynthCore`. Run the setup manually to test it. diff --git a/Changelog/2026-10-04-installer-2026.10.4.10-release.md b/Changelog/2026-10-04-installer-2026.10.4.10-release.md new file mode 100644 index 0000000..efb8175 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.10-release.md @@ -0,0 +1,36 @@ +# Installer 2026.10.4.10 + +**Date:** 2026-10-04 +**Branch:** `SK-local` (RynthCore `a7cdbee`, RynthSuite `898bf8b`) +**Previous release:** 2026.10.4.9 + +## Contents +- **Engine 2026.10.4.10:** the CreateObject hook records each object's name and ItemType from the + server's create descriptor. Off-thread lookups therefore work at login, before the 500 ms + identity snapshot can resolve names (`2026-10-04-create-seeds-and-fatal-only-crash-logger.md`). +- **RynthCore.SehTrampoline.dll v2:** `native-crash.log` now records fatal crashes only: + - Unhandled exceptions are caught by a chained unhandled-exception filter. + - Faults in engine/plugin code are logged immediately, because the runtime kills the process + without running any filter. + - Other first-chance AVs are written only if the process dies soon after. + - The stack sweep stops at StackBase. + - Per-thread guards stop the logger from logging its own faults and AVs that its `SEH_*` + wrappers catch. +- **RynthAi 0.6.16:** keys, gems, spell components, food, misc items and portals are classified + by ItemType and ownership instead of being left as "Unknown" and rechecked every 2 s + (`RynthSuite/Changelog/RynthAi-0.6.16-typed-item-classification.md`). The CLASSIFY-GIVEUP + flood at login is gone. + +## Artifacts (`installer/Output/`) +- `RynthCore-Setup-2026.10.4.10.exe` + (SHA-256 `57462ea3fc03a71e92666cc54a961aa89f7b03a182540d05878ca6ce8f63e984`) +- `Release-2026.10.4.10/` and `RynthCore-2026.10.4.10-deploy.zip` (103 MB, hash-verified) + +## Build +- `Build-Release-All.ps1 -Version 2026.10.4.10`: everything built and the Inno Setup compile + succeeded. The first run stopped at the SEH trampoline staleness check: the DLL had been + built before `SehTrampoline.c` was committed. It was rebuilt from the identical source and the + release was rerun. The 2026.10.4.9 installer was archived as the previous release. +- Not yet verified in game. + - Check `[CreateSeed]` lines in the engine log for sensible names and types. + - Check that `native crash logger installed (v2, fatal-only)` is logged. diff --git a/Changelog/2026-10-04-installer-2026.10.4.11-release.md b/Changelog/2026-10-04-installer-2026.10.4.11-release.md new file mode 100644 index 0000000..1e1ee2e --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.11-release.md @@ -0,0 +1,27 @@ +# Installer 2026.10.4.11 + +**Date:** 2026-10-04 +**Branch:** `SK-local` (RynthCore `903d3ea`, RynthSuite `c236832`) +**Previous release:** 2026.10.4.10 + +## Contents +- **RynthJuice 0.1.2:** mob health polling used to re-check the same first 80 of about 700 + tracked objects. It now reaches every tracked object (`RynthSuite/Changelog/RynthJuice-0.1.2-rotating-mob-poll.md`): + - Candidates are checked in rotation, 80 per poll. + - Confirmed attackable mobs are polled every cycle, so health bars stay continuous. + - Objects with a known non-creature ItemType are never tracked. + - The safety cap was raised from 800 to 4096. +- **Engine 2026.10.4.10 changes are unchanged** apart from the version stamp. This includes + the create-time name/type seeds, which RynthJuice now relies on to drop items immediately. + The engine is stamped 2026.10.4.11. + +## Artifacts (`installer/Output/`) +- `RynthCore-Setup-2026.10.4.11.exe` + (SHA-256 `714bcdb1ec4b99ff98445f55386514839485afb4ae5501a19b52d7e08d5398de`) +- `Release-2026.10.4.11/` and `RynthCore-2026.10.4.11-deploy.zip` (103 MB, hash-verified) + +## Build +- `Build-Release-All.ps1 -Version 2026.10.4.11`: everything built and the Inno Setup compile + succeeded. The 2026.10.4.10 installer was archived as the previous release. +- Not yet verified in game. To check, compare the `[RynthJuice] pollcycle ... mobs=` and + `attackable=` counts with the engine's attackable count. diff --git a/Changelog/2026-10-04-installer-2026.10.4.12-release.md b/Changelog/2026-10-04-installer-2026.10.4.12-release.md new file mode 100644 index 0000000..8e840b9 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.12-release.md @@ -0,0 +1,18 @@ +# Installer 2026.10.4.12 + +Previous release: 2026.10.4.11 (RynthJuice rotating mob poll). + +* Installer: `installer/Output/RynthCore-Setup-2026.10.4.12.exe` + SHA-256 `3E3AAFD5DA6DFFE8FCC1A50B64C9431F6F705157D9E28296C7946EFFD16D1858` +* Deploy zip: `installer/Output/RynthCore-2026.10.4.12-deploy.zip` +* Source: RynthCore SK-local@6f9b985, RynthSuite SK-local@72d858e +* Plugin API: v68 + +## Included + +* Engine: off-thread PublicWeenieDesc int snapshot (stack size, max stack, + container, wielder, location, capacities, material) and merge-stack results + API (`GetMergeStackResult`). See + `2026-10-04-pwd-int-snapshot-and-merge-results.md`. +* RynthAi 0.6.17: AutoStack uses engine merge results, partial-merge success + detection, cooldown on full targets. diff --git a/Changelog/2026-10-04-installer-2026.10.4.13-release.md b/Changelog/2026-10-04-installer-2026.10.4.13-release.md new file mode 100644 index 0000000..bc296bd --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.13-release.md @@ -0,0 +1,23 @@ +# Installer 2026.10.4.13 + +Previous release: 2026.10.4.12 (PWD int snapshot + AutoStack merge results). + +* Installer: `installer/Output/RynthCore-Setup-2026.10.4.13.exe` + SHA-256 `E822BD93F8BF32AA04866CBDCC3300C566E814EB0B3602D647100CB843C89012` +* Deploy zip: `installer/Output/RynthCore-2026.10.4.13-deploy.zip` +* Source: RynthCore SK-local@6b94752, RynthSuite SK-local@82decc8 +* Plugin API: v68 (unchanged) + +## Included + +* Avalonia RynthAi panel: ILT Hub button (sends `hub show`). +* Plugin ImGui windows (ILT Hub, Item Info, ...) draw on top of the Avalonia + layer and get mouse priority when hovered. +* Live logging: global level (now with Off) and per-category engine levels from + engine.json, reloaded within 1 s; launcher 0.1.5 Logging card edits engine + categories and RynthAi categories/key events on the fly. +* RynthAi 0.6.18: per-category Off/Trace/Info levels (Info promotes trace lines + to the normal log), ILT Hub key events, `hub` remote command. + +See `2026-10-04-ilt-hub-button-imgui-on-top-live-logging.md` and +RynthSuite `Changelog/RynthAi-0.6.18-launcher-log-levels.md`. diff --git a/Changelog/2026-10-04-installer-2026.10.4.14-release.md b/Changelog/2026-10-04-installer-2026.10.4.14-release.md new file mode 100644 index 0000000..d20ff7b --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.14-release.md @@ -0,0 +1,20 @@ +# Installer 2026.10.4.14 + +Previous release: 2026.10.4.13 (ILT Hub button, ImGui on top, live logging) - crash-prone with AutoStack on. + +* Installer: `installer/Output/RynthCore-Setup-2026.10.4.14.exe` + SHA-256 `90E791016252CAECD165CEB9006BEFA4AA641A816B079FC63B802F8F8C7A2A63` +* Deploy zip: `installer/Output/RynthCore-2026.10.4.14-deploy.zip` +* Source: RynthCore SK-local@19095e1, RynthSuite SK-local@bd9be89 +* Plugin API: v69 + +## Included + +* Crash fix: `GetMergeStackResult` thunk is now cdecl. 4.12/4.13 corrupted + RynthAi's stack on every AutoStack merge check and killed the client. +* Release build rejects any plugin API delegate without the Cdecl attribute. +* RynthAi 0.6.19: ILT Hub draw diagnostics (overlay entry/skip, window geometry) + and off-screen rescue. + +See `2026-10-04-merge-result-cdecl-crash-fix.md` and RynthSuite +`Changelog/RynthAi-0.6.19-hub-draw-diagnostics.md`. \ No newline at end of file diff --git a/Changelog/2026-10-04-installer-2026.10.4.15-release.md b/Changelog/2026-10-04-installer-2026.10.4.15-release.md new file mode 100644 index 0000000..ad77b77 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.15-release.md @@ -0,0 +1,23 @@ +# Installer 2026.10.4.15 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.15.exe` +- SHA-256: `F76A08FDC4AF1096C022DAF1CC1A27FDB834B79641D8C23A9A27B64E1D3017CB` +- Deploy package: `installer/Output/RynthCore-2026.10.4.15-deploy.zip` +- Previous release: 2026.10.4.14 + +## Changes + +- **Engine fix: plugin ImGui windows now draw.** The plugin render snapshot was never + published after plugins loaded, so `RenderAll` / `RenderOverlayAll` called no plugins + and windows such as the RynthAi ILT Hub never appeared. See + `2026-10-04-plugin-render-snapshot-fix-and-imgui-diagnostics.md`. +- **Engine diagnostics:** one-time Info lines for the ImGui gate, init, first frame, branch, + first draw submit and overlay plugin binding, plus a 30 s heartbeat. Repeated frame + exceptions are rate-limited. +- CS0162 (unreachable code) is now a build error in the engine. + +## Upgrade notes + +- No plugin API change (still v69); plugins do not need rebuilding. +- `engine.json` may still be at `Trace` from earlier debugging. Set the logging level back to + `Info` in the launcher once the Hub is confirmed working. diff --git a/Changelog/2026-10-04-installer-2026.10.4.16-release.md b/Changelog/2026-10-04-installer-2026.10.4.16-release.md new file mode 100644 index 0000000..f018738 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.16-release.md @@ -0,0 +1,22 @@ +# Installer 2026.10.4.16 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.16.exe` +- SHA-256: `8D901EF8A6B80F9CB817372E7FBFAB18E334393E30A9BE3AC7F3FF9578E6E682` +- Deploy package: `installer/Output/RynthCore-2026.10.4.16-deploy.zip` +- Previous release: 2026.10.4.15 + +## Changes + +- **Floating panels are destroyed on the thread that owns them.** `LayeredWindow.Dispose` + destroys inline when the caller owns the window, and otherwise posts a self-destroy + message to the panel window itself. Before, the destroy always went to the game + thread, so panels created on another thread could be left frozen on screen. +- **The login-time pop-out waits for the game window hook**, so restored floating panels + are created on AC's game thread like every other pop-out. It falls back after 60 s. + +See `2026-10-04-panel-window-owner-thread-fixes.md` for details. + +## Upgrade notes + +- No plugin API change (still v69); plugins do not need rebuilding. +- `engine.json` may still be at `Trace` from earlier debugging; set it back to `Info` in the launcher. diff --git a/Changelog/2026-10-04-installer-2026.10.4.17-release.md b/Changelog/2026-10-04-installer-2026.10.4.17-release.md new file mode 100644 index 0000000..6c38982 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.17-release.md @@ -0,0 +1,23 @@ +# Installer 2026.10.4.17 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.17.exe` +- SHA-256: `7F21D78BEDD12DCFCFC865DA682E12498819B00C6BFC60BBDBA8BBF5D04E8EFF` +- Deploy package: `installer/Output/RynthCore-2026.10.4.17-deploy.zip` +- Previous release: 2026.10.4.16 +- RynthAi: 0.6.21 + +## Changes + +- **Items window: Shields section.** "Add Selected Shield", the shield list with delete, and the + auto-equip toggle. Shields no longer appear under Weapons. See + `2026-10-04-items-panel-shields.md`. +- **RynthAi panel Map and Lua buttons work.** Map toggles the dungeon map and Lua toggles the + Lua Scripts editor. Both are also available as `/ra map` and `/ra lua`. In Avalonia mode both + windows are now drawn on top of the overlay. The dungeon map also reopens again after being + closed with its X. See `2026-10-04-dashboard-map-and-lua-buttons.md`. + +## Upgrade notes + +- No plugin API change (still v69). RynthAi must be 0.6.20 or newer for the new Shields button and + the new Map/Lua commands (this installer ships 0.6.21). +- `engine.json` may still be at `Trace` from earlier debugging; set it back to `Info` in the launcher. diff --git a/Changelog/2026-10-04-installer-2026.10.4.18-release.md b/Changelog/2026-10-04-installer-2026.10.4.18-release.md new file mode 100644 index 0000000..9af1076 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.18-release.md @@ -0,0 +1,24 @@ +# Installer 2026.10.4.18 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.18.exe` +- SHA-256: `70F6A3C0EBE1C279D60E48C739E4664F8CE625B9AA5D055283B2C207219ACF26` +- Deploy package: `installer/Output/RynthCore-2026.10.4.18-deploy.zip` +- Previous release: 2026.10.4.17 +- RynthAi: 0.6.23 + +## Changes + +- **Floating HUDs.** Three new undockable windows: an item count HUD, a UB-style Mini Remote, and + a quest favorites HUD. The item HUD and Mini Remote are set up from Inventory Management > + **Inventory HUDs...** (both the ImGui Advanced Settings and the Avalonia Settings panel) or + `/ra huds`. The ILT Hub quest tracker gained a favorites star, the floating favorites HUD and a + **Pop out** button. See `2026-10-04-floating-huds.md`. +- **ILT Hub pet roster** (RynthAi 0.6.22, first shipped here). The Pet tab shows UB-style stats per + pet, sorts, and summons by type (Combat, Healing, Cosmetic). See + `2026-10-04-ilt-hub-pet-roster.md`. + +## Upgrade notes + +- No plugin API change. The engine's Inventory HUDs button needs RynthAi 0.6.23 or newer; older + plugins ignore the command. +- `engine.json` may still be at `Trace` from earlier debugging; set it back to `Info` in the launcher. diff --git a/Changelog/2026-10-04-installer-2026.10.4.19-release.md b/Changelog/2026-10-04-installer-2026.10.4.19-release.md new file mode 100644 index 0000000..29e3dab --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.19-release.md @@ -0,0 +1,27 @@ +# Installer 2026.10.4.19 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.19.exe` +- SHA-256: `780425B79594914296AC5E9E35708192E94E1D40697D96365D64D9A34FFEA1C3` +- Deploy package: `installer/Output/RynthCore-2026.10.4.19-deploy.zip` +- Previous release: 2026.10.4.18 +- RynthAi: 0.6.26 + +## Changes + +- **Missile ammo detection** (RynthAi 0.6.24). Ammo already in the ammo slot is recognised even + when its name isn't a stock arrow/bolt/dart name: it is matched by equip slot, `CombatUse` and + `AmmoType`, with a fallback probe and an `[AmmoDiag]` log line. See + `2026-10-04-missile-ammo-detection.md`. +- **Char / Hub launcher buttons** (RynthAi 0.6.25). "ILT Hub" is now **Char**, and a new **Hub** + button toggles the Mini Remote (right-click in the Avalonia panel opens Inventory HUDs). See + `2026-10-04-char-and-hub-launcher-buttons.md`. +- **Pet scan by type** (RynthAi 0.6.26 + engine). The ILT Hub Pet tab and Scan pack only count + real pet devices (essence WCID block, summoning-gem icon underlay, Summoning use requirement, + ACECustom bond/potency). A name ending in "Essence" is no longer enough. The engine now serves + `IconOverlay` / `IconUnderlay` DIDs. See `2026-10-04-pet-scan-type-detection.md`. + +## Upgrade notes + +- No plugin API version change. `IconOverlay` / `IconUnderlay` reads return false on older + engines, and RynthAi then confirms pets from appraisal data instead. +- `engine.json` may still be at `Trace` from earlier debugging; set it back to `Info` in the launcher. diff --git a/Changelog/2026-10-04-installer-2026.10.4.20-release.md b/Changelog/2026-10-04-installer-2026.10.4.20-release.md new file mode 100644 index 0000000..9729d55 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.20-release.md @@ -0,0 +1,24 @@ +# Installer 2026.10.4.20 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.20.exe` +- SHA-256: `8A5FE0DBB55A66FAD4BCB4FFBE70F205ADF2B8269BE60C748395214A45F66D53` +- Deploy package: `installer/Output/RynthCore-2026.10.4.20-deploy.zip` +- Previous release: 2026.10.4.19 +- RynthAi: 0.6.27 + +## Changes + +- **Looting fix: name rules never matched** (RynthAi 0.6.27). Loot rules that match on item name + read an empty string, because ACE never sends `Name` in appraisal data and the evaluator runs + off the main thread. Every corpse item was left behind; SilentKelpie looted nothing across 225 + items. Name reads now fall back to the object's snapshot name. See + `2026-10-04-loot-name-rules-and-ground-loot.md`. +- **Loot items on the ground** (RynthAi 0.6.27). A port of UB-IT AutoGroundLoot: loose ground + items that match the active loot profile are picked up within the corpse max range. Corpses + are looted first. Turn it on in Advanced Settings > Looting > **Loot Items On Ground** or with + `/ra groundloot on|off|status|scan`. + +## Upgrade notes + +- No engine or plugin API change. Ground loot is off by default. +- `engine.json` may still be at `Trace` from earlier debugging; set it back to `Info` in the launcher. diff --git a/Changelog/2026-10-04-installer-2026.10.4.3-experimental-plugins.md b/Changelog/2026-10-04-installer-2026.10.4.3-experimental-plugins.md new file mode 100644 index 0000000..9d5ea99 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.3-experimental-plugins.md @@ -0,0 +1,40 @@ +# RynthCore 2026.10.4.3: experimental plugins as optional installer components + +**Release date:** 2026-10-04 +**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.3.exe` (also copied to `RynthCore-Setup.exe`) +**Previous release:** `2026.10.4.2` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.2.exe`) +**Branch:** `feat/full-installer` (local test build, not on `main`) + +## What's new + +The **Select Components** page has a new **RynthSuite: Experimental plugins** group. Each plugin is unchecked by +default in every install type; ticking one switches the install to Custom. + +| Component | Installs to | Version | +|---|---|---| +| `experimental\rynthchat` | `\RynthChat\RynthCore.Plugin.RynthChat.dll` | 0.1.1 | +| `experimental\rynthjuice` | `\RynthJuice\RynthCore.Plugin.RynthJuice.dll` | 0.1.1 | +| `experimental\rynthnav` | `\RynthNav\RynthCore.Plugin.RynthNav.dll`, plus `\NavData\` | 0.5.5 | +| `experimental\rynthtracker` | `\RynthTracker\RynthCore.Plugin.RynthTracker.dll` | 0.1.1 | +| `experimental\rynthvision` | `\RynthVision\RynthCore.Plugin.RynthVision.dll` | 0.1.1 | + +- **Registration:** every selected plugin (RynthAi included) goes into `Software\Rynth\PendingPluginRegistration` + as a `;`-separated list. On next start the launcher adds them all to its Plugins list and syncs `engine.json`. +- **Suite folder page:** shown whenever any RynthSuite component is selected, experimental ones included. +- **RynthNav data:** the installer creates `\NavData` (kept on uninstall). It ships the starter + `portals.tsv` from `RynthNav.PortalGraph` only when that folder has none, so a newer generated file is never overwritten. + Navmesh tiles (`nav_XXXX.tile`) are **not** shipped; bake them with `RynthNav.Baker --tiled` (its default output + is `C:\Games\RynthCore\NavData`; pass `--out` for a different RynthCore folder). +- **Silent installs:** pick components with `/COMPONENTS`, for example + `/COMPONENTS="core,rynthai,monstereditor,experimental\rynthnav,experimental\rynthvision"`. + +## Build script (`installer\Build-Installer.ps1`) +- New step **7/7** publishes the five plugins (NativeAOT, x86), each keeping its own version. +- RynthJuice, RynthNav and RynthVision set `` to the live `C:\Games\RynthSuite\\` for dev hot-reload. + The build overrides it to each project's `bin\...\publish\`, so building an installer never touches a live install. +- Staging: `staging\suite\\` per plugin and `staging\navdata\portals.tsv`. All of them are in the required-files check. + +## Upgrade notes +- Re-running the installer without an experimental plugin does not remove one installed earlier. Uninstall + RynthCore, or delete `\\` and its row in the launcher's Plugins tab. +- These plugins are work in progress and may change or break between builds. diff --git a/Changelog/2026-10-04-installer-2026.10.4.4-dotnet10-prereq.md b/Changelog/2026-10-04-installer-2026.10.4.4-dotnet10-prereq.md new file mode 100644 index 0000000..98e2201 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.4-dotnet10-prereq.md @@ -0,0 +1,50 @@ +# RynthCore 2026.10.4.4: .NET 10 check with automatic download and install + +**Release date:** 2026-10-04 +**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.4.exe` (also copied to `RynthCore-Setup.exe`) +**Previous release:** `2026.10.4.3` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.3.exe`) +**Branch:** `feat/full-installer` (local test build, not on `main`) + +## Installer: .NET 10 Desktop Runtime (x86) + +- **Detection:** setup looks for a 10.x `Microsoft.WindowsDesktop.App` under `Program Files (x86)\dotnet\shared\`, or its + registration in `HKLM\SOFTWARE\dotnet\Setup\InstalledVersions\x86\sharedfx\Microsoft.WindowsDesktop.App` (32-bit view). + x86 matches RynthCore's x86 launcher and tools. The Desktop Runtime also contains the base .NET runtime. +- **When it's missing,** the Tasks page shows a **Prerequisites** task, checked by default: *Download and install the + Microsoft .NET 10 Desktop Runtime (x86)*. When the runtime is already there, the task is not shown at all. +- **Install:** on leaving the Ready page, setup downloads the latest 10.x runtime from Microsoft + (`https://aka.ms/dotnet/10.0/windowsdesktop-runtime-win-x86.exe`, about 55 MB) with a progress page, then runs it + with `/install /quiet /norestart`. The runtime's own installer asks for administrator approval (UAC) when setup + isn't elevated. +- **Silent installs** run the same step just before the files are copied, without a progress page. Skip it with + `/MERGETASKS="!installdotnet"`. That's useful offline, or for the launcher's silent self-update when no one is + there to approve UAC. +- **Never blocking:** exit codes 0, 3010, 1641 and 1638 (a newer runtime is already installed) count as success. A + failed download, a cancelled UAC prompt (1602) or any other error is logged and shown in a message box with the + manual download link, and the RynthCore install carries on. + +Why it isn't required: the launcher, Loot Editor and Monster Editor are self-contained (they bundle .NET 10.0.5), and the +engine, loader and plugins are NativeAOT. The shared runtime is a safety net for framework-dependent add-ons and tools. +Earlier blocking .NET pages (0.4.x) had to be made advisory for exactly this reason. + +## Build script: .NET 10 SDK + +`Build-Installer.ps1` needs a .NET 10 SDK to publish, so before building (skipped with `-SkipBuild`) it: +1. uses the `dotnet` on PATH if it lists a 10.x SDK; +2. otherwise reuses an earlier per-user install in `%LOCALAPPDATA%\Microsoft\dotnet`; +3. otherwise downloads Microsoft's `dotnet-install.ps1`, **checks its Authenticode signature** (must be valid and signed + by Microsoft Corporation), and installs the latest 10.0 SDK per-user. No admin is needed. Then it uses that SDK for the + rest of the build (`DOTNET_ROOT` and `PATH` are set for this session only). + +Pass `-NoDotNetInstall` to fail with a download link instead of installing. + +**Tested:** in an isolated session with no `dotnet` on PATH, the script verified the signature, installed SDK 10.0.401 to +a scratch folder and found it again on a second run without re-downloading. + +NativeAOT publishing also needs the Visual Studio C++ build tools ("Desktop development with C++"). The script doesn't +install those. + +## Not tested end to end +The runtime download and install path in the installer was compiled but not run on the build machine. That machine already +has the x86 Desktop Runtime 10.0.7, so the task stays hidden there. Running it would have meant installing 10.0.12 +machine-wide. diff --git a/Changelog/2026-10-04-installer-2026.10.4.5-suite-dir-per-mode.md b/Changelog/2026-10-04-installer-2026.10.4.5-suite-dir-per-mode.md new file mode 100644 index 0000000..dd7dbb9 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.5-suite-dir-per-mode.md @@ -0,0 +1,31 @@ +# RynthCore 2026.10.4.5: installer only reuses a RynthSuite folder from the same install mode + +**Release date:** 2026-10-04 +**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.5.exe` (also copied to `RynthCore-Setup.exe`) +**Previous release:** `2026.10.4.4` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.4.exe`). Don't +use 2026.10.4.4 for a per-user install on a machine that also has an all-users install (see below). +**Branch:** `feat/full-installer` (local test build, not on `main`) + +## Fix + +To pre-fill the **Select RynthSuite Location** page, the installer used to read `Software\Rynth\SuiteDir` from HKCU **and +then HKLM**. A per-user install on a machine that already had an all-users install therefore adopted the all-users +RynthSuite folder. The two installs then shared those files, and **uninstalling the per-user install deleted the +all-users install's RynthAi DLL and Monster Editor.** + +The lookup now reads only the hive of the current install mode (Inno's `HKA`: HKCU for per-user, HKLM for all-users), +matching how `GetPreviousData` and `UsePreviousAppDir` already behave. A per-user install with no per-user history +defaults to a `RynthSuite` folder next to its RynthCore folder again. + +The runtime resolver (`RynthInstallPaths`: HKCU, then HKLM) is unchanged. A per-user install's own values still +take precedence for that user. + +## Found by +A per-user test install of 2026.10.4.4 into a scratch folder on the build machine, which had an all-users 2026.10.4.3 +install in `C:\Games`. The test install wrote into `C:\Games\RynthSuite` and its uninstall removed +`RynthAi\RynthCore.Plugin.RynthAi.dll` and the Monster Editor. Both were restored right away from the same-source build +(RynthAi 0.5.3, 217 Monster Editor files). User data folders, the experimental plugins and `C:\Games\RynthCore` were not affected. + +## Also in this build +Everything from 2026.10.4.4: the .NET 10 Desktop Runtime check with automatic download and install in the installer, +and the .NET 10 SDK check with per-user auto-install in `Build-Installer.ps1`. diff --git a/Changelog/2026-10-04-installer-2026.10.4.6-tool-launch-buttons.md b/Changelog/2026-10-04-installer-2026.10.4.6-tool-launch-buttons.md new file mode 100644 index 0000000..c3eb85d --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.6-tool-launch-buttons.md @@ -0,0 +1,16 @@ +# Installer 2026.10.4.6 — RynthAi tool launch buttons + +**Date:** 2026-10-04 +**Branch:** `feat/full-installer` (testing only — not merged to `main`) + +## Changes +- Bundles **RynthAi 0.5.4**, which adds **Loot Editor** and **Monster Editor** launch buttons to the + in-game Items window and the Advanced Settings → Looting page. No more launching the editors from + the shell or Explorer while playing. +- No installer script changes; tool locations are unchanged (`\Tools\LootEditor`, + `\RynthAi\MonsterEditor`), and RynthAi finds them through the registered install paths. + +## Build +- `installer\Build-Installer.ps1 -Version 2026.10.4.6` +- Previous installer archived: `installer\previous-release\RynthCore-Setup-2026.10.4.5.exe` +- Output: `installer\Output\RynthCore-Setup-2026.10.4.6.exe` diff --git a/Changelog/2026-10-04-installer-2026.10.4.7-deployment-package.md b/Changelog/2026-10-04-installer-2026.10.4.7-deployment-package.md new file mode 100644 index 0000000..7d7c68a --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.7-deployment-package.md @@ -0,0 +1,45 @@ +# Installer 2026.10.4.7 — deployment-ready release package + +**Date:** 2026-10-04 +**Branch:** `SK-local` +**Previous release:** 2026.10.4.6 + +## Added +- `Build-Installer.ps1 -Version ` now finishes with a **deployment package**: + - `installer\Output\Release-\` + - `RynthCore-Setup-.exe` — the installer (its stamped ProductVersion must equal ``). + - `release-manifest.json` — version, release number, build time, previous release, RynthCore and + RynthSuite branch/commit/dirty flag, every shipped component's version (launcher, engine, + loader, Loot Editor, RynthAi, Monster Editor, experimental plugins) and the installer's size + SHA-256. + - `RELEASE-NOTES.md` — install / silent-install / hash-verification steps, component table, and the + Changelog entries from **both** repos added or changed since the previous release (by the previous + manifest's commits; falls back to the previous version's build date). + - `SHA256SUMS.txt` — `sha256sum`-format hashes of the files above. + - `installer\Output\RynthCore--deploy.zip` — the folder zipped, then extracted to a temp folder and + re-checked against `SHA256SUMS.txt`. + - `installer\previous-release\last-release-manifest.json` — kept so the next release lists only new notes. +- `-AllowDirty` and `-NoPackage` switches. + +## Changed +- Release (`-Version`) builds refuse uncommitted changes to tracked files in either repo (checked before the + slow publishes) so every package maps to exact commits; `-AllowDirty` overrides and flags the manifest. + `installer\previous-release\` is exempt because the script rewrites its markers. +- `last-built-version.txt` is written only after the whole build (including the package) succeeds, so a + failed package step is retried rather than skipped. +- `Build-Release-All.ps1` documents the package output. + +## Fixed +- **Previous-release archive mislabel:** when `RynthCore-Setup-.exe` was not in `Output\` (e.g. it + was built in another checkout), the canonical `RynthCore-Setup.exe` — possibly an older build — was archived + under the previous version's name. It is now archived only when its ProductVersion matches. +- **`Publish-Update.ps1` could not publish:** it copied the RynthAi plugin from `staging\plugins\RynthAi\`, + which the full installer layout no longer creates (`staging\suite\RynthAi\`). It also now takes the + versioned `RynthCore-Setup-.exe` (the unversioned copy is best effort and may be stale). +- **False "SehTrampoline.dll is STALE" after checkouts/merges:** the check compared file times, and git rewrites + `SehTrampoline.c` (new mtime, same content) on checkout. When the source matches HEAD its last commit + time is used instead; local edits still use the file time. +- **Launcher showed `0.1.3-x64-prereq-probe` instead of the release:** the SK-era launcher `.csproj` hard-coded + `InformationalVersion`, which overrides the `-p:Version` release stamp. Removed; launcher file version + 0.1.3 -> 0.1.4. The launcher / About now report `2026.10.4.7 ()`. +- Rebuilding the same `-Version` keeps that release's original "changes since" baseline (stored as + `changelogSince` in the manifest) instead of diffing against itself. diff --git a/Changelog/2026-10-04-installer-2026.10.4.8-release.md b/Changelog/2026-10-04-installer-2026.10.4.8-release.md new file mode 100644 index 0000000..7193d4d --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.8-release.md @@ -0,0 +1,28 @@ +# Installer 2026.10.4.8 + +**Date:** 2026-10-04 +**Branch:** `SK-local` (RynthCore `45f9ad2`, RynthSuite `975151b`) +**Previous release:** 2026.10.4.7 + +## Contents +- **Engine / launcher / loader** 2026.10.4.8 + - Nav panel waypoint list no longer jumps back to the top while editing + (`2026-10-04-nav-panel-scroll-fix.md`). +- **RynthAi 0.6.14** (was 0.6.11 in 2026.10.4.7): + - 0.6.12: shields in Items for the secondary (off) hand. + - 0.6.13: Mag-style item info line (`/ra iteminfo`): ratings, damage, spells, slayer, imbues, … + - 0.6.14: "RynthAi Item Info" settings window with live preview, per-field and per-rating + toggles, spell mode, chat type and prefix. The item info options now persist across reloads. +- Loot Editor, Monster Editor and experimental plugins rebuilt at RynthSuite `975151b`. + +## Artifacts (`installer/Output/`) +- `RynthCore-Setup-2026.10.4.8.exe` + (SHA-256 `a028c97469d6ad2d83a343c14e4b4884693ca524b16486825470d07cbba4a627`) +- `Release-2026.10.4.8/`: installer, `SHA256SUMS.txt`, `release-manifest.json`, `RELEASE-NOTES.md` +- `RynthCore-2026.10.4.8-deploy.zip` (103 MB, hash-verified) + +## Build +- `Build-Release-All.ps1 -Version 2026.10.4.8`: solution build, all NativeAOT publishes and the + Inno Setup compile succeeded. The 2026.10.4.7 installer was archived as the previous release, + and `installer/previous-release/` markers were updated to 2026.10.4.8. +- Not yet verified in game. diff --git a/Changelog/2026-10-04-installer-2026.10.4.9-release.md b/Changelog/2026-10-04-installer-2026.10.4.9-release.md new file mode 100644 index 0000000..c997109 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.9-release.md @@ -0,0 +1,24 @@ +# Installer 2026.10.4.9 + +**Date:** 2026-10-04 +**Branch:** `SK-local` (RynthCore `7a58cdc`, RynthSuite `22b77c5`) +**Previous release:** 2026.10.4.8 + +## Contents +- **Engine 2026.10.4.9:** new optional plugin export `RynthPluginRenderOverlay`, so plugins can show + extra windows beside the Avalonia UI while the ImGui shell is off + (`2026-10-04-plugin-overlay-windows.md`, engine.json `EnablePluginOverlayWindows`, default on). +- **RynthAi 0.6.15:** the **ILT Hub** window (and the Item Info settings window) now show as + separate windows next to the Avalonia RynthAi panel. Open with `/ra hub` and + `/ra iteminfo settings`. RynthAi's macro and automation never depend on these windows. + +## Artifacts (`installer/Output/`) +- `RynthCore-Setup-2026.10.4.9.exe` + (SHA-256 `95854d75eb1635e34474a9ef29deb65fc6dbc825d45e782fc9ecae501536efab`) +- `Release-2026.10.4.9/` and `RynthCore-2026.10.4.9-deploy.zip` (103 MB, hash-verified) + +## Build +- `Build-Release-All.ps1 -Version 2026.10.4.9`: everything built and the Inno Setup compile + succeeded. The remaining trim warnings are the existing ones in `AvaloniaOverlay.cs`. The + 2026.10.4.8 installer was archived as the previous release. +- Not yet verified in game. diff --git a/Changelog/2026-10-04-item-info-click-and-pet-layout.md b/Changelog/2026-10-04-item-info-click-and-pet-layout.md new file mode 100644 index 0000000..31c36bf --- /dev/null +++ b/Changelog/2026-10-04-item-info-click-and-pet-layout.md @@ -0,0 +1,70 @@ +# Item info: ID on left/right click + pet-style layout — RynthAi 0.6.29 + +**Date:** 2026-10-04 +**Component:** RynthCore.Plugin.RynthAi 0.6.28 → 0.6.29 + +## What's new + +### ID + print on click +- New **"ID + print on click"** option: **Off / Left mouse click / Right mouse click**. +- Clicking an item in the world or in your packs IDs it if needed and prints its info to chat. + It also prints for an item that was already selected; the old "on select" option only fired when the selection changed. +- Ignored: + - clicks on RynthCore / ImGui windows; + - drags (moving more than 6 px while held, e.g. dragging items between packs); + - holds longer than 0.6 s (right-button camera turning). +- The info is printed for the item that is selected 150 ms after the button is released. + With **Right mouse click**, if the client doesn't change the selection on a right click, it prints the + currently selected item. That still works as left-click to select, right-click to print. +- The weapon / armor / jewelry / other type filters apply to both the select and click triggers. +- If on-select and on-click both fire for the same item, it prints once (1.5 s duplicate guard). +- Requires the ImGui overlay (clicks are read from the overlay's input state). Works with both + the ImGui dashboard and the Avalonia UI overlay path. + +### Pet-style layout for weapons and armor +- New **Layout** option: **Pet-style lines** (new default) or **One line (Mag-Tools)** (the previous output). +- Pet-style mirrors the ILT Hub pet roster: a name/identity line, then indented detail lines: + + ``` + [RynthAi] Gold Ornate Long Sword (Slash Sword), Noble Relic Set, Tinks 4, Applied: Steel x2, Craft 8 + [RynthAi] CS, Undead Slayer, 152.48-236, 0.35v, 18%a, 12%md + [RynthAi] [D 3, CD 2] Wield Lvl 180, Heavy Weapons 375, Diff 270 + [RynthAi] Spells: Legendary Blood Thirst + ``` + + - Line 1: name (damage type + mastery), set, AL, tinks, applied materials, craft / salvage work, keyring. + - Line 2: imbues, armor cleave, crit stats, splits, range, cleaving, slayer, damage, variance, + elemental / damage-mod bonuses, %a / %md / %mgc.d / %msl.d / %mc, unenchantable protections. + - Line 3: ratings cluster, then wield / activation / difficulty requirements and value / burden. + - Line 4: spells. + - Empty lines are skipped, so plain armor prints only one or two lines. +- New **Detail lines colour** (chat type for lines 2–4), default "Same as name line", with a Test button. +- Every existing field and rating toggle, the spell mode, the prefix and the chat type apply to both layouts. + The one-line output is identical to 0.6.28. + +## Where to set it +- **Advanced Settings → Display → Item Info**: "ID + print on click" and "Layout" combos. +- **Item Info window** (`/ra iteminfo settings`): click trigger in *When to print*, layout and + detail colour in *Chat output*. The preview shows the multi-line layout. +- Commands: + - `/ra iteminfo click left|right|off` + - `/ra iteminfo layout pet|line` + +## Implementation notes +- `MagItemDescriber.Build` now returns a `MagItemDescription` (title plus fields tagged with a + `MagItemSection`, in Mag print order). `ToOneLine()` reproduces the classic line and + `ToPetLines()` groups the same fields by section. `Describe()` is kept as a one-line wrapper. +- Click detection (`DetectItemInfoClick`) runs on the render thread in `OnRender` / + `OnRenderOverlay`, edge-detecting `io.MouseDown`. The selection is read on the plugin tick + (`ResolveItemInfoClick`, handed over with `Interlocked`), so all describe / ID state stays on one thread. +- New `MagItemInfoSettings` fields: `ClickTrigger`, `Layout`, `DetailChatType` (sanitized and included in reset). + +## Files +- `Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs` +- `Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs` +- `Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs` +- `Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs` (render hooks, on-select dedupe, VersionPointer 0.6.29) +- `Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs` (help line) +- `Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs` +- `Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs` +- `Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj` (0.6.29) diff --git a/Changelog/2026-10-04-items-panel-shields.md b/Changelog/2026-10-04-items-panel-shields.md new file mode 100644 index 0000000..fcddecb --- /dev/null +++ b/Changelog/2026-10-04-items-panel-shields.md @@ -0,0 +1,39 @@ +# Items panel: Shields section and "Add Selected Shield" (2026-10-04) + +Engine Avalonia `ItemsPanel` plus RynthAi 0.6.20. Ships in the next installer after 2026.10.4.16. + +## Problem + +RynthAi stores off-hand shields in its item list (`ItemRule.Action = "Shield"`), and its +ImGui Items tab has a Shields section. The engine's Avalonia Items window (the one +opened from the dashboard) never got that section: + +- "Add Selected Weapon" rejects shields with "That is a shield — use Add Selected Shield", + but that button didn't exist in the engine panel, so shields couldn't be added there. +- Shields already in the list showed up under Weapons with an element picker. + +## Engine (`UI/Panels/ItemsPanel.cs`) + +- New **Shields (off-hand)** section between Weapons and Consumables: + - an "Auto-equip with one-handed melee weapons" ON/OFF toggle with a tooltip (shown when the + plugin reports the setting); + - a shield list with a Del button on each row; + - **Add Selected Shield**, which calls the plugin's new `RynthPluginAddSelectedShield` export. + With an older plugin the click does nothing and logs that RynthAi 0.6.20+ is required. +- The Weapons section now lists only non-shield entries. +- `WeaponEntry` carries `action` and the payload carries `autoEquipShield`; both are part of + change detection, so plugin-side edits appear within the 1 s poll. +- Deletes now remove the row's own entry instead of a list index, because the weapon and + shield rows are filtered views of one list. + +## RynthAi 0.6.20 + +- New export `RynthPluginAddSelectedShield`, which goes through `LegacyDashboardRenderer.AddSelectedShield` + to the existing `LegacyWeaponsUi.AddSelectedShield` and then saves settings. +- `ItemsBridgePayload.AutoEquipShield` (`bool?`) is sent to the panel. It's applied on write-back + only when present, so older engine panels leave the setting alone. +- `ApplyItemsJson`: + - new entries keep the `Shield` action the panel sends (anything else becomes `Weapon`); + - deleting a shield from the engine panel clears any monster off-hand that pointed at it and + saves the monsters file (the same cleanup as the ImGui Del button). +- Version bumped to 0.6.20 (`csproj`, `RynthAiPlugin.VersionPointer`). diff --git a/Changelog/2026-10-04-loot-name-rules-and-ground-loot.md b/Changelog/2026-10-04-loot-name-rules-and-ground-loot.md new file mode 100644 index 0000000..1e2760b --- /dev/null +++ b/Changelog/2026-10-04-loot-name-rules-and-ground-loot.md @@ -0,0 +1,66 @@ +# Looting fix (name rules never matched) + ground-item looting + +**Date:** 2026-10-04 +**Components:** RynthAi plugin 0.6.27 (RynthSuite) + +## Problem: SilentKelpie looted nothing + +SilentKelpie's log for this session (pid 30364) shows 21 corpses claimed, opened and fully +evaluated. All 225 items evaluated across two sessions came out `-> leave`. That includes items +the active profile (`T10locky.utl`) explicitly keeps by name, such as "Thaelaryn Core" via its +`(T) Thaelaryn Core` rule. + +### Cause +VTank name rules (node type 1, `StringValueMatch` on key 1 = Name) and native JSON name rules +read the name through `WorldObject.Values(StringValueKey.Name)`. That goes to the engine's +string-property read, which off the main thread only answers from the appraisal cache. ACE does +not mark `PropertyString.Name` as an assessment property, so appraisal data never contains it. +Because the loot evaluator runs on the plugin pump thread, every name read returned `""` and +every name rule failed. The object's own `Name` (from the network snapshot, which is what the +`[LootEval]` log line prints) was correct all along. + +### Fix +`Combat/AcStubs.cs` `WorldObject.Values(StringValueKey, ...)`: when the live read is empty and +the key is `Name`, return the snapshot `Name`. This affects every consumer of name rules: corpse +loot (VTank and native profiles), `/ra lootcheck`, AutoVendor rules, ILT equip suits and meta +expressions. + +## New: loot items on the ground (UB-IT AutoGroundLoot) + +- **Setting:** Advanced Settings > Looting > **Loot Items On Ground** (`EnableGroundLoot`, default + off; saved with the profile). +- **Command:** `/ra groundloot on|off|status|scan`. `scan` clears the skip list. +- **Range:** the corpse max range (`CorpseApproachRangeMax`, yards, Ranges tab). +- **Rules:** the active loot profile, through the same `ClassifyItemAgainstProfile` corpses use. + This covers VTank `.utl` and native `.json` profiles, mana stone and mana-tap rules, and + salvage items queued for salvaging. +- **What counts as a ground item:** readable ownership with no container and no wielder, plus a + world position within range. Scenery, creatures, players, NPCs, vendors, portals, doors, + corpses, lifestones, signs, housing, containers, combat pets and services are excluded. +- **Appraisal:** stat-gated rules request an appraisal first (two per scan). If none arrives + within 3 s, the item is classified best-effort, matching the corpse assess window. +- **Pickup:** only when the activity arbiter hands Looting the tick, so navigation is already + stopped. It sends `MoveItemExternal(item → player)`, and ACE walks the character over and picks + the item up. The pickup is confirmed when the item gets a container, is retried up to 3 times + over 5 s windows, and is then skipped for 5 minutes. Non-matching items are re-checked after + 60 s. +- **Priority:** corpses come first. Ground loot runs only when no corpse is claimed or open. A + ground pickup already sent finishes before the next corpse is claimed. +- **Logging:** every ground evaluation is logged as `[LootEval] ground '' ... -> KEEP|leave`, + and claims and pickups as `Ground loot: ...`. + +## Files +- `Combat/AcStubs.cs`: Name fallback. +- `Combat/WorldObjectCache.cs`: new `IsOnGround(id)`. +- `GroundLootController.cs` (new): scan, claim, pickup, confirm, `/ra groundloot`. +- `CorpseOpenController.cs`: ground loot hooked into `TickCorpseOpening`; `HasLootWork` includes + ground matches. +- `LegacyUi/LegacyUiSettings.cs`, `LegacyDashboardRenderer.cs`, `LegacyAdvancedSettingsUi.cs`: + `EnableGroundLoot` setting and checkbox. +- `RynthAiPlugin.cs`, `RynthAiCommands.cs`: command registration and help; ground state cleared + on logout. + +## Notes +- `T10locky.utl` has no Pyreal rule (its only coin rule matches "Coin"), so Pyreals are still left + on corpses. That is how the profile is set up, not a bug. +- Versions: RynthAi `0.6.26` → `0.6.27`. diff --git a/Changelog/2026-10-04-merge-result-cdecl-crash-fix.md b/Changelog/2026-10-04-merge-result-cdecl-crash-fix.md new file mode 100644 index 0000000..d76cff2 --- /dev/null +++ b/Changelog/2026-10-04-merge-result-cdecl-crash-fix.md @@ -0,0 +1,35 @@ +# 2026-10-04 — Fix: GetMergeStackResult stack corruption crash (API v69) + +## Problem + +Builds 2026.10.4.12 and .13 crashed a couple of seconds after AutoStack started +logging merges with garbage item names and IDs (e.g. `src=0x40C16E04 -> +tgt=0xFFFF7C95`, then `Event_StackableMerge from=0x40C16E04 to=0xBD8B1053`, a +target that didn't even match the request). The process died with no exception, +so the crash logger caught nothing and the launcher recorded a "normal close". + +## Cause + +`GetMergeStackResultCallbackDelegate` (PluginContract.cs) was the only one of the +API delegates without `[UnmanagedFunctionPointer(CallingConvention.Cdecl)]`. On +x86 that makes `Marshal.GetFunctionPointerForDelegate` produce a **stdcall** +thunk, while plugins call it as **cdecl**. Both sides popped the 16 bytes of +arguments, so RynthAi's stack shifted on every call. AutoStack (RynthAi 0.6.17+) +calls it on every pending-merge check, so locals turned to garbage until the +process died. + +## Fix + +* Added the missing `[UnmanagedFunctionPointer(CallingConvention.Cdecl)]`. +* API version bumped to **v69**. The SDK's `HasGetMergeStackResult` now requires + v69, so a rebuilt plugin never calls the broken v68 thunk on a 4.12/4.13 engine + (it falls back to the 10 s grace check). +* `Build-Release-All.ps1` now fails the release if any delegate in + `PluginContract.cs` is missing the Cdecl attribute. + +## ILT Hub draw diagnostics + +* Engine logs `PluginManager: first RenderOverlay call for ` once per + plugin per session, proving the overlay export is being driven. +* See RynthSuite `Changelog/RynthAi-0.6.19-hub-draw-diagnostics.md` for the + plugin-side lines. diff --git a/Changelog/2026-10-04-missile-ammo-detection.md b/Changelog/2026-10-04-missile-ammo-detection.md new file mode 100644 index 0000000..d5a4adc --- /dev/null +++ b/Changelog/2026-10-04-missile-ammo-detection.md @@ -0,0 +1,56 @@ +# Missile combat: equipped ammo not detected (2026-10-04) + +RynthAi 0.6.24. + +## Symptom + +Silentkelpie (InfiniteLeaftide) had ammo equipped for the Corrupted Bow, but RynthAi never +fired. The log shows the bow equipped and the stance reaching Missile (mode 4) with a target +locked, then `attack=never` on every combat tick from 22:13 onwards. Combat also never tried to +equip ammo from the pack. + +## Cause + +Combat refuses to fire in missile mode until `HasWieldedAmmo()` passes. That check had two weak +points: + +1. **Name only.** A wielded stack only counted as ammo if its name contained "arrow" (bow), + "quarrel"/"bolt" (crossbow) or "dart" (atlatl). Server-custom ammo with any other name was + invisible, both in the ammo slot and in the pack, which is why combat never tried to equip + anything either. +2. **Snapshot only.** It only looked at the direct-inventory snapshot. That snapshot merges in + wielded gear the object cache had already filed as inventory with a readable wield slot. + Ammo equipped before login can be missing from it, or read wield slot 0. + +The log can't say which of the two hit Silentkelpie: no line names the ammo stack. The fix +covers both, and adds a diagnostic line (below) that names it next time. + +## Fix + +- **The ammo slot counts as ammo.** Any item the player wields in the ammunition slot (EquipMask + `0x00800000`) is treated as ammo, whatever its name. This is safe because the server (ACE + `Player_Inventory`) refuses to wield ammo whose AmmoType conflicts with the launcher. +- **Property-based recognition.** Loose ammo is also recognized by COMBAT_USE = Ammo (STypeInt 51), + matched to the launcher by AMMO_TYPE (STypeInt 50) when readable. This covers: + - auto-equipping from the pack; + - Items > Missile ammunition > "Add selected as ammo"; + - the per-monster "Sel" ammo button. +- **Launcher detection.** Launcher kind now comes from the launcher's AMMO_TYPE when readable, + else from its name. Items in the ammo slot are never mistaken for the launcher. +- **Fallback probe.** If the snapshot shows no ammo, combat probes every known missile-class or + ammo-named object's wield slot through the host (wielder info, ownership info, then + CurrentWieldedLocation). The result is reused for 750 ms. +- **`[AmmoDiag]` log line** (Combat category, at most every 15 s while ammo is missing). It names + the ammo found outside the snapshot, or lists every wielded missile-class object with its slot, + COMBAT_USE and AMMO_TYPE. +- `MissileCraftingManager` uses the same ammo-slot rule. + +## Files + +- `Combat/MissileAmmoHelper.cs`: slot constants, `IsAmmoSlot`, `KindFromAmmoType`, + `IsWieldedAmmoForKind`, `GetAmmoKind`, `GetKindFromMissileWeapon`, public `PlayerWieldLocation`. +- `Combat/CombatManager.cs`: `HasWieldedAmmo` fallback probe and `[AmmoDiag]`. + `TryEnsureMissileAmmoForCombat` reuses `HasWieldedAmmo`. +- `Combat/MissileCraftingManager.cs`: ammo-slot aware launcher and ammo checks. +- `LegacyUi/LegacyWeaponsUi.cs`, `LegacyUi/LegacyMonstersUi.cs`: property-based ammo recognition. +- Version 0.6.23 → 0.6.24. diff --git a/Changelog/2026-10-04-nav-editor-overlay-breadcrumbs.md b/Changelog/2026-10-04-nav-editor-overlay-breadcrumbs.md new file mode 100644 index 0000000..3199d43 --- /dev/null +++ b/Changelog/2026-10-04-nav-editor-overlay-breadcrumbs.md @@ -0,0 +1,98 @@ +# Nav editor expansion, waypoint overlay/HUD and breadcrumb tracker + +**Date:** 2026-10-04 +**Component:** RynthAi plugin (RynthSuite `Plugins/RynthCore.Plugin.RynthAi`) +**Version:** 0.6.29 → 0.6.30 + +## Summary + +The Navigation tab has been rebuilt around the editing features UtilityBelt-IT +added to VTank-style navs. On top of that come an on-screen waypoint overlay (HUD, +step labels, guide line) and a breadcrumb tracker that records where you have +walked and can turn that trail into a route. + +## Nav editor (Navigation tab) + +- **File row:** New (with confirmation), Save (opens Save As for an unsaved route), + Save As (sanitised file name, confirms before overwriting) and Reload. +- **Insert position:** new steps go at the End, Above the selection or Below it, + like UB-IT's "insert before". +- **Add steps:** Point (your position), Snap to path (inserts into the nearest + segment), Pause, Chat (adds the leading `/` automatically), Recall (pick from the + spell list or type an id), Portal (uses the selected object) and Point at the + selected object. +- **Edit steps:** Up, Down, Duplicate, Delete (or the Delete key), Set active, + Select nearest, Reverse route, and select All or None. +- **Step list:** multi-select with Ctrl or Shift, double-click a step to make it + active, and right-click for a context menu. +- **Step editor:** shown when one step is selected. Edit NS/EW/height, "Set to my + position", pause duration, chat text, recall spell and portal target ("Use + selected object"). +- Edits are copy-on-write, so the navigation engine never sees a half-edited + route. The active step follows its waypoint when steps are moved. + +## Recording (Record tab) + +- **Record mode** (UB-IT KeyStoreRecorder style): adds a Point every N yards while + you walk. +- **Portal capture:** when you use a portal while recording, it adds a Portal step + for the portal you selected in the last 20 seconds, followed by an optional + pause. +- **Saving:** recording autosaves every 10 steps and again when it stops (or when + the session ends). + +## Breadcrumb tracker + +- **Trail:** records your path at a set spacing. A portal trip or teleport starts + a new trail segment instead of drawing a line across the map. +- **Drawing:** the trail is drawn in the world with a fade, within a set range, + using Nav3D (or the ImGui fallback when Nav3D isn't available). +- **Trail → route:** turns the latest trail segment into a new Once route. +- **Backtrack route:** the same as Trail → route, but reversed, to walk back the + way you came. +- **Clear trail.** + +## Waypoint overlay and HUD + +- **Nav HUD window:** route name and type, recording state, current step and its + type, distance with an up/down height hint, a direction arrow relative to your + facing, the next step, remaining or loop distance, nav status and trail stats. +- **Step labels:** "#index Nyd" labels on the next N Point steps. +- **Guide line:** a line from you to the active waypoint, like UB-IT's yellow + breadcrumb line. + +## Display options (Display tab) + +- Route markers on or off, and how many markers to draw around the active step. +- Ring and line thickness, and height offset. +- Colours for rings, the active ring, lines, the guide line and the trail, plus + Reset colours. +- HUD visibility, including a "only while navigating" option. + +## Tools tab + +- **Simplify route:** Douglas–Peucker with an adjustable tolerance. Removes + redundant Point steps and keeps every action step. +- **Height repair:** "Select raw-height steps" and "Divide Z by 240". + +## Bug fix: waypoint height + +The Add-point button, the `/ra addnavpt` command and the web bridge saved the raw +world height instead of height ÷ 240 (the VTank .nav unit). Those waypoints drew +their markers far above the ground. All three now save the correct value. Use the +height repair tool to fix routes that were already saved. + +## New chat commands + +- `/ra navrec [on|off]`: toggle route recording. +- `/ra navhud [on|off]`: show or hide the nav HUD. +- `/ra navtrail [clear]`: show trail stats, or wipe the trail. + +## Files + +- New: `LegacyUi/NavOverlaySettings.cs`, `LegacyUi/NavRouteEditing.cs`, + `NavBreadcrumbTracker.cs`, `NavOverlayRenderer.cs` +- Rewritten: `LegacyUi/LegacyNavigationUi.cs` +- Modified: `LegacyUi/LegacyUiSettings.cs`, `LegacyUi/LegacyDashboardRenderer.cs`, + `LegacyUi/NavCoordinateHelper.cs`, `NavMarkerRenderer.cs`, `RynthAiPlugin.cs`, + `RynthAiCommands.cs`, `RynthCore.Plugin.RynthAi.csproj` diff --git a/Changelog/2026-10-04-nav-panel-scroll-fix.md b/Changelog/2026-10-04-nav-panel-scroll-fix.md new file mode 100644 index 0000000..c2f31e3 --- /dev/null +++ b/Changelog/2026-10-04-nav-panel-scroll-fix.md @@ -0,0 +1,27 @@ +# Engine — Nav panel waypoint list no longer jumps while editing + +**Date:** 2026-10-04 +**Branch:** `SK-local` +**Ships in:** next installer release (2026.10.4.8; previous 2026.10.4.7) + +## Fixed +- **Nav panel (Avalonia "Nav" tab, `UI/Panels/NavPanel.cs`): the waypoint list kept scrolling + back to the top, so points could not be selected or deleted.** + - Cause: the 1-second poll timer rebuilt the entire panel every tick, including a brand-new + waypoint `ScrollViewer`, so its scroll offset reset to 0 once a second. A rebuild that landed + between mouse press and release also dropped the click on a row or its X button. + - The waypoint `ScrollViewer` (and its row stack) is now created once and only refilled on + rebuild; the scroll offset is saved and re-applied (immediately and after layout). + - The poll only rebuilds when the plugin's nav JSON actually changed. + - The poll does not rebuild while the mouse is over the waypoint list; the change is picked up + on the first poll after the pointer leaves. + - Rebuilds caused by your own edits (optimistic local updates) always resync on the next poll, + so a command the plugin rejected can't leave stale state on screen. + +## Not changed +- The ImGui Navigation window in the RynthAi plugin (`LegacyNavigationUi`) did not have this + problem (ImGui keeps the list-box scroll position itself). + +## Build +- `RynthCore.Engine`: `dotnet build -c Release` and NativeAOT `dotnet publish -c Release` succeed; + no new warnings. The engine version is stamped by the release build (`-p:Version=yyyy.m.d.n`). diff --git a/Changelog/2026-10-04-panel-window-owner-thread-fixes.md b/Changelog/2026-10-04-panel-window-owner-thread-fixes.md new file mode 100644 index 0000000..be2f448 --- /dev/null +++ b/Changelog/2026-10-04-panel-window-owner-thread-fixes.md @@ -0,0 +1,42 @@ +# Floating panel windows: destroy on the owner thread, create on the game thread (2026-10-04) + +Ships in the next installer after 2026.10.4.15. + +## Destroy each panel window on the thread that owns it + +`LayeredWindow.Dispose` used to call `Win32Backend.PostDestroyWindow`, which always +posted the destroy to the game window. That was wrong for any panel not created on +the game thread (for example the login-time pop-out, created on the Avalonia UI +thread). The game thread's `DestroyWindow` then failed because it didn't own the +window, and the panel stayed on screen, frozen. The post was also dropped if the +game WndProc had already been unhooked at shutdown. + +- New `LayeredWindow.DestroyOnOwnerThread`: it looks up the window's owning thread with + `GetWindowThreadProcessId`. + - If the window no longer exists, it logs and returns. + - If the caller owns the window, it calls `DestroyWindow` inline. + - Otherwise it posts the new `WM_RYNTH_SELF_DESTROY` (0x8005) to the panel window itself. + The panel's own `StaticWndProc` then destroys it on its owner thread. This never + blocks the caller, and it works after the game WndProc is unhooked. +- `PostMessage` in `LayeredWindow` now sets the last error, so a failed post is logged + with the real error code. +- Removed `Win32Backend.PostDestroyWindow` and its `WM_RYNTH_DESTROY_HWND` (0x8003) + handler; 0x8003 is reserved and not reused. The shutdown sweep + (`WM_RYNTH_SWEEP_PANELS`) remains as a backstop for panels that were never disposed. + +## Hold the login-time pop-out until panels can be created on the game thread + +Floating panels saved as popped out are restored when `LoginComplete` fires. That can +happen before the engine has found and subclassed the game window, so +`FloatingPanelHost` took its legacy path and created the window on the Avalonia UI +thread. That path brings back the Win11 `WS_EX_NOACTIVATE` click-drop race and the +cross-thread destroy problem above. + +- New `Win32Backend.CanRunOnGameThread`: true once the game window is known and its + WndProc is subclassed, which is what `RunOnGameThread` needs. The window handle + alone isn't enough. +- `AvaloniaOverlay.RestoreFloatingPanels` now polls every 200 ms on the UI thread until + `CanRunOnGameThread` is true, then restores. It logs once when it starts holding and + again when it releases. +- After 60 s it restores anyway on the legacy path and logs a warning line, so the panels + are not lost on a client that is never hooked. diff --git a/Changelog/2026-10-04-pet-refill-loop-fix.md b/Changelog/2026-10-04-pet-refill-loop-fix.md new file mode 100644 index 0000000..17de9bd --- /dev/null +++ b/Changelog/2026-10-04-pet-refill-loop-fix.md @@ -0,0 +1,52 @@ +# Pet essence refill loop fix — RynthAi 0.6.28 + engine + +**Date:** 2026-10-04 +**Components:** RynthCore.Engine (property caches), RynthCore.Plugin.RynthAi 0.6.27 → 0.6.28 + +## Problem + +SilentStorm got stuck refilling the same pet essence (0x9757B329) over and over. The log +(`RynthCore.9568.log.old`) showed `Pet: refilling essence … with spirit …` about every 7 s, +and every 30 s once cooldowns kicked in. Each attempt used an Encapsulated Spirit on the essence. +The server switches the player to peace mode and plays the clap animation for every refill, +so the character kept dropping out of combat. + +## Root cause + +- `PetManager` decides whether an essence is empty by reading its `Structure` (charges) through + `TryGetObjectIntProperty`. The plugin pump runs off the main thread, so that read was + served **only** from the appraisal cache. That cache is a snapshot from the last time the item was ID'd. +- When the server refills an essence it sends a `PublicUpdatePropertyInt(Structure = MaxStructure)`. + The engine stored that in the property-update cache, but the off-thread read never consulted + that cache, and the appraisal snapshot was never patched. So the essence kept reading 0 charges. +- The server's reply ("You add the spirit to the essence." / "This essence is already full.") + sent `PetManager` back to Idle without recording anything. On the next tick it read 0 again + and issued another refill. + +## Fix + +### Engine +- `PropertyUpdateHooks.CacheInt` / `CacheBool` now also patch the appraisal cache entry for that + object, if one exists (`AppraisalHooks.PatchCachedInt` / `PatchCachedBool`). Off-thread reads + now see live server updates (Structure after a refill or summon, etc.) instead of the last ID's value. +- `ClientObjectHooks.TryGetObjectIntProperty`: off the main thread, an appraisal-cache miss now + falls back to the property-update cache (a thread-safe managed dictionary) instead of failing. + +### RynthAi plugin (also protects against older engines) +- The server's success and already-full replies now mark the essence as confirmed full for up to 30 min. + While that mark is set, a stale 0-charge read is ignored and the essence is used for summoning. + The mark clears as soon as a summon reports "not enough charges". +- After a confirmed refill the plugin requests a fresh ID of the essence, so the cached charges and the + ILT pet roster agree. +- Loop guard: once an essence has been refilled twice within 2 min and still reads empty, it + is parked for 5 min with a log line, rather than burning more spirits. +- New log lines: `Pet: refill complete (essence …, server confirmed).`, + `Pet: essence … is already full; charge read was stale.`, and the parking message. + +## Files +- `RynthCore/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs` +- `RynthCore/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs` +- `RynthCore/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs` +- `RynthSuite/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs` +- `RynthSuite/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj` (0.6.28) +- `RynthSuite/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs` (VersionPointer 0.6.28) diff --git a/Changelog/2026-10-04-pet-scan-type-detection.md b/Changelog/2026-10-04-pet-scan-type-detection.md new file mode 100644 index 0000000..405155b --- /dev/null +++ b/Changelog/2026-10-04-pet-scan-type-detection.md @@ -0,0 +1,44 @@ +# Pet scan: detect pets by type, not by "Essence" in the name + +**Date:** 2026-10-04 +**Components:** RynthAi plugin 0.6.26 (RynthSuite), RynthCore Engine / PluginSdk (next installer, 2026.10.4.19) + +## Problem + +The ILT Hub **Pet** tab (roster, **Scan pack**, heal-pet lookup, Mini Remote pet line) counted +any carried item whose name ended in ` Essence` as a combat pet. Augmentation gems and other +non-pet items with that suffix (for example "Jibril's Essence") showed up in the roster and got +appraised by Scan pack. + +## Fix + +### RynthAi — `IltHub/IltPets.cs` +- New `IsPetDevice(WorldObject)` decides by item type: + - **Never pets:** Encapsulated Spirit, the charm block (78780030–78780089), capture + devices (78780001–78780012) and the summoned combat pet creature block (787802001–787802072). + - **Pets:** + - the ACECustom combat essence WCID block (787801001–787801072); + - the summoning-gem icon underlay (DID 0x06007420), which needs no appraisal; + - `UseRequiresSkill` / `UseRequiresSkillSpec` = Summoning (54); + - ACECustom `BondLevel` (9053) > 0 or `PotencyStored` (9056) present. + - **Name hints only nominate items.** A name ending in " Essence", Healing Buddy / Dule box, + stamina buddy/crate/pet, or cosmetic/plush/display pet only makes an item a candidate. + It counts as a pet once it shows charges (`MaxStructure` > 0), matching UtilityBelt's pet scan. +- `ClassifyKind` now requires `IsPetDevice`. After that, naming picks the type: heal naming + → Healing, cosmetic naming → Cosmetic, otherwise Combat. Manual re-types ("Add sel." / + right-click) and the ticked heal pet still win. +- **Scan pack** appraises every confirmed pet and also any un-appraised pet-named candidate, + so its type can be confirmed or ruled out. The chat line reports both counts. The 2 s + background trickle also appraises candidates, two per scan. + +### Engine / SDK +- `ClientObjectHooks.TryGetObjectDataIdProperty` now serves `IconOverlay` (50, PWD+20) and + `IconUnderlay` (52, PWD+24) as well as `Icon` (8). This is the same network-populated + PublicWeenieDesc read, so it works on never-appraised pack items. No API version change: + older engines just return false for 50/52, and the plugin falls back to the appraisal-based + signals. + +## Notes +- Without the new engine, a real pet whose WCID is outside the essence block appears once its + appraisal lands (via Scan pack or the background trickle) instead of right away. +- Versions: RynthAi `0.6.25` → `0.6.26`. diff --git a/Changelog/2026-10-04-plugin-overlay-windows.md b/Changelog/2026-10-04-plugin-overlay-windows.md new file mode 100644 index 0000000..a5ca6be --- /dev/null +++ b/Changelog/2026-10-04-plugin-overlay-windows.md @@ -0,0 +1,31 @@ +# Engine — plugin overlay windows while the ImGui shell is off + +**Date:** 2026-10-04 +**Branch:** `SK-local` +**Ships in:** installer 2026.10.4.9 (previous 2026.10.4.8) + +## Problem +`EngineSettings.EnableImGuiShell` is hard-off unless the developer env var +`RYNTHCORE_FORCE_IMGUI=1` is set. `EngineFrameController.RunImGuiFrame` skipped both +`RynthCoreShell.Render` and `PluginManager.RenderAll`, so any plugin window without an Avalonia +panel could never show. That included RynthAi's ILT Hub (log: the Hub was created and the server +features came back, but no window) and its Item Info settings window. + +## Added +- **Optional plugin export `void RynthPluginRenderOverlay()`** (`PluginContract.cs`, + `PluginLoader.cs`, `LoadedPlugin.RenderOverlay`). With the ImGui shell off, the engine calls it + every frame through the new `PluginManager.RenderOverlayAll()`. A plugin draws only its extra + windows there, beside the Avalonia UI. Plugins without the export are unaffected. Their full ImGui + UIs stay hidden, so nothing duplicates an Avalonia panel. The old ImGui bar stays hidden too. +- **Failure isolation:** if `RenderOverlay` throws, only that plugin's overlay windows are switched + off for the session. The plugin is **not** marked `Failed`, so its tick, automation and Avalonia + panels keep running. (`RenderAll` keeps its old behaviour.) +- **engine.json `"EnablePluginOverlayWindows"`** (default `true`) to hide the overlay windows. + `EngineSettings.Save` writes it, and the launcher's `EngineJsonStore` preserves it. + The windows need `EnableImGuiBackend` (default `true`). +- Same not-in-world guard as `RenderAll` (no drawing between logoff and the next login complete). + +## Build +- `RynthCore.Engine` Release build succeeds (no new warnings). Shipped with RynthAi 0.6.15, which + exports `RynthPluginRenderOverlay` (ILT Hub + Item Info windows). +- Not yet verified in game. diff --git a/Changelog/2026-10-04-plugin-render-snapshot-fix-and-imgui-diagnostics.md b/Changelog/2026-10-04-plugin-render-snapshot-fix-and-imgui-diagnostics.md new file mode 100644 index 0000000..e8b2b20 --- /dev/null +++ b/Changelog/2026-10-04-plugin-render-snapshot-fix-and-imgui-diagnostics.md @@ -0,0 +1,34 @@ +# Plugin render snapshot fix and ImGui pipeline diagnostics (2026-10-04) + +Ships in installer 2026.10.4.15. + +## Fix: plugin overlay windows never drew (ILT Hub not showing) + +`PluginManager.RenderAll` and `RenderOverlayAll` iterate `_pluginsRenderSnapshot`, a +copy of the plugin list published by `PublishPluginsRenderSnapshot()`. Since the aelrynth +2026.9.27.2 snapshot port (commit 4ddbb52e), the publish call that belonged at the end of +`LoadPluginsFromDisk()` had landed after the `return` in `TryGetCanonicalPath()`, where it +could never run. The only publish that ran was in `UnloadAllPlugins()`, which published an +empty list. The result was that every plugin's ImGui render and overlay callbacks were +skipped, so windows like the RynthAi ILT Hub never appeared even though `hub show` worked. + +- `LoadPluginsFromDisk()` now publishes the snapshot after loading and logs the plugin count. +- The unreachable call has been removed. +- `RynthCore.Engine.csproj` now treats CS0162 (unreachable code) as a build error, so a + misplaced statement like this one fails the build. + +## Diagnostics: per-frame ImGui pipeline + +All of these lines appear in the normal log at Info, and each is written once (or when its value changes): + +- `reached ImGui gate (EnableImGuiBackend, EnableImGuiShell, EnablePluginOverlayWindows)`. +- ImGui init: success, or an Error naming the failing step (EnsureCore, Win32Backend.Init, + DX9Backend.InitImGui), and an Error if frames are skipped because init failed. +- `first ImGui frame started` with the display size, and `first deferred ImGui draw submitted`. +- Which branch the frame took (shell, overlay or none), logged when it changes. +- `RenderOverlayAll`: waiting for login, then `login seen, N of M plugin(s) will draw overlay windows` + with each plugin's state (overlay / no-overlay, not-init, failed). +- A heartbeat every 30 s: frames completed, draws submitted, last-frame draw lists and vertices, + overlay calls, login seen, overlay plugin count. +- Engine-frame and ImGui-frame exceptions: the first one is logged as an Error with the full exception, + then a count every 30 s instead of one line per frame. diff --git a/Changelog/2026-10-04-pwd-int-snapshot-and-merge-results.md b/Changelog/2026-10-04-pwd-int-snapshot-and-merge-results.md new file mode 100644 index 0000000..546c356 --- /dev/null +++ b/Changelog/2026-10-04-pwd-int-snapshot-and-merge-results.md @@ -0,0 +1,54 @@ +# 2026-10-04 — PublicWeenieDesc int snapshot + merge-stack results (API v68) + +## Problem + +AutoStack failed almost every merge (one session: 515 attempts / 514 failures; +the day: 1,521 / 1,515 — mostly Prismatic Tapers and Diamond Scarabs). + +* The RynthAi update loop runs on the plugin pump thread, not AC's main thread. +* Since audit finding #24 (no live AC memory reads off-thread), + `TryGetObjectIntProperty` refused stack size / max stack size off-thread and + had no snapshot to fall back on, so every stack read as "unknown" → 1. +* The engine's main-thread merge then read the *real* counts, found the target + full and silently skipped it (logged only at Verbose). RynthAi waited its 10 s + grace window and logged a failure — forever, for the same pairs. +* The same bad count fed AutoCram amounts, missile-crafting head/shaft counts + and ExpressionEngine item-count expressions. + +## Fix + +### PublicWeenieDesc int snapshot (`ClientObjectHooks`) + +* The 100 ms main-thread position walk (`PrefetchPositions` → + `CapturePositionForId`) now also captures, per object, the PWD fields: + container (+28), wielder (+32), valid locations (+40), location (+44), + items capacity (+48), containers capacity (+52), stack size (+96), + max stack size (+100) and material (+148). +* One `VirtualQuery` range check per object guards the whole field block; the + walk stays allocation-free (struct values in pre-sized dictionaries). +* The snapshot is double-buffered and swapped together with the weenie-pointer + buffers under `_weeniePtrSwapLock`, so readers always see one coherent frame. +* Off-thread reads route to the snapshot: + * `TryGetObjectIntProperty` for STypes 6, 7, 9, 10, 11, 12, 131. + Stack size / max stack of `<= 0` still prefer the appraisal cache. + * `TryReadPwdInt32` (previously returned `false` off-thread). + * `TryGetObjectOwnershipInfo` / `TryGetObjectWielderInfo` (container, + wielder, location). +* Main-thread reads are unchanged (live PWD reads). +* A one-time `PWD int snapshot warm` log line confirms the snapshot is serving. + +### Merge-stack results (`MergeStackResults`, API v68) + +* New `MergeStackResults` table keyed by (source, target) records the outcome + of every `MergeStackInternal` exit: `Queued`, `Sent` (with amount), + `TargetFull`, `Failed`, `QueueFull`. +* New API slot `GetMergeStackResultFn` (appended; `PluginContractVersion` 68): + returns the latest status plus amount and age in milliseconds. +* SDK: `RynthCoreHost.CurrentApiVersion = 68`, `HasGetMergeStackResult`, + `GetMergeStackResult(...)` and `RynthCoreHost.MergeStackStatus` constants. + Returns `None` on older engines, so plugins degrade to their old behaviour. + +## Compatibility + +* ABI: append-only; plugins built against v66/v67 keep working. +* No behaviour change on the main thread. diff --git a/Changelog/2026-10-04-sk-local-unified.md b/Changelog/2026-10-04-sk-local-unified.md new file mode 100644 index 0000000..6973b36 --- /dev/null +++ b/Changelog/2026-10-04-sk-local-unified.md @@ -0,0 +1,54 @@ +# SK-local unified branch — full installer + SK logging + ub-Rythai component + +**Date:** 2026-10-04 +**Branch:** `SK-local` (now contains `main`, `feat/full-installer`, `fix/tmds-dbus-advisory`, +`SK`, and PR #2 docs) + +## Branch integration +- `feat/full-installer` merged into `SK-local`: aelrynth snapshot port, Loader, full installer + (installers 2026.10.4.1–2026.10.4.6), update checker, crash relaunch / stuck-client handling, + per-PID logs, tmds.dbus advisory fix. +- `origin/main` (PR #2 Hub playbook) merged; SK-local's newer playbook revision kept. + +## Kept from SK-local +- **Engine logging level** (`EngineLogLevel`, `EntryPoint.ShouldLog`, `engine.json` `LoggingLevel`) + combined with full-installer's tagged WRN/ERR lines, `RynthLog.LastIssue` and per-PID log files. + `EngineSettings.Save()` preserves the launcher-chosen `LoggingLevel`. +- **Launcher:** "Inject all running AC sessions" toggle and Logging level dropdown, alongside the new + stagger / crash-relaunch / stuck-client / window-title options. The level is written to + `engine.json` through `EngineJsonStore.SetString` (new; preserves every other key). +- **PluginManager:** basename / canonical-path de-duplication of plugin DLLs. +- `TryPreloadMinHookForEarlyInit` before multi-client init. + +## Taken from full-installer +- Injector (unified log, launch command), installer scripts, release workflow, BUILD.md. +- Solution adds `RynthCore.DesktopLog` and `RynthCore.Loader`; the stale + `Plugins\RynthCore.Plugin.RynthAi` stub is no longer in the solution (the real plugin is in RynthSuite). +- The Desktop rolling log (`DesktopRollingLog`) is superseded by the unified/per-PID logs. + +## Fixed +- Auto-merge had left SK-era fragments in full-installer's scripts: an undefined `$PluginProjects` + check in `Build-Installer.ps1` (would abort every build), a duplicate bundle-archive block, the + `RynthBundle-Setup` output name in `RynthCore.iss`, and `-SkipUbRythai` / `RynthBundle-Setup-*.exe` + in the release workflow. All restored to full-installer's working versions. +- `Build-Release-All.ps1` now forwards only parameters `Build-Installer.ps1` declares + (`-Version`, `-RynthSuiteRoot`, `-IsccPath`). +- Engine / Injector `.csproj` restored to full-installer: SK's cimgui de-duplication deleted the plain + `cimgui.dll` that `Build-Installer.ps1` requires in `Runtime\` (and that plugins import by name), and + the DesktopLog reference was no longer used there. The launcher keeps DesktopLog (host diagnostics). + +## Added +- **ub-Rythai 3.1.10** as an optional experimental installer component + (`experimental\ubrythai` → `\UbRythai\RynthCore.Plugin.UbRythai.dll`, registered with the + launcher like the other experimental plugins). `RynthCore.iss` uses an `ExperimentalCount` constant + instead of hard-coded `0 to 4` loops. + +## Repository hygiene +- Stopped tracking SK-era build output: `installer/_toolpublish/` (published Loot/Monster Editor + binaries) and `build_out/RynthBundle-Setup-0.4.7.exe`. Both are git-ignored now; files remain on disk + and in history. + +## Build +- Engine, Launcher, Injector and Loader build with 0 errors on the merged branch. +- No installer was compiled for this entry; the next installer build should use + `installer\Build-Installer.ps1 -Version 2026.10.4.7` (previous: 2026.10.4.6). diff --git a/Changelog/2026-10-04-tmds-dbus-advisory.md b/Changelog/2026-10-04-tmds-dbus-advisory.md new file mode 100644 index 0000000..0845e7c --- /dev/null +++ b/Changelog/2026-10-04-tmds-dbus-advisory.md @@ -0,0 +1,26 @@ +# Security: pin Tmds.DBus.Protocol 0.21.3 (NU1903) + +**Date:** 2026-10-04 +**Branch:** `fix/tmds-dbus-advisory` (based on `main`; not merged) +**Advisory:** NU1903 / [GHSA-xrw6-gwf8-vvr9](https://github.com/advisories/GHSA-xrw6-gwf8-vvr9) (high severity) + +## Problem +Avalonia 11.x (through `Avalonia.FreeDesktop`) depends on `Tmds.DBus.Protocol` 0.20.x, which has a +known vulnerability. NuGet restore reported NU1903 for every project that references Avalonia. + +## Fix +A direct `PackageReference` to `Tmds.DBus.Protocol` **0.21.3** overrides the vulnerable transitive version: + +- `src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj` +- `src/RynthCore.Engine/RynthCore.Engine.csproj` + +The same pin is in RynthSuite (`Tools/RynthCore.LootEditor`, `Tools/RynthCore.MonsterEditor`) on `feat/ilt-hub`. + +## Verification +- `dotnet restore` / `dotnet list package --include-transitive` resolve `Tmds.DBus.Protocol 0.21.3` in all projects. +- No NU190x warnings remain. +- RynthAi 0.5.2 builds and publishes (NativeAOT) against this branch. + +## Notes +- No runtime behaviour change on Windows. D-Bus is only used by Avalonia on Linux desktops. +- Drop the explicit pin once Avalonia ships a release that depends on a fixed version. 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-chat-standard-filters.md b/Changelog/2026-10-05-chat-standard-filters.md new file mode 100644 index 0000000..9a8e639 --- /dev/null +++ b/Changelog/2026-10-05-chat-standard-filters.md @@ -0,0 +1,70 @@ +# RynthChat: standard (canned) filters and easier custom rules + +**Date:** 2026-10-05 +**Component:** RynthCore Engine — RynthChat filters panel (`UI/Panels/RynthChatFiltersPanel.cs`) + +## Summary + +The Chat Filters window used to be a list of raw regex rows. It now has a +**Standard filters** page of ready-made tick-boxes, modelled on UtilityBelt-IT's +chat filter categories. Custom rules now work with plain text, so you no longer +need to know regex. + +## Standard filters page + +38 canned filters in 6 groups. Each group has **All on** / **All off** buttons and +an "n/total on" count, and a search box at the top narrows the list. + +| Group | Filters | +|---------|---------| +| Combat | Your attacks evaded, You evade attacks, Damage you deal, Damage you take, Your spells resisted, You resist spells, Not-a-PK failures, Dirty Fighting procs, Monster death messages | +| Casting | Your spell words, Others' spell words, Spell fizzles, Component usage, Your buff casts, Buffs others cast on you, Spell expiry (keeps Brilliance / Prodigal / Spectral) | +| Items | Healing kit success / failure, Salvage results / failures, Aura of the Craftsman, Mana stone usage, Periodic healing ticks | +| Social | Trade / buff bot spam (-t- / -b-), Failed assess on you, Kill task complete, General / Trade / LFG / Roleplay / Society channels | +| NPCs | Master Arbitrator (Colosseum) | +| Pets | Pet hits, Pet attacks evaded, Pet damage taken, Pet died, Pet recall blocked, Pet heal overflow | + +- **Tick a box** to hide those lines. **Type a tab name** beside it to move them + to that tab instead; the tab is created automatically, like custom rules do. +- **Hover a filter** to see what it catches and an example line. +- **Player chat is protected:** filters on system text skip the Chat and Channels + tabs, so a player typing the same words in Local is never hidden. +- **Spell words:** ACE sends incantations as chat type 0x11, which RynthChat files + under Combat. "Your spell words" therefore never hides real Local speech. + +## Custom rules page + +- **Match modes:** each rule has a click-to-cycle mode button: **Contains**, + **Starts with**, **Ends with** (plain text, case-insensitive) or **Regex**. + - New rules default to Contains. + - Plain-text modes match the message itself, so the timestamp prefix can't + break "Starts with". + - Regex mode keeps the old behaviour (matches "hh:mm:ss Sender: message"), so + existing rules load and behave exactly as before. +- **Order:** first match wins, and ▲▼ reorder rules. Custom rules are checked + before the standard filters, so a custom rule can override a preset. + +## Line tester + +Paste any chat line at the bottom of the window to see which custom rule or +standard filter catches it, and whether it is hidden or moved. + +- **"as System / Combat / …":** picks the channel the line is treated as arriving on. +- **Not filtered:** if nothing catches the line, the tester names the standard + filter you'd need to tick. +- **Make rule:** turns the test text into a Contains rule, ready to trim down. + +## Settings + +Saved in `%APPDATA%\RynthCore\rynthchat_settings.json`: + +- `filters[].mode`: match mode. When missing, the rule is treated as Regex. +- `presets[]`: `{ id, enabled, tab }`, written only for filters you changed. +- Deleting a custom tab also turns off any standard filter that moved lines to it. + +## Files + +- New: `src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs` +- Rewritten: `src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs` +- Modified: `src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs` (match modes, + preset routing, tester, persistence) diff --git a/Changelog/2026-10-05-chat-translation.md b/Changelog/2026-10-05-chat-translation.md new file mode 100644 index 0000000..d5b8a62 --- /dev/null +++ b/Changelog/2026-10-05-chat-translation.md @@ -0,0 +1,139 @@ +# Chat auto-translation (inbound and outbound) + +**Date:** 2026-10-05 +**Component:** RynthAi plugin (RynthSuite `Plugins/RynthCore.Plugin.RynthAi`) +**Version:** 0.6.31 → 0.6.32 + +## What's new + +RynthAi can translate chat automatically, modelled on UB-IT's Chat Translate tool +but with a choice of translation service. + +- **Incoming:** lines on the channels you tick are translated into your receive + language. Each translation is written back to chat as + `[Translate] [General] Bob (es): Hello everyone`, in the same colour and tab as + the original. It shows in AC's chat window and in RynthChat (the RynthAi + dashboard chat and the RynthChat panel). Lines already in your language are + left alone. +- **Outgoing:** what you type on the ticked channels is held back, translated into + your send language and sent with the same command (`/f`, `/t Bob,`, `/cg`, ...). + This works from AC's chat bar, RynthChat and meta chat commands. Start a line + with `\` to send it untranslated. If the translation fails, the original is sent + instead (this can be switched off). +- **Channels:** each of these can be ticked separately to listen to, send on, or + both: Local, Tell, Fellowship, Allegiance, Patron, Vassals, Covassals, Monarch, + General, Trade, LFG, Roleplay, Society and Olthoi. +- **Translation services:** + - **Google Cloud Translation** (default): needs an API key; 500k characters a + month are free. + - **DeepL:** Free-plan keys ending in `:fx` are sent to the free endpoint + automatically. + - **LibreTranslate:** your own server URL, or the public server with a key. + +### Chat Translate window + +Opened with `/ra translate window` or the Mini Remote's "Window" button. It has: + +- **Header:** Enabled, Incoming and Outgoing switches, counters (translations + done, characters used, requests queued) and the last error. +- **Language row:** Receive, a swap button (<->), Send, and Default (puts the send + language back to the default). +- **Log:** every translation, both directions. Hover a line to see the original. +- **Compose:** pick a channel (and a tell name), type in any language, then + Translate & send, or Preview only. +- **Channels:** a Listen and a Send checkbox for every channel, plus all / none / + defaults buttons. +- **Settings:** the same page as Advanced Settings > Translate. + +### Settings (Advanced Settings > Translate) + +- Service, API key (hidden unless "Show" is ticked) and endpoint. +- **Receive (my language)**, the language incoming chat is in (auto-detect by + default), and the **Default send language**. Every login starts with the + default send language. +- Skip my own lines, write incoming translations to chat, show what I typed after + sending, send the original on failure, the send-untranslated prefix, the minimum + time between requests (750 ms default) and the log size. +- A Test box that translates into the current send language. + +### Mini Remote (hub) + +A new **Translate** row has an on/off box, Receive and Send pickers with a swap +button, a "def" button to go back to the default send language, and a Window +button. It can be hidden from the Mini Remote's right-click menu. + +### Commands + +`/ra translate` (or `/ra tr`): + +- `on` / `off` +- `in [on|off]` and `out [on|off]` +- `window` +- `send `, `recv `, `default ` +- `swap` +- `reset` (send language back to the default) +- `test ` +- With no argument it prints the status. + +## How it works + +- `ChatTranslator` runs on the plugin pump thread. + - Chat hooks and the UI only add work to a queue. + - One HTTP request runs at a time, spaced by the minimum interval. Outgoing + lines go ahead of incoming ones. + - Incoming lines are de-duplicated for 5 s, and the incoming queue is capped at + 40. +- **Incoming parsing:** + - Understands `Name says, "..."`, `Name says on the X channel, "..."`, + `Name tells you, "..."` and the `[Channel]` prefix. + - Removes tell-link markup. + - Expands AC's `` Unicode escapes before translating. + - The channel comes from the prefix, the "on the X channel" text, the chat + colour, or words such as "patron" and "vassal". + - Your own lines and the translator's `[Translate]` echoes are skipped. +- **Outgoing:** + - The translated text is resent through the chat parser with the original + command prefix. + - A short-lived "resend" set lets that line pass back through `OnChatBarEnter` + without being translated again. + - Characters above U+00FF are sent as `` escapes. Latin-1 letters such + as ä and ñ stay as they are. +- **Chat echoes:** `Host.WriteToChat` drops calls made within 100 ms of each other + off AC's main thread, so echoes are queued 150 ms apart and retried when one is + dropped. +- **HTTP:** a single `HttpClient` with a 15 s timeout. Requests are built with + `Utf8JsonWriter` and responses read with `JsonDocument`, which is safe for + NativeAOT (the publish finishes with no trim or AOT warnings). +- **Settings file:** `RynthAi\translate.json` is shared by every character. It is + saved every 2 s, and only when something changed. + +## Notes + +- The API key is stored in plain text in `translate.json`. +- AC's chat font can't draw CJK, Thai or Arabic script. Translations into those + languages show as boxes in AC chat. +- Listening to Local also translates NPC speech, which uses more of your quota. + Local is off by default. +- The Advanced Settings page list gained "Translate" before "Diagnostics". + +## Files + +- New: + - `Translate/ChatTranslator.cs` + - `Translate/TranslateClient.cs` + - `Translate/TranslateSettings.cs` + - `Translate/TranslateChannels.cs` + - `Translate/TranslateLanguages.cs` + - `Translate/AcChatEscapes.cs` + - `Translate/TranslateUi.cs` +- Modified: + - `RynthAiPlugin.cs` + - `RynthAiCommands.cs` + - `Huds/MiniRemoteHud.cs` + - `Huds/HudController.cs` + - `Huds/HudState.cs` + - `LegacyUi/LegacyAdvancedSettingsUi.cs` + - `LegacyUi/LegacyDashboardRenderer.cs` + - `LegacyUi/LegacyUiSettings.cs` + - `LegacyUi/RynthAiJsonContext.cs` + - `RynthCore.Plugin.RynthAi.csproj` 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-installer-2026.10.4.21-release.md b/Changelog/2026-10-05-installer-2026.10.4.21-release.md new file mode 100644 index 0000000..bf64393 --- /dev/null +++ b/Changelog/2026-10-05-installer-2026.10.4.21-release.md @@ -0,0 +1,46 @@ +# Installer 2026.10.4.21 release (2026-10-05) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.21.exe` +- SHA-256: `5C18E6CEFE3A2A0FA60FEB542FEFB8934DB46E078291840F1571C97AEC0F46E7` +- Deploy package: `installer/Output/RynthCore-2026.10.4.21-deploy.zip` +- Previous release: 2026.10.4.20 (archived in `installer/previous-release/`) +- RynthAi: 0.6.31 + +## Changes + +- **Pet refill loop fix** (RynthAi 0.6.28 + engine). SilentStorm kept re-using Encapsulated + Spirits on a full essence, because the engine served a stale empty charge count. Property + updates now patch the appraisal cache, and the plugin trusts the server's "full" reply and + parks an essence after repeated refills. See `2026-10-04-pet-refill-loop-fix.md`. +- **Item info on click** (RynthAi 0.6.29). Optionally print weapon and armour info to chat on a + left or right click, in the same multi-line layout as pets. See + `2026-10-04-item-info-click-and-pet-layout.md`. +- **Nav editor, waypoint overlay and breadcrumbs** (RynthAi 0.6.30). + - **Editor:** UB-IT-style editing (insert above/below, multi-select, duplicate, reverse, snap + to path, pause / chat / recall / portal steps, Save As), plus route recording with portal + capture and a Simplify tool. + - **Overlay:** a Nav HUD (distance, direction arrow, next step), step labels and a guide line. + - **Breadcrumbs:** a trail you can turn into a route or a backtrack route. + - **Height fix:** waypoints added from the UI, `/ra addnavpt` and the bridge were saved at + the wrong height; a repair tool fixes saved routes. + - See `2026-10-04-nav-editor-overlay-breadcrumbs.md`. +- **Mini Remote target and summon** (RynthAi 0.6.31). The Mini Remote shows the creature combat + is attacking (name, distance, health bar) and your summon's health and time left. See + `2026-10-05-mini-remote-target-and-summon.md`. +- **Chat standard filters** (engine). + - **Standard filters:** the Chat Filters window has a page of 38 canned UB-IT-style filters + (combat, casting, items, social, NPC, pets). Tick one to hide those lines, or name a tab to + move them there. + - **Custom rules:** now support plain-text Contains / Starts with / Ends with as well as regex. + - **Line tester:** shows which filter catches a pasted line. + - See `2026-10-05-chat-standard-filters.md`. + +## Upgrade notes + +- **Settings:** existing chat filter rules load unchanged (they stay in Regex mode). All + standard filters start off. +- **Mini Remote polling:** while it is open, the Mini Remote polls the summon's health every + 3 s and re-queries the combat target afterwards. If mobs start getting blacklisted while + the summon row is showing, report it. +- **Logging:** `engine.json` may still be at `Trace` from earlier debugging; set it back to + `Info` in the launcher. diff --git a/Changelog/2026-10-05-installer-2026.10.4.22-release.md b/Changelog/2026-10-05-installer-2026.10.4.22-release.md new file mode 100644 index 0000000..114c9df --- /dev/null +++ b/Changelog/2026-10-05-installer-2026.10.4.22-release.md @@ -0,0 +1,35 @@ +# Installer 2026.10.4.22 release (2026-10-05) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.22.exe` +- SHA-256: `9E29C47918DFAE7CBCF6DEF51386E55D9ECB9B7D410D9E2FEA5D29CE86911379` +- Deploy package: `installer/Output/RynthCore-2026.10.4.22-deploy.zip` +- Previous release: 2026.10.4.21 (archived in `installer/previous-release/`) +- RynthAi: 0.6.32 + +## Changes + +- **Chat auto-translation** (RynthAi 0.6.32). + - **Incoming:** chat on the channels you tick is translated into your receive language and + written back to AC chat and RynthChat as `[Translate] [Channel] Name (lang): text`. + - **Outgoing:** lines you type on the ticked channels are translated into your send language + before they go out. Start a line with `\` to send it untranslated. + - **Channels:** all 14 (Local, Tell, Fellowship, the allegiance channels, General, Trade, + LFG, Roleplay, Society, Olthoi) can be ticked for listen and send separately. + - **Services:** Google Cloud Translation (default), DeepL or LibreTranslate. + - **Where to find it:** + - Chat Translate window: `/ra translate window` + - Settings: Advanced Settings > Translate, which includes the default send language + - Mini Remote: a new row for the receive and send languages, with a swap button + - See `2026-10-05-chat-translation.md`. + +## Upgrade notes + +- **Setup:** translation is off until you add an API key (Settings tab or Advanced Settings > + Translate) and tick Enabled. Outgoing translation also has its own switch, and is off by + default. +- **Settings file:** settings are shared by all characters in `RynthAi\translate.json`. The API + key is stored there in plain text. +- **Fonts:** AC's chat font can't draw CJK, Thai or Arabic script, so translations into those + languages show as boxes in chat. +- **Advanced Settings:** "Translate" was added just above "Diagnostics" in the page list. If + the window was left on Diagnostics, it opens on Translate once. 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-mini-remote-target-and-summon.md b/Changelog/2026-10-05-mini-remote-target-and-summon.md new file mode 100644 index 0000000..9a95cb6 --- /dev/null +++ b/Changelog/2026-10-05-mini-remote-target-and-summon.md @@ -0,0 +1,44 @@ +# Mini Remote: attack target and summon health / time left + +**Date:** 2026-10-05 +**Component:** RynthAi plugin (RynthSuite `Plugins/RynthCore.Plugin.RynthAi`) +**Version:** 0.6.30 → 0.6.31 + +## What's new + +The Mini Remote HUD has two new live rows. + +- **Target:** the creature combat is attacking, with its name, distance in yards + and a health bar (green, yellow or red). It reads "Target: none" when combat has + no target, and the bar shows "HP --" until the first health update arrives. +- **Summon:** while your pet is out, shows its name, a health bar and the time + left, with a countdown bar that turns yellow under 90 s and red under 30 s. A + "Healing" tag appears while the ILT Hub heal pet is working. When no pet is out, + the row shows the ILT Hub's next combat essence with Ready / Empty, as before. + +Both rows can be switched off from the Mini Remote's right-click menu ("Attack +target" and "Pet / summon"). + +## How it works + +- A new `CombatHudTracker` runs on the pump thread and publishes an immutable + snapshot for the HUD. It only runs while the Mini Remote and one of these rows + are shown. +- **Target:** comes from `CombatManager.activeTargetId`. Health uses the object + cache's health ratio, which the server already pushes during the fight. +- **Summon:** found as "<Player>'s <Pet>" in the landscape. + - **Time left:** the new pet is appraised once (up to 3 tries, 5 s apart), and + its `RemainingLifespan` (268) anchors a local countdown. `Lifespan` (267) sets + the bar's full length. + - **Fallback:** if the server never reports a lifespan, the row shows how long + the pet has been out instead. + - **Health:** polled with `QueryHealth` every 3 s. The server streams health for + only the most recently queried creature, so each pet poll is followed by a + re-query of the combat target (or your selected target). This keeps combat's + damage detection working. + +## Files + +- New: `Huds/CombatHudTracker.cs` +- Modified: `Huds/MiniRemoteHud.cs`, `Huds/HudController.cs`, `Huds/HudState.cs`, + `RynthAiPlugin.cs`, `RynthCore.Plugin.RynthAi.csproj` 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/Changelog/2026-10-06-release-2026.10.5.14-heartbeat-always-logged.md b/Changelog/2026-10-06-release-2026.10.5.14-heartbeat-always-logged.md new file mode 100644 index 0000000..01080f3 --- /dev/null +++ b/Changelog/2026-10-06-release-2026.10.5.14-heartbeat-always-logged.md @@ -0,0 +1,45 @@ +# RynthCore 2026.10.5.14 — engine heartbeat is always logged + +**Date:** 2026-10-06 +**Branch:** `fix/heartbeat-always-logged` (from `main` 143eaa9); deployed build is the +same fix cherry-picked onto `fix/restore-sk-features` (the 2026.10.5.13 line) +**Previous release:** 2026.10.5.13 (895a63a) +**Component:** `RynthCore.Engine` only (no plugin API change) + +## Problem + +The launcher killed healthy, in-world clients and relaunched them every few minutes +(Silentkelpie and Silentstorm, 2026-10-06 14:46 to 15:13; launcher log lines +`WEDGE: PID … killed - engine heartbeat silent for >120s while process alive`). + +- The launcher's wedge watchdog treats `RynthCore.<pid>.log` not being written for + 120 s as a dead engine and kills the process. +- The engine's once-a-second heartbeat line (`hb #N … fps= … login= …`) was written + through `RynthLog.Info`, which writes at the **General category's** level. +- With `LoggingLevel = Info` and `General = Trace` (launcher logging settings), the + heartbeat was emitted at Trace and filtered out by the global Info threshold, so the + log went quiet once a character was in-world and the watchdog fired. +- The launcher copies its own `LoggingLevel` into `engine.json` on every launch, so a + hand edit of `engine.json` only lasted until the next relaunch. +- Knock-on effect: relaunches landed while the killed character was still logged in on + the server, and the new client was booted to the end-of-session screen + (`LogOffCharacter(immediate=1)` from `gmEpilogueUI`) about 35 s after launch. + +## Fix + +- New `RynthLog.Heartbeat(string)`: writes unconditionally (every `LoggingLevel`, + including Off), tagged `[INF]`, like `RynthLog.Error` does for errors. +- `HeartbeatLogger` writes the `hb #` line through `RynthLog.Heartbeat`. +- No change to the line format, so every launcher's `WedgeHbRegex` still parses it. + +## Notes + +- The startup warning about categories above the global level stays; it still applies + to every other line. +- Workaround for older engines: set the launcher's global logging level to Trace, or + turn off auto-restart of wedged clients. + +## Files + +- `src/RynthCore.Engine/RynthLog.cs` — `Heartbeat` method. +- `src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs` — heartbeat uses it. diff --git a/Changelog/2026-10-06-upstream-snapshot-comparison.md b/Changelog/2026-10-06-upstream-snapshot-comparison.md new file mode 100644 index 0000000..c7696a1 --- /dev/null +++ b/Changelog/2026-10-06-upstream-snapshot-comparison.md @@ -0,0 +1,117 @@ +# Upstream snapshot comparison: rynth/RynthCore 2026.10.6.1 vs GitHub main + +Date: 2026-10-06 +Report only. Nothing has been merged or pushed. + +| Side | Ref | Commit | +|---|---|---| +| Upstream (aelrynth `rynth/RynthCore`) | `aelrynth/main` | `abf9146` Snapshot for release 2026.10.6.1 (internal 1cbe514) | +| GitHub (`BlankenshipG/RynthCore`) | `origin/main` | `143eaa9` feat(ui): nav route editing, progression, charms and chat presets | +| Common base | merge-base | `913a2a0` release 2026.10.5.20 | + +Upstream snapshot not on GitHub: `abf9146`, 93 files, +10168 / -597. + +GitHub commits not upstream. All three are in open rynth/RynthCore PR #2; PR #1 is superseded. +- `9709a39` install-aware paths, logging levels, item drag bridge +- `4be686e` plugin overlay windows and create-time identity seeds +- `143eaa9` nav route editing, progression, charms and chat presets + +## Policy for the next merge + +- **Keep everything we sent up:** + - logging levels and desktop log; + - item drag bridge; + - plugin overlay windows; + - progression, charms and chat presets; + - nav route editing; + - install-aware paths. +- **Bring down the new upstream items flagged below**, merge them in and test them. + +## FLAG: new upstream items to bring down, merge and test + +### New files (38): missing on GitHub +- **Flight recorder** (network capture ring): + - `Net/FlightCapture.cs`, `Net/FlightFormat.cs`, `Net/FlightRecorder.cs`, `Net/FlightRing.cs` + - `tools/FlightRecorderTests` +- **Video patch:** + - `D3D9/VideoPatch.cs`, `D3D9/VideoPatchPolicy.cs`, `ImGui/VideoPatchBanner.cs` + - `tools/VideoPatchTests` +- **Meta editor:** + - `ImGui/Panels/MetaFace.Editor.cs` + - `UI/Data/MetaEditing.cs`, `UI/Data/MetaLocation.cs`, `UI/Data/MetaRuleDto.cs` + - `tools/MetaEditTests` +- **Item count HUD:** + - `ImGui/Panels/ItemCountFace.cs` + - `UI/Data/ItemHudModel.cs`, `UI/Data/ItemHudStore.cs` + - `tools/ItemHudTests` +- **Mini remote:** `ImGui/Panels/MiniRemoteFace.cs`. +- **Engine settings:** + - `Plugins/EngineSettingsFile.cs`, `Plugins/PluginPathDedupe.cs` + - `tools/EngineSettingsTests` +- **Chat filters:** + - `UI/Data/ChatFilterPresets.cs`, `UI/Data/ChatRuleMatching.cs`, `UI/Data/ChatSettingsDto.cs` + - `tools/ChatFilterTests` +- **Panels:** `UI/PanelDestroyFallback.cs`, `tools/PanelWindowTests`. +- **Install paths:** `src/Shared/RynthInstallPaths.cs`, `tools/InstallPathsTests`. See the + overlaps below. + +### Upstream edits to files GitHub never changed (31): merge cleanly +- **Launcher:** `RynthUpdater.NavData`, `UsageStats`. +- **Compatibility:** + - `AcActionTrace`, `AcMainThreadQueue`, `BusyCountHooks`, `ClientActionGates` + - `GameTickHooks`, `HeartbeatLogger`, `InventoryModel`, `LoginLifecycleHooks` + - `RawPacketHooks`, `RynthCoreChatCommands`, `SmartBoxHooks` +- **D3D9:** `AcUiPassHook`, `Nav3DRenderInjector`. +- **ImGui:** + - `ImGuiBar`, `ImGuiPopOuts`, `MonsterHud` + - `MetaFace`, `MetaFace.Schedule`, `P1Faces`, `RynthNavFace` + - `UiDropTargets`, `RynthNavData` +- **Tools:** test project files, `PluginManifestTests/Program.cs`, `tools/pe_pattern.py`. + +### Edited on both sides (24): needs a hand merge (14 conflict in a trial merge) + +Conflicting: +- `RynthCore.App.Avalonia/LauncherDiag.cs`, `MainWindow.axaml.cs`, `RynthCore.App.Avalonia.csproj` +- `Engine/ImGui/EngineFrameController.cs` +- `Engine/ImGui/Panels/ChatFiltersFace.cs`, `Engine/ImGui/Panels/InventoryFace.cs` +- `Engine/LogPaths.cs`, `Engine/RynthCore.Engine.csproj` +- `Engine/UI/Data/ChatData.cs`, `Engine/UI/Data/MetaData.cs` +- `Injector/Program.cs`, `Loader/EntryPoint.cs` +- `StatusAgent/AgentConfig.cs`, `StatusAgent/RynthCore.StatusAgent.csproj` + +Auto-merged, but changed on both sides, so review them: +- `D3D9/EndSceneHook.cs`, `EngineLifecycle.cs`, `EntryPoint.cs` +- `ImGui/Win32Backend.cs` +- `Plugins/EngineSettings.cs`, `Plugins/PluginManager.cs` +- `UI/Data/SettingsData.cs`, `UI/LayeredWindow.cs` +- `Injector.csproj`, `Loader.csproj` + +## Overlaps to resolve when merging + +1. **Install paths: two copies of `RynthInstallPaths`.** GitHub has + `src/RynthCore.App/RynthInstallPaths.cs`; upstream has `src/Shared/RynthInstallPaths.cs`, + linked into several projects. The two differ by about 190 lines. Keep one and update the + links (App, Engine, Injector, Loader, StatusAgent, tests). +2. **Chat presets:** our `UI/Panels/RynthChatPresets.cs` against upstream's + `ChatFilterPresets` / `ChatRuleMatching` / `ChatSettingsDto`, which touch the same + `ChatData.cs` and `ChatFiltersFace.cs`. Review both side by side; don't keep two preset + systems. +3. **Panel destroy:** our posted-destroy fix (PR #2) against upstream's + `PanelDestroyFallback.cs`, both in `LayeredWindow.cs`. +4. **Logging:** our `LogSettings.cs` and logging levels against upstream's `LogPaths.cs` and + `EngineSettingsFile.cs` changes. + +## Suggested test pass after merging + +- New upstream tools: `ChatFilterTests`, `EngineSettingsTests`, `FlightRecorderTests`, + `InstallPathsTests`, `ItemHudTests`, `MetaEditTests`, `PanelWindowTests`, `VideoPatchTests`. +- Existing tools: `PluginManifestTests`, `StatusAgentTests`, `LauncherUpdateTests`, + `NavDataUpdateTests`, `UsageStatsTests`. +- NativeAOT Engine publish. +- In game: + - overlay windows and item drag; + - chat presets and filters; + - meta editor; + - item count HUD; + - video patch banner; + - logging level settings in the launcher. diff --git a/Changelog/2026-10-07-merge-main-into-QOL-items.md b/Changelog/2026-10-07-merge-main-into-QOL-items.md new file mode 100644 index 0000000..8e07510 --- /dev/null +++ b/Changelog/2026-10-07-merge-main-into-QOL-items.md @@ -0,0 +1,66 @@ +# QOL-items: main merged in, PR #10 conflicts resolved (plugin API 80) + +**Date:** 2026-10-07 +**Branch:** `QOL-items` ([PR #10](https://github.com/BlankenshipG/RynthCore/pull/10), into `main`) +**Merged:** `origin/main` 784ddf1 (engine 2026.10.5.16) into `QOL-items` f2bd3b2 +**Plugin API:** 80 (previous: 77 on `QOL-items`, 79 on `main`) + +## Why + +PR #10 could not merge: `main` took the 2026-10-05 evening upstream snapshot (913a2a0) and the +three commits that sent the SK features upstream (9709a39, 4be686e, 143eaa9), and both lines +edited the same 15 files. This merge brings `main` into `QOL-items` so the PR merges cleanly. +Nothing on `main` is rewritten. + +## Plugin API: GetMergeStackResult moves to v80 + +Both lines used API v77 for different table fields: +- `QOL-items`: v77 = `GetMergeStackResultFn`. +- `main` (upstream): v77 = `GetScreenModeFn`, `GetUiHookFlagsFn`; v78 = + `SetServerMessageInterestFn`; v79 = `GetTrainingInfoFn`, `RaiseFn`, `TrainSkillFn`. + +`main`'s numbering is the one upstream ships, so it stays. `GetMergeStackResultFn` is appended +after `TrainSkillFn` as v80, in both the engine's `RynthCoreAPI` and the SDK's +`RynthCoreApiNative`. `PluginContractVersion.Current`, `RynthCoreSdkApiVersion` (SDK targets) and +`RynthCoreHost.HasGetMergeStackResult` (now `Version >= 80`) follow. + +A plugin built against the old `QOL-items` SDK would read the wrong slot for +`GetMergeStackResult`. No RynthSuite plugin calls it, and RynthAi (RynthSuite `main` 272e9f5) +builds against the merged SDK, but rebuild plugins against this SDK before running them on this +engine. + +## Conflicts resolved + +`main`'s side already contains the `QOL-items` change plus upstream's additions in most files, so +those hunks take `main`: +- `ImGui/EngineFrameController.cs`: line endings only; `main` adds the Client::Cleanup guard. +- `ImGui/Panels/NavFace.cs`: header lists the route editor. +- `Plugins/EngineSettings.cs`: `DisabledUiHooks` read before `LoggingLevel`. +- `Plugins/LoadedPlugin.cs`: v77/v78 export pointers, `Manifest`, `NotStartedReason`. +- `RynthLog.cs`: `Heartbeat` (always written), the Move / UseDone traces, `Write` wrapper. +- `UI/Data/ChatData.cs`, `UI/Data/NavData.cs`: route editor fields and requests. +- `UI/Data/SettingsData.cs`, `ImGui/Panels/SettingsFace.cs`, `UI/Panels/SettingsPanel.cs`: the + TraceCategories row next to Button / Text / Status; the Diagnostics tab icon. +- `StatusAgent/AgentConfig.cs`: `CellDatPath` and `NavAtlasPath`. + +Merged by hand: +- `Plugins/PluginContract.cs`: header lists both `RynthPluginRenderOverlay` and + `RynthPluginOnServerMessage`; table as above; `PluginContractVersion` lives only in + `PluginContractVersion.cs`. +- `Plugins/PluginManager.cs`: `main` gathers the plugin list first and loads it afterwards, so + `QOL-items`' duplicate guard (same file name or same resolved path) now records each candidate + as it is accepted instead of after loading. +- `ImGui/Panels/SettingsFace.cs`: git kept two identical copies of `TextRow`, `StatusRow` and + `ButtonRow` (both lines added them); one copy removed. +- `tools/PluginManifestTests`: the table's tail is now the v79 slots then `GetMergeStackResultFn`. + +## Verification + +- `RynthCore.sln` (Release, x86): builds, no errors. +- PluginManifestTests 156/156, LauncherUpdateTests 134/134, TrainingCostTests 70/70, + ReloadDeferralTests 19/19, NetMessageTests 203/203. +- StatusAgentTests does not compile, the same as on `main` (its project compiles + `AgentConfig.cs` without `RynthInstallPaths`); not caused by this merge. +- RynthSuite `main` against this SDK: RynthAi builds; host tests 431 passed, 5 known failures, + 1 unrelated failure (map bake reads the real dats), the same as before. +- No release was built or deployed from this merge. diff --git a/Changelog/2026-10-07-release-2026.10.5.15-loot-add-t11-checkbox.md b/Changelog/2026-10-07-release-2026.10.5.15-loot-add-t11-checkbox.md new file mode 100644 index 0000000..1dcf913 --- /dev/null +++ b/Changelog/2026-10-07-release-2026.10.5.15-loot-add-t11-checkbox.md @@ -0,0 +1,32 @@ +# RynthCore 2026.10.5.15 — "Include T11 attributes" in the Add to loot profile popup + +**Date:** 2026-10-07 +**Branch:** `feat/loot-add-t11-checkbox` (from `fix/restore-sk-features` 5926a46) +**Previous release:** 2026.10.5.14 +**Pairs with:** RynthAi 0.5.21-legacy-ui (RynthSuite `feat/loot-add-t11-attributes`) + +## What's new + +The "Add to loot profile" popup has a new **Include T11 attributes** checkbox under Match. The +popup opens from the Inventory panel's right-click menu, or from "Add selected item" in the Loot +Editor. + +- When checked, RynthAi adds the item's T11 conditions to the rule: tier, weapon grade, + damage %, every modifier, slot special and Cast on Strike. Each must be at least as good as + the clicked item's. +- It works with every match mode, and the preview updates as soon as it is toggled. +- The tooltip lists what is added, and why Can Wield and Zone Locked are not: they depend on + the character and on where the item was assessed. +- "(not a T11 item)" shows next to the checkbox when the item isn't T11 gear. + +## Compatibility + +- `LootEditItemRequestDto.IncludeT11` is new; an older RynthAi ignores it. +- `LootEditItemDraftDto.IncludeT11` and `IsT11` are new; an older RynthAi never sends them, so + they read false. With an older RynthAi the checkbox has no effect, and "(not a T11 item)" + shows for every item. + +## Files + +- `src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs` +- `src/RynthCore.Engine/UI/Data/LootEditData.cs` diff --git a/Changelog/2026-10-07-release-2026.10.5.16-main-integration.md b/Changelog/2026-10-07-release-2026.10.5.16-main-integration.md new file mode 100644 index 0000000..0448368 --- /dev/null +++ b/Changelog/2026-10-07-release-2026.10.5.16-main-integration.md @@ -0,0 +1,51 @@ +# RynthCore engine 2026.10.5.16 — 2026-10-06/07 work brought onto main + +**Date:** 2026-10-07 +**Branch:** `integrate/main-2026-10-07` (from `main` 143eaa9), fast-forwarded into `main` +**Previous release:** 2026.10.5.15 (the T11 checkbox build on `fix/restore-sk-features`) + +## Why + +The night of 2026-10-06 left engine changes on three local branches, none of them on `main`. +This release puts the ones that apply to `main` on it in one line. It pairs with RynthAi +0.5.22-legacy-ui on RynthSuite `main`. + +## What's in it + +| Commit on main | From | Change | +|----------------|------|--------| +| b467573 | `fix/heartbeat-always-logged` 2c67875 | The heartbeat line is written at every logging level (2026.10.5.14) | +| b361152 | `SK-local` f2bd3b2 | Attribute raiser on the Skills face's Progression tab; text and status rows for Server Features | +| ead4828 | `feat/loot-add-t11-checkbox` ef0e6cf | "Include T11 attributes" checkbox in the Add to loot profile popup (2026.10.5.15) | +| (docs) | untracked in the main checkout | The upstream snapshot comparison report (`2026-10-06-upstream-snapshot-comparison.md`) | + +## Left out on purpose + +ab18df2 on `SK-local`, "log CoreCLR-hosted engine AVs immediately in the native crash logger", +patches the crash logger rewrite in `native/SehTrampoline/SehTrampoline.c` from a7cdbee. `main` +never got a7cdbee: its trampoline is the older 406-line version, against 674 lines on `SK-local`, +so the cherry-pick conflicted in four places. a7cdbee also changes create-time object seeding, +which overlaps `main`'s own identity seeds from 4be686e. Bringing the crash logger over is its own +port, and it only takes effect after `scripts/Build-SehTrampoline.ps1` rebuilds the native DLL. +ab18df2 stays on `SK-local` until then. + +5926a46 is the same heartbeat fix as 2c67875 on the `fix/restore-sk-features` line, so it was not +picked twice. + +## Conflicts resolved + +`main` added a TraceCategories settings row in the same places f2bd3b2 adds its Text and Status +rows. Both are kept: +- `UI/Data/SettingsData.cs`: `SettingKind` has `TraceCategories, Text, Status`, and + `TraceCategoryLevels` stays. +- `ImGui/Panels/SettingsFace.cs`: all three switch cases, then `TraceCategoriesRow` / + `SaveCategories`, then `TextRow` / `StatusRow`. +- `UI/Panels/SettingsPanel.cs` (the Avalonia face): all three cases. + +## Build + +- `scripts/Publish-EngineCoreClr.ps1 -EngineOnly -MsBuildArgs '-p:Version=2026.10.5.16'` to + `out/staged-2026.10.5.16`. It built with no errors, and every warning was already on `main`. +- `RynthCore.Engine.dll` FileVersion 2026.10.5.16. +- Not deployed. The live engine (2026.10.5.15) is built from the `fix/restore-sk-features` line, + not from `main`. diff --git a/Changelog/2026-10-07-release-2026.10.5.17-progression-ub-parity.md b/Changelog/2026-10-07-release-2026.10.5.17-progression-ub-parity.md new file mode 100644 index 0000000..b06d415 --- /dev/null +++ b/Changelog/2026-10-07-release-2026.10.5.17-progression-ub-parity.md @@ -0,0 +1,57 @@ +# RynthCore engine 2026.10.5.17 — Progression tab laid out like UB's ILT Tools XP and Augs tabs + +**Date:** 2026-10-07 +**Previous release:** 2026.10.5.16 (main integration) +**Branch:** `QOL-items` +**Pairs with:** RynthAi 0.5.23-legacy-ui, which sends the new snapshot fields. With an older +RynthAi the panel falls back to plain +1 / +10 buttons and the old totals lines. + +## Attribute raiser (`ImGui/Panels/SkillsFace.Progression.cs`) + +- The table now has UB's columns: **Auto** (tick), **Stat**, **Base**, **+1 Level**, **+10 + Levels** and **Order** (arrows). +- The raise buttons fill their cells and are labelled with what they cost: the next-level cost + from `/xp all`, and `~` plus the projected cost for ten levels. + - Teal with a teal border: you can afford it. + - Red and disabled: the known cost is more than your unassigned XP. + - Plain: the cost hasn't been read yet. The button still works and the server decides. + - Tooltips give the exact XP and why a button is off. +- The header shows "Level N Total XP X Unassigned Y". +- "Refresh costs" is now "Refresh XP", with "Last updated: HH:mm:ss" beside it. +- The footnote explains that +10 is a 7.7%-per-level estimate. + +## Augmentations + +- Four buttons, as in UB's Augs tab: + - **Refresh current** reads your levels with `/aug`. RynthAi also does this once when the tab + first opens. + - **Reset targets** sets every target back to the current level. + - **Copy Discord** and **Copy in-game** put RynthAi's ready-made text on the clipboard with + `ImGui.SetClipboardText`. +- The table now has **Current / Target / Inc / Luminance / Coins** columns and a **TOTALS** row. +- **Target** has −/+ step buttons (Ctrl for 100). Typing commits on Enter or when the box loses + focus, so a half-typed number is never sent. It is clamped to current..cap before sending. +- **Lum per e-coin** also commits on Enter or focus loss (it used to send on every keystroke) and + accepts k / m / b / t. +- Under the table: E-coins needed / banked / short, the luminance needed to buy them, and your + banked luminance. + +## Data (`UI/Data/ProgressionData.cs`) + +- `AttrRaiser`: `Updated`, `XpHeader`. +- `AttrRow`: `Known`, `Afford1`, `Afford10`, `Cost10`, `CostFull`, `Cost10Full`. +- `AugPlanner`: `TotalCurrent`, `TotalTarget`, `TotalIncrease`, `TotalLum`, `TotalCoins`, + `CoinsLine`, `LumToBuy`, `CopyDiscord`, `CopyIngame`. +- `AugRow`: `Increase`. +- Every new field has a default, so an older RynthAi's snapshot still deserializes. + +## Build + +- `scripts/Publish-EngineCoreClr.ps1 -Target out\staged-2026.10.5.17 -EngineOnly -MsBuildArgs + @('-p:Version=2026.10.5.17')`. It built with no errors; the one warning (CS0618 in + `EntryPoint.cs`) was already there. +- `RynthCore.Engine.dll` FileVersion 2026.10.5.17. +- Not deployed. Called with no `-Target`, the script deploys to the live Runtime, and its + status-export check refused this checkout. +- This is a `QOL-items` engine (plugin API 80). Deploy it only together with a RynthAi built + against the `QOL-items` SDK, such as RynthAi 0.5.23. diff --git a/Changelog/2026-10-07-release-2026.10.5.18-aug-cost-settings.md b/Changelog/2026-10-07-release-2026.10.5.18-aug-cost-settings.md new file mode 100644 index 0000000..980e6bb --- /dev/null +++ b/Changelog/2026-10-07-release-2026.10.5.18-aug-cost-settings.md @@ -0,0 +1,34 @@ +# RynthCore engine 2026.10.5.18 — Aug cost settings in the Progression tab + +**Date:** 2026-10-07 +**Previous release:** 2026.10.5.17 (Progression tab laid out like UB's ILT Tools) +**Branch:** `QOL-items` +**Pairs with:** RynthAi 0.5.24-legacy-ui. With an older RynthAi the editor is hidden. + +## What's new + +The Augmentations section has a collapsible **Cost settings for <world>** block. Its header says +whether the world is on the InfiniteLeaftide defaults or has its own (custom) rules. + +- **Tier multipliers:** five boxes (Below S1, From S1, From S2, From S3, From S4). The defaults are + UB's 1 / 4 / 8 / 16 / 24, and decimals are allowed. +- **Per-aug rules:** a table with Base, Growth%, S1, S2, S3, S4, Cap (0 = no limit) and Coins per + level. +- **Reset to InfiniteLeaftide defaults:** drops this world's changes. +- A note explains the formula: level i costs (Base + (i − 1) × Base × Growth% / 100) × the + multiplier of its tier, and a tier starts at its S level. + +Every box commits on Enter or when it loses focus, so a half-typed value never reaches RynthAi. +RynthAi saves the rules for the current world only, and the plan above re-prices on the next +snapshot. + +## Data (`UI/Data/ProgressionData.cs`) + +- `AugPlanner.Config`, of type `AugCostConfig`: World, Custom, Multipliers and Rows. +- `AugCostRule`: Key, Label, Base, Percent, Coins, S1 to S4, and Cap. + +## Build + +- `scripts/Publish-EngineCoreClr.ps1 -Target out\staged-2026.10.5.18 -EngineOnly -MsBuildArgs + @('-p:Version=2026.10.5.18')`. It built with no errors; the one warning was already there. +- `RynthCore.Engine.dll` FileVersion 2026.10.5.18. diff --git a/Changelog/2026-10-08-installer-2026.10.5.21-release.md b/Changelog/2026-10-08-installer-2026.10.5.21-release.md new file mode 100644 index 0000000..5c5492a --- /dev/null +++ b/Changelog/2026-10-08-installer-2026.10.5.21-release.md @@ -0,0 +1,43 @@ +# Installer 2026.10.5.21 + +**Date:** 2026-10-08 +**Source:** RynthCore `QOL-items` d46cd91; RynthSuite c60243c, built from a clean worktree. +Both are clean in the manifest. **Local only**: the commits are not pushed. +**Previous installer:** 2026.10.5.11, archived by the build in `installer/previous-release/`. + +## Contents + +- **Engine 2026.10.5.21:** Mini Remote drawer on the RynthAi dashboard. Right-click Hub + or use the drawer tab. Adds the new optional plugin export `RynthPluginRenderEmbed` + (`2026-10-08-release-2026.10.5.21-mini-remote-drawer.md`). +- **Engine 2026.10.5.20:** the Add-to-loot T11 tooltip covers stamped tier and gear grade. + Earlier 2026.10.5.x work on this branch is included too. +- **RynthAi 0.5.27-legacy-ui:** the Mini Remote draws inside that drawer, with its own + Options menu. Also includes 0.5.26 (new ACECustom T11 item state for item ID and loot + rules) and the 0.5.23 / 0.5.24 progression and aug-cost work. +- **RynthCore.SehTrampoline.dll** was rebuilt from `SehTrampoline.c`. The prebuilt DLL + predated commit ab18df2 (CoreCLR-hosted engine AVs logged immediately), and the build + refuses a stale DLL. + +## Not included + +- The uncommitted ENL sigil-chain work (RynthAi 0.5.25 working tree, another session). + It ships later as its own release. +- The `feat/skills-augments-tab` engine branch. + +## Artifacts (`installer/Output/`) + +- `RynthCore-Setup-2026.10.5.21.exe`, 125.4 MB, SHA-256 + `9b5ca2a6f41d4615376281f8511a10c2ed614a1b8ec7282be3859a75c302e6cd`. +- `Release-2026.10.5.21/` and `RynthCore-2026.10.5.21-deploy.zip` (124.9 MB, hash-verified). + +## Build + +- Command: `Build-Release-All.ps1 -Version 2026.10.5.21 -RynthSuiteRoot <clean RynthSuite worktree>`. +- The optional RynthJuice and UbRythai plugins are git-ignored and empty in this + checkout. Their sources were copied into the build worktree from the 2026-10-06 build + tree (`C:\Games\Rynthcore\build\sk-attr\RynthSuite`). +- The manifest lists the RynthAi plugin as `1.0.0+c60243c`: its assembly version. The + in-game version is `/ra version`, 0.5.27-legacy-ui. +- The engine and RynthAi are already deployed live to `C:\Games` (both clients + hot-reloaded). The installer is not yet verified on a fresh install. diff --git a/Changelog/2026-10-08-release-2026.10.5.20-t11-item-state.md b/Changelog/2026-10-08-release-2026.10.5.20-t11-item-state.md new file mode 100644 index 0000000..3cdff30 --- /dev/null +++ b/Changelog/2026-10-08-release-2026.10.5.20-t11-item-state.md @@ -0,0 +1,28 @@ +# RynthCore engine 2026.10.5.20 - Add-to-loot text for the new T11 item state + +**Date:** 2026-10-08 +**Previous release:** 2026.10.5.18 (2026.10.5.19 is reserved by the Skills augments-tab work on +`feat/skills-augments-tab`, not yet released) +**Branch:** `QOL-items` +**Pairs with:** RynthAi 0.5.26-legacy-ui + +## Why + +RynthAi 0.5.26 reads the T11 state ACECustom added in its endgame updates: the stamped loot tier +(`ZcTier` 50109, `WeaponAugScaleTier` 9061), the weapon quality roll (`WeaponAugScaleQuality` 9060), +Gear Grade, property slots, Tainted and the jewelry Cast on Strike. "Add to loot profile" with +"Include T11 attributes" now adds the stamped tier and Gear Grade, so the checkbox tooltip had to say so. + +## What changed + +- `ImGui/Panels/LootAddDialog.cs`: the "Include T11 attributes" tooltip lists the server's stamped tier, + gear grade, and that property slots / Tainted are not added. +- No engine-side key tables changed: the new loot keys (T11: Gear Grade, Tier Is Exact, Property + Slots, Tainted, T11 Mod: Cast on Strike, and the named ZcTier / WeaponAugScale* properties) and the + Gear Grade letter table come from RynthAi's editor vocabulary, so the loot editor face shows them + as soon as RynthAi 0.5.26 is loaded. + +## Build + +- `scripts/Publish-EngineCoreClr.ps1 -EngineOnly -MsBuildArgs @('-p:Version=2026.10.5.20')` +- Previous live engine saved to `C:\Games\RynthCore\PreviousReleases\2026.10.5.18-engine\`. diff --git a/Changelog/2026-10-08-release-2026.10.5.21-mini-remote-drawer.md b/Changelog/2026-10-08-release-2026.10.5.21-mini-remote-drawer.md new file mode 100644 index 0000000..c5dd3d6 --- /dev/null +++ b/Changelog/2026-10-08-release-2026.10.5.21-mini-remote-drawer.md @@ -0,0 +1,56 @@ +# RynthCore 2026.10.5.21: Mini Remote drawer on the RynthAi dashboard + +Released 2026-10-08. Previous release: 2026.10.5.20 (T11 item state tooltip). +Pairs with RynthAi 0.5.27-legacy-ui. + +## What's new + +- **Mini Remote drawer.** The RynthAi dashboard has a fourth left-edge drawer, + under Ranges, Loaded files and Patrol. It holds RynthAi's whole Mini Remote: + - session rates with Reset XP / Report + - the attack target and summon health bars, with the summon's time left + - the 5 x 6 item slots (click to use, right-click to assign, drag items in) + - the macro toggles, bank balances and rebuff buttons + - the Translate row and the Guardian answer +- **Options inside the drawer.** The remote's Options button, or a right-click on + it, opens the same menu as the floating window: which sections show, the ILT Hub + windows, horizontal layout, Inventory HUDs setup, and "Floating window too". +- **Opening it.** Use the drawer tab, or right-click the **Hub** launcher (as + right-clicking Patrol opens its drawer). Left-click Hub still toggles the floating + Mini Remote. On a popped-out dashboard (no drawers), right-click Hub shows the + floating Mini Remote. +- The drawer sizes itself to the remote: one column when stacked, three side by side + in horizontal layout. It is never taller than the screen; past that it scrolls. +- The drawer's open / closed state is saved with the dashboard, as line 11 of + `rynthai_avalonia.cache`. + +## Changed + +- Right-click **Hub** no longer opens Inventory HUDs setup directly. It is in the + Mini Remote's Options menu (and `/ra huds`). + +## Plugin API + +- New optional plugin export: + `int RynthPluginRenderEmbed(const char* surface, float width, float height, float* wantWidth, float* wantHeight)` + (Cdecl). + - The engine calls it on the render thread, inside a child window of the size + given, in the main ImGui context. + - The plugin draws the named UTF-8 surface there and reports the content size it + wants. + - Returns 1 if it drew, 0 if it isn't ready or doesn't know the surface. +- The export is resolved at load, like `RynthPluginRenderOverlay`. + - A plugin without it shows a "needs RynthAi 0.5.27 or later" note in the drawer. + - If it throws, the export is switched off for the session; the plugin keeps + running. +- No `RynthCoreAPI` struct change; the API version is unchanged. + +## Files + +- `ImGui/Panels/RynthAiFace.Drawers.cs`: `RemoteDrawer`. +- `ImGui/Panels/RynthAiFace.cs`: the drawer added to the dashboard; Hub right-click. +- `ImGui/Panels/DashboardDrawers.cs`: header comment. +- `Plugins/PluginManager.cs`: `RenderEmbed` (render thread, login gated). +- `Plugins/LoadedPlugin.cs`, `Plugins/PluginLoader.cs`: `RenderEmbedPtr`. +- `Plugins/PluginContract.cs`: export documented. +- `UI/RynthAiDashboardState.cs`: `RemoteOpen` (cache line 11). diff --git a/Changelog/2026-10-09-release-2026.10.5.22-buffs-picker.md b/Changelog/2026-10-09-release-2026.10.5.22-buffs-picker.md new file mode 100644 index 0000000..30a9031 --- /dev/null +++ b/Changelog/2026-10-09-release-2026.10.5.22-buffs-picker.md @@ -0,0 +1,37 @@ +# RynthCore 2026.10.5.22: Buffs picker in Loaded Files + +Released 2026-10-09. Previous release: 2026.10.5.21 (Mini Remote drawer). +Pairs with RynthAi 0.5.31-legacy-ui. + +## What's new + +- **Buffs picker.** The RynthAi dashboard's loaded files (the docked Loaded files drawer, and + the header of a popped-out dashboard) have a fifth row, **Buffs:**, under Meta. It lists + "Built-in" (buffing's own list) and every buff profile in `RynthAi\BuffProfiles`; picking one + makes buffing use it. +- **Spells button.** A sparkle button at the end of the Buffs row opens or closes RynthAi's + Spells window, where buff profiles are built. +- **Settings > Buffing** has a "Buff Profiles: Spells..." button that opens the same window. +- The Loaded files tooltips (drawer tab, popped-out caret) list the Buffs choice too. + +## Compatibility + +- With a RynthAi older than 0.5.31 the snapshot has no buff profiles: the row shows "Built-in" + and its picker has nothing to choose; the Spells button does nothing (the plugin logs an unknown + remote command). + +## Files + +- `UI/Data/RynthAiData.cs`: `RynthAiSnapshot.BuffProfiles` / `CurrentBuffName` / + `SelectedBuffIdx`; `RynthAiView.BuffText`. +- `ImGui/Panels/RynthAiFace.cs`: fifth selector slot (picker kind 4), the Buffs row in the + header grid, the Spells button option on `Selector`, caret tooltip. +- `ImGui/Panels/RynthAiFace.Drawers.cs`: the Buffs row and height in `FilesDrawer`, tab tooltip. +- `UI/Data/SettingsData.cs`: Buffing > Buff Profiles button (`spells show`). + +## Checks + +- Release publish (NativeAOT) succeeds. +- RynthAi's host tests check the plugin side of the picker (list, pick by index, snapshot + fields). +- Not yet tried in game. diff --git a/Changelog/2026-10-10-hookresolver-ui-1.0.1-tmds-dbus-security.md b/Changelog/2026-10-10-hookresolver-ui-1.0.1-tmds-dbus-security.md new file mode 100644 index 0000000..dd3d0e5 --- /dev/null +++ b/Changelog/2026-10-10-hookresolver-ui-1.0.1-tmds-dbus-security.md @@ -0,0 +1,24 @@ +# HookResolver UI 1.0.1: Tmds.DBus.Protocol security update + +Released 2026-10-10. Previous release: 1.0.0 (no version was set; the SDK default). +Developer tool only: nothing that ships in the installer changes. + +## What's fixed + +- **Dependabot alert #1 (high), GHSA-xrw6-gwf8-vvr9.** Through Avalonia (Avalonia.FreeDesktop), + `tools/HookResolver.UI` pulled in `Tmds.DBus.Protocol` older than 0.21.3. In those versions a + malicious D-Bus peer can spoof signals, exhaust file descriptors and cause a denial of service. + D-Bus is only used on Linux, so the Windows tool was never exposed, but the alert is real for the + manifest. +- The project now references `Tmds.DBus.Protocol` 0.21.3 directly, the same override the engine + and the launcher already have. + +## Files + +- `tools/HookResolver.UI/RynthCore.HookResolver.UI.csproj`: direct `Tmds.DBus.Protocol` 0.21.3 + reference; `Version` 1.0.1. + +## Checks + +- Release build succeeds with no warnings or errors (no NU1903). +- `dotnet list package --include-transitive` resolves `Tmds.DBus.Protocol` 0.21.3. diff --git a/Changelog/2026-10-10-installer-2026.10.5.24-release.md b/Changelog/2026-10-10-installer-2026.10.5.24-release.md new file mode 100644 index 0000000..e78d235 --- /dev/null +++ b/Changelog/2026-10-10-installer-2026.10.5.24-release.md @@ -0,0 +1,44 @@ +# Installer 2026.10.5.24 + +**Date:** 2026-10-10 +**Source:** RynthCore `main` 75bac26; RynthSuite `main` fc0d7a0. Both are clean in the manifest. +RynthCore 75bac26 is on GitHub `main`. RynthSuite fc0d7a0 (RynthAi 0.5.32) is a local commit, not +pushed yet. +**Previous installer:** 2026.10.5.21, archived by the build in `installer/previous-release/`. + +## Contents + +- **Engine 2026.10.5.24** (same code as the live 2026.10.5.23, now stamped with the installer + version): + - 2026.10.5.23: large-address alignment fix. On a large-address-aware client the 190 + `and r32,0x80000003` sites in AC's unpack code rounded heap blocks above 2 GB to the wrong + size and crashed in open world. The engine now patches them in memory at load + (`2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md`). + - 2026.10.5.22: Buffs picker under Loaded Files and the Spells window button. +- **HookResolver UI 1.0.1:** Tmds.DBus.Protocol pinned to 0.21.3 (GHSA-xrw6-gwf8-vvr9). It is a + developer tool and is not in the installer; listed because its changelog falls in this range. +- **RynthAi 0.5.32-legacy-ui:** + - 0.5.32: Mini Remote / ILT Hub Lum/h follows the bank's luminance property, so + fellowship and zone-share luminance count. + - 0.5.25 (first shipped here): enlightenment planner breaks levels 301-325 down into the + sigil craft chain (crafts left, raw items, e-coin demand). + - 0.5.28 - 0.5.31: Mini Remote drawer without Toggles, item info kept on profile load, + Bounties window, Spells window and buff profiles. + +## Artifacts (`installer/Output/`) + +- `RynthCore-Setup-2026.10.5.24.exe`, 125.5 MB, SHA-256 + `377b3325f6bafc49bf0f892d14227cabc2f500af2c5465b152ccb25302fd6fa2`. +- `Release-2026.10.5.24/` and `RynthCore-2026.10.5.24-deploy.zip` (125.1 MB, hash-verified). + +## Build + +- Command: `Build-Release-All.ps1 -Version 2026.10.5.24` from the main checkouts. +- The optional RynthJuice and UbRythai plugins are not tracked in RynthSuite. Their sources were + copied in from the 2026-10-06 build tree (`C:\Games\Rynthcore\build\sk-attr\RynthSuite`) for + the build and removed afterwards. +- RynthAi host tests before the build: 470 tests, 464 passed, 5 known failures, 1 failure (the + map bake, which needs the real dat files on this machine - same as 0.5.31). +- The manifest lists the RynthAi plugin as `1.0.0+fc0d7a0`, its assembly version. The in-game + version is `/ra version`, 0.5.32-legacy-ui. +- Not deployed live and not published as an update. Not yet tried on a fresh install. diff --git a/Changelog/2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md b/Changelog/2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md new file mode 100644 index 0000000..7b73590 --- /dev/null +++ b/Changelog/2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md @@ -0,0 +1,64 @@ +# RynthCore 2026.10.5.23: fix AC crashes when its memory goes above 2 GB + +Released 2026-10-10. Previous release: 2026.10.5.22 (Buffs picker). +No plugin changes; any RynthAi version works with it. + +## What's fixed + +- **Random client crashes on long open-world sessions** (hunting nav routes across many + landblocks while fighting and looting). Windows reported them as faults in `acclient.exe` + (`+0x1271C3`, `+0x12718B`, `+0x126A70`, `+0x139153`) or, when they passed through an engine + hook, in `coreclr.dll`. + +## Cause + +Asheron's Call pads its read and write position to a multiple of 4 bytes when it unpacks dat +files and network messages. It works the padding out as a *signed* `address % 4`. The client +runs large-address-aware, so once a session has used enough memory, AC gets buffers above +2 GB. Their addresses count as negative, the remainder comes out negative, and AC pads 4 +bytes too many. It then reads every later field from the wrong place, writes zeros over real +data, and reads garbage counts until it runs off the end of the memory region. + +A crash dump of kelpie (10 October, 10:32) showed motion table 0x09000009 being unpacked into a +buffer at 0x80438034. The data on disk was fine, but 21 bytes of the in-memory copy were zeroed. +Replaying AC's padding code at that address zeroes the same 21 bytes, and reads the modifier +count as 0xFFFF0000, the value on the crashed stack. At an address below 2 GB the same data +unpacks cleanly. + +## The fix + +At startup the engine finds every place in `acclient.exe` that pads this way (190 in the +retail client) and changes `and reg, 0x80000003` to `and reg, 3` in memory. The remainder is +then 0 to 3 at any address, so AC pads correctly above 2 GB too. Below 2 GB nothing changes. +`acclient.exe` on disk is not modified. A site is only changed when it is followed by AC's +"already aligned" check, so a signed `% 4` of a value that can really be negative is left +alone (one in the retail client: a 16-bit ring index). + +The change stays for the life of the client: a hot reload finds every site already patched +and logs `0 site(s) patched, 190 already patched`. + +To turn it off for diagnostics, add `"EnableLargeAddressAlignmentFix": false` to +`%APPDATA%\RynthCore\engine.json`. The launcher keeps that setting when it saves. + +## Files + +- `Compatibility/LargeAddressAlignmentScan.cs` (new): the byte-pattern scan for the padding + code. +- `Compatibility/LargeAddressAlignmentPatch.cs` (new): finds `.text` in the loaded client, + rewrites each site's immediate (one byte, page protection restored per site), flushes the + instruction cache, and logs the counts. +- `EntryPoint.cs`: runs the patch in early init, right after the multi-client hooks. +- `Plugins/EngineSettings.cs`: the `EnableLargeAddressAlignmentFix` kill-switch. +- `tools/LargeAddressAlignmentTests` (new): offline checks. + +## Checks + +- `tools/LargeAddressAlignmentTests` (31 checks) pass: + - The real `acclient.exe` has 190 sites, including the ones in the crash dumps. + - The 16-bit ring index is left alone. + - A patched image rescans as fully patched. + - Bytes that only look like the pattern are refused. + - The padding above and below 2 GB comes out as expected. +- Release publish of the CoreCLR engine succeeds. +- Not yet run in game. The engine log should show + `Compat: large-address alignment fix - 190 site(s) patched`. diff --git a/Changelog/changelog-installer-full-rynthsuite-setup-2026-04-22.md b/Changelog/changelog-installer-full-rynthsuite-setup-2026-04-22.md new file mode 100644 index 0000000..bf3219a --- /dev/null +++ b/Changelog/changelog-installer-full-rynthsuite-setup-2026-04-22.md @@ -0,0 +1,19 @@ +## RynthCore Installer Update - Full RynthCore + RynthSuite Setup + +Date: 2026-04-22 + +### What changed +- Expanded `installer/Build-Installer.ps1` to package a full setup payload: + - Publishes launcher + engine. + - Discovers and publishes all default `RynthSuite` plugin projects (`RynthCore.Plugin.*`). + - Bundles `RynthCore.LootEditor` and `RynthCore.MonsterEditor` as self-contained tools. +- Updated installer staging to copy default plugin DLLs into `Runtime/Plugins` for automatic loading. +- ~~Added a mirrored `RynthAi` plugin copy under `Suite/RynthAi/` for data/profile adjacency.~~ **Removed in 0.4.8** — plugin lives only in `Runtime\Plugins\`; data stays under `C:\Games\RynthSuite\RynthAi\`. +- Updated `installer/RynthCore.iss`: + - Added `MonsterProfiles` data directory creation. + - Added Start Menu shortcuts for Loot Editor and Monster Editor when present. +- Updated `BUILD.md` installer documentation to reflect full setup behavior and default plugin autoload. + +### Why +- Provide one setup executable that installs both core runtime and suite defaults. +- Remove manual post-install steps for loading default plugins and installing suite tools. diff --git a/Plugins/RynthAi/Combat/BuffManager.cs b/Plugins/RynthAi/Combat/BuffManager.cs new file mode 100644 index 0000000..a4119c2 --- /dev/null +++ b/Plugins/RynthAi/Combat/BuffManager.cs @@ -0,0 +1,580 @@ +using System; +using System.Collections.Generic; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; + +namespace NexSuite.Plugins.RynthAi +{ + public class BuffManager : IDisposable + { + private CoreManager _core; + private UISettings _settings; + private SpellManager _spellManager; + + private DateTime _lastCastAttempt = DateTime.MinValue; + private bool _isForceRebuffing = false; + private int _pendingSpellId = 0; + + private class RamTimerInfo + { + public DateTime Expiration; + public int SpellLevel; + public string SpellName; // Added to make debug easier + } + private Dictionary<int, RamTimerInfo> _ramBuffTimers = new Dictionary<int, RamTimerInfo>(); + private string _buffTimerPath; + + private bool _isRechargingMana = false; + private bool _isRechargingStamina = false; + private bool _isHealingSelf = false; + + private readonly List<string> BaseCreatureBuffs = new List<string> + { + "Strength Self", "Endurance Self", "Coordination Self", + "Quickness Self", "Focus Self", "Willpower Self", + "Magic Resistance Self", "Invulnerability Self", "Impregnability Self" + }; + + private readonly Dictionary<CharFilterSkillType, string> CreatureSkillBuffs = new Dictionary<CharFilterSkillType, string> + { + { CharFilterSkillType.MeleeDefense, "Invulnerability Self" }, + { CharFilterSkillType.MissileDefense, "Impregnability Self" }, + { CharFilterSkillType.MagicDefense, "Magic Resistance Self" }, + { CharFilterSkillType.HeavyWeapons, "Heavy Weapon Mastery" }, + { CharFilterSkillType.LightWeapons, "Light Weapon Mastery" }, + { CharFilterSkillType.FinesseWeapons, "Finesse Weapon Mastery" }, + { CharFilterSkillType.TwoHandedCombat, "Two Handed Combat Mastery" }, + { CharFilterSkillType.Shield, "Shield Mastery" }, + { CharFilterSkillType.DualWield, "Dual Wield Mastery" }, + { CharFilterSkillType.Recklessness, "Recklessness Mastery" }, + { CharFilterSkillType.SneakAttack, "Sneak Attack Mastery" }, + { CharFilterSkillType.DirtyFighting, "Dirty Fighting Mastery" }, + { CharFilterSkillType.AssessCreature, "Monster Attunement" }, + { CharFilterSkillType.AssessPerson, "Person Attunement" }, + { CharFilterSkillType.ArcaneLore, "Arcane Enlightenment" }, + { CharFilterSkillType.ArmorTinkering, "Armor Tinkering Expertise" }, + { CharFilterSkillType.ItemTinkering, "Item Tinkering Expertise" }, + { CharFilterSkillType.MagicItemTinkering, "Magic Item Tinkering Expertise" }, + { CharFilterSkillType.WeaponTinkering, "Weapon Tinkering Expertise" }, + { CharFilterSkillType.Salvaging, "Arcanum Salvaging" }, + { CharFilterSkillType.Run, "Sprint" }, + { CharFilterSkillType.Jump, "Jumping Mastery" }, + { CharFilterSkillType.Loyalty, "Fealty" }, + { CharFilterSkillType.Leadership, "Leadership Mastery" }, + { CharFilterSkillType.Deception, "Deception Mastery" }, + { CharFilterSkillType.Healing, "Healing Mastery" }, + { CharFilterSkillType.Lockpick, "Lockpick Mastery" }, + { CharFilterSkillType.Cooking, "Cooking Mastery" }, + { CharFilterSkillType.Fletching, "Fletching Mastery" }, + { CharFilterSkillType.Alchemy, "Alchemy Mastery" }, + { CharFilterSkillType.ManaConversion, "Mana Conversion Mastery" }, + { CharFilterSkillType.CreatureEnchantment, "Creature Enchantment Mastery" }, + { CharFilterSkillType.ItemEnchantment, "Item Enchantment Mastery" }, + { CharFilterSkillType.LifeMagic, "Life Magic Mastery" }, + { CharFilterSkillType.WarMagic, "War Magic Mastery" }, + { CharFilterSkillType.VoidMagic, "Void Magic Mastery" }, + { CharFilterSkillType.Summoning, "Summoning Mastery" } + }; + + public BuffManager(CoreManager core, UISettings settings, SpellManager spellManager) + { + _core = core; + _settings = settings; + _spellManager = spellManager; + _core.ChatBoxMessage += OnChatMsg; + } + + /// <summary> + /// Set the path for persisting buff timers. Call after settings path is known. + /// Automatically loads any existing timers from disk. + /// </summary> + public void SetTimerPath(string charFolder) + { + _buffTimerPath = System.IO.Path.Combine(charFolder, "bufftimers.txt"); + LoadBuffTimers(); + } + + public void SaveBuffTimers() + { + if (string.IsNullOrEmpty(_buffTimerPath)) return; + try + { + var lines = new System.Collections.Generic.List<string>(); + foreach (var kvp in _ramBuffTimers) + { + var info = kvp.Value; + // Format: Family|Expiration(ticks)|SpellLevel|SpellName + lines.Add($"{kvp.Key}|{info.Expiration.Ticks}|{info.SpellLevel}|{info.SpellName}"); + } + System.IO.File.WriteAllLines(_buffTimerPath, lines); + } + catch { } + } + + public void LoadBuffTimers() + { + if (string.IsNullOrEmpty(_buffTimerPath)) return; + if (!System.IO.File.Exists(_buffTimerPath)) return; + try + { + _ramBuffTimers.Clear(); + foreach (string line in System.IO.File.ReadAllLines(_buffTimerPath)) + { + string[] parts = line.Split('|'); + if (parts.Length < 4) continue; + + int family = int.Parse(parts[0]); + DateTime expiration = new DateTime(long.Parse(parts[1])); + int level = int.Parse(parts[2]); + string name = parts[3]; + + // Only load if not expired + if (expiration > DateTime.Now) + { + _ramBuffTimers[family] = new RamTimerInfo + { + Expiration = expiration, + SpellLevel = level, + SpellName = name + }; + } + } + if (_ramBuffTimers.Count > 0) + _core.Actions.AddChatText($"[RynthAi] Restored {_ramBuffTimers.Count} buff timer(s) from last session.", 1); + } + catch { } + } + + public void Dispose() => _core.ChatBoxMessage -= OnChatMsg; + + public void ForceFullRebuff() + { + _isForceRebuffing = true; + _ramBuffTimers.Clear(); + SaveBuffTimers(); + _core.Actions.AddChatText("[RynthAi] Starting Force Rebuff...", 5); + } + + public void CancelBuffing() + { + _isForceRebuffing = false; + _isRechargingMana = false; + _isRechargingStamina = false; + _isHealingSelf = false; + _pendingSpellId = 0; + _core.Actions.AddChatText("[RynthAi] Sequence cancelled.", 5); + } + + public void OnHeartbeat() + { + if (!_settings.IsMacroRunning) return; + if (_core.CharacterFilter.LoginStatus != 3) return; + + // 1. Are we locked in a cast/equip animation? + if ((DateTime.Now - _lastCastAttempt).TotalMilliseconds < 1500) + { + _settings.CurrentState = "Buffing"; + return; + } + + // 2. Do we need to heal/recharge? + if (CheckVitals()) + { + _settings.CurrentState = "Buffing"; + return; + } + + // 3. Do we need to buff? + if (_settings.EnableBuffing) + { + if (CheckAndCastSelfBuffs()) + { + _settings.CurrentState = "Buffing"; + return; + } + + if (_isForceRebuffing) + { + _isForceRebuffing = false; + _core.Actions.AddChatText("[RynthAi] Force Rebuff Complete.", 1); + } + } + + // === THE FIX === + // 4. Only release the traffic light if WE were the ones holding it! + if (_settings.CurrentState == "Buffing") + { + _settings.CurrentState = "Idle"; + } + } + + private bool CheckVitals() + { + double maxHealth = _core.CharacterFilter.EffectiveVital[CharFilterVitalType.Health]; + double maxMana = _core.CharacterFilter.EffectiveVital[CharFilterVitalType.Mana]; + double maxStam = _core.CharacterFilter.EffectiveVital[CharFilterVitalType.Stamina]; + + int curHealthPct = maxHealth > 0 ? (int)((_core.CharacterFilter.Health / maxHealth) * 100) : 100; + int curManaPct = maxMana > 0 ? (int)((_core.CharacterFilter.Mana / maxMana) * 100) : 100; + int curStamPct = maxStam > 0 ? (int)((_core.CharacterFilter.Stamina / maxStam) * 100) : 100; + + if (curHealthPct <= 30 && curStamPct > 20) return AttemptVitalCast("Stamina to Health Self"); + + if (curHealthPct <= _settings.HealAt) _isHealingSelf = true; + if (curHealthPct >= _settings.TopOffHP) _isHealingSelf = false; + if (curManaPct <= _settings.GetManaAt) _isRechargingMana = true; + if (curManaPct >= _settings.TopOffMana) _isRechargingMana = false; + if (curStamPct <= _settings.RestamAt) _isRechargingStamina = true; + if (curStamPct >= _settings.TopOffStam) _isRechargingStamina = false; + + if (_isHealingSelf) return AttemptVitalCast("Heal Self"); + if (_isRechargingMana && curStamPct > 15) return AttemptVitalCast("Stamina to Mana Self"); + if (_isRechargingStamina) return AttemptVitalCast("Revitalize Self"); + + return false; + } + + private bool AttemptVitalCast(string baseName) + { + int spellId = FindBestSpellId(baseName, CharFilterSkillType.LifeMagic); + if (spellId == 0) return false; + + // Use our new wand-equipping check + if (!EnsureMagicMode()) return true; + + _core.Actions.CastSpell(spellId, _core.CharacterFilter.Id); + _lastCastAttempt = DateTime.Now; + return true; + } + + private bool CheckAndCastSelfBuffs() + { + List<string> desiredBuffs = BuildDynamicBuffList(); + + foreach (string buffBaseName in desiredBuffs) + { + CharFilterSkillType castSkill = SkillForBuff(buffBaseName); + if (!IsSkillUsable(castSkill)) continue; + + int spellId = FindBestSpellId(buffBaseName, castSkill); + if (spellId == 0) continue; + + if (!IsBuffActive(spellId)) + { + // Use our new wand-equipping check + if (!EnsureMagicMode()) return true; + + _pendingSpellId = spellId; + + var fs = _core.Filter<FileService>(); + var spell = fs.SpellTable.GetById(spellId); + if (spell != null) _core.Actions.AddChatText($"[RynthAi] Casting: {spell.Name}", 5); + + _core.Actions.CastSpell(spellId, _core.CharacterFilter.Id); + _lastCastAttempt = DateTime.Now; + return true; + } + } + return false; + } + + private int FindBestSpellId(string baseName, CharFilterSkillType skill) + { + // GetDynamicSelfBuffId handles the correct priority: + // Incantation → Lore name → VII → VI → ... → I + return _spellManager.GetDynamicSelfBuffId(baseName, skill); + } + + private bool IsArmorEnchantment(string name) + { + string[] armorSpells = { + "Impenetrability", "Brogard's Defiance", "Acid Bane", "Olthoi's Bane", + "Blade Bane", "Swordsman's Bane", "Swordman's Bane", "Bludgeoning Bane", "Tusker's Bane", + "Flame Bane", "Inferno's Bane", "Frost Bane", "Gelidite's Bane", + "Lightning Bane", "Astyrrian's Bane", "Piercing Bane", "Archer's Bane" + }; + + foreach (string s in armorSpells) + { + if (name.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0) return true; + } + return false; + } + + private bool IsBuffActive(int spellId) + { + var fs = _core.Filter<FileService>(); + var targetSpell = fs.SpellTable.GetById(spellId); + if (targetSpell == null) return false; + + int targetLevel = GetSpellLevel(targetSpell); + + if (_ramBuffTimers.TryGetValue(targetSpell.Family, out RamTimerInfo timer)) + { + if (DateTime.Now < timer.Expiration.AddMinutes(-5)) + { + if (timer.SpellLevel >= targetLevel) return true; + } + } + + if (_isForceRebuffing) return false; + + if (IsArmorEnchantment(targetSpell.Name)) + { + return false; + } + + foreach (var ench in _core.CharacterFilter.Enchantments) + { + var activeSpell = fs.SpellTable.GetById(ench.SpellId); + if (activeSpell != null && activeSpell.Family == targetSpell.Family) + { + if (GetSpellLevel(activeSpell) < targetLevel) continue; + return ench.TimeRemaining > 300; + } + } + return false; + } + + private int GetSpellLevel(Spell spell) + { + if (spell == null) return 0; + string n = spell.Name; + if (n.StartsWith("Incantation")) return 8; + if (n.Contains(" VII")) return 7; + if (n.Contains(" VI")) return 6; + if (n.Contains(" V")) return 5; + if (n.Contains(" IV")) return 4; + if (n.Contains(" III")) return 3; + if (n.Contains(" II")) return 2; + if (n.EndsWith(" I") || n.Contains(" I ")) return 1; + + if (n.Contains("Mastery") || n.Contains("Blessing") || n.Contains("Aura of") || + n.Contains("Intervention") || n.Contains("Trance") || n.Contains("Recovery") || + n.Contains("Robustify") || n.Contains("Persistence") || n.Contains("Robustification") || + n.Contains("Might of the Lugians") || n.Contains("Preservance") || n.Contains("Perseverance") || + n.Contains("Honed Control") || n.Contains("Hastening") || n.Contains("Inner Calm") || + n.Contains("Mind Blossom") || n.Contains("Infected Caress") || n.Contains("Elysa's Sight") || + n.Contains("Infected Spirit") || n.Contains("Atlan's Alacrity") || n.Contains("Cragstone's Will") || + n.Contains("Brogard's Defiance") || n.Contains("Olthoi's Bane") || n.Contains("Swordsman's Bane") || + n.Contains("Swordman's Bane") || n.Contains("Tusker's Bane") || n.Contains("Inferno's Bane") || + n.Contains("Gelidite's Bane") || n.Contains("Astyrrian's Bane") || n.Contains("Archer's Bane")) + return 7; + + return 1; + } + + private int GetArchmageEnduranceCount() + { + try + { + var me = _core.WorldFilter[_core.CharacterFilter.Id]; + if (me != null) + { + int count = me.Values((LongValueKey)238, 0); + return Math.Min(Math.Max(count, 0), 5); + } + } + catch { } + return 0; + } + + private double GetCustomSpellDuration(int spellLevel) + { + double baseSeconds = 1800; + if (spellLevel == 6) baseSeconds = 2700; + else if (spellLevel == 7) baseSeconds = 3600; + else if (spellLevel == 8) baseSeconds = 5400; + + int augs = GetArchmageEnduranceCount(); + return baseSeconds * (1.0 + (augs * 0.20)); + } + + public void PrintBuffDebug() + { + int augs = GetArchmageEnduranceCount(); + _core.Actions.AddChatText($"[RynthAi] Archmage endurance count: {augs}", 1); + + if (_ramBuffTimers.Count == 0) + { + _core.Actions.AddChatText("[RynthAi] No RAM timers active.", 1); + return; + } + + foreach (var kvp in _ramBuffTimers) + { + var info = kvp.Value; + double total = GetCustomSpellDuration(info.SpellLevel); + TimeSpan left = info.Expiration - DateTime.Now; + double passed = total - left.TotalSeconds; + + _core.Actions.AddChatText($"[RynthAi] {info.SpellName} (Lvl {info.SpellLevel}): {Math.Round(passed / 60, 1)}m passed, {Math.Round(left.TotalMinutes, 1)}m left. Total: {total / 60}m", 1); + } + } + + private List<string> BuildDynamicBuffList() + { + List<string> step1_CreatureMastery = new List<string>(); + List<string> step2_Focus = new List<string>(); + List<string> step3_Willpower = new List<string>(); + List<string> step4_OtherCreature = new List<string>(); + List<string> step5_LifeAndItem = new List<string>(); + List<string> step6_WeaponAuras = new List<string>(); + List<string> step7_ArmorBanes = new List<string>(); + + foreach (string attr in BaseCreatureBuffs) + { + if (attr == "Focus Self") step2_Focus.Add(attr); + else if (attr == "Willpower Self") step3_Willpower.Add(attr); + else step4_OtherCreature.Add(attr); + } + + foreach (var kvp in CreatureSkillBuffs) + { + if (IsSkillUsable(kvp.Key)) + { + if (kvp.Value.Contains("Creature Enchantment Mastery")) + step1_CreatureMastery.Add(kvp.Value); + else if (!BaseCreatureBuffs.Contains(kvp.Value)) + step4_OtherCreature.Add(kvp.Value); + } + } + + step5_LifeAndItem.AddRange(new List<string> { + "Regeneration Self", "Rejuvenation Self", "Mana Renewal Self", + "Armor Self", "Acid Protection Self", "Fire Protection Self", + "Cold Protection Self", "Lightning Protection Self", + "Blade Protection Self", "Piercing Protection Self", + "Bludgeoning Protection Self", "Impregnability Self" + }); + + step6_WeaponAuras.AddRange(new List<string> { + "Blood Drinker Self", "Hermetic Link Self", "Heart Seeker Self", + "Spirit Drinker Self", "Swift Killer Self", "Defender Self" + }); + + step7_ArmorBanes.AddRange(new List<string> { + "Impenetrability", "Acid Bane", "Blade Bane", "Bludgeoning Bane", + "Flame Bane", "Frost Bane", "Lightning Bane", "Piercing Bane" + }); + + List<string> final = new List<string>(); + final.AddRange(step1_CreatureMastery); + final.AddRange(step2_Focus); + final.AddRange(step3_Willpower); + final.AddRange(step4_OtherCreature); + final.AddRange(step5_LifeAndItem); + final.AddRange(step6_WeaponAuras); + final.AddRange(step7_ArmorBanes); + return final; + } + + private void OnChatMsg(object sender, ChatTextInterceptEventArgs e) + { + string text = e.Text.ToLower(); + if (text.Contains("you cast ") || text.Contains("you say, ")) + { + if (_pendingSpellId != 0) + { + var fs = _core.Filter<FileService>(); + var spellInfo = fs.SpellTable.GetById(_pendingSpellId); + if (spellInfo != null) + { + int level = GetSpellLevel(spellInfo); + double dur = GetCustomSpellDuration(level); + + _ramBuffTimers[spellInfo.Family] = new RamTimerInfo + { + Expiration = DateTime.Now.AddSeconds(dur), + SpellLevel = level, + SpellName = spellInfo.Name + }; + SaveBuffTimers(); + } + _pendingSpellId = 0; + } + } + else if (text.Contains("fizzle") || text.Contains("fail") || text.Contains("component") || text.Contains("lack the mana")) + { + _lastCastAttempt = DateTime.MinValue; + _pendingSpellId = 0; + } + } + + private bool IsSkillUsable(CharFilterSkillType s) => (int)_core.CharacterFilter.Skills[s].Training >= 2; + + private CharFilterSkillType SkillForBuff(string name) + { + if (name.Contains("Impregnability") || name.Contains("Blood Drinker") || + name.Contains("Hermetic Link") || name.Contains("Heart Seeker") || + name.Contains("Spirit Drinker") || name.Contains("Swift Killer") || + name.Contains("Defender") || name.Contains("Impenetrability") || + name.Contains("Bane")) + return CharFilterSkillType.ItemEnchantment; + + if (name.Contains("Protection") || name.Contains("Armor") || + name.Contains("Regeneration") || name.Contains("Rejuvenation") || + name.Contains("Renewal") || name == "Harlune's Blessing" || + name.Contains("Stamina to Mana") || name.Contains("Revitalize") || + name.Contains("Stamina to Health") || name == "Heal Self") + return CharFilterSkillType.LifeMagic; + + return CharFilterSkillType.CreatureEnchantment; + } + + private bool EnsureMagicMode() + { + if (_core.Actions.CombatMode == CombatState.Magic) + return true; // We are in magic mode and ready to cast + + bool wandEquipped = false; + int wandToEquip = 0; + + // 1. Check ItemRules for a preferred wand + foreach (var rule in _settings.ItemRules) + { + var ruleItem = _core.WorldFilter[rule.Id]; + if (ruleItem != null && ruleItem.ObjectClass == ObjectClass.WandStaffOrb) + { + wandToEquip = ruleItem.Id; + if (ruleItem.Values(LongValueKey.EquippedSlots, 0) > 0) + { + wandEquipped = true; + } + break; // Found the preferred wand + } + } + + // 2. Fallback: Find any wand in inventory if no rule matches + if (wandToEquip == 0 && !wandEquipped) + { + foreach (WorldObject wo in _core.WorldFilter.GetInventory()) + { + if (wo.ObjectClass == ObjectClass.WandStaffOrb) + { + if (wo.Values(LongValueKey.EquippedSlots, 0) > 0) + { + wandEquipped = true; + break; + } + if (wandToEquip == 0) wandToEquip = wo.Id; + } + } + } + + // 3. Equip the wand if we aren't holding one + if (!wandEquipped && wandToEquip != 0) + { + _core.Actions.UseItem(wandToEquip, 0); + _lastCastAttempt = DateTime.Now; + return false; // Yield tick to let the server equip the item + } + + // 4. Safe to switch modes (we either have a wand equipped, or are empty-handed) + _core.Actions.SetCombatMode(CombatState.Magic); + _lastCastAttempt = DateTime.Now; + return false; // Yield tick to let the stance animation finish + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/CombatActionHelper.cs b/Plugins/RynthAi/Combat/CombatActionHelper.cs new file mode 100644 index 0000000..83f8ed0 --- /dev/null +++ b/Plugins/RynthAi/Combat/CombatActionHelper.cs @@ -0,0 +1,356 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Direct calls to acclient.exe CM_Combat functions for attack actions. + /// Derived entirely from Turbine's acclient.exe decompilation — no VTank code involved. + /// + /// Uses runtime pattern scanning to find function addresses in any client build. + /// Each CM_Combat::Event_* function writes a unique opcode DWORD into a packed buffer + /// before calling Proto_UI::SendToWeenie. We search acclient.exe's .text section for + /// these opcode write patterns, then walk backwards to find the function prologue. + /// + /// Source: acclient.exe CM_Combat namespace (IDA decompilation of Turbine's client) + /// Event_TargetedMeleeAttack — opcode 0x08, 3 args (targetID, height, power) + /// Event_TargetedMissileAttack — opcode 0x0A, 3 args (targetID, height, accuracy) + /// Event_ChangeCombatMode — opcode 0x53, 1 arg (combatMode) + /// Event_CancelAttack — opcode 0x1B7, 0 args + /// Event_QueryHealth — opcode 0x1BF, 1 arg (targetID) + /// + /// All functions are __cdecl with standard prologue: sub esp,0Ch; push ebx; push esi; push edi + /// Signature bytes: 83 EC 0C 53 56 57 E8 + /// </summary> + internal static class CombatActionHelper + { + // ── Delegate types matching __cdecl signatures ─────────────────────── + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelTargetedMeleeAttack(uint targetID, int attackHeight, float powerLevel); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelTargetedMissileAttack(uint targetID, int attackHeight, float accuracyLevel); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelChangeCombatMode(int combatMode); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelCancelAttack(); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelQueryHealth(uint targetID); + + // ── Cached delegates (created once at init) ───────────────────────── + private static DelTargetedMeleeAttack _meleeAttack; + private static DelTargetedMissileAttack _missileAttack; + private static DelChangeCombatMode _changeCombatMode; + private static DelCancelAttack _cancelAttack; + private static DelQueryHealth _queryHealth; + + private static bool _initialized; + private static Action<string> _log; + + // ── ATTACK_HEIGHT enum values (from acclient.exe) ─────────────────── + public const int ATTACK_HEIGHT_HIGH = 1; + public const int ATTACK_HEIGHT_MEDIUM = 2; + public const int ATTACK_HEIGHT_LOW = 3; + + // ── COMBAT_MODE enum values (from acclient.exe) ───────────────────── + public const int COMBAT_MODE_NONCOMBAT = 1; + public const int COMBAT_MODE_MELEE = 2; + public const int COMBAT_MODE_MISSILE = 4; + public const int COMBAT_MODE_MAGIC = 8; + + // ── Shared function prologue for all CM_Combat::Event_* functions ─── + // sub esp, 0Ch; push ebx; push esi; push edi; call OrderHdr_ctor + private static readonly byte[] CM_COMBAT_PROLOGUE = { 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8 }; + + /// <summary> + /// Scans acclient.exe's loaded image at runtime to find CM_Combat functions. + /// Call once at plugin startup. + /// </summary> + public static void Initialize(Action<string> chatLog = null) + { + _log = chatLog; + + try + { + // Find acclient.exe's base address in memory + Process proc = Process.GetCurrentProcess(); + IntPtr baseAddr = IntPtr.Zero; + int imageSize = 0; + + foreach (ProcessModule mod in proc.Modules) + { + if (mod.ModuleName.Equals("acclient.exe", StringComparison.OrdinalIgnoreCase)) + { + baseAddr = mod.BaseAddress; + imageSize = mod.ModuleMemorySize; + break; + } + } + + if (baseAddr == IntPtr.Zero) + { + Log("Pattern scan FAILED: acclient.exe module not found"); + return; + } + + Log($"acclient.exe base: 0x{baseAddr.ToInt32():X8}, size: 0x{imageSize:X}"); + + // Read the .text section into managed memory for scanning + // .text typically starts at offset 0x1000 from base + int textRva = 0x1000; + int textSize = imageSize - textRva; + if (textSize <= 0 || textSize > 0x500000) + { + Log($"Text section size suspect: 0x{textSize:X}, clamping"); + textSize = Math.Min(imageSize - textRva, 0x400000); + } + + IntPtr textBase = new IntPtr(baseAddr.ToInt32() + textRva); + byte[] text = new byte[textSize]; + Marshal.Copy(textBase, text, 0, textSize); + + int textBaseVA = baseAddr.ToInt32() + textRva; + + // ── Step 1: Find CancelAttack via unique opcode 0x1B7 ────── + // Pattern: C7 02 B7 01 00 00 (mov dword ptr [edx], 1B7h) + // This opcode value is unique in the entire binary. + byte[] cancelOpcode = { 0xC7, 0x02, 0xB7, 0x01, 0x00, 0x00 }; + int cancelOpcodeOff = FindPattern(text, cancelOpcode); + if (cancelOpcodeOff < 0) + { + Log("Pattern scan FAILED: CancelAttack opcode 0x1B7 not found"); + return; + } + + int cancelFuncOff = FindPrologueBefore(text, cancelOpcodeOff); + if (cancelFuncOff < 0) + { + Log("Pattern scan FAILED: CancelAttack prologue not found"); + return; + } + + int cancelVA = textBaseVA + cancelFuncOff; + Log($"CancelAttack found at 0x{cancelVA:X8}"); + + // ── Step 2: Search near CancelAttack for the others ──────── + // All CM_Combat::Event_* functions cluster within ~0x500 bytes + int regionStart = Math.Max(0, cancelOpcodeOff - 0x500); + int regionEnd = Math.Min(text.Length, cancelOpcodeOff + 0x500); + + // ChangeCombatMode: opcode 0x53 (unique in CM_Combat region) + byte[] changeModeOpcode = { 0xC7, 0x02, 0x53, 0x00, 0x00, 0x00 }; + int changeModeOff = FindPatternInRegion(text, changeModeOpcode, regionStart, regionEnd); + int changeModeFuncOff = changeModeOff >= 0 ? FindPrologueBefore(text, changeModeOff) : -1; + + // QueryHealth: opcode 0x1BF (unique in entire binary) + byte[] queryHealthOpcode = { 0xC7, 0x02, 0xBF, 0x01, 0x00, 0x00 }; + int queryHealthOff = FindPatternInRegion(text, queryHealthOpcode, regionStart, regionEnd); + int queryHealthFuncOff = queryHealthOff >= 0 ? FindPrologueBefore(text, queryHealthOff) : -1; + + // MeleeAttack: opcode 0x08 (common globally, but unique in CM_Combat region) + byte[] meleeOpcode = { 0xC7, 0x02, 0x08, 0x00, 0x00, 0x00 }; + int meleeOff = FindPatternInRegion(text, meleeOpcode, regionStart, regionEnd); + int meleeFuncOff = meleeOff >= 0 ? FindPrologueBefore(text, meleeOff) : -1; + + // MissileAttack: opcode 0x0A (search in CM_Combat region only) + byte[] missileOpcode = { 0xC7, 0x02, 0x0A, 0x00, 0x00, 0x00 }; + int missileOff = FindPatternInRegion(text, missileOpcode, regionStart, regionEnd); + int missileFuncOff = missileOff >= 0 ? FindPrologueBefore(text, missileOff) : -1; + + // ── Step 3: Verify all found ─────────────────────────────── + if (changeModeFuncOff < 0 || queryHealthFuncOff < 0 || + meleeFuncOff < 0 || missileFuncOff < 0) + { + Log($"Pattern scan INCOMPLETE: CancelAttack=OK, " + + $"ChangeCombatMode={changeModeFuncOff >= 0}, " + + $"QueryHealth={queryHealthFuncOff >= 0}, " + + $"MeleeAttack={meleeFuncOff >= 0}, " + + $"MissileAttack={missileFuncOff >= 0}"); + return; + } + + int changeModeVA = textBaseVA + changeModeFuncOff; + int queryHealthVA = textBaseVA + queryHealthFuncOff; + int meleeVA = textBaseVA + meleeFuncOff; + int missileVA = textBaseVA + missileFuncOff; + + Log($"ChangeCombatMode at 0x{changeModeVA:X8}"); + Log($"QueryHealth at 0x{queryHealthVA:X8}"); + Log($"MeleeAttack at 0x{meleeVA:X8}"); + Log($"MissileAttack at 0x{missileVA:X8}"); + + // Verify all have the expected prologue bytes + if (!VerifyPrologue(text, cancelFuncOff) || + !VerifyPrologue(text, changeModeFuncOff) || + !VerifyPrologue(text, queryHealthFuncOff) || + !VerifyPrologue(text, meleeFuncOff) || + !VerifyPrologue(text, missileFuncOff)) + { + Log("Pattern scan FAILED: prologue verification failed"); + return; + } + + // ── Step 4: Create delegates ─────────────────────────────── + _cancelAttack = (DelCancelAttack)Marshal.GetDelegateForFunctionPointer( + new IntPtr(cancelVA), typeof(DelCancelAttack)); + _changeCombatMode = (DelChangeCombatMode)Marshal.GetDelegateForFunctionPointer( + new IntPtr(changeModeVA), typeof(DelChangeCombatMode)); + _queryHealth = (DelQueryHealth)Marshal.GetDelegateForFunctionPointer( + new IntPtr(queryHealthVA), typeof(DelQueryHealth)); + _meleeAttack = (DelTargetedMeleeAttack)Marshal.GetDelegateForFunctionPointer( + new IntPtr(meleeVA), typeof(DelTargetedMeleeAttack)); + _missileAttack = (DelTargetedMissileAttack)Marshal.GetDelegateForFunctionPointer( + new IntPtr(missileVA), typeof(DelTargetedMissileAttack)); + + _initialized = true; + Log("CombatActionHelper initialized — all 5 CM_Combat functions found via pattern scan"); + } + catch (Exception ex) + { + _initialized = false; + Log("CombatActionHelper init FAILED: " + ex.Message); + } + } + + public static bool IsInitialized => _initialized; + + // ══════════════════════════════════════════════════════════════════════ + // PUBLIC API + // ══════════════════════════════════════════════════════════════════════ + + public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel) + { + if (!_initialized) return false; + try + { + return _meleeAttack(targetId, attackHeight, Math.Max(0f, Math.Min(1f, powerLevel))); + } + catch (Exception ex) { Log("MeleeAttack failed: " + ex.Message); return false; } + } + + public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel) + { + if (!_initialized) return false; + try + { + return _missileAttack(targetId, attackHeight, Math.Max(0f, Math.Min(1f, accuracyLevel))); + } + catch (Exception ex) { Log("MissileAttack failed: " + ex.Message); return false; } + } + + public static bool ChangeCombatMode(int combatMode) + { + if (!_initialized) return false; + try { return _changeCombatMode(combatMode); } + catch (Exception ex) { Log("ChangeCombatMode failed: " + ex.Message); return false; } + } + + public static bool CancelAttack() + { + if (!_initialized) return false; + try { return _cancelAttack(); } + catch (Exception ex) { Log("CancelAttack failed: " + ex.Message); return false; } + } + + public static bool QueryHealth(uint targetId) + { + if (!_initialized) return false; + try { return _queryHealth(targetId); } + catch (Exception ex) { Log("QueryHealth failed: " + ex.Message); return false; } + } + + /// <summary> + /// Maps UISettings height (0=Low, 1=Medium, 2=High) to AC ATTACK_HEIGHT enum. + /// </summary> + public static int MapAttackHeight(int uiHeight) + { + switch (uiHeight) + { + case 0: return ATTACK_HEIGHT_LOW; + case 2: return ATTACK_HEIGHT_HIGH; + default: return ATTACK_HEIGHT_MEDIUM; + } + } + + // ══════════════════════════════════════════════════════════════════════ + // PATTERN SCANNER + // ══════════════════════════════════════════════════════════════════════ + + private static int FindPattern(byte[] data, byte[] pattern) + { + return FindPatternInRegion(data, pattern, 0, data.Length); + } + + private static int FindPatternInRegion(byte[] data, byte[] pattern, int start, int end) + { + int limit = Math.Min(end, data.Length) - pattern.Length; + for (int i = Math.Max(0, start); i <= limit; i++) + { + bool match = true; + for (int j = 0; j < pattern.Length; j++) + { + if (data[i + j] != pattern[j]) + { + match = false; + break; + } + } + if (match) return i; + } + return -1; + } + + /// <summary> + /// Walks backwards from an opcode write to find the CM_Combat function prologue. + /// Must be preceded by CC (int3), 90 (nop), or C3 (ret). + /// </summary> + private static int FindPrologueBefore(byte[] data, int opcodeOffset) + { + for (int back = 1; back < 300; back++) + { + int pos = opcodeOffset - back; + if (pos < 1 || pos + CM_COMBAT_PROLOGUE.Length > data.Length) + continue; + + bool match = true; + for (int j = 0; j < CM_COMBAT_PROLOGUE.Length; j++) + { + if (data[pos + j] != CM_COMBAT_PROLOGUE[j]) + { + match = false; + break; + } + } + + if (match) + { + byte prev = data[pos - 1]; + if (prev == 0xCC || prev == 0x90 || prev == 0xC3) + return pos; + } + } + return -1; + } + + private static bool VerifyPrologue(byte[] data, int offset) + { + if (offset < 0 || offset + CM_COMBAT_PROLOGUE.Length > data.Length) + return false; + for (int i = 0; i < CM_COMBAT_PROLOGUE.Length; i++) + { + if (data[offset + i] != CM_COMBAT_PROLOGUE[i]) + return false; + } + return true; + } + + private static void Log(string msg) + { + try { _log?.Invoke($"[RynthAi] {msg}"); } catch { } + } + } +} diff --git a/Plugins/RynthAi/Combat/CombatManager.cs b/Plugins/RynthAi/Combat/CombatManager.cs new file mode 100644 index 0000000..d248ee7 --- /dev/null +++ b/Plugins/RynthAi/Combat/CombatManager.cs @@ -0,0 +1,1302 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; +using NexSuite.Plugins.RynthAi.Raycasting; + +namespace NexSuite.Plugins.RynthAi +{ + public class CombatManager : IDisposable + { + private CoreManager _coreManager; + private PluginHost _host; + private RynthAiUI _ui; + private UISettings _settings; + private SpellManager _spellManager; + + private MainLogic _raycastSystem; + public bool RaycastInitialized { get; private set; } + + public int activeTargetId = 0; + private DateTime lastAttackCmd = DateTime.MinValue; + private DateTime lastStanceAttempt = DateTime.MinValue; + private DateTime _lastPeaceAttempt = DateTime.MinValue; + private DateTime lastTargetSearchTime = DateTime.MinValue; + private const int TARGET_SEARCH_INTERVAL_MS = 500; + + // --- Magic Combat --- + private DateTime _lastSpellCast = DateTime.MinValue; + private const double SPELL_CAST_COOLDOWN_MS = 1500.0; // Debuff cast recovery + private const double ATTACK_SPELL_COOLDOWN_MS = 100.0; // War/void spam as fast as possible + + // Flag: when melee/missile needs debuffs, we temporarily switch to wand. + // After debuffs are done, switch back. + private bool _returnToPhysicalCombat = false; + private int _savedWeaponId = 0; // Weapon to re-equip after debuffs + + // Element vulnerability spell bases (used by V light) + private static readonly Dictionary<string, string[]> VulnSpells = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) + { + { "Fire", new[] { "Fire Vulnerability Other" } }, + { "Cold", new[] { "Cold Vulnerability Other" } }, + { "Lightning", new[] { "Lightning Vulnerability Other" } }, + { "Acid", new[] { "Acid Vulnerability Other" } }, + { "Blade", new[] { "Blade Vulnerability Other" } }, + { "Slash", new[] { "Blade Vulnerability Other" } }, + { "Pierce", new[] { "Piercing Vulnerability Other" } }, + { "Bludgeon", new[] { "Bludgeoning Vulnerability Other" } }, + }; + + private Dictionary<int, BlacklistedTarget> blacklistedTargets = new Dictionary<int, BlacklistedTarget>(); + + // Configurable blacklist manager — uses UISettings.BlacklistAttempts/BlacklistTimeoutSec + private Raycasting.BlacklistManager _blacklistManager = new Raycasting.BlacklistManager(); + private DateTime _lastAttackFeedbackCheck = DateTime.MinValue; + private int _lastAttackedTargetId = 0; + + public int RaycastBlockCount { get; private set; } + public int RaycastCheckCount { get; private set; } + + + + private class BlacklistedTarget + { + public int TargetId { get; set; } + public DateTime BlacklistedTime { get; set; } + public bool IsLosBlocked { get; set; } + public bool IsExpired() + { + // LOS-blocked targets get a shorter blacklist (5s) since player moves + double duration = IsLosBlocked ? 5000 : 20000; + return (DateTime.Now - BlacklistedTime).TotalMilliseconds > duration; + } + } + + public CombatManager(CoreManager coreManager, UISettings settings, PluginHost host = null, SpellManager spellManager = null) + { + _coreManager = coreManager ?? throw new ArgumentNullException(nameof(coreManager)); + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _host = host; + _spellManager = spellManager; + } + + public void SetSpellManager(SpellManager spellManager) + { + _spellManager = spellManager; + } + + // --- Monster Weaknesses (from monsters.json) --- + private Dictionary<string, string> _monsterWeaknesses = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + + public void SetMonsterWeaknesses(Dictionary<string, string> weaknesses) + { + _monsterWeaknesses = weaknesses ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + } + + // --- Debuff tracking (chat-driven: spam until confirmed) --- + // Tracks which debuffs have been CONFIRMED on the current target via chat + // Key: "targetId_debuffKey" — only added on "You cast X" chat message + private HashSet<string> _confirmedDebuffs = new HashSet<string>(); + private int _lastDebuffTargetId = 0; + + // Pending debuff: cast sent, waiting for chat result + private string _pendingDebuffKey = null; + private int _pendingDebuffTargetId = 0; + private int _pendingDebuffTier = 0; + private bool _waitingForDebuffResult = false; + private DateTime _pendingDebuffCastTime = DateTime.MinValue; + private const double DEBUFF_RESULT_TIMEOUT_MS = 3000.0; // Safety: assume success after 3s + + // Debuff spell definitions — base name for tiered resolution, plus optional lore name + // Format: { key, (tieredBase, loreName) } + // Resolver order: Incantation of [base] → [lore] → [base] VII → VI → ... → I + private static readonly Dictionary<string, string[]> DebuffSpells = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) + { + // { key, { tieredBase, loreName } } + { "Fester", new[] { "Fester Other", "Decrepitude's Grasp" } }, + { "Broadside", new[] { "Missile Weapon Ineptitude Other", "Broadside of a Barn" } }, + { "Gravity", new[] { "Vulnerability Other", "Gravity Well" } }, + { "Imperil", new[] { "Imperil Other", "Gossamer Flesh" } }, + { "Yield", new[] { "Magic Yield Other", "Yield" } }, + }; + + // Spell shape base names for war/void + // Arc spells: "X Arc" pattern + // Ring spells: "X Ring" pattern (+ lore names for T6/T7/T8) + // Streak spells: "X Streak" pattern + // Bolt spells: "X Bolt" pattern (default) + private static readonly Dictionary<string, string[]> SpellShapes = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) + { + // element → { Arc, Ring, Streak, Bolt } base patterns + { "Fire", new[] { "Flame Arc", "Ring of Fire", "Flame Streak", "Flame Bolt" } }, + { "Cold", new[] { "Frost Arc", "Frost Ring", "Frost Streak", "Frost Bolt" } }, + { "Lightning", new[] { "Lightning Arc", "Shock Ring", "Lightning Streak", "Shock Wave" } }, + { "Acid", new[] { "Acid Arc", "Acid Ring", "Acid Streak", "Acid Stream" } }, + { "Blade", new[] { "Blade Arc", "Blade Ring", "Blade Streak", "Whirling Blade" } }, + { "Pierce", new[] { "Force Arc", "Force Ring", "Force Streak", "Force Bolt" } }, + { "Bludgeon", new[] { "Bludgeoning Arc", "Bludgeoning Ring", "Bludgeoning Streak", "Shock Wave" } }, + { "Slash", new[] { "Blade Arc", "Blade Ring", "Blade Streak", "Whirling Blade" } }, + }; + + // Ring spell LORE NAMES — AC ring spells use unique names at T6/T7 + // These don't follow the standard "Base VII" pattern + // Format: element → { T6 lore, T7 lore } + private static readonly Dictionary<string, string[]> RingLoreNames = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) + { + { "Fire", new[] { "Cassius' Ring of Fire", "Cassius' Ring of Fire II" } }, + { "Cold", new[] { "Halo of Frost", "Halo of Frost II" } }, + { "Lightning", new[] { "Eye of the Storm", "Eye of the Storm II" } }, + { "Acid", new[] { "Searing Disc", "Searing Disc II" } }, + { "Blade", new[] { "Horizon's Blades", "Horizon's Blades II" } }, + { "Slash", new[] { "Horizon's Blades", "Horizon's Blades II" } }, + { "Pierce", new[] { "Nuhumudira's Spines", "Nuhumudira's Spines II" } }, + { "Bludgeon", new[] { "Tectonic Rifts", "Tectonic Rifts II" } }, + }; + + // Void Magic equivalents + private static readonly Dictionary<string, string[]> VoidSpellShapes = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) + { + { "Nether", new[] { "Nether Arc", "Nether Ring", "Nether Streak", "Nether Bolt" } }, + { "Fire", new[] { "Corrosion Arc", "Corrosion Ring", "Corrosion Streak", "Nether Bolt" } }, + }; + + public void InitializeRaycasting(string acFolderPath = null) + { + try + { + _raycastSystem = new MainLogic(); + if (string.IsNullOrEmpty(acFolderPath)) acFolderPath = @"C:\Turbine\Asheron's Call"; + RaycastInitialized = _raycastSystem.Initialize(acFolderPath); + } + catch { RaycastInitialized = false; } + } + + public void AttachUI(RynthAiUI ui) { _ui = ui; } + + /// <summary> + /// Called by PluginCore when chat messages arrive. Tracks debuff results: + /// "You cast X on Y" → SUCCESS → add to confirmed set, immediately ready for next + /// "Your spell fizzled" → FIZZLE → clear pending, recast same debuff + /// "Y resists your spell" → RESIST → clear pending, recast same debuff + /// </summary> + public void HandleChatForDebuffs(string text) + { + if (!_waitingForDebuffResult || string.IsNullOrEmpty(text)) return; + + // SUCCESS: "You cast Incantation of Imperil Other on Drudge Skulker" + if (text.StartsWith("You cast ", StringComparison.OrdinalIgnoreCase)) + { + string key = $"{_pendingDebuffTargetId}_{_pendingDebuffKey}"; + _confirmedDebuffs.Add(key); + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; // Reset cooldown from this moment + return; + } + + // FIZZLE: "Your spell fizzled." + if (text.IndexOf("fizzle", StringComparison.OrdinalIgnoreCase) >= 0) + { + try { _host?.Actions?.AddChatText($"[RynthAi] Fizzled: {_pendingDebuffKey} — recasting", 2); } catch { } + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; // Reset cooldown from this moment + return; + } + + // RESIST: "X resists your spell" + if (text.IndexOf("resists your spell", StringComparison.OrdinalIgnoreCase) >= 0) + { + try { _host?.Actions?.AddChatText($"[RynthAi] Resisted: {_pendingDebuffKey} — recasting", 2); } catch { } + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; + return; + } + } + + /// <summary> + /// Called by PluginCore when a health ratio update is received for a target. + /// Clears the blacklist failure counter since the mob is taking damage. + /// </summary> + public void ReportDamageOnTarget(int targetId) + { + _blacklistManager.ClearFailure(targetId); + } + + /// <summary> + /// Called internally after an attack command is sent. If no damage feedback + /// arrives within a window, the next attack attempt increments the failure count. + /// </summary> + private void TrackAttackAttempt(int targetId) + { + if (_lastAttackedTargetId != 0 && _lastAttackedTargetId == targetId) + { + // We attacked this same target last tick too — if no damage feedback + // was received since last attack, count it as a failure + if (_lastAttackFeedbackCheck != DateTime.MinValue && + (DateTime.Now - _lastAttackFeedbackCheck).TotalMilliseconds > 2500) + { + _blacklistManager.ReportFailure(targetId); + if (_blacklistManager.IsBlacklisted(targetId)) + { + try { _host?.Actions?.AddChatText($"[RynthAi] Blacklisted mob (no damage feedback): id={targetId}", 2); } catch { } + } + } + } + _lastAttackedTargetId = targetId; + _lastAttackFeedbackCheck = DateTime.Now; + } + + public bool Think() + { + if (!_settings.EnableCombat) return false; + + double acDistanceLimit = (_settings.MonsterRange) / 240.0; + CleanupExpiredBlacklist(); + + // Sync configurable blacklist settings from UI + _blacklistManager.AttemptThreshold = _settings.BlacklistAttempts; + _blacklistManager.TimeoutSeconds = _settings.BlacklistTimeoutSec; + + // Update raycast scan distance: MonsterRange + 40m buffer + // MonsterRange is in yards ≈ meters. Convert to actual meters for the scan radius. + if (_raycastSystem?.TargetingFSM != null) + _raycastSystem.TargetingFSM.MaxScanDistanceMeters = _settings.MonsterRange + 40.0f; + + // Validate current target + if (activeTargetId != 0) + { + var target = _coreManager.WorldFilter[activeTargetId]; + if (target == null || (int)target.ObjectClass != 5 || blacklistedTargets.ContainsKey(activeTargetId) || _blacklistManager.IsBlacklisted(activeTargetId)) + activeTargetId = 0; + // Target lock: don't drop a target we're actively fighting just because + // it moved slightly. Use 1.5x range for disengage so we finish the kill. + else if (_coreManager.WorldFilter.Distance(_coreManager.CharacterFilter.Id, activeTargetId) > acDistanceLimit * 1.5) + activeTargetId = 0; + } + + // Find a new target if we don't have one + if (activeTargetId == 0) + { + if ((DateTime.Now - lastTargetSearchTime).TotalMilliseconds > TARGET_SEARCH_INTERVAL_MS) + { + HandleCombatTrigger(); + lastTargetSearchTime = DateTime.Now; + } + + if (activeTargetId == 0 && _settings.PeaceModeWhenIdle) + { + if (_coreManager.Actions.CombatMode != Decal.Adapter.Wrappers.CombatState.Peace) + { + if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > 2000) + { + _coreManager.Actions.SetCombatMode(Decal.Adapter.Wrappers.CombatState.Peace); + _lastPeaceAttempt = DateTime.Now; + } + } + } + return true; + } + + var targetObj = _coreManager.WorldFilter[activeTargetId]; + if (targetObj == null) { activeTargetId = 0; return true; } + + // If still in Peace mode, force combat mode based on what's equipped + if (_coreManager.Actions.CombatMode == Decal.Adapter.Wrappers.CombatState.Peace) + { + if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > 1500) + { + _lastPeaceAttempt = DateTime.Now; + EquipWeaponAndSetStance(targetObj, "Auto"); + + // If STILL in peace, scan equipped items and force the right stance + if (_coreManager.Actions.CombatMode == Decal.Adapter.Wrappers.CombatState.Peace) + { + foreach (var inv in _coreManager.WorldFilter.GetInventory()) + { + if (inv.Values(LongValueKey.EquippedSlots, 0) <= 0) continue; + if (inv.ObjectClass == ObjectClass.WandStaffOrb) + { _coreManager.Actions.SetCombatMode(CombatState.Magic); break; } + else if (inv.ObjectClass == ObjectClass.MeleeWeapon) + { _coreManager.Actions.SetCombatMode(CombatState.Melee); break; } + else if (inv.ObjectClass == ObjectClass.MissileWeapon) + { _coreManager.Actions.SetCombatMode(CombatState.Missile); break; } + } + } + } + return true; // Yield this tick — let stance change process + } + + if ((DateTime.Now - lastAttackCmd).TotalMilliseconds >= 1000) + { + // LOS gate: verify EVERY shot + if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem != null) + { + // Determine attack type: weapon-based for melee/missile, shape-based for magic + TargetingFSM.AttackType attackType = DetermineAttackTypeForLOS(targetObj); + + RaycastCheckCount++; + if (_raycastSystem.IsTargetBlocked(_coreManager, targetObj, attackType)) + { + RaycastBlockCount++; + try { _host?.Actions?.AddChatText($"[RynthAi] LOS blocked: {targetObj.Name} — dropping", 1); } catch { } + activeTargetId = 0; + return true; + } + } + + FaceTarget(targetObj); + _coreManager.Actions.SelectItem(activeTargetId); + + // MAGIC COMBAT: If we're in magic mode with a wand, cast spells + if (_coreManager.Actions.CombatMode == CombatState.Magic && _spellManager != null) + { + AttackWithMagic(targetObj); + + // If we were in magic mode for debuffs only, check if done → switch back + if (_returnToPhysicalCombat) + { + var rule2 = GetRuleForTarget(targetObj); + string elem2 = GetPreferredElement(targetObj, rule2); + if (rule2 != null && !HasPendingDebuffs(rule2, elem2)) + { + // All debuffs confirmed — switch back to physical weapon + _returnToPhysicalCombat = false; + if (_savedWeaponId != 0) + { + _coreManager.Actions.UseItem(_savedWeaponId, 0); + _savedWeaponId = 0; + } + EquipWeaponAndSetStance(targetObj, "Auto"); + } + } + } + else + { + // Melee / Missile mode + var rule = GetRuleForTarget(targetObj); + + // Check if debuffs need casting before physical attack + if (rule != null && _spellManager != null && !_returnToPhysicalCombat) + { + string elem = GetPreferredElement(targetObj, rule); + if (HasPendingDebuffs(rule, elem)) + { + // Find wand in ItemRules to cast debuffs + int wandId = FindWandInItems(); + if (wandId != 0) + { + // Save current weapon, switch to wand for debuffs + var equipped = _coreManager.WorldFilter.GetInventory() + .FirstOrDefault(w => w.Values(LongValueKey.EquippedSlots, 0) > 0 && + (w.ObjectClass == ObjectClass.MeleeWeapon || w.ObjectClass == ObjectClass.MissileWeapon)); + _savedWeaponId = equipped?.Id ?? 0; + _returnToPhysicalCombat = true; + _coreManager.Actions.UseItem(wandId, 0); + _coreManager.Actions.SetCombatMode(CombatState.Magic); + lastAttackCmd = DateTime.Now; + return true; // Yield — next tick will be in magic mode + } + } + } + + bool anyAttackLight = (rule == null) || rule.UseArc || rule.UseBolt || rule.UseRing || rule.UseStreak; + if (!anyAttackLight) + { + // No attack shape selected — do not attack in melee/missile mode + } + else + { + AttackTarget(); + } + } + TrackAttackAttempt(activeTargetId); + lastAttackCmd = DateTime.Now; + } + return true; + } + + public void OnHeartbeat() + { + if (!_settings.IsMacroRunning) return; + + // === YIELD to any higher-priority system that has claimed the state === + if (_settings.CurrentState != "Idle" && _settings.CurrentState != "Combat") return; + + if (_settings.EnableCombat) + { + Think(); + + // If Think() found or maintained a target, we are in combat + if (activeTargetId != 0) + { + _settings.CurrentState = "Combat"; + var target = _coreManager.WorldFilter[activeTargetId]; + if (target != null) EquipWeaponAndSetStance(target, "Auto"); + } + // If no target, leave state as-is (dispatcher resets to Idle each frame) + } + } + + public void HandleCombatTrigger() + { + double acDistanceLimit = (_settings.MonsterRange) / 240.0; + + // For target SEARCH, use weapon/mode-based attack type (no specific rule yet) + TargetingFSM.AttackType attackType = TargetingFSM.AttackType.Linear; + if (RaycastInitialized && _raycastSystem?.TargetingFSM != null) + attackType = _raycastSystem.GetAttackType(_coreManager); + + int targetId = FindBestVisibleTarget(acDistanceLimit, attackType); + if (targetId != 0 && targetId != activeTargetId) + { + activeTargetId = targetId; + + var target = _coreManager.WorldFilter[targetId]; + if (target != null) EquipWeaponAndSetStance(target, "Auto"); + } + } + + private int FindBestVisibleTarget(double maxDist, TargetingFSM.AttackType attackType) + { + int foundId = 0; + int playerId = _coreManager.CharacterFilter.Id; + var candidates = new List<KeyValuePair<int, double>>(); + + foreach (var wo in _coreManager.WorldFilter.GetLandscape()) + { + if ((int)wo.ObjectClass != 5 || blacklistedTargets.ContainsKey(wo.Id) || _blacklistManager.IsBlacklisted(wo.Id)) continue; + double dist = _coreManager.WorldFilter.Distance(playerId, wo.Id); + if (dist <= maxDist) candidates.Add(new KeyValuePair<int, double>(wo.Id, dist)); + } + + candidates.Sort((a, b) => a.Value.CompareTo(b.Value)); + + foreach (var candidate in candidates) + { + int id = candidate.Key; + if (_settings.EnableRaycasting && RaycastInitialized) + { + RaycastCheckCount++; + if (_raycastSystem.IsTargetBlocked(_coreManager, _coreManager.WorldFilter[id], attackType)) + { + RaycastBlockCount++; + continue; + } + } + foundId = id; + break; + } + return foundId; + } + + private DateTime _lastEquipTime = DateTime.MinValue; + private DateTime _lastStanceTime = DateTime.MinValue; + + private void EquipWeaponAndSetStance(WorldObject target, string monsterWeakness = "Auto") + { + if (target == null) return; + + int targetWeaponId = 0; + + // 1. Target Resolution + var rule = _settings.MonsterRules.FirstOrDefault(r => target.Name.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0); + + if (rule == null) + { + rule = _settings.MonsterRules.FirstOrDefault(m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + } + + string desired = (rule != null && rule.DamageType != "Auto") ? rule.DamageType : monsterWeakness; + + if (rule != null && rule.WeaponId != 0) + { + targetWeaponId = rule.WeaponId; + } + else + { + var bestWeapon = _settings.ItemRules.FirstOrDefault(i => i.Element.Equals(desired, StringComparison.OrdinalIgnoreCase)) + ?? _settings.ItemRules.FirstOrDefault(); + if (bestWeapon != null) targetWeaponId = bestWeapon.Id; + } + + if (targetWeaponId == 0) return; + + var weaponObj = _coreManager.WorldFilter[targetWeaponId]; + if (weaponObj == null) return; + + // 2. Equipment Enforcement + bool isEquipped = weaponObj.Values(LongValueKey.EquippedSlots, 0) > 0; + + if (!isEquipped) + { + // Reverted to 1000ms (1 second) to prevent bare-hand attacks during slow animations + if ((DateTime.Now - _lastEquipTime).TotalMilliseconds > 1000) + { + _coreManager.Actions.UseItem(targetWeaponId, 0); + _lastEquipTime = DateTime.Now; + _lastStanceTime = DateTime.Now; // Reset stance timer to sync with new equip + } + return; + } + + // 3. Stance Enforcement + // Increased to 1000ms to allow the server to finish the "Draw Weapon" animation + if ((DateTime.Now - _lastStanceTime).TotalMilliseconds > 1000) + { + bool changedStance = false; + + if (weaponObj.ObjectClass == ObjectClass.MeleeWeapon && _coreManager.Actions.CombatMode != CombatState.Melee) + { + _coreManager.Actions.SetCombatMode(CombatState.Melee); + changedStance = true; + } + else if (weaponObj.ObjectClass == ObjectClass.MissileWeapon && _coreManager.Actions.CombatMode != CombatState.Missile) + { + _coreManager.Actions.SetCombatMode(CombatState.Missile); + changedStance = true; + } + else if (weaponObj.ObjectClass == ObjectClass.WandStaffOrb && _coreManager.Actions.CombatMode != CombatState.Magic) + { + _coreManager.Actions.SetCombatMode(CombatState.Magic); + changedStance = true; + } + + if (changedStance) _lastStanceTime = DateTime.Now; + } + } + + public string GetRaycastStatus() + { + if (_raycastSystem == null) return "Raycasting: NOT INITIALIZED"; + string status = _settings.EnableRaycasting ? "ACTIVE" : "DISABLED"; + return "Raycasting: " + status + "\n Status: " + _raycastSystem.StatusMessage + "\n" + + " Checks: " + RaycastCheckCount + ", Blocks: " + RaycastBlockCount; + } + + public List<string> GetRaycastDiagLog() + { + var lines = new List<string>(); + if (_raycastSystem?.GeometryLoader?.DiagLog != null) + foreach (var line in _raycastSystem.GeometryLoader.DiagLog) lines.Add(line); + return lines; + } + + /// <summary> + /// Determines the correct LOS check type based on combat mode and spell shape. + /// - Magic + Arc spell shape → MagicArc (same trajectory as missiles) + /// - Magic + Bolt/Streak/Ring → Linear (straight line) + /// - Missile mode → delegates to FSM (BowArc, ThrownArc, or Linear for crossbow) + /// - Melee/Peace → Linear + /// </summary> + private TargetingFSM.AttackType DetermineAttackTypeForLOS(WorldObject target) + { + // Magic mode: check spell shape from monster rule + if (_coreManager.Actions.CombatMode == CombatState.Magic) + { + var rule = GetRuleForTarget(target); + if (rule != null && rule.UseArc) + return TargetingFSM.AttackType.MagicArc; + + // Bolts, Streaks, Rings = straight line + return TargetingFSM.AttackType.Linear; + } + + // Missile/Melee: use weapon-based detection + if (_raycastSystem?.TargetingFSM != null) + return _raycastSystem.GetAttackType(_coreManager); + + return TargetingFSM.AttackType.Linear; + } + + private void FaceTarget(WorldObject target) + { + try + { + var p = _coreManager.WorldFilter[_coreManager.CharacterFilter.Id]; + double dx = target.Coordinates().EastWest - p.Coordinates().EastWest; + double dy = target.Coordinates().NorthSouth - p.Coordinates().NorthSouth; + double heading = Math.Atan2(dx, dy) * (180.0 / Math.PI); + if (heading < 0) heading += 360.0; + _coreManager.Actions.Heading = (float)heading; + } + catch { } + } + + private void AttackTarget() + { + try + { + if (!CombatActionHelper.IsInitialized) return; + + bool isMissile = _coreManager.Actions.CombatMode == CombatState.Missile; + uint targetId = (uint)activeTargetId; + + // Resolve attack power (0.0–1.0) + int powerPct = isMissile ? _settings.MissileAttackPower : _settings.MeleeAttackPower; + float power; + if (powerPct < 0) + { + // Auto mode: 100% unless Recklessness is enabled and trained + power = 1.0f; + if (_settings.UseRecklessness) + { + try + { + int reckTraining = (int)_coreManager.CharacterFilter + .Skills[CharFilterSkillType.Recklessness].Training; + if (reckTraining >= 2) // Trained or Specialized + power = 0.8f; + } + catch { } + } + } + else + { + power = powerPct / 100f; + } + + // Map UI height (0=Low,1=Med,2=High) → AC ATTACK_HEIGHT enum + int uiHeight = isMissile ? _settings.MissileAttackHeight : _settings.MeleeAttackHeight; + int acHeight = CombatActionHelper.MapAttackHeight(uiHeight); + + // Send attack directly via acclient.exe CM_Combat functions + if (isMissile) + CombatActionHelper.MissileAttack(targetId, acHeight, power); + else + CombatActionHelper.MeleeAttack(targetId, acHeight, power); + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // MAGIC COMBAT SYSTEM + // Supports: debuff lights (F/B/G/I/Y/V), spell shapes (A/R/S/B=default Bolt), + // monsters.json weakness lookup, War + Void magic + // If none of A/R/S/B are set → no attack (buff bot mode) + // ══════════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Resolves the MonsterRule for a target (specific rule first, then Default). + /// Cached per-target so we don't re-scan every frame. + /// </summary> + private MonsterRule GetRuleForTarget(WorldObject target) + { + if (target == null) return null; + // Specific name match first + var rule = _settings.MonsterRules.FirstOrDefault( + r => !r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase) && + target.Name.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0); + if (rule != null) return rule; + // Fall back to Default + return _settings.MonsterRules.FirstOrDefault( + m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + } + + private void AttackWithMagic(WorldObject target) + { + if (_spellManager == null || target == null) return; + if ((DateTime.Now - _lastSpellCast).TotalMilliseconds < SPELL_CAST_COOLDOWN_MS) return; + + // If waiting for debuff result, check timeout only + if (_waitingForDebuffResult) + { + if ((DateTime.Now - _pendingDebuffCastTime).TotalMilliseconds > DEBUFF_RESULT_TIMEOUT_MS) + { + // Timed out — assume success, add to confirmed + _confirmedDebuffs.Add($"{_pendingDebuffTargetId}_{_pendingDebuffKey}"); + _waitingForDebuffResult = false; + } + else + { + return; // Still waiting for chat — don't cast anything + } + } + + // Clear confirmed debuffs if target changed + if (activeTargetId != _lastDebuffTargetId) + { + _confirmedDebuffs.Clear(); + _lastDebuffTargetId = activeTargetId; + } + + var rule = GetRuleForTarget(target); + string element = GetPreferredElement(target, rule); + + // ── Phase 1: Debuffs — spam until chat confirms each one ── + if (rule != null) + { + var pendingDebuffs = BuildDebuffList(rule, element); + + foreach (var debuffKey in pendingDebuffs) + { + string key = $"{activeTargetId}_{debuffKey}"; + + if (_confirmedDebuffs.Contains(key)) + continue; // Chat confirmed this one — move on + + int spellId = 0; + int castTier = 0; + if (debuffKey.StartsWith("Vuln:")) + spellId = FindBestVulnSpellWithTier(debuffKey.Substring(5), out castTier); + else + spellId = FindBestDebuffSpellWithTier(debuffKey, out castTier); + + if (spellId == 0) continue; + + try + { + _coreManager.Actions.CastSpell(spellId, activeTargetId); + _lastSpellCast = DateTime.Now; + _pendingDebuffKey = debuffKey; + _pendingDebuffTargetId = activeTargetId; + _pendingDebuffTier = castTier; + _waitingForDebuffResult = true; + _pendingDebuffCastTime = DateTime.Now; + try { _host?.Actions?.AddChatText($"[RynthAi] Casting: {debuffKey} (T{castTier}) on {target.Name}", 5); } catch { } + } + catch { } + return; // Wait for chat result + } + } + + // ── Phase 2: War/Void spell spam — faster cooldown ── + if ((DateTime.Now - _lastSpellCast).TotalMilliseconds < ATTACK_SPELL_COOLDOWN_MS) return; + + if (rule != null && !rule.UseArc && !rule.UseRing && !rule.UseStreak && !rule.UseBolt) + return; + + int offensiveSpellId = FindBestShapedSpell(element, rule); + if (offensiveSpellId != 0) + { + try + { + _coreManager.Actions.CastSpell(offensiveSpellId, activeTargetId); + _lastSpellCast = DateTime.Now; + } + catch { } + } + else + { + AttackTarget(); + } + } + + private string GetPreferredElement(WorldObject target, MonsterRule rule) + { + // 1. Explicit element from rule + if (rule != null && !string.IsNullOrEmpty(rule.DamageType) && + !rule.DamageType.Equals("Auto", StringComparison.OrdinalIgnoreCase)) + { + return rule.DamageType; + } + + // 2. Auto: check monsters.json weakness database + if (target != null && _monsterWeaknesses != null && _monsterWeaknesses.Count > 0) + { + foreach (var entry in _monsterWeaknesses) + { + if (target.Name.IndexOf(entry.Key, StringComparison.OrdinalIgnoreCase) >= 0) + { + return entry.Value; + } + } + } + + // 3. Ultimate fallback + return "Fire"; + } + + // ── DEBUFF SYSTEM ──────────────────────────────────────────────────────── + + /// <summary> + /// Returns true if any debuff in the rule's list still needs casting on the active target. + /// </summary> + private bool HasPendingDebuffs(MonsterRule rule, string element) + { + if (rule == null) return false; + var debuffs = BuildDebuffList(rule, element); + foreach (var debuffKey in debuffs) + { + string key = $"{activeTargetId}_{debuffKey}"; + if (!_confirmedDebuffs.Contains(key)) + return true; + } + return false; + } + + /// <summary> + /// Finds the first wand/staff/orb in ItemRules for debuff casting. + /// </summary> + private int FindWandInItems() + { + foreach (var item in _settings.ItemRules) + { + var wo = _coreManager.WorldFilter[item.Id]; + if (wo != null && wo.ObjectClass == ObjectClass.WandStaffOrb) + return item.Id; + } + return 0; + } + + /// <summary> + /// Builds the ordered debuff list from a MonsterRule's lights. + /// </summary> + private List<string> BuildDebuffList(MonsterRule rule, string element) + { + var list = new List<string>(); + if (rule.Imperil) list.Add("Imperil"); + if (rule.Vuln) list.Add("Vuln:" + element); + if (!string.IsNullOrEmpty(rule.ExVuln) && !rule.ExVuln.Equals("None", StringComparison.OrdinalIgnoreCase)) + list.Add("Vuln:" + rule.ExVuln); + if (rule.Fester) list.Add("Fester"); + if (rule.Yield) list.Add("Yield"); + if (rule.Broadside) list.Add("Broadside"); + if (rule.GravityWell) list.Add("Gravity"); + return list; + } + + // ── DEBUFF SPELL RESOLUTION (with tier output for duration tracking) ── + + private int FindBestDebuffSpellWithTier(string debuffType, out int tier) + { + tier = 0; + if (_spellManager == null) return 0; + + string[] spellInfo; + if (!DebuffSpells.TryGetValue(debuffType, out spellInfo) || spellInfo.Length < 2) + return 0; + + string tieredBase = spellInfo[0]; // e.g., "Imperil Other" + string loreName = spellInfo[1]; // e.g., "Gossamer Flesh" + + CharFilterSkillType skill = CharFilterSkillType.CreatureEnchantment; + int maxTier = _spellManager.GetHighestSpellTier(skill); + + // 1. Tier 8: Incantation of [tieredBase] + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {tieredBase}"); + if (id != 0) { tier = 8; return id; } + } + + // 2. Tier 7: Lore name (direct lookup) + if (maxTier >= 7 && !string.IsNullOrEmpty(loreName)) + { + int id = TrySpellByName(loreName); + if (id != 0) { tier = 7; return id; } + } + + // 3. Tier 7 numbered fallback, then VI → I + for (int t = Math.Min(maxTier, 7); t >= 1; t--) + { + string numeral = GetRomanNumeral(t); + int id = TrySpellByName($"{tieredBase} {numeral}"); + if (id != 0) { tier = t; return id; } + } + + return 0; + } + + private int FindBestVulnSpellWithTier(string element, out int tier) + { + tier = 0; + if (_spellManager == null) return 0; + + string[] vulnBases; + if (!VulnSpells.TryGetValue(element, out vulnBases)) + return 0; + + CharFilterSkillType skill = CharFilterSkillType.CreatureEnchantment; + int maxTier = _spellManager.GetHighestSpellTier(skill); + + foreach (string baseName in vulnBases) + { + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {baseName}"); + if (id != 0) { tier = 8; return id; } + } + + for (int t = Math.Min(maxTier, 7); t >= 1; t--) + { + int id = TrySpellByName($"{baseName} {GetRomanNumeral(t)}"); + if (id != 0) { tier = t; return id; } + } + } + return 0; + } + + /// <summary> + /// Tries to find a spell by exact name. Returns spell ID if known, 0 if not. + /// </summary> + private int TrySpellByName(string name) + { + int id; + if (_spellManager.SpellDictionary.TryGetValue(name, out id)) + { + if (_coreManager.CharacterFilter.IsSpellKnown(id)) + return id; + } + return 0; + } + + // ── SPELL SHAPE SELECTION (A/R/S/B lights) ────────────────────────── + + /// <summary> + /// Counts monsters within the given AC distance (yards/240). + /// </summary> + private int CountMonstersInRange(double rangeYards) + { + double acDist = rangeYards / 240.0; + int count = 0; + int playerId = _coreManager.CharacterFilter.Id; + foreach (var wo in _coreManager.WorldFilter.GetLandscape()) + { + if ((int)wo.ObjectClass != 5) continue; + if (_coreManager.WorldFilter.Distance(playerId, wo.Id) <= acDist) + count++; + } + return count; + } + + /// <summary> + /// Finds the best offensive spell using the rule's shape lights. + /// A = Arc, R = Ring, S = Streak, B = Bolt. + /// RING OVERRIDE: If >= MinRingTargets monsters are within RingRange, forces Ring spells. + /// If none are set, returns 0 (no attack - buff bot mode). + /// Uses Void Magic for Nether element, War Magic for everything else. + /// </summary> + private int FindBestShapedSpell(string element, MonsterRule rule) + { + if (_spellManager == null) return 0; + + // Determine skill: Void or War + bool useVoid = element.Equals("Nether", StringComparison.OrdinalIgnoreCase); + // Also check if character has Void trained but not War (or vice versa) + bool warTrained = false, voidTrained = false; + try { warTrained = (int)_coreManager.CharacterFilter.Skills[CharFilterSkillType.WarMagic].Training >= 2; } catch { } + try { voidTrained = (int)_coreManager.CharacterFilter.Skills[CharFilterSkillType.VoidMagic].Training >= 2; } catch { } + + if (useVoid && !voidTrained && warTrained) useVoid = false; // fallback to war + if (!useVoid && !warTrained && voidTrained) useVoid = true; // fallback to void + + CharFilterSkillType skill = useVoid ? CharFilterSkillType.VoidMagic : CharFilterSkillType.WarMagic; + + // Determine shape index: 0=Arc, 1=Ring, 2=Streak, 3=Bolt + // Priority: A > R > S > B. If none set, caller already blocked attack. + int shapeIdx = 3; // default = Bolt + if (rule != null) + { + if (rule.UseArc) shapeIdx = 0; + else if (rule.UseRing) shapeIdx = 1; + else if (rule.UseStreak) shapeIdx = 2; + else if (rule.UseBolt) shapeIdx = 3; + else return 0; // No attack shape selected + } + + // RING OVERRIDE: only if R light is on for this rule, and enough monsters nearby + if (rule != null && rule.UseRing && _settings.MinRingTargets > 0 && _settings.RingRange > 0) + { + int nearbyCount = CountMonstersInRange(_settings.RingRange); + if (nearbyCount >= _settings.MinRingTargets) + shapeIdx = 1; // Force Ring + } + + // Look up shape patterns + var shapes = useVoid ? VoidSpellShapes : SpellShapes; + string[] elementShapes; + if (!shapes.TryGetValue(element, out elementShapes)) + { + // Fallback element + if (!SpellShapes.TryGetValue("Fire", out elementShapes)) + return 0; + skill = CharFilterSkillType.WarMagic; + } + + // Clamp index + if (shapeIdx >= elementShapes.Length) shapeIdx = elementShapes.Length - 1; + + // Try preferred shape first + // SPECIAL: Ring spells (shapeIdx==1) have unique lore names that don't follow "Base VII" pattern + if (shapeIdx == 1) + { + int ringId = FindBestRingSpell(element, skill); + if (ringId != 0) return ringId; + } + + // Standard resolution: try preferred shape, then fall back to others + int id = FindBestOffensiveSpellId(elementShapes[shapeIdx], skill); + if (id != 0) return id; + + // Fallback: try bolt (index 3), then any shape that works + for (int i = elementShapes.Length - 1; i >= 0; i--) + { + if (i == shapeIdx) continue; + id = FindBestOffensiveSpellId(elementShapes[i], skill); + if (id != 0) return id; + } + + return 0; + } + + // ── SPELL RESOLUTION ───────────────────────────────────────────────────── + + /// <summary> + /// Resolves ring spells using AC's unique lore names. + /// Order: Incantation of [lore] (T8) → [lore] II (T7) → [lore] (T6) → generic tiers V→I + /// </summary> + private int FindBestRingSpell(string element, CharFilterSkillType skill) + { + string[] loreNames; + if (!RingLoreNames.TryGetValue(element, out loreNames) || loreNames.Length < 2) + return 0; + + int maxTier = _spellManager.GetHighestSpellTier(skill); + + // T7: [lore name] II (try first — most likely to be known) + if (maxTier >= 7) + { + int id = TrySpellByName(loreNames[1]); + if (id != 0) return id; + // Try with smart apostrophe variants + id = TrySpellByName(loreNames[1].Replace("'", "\u2019")); + if (id != 0) return id; + id = TrySpellByName(loreNames[1].Replace("'", "`")); + if (id != 0) return id; + } + + // T6: [lore name] + if (maxTier >= 6) + { + int id = TrySpellByName(loreNames[0]); + if (id != 0) return id; + id = TrySpellByName(loreNames[0].Replace("'", "\u2019")); + if (id != 0) return id; + id = TrySpellByName(loreNames[0].Replace("'", "`")); + if (id != 0) return id; + } + + // T8: Incantation of [lore name] + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {loreNames[0]}"); + if (id != 0) return id; + } + + // Fallback: try generic ring names (e.g., "Ring of Fire V") + string[] genericRingBases; + if (SpellShapes.TryGetValue(element, out genericRingBases) && genericRingBases.Length > 1) + { + string ringBase = genericRingBases[1]; // Index 1 = Ring + for (int t = Math.Min(maxTier, 5); t >= 1; t--) + { + int id = TrySpellByName($"{ringBase} {GetRomanNumeral(t)}"); + if (id != 0) return id; + } + } + + // Debug: if we get here, log what we tried + try { _host?.Actions?.AddChatText($"[RynthAi] Ring spell not found for {element} (tried: {loreNames[1]}, {loreNames[0]})", 2); } catch { } + return 0; + } + + /// <summary> + /// Searches for the highest tier of a spell the character knows. + /// Order: Incantation (8) → VII → VI → V → IV → III → II → I + /// Respects skill level — won't try tiers the character can't cast. + /// </summary> + private int FindBestOffensiveSpellId(string baseName, CharFilterSkillType skill) + { + if (_spellManager == null) return 0; + + int maxTier = _spellManager.GetHighestSpellTier(skill); + + // Tier 8: Incantation + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {baseName}"); + if (id != 0) return id; + id = TrySpellByName(baseName + " VIII"); + if (id != 0) return id; + } + + // Tiers 7 → 1 + for (int tier = Math.Min(maxTier, 7); tier >= 1; tier--) + { + string numeral = GetRomanNumeral(tier); + int id = TrySpellByName($"{baseName} {numeral}"); + if (id != 0) return id; + } + + return 0; + } + + private static string GetRomanNumeral(int tier) + { + switch (tier) + { + case 1: return "I"; + case 2: return "II"; + case 3: return "III"; + case 4: return "IV"; + case 5: return "V"; + case 6: return "VI"; + case 7: return "VII"; + case 8: return "VIII"; + default: return "I"; + } + } + + private void CleanupExpiredBlacklist() + { + var expired = new List<int>(); + foreach (var kvp in blacklistedTargets) if (kvp.Value.IsExpired()) expired.Add(kvp.Key); + foreach (var id in expired) blacklistedTargets.Remove(id); + // _confirmedDebuffs is cleared automatically when target changes + } + + + + public void Dispose() { _raycastSystem?.Dispose(); } + + /// <summary> + /// Diagnostic: runs a full LOS test against the currently selected target + /// and reports all coordinates, geometry volumes, and intersection results. + /// </summary> + public List<string> RunLosTestDiag(CoreManager core) + { + var lines = new List<string>(); + try + { + if (_raycastSystem == null || !RaycastInitialized) + { + lines.Add("Raycast system not initialized"); + return lines; + } + + int targetId = core.Actions.CurrentSelection; + if (targetId == 0) + { + lines.Add("No target selected — select a monster first"); + return lines; + } + + var target = core.WorldFilter[targetId]; + if (target == null) + { + lines.Add($"Target {targetId} not found in WorldFilter"); + return lines; + } + + lines.Add($"Target: {target.Name} (id={targetId})"); + + // Player position + uint landcell = (uint)core.Actions.Landcell; + uint blockX = (landcell >> 24) & 0xFF; + uint blockY = (landcell >> 16) & 0xFF; + float locX = (float)core.Actions.LocationX; + float locY = (float)core.Actions.LocationY; + float locZ = (float)core.Actions.LocationZ; + float playerGX = blockX * 192.0f + locX; + float playerGY = blockY * 192.0f + locY; + lines.Add($"Player Landcell=0x{landcell:X8} Block=({blockX},{blockY})"); + lines.Add($"Player Local=({locX:F1},{locY:F1},{locZ:F1})"); + lines.Add($"Player Global=({playerGX:F1},{playerGY:F1},{locZ:F1})"); + + // Target position + var coords = target.Coordinates(); + double ew = coords.EastWest; + double ns = coords.NorthSouth; + float targetGX = (float)((ew * 10.0 + 1019.5) * 24.0); + float targetGY = (float)((ns * 10.0 + 1019.5) * 24.0); + float targetZ = locZ; // approximate + try { targetZ = (float)target.RawCoordinates().Z; } catch { } + lines.Add($"Target EW={ew:F3} NS={ns:F3}"); + lines.Add($"Target Global=({targetGX:F1},{targetGY:F1},{targetZ:F1})"); + + float dx = targetGX - playerGX; + float dy = targetGY - playerGY; + float dist = (float)Math.Sqrt(dx * dx + dy * dy); + lines.Add($"Distance: {dist:F1}m, Delta=({dx:F1},{dy:F1})"); + + // Load geometry + var geometry = _raycastSystem.GeometryLoader.GetLandblockGeometry(landcell); + lines.Add($"Geometry: {geometry?.Count ?? 0} volumes loaded"); + + if (geometry != null && geometry.Count > 0) + { + var origin = new Raycasting.Vector3(playerGX, playerGY, locZ + 1.0f); + var targetPos = new Raycasting.Vector3(targetGX, targetGY, targetZ + 1.0f); + + var rayDir = targetPos - origin; + float rayLen = rayDir.Length(); + if (rayLen > 0.001f) rayDir = rayDir / rayLen; + + float pathMinX = Math.Min(playerGX, targetGX) - 15f; + float pathMaxX = Math.Max(playerGX, targetGX) + 15f; + float pathMinY = Math.Min(playerGY, targetGY) - 15f; + float pathMaxY = Math.Max(playerGY, targetGY) + 15f; + + int nearCount = 0; + int hitCount = 0; + var hitVolumes = new List<string>(); + var nearVolumes = new List<string>(); + + foreach (var vol in geometry) + { + bool nearPath = vol.Center.X >= pathMinX && vol.Center.X <= pathMaxX && + vol.Center.Y >= pathMinY && vol.Center.Y <= pathMaxY; + + float volDist; + bool hit = vol.RayIntersect(origin, rayDir, rayLen, out volDist); + + if (hit) hitCount++; + if (nearPath) nearCount++; + + // ALWAYS capture hitting volumes + if (hit && hitVolumes.Count < 10) + { + hitVolumes.Add($" ** HIT at {volDist:F2}yd: center=({vol.Center.X:F1},{vol.Center.Y:F1},{vol.Center.Z:F1}) " + + $"dim=({vol.Dimensions.X:F1},{vol.Dimensions.Y:F1},{vol.Dimensions.Z:F1}) type={vol.Type}"); + } + + if (nearPath && !hit && nearVolumes.Count < 10) + { + nearVolumes.Add($" NEAR: center=({vol.Center.X:F0},{vol.Center.Y:F0},{vol.Center.Z:F0}) " + + $"r={vol.Dimensions.X:F1} type={vol.Type}"); + } + } + + // Show hits first + if (hitVolumes.Count > 0) + { + lines.Add("=== BLOCKING VOLUMES ==="); + foreach (var hv in hitVolumes) lines.Add(hv); + } + + if (nearVolumes.Count > 0) + { + lines.Add($"=== NEAR (non-hit, showing {nearVolumes.Count} of {nearCount}) ==="); + foreach (var nv in nearVolumes) lines.Add(nv); + } + + if (hitVolumes.Count == 0 && nearVolumes.Count == 0) + lines.Add(" NO volumes found near path!"); + + lines.Add($"Summary: {geometry.Count} total, {nearCount} near path, {hitCount} ray hits"); + + bool nearby = Raycasting.RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry); + bool blocked = Raycasting.RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + lines.Add($"HasNearbyGeometry: {nearby}"); + lines.Add($"IsLinearPathBlocked: {blocked}"); + } + } + catch (Exception ex) + { + lines.Add($"Error: {ex.Message}"); + } + return lines; + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/FellowshipTracker.cs b/Plugins/RynthAi/Combat/FellowshipTracker.cs new file mode 100644 index 0000000..ab1a797 --- /dev/null +++ b/Plugins/RynthAi/Combat/FellowshipTracker.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using Decal.Adapter; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Reads fellowship membership directly from AC client memory. + /// + /// Memory layout (from UB's AcClient structs / acclient.exe analysis): + /// + /// Static pointers: + /// 0x0087150C = ClientFellowshipSystem** s_pFellowshipSystem + /// 0x00844C08 = UInt32* player_iid (our character ID) + /// + /// ClientFellowshipSystem: + /// +0x10 = CFellowship* m_pFellowship (null if not in fellowship) + /// + /// CFellowship / Fellowship: + /// +0x0C = PackableHashData** _buckets (hash table bucket array) + /// +0x10 = UInt32 _table_size (number of buckets) + /// +0x14 = UInt32 _currNum (member count) + /// +0x18 = PStringBase _name (fellowship name, char*) + /// +0x1C = UInt32 _leader (leader character ID) + /// +0x20 = int _share_xp + /// +0x24 = int _even_xp_split + /// +0x28 = int _open_fellow + /// +0x2C = int _locked + /// + /// PackableHashData (hash table entry for each member): + /// +0x00 = UInt32 _key (member character ID) + /// +0x04 = Fellow _data: + /// +0x04 = Fellow.PackObj vtable (4 bytes) + /// +0x08 = Fellow._name (PStringBase = char*, 4 bytes) + /// +0x0C = Fellow._level (UInt32) + /// +0x1C = Fellow._share_loot (int) + /// +0x20 = Fellow._max_health (UInt32) + /// +0x28 = Fellow._max_mana (UInt32) + /// +0x2C = Fellow._current_health (UInt32) + /// +0x34 = PackableHashData* _next (next in chain, null = end) + /// </summary> + public class FellowshipTracker : IDisposable + { + // Static memory addresses in acclient.exe + private static readonly IntPtr ADDR_FELLOWSHIP_SYSTEM = new IntPtr(0x0087150C); + private static readonly IntPtr ADDR_PLAYER_IID = new IntPtr(0x00844C08); + + // Struct offsets + private const int OFF_SYS_FELLOWSHIP = 0x10; // ClientFellowshipSystem → m_pFellowship + private const int OFF_FEL_BUCKETS = 0x0C; // Fellowship → _buckets + private const int OFF_FEL_TABLE_SIZE = 0x10; // Fellowship → _table_size + private const int OFF_FEL_CURR_NUM = 0x14; // Fellowship → _currNum + private const int OFF_FEL_NAME = 0x18; // Fellowship → _name (char*) + private const int OFF_FEL_LEADER = 0x1C; // Fellowship → _leader + private const int OFF_FEL_SHARE_XP = 0x20; // Fellowship → _share_xp + private const int OFF_FEL_EVEN_SPLIT = 0x24; // Fellowship → _even_xp_split + private const int OFF_FEL_OPEN = 0x28; // Fellowship → _open_fellow + private const int OFF_FEL_LOCKED = 0x2C; // Fellowship → _locked + + // Hash entry offsets (PackableHashData<UInt32, Fellow>) + private const int OFF_ENTRY_KEY = 0x00; // _key (member character ID) + private const int OFF_ENTRY_NAME_PTR = 0x08; // Fellow._name (char*) + private const int OFF_ENTRY_LEVEL = 0x0C; // Fellow._level + private const int OFF_ENTRY_NEXT = 0x34; // _next pointer + + // Cached member data + private Dictionary<int, string> _memberCache = new Dictionary<int, string>(); + private DateTime _lastRefresh = DateTime.MinValue; + private const double REFRESH_INTERVAL_MS = 2000; + + private CoreManager _core; + + public FellowshipTracker(CoreManager core) + { + _core = core; + } + + public void Dispose() { } + + // ══════════════════════════════════════════════════════════════ + // PUBLIC API — matches the UB expression interface + // ══════════════════════════════════════════════════════════════ + + /// <summary>True if the player is currently in a fellowship.</summary> + public bool IsInFellowship + { + get + { + try { return GetFellowshipPtr() != IntPtr.Zero; } + catch { return false; } + } + } + + /// <summary>Number of members in the current fellowship.</summary> + public int MemberCount + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return 0; + return Marshal.ReadInt32(fel + OFF_FEL_CURR_NUM); + } + catch { return 0; } + } + } + + /// <summary>Name of the current fellowship.</summary> + public string FellowshipName + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return ""; + return ReadPString(fel + OFF_FEL_NAME); + } + catch { return ""; } + } + } + + /// <summary>Character ID of the fellowship leader.</summary> + public int LeaderId + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return 0; + return Marshal.ReadInt32(fel + OFF_FEL_LEADER); + } + catch { return 0; } + } + } + + /// <summary>True if the player is the fellowship leader.</summary> + public bool IsLeader + { + get + { + try + { + int leader = LeaderId; + if (leader == 0) return false; + int myId = Marshal.ReadInt32(ADDR_PLAYER_IID); + return leader == myId; + } + catch { return false; } + } + } + + /// <summary>True if the fellowship is open for recruitment.</summary> + public bool IsOpen + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return false; + return Marshal.ReadInt32(fel + OFF_FEL_OPEN) == 1; + } + catch { return false; } + } + } + + /// <summary>True if the fellowship is locked.</summary> + public bool IsLocked + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return false; + return Marshal.ReadInt32(fel + OFF_FEL_LOCKED) == 1; + } + catch { return false; } + } + } + + /// <summary>True if the fellowship is sharing XP.</summary> + public bool ShareXP + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return false; + return Marshal.ReadInt32(fel + OFF_FEL_SHARE_XP) == 1; + } + catch { return false; } + } + } + + /// <summary>Check if a character name is a fellowship member.</summary> + public bool IsMember(string name) + { + if (string.IsNullOrEmpty(name)) return false; + RefreshIfNeeded(); + foreach (var kvp in _memberCache) + { + if (kvp.Value.Equals(name, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } + + /// <summary>Check if a character ID is a fellowship member.</summary> + public bool IsMember(int characterId) + { + RefreshIfNeeded(); + return _memberCache.ContainsKey(characterId); + } + + /// <summary>Get all member names.</summary> + public IEnumerable<string> GetMemberNames() + { + RefreshIfNeeded(); + return _memberCache.Values; + } + + /// <summary>Get member name by index (0-based).</summary> + public string GetMemberName(int index) + { + RefreshIfNeeded(); + int i = 0; + foreach (var kvp in _memberCache) + { + if (i == index) return kvp.Value; + i++; + } + return ""; + } + + /// <summary>Get member character ID by index (0-based).</summary> + public int GetMemberId(int index) + { + RefreshIfNeeded(); + int i = 0; + foreach (var kvp in _memberCache) + { + if (i == index) return kvp.Key; + i++; + } + return 0; + } + + // ══════════════════════════════════════════════════════════════ + // NATIVE MEMORY READING + // ══════════════════════════════════════════════════════════════ + + /// <summary> + /// Gets the CFellowship pointer. Returns IntPtr.Zero if not in a fellowship. + /// Chain: [s_pFellowshipSystem] → ClientFellowshipSystem → [+0x10] → CFellowship + /// </summary> + private IntPtr GetFellowshipPtr() + { + int sysPtr = Marshal.ReadInt32(ADDR_FELLOWSHIP_SYSTEM); + if (sysPtr == 0) return IntPtr.Zero; + + int felPtr = Marshal.ReadInt32(new IntPtr(sysPtr + OFF_SYS_FELLOWSHIP)); + if (felPtr == 0) return IntPtr.Zero; + + return new IntPtr(felPtr); + } + + /// <summary> + /// Refreshes the member cache by iterating the hash table in client memory. + /// Only refreshes every REFRESH_INTERVAL_MS to avoid overhead. + /// </summary> + private void RefreshIfNeeded() + { + if ((DateTime.Now - _lastRefresh).TotalMilliseconds < REFRESH_INTERVAL_MS) + return; + _lastRefresh = DateTime.Now; + + _memberCache.Clear(); + + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return; + + int bucketsPtr = Marshal.ReadInt32(fel + OFF_FEL_BUCKETS); + int tableSize = Marshal.ReadInt32(fel + OFF_FEL_TABLE_SIZE); + int currNum = Marshal.ReadInt32(fel + OFF_FEL_CURR_NUM); + + if (bucketsPtr == 0 || tableSize == 0 || currNum == 0) return; + + // Safety: don't iterate more than 9 members (AC fellowship max) + int maxMembers = Math.Min(currNum, 9); + int found = 0; + + // Walk each bucket in the hash table + for (int b = 0; b < tableSize && found < maxMembers; b++) + { + // Read bucket pointer: _buckets[b] + int entryPtr = Marshal.ReadInt32(new IntPtr(bucketsPtr + b * 4)); + + // Walk the chain for this bucket + while (entryPtr != 0 && found < maxMembers) + { + // Read _key (member character ID) at entry + 0x00 + int memberId = Marshal.ReadInt32(new IntPtr(entryPtr + OFF_ENTRY_KEY)); + + // Read _name pointer at entry + 0x08 (Fellow._name = char*) + string name = ReadPString(new IntPtr(entryPtr + OFF_ENTRY_NAME_PTR)); + + if (memberId != 0 && !string.IsNullOrEmpty(name)) + { + _memberCache[memberId] = name; + found++; + } + + // Follow _next pointer at entry + 0x34 + entryPtr = Marshal.ReadInt32(new IntPtr(entryPtr + OFF_ENTRY_NEXT)); + } + } + } + catch { } + } + + /// <summary> + /// Reads a PStringBase<char> from a memory address. + /// + /// PStringBase contains a single m_buffer pointer to PSRefBuffer<char>. + /// PSRefBuffer layout (verified from acclient.exe binary analysis — + /// PStringBase ctor at 0x48C3E0 copies chars to buf+0x14, + /// allocation helper at 0x403560 initializes the header): + /// +0x00: vtable (ReferenceCountTemplate vftable, e.g. 0x7CAE34) + /// +0x04: m_cRef (int32 — reference count) + /// +0x08: m_Length (int32 — string length INCLUDING null terminator) + /// +0x0C: m_Capacity (int32 — allocated buffer capacity) + /// +0x10: m_Hash (int32 — initialized to 0xFFFFFFFF) + /// +0x14: char[] (actual string data, null-terminated) + /// </summary> + private string ReadPString(IntPtr addr) + { + try + { + // Step 1: Read PSRefBuffer* from PStringBase.m_buffer + int bufPtr = Marshal.ReadInt32(addr); + if (bufPtr == 0) return ""; + + // Step 2: Read string data from PSRefBuffer + 0x14 (after 20-byte header) + // Use null-terminated read with safety cap at 64 chars + string raw = Marshal.PtrToStringAnsi(new IntPtr(bufPtr + 0x14)); + if (raw == null) return ""; + if (raw.Length > 64) raw = raw.Substring(0, 64); + return raw; + } + catch { return ""; } + } + } +} diff --git a/Plugins/RynthAi/Combat/MissileCraftingManager.cs b/Plugins/RynthAi/Combat/MissileCraftingManager.cs new file mode 100644 index 0000000..c62d735 --- /dev/null +++ b/Plugins/RynthAi/Combat/MissileCraftingManager.cs @@ -0,0 +1,521 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Automates missile ammunition management. + /// + /// Triggers when ammo slot is empty: + /// 1. Can craft better ammo than loose inventory? → Craft (up to 2x), then equip + /// 2. Loose ammo available? → Equip best one + /// 3. Can craft anything? → Craft, then equip + /// + /// Crafting is chat-driven: issues ApplyItem, waits for "You make" chat message, + /// then advances to next combine or equips. Retries every 2s if no response. + /// </summary> + public class MissileCraftingManager + { + private CoreManager _core; + private UISettings _settings; + private PluginHost _host; + + public enum CraftState + { + Idle, + Evaluating, + Combining, // ApplyItem issued, waiting for "You make" in chat + EquippingAmmo + } + + public CraftState State { get; private set; } = CraftState.Idle; + public bool IsCrafting => State != CraftState.Idle; + public string StatusMessage { get; private set; } = ""; + + // ── Timing ───────────────────────────────────────────────────────── + private DateTime _phaseStart = DateTime.MinValue; + private DateTime _lastAmmoCheck = DateTime.MinValue; + private DateTime _lastApplyAttempt = DateTime.MinValue; + private const int AMMO_CHECK_INTERVAL_MS = 5000; + private const int APPLY_RETRY_MS = 2000; + private const int CRAFT_TIMEOUT_MS = 15000; + private const int EQUIP_DELAY_MS = 500; + + // ── Current craft job ────────────────────────────────────────────── + private int _headBundleId = 0; + private int _shaftBundleId = 0; + private AmmoRecipe _currentRecipe = null; + private int _equipTargetId = 0; + private bool _allCombinesDone = false; + + // Pre-identified bundle pairs (up to 2). Populated before first combine. + private Queue<int[]> _pendingBundlePairs = new Queue<int[]>(); + private int _totalCombines = 0; + private int _combinesCompleted = 0; + + // ══════════════════════════════════════════════════════════════════ + // RECIPE DATABASE + // ══════════════════════════════════════════════════════════════════ + + public enum WeaponCategory { Bow, Crossbow, Atlatl } + + public class AmmoRecipe + { + public string HeadBundleName; + public string ShaftBundleName; + public string OutputName; + public WeaponCategory Category; + public bool RequiresSpecialized; + public int Priority; + } + + public static readonly List<AmmoRecipe> AllRecipes = new List<AmmoRecipe> + { + // ── ARROWS (Bow) ─────────────────────────────────────────── + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Lethal Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Lethal Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = true, Priority = 40 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Deadly Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Deadly Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = true, Priority = 30 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Greater Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Greater Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 20 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 10 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Armor Piercing Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Armor Piercing Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 6 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Broad Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Broad Head Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 5 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Blunt Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Blunt Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 4 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Frog Crotch Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Frog Crotch Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 3 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 1 }, + + // ── QUARRELS (Crossbow) ──────────────────────────────────── + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Lethal Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Lethal Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = true, Priority = 40 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Deadly Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Deadly Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = true, Priority = 30 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Greater Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Greater Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 20 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 10 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Armor Piercing Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Armor Piercing Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 6 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Broad Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Broad Head Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 5 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Blunt Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Blunt Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 4 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 1 }, + + // ── DARTS (Atlatl) ───────────────────────────────────────── + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Lethal Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Lethal Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = true, Priority = 40 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Deadly Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Deadly Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = true, Priority = 30 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Greater Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Greater Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 20 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 10 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Armor Piercing Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Armor Piercing Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 6 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Broad Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Broad Head Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 5 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Blunt Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Blunt Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 4 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 1 }, + }; + + // ══════════════════════════════════════════════════════════════════ + // CONSTRUCTOR + // ══════════════════════════════════════════════════════════════════ + + public MissileCraftingManager(CoreManager core, UISettings settings, PluginHost host) + { + _core = core; + _settings = settings; + _host = host; + } + + // ══════════════════════════════════════════════════════════════════ + // MAIN TICK + // ══════════════════════════════════════════════════════════════════ + + public void ProcessCrafting() + { + if (!_settings.EnableMissileCrafting) return; + if (_core.Actions.BusyState != 0) return; + + switch (State) + { + case CraftState.Idle: ProcessIdle(); break; + case CraftState.Evaluating: ProcessEvaluating(); break; + case CraftState.Combining: ProcessCombining(); break; + case CraftState.EquippingAmmo: ProcessEquippingAmmo(); break; + } + } + + // ══════════════════════════════════════════════════════════════════ + // CHAT HANDLER — called from PluginCore.OnChatBoxMessage + // Listens for "You make" to confirm a successful combine. + // ══════════════════════════════════════════════════════════════════ + + public void HandleChat(string text) + { + if (State != CraftState.Combining) return; + if (string.IsNullOrEmpty(text)) return; + + // AC craft success: "You make a big bundle of deadly prismatic arrows." + if (text.IndexOf("You make", StringComparison.OrdinalIgnoreCase) < 0) return; + + _combinesCompleted++; + ChatLog($"Craft confirmed ({_combinesCompleted}/{_totalCombines})"); + + // More pairs to combine? + if (_pendingBundlePairs.Count > 0) + { + var pair = _pendingBundlePairs.Dequeue(); + _headBundleId = pair[0]; + _shaftBundleId = pair[1]; + _lastApplyAttempt = DateTime.MinValue; // Force immediate ApplyItem next tick + StatusMessage = $"Crafting {_currentRecipe.OutputName} (batch {_combinesCompleted + 1})..."; + } + else + { + // All combines done — signal ProcessCombining to transition + _allCombinesDone = true; + } + } + + // ══════════════════════════════════════════════════════════════════ + // IDLE — only triggers when ammo slot is empty + // ══════════════════════════════════════════════════════════════════ + + private void ProcessIdle() + { + if ((DateTime.Now - _lastAmmoCheck).TotalMilliseconds < AMMO_CHECK_INTERVAL_MS) return; + _lastAmmoCheck = DateTime.Now; + + WeaponCategory? category = GetEquippedMissileCategory(); + if (category == null) return; + if (HasWieldedAmmo(category.Value)) return; + + ChatLog($"No {GetCategoryLabel(category.Value)}s equipped. Evaluating..."); + SetState(CraftState.Evaluating); + } + + // ══════════════════════════════════════════════════════════════════ + // EVALUATING — decide: craft or equip existing? + // ══════════════════════════════════════════════════════════════════ + + private void ProcessEvaluating() + { + WeaponCategory? category = GetEquippedMissileCategory(); + if (category == null) { Reset("No missile weapon equipped"); return; } + + int trainingLevel = 0; + try { trainingLevel = (int)_core.CharacterFilter.Skills[CharFilterSkillType.Fletching].Training; } catch { } + + var inv = _core.WorldFilter.GetInventory().ToList(); + + // Find best craftable recipe + AmmoRecipe bestCraftable = null; + foreach (var recipe in AllRecipes + .Where(r => r.Category == category.Value) + .OrderByDescending(r => r.Priority)) + { + if (recipe.RequiresSpecialized && trainingLevel < 3) continue; + if (!recipe.RequiresSpecialized && trainingLevel < 2) continue; + + bool hasHead = inv.Any(i => i.Name != null && i.Name.Equals(recipe.HeadBundleName, StringComparison.OrdinalIgnoreCase)); + bool hasShaft = inv.Any(i => i.Name != null && i.Name.Equals(recipe.ShaftBundleName, StringComparison.OrdinalIgnoreCase)); + + if (hasHead && hasShaft) { bestCraftable = recipe; break; } + } + + // Find best loose ammo + int bestExistingPriority = 0; + WorldObject bestExistingAmmo = null; + foreach (var item in inv) + { + if (!IsLooseAmmo(item, category.Value)) continue; + int pri = GetAmmoPriority(item, category.Value); + if (pri > bestExistingPriority) { bestExistingPriority = pri; bestExistingAmmo = item; } + } + + // Can craft better? → Craft. + if (bestCraftable != null && bestCraftable.Priority > bestExistingPriority) + { StartCrafting(bestCraftable, inv); return; } + + // Loose ammo? → Equip. + if (bestExistingAmmo != null) + { + _equipTargetId = bestExistingAmmo.Id; + ChatLog($"Equipping {bestExistingAmmo.Name} (x{bestExistingAmmo.Values(LongValueKey.StackCount, 1)})"); + SetState(CraftState.EquippingAmmo); + return; + } + + // Can craft anything? → Craft. + if (bestCraftable != null) + { StartCrafting(bestCraftable, inv); return; } + + Reset("No ammo and no bundles available"); + } + + private void StartCrafting(AmmoRecipe recipe, List<WorldObject> inv) + { + _currentRecipe = recipe; + _pendingBundlePairs.Clear(); + _combinesCompleted = 0; + _allCombinesDone = false; + + // Enter Peace mode so the game client doesn't auto-fire arrows mid-craft + try { _core.Actions.SetCombatMode(CombatState.Peace); } catch { } + + // Find head and shaft bundles. Bundles are stackable — a single WorldObject + // can have StackCount=2+, meaning multiple combines from the same item ID. + var headItems = inv.Where(i => i.Name != null && i.Name.Equals(recipe.HeadBundleName, StringComparison.OrdinalIgnoreCase)).ToList(); + var shaftItems = inv.Where(i => i.Name != null && i.Name.Equals(recipe.ShaftBundleName, StringComparison.OrdinalIgnoreCase)).ToList(); + + // Sum total available across all stacks + int totalHeads = 0; + foreach (var h in headItems) totalHeads += h.Values(LongValueKey.StackCount, 1); + int totalShafts = 0; + foreach (var s in shaftItems) totalShafts += s.Values(LongValueKey.StackCount, 1); + + int pairCount = Math.Min(2, Math.Min(totalHeads, totalShafts)); + if (pairCount <= 0) { Reset("No bundles available"); return; } + + // Queue up pairs. Each combine uses the same IDs if stacked — the server + // decrements the stack. Only need different IDs if we exhaust one stack. + int headIdx = 0, shaftIdx = 0; + int headRemaining = headItems[0].Values(LongValueKey.StackCount, 1); + int shaftRemaining = shaftItems[0].Values(LongValueKey.StackCount, 1); + + for (int i = 0; i < pairCount; i++) + { + // Advance to next stack if current one is exhausted + while (headRemaining <= 0 && headIdx < headItems.Count - 1) + { headIdx++; headRemaining = headItems[headIdx].Values(LongValueKey.StackCount, 1); } + while (shaftRemaining <= 0 && shaftIdx < shaftItems.Count - 1) + { shaftIdx++; shaftRemaining = shaftItems[shaftIdx].Values(LongValueKey.StackCount, 1); } + + _pendingBundlePairs.Enqueue(new[] { headItems[headIdx].Id, shaftItems[shaftIdx].Id }); + headRemaining--; + shaftRemaining--; + } + + _totalCombines = pairCount; + + // Pop first pair + var first = _pendingBundlePairs.Dequeue(); + _headBundleId = first[0]; + _shaftBundleId = first[1]; + + ChatLog($"Crafting {recipe.OutputName} x{_totalCombines}"); + StatusMessage = $"Crafting {recipe.OutputName}..."; + _lastApplyAttempt = DateTime.MinValue; + SetState(CraftState.Combining); + } + + // ══════════════════════════════════════════════════════════════════ + // COMBINING — issues ApplyItem, retries until "You make" in chat. + // HandleChat advances to next pair or signals done. + // ══════════════════════════════════════════════════════════════════ + + private void ProcessCombining() + { + // HandleChat flagged all combines done → equip + if (_allCombinesDone) + { + StatusMessage = $"Equipping {_currentRecipe.OutputName}..."; + _equipTargetId = 0; + SetState(CraftState.EquippingAmmo); + return; + } + + // Timeout safety + if ((DateTime.Now - _phaseStart).TotalMilliseconds > CRAFT_TIMEOUT_MS) + { + if (_combinesCompleted > 0) + { + ChatLog($"Timeout after {_combinesCompleted} combine(s). Equipping what we have."); + _equipTargetId = 0; + SetState(CraftState.EquippingAmmo); + } + else + { + Reset("Craft timed out — no response from server"); + } + return; + } + + // Issue / retry ApplyItem every APPLY_RETRY_MS + if ((DateTime.Now - _lastApplyAttempt).TotalMilliseconds >= APPLY_RETRY_MS) + { + try + { + _host.Actions.ApplyItem(_headBundleId, _shaftBundleId); + _lastApplyAttempt = DateTime.Now; + StatusMessage = $"Combining → {_currentRecipe.OutputName} ({_combinesCompleted + 1}/{_totalCombines})..."; + } + catch (Exception ex) + { + Reset($"Combine failed: {ex.Message}"); + } + } + } + + // ══════════════════════════════════════════════════════════════════ + // EQUIPPING — UseItem on the ammo to wield it + // ══════════════════════════════════════════════════════════════════ + + private void ProcessEquippingAmmo() + { + if ((DateTime.Now - _phaseStart).TotalMilliseconds < EQUIP_DELAY_MS) return; + + try + { + int targetId = _equipTargetId; + + if (targetId == 0) + { + WeaponCategory? cat = GetEquippedMissileCategory(); + if (cat != null) + { + var ammo = FindBestAmmoInInventory(cat.Value); + if (ammo != null) targetId = ammo.Id; + } + } + + if (targetId != 0) + { + var ammoItem = _core.WorldFilter[targetId]; + if (ammoItem != null) + { + if (ammoItem.Values((LongValueKey)10, 0) > 0) + { + ChatLog($"Already equipped: {ammoItem.Name}"); + } + else + { + _host.Actions.UseItem(targetId, 0); + ChatLog($"Equipped {ammoItem.Name} (x{ammoItem.Values(LongValueKey.StackCount, 1)})"); + } + } + else + { + ChatLog("Ammo item no longer exists."); + } + } + else + { + ChatLog("Could not find ammo to equip."); + } + } + catch (Exception ex) + { + ChatLog($"Equip error: {ex.Message}"); + } + + Reset($"Done: {_currentRecipe?.OutputName ?? "ammo"}"); + } + + // ══════════════════════════════════════════════════════════════════ + // HELPERS + // ══════════════════════════════════════════════════════════════════ + + private bool HasWieldedAmmo(WeaponCategory category) + { + try + { + foreach (var item in _core.WorldFilter.GetInventory()) + { + if (item.Values((LongValueKey)10, 0) <= 0) continue; + if (IsLooseAmmo(item, category)) return true; + } + } + catch { } + return false; + } + + private bool IsLooseAmmo(WorldObject item, WeaponCategory category) + { + if (item.Name == null) return false; + string n = item.Name; + + if (n.Contains("Bundle") || n.Contains("Wrapped")) return false; + if (n.Contains("Arrowhead") || n.Contains("Arrowshaft")) return false; + if (n.Contains("Quarrelhead") || n.Contains("Quarrelshaft")) return false; + if (n.Contains("Dart Head") || n.Contains("Dart Shaft")) return false; + + switch (category) + { + case WeaponCategory.Bow: return n.Contains("Arrow"); + case WeaponCategory.Crossbow: return n.Contains("Quarrel") || n.Contains("Bolt"); + case WeaponCategory.Atlatl: return n.Contains("Dart"); + default: return false; + } + } + + private int GetAmmoPriority(WorldObject item, WeaponCategory category) + { + if (item.Name == null) return 0; + foreach (var recipe in AllRecipes.Where(r => r.Category == category).OrderByDescending(r => r.Priority)) + { + if (item.Name.Equals(recipe.OutputName, StringComparison.OrdinalIgnoreCase)) + return recipe.Priority; + } + return 1; + } + + private WorldObject FindBestAmmoInInventory(WeaponCategory category) + { + int bestPri = 0; + WorldObject best = null; + foreach (var item in _core.WorldFilter.GetInventory()) + { + if (!IsLooseAmmo(item, category)) continue; + int pri = GetAmmoPriority(item, category); + if (pri > bestPri) { bestPri = pri; best = item; } + } + return best; + } + + private WeaponCategory? GetEquippedMissileCategory() + { + try + { + foreach (var wo in _core.WorldFilter.GetInventory()) + { + if (wo.Values((LongValueKey)10, 0) <= 0) continue; + if (wo.ObjectClass != ObjectClass.MissileWeapon) continue; + string name = wo.Name?.ToLower() ?? ""; + if (name.Contains("crossbow")) return WeaponCategory.Crossbow; + if (name.Contains("atlatl")) return WeaponCategory.Atlatl; + return WeaponCategory.Bow; + } + } + catch { } + return null; + } + + private string GetCategoryLabel(WeaponCategory cat) + { + switch (cat) + { + case WeaponCategory.Bow: return "Arrow"; + case WeaponCategory.Crossbow: return "Quarrel"; + case WeaponCategory.Atlatl: return "Dart"; + default: return "Ammo"; + } + } + + private void SetState(CraftState newState) + { + State = newState; + _phaseStart = DateTime.Now; + } + + private void Reset(string reason) + { + StatusMessage = reason; + State = CraftState.Idle; + _currentRecipe = null; + _headBundleId = 0; + _shaftBundleId = 0; + _equipTargetId = 0; + _allCombinesDone = false; + _combinesCompleted = 0; + _totalCombines = 0; + _pendingBundlePairs.Clear(); + } + + private void ChatLog(string msg) + { + try { _host.Actions.AddChatText($"[RynthAi Craft] {msg}", 1); } catch { } + } + } +} diff --git a/Plugins/RynthAi/Combat/SpellDatabase.cs b/Plugins/RynthAi/Combat/SpellDatabase.cs new file mode 100644 index 0000000..9e1ad05 --- /dev/null +++ b/Plugins/RynthAi/Combat/SpellDatabase.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Reflection; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public static class SpellDatabase + { + private static Dictionary<int, string> _spellNames = new Dictionary<int, string>(); + private static bool _loaded = false; + + private static readonly Dictionary<int, string> _builtinSpells = new Dictionary<int, string> + { + { 47, "Primary Portal Tie" }, { 48, "Primary Portal Recall" }, + { 157, "Summon Primary Portal I" }, { 158, "Summon Primary Portal II" }, + { 1634, "Portal Sending" }, { 1635, "Lifestone Recall" }, + { 1636, "Lifestone Sending" }, { 1637, "Summon Primary Portal III" }, + { 2023, "Recall the Sanctuary" }, { 2041, "Aerlinthe Recall" }, + { 2358, "Lyceum Recall" }, { 2644, "Lifestone Tie" }, + { 2645, "Portal Recall" }, { 2646, "Secondary Portal Tie" }, + { 2647, "Secondary Portal Recall" }, { 2648, "Summon Secondary Portal I" }, + { 2649, "Summon Secondary Portal II" }, { 2650, "Summon Secondary Portal III" }, + { 2813, "Mount Lethe Recall" }, { 2931, "Recall Aphus Lassel" }, + { 2941, "Ulgrim's Recall" }, { 2943, "Recall to the Singularity Caul" }, + { 3865, "Glenden Wood Recall" }, { 3929, "Rossu Morta Chapterhouse Recall" }, + { 3930, "Whispering Blade Chapterhouse Recall" }, { 4084, "Bur Recall" }, + { 4198, "Paradox-touched Olthoi Infested Area Recall" }, { 4213, "Colosseum Recall" }, + { 4907, "Celestial Hand Stronghold Recall" }, { 4908, "Eldrytch Web Stronghold Recall" }, + { 4909, "Radiant Blood Stronghold Recall" }, { 5175, "Facility Hub Recall" }, + { 5330, "Gear Knight Invasion Area Camp Recall" }, { 5541, "Lost City of Neftet Recall" }, + { 6150, "Rynthid Recall" }, { 6321, "Viridian Rise Recall" }, + { 6322, "Viridian Rise Great Tree Recall" }, + }; + + public static bool IsLoaded => _loaded; + + public static void Load(PluginHost host) + { + _spellNames.Clear(); + _loaded = false; + + try + { + Assembly assembly = Assembly.GetExecutingAssembly(); + string resourceName = "NexSuite.Plugins.RynthAi.Combat.Vtank spelldump.txt"; + + using (Stream stream = assembly.GetManifestResourceStream(resourceName)) + { + if (stream == null) + { + host.Actions.AddChatText($"[RynthAi] ERROR: Could not find embedded resource: {resourceName}", 2); + return; + } + + using (StreamReader reader = new StreamReader(stream, true)) + { + string line; + while ((line = reader.ReadLine()) != null) + { + if (string.IsNullOrWhiteSpace(line)) continue; + + // Split the line by tabs to isolate the columns + string[] columns = line.Split('\t'); + + // Column 0 is ID, Column 1 is Name + if (columns.Length >= 2) + { + if (int.TryParse(columns[0].Trim(), out int spellId)) + { + string spellName = columns[1].Trim(); + _spellNames[spellId] = spellName; + } + } + } + } + } + + _loaded = _spellNames.Count > 0; + + } + catch (Exception ex) + { + host.Actions.AddChatText($"[RynthAi] Spell Load Error: {ex.Message}", 2); + } + } + + public static string GetSpellName(int spellId) + { + if (_spellNames.TryGetValue(spellId, out string name)) return name; + if (_builtinSpells.TryGetValue(spellId, out string builtin)) return builtin; + return $"Unknown Spell ({spellId})"; + } + + public static string GetSpellNameOrId(int spellId) + { + if (_spellNames.TryGetValue(spellId, out string name)) return name; + if (_builtinSpells.TryGetValue(spellId, out string builtin)) return builtin; + return spellId.ToString(); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/SpellManager.cs b/Plugins/RynthAi/Combat/SpellManager.cs new file mode 100644 index 0000000..1244dd7 --- /dev/null +++ b/Plugins/RynthAi/Combat/SpellManager.cs @@ -0,0 +1,215 @@ +using System; +using System.Collections.Generic; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; + +namespace NexSuite.Plugins.RynthAi +{ + public class SpellManager + { + private CoreManager _core; + + public Dictionary<string, int> SpellDictionary { get; private set; } = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); + + // Map base spell names to their exact Level 7 Lore counterparts + private readonly Dictionary<string, string[]> LoreNames = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) + { + // Attributes (Using the exact AC names you provided) + { "Strength", new[] { "Might of the Lugians" } }, + { "Endurance", new[] { "Preservance", "Perseverance" } }, + { "Coordination", new[] { "Honed Control" } }, + { "Quickness", new[] { "Hastening" } }, + { "Focus", new[] { "Inner Calm" } }, + { "Willpower", new[] { "Mind Blossom" } }, + + // Defenses + { "Invulnerability", new[] { "Aura of Defense" } }, + { "Impregnability", new[] { "Aura of Deflection" } }, + { "Magic Resistance", new[] { "Aura of Resistance" } }, + + // Life Magic + { "Armor", new[] { "Executor's Blessing" } }, + { "Acid Protection", new[] { "Caustic Blessing" } }, + { "Blade Protection", new[] { "Blessing of the Blade Turner" } }, + { "Bludgeoning Protection", new[] { "Blessing of the Mace Turner" } }, + { "Cold Protection", new[] { "Icy Blessing" } }, + { "Fire Protection", new[] { "Fiery Blessing" } }, + { "Lightning Protection", new[] { "Storm's Blessing" } }, + { "Mana Renewal", new[] { "Battlemage's Blessing" } }, + { "Piercing Protection", new[] { "Blessing of the Arrow Turner" } }, + { "Regeneration", new[] { "Robustify" } }, + { "Rejuvenation", new[] { "Unflinching Persistence", "Unfinching Persistance" } }, + + // Vitals + { "Heal", new[] { "Adja's Intervention" } }, + { "Revitalize", new[] { "Robustification" } }, + { "Stamina to Mana", new[] { "Meditative Trance" } }, + { "Stamina to Health", new[] { "Rushed Recovery" } }, + + // Skills & Masteries + { "Monster Attunement", new[] { "Topheron's Blessing" } }, + { "Person Attunement", new[] { "Kaluhc's Blessing" } }, + { "Arcane Enlightenment", new[] { "Aliester's Blessing" } }, + { "Armor Tinkering Expertise", new[] { "Jibril's Blessing" } }, + { "Item Tinkering Expertise", new[] { "Yoshi's Blessing" } }, + { "Weapon Tinkering Expertise", new[] { "Koga's Blessing" } }, + { "Mana Conversion Mastery", new[] { "Nuhmidura's Blessing" } }, + { "Sprint", new[] { "Saladur's Blessing" } }, + { "Jumping Mastery", new[] { "Jahannan's Blessing" } }, + { "Fealty", new[] { "Odif's Blessing", "Odif's Boon" } }, + { "Leadership Mastery", new[] { "Ar-Pei's Blessing" } }, + { "Deception Mastery", new[] { "Ketnan's Blessing" } }, + { "Healing Mastery", new[] { "Avalenne's Blessing" } }, + { "Lockpick Mastery", new[] { "Oswald's Blessing" } }, + { "Cooking Mastery", new[] { "Morimoto's Blessing" } }, + { "Fletching Mastery", new[] { "Lilitha's Blessing" } }, + { "Alchemy Mastery", new[] { "Silencia's Blessing" } }, + { "Creature Enchantment Mastery", new[] { "Adja's Blessing" } }, + { "Item Enchantment Mastery", new[] { "Celcynd's Blessing" } }, + { "Life Magic Mastery", new[] { "Harlune's Blessing" } }, + { "War Magic Mastery", new[] { "Hieromancer's Blessing" } }, + + // Weapon Auras (Item Enchantment) + { "Blood Drinker", new[] { "Aura of Infected Caress" } }, + { "Hermetic Link", new[] { "Aura of Mystic's Blessing" } }, + { "Heart Seeker", new[] { "Aura of Elysa's Sight" } }, + { "Spirit Drinker", new[] { "Aura of Infected Spirit Carress", "Aura of Infected Spirit Caress" } }, + { "Swift Killer", new[] { "Aura of Atlan's Alacrity" } }, + { "Defender", new[] { "Aura of Cragstone's Will" } }, + + // Armor Banes (Item Enchantment) + { "Impenetrability", new[] { "Brogard's Defiance" } }, + { "Acid Bane", new[] { "Olthoi's Bane" } }, + { "Blade Bane", new[] { "Swordsman's Bane", "Swordman's Bane" } }, + { "Bludgeoning Bane", new[] { "Tusker's Bane" } }, + { "Flame Bane", new[] { "Inferno's Bane" } }, + { "Frost Bane", new[] { "Gelidite's Bane" } }, + { "Lightning Bane", new[] { "Astyrrian's Bane" } }, + { "Piercing Bane", new[] { "Archer's Bane" } } + }; + + public SpellManager(CoreManager core) + { + _core = core; + } + + public void InitializeNatively() + { + try + { + var fs = _core.Filter<FileService>(); + if (fs == null) return; + + for (int i = 1; i <= 40000; i++) + { + try + { + var spell = fs.SpellTable.GetById(i); + if (spell != null && !string.IsNullOrWhiteSpace(spell.Name)) + { + SpellDictionary[spell.Name] = spell.Id; + } + } + catch { } + } + + _core.Actions.AddChatText($"[RynthAi] Magic System Online: {SpellDictionary.Count} spells loaded.", 1); + } + catch (Exception ex) { _core.Actions.AddChatText("[RynthAi] Native load error: " + ex.Message, 2); } + } + + public int GetHighestSpellTier(CharFilterSkillType skill) + { + try + { + int buffedSkill = _core.CharacterFilter.Skills[skill].Buffed; + if (buffedSkill >= 400) return 8; + if (buffedSkill >= 315) return 7; // Adjusted to common AC skill requirements + if (buffedSkill >= 250) return 6; + if (buffedSkill >= 200) return 5; + if (buffedSkill >= 150) return 4; + if (buffedSkill >= 100) return 3; + if (buffedSkill >= 50) return 2; + return 1; + } + catch { return 1; } + } + + private string GetRomanNumeral(int tier) + { + switch (tier) + { + case 1: return "I"; + case 2: return "II"; + case 3: return "III"; + case 4: return "IV"; + case 5: return "V"; + case 6: return "VI"; + case 7: return "VII"; + case 8: return "VIII"; + default: return "I"; + } + } + + // Spell resolution for self-buffs. Capped by skill level. + // Within each tier tries standard names first, then "Aura of" prefixed variants + // (weapon enchantments like Blood Drinker, Heart Seeker use "Aura of" prefix). + public int GetDynamicSelfBuffId(string baseSpellName, CharFilterSkillType magicSkill) + { + int maxTier = GetHighestSpellTier(magicSkill); + string cleanBase = baseSpellName.Replace(" Self", "").Trim(); + + for (int tier = maxTier; tier >= 1; tier--) + { + if (tier == 8) + { + // Standard: "Incantation of Focus Self" + if (TryGetId($"Incantation of {cleanBase} Self", out int id1)) return id1; + if (TryGetId($"Incantation of {cleanBase}", out int id2)) return id2; + // Aura variant: "Aura of Incantation of Blood Drinker Self" + if (TryGetId($"Aura of Incantation of {cleanBase} Self", out int id3)) return id3; + if (TryGetId($"Aura of Incantation of {cleanBase}", out int id4)) return id4; + } + else if (tier == 7) + { + // Lore names first (already includes "Aura of" where needed) + if (LoreNames.TryGetValue(cleanBase, out string[] lores)) + { + foreach (string lore in lores) + { + if (TryGetId(lore, out int idL)) return idL; + } + } + // Standard VII + if (TryGetId($"{cleanBase} Self VII", out int id7a)) return id7a; + if (TryGetId($"{cleanBase} VII", out int id7b)) return id7b; + // Aura variant VII + if (TryGetId($"Aura of {cleanBase} Self VII", out int id7c)) return id7c; + if (TryGetId($"Aura of {cleanBase} VII", out int id7d)) return id7d; + } + else + { + // Standard: "Focus Self VI" + string numeral = GetRomanNumeral(tier); + if (TryGetId($"{cleanBase} Self {numeral}", out int idNum1)) return idNum1; + if (TryGetId($"{cleanBase} {numeral}", out int idNum2)) return idNum2; + // Aura variant: "Aura of Blood Drinker Self VI" + if (TryGetId($"Aura of {cleanBase} Self {numeral}", out int idNum3)) return idNum3; + if (TryGetId($"Aura of {cleanBase} {numeral}", out int idNum4)) return idNum4; + } + } + return 0; + } + + private bool TryGetId(string exactName, out int spellId) + { + if (SpellDictionary.TryGetValue(exactName, out spellId)) + { + if (_core.CharacterFilter.IsSpellKnown(spellId)) return true; + } + spellId = 0; + return false; + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/Vtank spelldump.txt b/Plugins/RynthAi/Combat/Vtank spelldump.txt new file mode 100644 index 0000000..f6873ca Binary files /dev/null and b/Plugins/RynthAi/Combat/Vtank spelldump.txt differ diff --git a/Plugins/RynthAi/DecalInspector.cs b/Plugins/RynthAi/DecalInspector.cs new file mode 100644 index 0000000..84b5ede --- /dev/null +++ b/Plugins/RynthAi/DecalInspector.cs @@ -0,0 +1,38 @@ +using System; +using System.Reflection; +using Decal.Adapter; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public static class DecalInspector + { + public static void DumpType(Type t, CoreManager core) + { + core.Actions.AddChatText("====== " + t.FullName + " ======", 3); + + core.Actions.AddChatText("-- PROPERTIES --", 3); + foreach (var p in t.GetProperties()) + { + core.Actions.AddChatText(p.PropertyType.Name + " " + p.Name, 3); + } + + core.Actions.AddChatText("-- METHODS --", 3); + foreach (var m in t.GetMethods()) + { + core.Actions.AddChatText(m.ReturnType.Name + " " + m.Name, 3); + } + } + + public static void DumpDecalAPI(CoreManager core) + { + DumpType(typeof(WorldObject), core); + DumpType(typeof(CharacterFilter), core); + DumpType(typeof(CoreManager), core); + + // These are the important ones for navigation + DumpType(typeof(HooksWrapper), core); + DumpType(typeof(WorldFilter), core); + } + } +} diff --git a/Plugins/RynthAi/Logic/BackgroundFpsUnlocker.cs b/Plugins/RynthAi/Logic/BackgroundFpsUnlocker.cs new file mode 100644 index 0000000..d018b03 --- /dev/null +++ b/Plugins/RynthAi/Logic/BackgroundFpsUnlocker.cs @@ -0,0 +1,81 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi.Utility +{ + public class BackgroundFpsUnlocker : IDisposable + { + // --- THE FIX: Tell Windows to use the correct C++ memory standard --- + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + + [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")] + private static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong); + + [DllImport("user32.dll", EntryPoint = "SetWindowLong")] + private static extern IntPtr SetWindowLong32(IntPtr hWnd, int nIndex, IntPtr dwNewLong); + + private static IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong) + { + if (IntPtr.Size == 8) return SetWindowLongPtr64(hWnd, nIndex, dwNewLong); + return SetWindowLong32(hWnd, nIndex, dwNewLong); + } + + [DllImport("user32.dll")] + private static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); + + private const int GWLP_WNDPROC = -4; + private const uint WM_ACTIVATEAPP = 0x001C; + + private WndProcDelegate _newWndProc; + private IntPtr _oldWndProc = IntPtr.Zero; + private IntPtr _acWindowHandle; + private PluginHost _host; + private bool _isUnlocked = false; + + public void Start(PluginHost host) + { + _host = host; + if (_isUnlocked) return; + + try + { + _acWindowHandle = Process.GetCurrentProcess().MainWindowHandle; + + _newWndProc = new WndProcDelegate(CustomWndProc); + IntPtr pNewWndProc = Marshal.GetFunctionPointerForDelegate(_newWndProc); + + _oldWndProc = SetWindowLongPtr(_acWindowHandle, GWLP_WNDPROC, pNewWndProc); + + _isUnlocked = true; + _host.Actions.AddChatText("[RynthAi] Native Background FPS Unlocked.", 5); + } + catch (Exception ex) + { + _host.Actions.AddChatText("[RynthAi] Failed to unlock FPS: " + ex.Message, 1); + } + } + + public void Dispose() + { + if (_isUnlocked && _oldWndProc != IntPtr.Zero) + { + SetWindowLongPtr(_acWindowHandle, GWLP_WNDPROC, _oldWndProc); + _isUnlocked = false; + } + } + + private IntPtr CustomWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) + { + // When the game is told to sleep, we intercept it and tell it to stay awake + if (msg == WM_ACTIVATEAPP) + { + return CallWindowProc(_oldWndProc, hWnd, msg, (IntPtr)1, lParam); + } + + return CallWindowProc(_oldWndProc, hWnd, msg, wParam, lParam); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Logic/CommandProcessor.cs b/Plugins/RynthAi/Logic/CommandProcessor.cs new file mode 100644 index 0000000..7a9779b --- /dev/null +++ b/Plugins/RynthAi/Logic/CommandProcessor.cs @@ -0,0 +1,812 @@ +using System; +using System.IO; +using System.Linq; +using System.Collections.Generic; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; +using RynthAi.Meta; + +namespace NexSuite.Plugins.RynthAi +{ + public class CommandProcessor + { + private readonly PluginCore _plugin; + private readonly UISettings _settings; + private readonly MetaManager _meta; + private readonly NavigationManager _nav; + private readonly BuffManager _buff; + private readonly CombatManager _combat; + private readonly LootManager _loot; + private readonly LuaManager _lua; + private readonly RynthJumper _jumper; + private readonly SpellManager _spellManager; + private readonly FellowshipTracker _fellowship; + + public CommandProcessor(PluginCore plugin, UISettings settings, MetaManager meta, NavigationManager nav, BuffManager buff, CombatManager combat, LootManager loot, LuaManager lua, RynthJumper jumper, SpellManager spellManager, FellowshipTracker fellowship) + { + _plugin = plugin; + _settings = settings; + _meta = meta; + _nav = nav; + _buff = buff; + _combat = combat; + _loot = loot; + _lua = lua; + _jumper = jumper; + _spellManager = spellManager; + _fellowship = fellowship; + } + + public void Execute(string text, ChatParserInterceptEventArgs e) + { + try + { + string trimmed = text.Trim(); + bool isNA = trimmed.StartsWith("/na", StringComparison.OrdinalIgnoreCase); + bool isVT = trimmed.StartsWith("/vt", StringComparison.OrdinalIgnoreCase); + bool isLua = trimmed.StartsWith("/lua", StringComparison.OrdinalIgnoreCase); + + if (!isNA && !isVT && !isLua) return; + + string[] parts = trimmed.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + + // --- Handle Top-Level /lua command --- + if (isLua) + { + e.Eat = true; + if (parts.Length < 2) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /lua <script>", 1); + return; + } + string script = trimmed.Substring(5).Trim(); + _lua?.ExecuteString(script); + return; + } + + if (parts.Length < 2) + { + PrintHelp(); + e.Eat = true; + return; + } + + e.Eat = true; + string cmd = parts[1].ToLower(); + + switch (cmd) + { + // --- NEW COMMANDS --- + case "lua": + if (parts.Length >= 3) + { + string script = string.Join(" ", parts, 2, parts.Length - 2); + _lua?.ExecuteString(script); + } + break; + + case "opt": + HandleOptCommand(parts); + break; + + case "addnavpt": + HandleAddNavPoint(); + break; + + // --- CORE MACRO CONTROLS --- + case "start": + case "on": + _settings.IsMacroRunning = true; + _plugin.SaveSettings(); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Macro STARTED.", 5); + break; + + case "stop": + case "off": + _settings.IsMacroRunning = false; + _buff?.CancelBuffing(); + _nav?.Stop(); + _plugin.SaveSettings(); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Macro STOPPED.", 5); + break; + + case "status": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Macro: {(_settings.IsMacroRunning ? "ON" : "OFF")} | State: {_settings.CurrentState} | Nav: {Path.GetFileName(_settings.CurrentNavPath)} | Meta: {Path.GetFileName(_settings.CurrentMetaPath)}", 1); + break; + + // --- SUBSYSTEMS & PROFILES --- + case "settings": + HandleSettingsCommand(parts); + break; + + case "nav": + case "loot": + case "meta": + HandleSubsystemCommand(cmd, parts, text); + break; + + case "setmetastate": + if (parts.Length >= 3) + { + string newState = string.Join(" ", parts, 2, parts.Length - 2); + _settings.CurrentState = newState; + _settings.ForceStateReset = true; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Meta State forced to: {newState}", 5); + } + break; + + case "db": + case "debugbuffs": + _buff?.PrintBuffDebug(); + break; + + case "dn": + case "debugnav": + if (_nav != null) + { + _nav.DebugNav = !_nav.DebugNav; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Nav debug: {(_nav.DebugNav ? "ON" : "OFF")}", 5); + } + break; + + case "wd": + case "watchdog": + _meta?.PrintWatchdogStatus(); + break; + + case "fakedeath": + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Faking character death trigger...", 5); + _meta?.HandleChat("You have died."); + break; + + case "rebuff": + case "forcebuff": + _buff?.ForceFullRebuff(); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Force-buff sequence initiated.", 5); + break; + + case "cancelforcebuff": + _buff?.CancelBuffing(); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Force-buff sequence cancelled.", 5); + break; + + case "raycast": + HandleRaycastCommand(parts); + break; + + case "lostest": + if (_combat != null) + { + var diagLines = _combat.RunLosTestDiag(_plugin.PluginCoreManager); + foreach (var line in diagLines) + _plugin.PluginHost.Actions.AddChatText("[RynthAi LOS] " + line, 1); + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Combat manager not initialized", 1); + } + break; + + case "blacklist": + if (parts.Length >= 3 && parts[2].ToLower() == "clear") + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Blacklist cleared.", 5); + } + else + { + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Blacklist: attempts={_settings.BlacklistAttempts}, timeout={_settings.BlacklistTimeoutSec}s", 1); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na blacklist clear", 1); + } + break; + + // --- COMBAT & UTILITY STUBS --- + case "deletemonster": + int targetId = _plugin.PluginHost.Actions.CurrentSelection; + if (targetId != 0) _plugin.PluginHost.Actions.AddChatText($"[RynthAi] DeleteMonster stubbed target: {targetId}", 5); + break; + + case "setattackbar": + if (parts.Length >= 3) + { + string target = "melee"; // default + float rawVal; + if (parts.Length >= 4 && float.TryParse(parts[3], out rawVal)) + { + target = parts[2].ToLower(); // "melee" or "missile" + } + else if (float.TryParse(parts[2], out rawVal)) + { + // /na setattackbar 0.5 → sets both + target = "both"; + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na setattackbar [melee|missile] 0-1", 1); + break; + } + int pct = Math.Max(0, Math.Min(100, (int)(rawVal * 100))); + if (target == "missile") { _settings.MissileAttackPower = pct; } + else if (target == "melee") { _settings.MeleeAttackPower = pct; } + else { _settings.MeleeAttackPower = pct; _settings.MissileAttackPower = pct; } + _plugin.SaveSettings(); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Attack power ({target}): {pct}%", 5); + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na setattackbar [melee|missile] 0-1", 1); + } + break; + + case "autoattackpower": + if (parts.Length >= 3) + { + if (parts[2].Equals("auto", StringComparison.OrdinalIgnoreCase)) + { + _settings.MeleeAttackPower = -1; + _settings.MissileAttackPower = -1; + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Attack power set to AUTO (full power) for both modes", 5); + } + else if (int.TryParse(parts[2], out int pwr)) + { + pwr = Math.Max(0, Math.Min(100, pwr)); + _settings.MeleeAttackPower = pwr; + _settings.MissileAttackPower = pwr; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Attack power set to {pwr}% for both modes", 5); + } + _plugin.SaveSettings(); + } + else + { + string mPwr = _settings.MeleeAttackPower < 0 ? "AUTO" : $"{_settings.MeleeAttackPower}%"; + string rPwr = _settings.MissileAttackPower < 0 ? "AUTO" : $"{_settings.MissileAttackPower}%"; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Melee: {mPwr}, Missile: {rPwr}. Usage: /na autoattackpower [auto|0-100]", 1); + } + break; + + case "tapjump": + if (_jumper != null) _jumper.TapJump(); + break; + + case "spelldump": + // /na spelldump Focus — shows all spells containing "Focus" + if (parts.Length >= 3 && _spellManager != null) + { + string keyword = string.Join(" ", parts, 2, parts.Length - 2).ToLower(); + int found = 0; + foreach (var kvp in _spellManager.SpellDictionary) + { + if (kvp.Key.ToLower().Contains(keyword)) + { + bool known = false; + try { known = _plugin.PluginCoreManager.CharacterFilter.IsSpellKnown(kvp.Value); } catch { } + _plugin.PluginHost.Actions.AddChatText($" {kvp.Key} (id={kvp.Value}) {(known ? "[KNOWN]" : "[unknown]")}", 1); + found++; + } + } + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Found {found} spells matching '{keyword}'", 1); + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na spelldump <keyword>", 1); + } + break; + + case "bufftest": + // /na bufftest Focus Self — traces the full buff lookup path + if (parts.Length >= 3 && _spellManager != null) + { + string buffName = string.Join(" ", parts, 2, parts.Length - 2); + string cleanBase = buffName.Replace(" Self", "").Trim(); + _plugin.PluginHost.Actions.AddChatText($"[BuffTest] Input: '{buffName}' → cleanBase: '{cleanBase}'", 1); + + // Check what GetHighestSpellTier returns + var testSkills = new[] { + CharFilterSkillType.CreatureEnchantment, + CharFilterSkillType.LifeMagic, + CharFilterSkillType.ItemEnchantment + }; + foreach (var sk in testSkills) + { + int tier = _spellManager.GetHighestSpellTier(sk); + _plugin.PluginHost.Actions.AddChatText($"[BuffTest] {sk} → maxTier={tier}", 1); + } + + // Trace the exact lookups + string[] tries = new[] { + $"Incantation of {cleanBase} Self", + $"Incantation of {cleanBase}", + }; + foreach (string tryName in tries) + { + bool inDict = _spellManager.SpellDictionary.ContainsKey(tryName); + int id = inDict ? _spellManager.SpellDictionary[tryName] : 0; + bool known = false; + if (id > 0) try { known = _plugin.PluginCoreManager.CharacterFilter.IsSpellKnown(id); } catch { } + _plugin.PluginHost.Actions.AddChatText($"[BuffTest] Try '{tryName}' → inDict={inDict}, id={id}, known={known}", 1); + } + + // Now call the actual method + int result = _spellManager.GetDynamicSelfBuffId(buffName, CharFilterSkillType.CreatureEnchantment); + string resultName = "(none)"; + if (result > 0 && _spellManager.SpellDictionary.Values.Contains(result)) + { + foreach (var kvp in _spellManager.SpellDictionary) + { + if (kvp.Value == result) { resultName = kvp.Key; break; } + } + } + _plugin.PluginHost.Actions.AddChatText($"[BuffTest] GetDynamicSelfBuffId returned: {result} = '{resultName}'", 1); + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na bufftest Focus Self", 1); + } + break; + + case "fellow": + case "fellowship": + // /na fellow [subcommand] — fellowship info and actions + if (_fellowship == null) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Fellowship tracker not initialized.", 1); + break; + } + + string fellowSub = (parts.Length >= 3) ? parts[2].ToLower() : "status"; + + if (!_fellowship.IsInFellowship && fellowSub != "help") + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Not in a fellowship.", 1); + break; + } + + switch (fellowSub) + { + case "status": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Fellowship: \"{_fellowship.FellowshipName}\"", 1); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Members: {_fellowship.MemberCount} | Leader: {(_fellowship.IsLeader ? "ME" : $"0x{_fellowship.LeaderId:X8}")} | Open: {_fellowship.IsOpen} | Locked: {_fellowship.IsLocked} | ShareXP: {_fellowship.ShareXP}", 1); + { + int fidx = 0; + foreach (string mName in _fellowship.GetMemberNames()) + { + int mId = _fellowship.GetMemberId(fidx); + bool isLdr = (mId == _fellowship.LeaderId); + _plugin.PluginHost.Actions.AddChatText($" [{fidx}] {mName} (0x{mId:X8}){(isLdr ? " [LEADER]" : "")}", 1); + fidx++; + } + } + break; + + case "leader": + { + int leaderId = _fellowship.LeaderId; + string leaderName = "(unknown)"; + int li = 0; + foreach (string mn in _fellowship.GetMemberNames()) + { + if (_fellowship.GetMemberId(li) == leaderId) { leaderName = mn; break; } + li++; + } + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Leader: {leaderName} (0x{leaderId:X8}){(_fellowship.IsLeader ? " (you)" : "")}", 1); + } + break; + + case "count": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Fellowship member count: {_fellowship.MemberCount}", 1); + break; + + case "names": + { + var names = new List<string>(_fellowship.GetMemberNames()); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Members ({names.Count}): {string.Join(", ", names)}", 1); + } + break; + + case "name": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Fellowship name: \"{_fellowship.FellowshipName}\"", 1); + break; + + case "open": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Open: {_fellowship.IsOpen}", 1); + break; + + case "locked": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Locked: {_fellowship.IsLocked}", 1); + break; + + case "sharexp": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] ShareXP: {_fellowship.ShareXP}", 1); + break; + + case "ismember": + if (parts.Length >= 4) + { + string checkName = string.Join(" ", parts, 3, parts.Length - 3); + bool found = _fellowship.IsMember(checkName); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] IsMember(\"{checkName}\"): {found}", 1); + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na fellow ismember <name>", 1); + } + break; + + case "help": + _plugin.PluginHost.Actions.AddChatText("[RynthAi] /na fellow [status|leader|count|names|name|open|locked|sharexp|ismember <name>]", 1); + break; + + default: + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Unknown fellow subcommand: {fellowSub}. Try /na fellow help", 1); + break; + } + break; + + case "corpsedebug": + // /na corpsedebug — check the currently selected corpse's ownership info + { + int selId = _plugin.PluginHost.Actions.CurrentSelection; + if (selId == 0) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Select a corpse first.", 1); + break; + } + var wo = _plugin.PluginCoreManager.WorldFilter[selId]; + if (wo == null) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Selected object not found.", 1); + break; + } + string corpName = wo.Name ?? "(null)"; + string longDesc = ""; + try { longDesc = wo.Values((StringValueKey)16, ""); } catch { } + string myName = _plugin.PluginCoreManager.CharacterFilter.Name; + + // Extract killer + string killerName = "(unknown)"; + const string prefix = "Killed by "; + int idx = longDesc.IndexOf(prefix, StringComparison.OrdinalIgnoreCase); + if (idx >= 0) + { + killerName = longDesc.Substring(idx + prefix.Length).TrimEnd('.', ' ', '\n', '\r'); + } + + bool isMe = killerName.Equals(myName, StringComparison.OrdinalIgnoreCase); + bool isFellow = _fellowship != null && _fellowship.IsMember(killerName); + + _plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] Name: {corpName}", 1); + _plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] LongDesc: '{longDesc}'", 1); + _plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] Killer: '{killerName}'", 1); + _plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] IsMe: {isMe}, IsFellow: {isFellow}", 1); + _plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] LootOwnership: {_settings.LootOwnership} (0=Mine, 1=Fellow, 2=All)", 1); + } + break; + + // ── NATIVE JUMP SYSTEM ── + case "jump": + case "jumpsw": + case "jumpsx": + case "jumpswz": + case "jumpswx": + case "jumpswzx": + case "jumpswzxc": + HandleJumpCommand(cmd, parts); + break; + + case "face": + if (parts.Length >= 3 && double.TryParse(parts[2], out double faceHeading)) + { + _plugin.PluginCoreManager.Actions.Heading = (float)faceHeading; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Facing {faceHeading:F0}", 5); + } + break; + + case "reverseroute": + if (parts.Length >= 3) + { + bool rev = parts[2].ToLower() == "true"; + _nav?.SetReverse(rev); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Reverse Route: {rev}", 5); + } + break; + + case "reverseroutequery": + bool isRev = _nav?.IsReversed ?? false; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Reverse Route is: {isRev}", 5); + break; + + case "mexec": + if (parts.Length >= 3) + { + string expr = text.Substring(text.IndexOf("mexec") + 5).Trim(); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] MEXEC: {expr}", 5); + try { _plugin.PluginHost.Actions.InvokeChatParser($"/ub mexec {expr}"); } + catch (Exception ex) { _plugin.PluginHost.Actions.AddChatText($"[RynthAi] UB Error: {ex.Message}", 1); } + } + break; + + case "echo": + string echoText = string.Join(" ", parts, 2, parts.Length - 2); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] {echoText}", 5); + break; + + case "ui": + _plugin.ToggleUI(); + break; + + // ── COMBAT ACTION DIAGNOSTICS ── + case "probe": + // /na probe — show CombatActionHelper initialization status + { + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] CombatActionHelper initialized: {CombatActionHelper.IsInitialized}", 1); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] (Check chat log at plugin load for detailed scan results)", 1); + if (!CombatActionHelper.IsInitialized) + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Pattern scan failed — CM_Combat functions not found in this acclient.exe build", 1); + } + break; + + case "testattack": + // /na testattack — attempts a single melee attack on current selection + // Use this with combat OFF to isolate the direct call + { + int selId = _plugin.PluginHost.Actions.CurrentSelection; + if (selId == 0) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Select a target first.", 1); + break; + } + if (!CombatActionHelper.IsInitialized) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] CombatActionHelper not initialized.", 1); + break; + } + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Sending MeleeAttack to target 0x{selId:X8}, height=Medium, power=0.5...", 1); + bool ok = CombatActionHelper.MeleeAttack((uint)selId, CombatActionHelper.ATTACK_HEIGHT_MEDIUM, 0.5f); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] MeleeAttack returned: {ok}", 1); + } + break; + + default: + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Unknown command: {cmd}", 1); + break; + } + } + catch (Exception ex) + { + _plugin.PluginHost.Actions.AddChatText($"[RynthAi Cmd Error] {ex.Message}", 1); + } + } + + private void HandleOptCommand(string[] parts) + { + if (parts.Length < 5 || !parts[2].Equals("set", StringComparison.OrdinalIgnoreCase)) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na opt set <setting> <value>", 1); + return; + } + + string setting = parts[3].ToLower(); + string val = parts[4].ToLower(); + + switch (setting) + { + case "enablecombat": _settings.EnableCombat = (val == "true"); break; + case "enablenav": _settings.EnableNavigation = (val == "true"); break; + case "enablelooting": _settings.EnableLooting = (val == "true"); break; + case "summonpets": _settings.SummonPets = (val == "true"); break; + case "enablemeta": _settings.EnableMeta = (val == "true"); break; + case "attackdistance": + if (float.TryParse(val, out float dist)) _settings.FollowNavMin = dist; + break; + default: + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Unknown option: {setting}", 1); + return; + } + + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Option {setting} set to {val}", 5); + _plugin.SaveSettings(); + } + + private void HandleAddNavPoint() + { + if (_settings.CurrentRoute == null) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Error: No route loaded.", 1); + return; + } + + var coords = _plugin.PluginCoreManager.WorldFilter[_plugin.PluginCoreManager.CharacterFilter.Id].Coordinates(); + + // FIX: Using Object Initializer to avoid constructor errors + var newPoint = new NavPoint + { + NS = (float)coords.NorthSouth, + EW = (float)coords.EastWest, + Z = (float)_plugin.PluginCoreManager.Actions.LocationZ + }; + + _settings.CurrentRoute.Points.Add(newPoint); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Added Nav Point at: {newPoint.NS:F2}N, {newPoint.EW:F2}E", 5); + _plugin.UI?.RouteTab?.UpdateRouteGraphics(); + } + + private void HandleSettingsCommand(string[] parts) + { + if (parts.Length < 3) return; + string sub = parts[2].ToLower(); + string fileName = (parts.Length >= 4) ? parts[3] : "default"; + if (!fileName.EndsWith(".json")) fileName += ".json"; + + string server = _plugin.PluginCoreManager.CharacterFilter.Server; + string name = _plugin.PluginCoreManager.CharacterFilter.Name; + string globalDir = @"C:\Games\DecalPlugins\NexSuite\RynthAi\GlobalSettings"; + string charDir = Path.Combine(@"C:\Games\DecalPlugins\NexSuite\RynthAi\SettingsProfiles", server, name); + + if (!Directory.Exists(globalDir)) Directory.CreateDirectory(globalDir); + if (!Directory.Exists(charDir)) Directory.CreateDirectory(charDir); + + string globalPath = Path.Combine(globalDir, fileName); + string charPath = Path.Combine(charDir, fileName); + + switch (sub) + { + case "save": _plugin.SaveSettings(globalPath); break; + case "load": _plugin.LoadSettings(globalPath); break; + case "savechar": _settings.MineOnly = true; _plugin.SaveSettings(charPath); break; + case "loadchar": _settings.MineOnly = true; _plugin.LoadSettings(charPath); break; + } + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Settings {sub} successful: {fileName}", 5); + } + + private void HandleSubsystemCommand(string type, string[] parts, string fullText) + { + if (parts.Length < 4) return; + string action = parts[2].ToLower(); + string fileName = string.Join(" ", parts, 3, parts.Length - 3); + + string folder = type == "nav" ? _plugin.NavFolder : (type == "meta" ? _plugin.MetaFolder : _plugin.LootFolder); + string ext = type == "nav" ? ".nav" : (type == "meta" ? ".met" : ".utl"); + + if (!fileName.EndsWith(ext)) fileName += ext; + string fullPath = Path.Combine(folder, fileName); + + if (action == "save") + { + if (!File.Exists(fullPath)) File.WriteAllText(fullPath, ""); + if (type == "nav") _settings.CurrentRoute?.Save(fullPath); + else if (type == "meta") { _settings.CurrentMetaPath = fullPath; _meta?.SaveCurrentProfile(); } + else if (type == "loot") { _settings.EnableLooting = true; _loot?.SaveProfile(fullPath); } + } + else if (action == "load") + { + if (!File.Exists(fullPath)) + { + File.WriteAllText(fullPath, ""); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Created new {type} profile: {fileName}", 5); + } + + if (type == "nav") + { + _settings.CurrentNavPath = fullPath; + _settings.CurrentRoute = VTankNavParser.Load(fullPath); + _nav?.ResetRouteState(); + + // Find nearest waypoint for Circular/Linear routes + if (_settings.CurrentRoute.RouteType == NavRouteType.Circular || + _settings.CurrentRoute.RouteType == NavRouteType.Linear) + { + _settings.ActiveNavIndex = _nav != null ? _nav.FindNearestWaypoint(_settings.CurrentRoute) : 0; + } + else + { + _settings.ActiveNavIndex = 0; + } + + // Refresh route graphics + if (_plugin.UI?.RouteTab != null) + _plugin.UI.RouteTab.NeedsRouteGraphicsRefresh = true; + } + else if (type == "meta") { _settings.CurrentMetaPath = fullPath; _meta?.LoadProfile(fullPath); } + else if (type == "loot") { _settings.EnableLooting = true; _loot?.LoadProfile(fullPath); } + } + + SyncUI(type, fileName, folder); + _plugin.SaveSettings(); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] {type.ToUpper()} {action} successful: {fileName}", 5); + } + + private void SyncUI(string type, string fileName, string folder) + { + if (_plugin.UI == null) return; + if (type == "nav") _plugin.UI.RefreshNavFiles(); + if (type != "meta") return; + + _plugin.UI.RefreshMetaFiles(); + if (Directory.Exists(folder)) + { + string[] files = Directory.GetFiles(folder, "*.met"); + Array.Sort(files); + for (int i = 0; i < files.Length; i++) + { + if (Path.GetFileName(files[i]).Equals(fileName, StringComparison.OrdinalIgnoreCase)) + { + _settings.MetaProfileIdx = i + 1; + break; + } + } + } + } + + private void HandleRaycastCommand(string[] parts) + { + if (parts.Length > 2) + { + _settings.EnableRaycasting = (parts[2].ToLower() == "on"); + _plugin.SaveSettings(); + } + else + { + string rayStatus = _combat?.GetRaycastStatus() ?? "No info"; + foreach (var line in rayStatus.Split('\n')) _plugin.PluginHost.Actions.AddChatText("[RynthAi] " + line.Trim(), 1); + } + } + + /// <summary> + /// Handles /na jump commands natively using RynthJumper. + /// Format: /na jump[swzxc] [heading] [holdtime] + /// - /na jump = tap jump + /// - /na jumpsw 180 500 = face south, jump forward with 500/1000 power + /// - /na jumpsx 300 = jump backward with 300/1000 power + /// </summary> + private void HandleJumpCommand(string cmd, string[] parts) + { + if (_jumper == null) return; + if (_jumper.IsJumping) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Already jumping — wait for completion", 1); + return; + } + + // Simple tap jump + if (cmd == "jump" && parts.Length <= 2) + { + _jumper.TapJump(); + return; + } + + // Parse hold time + int holdMs = 0; + double heading = -1; // -1 = use current heading + + if (parts.Length >= 4 && int.TryParse(parts[3], out int ht)) + holdMs = ht; + else if (parts.Length >= 3 && int.TryParse(parts[2], out int ht2)) + holdMs = ht2; + + if (parts.Length >= 3 && double.TryParse(parts[2], out double hd)) + { + heading = hd; + // If heading was parsed as first arg, holdtime is second + if (parts.Length >= 4 && int.TryParse(parts[3], out int ht3)) + holdMs = ht3; + } + + // Parse direction keys from command suffix + bool shift = cmd.Contains("s"); + bool forward = cmd.Contains("w"); + bool backward = cmd.Contains("x"); + bool slideLeft = cmd.Contains("z"); + bool slideRight = cmd.Contains("c"); + + _jumper.StartJump(heading, holdMs, shift, forward, backward, slideLeft, slideRight); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Jumping: heading={heading:F0} hold={holdMs}ms keys={cmd.Replace("jump","")}", 5); + } + + private void PrintHelp() + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Commands: /na [start|stop|status], /na lostest, /na setattackbar 0-1, /na autoattackpower [auto|0-1]", 1); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] /na fellow [status|leader|count|names|name|ismember <n>], /na probe, /na testattack", 1); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] /na jump[sw|sx|swz|swx|swzx|swzxc] [heading] [holdtime], /na blacklist [clear], /lua <script>", 1); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Logic/NavigationManager.cs b/Plugins/RynthAi/Logic/NavigationManager.cs new file mode 100644 index 0000000..921c055 --- /dev/null +++ b/Plugins/RynthAi/Logic/NavigationManager.cs @@ -0,0 +1,1154 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using AcClient; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// VTank-faithful navigation engine. + /// + /// ARCHITECTURE: + /// Forward motion: SetAutorun(true/false) via Decal API. + /// - Player can toggle autorun off manually for immediate control. + /// - Re-asserted every 500ms as heartbeat. + /// + /// Steering while running: SetClientMotion(TurnRight/TurnLeft) via + /// AcClient command interpreter. These combine with autorun naturally + /// (like pressing W+A or W+D) without interrupting forward motion. + /// + /// Large turns (>60°): Stop autorun, snap Actions.Heading while + /// stopped, resume autorun once error is below 20°. + /// + /// Closest-approach detection prevents circling waypoints. + /// </summary> + public class NavigationManager + { + private readonly CoreManager _core; + private readonly UISettings _settings; + private readonly PluginHost _host; + + // ── Motion command constants (turns only — forward uses SetAutorun) ──── + private const uint MOTION_TURNRIGHT = 0x6500000D; + private const uint MOTION_TURNLEFT = 0x6500000E; + + // ── Nav tick ──────────────────────────────────────────────────────────── + private DateTime _lastNavTick = DateTime.MinValue; + private const double NAV_TICK_MS = 33.0; // ~30 Hz — smoother turn toggling + + // ── Stop debounce ─────────────────────────────────────────────────────── + private DateTime _stopRequestedAt = DateTime.MaxValue; + private const double STOP_DEBOUNCE_MS = 300.0; + + // ── Movement state ────────────────────────────────────────────────────── + private bool _isMovingForward = false; + private bool _hasStopped = true; + private bool _turnsStopped = true; + public bool DebugNav = false; + private DateTime _lastDebugPrint = DateTime.MinValue; + private double _lastGoodHeading = 0; + private bool _hasGoodHeading = false; // true = we've already stopped, don't repeat + + // ── W tap heartbeat — periodic safety tap ─────────────────────────────── + private DateTime _lastWTap = DateTime.MinValue; + private const double W_HEARTBEAT_MS = 500.0; + + // ── Turning state ─────────────────────────────────────────────────────── + private bool _isTurning = false; + + // ── Heading thresholds ────────────────────────────────────────────────── + private const double DEAD_ZONE = 4.0; // wider for indoor stability — frequent small corrections = smooth + private const double BIG_TURN_ENTER = 20.0; // stop and turn above this + private const double BIG_TURN_EXIT = 10.0; // resume running below this + + // ── Arrival / lookahead ───────────────────────────────────────────────── + private double ArrivalYards => Math.Max(1.5, _settings.FollowNavMin); + private double LookaheadYards => ArrivalYards * 0.1; + + // ── Closest approach tracking ─────────────────────────────────────────── + // Detects when we've passed a waypoint even if we never entered the + // arrival radius (turn radius at speed is too wide). If distance was + // decreasing and starts increasing, we've swept past — advance. + private double _prevDist = double.MaxValue; + + // ── Route bookkeeping ─────────────────────────────────────────────────── + private int _linearDir = 1; + private bool _inPause = false; + private DateTime _pauseUntil = DateTime.MinValue; + private bool _actionFired = false; + private DateTime _actionExpiry = DateTime.MinValue; + private const double ACTION_TIMEOUT_MS = 10000.0; + + // ── Portal/Recall state machine ───────────────────────────────────────── + private enum PortalState + { + None, + Settling, + EquippingWand, + EnteringMagicMode, + CastingSpell, + WaitingForPortalOrTeleport, + WaitingForPortalExit, + PostTeleportSettle // Brief pause after teleporting to cancel UseItem effects + } + private PortalState _portalState = PortalState.None; + private DateTime _portalStateStart = DateTime.MinValue; + private int _preCastLandblock = 0; + private int _prePortalLandblock = 0; + private double _prePortalNS = double.NaN; + private double _prePortalEW = double.NaN; + private const double PORTAL_STATE_TIMEOUT_MS = 15000.0; + private const double SETTLE_DELAY_MS = 600.0; + private const double WAND_EQUIP_DELAY_MS = 1000.0; + private const double MAGIC_MODE_DELAY_MS = 800.0; + private const double CAST_DELAY_MS = 500.0; + private const double PORTAL_WAIT_MS = 3000.0; + + // ── Stuck watchdog ────────────────────────────────────────────────────── + private double _watchdogNS = double.NaN; + private double _watchdogEW = double.NaN; + private DateTime _watchdogNext = DateTime.MinValue; + private int _stuckCount = 0; + private bool _inRecovery = false; + private DateTime _recoveryUntil = DateTime.MinValue; + private const double WATCHDOG_MS = 5000.0; + private const double STUCK_YD = 2.0; + private const double RECOVERY_MS = 1200.0; + + // ── Tier 2 state (MoveToPosition via MovementManager) ───────────────── + private int _tier2TargetIdx = -1; // waypoint index we last issued MoveToPosition for + private bool _tier2Active = false; // true while a Tier2 MoveToPosition is in flight + private DateTime _tier2IssuedAt = DateTime.MinValue; + private const double TIER2_REISSUE_MS = 2000.0; // re-issue if no progress for this long + private const double TIER2_ARRIVAL_YD = 1.5; // arrival radius (yards) + + // ── Win32 (focus detection only) ──────────────────────────────────────── + [DllImport("user32.dll")] + private static extern IntPtr GetForegroundWindow(); + + public bool IsReversed { get; set; } = false; + public void SetReverse(bool reverse) { IsReversed = reverse; } + + private IntPtr _gameHwnd = IntPtr.Zero; + private IntPtr GameHwnd + { + get + { + if (_gameHwnd == IntPtr.Zero) + _gameHwnd = Process.GetCurrentProcess().MainWindowHandle; + return _gameHwnd; + } + } + + private bool IsGameFocused() => GetForegroundWindow() == GameHwnd; + + public NavigationManager(CoreManager core, UISettings settings, PluginHost host) + { + _core = core; + _settings = settings; + _host = host; + } + + // ══════════════════════════════════════════════════════════════════════════ + // CLIENT MOTION + W TAP + // ══════════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Direct client memory motion — same as UB's setmotion. + /// Used ONCE to establish forward motion state. + /// </summary> + private unsafe void SetClientMotion(uint motion, bool on) + { + try + { + ((ACCmdInterp*)(*SmartBox.smartbox)->cmdinterp)->SetMotion(motion, on); + } + catch { } + } + + private void StartForward() + { + if (!_isMovingForward) + { + try { _core.Actions.SetAutorun(true); } catch { } + _isMovingForward = true; + } + } + + private void StopForward() + { + try { _core.Actions.SetAutorun(false); } catch { } + _isMovingForward = false; + } + + private void StopMovement() + { + _isTurning = false; + StopForward(); + ClearTurnMotions(); + CancelTier2(); + } + + private void CancelTier2() + { + if (_tier2Active) + { + try { Tier2MovementHelper.CancelMoveTo(); } catch { } + _tier2Active = false; + } + _tier2TargetIdx = -1; + } + + private void ClearTurnMotions() + { + SetClientMotion(MOTION_TURNRIGHT, false); + SetClientMotion(MOTION_TURNLEFT, false); + } + + // ══════════════════════════════════════════════════════════════════════════ + // PUBLIC ENTRY POINT + // ══════════════════════════════════════════════════════════════════════════ + + public void ProcessNavigation(bool isFighting) + { + // The priority dispatcher in PluginCore already controls call order. + // Nav only needs to check: macro running, nav enabled, and state is available. + // "Idle" means no higher-priority system claimed this frame. + // "Navigating" means WE claimed it last frame and are still going. + bool shouldNav = _settings.IsMacroRunning + && _settings.EnableNavigation + && (_settings.CurrentState == "Idle" || _settings.CurrentState == "Navigating"); + + if (!shouldNav) + { + if (!_hasStopped && !_turnsStopped) + { try { ClearTurnMotions(); } catch { } _turnsStopped = true; } + if (_stopRequestedAt == DateTime.MaxValue) + _stopRequestedAt = DateTime.Now; + if ((DateTime.Now - _stopRequestedAt).TotalMilliseconds >= STOP_DEBOUNCE_MS) + { + if (!_hasStopped) + { + CancelTier2(); + try { _core.Actions.SetAutorun(false); } catch { } + _isMovingForward = false; + _isTurning = false; + _hasStopped = true; + } + } + return; + } + _stopRequestedAt = DateTime.MaxValue; + _hasStopped = false; + _turnsStopped = false; + + var route = _settings.CurrentRoute; + if (route == null || route.Points.Count == 0) { StopMovement(); return; } + + // Claim the traffic light — we are actively navigating + _settings.CurrentState = "Navigating"; + + // Rate limit to ~15 Hz + if ((DateTime.Now - _lastNavTick).TotalMilliseconds < NAV_TICK_MS) return; + _lastNavTick = DateTime.Now; + + int idx = _settings.ActiveNavIndex; + if (!IndexValid(idx, route)) { HandleRouteEnd(route); return; } + + UpdateWatchdog(); + if (_inRecovery) + { + if (DateTime.Now >= _recoveryUntil) _inRecovery = false; + return; + } + + var pt = route.Points[idx]; + + // ── Pause ─────────────────────────────────────────────────────────── + if (pt.Type == NavPointType.Pause) + { + StopMovement(); + if (!_inPause) { _inPause = true; _pauseUntil = DateTime.Now.AddMilliseconds(pt.PauseTimeMs); } + if (DateTime.Now >= _pauseUntil) { _inPause = false; Advance(route); } + return; + } + + // ── Chat ──────────────────────────────────────────────────────────── + if (pt.Type == NavPointType.Chat) + { + StopMovement(); + if (!_actionFired) + { + _actionFired = true; + try { _core.Actions.InvokeChatParser(pt.ChatCommand); } catch { } + Advance(route); + } + return; + } + + // ── Recall / PortalNPC ────────────────────────────────────────────── + if (pt.Type == NavPointType.Recall || pt.Type == NavPointType.PortalNPC) + { + if (_portalState == PortalState.None) StopMovement(); + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + try { _host.Actions.AddChatText($"[NavDbg] PORTAL state={_portalState} elapsed={(DateTime.Now - _portalStateStart).TotalMilliseconds:F0}ms", 1); } catch { } + } + ProcessPortalAction(pt, route); + return; + } + + // ── Standard coordinate waypoint ──────────────────────────────────── + _actionFired = false; + _inPause = false; + + var pos = GetPos(); + if (pos == null) return; + + double dNS = pt.NS - pos.NorthSouth; + double dEW = pt.EW - pos.EastWest; + double dist = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + + if (dist < ArrivalYards) + { + _prevDist = double.MaxValue; + Advance(route); + return; + } + + // ── Tier 2: delegate to client physics engine ──────────────────── + // The client's MovementManager handles interpolation, heading, and + // speed internally — no frame-by-frame PD-controller needed. + // Falls through to Tier 0/1 steering if not mode 2, not initialized, + // or player is indoors (coordinate conversion is outdoor-only). + if (_settings.MovementMode == 2 && Tier2MovementHelper.IsInitialized + && (Tier2MovementHelper.GetPlayerCellId() & 0xFFFF) < 0x100) + { + ProcessTier2Waypoint(idx, pt, route, pos, dist); + return; + } + + // ── Closest approach detection (Tier 0/1 only) ─────────────────── + // If we were getting closer (within a reasonable range) and now + // we're moving away, we've swept past the waypoint. Advance. + // This handles the case where the turn radius at speed prevents + // the character from entering the arrival radius exactly. + if (_prevDist < ArrivalYards * 2.5 && dist > _prevDist + 0.3) + { + _prevDist = double.MaxValue; + Advance(route); + return; + } + _prevDist = dist; + + // ── Lookahead blend ───────────────────────────────────────────────── + double tNS = pt.NS, tEW = pt.EW; + if (dist < LookaheadYards) + { + int ni = PeekNext(idx, route); + if (ni >= 0) + { + var np = route.Points[ni]; + double t = 1.0 - (dist / LookaheadYards); + tNS = Lerp(pt.NS, np.NS, t); + tEW = Lerp(pt.EW, np.EW, t); + } + } + + // ── Compute heading error ─────────────────────────────────────────── + double desiredDeg = Math.Atan2(tEW - pos.EastWest, tNS - pos.NorthSouth) * (180.0 / Math.PI); + if (desiredDeg < 0) desiredDeg += 360.0; + + double rawHeading = 0; + try { rawHeading = _core.Actions.Heading; } catch { } + double currentDeg; + if (rawHeading != 0.0) + { currentDeg = rawHeading; _lastGoodHeading = rawHeading; _hasGoodHeading = true; } + else if (_hasGoodHeading) + { currentDeg = _lastGoodHeading; } + else + { currentDeg = desiredDeg; } + double error = NormalizeAngle(desiredDeg - currentDeg); + double absError = Math.Abs(error); + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + string turnDir = absError < DEAD_ZONE ? "NONE" : (error > 0 ? "RIGHT" : "LEFT"); + double ox = 0, oy = 0; + try { var me = _core.WorldFilter[_core.CharacterFilter.Id]; if (me != null) { var o = me.Offset(); ox = o.X; oy = o.Y; } } catch { } + try { _host.Actions.AddChatText($"[NavDbg] raw={rawHeading:F1} cur={currentDeg:F1} des={desiredDeg:F1} err={error:F1} turn={turnDir} dist={dist:F1}yd oX={ox:F2} oY={oy:F2}", 1); } catch { } + } + + // ═════════════════════════════════════════════════════════════════════ + // STEERING + // ═════════════════════════════════════════════════════════════════════ + + // ── STATE: Turning in place (big turn while stopped) ───────────────── + if (_isTurning) + { + if (absError > BIG_TURN_EXIT) + { + try { _core.Actions.Heading = (float)desiredDeg; } catch { } + return; + } + + // Close enough — clear turn keys, start running + _isTurning = false; + ClearTurnMotions(); + StartForward(); + return; + } + + // ── BIG TURN (>60°): stop and face ────────────────────────────────── + if (absError > BIG_TURN_ENTER) + { + StopForward(); + ClearTurnMotions(); + try { _core.Actions.Heading = (float)desiredDeg; } catch { } + _isTurning = true; + return; + } + + // ── Ensure we're moving forward ───────────────────────────────────── + StartForward(); + + // ── Near waypoint: stop turning, just run straight ─────────────────── + bool closeToWaypoint = dist < ArrivalYards * 3.0; + + // ── SMALL CORRECTION: use TurnRight/TurnLeft while running ────────── + // These combine with Forward at the command interpreter level — + // the character turns while running naturally, like pressing W+A or W+D. + // No Actions.Heading, no motion interrupt, no W tap needed. + if (absError > DEAD_ZONE && !closeToWaypoint) + { + if (error > 0) + { + // Need to turn right + SetClientMotion(MOTION_TURNRIGHT, true); + SetClientMotion(MOTION_TURNLEFT, false); + } + else + { + // Need to turn left + SetClientMotion(MOTION_TURNLEFT, true); + SetClientMotion(MOTION_TURNRIGHT, false); + } + } + else + { + // On course or close to waypoint — stop turning + ClearTurnMotions(); + } + + // ── HEARTBEAT: re-assert autorun periodically as safety net ───────── + if (_isMovingForward && (DateTime.Now - _lastWTap).TotalMilliseconds > W_HEARTBEAT_MS) + { + try { _core.Actions.SetAutorun(true); } catch { } + _lastWTap = DateTime.Now; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // ROUTE ADVANCEMENT + // ══════════════════════════════════════════════════════════════════════════ + + private void Advance(VTankNavParser route) + { + _actionFired = false; + _prevDist = double.MaxValue; + switch (route.RouteType) + { + case NavRouteType.Circular: + _settings.ActiveNavIndex = (_settings.ActiveNavIndex + 1) % route.Points.Count; + break; + case NavRouteType.Linear: + int n = _settings.ActiveNavIndex + _linearDir; + if (n < 0 || n >= route.Points.Count) { _linearDir = -_linearDir; n = _settings.ActiveNavIndex + _linearDir; } + _settings.ActiveNavIndex = n; + break; + case NavRouteType.Once: + _settings.ActiveNavIndex++; + if (_settings.ActiveNavIndex >= route.Points.Count) { _settings.EnableNavigation = false; StopMovement(); } + break; + case NavRouteType.Follow: + _settings.ActiveNavIndex = 0; + break; + } + } + + private void HandleRouteEnd(VTankNavParser route) + { + if (route.RouteType == NavRouteType.Circular) _settings.ActiveNavIndex = 0; + else StopMovement(); + } + + private int PeekNext(int cur, VTankNavParser route) + { + switch (route.RouteType) + { + case NavRouteType.Circular: return (cur + 1) % route.Points.Count; + case NavRouteType.Linear: int n = cur + _linearDir; return (n >= 0 && n < route.Points.Count) ? n : -1; + case NavRouteType.Once: return (cur + 1 < route.Points.Count) ? cur + 1 : -1; + default: return -1; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // TIER 2 MOVEMENT (CPhysicsObj::MoveToPosition via MovementManager) + // ══════════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Tier 2 waypoint processor — issues a single MoveToPosition call to the + /// client's physics engine, then lets it handle all interpolation and heading. + /// Re-issues the call on waypoint change or if no progress after timeout. + /// </summary> + private void ProcessTier2Waypoint( + int idx, NavPoint pt, VTankNavParser route, + CoordsObject pos, double distYards) + { + // ── Closest approach detection (shared with Tier 0/1) ──────────── + if (_prevDist < ArrivalYards * 2.5 && distYards > _prevDist + 0.3) + { + _prevDist = double.MaxValue; + CancelTier2(); + Advance(route); + return; + } + _prevDist = distYards; + + // ── Decide whether to issue / re-issue the MoveToPosition call ─── + bool needsIssue = false; + + if (idx != _tier2TargetIdx) + { + // Waypoint changed — cancel old movement, issue new + CancelTier2(); + needsIssue = true; + } + else if (_tier2Active && + (DateTime.Now - _tier2IssuedAt).TotalMilliseconds > TIER2_REISSUE_MS) + { + // Timeout — re-issue in case the client gave up + CancelTier2(); + needsIssue = true; + } + else if (!_tier2Active) + { + needsIssue = true; + } + + if (needsIssue) + { + IssueTier2Move(pt, pos); + _tier2TargetIdx = idx; + } + + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + try + { + _host.Actions.AddChatText( + $"[NavDbg] T2 idx={idx} dist={distYards:F1}yd active={_tier2Active} " + + $"age={(DateTime.Now - _tier2IssuedAt).TotalMilliseconds:F0}ms", 1); + } + catch { } + } + } + + /// <summary> + /// Converts Decal NS/EW to internal AC coordinates and calls MoveToPosition. + /// Works by adding the yard-delta to the player's known-good internal position, + /// then normalizing cell/landblock boundaries with Math.Floor (critical for + /// negative deltas — (int) rounds toward zero, not down, producing garbage cells). + /// </summary> + private void IssueTier2Move(NavPoint pt, CoordsObject decalPos) + { + try + { + // Read player's internal position for coordinate reference + uint playerCell; + float playerX, playerY, playerZ; + if (!Tier2MovementHelper.GetPlayerPosition( + out playerCell, out playerX, out playerY, out playerZ)) + return; + + // Indoor cells (objcell_id & 0xFFFF >= 0x100) — fall back to Tier 0/1 + if ((playerCell & 0xFFFF) >= 0x100) + return; + + // ── AC cell ID format: 0xEENNcccc ──────────────────────────── + // EE (bits 24-31) = EW landblock index (increases east) + // NN (bits 16-23) = NS landblock index (increases north) + // cccc = outdoor cell 1-64: (rowNS * 8 + colEW + 1) + // Internal Position.Frame: x = EW, y = NS + // Each landblock = 8×8 cells, each cell = 24×24 yards + + // ── Delta in yards from Decal coordinates ──────────────────── + // Decal: 1 unit = 240 yards. EW→x, NS→y. + double deltaEW = (pt.EW - decalPos.EastWest) * 240.0; + double deltaNS = (pt.NS - decalPos.NorthSouth) * 240.0; + + // ── Safety: clamp to 500 yards max ─────────────────────────── + // Beyond ~2 landblocks the target cell is likely unloaded. + double deltaDist = Math.Sqrt(deltaEW * deltaEW + deltaNS * deltaNS); + if (deltaDist > 500.0) + { + // Scale delta to 500 yards — we'll re-issue when closer + double scale = 500.0 / deltaDist; + deltaEW *= scale; + deltaNS *= scale; + } + + // ── Compute target global position from player's known-good pos ─ + int pLbEW = (int)((playerCell >> 24) & 0xFF); + int pLbNS = (int)((playerCell >> 16) & 0xFF); + int pCellIdx = (int)(playerCell & 0xFFFF) - 1; + if (pCellIdx < 0 || pCellIdx >= 64) return; // invalid outdoor cell + int pColEW = pCellIdx % 8; + int pRowNS = pCellIdx / 8; + + double globalEW = pLbEW * 192.0 + pColEW * 24.0 + playerX + deltaEW; + double globalNS = pLbNS * 192.0 + pRowNS * 24.0 + playerY + deltaNS; + + // ── Decompose to landblock + cell + local ──────────────────── + // Math.Floor is critical — (int) truncates toward zero, which + // produces wrong results for negative coordinates. + int tLbEW = (int)Math.Floor(globalEW / 192.0); + int tLbNS = (int)Math.Floor(globalNS / 192.0); + tLbEW = Math.Max(0, Math.Min(254, tLbEW)); + tLbNS = Math.Max(0, Math.Min(254, tLbNS)); + + double inLbEW = globalEW - tLbEW * 192.0; + double inLbNS = globalNS - tLbNS * 192.0; + + int tColEW = (int)Math.Floor(inLbEW / 24.0); + int tRowNS = (int)Math.Floor(inLbNS / 24.0); + tColEW = Math.Max(0, Math.Min(7, tColEW)); + tRowNS = Math.Max(0, Math.Min(7, tRowNS)); + + float localX = (float)(inLbEW - tColEW * 24.0); + float localY = (float)(inLbNS - tRowNS * 24.0); + float localZ = playerZ; + + // Clamp to valid range within cell (guard against float drift) + localX = Math.Max(0.5f, Math.Min(23.5f, localX)); + localY = Math.Max(0.5f, Math.Min(23.5f, localY)); + + int cellIdx = tRowNS * 8 + tColEW + 1; + uint targetCell = (uint)((tLbEW << 24) | (tLbNS << 16) | cellIdx); + + // ── Sanity: target landblock within 3 of player ────────────── + // If further, the cell is almost certainly not loaded → skip. + if (Math.Abs(tLbEW - pLbEW) > 3 || Math.Abs(tLbNS - pLbNS) > 3) + { + if (DebugNav) + try { _host.Actions.AddChatText($"[NavDbg] T2 SKIP: target lb ({tLbEW},{tLbNS}) too far from player ({pLbEW},{pLbNS})", 1); } catch { } + return; + } + + uint result = Tier2MovementHelper.MoveToPosition( + targetCell, localX, localY, localZ, + 1.0f, + (float)Math.Max(0.5, ArrivalYards * 0.5)); + + _tier2Active = (result == 0); + _tier2IssuedAt = DateTime.Now; + + if (DebugNav) + { + try + { + _host.Actions.AddChatText( + $"[NavDbg] T2 issued: cell=0x{targetCell:X8} lx={localX:F1} ly={localY:F1} " + + $"lz={localZ:F1} lb=({tLbEW},{tLbNS}) delta=({deltaEW:F0},{deltaNS:F0})yd result={result}", 1); + } + catch { } + } + } + catch (Exception ex) + { + if (DebugNav) + try { _host.Actions.AddChatText($"[NavDbg] T2 issue FAILED: {ex.Message}", 1); } catch { } + } + } + + private void ProcessPortalAction(NavPoint pt, VTankNavParser route) + { + // Timeout check - if we've been in this portal action too long, reset and advance + if (_portalState != PortalState.None) + { + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > PORTAL_STATE_TIMEOUT_MS) + { + ResetPortalState(); + Advance(route); + return; + } + } + + // Initialize state machine — go to Settling first to let turns stop + if (_portalState == PortalState.None) + { + _portalState = PortalState.Settling; + _portalStateStart = DateTime.Now; + _preCastLandblock = GetCurrentLandblock(); + // Store position for teleport detection + try { var p = GetPos(); if (p != null) { _prePortalNS = p.NorthSouth; _prePortalEW = p.EastWest; } } catch { } + // Aggressively clear ALL motion + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + try { _core.Actions.SetCombatMode(CombatState.Peace); } catch { } + _isMovingForward = false; + _isTurning = false; + return; + } + + switch (_portalState) + { + case PortalState.Settling: + // Keep clearing turns every frame until settled + try { ClearTurnMotions(); } catch { } + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > SETTLE_DELAY_MS) + { + _portalState = PortalState.EquippingWand; + _portalStateStart = DateTime.Now; + } + break; + + case PortalState.EquippingWand: + ProcessEquippingWand(pt); + break; + + case PortalState.EnteringMagicMode: + ProcessEnteringMagicMode(); + break; + + case PortalState.CastingSpell: + ProcessCastingSpell(pt); + break; + + case PortalState.WaitingForPortalOrTeleport: + ProcessWaitingForPortalOrTeleport(pt, route); + break; + + case PortalState.WaitingForPortalExit: + ProcessWaitingForPortalExit(route); + break; + + case PortalState.PostTeleportSettle: + // Hammer stop commands to cancel any lingering UseItem walk action + // UseItem walk persists through teleportation in the AC client — need + // to keep hammering for ~2s until it expires on its own + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + try { _core.Actions.SetCombatMode(CombatState.Peace); } catch { } + _isMovingForward = false; + _isTurning = false; + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > 4000) + { + ResetPortalState(); + Advance(route); + } + break; + } + } + + private void ProcessEquippingWand(NavPoint pt) + { + // Only equip wand for recall spells, not portal NPCs + if (pt.Type == NavPointType.PortalNPC) + { + _portalState = PortalState.WaitingForPortalOrTeleport; + _portalStateStart = DateTime.Now; + _prePortalLandblock = GetCurrentLandblock(); + try { var p = GetPos(); if (p != null) { _prePortalNS = p.NorthSouth; _prePortalEW = p.EastWest; } } catch { } + + // Use the portal NPC — partial name matching + try + { + WorldObject bestMatch = null; + foreach (WorldObject wo in _core.WorldFilter.GetLandscape()) + { + if (wo == null) continue; + if (wo.Name == pt.TargetName) { bestMatch = wo; break; } + if (wo.Name != null && pt.TargetName != null && + (wo.Name.Contains(pt.TargetName) || pt.TargetName.Contains(wo.Name))) + { bestMatch = wo; } + } + if (bestMatch != null) + _core.Actions.UseItem(bestMatch.Id, 0); + } + catch { } + return; + } + + // For recall spells, equip a wand if needed + double elapsed = (DateTime.Now - _portalStateStart).TotalMilliseconds; + + if (elapsed < 50) + { + try + { + // Check if wand already equipped — UseItem on equipped wand UNEQUIPS it + bool wandEquipped = false; + int wandToEquip = 0; + + // Scan all known objects for wands + foreach (WorldObject wo in _core.WorldFilter.GetInventory()) + { + if (wo.ObjectClass == ObjectClass.WandStaffOrb) + { + int slots = wo.Values(LongValueKey.EquippedSlots, 0); + if (slots != 0) + { + wandEquipped = true; + break; + } + else if (wandToEquip == 0) + { + wandToEquip = wo.Id; // remember first unequipped wand + } + } + } + + if (!wandEquipped && wandToEquip != 0) + { + _core.Actions.UseItem(wandToEquip, 0); + if (DebugNav) try { _host.Actions.AddChatText($"[NavDbg] WAND equipping id={wandToEquip}", 1); } catch { } + } + else if (wandEquipped) + { + if (DebugNav) try { _host.Actions.AddChatText("[NavDbg] WAND already equipped, skipping", 1); } catch { } + } + else + { + if (DebugNav) try { _host.Actions.AddChatText("[NavDbg] WAND none found in inventory!", 1); } catch { } + } + } + catch { } + } + + // Wait for wand equip to complete, then proceed to magic mode + if (elapsed > WAND_EQUIP_DELAY_MS) + { + _portalState = PortalState.EnteringMagicMode; + _portalStateStart = DateTime.Now; + } + } + + private void ProcessEnteringMagicMode() + { + // Enter magic casting mode + try + { + _core.Actions.SetCombatMode(CombatState.Magic); + } + catch { } + + // Wait a moment for mode change, then proceed + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > MAGIC_MODE_DELAY_MS) + { + _portalState = PortalState.CastingSpell; + _portalStateStart = DateTime.Now; + } + } + + private void ProcessCastingSpell(NavPoint pt) + { + // Cast the recall spell + if ((DateTime.Now - _portalStateStart).TotalMilliseconds < 100) // Only cast once + { + try + { + _core.Actions.CastSpell(pt.SpellId, _core.CharacterFilter.Id); + } + catch { } + } + + // Wait a moment for cast, then proceed to waiting + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > CAST_DELAY_MS) + { + _portalState = PortalState.WaitingForPortalOrTeleport; + _portalStateStart = DateTime.Now; + _prePortalLandblock = GetCurrentLandblock(); + } + } + + private void ProcessWaitingForPortalOrTeleport(NavPoint pt, VTankNavParser route) + { + // Detect teleport by checking if we moved far from pre-portal position + try + { + var pos = GetPos(); + if (pos != null && !double.IsNaN(_prePortalNS)) + { + double dNS = pos.NorthSouth - _prePortalNS; + double dEW = pos.EastWest - _prePortalEW; + double distFromStart = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + + if (distFromStart > 50.0) // moved > 50 yards = definitely teleported + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + } + } + catch { } + + // Also check landblock as fallback + int currentLandblock = GetCurrentLandblock(); + if (currentLandblock != _prePortalLandblock && currentLandblock != 0 && _prePortalLandblock != 0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + + // For PortalNPC: no short timeout — let UseItem walk complete. + // The global PORTAL_STATE_TIMEOUT_MS (15s) handles overall timeout. + // For Recall: use shorter timeout since teleport should be instant. + if (pt.Type == NavPointType.Recall) + { + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > PORTAL_WAIT_MS) + { + ResetPortalState(); + Advance(route); + } + } + } + + private void ProcessWaitingForPortalExit(VTankNavParser route) + { + // Distance-based teleport detection + try + { + var pos = GetPos(); + if (pos != null && !double.IsNaN(_prePortalNS)) + { + double dNS = pos.NorthSouth - _prePortalNS; + double dEW = pos.EastWest - _prePortalEW; + double distFromStart = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + if (distFromStart > 50.0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + } + } + catch { } + + // Landblock fallback + int currentLandblock = GetCurrentLandblock(); + if (currentLandblock != _prePortalLandblock && currentLandblock != 0 && _prePortalLandblock != 0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + } + } + + private void ResetPortalState() + { + _portalState = PortalState.None; + _portalStateStart = DateTime.MinValue; + _preCastLandblock = 0; + _prePortalLandblock = 0; + _prePortalNS = double.NaN; + _prePortalEW = double.NaN; + + // Return to peace mode after portal/recall + try + { + _core.Actions.SetCombatMode(CombatState.Peace); + } + catch { } + } + + private int GetCurrentLandblock() + { + try + { + var pos = GetPos(); + if (pos != null) + { + // Landblock is the high word of the location + // AC coordinates encode landblock in a specific way + // For simplicity, we'll use a combination of NS/EW rounded to detect changes + int nsBlock = (int)(pos.NorthSouth / 0.8); + int ewBlock = (int)(pos.EastWest / 0.8); + return (nsBlock << 16) | (ewBlock & 0xFFFF); + } + } + catch { } + return 0; + } + + private void FireSpecialAction(NavPoint pt) + { + // Legacy method - now mostly unused, kept for compatibility + try + { + if (pt.Type == NavPointType.Recall) + _core.Actions.CastSpell(pt.SpellId, _core.CharacterFilter.Id); + else if (pt.Type == NavPointType.PortalNPC) + { + foreach (WorldObject wo in _core.WorldFilter.GetLandscape()) + { + if (wo != null && wo.Name == pt.TargetName) { _core.Actions.UseItem(wo.Id, 0); break; } + } + } + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // STUCK WATCHDOG + // ══════════════════════════════════════════════════════════════════════════ + + private void UpdateWatchdog() + { + if (DateTime.Now < _watchdogNext) return; + _watchdogNext = DateTime.Now.AddMilliseconds(WATCHDOG_MS); + + var pos = GetPos(); + if (pos == null) return; + + double curNS = pos.NorthSouth, curEW = pos.EastWest; + + if (!double.IsNaN(_watchdogNS) && _isMovingForward) + { + bool dataStale = Math.Abs(curNS - _watchdogNS) < 0.000001 + && Math.Abs(curEW - _watchdogEW) < 0.000001 + && !IsGameFocused(); + + if (!dataStale) + { + double dN = curNS - _watchdogNS, dE = curEW - _watchdogEW; + double moved = Math.Sqrt(dN * dN + dE * dE) * 240.0; + if (moved < STUCK_YD) { _stuckCount++; BeginRecovery(); } + else _stuckCount = 0; + } + } + _watchdogNS = curNS; _watchdogEW = curEW; + } + + private void BeginRecovery() + { + _inRecovery = true; + _recoveryUntil = DateTime.Now.AddMilliseconds(RECOVERY_MS); + StopMovement(); + + // Jump to try to unstick + try + { + if (MovementActionHelper.IsInitialized) + { + // Tier 1: direct jump call — no keyboard/motion interpreter dependency + MovementActionHelper.JumpNonAutonomous(0.5f); + } + else + { + // Legacy: local motion command for jump + SetClientMotion(0x2500003b, true); + SetClientMotion(0x2500003b, false); + } + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // PUBLIC LIFECYCLE + // ══════════════════════════════════════════════════════════════════════════ + + public void Stop() + { + _inPause = false; _actionFired = false; _inRecovery = false; + _linearDir = 1; _stopRequestedAt = DateTime.MaxValue; + ResetPortalState(); + CancelTier2(); + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + _isMovingForward = false; + _isTurning = false; + _hasStopped = true; + _turnsStopped = true; + } + + public void ResetRouteState() + { + Stop(); + _stuckCount = 0; + _prevDist = double.MaxValue; + _watchdogNS = double.NaN; _watchdogEW = double.NaN; + _hasGoodHeading = false; + } + + public int FindNearestWaypoint(VTankNavParser route) + { + if (route == null || route.Points == null || route.Points.Count == 0) + return 0; + + try + { + var pos = GetPos(); + if (pos == null) + return 0; + + double myNS = pos.NorthSouth; + double myEW = pos.EastWest; + + int nearestIdx = 0; + double nearestDist = double.MaxValue; + + for (int i = 0; i < route.Points.Count; i++) + { + var pt = route.Points[i]; + // Only consider regular waypoints, not special actions + if (pt.Type == NavPointType.Point) + { + double dNS = pt.NS - myNS; + double dEW = pt.EW - myEW; + double dist = Math.Sqrt(dNS * dNS + dEW * dEW); + + if (dist < nearestDist) + { + nearestDist = dist; + nearestIdx = i; + } + } + } + + return nearestIdx; + } + catch + { + return 0; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // UTILITIES + // ══════════════════════════════════════════════════════════════════════════ + + private bool IndexValid(int i, VTankNavParser r) => r?.Points != null && i >= 0 && i < r.Points.Count; + + private CoordsObject GetPos() + { + try { return _core.WorldFilter[_core.CharacterFilter.Id].Coordinates(); } + catch { return null; } + } + + private static double NormalizeAngle(double a) + { + while (a > 180.0) a -= 360.0; + while (a < -180.0) a += 360.0; + return a; + } + + private static double Lerp(double a, double b, double t) => a + (b - a) * t; + } +} diff --git a/Plugins/RynthAi/Logic/RynthJumper.cs b/Plugins/RynthAi/Logic/RynthJumper.cs new file mode 100644 index 0000000..da30d5e --- /dev/null +++ b/Plugins/RynthAi/Logic/RynthJumper.cs @@ -0,0 +1,256 @@ +using System; +using System.Runtime.InteropServices; +using Decal.Adapter; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Native RynthAi jump system — no UB dependency. + /// Tier 1: Uses CM_Movement::Event_Jump_NonAutonomous for direct jump + /// commands when MovementActionHelper is initialized (no keyboard input). + /// Fallback: PostMessage keyboard simulation for legacy mode. + /// Direction keys (W/X/Z/C) still use PostMessage in Tier 1 since + /// they control local physics direction. Tier 2 will replace these. + /// Flow: Face heading → hold direction keys → jump → release → resume macro + /// </summary> + public class RynthJumper + { + [DllImport("user32.dll", CharSet = CharSet.Auto)] + private static extern bool PostMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam); + + private const uint WM_KEYDOWN = 0x0100; + private const uint WM_KEYUP = 0x0101; + + // AC key codes + private const uint VK_SPACE = 0x20; // Jump + private const uint VK_SHIFT = 0x10; // Run modifier + private const uint VK_W = 0x57; // Forward + private const uint VK_X = 0x58; // Backward + private const uint VK_Z = 0x5A; // Slide left + private const uint VK_C = 0x43; // Slide right + + private enum JumpState { Idle, Turning, HoldingKeys, Done } + private JumpState _state = JumpState.Idle; + + private PluginHost _host; + private UISettings _settings; + + // Jump parameters + private double _targetHeading; + private int _holdTimeMs; + private bool _addShift, _addW, _addX, _addZ, _addC; + private DateTime _stateStart; + private int _turnRetries; + private const int MAX_TURN_RETRIES = 50; // 50 * 100ms = 5 seconds + + public bool IsJumping => _state != JumpState.Idle; + + public RynthJumper(PluginHost host, UISettings settings) + { + _host = host; + _settings = settings; + } + + /// <summary> + /// Start a jump. Mirrors /ub jump[swzxc] [heading] [holdtime] + /// </summary> + /// <param name="heading">Heading to face (0-359), or -1 for current heading</param> + /// <param name="holdTimeMs">How long to hold jump key (0-1000ms)</param> + /// <param name="shift">S modifier — run</param> + /// <param name="forward">W — forward</param> + /// <param name="backward">X — backward</param> + /// <param name="slideLeft">Z — slide left</param> + /// <param name="slideRight">C — slide right</param> + public void StartJump(double heading, int holdTimeMs, bool shift, bool forward, bool backward, bool slideLeft, bool slideRight) + { + if (_state != JumpState.Idle) return; + + _holdTimeMs = Math.Max(0, Math.Min(1000, holdTimeMs)); + _addShift = shift; + _addW = forward; + _addX = backward; + _addZ = slideLeft; + _addC = slideRight; + _turnRetries = 0; + + // Pause macro during jump + _settings.IsMacroRunning = false; + + if (heading >= 0) + { + _targetHeading = heading; + _state = JumpState.Turning; + CoreManager.Current.Actions.Heading = (float)_targetHeading; + } + else + { + _targetHeading = CoreManager.Current.Actions.Heading; + // No turn needed — go straight to keys + _state = JumpState.HoldingKeys; + PressKeys(); + } + _stateStart = DateTime.Now; + } + + /// <summary> + /// Tap jump — no heading change, no hold time. + /// Uses CM_Movement::Event_Jump_NonAutonomous for a minimal jump + /// when available, falls back to PostMessage keyboard simulation. + /// </summary> + public void TapJump() + { + if (_state != JumpState.Idle) return; + + // Tier 1: direct acclient.exe call — no keyboard input needed + if (MovementActionHelper.IsInitialized) + { + MovementActionHelper.JumpNonAutonomous(0.01f); // minimal extent = tap + return; + } + + // Legacy fallback: keyboard simulation + IntPtr hwnd = _host?.Decal?.Hwnd ?? IntPtr.Zero; + if (hwnd == IntPtr.Zero) return; + + PostMessage(hwnd, WM_KEYDOWN, VK_SPACE, 0x00390001); + PostMessage(hwnd, WM_KEYUP, VK_SPACE, 0xC0390001); + } + + /// <summary> + /// Called every frame by PluginCore. Drives the jump state machine. + /// </summary> + public void Think() + { + if (_state == JumpState.Idle) return; + + switch (_state) + { + case JumpState.Turning: + // Check if heading is close enough + double currentHeading = CoreManager.Current.Actions.Heading; + if (Math.Abs(_targetHeading - currentHeading) < 2.0 || + Math.Abs(_targetHeading - currentHeading) > 358.0) // Handle 0/360 wrap + { + // Heading matched — start the jump + _state = JumpState.HoldingKeys; + _stateStart = DateTime.Now; + PressKeys(); + } + else + { + _turnRetries++; + // Keep setting heading every 100ms + if (_turnRetries % 5 == 0) + CoreManager.Current.Actions.Heading = (float)_targetHeading; + + // Timeout after 5 seconds + if (_turnRetries > MAX_TURN_RETRIES) + { + try { _host?.Actions?.AddChatText("[RynthAi] Jump: turn timed out", 2); } catch { } + Finish(); + } + } + break; + + case JumpState.HoldingKeys: + // Tier 1: jump already fired with correct extent in PressKeys(). + // Direction keys only need ~100ms for physics to register direction. + // Legacy: space bar held to build power bar over holdTimeMs. + int effectiveHold = (MovementActionHelper.IsInitialized && _holdTimeMs > 100) + ? 100 // Tier 1: brief hold for direction registration + : _holdTimeMs; + + if ((DateTime.Now - _stateStart).TotalMilliseconds >= effectiveHold) + { + ReleaseKeys(); + _state = JumpState.Done; + _stateStart = DateTime.Now; + } + break; + + case JumpState.Done: + // Brief delay after releasing keys before resuming macro + if ((DateTime.Now - _stateStart).TotalMilliseconds >= 200) + { + Finish(); + } + break; + } + } + + private void PressKeys() + { + IntPtr hwnd = _host?.Decal?.Hwnd ?? IntPtr.Zero; + + // Tier 1: Use direct jump call for the jump itself. + // Direction keys (W/X/Z/C) still need PostMessage since they control + // local movement direction during the jump, which DoMovementCommand + // doesn't handle (it's server-side only). Tier 2 will replace these + // with CPhysicsObj movement calls. + if (MovementActionHelper.IsInitialized) + { + // Press direction modifiers via PostMessage (needed for local physics) + if (hwnd != IntPtr.Zero) + { + if (_addShift) PostMessage(hwnd, WM_KEYDOWN, VK_SHIFT, 0x002A0001); + if (_addW) PostMessage(hwnd, WM_KEYDOWN, VK_W, 0x00110001); + if (_addX) PostMessage(hwnd, WM_KEYDOWN, VK_X, 0x002D0001); + if (_addZ) PostMessage(hwnd, WM_KEYDOWN, VK_Z, 0x002C0001); + if (_addC) PostMessage(hwnd, WM_KEYDOWN, VK_C, 0x002E0001); + } + + // Map holdTimeMs to jump extent (0.0–1.0) + // AC power bar fills over ~1000ms, so holdTime/1000 approximates extent + float extent = Math.Max(0.01f, Math.Min(1.0f, _holdTimeMs / 1000.0f)); + MovementActionHelper.JumpNonAutonomous(extent); + return; + } + + // Legacy fallback: all keyboard simulation + if (hwnd == IntPtr.Zero) return; + PostMessage(hwnd, WM_KEYDOWN, VK_SPACE, 0x00390001); + if (_addShift) PostMessage(hwnd, WM_KEYDOWN, VK_SHIFT, 0x002A0001); + if (_addW) PostMessage(hwnd, WM_KEYDOWN, VK_W, 0x00110001); + if (_addX) PostMessage(hwnd, WM_KEYDOWN, VK_X, 0x002D0001); + if (_addZ) PostMessage(hwnd, WM_KEYDOWN, VK_Z, 0x002C0001); + if (_addC) PostMessage(hwnd, WM_KEYDOWN, VK_C, 0x002E0001); + } + + private void ReleaseKeys() + { + IntPtr hwnd = _host?.Decal?.Hwnd ?? IntPtr.Zero; + if (hwnd == IntPtr.Zero) return; + + // Legacy mode: release space bar (Tier 1 never pressed it) + if (!MovementActionHelper.IsInitialized) + PostMessage(hwnd, WM_KEYUP, VK_SPACE, 0xC0390001); + + // Release direction keys (used by both Tier 1 and Legacy) + if (_addShift) PostMessage(hwnd, WM_KEYUP, VK_SHIFT, 0xC02A0001); + if (_addW) PostMessage(hwnd, WM_KEYUP, VK_W, 0xC0110001); + if (_addX) PostMessage(hwnd, WM_KEYUP, VK_X, 0xC02D0001); + if (_addZ) PostMessage(hwnd, WM_KEYUP, VK_Z, 0xC02C0001); + if (_addC) PostMessage(hwnd, WM_KEYUP, VK_C, 0xC02E0001); + } + + private void Finish() + { + _state = JumpState.Idle; + _addShift = _addW = _addX = _addZ = _addC = false; + _turnRetries = 0; + // Resume macro + _settings.IsMacroRunning = true; + try { _host?.Actions?.AddChatText("[RynthAi] Jump complete", 5); } catch { } + } + + public void Cancel() + { + if (_state != JumpState.Idle) + { + ReleaseKeys(); + Finish(); + } + } + } +} diff --git a/Plugins/RynthAi/Loot/LootManager.cs b/Plugins/RynthAi/Loot/LootManager.cs new file mode 100644 index 0000000..b4171be --- /dev/null +++ b/Plugins/RynthAi/Loot/LootManager.cs @@ -0,0 +1,1150 @@ +using Decal.Adapter.Wrappers; +using Decal.Adapter; +using System.Collections.Generic; +using System.Linq; +using System; +using System.IO; + +namespace NexSuite.Plugins.RynthAi +{ + public class LootManager : IDisposable + { + private CoreManager _core; + private UISettings _settings; + private PluginHost _host; + private FellowshipTracker _fellowshipTracker; + + private VTClassic.LootCore _vtLootCore; + private VTankLootProfile _parsedLootProfile; + private string _loadedProfilePath = ""; + private DateTime _loadedProfileWriteTimeUtc = DateTime.MinValue; + private int _lastSelectedId = 0; + + // --- Auto Cram & Stack --- + private DateTime _nextInventoryActionTime = DateTime.MinValue; + private HashSet<string> _failedStackPairs = new HashSet<string>(); + private HashSet<int> _cramBlacklist = new HashSet<int>(); + private DateTime _lastBlacklistClear = DateTime.MinValue; + private const double BLACKLIST_CLEAR_INTERVAL_MS = 30000.0; // Clear every 30 seconds + private bool _inventoryDirty = true; // Start dirty so first scan happens + private int _lastInventoryCount = 0; // Track inventory count changes + + // --- Looting State Machine --- + private enum LootState { Idle, Approaching, WaitingForContents, Identifying, Looting, Closing } + private LootState _lootState = LootState.Idle; + private int _targetCorpseId = 0; + private DateTime _lootTimer = DateTime.MinValue; + private HashSet<int> _lootedCorpses = new HashSet<int>(); + + // --- Sequential Scanner Variables --- + private int _currentItemIdx = 0; + private int _itemsLootedFromCorpse = 0; + private List<int> _corpseItemsToCheck = new List<int>(); + private int _lootRetryCount = 0; + private int _assessingItemId = 0; + private DateTime _assessItemStart = DateTime.MinValue; + private DateTime _lastAssessRequest = DateTime.MinValue; + private DateTime _stateEnteredAt = DateTime.MinValue; + private DateTime _lastOpenAttemptAt = DateTime.MinValue; + private DateTime _openedContainerAt = DateTime.MinValue; + private DateTime _lastContentsCheckAt = DateTime.MinValue; + private DateTime _lastLootPickupTime = DateTime.MinValue; // Inter-item delay timer + // Loot timing now driven by _settings — see UISettings for defaults + private readonly string _debugLogPath = @"C:\Projects\NexSuite\Plugins\RynthAi\Loot\loot-debug.log"; + + // --- VTank-style Deferred Salvage System --- + // Items are picked up during looting, then salvaged during idle phase + // --- Single-Item Salvage System --- + // Items are picked up during looting, then salvaged one at a time during idle phase + // First item has longer delays (panel opening), subsequent items are faster + private bool _isSalvagingCurrentItem = false; + private Queue<int> _salvageQueue = new Queue<int>(); + private DateTime _nextSalvageAction = DateTime.MinValue; + private enum SalvagePhase { Idle, OpeningPanel, AddingItem, Salvaging, WaitingForResult, CombiningSalvage } + private SalvagePhase _salvagePhase = SalvagePhase.Idle; + private int _currentSalvageItemId = 0; + private bool _salvagePanelOpened = false; // True after first item — faster delays + private DateTime _salvagePhaseStart = DateTime.MinValue; + + public LootManager(CoreManager core, UISettings settings, PluginHost host) + { + _core = core; + _settings = settings; + _host = host; + try + { + _vtLootCore = new VTClassic.LootCore(); + } + catch (Exception ex) + { + _host.Actions.AddChatText($"[RynthAi] VTClassic Load Error: {ex.Message}", 1); + } + } + + public void SetFellowshipTracker(FellowshipTracker tracker) + { + _fellowshipTracker = tracker; + } + + // Restored for PluginCore/CommandProcessor compatibility + public void ForceReload() + { + _loadedProfilePath = ""; + _loadedProfileWriteTimeUtc = DateTime.MinValue; + } + + // Restored for CommandProcessor compatibility + public void SaveProfile(string path) + { + // Placeholder: VTank profiles are typically managed within the VTank UI + } + + public void LoadProfile(string path) + { + _loadedProfilePath = path; + _loadedProfileWriteTimeUtc = DateTime.MinValue; + _parsedLootProfile = null; + + if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path)) + { + DebugLog($"LoadProfile skipped path='{path}' exists={System.IO.File.Exists(path)}"); + return; + } + + try + { + // DESTROY the old engine to clear the internal cache before reloading + if (_vtLootCore != null) + { + _vtLootCore.UnloadProfile(); + _vtLootCore = null; + } + + _vtLootCore = new VTClassic.LootCore(); + _vtLootCore.LoadProfile(path, false); + + _parsedLootProfile = VTankLootParser.Load(path); + _loadedProfileWriteTimeUtc = File.GetLastWriteTimeUtc(path); + + DebugLog($"LoadProfile ok path='{path}' parsedRules={(_parsedLootProfile?.Rules?.Count ?? 0)}"); + if (_parsedLootProfile?.Rules != null) + { + for (int i = 0; i < _parsedLootProfile.Rules.Count && i < 5; i++) + { + var r = _parsedLootProfile.Rules[i]; + if (r == null) continue; + DebugLog($"Rule[{i}] name='{r.Name}' action={r.Action} info='{r.RawInfoLine}'"); + } + } + _host.Actions.AddChatText($"[RynthAi] Loaded Loot Profile: {System.IO.Path.GetFileName(path)}", 1); + } + catch (Exception ex) + { + DebugLog($"LoadProfile error path='{path}' msg='{ex.Message}'"); + _host.Actions.AddChatText($"[RynthAi] Error loading {path}", 1); + } + } + + /// <summary> + /// Returns true if salvage has items queued or is actively processing. + /// </summary> + public bool IsSalvageActive => _salvageQueue.Count > 0 || _salvagePhase != SalvagePhase.Idle; + + /// <summary> + /// Returns true if salvage should block combat/nav. + /// True when: queue has items ready to salvage (not looting) OR panel is actively open. + /// </summary> + public bool IsSalvageProcessing + { + get + { + // Panel is actively open — always block + if (_salvagePhase != SalvagePhase.Idle) return true; + // Queue has items and we're not looting a corpse — about to start salvaging + if (_salvageQueue.Count > 0 && _lootState == LootState.Idle) return true; + return false; + } + } + + /// <summary> + /// Returns true if actively looting a corpse (don't block looting with salvage priority). + /// </summary> + public bool IsLootingCorpse => _lootState != LootState.Idle; + + /// <summary> + /// Process salvage queue — called every frame, highest priority. + /// Runs independently of loot state (items are already in inventory). + /// </summary> + public void ProcessSalvage() + { + if (!_settings.IsMacroRunning) return; + if (_salvageQueue.Count == 0 && _salvagePhase == SalvagePhase.Idle) return; + if (_lootState != LootState.Idle) return; // Don't salvage while looting a corpse + if (_core.Actions.BusyState != 0) return; + ProcessIdleSalvage(); + } + + /// <summary> + /// Process autostack — only when server is idle (not casting spells). + /// </summary> + public bool ProcessStack() + { + if (!_settings.IsMacroRunning) return false; + if (_core.Actions.BusyState != 0) return false; // Don't move items while casting + if (DateTime.Now < _nextInventoryActionTime) return false; + if (!_inventoryDirty) return false; + if (ProcessAutoStack()) { _nextInventoryActionTime = DateTime.Now.AddMilliseconds(500); return true; } + return false; + } + + /// <summary> + /// Process autocram — only when server is idle (not casting spells). + /// </summary> + public bool ProcessCram() + { + if (!_settings.IsMacroRunning) return false; + if (_core.Actions.BusyState != 0) return false; // Don't move items while casting + if (DateTime.Now < _nextInventoryActionTime) return false; + if (!_inventoryDirty) return false; + if (ProcessAutoCram()) { _nextInventoryActionTime = DateTime.Now.AddMilliseconds(500); return true; } + _inventoryDirty = false; + _nextInventoryActionTime = DateTime.Now.AddMilliseconds(2000); + return false; + } + + public void OnHeartbeat() + { + if (_settings.CurrentLootPath != _loadedProfilePath) + { + LoadProfile(_settings.CurrentLootPath); + } + else if (!string.IsNullOrEmpty(_settings.CurrentLootPath) && File.Exists(_settings.CurrentLootPath)) + { + var writeTime = File.GetLastWriteTimeUtc(_settings.CurrentLootPath); + if (writeTime > _loadedProfileWriteTimeUtc) + { + DebugLog($"Profile changed on disk, reloading path='{_settings.CurrentLootPath}'"); + LoadProfile(_settings.CurrentLootPath); + } + } + TestSelectionLogic(); + + if (!_settings.IsMacroRunning) return; + + // Periodically clear autostack/autocram blacklists + if ((DateTime.Now - _lastBlacklistClear).TotalMilliseconds >= BLACKLIST_CLEAR_INTERVAL_MS) + { + _failedStackPairs.Clear(); + _cramBlacklist.Clear(); + _lastBlacklistClear = DateTime.Now; + } + + // Dirty detection for inventory changes + int currentInvCount = 0; + try { currentInvCount = _core.WorldFilter.GetInventory().Count; } catch { } + if (currentInvCount != _lastInventoryCount) + { + _inventoryDirty = true; + _lastInventoryCount = currentInvCount; + } + + if (!_settings.EnableLooting) return; + + // Don't loot if a higher-priority system has claimed the state + if (_settings.CurrentState != "Idle" && _settings.CurrentState != "Looting") + { + if (_lootState != LootState.Idle) ResetLootingState(); + return; + } + + ProcessLootingState(); + } + + private void ProcessLootingState() + { + switch (_lootState) + { + case LootState.Idle: + // Don't start next corpse while salvage is running + if (_salvagePhase != SalvagePhase.Idle) return; + + int nearest = FindNearestCorpse(); + if (nearest != 0) + { + DebugLog($"Idle->Approaching corpse={nearest}"); + _targetCorpseId = nearest; + _currentItemIdx = 0; + _itemsLootedFromCorpse = 0; + _corpseItemsToCheck.Clear(); + _settings.CurrentState = "Looting"; + + // Open the corpse ONCE + _host.Actions.SelectItem(_targetCorpseId); + _host.Actions.UseItem(_targetCorpseId, 0); + + _lootState = LootState.Approaching; + _stateEnteredAt = DateTime.Now; + _lastOpenAttemptAt = DateTime.Now; + _lootTimer = DateTime.Now; + } + break; + + case LootState.Approaching: + // Check if corpse opened + if (_core.Actions.OpenedContainer == _targetCorpseId) + { + _lootState = LootState.WaitingForContents; + _stateEnteredAt = DateTime.Now; + _openedContainerAt = DateTime.Now; + _lootTimer = DateTime.Now; + DebugLog($"Approaching->WaitingForContents corpse={_targetCorpseId} (opened)"); + } + else + { + // NOT open yet — only retry UseItem after the configured delay + // UseItem is a TOGGLE — calling it again would close it + if ((DateTime.Now - _lastOpenAttemptAt).TotalMilliseconds >= _settings.LootOpenRetryMs) + { + // 8 seconds passed, corpse still not open — retry ONCE + _host.Actions.SelectItem(_targetCorpseId); + _host.Actions.UseItem(_targetCorpseId, 0); + _lastOpenAttemptAt = DateTime.Now; + DebugLog($"Approaching: retry open after 8s corpse={_targetCorpseId}"); + } + + // If close enough but not open, just wait — the server is processing + // Timeout after 10 seconds total + if ((DateTime.Now - _stateEnteredAt).TotalSeconds > 10) + { + DebugLog($"Approaching timeout corpse={_targetCorpseId}"); + _lootedCorpses.Add(_targetCorpseId); + ResetLootingState(); + } + } + break; + + case LootState.WaitingForContents: + // Corpse is confirmed open — DO NOT call UseItem again (it would close it!) + if (_core.Actions.OpenedContainer == _targetCorpseId) + { + // Give server a moment to populate contents + if ((DateTime.Now - _openedContainerAt).TotalMilliseconds < _settings.LootContentSettleMs) return; + + var items = _core.WorldFilter.GetByContainer(_targetCorpseId); + if (items != null && items.Count > 0) + { + _corpseItemsToCheck = items.Select(i => i.Id).ToList(); + DebugLog($"Corpse contents loaded id={_targetCorpseId}, items={_corpseItemsToCheck.Count}"); + _lootState = LootState.Identifying; + _lootTimer = DateTime.Now; + } + else + { + // Empty — wait briefly for items to populate, then close + if ((DateTime.Now - _openedContainerAt).TotalMilliseconds > _settings.LootEmptyCorpseMs) + { + DebugLog($"Corpse confirmed empty id={_targetCorpseId}"); + _lootState = LootState.Closing; + } + } + } + else + { + // Container closed unexpectedly (server closed it, or something toggled it) + // Wait briefly then retry open ONCE + if ((DateTime.Now - _stateEnteredAt).TotalSeconds > 4) + { + DebugLog($"WaitingForContents: container closed, giving up on corpse={_targetCorpseId}"); + _lootedCorpses.Add(_targetCorpseId); + ResetLootingState(); + } + else if ((DateTime.Now - _lastOpenAttemptAt).TotalMilliseconds >= _settings.LootOpenRetryMs) + { + // Retry open once after 3s + _host.Actions.SelectItem(_targetCorpseId); + _host.Actions.UseItem(_targetCorpseId, 0); + _lastOpenAttemptAt = DateTime.Now; + DebugLog($"WaitingForContents: re-opening corpse={_targetCorpseId}"); + } + } + break; + + case LootState.Identifying: + // Inter-item delay + if (_lastLootPickupTime != DateTime.MinValue && + (DateTime.Now - _lastLootPickupTime).TotalMilliseconds < _settings.LootInterItemDelayMs) + return; + + if (_currentItemIdx >= _corpseItemsToCheck.Count) + { + // Before closing: verify no lootable items are still on the corpse + var remaining = _core.WorldFilter.GetByContainer(_targetCorpseId); + if (remaining != null) + { + foreach (var rem in remaining) + { + string skipReason; + bool isSalv; + if (ShouldLootItem(rem.Id, rem, out skipReason, out isSalv)) + { + DebugLog($"Pre-close check: {rem.Name} still on corpse, looting"); + _host.Actions.MoveItem(rem.Id, _core.CharacterFilter.Id, 0, false); + _lootTimer = DateTime.Now; + _lootRetryCount = 0; + _lootState = LootState.Looting; + return; + } + } + } + _lootState = LootState.Closing; + if (_itemsLootedFromCorpse == 0) + { + try { _host.Actions.AddChatText($"[RynthAi] No items on corpse matched loot rules ({_corpseItemsToCheck.Count} scanned)", 5); } catch { } + } + return; + } + + int id = _corpseItemsToCheck[_currentItemIdx]; + var wo = _core.WorldFilter[id]; + if (wo == null || wo.Container != _targetCorpseId) + { + _currentItemIdx++; + _lootTimer = DateTime.Now; + return; + } + + // Assessment + if (_assessingItemId != id) + { + _assessingItemId = id; + _assessItemStart = DateTime.Now; + _lastAssessRequest = DateTime.MinValue; + } + + double assessMs = (DateTime.Now - _assessItemStart).TotalMilliseconds; + bool needsId = uTank2.PluginCore.PC.FLootPluginQueryNeedsID(id); + + if (needsId && (DateTime.Now - _lastAssessRequest).TotalMilliseconds >= 250) + { + _host.Actions.RequestId(id); + _lastAssessRequest = DateTime.Now; + } + + if (needsId && assessMs < _settings.LootAssessWindowMs) return; + + string decisionReason; + if (ShouldLootItem(id, wo, out decisionReason, out _isSalvagingCurrentItem)) + { + string actionStr = _isSalvagingCurrentItem ? "SALVAGE" : "KEEP"; + DebugLog($"Assess {actionStr} id={id} name='{wo.Name}' via={decisionReason}"); + _host.Actions.AddChatText($"[RynthAi] Scooping {wo.Name} (via {decisionReason})", 1); + _host.Actions.MoveItem(id, _core.CharacterFilter.Id, 0, false); + _lootState = LootState.Looting; _lootTimer = DateTime.Now; _lootRetryCount = 0; + return; + } + DebugLog($"Assess SKIP id={id} name='{wo.Name}' needsId={needsId} elapsedMs={assessMs:0} via={decisionReason}"); + _currentItemIdx++; + _assessingItemId = 0; + _lootTimer = DateTime.Now; + break; + + case LootState.Looting: + int vId = _corpseItemsToCheck[_currentItemIdx]; + var itemToVerify = _core.WorldFilter[vId]; + if (itemToVerify == null || itemToVerify.Container != _targetCorpseId) + { + DebugLog($"Looted/moved id={vId}"); + if (_isSalvagingCurrentItem) + { + _salvageQueue.Enqueue(vId); + DebugLog($"Queued for salvage id={vId} (queue={_salvageQueue.Count})"); + } + _isSalvagingCurrentItem = false; + _inventoryDirty = true; + _itemsLootedFromCorpse++; + _lastLootPickupTime = DateTime.Now; + _currentItemIdx++; _lootState = LootState.Identifying; + } + else if ((DateTime.Now - _lootTimer).TotalMilliseconds > _settings.LootRetryTimeoutMs) + { + _lootRetryCount++; + if (_lootRetryCount > 5) + { + DebugLog($"Loot retries exhausted id={vId}"); + _currentItemIdx++; _lootState = LootState.Identifying; + } + else + { + DebugLog($"Loot retry id={vId} attempt={_lootRetryCount}"); + _host.Actions.MoveItem(vId, _core.CharacterFilter.Id, 0, false); + _lootTimer = DateTime.Now; + } + } + break; + + case LootState.Closing: + // Brief settle before closing + if (_openedContainerAt != DateTime.MinValue && (DateTime.Now - _openedContainerAt).TotalMilliseconds < _settings.LootClosingDelayMs) + return; + + DebugLog($"Closing corpse id={_targetCorpseId}"); + _lootedCorpses.Add(_targetCorpseId); // Mark as done + // Close the corpse by using it (toggle) + _host.Actions.UseItem(_targetCorpseId, 0); + _host.Actions.SelectItem(0); + ResetLootingState(); + break; + } + } + + private int FindUST() + { + foreach (var item in _core.WorldFilter.GetInventory()) + { + if (item.Name == null) continue; + + // NEVER match actual salvage bags — they contain "Salvage" but are ObjectClass.Salvage + if (item.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Salvage) continue; + + // Match by exact name "Ust" or names containing "Salvaging Tool" + // The AC item is literally named "Ust" — exact match is safest + if (item.Name.Equals("Ust", StringComparison.OrdinalIgnoreCase)) + return item.Id; + + // Fallback: "Ust" as part of a longer name (e.g., custom servers) + // But exclude items that contain common false-positive substrings + if (item.Name.Equals("Salvaging Tool", StringComparison.OrdinalIgnoreCase) || + item.Name.Equals("Ust of Mhoire", StringComparison.OrdinalIgnoreCase)) + return item.Id; + } + return 0; + } + // ══════════════════════════════════════════════════════════════════════════ + // SINGLE-ITEM SALVAGE PROCESSOR (No UB dependency) + // Opens panel → adds ONE item → Salvage → repeat for next + // First item: full delays. Subsequent items: faster. + // ══════════════════════════════════════════════════════════════════════════ + + private void ProcessIdleSalvage() + { + if (_salvageQueue.Count == 0 && _salvagePhase == SalvagePhase.Idle) return; + if (_core.Actions.BusyState != 0) return; + + // SAFETY: Global timeout — re-queue item if stuck + if (_salvagePhase != SalvagePhase.Idle && (DateTime.Now - _salvagePhaseStart).TotalMilliseconds > 10000) + { + DebugLog($"IdleSalvage: TIMEOUT in phase {_salvagePhase}, re-queuing item {_currentSalvageItemId}"); + if (_currentSalvageItemId != 0 && IsItemInPlayerInventory(_currentSalvageItemId)) + { + var wo = _core.WorldFilter[_currentSalvageItemId]; + if (wo != null && wo.ObjectClass != Decal.Adapter.Wrappers.ObjectClass.Salvage) + _salvageQueue.Enqueue(_currentSalvageItemId); + } + _salvagePhase = SalvagePhase.Idle; + _currentSalvageItemId = 0; + return; + } + + // Delays: first item slower (panel opening), subsequent near-instant + double openDelay = _salvagePanelOpened ? _settings.SalvageOpenDelayFastMs : _settings.SalvageOpenDelayFirstMs; + double addDelay = _salvagePanelOpened ? _settings.SalvageAddDelayFastMs : _settings.SalvageAddDelayFirstMs; + double salvageDelay = _settings.SalvageSalvageDelayMs; + double resultDelay = _salvagePanelOpened ? _settings.SalvageResultDelayFastMs : _settings.SalvageResultDelayFirstMs; + + switch (_salvagePhase) + { + case SalvagePhase.Idle: + // Dequeue next valid item + while (_salvageQueue.Count > 0) + { + _currentSalvageItemId = _salvageQueue.Dequeue(); + if (!IsItemInPlayerInventory(_currentSalvageItemId)) { _currentSalvageItemId = 0; continue; } + var wo = _core.WorldFilter[_currentSalvageItemId]; + if (wo == null || wo.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Salvage) + { _currentSalvageItemId = 0; continue; } + + _salvagePhase = SalvagePhase.OpeningPanel; + _salvagePhaseStart = DateTime.Now; + DebugLog($"IdleSalvage: Dequeued id={_currentSalvageItemId} name='{wo.Name}'"); + return; + } + // Queue empty — reset panel flag for next batch + _salvagePanelOpened = false; + break; + + case SalvagePhase.OpeningPanel: + if ((DateTime.Now - _salvagePhaseStart).TotalMilliseconds < openDelay) return; + int ustId = FindUST(); + if (ustId == 0) + { + _host.Actions.AddChatText("[RynthAi] No Ust found — salvage cleared", 2); + _salvageQueue.Clear(); + _salvagePhase = SalvagePhase.Idle; + _currentSalvageItemId = 0; + return; + } + if (!IsItemInPlayerInventory(_currentSalvageItemId)) + { _salvagePhase = SalvagePhase.Idle; _currentSalvageItemId = 0; return; } + + try { _host.Actions.UseItem(ustId, 0); } + catch + { + // Re-queue the item on failure + _salvageQueue.Enqueue(_currentSalvageItemId); + _salvagePhase = SalvagePhase.Idle; _currentSalvageItemId = 0; return; + } + + _salvagePhase = SalvagePhase.AddingItem; + _salvagePhaseStart = DateTime.Now; + break; + + case SalvagePhase.AddingItem: + if ((DateTime.Now - _salvagePhaseStart).TotalMilliseconds < addDelay) return; + + if (!IsItemInPlayerInventory(_currentSalvageItemId)) + { _salvagePhase = SalvagePhase.Idle; _currentSalvageItemId = 0; return; } + + var salvItem = _core.WorldFilter[_currentSalvageItemId]; + _host.Actions.AddChatText($"[RynthAi] Salvaging {salvItem?.Name}", 1); + + try { _host.Actions.SalvagePanelAdd(_currentSalvageItemId); } + catch + { + _salvageQueue.Enqueue(_currentSalvageItemId); // Re-queue on failure + _salvagePhase = SalvagePhase.Idle; _currentSalvageItemId = 0; return; + } + + _salvagePhase = SalvagePhase.Salvaging; + _salvagePhaseStart = DateTime.Now; + break; + + case SalvagePhase.Salvaging: + if ((DateTime.Now - _salvagePhaseStart).TotalMilliseconds < salvageDelay) return; + try { _host.Actions.SalvagePanelSalvage(); } catch { } + _salvagePhase = SalvagePhase.WaitingForResult; + _salvagePhaseStart = DateTime.Now; + break; + + case SalvagePhase.WaitingForResult: + if ((DateTime.Now - _salvagePhaseStart).TotalMilliseconds < resultDelay) return; + if (_core.Actions.BusyState != 0) return; + + // VERIFY the item was actually salvaged + if (IsItemInPlayerInventory(_currentSalvageItemId)) + { + // Item still in inventory — salvage FAILED, re-queue it + var failItem = _core.WorldFilter[_currentSalvageItemId]; + if (failItem != null && failItem.ObjectClass != Decal.Adapter.Wrappers.ObjectClass.Salvage) + { + _salvageQueue.Enqueue(_currentSalvageItemId); + DebugLog($"IdleSalvage: Item {_currentSalvageItemId} still in inventory — re-queued ({failItem.Name})"); + } + } + else + { + DebugLog($"IdleSalvage: Item {_currentSalvageItemId} salvaged OK"); + } + + _salvagePanelOpened = true; + _currentSalvageItemId = 0; + _inventoryDirty = true; + + if (_settings.EnableCombineSalvage) + { _salvagePhase = SalvagePhase.CombiningSalvage; _salvagePhaseStart = DateTime.Now; } + else + { _salvagePhase = SalvagePhase.Idle; } + break; + + case SalvagePhase.CombiningSalvage: + if ((DateTime.Now - _salvagePhaseStart).TotalMilliseconds < 150) return; + CombineSalvageBags(); + _salvagePhase = SalvagePhase.Idle; // Next item picks up immediately + break; + } + } + + /// <summary> + /// Checks if an item is anywhere in the player's inventory (main pack or sub-packs). + /// AC inventory structure: Player → main items + sub-packs → items inside sub-packs. + /// </summary> + private bool IsItemInPlayerInventory(int itemId) + { + var item = _core.WorldFilter[itemId]; + if (item == null) return false; + + int playerId = _core.CharacterFilter.Id; + + // Direct child of player (main pack) + if (item.Container == playerId) return true; + + // Child of a sub-pack (pack.Container == playerId) + var container = _core.WorldFilter[item.Container]; + if (container != null && container.Container == playerId) return true; + + return false; + } + + /// <summary> + /// Finds salvage bags of the same material type and combines them. + /// AC allows combining bags via MoveItem (stack merge). + /// </summary> + private void CombineSalvageBags() + { + try + { + var salvageBags = _core.WorldFilter.GetInventory() + .Where(i => i.Name != null && i.Name.Contains("Salvage") && !i.Name.Contains("Tool")) + .ToList(); + + // Group by material name and combine bags of the same type + var groups = salvageBags.GroupBy(b => b.Name).Where(g => g.Count() > 1); + foreach (var group in groups) + { + var bags = group.OrderByDescending(b => b.Values(LongValueKey.StackCount, 1)).ToList(); + if (bags.Count >= 2) + { + DebugLog($"CombineSalvage: Merging {bags[1].Name} ({bags[1].Id}) into ({bags[0].Id})"); + _host.Actions.MoveItem(bags[1].Id, bags[0].Id, 0, false); + return; // One combine per tick + } + } + } + catch (Exception ex) + { + DebugLog($"CombineSalvage error: {ex.Message}"); + } + } + + private void ResetLootingState() + { + _lootState = LootState.Idle; + _settings.CurrentState = "Idle"; + _targetCorpseId = 0; + _currentItemIdx = 0; + _itemsLootedFromCorpse = 0; + _corpseItemsToCheck.Clear(); + _lootRetryCount = 0; + _assessingItemId = 0; + _assessItemStart = DateTime.MinValue; + _lastAssessRequest = DateTime.MinValue; + _stateEnteredAt = DateTime.MinValue; + _lastOpenAttemptAt = DateTime.MinValue; + _openedContainerAt = DateTime.MinValue; + _lastContentsCheckAt = DateTime.MinValue; + _lastLootPickupTime = DateTime.MinValue; + _isSalvagingCurrentItem = false; + // NOTE: Do NOT clear _salvageQueue here — items survive between corpses + } + + private int FindNearestCorpse() + { + int best = 0; double d = double.MaxValue; + foreach (var wo in _core.WorldFilter.GetLandscape()) + { + if (wo.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Corpse + && !_lootedCorpses.Contains(wo.Id) + && wo.Id != _targetCorpseId + && ShouldLootCorpse(wo)) + { + double dist = _core.WorldFilter.Distance(_core.CharacterFilter.Id, wo.Id); + if (dist <= _settings.CorpseApproachRangeMax && dist < d) { d = dist; best = wo.Id; } + } + } + return best; + } + + /// <summary> + /// Returns true if there are unlooted corpses within loot range OR we're actively looting. + /// Uses CorpseApproachRangeMax — only pause for corpses we can actually reach. + /// </summary> + public bool HasUnlootedCorpsesNearby() + { + if (!_settings.EnableLooting) return false; + + // If we're actively looting a corpse, nav must wait + if (_lootState != LootState.Idle) return true; + + // Check for unlooted corpses within actual loot range only + int playerId = _core.CharacterFilter.Id; + foreach (var wo in _core.WorldFilter.GetLandscape()) + { + if (wo.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Corpse + && !_lootedCorpses.Contains(wo.Id) + && ShouldLootCorpse(wo)) + { + double dist = _core.WorldFilter.Distance(playerId, wo.Id); + if (dist <= _settings.CorpseApproachRangeMax) return true; + } + } + return false; + } + + /// <summary> + /// Determines if a corpse should be looted based on ownership settings. + /// Reads the corpse's LongDesc property ("Killed by {name}.") to determine who killed it. + /// + /// LootOwnership: 0=MyKillsOnly, 1=FellowshipKills, 2=AllCorpses + /// + /// Fellowship mode relies on: + /// 1. Chat-based FellowshipTracker for known member names + /// 2. Server-enforced corpse permissions (you can't open corpses you don't have rights to) + /// Our existing approach timeout gracefully handles failed opens. + /// </summary> + private bool ShouldLootCorpse(WorldObject corpse) + { + if (corpse == null) return false; + + // AllCorpses mode — loot everything + if (_settings.LootOwnership >= 2) return true; + + string longDesc = ""; + try { longDesc = corpse.Values((StringValueKey)16, ""); } catch { } + + string killerName = ExtractKillerName(longDesc); + string myName = _core.CharacterFilter.Name; + + // MyKillsOnly — only loot corpses I killed + if (_settings.LootOwnership == 0) + { + if (string.IsNullOrEmpty(killerName)) return false; + return killerName.Equals(myName, StringComparison.OrdinalIgnoreCase); + } + + // FellowshipKills mode + if (_settings.LootOwnership == 1) + { + // Always loot my own kills + if (!string.IsNullOrEmpty(killerName) && killerName.Equals(myName, StringComparison.OrdinalIgnoreCase)) + return true; + + // If we're in a fellowship, check if the killer is a known member + if (_fellowshipTracker != null && _fellowshipTracker.IsInFellowship) + { + // If killer is a tracked fellow member, loot it + if (!string.IsNullOrEmpty(killerName) && _fellowshipTracker.IsMember(killerName)) + return true; + + // If we're in a fellowship but can't identify the killer or they're not tracked yet, + // still attempt to loot — the server enforces permissions and our timeout handles failures. + // This covers the case where members joined before us and aren't tracked by chat. + return true; + } + + // Not in a fellowship — only loot my kills + if (string.IsNullOrEmpty(killerName)) return false; + return killerName.Equals(myName, StringComparison.OrdinalIgnoreCase); + } + + return false; + } + + /// <summary> + /// Extracts the killer name from "Killed by {name}." format. + /// </summary> + private string ExtractKillerName(string longDesc) + { + if (string.IsNullOrEmpty(longDesc)) return null; + + const string prefix = "Killed by "; + int idx = longDesc.IndexOf(prefix, StringComparison.OrdinalIgnoreCase); + if (idx < 0) return null; + + string remainder = longDesc.Substring(idx + prefix.Length); + remainder = remainder.TrimEnd('.', ' ', '\n', '\r'); + return string.IsNullOrEmpty(remainder) ? null : remainder; + } + + private void TestSelectionLogic() + { + int sel = _core.Actions.CurrentSelection; + if (sel != _lastSelectedId && sel != 0) + { + _lastSelectedId = sel; + var info = uTank2.PluginCore.PC.FWorldTracker_GetWithID(sel); + if (info != null && _vtLootCore != null) + { + var dec = _vtLootCore.GetLootDecision(info); + if (dec != null && (dec.IsKeep || dec.IsSalvage)) + _host.Actions.AddChatText($"[RynthAi] Match: {_core.WorldFilter[sel].Name} ({dec.RuleName})", 5); + } + } + } + + private bool ShouldLootItem(int id, WorldObject wo, out string reason, out bool isSalvage) + { + reason = "none"; + isSalvage = false; + + if (wo == null) + { + reason = "null-worldobject"; + return false; + } + + bool needsId = uTank2.PluginCore.PC.FLootPluginQueryNeedsID(id); + + // 1. PRIMARY PATH: Local VTClassic Engine (Always up-to-date) + if (!needsId && _vtLootCore != null) + { + var info = uTank2.PluginCore.PC.FWorldTracker_GetWithID(id); + if (info != null) + { + var decision = _vtLootCore.GetLootDecision(info); + if (decision != null) + { + if (decision.IsKeep || decision.IsSalvage || decision.IsKeepUpTo) + { + isSalvage = decision.IsSalvage; + reason = $"vtclassic:{decision.RuleName}"; + return true; + } + else + { + reason = $"vtclassic-noloot:{decision.RuleName}"; + return false; + } + } + } + } + + // 2. SECONDARY PATH: Local Parsed Profile + if (_parsedLootProfile != null && _parsedLootProfile.Rules != null && _parsedLootProfile.Rules.Count > 0) + { + foreach (var rule in _parsedLootProfile.Rules) + { + if (rule == null) continue; + if (rule.IsMatch(wo)) + { + if (rule.Action == LootAction.Keep || rule.Action == LootAction.Salvage) + { + isSalvage = (rule.Action == LootAction.Salvage); + reason = $"parser:{rule.Name}"; + return true; + } + + reason = $"parser-noloot:{rule.Name}:{rule.Action}"; + return false; + } + } + } + + // 3. TERTIARY PATH: Global VTank + if (!needsId) + { + var immediate = uTank2.PluginCore.PC.FLootPluginClassifyImmediate(id); + if (immediate != null) + { + if (immediate.IsKeep || immediate.IsSalvage) + { + isSalvage = immediate.IsSalvage; + reason = $"vtank-immediate:{immediate.RuleName}"; + return true; + } + + if (immediate.IsKeepUpTo) + { + int heldCount = CountInventoryMatchesForRule(immediate.RuleName); + if (heldCount < immediate.Data1) + { + reason = $"vtank-keepupto:{immediate.RuleName} held={heldCount} max={immediate.Data1}"; + return true; + } + reason = $"vtank-keepupto-limit:{immediate.RuleName} held={heldCount} max={immediate.Data1}"; + return false; + } + } + } + + if (needsId) reason = "needsid-timeout"; + else if (_parsedLootProfile == null || _parsedLootProfile.Rules == null || _parsedLootProfile.Rules.Count == 0) + reason = "no-parser-rules"; + + return false; + } + + private int CountInventoryMatchesForRule(string ruleName) + { + if (string.IsNullOrEmpty(ruleName)) return 0; + int count = 0; + + foreach (var inv in _core.WorldFilter.GetInventory()) + { + if (uTank2.PluginCore.PC.FLootPluginQueryNeedsID(inv.Id)) continue; + var invDecision = uTank2.PluginCore.PC.FLootPluginClassifyImmediate(inv.Id); + if (invDecision == null || invDecision.RuleName != ruleName) continue; + + int stackMax = inv.Values(LongValueKey.StackMax, 0); + count += stackMax > 0 ? inv.Values(LongValueKey.StackCount, 1) : 1; + } + + return count; + } + + private void DebugLog(string message) + { + try + { + File.AppendAllText(_debugLogPath, $"{DateTime.Now:HH:mm:ss.fff} {message}{Environment.NewLine}"); + } + catch { } + } + + private bool ProcessAutoCram() + { + if (!_settings.EnableAutocram) return false; + + var inv = _core.WorldFilter.GetInventory().ToList(); + int playerId = _core.CharacterFilter.Id; + + int mainPackCount = 0; + foreach (var item in inv) + { + if (item.Container != playerId) continue; + if (item.Values(LongValueKey.EquippedSlots, 0) != 0) continue; + if (_settings.ItemRules.Any(r => r.Id == item.Id)) continue; + if (item.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Container) continue; + if (item.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Foci) continue; + if (item.Values(LongValueKey.ItemSlots, 0) > 0) continue; // Has pack slots = is a container + if (item.Values((LongValueKey)151, 0) > 0) continue; // Alt container capacity key + if (_cramBlacklist.Contains(item.Id)) continue; + if (_salvageQueue.Contains(item.Id)) continue; + if (item.Id == _currentSalvageItemId) continue; + // Salvage bags ARE crammable — don't skip them + mainPackCount++; + + int pack = FindOpenPack(inv, playerId); + if (pack != 0) + { + DebugLog($"AutoCram: Moving {item.Name} (id={item.Id}) to pack {pack}"); + try + { + _host.Actions.MoveItem(item.Id, pack, 0, false); + } + catch (Exception ex) + { + DebugLog($"AutoCram: MoveItem FAILED: {ex.Message}"); + } + _cramBlacklist.Add(item.Id); + return true; + } + else + { + DebugLog($"AutoCram: No open pack found for {item.Name}"); + } + break; // Only try one item per tick + } + // No debug log when nothing to cram — this fires every tick and floods the log + return false; + } + + private int FindOpenPack(List<WorldObject> inv, int playerId) + { + foreach (var p in inv) + { + if (p.Container != playerId) continue; + + // Must be a container — check both ObjectClass and capacity properties + bool isContainer = (p.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Container); + if (!isContainer) continue; + + // Skip foci + if (p.Name != null && p.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0) continue; + + int itemsInPack = 0; + foreach (var item in inv) + { + if (item.Container == p.Id) itemsInPack++; + } + + // Get capacity + int cap = p.Values(LongValueKey.ItemSlots, 0); + if (cap <= 0) cap = p.Values((LongValueKey)151, 0); + if (cap <= 0) cap = 24; + + // 3-slot safety margin — prevents concurrent move conflicts + if (itemsInPack <= cap - 3) return p.Id; + } + return 0; + } + + private bool ProcessAutoStack() + { + if (!_settings.EnableAutostack) return false; + + int playerId = _core.CharacterFilter.Id; + var inv = _core.WorldFilter.GetInventory().ToList(); + + var playerItems = new List<WorldObject>(); + foreach (var item in inv) + { + if (item.Container == playerId) { playerItems.Add(item); continue; } + var container = inv.FirstOrDefault(c => c.Id == item.Container); + if (container != null && container.Container == playerId) playerItems.Add(item); + } + + var groups = playerItems + .Where(x => GetMaxStackSize(x) > 1 && !_salvageQueue.Contains(x.Id) && x.Id != _currentSalvageItemId) + .GroupBy(x => x.Name) + .Where(g => g.Count() > 1); + + foreach (var g in groups) + { + int max = GetMaxStackSize(g.First()); + var parts = g + .Where(x => x.Values(LongValueKey.StackCount, 1) < max) + .OrderByDescending(x => x.Values(LongValueKey.StackCount, 1)) + .ToList(); + + if (parts.Count < 2) continue; + + string pairKey = parts[0].Id + "_" + parts[parts.Count - 1].Id; + if (_failedStackPairs.Contains(pairKey)) continue; + + DebugLog($"AutoStack: Merging {parts[parts.Count - 1].Name} (count={parts[parts.Count - 1].Values(LongValueKey.StackCount, 1)}, id={parts[parts.Count - 1].Id}) into (count={parts[0].Values(LongValueKey.StackCount, 1)}, id={parts[0].Id}), max={max}"); + try + { + _host.Actions.MoveItem(parts[parts.Count - 1].Id, parts[0].Container, parts[0].Id, true); + } + catch (Exception ex) + { + DebugLog($"AutoStack: MoveItem FAILED: {ex.Message}"); + } + _failedStackPairs.Add(pairKey); + return true; + } + return false; + } + + private int GetMaxStackSize(WorldObject item) + { + // Primary: Use the standard Decal StackMax property + int max = item.Values(LongValueKey.StackMax, 0); + if (max > 1) return max; + + // Secondary: Some server emulators use a different key for certain items + int altMax = item.Values((LongValueKey)38, 0); + if (altMax > 1) return altMax; + + // Tertiary: Known AC item type fallbacks + if (item.Name != null) + { + if (item.Name.Contains("Pyreal")) return 25000; + if (item.Name.Contains("Trade Note")) return 100; + if (item.Name.Contains("Taper") || item.Name.Contains("Scarab") || + item.Name.Contains("Prismatic")) return 100; + if (item.Name.Contains("Arrow") || item.Name.Contains("Bolt") || + item.Name.Contains("Quarrel") || item.Name.Contains("Dart") || + item.Name.Contains("Throwing")) return 250; + if (item.Name.Contains("Pea") || item.Name.Contains("Grain") || + item.Name.Contains("Salvage")) return 100; + } + + return 1; // Not stackable + } + + public void Dispose() + { + if (_vtLootCore != null) { _vtLootCore.UnloadProfile(); _vtLootCore = null; } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Loot/VTankLootParser.cs b/Plugins/RynthAi/Loot/VTankLootParser.cs new file mode 100644 index 0000000..991bacb --- /dev/null +++ b/Plugins/RynthAi/Loot/VTankLootParser.cs @@ -0,0 +1,285 @@ +using System; +using System.IO; +using System.Collections.Generic; +using Decal.Adapter.Wrappers; +using System.Text.RegularExpressions; + +namespace NexSuite.Plugins.RynthAi +{ + public enum LootAction + { + Keep = 0, + Salvage = 1, + Sell = 2, + Read = 3, + User1 = 4 + } + + public class LootRule + { + public string Name { get; set; } + public LootAction Action { get; set; } + public int KeepCount { get; set; } + public string RawInfoLine { get; set; } + public List<string> RawDataLines { get; set; } = new List<string>(); + + public bool IsMatch(WorldObject item) + { + if (item == null || string.IsNullOrEmpty(RawInfoLine)) return false; + + try + { + var parts = RawInfoLine.Split(';'); + if (parts.Length < 2) return false; + + // A rule with no requirement nodes (only Action;KeepCount) is unconditional. + // "Loot Everything" style profiles depend on this behavior. + if (parts.Length == 2) return true; + + var data = new Queue<string>(RawDataLines); + var stack = new Stack<bool>(); + + // VTank stores requirement nodes in POSTFIX notation (Reverse Polish Notation) + // We start at index 2 to skip the Action and KeepCount numbers + for (int i = 2; i < parts.Length; i++) + { + if (!int.TryParse(parts[i], out int type)) continue; + + if (type == 9998) // OR Operator + { + if (stack.Count < 2) return false; + bool right = stack.Pop(); + bool left = stack.Pop(); + stack.Push(left || right); + } + else if (type == 9999) // AND Operator + { + if (stack.Count < 2) return false; + bool right = stack.Pop(); + bool left = stack.Pop(); + stack.Push(left && right); + } + else + { + // Leaf Node: Dequeue its specific data, evaluate, and push to stack + bool result = false; + + switch (type) + { + case 1: // StringValueMatch (Consumes 2 lines) + int sKey = int.Parse(data.Dequeue()); + string sMatch = data.Dequeue(); + string sVal = item.Values((StringValueKey)sKey, ""); + result = Regex.IsMatch(sVal, sMatch, RegexOptions.IgnoreCase); + break; + + case 2: // LongValKeyLE (Consumes 2 lines) + int lKeyLE = int.Parse(data.Dequeue()); + int lValLE = int.Parse(data.Dequeue()); + result = item.Values((LongValueKey)lKeyLE, 0) <= lValLE; + break; + + case 3: // LongValKeyGE (Consumes 2 lines) + int lKeyGE = int.Parse(data.Dequeue()); + int lValGE = int.Parse(data.Dequeue()); + result = item.Values((LongValueKey)lKeyGE, 0) >= lValGE; + break; + + case 4: // DoubleValKeyLE (Consumes 2 lines) + int dKeyLE = int.Parse(data.Dequeue()); + double dValLE = double.Parse(data.Dequeue()); + result = item.Values((DoubleValueKey)dKeyLE, 0.0) <= dValLE; + break; + + case 5: // DoubleValKeyGE (Consumes 2 lines) + int dKeyGE = int.Parse(data.Dequeue()); + double dValGE = double.Parse(data.Dequeue()); + result = item.Values((DoubleValueKey)dKeyGE, 0.0) >= dValGE; + break; + + case 7: // ObjectClass (Consumes 1 line) + int objClass = int.Parse(data.Dequeue()); + result = (int)item.ObjectClass == objClass; + break; + + case 12: // LongValKeyE (Consumes 2 lines) + int lKeyE = int.Parse(data.Dequeue()); + int lValE = int.Parse(data.Dequeue()); + result = item.Values((LongValueKey)lKeyE, 0) == lValE; + break; + + case 13: // LongValKeyNE (Consumes 2 lines) + int lKeyNE = int.Parse(data.Dequeue()); + int lValNE = int.Parse(data.Dequeue()); + result = item.Values((LongValueKey)lKeyNE, 0) != lValNE; + break; + + default: + // If we encounter a VTank node type we haven't mapped yet, we MUST abort the rule. + // If we don't know how many lines of data it consumes, we can't safely + // process the rest of the queue, so we fail safely and skip to the next rule. + return false; + } + + stack.Push(result); + } + } + + // The final result of the tree will be the only item left sitting in the stack. + // If nodes existed but did not produce a valid expression, fail safely. + return stack.Count == 1 && stack.Pop(); + } + catch + { + return false; // Failsafe for missing data or parsing exceptions + } + } + } + + public class VTankLootProfile + { + public List<LootRule> Rules { get; set; } = new List<LootRule>(); + } + + public static class VTankLootParser + { + public static VTankLootProfile Load(string filePath) + { + var profile = new VTankLootProfile(); + if (!File.Exists(filePath)) return profile; + + string[] lines = File.ReadAllLines(filePath); + if (lines.Length < 3 || lines[0].Trim() != "UTL") + throw new Exception("Invalid UTL file format."); + + int version = int.Parse(lines[1].Trim()); + int ruleCount = int.Parse(lines[2].Trim()); + + int lineIndex = 3; + + while (lineIndex < lines.Length && profile.Rules.Count < ruleCount) + { + LootRule rule = new LootRule(); + + // 1. Read Name (VTank sometimes leaves these blank, so we just trim the end) + rule.Name = lines[lineIndex++].TrimEnd(); + + // 2. Read the mandatory Empty Line VTank puts after names + if (lineIndex < lines.Length && string.IsNullOrWhiteSpace(lines[lineIndex])) + { + lineIndex++; + } + + // 3. Read the InfoLine (e.g., "0;1;1;12") + if (lineIndex < lines.Length) + { + rule.RawInfoLine = lines[lineIndex++].Trim(); + string[] parts = rule.RawInfoLine.Split(';'); + if (parts.Length >= 2 && int.TryParse(parts[0], out int act) && int.TryParse(parts[1], out int count)) + { + rule.Action = (LootAction)act; + rule.KeepCount = count; + } + } + + // 4. Read Requirement Data using node-token arity when possible. + // This is more reliable than heuristic rule boundary detection for complex profiles. + int requiredDataLines = TryGetRequiredDataLineCount(rule.RawInfoLine); + if (requiredDataLines >= 0) + { + for (int i = 0; i < requiredDataLines && lineIndex < lines.Length; i++) + { + rule.RawDataLines.Add(lines[lineIndex++].TrimEnd()); + } + } + else + { + // Fallback for unknown token types: heuristic boundary detection. + while (lineIndex < lines.Length) + { + if (IsStartOfNextRule(lines, lineIndex)) + { + break; + } + + rule.RawDataLines.Add(lines[lineIndex++].TrimEnd()); + } + } + + profile.Rules.Add(rule); + } + + return profile; + } + + private static bool IsStartOfNextRule(string[] lines, int index) + { + // We need at least 3 lines to form a valid rule start: [Name], [Empty Line], [InfoLine] + if (index + 2 >= lines.Length) return false; + + // lines[index] is the Name. It can be literally anything, so we skip checking it. + + // lines[index+1] MUST be an empty line in the VTank format + if (!string.IsNullOrWhiteSpace(lines[index + 1])) return false; + + // lines[index+2] MUST be an InfoLine containing semicolons + string infoLine = lines[index + 2].Trim(); + if (!infoLine.Contains(";")) return false; + + string[] parts = infoLine.Split(';'); + if (parts.Length >= 2) + { + // An InfoLine always starts with two integers (Action and KeepCount) + if (int.TryParse(parts[0], out int action) && int.TryParse(parts[1], out int _)) + { + // Valid VTank Actions are 0 to 4 (Allowing up to 10 just for forward compatibility) + if (action >= 0 && action <= 10) return true; + } + } + + return false; + } + + private static int TryGetRequiredDataLineCount(string rawInfoLine) + { + if (string.IsNullOrWhiteSpace(rawInfoLine)) return -1; + var parts = rawInfoLine.Split(';'); + if (parts.Length < 2) return -1; + if (parts.Length == 2) return 0; // unconditional rule + + int required = 0; + for (int i = 2; i < parts.Length; i++) + { + if (!int.TryParse(parts[i], out int type)) continue; + + int lines = GetDataLinesForNodeType(type); + if (lines < 0) return -1; + required += lines; + } + + return required; + } + + private static int GetDataLinesForNodeType(int type) + { + switch (type) + { + case 9998: // OR + case 9999: // AND + return 0; + case 1: // StringValueMatch + case 2: // LongValKeyLE + case 3: // LongValKeyGE + case 4: // DoubleValKeyLE + case 5: // DoubleValKeyGE + case 12: // LongValKeyE + case 13: // LongValKeyNE + return 2; + case 7: // ObjectClass + return 1; + default: + return -1; + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Lua/LuaBridge.cs b/Plugins/RynthAi/Lua/LuaBridge.cs new file mode 100644 index 0000000..5aabf80 --- /dev/null +++ b/Plugins/RynthAi/Lua/LuaBridge.cs @@ -0,0 +1,115 @@ +using System; +using System.Text.RegularExpressions; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public class LuaBridge + { + private readonly PluginCore _core; + // Returns the actual North/South coordinate (e.g. 42.5) + public double GetPlayerNS() + { + return Decal.Adapter.CoreManager.Current.WorldFilter[Decal.Adapter.CoreManager.Current.CharacterFilter.Id].Coordinates().NorthSouth; + } + + // Returns the actual East/West coordinate (e.g. -33.7) + public double GetPlayerEW() + { + return Decal.Adapter.CoreManager.Current.WorldFilter[Decal.Adapter.CoreManager.Current.CharacterFilter.Id].Coordinates().EastWest; + } + + // Returns the altitude in meters + public double GetPlayerZ() + { + return Decal.Adapter.CoreManager.Current.Actions.LocationZ; + } + + public LuaBridge(PluginCore core) + { + _core = core; + } + + // --- MOVEMENT --- + public void GoTo(string ns, string ew) + { + double dNS = ParseCoord(ns); + double dEW = ParseCoord(ew); + + _core.UI.Settings.CurrentRoute.Points.Clear(); + _core.UI.Settings.CurrentRoute.Points.Add(new NavPoint { NS = dNS, EW = dEW, Type = NavPointType.Point }); + _core.UI.Settings.CurrentRoute.RouteType = NavRouteType.Once; + _core.UI.Settings.ActiveNavIndex = 0; + + _core.UI.Settings.IsMacroRunning = true; + _core.UI.Settings.EnableNavigation = true; + + if (_core.UI?.RouteTab != null) _core.UI.RouteTab.NeedsRouteGraphicsRefresh = true; + _core.PluginHost.Actions.AddChatText($"[RynthLua] Navigating to: {ns}, {ew}", 1); + } + + public void Stop() + { + _core.UI.Settings.IsMacroRunning = false; + _core.UI.Settings.EnableNavigation = false; + _core.PluginHost.Actions.AddChatText("[RynthLua] Macro Stopped.", 1); + } + + // --- INTERACTION --- + public void UsePortal(string portalName) + { + foreach (WorldObject wo in _core.PluginCoreManager.WorldFilter.GetLandscape()) + { + if (wo.Name.IndexOf(portalName, StringComparison.OrdinalIgnoreCase) >= 0) + { + if (wo.ObjectClass == ObjectClass.Portal || wo.ObjectClass == ObjectClass.Npc) + { + // The correct Decal API call: UseItem(GUID, ContainerID) + // We use 0 for the container because portals are in the world. + _core.PluginHost.Actions.UseItem(wo.Id, 0); + return; + } + } + } + } + + // --- UTILS --- + private double ParseCoord(string val) + { + if (string.IsNullOrEmpty(val)) return 0; + string clean = Regex.Replace(val, "[^0-9.-]", ""); + if (!double.TryParse(clean, out double result)) return 0; + return (val.ToUpper().Contains("S") || val.ToUpper().Contains("W")) ? -result : result; + } + + public bool IsPathClear(double startNS, double startEW, double startZ, double endNS, double endEW, double endZ) + { + try + { + // Use '_core' instead of '_plugin' + if (_core.Raycast == null || !_core.Raycast.IsInitialized) + return true; + + // Convert EW/NS to Global Meters + float startX = (float)((startEW * 10.0 + 1019.5) * 24.0); + float startY = (float)((startNS * 10.0 + 1019.5) * 24.0); + var origin = new RynthAi.Raycasting.Vector3(startX, startY, (float)startZ + 1.0f); + + float endX = (float)((endEW * 10.0 + 1019.5) * 24.0); + float endY = (float)((endNS * 10.0 + 1019.5) * 24.0); + var destination = new RynthAi.Raycasting.Vector3(endX, endY, (float)endZ + 1.0f); + + // Access Landcell safely via CoreManager + uint landcell = (uint)Decal.Adapter.CoreManager.Current.Actions.Landcell; + var geometry = _core.Raycast.GeometryLoader.GetLandblockGeometry(landcell); + + // Test the line + return !RynthAi.Raycasting.RaycastEngine.IsLinearPathBlocked(origin, destination, geometry); + } + catch + { + return true; // Default to assuming clear if it fails, to prevent the bot from freezing + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Lua/LuaManager.cs b/Plugins/RynthAi/Lua/LuaManager.cs new file mode 100644 index 0000000..37a88af --- /dev/null +++ b/Plugins/RynthAi/Lua/LuaManager.cs @@ -0,0 +1,154 @@ +using System; +using System.Text; +using NLua; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using System.IO; + +namespace NexSuite.Plugins.RynthAi +{ + public class LuaManager : IDisposable + { + private Lua _lua; + private readonly PluginCore _core; + private bool _isDisposed; + public void Execute(string script) => ExecuteString(script); + + public LuaManager(PluginCore core) + { + _core = core; + Init(); + } + + public void Init() + { + try + { + // 1. Clean up old state if re-initializing to prevent memory leaks + _lua?.Dispose(); + + // 2. Initialize the fresh NLua state + _lua = new Lua(); + _lua.LoadCLRPackage(); + + // 3. Instantiate the Bridge + // This class acts as the middle-man, housing GoTo, Stop, and UsePortal logic + var bridge = new LuaBridge(_core); + + // --- THE API BRIDGE: Expose the Bridge as "RynthAi" --- + // Usage in Lua: RynthAi:GoTo("33.5N", "44.8E") + _lua["RynthAi"] = bridge; + + // --- SHORTCUTS: Direct manager access for advanced scripting --- + if (_core.UI != null) + { + _lua["Combat"] = _core.UI.CombatManager; + _lua["Settings"] = _core.UI.Settings; + _lua["Nav"] = _core.UI.Settings.CurrentRoute; + } + + // Expose the raw Decal CoreManager (e.g., Core.WorldFilter) + _lua["Core"] = _core.PluginCoreManager; + + // --- REDIRECT PRINT --- + // Replaces Lua's default print() with our custom C# method + // which sends text to both AC Chat and the UI Console. + _lua.RegisterFunction("print", this, typeof(LuaManager).GetMethod("LuaPrint")); + + LuaPrint("Lua Engine Initialized."); + } + catch (Exception ex) + { + LogError("Init Error: " + ex.Message); + } + } + + public void ExecuteString(string script) + { + try + { + if (string.IsNullOrEmpty(script) || _lua == null) return; + _lua.DoString(script); + } + catch (NLua.Exceptions.LuaException ex) + { + // This will now show you the EXACT line number and error in AC chat + LogError("Lua Script Error: " + ex.Message); + } + catch (Exception ex) + { + LogError("Engine Error: " + ex.Message); + } + } + public void LuaPrint(object msg) + { + // 1. Format the basic string and timestamp + string text = msg?.ToString() ?? "nil"; + string timestamp = DateTime.Now.ToString("HH:mm:ss"); + string formattedMsg = $"[{timestamp}] {text}"; + + // 2. Always output to Asheron's Call Chat (Green text) + // This is safe even if the UI window isn't open yet + _core.PluginHost.Actions.AddChatText($"[RynthLua] {text}", 5); + + // 3. Safely update the ImGui Console Tab + // We wrap everything in this check so the plugin doesn't crash + // if you try to print something before the UI is fully loaded. + if (_core.UI?.Settings != null) + { + // Append the new line to the console + _core.UI.Settings.LuaConsoleOutput += $"\n{formattedMsg}"; + + // Limit console size to roughly 10k characters to prevent memory bloat + if (_core.UI.Settings.LuaConsoleOutput.Length > 10000) + { + // Trims the oldest 5,000 characters + _core.UI.Settings.LuaConsoleOutput = _core.UI.Settings.LuaConsoleOutput.Substring(5000); + } + } + } + + public void LoadMainScript() + { + try + { + string scriptDir = Path.Combine(_core.AssemblyDirectory, "Scripts"); + if (!Directory.Exists(scriptDir)) Directory.CreateDirectory(scriptDir); + + string path = Path.Combine(scriptDir, "main.lua"); + + if (File.Exists(path)) + { + string code = File.ReadAllText(path); + ExecuteString(code); + LuaPrint("Main script loaded from: " + path); + } + else + { + // Create a dummy file so the user has a template + File.WriteAllText(path, "-- RynthAi Main Lua Script\nfunction OnBotTick()\nend"); + LuaPrint("Created template main.lua at: " + path); + } + } + catch (Exception ex) + { + LogError("LoadMainScript Error: " + ex.Message); + } + } + + private void LogError(string msg) + { + _core.PluginHost.Actions.AddChatText($"[RynthLua Error] {msg}", 2); + _core.UI.Settings.LuaConsoleOutput += $"\n[ERROR] {msg}"; + } + + public void Dispose() + { + if (!_isDisposed) + { + _lua?.Dispose(); + _isDisposed = true; + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Meta/MetaManager.cs b/Plugins/RynthAi/Meta/MetaManager.cs new file mode 100644 index 0000000..1445495 --- /dev/null +++ b/Plugins/RynthAi/Meta/MetaManager.cs @@ -0,0 +1,684 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Newtonsoft.Json; +using NexSuite.Plugins.RynthAi; +using System.Numerics; +using System.Linq; + + +namespace RynthAi.Meta +{ + public class MetaManager + { + private CoreManager _core; + private UISettings _settings; + private PluginHost _host; + + private string _lastChatText = ""; + private DateTime _lastChatTime = DateTime.MinValue; + private System.Text.RegularExpressions.Match _lastChatMatch = null; + + // Timer tracking for "Seconds in State" + private DateTime _lastStateChange = DateTime.Now; + private string _previousState = ""; + + // Tracks if the meta was turned off so we can clean the slate when turned back on + private bool _wasMetaEnabled = false; + public Action OnRouteDynamicallyLoaded; + private Stack<string> _stateStack = new Stack<string>(); + private bool _watchdogActive = false; + private string _watchdogState = ""; + private float _watchdogMetersRequired = 0f; + private double _watchdogSecondsConfig = 0; + private DateTime _watchdogExpiration; + private Vector3 _lastWatchdogPos; // Requires 'using System.Numerics;' + private string _lastState = ""; + private DateTime _stateStartTime = DateTime.Now; + + + public MetaManager(CoreManager core, UISettings settings, PluginHost host) + { + _core = core; + _settings = settings; + _host = host; + } + + public void OnHeartbeat() + { + // 1. If Meta is disabled, reset our tracker and do absolutely nothing + if (!_settings.IsMacroRunning || !_settings.EnableMeta || _settings.MetaRules == null) + { + _wasMetaEnabled = false; + return; + } + + // 2. If Meta was just turned on, we need a clean slate so old timers don't instantly trigger + if (!_wasMetaEnabled) + { + _wasMetaEnabled = true; + _lastStateChange = DateTime.Now; + _previousState = _settings.CurrentState; + + // Reset all rules so they can fire again + foreach (var r in _settings.MetaRules) r.HasFired = false; + } + + // 3. Normal State Change OR Forced Reset from UI + if (!string.Equals(_settings.CurrentState, _previousState, StringComparison.OrdinalIgnoreCase) || _settings.ForceStateReset) + { + _settings.ForceStateReset = false; // Consume the flag so it only resets once + _lastStateChange = DateTime.Now; + _previousState = _settings.CurrentState; + + // Reset all rules so they can fire again in the new/reset state + foreach (var r in _settings.MetaRules) + { + r.HasFired = false; + } + } + + // Calculate the time ONCE per heartbeat to pass into evaluations, + // saving CPU cycles on deep 'Any'/'All' recursive checks. + double currentSecondsInState = (DateTime.Now - _lastStateChange).TotalSeconds; + + // 4. Evaluate Rules + foreach (var rule in _settings.MetaRules) + { + // Case-insensitive check so "Default" and "default" don't break the meta + if (string.Equals(rule.State, _settings.CurrentState, StringComparison.OrdinalIgnoreCase)) + { + // Check our boolean to prevent chat/action spam + if (!rule.HasFired) + { + if (EvaluateCondition(rule, currentSecondsInState)) + { + ExecuteAction(rule); + + // Mark this specific rule as fired so it glows red in UI and stops spamming + rule.HasFired = true; + + break; // Process one successful rule per heartbeat + } + } + } + } + } + + private bool EvaluateCondition(MetaRule rule, double secondsInState) + { + try + { + // Explicitly using Decal.Adapter for Vitals + dynamic actions = _host.Actions; + + switch (rule.Condition) + { + case MetaConditionType.Always: return true; + case MetaConditionType.Never: return false; + + case MetaConditionType.All: + { + if (rule.Children == null || rule.Children.Count == 0) return false; + foreach (var child in rule.Children) + if (!EvaluateCondition(child, secondsInState)) return false; + return true; + } + + case MetaConditionType.Any: + { + if (rule.Children == null || rule.Children.Count == 0) return false; + foreach (var child in rule.Children) + if (EvaluateCondition(child, secondsInState)) return true; + return false; + } + + case MetaConditionType.Not: + { + if (rule.Children == null || rule.Children.Count == 0) return false; + return !EvaluateCondition(rule.Children[0], secondsInState); + } + + // --- VITAL CHECKS (Value) --- + case MetaConditionType.MainHealthLE: + { + if (int.TryParse(rule.ConditionData, out int hVal)) + return _core.CharacterFilter.Health <= hVal; + return false; + } + + case MetaConditionType.MainManaLE: + { + if (int.TryParse(rule.ConditionData, out int mVal)) + return _core.CharacterFilter.Mana <= mVal; + return false; + } + + case MetaConditionType.MainStamLE: + { + if (int.TryParse(rule.ConditionData, out int sVal)) + return _core.CharacterFilter.Stamina <= sVal; + return false; + } + + // --- VITAL CHECKS (Percentage) --- + case MetaConditionType.MainHealthPHE: + { + if (int.TryParse(rule.ConditionData, out int hPct)) + { + double cur = _core.CharacterFilter.Health; // Live HP + double max = _core.CharacterFilter.Vitals[Decal.Adapter.Wrappers.CharFilterVitalType.Health].Current; // Max HP + return max > 0 && (cur / max) * 100 <= hPct; + } + return false; + } + + case MetaConditionType.MainManaPHE: + { + if (int.TryParse(rule.ConditionData, out int mPct)) + { + double cur = _core.CharacterFilter.Mana; // Live MP + double max = _core.CharacterFilter.Vitals[Decal.Adapter.Wrappers.CharFilterVitalType.Mana].Current; // Max MP + return max > 0 && (cur / max) * 100 <= mPct; + } + return false; + } + + case MetaConditionType.CharacterDeath: + return _core.CharacterFilter.Health <= 0; + + // --- TIME & CHAT --- + case MetaConditionType.SecondsInState_GE: + case MetaConditionType.SecondsInStateP_GE: + { + if (double.TryParse(rule.ConditionData, out double reqSecs)) + return secondsInState >= reqSecs; + return false; + } + + case MetaConditionType.ChatMessage: + case MetaConditionType.ChatMessageCapture: + { + if ((DateTime.Now - _lastChatTime).TotalSeconds > 1.0) return false; + try + { + var regex = new System.Text.RegularExpressions.Regex(rule.ConditionData); + var match = regex.Match(_lastChatText); + if (match.Success) + { + if (rule.Condition == MetaConditionType.ChatMessageCapture) _lastChatMatch = match; + return true; + } + } + catch { } + return false; + } + + // --- WORLD & INVENTORY --- + case MetaConditionType.BurdenPercentage_GE: + { + if (int.TryParse(rule.ConditionData, out int targetB)) + return _core.CharacterFilter.Burden >= targetB; + return false; + } + + case MetaConditionType.PackSlots_LE: + { + if (int.TryParse(rule.ConditionData, out int targetSlots)) + { + int myId = _core.CharacterFilter.Id; + int usedGridSquares = 0; + foreach (var item in _core.WorldFilter.GetInventory()) + { + if (item.Container == myId) + { + int slot = item.Values(Decal.Adapter.Wrappers.LongValueKey.Slot, -1); + bool isEquipped = item.Values(Decal.Adapter.Wrappers.LongValueKey.EquippedSlots, 0) > 0; + bool isBag = item.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Container; + bool isFoci = item.Name != null && item.Name.Contains("Foci"); + + if (slot >= 0 && slot <= 101 && !isEquipped && !isBag && !isFoci) + usedGridSquares++; + } + } + int freeSlots = 102 - usedGridSquares; + return freeSlots <= targetSlots; + } + return false; + } + + case MetaConditionType.InventoryItemCount_LE: + case MetaConditionType.InventoryItemCount_GE: + { + if (string.IsNullOrEmpty(rule.ConditionData)) return false; + string[] invParts = rule.ConditionData.Split(','); + if (invParts.Length >= 2) + { + string itemName = invParts[0].Trim(); + if (!int.TryParse(invParts[1], out int targetCount)) return false; + + int currentCount = 0; + int myId = _core.CharacterFilter.Id; + foreach (var item in _core.WorldFilter.GetInventory()) + { + bool isMine = (item.Container == myId); + if (!isMine) + { + var parentBag = _core.WorldFilter[item.Container]; + if (parentBag != null && parentBag.Container == myId) isMine = true; + } + + if (isMine && item.Name != null && item.Name.Equals(itemName, StringComparison.OrdinalIgnoreCase)) + currentCount += item.Values(Decal.Adapter.Wrappers.LongValueKey.StackCount, 1); + } + + if (rule.Condition == MetaConditionType.InventoryItemCount_LE) + return currentCount <= targetCount; + else + return currentCount >= targetCount; + } + return false; + } + + case MetaConditionType.TimeLeftOnSpell_GE: + case MetaConditionType.TimeLeftOnSpell_LE: + { + if (string.IsNullOrEmpty(rule.ConditionData)) return false; + string[] spellParts = rule.ConditionData.Split(','); + if (spellParts.Length >= 2) + { + if (int.TryParse(spellParts[0], out int spellId) && double.TryParse(spellParts[1], out double reqSecs)) + { + double remaining = 0; + bool found = false; + foreach (var ench in _core.CharacterFilter.Enchantments) + { + if (ench.SpellId == spellId) + { + remaining = ench.TimeRemaining; + found = true; + break; + } + } + if (rule.Condition == MetaConditionType.TimeLeftOnSpell_GE) + return found && remaining >= reqSecs; + else + return !found || remaining <= reqSecs; + } + } + return false; + } + + case MetaConditionType.MonsterNameCountWithinDistance: + { + if (string.IsNullOrEmpty(rule.ConditionData)) return false; + string[] mParts = rule.ConditionData.Split(','); + if (mParts.Length >= 3) + { + string pattern = mParts[0]; + if (!double.TryParse(mParts[1], out double dist) || !int.TryParse(mParts[2], out int count)) return false; + int matchCount = 0; + var regex = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); + foreach (var obj in _core.WorldFilter.GetLandscape()) + { + if (obj.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Monster && _core.WorldFilter.Distance(obj.Id, _core.CharacterFilter.Id) <= dist) + if (regex.IsMatch(obj.Name)) matchCount++; + } + return matchCount >= count; + } + return false; + } + + case MetaConditionType.NoMonstersWithinDistance: + { + double maxD = 20.0; + double.TryParse(rule.ConditionData, out maxD); + foreach (var obj in _core.WorldFilter.GetLandscape()) + { + if (obj.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Monster && _core.WorldFilter.Distance(obj.Id, _core.CharacterFilter.Id) <= maxD) + return false; + } + return true; + } + + case MetaConditionType.NavrouteEmpty: + if (_settings.CurrentRoute == null || _settings.CurrentRoute.Points.Count == 0) return true; + return _settings.ActiveNavIndex >= _settings.CurrentRoute.Points.Count; + + case MetaConditionType.AnyVendorOpen: + return actions.VendorId != 0; + + case MetaConditionType.PortalspaceEntered: + return (actions.Status & 0x1) != 0; + + case MetaConditionType.PortalspaceExited: + return (actions.Status & 0x1) == 0; + + default: + return false; + } + } + catch (Exception ex) + { + _host.Actions.AddChatText($"[RynthAi] EvaluateCondition Error: {ex.Message}", 2); + } + return false; + } + + private void ExecuteAction(MetaRule rule) + { + dynamic actions = _host.Actions; + + // --- HELPER: Regex Variable Replacement --- + string ProcessData(string rawData) + { + if (string.IsNullOrEmpty(rawData)) return ""; + if (_lastChatMatch == null || !_lastChatMatch.Success) return rawData; + + string result = rawData; + for (int i = 0; i < _lastChatMatch.Groups.Count; i++) + { + result = result.Replace($"{{{i}}}", _lastChatMatch.Groups[i].Value); + } + return result; + } + + switch (rule.Action) + { + case MetaActionType.All: + if (rule.Children != null && rule.Children.Count > 0) + { + foreach (var childAction in rule.Children) ExecuteAction(childAction); + } + break; + + case MetaActionType.ChatCommand: + string finalCommand = ProcessData(rule.ActionData); + if (!string.IsNullOrEmpty(finalCommand)) actions.InvokeChatParser(finalCommand); + break; + + case MetaActionType.SetMetaState: + string nextState = ProcessData(rule.ActionData); + if (!string.IsNullOrEmpty(nextState)) + { + _settings.CurrentState = nextState; + _settings.ForceStateReset = true; + actions.AddChatText($"[RynthAi] Meta State -> {nextState}", 5); + } + break; + + case MetaActionType.CallMetaState: + string callState = ProcessData(rule.ActionData); + if (!string.IsNullOrEmpty(callState)) + { + _stateStack.Push(_settings.CurrentState); + _settings.CurrentState = callState; + _settings.ForceStateReset = true; + actions.AddChatText($"[RynthAi] Calling State -> {callState}", 5); + } + break; + + case MetaActionType.ReturnFromCall: + if (_stateStack.Count > 0) + { + string returnTo = _stateStack.Pop(); + _settings.CurrentState = returnTo; + _settings.ForceStateReset = true; + actions.AddChatText($"[RynthAi] Returning to -> {returnTo}", 5); + } + else { actions.AddChatText("[RynthAi] Error: Return From Call failed (Stack Empty)", 2); } + break; + + case MetaActionType.EmbeddedNavRoute: + if (string.IsNullOrWhiteSpace(rule.ActionData)) break; + string routeName = rule.ActionData.Split(';')[0]; + string navFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\NavProfiles"; + string fullPath = System.IO.Path.Combine(navFolder, routeName + ".nav"); + + if (System.IO.File.Exists(fullPath)) + { + try + { + _settings.CurrentNavPath = fullPath; + _settings.CurrentRoute = VTankNavParser.Load(fullPath); + _settings.ActiveNavIndex = 0; + actions.AddChatText($"[RynthAi Meta] Switched to route: {routeName}", 5); + OnRouteDynamicallyLoaded?.Invoke(); + } + catch (Exception ex) { actions.AddChatText($"[RynthAi Meta] Load Error: {ex.Message}", 2); } + } + else { actions.AddChatText($"[RynthAi Meta] Route file missing: {fullPath}", 2); } + break; + + case MetaActionType.SetWatchdog: + // IGNITION SWITCH: If it's already ticking, do absolutely nothing. + // This prevents the rule from resetting the timer every single frame! + if (_watchdogActive) break; + + string[] wdParts = (rule.ActionData ?? "").Split(';'); + if (wdParts.Length >= 3) + { + _watchdogState = wdParts[0].Trim(); + if (!float.TryParse(wdParts[1].Trim(), out _watchdogMetersRequired)) _watchdogMetersRequired = 5f; + if (!double.TryParse(wdParts[2].Trim(), out _watchdogSecondsConfig)) _watchdogSecondsConfig = 5.0; + + _watchdogExpiration = DateTime.Now.AddSeconds(_watchdogSecondsConfig); + _lastWatchdogPos = new Vector3((float)actions.LocationX, (float)actions.LocationY, (float)actions.LocationZ); + + _watchdogActive = true; + + actions.AddChatText($"[RynthAi] Watchdog Started: To {_watchdogState} if not moved {_watchdogMetersRequired}m in {_watchdogSecondsConfig}s.", 5); + } + break; + + case MetaActionType.ClearWatchdog: + _watchdogActive = false; + actions.AddChatText("[RynthAi] Watchdog Cleared", 5); + break; + + case MetaActionType.SetNTOption: + string[] ntParts = (rule.ActionData ?? "").Split(';'); + if (ntParts.Length >= 2) actions.AddChatText($"[RynthAi] Option Set: {ntParts[0]} = {ntParts[1]}", 5); + break; + + case MetaActionType.ExpressionAction: + case MetaActionType.ChatExpression: + case MetaActionType.CreateView: + case MetaActionType.DestroyView: + case MetaActionType.DestroyAllViews: + break; + } + } + + + + public void Think() + { + try + { + dynamic actions = _host.Actions; + + // 1. THE KILL SWITCH (State Entry/Exit) + if (_settings.CurrentState != _lastState || _settings.ForceStateReset) + { + _lastState = _settings.CurrentState; + _stateStartTime = DateTime.Now; + + _watchdogActive = false; + _settings.ForceStateReset = false; + + // --- THE FIX: Wipe the slate clean for the new state --- + // This ensures rules can fire again if we leave the state and come back later + if (_settings.MetaRules != null) + { + foreach (var r in _settings.MetaRules) + { + r.HasFired = false; + } + } + } + + double secondsInState = (DateTime.Now - _stateStartTime).TotalSeconds; + + // 2. THE WATCHDOG TIMER + if (_watchdogActive) + { + Vector3 currentPos = new Vector3( + (float)actions.LocationX, + (float)actions.LocationY, + (float)actions.LocationZ + ); + + float distMoved = Vector3.Distance(currentPos, _lastWatchdogPos); + + if (distMoved < _watchdogMetersRequired) + { + if (DateTime.Now > _watchdogExpiration) + { + _watchdogActive = false; + _settings.CurrentState = _watchdogState; + _settings.ForceStateReset = true; + + actions.AddChatText($"[RynthAi] WATCHDOG TRIGGERED! Jumping to: {_watchdogState}", 5); + return; + } + } + else + { + _lastWatchdogPos = currentPos; + _watchdogExpiration = DateTime.Now.AddSeconds(_watchdogSecondsConfig); + } + } + + // 3. RULE EVALUATION + if (!_settings.EnableMeta || _settings.MetaRules == null) return; + + var currentRules = _settings.MetaRules.Where(r => r.State == _settings.CurrentState).ToList(); + + foreach (var rule in currentRules) + { + // --- THE FIX: Skip this rule if it already successfully fired during this state visit --- + if (rule.HasFired) continue; + + if (EvaluateCondition(rule, secondsInState)) + { + rule.HasFired = true; // Lock it out from firing again + ExecuteAction(rule); + + if (_settings.CurrentState != _lastState || _settings.ForceStateReset) + { + break; + } + } + } + } + catch (Exception ex) + { + _host.Actions.AddChatText($"[RynthAi] ENGINE CRASH in Think(): {ex.Message}", 5); + } + } + + public void PrintWatchdogStatus() + { + if (!_watchdogActive) + { + _host.Actions.AddChatText("[RynthAi] Watchdog Status: INACTIVE", 5); + return; + } + + // Grab current coordinates + Vector3 currentPos = new Vector3( + (float)_host.Actions.LocationX, + (float)_host.Actions.LocationY, + (float)_host.Actions.LocationZ + ); + + // Calculate real-time stats + float distMoved = Vector3.Distance(currentPos, _lastWatchdogPos); + double secondsLeft = (_watchdogExpiration - DateTime.Now).TotalSeconds; + + // Print the diagnostic readout + _host.Actions.AddChatText($"[RynthAi] Watchdog Status: ACTIVE", 5); + _host.Actions.AddChatText($" -> Target State: {_watchdogState}", 5); + _host.Actions.AddChatText($" -> Distance Moved: {distMoved:F2}m / {_watchdogMetersRequired}m", 5); + _host.Actions.AddChatText($" -> Time Left: {Math.Max(0, secondsLeft):F1}s", 5); + } + + private Vector3 GetCurrentPosition() + { + // Accessing the host's actions coordinates directly + return new Vector3( + (float)_host.Actions.LocationX, + (float)_host.Actions.LocationY, + (float)_host.Actions.LocationZ + ); + } + + + + // --- PROFILE PERSISTENCE --- + + public void LoadProfile(string path) + { + try + { + if (string.IsNullOrEmpty(path) || !File.Exists(path)) + { + _settings.MetaRules = new List<MetaRule>(); + return; + } + + // Try VTank Parser first for .met files + if (path.EndsWith(".met", StringComparison.OrdinalIgnoreCase)) + { + var vtankRules = VTankMetaParser.IntelligentlyLoad(path); + if (vtankRules != null) + { + _settings.MetaRules = vtankRules; + _host.Actions.AddChatText($"[RynthAi] Imported VTank Profile: {Path.GetFileName(path)}", 5); + return; + } + } + + // Fallback to our native JSON loader + string json = File.ReadAllText(path); + var rules = JsonConvert.DeserializeObject<List<MetaRule>>(json); + if (rules != null) _settings.MetaRules = rules; + } + catch (Exception ex) + { + _host.Actions.AddChatText($"[RynthAi] Meta Load Error: {ex.Message}", 1); + } + } + + + public void SaveCurrentProfile() + { + try + { + if (string.IsNullOrEmpty(_settings.CurrentMetaPath)) return; + + string directory = Path.GetDirectoryName(_settings.CurrentMetaPath); + if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); + + string json = JsonConvert.SerializeObject(_settings.MetaRules, Formatting.Indented); + File.WriteAllText(_settings.CurrentMetaPath, json); + } + catch (Exception ex) + { + _host.Actions.AddChatText($"[RynthAi] Meta Save Error: {ex.Message}", 1); + } + } + + public void HandleChat(string text) + { + // TEMPORARY DEBUG: Uncomment this to see if text is hitting the manager + // _host.Actions.AddChatText($"[Meta Debug] Received: {text}", 5); + + _lastChatText = text; + _lastChatTime = DateTime.Now; + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Meta/VTankMetaParser.cs b/Plugins/RynthAi/Meta/VTankMetaParser.cs new file mode 100644 index 0000000..4e8f40e --- /dev/null +++ b/Plugins/RynthAi/Meta/VTankMetaParser.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.IO; +using NexSuite.Plugins.RynthAi; + +namespace RynthAi.Meta +{ + public static class VTankMetaParser + { + public static List<MetaRule> IntelligentlyLoad(string path) + { + if (!File.Exists(path)) return new List<MetaRule>(); + + try + { + using (StreamReader reader = new StreamReader(path)) + { + string firstLine = reader.ReadLine(); + if (firstLine != "1") return null; // Not a valid VTank file format + + // Skip the 11-line header (CondAct schema metadata) + for (int i = 0; i < 11; i++) reader.ReadLine(); + + string countLine = reader.ReadLine(); + int ruleCount = int.Parse(countLine ?? "0"); + List<MetaRule> rules = new List<MetaRule>(); + + for (int i = 0; i < ruleCount; i++) + { + rules.Add(ParseCondAct(reader)); + } + return rules; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[RynthAi] Meta Load Error: {ex.Message}"); + return new List<MetaRule>(); + } + } + + private static MetaRule ParseCondAct(StreamReader reader) + { + MetaRule rule = new MetaRule(); + + // 1. CType (Condition Type - Integer) + reader.ReadLine(); // Consume 'i' type marker + rule.Condition = (MetaConditionType)int.Parse(reader.ReadLine()); + + // 2. AType (Action Type - Integer) + reader.ReadLine(); // Consume 'i' type marker + int vTankActionType = int.Parse(reader.ReadLine()); + + // Map VTank Action IDs to RynthAi Action Enums + if (vTankActionType == 1) rule.Action = MetaActionType.SetMetaState; + else if (vTankActionType == 2) rule.Action = MetaActionType.ChatCommand; + else if (vTankActionType == 3) rule.Action = MetaActionType.EmbeddedNavRoute; + + // 3. CData (Condition Data - Variant) + object cData = ReadVariant(reader); + + // Handle VTank Data Tables (Type 2) for complex conditions + if (cData is Dictionary<string, object> cDict) + { + // --- MONSTER COUNT TABLE --- + if (rule.Condition == MetaConditionType.MonsterNameCountWithinDistance) + { + string name = cDict.ContainsKey("n") ? cDict["n"].ToString() : ""; + string dist = cDict.ContainsKey("d") ? cDict["d"].ToString() : "0"; + string count = cDict.ContainsKey("c") ? cDict["c"].ToString() : "0"; + rule.ConditionData = $"{name},{dist},{count}"; + } + // --- INVENTORY COUNT TABLE --- + else if (rule.Condition == MetaConditionType.InventoryItemCount_LE || + rule.Condition == MetaConditionType.InventoryItemCount_GE) + { + string name = cDict.ContainsKey("n") ? cDict["n"].ToString() : ""; + string count = cDict.ContainsKey("c") ? cDict["c"].ToString() : "0"; + rule.ConditionData = $"{name},{count}"; + } + // --- SPELL TIME TABLE (NEW) --- + else if (rule.Condition == MetaConditionType.TimeLeftOnSpell_GE) + { + string id = cDict.ContainsKey("s") ? cDict["s"].ToString() : "0"; + string time = cDict.ContainsKey("t") ? cDict["t"].ToString() : "0"; + rule.ConditionData = $"{id},{time}"; + } + else + { + rule.ConditionData = "TableData"; // Fallback for unsupported tables + } + } + else + { + rule.ConditionData = cData?.ToString() ?? ""; + } + + // 4. AData (Action Data - Variant) + object aData = ReadVariant(reader); + rule.ActionData = aData?.ToString() ?? ""; + + // 5. State (The State this rule belongs to - String) + reader.ReadLine(); // Consume 's' type marker + rule.State = reader.ReadLine(); + + // 6. Check for recursion (Children for Group conditions like All/Any/Not) + if (rule.Condition == MetaConditionType.All || rule.Condition == MetaConditionType.Any || rule.Condition == MetaConditionType.Not) + { + string nextType = reader.ReadLine(); + if (nextType == "2") // Marker for the children table + { + // Skip table metadata (k, v, n, n) + for (int j = 0; j < 4; j++) reader.ReadLine(); + + int childCount = int.Parse(reader.ReadLine() ?? "0"); + for (int j = 0; j < childCount; j++) + { + // Consume the table index key, then parse the child rule + ReadVariant(reader); + rule.Children.Add(ParseCondAct(reader)); + } + } + } + + return rule; + } + + /// <summary> + /// Reads a VTank "Variant" which includes a type marker (s, i, d, 2, etc.) + /// followed by the data. This allows the parser to stay synchronized. + /// </summary> + private static object ReadVariant(StreamReader reader) + { + string typeMarker = reader.ReadLine(); + if (typeMarker == null) return null; + + // Handle standard scalar types + switch (typeMarker) + { + case "s": // String + case "i": // Integer + case "d": // Double + case "b": // Boolean + case "u": // Unsigned Int + case "f": // Float + return reader.ReadLine(); + + case "2": // Table / Dictionary + // Skip table metadata headers + for (int i = 0; i < 4; i++) reader.ReadLine(); + + int pairCount = int.Parse(reader.ReadLine() ?? "0"); + Dictionary<string, object> table = new Dictionary<string, object>(); + + for (int j = 0; j < pairCount; j++) + { + object key = ReadVariant(reader); + object val = ReadVariant(reader); + + if (key != null) + { + table[key.ToString()] = val; + } + } + return table; + + default: + return null; + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Nav/MovementActionHelper.cs b/Plugins/RynthAi/Nav/MovementActionHelper.cs new file mode 100644 index 0000000..8e6f8ef --- /dev/null +++ b/Plugins/RynthAi/Nav/MovementActionHelper.cs @@ -0,0 +1,310 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Direct calls to acclient.exe CM_Movement functions. + /// Derived entirely from Turbine's acclient.exe decompilation. + /// + /// Uses the same runtime pattern-scan approach as CombatActionHelper. + /// + /// ═══ TIER 1: CM_Movement server events (Proto_UI::SendToWeenie) ═══ + /// These send ordered game events to the server. They are __cdecl statics. + /// + /// Event_DoMovementCommand(motion, speed, hold_key) — opcode 0xF61E + /// Event_StopMovementCommand(motion, hold_key) — opcode 0xF661 + /// Event_Jump_NonAutonomous(extent) — opcode 0xF7C9 + /// Event_AutonomyLevel(level) — opcode 0xF752 + /// + /// All share the CM prologue: 83 EC 0C 53 56 57 E8 + /// Anchored by Event_StopMovementCommand (opcode 0xF661) which has a + /// unique-enough value in the CM_Movement cluster. + /// + /// ═══ TIER 2: CPhysicsObj::MoveToPosition (planned) ═══ + /// Client-side pathfinding via the player's physics object. + /// Requires tracing SmartBox::smartbox → player → MovementManager. + /// Would let the client handle all interpolation, heading, speed natively. + /// + /// ═══ TIER 3: MoveToManager queue (planned) ═══ + /// Direct movement node queue manipulation for maximum control. + /// + /// Motion constants (from acclient.exe motion tables): + /// 0x45000005 = MoveForward (WalkForward) + /// 0x45000006 = MoveBackward (WalkBackward) + /// 0x6500000D = TurnRight + /// 0x6500000E = TurnLeft + /// 0x41000003 = RunForward + /// + /// HoldKey values: + /// 0 = None + /// 1 = Run (hold shift) + /// 2 = AutoRun + /// </summary> + internal static class MovementActionHelper + { + // ── Motion constants ──────────────────────────────────────────────── + public const uint MOTION_WALK_FORWARD = 0x45000005; + public const uint MOTION_WALK_BACKWARD = 0x45000006; + public const uint MOTION_RUN_FORWARD = 0x41000003; + public const uint MOTION_TURN_RIGHT = 0x6500000D; + public const uint MOTION_TURN_LEFT = 0x6500000E; + public const uint MOTION_SIDESTEP_RIGHT = 0x6500000F; + public const uint MOTION_SIDESTEP_LEFT = 0x65000010; + + // ── HoldKey values ────────────────────────────────────────────────── + public const int HOLDKEY_NONE = 0; + public const int HOLDKEY_RUN = 1; + public const int HOLDKEY_AUTORUN = 2; + + // ── Delegate types ────────────────────────────────────────────────── + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelDoMovementCommand(uint motion, float speed, int holdKey); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelStopMovementCommand(uint motion, int holdKey); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelJumpNonAutonomous(float extent); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelAutonomyLevel(uint level); + + // ── Cached delegates ──────────────────────────────────────────────── + private static DelDoMovementCommand _doMovement; + private static DelStopMovementCommand _stopMovement; + private static DelJumpNonAutonomous _jumpNonAutonomous; + private static DelAutonomyLevel _autonomyLevel; + + private static bool _initialized; + private static Action<string> _log; + + // ── Shared prologue for CM_Movement functions ─────────────────────── + private static readonly byte[] CM_PROLOGUE = { 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8 }; + + /// <summary> + /// Pattern-scans acclient.exe for CM_Movement functions at runtime. + /// Call once at plugin startup (after CombatActionHelper.Initialize). + /// </summary> + public static void Initialize(Action<string> chatLog = null) + { + _log = chatLog; + + try + { + Process proc = Process.GetCurrentProcess(); + IntPtr baseAddr = IntPtr.Zero; + int imageSize = 0; + + foreach (ProcessModule mod in proc.Modules) + { + if (mod.ModuleName.Equals("acclient.exe", StringComparison.OrdinalIgnoreCase)) + { + baseAddr = mod.BaseAddress; + imageSize = mod.ModuleMemorySize; + break; + } + } + + if (baseAddr == IntPtr.Zero) + { + Log("Movement scan FAILED: acclient.exe not found"); + return; + } + + int textRva = 0x1000; + int textSize = Math.Min(imageSize - textRva, 0x400000); + IntPtr textBase = new IntPtr(baseAddr.ToInt32() + textRva); + byte[] text = new byte[textSize]; + Marshal.Copy(textBase, text, 0, textSize); + int textBaseVA = baseAddr.ToInt32() + textRva; + + // ── Anchor: StopMovementCommand via opcode 0xF661 ────────── + // This is unique enough in the CM_Movement region. + byte[] stopOpcode = { 0xC7, 0x02, 0x61, 0xF6, 0x00, 0x00 }; + int stopOpcodeOff = FindPattern(text, stopOpcode); + if (stopOpcodeOff < 0) + { + Log("Movement scan FAILED: StopMovementCommand opcode 0xF661 not found"); + return; + } + + int stopFuncOff = FindPrologueBefore(text, stopOpcodeOff); + if (stopFuncOff < 0) + { + Log("Movement scan FAILED: StopMovementCommand prologue not found"); + return; + } + + int stopVA = textBaseVA + stopFuncOff; + Log($"StopMovementCommand at 0x{stopVA:X8}"); + + // ── Search near StopMovementCommand for the others ───────── + // CM_Movement functions cluster within ~0x700 bytes + int regionStart = Math.Max(0, stopOpcodeOff - 0x700); + int regionEnd = Math.Min(text.Length, stopOpcodeOff + 0x300); + + // DoMovementCommand: opcode 0xF61E (63006 decimal) + byte[] doOpcode = { 0xC7, 0x02, 0x1E, 0xF6, 0x00, 0x00 }; + int doOpcodeOff = FindPatternInRegion(text, doOpcode, regionStart, regionEnd); + int doFuncOff = doOpcodeOff >= 0 ? FindPrologueBefore(text, doOpcodeOff) : -1; + + // Jump_NonAutonomous: opcode 0xF7C9 (63433 decimal) + byte[] jumpNAOpcode = { 0xC7, 0x02, 0xC9, 0xF7, 0x00, 0x00 }; + int jumpNAOff = FindPatternInRegion(text, jumpNAOpcode, regionStart, regionEnd); + int jumpNAFuncOff = jumpNAOff >= 0 ? FindPrologueBefore(text, jumpNAOff) : -1; + + // AutonomyLevel: opcode 0xF752 (63314 decimal) + byte[] autoLevelOpcode = { 0xC7, 0x02, 0x52, 0xF7, 0x00, 0x00 }; + int autoLevelOff = FindPatternInRegion(text, autoLevelOpcode, regionStart, regionEnd); + int autoLevelFuncOff = autoLevelOff >= 0 ? FindPrologueBefore(text, autoLevelOff) : -1; + + // ── Verify and create delegates ──────────────────────────── + if (doFuncOff < 0) + { + Log("Movement scan INCOMPLETE: DoMovementCommand not found"); + return; + } + + int doVA = textBaseVA + doFuncOff; + Log($"DoMovementCommand at 0x{doVA:X8}"); + + _stopMovement = (DelStopMovementCommand)Marshal.GetDelegateForFunctionPointer( + new IntPtr(stopVA), typeof(DelStopMovementCommand)); + _doMovement = (DelDoMovementCommand)Marshal.GetDelegateForFunctionPointer( + new IntPtr(doVA), typeof(DelDoMovementCommand)); + + if (jumpNAFuncOff >= 0) + { + int jumpNAVA = textBaseVA + jumpNAFuncOff; + _jumpNonAutonomous = (DelJumpNonAutonomous)Marshal.GetDelegateForFunctionPointer( + new IntPtr(jumpNAVA), typeof(DelJumpNonAutonomous)); + Log($"Jump_NonAutonomous at 0x{jumpNAVA:X8}"); + } + + if (autoLevelFuncOff >= 0) + { + int autoLevelVA = textBaseVA + autoLevelFuncOff; + _autonomyLevel = (DelAutonomyLevel)Marshal.GetDelegateForFunctionPointer( + new IntPtr(autoLevelVA), typeof(DelAutonomyLevel)); + Log($"AutonomyLevel at 0x{autoLevelVA:X8}"); + } + + _initialized = true; + Log("MovementActionHelper initialized — CM_Movement functions found via pattern scan"); + } + catch (Exception ex) + { + _initialized = false; + Log("MovementActionHelper init FAILED: " + ex.Message); + } + } + + public static bool IsInitialized => _initialized; + + // ══════════════════════════════════════════════════════════════════════ + // TIER 1 PUBLIC API — Server-side movement events + // ══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Sends a movement command to the server. + /// Replaces keyboard-driven movement for server authorization. + /// motion: one of MOTION_* constants + /// speed: 1.0 = normal, can scale + /// holdKey: HOLDKEY_NONE, HOLDKEY_RUN, or HOLDKEY_AUTORUN + /// </summary> + public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HOLDKEY_RUN) + { + if (!_initialized || _doMovement == null) return false; + try { return _doMovement(motion, speed, holdKey); } + catch (Exception ex) { Log("DoMovement failed: " + ex.Message); return false; } + } + + /// <summary> + /// Stops a specific movement command on the server. + /// motion: the motion to stop (same constant used in DoMovement) + /// holdKey: must match the holdKey used in the corresponding DoMovement + /// </summary> + public static bool StopMovement(uint motion, int holdKey = HOLDKEY_RUN) + { + if (!_initialized || _stopMovement == null) return false; + try { return _stopMovement(motion, holdKey); } + catch (Exception ex) { Log("StopMovement failed: " + ex.Message); return false; } + } + + /// <summary> + /// Non-autonomous jump with specified extent (0.0–1.0). + /// Replaces keyboard-simulated jump in RynthJumper. + /// </summary> + public static bool JumpNonAutonomous(float extent) + { + if (!_initialized || _jumpNonAutonomous == null) return false; + try { return _jumpNonAutonomous(Math.Max(0f, Math.Min(1f, extent))); } + catch (Exception ex) { Log("JumpNA failed: " + ex.Message); return false; } + } + + /// <summary> + /// Sets the autonomy level for the client. + /// 0 = server controls, 1 = client controls (normal play), 2 = full autonomy. + /// </summary> + public static bool SetAutonomyLevel(uint level) + { + if (!_initialized || _autonomyLevel == null) return false; + try { return _autonomyLevel(level); } + catch (Exception ex) { Log("AutonomyLevel failed: " + ex.Message); return false; } + } + + // ══════════════════════════════════════════════════════════════════════ + // PATTERN SCANNER (shared with CombatActionHelper design) + // ══════════════════════════════════════════════════════════════════════ + + private static int FindPattern(byte[] data, byte[] pattern) + { + return FindPatternInRegion(data, pattern, 0, data.Length); + } + + private static int FindPatternInRegion(byte[] data, byte[] pattern, int start, int end) + { + int limit = Math.Min(end, data.Length) - pattern.Length; + for (int i = Math.Max(0, start); i <= limit; i++) + { + bool match = true; + for (int j = 0; j < pattern.Length; j++) + { + if (data[i + j] != pattern[j]) { match = false; break; } + } + if (match) return i; + } + return -1; + } + + private static int FindPrologueBefore(byte[] data, int opcodeOffset) + { + for (int back = 1; back < 300; back++) + { + int pos = opcodeOffset - back; + if (pos < 1 || pos + CM_PROLOGUE.Length > data.Length) continue; + + bool match = true; + for (int j = 0; j < CM_PROLOGUE.Length; j++) + { + if (data[pos + j] != CM_PROLOGUE[j]) { match = false; break; } + } + + if (match) + { + byte prev = data[pos - 1]; + if (prev == 0xCC || prev == 0x90 || prev == 0xC3) + return pos; + } + } + return -1; + } + + private static void Log(string msg) + { + try { _log?.Invoke($"[RynthAi] {msg}"); } catch { } + } + } +} diff --git a/Plugins/RynthAi/Nav/NavigationManager.cs b/Plugins/RynthAi/Nav/NavigationManager.cs new file mode 100644 index 0000000..2cf6290 --- /dev/null +++ b/Plugins/RynthAi/Nav/NavigationManager.cs @@ -0,0 +1,1139 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using AcClient; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// VTank-faithful navigation engine. + /// + /// ARCHITECTURE: + /// Forward motion: SetAutorun(true/false) via Decal API. + /// - Player can toggle autorun off manually for immediate control. + /// - Re-asserted every 500ms as heartbeat. + /// + /// Steering while running: SetClientMotion(TurnRight/TurnLeft) via + /// AcClient command interpreter. These combine with autorun naturally + /// (like pressing W+A or W+D) without interrupting forward motion. + /// + /// Large turns (>60°): Stop autorun, snap Actions.Heading while + /// stopped, resume autorun once error is below 20°. + /// + /// Closest-approach detection prevents circling waypoints. + /// </summary> + public class NavigationManager + { + private readonly CoreManager _core; + private readonly UISettings _settings; + private readonly PluginHost _host; + + // ── Motion command constants (turns only — forward uses SetAutorun) ──── + private const uint MOTION_TURNRIGHT = 0x6500000D; + private const uint MOTION_TURNLEFT = 0x6500000E; + + // ── Nav tick ──────────────────────────────────────────────────────────── + private DateTime _lastNavTick = DateTime.MinValue; + private const double NAV_TICK_MS = 33.0; // ~30 Hz — smoother turn toggling + + // ── Stop debounce ─────────────────────────────────────────────────────── + private DateTime _stopRequestedAt = DateTime.MaxValue; + private const double STOP_DEBOUNCE_MS = 300.0; + + // ── Movement state ────────────────────────────────────────────────────── + private bool _isMovingForward = false; + private bool _hasStopped = true; + private bool _turnsStopped = true; + public bool DebugNav = false; + private DateTime _lastDebugPrint = DateTime.MinValue; + private double _lastGoodHeading = 0; + private bool _hasGoodHeading = false; // true = we've already stopped, don't repeat + + // ── W tap heartbeat — periodic safety tap ─────────────────────────────── + private DateTime _lastWTap = DateTime.MinValue; + private const double W_HEARTBEAT_MS = 500.0; + + // ── Turning state ─────────────────────────────────────────────────────── + private bool _isTurning = false; + + // ── Heading thresholds (from settings — tunable in Advanced → Navigation) ── + private double DeadZone => Math.Max(0.5, _settings.NavDeadZone); + private double BigTurnEnter => Math.Max(5.0, _settings.NavStopTurnAngle); + private double BigTurnExit => Math.Max(1.0, Math.Min(_settings.NavResumeTurnAngle, BigTurnEnter - 1)); + private double SweepMult => Math.Max(1.0, _settings.NavSweepMult); + + // ── Arrival / lookahead ───────────────────────────────────────────────── + private double ArrivalYards => Math.Max(1.5, _settings.FollowNavMin); + private double LookaheadYards => ArrivalYards * 0.1; + + // ── Closest approach tracking ─────────────────────────────────────────── + // Detects when we've passed a waypoint even if we never entered the + // arrival radius (turn radius at speed is too wide). If distance was + // decreasing and starts increasing, we've swept past — advance. + private double _prevDist = double.MaxValue; + + // ── Route bookkeeping ─────────────────────────────────────────────────── + private int _linearDir = 1; + private bool _inPause = false; + private DateTime _pauseUntil = DateTime.MinValue; + private bool _actionFired = false; + private DateTime _actionExpiry = DateTime.MinValue; + private const double ACTION_TIMEOUT_MS = 10000.0; + + // ── Portal/Recall state machine ───────────────────────────────────────── + private enum PortalState + { + None, + Settling, + EquippingWand, + EnteringMagicMode, + CastingSpell, + WaitingForPortalOrTeleport, + WaitingForPortalExit, + PostTeleportSettle // Brief pause after teleporting to cancel UseItem effects + } + private PortalState _portalState = PortalState.None; + private DateTime _portalStateStart = DateTime.MinValue; + private int _preCastLandblock = 0; + private int _prePortalLandblock = 0; + private double _prePortalNS = double.NaN; + private double _prePortalEW = double.NaN; + private const double PORTAL_STATE_TIMEOUT_MS = 15000.0; + private const double SETTLE_DELAY_MS = 600.0; + private const double WAND_EQUIP_DELAY_MS = 1000.0; + private const double MAGIC_MODE_DELAY_MS = 800.0; + private const double CAST_DELAY_MS = 500.0; + private const double PORTAL_WAIT_MS = 3000.0; + + // ── Stuck watchdog ────────────────────────────────────────────────────── + private double _watchdogNS = double.NaN; + private double _watchdogEW = double.NaN; + private DateTime _watchdogNext = DateTime.MinValue; + private int _stuckCount = 0; + private bool _inRecovery = false; + private DateTime _recoveryUntil = DateTime.MinValue; + private const double WATCHDOG_MS = 5000.0; + private const double STUCK_YD = 2.0; + private const double RECOVERY_MS = 1200.0; + + // ── Tier 2 state (MoveToPosition via MovementManager) ───────────────── + private int _tier2TargetIdx = -1; // waypoint index we last issued MoveToPosition for + private bool _tier2Active = false; // true while a Tier2 MoveToPosition is in flight + private DateTime _tier2IssuedAt = DateTime.MinValue; + + // ── Win32 (focus detection only) ──────────────────────────────────────── + [DllImport("user32.dll")] + private static extern IntPtr GetForegroundWindow(); + + public bool IsReversed { get; set; } = false; + public void SetReverse(bool reverse) { IsReversed = reverse; } + + private IntPtr _gameHwnd = IntPtr.Zero; + private IntPtr GameHwnd + { + get + { + if (_gameHwnd == IntPtr.Zero) + _gameHwnd = Process.GetCurrentProcess().MainWindowHandle; + return _gameHwnd; + } + } + + private bool IsGameFocused() => GetForegroundWindow() == GameHwnd; + + public NavigationManager(CoreManager core, UISettings settings, PluginHost host) + { + _core = core; + _settings = settings; + _host = host; + } + + // ══════════════════════════════════════════════════════════════════════════ + // CLIENT MOTION + W TAP + // ══════════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Direct client memory motion — same as UB's setmotion. + /// Used ONCE to establish forward motion state. + /// </summary> + private unsafe void SetClientMotion(uint motion, bool on) + { + try + { + ((ACCmdInterp*)(*SmartBox.smartbox)->cmdinterp)->SetMotion(motion, on); + } + catch { } + } + + /// <summary> + private void StartForward() + { + if (!_isMovingForward) + { + try { _core.Actions.SetAutorun(true); } catch { } + _isMovingForward = true; + } + } + + private void StopForward() + { + try { _core.Actions.SetAutorun(false); } catch { } + _isMovingForward = false; + } + + private void StopMovement() + { + _isTurning = false; + StopForward(); + ClearTurnMotions(); + CancelTier2(); + } + + private void CancelTier2() + { + if (_tier2Active) + { + try { Tier2MovementHelper.CancelMoveTo(); } catch { } + _tier2Active = false; + } + _tier2TargetIdx = -1; + } + + private void ClearTurnMotions() + { + SetClientMotion(MOTION_TURNRIGHT, false); + SetClientMotion(MOTION_TURNLEFT, false); + } + + // ══════════════════════════════════════════════════════════════════════════ + // PUBLIC ENTRY POINT + // ══════════════════════════════════════════════════════════════════════════ + + private bool _tier2ModeLoggedOnce = false; + + public void ProcessNavigation(bool isFighting) + { + // One-shot: dump UB's SmartBox pointer chain vs our pattern-scanned one + if (_settings.MovementMode == 2 && !_tier2ModeLoggedOnce) + { + _tier2ModeLoggedOnce = true; + Tier2Log.Log($"MODE 2 ACTIVE: macro={_settings.IsMacroRunning} " + + $"nav={_settings.EnableNavigation} state={_settings.CurrentState}"); + } + // The priority dispatcher in PluginCore already controls call order. + // Nav only needs to check: macro running, nav enabled, and state is available. + // "Idle" means no higher-priority system claimed this frame. + // "Navigating" means WE claimed it last frame and are still going. + bool shouldNav = _settings.IsMacroRunning + && _settings.EnableNavigation + && (_settings.CurrentState == "Idle" || _settings.CurrentState == "Navigating"); + + if (!shouldNav) + { + if (!_hasStopped && !_turnsStopped) + { try { ClearTurnMotions(); } catch { } _turnsStopped = true; } + if (_stopRequestedAt == DateTime.MaxValue) + _stopRequestedAt = DateTime.Now; + if ((DateTime.Now - _stopRequestedAt).TotalMilliseconds >= STOP_DEBOUNCE_MS) + { + if (!_hasStopped) + { + CancelTier2(); + try { _core.Actions.SetAutorun(false); } catch { } + _isMovingForward = false; + _isTurning = false; + _hasStopped = true; + } + } + return; + } + _stopRequestedAt = DateTime.MaxValue; + _hasStopped = false; + _turnsStopped = false; + + var route = _settings.CurrentRoute; + if (route == null || route.Points.Count == 0) { StopMovement(); return; } + + // Claim the traffic light — we are actively navigating + _settings.CurrentState = "Navigating"; + + // Rate limit to ~15 Hz + if ((DateTime.Now - _lastNavTick).TotalMilliseconds < NAV_TICK_MS) return; + _lastNavTick = DateTime.Now; + + int idx = _settings.ActiveNavIndex; + if (!IndexValid(idx, route)) { HandleRouteEnd(route); return; } + + UpdateWatchdog(); + if (_inRecovery) + { + if (DateTime.Now >= _recoveryUntil) _inRecovery = false; + return; + } + + var pt = route.Points[idx]; + + // ── Pause ─────────────────────────────────────────────────────────── + if (pt.Type == NavPointType.Pause) + { + StopMovement(); + if (!_inPause) { _inPause = true; _pauseUntil = DateTime.Now.AddMilliseconds(pt.PauseTimeMs); } + if (DateTime.Now >= _pauseUntil) { _inPause = false; Advance(route); } + return; + } + + // ── Chat ──────────────────────────────────────────────────────────── + if (pt.Type == NavPointType.Chat) + { + StopMovement(); + if (!_actionFired) + { + _actionFired = true; + try { _core.Actions.InvokeChatParser(pt.ChatCommand); } catch { } + Advance(route); + } + return; + } + + // ── Recall / PortalNPC ────────────────────────────────────────────── + if (pt.Type == NavPointType.Recall || pt.Type == NavPointType.PortalNPC) + { + if (_portalState == PortalState.None) StopMovement(); + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + try { _host.Actions.AddChatText($"[NavDbg] PORTAL state={_portalState} elapsed={(DateTime.Now - _portalStateStart).TotalMilliseconds:F0}ms", 1); } catch { } + } + ProcessPortalAction(pt, route); + return; + } + + // ── Standard coordinate waypoint ──────────────────────────────────── + _actionFired = false; + _inPause = false; + + var pos = GetPos(); + if (pos == null) return; + + double dNS = pt.NS - pos.NorthSouth; + double dEW = pt.EW - pos.EastWest; + double dist = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + + if (dist < ArrivalYards) + { + _prevDist = double.MaxValue; + Advance(route); + return; + } + + // ── Tier 2: delegate to client physics engine ──────────────────── + if (_settings.MovementMode == 2 && Tier2MovementHelper.IsInitialized) + { + try + { + Tier2Log.Log("T2 CHECK: calling GetPlayerCellId"); + uint _t2cell = Tier2MovementHelper.GetPlayerCellId(); + Tier2Log.Log($"T2 CHECK: cell=0x{_t2cell:X8} outdoor={(_t2cell & 0xFFFF) < 0x100}"); + Tier2MovementHelper.LogPointerChain(); // after cellId succeeds + if ((_t2cell & 0xFFFF) < 0x100) + { + ProcessTier2Waypoint(idx, pt, route, pos, dist); + return; + } + } + catch (Exception ex) + { + Tier2Log.Log($"T2 CHECK CRASHED: {ex}"); + // Fall through to Legacy + } + } + + // ── Closest approach detection (Tier 0/1 only) ─────────────────── + // If we were getting closer (within a reasonable range) and now + // we're moving away, we've swept past the waypoint. Advance. + // This handles the case where the turn radius at speed prevents + // the character from entering the arrival radius exactly. + if (_prevDist < ArrivalYards * SweepMult && dist > _prevDist + 0.3) + { + _prevDist = double.MaxValue; + Advance(route); + return; + } + _prevDist = dist; + + // ── Lookahead blend ───────────────────────────────────────────────── + double tNS = pt.NS, tEW = pt.EW; + if (dist < LookaheadYards) + { + int ni = PeekNext(idx, route); + if (ni >= 0) + { + var np = route.Points[ni]; + double t = 1.0 - (dist / LookaheadYards); + tNS = Lerp(pt.NS, np.NS, t); + tEW = Lerp(pt.EW, np.EW, t); + } + } + + // ── Compute heading error ─────────────────────────────────────────── + double desiredDeg = Math.Atan2(tEW - pos.EastWest, tNS - pos.NorthSouth) * (180.0 / Math.PI); + if (desiredDeg < 0) desiredDeg += 360.0; + + double rawHeading = 0; + try { rawHeading = _core.Actions.Heading; } catch { } + double currentDeg; + if (rawHeading != 0.0) + { currentDeg = rawHeading; _lastGoodHeading = rawHeading; _hasGoodHeading = true; } + else if (_hasGoodHeading) + { currentDeg = _lastGoodHeading; } + else + { currentDeg = desiredDeg; } + double error = NormalizeAngle(desiredDeg - currentDeg); + double absError = Math.Abs(error); + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + string turnDir = absError < DeadZone ? "NONE" : (error > 0 ? "RIGHT" : "LEFT"); + double ox = 0, oy = 0; + try { var me = _core.WorldFilter[_core.CharacterFilter.Id]; if (me != null) { var o = me.Offset(); ox = o.X; oy = o.Y; } } catch { } + try { _host.Actions.AddChatText($"[NavDbg] raw={rawHeading:F1} cur={currentDeg:F1} des={desiredDeg:F1} err={error:F1} turn={turnDir} dist={dist:F1}yd oX={ox:F2} oY={oy:F2}", 1); } catch { } + } + + // ═════════════════════════════════════════════════════════════════════ + // STEERING + // ═════════════════════════════════════════════════════════════════════ + + // ── STATE: Turning in place (big turn while stopped) ───────────────── + if (_isTurning) + { + if (absError > BigTurnExit) + { + try { _core.Actions.Heading = (float)desiredDeg; } catch { } + return; + } + + // Close enough — clear turn keys, start running + _isTurning = false; + ClearTurnMotions(); + StartForward(); + return; + } + + // ── BIG TURN (>60°): stop and face ────────────────────────────────── + if (absError > BigTurnEnter) + { + StopForward(); + ClearTurnMotions(); + try { _core.Actions.Heading = (float)desiredDeg; } catch { } + _isTurning = true; + return; + } + + // ── Ensure we're moving forward ───────────────────────────────────── + StartForward(); + + // ── Near waypoint: stop turning, just run straight ─────────────────── + bool closeToWaypoint = dist < ArrivalYards * SweepMult; + + // ── SMALL CORRECTION: use TurnRight/TurnLeft while running ────────── + // These combine with Forward at the command interpreter level — + // the character turns while running naturally, like pressing W+A or W+D. + // No Actions.Heading, no motion interrupt, no W tap needed. + if (absError > DeadZone && !closeToWaypoint) + { + if (error > 0) + { + // Need to turn right + SetClientMotion(MOTION_TURNRIGHT, true); + SetClientMotion(MOTION_TURNLEFT, false); + } + else + { + // Need to turn left + SetClientMotion(MOTION_TURNLEFT, true); + SetClientMotion(MOTION_TURNRIGHT, false); + } + } + else + { + // On course or close to waypoint — stop turning + ClearTurnMotions(); + } + + // ── HEARTBEAT: re-assert autorun periodically as safety net ───────── + if (_isMovingForward && (DateTime.Now - _lastWTap).TotalMilliseconds > W_HEARTBEAT_MS) + { + try { _core.Actions.SetAutorun(true); } catch { } + _lastWTap = DateTime.Now; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // ROUTE ADVANCEMENT + // ══════════════════════════════════════════════════════════════════════════ + + private void Advance(VTankNavParser route) + { + _actionFired = false; + _prevDist = double.MaxValue; + switch (route.RouteType) + { + case NavRouteType.Circular: + _settings.ActiveNavIndex = (_settings.ActiveNavIndex + 1) % route.Points.Count; + break; + case NavRouteType.Linear: + int n = _settings.ActiveNavIndex + _linearDir; + if (n < 0 || n >= route.Points.Count) { _linearDir = -_linearDir; n = _settings.ActiveNavIndex + _linearDir; } + _settings.ActiveNavIndex = n; + break; + case NavRouteType.Once: + _settings.ActiveNavIndex++; + if (_settings.ActiveNavIndex >= route.Points.Count) { _settings.EnableNavigation = false; StopMovement(); } + break; + case NavRouteType.Follow: + _settings.ActiveNavIndex = 0; + break; + } + } + + private void HandleRouteEnd(VTankNavParser route) + { + if (route.RouteType == NavRouteType.Circular) _settings.ActiveNavIndex = 0; + else StopMovement(); + } + + private int PeekNext(int cur, VTankNavParser route) + { + switch (route.RouteType) + { + case NavRouteType.Circular: return (cur + 1) % route.Points.Count; + case NavRouteType.Linear: int n = cur + _linearDir; return (n >= 0 && n < route.Points.Count) ? n : -1; + case NavRouteType.Once: return (cur + 1 < route.Points.Count) ? cur + 1 : -1; + default: return -1; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // TIER 2 MOVEMENT (CPhysicsObj::MoveToPosition via MovementManager) + // ══════════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Tier 2 waypoint processor — issues a single MoveToPosition call to the + /// client's physics engine, then lets it handle all interpolation and heading. + /// Re-issues the call on waypoint change or if no progress after timeout. + /// </summary> + private void ProcessTier2Waypoint( + int idx, NavPoint pt, VTankNavParser route, + CoordsObject pos, double distYards) + { + // ── Closest approach detection (shared with Tier 0/1) ──────────── + if (_prevDist < ArrivalYards * SweepMult && distYards > _prevDist + 0.3) + { + _prevDist = double.MaxValue; + CancelTier2(); + Advance(route); + return; + } + _prevDist = distYards; + + // ── Decide whether to issue / re-issue the MoveToPosition call ─── + bool needsIssue = false; + + if (idx != _tier2TargetIdx) + { + // Waypoint changed — cancel old movement, issue new + CancelTier2(); + needsIssue = true; + } + else if (_tier2Active && + (DateTime.Now - _tier2IssuedAt).TotalMilliseconds > _settings.T2ReissueMs) + { + // Timeout — re-issue in case the client gave up + CancelTier2(); + needsIssue = true; + } + else if (!_tier2Active) + { + needsIssue = true; + } + + if (needsIssue) + { + IssueTier2Move(pt, pos); + _tier2TargetIdx = idx; + } + + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + try + { + _host.Actions.AddChatText( + $"[NavDbg] T2 idx={idx} dist={distYards:F1}yd active={_tier2Active} " + + $"age={(DateTime.Now - _tier2IssuedAt).TotalMilliseconds:F0}ms", 1); + } + catch { } + } + } + + /// <summary> + /// Converts Decal NS/EW to internal AC coordinates and calls MoveToPosition. + /// Works by adding the yard-delta to the player's known-good internal position, + /// then normalizing cell/landblock boundaries with Math.Floor (critical for + /// negative deltas — (int) rounds toward zero, not down, producing garbage cells). + /// </summary> + private void IssueTier2Move(NavPoint pt, CoordsObject decalPos) + { + try + { + uint playerCell; + float playerX, playerY, playerZ; + if (!Tier2MovementHelper.GetPlayerPosition( + out playerCell, out playerX, out playerY, out playerZ)) + return; + + if ((playerCell & 0xFFFF) >= 0x100) + return; // indoor — caller shouldn't have sent us here + + double deltaEW = (pt.EW - decalPos.EastWest) * 240.0; + double deltaNS = (pt.NS - decalPos.NorthSouth) * 240.0; + double deltaDist = Math.Sqrt(deltaEW * deltaEW + deltaNS * deltaNS); + double maxRange = Math.Max(10.0, _settings.T2MaxRangeYd); + if (deltaDist > maxRange) + { + double scale = maxRange / deltaDist; + deltaEW *= scale; + deltaNS *= scale; + } + + int pLbEW = (int)((playerCell >> 24) & 0xFF); + int pLbNS = (int)((playerCell >> 16) & 0xFF); + + // Player origin is LANDBLOCK-relative (0–192 yards), NOT cell-relative + double globalEW = pLbEW * 192.0 + playerX + deltaEW; + double globalNS = pLbNS * 192.0 + playerY + deltaNS; + + int tLbEW = (int)Math.Floor(globalEW / 192.0); + int tLbNS = (int)Math.Floor(globalNS / 192.0); + tLbEW = Math.Max(0, Math.Min(254, tLbEW)); + tLbNS = Math.Max(0, Math.Min(254, tLbNS)); + + // Target origin: landblock-relative (0–192), same as how AC stores it + double inLbEW = globalEW - tLbEW * 192.0; + double inLbNS = globalNS - tLbNS * 192.0; + + // Cell index is derived from position but origin stays landblock-relative + int tColEW = Math.Max(0, Math.Min(7, (int)Math.Floor(inLbEW / 24.0))); + int tRowNS = Math.Max(0, Math.Min(7, (int)Math.Floor(inLbNS / 24.0))); + + float localX = Math.Max(0.5f, Math.Min(191.5f, (float)inLbEW)); + float localY = Math.Max(0.5f, Math.Min(191.5f, (float)inLbNS)); + float localZ = playerZ; + + int cellIdx = tRowNS * 8 + tColEW + 1; + uint targetCell = (uint)((tLbEW << 24) | (tLbNS << 16) | cellIdx); + + int maxLb = Math.Max(1, _settings.T2MaxLandblocks); + if (Math.Abs(tLbEW - pLbEW) > maxLb || Math.Abs(tLbNS - pLbNS) > maxLb) + { + Tier2Log.Log($"SKIP: lb ({tLbEW},{tLbNS}) too far from ({pLbEW},{pLbNS})"); + return; + } + + Tier2Log.Log($"ISSUE: 0x{targetCell:X8} local=({localX:F1},{localY:F1},{localZ:F1}) " + + $"delta=({deltaEW:F0},{deltaNS:F0})yd spd={_settings.T2Speed} dist={_settings.T2DistanceTo} walk={_settings.T2WalkWithinYd}"); + + uint result = Tier2MovementHelper.MoveToPosition( + targetCell, localX, localY, localZ, + Math.Max(0.1f, _settings.T2Speed), + Math.Max(0.1f, _settings.T2DistanceTo), + Math.Max(0f, _settings.T2WalkWithinYd)); + + _tier2Active = (result == 0); + _tier2IssuedAt = DateTime.Now; + Tier2Log.Log($"RESULT: {result}"); + } + catch (Exception ex) + { + Tier2Log.Log($"ISSUE EXCEPTION: {ex}"); + } + } + + private void ProcessPortalAction(NavPoint pt, VTankNavParser route) + { + // Timeout check - if we've been in this portal action too long, reset and advance + if (_portalState != PortalState.None) + { + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > PORTAL_STATE_TIMEOUT_MS) + { + ResetPortalState(); + Advance(route); + return; + } + } + + // Initialize state machine — go to Settling first to let turns stop + if (_portalState == PortalState.None) + { + _portalState = PortalState.Settling; + _portalStateStart = DateTime.Now; + _preCastLandblock = GetCurrentLandblock(); + // Store position for teleport detection + try { var p = GetPos(); if (p != null) { _prePortalNS = p.NorthSouth; _prePortalEW = p.EastWest; } } catch { } + // Aggressively clear ALL motion + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + try { _core.Actions.SetCombatMode(CombatState.Peace); } catch { } + _isMovingForward = false; + _isTurning = false; + return; + } + + switch (_portalState) + { + case PortalState.Settling: + // Keep clearing turns every frame until settled + try { ClearTurnMotions(); } catch { } + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > SETTLE_DELAY_MS) + { + _portalState = PortalState.EquippingWand; + _portalStateStart = DateTime.Now; + } + break; + + case PortalState.EquippingWand: + ProcessEquippingWand(pt); + break; + + case PortalState.EnteringMagicMode: + ProcessEnteringMagicMode(); + break; + + case PortalState.CastingSpell: + ProcessCastingSpell(pt); + break; + + case PortalState.WaitingForPortalOrTeleport: + ProcessWaitingForPortalOrTeleport(pt, route); + break; + + case PortalState.WaitingForPortalExit: + ProcessWaitingForPortalExit(route); + break; + + case PortalState.PostTeleportSettle: + // Hammer stop commands to cancel any lingering UseItem walk action + // UseItem walk persists through teleportation in the AC client — need + // to keep hammering for ~2s until it expires on its own + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + try { _core.Actions.SetCombatMode(CombatState.Peace); } catch { } + _isMovingForward = false; + _isTurning = false; + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > 4000) + { + ResetPortalState(); + Advance(route); + } + break; + } + } + + private void ProcessEquippingWand(NavPoint pt) + { + // Only equip wand for recall spells, not portal NPCs + if (pt.Type == NavPointType.PortalNPC) + { + _portalState = PortalState.WaitingForPortalOrTeleport; + _portalStateStart = DateTime.Now; + _prePortalLandblock = GetCurrentLandblock(); + try { var p = GetPos(); if (p != null) { _prePortalNS = p.NorthSouth; _prePortalEW = p.EastWest; } } catch { } + + // Use the portal NPC — partial name matching + try + { + WorldObject bestMatch = null; + foreach (WorldObject wo in _core.WorldFilter.GetLandscape()) + { + if (wo == null) continue; + if (wo.Name == pt.TargetName) { bestMatch = wo; break; } + if (wo.Name != null && pt.TargetName != null && + (wo.Name.Contains(pt.TargetName) || pt.TargetName.Contains(wo.Name))) + { bestMatch = wo; } + } + if (bestMatch != null) + _core.Actions.UseItem(bestMatch.Id, 0); + } + catch { } + return; + } + + // For recall spells, equip a wand if needed + double elapsed = (DateTime.Now - _portalStateStart).TotalMilliseconds; + + if (elapsed < 50) + { + try + { + // Check if wand already equipped — UseItem on equipped wand UNEQUIPS it + bool wandEquipped = false; + int wandToEquip = 0; + + // Scan all known objects for wands + foreach (WorldObject wo in _core.WorldFilter.GetInventory()) + { + if (wo.ObjectClass == ObjectClass.WandStaffOrb) + { + int slots = wo.Values(LongValueKey.EquippedSlots, 0); + if (slots != 0) + { + wandEquipped = true; + break; + } + else if (wandToEquip == 0) + { + wandToEquip = wo.Id; // remember first unequipped wand + } + } + } + + if (!wandEquipped && wandToEquip != 0) + { + _core.Actions.UseItem(wandToEquip, 0); + if (DebugNav) try { _host.Actions.AddChatText($"[NavDbg] WAND equipping id={wandToEquip}", 1); } catch { } + } + else if (wandEquipped) + { + if (DebugNav) try { _host.Actions.AddChatText("[NavDbg] WAND already equipped, skipping", 1); } catch { } + } + else + { + if (DebugNav) try { _host.Actions.AddChatText("[NavDbg] WAND none found in inventory!", 1); } catch { } + } + } + catch { } + } + + // Wait for wand equip to complete, then proceed to magic mode + if (elapsed > WAND_EQUIP_DELAY_MS) + { + _portalState = PortalState.EnteringMagicMode; + _portalStateStart = DateTime.Now; + } + } + + private void ProcessEnteringMagicMode() + { + // Enter magic casting mode + try + { + _core.Actions.SetCombatMode(CombatState.Magic); + } + catch { } + + // Wait a moment for mode change, then proceed + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > MAGIC_MODE_DELAY_MS) + { + _portalState = PortalState.CastingSpell; + _portalStateStart = DateTime.Now; + } + } + + private void ProcessCastingSpell(NavPoint pt) + { + // Cast the recall spell + if ((DateTime.Now - _portalStateStart).TotalMilliseconds < 100) // Only cast once + { + try + { + _core.Actions.CastSpell(pt.SpellId, _core.CharacterFilter.Id); + } + catch { } + } + + // Wait a moment for cast, then proceed to waiting + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > CAST_DELAY_MS) + { + _portalState = PortalState.WaitingForPortalOrTeleport; + _portalStateStart = DateTime.Now; + _prePortalLandblock = GetCurrentLandblock(); + } + } + + private void ProcessWaitingForPortalOrTeleport(NavPoint pt, VTankNavParser route) + { + // Detect teleport by checking if we moved far from pre-portal position + try + { + var pos = GetPos(); + if (pos != null && !double.IsNaN(_prePortalNS)) + { + double dNS = pos.NorthSouth - _prePortalNS; + double dEW = pos.EastWest - _prePortalEW; + double distFromStart = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + + if (distFromStart > 50.0) // moved > 50 yards = definitely teleported + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + } + } + catch { } + + // Also check landblock as fallback + int currentLandblock = GetCurrentLandblock(); + if (currentLandblock != _prePortalLandblock && currentLandblock != 0 && _prePortalLandblock != 0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + + // For PortalNPC: no short timeout — let UseItem walk complete. + // The global PORTAL_STATE_TIMEOUT_MS (15s) handles overall timeout. + // For Recall: use shorter timeout since teleport should be instant. + if (pt.Type == NavPointType.Recall) + { + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > PORTAL_WAIT_MS) + { + ResetPortalState(); + Advance(route); + } + } + } + + private void ProcessWaitingForPortalExit(VTankNavParser route) + { + // Distance-based teleport detection + try + { + var pos = GetPos(); + if (pos != null && !double.IsNaN(_prePortalNS)) + { + double dNS = pos.NorthSouth - _prePortalNS; + double dEW = pos.EastWest - _prePortalEW; + double distFromStart = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + if (distFromStart > 50.0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + } + } + catch { } + + // Landblock fallback + int currentLandblock = GetCurrentLandblock(); + if (currentLandblock != _prePortalLandblock && currentLandblock != 0 && _prePortalLandblock != 0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + } + } + + private void ResetPortalState() + { + _portalState = PortalState.None; + _portalStateStart = DateTime.MinValue; + _preCastLandblock = 0; + _prePortalLandblock = 0; + _prePortalNS = double.NaN; + _prePortalEW = double.NaN; + + // Return to peace mode after portal/recall + try + { + _core.Actions.SetCombatMode(CombatState.Peace); + } + catch { } + } + + private int GetCurrentLandblock() + { + try + { + var pos = GetPos(); + if (pos != null) + { + // Landblock is the high word of the location + // AC coordinates encode landblock in a specific way + // For simplicity, we'll use a combination of NS/EW rounded to detect changes + int nsBlock = (int)(pos.NorthSouth / 0.8); + int ewBlock = (int)(pos.EastWest / 0.8); + return (nsBlock << 16) | (ewBlock & 0xFFFF); + } + } + catch { } + return 0; + } + + private void FireSpecialAction(NavPoint pt) + { + // Legacy method - now mostly unused, kept for compatibility + try + { + if (pt.Type == NavPointType.Recall) + _core.Actions.CastSpell(pt.SpellId, _core.CharacterFilter.Id); + else if (pt.Type == NavPointType.PortalNPC) + { + foreach (WorldObject wo in _core.WorldFilter.GetLandscape()) + { + if (wo != null && wo.Name == pt.TargetName) { _core.Actions.UseItem(wo.Id, 0); break; } + } + } + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // STUCK WATCHDOG + // ══════════════════════════════════════════════════════════════════════════ + + private void UpdateWatchdog() + { + if (DateTime.Now < _watchdogNext) return; + _watchdogNext = DateTime.Now.AddMilliseconds(WATCHDOG_MS); + + var pos = GetPos(); + if (pos == null) return; + + double curNS = pos.NorthSouth, curEW = pos.EastWest; + + if (!double.IsNaN(_watchdogNS) && _isMovingForward) + { + bool dataStale = Math.Abs(curNS - _watchdogNS) < 0.000001 + && Math.Abs(curEW - _watchdogEW) < 0.000001 + && !IsGameFocused(); + + if (!dataStale) + { + double dN = curNS - _watchdogNS, dE = curEW - _watchdogEW; + double moved = Math.Sqrt(dN * dN + dE * dE) * 240.0; + if (moved < STUCK_YD) { _stuckCount++; BeginRecovery(); } + else _stuckCount = 0; + } + } + _watchdogNS = curNS; _watchdogEW = curEW; + } + + private void BeginRecovery() + { + _inRecovery = true; + _recoveryUntil = DateTime.Now.AddMilliseconds(RECOVERY_MS); + StopMovement(); + + // Jump to try to unstick + try + { + if (MovementActionHelper.IsInitialized) + { + // Tier 1: direct jump call — no keyboard/motion interpreter dependency + MovementActionHelper.JumpNonAutonomous(0.5f); + } + else + { + // Legacy: local motion command for jump + SetClientMotion(0x2500003b, true); + SetClientMotion(0x2500003b, false); + } + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // PUBLIC LIFECYCLE + // ══════════════════════════════════════════════════════════════════════════ + + public void Stop() + { + _inPause = false; _actionFired = false; _inRecovery = false; + _linearDir = 1; _stopRequestedAt = DateTime.MaxValue; + ResetPortalState(); + CancelTier2(); + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + _isMovingForward = false; + _isTurning = false; + _hasStopped = true; + _turnsStopped = true; + } + + public void ResetRouteState() + { + Stop(); + _stuckCount = 0; + _prevDist = double.MaxValue; + _watchdogNS = double.NaN; _watchdogEW = double.NaN; + _hasGoodHeading = false; + } + + public int FindNearestWaypoint(VTankNavParser route) + { + if (route == null || route.Points == null || route.Points.Count == 0) + return 0; + + try + { + var pos = GetPos(); + if (pos == null) + return 0; + + double myNS = pos.NorthSouth; + double myEW = pos.EastWest; + + int nearestIdx = 0; + double nearestDist = double.MaxValue; + + for (int i = 0; i < route.Points.Count; i++) + { + var pt = route.Points[i]; + // Only consider regular waypoints, not special actions + if (pt.Type == NavPointType.Point) + { + double dNS = pt.NS - myNS; + double dEW = pt.EW - myEW; + double dist = Math.Sqrt(dNS * dNS + dEW * dEW); + + if (dist < nearestDist) + { + nearestDist = dist; + nearestIdx = i; + } + } + } + + return nearestIdx; + } + catch + { + return 0; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // UTILITIES + // ══════════════════════════════════════════════════════════════════════════ + + private bool IndexValid(int i, VTankNavParser r) => r?.Points != null && i >= 0 && i < r.Points.Count; + + private CoordsObject GetPos() + { + try { return _core.WorldFilter[_core.CharacterFilter.Id].Coordinates(); } + catch { return null; } + } + + private static double NormalizeAngle(double a) + { + while (a > 180.0) a -= 360.0; + while (a < -180.0) a += 360.0; + return a; + } + + private static double Lerp(double a, double b, double t) => a + (b - a) * t; + } +} diff --git a/Plugins/RynthAi/Nav/Tier2Log.cs b/Plugins/RynthAi/Nav/Tier2Log.cs new file mode 100644 index 0000000..e789f5c --- /dev/null +++ b/Plugins/RynthAi/Nav/Tier2Log.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Crash-safe file logger. Every write flushes immediately so the last + /// line survives a hard client crash. Writes to RynthAi\Logs\tier2.log, + /// rolls over at 1 MB. + /// </summary> + internal static class Tier2Log + { + private static readonly string LogDir = + @"C:\Games\DecalPlugins\NexSuite\RynthAi\Logs"; + private static readonly string LogPath = + Path.Combine(LogDir, "tier2.log"); + private const long MAX_SIZE = 1024 * 1024; // 1 MB rollover + + private static readonly object _lock = new object(); + private static bool _initialized; + + /// <summary> + /// Write a timestamped line to tier2.log. Safe to call from any thread. + /// </summary> + public static void Log(string msg) + { + try + { + lock (_lock) + { + EnsureDir(); + Rollover(); + using (var sw = new StreamWriter(LogPath, true)) + { + sw.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] {msg}"); + sw.Flush(); + } + } + } + catch { } + } + + /// <summary> + /// Write a separator + header for a new session. + /// </summary> + public static void StartSession() + { + Log("════════════════════════════════════════════════════════════"); + Log($"Session start — {DateTime.Now:yyyy-MM-dd HH:mm:ss}"); + } + + private static void EnsureDir() + { + if (!_initialized) + { + if (!Directory.Exists(LogDir)) + Directory.CreateDirectory(LogDir); + _initialized = true; + } + } + + private static void Rollover() + { + try + { + if (File.Exists(LogPath) && new FileInfo(LogPath).Length > MAX_SIZE) + { + string backup = LogPath + ".old"; + if (File.Exists(backup)) File.Delete(backup); + File.Move(LogPath, backup); + } + } + catch { } + } + } +} diff --git a/Plugins/RynthAi/Nav/Tier2MovementHelper.cs b/Plugins/RynthAi/Nav/Tier2MovementHelper.cs new file mode 100644 index 0000000..72b1c3b --- /dev/null +++ b/Plugins/RynthAi/Nav/Tier2MovementHelper.cs @@ -0,0 +1,942 @@ +using System; +using System.Diagnostics; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Security; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Tier 2 movement: calls MovementManager::PerformMovement directly on the + /// player's CPhysicsObj. The client's own pathfinding handles interpolation, + /// heading, speed — producing smooth arcs instead of autorun + PD-controller + /// correction jitter. + /// + /// Pointer chain (all from acclient.exe decompilation + binary verification): + /// [SmartBox::smartbox] → SmartBox* + /// [SmartBox+0xF8] → CPhysicsObj* (player) + /// [player+0xC4] → MovementManager* + /// PerformMovement(__thiscall, const MovementStruct*) + /// + /// MovementTypes (from MovementStruct.type): + /// 6 = MoveToObject — approach a world object + /// 7 = MoveToPosition — walk/run to an (x,y,z) in a landblock cell + /// 8 = TurnToObject — face a world object + /// 9 = TurnToHeading — face a compass heading (degrees) + /// + /// All structs are stack-allocated in unmanaged memory, filled, passed to the + /// native function, then freed. No persistent allocations. + /// + /// Pattern scans (version-independent): + /// PerformMovement — anchored by its unique return-71 epilogue + /// CancelMoveTo — immediately follows PerformMovement (reads [ecx+4]) + /// Position vtable — found in CPhysicsObj::MoveToObject's stack init + /// MovParams vtable — found in MovementParameters constructor (writes speed=1.0) + /// </summary> + internal static class Tier2MovementHelper + { + // ═══════════════════════════════════════════════════════════════════════ + // MOVEMENT TYPE CONSTANTS + // ═══════════════════════════════════════════════════════════════════════ + + public const uint TYPE_MOVE_TO_OBJECT = 6; + public const uint TYPE_MOVE_TO_POSITION = 7; + public const uint TYPE_TURN_TO_OBJECT = 8; + public const uint TYPE_TURN_TO_HEADING = 9; + + // ═══════════════════════════════════════════════════════════════════════ + // STRUCT SIZES & OFFSETS + // ═══════════════════════════════════════════════════════════════════════ + + // ── SmartBox ────────────────────────────────────────────────────────── + private const int SB_PLAYER_ID = 0xF4; + private const int SB_PLAYER = 0xF8; + private const int SB_CMDINTERP = 0xB8; + + // ── CPhysicsObj ─────────────────────────────────────────────────────── + private const int PO_POSITION = 0x48; // Position (embedded, 72 bytes — starts at vtable) + private const int PO_MOVEMENT_MGR = 0xC4; // MovementManager* + + // ── MovementStruct (0x64 = 100 bytes) ──────────────────────────────── + private const int MS_SIZE = 0x64; + private const int MS_TYPE = 0x00; // uint MovementTypes::Type + private const int MS_MOTION = 0x04; // uint motion + private const int MS_OBJECT_ID = 0x08; // uint object_id + private const int MS_TOP_LEVEL_ID = 0x0C; // uint top_level_id + private const int MS_POS = 0x10; // Position (72 bytes, embedded) + private const int MS_RADIUS = 0x58; // float radius + private const int MS_HEIGHT = 0x5C; // float height + private const int MS_PARAMS = 0x60; // MovementParameters* (pointer) + + // ── Position (0x48 = 72 bytes, embedded inside MovementStruct) ─────── + // Relative to MS_POS: + // Frame layout: quaternion(16) → cache/matrix(36) → origin(12) + // (verified from binary: origin at Pos+0x3C, not Pos+0x18) + private const int POS_VTABLE = 0x00; // Position_vtbl* + private const int POS_OBJCELL_ID = 0x04; // uint32 landblock cell + private const int POS_QW = 0x08; // float Frame.qw (quaternion w) + private const int POS_QX = 0x0C; // float Frame.qx + private const int POS_QY = 0x10; // float Frame.qy + private const int POS_QZ = 0x14; // float Frame.qz + private const int POS_CACHE = 0x18; // float[9] (3×3 rotation matrix, 36 bytes) + private const int POS_ORIGIN_X = 0x3C; // float Frame.m_fOrigin.x + private const int POS_ORIGIN_Y = 0x40; // float Frame.m_fOrigin.y + private const int POS_ORIGIN_Z = 0x44; // float Frame.m_fOrigin.z + + // ── MovementParameters (0x2C = 44 bytes) ──────────────────────────── + private const int MP_SIZE = 0x2C; + private const int MP_VTABLE = 0x00; // MovementParameters_vtbl* + private const int MP_BITFIELD = 0x04; // uint flags + private const int MP_DIST_TO_OBJ = 0x08; // float distance_to_object + private const int MP_MIN_DIST = 0x0C; // float min_distance + private const int MP_HEADING = 0x10; // float desired_heading + private const int MP_SPEED = 0x14; // float speed + private const int MP_FAIL_DIST = 0x18; // float fail_distance + private const int MP_WR_THRESH = 0x1C; // float walk_run_threshhold + private const int MP_CONTEXT_ID = 0x20; // uint context_id + private const int MP_HOLD_KEY = 0x24; // int hold_key_to_apply + private const int MP_ACTION_STAMP = 0x28; // uint action_stamp + + // ── MovementParameters defaults (from acclient.exe statics) ────────── + private const uint MP_DEFAULT_BITFIELD = 0x0001EE1F; // 0x10 bit = always autorun speed + private const float MP_DEFAULT_DIST_OBJ = 0.6f; + private const float MP_DEFAULT_MIN_DIST = 0.0f; + private const float MP_DEFAULT_FAIL_DIST = float.MaxValue; + private const float MP_DEFAULT_WR_THRESH = 0.0f; // 0 = never walk, always run + private const float MP_DEFAULT_SPEED = 1.0f; + + // ═══════════════════════════════════════════════════════════════════════ + // NATIVE DELEGATES + // ═══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// MovementManager::PerformMovement(const MovementStruct*) + /// __thiscall — ECX = MovementManager*, stack arg = MovementStruct* + /// Returns 0 on success, non-zero error code on failure. + /// </summary> + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate uint DelPerformMovement(IntPtr thisPtr, IntPtr movementStruct); + + /// <summary> + /// MovementManager::CancelMoveTo(unsigned int err) + /// __thiscall — ECX = MovementManager*, stack arg = error code + /// Error 0 = cancelled by user. + /// </summary> + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void DelCancelMoveTo(IntPtr thisPtr, uint err); + + // ═══════════════════════════════════════════════════════════════════════ + // CACHED STATE + // ═══════════════════════════════════════════════════════════════════════ + + private static DelPerformMovement _performMovement; + private static DelCancelMoveTo _cancelMoveTo; + + private static IntPtr _smartboxStaticAddr; // Address of SmartBox::smartbox global + private static IntPtr _positionVtable; // Position::`vftable' address + private static IntPtr _movParamsVtable; // MovementParameters::`vftable' address + + private static bool _initialized; + private static Action<string> _log; + + public static bool IsInitialized => _initialized; + + // ═══════════════════════════════════════════════════════════════════════ + // INITIALIZATION (pattern scan) + // ═══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Scans acclient.exe at runtime for MovementManager functions and + /// struct vtable addresses. Call once at plugin startup, after + /// CombatActionHelper and MovementActionHelper have initialized. + /// + /// smartboxAddr: if non-zero, use this as SmartBox::smartbox static + /// address instead of pattern scanning (pass UB's SmartBox.smartbox + /// pointer address for guaranteed correctness). + /// </summary> + public static void Initialize(Action<string> chatLog = null, IntPtr smartboxAddr = default) + { + _log = chatLog; + + try + { + Process proc = Process.GetCurrentProcess(); + IntPtr baseAddr = IntPtr.Zero; + int imageSize = 0; + + foreach (ProcessModule mod in proc.Modules) + { + if (mod.ModuleName.Equals("acclient.exe", StringComparison.OrdinalIgnoreCase)) + { + baseAddr = mod.BaseAddress; + imageSize = mod.ModuleMemorySize; + break; + } + } + + if (baseAddr == IntPtr.Zero) + { + Log("Tier2 scan FAILED: acclient.exe not found"); + return; + } + + int textRva = 0x1000; + int textSize = Math.Min(imageSize - textRva, 0x400000); + IntPtr textBase = new IntPtr(baseAddr.ToInt32() + textRva); + byte[] text = new byte[textSize]; + Marshal.Copy(textBase, text, 0, textSize); + int textBaseVA = baseAddr.ToInt32() + textRva; + + // ── 1. Find MovementManager::PerformMovement ───────────────── + // Unique epilogue: pop edi; mov eax, 71; pop esi; ret 4 + // Hex: 5F B8 47 00 00 00 5E C2 04 00 + byte[] pmEpilogue = { 0x5F, 0xB8, 0x47, 0x00, 0x00, 0x00, 0x5E, 0xC2, 0x04, 0x00 }; + int pmEpiOff = -1; + + // PerformMovement is in the MovementManager code region (~0x520000–0x530000) + // Narrow the search to avoid false positives in unrelated code. + for (int i = 0; i < text.Length - pmEpilogue.Length; i++) + { + if (!BytesMatch(text, i, pmEpilogue)) continue; + + // Verify: the function should start with push esi; push edi; mov esi, ecx + // (56 57 8B F1) preceded by CC/90/C3 padding. + int funcOff = FindFuncStartBefore(text, i, + new byte[] { 0x56, 0x57, 0x8B, 0xF1 }); + if (funcOff >= 0) + { + // Extra verify: function reads [esi+0x08] (physics_obj) then pushes 1 + // Pattern at funcOff+4: 8B 4E 08 6A 01 + if (funcOff + 9 < text.Length && + text[funcOff + 4] == 0x8B && + text[funcOff + 5] == 0x4E && + text[funcOff + 6] == 0x08 && + text[funcOff + 7] == 0x6A && + text[funcOff + 8] == 0x01) + { + pmEpiOff = funcOff; + break; + } + } + } + + if (pmEpiOff < 0) + { + Log("Tier2 scan FAILED: PerformMovement not found"); + return; + } + + int pmVA = textBaseVA + pmEpiOff; + Log($"PerformMovement at 0x{pmVA:X8}"); + _performMovement = (DelPerformMovement)Marshal.GetDelegateForFunctionPointer( + new IntPtr(pmVA), typeof(DelPerformMovement)); + + // ── 2. Find CancelMoveTo ───────────────────────────────────── + // Immediately after PerformMovement's ret — small function: + // 8B 49 04 mov ecx, [ecx+4] (moveto_manager at MM+0x04) + // 85 C9 test ecx, ecx + // 74 XX jz skip + // E9 XX jmp MoveToManager::CancelMoveTo + // C2 04 00 ret 4 + // Search forward from the epilogue for this pattern. + int cancelOff = -1; + int searchFrom = pmEpiOff + pmEpilogue.Length; + // Search up to 128 bytes past the epilogue — the switch jump table + // data sits between PerformMovement's ret and CancelMoveTo's start. + for (int i = searchFrom; i < Math.Min(searchFrom + 128, text.Length - 8); i++) + { + if (text[i] == 0x8B && text[i + 1] == 0x49 && text[i + 2] == 0x04 && + text[i + 3] == 0x85 && text[i + 4] == 0xC9 && text[i + 5] == 0x74) + { + cancelOff = i; + break; + } + } + + if (cancelOff < 0) + { + Log("Tier2 scan WARNING: CancelMoveTo not found (non-fatal)"); + } + else + { + int cancelVA = textBaseVA + cancelOff; + Log($"CancelMoveTo at 0x{cancelVA:X8}"); + _cancelMoveTo = (DelCancelMoveTo)Marshal.GetDelegateForFunctionPointer( + new IntPtr(cancelVA), typeof(DelCancelMoveTo)); + } + + // ── 3. Find SmartBox::smartbox static address ──────────────── + if (smartboxAddr != IntPtr.Zero) + { + // Caller provided the address (e.g. from UB's AcClient.SmartBox) + _smartboxStaticAddr = smartboxAddr; + Log($"SmartBox::smartbox at 0x{_smartboxStaticAddr.ToInt32():X8} (provided by caller)"); + } + else + { + // Fall back to pattern scan + _smartboxStaticAddr = FindSmartBoxStatic(text, textBaseVA, baseAddr.ToInt32()); + if (_smartboxStaticAddr == IntPtr.Zero) + { + Log("Tier2 scan FAILED: SmartBox::smartbox static not found"); + return; + } + Log($"SmartBox::smartbox at 0x{_smartboxStaticAddr.ToInt32():X8} (pattern scan)"); + } + + // ── 4. Find Position vtable ────────────────────────────────── + // CPhysicsObj movement functions init a stack Position with: + // C7 44 24 XX [vtable] ← .rdata pointer + // C7 44 24 XX 00 00 00 00 ← objcell_id = 0 + // C7 44 24 XX 00 00 80 3F ← qw = 1.0f + // Search callers of PerformMovement for this pattern. + _positionVtable = FindPositionVtable(text, textBaseVA, pmVA); + if (_positionVtable == IntPtr.Zero) + { + Log("Tier2 scan FAILED: Position vtable not found"); + return; + } + Log($"Position vtable at 0x{_positionVtable.ToInt32():X8}"); + + // ── 5. Find MovementParameters vtable ──────────────────────── + // MovementParameters constructor writes vtable then speed = 1.0: + // C7 00 [vtable] ← mov [eax], vtable + // ... + // C7 40 14 00 00 80 3F ← mov [eax+0x14], 1.0f (speed) + _movParamsVtable = FindMovParamsVtable(text, textBaseVA); + if (_movParamsVtable == IntPtr.Zero) + { + Log("Tier2 scan FAILED: MovementParameters vtable not found"); + return; + } + Log($"MovParams vtable at 0x{_movParamsVtable.ToInt32():X8}"); + + _initialized = true; + Log("Tier2MovementHelper initialized — all addresses found via pattern scan"); + Tier2Log.StartSession(); + Tier2Log.Log($"PerformMovement=0x{pmVA:X8} SmartBox=0x{_smartboxStaticAddr.ToInt32():X8} " + + $"PosVT=0x{_positionVtable.ToInt32():X8} MpVT=0x{_movParamsVtable.ToInt32():X8}"); + } + catch (Exception ex) + { + _initialized = false; + Log("Tier2 init FAILED: " + ex.Message); + } + } + + // ═══════════════════════════════════════════════════════════════════════ + // PUBLIC API + // ═══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Tells the client's physics engine to walk/run to a world position. + /// The client handles all interpolation, heading changes, and speed + /// internally — no frame-by-frame steering required. + /// + /// Parameters use AC's internal coordinate system: + /// objcell_id — landblock cell (e.g. 0xABCD0012 for outdoor cell) + /// x, y, z — local position within the cell (yards) + /// speed — movement speed multiplier (1.0 = normal) + /// distTo — stop this far from the target (yards, default 0.6) + /// + /// Returns 0 on success, non-zero error code on failure. + /// </summary> + [HandleProcessCorruptedStateExceptions, SecurityCritical] + public static uint MoveToPosition( + uint objcell_id, float x, float y, float z, + float speed = 1.0f, float distTo = 0.5f, float walkRunThreshold = 15f) + { + if (!_initialized || _performMovement == null) return uint.MaxValue; + + LogPointerChain(); // once — logs the full chain to file + + IntPtr mm = GetMovementManager(); + if (mm == IntPtr.Zero) + { + Tier2Log.Log("MoveToPosition: MovementManager is NULL — aborting"); + return uint.MaxValue; + } + + IntPtr msPtr = IntPtr.Zero; + IntPtr mpPtr = IntPtr.Zero; + try + { + msPtr = Marshal.AllocHGlobal(MS_SIZE); + mpPtr = Marshal.AllocHGlobal(MP_SIZE); + ZeroMemory(msPtr, MS_SIZE); + ZeroMemory(mpPtr, MP_SIZE); + + // ── MovementParameters ──────────────────────────────────────── + WriteMovementParams(mpPtr, speed, distTo, 0f, walkRunThreshold); + + // ── MovementStruct ──────────────────────────────────────────── + Marshal.WriteInt32(msPtr + MS_TYPE, (int)TYPE_MOVE_TO_POSITION); + WritePosition(msPtr + MS_POS, objcell_id, x, y, z, 1f, 0f, 0f, 0f); + Marshal.WriteIntPtr(msPtr + MS_PARAMS, mpPtr); + + Tier2Log.Log($"MoveToPosition CALL: mm=0x{mm.ToInt32():X8} cell=0x{objcell_id:X8} " + + $"x={x:F2} y={y:F2} z={z:F2} speed={speed} distTo={distTo} wrTh={walkRunThreshold}"); + + uint result = _performMovement(mm, msPtr); + + Tier2Log.Log($"MoveToPosition RETURNED: {result}"); + return result; + } + catch (Exception ex) + { + Tier2Log.Log($"MoveToPosition EXCEPTION: {ex}"); + Log("MoveToPosition failed: " + ex.Message); + return uint.MaxValue; + } + finally + { + if (msPtr != IntPtr.Zero) Marshal.FreeHGlobal(msPtr); + if (mpPtr != IntPtr.Zero) Marshal.FreeHGlobal(mpPtr); + } + } + + /// <summary> + /// Tells the client's physics engine to approach a world object by ID. + /// The client tracks the object's position and adjusts the path. + /// </summary> + public static uint MoveToObject( + uint objectId, float speed = 1.0f, float distTo = 0.5f) + { + if (!_initialized || _performMovement == null) return uint.MaxValue; + + IntPtr mm = GetMovementManager(); + if (mm == IntPtr.Zero) return uint.MaxValue; + + IntPtr msPtr = IntPtr.Zero; + IntPtr mpPtr = IntPtr.Zero; + try + { + msPtr = Marshal.AllocHGlobal(MS_SIZE); + mpPtr = Marshal.AllocHGlobal(MP_SIZE); + ZeroMemory(msPtr, MS_SIZE); + ZeroMemory(mpPtr, MP_SIZE); + + WriteMovementParams(mpPtr, speed, distTo, 0f); + + Marshal.WriteInt32(msPtr + MS_TYPE, (int)TYPE_MOVE_TO_OBJECT); + Marshal.WriteInt32(msPtr + MS_OBJECT_ID, (int)objectId); + WriteIdentityPosition(msPtr + MS_POS); + Marshal.WriteIntPtr(msPtr + MS_PARAMS, mpPtr); + + return _performMovement(mm, msPtr); + } + catch (Exception ex) + { + Log("MoveToObject failed: " + ex.Message); + return uint.MaxValue; + } + finally + { + if (msPtr != IntPtr.Zero) Marshal.FreeHGlobal(msPtr); + if (mpPtr != IntPtr.Zero) Marshal.FreeHGlobal(mpPtr); + } + } + + /// <summary> + /// Tells the client to turn the player to face a compass heading. + /// heading: 0 = North, 90 = East, 180 = South, 270 = West (degrees). + /// </summary> + public static uint TurnToHeading(float heading, float speed = 1.0f) + { + if (!_initialized || _performMovement == null) return uint.MaxValue; + + IntPtr mm = GetMovementManager(); + if (mm == IntPtr.Zero) return uint.MaxValue; + + IntPtr msPtr = IntPtr.Zero; + IntPtr mpPtr = IntPtr.Zero; + try + { + msPtr = Marshal.AllocHGlobal(MS_SIZE); + mpPtr = Marshal.AllocHGlobal(MP_SIZE); + ZeroMemory(msPtr, MS_SIZE); + ZeroMemory(mpPtr, MP_SIZE); + + // For TurnToHeading, the heading goes in MovementParameters.desired_heading + WriteMovementParams(mpPtr, speed, 0f, heading); + + Marshal.WriteInt32(msPtr + MS_TYPE, (int)TYPE_TURN_TO_HEADING); + WriteIdentityPosition(msPtr + MS_POS); + Marshal.WriteIntPtr(msPtr + MS_PARAMS, mpPtr); + + return _performMovement(mm, msPtr); + } + catch (Exception ex) + { + Log("TurnToHeading failed: " + ex.Message); + return uint.MaxValue; + } + finally + { + if (msPtr != IntPtr.Zero) Marshal.FreeHGlobal(msPtr); + if (mpPtr != IntPtr.Zero) Marshal.FreeHGlobal(mpPtr); + } + } + + /// <summary> + /// Cancels any in-progress MoveToPosition / MoveToObject / TurnToHeading. + /// Safe to call if nothing is in progress. + /// </summary> + public static void CancelMoveTo() + { + if (!_initialized || _cancelMoveTo == null) return; + try + { + IntPtr mm = GetMovementManager(); + if (mm != IntPtr.Zero) + _cancelMoveTo(mm, 0); + } + catch (Exception ex) + { + Log("CancelMoveTo failed: " + ex.Message); + } + } + + /// <summary> + /// Returns true if the player has a MovementManager and its MoveToManager + /// is non-null (meaning some Tier 2 movement is potentially active). + /// </summary> + public static bool IsMovingTo() + { + try + { + IntPtr mm = GetMovementManager(); + if (mm == IntPtr.Zero) return false; + // MoveToManager* at MovementManager+0x04 + IntPtr mtm = Marshal.ReadIntPtr(mm + 0x04); + return mtm != IntPtr.Zero; + } + catch { return false; } + } + + /// <summary> + /// Reads the player's current internal Position struct. + /// Uses Marshal.ReadInt32 + BitConverter (safe) instead of unsafe pointers + /// to avoid SEH crashes that bypass managed try/catch. + /// </summary> + [HandleProcessCorruptedStateExceptions, SecurityCritical] + public static bool GetPlayerPosition( + out uint objcell_id, out float x, out float y, out float z) + { + objcell_id = 0; x = y = z = 0; + try + { + IntPtr player = GetPlayerPtr(); + if (player == IntPtr.Zero) return false; + + IntPtr pos = new IntPtr(player.ToInt32() + PO_POSITION); + objcell_id = (uint)Marshal.ReadInt32(pos + POS_OBJCELL_ID); + x = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_X)); + y = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Y)); + z = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Z)); + return true; + } + catch (Exception ex) + { + Tier2Log.Log($"GetPlayerPos EXCEPTION: {ex.Message}"); + return false; + } + } + + /// <summary>Reinterpret int32 bits as float (safe alternative to unsafe pointer cast).</summary> + private static float IntToFloat(int bits) + { + byte[] b = BitConverter.GetBytes(bits); + return BitConverter.ToSingle(b, 0); + } + + /// <summary> + /// Returns the player's current landblock cell ID, or 0 if unavailable. + /// HPCSE attribute required: Marshal.ReadInt32 is unsafe under the hood — + /// AccessViolationException is a Corrupted State Exception on .NET 4.8 + /// and bypasses normal try/catch without this attribute. + /// </summary> + [HandleProcessCorruptedStateExceptions, SecurityCritical] + public static uint GetPlayerCellId() + { + try + { + IntPtr sb = Marshal.ReadIntPtr(_smartboxStaticAddr); + if (sb == IntPtr.Zero) return 0; + + IntPtr player = Marshal.ReadIntPtr(sb + SB_PLAYER); + if (player == IntPtr.Zero) return 0; + + return (uint)Marshal.ReadInt32(new IntPtr( + player.ToInt32() + PO_POSITION + POS_OBJCELL_ID)); + } + catch (Exception ex) + { + Tier2Log.Log($"GetPlayerCellId CRASHED: {ex.GetType().Name}: {ex.Message}"); + return 0; + } + } + + // ═══════════════════════════════════════════════════════════════════════ + // POINTER CHAIN HELPERS + // ═══════════════════════════════════════════════════════════════════════ + + [HandleProcessCorruptedStateExceptions, SecurityCritical] + private static IntPtr GetSmartBox() + { + try + { + if (_smartboxStaticAddr == IntPtr.Zero) return IntPtr.Zero; + return Marshal.ReadIntPtr(_smartboxStaticAddr); + } + catch (Exception ex) + { + Tier2Log.Log($"GetSmartBox CRASHED: {ex.GetType().Name}"); + return IntPtr.Zero; + } + } + + [HandleProcessCorruptedStateExceptions, SecurityCritical] + private static IntPtr GetPlayerPtr() + { + try + { + IntPtr sb = GetSmartBox(); + if (sb == IntPtr.Zero) return IntPtr.Zero; + return Marshal.ReadIntPtr(sb + SB_PLAYER); + } + catch (Exception ex) + { + Tier2Log.Log($"GetPlayerPtr CRASHED: {ex.GetType().Name}"); + return IntPtr.Zero; + } + } + + [HandleProcessCorruptedStateExceptions, SecurityCritical] + private static IntPtr GetMovementManager() + { + try + { + IntPtr player = GetPlayerPtr(); + if (player == IntPtr.Zero) return IntPtr.Zero; + return Marshal.ReadIntPtr(player + PO_MOVEMENT_MGR); + } + catch (Exception ex) + { + Tier2Log.Log($"GetMovementManager CRASHED: {ex.GetType().Name}"); + return IntPtr.Zero; + } + } + + /// <summary> + /// Logs the full pointer chain once. Call before first movement. + /// </summary> + private static bool _chainLogged; + [HandleProcessCorruptedStateExceptions, SecurityCritical] + public static void LogPointerChain() + { + if (_chainLogged) return; + _chainLogged = true; + try + { + IntPtr sb = Marshal.ReadIntPtr(_smartboxStaticAddr); + IntPtr player = (sb != IntPtr.Zero) ? Marshal.ReadIntPtr(sb + SB_PLAYER) : IntPtr.Zero; + IntPtr mm = (player != IntPtr.Zero) ? Marshal.ReadIntPtr(player + PO_MOVEMENT_MGR) : IntPtr.Zero; + uint cell = 0; float px = 0, py = 0, pz = 0; + if (player != IntPtr.Zero) + { + IntPtr pos = new IntPtr(player.ToInt32() + PO_POSITION); + cell = (uint)Marshal.ReadInt32(pos + POS_OBJCELL_ID); + px = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_X)); + py = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Y)); + pz = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Z)); + } + Tier2Log.Log($"CHAIN: [0x{_smartboxStaticAddr.ToInt32():X8}]→sb=0x{sb.ToInt32():X8} " + + $"[sb+0x{SB_PLAYER:X2}]→player=0x{player.ToInt32():X8} " + + $"[player+0x{PO_MOVEMENT_MGR:X2}]→mm=0x{mm.ToInt32():X8}"); + Tier2Log.Log($"CHAIN: playerPos cell=0x{cell:X8} origin=({px:F2},{py:F2},{pz:F2})"); + } + catch (Exception ex) + { + Tier2Log.Log($"CHAIN FAILED: {ex.GetType().Name}: {ex.Message}"); + _chainLogged = false; // retry next time + } + } + + // ═══════════════════════════════════════════════════════════════════════ + // STRUCT WRITERS + // ═══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Fills a 44-byte MovementParameters at the given unmanaged address. + /// walkRunThreshold: distance in yards at which to switch from run to walk. + /// 0 = always run. Default AC value is 15.0. + /// </summary> + private static void WriteMovementParams( + IntPtr ptr, float speed, float distTo, float heading, float walkRunThreshold = 15f) + { + Marshal.WriteIntPtr(ptr + MP_VTABLE, _movParamsVtable); + WriteInt(ptr + MP_BITFIELD, MP_DEFAULT_BITFIELD); + WriteFloat(ptr + MP_DIST_TO_OBJ, distTo); + WriteFloat(ptr + MP_MIN_DIST, MP_DEFAULT_MIN_DIST); + WriteFloat(ptr + MP_HEADING, heading); + WriteFloat(ptr + MP_SPEED, speed); + WriteFloat(ptr + MP_FAIL_DIST, MP_DEFAULT_FAIL_DIST); + WriteFloat(ptr + MP_WR_THRESH, walkRunThreshold); + WriteInt(ptr + MP_CONTEXT_ID, 0); + WriteInt(ptr + MP_HOLD_KEY, 0); // 0 = let walk_run_threshold decide + WriteInt(ptr + MP_ACTION_STAMP, 0); + } + + /// <summary> + /// Fills a 72-byte Position at the given unmanaged address. + /// Computes the Frame cache (3×3 rotation matrix from quaternion). + /// </summary> + private static void WritePosition( + IntPtr ptr, uint objcell_id, + float x, float y, float z, + float qw, float qx, float qy, float qz) + { + Marshal.WriteIntPtr(ptr + POS_VTABLE, _positionVtable); + WriteInt(ptr + POS_OBJCELL_ID, objcell_id); + WriteFloat(ptr + POS_QW, qw); + WriteFloat(ptr + POS_QX, qx); + WriteFloat(ptr + POS_QY, qy); + WriteFloat(ptr + POS_QZ, qz); + WriteFloat(ptr + POS_ORIGIN_X, x); + WriteFloat(ptr + POS_ORIGIN_Y, y); + WriteFloat(ptr + POS_ORIGIN_Z, z); + + // Frame::cache — quaternion → 3×3 rotation matrix (row-major) + float xx = qx * qx, yy = qy * qy, zz = qz * qz; + float xy = qx * qy, xz = qx * qz, yz = qy * qz; + float wx = qw * qx, wy = qw * qy, wz = qw * qz; + + IntPtr c = ptr + POS_CACHE; + WriteFloat(c + 0x00, 1f - 2f * (yy + zz)); // m00 + WriteFloat(c + 0x04, 2f * (xy - wz)); // m01 + WriteFloat(c + 0x08, 2f * (xz + wy)); // m02 + WriteFloat(c + 0x0C, 2f * (xy + wz)); // m10 + WriteFloat(c + 0x10, 1f - 2f * (xx + zz)); // m11 + WriteFloat(c + 0x14, 2f * (yz - wx)); // m12 + WriteFloat(c + 0x18, 2f * (xz - wy)); // m20 + WriteFloat(c + 0x1C, 2f * (yz + wx)); // m21 + WriteFloat(c + 0x20, 1f - 2f * (xx + yy)); // m22 + } + + /// <summary> + /// Writes an identity Position (objcell_id=0, identity quaternion). + /// </summary> + private static void WriteIdentityPosition(IntPtr ptr) + { + WritePosition(ptr, 0, 0f, 0f, 0f, 1f, 0f, 0f, 0f); + } + + // ═══════════════════════════════════════════════════════════════════════ + // PATTERN SCAN HELPERS + // ═══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Finds SmartBox::smartbox by looking for the Cleanup pattern: + /// A1 [addr] ; load smartbox + /// 85 C0 ; test eax, eax + /// 74 XX ; jz skip + /// ... ; vtable destructor call + /// C7 05 [addr] 00 00 00 00 ; store 0 to smartbox + /// C3 ; ret + /// </summary> + private static IntPtr FindSmartBoxStatic(byte[] text, int textBaseVA, int imageBase) + { + int dataLo = imageBase + 0x400000; // rough .data start + int dataHi = imageBase + 0x510000; // rough .data end + + // Search for: C7 05 [addr] 00 00 00 00 C3 + // where [addr] is also loaded with A1 [addr] within 30 bytes before + for (int i = 0; i < text.Length - 12; i++) + { + if (text[i] != 0xC7 || text[i + 1] != 0x05) continue; + int addr = BitConverter.ToInt32(text, i + 2); + if (addr < dataLo || addr > dataHi) continue; + // Check imm32 = 0 and next byte = C3 (ret) + if (BitConverter.ToInt32(text, i + 6) != 0) continue; + if (text[i + 10] != 0xC3) continue; + + // Verify: A1 [same addr] appears within 40 bytes before + byte[] loadPat = new byte[5]; + loadPat[0] = 0xA1; + BitConverter.GetBytes(addr).CopyTo(loadPat, 1); + for (int back = 5; back < 40; back++) + { + int j = i - back; + if (j < 0) break; + if (BytesMatch(text, j, loadPat)) + { + // Also verify: 85 C0 (test eax,eax) appears after the load + for (int k = j + 5; k < j + 10 && k < text.Length - 1; k++) + { + if (text[k] == 0x85 && text[k + 1] == 0xC0) + { + // Extra verify: the load is near a vtable dtor call + // SmartBox::Cleanup does: lea ecx,[eax+4]; mov eax,[ecx]; + // push 1; call [eax] — the push 1 is the destructor flag, + // distinguishing this from other cleanup patterns. + bool hasDtorCall = false; + for (int m = k; m < i - 2 && m < text.Length - 3; m++) + { + if (text[m] == 0x6A && text[m + 1] == 0x01 && + text[m + 2] == 0xFF && text[m + 3] == 0x10) + { + hasDtorCall = true; // push 1; call [eax] + break; + } + } + if (hasDtorCall) + return new IntPtr(addr); + } + } + } + } + } + return IntPtr.Zero; + } + + /// <summary> + /// Finds Position::`vftable' by scanning PerformMovement callers + /// for the stack-init pattern that writes a .rdata pointer followed + /// by objcell_id=0 then qw=1.0f. + /// </summary> + private static IntPtr FindPositionVtable(byte[] text, int textBaseVA, int pmVA) + { + int rdataLo = textBaseVA + 0x390000; // .rdata region + int rdataHi = rdataLo + 0x80000; + + // Find callers of PerformMovement (E8 relative calls) + for (int i = 0; i < text.Length - 5; i++) + { + if (text[i] != 0xE8) continue; + int rel = BitConverter.ToInt32(text, i + 1); + int target = textBaseVA + i + 5 + rel; + if (target != pmVA) continue; + + // Found a caller. Search backwards up to 300 bytes for: + // C7 44 24 XX [rdata_addr] (Position vtable) + // C7 44 24 YY 00 00 00 00 (objcell_id = 0) + // C7 44 24 ZZ 00 00 80 3F (qw = 1.0f) + int searchStart = Math.Max(0, i - 300); + for (int j = searchStart; j < i - 8; j++) + { + // Look for C7 44 24 XX followed by .rdata address + if (text[j] != 0xC7 || text[j + 1] != 0x44 || text[j + 2] != 0x24) + continue; + int val = BitConverter.ToInt32(text, j + 4); + if (val < rdataLo || val > rdataHi) continue; + + // Check: within 16 bytes, there should be C7 44 24 XX 00 00 80 3F (qw=1.0) + for (int k = j + 8; k < Math.Min(j + 40, i); k++) + { + if (text[k] == 0xC7 && text[k + 1] == 0x44 && text[k + 2] == 0x24 && + text[k + 4] == 0x00 && text[k + 5] == 0x00 && + text[k + 6] == 0x80 && text[k + 7] == 0x3F) + { + return new IntPtr(val); + } + } + } + } + return IntPtr.Zero; + } + + /// <summary> + /// Finds MovementParameters::`vftable' by searching for the constructor + /// that writes a .rdata vtable to [eax+0] then speed=1.0 to [eax+0x14]: + /// C7 00 [vtable] ← mov [eax], vtable + /// ... (field inits) ... + /// C7 40 14 00 00 80 3F ← mov [eax+0x14], 1.0f + /// </summary> + private static IntPtr FindMovParamsVtable(byte[] text, int textBaseVA) + { + int rdataLo = textBaseVA + 0x390000; + int rdataHi = rdataLo + 0x80000; + + // Search for: C7 40 14 00 00 80 3F (speed = 1.0f at +0x14) + byte[] speedPat = { 0xC7, 0x40, 0x14, 0x00, 0x00, 0x80, 0x3F }; + for (int i = 0; i < text.Length - speedPat.Length; i++) + { + if (!BytesMatch(text, i, speedPat)) continue; + + // Walk backwards up to 40 bytes for C7 00 [rdata_addr] + for (int back = 4; back < 40; back++) + { + int j = i - back; + if (j < 0) break; + if (text[j] == 0xC7 && text[j + 1] == 0x00) + { + int val = BitConverter.ToInt32(text, j + 2); + if (val >= rdataLo && val <= rdataHi) + return new IntPtr(val); + } + } + } + return IntPtr.Zero; + } + + /// <summary> + /// Walks backwards from an offset to find a function start. + /// The function must begin with the given prologue bytes, preceded + /// by CC/90/C3 alignment padding. + /// </summary> + private static int FindFuncStartBefore(byte[] data, int fromOffset, byte[] prologue) + { + for (int back = 1; back < 400; back++) + { + int pos = fromOffset - back; + if (pos < 1 || pos + prologue.Length > data.Length) continue; + + if (!BytesMatch(data, pos, prologue)) continue; + + byte prev = data[pos - 1]; + if (prev == 0xCC || prev == 0x90 || prev == 0xC3) + return pos; + } + return -1; + } + + // ═══════════════════════════════════════════════════════════════════════ + // LOW-LEVEL HELPERS + // ═══════════════════════════════════════════════════════════════════════ + + private static bool BytesMatch(byte[] data, int offset, byte[] pattern) + { + if (offset + pattern.Length > data.Length) return false; + for (int i = 0; i < pattern.Length; i++) + if (data[offset + i] != pattern[i]) return false; + return true; + } + + private static unsafe void WriteFloat(IntPtr addr, float value) + { + *(float*)addr.ToPointer() = value; + } + + private static unsafe float ReadFloat(IntPtr addr) + { + return *(float*)addr.ToPointer(); + } + + private static void WriteInt(IntPtr addr, uint value) + { + Marshal.WriteInt32(addr, (int)value); + } + + private static void ZeroMemory(IntPtr addr, int size) + { + byte[] zeros = new byte[size]; + Marshal.Copy(zeros, 0, addr, size); + } + + private static void Log(string msg) + { + try { _log?.Invoke($"[RynthAi] {msg}"); } catch { } + } + } +} diff --git a/Plugins/RynthAi/Nav/VTankNavParser.cs b/Plugins/RynthAi/Nav/VTankNavParser.cs new file mode 100644 index 0000000..61e9793 --- /dev/null +++ b/Plugins/RynthAi/Nav/VTankNavParser.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Globalization; + +namespace NexSuite.Plugins.RynthAi +{ + public enum NavRouteType + { + Circular = 1, + Linear = 2, + Follow = 3, + Once = 4 + } + + public enum NavPointType + { + Point = 0, + Recall = 2, + Pause = 3, + Chat = 4, + PortalNPC = 6 + } + + public class NavPoint + { + public NavPointType Type { get; set; } + public double NS { get; set; } + public double EW { get; set; } + public double Z { get; set; } + + public int SpellId { get; set; } + public int PauseTimeMs { get; set; } + public string ChatCommand { get; set; } + public string TargetName { get; set; } + public int ObjectClass { get; set; } + public bool IsTie { get; set; } + + // PortalNPC extra coordinate blocks (exit/destination coords) + public double PortalExitNS { get; set; } + public double PortalExitEW { get; set; } + public double PortalExitZ { get; set; } + public double PortalLandNS { get; set; } + public double PortalLandEW { get; set; } + public double PortalLandZ { get; set; } + + public override string ToString() + { + switch (Type) + { + // UI display converted to exact 3-decimal precision + case NavPointType.Point: return $"[Point] {NS:F3}, {EW:F3}"; + case NavPointType.Recall: + { + string spellName = SpellDatabase.GetSpellName(SpellId); + return $"[Recall] {spellName} ({SpellId})"; + } + case NavPointType.Pause: return $"[Pause] {PauseTimeMs / 1000.0}s"; + case NavPointType.Chat: return $"[Chat] {ChatCommand}"; + case NavPointType.PortalNPC: return $"[Portal] {TargetName}"; + default: return $"[Unknown] {Type}"; + } + } + } + + public class VTankNavParser + { + public NavRouteType RouteType { get; set; } + public List<NavPoint> Points { get; set; } = new List<NavPoint>(); + + public static VTankNavParser Load(string filePath) + { + var route = new VTankNavParser(); + string[] lines = File.ReadAllLines(filePath); + + if (lines.Length < 3) return route; + + if (!lines[0].Contains("uTank2 NAV 1.2")) + throw new Exception("Invalid or unsupported VTank .nav file format."); + + route.RouteType = (NavRouteType)int.Parse(lines[1]); + int pointCount = int.Parse(lines[2]); + + int idx = 3; + for (int i = 0; i < pointCount && idx < lines.Length; i++) + { + var pt = new NavPoint(); + pt.Type = (NavPointType)int.Parse(lines[idx++]); + + pt.EW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); // First coord is EW + pt.NS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); // Second coord is NS + pt.Z = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + + idx++; // Skip the 0 spacer line + + switch (pt.Type) + { + case NavPointType.Point: break; + case NavPointType.Recall: pt.SpellId = int.Parse(lines[idx++]); break; + case NavPointType.Pause: pt.PauseTimeMs = int.Parse(lines[idx++]); break; + case NavPointType.Chat: pt.ChatCommand = lines[idx++]; break; + case NavPointType.PortalNPC: + pt.TargetName = lines[idx++]; + pt.ObjectClass = int.Parse(lines[idx++]); + pt.IsTie = bool.Parse(lines[idx++]); + // Two extra coordinate blocks (exit + landing) - also EW/NS/Z format + pt.PortalExitEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalExitNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalExitZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + idx++; // spacer + pt.PortalLandEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalLandNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalLandZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + idx++; // spacer + break; + } + + route.Points.Add(pt); + } + + return route; + } + + public void Save(string filePath) + { + using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath, false)) + { + writer.WriteLine("uTank2 NAV 1.2"); + writer.WriteLine((int)RouteType); + writer.WriteLine(Points.Count); + + foreach (var pt in Points) + { + writer.WriteLine((int)pt.Type); + writer.WriteLine(pt.EW.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.NS.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.Z.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + + switch (pt.Type) + { + case NavPointType.Recall: writer.WriteLine(pt.SpellId); break; + case NavPointType.Pause: writer.WriteLine(pt.PauseTimeMs); break; + case NavPointType.Chat: writer.WriteLine(pt.ChatCommand); break; + case NavPointType.PortalNPC: + writer.WriteLine(pt.TargetName); + writer.WriteLine(pt.ObjectClass); + writer.WriteLine(pt.IsTie.ToString()); + writer.WriteLine(pt.PortalExitEW.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalExitNS.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalExitZ.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + writer.WriteLine(pt.PortalLandEW.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalLandNS.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalLandZ.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + break; + } + } + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/PluginCore.cs b/Plugins/RynthAi/PluginCore.cs new file mode 100644 index 0000000..6daba04 --- /dev/null +++ b/Plugins/RynthAi/PluginCore.cs @@ -0,0 +1,1115 @@ +using System; +using System.IO; +using System.Reflection; +using System.Collections.Generic; +using System.Numerics; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using UtilityBelt.Service; +using ImGuiNET; +using System.IO.Ports; +using UtilityBelt.Service.Lib.Settings; +using RynthAi.Meta; +using System.Runtime.InteropServices; +using System.Diagnostics; +using NexSuite.Plugins.RynthAi.Utility; +using AcClient; + +namespace NexSuite.Plugins.RynthAi +{ + [FriendlyName("RynthAi")] + public class PluginCore : PluginBase + { + // --- PRIVATE MANAGERS & UI --- + private RynthAiUI _ui; + private CombatManager _combatManager; + private NavigationManager _navigationManager; + private UISettings _settings; + private SpellManager _spellManager; + private LootManager _lootManager; + private BuffManager _buffManager; + private MetaManager _metaManager; + private MissileCraftingManager _missileCraftingManager; + private FellowshipTracker _fellowshipTracker; + private UtilityBelt.Service.Views.Hud _mainHud; + private BackgroundFpsUnlocker _fpsUnlocker; + + private string _settingsPath; + private CommandProcessor _commandProcessor; + + // --- PUBLIC FOLDERS (Exposed for CommandProcessor) --- + public string NavFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\NavProfiles"; + public string LootFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\LootProfiles"; + public string MetaFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\MetaProfiles"; + public string LuaFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\LuaScripts"; + public string AssemblyDirectory => System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); + + // --- EXPOSED DECAL HOOKS & UI (For CommandProcessor) --- + public RynthAiUI UI => _ui; + + // These create safe, public doorways for your CommandProcessor to access Decal + public Decal.Adapter.Wrappers.PluginHost PluginHost => base.Host; + public Decal.Adapter.CoreManager PluginCoreManager => base.Core; + + public void ToggleUI() + { + if (_mainHud != null) _mainHud.Visible = !_mainHud.Visible; + } + + //FPS Throttling System + private Stopwatch _frameTimer = Stopwatch.StartNew(); + private DateTime _nextLuaTick = DateTime.Now; + + + + // --- COMBAT & VITAL TRACKING --- + private Dictionary<int, float> healthRatioTracker = new Dictionary<int, float>(); + private Dictionary<int, int> maxHealthTracker = new Dictionary<int, int>(); + private Dictionary<string, string> monsterWeaknesses = new Dictionary<string, string>(); + + + private DateTime lastRequestTime = DateTime.MinValue; + private const double RETRY_INTERVAL_SEC = 0.75; + private const int MAX_RETRIES = 5; + + // --- STATE TRACKING --- + + public RynthAi.Raycasting.MainLogic Raycast { get; private set; } + + // LUA + private LuaManager _luaManager; + // Native Jumper + private RynthJumper _jumper; + + // ... (Your protected override void Startup() method starts here) ... + protected override void Startup() + { + try + { + // 1. Initialize Global Folders + if (!System.IO.Directory.Exists(NavFolder)) System.IO.Directory.CreateDirectory(NavFolder); + if (!System.IO.Directory.Exists(LootFolder)) System.IO.Directory.CreateDirectory(LootFolder); + if (!System.IO.Directory.Exists(MetaFolder)) System.IO.Directory.CreateDirectory(MetaFolder); + if (!System.IO.Directory.Exists(LuaFolder)) System.IO.Directory.CreateDirectory(LuaFolder); + + // 2. Load Databases + LoadWeaknesses(); + + // Path to the spell dump + string dllPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); + string spellDumpPath = System.IO.Path.Combine(dllPath, "Combat", "Vtank spelldump.txt"); + + + // 3. Subscribe to Core Events + Core.ChatBoxMessage += OnChatBoxMessage; + Core.RenderFrame += OnRenderFrame; + + // Wait for server login to finish before initializing character-specific data + Core.CharacterFilter.LoginComplete += CharacterFilter_LoginComplete; + + // Hook command line and server traffic + CommandLineText += OnChatCommand; + Core.EchoFilter.ServerDispatch += OnServerDispatch; + + System.Diagnostics.Debug.WriteLine("[RynthAi] Startup Complete."); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine("[RynthAi Startup Error] " + ex.Message); + } + } + + protected override void Shutdown() + { + try + { + SaveSettings(); + + // Safely dispose of the D3D graphics using the new RouteTab + if (_ui != null && _ui.RouteTab != null) + { + _ui.RouteTab.DisposeRouteGraphics(); + } + + if (_mainHud != null) _mainHud.Dispose(); + + // --- UNHOOK EVENTS --- + Core.RenderFrame -= OnRenderFrame; + Core.ChatBoxMessage -= OnChatBoxMessage; + Core.EchoFilter.ServerDispatch -= OnServerDispatch; + CommandLineText -= OnChatCommand; + Core.CharacterFilter.LoginComplete -= CharacterFilter_LoginComplete; + + // --- DISPOSE MANAGERS --- + if (_buffManager != null) _buffManager.Dispose(); + if (_combatManager != null) _combatManager.Dispose(); + if (_fellowshipTracker != null) _fellowshipTracker.Dispose(); + if (_navigationManager != null) _navigationManager.Stop(); + if (_luaManager != null) _luaManager.Dispose(); + if (Raycast != null) Raycast.Dispose(); + + + } + catch (Exception ex) + { + // Try to print to chat, but if the Host is already destroyed, just swallow it gracefully + try { Host.Actions.AddChatText($"[RynthAi Shutdown Error] {ex.Message}", 1); } catch { } + } + _fpsUnlocker?.Dispose(); + } + + private void LoadWeaknesses() + { + // Embedded fallback data — used if monsters.json is missing + var embedded = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) + { + { "Olthoi", "Cold" }, { "Tusker", "Fire" }, { "Lugian", "Lightning" }, + { "Drudge", "Fire" }, { "Skeleton", "Fire" }, { "Gromnie", "Acid" }, + { "Reedshark", "Fire" }, { "Armoredillo", "Lightning" }, { "Banderling", "Fire" }, + { "Bunny", "Fire" }, { "Carenzi", "Fire" }, { "Dire Wolf", "Fire" }, + { "Doll", "Fire" }, { "Eater", "Lightning" }, { "Golem", "Acid" }, + { "Grievver", "Cold" }, { "Lich", "Fire" }, { "Matredien", "Lightning" }, + { "Mimic", "Fire" }, { "Mite", "Fire" }, { "Monouga", "Fire" }, + { "Mosswart", "Fire" }, { "Mu-miyah", "Fire" }, { "Niffis", "Lightning" }, + { "Phantasm", "Fire" }, { "Rat", "Fire" }, { "Remoran", "Fire" }, + { "Ruschk", "Fire" }, { "Sclavus", "Cold" }, { "Shreth", "Fire" }, + { "Teth", "Lightning" }, { "Thrass", "Fire" }, { "Ursuin", "Fire" }, + { "Viamontian", "Lightning" }, { "Virindi", "Lightning" }, { "Wasp", "Fire" }, + { "Wight", "Fire" }, { "Zharalim", "Lightning" }, { "Impy", "Lightning" }, + }; + + // Start with embedded data + foreach (var kvp in embedded) monsterWeaknesses[kvp.Key] = kvp.Value; + + // Normalize map for shorthand → spell element names + var normalizeMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) + { + { "Bludge", "Bludgeon" }, { "Bludgeon", "Bludgeon" }, + { "Pierce", "Pierce" }, { "Slash", "Slash" }, + { "Fire", "Fire" }, { "Cold", "Cold" }, + { "Lightning", "Lightning" }, { "Acid", "Acid" }, + { "Light", "Fire" }, { "Nether", "Nether" }, + }; + + try + { + string basePath = @"C:\Games\DecalPlugins\NexSuite\RynthAi"; + string path = System.IO.Path.Combine(basePath, "monsters.json"); + + if (System.IO.File.Exists(path)) + { + string content = System.IO.File.ReadAllText(path); + var lines = content.Split(new[] { ',', '{', '}', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + foreach (var line in lines) + { + var parts = line.Split(':'); + if (parts.Length == 2) + { + string name = parts[0].Trim().Trim('"'); + string rawWeakness = parts[1].Trim().Trim('"'); + + if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(rawWeakness)) continue; + + // Extract the MAGIC element: last entry in "Physical / Magic" format + // e.g., "Bludge / Pierce / Cold" → "Cold" + // e.g., "Slash / Fire" → "Fire" + string[] elements = rawWeakness.Split('/'); + string magicElement = elements[elements.Length - 1].Trim(); + + // Skip "(Varies)" entries + if (magicElement.Contains("Varies")) continue; + + // Normalize the element name + string normalized; + if (normalizeMap.TryGetValue(magicElement, out normalized)) + monsterWeaknesses[name] = normalized; + else + monsterWeaknesses[name] = magicElement; // Use as-is if unknown + } + } + } + } + catch { } + } + + private void CharacterFilter_LoginComplete(object sender, EventArgs e) + { + try + { + // --- 1. Load Spell Database with In-Game Debugging --- + string dllPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); + string spellDumpPath = System.IO.Path.Combine(dllPath, "Combat", "Vtank spelldump.txt"); + + // This will now print the "Raw Line" debug messages to your AC chat + SpellDatabase.Load(Host); + + // --- 2. Get Character & Server Name safely --- + string serverName = Core.CharacterFilter.Server; + string charName = Core.CharacterFilter.Name; + + if (string.IsNullOrEmpty(serverName)) serverName = "UnknownServer"; + if (string.IsNullOrEmpty(charName)) charName = "UnknownCharacter"; + + // --- 3. Build CUSTOM dynamic paths --- + string basePath = @"C:\Games\DecalPlugins\NexSuite\RynthAi\SettingsProfiles"; + string charFolder = System.IO.Path.Combine(basePath, serverName, charName); + + _settingsPath = System.IO.Path.Combine(charFolder, "settings.json"); + if (!System.IO.Directory.Exists(charFolder)) System.IO.Directory.CreateDirectory(charFolder); + + // --- 4. Load settings --- + LoadSettings(); + + // --- 5. Initialize Core Managers --- + _spellManager = new SpellManager(CoreManager.Current); + _buffManager = new BuffManager(CoreManager.Current, _settings, _spellManager); + _buffManager.SetTimerPath(charFolder); + _combatManager = new CombatManager(Core, _settings, Host, _spellManager); + _combatManager.SetMonsterWeaknesses(monsterWeaknesses); + _combatManager.InitializeRaycasting(@"C:\Turbine\Asheron's Call"); + _navigationManager = new NavigationManager(CoreManager.Current, _settings, Host); + _lootManager = new LootManager(CoreManager.Current, _settings, Host); + _metaManager = new MetaManager(Core, _settings, Host); + _missileCraftingManager = new MissileCraftingManager(CoreManager.Current, _settings, Host); + _fellowshipTracker = new FellowshipTracker(CoreManager.Current); + _lootManager.SetFellowshipTracker(_fellowshipTracker); + + // Initialize the Raycast Engine and let it auto-find the AC installation folder + Raycast = new RynthAi.Raycasting.MainLogic(); + Raycast.Initialize(); + + // --- 6. Initialize Command Processor --- + _jumper = new RynthJumper(Host, _settings); + _commandProcessor = new CommandProcessor(this, _settings, _metaManager, _navigationManager, _buffManager, _combatManager, _lootManager, _luaManager, _jumper, _spellManager, _fellowshipTracker); + + // --- 7. Initialize UI and HUD --- + _spellManager.InitializeNatively(); + _ui = new RynthAiUI(_settings, _combatManager, Core); + + // --- 8. LUA INITIALIZATION & WIRING --- + // Initialize AFTER _ui exists to prevent NullRef during bridge setup + _luaManager = new LuaManager(this); + + // Wire: Run Button (Routed through the new LuaUI tab class) + _luaManager.ExecuteString("OnBotTick()"); + + // Wire: Stop Button (Emergency Shutdown) + _ui.LuaTab.OnStopRequested = () => { + _settings.IsMacroRunning = false; + _settings.EnableNavigation = false; + _settings.EnableCombat = false; + _navigationManager?.Stop(); + Host.Actions.AddChatText("[RynthLua] Emergency Stop Triggered.", 1); + }; + + // Wire: Settings changes from the Lua tab + _ui.LuaTab.OnSettingsChanged = () => SaveSettings(); + + // --- 9. Wire standard UI Actions --- + _ui.OnSettingsChanged = () => SaveSettings(); + _ui.OnForceRebuffClicked = () => _buffManager?.ForceFullRebuff(); + _ui.OnLootProfileSelected = () => _lootManager?.ForceReload(); + _ui.OnMetaProfileSelected = () => _metaManager?.LoadProfile(_settings.CurrentMetaPath); + _ui.OnMetaRulesUpdated = () => _metaManager?.SaveCurrentProfile(); + + // Route refresh wire-up + _metaManager.OnRouteDynamicallyLoaded += () => { if (_ui?.RouteTab != null) _ui.RouteTab.NeedsRouteGraphicsRefresh = true; }; + + _combatManager.AttachUI(_ui); + _ui.SetMissileCraftingManager(_missileCraftingManager); + + // Initialize direct combat action calls (acclient.exe function pointers) + CombatActionHelper.Initialize(msg => { + try { Host.Actions.AddChatText(msg, 1); } catch { } + }); + + // Initialize direct movement action calls (acclient.exe CM_Movement functions) + MovementActionHelper.Initialize(msg => { + try { Host.Actions.AddChatText(msg, 1); } catch { } + }); + + // Initialize Tier 2 movement (MoveToPosition via MovementManager) + unsafe + { + Tier2MovementHelper.Initialize( + msg => { try { Host.Actions.AddChatText(msg, 1); } catch { } }, + (IntPtr)SmartBox.smartbox); + } + + // --- 10. Load Navigation Profile --- + if (!string.IsNullOrEmpty(_settings.CurrentNavPath) && System.IO.File.Exists(_settings.CurrentNavPath)) + { + try + { + // This loads the points into memory + _settings.CurrentRoute = VTankNavParser.Load(_settings.CurrentNavPath); + + // FIX: The following block overwrites the ActiveNavIndex you just loaded from settings.json. + // If you want to RESUME where you left off, comment this logic out. + /* + if (_settings.CurrentRoute.RouteType == NavRouteType.Once || _settings.CurrentRoute.RouteType == NavRouteType.Follow) + _settings.ActiveNavIndex = 0; + else if (_settings.CurrentRoute.RouteType == NavRouteType.Linear || _settings.CurrentRoute.RouteType == NavRouteType.Circular) + _settings.ActiveNavIndex = _navigationManager.FindNearestWaypoint(_settings.CurrentRoute); + */ + + _navigationManager.ResetRouteState(); + + // FIX: Tell the UI to draw the rings and dots on the floor now that data is loaded + if (_ui?.RouteTab != null) + { + _ui.RouteTab.UpdateRouteGraphics(); + } + + Host.Actions.AddChatText($"[RynthAi] Restored route: {System.IO.Path.GetFileName(_settings.CurrentNavPath)}", 1); + } + catch (Exception ex) + { + _settings.CurrentNavPath = ""; + Host.Actions.AddChatText($"[RynthAi] Failed to load route: {ex.Message}", 1); + } + } + + // --- 11. Initialize standalone Meta Profile --- + if (!string.IsNullOrEmpty(_settings.CurrentMetaPath) && System.IO.File.Exists(_settings.CurrentMetaPath)) + { + _metaManager?.LoadProfile(_settings.CurrentMetaPath); + } + + _ui.RefreshNavFiles(); + + // --- 12. Initialize the HUD --- + _mainHud = UBService.Huds.CreateHud("RynthAi"); + _mainHud.ShowInBar = true; + _mainHud.Visible = true; + _mainHud.OnRender += MainHud_OnRender; + + Host.Actions.AddChatText($"[RynthAi] v1.9.1 loaded for {charName} on {serverName}.", 1); + } + catch (Exception ex) + { + Host.Actions.AddChatText("[RynthAi Login Error] " + ex.Message, 1); + } + _fpsUnlocker = new BackgroundFpsUnlocker(); + _fpsUnlocker.Start(Host); + + + } + + private void MainHud_OnRender(object sender, EventArgs e) + { + try + { + // This single line safely renders your entire unified dashboard + // (and all its tabs) every frame without crashing! + if (_ui != null) + { + _ui.Render(); + } + } + catch (Exception ex) + { + // Replace this with however you normally log errors in your plugin, + // e.g., System.Diagnostics.Debug.WriteLine(ex.ToString()); + System.Diagnostics.Debug.WriteLine(ex.ToString()); + } + } + private void OnServerDispatch(object sender, NetworkMessageEventArgs e) + { + if (e.Message.Type == 0xF7B0) + { + int eventType = (int)e.Message[2]; + if (eventType == 0x1C0) + { + int targetId = (int)e.Message[3]; + object raw = e.Message[4]; + if (raw is float f) healthRatioTracker[targetId] = f; + else if (raw is double d) healthRatioTracker[targetId] = (float)d; + // Report damage feedback to blacklist system — mob is taking damage, so it's reachable + _combatManager?.ReportDamageOnTarget(targetId); + } + else if (eventType == 0xC9) TryExtractVitals(e.Message); + } + } + + private void TryExtractVitals(Decal.Adapter.Message msg) + { + try + { + MessageStruct ev = msg.Struct("event"); + if (ev != null) + { + int hm = 0; try { hm = ev.Value<int>("healthMax"); } catch { } + if (hm > 0) + { + int obj = ev.Value<int>("object"); + if (obj == 0) obj = _combatManager.activeTargetId; + if (obj != 0) { maxHealthTracker[obj] = hm; return; } + } + } + + int tId = (int)msg[3]; + if (healthRatioTracker.ContainsKey(tId)) + { + float currentRatio = healthRatioTracker[tId]; + for (int i = 4; i < msg.Count - 1; i++) + { + if (msg[i] is int h && msg[i + 1] is int hMax) + { + if (hMax >= 50 && hMax < 5000000 && h >= 0 && h <= hMax) + { + float checkRatio = (float)h / hMax; + float currentDiff = Math.Abs(currentRatio - checkRatio); + if (currentDiff < 0.05f) + { + maxHealthTracker[tId] = hMax; + return; + } + } + } + } + } + } + catch { } + } + + public void SaveSettings(string customPath = null) + { + // Use the custom path if provided (by CommandProcessor), otherwise use the default char path + string path = customPath ?? _settingsPath; + + try + { + using (StreamWriter sw = new StreamWriter(path)) + { + // Core state + sw.WriteLine("IsMacroRunning=" + _settings.IsMacroRunning); + sw.WriteLine("CurrentNavPath=" + _settings.CurrentNavPath); + sw.WriteLine("ActiveNavIndex=" + _settings.ActiveNavIndex); + + // Subsystem toggles + sw.WriteLine("EnableBuffing=" + _settings.EnableBuffing); + sw.WriteLine("EnableCombat=" + _settings.EnableCombat); + sw.WriteLine("EnableNavigation=" + _settings.EnableNavigation); + sw.WriteLine("EnableLooting=" + _settings.EnableLooting); + sw.WriteLine("EnableMeta=" + _settings.EnableMeta); + sw.WriteLine("EnableRaycasting=" + _settings.EnableRaycasting); + + // Vitals + sw.WriteLine("HealAt=" + _settings.HealAt); + sw.WriteLine("RestamAt=" + _settings.RestamAt); + sw.WriteLine("GetManaAt=" + _settings.GetManaAt); + sw.WriteLine("TopOffHP=" + _settings.TopOffHP); + sw.WriteLine("TopOffStam=" + _settings.TopOffStam); + sw.WriteLine("TopOffMana=" + _settings.TopOffMana); + sw.WriteLine("HealOthersAt=" + _settings.HealOthersAt); + sw.WriteLine("RestamOthersAt=" + _settings.RestamOthersAt); + sw.WriteLine("InfuseOthersAt=" + _settings.InfuseOthersAt); + + // Ranges + sw.WriteLine("MonsterRange=" + _settings.MonsterRange); + sw.WriteLine("RingRange=" + _settings.RingRange); + sw.WriteLine("MinRingTargets=" + _settings.MinRingTargets); + sw.WriteLine("ApproachRange=" + _settings.ApproachRange); + sw.WriteLine("FollowNavMin=" + _settings.FollowNavMin); + sw.WriteLine("CorpseApproachRangeMax=" + _settings.CorpseApproachRangeMax); + sw.WriteLine("CorpseApproachRangeMin=" + _settings.CorpseApproachRangeMin); + + // Advanced toggles + sw.WriteLine("BoostNavPriority=" + _settings.BoostNavPriority); + sw.WriteLine("BoostLootPriority=" + _settings.BoostLootPriority); + sw.WriteLine("LootOnlyRareCorpses=" + _settings.LootOnlyRareCorpses); + sw.WriteLine("LootOwnership=" + _settings.LootOwnership); + sw.WriteLine("PeaceModeWhenIdle=" + _settings.PeaceModeWhenIdle); + sw.WriteLine("RebuffWhenIdle=" + _settings.RebuffWhenIdle); + + // Blacklist + sw.WriteLine("BlacklistAttempts=" + _settings.BlacklistAttempts); + sw.WriteLine("BlacklistTimeoutSec=" + _settings.BlacklistTimeoutSec); + + // FPS Throttling + sw.WriteLine("EnableFPSLimit=" + _settings.EnableFPSLimit); + sw.WriteLine("TargetFPSFocused=" + _settings.TargetFPSFocused); + sw.WriteLine("TargetFPSBackground=" + _settings.TargetFPSBackground); + + // Attack Power + sw.WriteLine("MeleeAttackPower=" + _settings.MeleeAttackPower); + sw.WriteLine("MissileAttackPower=" + _settings.MissileAttackPower); + sw.WriteLine("UseRecklessness=" + _settings.UseRecklessness); + sw.WriteLine("MeleeAttackHeight=" + _settings.MeleeAttackHeight); + sw.WriteLine("MissileAttackHeight=" + _settings.MissileAttackHeight); + + // Automation toggles + sw.WriteLine("EnableAutostack=" + _settings.EnableAutostack); + sw.WriteLine("EnableAutocram=" + _settings.EnableAutocram); + sw.WriteLine("EnableCombineSalvage=" + _settings.EnableCombineSalvage); + // Missile crafting + sw.WriteLine("EnableMissileCrafting=" + _settings.EnableMissileCrafting); + sw.WriteLine("MissileCraftAmmoThreshold=" + _settings.MissileCraftAmmoThreshold); + // Loot timers + sw.WriteLine("LootInterItemDelayMs=" + _settings.LootInterItemDelayMs); + sw.WriteLine("LootContentSettleMs=" + _settings.LootContentSettleMs); + sw.WriteLine("LootEmptyCorpseMs=" + _settings.LootEmptyCorpseMs); + sw.WriteLine("LootClosingDelayMs=" + _settings.LootClosingDelayMs); + sw.WriteLine("LootAssessWindowMs=" + _settings.LootAssessWindowMs); + sw.WriteLine("LootRetryTimeoutMs=" + _settings.LootRetryTimeoutMs); + sw.WriteLine("LootOpenRetryMs=" + _settings.LootOpenRetryMs); + // Salvage timers + sw.WriteLine("SalvageOpenDelayFirstMs=" + _settings.SalvageOpenDelayFirstMs); + sw.WriteLine("SalvageOpenDelayFastMs=" + _settings.SalvageOpenDelayFastMs); + sw.WriteLine("SalvageAddDelayFirstMs=" + _settings.SalvageAddDelayFirstMs); + sw.WriteLine("SalvageAddDelayFastMs=" + _settings.SalvageAddDelayFastMs); + sw.WriteLine("SalvageSalvageDelayMs=" + _settings.SalvageSalvageDelayMs); + sw.WriteLine("SalvageResultDelayFirstMs=" + _settings.SalvageResultDelayFirstMs); + sw.WriteLine("SalvageResultDelayFastMs=" + _settings.SalvageResultDelayFastMs); + sw.WriteLine("UseDispelItems=" + _settings.UseDispelItems); + sw.WriteLine("CastDispelSelf=" + _settings.CastDispelSelf); + sw.WriteLine("AutoFellowMgmt=" + _settings.AutoFellowMgmt); + sw.WriteLine("MChargesWhenOff=" + _settings.MChargesWhenOff); + + // Pets + sw.WriteLine("SummonPets=" + _settings.SummonPets); + sw.WriteLine("CustomPetRange=" + _settings.CustomPetRange); + sw.WriteLine("PetMinMonsters=" + _settings.PetMinMonsters); + + // Profile indices + sw.WriteLine("MacroSettingsIdx=" + _settings.MacroSettingsIdx); + sw.WriteLine("NavProfileIdx=" + _settings.NavProfileIdx); + sw.WriteLine("LootProfileIdx=" + _settings.LootProfileIdx); + sw.WriteLine("MetaProfileIdx=" + _settings.MetaProfileIdx); + + // UI state + sw.WriteLine("AdvancedOptions=" + _settings.AdvancedOptions); + sw.WriteLine("MineOnly=" + _settings.MineOnly); + sw.WriteLine("ShowEditor=" + _settings.ShowEditor); + + // Item rules (with GUID) + sw.WriteLine("ItemCount=" + _settings.ItemRules.Count); + for (int i = 0; i < _settings.ItemRules.Count; i++) + { + var r = _settings.ItemRules[i]; + sw.WriteLine($"Item_{i}={r.Id}|{r.Name}|{r.Element}|{r.KeepBuffed}|{r.Action}"); + } + + // Monster rules — saved to separate TSV file for easy Excel editing + // Also write count to settings for backwards compat detection + sw.WriteLine("MonsterCount=" + _settings.MonsterRules.Count); + SaveMonsterRulesTSV(path); + + // Meta Rules + sw.WriteLine("MetaCount=" + _settings.MetaRules.Count); + for (int i = 0; i < _settings.MetaRules.Count; i++) + { + var r = _settings.MetaRules[i]; + sw.WriteLine($"Meta_{i}={r.State}|{(int)r.Condition}|{r.ConditionData}|{(int)r.Action}|{r.ActionData}"); + } + } + } + catch (Exception ex) + { + Host.Actions.AddChatText($"[RynthAi] Save Error: {ex.Message}", 2); + } + } + + public void LoadSettings(string customPath = null) + { + string path = customPath ?? _settingsPath; + _settings = new UISettings(); + + try + { + if (System.IO.File.Exists(path)) + { + foreach (string line in System.IO.File.ReadAllLines(path)) + { + int eq = line.IndexOf('='); + if (eq < 1) continue; + string k = line.Substring(0, eq).Trim(); + string v = line.Substring(eq + 1).Trim(); + + // Core state + if (k == "IsMacroRunning") _settings.IsMacroRunning = bool.Parse(v); + else if (k == "CurrentNavPath") _settings.CurrentNavPath = v; + else if (k == "ActiveNavIndex") _settings.ActiveNavIndex = int.Parse(v); + + // Subsystem toggles + else if (k == "EnableBuffing") _settings.EnableBuffing = bool.Parse(v); + else if (k == "EnableCombat") _settings.EnableCombat = bool.Parse(v); + else if (k == "EnableNavigation") _settings.EnableNavigation = bool.Parse(v); + else if (k == "EnableLooting") _settings.EnableLooting = bool.Parse(v); + else if (k == "EnableMeta") _settings.EnableMeta = bool.Parse(v); + else if (k == "EnableRaycasting") _settings.EnableRaycasting = bool.Parse(v); + + // Vitals + else if (k == "HealAt") _settings.HealAt = int.Parse(v); + else if (k == "RestamAt") _settings.RestamAt = int.Parse(v); + else if (k == "GetManaAt") _settings.GetManaAt = int.Parse(v); + else if (k == "TopOffHP") _settings.TopOffHP = int.Parse(v); + else if (k == "TopOffStam") _settings.TopOffStam = int.Parse(v); + else if (k == "TopOffMana") _settings.TopOffMana = int.Parse(v); + else if (k == "HealOthersAt") _settings.HealOthersAt = int.Parse(v); + else if (k == "RestamOthersAt") _settings.RestamOthersAt = int.Parse(v); + else if (k == "InfuseOthersAt") _settings.InfuseOthersAt = int.Parse(v); + + // Ranges + else if (k == "MonsterRange") _settings.MonsterRange = int.Parse(v); + else if (k == "RingRange") _settings.RingRange = int.Parse(v); + else if (k == "MinRingTargets") _settings.MinRingTargets = int.Parse(v); + else if (k == "ApproachRange") _settings.ApproachRange = int.Parse(v); + else if (k == "FollowNavMin") _settings.FollowNavMin = float.Parse(v); + else if (k == "CorpseApproachRangeMax") _settings.CorpseApproachRangeMax = double.Parse(v); + else if (k == "CorpseApproachRangeMin") _settings.CorpseApproachRangeMin = double.Parse(v); + + // Advanced toggles + else if (k == "BoostNavPriority") _settings.BoostNavPriority = bool.Parse(v); + else if (k == "BoostLootPriority") _settings.BoostLootPriority = bool.Parse(v); + else if (k == "LootOnlyRareCorpses") _settings.LootOnlyRareCorpses = bool.Parse(v); + else if (k == "LootOwnership") _settings.LootOwnership = int.Parse(v); + else if (k == "PeaceModeWhenIdle") _settings.PeaceModeWhenIdle = bool.Parse(v); + else if (k == "RebuffWhenIdle") _settings.RebuffWhenIdle = bool.Parse(v); + + // Blacklist + else if (k == "BlacklistAttempts") _settings.BlacklistAttempts = int.Parse(v); + else if (k == "BlacklistTimeoutSec") _settings.BlacklistTimeoutSec = int.Parse(v); + + // FPS Throttling + else if (k == "EnableFPSLimit") _settings.EnableFPSLimit = bool.Parse(v); + else if (k == "TargetFPSFocused") _settings.TargetFPSFocused = int.Parse(v); + else if (k == "TargetFPSBackground") _settings.TargetFPSBackground = int.Parse(v); + + // Attack Power + else if (k == "MeleeAttackPower") _settings.MeleeAttackPower = int.Parse(v); + else if (k == "MissileAttackPower") _settings.MissileAttackPower = int.Parse(v); + else if (k == "UseRecklessness") _settings.UseRecklessness = bool.Parse(v); + else if (k == "MeleeAttackHeight") _settings.MeleeAttackHeight = int.Parse(v); + else if (k == "MissileAttackHeight") _settings.MissileAttackHeight = int.Parse(v); + // Backwards compat: old float AttackPower → both + else if (k == "AttackPower") { float old = float.Parse(v); int pct = old < 0 ? -1 : (int)(old * 100); _settings.MeleeAttackPower = pct; _settings.MissileAttackPower = pct; } + + // Automation toggles + else if (k == "EnableAutostack") _settings.EnableAutostack = bool.Parse(v); + else if (k == "EnableAutocram") _settings.EnableAutocram = bool.Parse(v); + else if (k == "EnableCombineSalvage") _settings.EnableCombineSalvage = bool.Parse(v); + // Missile crafting + else if (k == "EnableMissileCrafting") _settings.EnableMissileCrafting = bool.Parse(v); + else if (k == "MissileCraftAmmoThreshold") _settings.MissileCraftAmmoThreshold = int.Parse(v); + // Loot timers + else if (k == "LootInterItemDelayMs") _settings.LootInterItemDelayMs = int.Parse(v); + else if (k == "LootContentSettleMs") _settings.LootContentSettleMs = int.Parse(v); + else if (k == "LootEmptyCorpseMs") _settings.LootEmptyCorpseMs = int.Parse(v); + else if (k == "LootClosingDelayMs") _settings.LootClosingDelayMs = int.Parse(v); + else if (k == "LootAssessWindowMs") _settings.LootAssessWindowMs = int.Parse(v); + else if (k == "LootRetryTimeoutMs") _settings.LootRetryTimeoutMs = int.Parse(v); + else if (k == "LootOpenRetryMs") _settings.LootOpenRetryMs = int.Parse(v); + // Salvage timers + else if (k == "SalvageOpenDelayFirstMs") _settings.SalvageOpenDelayFirstMs = int.Parse(v); + else if (k == "SalvageOpenDelayFastMs") _settings.SalvageOpenDelayFastMs = int.Parse(v); + else if (k == "SalvageAddDelayFirstMs") _settings.SalvageAddDelayFirstMs = int.Parse(v); + else if (k == "SalvageAddDelayFastMs") _settings.SalvageAddDelayFastMs = int.Parse(v); + else if (k == "SalvageSalvageDelayMs") _settings.SalvageSalvageDelayMs = int.Parse(v); + else if (k == "SalvageResultDelayFirstMs") _settings.SalvageResultDelayFirstMs = int.Parse(v); + else if (k == "SalvageResultDelayFastMs") _settings.SalvageResultDelayFastMs = int.Parse(v); + else if (k == "UseDispelItems") _settings.UseDispelItems = bool.Parse(v); + else if (k == "CastDispelSelf") _settings.CastDispelSelf = bool.Parse(v); + else if (k == "AutoFellowMgmt") _settings.AutoFellowMgmt = bool.Parse(v); + else if (k == "MChargesWhenOff") _settings.MChargesWhenOff = bool.Parse(v); + + // Pets + else if (k == "SummonPets") _settings.SummonPets = bool.Parse(v); + else if (k == "CustomPetRange") _settings.CustomPetRange = int.Parse(v); + else if (k == "PetMinMonsters") _settings.PetMinMonsters = int.Parse(v); + + // Profile indices + else if (k == "MacroSettingsIdx") _settings.MacroSettingsIdx = int.Parse(v); + else if (k == "NavProfileIdx") _settings.NavProfileIdx = int.Parse(v); + else if (k == "LootProfileIdx") _settings.LootProfileIdx = int.Parse(v); + else if (k == "MetaProfileIdx") _settings.MetaProfileIdx = int.Parse(v); + + // UI state + else if (k == "AdvancedOptions") _settings.AdvancedOptions = bool.Parse(v); + else if (k == "MineOnly") _settings.MineOnly = bool.Parse(v); + else if (k == "ShowEditor") _settings.ShowEditor = bool.Parse(v); + + // Item rules + else if (k.StartsWith("Item_")) + { + var bits = v.Split('|'); + if (bits.Length >= 5) + { + _settings.ItemRules.Add(new ItemRule { Id = int.Parse(bits[0]), Name = bits[1], Element = bits[2], KeepBuffed = bool.Parse(bits[3]), Action = bits[4] }); + } + } + + // Monster rules + else if (k.StartsWith("Monster_")) + { + var bits = v.Split('|'); + if (bits.Length >= 4) + { + var mr = new MonsterRule { Name = bits[0], Priority = int.Parse(bits[1]), DamageType = bits[2], WeaponId = int.Parse(bits[3]) }; + // Load debuff/spell type flags if present (backwards compat) + if (bits.Length >= 13) + { + mr.Fester = bool.Parse(bits[4]); + mr.Broadside = bool.Parse(bits[5]); + mr.GravityWell = bool.Parse(bits[6]); + mr.Imperil = bool.Parse(bits[7]); + mr.Yield = bool.Parse(bits[8]); + mr.Vuln = bool.Parse(bits[9]); + mr.UseArc = bool.Parse(bits[10]); + mr.UseRing = bool.Parse(bits[11]); + mr.UseStreak = bool.Parse(bits[12]); + } + // Load ExVuln, OffhandId, PetDamage if present + if (bits.Length >= 16) + { + mr.ExVuln = bits[13]; + mr.OffhandId = int.Parse(bits[14]); + mr.PetDamage = bits[15]; + } + // Load UseBolt if present (backwards compat: defaults to true) + if (bits.Length >= 17) + { + mr.UseBolt = bool.Parse(bits[16]); + } + _settings.MonsterRules.Add(mr); + } + } + + // Meta Rules + else if (k.StartsWith("Meta_")) + { + var bits = v.Split('|'); + if (bits.Length >= 5) + { + _settings.MetaRules.Add(new MetaRule { State = bits[0], Condition = (MetaConditionType)int.Parse(bits[1]), ConditionData = bits[2], Action = (MetaActionType)int.Parse(bits[3]), ActionData = bits[4] }); + } + } + } + } + } + catch (Exception ex) + { + Host.Actions.AddChatText($"[RynthAi] Load Error: {ex.Message}", 2); + } + + _settings.IsMacroRunning = false; + + // Try loading monster rules from TSV file (preferred) — overrides any inline Monster_ lines + string tsvPath = GetMonsterRulesTSVPath(path); + if (System.IO.File.Exists(tsvPath)) + { + var tsvRules = LoadMonsterRulesTSV(tsvPath); + if (tsvRules.Count > 0) + { + _settings.MonsterRules = tsvRules; + } + } + + _settings.EnsureDefaultRule(); + } + + private string GetMonsterRulesTSVPath(string settingsPath) + { + string dir = System.IO.Path.GetDirectoryName(settingsPath); + return System.IO.Path.Combine(dir, "monsters.tsv"); + } + + private void SaveMonsterRulesTSV(string settingsPath) + { + string tsvPath = GetMonsterRulesTSVPath(settingsPath); + string tmpPath = tsvPath + ".tmp"; + + try + { + // Write to temp file first to avoid lock conflicts + using (var fs = new FileStream(tmpPath, FileMode.Create, FileAccess.Write, FileShare.None)) + using (var sw = new StreamWriter(fs)) + { + sw.WriteLine("Name\tPriority\tDmgType\tWeaponId\tFester\tBroadside\tGravity\tImperil\tYield\tVuln\tArc\tRing\tStreak\tBolt\tExVuln\tOffhandId\tPetDamage"); + foreach (var r in _settings.MonsterRules) + { + sw.WriteLine($"{r.Name}\t{r.Priority}\t{r.DamageType}\t{r.WeaponId}\t{r.Fester}\t{r.Broadside}\t{r.GravityWell}\t{r.Imperil}\t{r.Yield}\t{r.Vuln}\t{r.UseArc}\t{r.UseRing}\t{r.UseStreak}\t{r.UseBolt}\t{r.ExVuln}\t{r.OffhandId}\t{r.PetDamage}"); + } + } + + // Atomic replace — if the main file is locked, this will fail gracefully + try + { + if (File.Exists(tsvPath)) File.Delete(tsvPath); + File.Move(tmpPath, tsvPath); + } + catch + { + // Main file is locked (e.g., open in Excel) — leave tmp for next attempt + // Don't spam chat about it, it's not critical + } + } + catch (Exception ex) + { + try { Host.Actions.AddChatText($"[RynthAi] Monster TSV save error: {ex.Message}", 2); } catch { } + } + } + + private List<MonsterRule> LoadMonsterRulesTSV(string tsvPath) + { + var rules = new List<MonsterRule>(); + try + { + var lines = System.IO.File.ReadAllLines(tsvPath); + // Skip header row + for (int i = 1; i < lines.Length; i++) + { + string line = lines[i]; + if (string.IsNullOrWhiteSpace(line)) continue; + var c = line.Split('\t'); + if (c.Length < 4) continue; + + var mr = new MonsterRule + { + Name = c[0], + Priority = int.Parse(c[1]), + DamageType = c[2], + WeaponId = int.Parse(c[3]) + }; + if (c.Length >= 14) + { + mr.Fester = bool.Parse(c[4]); + mr.Broadside = bool.Parse(c[5]); + mr.GravityWell = bool.Parse(c[6]); + mr.Imperil = bool.Parse(c[7]); + mr.Yield = bool.Parse(c[8]); + mr.Vuln = bool.Parse(c[9]); + mr.UseArc = bool.Parse(c[10]); + mr.UseRing = bool.Parse(c[11]); + mr.UseStreak = bool.Parse(c[12]); + mr.UseBolt = bool.Parse(c[13]); + } + if (c.Length >= 17) + { + mr.ExVuln = c[14]; + mr.OffhandId = int.Parse(c[15]); + mr.PetDamage = c[16]; + } + rules.Add(mr); + } + } + catch (Exception ex) + { + try { Host.Actions.AddChatText($"[RynthAi] Monster TSV load error: {ex.Message}", 2); } catch { } + } + return rules; + } + + private void OnChatCommand(object sender, ChatParserInterceptEventArgs e) + { + _commandProcessor?.Execute(e.Text, e); + } + + // --- API Imports for FPS Governor --- + [System.Runtime.InteropServices.DllImport("user32.dll")] + private static extern IntPtr GetForegroundWindow(); + + [System.Runtime.InteropServices.DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); + + private int _fpsDebugCounter = 0; + + private void OnRenderFrame(object sender, EventArgs e) + { + // === 1. FPS GOVERNOR (ThwargLauncher Safe PID Version) === + // This manages CPU usage by throttling frames when the window is in the background. + if (_settings.EnableFPSLimit) + { + // Get the window currently on top of everything + IntPtr foregroundWindow = GetForegroundWindow(); + + // Get the Process ID of that foreground window + GetWindowThreadProcessId(foregroundWindow, out uint foregroundPid); + + // Get the Process ID of THIS specific AC client + uint thisPid = (uint)System.Diagnostics.Process.GetCurrentProcess().Id; + + // If the PIDs match, this specific client is the one being looked at + bool isFocused = (foregroundPid == thisPid); + int targetFPS = isFocused ? _settings.TargetFPSFocused : _settings.TargetFPSBackground; + + // --- THE SPY (Debug logging to chat) --- + _fpsDebugCounter++; + if (_fpsDebugCounter >= (isFocused ? 200 : 50)) + { + _fpsDebugCounter = 0; + // Uncomment the line below if you need to debug FPS stability + // Host.Actions.AddChatText($"[RynthFPS] PID: {thisPid} | Mode: {(isFocused ? "FOCUSED" : "BACKGROUND")} | Target: {targetFPS} FPS", 1); + } + + // Calculate timing: 1000ms / Target + double minFrameTimeMs = 1000.0 / Math.Max(targetFPS, 1); + + while (_frameTimer.Elapsed.TotalMilliseconds < minFrameTimeMs) + { + // Use Sleep(1) for background to save massive CPU; Sleep(0) for focus to maintain responsiveness + System.Threading.Thread.Sleep(isFocused ? 0 : 1); + } + _frameTimer.Restart(); + } + + // === 2. DEFENSIVE LUA HEARTBEAT === + // Ensures the Lua environment stays alive and ticks the OnBotTick() function. + if (DateTime.Now > _nextLuaTick) + { + _nextLuaTick = DateTime.Now.AddMilliseconds(250); + if (_luaManager != null && _settings.IsMacroRunning) + { + // Safety check to prevent "nil value" crashes if the user hasn't defined OnBotTick + _luaManager.ExecuteString("if OnBotTick ~= nil then OnBotTick() end"); + } + } + + // === 2.5 NATIVE JUMPER === + // Ticks the jump state machine (runs even when macro is paused for jumping) + _jumper?.Think(); + + // === 3. CORE BOT LOGIC === + // If the macro is off, we stop here. + // Note: UI Rendering should stay in MainHud_OnRender to keep the ImGui lifecycle clean. + if (!_settings.IsMacroRunning) return; + + // 3a. Meta System (Decides what the bot should be doing) + _metaManager?.Think(); + + // 3b. Maintenance (Buffs, Vitals, Recharging) — ALWAYS runs first regardless of priority + _buffManager?.OnHeartbeat(); + + // If buffing claimed the state, yield everything else this frame + if (_settings.CurrentState == "Buffing") return; + + // 3c. INVENTORY MANAGEMENT + // Salvage blocks everything until complete — prevents items piling up. + if (_lootManager != null && _settings.IsMacroRunning) + { + _lootManager.ProcessSalvage(); + + if (_lootManager.IsSalvageProcessing) + return; // Block combat, nav, AND looting until salvage finishes + + // Missile crafting runs after salvage, before stack/cram. + if (_missileCraftingManager != null) + { + _missileCraftingManager.ProcessCrafting(); + if (_missileCraftingManager.IsCrafting) + return; // Block combat, nav, looting until crafting finishes + } + + _lootManager.ProcessStack(); + _lootManager.ProcessCram(); + } + + // 3d. PRIORITY DISPATCHER + // Reset the traffic light to Idle at the start of each frame. + // Each subsystem will claim the state if it has active work to do. + // This prevents stale states from previous frames blocking subsystems + // (e.g., "Looting" state lingering and preventing Navigation from running). + _settings.CurrentState = "Idle"; + + // Determines the order that Combat, Navigation, and Looting run in. + // + // Default: Combat → Loot → Nav + // NavPriorityBoost ON: Nav → Combat → Loot + // LootPriorityBoost ON: Loot → Combat → Nav + // Both boosts ON: Nav → Loot → Combat + // + // Each subsystem checks _settings.CurrentState as a traffic light. + // The FIRST system to claim the state blocks the others. + + bool navBoost = _settings.BoostNavPriority; + bool lootBoost = _settings.BoostLootPriority; + + if (navBoost && lootBoost) + { + RunNavigation(); + RunLooting(); + RunCombat(); + } + else if (navBoost) + { + RunNavigation(); + RunCombat(); + RunLooting(); + } + else if (lootBoost) + { + RunLooting(); + RunCombat(); + RunNavigation(); + } + else + { + RunCombat(); + RunLooting(); + RunNavigation(); + } + } + + // ── Priority Dispatcher Helpers ────────────────────────────────────── + // Each checks if the state is still "Idle" before claiming it. + // Once a system claims the state, later systems in the priority chain yield. + + private void RunCombat() + { + if (!_settings.EnableCombat) return; + // Yield if a higher-priority system already claimed the state this frame + if (_settings.CurrentState != "Idle") return; + _combatManager?.OnHeartbeat(); + } + + private void RunNavigation() + { + // Yield if a higher-priority system already claimed the state this frame + if (_settings.CurrentState != "Idle") return; + // Pause nav if there are unlooted corpses nearby — let looting finish first + if (_settings.EnableLooting && (_lootManager?.HasUnlootedCorpsesNearby() ?? false)) return; + bool isFighting = _settings.EnableCombat && (_combatManager?.activeTargetId ?? 0) != 0; + _navigationManager?.ProcessNavigation(isFighting); + } + + private void RunLooting() + { + // Yield if a higher-priority system already claimed the state this frame + if (_settings.CurrentState != "Idle" && _settings.CurrentState != "Looting") return; + _lootManager?.OnHeartbeat(); + } + + private void OnChatBoxMessage(object sender, ChatTextInterceptEventArgs e) + { + try + { + // Feed the chat text to your sub-managers + _metaManager?.HandleChat(e.Text); + _combatManager?.HandleChatForDebuffs(e.Text); + _missileCraftingManager?.HandleChat(e.Text); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(ex.ToString()); + } + } + + + + private double ParseCoord(string val) + { + if (string.IsNullOrEmpty(val)) return 0; + + // Remove letters and whitespace, then parse the number + string clean = System.Text.RegularExpressions.Regex.Replace(val, "[^0-9.-]", ""); + if (!double.TryParse(clean, out double result)) return 0; + + // If it contains S or W, it must be negative for the coordinate system + if (val.ToUpper().Contains("S") || val.ToUpper().Contains("W")) + return -result; + + return result; + } + } +} diff --git a/Plugins/RynthAi/Raycasting/BlacklistManager.cs b/Plugins/RynthAi/Raycasting/BlacklistManager.cs new file mode 100644 index 0000000..3b60488 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/BlacklistManager.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + public class BlacklistManager + { + /// <summary> + /// Tracks consecutive failures for specific WorldObjects. + /// Incremented when an attack on a target produces no server feedback. + /// </summary> + private readonly Dictionary<int, int> _failureCounts = new Dictionary<int, int>(); + + /// <summary> + /// Tracks the expiration time for blacklisted targets. + /// Targets are temporarily ignored if they're stuck in walls or ghosts. + /// </summary> + private readonly Dictionary<int, DateTime> _blacklistExpirations = new Dictionary<int, DateTime>(); + + /// <summary> + /// Number of consecutive attack failures before a target is blacklisted. + /// Default: 3 attempts (adjustable for different difficulty settings). + /// </summary> + public int AttemptThreshold { get; set; } = 3; + + /// <summary> + /// Duration in seconds that a target remains blacklisted after threshold is breached. + /// Default: 30 seconds (allows time for stuck/ghost detection to resolve). + /// </summary> + public int TimeoutSeconds { get; set; } = 30; + + /// <summary> + /// Increments the failure count for a target. + /// Call this if an attack is launched but yields no server feedback (damage, XP, etc.). + /// If the failure count reaches the threshold, the target is automatically blacklisted. + /// </summary> + public void ReportFailure(int targetId) + { + if (!_failureCounts.ContainsKey(targetId)) + _failureCounts[targetId] = 0; + + _failureCounts[targetId]++; + + // Log the failure for debugging + System.Diagnostics.Debug.WriteLine($"Target {targetId} failure count: {_failureCounts[targetId]}/{AttemptThreshold}"); + + // If the threshold is breached, blacklist the target + if (_failureCounts[targetId] >= AttemptThreshold) + { + BlacklistTarget(targetId); + } + } + + /// <summary> + /// Immediately blacklists a target for the configured timeout duration. + /// </summary> + private void BlacklistTarget(int targetId) + { + DateTime expirationTime = DateTime.Now.AddSeconds(TimeoutSeconds); + _blacklistExpirations[targetId] = expirationTime; + + System.Diagnostics.Debug.WriteLine($"Target {targetId} blacklisted until {expirationTime:HH:mm:ss}"); + } + + /// <summary> + /// Checks if a target should be ignored by the targeting system. + /// Returns true if the target is currently blacklisted (timeout not expired). + /// Returns false if the target is not blacklisted or if its timeout has expired. + /// </summary> + public bool IsBlacklisted(int targetId) + { + if (!_blacklistExpirations.TryGetValue(targetId, out var expiration)) + return false; // Target not in blacklist + + // Check if blacklist timeout has expired + if (DateTime.Now >= expiration) + { + // Timeout expired - remove from blacklist and allow re-evaluation + _blacklistExpirations.Remove(targetId); + _failureCounts.Remove(targetId); + System.Diagnostics.Debug.WriteLine($"Target {targetId} blacklist expired, re-evaluating"); + return false; + } + + // Target still blacklisted + return true; + } + + /// <summary> + /// Clears the failure count and blacklist status for a target. + /// Call this when a target successfully takes damage or shows other server feedback. + /// This allows the target to be re-engaged if it becomes blocked again later. + /// </summary> + public void ClearFailure(int targetId) + { + _failureCounts.Remove(targetId); + _blacklistExpirations.Remove(targetId); + System.Diagnostics.Debug.WriteLine($"Target {targetId} failure cleared"); + } + + /// <summary> + /// Completely clears all blacklist and failure tracking data. + /// Useful when transitioning between combat zones or resetting the bot state. + /// </summary> + public void ClearAll() + { + _failureCounts.Clear(); + _blacklistExpirations.Clear(); + System.Diagnostics.Debug.WriteLine("All blacklist data cleared"); + } + + /// <summary> + /// Returns the number of currently blacklisted targets. + /// Useful for debugging and monitoring bot behavior. + /// </summary> + public int GetBlacklistCount() + { + int count = 0; + var expiredKeys = new List<int>(); + + foreach (var kvp in _blacklistExpirations) + { + if (DateTime.Now < kvp.Value) + { + count++; + } + else + { + expiredKeys.Add(kvp.Key); + } + } + + // Clean up expired entries while we're here + foreach (var key in expiredKeys) + { + _blacklistExpirations.Remove(key); + _failureCounts.Remove(key); + } + + return count; + } + } +} diff --git a/Plugins/RynthAi/Raycasting/BoundingVolume.cs b/Plugins/RynthAi/Raycasting/BoundingVolume.cs new file mode 100644 index 0000000..d51cfaf --- /dev/null +++ b/Plugins/RynthAi/Raycasting/BoundingVolume.cs @@ -0,0 +1,245 @@ +using System; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Bounding volume for collision detection + /// Supports ray-volume intersection testing for raycasting + /// </summary> + public class BoundingVolume + { + public enum VolumeType + { + Sphere = 1, + Cylinder = 2, + Ellipsoid = 3, + Polygon = 4, + AxisAlignedBox = 5, + Torus = 6 + } + + public VolumeType Type { get; set; } + public Vector3 Center { get; set; } // X, Y, Z + public Vector3 Dimensions { get; set; } // Radius, Height, etc + public Vector3[] Vertices { get; set; } // For polygons + + // Additional properties for geometry loading + public Vector3 Min { get; set; } // Minimum bounds + public Vector3 Max { get; set; } // Maximum bounds + public bool IsDoor { get; set; } // Whether this is a door (passable) + + public BoundingVolume() + { + Center = new Vector3(0, 0, 0); + Dimensions = new Vector3(0, 0, 0); + Min = new Vector3(0, 0, 0); + Max = new Vector3(0, 0, 0); + IsDoor = false; + } + + /// <summary> + /// Test if a ray intersects this volume + /// Returns true if collision detected + /// </summary> + public bool RayIntersect(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist) + { + hitDist = float.MaxValue; + + try + { + switch (Type) + { + case VolumeType.Sphere: + return RayIntersectSphere(rayStart, rayDir, maxDist, out hitDist); + case VolumeType.Cylinder: + return RayIntersectCylinder(rayStart, rayDir, maxDist, out hitDist); + case VolumeType.AxisAlignedBox: + return RayIntersectAABB(rayStart, rayDir, maxDist, out hitDist); + case VolumeType.Polygon: + return RayIntersectPolygon(rayStart, rayDir, maxDist, out hitDist); + default: + return false; + } + } + catch + { + return false; + } + } + + /// <summary> + /// Overload to accept float arrays for backwards compatibility + /// </summary> + public bool RayIntersect(float[] rayStart, float[] rayDir, float maxDist, out float hitDist) + { + return RayIntersect( + Vector3.FromArray(rayStart), + Vector3.FromArray(rayDir), + maxDist, + out hitDist + ); + } + + /// <summary> + /// Ray-Sphere intersection + /// </summary> + private bool RayIntersectSphere(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist) + { + hitDist = float.MaxValue; + + Vector3 oc = rayStart - Center; + + float a = Vector3.Dot(rayDir, rayDir); + float b = 2.0f * Vector3.Dot(oc, rayDir); + float c = Vector3.Dot(oc, oc) - (Dimensions.X * Dimensions.X); + + float discriminant = b * b - 4 * a * c; + if (discriminant < 0) + return false; + + float sqrt_disc = (float)Math.Sqrt(discriminant); + float t1 = (-b - sqrt_disc) / (2 * a); + float t2 = (-b + sqrt_disc) / (2 * a); + + if (t1 > 0 && t1 < maxDist) + { + hitDist = t1; + return true; + } + + // Ray starts inside sphere (t1 < 0, t2 > 0) + if (t1 <= 0 && t2 > 0 && t2 < maxDist) + { + hitDist = 0; + return true; + } + + return false; + } + + /// <summary> + /// Ray-Cylinder intersection + /// </summary> + private bool RayIntersectCylinder(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist) + { + hitDist = float.MaxValue; + return false; + } + + /// <summary> + /// Ray-AABB intersection + /// </summary> + private bool RayIntersectAABB(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist) + { + hitDist = float.MaxValue; + + float tmin = 0, tmax = maxDist; + + for (int i = 0; i < 3; i++) + { + float rayStartCoord = i == 0 ? rayStart.X : (i == 1 ? rayStart.Y : rayStart.Z); + float rayDirCoord = i == 0 ? rayDir.X : (i == 1 ? rayDir.Y : rayDir.Z); + float minCoord = i == 0 ? Min.X : (i == 1 ? Min.Y : Min.Z); + float maxCoord = i == 0 ? Max.X : (i == 1 ? Max.Y : Max.Z); + + if (Math.Abs(rayDirCoord) < 0.00001f) + { + if (rayStartCoord < minCoord || rayStartCoord > maxCoord) + return false; + } + else + { + float t1 = (minCoord - rayStartCoord) / rayDirCoord; + float t2 = (maxCoord - rayStartCoord) / rayDirCoord; + + if (t1 > t2) + { + float temp = t1; + t1 = t2; + t2 = temp; + } + + tmin = Math.Max(tmin, t1); + tmax = Math.Min(tmax, t2); + + if (tmin > tmax) + return false; + } + } + + if (tmin > 0 && tmin < maxDist) + { + hitDist = tmin; + return true; + } + + // Ray starts inside the box (tmin <= 0 but tmax > 0) + // This means the player is inside/overlapping the obstacle + if (tmin <= 0 && tmax > 0 && tmax < maxDist) + { + hitDist = 0; + return true; + } + + return false; + } + + /// <summary> + /// Ray-Polygon intersection + /// </summary> + private bool RayIntersectPolygon(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist) + { + hitDist = float.MaxValue; + if (Vertices == null || Vertices.Length < 3) + return false; + + for (int i = 0; i < Vertices.Length - 2; i++) + { + if (RayIntersectTriangle(rayStart, rayDir, Vertices[0], Vertices[i + 1], Vertices[i + 2], out float t)) + { + if (t >= 0 && t < maxDist && t < hitDist) + { + hitDist = t; + return true; + } + } + } + + return false; + } + + /// <summary> + /// Ray-Triangle intersection (Möller-Trumbore algorithm) + /// </summary> + private bool RayIntersectTriangle(Vector3 rayStart, Vector3 rayDir, Vector3 v0, Vector3 v1, Vector3 v2, out float t) + { + t = float.MaxValue; + const float EPSILON = 0.0000001f; + + Vector3 edge1 = v1 - v0; + Vector3 edge2 = v2 - v0; + + Vector3 h = Vector3.Cross(rayDir, edge2); + float a = Vector3.Dot(edge1, h); + + if (a > -EPSILON && a < EPSILON) + return false; + + float f = 1.0f / a; + Vector3 s = rayStart - v0; + + float u = f * Vector3.Dot(s, h); + if (u < 0 || u > 1) + return false; + + Vector3 q = Vector3.Cross(s, edge1); + float v = f * Vector3.Dot(rayDir, q); + + if (v < 0 || u + v > 1) + return false; + + t = f * Vector3.Dot(edge2, q); + return t >= 0; + } + } +} diff --git a/Plugins/RynthAi/Raycasting/DatDatabase.cs b/Plugins/RynthAi/Raycasting/DatDatabase.cs new file mode 100644 index 0000000..cd93aa0 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/DatDatabase.cs @@ -0,0 +1,321 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// AC .dat file reader — ported directly from ACEmulator's DatLoader. + /// + /// Key format details (from ACE source): + /// - Header at file offset 0x140 + /// - Block chain: FIRST 4 bytes of each block = next block address (byte offset) + /// Remaining (BlockSize - 4) bytes = data + /// - B-tree node (DatDirectoryHeader): 62 branches, entry count, 61 entries × 24 bytes = 1716 total + /// - All pointers (BTree root, chain pointers, file offsets) are byte offsets + /// </summary> + public class DatDatabase : IDisposable + { + private FileStream _stream; + private readonly object _lock = new object(); + + private const uint DAT_HEADER_OFFSET = 0x140; + + // B-tree geometry (from ACE DatDirectoryHeader.cs): + // 0x3E (62) branches, 0x3D (61) max entries, each entry = 6 × uint32 = 24 bytes + // ObjectSize = (4 * 62) + 4 + (24 * 61) = 248 + 4 + 1464 = 1716 + private const int BTREE_BRANCH_COUNT = 0x3E; // 62 + private const int BTREE_MAX_ENTRIES = 0x3D; // 61 + private const int BTREE_ENTRY_SIZE = 24; // 6 × uint32 + private const int BTREE_NODE_SIZE = (4 * BTREE_BRANCH_COUNT) + 4 + (BTREE_ENTRY_SIZE * BTREE_MAX_ENTRIES); // 1716 + + // Header fields + public uint FileType { get; private set; } + public uint BlockSize { get; private set; } + public uint FileSize { get; private set; } + public uint DataSet { get; private set; } + public uint BTreeRoot { get; private set; } // Byte offset + + public bool IsLoaded { get; private set; } + public string FilePath { get; private set; } + public int RecordCount { get; private set; } + + // All files indexed by ObjectId (populated during Open) + private readonly Dictionary<uint, DatBTreeEntry> _allFiles = new Dictionary<uint, DatBTreeEntry>(); + + public List<string> DiagLog { get; } = new List<string>(); + + public bool Open(string path) + { + try + { + if (!File.Exists(path)) + { + Log($"File not found: {path}"); + return false; + } + + FilePath = path; + _stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + + Log($"File: {Path.GetFileName(path)}, Size: {_stream.Length:N0} bytes"); + + if (!ReadHeader()) + { + Close(); + return false; + } + + // Read the entire B-tree directory and index all files + ReadDirectory(BTreeRoot); + + RecordCount = _allFiles.Count; + IsLoaded = true; + + Log($"SUCCESS: {RecordCount} files indexed, BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}"); + + return true; + } + catch (Exception ex) + { + Log($"Error: {ex.Message}"); + Close(); + return false; + } + } + + /// <summary> + /// Reads the dat header from offset 0x140. + /// Format matches ACE's DatDatabaseHeader.Unpack(). + /// </summary> + private bool ReadHeader() + { + if (_stream.Length < DAT_HEADER_OFFSET + 64) + { + Log("File too small"); + return false; + } + + _stream.Seek(DAT_HEADER_OFFSET, SeekOrigin.Begin); + using (var reader = new BinaryReader(_stream, System.Text.Encoding.Default, true)) + { + FileType = reader.ReadUInt32(); + BlockSize = reader.ReadUInt32(); + FileSize = reader.ReadUInt32(); + DataSet = reader.ReadUInt32(); + uint dataSubset = reader.ReadUInt32(); + + uint freeHead = reader.ReadUInt32(); + uint freeTail = reader.ReadUInt32(); + uint freeCount = reader.ReadUInt32(); + BTreeRoot = reader.ReadUInt32(); + } + + Log($"FileType=0x{FileType:X8}, BlockSize={BlockSize}, DataSet={DataSet}, BTree=0x{BTreeRoot:X8}"); + + if (BlockSize == 0 || BTreeRoot == 0 || BTreeRoot >= (uint)_stream.Length) + { + Log("Invalid header values"); + return false; + } + + return true; + } + + /// <summary> + /// Reads data from the dat file following the block chain. + /// Matches ACE's DatReader.ReadDat() exactly. + /// + /// Block format: + /// [4 bytes: next block address] [BlockSize - 4 bytes: data] + /// + /// The FIRST 4 bytes of each block are the chain pointer (next block address). + /// If 0, this is the last block. + /// </summary> + private byte[] ReadDatData(uint offset, int size) + { + if (offset + BlockSize > (uint)_stream.Length || size <= 0) + return null; + + byte[] buffer = new byte[size]; + + _stream.Seek(offset, SeekOrigin.Begin); + + // Read first 4 bytes = next block address + byte[] addrBuf = new byte[4]; + _stream.Read(addrBuf, 0, 4); + uint nextAddress = BitConverter.ToUInt32(addrBuf, 0); + + int bufferOffset = 0; + int remaining = size; + + while (remaining > 0) + { + if (nextAddress == 0) + { + // Last block — read remaining data directly + int toRead = Math.Min(remaining, (int)(_stream.Length - _stream.Position)); + if (toRead <= 0) break; + _stream.Read(buffer, bufferOffset, toRead); + remaining = 0; + } + else + { + // Read data portion of this block (BlockSize - 4 bytes) + int dataInBlock = (int)BlockSize - 4; + int toRead = Math.Min(dataInBlock, remaining); + _stream.Read(buffer, bufferOffset, toRead); + bufferOffset += toRead; + remaining -= toRead; + + if (remaining > 0) + { + // Follow chain to next block + if (nextAddress >= (uint)_stream.Length) break; + _stream.Seek(nextAddress, SeekOrigin.Begin); + + // Read next block's chain pointer + _stream.Read(addrBuf, 0, 4); + nextAddress = BitConverter.ToUInt32(addrBuf, 0); + } + } + } + + return buffer; + } + + /// <summary> + /// Recursively reads the B-tree directory and indexes all files. + /// Matches ACE's DatDirectory.Read() + AddFilesToList(). + /// </summary> + private void ReadDirectory(uint sectorOffset) + { + if (sectorOffset == 0 || sectorOffset >= (uint)_stream.Length) + return; + + // Read the directory header (B-tree node) + byte[] nodeData; + lock (_lock) + { + nodeData = ReadDatData(sectorOffset, BTREE_NODE_SIZE); + } + + if (nodeData == null || nodeData.Length < BTREE_NODE_SIZE) + return; + + // Parse branches (62 × uint32) + uint[] branches = new uint[BTREE_BRANCH_COUNT]; + for (int i = 0; i < BTREE_BRANCH_COUNT; i++) + branches[i] = BitConverter.ToUInt32(nodeData, i * 4); + + // Parse entry count + int countOffset = BTREE_BRANCH_COUNT * 4; // 248 + uint entryCount = BitConverter.ToUInt32(nodeData, countOffset); + + if (entryCount > BTREE_MAX_ENTRIES) + return; // Invalid node + + // Parse entries + int entriesOffset = countOffset + 4; // 252 + var entries = new DatBTreeEntry[entryCount]; + + for (int i = 0; i < entryCount; i++) + { + int eOff = entriesOffset + i * BTREE_ENTRY_SIZE; + entries[i] = new DatBTreeEntry + { + BitFlags = BitConverter.ToUInt32(nodeData, eOff), + ObjectId = BitConverter.ToUInt32(nodeData, eOff + 4), + FileOffset = BitConverter.ToUInt32(nodeData, eOff + 8), + FileSize = BitConverter.ToUInt32(nodeData, eOff + 12) + }; + } + + // Recurse into child directories (if branches[0] != 0, node has children) + if (branches[0] != 0) + { + for (int i = 0; i < entryCount + 1 && i < BTREE_BRANCH_COUNT; i++) + { + if (branches[i] != 0) + ReadDirectory(branches[i]); + } + } + + // Add entries to the file index + for (int i = 0; i < entryCount; i++) + { + if (entries[i].ObjectId != 0) + _allFiles[entries[i].ObjectId] = entries[i]; + } + } + + /// <summary> + /// Finds a file by ID. O(1) lookup from the pre-built index. + /// </summary> + public DatBTreeEntry FindFile(uint fileId) + { + if (!IsLoaded) return null; + _allFiles.TryGetValue(fileId, out var entry); + return entry; + } + + /// <summary> + /// Reads file data for a given entry. + /// </summary> + public byte[] ReadFileData(DatBTreeEntry entry) + { + if (!IsLoaded || entry == null || entry.FileSize == 0 || _stream == null) + return null; + + lock (_lock) + { + return ReadDatData(entry.FileOffset, (int)entry.FileSize); + } + } + + public byte[] GetFileData(uint fileId) + { + var entry = FindFile(fileId); + return entry != null ? ReadFileData(entry) : null; + } + + /// <summary> + /// Returns sample file IDs from the index for diagnostics. + /// </summary> + public List<uint> GetSampleIds(int maxCount = 20) + { + var ids = new List<uint>(); + foreach (var kvp in _allFiles) + { + ids.Add(kvp.Key); + if (ids.Count >= maxCount) break; + } + return ids; + } + + public void Close() + { + _stream?.Dispose(); + _stream = null; + IsLoaded = false; + _allFiles.Clear(); + } + + public void Dispose() { Close(); } + + private void Log(string msg) + { + string line = $"[DatDB] {msg}"; + System.Diagnostics.Debug.WriteLine(line); + if (DiagLog.Count < 100) DiagLog.Add(line); + } + } + + public class DatBTreeEntry + { + public uint BitFlags; + public uint ObjectId; + public uint FileOffset; // Byte offset into file + public uint FileSize; + } +} diff --git a/Plugins/RynthAi/Raycasting/DungeonLOS.cs b/Plugins/RynthAi/Raycasting/DungeonLOS.cs new file mode 100644 index 0000000..cb84bca --- /dev/null +++ b/Plugins/RynthAi/Raycasting/DungeonLOS.cs @@ -0,0 +1,658 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Extracts dungeon wall geometry from cell.dat Environment files for raycasting. + /// + /// Pipeline: + /// EnvCell (0xXXYY01nn) → EnvironmentId (0x0Dxxxx) + CellStructure index + /// Environment (0x0Dxxxx) → CellStruct at index → Vertices + Polygons + /// Transform polygon vertices by cell position → BoundingVolumes for raycasting + /// + /// Binary formats (from ACE source): + /// SWVertex: ushort numUVs, float3 Origin, float3 Normal, Vec2Duv[numUVs] + /// CVertexArray: int32 type=1, uint32 count, (ushort key + SWVertex)[count] + /// Polygon: byte numPts, byte stippling, int32 sidesType, short posSurf, short negSurf, + /// short[numPts] vertexIds, byte[numPts] posUV (if !NoPos), byte[numPts] negUV (if clockwise+!NoNeg) + /// CellStruct: uint32 numPolygons, uint32 numPhysicsPolygons, uint32 numPortals, + /// CVertexArray, Dictionary{ushort,Polygon}[numPolygons], ... + /// </summary> + public class DungeonLOS + { + private DatDatabase _portalDat; + private DatDatabase _cellDat; + + // Cache: EnvironmentId → parsed CellStruct geometry per structure index + private readonly Dictionary<uint, Dictionary<uint, CellGeometry>> _envCache = + new Dictionary<uint, Dictionary<uint, CellGeometry>>(); + + // Cache: landblock → dungeon wall volumes + private readonly Dictionary<uint, List<BoundingVolume>> _wallCache = + new Dictionary<uint, List<BoundingVolume>>(); + + private const int MAX_ENV_CACHE = 50; + private const int MAX_WALL_CACHE = 20; + + public void Initialize(DatDatabase portalDat, DatDatabase cellDat) + { + _portalDat = portalDat; + _cellDat = cellDat; + } + + /// <summary> + /// Gets dungeon wall collision volumes for a landblock. + /// Returns empty list for outdoor-only landblocks. + /// </summary> + public List<BoundingVolume> GetDungeonWalls(uint landblockKey) + { + if (_wallCache.TryGetValue(landblockKey, out var cached)) + return cached; + + var walls = LoadDungeonWalls(landblockKey); + + if (_wallCache.Count >= MAX_WALL_CACHE) + { + foreach (var key in _wallCache.Keys) { _wallCache.Remove(key); break; } + } + _wallCache[landblockKey] = walls; + return walls; + } + + private List<BoundingVolume> LoadDungeonWalls(uint landblockKey) + { + var volumes = new List<BoundingVolume>(); + if (_cellDat == null || _portalDat == null) return volumes; + + uint baseId = landblockKey << 16; + float globalOffsetX = ((landblockKey >> 8) & 0xFF) * 192.0f; + float globalOffsetY = (landblockKey & 0xFF) * 192.0f; + + int consecutiveMisses = 0; + for (uint cellNum = 0x0100; cellNum <= 0xFFFD; cellNum++) + { + uint cellId = baseId | cellNum; + byte[] cellData = _cellDat.GetFileData(cellId); + if (cellData == null) + { + consecutiveMisses++; + if (consecutiveMisses > 10) break; + continue; + } + consecutiveMisses = 0; + if (cellData.Length < 20) continue; + + try + { + var envCell = ParseEnvCellHeader(cellData); + if (envCell == null) continue; + + var cellGeo = GetCellGeometry(envCell.EnvironmentId, envCell.CellStructureIndex); + if (cellGeo == null || cellGeo.Polygons.Count == 0) continue; + + foreach (var poly in cellGeo.Polygons) + { + if (poly.Vertices.Count < 3) continue; + + // Transform vertices to world space + var worldVerts = new List<Vector3>(); + foreach (var localVert in poly.Vertices) + worldVerts.Add(TransformVertex(localVert, envCell, globalOffsetX, globalOffsetY)); + + // Compute AABB from all vertices of the polygon + var min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); + var max = new Vector3(float.MinValue, float.MinValue, float.MinValue); + foreach (var wv in worldVerts) + { + min = Vector3.Min(min, wv); + max = Vector3.Max(max, wv); + } + + var size = max - min; + if (size.X < 0.01f && size.Y < 0.01f && size.Z < 0.01f) continue; + + // Thicken walls to seal corner gaps. Where two perpendicular walls meet, + // we may be missing one wall's geometry (unparsed CellStruct). + // 0.5 yards ensures the existing walls overlap at corners. + // Portal polygons are excluded so doorways stay open. + // 1.0 yard skin on thin axes — creates 2 yard total thickness. + // Seals corner jut-outs where perpendicular walls meet. + // Portal polygons are excluded so doorways stay open. + float wallSkin = 0.5f; + if (size.X < wallSkin) { min.X -= wallSkin; max.X += wallSkin; } + if (size.Y < wallSkin) { min.Y -= wallSkin; max.Y += wallSkin; } + + volumes.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.AxisAlignedBox, + Center = (min + max) * 0.5f, + Dimensions = max - min, + Min = min, + Max = max, + IsDoor = false + }); + } + } + catch { } + } + + if (volumes.Count > 0) + Log($"Landblock 0x{landblockKey:X4}: {volumes.Count} dungeon wall volumes"); + + return volumes; + } + + private Vector3 TransformVertex(Vector3 local, EnvCellHeader cell, float gx, float gy) + { + Vector3 rotated = RotateByQuat(local, cell.RotW, cell.RotX, cell.RotY, cell.RotZ); + return new Vector3( + rotated.X + cell.PosX + gx, + rotated.Y + cell.PosY + gy, + rotated.Z + cell.PosZ + ); + } + + private Vector3 RotateByQuat(Vector3 v, float qw, float qx, float qy, float qz) + { + float cx = qy * v.Z - qz * v.Y; + float cy = qz * v.X - qx * v.Z; + float cz = qx * v.Y - qy * v.X; + float cx2 = qy * cz - qz * cy; + float cy2 = qz * cx - qx * cz; + float cz2 = qx * cy - qy * cx; + return new Vector3( + v.X + 2f * (qw * cx + cx2), + v.Y + 2f * (qw * cy + cy2), + v.Z + 2f * (qw * cz + cz2) + ); + } + + // =================================================================== + // EnvCell header parsing + // =================================================================== + + private class EnvCellHeader + { + public uint EnvironmentId; + public uint CellStructureIndex; + public float PosX, PosY, PosZ; + public float RotW, RotX, RotY, RotZ; + } + + private EnvCellHeader ParseEnvCellHeader(byte[] data) + { + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); + uint flags = reader.ReadUInt32(); + reader.ReadUInt32(); // duplicate CellId + + byte numSurfaces = reader.ReadByte(); + byte numPortals = reader.ReadByte(); + ushort numVisibleCells = reader.ReadUInt16(); + + ms.Seek(numSurfaces * 2, SeekOrigin.Current); + + ushort envIdShort = reader.ReadUInt16(); + ushort cellStructure = reader.ReadUInt16(); + + return new EnvCellHeader + { + EnvironmentId = 0x0D000000u | envIdShort, + CellStructureIndex = cellStructure, + PosX = reader.ReadSingle(), + PosY = reader.ReadSingle(), + PosZ = reader.ReadSingle(), + RotW = reader.ReadSingle(), + RotX = reader.ReadSingle(), + RotY = reader.ReadSingle(), + RotZ = reader.ReadSingle() + }; + } + } + catch { return null; } + } + + // =================================================================== + // Environment + CellStruct parsing + // =================================================================== + + private class CellGeometry + { + public List<CellPolygon> Polygons = new List<CellPolygon>(); + } + + private class CellPolygon + { + public List<Vector3> Vertices = new List<Vector3>(); + } + + private CellGeometry GetCellGeometry(uint environmentId, uint cellStructIndex) + { + if (_envCache.TryGetValue(environmentId, out var envCells)) + { + if (envCells.TryGetValue(cellStructIndex, out var cached)) + return cached; + } + + byte[] envData = _portalDat.GetFileData(environmentId); + if (envData == null || envData.Length < 8) return null; + + if (envCells == null) + { + envCells = ParseEnvironment(envData); + if (_envCache.Count >= MAX_ENV_CACHE) + { + foreach (var key in _envCache.Keys) { _envCache.Remove(key); break; } + } + _envCache[environmentId] = envCells; + } + + envCells.TryGetValue(cellStructIndex, out var result); + return result; + } + + private Dictionary<uint, CellGeometry> ParseEnvironment(byte[] data) + { + var result = new Dictionary<uint, CellGeometry>(); + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); + + // Dictionary<uint, CellStruct> + uint numCells = reader.ReadUInt32(); + if (numCells > 200) return result; + + for (uint i = 0; i < numCells; i++) + { + if (ms.Position + 4 > ms.Length) break; + uint key = reader.ReadUInt32(); + + var geo = ParseCellStruct(reader, ms); + if (geo != null) + result[key] = geo; + else + { + Log($"Environment 0x{id:X8}: failed parsing CellStruct {i} (key={key}), stopping"); + break; // Stream position unknown — can't continue + } + } + } + } + catch (Exception ex) + { + Log($"Environment parse error: {ex.Message}"); + } + + if (result.Count > 0) + Log($"Environment: parsed {result.Count} CellStructs successfully"); + + return result; + } + + /// <summary> + /// Parses CellStruct: vertices + rendering polygons + portal indices. + /// NOW ALSO SKIPS BSP trees so we can continue to the next CellStruct. + /// </summary> + private CellGeometry ParseCellStruct(BinaryReader reader, MemoryStream ms) + { + var geo = new CellGeometry(); + + try + { + uint numPolygons = reader.ReadUInt32(); + uint numPhysicsPolygons = reader.ReadUInt32(); + uint numPortals = reader.ReadUInt32(); + + if (numPolygons > 5000 || numPhysicsPolygons > 5000) return null; + + var vertices = ParseVertexArray(reader, ms); + if (vertices == null) return null; + + var polygons = ParsePolygons(reader, ms, numPolygons); + if (polygons == null) return null; + + // Read portal polygon indices + var portalIndices = new HashSet<ushort>(); + for (uint p = 0; p < numPortals && ms.Position + 2 <= ms.Length; p++) + portalIndices.Add(reader.ReadUInt16()); + + // Align to 4-byte boundary + long aligned = (ms.Position + 3) & ~3L; + if (aligned <= ms.Length) ms.Position = aligned; + + // BUILD polygon geometry NOW, before BSP skip attempt. + // If BSP skip fails we still have the wall data. + for (int i = 0; i < polygons.Count; i++) + { + var poly = polygons[i]; + if (portalIndices.Contains(poly.Key)) continue; + if (poly.VertexIds == null || poly.VertexIds.Count < 3) continue; + + var cellPoly = new CellPolygon(); + foreach (var vid in poly.VertexIds) + { + if (vertices.ContainsKey(vid)) + cellPoly.Vertices.Add(vertices[vid]); + } + + if (cellPoly.Vertices.Count >= 3) + geo.Polygons.Add(cellPoly); + } + + // Now attempt to skip BSP trees so ParseEnvironment can read the next CellStruct. + // If this fails, we still have this CellStruct's geometry — we just can't parse further. + bool canContinue = true; + + // Skip CellBSP + if (!SkipBSPTree(reader, ms, BSPTreeType.Cell)) + canContinue = false; + + // Skip PhysicsPolygons + if (canContinue && !SkipPolygons(reader, ms, numPhysicsPolygons)) + canContinue = false; + + // Skip PhysicsBSP + if (canContinue && !SkipBSPTree(reader, ms, BSPTreeType.Physics)) + canContinue = false; + + // Skip optional DrawingBSP + if (canContinue && ms.Position + 4 <= ms.Length) + { + uint hasDrawingBSP = reader.ReadUInt32(); + if (hasDrawingBSP != 0) + { + if (!SkipBSPTree(reader, ms, BSPTreeType.Drawing)) + canContinue = false; + } + } + + // Final alignment + if (canContinue) + { + aligned = (ms.Position + 3) & ~3L; + if (aligned <= ms.Length) ms.Position = aligned; + } + + // Return geometry. If canContinue is false, ParseEnvironment will break + // at the next iteration (stream position wrong), but we keep this CellStruct's data. + return geo; + } + catch + { + return geo.Polygons.Count > 0 ? geo : null; + } + } + + // =================================================================== + // BSP Tree Skipping — matches ACE BSPNode/BSPLeaf exactly + // =================================================================== + + private enum BSPTreeType { Cell, Physics, Drawing } + + // ACE's uint32 constants for BSP node types (read as LE uint32, stored reversed in file) + private const uint BSP_PORT = 0x504F5254; + private const uint BSP_LEAF = 0x4C454146; + private const uint BSP_BPnn = 0x42506E6E; + private const uint BSP_BPIn = 0x4250496E; + private const uint BSP_BpIN = 0x4270494E; + private const uint BSP_BpnN = 0x42706E4E; + private const uint BSP_BPIN = 0x4250494E; + private const uint BSP_BPnN = 0x42506E4E; + + private bool SkipBSPTree(BinaryReader reader, MemoryStream ms, BSPTreeType treeType) + { + return SkipBSPNode(reader, ms, treeType); + } + + private bool SkipBSPNode(BinaryReader reader, MemoryStream ms, BSPTreeType treeType) + { + if (ms.Position + 4 > ms.Length) return false; + uint typeTag = reader.ReadUInt32(); + + if (typeTag == BSP_LEAF) + { + return SkipBSPLeaf(reader, ms, treeType); + } + + if (typeTag == BSP_PORT) + { + // Portal node — same as leaf for our purposes + return SkipBSPLeaf(reader, ms, treeType); + } + + // Internal node: read splitting plane (float3 normal + float dist = 16 bytes) + if (ms.Position + 16 > ms.Length) return false; + ms.Seek(16, SeekOrigin.Current); + + // Read children based on type — matches ACE's switch exactly + switch (typeTag) + { + case BSP_BPnn: + case BSP_BPIn: + // Pos child only + if (!SkipBSPNode(reader, ms, treeType)) return false; + break; + case BSP_BpIN: + case BSP_BpnN: + // Neg child only + if (!SkipBSPNode(reader, ms, treeType)) return false; + break; + case BSP_BPIN: + case BSP_BPnN: + // Both children: Pos then Neg + if (!SkipBSPNode(reader, ms, treeType)) return false; + if (!SkipBSPNode(reader, ms, treeType)) return false; + break; + default: + return false; // Unknown type + } + + // Cell BSP internal nodes have NO sphere — done + if (treeType == BSPTreeType.Cell) + return true; + + // Physics and Drawing: read Sphere (float3 center + float radius = 16 bytes) + if (ms.Position + 16 > ms.Length) return false; + ms.Seek(16, SeekOrigin.Current); + + // Physics: done after sphere + if (treeType == BSPTreeType.Physics) + return true; + + // Drawing: also read InPolys (uint32 count + ushort[count]) + if (ms.Position + 4 > ms.Length) return false; + uint numPolys = reader.ReadUInt32(); + if (numPolys > 100000) return false; + long skip = numPolys * 2L; // ushort per poly + if (ms.Position + skip > ms.Length) return false; + ms.Seek(skip, SeekOrigin.Current); + + return true; + } + + /// <summary> + /// BSPLeaf: uint32 type + int32 leafIndex + (Physics only: int32 solid + Sphere(16) + uint32 numPolys + ushort[numPolys]) + /// Note: Physics leaf ALWAYS reads Sphere even when solid=0 (per ACE source). + /// Cell and Drawing leaves are just type + leafIndex. + /// </summary> + private bool SkipBSPLeaf(BinaryReader reader, MemoryStream ms, BSPTreeType treeType) + { + // Type tag already read by caller. Read leafIndex. + if (ms.Position + 4 > ms.Length) return false; + reader.ReadInt32(); // leafIndex + + if (treeType == BSPTreeType.Physics) + { + // int32 Solid + if (ms.Position + 4 > ms.Length) return false; + reader.ReadInt32(); + + // Sphere: ALWAYS read (16 bytes), even when solid=0 + if (ms.Position + 16 > ms.Length) return false; + ms.Seek(16, SeekOrigin.Current); + + // uint32 numPolys + ushort[numPolys] + if (ms.Position + 4 > ms.Length) return false; + uint numPolys = reader.ReadUInt32(); + if (numPolys > 100000) return false; + long skip = numPolys * 2L; + if (ms.Position + skip > ms.Length) return false; + ms.Seek(skip, SeekOrigin.Current); + } + // Cell and Drawing leaves: nothing more after leafIndex + + return true; + } + + /// <summary> + /// Skips a Dictionary{ushort, Polygon} block — same format as ParsePolygons + /// but doesn't store results. + /// </summary> + private bool SkipPolygons(BinaryReader reader, MemoryStream ms, uint count) + { + for (uint i = 0; i < count; i++) + { + if (ms.Position + 12 > ms.Length) return false; + ushort polyKey = reader.ReadUInt16(); + byte numPts = reader.ReadByte(); + byte stippling = reader.ReadByte(); + int sidesType = reader.ReadInt32(); + ms.Seek(4, SeekOrigin.Current); // posSurf + negSurf + + if (numPts == 0 || numPts > 50) return false; + + // Vertex IDs + long vertBytes = numPts * 2L; + if (ms.Position + vertBytes > ms.Length) return false; + ms.Seek(vertBytes, SeekOrigin.Current); + + // PosUV + if ((stippling & 0x04) == 0) + { + if (ms.Position + numPts > ms.Length) return false; + ms.Seek(numPts, SeekOrigin.Current); + } + + // NegUV + if (sidesType == 2 && (stippling & 0x08) == 0) + { + if (ms.Position + numPts > ms.Length) return false; + ms.Seek(numPts, SeekOrigin.Current); + } + } + return true; + } + + /// <summary> + /// CVertexArray: int32 type(=1) + uint32 count + (ushort key + SWVertex)[count] + /// SWVertex: ushort numUVs + float3 Origin(12) + float3 Normal(12) + numUVs × 8 bytes + /// </summary> + private Dictionary<ushort, Vector3> ParseVertexArray(BinaryReader reader, MemoryStream ms) + { + var verts = new Dictionary<ushort, Vector3>(); + + int vertexType = reader.ReadInt32(); + if (vertexType != 1) return null; + + uint numVerts = reader.ReadUInt32(); + if (numVerts > 50000) return null; + + for (uint i = 0; i < numVerts; i++) + { + if (ms.Position + 28 > ms.Length) break; // key(2) + numUVs(2) + origin(12) + normal(12) + ushort key = reader.ReadUInt16(); + ushort numUVs = reader.ReadUInt16(); + + float ox = reader.ReadSingle(); + float oy = reader.ReadSingle(); + float oz = reader.ReadSingle(); + reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); // normal + + long uvBytes = numUVs * 8L; + if (uvBytes > 0 && ms.Position + uvBytes <= ms.Length) + ms.Seek(uvBytes, SeekOrigin.Current); + + verts[key] = new Vector3(ox, oy, oz); + } + + return verts.Count > 0 ? verts : null; + } + + /// <summary> + /// Dictionary{ushort, Polygon}: count × (ushort key + Polygon) + /// Polygon: byte numPts, byte stippling, int32 sidesType, short posSurf, short negSurf, + /// short[numPts] vertexIds, optional UV index arrays + /// </summary> + private List<ParsedPolygon> ParsePolygons(BinaryReader reader, MemoryStream ms, uint count) + { + var polys = new List<ParsedPolygon>(); + + for (uint i = 0; i < count; i++) + { + if (ms.Position + 12 > ms.Length) return polys; // key(2) + header(10 min) + ushort polyKey = reader.ReadUInt16(); + + byte numPts = reader.ReadByte(); + byte stippling = reader.ReadByte(); + int sidesType = reader.ReadInt32(); + short posSurf = reader.ReadInt16(); + short negSurf = reader.ReadInt16(); + + if (numPts == 0 || numPts > 50) return polys; + + var poly = new ParsedPolygon { Key = polyKey, VertexIds = new List<ushort>() }; + + for (int v = 0; v < numPts; v++) + { + if (ms.Position + 2 > ms.Length) return polys; + poly.VertexIds.Add((ushort)reader.ReadInt16()); + } + + // Skip PosUVIndices (byte per point) unless NoPos flag (0x04) + if ((stippling & 0x04) == 0) + { + if (ms.Position + numPts > ms.Length) return polys; + ms.Seek(numPts, SeekOrigin.Current); + } + + // Skip NegUVIndices if Clockwise(2) and not NoNeg(0x08) + if (sidesType == 2 && (stippling & 0x08) == 0) + { + if (ms.Position + numPts > ms.Length) return polys; + ms.Seek(numPts, SeekOrigin.Current); + } + + polys.Add(poly); + } + + return polys; + } + + private class ParsedPolygon + { + public ushort Key; + public List<ushort> VertexIds; + } + + public void FlushCache() + { + _wallCache.Clear(); + _envCache.Clear(); + } + + private static void Log(string msg) + { + System.Diagnostics.Debug.WriteLine($"[DungeonLOS] {msg}"); + } + } +} diff --git a/Plugins/RynthAi/Raycasting/GeometryLoader.cs b/Plugins/RynthAi/Raycasting/GeometryLoader.cs new file mode 100644 index 0000000..dada214 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/GeometryLoader.cs @@ -0,0 +1,1112 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Loads collision geometry from Asheron's Call's .dat files for raycasting. + /// + /// Pipeline: + /// 1. cell.dat → LandblockInfo (0xXXYYFFFF) → list of static objects + placements + /// 2. portal.dat → Setup (0x02xxxxxx) → bounding sphere + collision volumes + /// 3. portal.dat → GfxObj (0x01xxxxxx) → vertex AABB (fallback if Setup has no bounds) + /// 4. Transform collision volumes by placement frame → BoundingVolume list for raycasting + /// </summary> + public class GeometryLoader : IDisposable + { + private DatDatabase _portalDat; + private DatDatabase _cellDat; + private bool _initialized; + + /// <summary> + /// Public accessor for the cell.dat database, used by DungeonLOS. + /// </summary> + public DatDatabase CellDat => _cellDat; + + /// <summary> + /// Public accessor for the portal.dat database, used by DungeonLOS. + /// </summary> + public DatDatabase PortalDat => _portalDat; + + /// <summary> + /// Cache for loaded landblock geometry. + /// Key: Landblock ID (upper 16 bits, e.g., 0xXXYY), Value: BoundingVolumes. + /// </summary> + private readonly Dictionary<uint, List<BoundingVolume>> _landblockCache = + new Dictionary<uint, List<BoundingVolume>>(); + + /// <summary> + /// Cache for parsed Setup files to avoid re-reading portal.dat. + /// </summary> + private readonly Dictionary<uint, SetupInfo> _setupCache = + new Dictionary<uint, SetupInfo>(); + + private const int MAX_LANDBLOCK_CACHE = 20; + private const int MAX_SETUP_CACHE = 1000; + + /// <summary> + /// Scatter system for procedurally placed terrain objects (trees, rocks, etc.) + /// </summary> + private ScatterSystem _scatterSystem; + + /// <summary> + /// Dungeon wall geometry extractor. + /// </summary> + private DungeonLOS _dungeonLOS; + + // Statistics + public int LandblocksCached => _landblockCache.Count; + public int SetupsCached => _setupCache.Count; + public bool IsInitialized => _initialized; + public string StatusMessage { get; private set; } = "Not initialized"; + public List<string> DiagLog { get; } = new List<string>(); + + /// <summary> + /// Initializes the geometry loader by opening the .dat files. + /// Call this once during plugin startup. + /// </summary> + public bool Initialize(string acFolderPath = null) + { + try + { + string folder = acFolderPath ?? FindACFolder(); + if (string.IsNullOrEmpty(folder)) + { + StatusMessage = "AC installation folder not found"; + Log(StatusMessage); + return false; + } + + Log($"Using AC folder: {folder}"); + + // Find portal.dat — try all known filenames + string portalPath = FindDatFile(folder, new[] { + "client_portal.dat", "portal.dat", "client_portal_dat" + }); + string cellPath = FindDatFile(folder, new[] { + "client_cell_1.dat", "cell.dat", "client_cell_1_dat" + }); + + if (portalPath == null) + { + // List what files ARE in the folder for diagnostics + string files = ""; + try + { + foreach (var f in Directory.GetFiles(folder, "*.dat")) + files += Path.GetFileName(f) + ", "; + } + catch { } + StatusMessage = $"No portal.dat found in {folder}. Files: {files}"; + Log(StatusMessage); + return false; + } + + if (cellPath == null) + { + StatusMessage = $"No cell.dat found in {folder}"; + Log(StatusMessage); + return false; + } + + Log($"Portal: {portalPath}"); + Log($"Cell: {cellPath}"); + + // Open portal.dat + _portalDat = new DatDatabase(); + if (!_portalDat.Open(portalPath)) + { + StatusMessage = $"Failed to open {Path.GetFileName(portalPath)}"; + // Include ALL diagnostic info so user can report it + foreach (var msg in _portalDat.DiagLog) + Log(msg); + if (_portalDat.DiagLog.Count > 0) + StatusMessage += " — " + string.Join(" | ", _portalDat.DiagLog); + Log(StatusMessage); + return false; + } + + // Open cell.dat + _cellDat = new DatDatabase(); + if (!_cellDat.Open(cellPath)) + { + StatusMessage = $"Failed to open {Path.GetFileName(cellPath)}"; + if (_cellDat.DiagLog.Count > 0) + StatusMessage += " — " + _cellDat.DiagLog[_cellDat.DiagLog.Count - 1]; + Log(StatusMessage); + _portalDat.Dispose(); + return false; + } + + _initialized = true; + StatusMessage = $"portal={_portalDat.RecordCount} entries (BS={_portalDat.BlockSize}), " + + $"cell={_cellDat.RecordCount} entries (BS={_cellDat.BlockSize})"; + Log($"SUCCESS: {StatusMessage}"); + Log($"Portal root=0x{_portalDat.BTreeRoot:X8}, Cell root=0x{_cellDat.BTreeRoot:X8}"); + + // Initialize scatter system for procedural terrain objects + _scatterSystem = new ScatterSystem(); + if (_scatterSystem.Initialize(_portalDat, _cellDat)) + Log("Scatter system initialized"); + else + Log("Scatter system failed to initialize (tree/rock LOS may be limited)"); + + // Initialize dungeon wall geometry extractor + _dungeonLOS = new DungeonLOS(); + _dungeonLOS.Initialize(_portalDat, _cellDat); + Log("Dungeon wall system initialized"); + + // Copy scatter diagnostic logs + if (_scatterSystem.DiagLog.Count > 0) + foreach (var line in _scatterSystem.DiagLog) + Log("[Scatter] " + line); + + return true; + } + catch (Exception ex) + { + StatusMessage = $"Init error: {ex.Message}"; + Log(StatusMessage); + return false; + } + } + + /// <summary> + /// Finds a .dat file by trying multiple possible filenames. + /// </summary> + private string FindDatFile(string folder, string[] names) + { + foreach (var name in names) + { + string path = Path.Combine(folder, name); + if (File.Exists(path)) + return path; + } + return null; + } + + /// <summary> + /// Retrieves collision geometry for a landblock AND its 8 neighbors (3x3 grid). + /// This ensures obstacles near landblock boundaries are always loaded. + /// The landblockId should be the Decal Landcell value (format: 0xXXYYnnnn). + /// </summary> + public List<BoundingVolume> GetLandblockGeometry(uint landcellId) + { + uint landblockKey = (landcellId >> 16) & 0xFFFF; + uint cellPart = landcellId & 0xFFFF; + bool isDungeon = cellPart >= 0x0100; + + if (_landblockCache.TryGetValue(landblockKey, out var cached)) + return cached; + + var volumes = new List<BoundingVolume>(); + + if (isDungeon) + { + // Dungeons: only load the current landblock (walls contain everything) + var lbVolumes = LoadLandblockGeometry(landblockKey); + volumes.AddRange(lbVolumes); + } + else + { + // Outdoors: load 3×3 grid for boundary coverage + uint blockX = (landblockKey >> 8) & 0xFF; + uint blockY = landblockKey & 0xFF; + + for (int dx = -1; dx <= 1; dx++) + { + for (int dy = -1; dy <= 1; dy++) + { + int nx = (int)blockX + dx; + int ny = (int)blockY + dy; + if (nx < 0 || nx > 0xFE || ny < 0 || ny > 0xFE) continue; + + uint neighborKey = (uint)((nx << 8) | ny); + var neighborVolumes = LoadLandblockGeometry(neighborKey); + volumes.AddRange(neighborVolumes); + } + } + } + + Log($"{(isDungeon ? "Dungeon" : "3x3 grid")} for 0x{landblockKey:X4}: {volumes.Count} total collision volumes"); + + if (_landblockCache.Count >= MAX_LANDBLOCK_CACHE) + EvictOldestLandblock(); + + _landblockCache[landblockKey] = volumes; + return volumes; + } + + /// <summary> + /// Loads collision geometry for a landblock from cell.dat and portal.dat. + /// </summary> + private List<BoundingVolume> LoadLandblockGeometry(uint landblockKey) + { + var volumes = new List<BoundingVolume>(); + + if (!_initialized) + { + Log("LoadLandblockGeometry called but not initialized!"); + return volumes; + } + + try + { + Log($"--- Loading landblock 0x{landblockKey:X4} ---"); + + // Dump sample IDs from cell.dat root to understand the ID format (first time only) + if (_landblockCache.Count <= 1 && _cellDat.IsLoaded) + { + DumpSampleCellIds(); + } + + // LandblockInfo is always 0xXXYYFFFE — this is where static objects live + // 0xXXYYFFFF is just terrain heightmap data (no objects) + uint landblockInfoId = (landblockKey << 16) | 0xFFFE; + + byte[] landblockData = _cellDat.GetFileData(landblockInfoId); + uint foundId = landblockInfoId; + + if (landblockData == null || landblockData.Length <= 8) + { + Log($"No LandblockInfo found for 0x{landblockInfoId:X8}"); + + // Some landblocks legitimately have no FFFE entry (empty ocean tiles etc.) + landblockData = null; + } + + if (landblockData != null) + { + DumpBytes(landblockData, $"Landblock 0x{foundId:X8}"); + int objectCount = ParseLandblockObjects(landblockData, landblockKey, volumes); + Log($"Parsed: {objectCount} static objects -> {volumes.Count} collision volumes"); + } + else + { + Log($"No LandblockInfo data for 0x{landblockKey:X4}"); + + // Pull search diagnostics from cell.dat + foreach (var msg in _cellDat.DiagLog) + { + if (msg.Contains("FindFile") || msg.Contains("depth=") || msg.Contains("Block[") || msg.Contains("Winner")) + Log($" cell.dat: {msg}"); + } + } + + // Also try loading indoor cells (static objects in dungeon rooms) + LoadIndoorCells(landblockKey, volumes); + + // Load dungeon wall geometry (EnvCell → Environment → CellStruct polygons) + if (_dungeonLOS != null) + { + var wallVolumes = _dungeonLOS.GetDungeonWalls(landblockKey); + volumes.AddRange(wallVolumes); + } + + // Load scatter objects (trees, rocks) — always load for outdoor terrain + if (_scatterSystem != null && _scatterSystem.IsInitialized) + { + var scatterVolumes = _scatterSystem.GetScatterVolumes(landblockKey, this); + volumes.AddRange(scatterVolumes); + } + + Log($"Landblock 0x{landblockKey:X4}: TOTAL {volumes.Count} collision volumes"); + } + catch (Exception ex) + { + Log($"Error loading landblock 0x{landblockKey:X4}: {ex.Message}"); + } + + return volumes; + } + + /// <summary> + /// Dumps sample file IDs from the cell.dat B-tree root node for diagnostics. + /// This tells us what format the IDs use. + /// </summary> + private bool _cellIdsDumped = false; + private void DumpSampleCellIds() + { + if (_cellIdsDumped) return; + _cellIdsDumped = true; + + try + { + Log("=== Sampling cell.dat file IDs ==="); + + var sampleIds = _cellDat.GetSampleIds(30); + if (sampleIds.Count > 0) + { + string idList = $"Cell.dat samples ({sampleIds.Count}): "; + foreach (uint id in sampleIds) + idList += $"0x{id:X8} "; + Log(idList); + + uint first = sampleIds[0]; + uint last = sampleIds[sampleIds.Count - 1]; + Log($"ID range: 0x{first:X8} to 0x{last:X8}"); + Log($"First: high=0x{(first >> 16):X4} low=0x{(first & 0xFFFF):X4}"); + } + else + { + Log("WARNING: No sample IDs from cell.dat B-tree!"); + } + + var portalSamples = _portalDat.GetSampleIds(10); + if (portalSamples.Count > 0) + { + string pList = "Portal.dat samples: "; + foreach (uint id in portalSamples) + pList += $"0x{id:X8} "; + Log(pList); + } + } + catch (Exception ex) + { + Log($"Cell sampling error: {ex.Message}"); + } + } + + /// <summary> + /// Dumps first bytes of data for diagnostics. + /// </summary> + private void DumpBytes(byte[] data, string label) + { + int len = Math.Min(64, data.Length); + string vals = $"{label} uint32s: "; + for (int i = 0; i < len; i += 4) + { + uint v = BitConverter.ToUInt32(data, i); + vals += $"[{i}]=0x{v:X8} "; + if (i == 28) + { + Log(vals); + vals = $"{label} +32: "; + } + } + Log(vals); + } + + /// <summary> + /// Parses static object placements from a LandblockInfo (0xFFFE) file. + /// + /// Exact format from ACE.DatLoader.FileTypes.LandblockInfo: + /// uint32 Id (file ID, e.g. 0xAAB3FFFE) + /// uint32 NumCells (number of EnvCells in landblock) + /// uint32 NumObjects (count of Stab entries) + /// Stab[NumObjects]: (static object placements) + /// uint32 Id (Setup/model ID, e.g. 0x02xxxxxx or 0x01xxxxxx) + /// Frame: (7 floats = 28 bytes) + /// float OriginX, OriginY, OriginZ + /// float RotW, RotX, RotY, RotZ + /// ushort NumBuildings + /// ushort PackMask + /// BuildInfo[NumBuildings]: + /// uint32 ModelId + /// Frame (7 floats) + /// uint32 NumLeaves + /// List{CBldPortal} Portals + /// if (PackMask & 1): + /// PackedHashTable RestrictionTables + /// + /// Each Stab = 32 bytes (4 + 28). NO InstanceId field. + /// </summary> + private int ParseLandblockObjects(byte[] data, uint landblockKey, List<BoundingVolume> volumes) + { + if (data == null || data.Length < 12) + { + Log($"Landblock data too small ({data?.Length ?? 0} bytes)"); + return 0; + } + + // --- Parse header --- + // [0] uint32 Id + // [4] uint32 NumCells + // [8] uint32 NumObjects (count for List<Stab>) + uint fileId = BitConverter.ToUInt32(data, 0); + uint numCells = BitConverter.ToUInt32(data, 4); + uint numObjects = BitConverter.ToUInt32(data, 8); + + Log($"LandblockInfo 0x{fileId:X8}: NumCells={numCells}, NumObjects={numObjects}"); + + if (numObjects == 0) + { + Log("No static objects in this landblock"); + return 0; + } + + if (numObjects > 5000) + { + Log($"Suspicious NumObjects={numObjects}, clamping to 5000"); + numObjects = 5000; + } + + // --- Parse Stab entries --- + // Each Stab = uint32 Id (4) + Frame (7 floats = 28) = 32 bytes + const int STAB_SIZE = 32; // 4 + 28 + int stabStart = 12; // After Id + NumCells + NumObjects + long neededBytes = stabStart + (long)numObjects * STAB_SIZE; + + if (neededBytes > data.Length) + { + Log($"Data too small for {numObjects} Stabs: need {neededBytes}, have {data.Length}"); + // Parse as many as we can fit + numObjects = (uint)((data.Length - stabStart) / STAB_SIZE); + if (numObjects == 0) return 0; + Log($"Adjusted to {numObjects} Stabs"); + } + + // Global offset for world coordinates + uint blockX = (landblockKey >> 8) & 0xFF; + uint blockY = landblockKey & 0xFF; + float globalOffsetX = blockX * 192.0f; + float globalOffsetY = blockY * 192.0f; + + int parsedCount = 0; + + for (uint i = 0; i < numObjects; i++) + { + int off = stabStart + (int)i * STAB_SIZE; + if (off + STAB_SIZE > data.Length) break; + + // Stab.Unpack: Id then Frame + uint stabId = BitConverter.ToUInt32(data, off); + + int frameOff = off + 4; + float px = BitConverter.ToSingle(data, frameOff); + float py = BitConverter.ToSingle(data, frameOff + 4); + float pz = BitConverter.ToSingle(data, frameOff + 8); + float rw = BitConverter.ToSingle(data, frameOff + 12); + float rx = BitConverter.ToSingle(data, frameOff + 16); + float ry = BitConverter.ToSingle(data, frameOff + 20); + float rz = BitConverter.ToSingle(data, frameOff + 24); + + // Validate position + if (float.IsNaN(px) || float.IsInfinity(px) || Math.Abs(px) > 50000) + { + Log($" Obj[{i}]: SKIPPED invalid position ({px},{py},{pz})"); + continue; + } + + // Log first few for verification + if (parsedCount < 5) + Log($" Obj[{i}]: Id=0x{stabId:X8} Pos=({px:F1},{py:F1},{pz:F1}) Rot=({rw:F3},{rx:F3},{ry:F3},{rz:F3})"); + + var frame = new Frame + { + OriginX = px, OriginY = py, OriginZ = pz, + RotW = rw, RotX = rx, RotY = ry, RotZ = rz + }; + + var setupVolumes = GetSetupBoundingVolumes(stabId); + foreach (var vol in setupVolumes) + { + var transformed = TransformVolume(vol, frame, globalOffsetX, globalOffsetY); + if (transformed != null) + volumes.Add(transformed); + } + + parsedCount++; + } + + // --- Also parse Buildings --- + int buildingOffset = stabStart + (int)numObjects * STAB_SIZE; + if (buildingOffset + 4 <= data.Length) + { + ushort numBuildings = BitConverter.ToUInt16(data, buildingOffset); + ushort packMask = BitConverter.ToUInt16(data, buildingOffset + 2); + Log($"Buildings: {numBuildings}, PackMask=0x{packMask:X4}"); + + int bOff = buildingOffset + 4; + for (int b = 0; b < numBuildings && bOff + 36 <= data.Length; b++) + { + // BuildInfo: uint32 ModelId + Frame(28) + uint32 NumLeaves + List<CBldPortal> + uint modelId = BitConverter.ToUInt32(data, bOff); + float bpx = BitConverter.ToSingle(data, bOff + 4); + float bpy = BitConverter.ToSingle(data, bOff + 8); + float bpz = BitConverter.ToSingle(data, bOff + 12); + float brw = BitConverter.ToSingle(data, bOff + 16); + float brx = BitConverter.ToSingle(data, bOff + 20); + float bry = BitConverter.ToSingle(data, bOff + 24); + float brz = BitConverter.ToSingle(data, bOff + 28); + + if (b < 3) + Log($" Building[{b}]: Model=0x{modelId:X8} Pos=({bpx:F1},{bpy:F1},{bpz:F1})"); + + var bFrame = new Frame + { + OriginX = bpx, OriginY = bpy, OriginZ = bpz, + RotW = brw, RotX = brx, RotY = bry, RotZ = brz + }; + + var bVolumes = GetSetupBoundingVolumes(modelId); + foreach (var vol in bVolumes) + { + var transformed = TransformVolume(vol, bFrame, globalOffsetX, globalOffsetY); + if (transformed != null) + volumes.Add(transformed); + } + + // Skip past: ModelId(4) + Frame(28) + NumLeaves(4) = 36 + uint numLeaves = BitConverter.ToUInt32(data, bOff + 32); + bOff += 36; + + // Skip portal list: uint32 count, then count × portal entries + if (bOff + 4 <= data.Length) + { + uint numPortals = BitConverter.ToUInt32(data, bOff); + bOff += 4; + // Each CBldPortal is variable size; skip conservatively + // We got the building model, which is the main thing we need + // Portal data is complex (flags + cell lists); skip the rest + // for now by breaking out of building loop if we can't parse further + for (uint p = 0; p < numPortals && bOff + 8 <= data.Length; p++) + { + ushort portalFlags = BitConverter.ToUInt16(data, bOff); + bOff += 2; + // Skip remaining portal data (OtherCellId + OtherPortalId + StabList) + // This is complex; break if we hit something unexpected + if (bOff + 6 <= data.Length) + { + bOff += 6; // Approximate skip for simple portal entries + } + } + } + + parsedCount++; + } + } + + if (parsedCount == 0) + Log($"No static objects found in landblock data ({data.Length} bytes)"); + + return parsedCount; + } + + /// <summary> + /// Loads static objects from the LandblockInfo entry in cell.dat. + /// These are outdoor objects: buildings, trees, rocks, terrain features. + /// </summary> + private void LoadOutdoorObjects(uint landblockInfoId, uint landblockKey, List<BoundingVolume> volumes) + { + // This method is now unused - logic moved into LoadLandblockGeometry + // Kept for API compatibility + } + + /// <summary> + /// Loads static objects from dungeon/interior cells in cell.dat. + /// Indoor cells are numbered 0xXXYY0100 through 0xXXYYFFFD. + /// Uses ACE's EnvCell format for correct parsing. + /// </summary> + private void LoadIndoorCells(uint landblockKey, List<BoundingVolume> volumes) + { + uint baseId = landblockKey << 16; + float globalOffsetX = ((landblockKey >> 8) & 0xFF) * 192.0f; + float globalOffsetY = (landblockKey & 0xFF) * 192.0f; + + // EnvCells start at 0x0100 + int consecutiveMisses = 0; + for (uint cellNum = 0x0100; cellNum <= 0xFFFD; cellNum++) + { + uint cellId = baseId | cellNum; + byte[] data = _cellDat.GetFileData(cellId); + if (data == null) + { + consecutiveMisses++; + if (consecutiveMisses > 10) break; // No more cells after 10 gaps + continue; + } + consecutiveMisses = 0; + if (data.Length < 20) continue; + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); + uint flags = reader.ReadUInt32(); + reader.ReadUInt32(); // duplicate CellId + + byte numSurfaces = reader.ReadByte(); + byte numPortals = reader.ReadByte(); + ushort numVisibleCells = reader.ReadUInt16(); + + // Skip surfaces + for (int i = 0; i < numSurfaces; i++) + reader.ReadUInt16(); + + ushort envId = reader.ReadUInt16(); + ushort cellStructure = reader.ReadUInt16(); + + // Cell Position (Frame) + float cellX = reader.ReadSingle(); + float cellY = reader.ReadSingle(); + float cellZ = reader.ReadSingle(); + reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); // rotation + + // Skip portals (8 bytes each) + for (int i = 0; i < numPortals; i++) + { + if (ms.Position + 8 > ms.Length) break; + reader.ReadUInt64(); // 4 × ushort + } + + // Skip visible cells + for (int i = 0; i < numVisibleCells; i++) + { + if (ms.Position + 2 > ms.Length) break; + reader.ReadUInt16(); + } + + // Read static objects if present (flag 0x02 = HasStaticObjs) + if ((flags & 0x02) != 0 && ms.Position + 4 <= ms.Length) + { + uint numStabs = reader.ReadUInt32(); + if (numStabs > 500) numStabs = 500; + + for (uint i = 0; i < numStabs; i++) + { + if (ms.Position + 32 > ms.Length) break; + + uint setupId = reader.ReadUInt32(); + float px = reader.ReadSingle(); + float py = reader.ReadSingle(); + float pz = reader.ReadSingle(); + float rw = reader.ReadSingle(); + float rx = reader.ReadSingle(); + float ry = reader.ReadSingle(); + float rz = reader.ReadSingle(); + + var frame = new Frame + { + // Static object position is in cell-local space + // Cell position is already in landblock-local space + OriginX = px + cellX, + OriginY = py + cellY, + OriginZ = pz + cellZ, + RotW = rw, RotX = rx, RotY = ry, RotZ = rz + }; + + var objVolumes = GetSetupBoundingVolumes(setupId); + foreach (var vol in objVolumes) + { + var transformed = TransformVolume(vol, frame, globalOffsetX, globalOffsetY); + if (transformed != null) + volumes.Add(transformed); + } + } + } + } + } + catch { } + } + } + + /// <summary> + /// Retrieves bounding volumes for a model ID from portal.dat. + /// Handles both 0x02xxxxxx (Setup) and 0x01xxxxxx (GfxObj) IDs. + /// Falls back through: collision spheres → cylinders → SortingSphere → Height+Radius cylinder → GfxObj AABB. + /// </summary> + private int _setupLogCount = 0; + + /// <summary> + /// Public accessor for use by ScatterSystem. + /// </summary> + public List<BoundingVolume> GetSetupBoundingVolumesPublic(uint modelId) + { + return GetSetupBoundingVolumes(modelId); + } + + private List<BoundingVolume> GetSetupBoundingVolumes(uint modelId) + { + var result = new List<BoundingVolume>(); + + // If it's a GfxObj (0x01xxxxxx), try to get bounds from it directly + if ((modelId & 0xFF000000) == 0x01000000) + { + var gfxVol = GetGfxObjBounds(modelId); + if (gfxVol != null) + { + result.Add(gfxVol); + } + else + { + // GfxObj parse failed — use a default building bounding box. + // Buildings are solid structures; better to have an approximate volume + // than no volume (which lets rays pass through walls). + float defaultR = 5.0f; + float defaultH = 8.0f; + result.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.AxisAlignedBox, + Center = new Vector3(0, 0, defaultH * 0.5f), + Dimensions = new Vector3(defaultR * 2, defaultR * 2, defaultH), + Min = new Vector3(-defaultR, -defaultR, 0), + Max = new Vector3(defaultR, defaultR, defaultH), + IsDoor = false + }); + } + return result; + } + + // Check cache first + if (!_setupCache.TryGetValue(modelId, out var setup)) + { + // Load and parse the Setup file + byte[] data = _portalDat.GetFileData(modelId); + if (data == null) + { + if (_setupLogCount < 5) + { + Log($"Setup 0x{modelId:X8}: NOT FOUND in portal.dat"); + _setupLogCount++; + } + return result; + } + + if (_setupLogCount < 5) + { + Log($"Setup 0x{modelId:X8}: {data.Length} bytes loaded"); + _setupLogCount++; + } + + setup = new SetupInfo(); + if (!setup.Unpack(data)) + { + if (_setupLogCount < 10) + Log($"Setup 0x{modelId:X8}: PARSE FAILED"); + + // Even if parse failed, try GfxObj from Parts if we got them + if (setup.PartIds != null && setup.PartIds.Length > 0) + { + var gfxVol = GetGfxObjBounds(setup.PartIds[0]); + if (gfxVol != null) + result.Add(gfxVol); + } + return result; + } + + if (_setupLogCount < 10) + Log($"Setup 0x{modelId:X8}: {setup.NumParts} parts, radius={setup.BoundingSphereRadius:F2}, " + + $"{setup.Spheres.Count} spheres, {setup.Cylinders.Count} cylinders"); + + // Cache it + if (_setupCache.Count >= MAX_SETUP_CACHE) + _setupCache.Clear(); + _setupCache[modelId] = setup; + } + + // Priority 1: Use collision spheres from Setup + if (setup.Spheres.Count > 0) + { + foreach (var sphere in setup.Spheres) + { + result.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.Sphere, + Center = sphere.Center, + Dimensions = new Vector3(sphere.Radius, sphere.Radius, sphere.Radius), + Min = sphere.Center - new Vector3(sphere.Radius, sphere.Radius, sphere.Radius), + Max = sphere.Center + new Vector3(sphere.Radius, sphere.Radius, sphere.Radius), + IsDoor = false + }); + } + return result; + } + + // Priority 2: Use collision cylinders from Setup + if (setup.Cylinders.Count > 0) + { + foreach (var cyl in setup.Cylinders) + { + result.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.Cylinder, + Center = new Vector3( + cyl.BottomCenter.X, + cyl.BottomCenter.Y, + cyl.BottomCenter.Z + cyl.Height * 0.5f + ), + Dimensions = new Vector3(cyl.Radius, cyl.Radius, cyl.Height), + Min = new Vector3( + cyl.BottomCenter.X - cyl.Radius, + cyl.BottomCenter.Y - cyl.Radius, + cyl.BottomCenter.Z + ), + Max = new Vector3( + cyl.BottomCenter.X + cyl.Radius, + cyl.BottomCenter.Y + cyl.Radius, + cyl.BottomCenter.Z + cyl.Height + ), + IsDoor = false + }); + } + return result; + } + + // Priority 3: Use bounding sphere from Setup + if (setup.BoundingSphereRadius > 0.1f) + { + float r = setup.BoundingSphereRadius; + result.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.Sphere, + Center = setup.BoundingSphereCenter, + Dimensions = new Vector3(r, r, r), + Min = setup.BoundingSphereCenter - new Vector3(r, r, r), + Max = setup.BoundingSphereCenter + new Vector3(r, r, r), + IsDoor = false + }); + return result; + } + + // Priority 4: Use Height + Radius from Setup to create a cylinder + if (setup.Radius > 0.1f && setup.Height > 0.1f) + { + float r = setup.Radius; + float h = setup.Height; + result.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.Cylinder, + Center = new Vector3(0, 0, h * 0.5f), + Dimensions = new Vector3(r, r, h), + Min = new Vector3(-r, -r, 0), + Max = new Vector3(r, r, h), + IsDoor = false + }); + return result; + } + + // Priority 5: Fall back to GfxObj bounding data from first part + if (setup.PartIds != null && setup.PartIds.Length > 0) + { + var gfxVol = GetGfxObjBounds(setup.PartIds[0]); + if (gfxVol != null) + result.Add(gfxVol); + } + + return result; + } + + /// <summary> + /// Loads a GfxObj from portal.dat and extracts its bounding volume. + /// </summary> + private BoundingVolume GetGfxObjBounds(uint gfxObjId) + { + byte[] data = _portalDat.GetFileData(gfxObjId); + if (data == null) return null; + + var gfxObj = new GfxObjInfo(); + if (!gfxObj.Unpack(data) || !gfxObj.HasBounds) + return null; + + if (gfxObj.SortingRadius > 0.1f) + { + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.Sphere, + Center = gfxObj.SortingCenter, + Dimensions = new Vector3(gfxObj.SortingRadius, gfxObj.SortingRadius, gfxObj.SortingRadius), + Min = gfxObj.BoundsMin, + Max = gfxObj.BoundsMax, + IsDoor = false + }; + } + + // Use AABB from vertices + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.AxisAlignedBox, + Center = (gfxObj.BoundsMin + gfxObj.BoundsMax) * 0.5f, + Dimensions = gfxObj.BoundsMax - gfxObj.BoundsMin, + Min = gfxObj.BoundsMin, + Max = gfxObj.BoundsMax, + IsDoor = false + }; + } + + /// <summary> + /// Transforms a local-space bounding volume by a placement frame, + /// producing a world-space AABB for raycasting. + /// </summary> + private BoundingVolume TransformVolume(BoundingVolume localVol, Frame placement, + float globalOffsetX, float globalOffsetY) + { + if (localVol == null) return null; + + try + { + // For spheres: rotate center, keep radius (spheres are rotation-invariant) + if (localVol.Type == BoundingVolume.VolumeType.Sphere) + { + Vector3 worldCenter = placement.TransformPoint(localVol.Center); + worldCenter.X += globalOffsetX; + worldCenter.Y += globalOffsetY; + + float r = localVol.Dimensions.X; // Radius + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.Sphere, + Center = worldCenter, + Dimensions = localVol.Dimensions, + Min = worldCenter - new Vector3(r, r, r), + Max = worldCenter + new Vector3(r, r, r), + IsDoor = localVol.IsDoor + }; + } + + // For AABBs and other types: transform the 8 corners and compute new AABB + Vector3[] corners = new Vector3[8] + { + new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Min.Z), + new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Min.Z), + new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Min.Z), + new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Min.Z), + new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Max.Z), + new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Max.Z), + new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Max.Z), + new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Max.Z), + }; + + Vector3 newMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); + Vector3 newMax = new Vector3(float.MinValue, float.MinValue, float.MinValue); + + for (int i = 0; i < 8; i++) + { + Vector3 world = placement.TransformPoint(corners[i]); + world.X += globalOffsetX; + world.Y += globalOffsetY; + + newMin = Vector3.Min(newMin, world); + newMax = Vector3.Max(newMax, world); + } + + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.AxisAlignedBox, + Center = (newMin + newMax) * 0.5f, + Dimensions = newMax - newMin, + Min = newMin, + Max = newMax, + IsDoor = localVol.IsDoor + }; + } + catch (Exception ex) + { + Log($"Error transforming volume: {ex.Message}"); + return null; + } + } + + /// <summary> + /// Searches common installation paths for Asheron's Call. + /// </summary> + private string FindACFolder() + { + string[] searchPaths = new string[] + { + @"C:\Turbine\Asheron's Call", // User's known path + @"C:\Program Files\Turbine\Asheron's Call", + @"C:\Program Files (x86)\Turbine\Asheron's Call", + @"C:\Games\Asheron's Call", + @"C:\AC", + @"C:\Asheron's Call", + @"C:\Games\AC", + @"D:\Turbine\Asheron's Call", + @"D:\Games\Asheron's Call", + @"D:\AC", + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Turbine", "Asheron's Call"), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Turbine", "Asheron's Call"), + }; + + // Check for both original (portal.dat) and ToD (client_portal.dat) filenames + string[] portalNames = { "client_portal.dat", "portal.dat" }; + string[] cellNames = { "client_cell_1.dat", "cell.dat" }; + + foreach (var path in searchPaths) + { + try + { + if (!Directory.Exists(path)) continue; + + bool hasPortal = false, hasCell = false; + foreach (var pn in portalNames) + if (File.Exists(Path.Combine(path, pn))) { hasPortal = true; break; } + foreach (var cn in cellNames) + if (File.Exists(Path.Combine(path, cn))) { hasCell = true; break; } + + if (hasPortal && hasCell) + { + Log($"Found AC folder: {path}"); + return path; + } + else if (hasPortal || hasCell) + { + Log($"Partial match at {path} (portal={hasPortal}, cell={hasCell})"); + } + } + catch { } + } + + // Also try to find via registry + try + { + using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Turbine\Asheron's Call")) + { + if (key != null) + { + string installPath = key.GetValue("InstallPath") as string; + if (!string.IsNullOrEmpty(installPath) && Directory.Exists(installPath)) + return installPath; + } + } + } + catch { } + + Log("Could not find Asheron's Call installation"); + return null; + } + + private void EvictOldestLandblock() + { + if (_landblockCache.Count == 0) return; + + // Simple eviction: remove the first key + foreach (var key in _landblockCache.Keys) + { + _landblockCache.Remove(key); + break; + } + } + + public void FlushCache() + { + _landblockCache.Clear(); + _setupCache.Clear(); + Log("All caches flushed"); + } + + public void FlushLandblock(uint landblockKey) + { + _landblockCache.Remove(landblockKey); + } + + public void Dispose() + { + _portalDat?.Dispose(); + _cellDat?.Dispose(); + _landblockCache.Clear(); + _setupCache.Clear(); + _initialized = false; + } + + private void Log(string msg) + { + string line = $"[GeoLoader] {msg}"; + System.Diagnostics.Debug.WriteLine(line); + if (DiagLog.Count < 200) DiagLog.Add(msg); + } + } +} diff --git a/Plugins/RynthAi/Raycasting/LandblockStructs.cs b/Plugins/RynthAi/Raycasting/LandblockStructs.cs new file mode 100644 index 0000000..c7d4e87 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/LandblockStructs.cs @@ -0,0 +1,751 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// A position + rotation in AC's 3D world. + /// Position is in local landblock meters (0-192 for outdoors). + /// Rotation is a quaternion (W, X, Y, Z). + /// </summary> + public class Frame + { + public float OriginX, OriginY, OriginZ; + public float RotW, RotX, RotY, RotZ; + + public Frame() + { + RotW = 1.0f; // Identity quaternion + } + + public void Unpack(BinaryReader reader) + { + OriginX = reader.ReadSingle(); + OriginY = reader.ReadSingle(); + OriginZ = reader.ReadSingle(); + RotW = reader.ReadSingle(); + RotX = reader.ReadSingle(); + RotY = reader.ReadSingle(); + RotZ = reader.ReadSingle(); + } + + /// <summary> + /// Rotates a point by this frame's quaternion. + /// q * v * q^-1 (for unit quaternion, q^-1 = conjugate) + /// </summary> + public Vector3 RotatePoint(Vector3 point) + { + // Quaternion rotation: v' = q * v * q* + float qw = RotW, qx = RotX, qy = RotY, qz = RotZ; + + // Cross product of quaternion xyz with point + float cx = qy * point.Z - qz * point.Y; + float cy = qz * point.X - qx * point.Z; + float cz = qx * point.Y - qy * point.X; + + // Result = point + 2 * (qw * cross + qxyz x cross) + float cx2 = qy * cz - qz * cy; + float cy2 = qz * cx - qx * cz; + float cz2 = qx * cy - qy * cx; + + return new Vector3( + point.X + 2.0f * (qw * cx + cx2), + point.Y + 2.0f * (qw * cy + cy2), + point.Z + 2.0f * (qw * cz + cz2) + ); + } + + /// <summary> + /// Transforms a point: rotate then translate. + /// </summary> + public Vector3 TransformPoint(Vector3 localPoint) + { + Vector3 rotated = RotatePoint(localPoint); + return new Vector3( + rotated.X + OriginX, + rotated.Y + OriginY, + rotated.Z + OriginZ + ); + } + + public override string ToString() + { + return $"Pos({OriginX:F2}, {OriginY:F2}, {OriginZ:F2}) Rot({RotW:F3}, {RotX:F3}, {RotY:F3}, {RotZ:F3})"; + } + } + + /// <summary> + /// A static object placed on a landblock (building, tree, rock, structure, etc.) + /// </summary> + public class StaticObject + { + public uint InstanceId; // Unique placement ID + public uint SetupId; // Reference to 0x02xxxxxx Setup in portal.dat + public Frame Placement; // Position and rotation in landblock space + + public StaticObject() + { + Placement = new Frame(); + } + } + + /// <summary> + /// Parsed landblock info from cell.dat (file ID = 0xXXYYFFFE). + /// Contains static object placements (Stabs) and building info for an outdoor landblock. + /// + /// Format (from ACE.DatLoader.FileTypes.LandblockInfo): + /// uint32 Id + /// uint32 NumCells + /// uint32 NumObjects (List<Stab> count) + /// Stab[NumObjects]: + /// uint32 Id (model/setup reference, 0x01xx or 0x02xx) + /// Frame (7 floats: pos.xyz + rot.wxyz = 28 bytes) + /// ushort NumBuildings + /// ushort PackMask + /// BuildInfo[NumBuildings]: + /// uint32 ModelId + /// Frame (28 bytes) + /// uint32 NumLeaves + /// List<CBldPortal> Portals + /// if (PackMask & 1): + /// PackedHashTable RestrictionTables + /// </summary> + public class LandblockInfo + { + public uint Id; + public uint NumCells; + public List<StaticObject> StaticObjects = new List<StaticObject>(); + public bool HasObjects; + + /// <summary> + /// Parse landblock info from raw .dat file data using the ACE format. + /// </summary> + public bool Unpack(byte[] data) + { + if (data == null || data.Length < 12) + return false; + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + Id = reader.ReadUInt32(); + NumCells = reader.ReadUInt32(); + + // Read List<Stab> — uint32 count + count × Stab entries + uint numObjects = reader.ReadUInt32(); + + if (numObjects > 5000) numObjects = 5000; // Sanity + + for (uint i = 0; i < numObjects; i++) + { + if (ms.Position + 32 > ms.Length) break; // Need 4 (Id) + 28 (Frame) + + var obj = new StaticObject(); + obj.SetupId = reader.ReadUInt32(); + obj.Placement.Unpack(reader); + StaticObjects.Add(obj); + } + + HasObjects = StaticObjects.Count > 0; + Log($"Landblock 0x{Id:X8}: {StaticObjects.Count} static objects"); + return true; + } + } + catch (Exception ex) + { + Log($"Error parsing landblock 0x{Id:X8}: {ex.Message}"); + return false; + } + } + + private static void Log(string msg) + { + System.Diagnostics.Debug.WriteLine($"[LandblockInfo] {msg}"); + } + } + + /// <summary> + /// Parsed environment cell from cell.dat (file ID = 0xXXYY0001 to 0xXXYYFFFE). + /// Represents an indoor dungeon room with walls, portals, and static objects. + /// </summary> + public class EnvCellInfo + { + public uint Id; + public uint Flags; + public List<Vector3> Vertices = new List<Vector3>(); + public List<CellPolygon> Polygons = new List<CellPolygon>(); + public List<ushort> PortalPolygonIndices = new List<ushort>(); + public List<StaticObject> StaticObjects = new List<StaticObject>(); + public List<uint> ConnectedCells = new List<uint>(); + public uint EnvironmentId; // Reference to portal.dat environment + public uint StructureId; // Reference to portal.dat cell structure + + /// <summary> + /// Parse environment cell from raw data. + /// + /// Format (simplified): + /// uint32 id + /// uint32 flags + /// uint32 environmentId (0x0Dxxxxxx) + /// uint16 cellStructId + /// uint16 position (index into structure) + /// Frame placement + /// uint32 numPortals + /// for each portal: + /// uint16 polygonId (portal polygon index) + /// uint16 flags + /// uint32 connectedCell + /// uint32 numStaticObjects + /// for each static object: + /// uint32 setupId + /// Frame placement + /// </summary> + public bool Unpack(byte[] data) + { + if (data == null || data.Length < 12) + return false; + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + Id = reader.ReadUInt32(); + Flags = reader.ReadUInt32(); + + // Read environment/structure references + if (ms.Position + 8 > ms.Length) return false; + + // The exact format depends on flags, but typically: + EnvironmentId = reader.ReadUInt32(); + + if (ms.Position + 4 > ms.Length) return false; + StructureId = reader.ReadUInt32(); + + // Read cell frame (position + rotation) + if ((Flags & 0x02) != 0 && ms.Position + 28 <= ms.Length) + { + var frame = new Frame(); + frame.Unpack(reader); + } + + // Read portals + if ((Flags & 0x04) != 0 || ms.Position + 4 <= ms.Length) + { + if (ms.Position + 4 <= ms.Length) + { + uint numPortals = reader.ReadUInt32(); + if (numPortals > 1000) numPortals = 0; // Sanity + + for (uint i = 0; i < numPortals && ms.Position + 8 <= ms.Length; i++) + { + ushort polyId = reader.ReadUInt16(); + ushort portalFlags = reader.ReadUInt16(); + uint connCell = reader.ReadUInt32(); + + PortalPolygonIndices.Add(polyId); + ConnectedCells.Add(connCell); + } + } + } + + // Read static objects + if (ms.Position + 4 <= ms.Length) + { + uint numObjects = reader.ReadUInt32(); + if (numObjects > 10000) numObjects = 0; + + for (uint i = 0; i < numObjects && ms.Position + 32 <= ms.Length; i++) + { + var obj = new StaticObject(); + obj.SetupId = reader.ReadUInt32(); + obj.Placement.Unpack(reader); + StaticObjects.Add(obj); + } + } + + Log($"EnvCell 0x{Id:X8}: {StaticObjects.Count} objects, " + + $"{PortalPolygonIndices.Count} portals"); + return true; + } + } + catch (Exception ex) + { + Log($"Error parsing EnvCell 0x{Id:X8}: {ex.Message}"); + return false; + } + } + + private static void Log(string msg) + { + System.Diagnostics.Debug.WriteLine($"[EnvCell] {msg}"); + } + } + + /// <summary> + /// A polygon in a cell structure (wall, floor, ceiling). + /// </summary> + public class CellPolygon + { + public ushort[] VertexIndices; + public bool IsPortal; // Portal polygons are openings, not solid walls + } + + /// <summary> + /// Parsed Setup file from portal.dat (file ID = 0x02xxxxxx). + /// Matches ACE.DatLoader.FileTypes.SetupModel.Unpack() exactly. + /// + /// Format: + /// uint32 Id + /// uint32 Flags (SetupFlags) + /// uint32 numParts + /// uint32[numParts] Parts (GfxObj references, 0x01xxxxxx) + /// if (Flags & 0x01): uint32[numParts] ParentIndex + /// if (Flags & 0x02): Vector3[numParts] DefaultScale + /// Dictionary<int,LocationType> HoldingLocations (uint32 count + entries) + /// Dictionary<int,LocationType> ConnectionPoints (uint32 count + entries) + /// int32 placementsCount + /// PlacementType[placementsCount]: key(int32) + AnimFrame(numParts × Frame(28) + uint32 numHooks + hooks) + /// List<CylSphere> CylSpheres (uint32 count + count × 20 bytes) + /// List<Sphere> Spheres (uint32 count + count × 16 bytes) + /// float Height, Radius, StepUpHeight, StepDownHeight + /// Sphere SortingSphere (Vector3 + float = 16 bytes) + /// Sphere SelectionSphere (16 bytes) + /// Dictionary<int,LightInfo> Lights + /// uint32 × 5 defaults + /// </summary> + public class SetupInfo + { + public uint Id; + public uint Flags; + public int NumParts; + public uint[] PartIds; + + // Bounding sphere (from SortingSphere) + public float BoundingSphereRadius; + public Vector3 BoundingSphereCenter; + + // Physics dimensions + public float Height; + public float Radius; // Physics collision radius + + // Collision spheres + public List<CollisionSphere> Spheres = new List<CollisionSphere>(); + + // Collision cylinders + public List<CollisionCylinder> Cylinders = new List<CollisionCylinder>(); + + public bool HasBounds; + + public bool Unpack(byte[] data) + { + if (data == null || data.Length < 16) + return false; + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + // --- Header --- + Id = reader.ReadUInt32(); + Flags = reader.ReadUInt32(); + + uint numParts = reader.ReadUInt32(); + if (numParts > 500) return false; + NumParts = (int)numParts; + + PartIds = new uint[numParts]; + for (int i = 0; i < numParts; i++) + PartIds[i] = reader.ReadUInt32(); + + // --- Optional arrays based on flags --- + // HasParent = 0x01 + if ((Flags & 0x01) != 0) + ms.Seek(numParts * 4, SeekOrigin.Current); + + // HasDefaultScale = 0x02 + if ((Flags & 0x02) != 0) + ms.Seek(numParts * 12, SeekOrigin.Current); // Vector3 = 12 bytes + + // --- Skip HoldingLocations: uint32 count + count × (key(4) + PartId(4) + Frame(28)) --- + if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data); + + // --- Skip ConnectionPoints: same format --- + if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data); + + // --- Skip PlacementFrames --- + if (ms.Position + 4 > ms.Length) return TryFallbackParse(data); + int placementsCount = reader.ReadInt32(); + if (placementsCount < 0 || placementsCount > 100) return TryFallbackParse(data); + + for (int p = 0; p < placementsCount; p++) + { + if (ms.Position + 4 > ms.Length) return TryFallbackParse(data); + reader.ReadInt32(); // key + + // AnimationFrame: numParts × Frame(28 bytes) + uint32 numHooks + for (int part = 0; part < numParts; part++) + { + if (ms.Position + 28 > ms.Length) return TryFallbackParse(data); + ms.Seek(28, SeekOrigin.Current); // Skip Frame + } + + if (ms.Position + 4 > ms.Length) return TryFallbackParse(data); + uint numHooks = reader.ReadUInt32(); + if (numHooks > 0) + { + // AnimationHooks are variable-size; can't easily skip + // Fall back to tail scanning + return TryFallbackParse(data); + } + } + + // --- NOW we're at the good stuff! --- + return ReadBoundsData(reader, ms, data); + } + } + catch + { + return TryFallbackParse(data); + } + } + + /// <summary> + /// Reads CylSpheres, Spheres, Height, Radius, SortingSphere from current position. + /// </summary> + private bool ReadBoundsData(BinaryReader reader, MemoryStream ms, byte[] data) + { + try + { + // CylSpheres: uint32 count + count × (Vector3 origin(12) + float radius(4) + float height(4) = 20) + if (ms.Position + 4 > ms.Length) return false; + uint numCylSpheres = reader.ReadUInt32(); + if (numCylSpheres > 50) return TryFallbackParse(data); + + for (uint i = 0; i < numCylSpheres; i++) + { + if (ms.Position + 20 > ms.Length) break; + var cyl = new CollisionCylinder(); + cyl.BottomCenter = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); + cyl.Radius = reader.ReadSingle(); + cyl.Height = reader.ReadSingle(); + if (cyl.Radius > 0 && cyl.Height > 0 && !float.IsNaN(cyl.Radius)) + Cylinders.Add(cyl); + } + + // Spheres: uint32 count + count × (Vector3 origin(12) + float radius(4) = 16) + if (ms.Position + 4 > ms.Length) return false; + uint numSpheres = reader.ReadUInt32(); + if (numSpheres > 50) return TryFallbackParse(data); + + for (uint i = 0; i < numSpheres; i++) + { + if (ms.Position + 16 > ms.Length) break; + var sphere = new CollisionSphere(); + sphere.Center = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); + sphere.Radius = reader.ReadSingle(); + if (sphere.Radius > 0 && !float.IsNaN(sphere.Radius)) + Spheres.Add(sphere); + } + + // Height, Radius, StepUpHeight, StepDownHeight + if (ms.Position + 16 > ms.Length) return false; + Height = reader.ReadSingle(); + Radius = reader.ReadSingle(); + float stepUp = reader.ReadSingle(); + float stepDown = reader.ReadSingle(); + + // SortingSphere: Vector3 center + float radius + if (ms.Position + 16 > ms.Length) return false; + float sx = reader.ReadSingle(), sy = reader.ReadSingle(), sz = reader.ReadSingle(); + float sr = reader.ReadSingle(); + + BoundingSphereCenter = new Vector3(sx, sy, sz); + BoundingSphereRadius = sr; + HasBounds = sr > 0.001f || Radius > 0.001f; + + // If SortingSphere radius is 0, use the physics Radius + if (BoundingSphereRadius < 0.001f && Radius > 0.001f) + BoundingSphereRadius = Radius; + + Log($"Setup 0x{Id:X8}: bounds OK — radius={BoundingSphereRadius:F2}, height={Height:F2}, " + + $"{Cylinders.Count} cyls, {Spheres.Count} spheres"); + return true; + } + catch + { + return TryFallbackParse(data); + } + } + + /// <summary> + /// Skip a hash table: uint32 count + count × entries of entrySize bytes. + /// </summary> + private bool SkipHashTable(BinaryReader reader, MemoryStream ms, int entrySize) + { + if (ms.Position + 4 > ms.Length) return false; + uint count = reader.ReadUInt32(); + if (count > 1000) return false; + long skip = (long)count * entrySize; + if (ms.Position + skip > ms.Length) return false; + ms.Seek(skip, SeekOrigin.Current); + return true; + } + + /// <summary> + /// Fallback: scan from the end of the file for the known tail structure. + /// The tail is always: + /// ... SortingSphere(16) + SelectionSphere(16) + Lights(uint32 count + entries) + 5×uint32(20) + /// If Lights is empty (count=0 → 4 bytes), tail is 56 bytes from end. + /// </summary> + private bool TryFallbackParse(byte[] data) + { + try + { + // Read header to get PartIds at minimum + if (PartIds == null && data.Length >= 16) + { + using (var ms2 = new MemoryStream(data)) + using (var r2 = new BinaryReader(ms2)) + { + Id = r2.ReadUInt32(); + Flags = r2.ReadUInt32(); + uint np = r2.ReadUInt32(); + if (np <= 500) + { + NumParts = (int)np; + PartIds = new uint[np]; + for (int i = 0; i < np && ms2.Position + 4 <= ms2.Length; i++) + PartIds[i] = r2.ReadUInt32(); + } + } + } + + // Try to find SortingSphere by scanning from end + // Known tail (if Lights empty): 5×uint32(20) + Lights(4) + SelectionSphere(16) + SortingSphere(16) + 4×float(16) + // = 72 bytes from end for start of Height/Radius/StepUp/StepDown + + int[] tailOffsets = { 72, 78, 84 }; // Try different Lights sizes (4, 10, 16 bytes) + + foreach (int tailOff in tailOffsets) + { + int offset = data.Length - tailOff; + if (offset < 16 || offset + 48 > data.Length) continue; + + float h = BitConverter.ToSingle(data, offset); + float r = BitConverter.ToSingle(data, offset + 4); + float sx = BitConverter.ToSingle(data, offset + 16); + float sy = BitConverter.ToSingle(data, offset + 20); + float sz = BitConverter.ToSingle(data, offset + 24); + float sr = BitConverter.ToSingle(data, offset + 28); + + // Validate: Height and Radius should be positive, sphere radius positive, center reasonable + if (h >= 0 && h < 100 && r > 0 && r < 200 && + sr > 0 && sr < 500 && + !float.IsNaN(h) && !float.IsNaN(r) && !float.IsNaN(sr) && + Math.Abs(sx) < 1000 && Math.Abs(sy) < 1000 && Math.Abs(sz) < 1000) + { + Height = h; + Radius = r; + BoundingSphereCenter = new Vector3(sx, sy, sz); + BoundingSphereRadius = sr; + HasBounds = true; + + Log($"Setup 0x{Id:X8}: FALLBACK found bounds at tailOff={tailOff} — radius={sr:F2}, height={h:F2}"); + return true; + } + } + + Log($"Setup 0x{Id:X8}: FALLBACK failed, no valid bounds found"); + return false; + } + catch + { + return false; + } + } + + private static void Log(string msg) + { + System.Diagnostics.Debug.WriteLine($"[Setup] {msg}"); + } + } + + /// <summary> + /// Parsed GfxObj from portal.dat (file ID = 0x01xxxxxx). + /// Contains 3D mesh data. We extract the bounding sphere and AABB. + /// </summary> + public class GfxObjInfo + { + public uint Id; + public uint Flags; + + // Bounding data (what we need for raycasting) + public Vector3 SortingCenter; + public float SortingRadius; + public Vector3 BoundsMin; + public Vector3 BoundsMax; + public bool HasBounds; + + // Vertex data (for precise bounds calculation) + public List<Vector3> Vertices = new List<Vector3>(); + + /// <summary> + /// Parse GfxObj to extract bounding information. + /// We don't need the full mesh/texture data for raycasting. + /// + /// Format (simplified): + /// uint32 id + /// uint32 flags + /// -- surface data (skip) -- + /// uint32 numVertices + /// for each vertex: + /// float3 position + /// float3 normal + /// (optional UV data based on flags) + /// -- polygon data (skip) -- + /// -- BSP data (skip for now) -- + /// float3 sortingCenter + /// float sortingRadius + /// </summary> + public bool Unpack(byte[] data) + { + if (data == null || data.Length < 12) + return false; + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + Id = reader.ReadUInt32(); + Flags = reader.ReadUInt32(); + + // Skip surface references + if (ms.Position + 4 > ms.Length) return false; + uint numSurfaces = reader.ReadUInt32(); + if (numSurfaces > 10000) return false; + ms.Seek(numSurfaces * 4, SeekOrigin.Current); // uint32 per surface + + // Read vertex count + if (ms.Position + 4 > ms.Length) return false; + uint numVertices = reader.ReadUInt32(); + if (numVertices > 100000) return false; + + // Read vertices and compute AABB + float minX = float.MaxValue, minY = float.MaxValue, minZ = float.MaxValue; + float maxX = float.MinValue, maxY = float.MinValue, maxZ = float.MinValue; + + for (uint i = 0; i < numVertices; i++) + { + if (ms.Position + 12 > ms.Length) break; + + float x = reader.ReadSingle(); + float y = reader.ReadSingle(); + float z = reader.ReadSingle(); + + if (float.IsNaN(x) || float.IsNaN(y) || float.IsNaN(z)) continue; + + Vertices.Add(new Vector3(x, y, z)); + + minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); + minY = Math.Min(minY, y); maxY = Math.Max(maxY, y); + minZ = Math.Min(minZ, z); maxZ = Math.Max(maxZ, z); + + // Skip normal (3 floats) + UV data + if (ms.Position + 12 <= ms.Length) + ms.Seek(12, SeekOrigin.Current); // Skip normal + + // UV data varies; skip based on flags + if ((Flags & 0x04) != 0 && ms.Position + 8 <= ms.Length) + ms.Seek(8, SeekOrigin.Current); // Skip UV + } + + if (Vertices.Count > 0) + { + BoundsMin = new Vector3(minX, minY, minZ); + BoundsMax = new Vector3(maxX, maxY, maxZ); + HasBounds = true; + + // Compute bounding sphere from AABB + SortingCenter = new Vector3( + (minX + maxX) * 0.5f, + (minY + maxY) * 0.5f, + (minZ + maxZ) * 0.5f + ); + SortingRadius = (BoundsMax - SortingCenter).Length(); + } + + // Also try to find the explicit sorting sphere at the end of file + TryReadSortingSphere(data); + + Log($"GfxObj 0x{Id:X8}: {Vertices.Count} verts, radius={SortingRadius:F2}"); + return true; + } + } + catch (Exception ex) + { + Log($"Error parsing GfxObj 0x{Id:X8}: {ex.Message}"); + return false; + } + } + + /// <summary> + /// Scans the end of the file for the sorting sphere data. + /// The sorting center + radius are typically near the end of the GfxObj. + /// </summary> + private void TryReadSortingSphere(byte[] data) + { + // The last 16 bytes before any trailing data often contain the sorting sphere + if (data.Length < 20) return; + + // Try reading from the last 16 bytes + for (int offset = data.Length - 16; offset >= Math.Max(0, data.Length - 64); offset -= 4) + { + if (offset + 16 > data.Length) continue; + + float cx = BitConverter.ToSingle(data, offset); + float cy = BitConverter.ToSingle(data, offset + 4); + float cz = BitConverter.ToSingle(data, offset + 8); + float r = BitConverter.ToSingle(data, offset + 12); + + if (r > 0.01f && r < 500f && !float.IsNaN(r) && !float.IsInfinity(r) && + !float.IsNaN(cx) && !float.IsNaN(cy) && !float.IsNaN(cz) && + Math.Abs(cx) < 1000 && Math.Abs(cy) < 1000 && Math.Abs(cz) < 1000) + { + SortingCenter = new Vector3(cx, cy, cz); + SortingRadius = r; + break; + } + } + } + + private static void Log(string msg) + { + System.Diagnostics.Debug.WriteLine($"[GfxObj] {msg}"); + } + } + + /// <summary> + /// A spherical collision volume from a Setup file. + /// </summary> + public class CollisionSphere + { + public Vector3 Center; + public float Radius; + } + + /// <summary> + /// A cylindrical collision volume from a Setup file. + /// </summary> + public class CollisionCylinder + { + public Vector3 BottomCenter; + public float Radius; + public float Height; + } +} diff --git a/Plugins/RynthAi/Raycasting/MainLogic.cs b/Plugins/RynthAi/Raycasting/MainLogic.cs new file mode 100644 index 0000000..c534bfd --- /dev/null +++ b/Plugins/RynthAi/Raycasting/MainLogic.cs @@ -0,0 +1,98 @@ +using System; +using Decal.Adapter; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Main integration point for the raycasting system. + /// Initializes the .dat file parsers, geometry loader, and targeting FSM. + /// + /// Usage: + /// var raycast = new MainLogic(); + /// raycast.Initialize(acFolderPath); // Call once at startup + /// + /// // During combat: + /// bool blocked = raycast.IsTargetBlocked(core, targetWorldObject, attackType); + /// </summary> + public class MainLogic : IDisposable + { + private GeometryLoader _geoLoader; + private BlacklistManager _blacklist; + private TargetingFSM _targetingFSM; + private bool _disposed; + + public GeometryLoader GeometryLoader => _geoLoader; + public BlacklistManager Blacklist => _blacklist; + public TargetingFSM TargetingFSM => _targetingFSM; + public bool IsInitialized => _geoLoader?.IsInitialized ?? false; + public string StatusMessage => _geoLoader?.StatusMessage ?? "Not created"; + + public MainLogic() + { + _geoLoader = new GeometryLoader(); + _blacklist = new BlacklistManager(); + _targetingFSM = new TargetingFSM(_geoLoader, _blacklist); + } + + /// <summary> + /// Initializes the raycasting system by loading portal.dat and cell.dat. + /// + /// acFolderPath: Optional explicit path to AC installation folder. + /// If null, will search common installation paths automatically. + /// + /// Returns true if initialization succeeded (both .dat files loaded). + /// </summary> + public bool Initialize(string acFolderPath = null) + { + try + { + bool result = _geoLoader.Initialize(acFolderPath); + if (result) + { + System.Diagnostics.Debug.WriteLine("[Raycast] MainLogic initialized successfully"); + } + else + System.Diagnostics.Debug.WriteLine($"[Raycast] MainLogic init failed: {_geoLoader.StatusMessage}"); + + return result; + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[Raycast] MainLogic init error: {ex.Message}"); + return false; + } + } + + /// <summary> + /// Quick check: is a specific target blocked by geometry? + /// Call this from CombatManager before engaging a target. + /// </summary> + public bool IsTargetBlocked(CoreManager core, Decal.Adapter.Wrappers.WorldObject target, + TargetingFSM.AttackType attackType) + { + if (!IsInitialized || _targetingFSM == null) + return false; + + return _targetingFSM.IsTargetBlocked(core, target, attackType); + } + + /// <summary> + /// Determines the attack type from the currently wielded weapon. + /// </summary> + public TargetingFSM.AttackType GetAttackType(CoreManager core) + { + return _targetingFSM?.DetermineAttackType(core) ?? TargetingFSM.AttackType.Linear; + } + + public void Dispose() + { + if (_disposed) return; + + _geoLoader?.Dispose(); + _blacklist?.ClearAll(); + + _disposed = true; + System.Diagnostics.Debug.WriteLine("[Raycast] MainLogic disposed"); + } + } +} diff --git a/Plugins/RynthAi/Raycasting/RaycastEngine.cs b/Plugins/RynthAi/Raycasting/RaycastEngine.cs new file mode 100644 index 0000000..25a4db6 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/RaycastEngine.cs @@ -0,0 +1,235 @@ +using System; +using System.Collections.Generic; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Core raycasting engine for line-of-sight checks. + /// Tests linear (spell/bolt) and parabolic (bow/thrown) trajectories + /// against the loaded collision geometry. + /// + /// NOTE: Uses custom Vector3 from this namespace, NOT System.Numerics. + /// </summary> + public static class RaycastEngine + { + /// <summary> + /// Gravity constant for parabolic trajectory calculations. + /// AC's gravity is approximately 9.81 m/s² but may need empirical tuning. + /// </summary> + private const float GRAVITY = 9.81f; + + /// <summary> + /// Number of sample points along an arc trajectory for collision testing. + /// Higher = more accurate but slower. 10 is a good balance. + /// </summary> + private const int ARC_SAMPLE_COUNT = 10; + + /// <summary> + /// Tests if a straight-line path (magic spells, crossbow bolts) is blocked + /// by any collision geometry. + /// + /// Returns true if the path IS blocked (an obstacle exists between origin and target). + /// Returns false if the path is clear. + /// </summary> + public static bool IsLinearPathBlocked(Vector3 origin, Vector3 target, List<BoundingVolume> geometry) + { + if (geometry == null || geometry.Count == 0) + return false; + + // Validate inputs + if (float.IsNaN(origin.X) || float.IsNaN(origin.Y) || float.IsNaN(origin.Z) || + float.IsNaN(target.X) || float.IsNaN(target.Y) || float.IsNaN(target.Z)) + return false; + + // Calculate direction and distance + Vector3 delta = target - origin; + float distanceToTarget = delta.Length(); + + // Origin and target are the same point — no obstruction possible + if (distanceToTarget < 1e-4f) + return false; + + // Normalize direction + Vector3 direction = delta / distanceToTarget; + + // Test ray against each bounding volume + foreach (var volume in geometry) + { + // Skip doors (state is unreliable, as per VTank's approach) + if (volume.IsDoor) + continue; + + // Test intersection + float hitDist; + if (volume.RayIntersect(origin, direction, distanceToTarget, out hitDist)) + { + // Ignore geometry within 2m of the player — prevents false blocks + // from walls/floors the player is standing on or touching. + // Only count geometry that's actually BETWEEN the player and target. + if (hitDist >= 2.0f && hitDist < distanceToTarget) + { + return true; // Path is blocked + } + } + } + + return false; // Path is clear + } + + /// <summary> + /// Tests if a parabolic arc path (bows, thrown weapons) is blocked by geometry. + /// + /// This allows attacks to arc over low obstacles like walls and rocks. + /// The arc is sampled at discrete points and each segment is tested for + /// intersection with geometry. + /// + /// Returns true if the arc IS blocked. + /// Returns false if the arc clears all obstacles. + /// </summary> + public static bool IsArcPathBlocked(Vector3 origin, Vector3 target, float initialVelocity, + List<BoundingVolume> geometry) + { + if (geometry == null || geometry.Count == 0) + return false; + + if (initialVelocity <= 0) + return true; // Can't fire with no velocity + + // Validate inputs + if (float.IsNaN(origin.X) || float.IsNaN(target.X)) + return true; + + Vector3 delta = target - origin; + float horizontalDist = delta.Length2D(); + float verticalDist = delta.Z; + + // Check maximum range: v² / g + float maxRange = (initialVelocity * initialVelocity) / GRAVITY; + if (horizontalDist > maxRange) + return true; // Out of range + + if (horizontalDist < 0.1f) + return false; // Basically on top of target + + // Calculate launch angle for the desired range + // Using the optimal angle that clears obstacles + // θ = 0.5 * arcsin(g * d / v²) for flat terrain + float sinArg = (GRAVITY * horizontalDist) / (initialVelocity * initialVelocity); + sinArg = Math.Min(sinArg, 1.0f); // Clamp for float precision + + // Use the high arc (π/2 - θ) for better obstacle clearance + float launchAngle = (float)(0.5 * Math.Asin(sinArg)); + if (launchAngle < 0.1f) + launchAngle = (float)(Math.PI / 4); // Default to 45° if calculation fails + + float cosAngle = (float)Math.Cos(launchAngle); + float sinAngle = (float)Math.Sin(launchAngle); + + // Calculate time of flight + float vHorizontal = initialVelocity * cosAngle; + float vVertical = initialVelocity * sinAngle; + + if (vHorizontal < 0.01f) + return true; // Basically firing straight up + + float totalTime = horizontalDist / vHorizontal; + + // Horizontal direction (unit vector in XY plane) + float hdx = delta.X / horizontalDist; + float hdy = delta.Y / horizontalDist; + + // Sample the arc at discrete points and test each segment + Vector3 prevPoint = origin; + + for (int i = 1; i <= ARC_SAMPLE_COUNT; i++) + { + float t = (float)i / ARC_SAMPLE_COUNT; + float time = t * totalTime; + + // Kinematic equations + float hDist = vHorizontal * time; + float height = origin.Z + vVertical * time - 0.5f * GRAVITY * time * time; + + // Adjust height to interpolate between origin.Z and target.Z + // (accounts for height difference between origin and target) + float heightAdjust = verticalDist * t; + + Vector3 arcPoint = new Vector3( + origin.X + hdx * hDist, + origin.Y + hdy * hDist, + height + heightAdjust * (1.0f - t) // Blend in height difference + ); + + // Test this segment for collisions + if (IsSegmentBlocked(prevPoint, arcPoint, geometry)) + return true; + + prevPoint = arcPoint; + } + + // Test final segment to target + if (IsSegmentBlocked(prevPoint, target, geometry)) + return true; + + return false; // Arc clears all obstacles + } + + /// <summary> + /// Tests if a line segment between two points intersects any geometry. + /// Used internally for arc sampling. + /// </summary> + private static bool IsSegmentBlocked(Vector3 start, Vector3 end, List<BoundingVolume> geometry) + { + Vector3 delta = end - start; + float dist = delta.Length(); + + if (dist < 0.01f) return false; + + Vector3 dir = delta / dist; + + foreach (var volume in geometry) + { + if (volume.IsDoor) continue; + + float hitDist; + if (volume.RayIntersect(start, dir, dist, out hitDist)) + { + if (hitDist > 0.05f && hitDist < dist - 0.05f) + return true; + } + } + + return false; + } + + /// <summary> + /// Quick distance-based pre-filter: checks if ANY geometry exists near the line + /// between origin and target. Used to skip the full raycast for wide-open areas. + /// Returns true if there is nearby geometry worth testing. + /// </summary> + public static bool HasNearbyGeometry(Vector3 origin, Vector3 target, List<BoundingVolume> geometry, float margin = 5.0f) + { + if (geometry == null || geometry.Count == 0) + return false; + + // Compute a rough bounding box for the path + Vector3 pathMin = Vector3.Min(origin, target) - new Vector3(margin, margin, margin); + Vector3 pathMax = Vector3.Max(origin, target) + new Vector3(margin, margin, margin); + + foreach (var vol in geometry) + { + if (vol.IsDoor) continue; + + // Quick AABB overlap test + if (vol.Max.X >= pathMin.X && vol.Min.X <= pathMax.X && + vol.Max.Y >= pathMin.Y && vol.Min.Y <= pathMax.Y && + vol.Max.Z >= pathMin.Z && vol.Min.Z <= pathMax.Z) + { + return true; + } + } + + return false; + } + } +} diff --git a/Plugins/RynthAi/Raycasting/ScatterSystem.cs b/Plugins/RynthAi/Raycasting/ScatterSystem.cs new file mode 100644 index 0000000..bb8785f --- /dev/null +++ b/Plugins/RynthAi/Raycasting/ScatterSystem.cs @@ -0,0 +1,948 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Implements AC's deterministic scatter placement system for terrain objects (trees, rocks, etc). + /// Ported from ACE's Landblock.get_land_scenes() + ObjectDesc.Displace/Rotate/Scale. + /// + /// Pipeline: + /// 1. Parse RegionDesc (0x13000000) from portal.dat → terrain-to-scene mapping tables + /// 2. Parse CellLandblock (0xXXYYFFFF) from cell.dat → 81 terrain values + 81 heights + /// 3. For each terrain cell, deterministically select and place scatter objects + /// 4. Look up bounding volumes for each placed object + /// </summary> + public class ScatterSystem + { + // LandDefs constants (from ACE) + private const int VertexDim = 9; // 9×9 vertices per landblock + private const int BlockSide = 8; // 8×8 cells per landblock + private const float CellLength = 24.0f; // Each cell is 24m + private const float BlockLength = 192.0f; + + // RegionDesc data (parsed once) + private List<ScatterTerrainType> _terrainTypes; + private List<ScatterSceneType> _sceneTypes; + private float[] _landHeightTable; + private bool _initialized; + + // Scene cache (portal.dat scenes) + private Dictionary<uint, List<ScatterObjectDesc>> _sceneCache = new Dictionary<uint, List<ScatterObjectDesc>>(); + + // Reference to dat files + private DatDatabase _portalDat; + private DatDatabase _cellDat; + + public bool IsInitialized => _initialized; + public List<string> DiagLog { get; } = new List<string>(); + + public bool Initialize(DatDatabase portalDat, DatDatabase cellDat) + { + _portalDat = portalDat; + _cellDat = cellDat; + + try + { + // Parse RegionDesc (0x13000000) from portal.dat + byte[] regionData = portalDat.GetFileData(0x13000000); + if (regionData == null || regionData.Length < 100) + { + Log($"RegionDesc 0x13000000 not found in portal.dat (data={regionData?.Length ?? 0})"); + return false; + } + + Log($"RegionDesc: {regionData.Length} bytes loaded"); + + // Dump first few uint32s for debugging + string header = "RegionDesc header: "; + for (int i = 0; i < Math.Min(32, regionData.Length); i += 4) + header += $"0x{BitConverter.ToUInt32(regionData, i):X8} "; + Log(header); + + if (!ParseRegionDesc(regionData)) + { + Log("Failed to parse RegionDesc"); + return false; + } + + _initialized = true; + Log($"Scatter system ready: {_terrainTypes?.Count ?? 0} terrain types, {_sceneTypes?.Count ?? 0} scene types"); + return true; + } + catch (Exception ex) + { + Log($"Scatter init error: {ex.Message}"); + return false; + } + } + + /// <summary> + /// Generates scatter object bounding volumes for a landblock. + /// Replicates ACE's Landblock.get_land_scenes() algorithm. + /// </summary> + public List<BoundingVolume> GetScatterVolumes(uint landblockKey, GeometryLoader geoLoader) + { + var volumes = new List<BoundingVolume>(); + if (!_initialized || _terrainTypes == null || _sceneTypes == null) + return volumes; + + try + { + // Read CellLandblock (0xXXYYFFFF) from cell.dat + uint cellLandblockId = (landblockKey << 16) | 0xFFFF; + byte[] data = _cellDat.GetFileData(cellLandblockId); + if (data == null || data.Length < 170) // Minimum: 4+4+81*2+81*1 = 255 + return volumes; + + // Parse terrain and height arrays + ushort[] terrain = new ushort[81]; + byte[] height = new byte[81]; + + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); + uint hasObjects = reader.ReadUInt32(); + + for (int i = 0; i < 81; i++) + terrain[i] = reader.ReadUInt16(); + + for (int i = 0; i < 81; i++) + height[i] = reader.ReadByte(); + } + + // Compute block offsets (global cell coordinates) + uint blockX = ((landblockKey >> 8) & 0xFF) * 8; + uint blockY = (landblockKey & 0xFF) * 8; + + float globalOffsetX = ((landblockKey >> 8) & 0xFF) * BlockLength; + float globalOffsetY = (landblockKey & 0xFF) * BlockLength; + + int scatterCount = 0; + + // Iterate all 81 terrain cells (matching ACE's get_land_scenes) + for (uint i = 0; i < 81; i++) + { + ushort t = terrain[i]; + int terrainType = (t >> 2) & 0x1F; // 5 bits, 0-31 + int sceneType = t >> 11; // 5 bits, 0-31 + + if (terrainType >= _terrainTypes.Count) continue; + var tt = _terrainTypes[terrainType]; + if (sceneType >= tt.SceneTypeIndices.Count) continue; + + int sceneInfoIdx = (int)tt.SceneTypeIndices[sceneType]; + if (sceneInfoIdx >= _sceneTypes.Count) continue; + + var scenes = _sceneTypes[sceneInfoIdx].SceneFileIds; + if (scenes.Count == 0) continue; + + uint cellX = i / (uint)VertexDim; + uint cellY = i % (uint)VertexDim; + + uint globalCellX = (uint)(cellX + blockX); + uint globalCellY = (uint)(cellY + blockY); + + // Deterministic scene selection — uses uint32 overflow arithmetic + // matching AC client's C++ unsigned int behavior + uint cellMat = (uint)((long)globalCellY * (712977289L * globalCellX + 1813693831L) - 1109124029L * globalCellX + 2139937281L); + double offset = cellMat * 2.3283064e-10; + int sceneIdx = (int)(scenes.Count * offset); + if (sceneIdx < 0 || sceneIdx >= scenes.Count) sceneIdx = 0; + + uint sceneId = scenes[sceneIdx]; + + // Load the Scene file + var sceneObjects = LoadScene(sceneId); + if (sceneObjects == null || sceneObjects.Count == 0) continue; + + // Per-object noise seeds — uint32 overflow + uint cellXMat = (uint)(-1109124029L * globalCellX); + uint cellYMat = (uint)(1813693831L * globalCellY); + uint cellMat2 = (uint)(1360117743L * globalCellX * globalCellY + 1888038839L); + + for (uint j = 0; j < sceneObjects.Count; j++) + { + var obj = sceneObjects[(int)j]; + + // Frequency check — uint32 overflow + double noise = (uint)(cellXMat + cellYMat - cellMat2 * (23399 + j)) * 2.3283064e-10; + if (noise >= obj.Freq || obj.WeenieObj != 0) + continue; + + // Displace + var position = Displace(obj, globalCellX, globalCellY, j); + + float lx = cellX * CellLength + position.X; + float ly = cellY * CellLength + position.Y; + + // Bounds check + if (lx < 0 || ly < 0 || lx >= BlockLength || ly >= BlockLength) + continue; + + // Get terrain height at this position + float z = GetTerrainHeight(height, lx, ly); + + // World coordinates + float worldX = globalOffsetX + lx; + float worldY = globalOffsetY + ly; + + // Get bounding volume for this object + var setupVolumes = geoLoader.GetSetupBoundingVolumesPublic(obj.ObjId); + foreach (var vol in setupVolumes) + { + // Create a frame for the scatter object + var frame = new Frame + { + OriginX = lx, OriginY = ly, OriginZ = z, + RotW = 1, RotX = 0, RotY = 0, RotZ = 0 + }; + + // Apply rotation from scatter algorithm + ApplyScatterRotation(frame, obj, globalCellX, globalCellY, j); + + var transformed = TransformScatterVolume(vol, frame, globalOffsetX, globalOffsetY); + if (transformed != null) + { + // Extend scatter volumes vertically to account for: + // 1. Terrain height imprecision (nearest-vertex vs polygon, can be 10-15m off) + // 2. Trees/rocks extend upward from ground level + // Use generous range to ensure ray intersection works + float extendBelow = 20.0f; + float extendAbove = 20.0f; + transformed.Min = new Vector3(transformed.Min.X, transformed.Min.Y, transformed.Min.Z - extendBelow); + transformed.Max = new Vector3(transformed.Max.X, transformed.Max.Y, transformed.Max.Z + extendAbove); + transformed.Center = new Vector3(transformed.Center.X, transformed.Center.Y, + (transformed.Min.Z + transformed.Max.Z) * 0.5f); + // Force AABB type so Min/Max Z extension is used by ray intersection + transformed.Type = BoundingVolume.VolumeType.AxisAlignedBox; + transformed.Dimensions = transformed.Max - transformed.Min; + + volumes.Add(transformed); + } + } + scatterCount++; + } + } + + if (scatterCount > 0) + Log($"Landblock 0x{landblockKey:X4}: {scatterCount} scatter objects -> {volumes.Count} volumes"); + } + catch (Exception ex) + { + Log($"Scatter error for 0x{landblockKey:X4}: {ex.Message}"); + } + + return volumes; + } + + // =================================================================== + // ObjectDesc.Displace — pseudo-random placement from ACE + // =================================================================== + + private Vector3 Displace(ScatterObjectDesc obj, uint ix, uint iy, uint iq) + { + float x, y, z; + float locX = obj.BaseLocX, locY = obj.BaseLocY, locZ = obj.BaseLocZ; + + // uint32 overflow arithmetic matching AC client C++ unsigned int + if (obj.DisplaceX <= 0) + x = locX; + else + x = (float)((uint)(1813693831L * iy - (iq + 45773) * (1360117743L * iy * ix + 1888038839L) - 1109124029L * ix) + * 2.3283064e-10 * obj.DisplaceX + locX); + + if (obj.DisplaceY <= 0) + y = locY; + else + y = (float)((uint)(1813693831L * iy - (iq + 72719) * (1360117743L * iy * ix + 1888038839L) - 1109124029L * ix) + * 2.3283064e-10 * obj.DisplaceY + locY); + + z = locZ; + + double quadrant = (uint)(1813693831L * iy - ix * (1870387557L * iy + 1109124029L) - 402451965L) * 2.3283064e-10; + + if (quadrant >= 0.75) return new Vector3(y, -x, z); + if (quadrant >= 0.5) return new Vector3(-x, -y, z); + if (quadrant >= 0.25) return new Vector3(-y, x, z); + return new Vector3(x, y, z); + } + + private void ApplyScatterRotation(Frame frame, ScatterObjectDesc obj, uint x, uint y, uint k) + { + if (obj.MaxRotation > 0.0f) + { + float degrees = (float)((uint)(1813693831L * y - (k + 63127) * (1360117743L * y * x + 1888038839L) - 1109124029L * x) * 2.3283064e-10 * obj.MaxRotation); + float radians = degrees * (float)(Math.PI / 180.0); + float halfRad = radians * 0.5f; + frame.RotW = (float)Math.Cos(halfRad); + frame.RotZ = (float)Math.Sin(halfRad); + } + } + + private float GetTerrainHeight(byte[] heights, float lx, float ly) + { + // Bilinear interpolation of height values + // LandHeightTable already contains actual in-game Z heights + // (the *2 factor from CellLandblock comments refers to raw bytes, not table values) + int ix = Math.Min((int)(lx / CellLength), BlockSide); + int iy = Math.Min((int)(ly / CellLength), BlockSide); + + int idx = ix * VertexDim + iy; + if (idx >= 0 && idx < 81 && _landHeightTable != null) + { + byte h = heights[idx]; + if (h < _landHeightTable.Length) + return _landHeightTable[h]; + } + return 0; + } + + private BoundingVolume TransformScatterVolume(BoundingVolume localVol, Frame placement, + float globalOffsetX, float globalOffsetY) + { + if (localVol == null) return null; + + try + { + Vector3 worldCenter = placement.TransformPoint(localVol.Center); + worldCenter.X += globalOffsetX; + worldCenter.Y += globalOffsetY; + + if (localVol.Type == BoundingVolume.VolumeType.Sphere) + { + float r = localVol.Dimensions.X; + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.Sphere, + Center = worldCenter, + Dimensions = localVol.Dimensions, + Min = worldCenter - new Vector3(r, r, r), + Max = worldCenter + new Vector3(r, r, r), + IsDoor = false + }; + } + + // For non-sphere: transform corners to get new AABB + Vector3[] corners = { + new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Min.Z), + new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Min.Z), + new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Min.Z), + new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Min.Z), + new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Max.Z), + new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Max.Z), + new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Max.Z), + new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Max.Z), + }; + + Vector3 newMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); + Vector3 newMax = new Vector3(float.MinValue, float.MinValue, float.MinValue); + + for (int c = 0; c < 8; c++) + { + Vector3 w = placement.TransformPoint(corners[c]); + w.X += globalOffsetX; + w.Y += globalOffsetY; + newMin = Vector3.Min(newMin, w); + newMax = Vector3.Max(newMax, w); + } + + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.AxisAlignedBox, + Center = (newMin + newMax) * 0.5f, + Dimensions = newMax - newMin, + Min = newMin, + Max = newMax, + IsDoor = false + }; + } + catch { return null; } + } + + // =================================================================== + // Scene loading + // =================================================================== + + private List<ScatterObjectDesc> LoadScene(uint sceneId) + { + if (_sceneCache.TryGetValue(sceneId, out var cached)) + return cached; + + var objects = new List<ScatterObjectDesc>(); + + try + { + byte[] data = _portalDat.GetFileData(sceneId); + if (data == null || data.Length < 8) + { + _sceneCache[sceneId] = objects; + return objects; + } + + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); // Scene ID + + // List<ObjectDesc>: uint32 count + count × ObjectDesc + uint numObjects = reader.ReadUInt32(); + if (numObjects > 200) numObjects = 200; + + for (uint i = 0; i < numObjects; i++) + { + if (ms.Position + 72 > ms.Length) break; // ObjectDesc is 72 bytes + + var obj = new ScatterObjectDesc(); + obj.ObjId = reader.ReadUInt32(); + + // Frame (BaseLoc): 7 floats + obj.BaseLocX = reader.ReadSingle(); + obj.BaseLocY = reader.ReadSingle(); + obj.BaseLocZ = reader.ReadSingle(); + obj.BaseLocW = reader.ReadSingle(); + obj.BaseLocRX = reader.ReadSingle(); + obj.BaseLocRY = reader.ReadSingle(); + obj.BaseLocRZ = reader.ReadSingle(); + + obj.Freq = reader.ReadSingle(); + obj.DisplaceX = reader.ReadSingle(); + obj.DisplaceY = reader.ReadSingle(); + obj.MinScale = reader.ReadSingle(); + obj.MaxScale = reader.ReadSingle(); + obj.MaxRotation = reader.ReadSingle(); + obj.MinSlope = reader.ReadSingle(); + obj.MaxSlope = reader.ReadSingle(); + obj.Align = reader.ReadUInt32(); + obj.Orient = reader.ReadUInt32(); + obj.WeenieObj = reader.ReadUInt32(); + + objects.Add(obj); + } + } + } + catch (Exception ex) + { + Log($"Scene 0x{sceneId:X8} parse error: {ex.Message}"); + } + + _sceneCache[sceneId] = objects; + return objects; + } + + // =================================================================== + // RegionDesc parsing (0x13000000) + // =================================================================== + + private bool ParseRegionDesc(byte[] data) + { + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); // 0x13000000 + uint regionNumber = reader.ReadUInt32(); + uint version = reader.ReadUInt32(); + + Log($"RegionDesc: id=0x{id:X8}, region={regionNumber}, version={version}"); + + // PString RegionName ("Dereth") + SkipPString(reader, ms); + Log($"After RegionName: pos={ms.Position}"); + + // LandDefs + if (!ParseLandDefs(reader, ms)) + { + Log($"LandDefs parse failed at pos={ms.Position}"); + return ScanForTables(data); + } + Log($"After LandDefs: pos={ms.Position}"); + + // GameTime + if (!SkipGameTime(reader, ms)) + { + Log($"GameTime skip failed at pos={ms.Position}"); + return ScanForTables(data); + } + Log($"After GameTime: pos={ms.Position}"); + + // PartsMask + uint partsMask = reader.ReadUInt32(); + Log($"PartsMask=0x{partsMask:X8}, pos={ms.Position}"); + + // Skip SkyDesc if present + if ((partsMask & 0x10) != 0) + { + Log("Skipping SkyDesc..."); + if (!SkipSkyDesc(reader, ms)) + { + Log($"SkyDesc skip failed at pos={ms.Position}, trying fallback"); + return ScanForTables(data); + } + Log($"After SkyDesc: pos={ms.Position}"); + } + + // Skip SoundDesc if present + if ((partsMask & 0x01) != 0) + { + Log("Skipping SoundDesc..."); + if (!SkipSoundDesc(reader, ms)) + { + Log($"SoundDesc skip failed at pos={ms.Position}, trying fallback"); + return ScanForTables(data); + } + Log($"After SoundDesc: pos={ms.Position}"); + } + + // Parse SceneDesc + if ((partsMask & 0x02) != 0) + { + Log("Parsing SceneDesc..."); + if (!ParseSceneDesc(reader, ms)) + { + Log($"SceneDesc parse failed at pos={ms.Position}, trying fallback"); + return ScanForTables(data); + } + Log($"After SceneDesc: pos={ms.Position}"); + } + + // Parse TerrainDesc + Log("Parsing TerrainDesc..."); + if (!ParseTerrainDesc(reader, ms)) + { + Log($"TerrainDesc parse failed at pos={ms.Position}, trying fallback"); + return ScanForTables(data); + } + + Log($"RegionDesc parsed: {_terrainTypes?.Count} terrainTypes, {_sceneTypes?.Count} sceneTypes"); + return _terrainTypes != null && _sceneTypes != null; + } + } + catch (Exception ex) + { + Log($"RegionDesc parse error at unknown pos: {ex.Message}"); + return ScanForTables(data); + } + } + + private bool ParseLandDefs(BinaryReader reader, MemoryStream ms) + { + if (ms.Position + 1056 > ms.Length) return false; + + reader.ReadInt32(); // NumBlockLength + reader.ReadInt32(); // NumBlockWidth + reader.ReadSingle(); // SquareLength + reader.ReadInt32(); // LBlockLength + reader.ReadInt32(); // VertexPerCell + reader.ReadSingle(); // MaxObjHeight + reader.ReadSingle(); // SkyHeight + reader.ReadSingle(); // RoadWidth + + _landHeightTable = new float[256]; + for (int i = 0; i < 256; i++) + _landHeightTable[i] = reader.ReadSingle(); + + return true; + } + + private bool SkipGameTime(BinaryReader reader, MemoryStream ms) + { + try + { + reader.ReadDouble(); // ZeroTimeOfYear + reader.ReadUInt32(); // ZeroYear + reader.ReadSingle(); // DayLength + reader.ReadUInt32(); // DaysPerYear + SkipPString(reader, ms); // YearSpec + + // List<TimeOfDay> — uint32 count + entries + uint numTOD = reader.ReadUInt32(); + if (numTOD > 100) return false; + for (uint i = 0; i < numTOD; i++) + { + reader.ReadSingle(); // Begin time + reader.ReadUInt32(); // IsNight flag + SkipPString(reader, ms); // Name + } + + // DaysOfTheWeek — uint32 count + PStrings + uint numDays = reader.ReadUInt32(); + if (numDays > 20) return false; + for (uint i = 0; i < numDays; i++) + SkipPString(reader, ms); + + // List<Season> — uint32 count + entries + uint numSeasons = reader.ReadUInt32(); + if (numSeasons > 20) return false; + for (uint i = 0; i < numSeasons; i++) + { + reader.ReadUInt32(); // StartDate + SkipPString(reader, ms); // Name + } + + return true; + } + catch + { + return false; + } + } + + private bool SkipSkyDesc(BinaryReader reader, MemoryStream ms) + { + // SkyDesc is complex (sky objects, colors, etc). Skip by searching for next recognizable section. + // Store position and try to skip it. + try + { + // SkyDesc format: TickSize(double) + LightTickSize(double) + DayGroup(SkyObjectReplace) + NightGroup + ... + // This is very complex. We'll use a heuristic: skip forward looking for SceneDesc signature. + // For now, try to skip a known minimum size + reader.ReadDouble(); // TickSize + reader.ReadDouble(); // LightTickSize + + // DayGroup + SkipSkyObjectGroup(reader, ms); + // NightGroup + SkipSkyObjectGroup(reader, ms); + + return true; + } + catch + { + return false; + } + } + + private void SkipSkyObjectGroup(BinaryReader reader, MemoryStream ms) + { + // SkyObjectReplace: uint32 count + entries + uint count = reader.ReadUInt32(); + for (uint i = 0; i < count && ms.Position < ms.Length; i++) + { + reader.ReadUInt32(); // object index + reader.ReadUInt32(); // GfxObj ID + reader.ReadSingle(); // rotate + reader.ReadSingle(); // transparent + reader.ReadSingle(); // luminosity + reader.ReadSingle(); // max bright + } + } + + private bool SkipSoundDesc(BinaryReader reader, MemoryStream ms) + { + try + { + // SoundDesc: List<AmbientSoundDesc> + uint count = reader.ReadUInt32(); + if (count > 200) return false; + for (uint i = 0; i < count && ms.Position < ms.Length; i++) + { + reader.ReadUInt32(); // SType + reader.ReadSingle(); // Volume + reader.ReadSingle(); // BaseChance + reader.ReadSingle(); // MinRate + reader.ReadSingle(); // MaxRate + } + return true; + } + catch + { + return false; + } + } + + private bool ParseSceneDesc(BinaryReader reader, MemoryStream ms) + { + try + { + // SceneDesc: List<SceneType> + uint numSceneTypes = reader.ReadUInt32(); + if (numSceneTypes > 500) return false; + + _sceneTypes = new List<ScatterSceneType>(); + + for (uint i = 0; i < numSceneTypes; i++) + { + var st = new ScatterSceneType(); + st.StbIndex = reader.ReadUInt32(); + + // List<uint> Scenes + uint numScenes = reader.ReadUInt32(); + if (numScenes > 500) return false; + + st.SceneFileIds = new List<uint>(); + for (uint s = 0; s < numScenes; s++) + st.SceneFileIds.Add(reader.ReadUInt32()); + + _sceneTypes.Add(st); + } + + Log($"SceneDesc: {_sceneTypes.Count} scene types parsed"); + return true; + } + catch + { + return false; + } + } + + private bool ParseTerrainDesc(BinaryReader reader, MemoryStream ms) + { + try + { + // TerrainDesc: List<TerrainType> + LandSurf + uint numTerrainTypes = reader.ReadUInt32(); + if (numTerrainTypes > 100) return false; + + _terrainTypes = new List<ScatterTerrainType>(); + + for (uint i = 0; i < numTerrainTypes; i++) + { + var tt = new ScatterTerrainType(); + + // PString TerrainName + SkipPString(reader, ms); + + // uint32 TerrainColor + reader.ReadUInt32(); + + // List<uint> SceneTypes + uint numSceneTypes = reader.ReadUInt32(); + if (numSceneTypes > 200) return false; + + tt.SceneTypeIndices = new List<uint>(); + for (uint s = 0; s < numSceneTypes; s++) + tt.SceneTypeIndices.Add(reader.ReadUInt32()); + + _terrainTypes.Add(tt); + } + + Log($"TerrainDesc: {_terrainTypes.Count} terrain types parsed"); + return true; + } + catch + { + return false; + } + } + + // =================================================================== + // Fallback: scan RegionDesc data for recognizable table patterns + // =================================================================== + + private bool ScanForTables(byte[] data) + { + Log("Attempting fallback scan for scatter tables..."); + + // Strategy: Scan for SceneDesc (uint32 count followed by entries with 0x12xxxxxx scene IDs) + // The real AC SceneDesc has ~89 entries. We require at least 20 to avoid false positives. + // TerrainDesc (~32 entries with PString names) follows right after SceneDesc. + + for (int pos = 100; pos < data.Length - 100; pos += 4) + { + uint count = BitConverter.ToUInt32(data, pos); + if (count < 20 || count > 200) continue; + + // Validate: try to read all entries as SceneType { uint32 StbIndex, uint32 numScenes, uint32[] sceneIds } + bool valid = true; + int scanPos = pos + 4; + int totalSceneIds = 0; + + for (int i = 0; i < count && valid; i++) + { + if (scanPos + 8 > data.Length) { valid = false; break; } + + uint stbIndex = BitConverter.ToUInt32(data, scanPos); + scanPos += 4; + + uint numScenes = BitConverter.ToUInt32(data, scanPos); + scanPos += 4; + + if (numScenes > 200) { valid = false; break; } + + for (int s = 0; s < numScenes && valid; s++) + { + if (scanPos + 4 > data.Length) { valid = false; break; } + uint sceneId = BitConverter.ToUInt32(data, scanPos); + scanPos += 4; + + // Scene files are 0x12xxxxxx + if ((sceneId & 0xFF000000) != 0x12000000) { valid = false; break; } + totalSceneIds++; + } + } + + if (!valid || totalSceneIds < 10) continue; + + // We found a candidate SceneDesc! Parse it fully. + _sceneTypes = new List<ScatterSceneType>(); + int fullPos = pos + 4; + + for (int i = 0; i < count; i++) + { + if (fullPos + 8 > data.Length) break; + uint stbIdx = BitConverter.ToUInt32(data, fullPos); + fullPos += 4; + uint nScenes = BitConverter.ToUInt32(data, fullPos); + fullPos += 4; + + var st = new ScatterSceneType { StbIndex = stbIdx, SceneFileIds = new List<uint>() }; + for (int s = 0; s < nScenes; s++) + { + if (fullPos + 4 > data.Length) break; + st.SceneFileIds.Add(BitConverter.ToUInt32(data, fullPos)); + fullPos += 4; + } + _sceneTypes.Add(st); + } + + Log($"Fallback found SceneDesc at offset {pos}: {_sceneTypes.Count} types, {totalSceneIds} total scene IDs"); + + // Now parse TerrainDesc starting right after SceneDesc + if (fullPos + 4 < data.Length) + { + if (ParseTerrainDescFromOffset(data, fullPos)) + { + Log($"Fallback TerrainDesc succeeded: {_terrainTypes.Count} terrain types"); + return true; + } + else + { + Log($"TerrainDesc failed at offset {fullPos}, continuing scan..."); + _sceneTypes = null; + continue; // Try finding another SceneDesc + } + } + } + + Log("Fallback scan failed to find scatter tables"); + return false; + } + + private bool ParseTerrainDescFromOffset(byte[] data, int startPos) + { + try + { + _terrainTypes = new List<ScatterTerrainType>(); + int pos = startPos; + + if (pos + 4 > data.Length) { _terrainTypes = null; return false; } + uint count = BitConverter.ToUInt32(data, pos); + pos += 4; + + if (count < 5 || count > 100) { _terrainTypes = null; return false; } + + for (int i = 0; i < count; i++) + { + var tt = new ScatterTerrainType(); + + // PString: ushort length + chars + align to 4 + if (pos + 2 > data.Length) { _terrainTypes = null; return false; } + ushort strLen = BitConverter.ToUInt16(data, pos); + pos += 2; + + if (strLen > 200 || pos + strLen > data.Length) { _terrainTypes = null; return false; } + + // Verify it looks like a text string (ASCII printable) + if (i < 3 && strLen > 0) + { + bool isPrintable = true; + for (int c = 0; c < Math.Min((int)strLen, 10); c++) + { + byte b = data[pos + c]; + if (b < 32 || b > 126) { isPrintable = false; break; } + } + if (!isPrintable) { _terrainTypes = null; return false; } + + string name = System.Text.Encoding.ASCII.GetString(data, pos, strLen); + Log($" TerrainType[{i}]: \"{name}\""); + } + + pos += strLen; + pos = (pos + 3) & ~3; // Align to 4 + + // uint32 TerrainColor + if (pos + 4 > data.Length) { _terrainTypes = null; return false; } + pos += 4; + + // List<uint> SceneTypes + if (pos + 4 > data.Length) { _terrainTypes = null; return false; } + uint numST = BitConverter.ToUInt32(data, pos); + pos += 4; + + if (numST > 200) { _terrainTypes = null; return false; } + + tt.SceneTypeIndices = new List<uint>(); + for (int s = 0; s < numST; s++) + { + if (pos + 4 > data.Length) { _terrainTypes = null; return false; } + tt.SceneTypeIndices.Add(BitConverter.ToUInt32(data, pos)); + pos += 4; + } + + _terrainTypes.Add(tt); + } + + return _terrainTypes.Count >= 5; + } + catch + { + _terrainTypes = null; + return false; + } + } + + // =================================================================== + // Helpers + // =================================================================== + + private void SkipPString(BinaryReader reader, MemoryStream ms) + { + ushort len = reader.ReadUInt16(); + if (len > 0 && ms.Position + len <= ms.Length) + ms.Seek(len, SeekOrigin.Current); + // Align to 4 bytes + long alignedPos = (ms.Position + 3) & ~3L; + if (alignedPos <= ms.Length) + ms.Position = alignedPos; + } + + private void Log(string msg) + { + string line = $"[Scatter] {msg}"; + System.Diagnostics.Debug.WriteLine(line); + if (DiagLog.Count < 100) DiagLog.Add(msg); + } + } + + // =================================================================== + // Data structures for scatter system + // =================================================================== + + public class ScatterTerrainType + { + public List<uint> SceneTypeIndices = new List<uint>(); + } + + public class ScatterSceneType + { + public uint StbIndex; + public List<uint> SceneFileIds = new List<uint>(); + } + + public class ScatterObjectDesc + { + public uint ObjId; + public float BaseLocX, BaseLocY, BaseLocZ; + public float BaseLocW, BaseLocRX, BaseLocRY, BaseLocRZ; + public float Freq; + public float DisplaceX, DisplaceY; + public float MinScale, MaxScale; + public float MaxRotation; + public float MinSlope, MaxSlope; + public uint Align, Orient, WeenieObj; + } +} diff --git a/Plugins/RynthAi/Raycasting/TargetingFSM.cs b/Plugins/RynthAi/Raycasting/TargetingFSM.cs new file mode 100644 index 0000000..c925764 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/TargetingFSM.cs @@ -0,0 +1,364 @@ +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using System; +using System.Collections.Generic; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Provides line-of-sight checking for the combat system. + /// Converts Decal API coordinates to global meter space and + /// performs raycasting against loaded landblock geometry. + /// + /// Coordinate system: + /// AC uses a landblock grid where each block is 192×192 meters. + /// Landcell ID format: 0xXXYYnnnn where XX=east-west block, YY=north-south block. + /// LocationX/Y are local offsets within the landblock (0-192 meters). + /// + /// We convert everything to "global meters" for raycasting: + /// GlobalX = (XX * 192) + LocationX + /// GlobalY = (YY * 192) + LocationY + /// GlobalZ = LocationZ (altitude, 0 = sea level) + /// </summary> + public class TargetingFSM + { + private readonly GeometryLoader _geoLoader; + private readonly BlacklistManager _blacklist; + + // Attack type determines which raycast to use + public enum AttackType + { + Linear, // Bolts, streaks, crossbow bolts, melee + BowArc, // Bows — moderate arc, arrows go higher than you'd think + ThrownArc, // Thrown weapons, atlatls — similar arc to bows + MagicArc // War/Void magic Arc spells — same trajectory as missile weapons + } + + // AC arrows arc noticeably — they go HIGH. A lower velocity = higher arc. + // At 70 yard range, arrows visibly arc 3-4 meters above the direct line. + // This must match the actual game trajectory to detect ceiling hits in dungeons. + public float BowArcVelocity { get; set; } = 25.0f; + + // Thrown weapons arc similarly to bows + public float ThrownArcVelocity { get; set; } = 22.0f; + + // Magic arc spells (War/Void Arc) have the same trajectory as missile weapons + public float MagicArcVelocity { get; set; } = 25.0f; + + // If true, use arc checks for missile weapons. If false, treat all as linear. + public bool UseArcs { get; set; } = true; + + // Max scan distance in meters. Only check LOS for targets within this range. + // Set from CombatManager based on MonsterRange + buffer. + public float MaxScanDistanceMeters { get; set; } = 120.0f; + + public TargetingFSM(GeometryLoader geoLoader, BlacklistManager blacklist) + { + _geoLoader = geoLoader ?? throw new ArgumentNullException(nameof(geoLoader)); + _blacklist = blacklist ?? throw new ArgumentNullException(nameof(blacklist)); + } + + /// <summary> + /// Checks if line-of-sight to a target is blocked by geometry. + /// + /// Returns true if the target IS blocked (should skip this target). + /// Returns false if the target is clear to attack. + /// </summary> + public bool IsTargetBlocked(CoreManager core, WorldObject target, AttackType attackType) + { + if (core == null || target == null) + return false; + + if (!_geoLoader.IsInitialized) + return false; + + try + { + Vector3 origin = GetPlayerPosition(core); + if (origin == Vector3.Zero) + return false; + + Vector3 targetPos = GetObjectPosition(target, core); + if (targetPos == Vector3.Zero) + return false; + + // Early-out: skip raycast if target is beyond scan distance + float dx = targetPos.X - origin.X; + float dy = targetPos.Y - origin.Y; + float flatDist = (float)Math.Sqrt(dx * dx + dy * dy); + if (flatDist > MaxScanDistanceMeters) + return false; // Too far to bother checking, let combat handle range + + // Offset to chest height + origin.Z += 1.0f; + targetPos.Z += 1.0f; + + uint landcell = GetPlayerLandcell(core); + uint cellPart = landcell & 0xFFFF; + bool isDungeon = cellPart >= 0x0100; + + // Force linear checks indoors — arc trajectories hit ceilings + if (isDungeon) + attackType = AttackType.Linear; + + var geometry = _geoLoader.GetLandblockGeometry(landcell); + + if (geometry == null || geometry.Count == 0) + return false; + + // Pre-filter: skip full ray test if no geometry near the path + float margin = Math.Min(flatDist * 0.3f, 15.0f); + margin = Math.Max(margin, 3.0f); + if (!RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry, margin)) + return false; + + switch (attackType) + { + case AttackType.Linear: + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + + case AttackType.BowArc: + if (UseArcs) + { + if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, BowArcVelocity, geometry)) + return false; + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + } + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + + case AttackType.ThrownArc: + if (UseArcs) + { + if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, ThrownArcVelocity, geometry)) + return false; + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + } + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + + case AttackType.MagicArc: + // Magic Arc spells have the same trajectory as missile weapons + if (UseArcs && !isDungeon) // Don't arc-check in dungeons (ceiling clips) + { + if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, MagicArcVelocity, geometry)) + return false; + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + } + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + + default: + return false; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[Targeting] Error checking LOS: {ex.Message}"); + return false; + } + } + + /// <summary> + /// Finds the best unblocked target from a list of candidates. + /// Returns the target ID, or 0 if no clear target is found. + /// </summary> + public int FindBestTarget(CoreManager core, List<WorldObject> candidates, AttackType attackType) + { + if (core == null || candidates == null || candidates.Count == 0) + return 0; + + foreach (var candidate in candidates) + { + try + { + int id = candidate.Id; + + // Skip blacklisted targets + if (_blacklist.IsBlacklisted(id)) + continue; + + // Skip blocked targets + if (IsTargetBlocked(core, candidate, attackType)) + { + System.Diagnostics.Debug.WriteLine($"[Targeting] Target {id} blocked by geometry, skipping"); + continue; + } + + return id; // Found a clear target + } + catch + { + continue; + } + } + + return 0; // No clear targets + } + + /// <summary> + /// Gets the player's position in global meter coordinates. + /// Uses Decal's HooksWrapper (accessed via CoreManager.Actions). + /// + /// Landcell format: 0xXXYYnnnn + /// XX = east-west block index (0-254) + /// YY = north-south block index (0-254) + /// + /// LocationX/Y = offset within landblock (0-192 meters for outdoors) + /// LocationZ = altitude in meters (0 = sea level) + /// + /// Global conversion: + /// GlobalX = XX * 192 + LocationX + /// GlobalY = YY * 192 + LocationY + /// GlobalZ = LocationZ + /// </summary> + private Vector3 GetPlayerPosition(CoreManager core) + { + try + { + uint landcell = (uint)core.Actions.Landcell; + + uint blockX = (landcell >> 24) & 0xFF; + uint blockY = (landcell >> 16) & 0xFF; + + float localX = (float)core.Actions.LocationX; + float localY = (float)core.Actions.LocationY; + float localZ = (float)core.Actions.LocationZ; + + float globalX = blockX * 192.0f + localX; + float globalY = blockY * 192.0f + localY; + + return new Vector3(globalX, globalY, localZ); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[Targeting] Error getting player pos: {ex.Message}"); + return Vector3.Zero; + } + } + + /// <summary> + /// Gets a world object's position in global meter coordinates. + /// Uses Decal's CoordsObject (EastWest/NorthSouth) and converts to meters. + /// + /// From Decal docs: + /// EW = ((Landcell >> 24) + LocationX / 24.0 - 1019.5) / 10.0 + /// NS = (((Landcell >> 16) & 0xFF) + LocationY / 24.0 - 1019.5) / 10.0 + /// + /// Reverse conversion (EW/NS → global meters): + /// GlobalX = (EW * 10.0 + 1019.5) * 24.0 + /// GlobalY = (NS * 10.0 + 1019.5) * 24.0 + /// </summary> + private Vector3 GetObjectPosition(WorldObject obj, CoreManager core) + { + try + { + var coords = obj.Coordinates(); + if (coords == null) + return Vector3.Zero; + + double ew = coords.EastWest; + double ns = coords.NorthSouth; + + float globalX = (float)((ew * 10.0 + 1019.5) * 24.0); + float globalY = (float)((ns * 10.0 + 1019.5) * 24.0); + + // Z coordinate: MUST come from RawCoordinates. + // If unavailable, return Zero to skip LOS (safer than guessing wrong Z). + float z = 0; + try + { + var raw = obj.RawCoordinates(); + if (raw != null) + z = (float)raw.Z; + else + return Vector3.Zero; // Can't determine Z — skip LOS + } + catch + { + return Vector3.Zero; // Can't determine Z — skip LOS + } + + return new Vector3(globalX, globalY, z); + } + catch + { + return Vector3.Zero; + } + } + + /// <summary> + /// Gets the player's current Landcell value for geometry lookup. + /// </summary> + private uint GetPlayerLandcell(CoreManager core) + { + try + { + return (uint)core.Actions.Landcell; + } + catch + { + return 0; + } + } + + /// <summary> + /// Determines the attack type based on combat mode and wielded weapon. + /// Magic mode ALWAYS returns Linear (spells travel straight). + /// Bows get a flat arc (high velocity). Thrown weapons arc more. + /// Melee and crossbows are Linear. + /// </summary> + public AttackType DetermineAttackType(CoreManager core) + { + try + { + // MAGIC MODE: Always linear — spells (bolts, streaks, arcs, rings) + // all use straight-line LOS in AC, regardless of equipped weapon + if (core.Actions.CombatMode == CombatState.Magic) + return AttackType.Linear; + + // PEACE MODE: Default to linear + if (core.Actions.CombatMode == CombatState.Peace) + return AttackType.Linear; + + // MELEE MODE: Linear (range check only, no projectile arc) + if (core.Actions.CombatMode == CombatState.Melee) + return AttackType.Linear; + + // MISSILE MODE: Check the actual weapon for bow vs crossbow vs thrown + foreach (var wo in core.WorldFilter.GetInventory()) + { + if (wo.Values((LongValueKey)10, 0) > 0) // CurrentWieldedLocation + { + if (wo.ObjectClass == ObjectClass.MissileWeapon) + { + string name = wo.Name?.ToLower() ?? ""; + + // Crossbows fire bolts in a straight line + if (name.Contains("crossbow")) + return AttackType.Linear; + + // Atlatls and thrown weapons arc more + if (name.Contains("atlatl") || name.Contains("thrown") || name.Contains("dart")) + return UseArcs ? AttackType.ThrownArc : AttackType.Linear; + + // Regular bows — fast, flat arc + if (name.Contains("bow")) + return UseArcs ? AttackType.BowArc : AttackType.Linear; + + // Unknown missile weapon — treat as bow arc + return UseArcs ? AttackType.BowArc : AttackType.Linear; + } + + // Wand in missile mode? Shouldn't happen, but treat as linear + if (wo.ObjectClass == ObjectClass.WandStaffOrb) + return AttackType.Linear; + } + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[Targeting] Error determining attack type: {ex.Message}"); + } + + return AttackType.Linear; // Default to linear + } + } +} diff --git a/Plugins/RynthAi/Raycasting/Vector3Helper.cs b/Plugins/RynthAi/Raycasting/Vector3Helper.cs new file mode 100644 index 0000000..40bfe81 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/Vector3Helper.cs @@ -0,0 +1,143 @@ +using System; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Custom Vector3 for the raycasting system. + /// + /// IMPORTANT: This replaces System.Numerics.Vector3 in the Raycasting namespace. + /// All Raycasting/*.cs files must NOT import System.Numerics to avoid type conflicts. + /// </summary> + public struct Vector3 + { + public float X { get; set; } + public float Y { get; set; } + public float Z { get; set; } + + public static readonly Vector3 Zero = new Vector3(0, 0, 0); + public static readonly Vector3 One = new Vector3(1, 1, 1); + public static readonly Vector3 Up = new Vector3(0, 0, 1); + + public Vector3(float x, float y, float z) + { + X = x; + Y = y; + Z = z; + } + + // --- Conversion --- + + public static Vector3 FromNumerics(System.Numerics.Vector3 v) + => new Vector3(v.X, v.Y, v.Z); + + public System.Numerics.Vector3 ToNumerics() + => new System.Numerics.Vector3(X, Y, Z); + + public float[] ToArray() + => new float[] { X, Y, Z }; + + public static Vector3 FromArray(float[] arr) + { + if (arr == null || arr.Length < 3) return Zero; + return new Vector3(arr[0], arr[1], arr[2]); + } + + // --- Arithmetic operators --- + + public static Vector3 operator +(Vector3 a, Vector3 b) + => new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z); + + public static Vector3 operator -(Vector3 a, Vector3 b) + => new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z); + + public static Vector3 operator -(Vector3 v) + => new Vector3(-v.X, -v.Y, -v.Z); + + public static Vector3 operator *(Vector3 v, float s) + => new Vector3(v.X * s, v.Y * s, v.Z * s); + + public static Vector3 operator *(float s, Vector3 v) + => new Vector3(v.X * s, v.Y * s, v.Z * s); + + public static Vector3 operator /(Vector3 v, float s) + { + float inv = 1.0f / s; + return new Vector3(v.X * inv, v.Y * inv, v.Z * inv); + } + + // --- Vector math --- + + public static float Dot(Vector3 a, Vector3 b) + => a.X * b.X + a.Y * b.Y + a.Z * b.Z; + + public static Vector3 Cross(Vector3 a, Vector3 b) + => new Vector3( + a.Y * b.Z - a.Z * b.Y, + a.Z * b.X - a.X * b.Z, + a.X * b.Y - a.Y * b.X + ); + + public float Length() + => (float)Math.Sqrt(X * X + Y * Y + Z * Z); + + public float LengthSquared() + => X * X + Y * Y + Z * Z; + + public Vector3 Normalize() + { + float len = Length(); + if (len < 1e-8f) return Zero; + return this * (1.0f / len); + } + + public float Distance(Vector3 other) + => (this - other).Length(); + + public static Vector3 Min(Vector3 a, Vector3 b) + => new Vector3(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Min(a.Z, b.Z)); + + public static Vector3 Max(Vector3 a, Vector3 b) + => new Vector3(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y), Math.Max(a.Z, b.Z)); + + public static Vector3 Lerp(Vector3 a, Vector3 b, float t) + => a + (b - a) * t; + + public float Length2D() + => (float)Math.Sqrt(X * X + Y * Y); + + // --- Equality --- + + public override bool Equals(object obj) + { + if (obj is Vector3 other) + return X == other.X && Y == other.Y && Z == other.Z; + return false; + } + + public override int GetHashCode() + => X.GetHashCode() ^ (Y.GetHashCode() << 8) ^ (Z.GetHashCode() << 16); + + public static bool operator ==(Vector3 a, Vector3 b) + => a.X == b.X && a.Y == b.Y && a.Z == b.Z; + + public static bool operator !=(Vector3 a, Vector3 b) + => !(a == b); + + public override string ToString() + => $"({X:F3}, {Y:F3}, {Z:F3})"; + + public float this[int i] + { + get + { + switch (i) + { + case 0: return X; + case 1: return Y; + case 2: return Z; + default: throw new IndexOutOfRangeException(); + } + } + } + } +} diff --git a/Plugins/RynthAi/RynthAi.csproj b/Plugins/RynthAi/RynthAi.csproj new file mode 100644 index 0000000..e7ee08f --- /dev/null +++ b/Plugins/RynthAi/RynthAi.csproj @@ -0,0 +1,174 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">x86</Platform> + <ProjectGuid>{AA060CDA-5478-4BFD-8CC3-B24827E19FC7}</ProjectGuid> + <OutputType>Library</OutputType> + <RootNamespace>NexSuite.Plugins.RynthAi</RootNamespace> + <AssemblyName>RynthAi</AssemblyName> + <TargetFrameworkVersion>v4.8</TargetFrameworkVersion> + <LangVersion>8.0</LangVersion> + <FileAlignment>512</FileAlignment> + <NuGetPackageImportStamp> + </NuGetPackageImportStamp> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'"> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <PlatformTarget>x86</PlatformTarget> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'"> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + </PropertyGroup> + <ItemGroup> + <Reference Include="Decal.Adapter"> + <HintPath>..\..\..\..\Program Files (x86)\Decal 3.0\Decal.Adapter.dll</HintPath> + <Private>False</Private> + </Reference> + <Reference Include="Decal.FileService"> + <HintPath>..\..\..\..\Program Files (x86)\Decal 3.0\Decal.FileService.dll</HintPath> + </Reference> + <Reference Include="Decal.Interop.D3DService, Version=2.9.8.3, Culture=neutral, PublicKeyToken=481f17d392f1fb65, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <EmbedInteropTypes>False</EmbedInteropTypes> + <HintPath>..\..\..\..\Program Files (x86)\Decal 3.0\.NET 4.0 PIA\Decal.Interop.D3DService.DLL</HintPath> + <Private>False</Private> + </Reference> + <Reference Include="KeraLua, Version=1.4.9.0, Culture=neutral, PublicKeyToken=6a194c04b9c89217, processorArchitecture=MSIL"> + <HintPath>..\..\packages\KeraLua.1.4.9\lib\net46\KeraLua.dll</HintPath> + </Reference> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> + <HintPath>..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll</HintPath> + </Reference> + <Reference Include="NLua, Version=1.7.8.0, Culture=neutral, PublicKeyToken=6a194c04b9c89217, processorArchitecture=MSIL"> + <HintPath>..\..\packages\NLua.1.7.8\lib\net46\NLua.dll</HintPath> + </Reference> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="System.Drawing" /> + <Reference Include="System.Numerics" /> + <Reference Include="System.Windows.Forms" /> + <Reference Include="System.Xml" /> + <Reference Include="System.Xml.Serialization" /> + <Reference Include="utank2-i"> + <HintPath>..\..\..\..\Games\VirindiPlugins\VirindiTank\utank2-i.dll</HintPath> + </Reference> + <Reference Include="UtilityBelt.Scripting"> + <HintPath>..\..\..\..\Games\DecalPlugins\UtilityBelt.Service\UtilityBelt.Scripting.dll</HintPath> + </Reference> + <Reference Include="UtilityBelt.Service"> + <HintPath>..\..\..\..\Games\DecalPlugins\UtilityBelt.Service\UtilityBelt.Service.dll</HintPath> + <Private>False</Private> + </Reference> + <Reference Include="VTClassic"> + <HintPath>..\..\..\..\Games\VirindiPlugins\VirindiTankClassicLooter\VTClassic.dll</HintPath> + </Reference> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\Shared\NexSuite.Shared.csproj"> + <Project>{11111111-1111-1111-1111-111111111111}</Project> + <Name>NexSuite.Shared</Name> + </ProjectReference> + <ProjectReference Include="..\..\Core\NexSuite.Core.csproj"> + <Project>{22222222-2222-2222-2222-222222222222}</Project> + <Name>NexSuite.Core</Name> + </ProjectReference> + </ItemGroup> + <ItemGroup> + <Compile Include="Combat\BuffManager.cs" /> + <Compile Include="Combat\SpellDatabase.cs" /> + <Compile Include="Combat\SpellManager.cs" /> + <Compile Include="DecalInspector.cs" /> + <Compile Include="Logic\BackgroundFpsUnlocker.cs" /> + <Compile Include="Logic\CommandProcessor.cs" /> + <Compile Include="Logic\RynthJumper.cs" /> + <Compile Include="Loot\LootManager.cs" /> + <Compile Include="Loot\VTankLootParser.cs" /> + <Compile Include="Lua\LuaBridge.cs" /> + <Compile Include="Lua\LuaManager.cs" /> + <Compile Include="Meta\MetaManager.cs" /> + <Compile Include="Meta\VTankMetaParser.cs" /> + <Compile Include="Nav\NavigationManager.cs" /> + <Compile Include="Nav\MovementActionHelper.cs" /> + <Compile Include="Nav\Tier2Log.cs" /> + <Compile Include="Nav\Tier2MovementHelper.cs" /> + <Compile Include="Nav\VTankNavParser.cs" /> + <Compile Include="Combat\CombatManager.cs" /> + <Compile Include="Combat\MissileCraftingManager.cs" /> + <Compile Include="Combat\CombatActionHelper.cs" /> + <Compile Include="Combat\FellowshipTracker.cs" /> + <Compile Include="PluginCore.cs" /> + <Compile Include="Raycasting\DatDatabase.cs" /> + <Compile Include="Raycasting\DungeonLOS.cs" /> + <Compile Include="Raycasting\LandblockStructs.cs" /> + <Compile Include="Raycasting\ScatterSystem.cs" /> + <Compile Include="Raycasting\Vector3Helper.cs" /> + <Compile Include="UI\AdvancedSettingsUI.cs" /> + <Compile Include="UI\LuaUI.cs" /> + <Compile Include="UI\MetaUI.cs" /> + <Compile Include="UI\MonstersUI.cs" /> + <Compile Include="UI\RynthAiUI.cs"> + <SubType>Form</SubType> + </Compile> + <Compile Include="UI\RynthAiUI.Rendering.cs" /> + <Compile Include="Raycasting\RaycastEngine.cs" /> + <Compile Include="Raycasting\BoundingVolume.cs" /> + <Compile Include="Raycasting\TargetingFSM.cs" /> + <Compile Include="Raycasting\BlacklistManager.cs" /> + <Compile Include="Raycasting\GeometryLoader.cs" /> + <Compile Include="Raycasting\MainLogic.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="UI\RouteUI.cs" /> + <Compile Include="UI\UISettings.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="app.config" /> + <None Include="packages.config" /> + </ItemGroup> + <ItemGroup> + <EmbeddedResource Include="Combat\Vtank spelldump.txt" /> + </ItemGroup> + <ItemGroup> + <COMReference Include="Decal"> + <Guid>{FF7F5F6D-34E0-4B6F-B3BB-8141DE2EF732}</Guid> + <VersionMajor>2</VersionMajor> + <VersionMinor>0</VersionMinor> + <Lcid>0</Lcid> + <WrapperTool>primary</WrapperTool> + <Isolated>False</Isolated> + <EmbedInteropTypes>True</EmbedInteropTypes> + </COMReference> + <COMReference Include="DecalNet"> + <Guid>{572B87C4-93BD-46B3-A291-CD58181D25DC}</Guid> + <VersionMajor>2</VersionMajor> + <VersionMinor>0</VersionMinor> + <Lcid>0</Lcid> + <WrapperTool>primary</WrapperTool> + <Isolated>False</Isolated> + <EmbedInteropTypes>True</EmbedInteropTypes> + </COMReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets" Condition="Exists('..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets')" /> + <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets'))" /> + </Target> +</Project> \ No newline at end of file diff --git a/Plugins/RynthAi/UI/AdvancedSettingsUI.cs b/Plugins/RynthAi/UI/AdvancedSettingsUI.cs new file mode 100644 index 0000000..fead046 --- /dev/null +++ b/Plugins/RynthAi/UI/AdvancedSettingsUI.cs @@ -0,0 +1,483 @@ +using System; +using System.Numerics; +using ImGuiNET; + +namespace NexSuite.Plugins.RynthAi +{ + public class AdvancedSettingsUI + { + private readonly UISettings _settings; + private MissileCraftingManager _missileCraftingManager; + public Action OnSettingsChanged; + + 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)" }; + + public AdvancedSettingsUI(UISettings settings) + { + _settings = settings; + } + + public void SetMissileCraftingManager(MissileCraftingManager mgr) + { + _missileCraftingManager = mgr; + } + + public void Render() + { + if (!_settings.ShowAdvancedWindow) return; + + // Set a default size for the popup window + ImGui.SetNextWindowSize(new Vector2(600, 400), ImGuiCond.FirstUseEver); + + if (ImGui.Begin("RynthAi Advanced Settings", ref _settings.ShowAdvancedWindow)) + { + // --- LEFT COLUMN (Sidebar) --- + ImGui.BeginChild("AdvancedSidebar", new Vector2(150, 0), true); + for (int i = 0; i < _settings.AdvancedTabs.Length; i++) + { + if (ImGui.Selectable(_settings.AdvancedTabs[i], _settings.SelectedAdvancedTab == i)) + { + _settings.SelectedAdvancedTab = i; + } + } + ImGui.EndChild(); + + ImGui.SameLine(); + + // --- RIGHT COLUMN (Content) --- + ImGui.BeginGroup(); + ImGui.BeginChild("AdvancedContent", new Vector2(0, -ImGui.GetFrameHeightWithSpacing()), true); + + RenderTabContent(_settings.SelectedAdvancedTab); + + ImGui.EndChild(); + + // Bottom Buttons + if (ImGui.Button("Close")) _settings.ShowAdvancedWindow = false; + ImGui.EndGroup(); + } + ImGui.End(); + } + + private void RenderTabContent(int tabIndex) + { + if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length) return; + + string tabName = _settings.AdvancedTabs[tabIndex]; + ImGui.TextColored(new System.Numerics.Vector4(0.4f, 0.7f, 1.0f, 1.0f), $"Advanced Settings > {tabName}"); + ImGui.Separator(); + ImGui.Spacing(); + + // Note: Ensure your AdvancedSettingsUI class has an 'Action OnSettingsChanged' + // property that you set in the RynthAiUI constructor to handle auto-saving. + + switch (tabName) + { + case "Misc": + // --- FPS THROTTLING --- + if (ImGui.Checkbox("Enable FPS Limit", ref _settings.EnableFPSLimit)) OnSettingsChanged?.Invoke(); + if (_settings.EnableFPSLimit) + { + ImGui.Indent(); + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Focused FPS", ref _settings.TargetFPSFocused, 10, 240)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Background FPS", ref _settings.TargetFPSBackground, 5, 60)) OnSettingsChanged?.Invoke(); + ImGui.Unindent(); + } + + ImGui.Separator(); + ImGui.Spacing(); + + // --- INVENTORY MANAGEMENT --- + // Uses EnableAutocram from UISettings + if (ImGui.Checkbox("Auto Cram", ref _settings.EnableAutocram)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("Automatically moves items from your main pack into side packs.\n" + + "Note: Recently used weapons will stay in the main pack for quick access."); + } + + ImGui.Spacing(); + + // --- GENERAL BEHAVIOR --- + if (ImGui.Checkbox("Peace Mode When Idle", ref _settings.PeaceModeWhenIdle)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Enable Raycasting", ref _settings.EnableRaycasting)) OnSettingsChanged?.Invoke(); + + ImGui.Separator(); + ImGui.Spacing(); + + // --- COMBAT BLACKLIST --- + ImGui.Text("Monster Blacklist"); + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Attempts Before Blacklist", ref _settings.BlacklistAttempts, 1, 20)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("How many failed attack attempts on a mob before it gets blacklisted.\n" + + "Helps avoid getting stuck on mobs clipped into walls or geometry."); + } + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Blacklist Timeout (sec)", ref _settings.BlacklistTimeoutSec, 5, 120)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("How long (seconds) a blacklisted mob is ignored before re-trying."); + } + break; + + case "Recharge": + ImGui.Text("Self Vitals (%)"); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Heal At", ref _settings.HealAt, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Re-stam At", ref _settings.RestamAt, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Get Mana At", ref _settings.GetManaAt, 0, 100)) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Top-Off Vitals (%)"); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Top HP", ref _settings.TopOffHP, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Top Stam", ref _settings.TopOffStam, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Top Mana", ref _settings.TopOffMana, 0, 100)) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Helper Settings (%)"); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Heal Others", ref _settings.HealOthersAt, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Re-stam Others", ref _settings.RestamOthersAt, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Infuse Others", ref _settings.InfuseOthersAt, 0, 100)) OnSettingsChanged?.Invoke(); + break; + + case "Melee Combat": + ImGui.Text("Attack Power & Height"); + ImGui.Separator(); + + // --- USE RECKLESSNESS --- + if (ImGui.Checkbox("Use Recklessness", ref _settings.UseRecklessness)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("When enabled and Recklessness is trained,\nauto power is set to 80% instead of 100%.\nThis activates the Recklessness damage bonus."); + + ImGui.Spacing(); + + // --- MELEE ATTACK POWER --- + bool meleeAuto = _settings.MeleeAttackPower < 0; + if (ImGui.Checkbox("Melee Auto Power", ref meleeAuto)) + { + _settings.MeleeAttackPower = meleeAuto ? -1 : 100; + OnSettingsChanged?.Invoke(); + } + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Auto = 100%, or 80% if Use Recklessness is on."); + if (!meleeAuto) + { + ImGui.Indent(); + int mPwr = _settings.MeleeAttackPower; + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Melee Power %", ref mPwr, 0, 100)) + { + _settings.MeleeAttackPower = mPwr; + OnSettingsChanged?.Invoke(); + } + ImGui.Unindent(); + } + + // --- MELEE ATTACK HEIGHT --- + ImGui.SetNextItemWidth(120); + if (ImGui.Combo("Melee Attack Height", ref _settings.MeleeAttackHeight, _attackHeights, _attackHeights.Length)) + OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Low = Delete, Medium = End, High = Page Down"); + + ImGui.Spacing(); + + // --- MISSILE ATTACK POWER --- + bool missileAuto = _settings.MissileAttackPower < 0; + if (ImGui.Checkbox("Missile Auto Power", ref missileAuto)) + { + _settings.MissileAttackPower = missileAuto ? -1 : 100; + OnSettingsChanged?.Invoke(); + } + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Auto = 100%, or 80% if Use Recklessness is on."); + if (!missileAuto) + { + ImGui.Indent(); + int rPwr = _settings.MissileAttackPower; + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Missile Power %", ref rPwr, 0, 100)) + { + _settings.MissileAttackPower = rPwr; + OnSettingsChanged?.Invoke(); + } + ImGui.Unindent(); + } + + // --- MISSILE ATTACK HEIGHT --- + ImGui.SetNextItemWidth(120); + if (ImGui.Combo("Missile Attack Height", ref _settings.MissileAttackHeight, _attackHeights, _attackHeights.Length)) + OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Low = Delete, Medium = End, High = Page Down"); + + ImGui.Separator(); + ImGui.Spacing(); + + // You can add weapon-specific toggles here later + if (ImGui.Checkbox("Summon Pets", ref _settings.SummonPets)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Pet Min Monsters", ref _settings.PetMinMonsters)) OnSettingsChanged?.Invoke(); + break; + + case "Spell Combat": + ImGui.Text("War/Void Casting Settings"); + ImGui.Separator(); + if (ImGui.Checkbox("Cast Dispel Self", ref _settings.CastDispelSelf)) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Ring Spell Override"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Min Ring Targets", ref _settings.MinRingTargets)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("If this many monsters are within Ring Range,\nring spells are used instead of arc/bolt/streak.\nSet to 0 to disable the override.\nDefault: 4"); + } + break; + + case "Ranges": + ImGui.Text("Standard Ranges (Yards)"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Monster Range", ref _settings.MonsterRange)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("Detection range in yards. Same units as VTank.\n" + + "Max bow range ≈ 70 yards. Magic ≈ 68 yards.\n" + + "AC internal = yards / 240"); + } + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Ring Range", ref _settings.RingRange)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("Distance at which Ring spells are used instead of other shapes."); + } + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Approach Range", ref _settings.ApproachRange)) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Corpse Acquisition (AC Units)"); + ImGui.Separator(); + // MOVED FROM MAIN TAB + ImGui.SetNextItemWidth(180); + if (ImGui.InputDouble("Corpse Max", ref _settings.CorpseApproachRangeMax, 0.005, 0.01, "%.6f")) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(180); + if (ImGui.InputDouble("Corpse Min", ref _settings.CorpseApproachRangeMin, 0.005, 0.01, "%.6f")) OnSettingsChanged?.Invoke(); + break; + + case "Navigation": + if (ImGui.Checkbox("Boost Nav Priority", ref _settings.BoostNavPriority)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputFloat("Follow/Nav Min", ref _settings.FollowNavMin, 0.1f, 1.0f, "%.1f")) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Movement Engine"); + ImGui.SetNextItemWidth(200); + if (ImGui.Combo("Mode", ref _settings.MovementMode, _movementModes, _movementModes.Length)) + OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip( + "Legacy: SetAutorun + TurnLeft/TurnRight (VTank-style)\n" + + "Tier 1: Direct CM_Movement server events\n" + + "Tier 2: Client physics MoveToPosition (smooth arcs, experimental)"); + if (_settings.MovementMode == 2 && !Tier2MovementHelper.IsInitialized) + { + ImGui.SameLine(); + ImGui.TextColored(new Vector4(1, 0.4f, 0.4f, 1), "(not initialized)"); + } + + // ── Steering (all modes) ───────────────────────────────── + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Text("Steering"); + + ImGui.SetNextItemWidth(80); + if (ImGui.InputFloat("Stop & Turn Angle", ref _settings.NavStopTurnAngle, 1f, 5f, "%.0f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Stop forward motion and turn in place when heading error exceeds this many degrees.\nLower = more precise but stop-start. Higher = wider arcs."); + + ImGui.SetNextItemWidth(80); + if (ImGui.InputFloat("Resume Run Angle", ref _settings.NavResumeTurnAngle, 1f, 5f, "%.0f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Resume running once the turn-in-place error drops below this.\nMust be less than Stop & Turn Angle."); + + ImGui.SetNextItemWidth(80); + if (ImGui.InputFloat("Dead Zone", ref _settings.NavDeadZone, 0.5f, 1f, "%.1f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Ignore heading corrections smaller than this.\nSmaller = tighter line but more twitchy. Larger = smoother but wider path."); + + ImGui.SetNextItemWidth(80); + if (ImGui.InputFloat("Sweep Detect Mult", ref _settings.NavSweepMult, 0.5f, 1f, "%.1f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Closest-approach detection radius = Arrival Radius * this.\nIf distance was decreasing and starts increasing within this radius, advance to next waypoint.\nHigher = more forgiving on tight turns. Lower = must pass closer."); + + // ── Tier 2 tuning (only visible when mode 2 selected) ──── + if (_settings.MovementMode == 2) + { + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Text("Tier 2 Tuning"); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputFloat("Speed##t2", ref _settings.T2Speed, 0.1f, 0.5f, "%.1f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Movement speed multiplier (1.0 = normal run speed)"); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputFloat("Walk Within (yd)", ref _settings.T2WalkWithinYd, 1f, 5f, "%.0f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Switch from run to walk when within this many yards of the waypoint.\n0 = always run."); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputFloat("Stop Distance (yd)", ref _settings.T2DistanceTo, 0.1f, 0.5f, "%.1f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Stop this far from the target position (yards)"); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputFloat("Reissue Timeout (ms)", ref _settings.T2ReissueMs, 100f, 500f, "%.0f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-send MoveToPosition if no progress after this many ms"); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputFloat("Max Range (yd)", ref _settings.T2MaxRangeYd, 50f, 100f, "%.0f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Clamp waypoint distance to this. Will re-issue as you get closer."); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputInt("Max Landblock Dist", ref _settings.T2MaxLandblocks, 1)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Skip MoveToPosition if target is more than N landblocks away"); + } + break; + + case "Buffing": + if (ImGui.Checkbox("Enable Buffing", ref _settings.EnableBuffing)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Rebuff When Idle", ref _settings.RebuffWhenIdle)) OnSettingsChanged?.Invoke(); + break; + + case "Looting": + if (ImGui.Checkbox("Enable Looting", ref _settings.EnableLooting)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Boost Loot Priority", ref _settings.BoostLootPriority)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Loot Only Rare Corpses", ref _settings.LootOnlyRareCorpses)) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Corpse Ownership"); + ImGui.SetNextItemWidth(180); + if (ImGui.Combo("Loot From", ref _settings.LootOwnership, _lootOwnershipModes, _lootOwnershipModes.Length)) + OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("My Kills Only: Only loot corpses you killed.\nFellowship Kills: Loot kills by any fellowship member.\nAll Corpses: Loot everything within range."); + + ImGui.Spacing(); + ImGui.Text("Inventory Management"); + if (ImGui.Checkbox("Enable Autostack", ref _settings.EnableAutostack)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Enable Autocram", ref _settings.EnableAutocram)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Combine Salvage Bags", ref _settings.EnableCombineSalvage)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("When enabled, salvage bags of the same material type\nare automatically combined after salvaging."); + } + + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Text("Loot Timers (ms)"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Inter-Item Delay", ref _settings.LootInterItemDelayMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Delay between picking up each item from a corpse."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Content Settle", ref _settings.LootContentSettleMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Wait for corpse contents to populate after opening."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Empty Corpse Wait", ref _settings.LootEmptyCorpseMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("How long to wait before declaring a corpse empty."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Closing Delay", ref _settings.LootClosingDelayMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Delay before closing corpse after all items looted."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Assess Window", ref _settings.LootAssessWindowMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Max time to wait for item ID data from server."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Loot Retry Timeout", ref _settings.LootRetryTimeoutMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Retry picking up an item after this many ms."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Corpse Open Retry", ref _settings.LootOpenRetryMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("If corpse doesn't open, retry UseItem after this many ms.\nLower = faster but may toggle-close an already-opening corpse."); + + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Text("Salvage Timers (ms) — First / Fast"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Open (First)", ref _settings.SalvageOpenDelayFirstMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Open (Fast)", ref _settings.SalvageOpenDelayFastMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Add Item (First)", ref _settings.SalvageAddDelayFirstMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Add Item (Fast)", ref _settings.SalvageAddDelayFastMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Salvage Click", ref _settings.SalvageSalvageDelayMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Result (First)", ref _settings.SalvageResultDelayFirstMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Result (Fast)", ref _settings.SalvageResultDelayFastMs)) OnSettingsChanged?.Invoke(); + break; + + case "Crafting": + ImGui.Text("Missile Ammo Crafting"); + ImGui.Separator(); + ImGui.Spacing(); + + if (ImGui.Checkbox("Enable Missile Crafting", ref _settings.EnableMissileCrafting)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Auto-manage missile ammo when the ammo slot is empty:\n\n1. If better ammo can be crafted from bundles → craft it\n2. Otherwise equip the best loose ammo in inventory\n3. If no ammo exists → craft from bundles, then equip\n\nRequires Fletching skill (Trained or Specialized).\nEach combine: 1 head bundle + 1 shaft bundle = 1000 ammo."); + + if (!_settings.EnableMissileCrafting) { ImGui.TextDisabled("(Disabled)"); break; } + + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Spacing(); + + if (_missileCraftingManager != null) + { + string stateLabel = _missileCraftingManager.State.ToString(); + Vector4 stateColor = _missileCraftingManager.IsCrafting + ? new Vector4(0.2f, 1.0f, 0.4f, 1.0f) + : new Vector4(0.6f, 0.6f, 0.6f, 1.0f); + + ImGui.TextColored(stateColor, "State: " + stateLabel); + + if (!string.IsNullOrEmpty(_missileCraftingManager.StatusMessage)) + ImGui.TextWrapped(_missileCraftingManager.StatusMessage); + } + else + { + ImGui.TextDisabled("Crafting manager not initialized."); + } + + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Spacing(); + + ImGui.TextDisabled("Ammo Types (by priority, highest first):"); + ImGui.BulletText("Lethal Prismatic (Specialized)"); + ImGui.BulletText("Deadly Prismatic (Specialized)"); + ImGui.BulletText("Greater Prismatic (Trained)"); + ImGui.BulletText("Prismatic (Trained)"); + ImGui.BulletText("Armor Piercing, Broad, Blunt, etc. (Trained)"); + ImGui.Spacing(); + ImGui.TextDisabled("Weapon → Ammo:"); + ImGui.BulletText("Bow → Arrows (arrowheads + arrowshafts)"); + ImGui.BulletText("Crossbow → Quarrels (quarrelheads + quarrelshafts)"); + ImGui.BulletText("Atlatl → Darts (dart heads + dart shafts)"); + break; + + default: + ImGui.Text($"Settings for {tabName} are currently under development."); + break; + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/LuaUI.cs b/Plugins/RynthAi/UI/LuaUI.cs new file mode 100644 index 0000000..ed34586 --- /dev/null +++ b/Plugins/RynthAi/UI/LuaUI.cs @@ -0,0 +1,157 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public class LuaUI + { + private readonly UISettings _settings; + private readonly Decal.Adapter.CoreManager _core; + + // Delegates for PluginCore to hook into + public Action OnSettingsChanged; + public Action<string> OnExecuteRequested; + public Action OnStopRequested; + + // Internal State + private string _luaFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\LuaScripts"; + private string _newLuaFileName = "MyScript"; + private int _selectedLuaIdx = 0; + public List<string> LuaFiles = new List<string>(); + + private string _selectedSnippetKey = "--- Select Snippet ---"; + private Dictionary<string, string> _luaSnippets = new Dictionary<string, string> + { + { "--- Select Snippet ---", "" }, + { "📍 Move to Coord", "RynthAi:GoTo(\"0.0N\", \"0.0E\")" }, + { "🌀 Use Portal/NPC", "RynthAi:UsePortal(\"Portal Name\")" }, + { "📏 Get Distance", "local dist = RynthAi:GetDistance(\"Object Name\")\nprint(\"Distance: \" .. dist)" }, + { "🛑 Emergency Stop", "RynthAi:Stop()" } + }; + + public LuaUI(UISettings settings, Decal.Adapter.CoreManager core) + { + _settings = settings; + _core = core; + RefreshLuaFiles(); + } + + public void RefreshLuaFiles() + { + LuaFiles.Clear(); + LuaFiles.Add("None"); + if (Directory.Exists(_luaFolder)) + { + foreach (var file in Directory.GetFiles(_luaFolder, "*.lua")) + LuaFiles.Add(Path.GetFileNameWithoutExtension(file)); + } + } + + public void Render() + { + // Safety Checks + if (_settings.LuaScript == null) _settings.LuaScript = ""; + if (_settings.LuaConsoleOutput == null) _settings.LuaConsoleOutput = ""; + + // 1. File & Snippet Bar + RenderTopBar(); + + ImGui.Separator(); + + // 2. Toolbar (Run, Stop, Clear) + RenderToolbar(); + + ImGui.Separator(); + + // 3. Editor & Console + RenderEditorAndConsole(); + } + + private void RenderTopBar() + { + ImGui.SetNextItemWidth(120); + string preview = (_selectedLuaIdx < LuaFiles.Count) ? LuaFiles[_selectedLuaIdx] : "None"; + if (ImGui.BeginCombo("##LoadLua", preview)) + { + for (int i = 0; i < LuaFiles.Count; i++) + { + if (ImGui.Selectable(LuaFiles[i], _selectedLuaIdx == i)) + { + _selectedLuaIdx = i; + if (LuaFiles[i] != "None") + { + string path = Path.Combine(_luaFolder, LuaFiles[i] + ".lua"); + if (File.Exists(path)) { _settings.LuaScript = File.ReadAllText(path); OnSettingsChanged?.Invoke(); } + } + } + } + ImGui.EndCombo(); + } + + ImGui.SameLine(); + if (ImGui.Button("🔄")) RefreshLuaFiles(); + + ImGui.SameLine(); + ImGui.SetNextItemWidth(120); + ImGui.InputText("##SaveAs", ref _newLuaFileName, 64); + + ImGui.SameLine(); + if (ImGui.Button("💾")) + { + if (!Directory.Exists(_luaFolder)) Directory.CreateDirectory(_luaFolder); + File.WriteAllText(Path.Combine(_luaFolder, _newLuaFileName + ".lua"), _settings.LuaScript); + RefreshLuaFiles(); + } + + ImGui.SameLine(); + RenderSnippets(); + } + + private void RenderSnippets() + { + ImGui.SetNextItemWidth(150); + if (ImGui.BeginCombo("##Snippets", _selectedSnippetKey)) + { + foreach (var s in _luaSnippets) + { + if (ImGui.Selectable(s.Key)) + { + if (!string.IsNullOrEmpty(_settings.LuaScript) && !_settings.LuaScript.EndsWith("\n")) _settings.LuaScript += "\n"; + _settings.LuaScript += s.Value; + OnSettingsChanged?.Invoke(); + } + } + ImGui.EndCombo(); + } + } + + private void RenderToolbar() + { + if (ImGui.Button("▶ Run Script")) OnExecuteRequested?.Invoke(_settings.LuaScript); + ImGui.SameLine(); + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.7f, 0.1f, 0.1f, 1.0f)); + if (ImGui.Button("🛑 Stop")) OnStopRequested?.Invoke(); + ImGui.PopStyleColor(); + ImGui.SameLine(); + if (ImGui.Button("🧹 Clear Console")) { _settings.LuaConsoleOutput = "--- Console Cleared ---"; OnSettingsChanged?.Invoke(); } + } + + private void RenderEditorAndConsole() + { + float editorH = ImGui.GetContentRegionAvail().Y - 150; + ImGui.InputTextMultiline("##LuaEditor", ref _settings.LuaScript, 50000, new Vector2(-1, editorH), ImGuiInputTextFlags.AllowTabInput); + + ImGui.TextDisabled("Console Output:"); + if (ImGui.BeginChild("LuaConsole", new Vector2(-1, 0), true, ImGuiWindowFlags.HorizontalScrollbar)) + { + ImGui.TextUnformatted(_settings.LuaConsoleOutput); + if (ImGui.GetScrollY() >= ImGui.GetScrollMaxY()) ImGui.SetScrollHereY(1.0f); + } + ImGui.EndChild(); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/MetaUI.cs b/Plugins/RynthAi/UI/MetaUI.cs new file mode 100644 index 0000000..d1937d2 --- /dev/null +++ b/Plugins/RynthAi/UI/MetaUI.cs @@ -0,0 +1,650 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Linq; +using ImGuiNET; +using RynthAi.Meta; + +namespace NexSuite.Plugins.RynthAi +{ + public class MetaUI + { + private readonly UISettings _settings; + private readonly List<string> _navFiles; // Passed in so we can embed routes + + public Action OnSettingsChanged; + public Action OnMetaRulesUpdated; + + // --- META STATE --- + private bool _showMetaEditor = false; + private MetaRule _editingRule = new MetaRule(); + private int _editingRuleIndex = -1; + private string _newStateName = ""; + + // --- META DICTIONARIES --- + private readonly string[] _metaConditionNames = { + "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 Distance", "Monster Priority Count Within Distance", + "Need To Buff", "No Monsters Within Distance", "Landblock ==", + "Landcell ==", "Portalspace Entered", "Portalspace Exited", "Not", + "Seconds in State (P) >=", "Time Left On Spell >=", "Time Left On Spell <=", + "Burden Percentage >=", "Dist Any Route PT >=", "Expression", + "Chat Message Capture", "Navroute Empty" + }; + + private readonly string[] _metaActionNames = { + "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 NT Option", "Set NT Option", + "Create View", "Destroy View", "Destroy All Views" + }; + + public MetaUI(UISettings settings, List<string> navFiles) + { + _settings = settings; + _navFiles = navFiles; + } + + public void Render() + { + if (ImGui.BeginTable("MetaRulesTable", 6, ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, new Vector2(0, -35))) + { + ImGui.TableSetupColumn("Up", ImGuiTableColumnFlags.WidthFixed, 20); + ImGui.TableSetupColumn("Dn", ImGuiTableColumnFlags.WidthFixed, 20); + ImGui.TableSetupColumn("Del", ImGuiTableColumnFlags.WidthFixed, 25); + ImGui.TableSetupColumn("State", ImGuiTableColumnFlags.WidthFixed, 100); + ImGui.TableSetupColumn("Condition", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Action", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableHeadersRow(); + + var groupedRules = _settings.MetaRules + .GroupBy(r => r.State) + .OrderBy(g => g.Key) + .ToList(); + + foreach (var group in groupedRules) + { + ImGui.TableNextRow(); + ImGui.TableSetColumnIndex(3); + ImGui.TextColored(new Vector4(0, 1, 1, 1), $"--- State: {group.Key} ---"); + + var stateRules = group.ToList(); + for (int i = 0; i < stateRules.Count; i++) + { + var rule = stateRules[i]; + int globalIdx = _settings.MetaRules.IndexOf(rule); + + ImGui.TableNextRow(); + + bool isFired = rule.HasFired; + if (isFired) ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1f, 0.2f, 0.2f, 1f)); + + ImGui.TableNextColumn(); + if (i > 0 && ImGui.Button($"^##up{globalIdx}")) + { + var prevRule = stateRules[i - 1]; + int prevGlobalIdx = _settings.MetaRules.IndexOf(prevRule); + _settings.MetaRules[globalIdx] = prevRule; + _settings.MetaRules[prevGlobalIdx] = rule; + OnSettingsChanged?.Invoke(); + } + + ImGui.TableNextColumn(); + if (i < stateRules.Count - 1 && ImGui.Button($"v##dn{globalIdx}")) + { + var nextRule = stateRules[i + 1]; + int nextGlobalIdx = _settings.MetaRules.IndexOf(nextRule); + _settings.MetaRules[globalIdx] = nextRule; + _settings.MetaRules[nextGlobalIdx] = rule; + OnSettingsChanged?.Invoke(); + } + + ImGui.TableNextColumn(); + ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1, 0, 0, 1)); + if (ImGui.Button($"X##delm{globalIdx}")) { _settings.MetaRules.Remove(rule); OnSettingsChanged?.Invoke(); } + ImGui.PopStyleColor(); + + ImGui.TableNextColumn(); + if (ImGui.Selectable($"{rule.State}##edit{globalIdx}", false, ImGuiSelectableFlags.SpanAllColumns)) + { + _editingRule = new MetaRule { State = rule.State, Condition = rule.Condition, ConditionData = rule.ConditionData, Action = rule.Action, ActionData = rule.ActionData }; + if (rule.Children != null) + { + string json = Newtonsoft.Json.JsonConvert.SerializeObject(rule.Children); + _editingRule.Children = Newtonsoft.Json.JsonConvert.DeserializeObject<List<MetaRule>>(json); + } + _editingRuleIndex = globalIdx; + _showMetaEditor = true; + } + + ImGui.TableNextColumn(); + ImGui.Text(rule.Condition.ToString() + (string.IsNullOrEmpty(rule.ConditionData) ? "" : $": {rule.ConditionData}")); + + ImGui.TableNextColumn(); + if (rule.Action == MetaActionType.All) + { + int childCount = rule.Children?.Count ?? 0; + ImGui.TextColored(new Vector4(1, 1, 0, 1), $"All: [{childCount} actions]"); + } + else if (rule.Action == MetaActionType.EmbeddedNavRoute && !string.IsNullOrEmpty(rule.ActionData) && rule.ActionData.Contains(";")) + { + var parts = rule.ActionData.Split(';'); + ImGui.Text($"EmbeddedNavRoute: {parts[0]} ({parts[1]} pts)"); + } + else + { + ImGui.Text(rule.Action.ToString() + (string.IsNullOrEmpty(rule.ActionData) ? "" : $": {rule.ActionData}")); + } + + if (isFired) ImGui.PopStyleColor(); + } + } + ImGui.EndTable(); + } + + ImGui.Separator(); + + bool isMetaEnabled = _settings.EnableMeta; + if (ImGui.Checkbox("Enable Meta", ref isMetaEnabled)) + { + _settings.EnableMeta = isMetaEnabled; + OnSettingsChanged?.Invoke(); + } + + ImGui.SameLine(); + ImGui.Text("Current State:"); + ImGui.SameLine(); + + ImGui.SetNextItemWidth(150); + if (ImGui.BeginCombo("##CurrentStateDropdown", _settings.CurrentState)) + { + if (ImGui.Selectable("< Create New State >")) + { + ImGui.OpenPopup("CreateStatePopup"); + } + + ImGui.Separator(); + + var uniqueStates = _settings.MetaRules.Select(r => r.State).Distinct().ToList(); + if (!uniqueStates.Contains("Default")) uniqueStates.Insert(0, "Default"); + + foreach (var state in uniqueStates) + { + if (ImGui.Selectable(state, _settings.CurrentState == state)) + { + if (_settings.CurrentState == state) _settings.ForceStateReset = true; + _settings.CurrentState = state; + OnSettingsChanged?.Invoke(); + } + } + ImGui.EndCombo(); + } + + if (ImGui.BeginPopupModal("CreateStatePopup", ref _showMetaEditor, ImGuiWindowFlags.AlwaysAutoResize)) + { + ImGui.Text("Enter New State Name:"); + ImGui.InputText("##newStateIn", ref _newStateName, 64); + ImGui.Spacing(); + if (ImGui.Button("Create", new Vector2(120, 0))) + { + if (!string.IsNullOrWhiteSpace(_newStateName)) + { + _settings.CurrentState = _newStateName; + _newStateName = ""; + OnSettingsChanged?.Invoke(); + } + ImGui.CloseCurrentPopup(); + } + ImGui.SameLine(); + if (ImGui.Button("Cancel", new Vector2(120, 0))) { ImGui.CloseCurrentPopup(); } + ImGui.EndPopup(); + } + + ImGui.SameLine(ImGui.GetWindowWidth() - 100); + if (ImGui.Button("Create", new Vector2(80, 25))) + { + _editingRule = new MetaRule { State = _settings.CurrentState }; + _editingRuleIndex = -1; + _showMetaEditor = true; + } + + RenderMetaEditorPopup(); + } + + private void RenderMetaEditorPopup() + { + if (_showMetaEditor) ImGui.OpenPopup("Edit Meta Rule"); + + ImGui.SetNextWindowSize(new Vector2(650, 450), ImGuiCond.Appearing); + + if (ImGui.BeginPopupModal("Edit Meta Rule", ref _showMetaEditor, ImGuiWindowFlags.NoCollapse)) + { + float halfWidth = ImGui.GetContentRegionAvail().X / 2f - 4f; + + var uniqueStates = _settings.MetaRules.Select(r => r.State).Distinct().ToList(); + if (!uniqueStates.Contains("Default")) uniqueStates.Insert(0, "Default"); + + ImGui.BeginChild("ConditionPane", new Vector2(halfWidth, -35), true); + + ImGui.TextColored(new Vector4(0, 1, 1, 1), "Condition Type:"); + int condIdx = (int)_editingRule.Condition; + ImGui.SetNextItemWidth(-1); + if (ImGui.Combo("##CondCombo", ref condIdx, _metaConditionNames, _metaConditionNames.Length)) + { + _editingRule.Condition = (MetaConditionType)condIdx; + ClearConditionDataIfNeeded(_editingRule); + } + + ImGui.TextColored(new Vector4(0, 1, 1, 1), "State Name:"); + ImGui.SetNextItemWidth(-30f); + string tempState = _editingRule.State ?? ""; + if (ImGui.InputTextWithHint("##StateName", "State (e.g. Default)", ref tempState, 64)) + _editingRule.State = tempState; + + ImGui.SameLine(); + ImGui.SetNextItemWidth(-1); + if (ImGui.BeginCombo("##StatePicker", "", ImGuiComboFlags.NoPreview)) + { + foreach (var state in uniqueStates) + { + if (ImGui.Selectable(state)) _editingRule.State = state; + } + ImGui.EndCombo(); + } + + ImGui.Separator(); + RenderRuleConditionNode(_editingRule, "root_cond"); + ImGui.EndChild(); + + ImGui.SameLine(); + + ImGui.BeginChild("ActionPane", new Vector2(0, -35), true); + ImGui.TextColored(new Vector4(1, 1, 0, 1), "Action Type:"); + RenderRuleActionNode(_editingRule, "root_action"); + ImGui.EndChild(); + + ImGui.SetCursorPosY(ImGui.GetWindowHeight() - 30); + if (ImGui.Button(_editingRuleIndex == -1 ? "Add Rule" : "Save Rule", new Vector2(100, 25))) + { + if (_editingRuleIndex == -1) _settings.MetaRules.Add(_editingRule); + else _settings.MetaRules[_editingRuleIndex] = _editingRule; + + OnSettingsChanged?.Invoke(); + OnMetaRulesUpdated?.Invoke(); + + _showMetaEditor = false; + } + + ImGui.SameLine(); + if (ImGui.Button("Cancel", new Vector2(100, 25))) { _showMetaEditor = false; } + + ImGui.EndPopup(); + } + } + + private void RenderRuleConditionNode(MetaRule rule, string idContext) + { + ImGui.PushID(idContext); + + if (rule.Condition == MetaConditionType.Any || + rule.Condition == MetaConditionType.All || + rule.Condition == MetaConditionType.Not) + { + if (rule.Condition != MetaConditionType.Not || rule.Children.Count == 0) + { + if (ImGui.Button("+##add")) + { + rule.Children.Add(new MetaRule() { Condition = MetaConditionType.Always }); + } + ImGui.SameLine(); + } + + ImGui.TextColored(new Vector4(1, 1, 0, 1), $"{rule.Condition} Sub-Conditions"); + ImGui.Indent(15f); + + for (int i = 0; i < rule.Children.Count; i++) + { + var child = rule.Children[i]; + ImGui.PushID($"child_{i}"); + + int childCondIdx = (int)child.Condition; + ImGui.SetNextItemWidth(150); + if (ImGui.Combo("##Cond", ref childCondIdx, _metaConditionNames, _metaConditionNames.Length)) + { + child.Condition = (MetaConditionType)childCondIdx; + ClearConditionDataIfNeeded(child); + } + + ImGui.SameLine(); + float startX = ImGui.GetCursorPosX(); + float startY = ImGui.GetCursorPosY(); + ImGui.SameLine(ImGui.GetWindowWidth() - 35f); + + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.8f, 0.1f, 0.1f, 1f)); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(1f, 0.2f, 0.2f, 1f)); + bool deleteClicked = ImGui.Button("X"); + ImGui.PopStyleColor(2); + + ImGui.SetCursorPos(new Vector2(startX, startY)); + RenderRuleConditionNode(child, $"node_{i}"); + + if (deleteClicked) + { + rule.Children.RemoveAt(i); + i--; + } + + ImGui.Dummy(new Vector2(0, 2f)); + ImGui.PopID(); + } + + ImGui.Unindent(15f); + } + else + { + bool needsData = true; + string condHint = "Data..."; + + if (rule.Condition == MetaConditionType.InventoryItemCount_LE || + rule.Condition == MetaConditionType.InventoryItemCount_GE) + { + string[] parts = (rule.ConditionData ?? "").Split(','); + string itemName = parts[0]; + string itemCount = parts.Length > 1 ? parts[1] : "0"; + + ImGui.Text("Item Name:"); + ImGui.SetNextItemWidth(-1); + if (ImGui.InputText("##InvName", ref itemName, 64)) + rule.ConditionData = $"{itemName},{itemCount}"; + + ImGui.Text("Item Count:"); + ImGui.SetNextItemWidth(-1); + if (ImGui.InputText("##InvCount", ref itemCount, 16, ImGuiInputTextFlags.CharsDecimal)) + rule.ConditionData = $"{itemName},{itemCount}"; + + needsData = false; + } + else if (rule.Condition == MetaConditionType.TimeLeftOnSpell_GE || + rule.Condition == MetaConditionType.TimeLeftOnSpell_LE) + { + string[] parts = (rule.ConditionData ?? "").Split(','); + string spellId = parts[0]; + string seconds = parts.Length > 1 ? parts[1] : "0"; + + ImGui.Text("Spell ID:"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputText("##SpellId", ref spellId, 16, ImGuiInputTextFlags.CharsDecimal)) + rule.ConditionData = $"{spellId},{seconds}"; + + if (int.TryParse(spellId, out int id)) + { + string sName = SpellDatabase.GetSpellName(id); + if (!string.IsNullOrEmpty(sName)) + { + ImGui.SameLine(); + ImGui.TextColored(new Vector4(0, 1, 1, 1), $"({sName})"); + } + } + + ImGui.Text("Seconds Remaining:"); + ImGui.SetNextItemWidth(-1); + if (ImGui.InputText("##SpellTime", ref seconds, 16, ImGuiInputTextFlags.CharsDecimal)) + rule.ConditionData = $"{spellId},{seconds}"; + + needsData = false; + } + else + { + switch (rule.Condition) + { + case MetaConditionType.Never: + case MetaConditionType.Always: + case MetaConditionType.CharacterDeath: + case MetaConditionType.AnyVendorOpen: + case MetaConditionType.VendorClosed: + case MetaConditionType.NeedToBuff: + case MetaConditionType.NoMonstersWithinDistance: + case MetaConditionType.PortalspaceEntered: + case MetaConditionType.PortalspaceExited: + case MetaConditionType.NavrouteEmpty: + needsData = false; + break; + case MetaConditionType.ChatMessage: + case MetaConditionType.ChatMessageCapture: + condHint = "Regex pattern..."; + break; + case MetaConditionType.PackSlots_LE: + condHint = "Min slots (e.g. 5)"; + break; + case MetaConditionType.BurdenPercentage_GE: + condHint = "Percentage (e.g. 250)"; + break; + case MetaConditionType.SecondsInState_GE: + case MetaConditionType.SecondsInStateP_GE: + condHint = "Seconds (e.g. 10)"; + break; + } + } + + if (needsData) + { + float availableSpace = ImGui.GetWindowWidth() - ImGui.GetCursorPosX() - 40f; + ImGui.SetNextItemWidth(Math.Max(50f, availableSpace)); + + string cData = rule.ConditionData ?? ""; + if (ImGui.InputTextWithHint("##Data", condHint, ref cData, 256)) + rule.ConditionData = cData; + } + else + { + if (rule.Condition != MetaConditionType.InventoryItemCount_LE && + rule.Condition != MetaConditionType.InventoryItemCount_GE && + rule.Condition != MetaConditionType.TimeLeftOnSpell_GE && + rule.Condition != MetaConditionType.TimeLeftOnSpell_LE) + { + ImGui.TextDisabled("(No extra data)"); + } + } + } + + ImGui.PopID(); + } + + private void RenderRuleActionNode(MetaRule rule, string idContext) + { + ImGui.PushID(idContext); + + int actionIdx = (int)rule.Action; + ImGui.SetNextItemWidth(180); + if (ImGui.Combo("##ActionType", ref actionIdx, _metaActionNames, _metaActionNames.Length)) + { + rule.Action = (MetaActionType)actionIdx; + if (rule.Action == MetaActionType.All) rule.ActionData = ""; + else if (rule.Children != null) rule.Children.Clear(); + } + + ImGui.SameLine(); + + if (rule.Action == MetaActionType.All) + { + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.2f, 0.6f, 0.2f, 1f)); + if (ImGui.Button("+ Add Action")) + { + rule.Children.Add(new MetaRule { Action = MetaActionType.ChatCommand }); + } + ImGui.PopStyleColor(); + + ImGui.Indent(20f); + for (int i = 0; i < rule.Children.Count; i++) + { + var child = rule.Children[i]; + ImGui.PushID($"act_child_{i}"); + + if (ImGui.Button("X")) + { + rule.Children.RemoveAt(i); + i--; + } + else + { + ImGui.SameLine(); + RenderRuleActionNode(child, $"child_node_{i}"); + } + + ImGui.PopID(); + if (i < rule.Children.Count - 1) ImGui.Separator(); + } + ImGui.Unindent(20f); + } + else + { + switch (rule.Action) + { + case MetaActionType.ChatCommand: + string cmd = rule.ActionData ?? ""; + ImGui.SetNextItemWidth(-1); + if (ImGui.InputTextWithHint("##Cmd", "e.g. /tell {1} hello!", ref cmd, 256)) + rule.ActionData = cmd; + break; + + case MetaActionType.SetMetaState: + case MetaActionType.CallMetaState: + string state = rule.ActionData ?? ""; + ImGui.SetNextItemWidth(-1); + if (ImGui.InputTextWithHint("##State", "Target State Name...", ref state, 64)) + rule.ActionData = state; + break; + + case MetaActionType.EmbeddedNavRoute: + if (ImGui.BeginCombo("##NavSelect", string.IsNullOrEmpty(rule.ActionData) ? "Select Route..." : rule.ActionData)) + { + foreach (var navFile in _navFiles) + { + if (navFile == "None") continue; + if (ImGui.Selectable(navFile, rule.ActionData == navFile)) + rule.ActionData = navFile; + } + ImGui.EndCombo(); + } + break; + + case MetaActionType.SetWatchdog: + string[] wdParts = (rule.ActionData ?? "Default;10;60").Split(';'); + string wdState = wdParts[0]; + string wdMeters = wdParts.Length > 1 ? wdParts[1] : "10"; + string wdSeconds = wdParts.Length > 2 ? wdParts[2] : "60"; + + ImGui.Text("To State:"); + ImGui.SetNextItemWidth(-1); + + var wdStates = _settings.MetaRules.Select(r => r.State).Distinct().ToList(); + if (!wdStates.Contains("Default")) wdStates.Insert(0, "Default"); + if (!wdStates.Contains(wdState) && !string.IsNullOrEmpty(wdState)) wdStates.Add(wdState); + + if (ImGui.BeginCombo("##WDStateCombo", wdState)) + { + foreach (var s in wdStates) + { + if (ImGui.Selectable(s, wdState == s)) + { + wdState = s; + } + } + ImGui.EndCombo(); + } + ImGui.Spacing(); + + ImGui.Text("Meters in:"); + ImGui.SetNextItemWidth(-1); + ImGui.InputText("##WDMeters", ref wdMeters, 8, ImGuiInputTextFlags.CharsDecimal); + ImGui.Spacing(); + + ImGui.Text("Seconds:"); + ImGui.SetNextItemWidth(-1); + ImGui.InputText("##WDSecs", ref wdSeconds, 8, ImGuiInputTextFlags.CharsDecimal); + + rule.ActionData = $"{wdState};{wdMeters};{wdSeconds}"; + break; + + case MetaActionType.SetNTOption: + string[] ntParts = (rule.ActionData ?? "EnableBuffing;False").Split(';'); + string ntO = ntParts[0]; + string ntV = ntParts.Length > 1 ? ntParts[1] : "False"; + + ImGui.Text("Option:"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputText("##NTOpt", ref ntO, 64)) rule.ActionData = $"{ntO};{ntV}"; + + ImGui.SameLine(); + ImGui.Text("Val:"); + ImGui.SetNextItemWidth(-1); + if (ImGui.InputText("##NTVal", ref ntV, 64)) rule.ActionData = $"{ntO};{ntV}"; + break; + + case MetaActionType.ExpressionAction: + case MetaActionType.ChatExpression: + string expr = rule.ActionData ?? ""; + ImGui.SetNextItemWidth(-1); + if (ImGui.InputTextWithHint("##Expr", "Expression (e.g. [SlotCount] < 5)", ref expr, 256)) + rule.ActionData = expr; + break; + + case MetaActionType.GetNTOption: + case MetaActionType.CreateView: + case MetaActionType.DestroyView: + string vData = rule.ActionData ?? ""; + ImGui.SetNextItemWidth(-1); + if (ImGui.InputText("##ViewData", ref vData, 128)) + rule.ActionData = vData; + break; + + case MetaActionType.ReturnFromCall: + case MetaActionType.ClearWatchdog: + case MetaActionType.DestroyAllViews: + ImGui.TextDisabled("(No extra data required)"); + break; + + case MetaActionType.None: + ImGui.TextDisabled("(Select an action type)"); + break; + } + } + + ImGui.PopID(); + } + + // ── Floating window wrapper (called from dashboard) ────────────────── + public void RenderAsWindow(ref bool open) + { + ImGui.SetNextWindowSize(new Vector2(600, 460), ImGuiCond.FirstUseEver); + if (ImGui.Begin("Macro Rules##RynthAiMeta", ref open)) + Render(); + ImGui.End(); + } + + private void ClearConditionDataIfNeeded(MetaRule rule) + { + switch (rule.Condition) + { + case MetaConditionType.Always: + case MetaConditionType.Never: + case MetaConditionType.CharacterDeath: + case MetaConditionType.AnyVendorOpen: + case MetaConditionType.VendorClosed: + case MetaConditionType.PortalspaceEntered: + case MetaConditionType.PortalspaceExited: + case MetaConditionType.NavrouteEmpty: + rule.ConditionData = ""; + break; + + case MetaConditionType.All: + case MetaConditionType.Any: + case MetaConditionType.Not: + rule.ConditionData = ""; + break; + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/MonstersUI.cs b/Plugins/RynthAi/UI/MonstersUI.cs new file mode 100644 index 0000000..0a838c3 --- /dev/null +++ b/Plugins/RynthAi/UI/MonstersUI.cs @@ -0,0 +1,282 @@ +using System; +using System.Linq; +using System.Numerics; +using ImGuiNET; +using Decal.Adapter; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public class MonstersUI + { + private readonly UISettings _settings; + private readonly CoreManager _core; + + public Action OnSettingsChanged; + + // Local state just for this tab + private string _newMonsterName = ""; + private readonly string[] _elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + + public MonstersUI(UISettings settings, CoreManager core) + { + _settings = settings; + _core = core; + } + + public void Render() + { + if (ImGui.BeginTable("MonstersGrid", 18, ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, new Vector2(0, 300))) + { + ImGui.TableSetupColumn("F", ImGuiTableColumnFlags.WidthFixed, 15); + ImGui.TableSetupColumn("B", ImGuiTableColumnFlags.WidthFixed, 15); + ImGui.TableSetupColumn("G", ImGuiTableColumnFlags.WidthFixed, 15); + ImGui.TableSetupColumn("I", ImGuiTableColumnFlags.WidthFixed, 15); + ImGui.TableSetupColumn("Y", ImGuiTableColumnFlags.WidthFixed, 15); + ImGui.TableSetupColumn("V", ImGuiTableColumnFlags.WidthFixed, 15); + ImGui.TableSetupColumn("A", ImGuiTableColumnFlags.WidthFixed, 15); + ImGui.TableSetupColumn("Bl", ImGuiTableColumnFlags.WidthFixed, 15); + ImGui.TableSetupColumn("R", ImGuiTableColumnFlags.WidthFixed, 15); + ImGui.TableSetupColumn("S", ImGuiTableColumnFlags.WidthFixed, 15); + ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("P", ImGuiTableColumnFlags.WidthFixed, 25); + ImGui.TableSetupColumn("Dmg type", ImGuiTableColumnFlags.WidthFixed, 80); + ImGui.TableSetupColumn("Ex Vuln", ImGuiTableColumnFlags.WidthFixed, 80); + ImGui.TableSetupColumn("Weapon", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Offhand", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("PetDmg", ImGuiTableColumnFlags.WidthFixed, 70); + ImGui.TableSetupColumn("Del", ImGuiTableColumnFlags.WidthFixed, 30); + + ImGui.TableHeadersRow(); + + uint checkColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.2f, 1.0f, 0.2f, 1.0f)); + uint offColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.3f, 0.3f, 0.3f, 1.0f)); + + for (int i = 0; i < _settings.MonsterRules.Count; i++) + { + var rule = _settings.MonsterRules[i]; + bool isDefault = rule.Name.Equals("Default", StringComparison.OrdinalIgnoreCase); + + ImGui.TableNextRow(); + + // --- 9 Toggle Lights --- + ImGui.TableNextColumn(); + if (DrawToggleLight($"##F{i}", rule.Fester, checkColor, offColor, "F: Fester (Decrepitude's Grasp / Fester Other I-VIII)")) + { rule.Fester = !rule.Fester; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##B{i}", rule.Broadside, checkColor, offColor, "B: Broadside (Broadside of a Barn / Missile Weapons Ineptitude I-VIII)")) + { rule.Broadside = !rule.Broadside; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##G{i}", rule.GravityWell, checkColor, offColor, "G: Gravity Well (Vulnerability Other I-VIII)")) + { rule.GravityWell = !rule.GravityWell; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##I{i}", rule.Imperil, checkColor, offColor, "I: Imperil (Gossamer Flesh / Imperil Other I-VIII)")) + { rule.Imperil = !rule.Imperil; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##Y{i}", rule.Yield, checkColor, offColor, "Y: Yield (Magic Yield Other I-VIII)")) + { rule.Yield = !rule.Yield; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##V{i}", rule.Vuln, checkColor, offColor, "V: Vulnerability (element-matched)")) + { rule.Vuln = !rule.Vuln; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##A{i}", rule.UseArc, checkColor, offColor, "A: Arc spells (War/Void magic)\nFor Melee/Missile: Attack toggle")) + { rule.UseArc = !rule.UseArc; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##Bl{i}", rule.UseBolt, checkColor, offColor, "Bl: Bolt spells (War/Void magic, default)\nIf none of A/Bl/R/S set in magic = no attack (buff bot)")) + { rule.UseBolt = !rule.UseBolt; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##R{i}", rule.UseRing, checkColor, offColor, "R: Ring spells (uses Ring Range)")) + { rule.UseRing = !rule.UseRing; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##S{i}", rule.UseStreak, checkColor, offColor, "S: Streak spells (War/Void magic)")) + { rule.UseStreak = !rule.UseStreak; OnSettingsChanged?.Invoke(); } + + // --- Name --- + ImGui.TableNextColumn(); + if (isDefault) ImGui.TextColored(new Vector4(1, 1, 0, 1), rule.Name); + else ImGui.Text(rule.Name); + + // --- Priority --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(25); + int p = rule.Priority; + if (ImGui.InputInt($"##P{i}", ref p, 0)) { rule.Priority = p; OnSettingsChanged?.Invoke(); } + + // --- Dmg type --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(80); + if (ImGui.BeginCombo($"##Dmg{i}", rule.DamageType, ImGuiComboFlags.NoArrowButton)) + { + if (ImGui.Selectable("Auto", rule.DamageType == "Auto")) { rule.DamageType = "Auto"; OnSettingsChanged?.Invoke(); } + foreach (var el in _elements) + { + if (ImGui.Selectable(el, rule.DamageType == el)) + { rule.DamageType = el; OnSettingsChanged?.Invoke(); } + } + ImGui.EndCombo(); + } + + // --- Ex Vuln (extra vulnerability element) --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(80); + if (ImGui.BeginCombo($"##Vuln{i}", rule.ExVuln, ImGuiComboFlags.NoArrowButton)) + { + if (ImGui.Selectable("None", rule.ExVuln == "None")) { rule.ExVuln = "None"; OnSettingsChanged?.Invoke(); } + foreach (var el in _elements) + { + if (ImGui.Selectable(el, rule.ExVuln == el)) + { rule.ExVuln = el; OnSettingsChanged?.Invoke(); } + } + ImGui.EndCombo(); + } + + // --- Weapon Dropdown --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + string currentWeaponName = "<AUTO>"; + if (rule.WeaponId != 0) + { + var matchedWep = _settings.ItemRules.FirstOrDefault(x => x.Id == rule.WeaponId); + if (matchedWep != null) currentWeaponName = matchedWep.Name; + } + if (ImGui.BeginCombo($"##Wep{i}", currentWeaponName, ImGuiComboFlags.NoArrowButton)) + { + if (ImGui.Selectable("<AUTO>", rule.WeaponId == 0)) + { rule.WeaponId = 0; OnSettingsChanged?.Invoke(); } + foreach (var itemRule in _settings.ItemRules) + { + if (ImGui.Selectable(itemRule.Name, rule.WeaponId == itemRule.Id)) + { rule.WeaponId = itemRule.Id; OnSettingsChanged?.Invoke(); } + } + ImGui.EndCombo(); + } + + // --- Offhand Dropdown (shield or dual-wield weapon from ItemRules) --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + string currentOffhandName = "<AUTO>"; + if (rule.OffhandId != 0) + { + var matchedOff = _settings.ItemRules.FirstOrDefault(x => x.Id == rule.OffhandId); + if (matchedOff != null) currentOffhandName = matchedOff.Name; + } + if (ImGui.BeginCombo($"##Off{i}", currentOffhandName, ImGuiComboFlags.NoArrowButton)) + { + if (ImGui.Selectable("<AUTO>", rule.OffhandId == 0)) + { rule.OffhandId = 0; OnSettingsChanged?.Invoke(); } + foreach (var itemRule in _settings.ItemRules) + { + if (ImGui.Selectable(itemRule.Name + "##off", rule.OffhandId == itemRule.Id)) + { rule.OffhandId = itemRule.Id; OnSettingsChanged?.Invoke(); } + } + ImGui.EndCombo(); + } + + // --- PetDmg (pet damage element) --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(70); + if (ImGui.BeginCombo($"##PetDmg{i}", rule.PetDamage, ImGuiComboFlags.NoArrowButton)) + { + if (ImGui.Selectable("PAuto", rule.PetDamage == "PAuto")) { rule.PetDamage = "PAuto"; OnSettingsChanged?.Invoke(); } + foreach (var el in _elements) + { + if (ImGui.Selectable(el, rule.PetDamage == el)) + { rule.PetDamage = el; OnSettingsChanged?.Invoke(); } + } + ImGui.EndCombo(); + } + + // --- Delete --- + ImGui.TableNextColumn(); + if (isDefault) + { + ImGui.TextDisabled("-"); + } + else + { + if (ImGui.Button($"X##del{i}")) + { + _settings.MonsterRules.RemoveAt(i); + OnSettingsChanged?.Invoke(); + } + } + } + ImGui.EndTable(); + } + + ImGui.Separator(); + + if (ImGui.BeginTable("AddTable", 3)) + { + ImGui.TableSetupColumn("NameIn", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("AddBtn", ImGuiTableColumnFlags.WidthFixed, 60); + ImGui.TableSetupColumn("AddSelBtn", ImGuiTableColumnFlags.WidthFixed, 80); + + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + ImGui.InputTextWithHint("##NewMonName", "Enter monster name to add...", ref _newMonsterName, 64); + + ImGui.TableNextColumn(); + if (ImGui.Button("Add", new Vector2(60, 22))) + { + if (!string.IsNullOrWhiteSpace(_newMonsterName) && !_settings.MonsterRules.Any(m => m.Name.Equals(_newMonsterName, StringComparison.OrdinalIgnoreCase))) + { + _settings.MonsterRules.Add(new MonsterRule { Name = _newMonsterName, DamageType = "Auto", WeaponId = 0 }); + _newMonsterName = ""; + OnSettingsChanged?.Invoke(); + } + } + + ImGui.TableNextColumn(); + if (ImGui.Button("Add Sel", new Vector2(80, 22))) + { + int selectedId = _core.Actions.CurrentSelection; + if (selectedId != 0) + { + var obj = _core.WorldFilter[selectedId]; + if (obj != null && !_settings.MonsterRules.Any(m => m.Name.Equals(obj.Name, StringComparison.OrdinalIgnoreCase))) + { + _settings.MonsterRules.Add(new MonsterRule { Name = obj.Name, DamageType = "Auto", WeaponId = 0 }); + OnSettingsChanged?.Invoke(); + } + } + } + + ImGui.EndTable(); + } + } + + // ── Floating window wrapper (called from dashboard) ────────────────── + public void RenderAsWindow(ref bool open) + { + ImGui.SetNextWindowSize(new Vector2(700, 400), ImGuiCond.FirstUseEver); + if (ImGui.Begin("Monster Config##RynthAiMonsters", ref open)) + Render(); + ImGui.End(); + } + + private bool DrawToggleLight(string id, bool isOn, uint onColor, uint offColor, string tooltip = null) + { + var pos = ImGui.GetCursorScreenPos(); + ImGui.GetWindowDrawList().AddRectFilled( + pos + new Vector2(2, 2), + pos + new Vector2(12, 12), + isOn ? onColor : offColor, 10.0f + ); + ImGui.InvisibleButton(id, new Vector2(14, 14)); + if (tooltip != null && ImGui.IsItemHovered()) + ImGui.SetTooltip(tooltip); + return ImGui.IsItemClicked(); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/RouteUI.cs b/Plugins/RynthAi/UI/RouteUI.cs new file mode 100644 index 0000000..0efd9cf --- /dev/null +++ b/Plugins/RynthAi/UI/RouteUI.cs @@ -0,0 +1,337 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using Decal.Adapter; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public class RouteUI + { + private readonly UISettings _settings; + private readonly CoreManager _core; + + public Action OnSettingsChanged; + + // --- ROUTE STATE --- + private readonly string[] _routeTypes = { "Once", "Circular", "Linear", "Follow" }; + private readonly string[] _addModes = { "End", "Above", "Below" }; + private int _addModeIdx = 0; + private int _selectedRouteIndex = -1; + + // --- GRAPHICS STATE --- + public bool NeedsRouteGraphicsRefresh = false; + private List<D3DObj> _routeGraphics = new List<D3DObj>(); + public List<D3DObj> TestD3DObjects = new List<D3DObj>(); + + public RouteUI(UISettings settings, CoreManager core) + { + _settings = settings; + _core = core; + } + + public void Render() + { + string activeNavName = string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None (Unsaved)" : Path.GetFileName(_settings.CurrentNavPath); + ImGui.TextColored(new Vector4(1, 1, 0, 1), $"Active Nav: {activeNavName}"); + ImGui.Separator(); + + int rTypeIdx = 0; + if (_settings.CurrentRoute.RouteType == NavRouteType.Circular) rTypeIdx = 1; + else if (_settings.CurrentRoute.RouteType == NavRouteType.Linear) rTypeIdx = 2; + else if (_settings.CurrentRoute.RouteType == NavRouteType.Follow) rTypeIdx = 3; + + ImGui.SetNextItemWidth(100); + if (ImGui.Combo("Route Type", ref rTypeIdx, _routeTypes, _routeTypes.Length)) + { + if (rTypeIdx == 0) _settings.CurrentRoute.RouteType = NavRouteType.Once; + else if (rTypeIdx == 1) _settings.CurrentRoute.RouteType = NavRouteType.Circular; + else if (rTypeIdx == 2) _settings.CurrentRoute.RouteType = NavRouteType.Linear; + else if (rTypeIdx == 3) _settings.CurrentRoute.RouteType = NavRouteType.Follow; + + TryAutoSaveNav(); + } + + ImGui.SameLine(); + ImGui.SetNextItemWidth(100); + ImGui.Combo("Insert", ref _addModeIdx, _addModes, _addModes.Length); + + ImGui.Spacing(); + + if (ImGui.Button("Add Waypoint", new Vector2(100, 25))) + { + var me = _core.WorldFilter[_core.CharacterFilter.Id]; + if (me != null) + { + var newPt = new NavPoint + { + NS = me.Coordinates().NorthSouth, + EW = me.Coordinates().EastWest, + Z = me.Offset().Z + }; + InsertPoint(newPt); + } + } + + ImGui.SameLine(); + if (ImGui.Button("Add Portal", new Vector2(100, 25))) + { + try + { + var me = _core.WorldFilter[_core.CharacterFilter.Id]; + if (me != null) + { + var myPos = me.Coordinates(); + WorldObject best = null; + double bestDist = double.MaxValue; + foreach (WorldObject wo in _core.WorldFilter.GetLandscape()) + { + if (wo == null) continue; + if (wo.ObjectClass == ObjectClass.Portal || wo.ObjectClass == ObjectClass.Npc || wo.ObjectClass == ObjectClass.Vendor) + { + try + { + double dNS = wo.Coordinates().NorthSouth - myPos.NorthSouth; + double dEW = wo.Coordinates().EastWest - myPos.EastWest; + double d = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + if (d < bestDist) { bestDist = d; best = wo; } + } + catch { } + } + } + if (best != null && bestDist < 20.0) + { + var newPt = new NavPoint + { + Type = NavPointType.PortalNPC, + NS = myPos.NorthSouth, + EW = myPos.EastWest, + Z = me.Offset().Z, + TargetName = best.Name, + ObjectClass = (int)best.ObjectClass, + IsTie = false + }; + InsertPoint(newPt); + _core.Actions.AddChatText($"[RynthAi] Added Portal/NPC: {best.Name} ({bestDist:F1}yd)", 1); + } + else + { + _core.Actions.AddChatText("[RynthAi] No portal/NPC found within 20 yards.", 1); + } + } + } + catch (Exception ex) { _core.Actions.AddChatText($"[RynthAi] Error: {ex.Message}", 1); } + } + + ImGui.SameLine(); + if (ImGui.Button("Add Recall", new Vector2(100, 25))) + { + ImGui.OpenPopup("RecallPopup"); + } + if (ImGui.BeginPopup("RecallPopup")) + { + int[] ids = { + 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 + }; + + for (int ri = 0; ri < ids.Length; ri++) + { + string name = SpellDatabase.GetSpellName(ids[ri]); + if (ImGui.Selectable($"{name} ({ids[ri]})")) + { + var me = _core.WorldFilter[_core.CharacterFilter.Id]; + if (me != null) + { + var newPt = new NavPoint + { + Type = NavPointType.Recall, + NS = me.Coordinates().NorthSouth, + EW = me.Coordinates().EastWest, + Z = me.Offset().Z, + SpellId = ids[ri] + }; + InsertPoint(newPt); + _core.Actions.AddChatText($"[RynthAi] Added Recall: {name} ({ids[ri]})", 1); + } + } + } + ImGui.EndPopup(); + } + + ImGui.SameLine(); + if (ImGui.Button("Clear Route", new Vector2(100, 25))) + { + _settings.CurrentRoute.Points.Clear(); + _settings.ActiveNavIndex = 0; + TryAutoSaveNav(); + DisposeRouteGraphics(); + OnSettingsChanged?.Invoke(); + } + + ImGui.SameLine(); + if (ImGui.Button("Save Route", new Vector2(100, 25))) + { + if (!string.IsNullOrEmpty(_settings.CurrentNavPath)) + { + try { _settings.CurrentRoute.Save(_settings.CurrentNavPath); _core.Actions.AddChatText("[RynthAi] Route saved.", 1); } catch { } + } + } + + if (ImGui.BeginListBox("##RoutePoints", new Vector2(-1, 200))) + { + for (int i = 0; i < _settings.CurrentRoute.Points.Count; i++) + { + // Push a unique ID so ImGui doesn't confuse the 50 different "X" buttons + ImGui.PushID($"route_pt_{i}"); + + // Draw the red "X" button + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.8f, 0.2f, 0.2f, 1f)); + if (ImGui.Button("X", new Vector2(20, 20))) + { + // 1. Remove the point + _settings.CurrentRoute.Points.RemoveAt(i); + + // 2. Safely shift our selected/active indexes so we don't crash + if (_selectedRouteIndex == i) _selectedRouteIndex = -1; + else if (_selectedRouteIndex > i) _selectedRouteIndex--; + + if (_settings.ActiveNavIndex == i) _settings.ActiveNavIndex = 0; + else if (_settings.ActiveNavIndex > i) _settings.ActiveNavIndex--; + + // 3. Save, update 3D graphics, and notify the plugin + TryAutoSaveNav(); + UpdateRouteGraphics(); + OnSettingsChanged?.Invoke(); + + // 4. Pop the styles and break the loop for this single frame to prevent index out-of-range errors + ImGui.PopStyleColor(); + ImGui.PopID(); + break; + } + ImGui.PopStyleColor(); + + ImGui.SameLine(); + + // Draw the selectable row text + string prefix = " "; + if (i == _settings.ActiveNavIndex) prefix = "==>"; + + bool isSelected = (_selectedRouteIndex == i); + if (ImGui.Selectable($"{prefix} [{i}] {_settings.CurrentRoute.Points[i]}", isSelected)) + { + _selectedRouteIndex = i; + } + + ImGui.PopID(); + } + ImGui.EndListBox(); + } + } + + public void InsertPoint(NavPoint newPt) + { + if (_addModeIdx == 0 || _settings.CurrentRoute.Points.Count == 0) + _settings.CurrentRoute.Points.Add(newPt); + else if (_addModeIdx == 1 && _selectedRouteIndex >= 0) + _settings.CurrentRoute.Points.Insert(_selectedRouteIndex, newPt); + else if (_addModeIdx == 2 && _selectedRouteIndex >= 0) + _settings.CurrentRoute.Points.Insert(_selectedRouteIndex + 1, newPt); + else + _settings.CurrentRoute.Points.Add(newPt); + + TryAutoSaveNav(); + UpdateRouteGraphics(); + OnSettingsChanged?.Invoke(); + } + + public void TryAutoSaveNav() + { + if (!string.IsNullOrEmpty(_settings.CurrentNavPath)) + { + try { _settings.CurrentRoute.Save(_settings.CurrentNavPath); } catch { } + } + } + + public void UpdateRouteGraphics() + { + DisposeRouteGraphics(); + + if (_settings.CurrentRoute?.Points == null || _settings.CurrentRoute.Points.Count == 0) + return; + + if (_core?.D3DService == null) + return; + + int colorAqua = unchecked((int)0xFF00FFFF); + int colorBlue = unchecked((int)0xFF0088FF); + int colorRed = unchecked((int)0xFFFF2222); + + float ringScale = Math.Max(0.5f, (float)_settings.FollowNavMin); + + try + { + for (int i = 0; i < _settings.CurrentRoute.Points.Count; i++) + { + var pt = _settings.CurrentRoute.Points[i]; + int wpColor = (i == _settings.ActiveNavIndex) ? colorRed : colorAqua; + + var ring = _core.D3DService.MarkCoordsWithShape( + (float)pt.NS, (float)pt.EW, (float)pt.Z + 0.5f, + Decal.Adapter.Wrappers.D3DShape.Ring, wpColor); + ring.Visible = true; + ring.ScaleX = ringScale; + ring.ScaleY = ringScale; + ring.ScaleZ = 0.1f; + try { ring.Anchor((float)pt.NS, (float)pt.EW, (float)pt.Z + 0.5f); } catch { } + _routeGraphics.Add(ring); + + int nextIdx = i + 1; + if (nextIdx >= _settings.CurrentRoute.Points.Count) + { + if (_settings.CurrentRoute.RouteType == NavRouteType.Circular) nextIdx = 0; + else continue; + } + + var nextPt = _settings.CurrentRoute.Points[nextIdx]; + double dNS = nextPt.NS - pt.NS; + double dEW = nextPt.EW - pt.EW; + double dZ = nextPt.Z - pt.Z; + double dist2D = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + + int dots = Math.Min(150, Math.Max(2, (int)dist2D)); + + for (int d = 1; d < dots; d++) + { + double f = (double)d / dots; + var dot = _core.D3DService.MarkCoordsWithShape( + (float)(pt.NS + dNS * f), + (float)(pt.EW + dEW * f), + (float)(pt.Z + dZ * f) + 0.5f, + Decal.Adapter.Wrappers.D3DShape.Sphere, colorBlue); + dot.Visible = true; + dot.Scale(0.15f); + _routeGraphics.Add(dot); + } + } + } + catch { } + } + + public void DisposeRouteGraphics() + { + foreach (var o in _routeGraphics) { try { o.Visible = false; ((IDisposable)o).Dispose(); } catch { } } + _routeGraphics.Clear(); + foreach (var o in TestD3DObjects) { try { o.Visible = false; ((IDisposable)o).Dispose(); } catch { } } + TestD3DObjects.Clear(); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/RynthAiUI.Rendering.cs b/Plugins/RynthAi/UI/RynthAiUI.Rendering.cs new file mode 100644 index 0000000..b9445ea --- /dev/null +++ b/Plugins/RynthAi/UI/RynthAiUI.Rendering.cs @@ -0,0 +1,9 @@ +namespace NexSuite.Plugins.RynthAi +{ + // This file intentionally left blank. + // The old "Unified Tabs" UI has been retired in favor of the clean Advanced Settings menu. + public partial class RynthAiUI + { + + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/RynthAiUI.cs b/Plugins/RynthAi/UI/RynthAiUI.cs new file mode 100644 index 0000000..a04e594 --- /dev/null +++ b/Plugins/RynthAi/UI/RynthAiUI.cs @@ -0,0 +1,997 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Numerics; +using System.Linq; +using ImGuiNET; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using RynthAi.Meta; + +namespace NexSuite.Plugins.RynthAi +{ + public static class DashWindows + { + public static bool ShowMacroRules = false; + public static bool ShowMonsters = false; + public static bool ShowNavigation = false; + public static bool ShowWeapons = false; + public static bool ShowLua = false; + } + + public partial class RynthAiUI : IDisposable + { + public UISettings Settings { get; set; } + public CombatManager CombatManager { get; set; } + public CoreManager Core { get; set; } + public MetaManager MetaManager { get; set; } + + public Action OnSettingsChanged; + public Action OnForceRebuffClicked; + public Action OnLootProfileSelected; + public Action OnMetaProfileSelected; + public Action OnMetaRulesUpdated; + + public LuaUI LuaTab; + public MetaUI MetaTab; + public MonstersUI MonstersTab; + public RouteUI RouteTab; + + private readonly AdvancedSettingsUI _advancedUI; + + public List<string> Profiles = new List<string>(); + public List<string> NavFiles = new List<string>(); + public List<string> LootFiles = new List<string>(); + public List<string> MetaFiles = new List<string>(); + + private int _selectedNavIdx = 0; + private string _navFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\NavProfiles"; + private string _lootFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\LootProfiles"; + private string _metaFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\MetaProfiles"; + + private readonly string[] _elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + + // ── Colour palette ─────────────────────────────────────────────────── + private static readonly Vector4 ColTeal = new Vector4(0.15f, 0.85f, 0.90f, 1.00f); + private static readonly Vector4 ColAmber = new Vector4(0.91f, 0.70f, 0.20f, 1.00f); + private static readonly Vector4 ColRed = new Vector4(0.85f, 0.25f, 0.25f, 1.00f); + private static readonly Vector4 ColGreen = new Vector4(0.25f, 0.85f, 0.45f, 1.00f); + private static readonly Vector4 ColTextDim = new Vector4(0.85f, 0.90f, 0.95f, 1.00f); + private static readonly Vector4 ColTextMute = new Vector4(0.55f, 0.65f, 0.75f, 1.00f); + private static readonly Vector4 ColHp = new Vector4(0.85f, 0.20f, 0.20f, 1.00f); + private static readonly Vector4 ColStam = new Vector4(0.20f, 0.80f, 0.35f, 1.00f); + private static readonly Vector4 ColMana = new Vector4(0.15f, 0.55f, 0.95f, 1.00f); + private static readonly Vector4 ColBarBg = new Vector4(0.08f, 0.12f, 0.16f, 1.00f); + private static readonly Vector4 ColPanelBg = new Vector4(0.04f, 0.07f, 0.10f, 0.95f); + + private static readonly Vector4 ColBtnOn = new Vector4(0.15f, 0.30f, 0.35f, 1.00f); + private static readonly Vector4 ColBtnFill = new Vector4(0.06f, 0.12f, 0.18f, 1.00f); + private static readonly Vector4 ColBtnHov = new Vector4(0.10f, 0.18f, 0.25f, 1.00f); + private static readonly Vector4 ColBtnAct = new Vector4(0.08f, 0.15f, 0.22f, 1.00f); + private static readonly Vector4 ColBtnBord = new Vector4(0.15f, 0.25f, 0.35f, 1.00f); + + // ── DRAKHUD HEALTH ENGINE ──────────────────────────────────────────── + private Dictionary<int, float> _healthRatioTracker = new Dictionary<int, float>(); + private Dictionary<int, int> _maxHealthTracker = new Dictionary<int, int>(); + private int _lastTargetId = 0; + private int _retryTargetId = 0; + private int _retryCount = 0; + private DateTime _lastRequestTime = DateTime.MinValue; + + // ── UI STATE ───────────────────────────────────────────────────────── + private bool _isMinimized = false; + private bool _isLocked = false; + private float _bgOpacity = 0.95f; + private Vector2 _expandedSize = new Vector2(430, 420); + private bool _wasMinimized = false; + + public RynthAiUI(UISettings settings, CombatManager combatManager, CoreManager core) + { + Settings = settings; + CombatManager = combatManager; + Core = core; + + LuaTab = new LuaUI(settings, core); + _advancedUI = new AdvancedSettingsUI(settings) { OnSettingsChanged = () => OnSettingsChanged?.Invoke() }; + MetaTab = new MetaUI(settings, NavFiles) { OnSettingsChanged = () => OnSettingsChanged?.Invoke(), OnMetaRulesUpdated = () => OnMetaRulesUpdated?.Invoke() }; + MonstersTab = new MonstersUI(settings, core) { OnSettingsChanged = () => OnSettingsChanged?.Invoke() }; + RouteTab = new RouteUI(settings, core) { OnSettingsChanged = () => OnSettingsChanged?.Invoke() }; + + RefreshProfilesList(); RefreshNavFiles(); RefreshLootFiles(); RefreshMetaFiles(); + + try { Core.EchoFilter.ServerDispatch += OnServerDispatch; } catch { } + } + + public void Dispose() + { + try { Core.EchoFilter.ServerDispatch -= OnServerDispatch; } catch { } + } + + public void SetMissileCraftingManager(MissileCraftingManager mgr) => _advancedUI.SetMissileCraftingManager(mgr); + + public void Render() + { + UpdateTargetAppraisal(); + + if (RouteTab != null && RouteTab.NeedsRouteGraphicsRefresh) + { RouteTab.NeedsRouteGraphicsRefresh = false; RouteTab.UpdateRouteGraphics(); } + + RenderDashboard(); + + // Render all active popup windows based on the button toggles + try { if (Settings.ShowAdvancedWindow) _advancedUI?.Render(); } catch { Settings.ShowAdvancedWindow = false; } + try { if (DashWindows.ShowMacroRules) MetaTab?.RenderAsWindow(ref DashWindows.ShowMacroRules); } catch { DashWindows.ShowMacroRules = false; } + try { if (DashWindows.ShowMonsters) MonstersTab?.RenderAsWindow(ref DashWindows.ShowMonsters); } catch { DashWindows.ShowMonsters = false; } + try { if (DashWindows.ShowWeapons) RenderWeaponsWindow(); } catch { DashWindows.ShowWeapons = false; } + try { if (DashWindows.ShowNavigation) RenderNavigationWindow(); } catch { DashWindows.ShowNavigation = false; } + try { if (DashWindows.ShowLua) RenderLuaWindow(); } catch { DashWindows.ShowLua = false; } + } + + private void RenderDashboard() + { + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 10)); + ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 8.0f); + ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, 6.0f); + + ImGui.PushStyleColor(ImGuiCol.WindowBg, new Vector4(0.04f, 0.06f, 0.08f, _bgOpacity)); + + ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoCollapse; + + if (_isMinimized) + { + flags |= ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoResize; + _wasMinimized = true; + } + else + { + if (_isLocked) flags |= ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove; + + if (_wasMinimized) + { + ImGui.SetNextWindowSize(_expandedSize, ImGuiCond.Always); + _wasMinimized = false; + } + } + + ImGui.SetNextWindowSizeConstraints(new Vector2(400, 0), new Vector2(1200, 2000)); + + if (!_wasMinimized && !_isMinimized && !_isLocked) + { + ImGui.SetNextWindowSize(_expandedSize, ImGuiCond.FirstUseEver); + } + + if (ImGui.Begin("RynthAi Dashboard##Main", flags)) + { + if (!_isMinimized && !_isLocked && !_wasMinimized) + { + _expandedSize = ImGui.GetWindowSize(); + } + + RenderDashHeader(); + + ImGui.PushStyleColor(ImGuiCol.ChildBg, ColPanelBg); + ImGui.PushStyleColor(ImGuiCol.Border, ColBtnBord); + ImGui.PushStyleVar(ImGuiStyleVar.ChildBorderSize, 1.0f); + + if (ImGui.BeginChild("CombatPanel", new Vector2(-1, 154), true, ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)) + { + RenderCombatPanel(); + ImGui.Dummy(new Vector2(0, 4)); + } + ImGui.EndChild(); + ImGui.PopStyleVar(); + ImGui.PopStyleColor(2); + + if (!_isMinimized) + { + ImGui.Spacing(); ImGui.Spacing(); + RenderLauncherGrid(); + } + } + ImGui.End(); + ImGui.PopStyleColor(); + ImGui.PopStyleVar(3); + } + + private void RenderDashHeader() + { + float W = ImGui.GetContentRegionAvail().X; + float startY = ImGui.GetCursorPosY(); + + ImGui.SetWindowFontScale(1.4f); + ImGui.TextColored(ColTeal, "N"); ImGui.SameLine(0, 2); + ImGui.TextColored(new Vector4(1, 1, 1, 1), "NEXAI DASHBOARD"); + ImGui.SetWindowFontScale(1.0f); + + ImGui.SameLine(); + ImGui.SetCursorPosY(startY + 5); + ImGui.TextColored(ColTextMute, "v4.0"); + + ImGui.SameLine(W - 130); + ImGui.SetCursorPosY(startY + 2); + + if (ImGui.SmallButton(_isLocked ? "Unlk" : "Lock")) { _isLocked = !_isLocked; } + if (ImGui.IsItemHovered()) ImGui.SetTooltip(_isLocked ? "Unlock Window" : "Lock Window"); + + ImGui.SameLine(); + if (ImGui.SmallButton("-")) _bgOpacity = Math.Max(0.1f, _bgOpacity - 0.1f); + + ImGui.SameLine(); + if (ImGui.SmallButton("+")) _bgOpacity = Math.Min(1.0f, _bgOpacity + 0.1f); + + ImGui.SameLine(); + if (ImGui.SmallButton(_isMinimized ? "^" : "_")) { _isMinimized = !_isMinimized; } + + ImGui.SameLine(); + if (ImGui.SmallButton("X")) { Settings.IsMacroRunning = false; } + + ImGui.Dummy(new Vector2(0, 2)); + + if (!_isMinimized) + { + if (ImGui.BeginTable("HeaderGrid", 2)) + { + ImGui.TableSetupColumn("Left", ImGuiTableColumnFlags.WidthFixed, W * 0.40f); + ImGui.TableSetupColumn("Right", ImGuiTableColumnFlags.WidthStretch); + + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.SetWindowFontScale(1.3f); + ImGui.TextColored(ColTextMute, "Macro Status:"); + ImGui.SetWindowFontScale(1.0f); + + ImGui.TableNextColumn(); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 2); + ImGui.TextColored(ColTextMute, "Profile:"); + ImGui.SameLine(60); + ImGui.SetNextItemWidth(-1); + if (ImGui.BeginCombo("##ProfCombo", TruncateName(Settings.SelectedProfile, 16))) + { + foreach (var p in Profiles) + { + if (ImGui.Selectable(p, p == Settings.SelectedProfile)) + { + Settings.SelectedProfile = p; OnSettingsChanged?.Invoke(); + } + } + ImGui.EndCombo(); + } + + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + var pos = ImGui.GetCursorScreenPos(); + var dl = ImGui.GetWindowDrawList(); + uint color = Settings.IsMacroRunning ? ImGui.ColorConvertFloat4ToU32(ColGreen) : ImGui.ColorConvertFloat4ToU32(ColTextMute); + + dl.AddCircleFilled(pos + new Vector2(8, 12), 6, color); + if (Settings.IsMacroRunning) dl.AddCircle(pos + new Vector2(8, 12), 9, color, 12, 1.5f); + + ImGui.SetCursorScreenPos(pos + new Vector2(24, 0)); + if (ImGui.InvisibleButton("ToggleMacro", new Vector2(100, 24))) + { + Settings.IsMacroRunning = !Settings.IsMacroRunning; + OnSettingsChanged?.Invoke(); + } + + ImGui.SetCursorScreenPos(pos + new Vector2(26, 2)); + ImGui.SetWindowFontScale(1.3f); + ImGui.TextColored(Settings.IsMacroRunning ? ColGreen : ColTextMute, Settings.IsMacroRunning ? "RUNNING" : "STOPPED"); + ImGui.SetWindowFontScale(1.0f); + + ImGui.TableNextColumn(); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 4); + ImGui.TextColored(ColTextMute, "Nav:"); + ImGui.SameLine(60); + ImGui.SetNextItemWidth(-1); + string navName = string.IsNullOrEmpty(Settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(Settings.CurrentNavPath); + if (ImGui.BeginCombo("##NavCombo", TruncateName(navName, 16))) + { + for (int i = 0; i < NavFiles.Count; i++) + { + if (ImGui.Selectable(NavFiles[i], _selectedNavIdx == i)) + { + _selectedNavIdx = i; LoadSelectedNav(); + } + } + ImGui.EndCombo(); + } + + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 4); + ImGui.TextColored(ColTextMute, "State:"); ImGui.SameLine(0, 8); + ImGui.TextColored(ColAmber, Settings.CurrentState ?? "Idle"); + + ImGui.TableNextColumn(); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 6); + ImGui.TextColored(ColTextMute, "Loot:"); + ImGui.SameLine(60); + ImGui.SetNextItemWidth(-1); + string lootName = string.IsNullOrEmpty(Settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(Settings.CurrentLootPath); + if (ImGui.BeginCombo("##LootCombo", TruncateName(lootName, 16))) + { + for (int i = 0; i < LootFiles.Count; i++) + { + if (ImGui.Selectable(LootFiles[i], Settings.LootProfileIdx == i)) + { + Settings.LootProfileIdx = i; + Settings.CurrentLootPath = (i == 0) ? "" : Path.Combine(_lootFolder, LootFiles[i] + ".utl"); + OnSettingsChanged?.Invoke(); OnLootProfileSelected?.Invoke(); + } + } + ImGui.EndCombo(); + } + + ImGui.EndTable(); + } + ImGui.Spacing(); + } + } + + private void RenderCombatPanel() + { + if (ImGui.BeginTable("CombatInnerTable", 2, ImGuiTableFlags.None)) + { + ImGui.TableSetupColumn("Toggles", ImGuiTableColumnFlags.WidthFixed, 68); + ImGui.TableSetupColumn("Vitals", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableNextRow(); + + // --- COLUMN 1: TOGGLES --- + ImGui.TableNextColumn(); + var tPos = ImGui.GetCursorScreenPos() + new Vector2(2, 28); + + // 2x2 Grid + DrawSquareToggle("sword", ref Settings.EnableCombat, tPos, "CombatTgl"); + DrawSquareToggle("buff", ref Settings.EnableBuffing, tPos + new Vector2(34, 0), "BuffTgl"); + DrawSquareToggle("shoe", ref Settings.EnableNavigation, tPos + new Vector2(0, 34), "NavTgl"); + DrawSquareToggle("bag", ref Settings.EnableLooting, tPos + new Vector2(34, 34), "LootTgl"); + + // Wide MACRO Button + DrawWideToggle("MACRO", "gear", ref Settings.EnableMeta, tPos + new Vector2(0, 68), "MetaTgl", 64f, 20f); + + // --- COLUMN 2: MOB + PLAYER VITALS --- + ImGui.TableNextColumn(); + + string targetName = "NO TARGET"; + float targetHpPct = 0f; + string mobHpDisplay = "0%"; + int currentTarget = Core.Actions.CurrentSelection; + + if (currentTarget != 0) + { + try + { + var wo = Core.WorldFilter[currentTarget]; + if (wo != null) + { + targetName = wo.Name; + + if (_healthRatioTracker.ContainsKey(currentTarget)) + { + targetHpPct = _healthRatioTracker[currentTarget]; + } + else + { + targetHpPct = (float)wo.Values((DoubleValueKey)0x92, 0.0); + } + + if (_maxHealthTracker.ContainsKey(currentTarget) && _maxHealthTracker[currentTarget] > 0) + { + int maxHp = _maxHealthTracker[currentTarget]; + int curHp = (int)Math.Round(targetHpPct * maxHp); + mobHpDisplay = $"{(int)(targetHpPct * 100)}% ({curHp}/{maxHp})"; + } + else + { + mobHpDisplay = $"{(int)(targetHpPct * 100)}%"; + } + } + } + catch { } + } + + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 4); + ImGui.TextColored(ColTextDim, TruncateName(targetName, 32).ToUpper()); + + float textWidth = ImGui.CalcTextSize(mobHpDisplay).X; + ImGui.SameLine(ImGui.GetContentRegionAvail().X - textWidth); + ImGui.TextColored(new Vector4(1, 1, 1, 1), mobHpDisplay); + + DrawSegmentedBar(targetHpPct, ImGui.GetContentRegionAvail().X - 4); + + ImGui.Spacing(); + ImGui.TextColored(ColTextMute, "PLAYER VITALS"); + + int hp = 0, hpMax = 1, st = 0, stMax = 1, mn = 0, mnMax = 1; + try + { + if (Core?.CharacterFilter != null) + { + hp = Core.CharacterFilter.Health; hpMax = Math.Max(1, (int)Core.CharacterFilter.EffectiveVital[CharFilterVitalType.Health]); + st = Core.CharacterFilter.Stamina; stMax = Math.Max(1, (int)Core.CharacterFilter.EffectiveVital[CharFilterVitalType.Stamina]); + mn = Core.CharacterFilter.Mana; mnMax = Math.Max(1, (int)Core.CharacterFilter.EffectiveVital[CharFilterVitalType.Mana]); + } + } + catch { } + + float hpPct = (float)hp / hpMax; float stPct = (float)st / stMax; float mnPct = (float)mn / mnMax; + + DrawVitalRow("heart", "HP", hpPct, ColHp, $"{hp}/{hpMax}"); + DrawVitalRow("run", "ST", stPct, ColGreen, $"{st}/{stMax}"); + DrawVitalRow("drop", "MN", mnPct, ColMana, $"{mn}/{mnMax}"); + + ImGui.EndTable(); + } + } + + private void RenderLauncherGrid() + { + if (ImGui.BeginTable("LauncherGridTable", 3, ImGuiTableFlags.SizingStretchSame)) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); GridBtn("Macro Rules", "gear", ref DashWindows.ShowMacroRules); + ImGui.TableNextColumn(); GridBtn("Monsters", "target", ref DashWindows.ShowMonsters); + ImGui.TableNextColumn(); GridBtn("Settings", "wrench", ref Settings.ShowAdvancedWindow); + + ImGui.TableNextRow(); + ImGui.TableNextColumn(); GridBtn("Navigation", "map", ref DashWindows.ShowNavigation); + ImGui.TableNextColumn(); GridBtn("Weapons", "shield", ref DashWindows.ShowWeapons); + ImGui.TableNextColumn(); GridBtn("Lua Scripts", "code", ref DashWindows.ShowLua); + + ImGui.EndTable(); + } + } + + private void GridBtn(string label, string icon, ref bool flag) + { + bool wasOn = flag; + float bH = 30f; + float bW = -1f; + + ImGui.PushStyleColor(ImGuiCol.Button, ColBtnFill); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, ColBtnHov); + ImGui.PushStyleColor(ImGuiCol.ButtonActive, ColBtnAct); + ImGui.PushStyleColor(ImGuiCol.Border, wasOn ? ColTeal : ColBtnBord); + + ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1.0f); + ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 4f); + + var startPos = ImGui.GetCursorScreenPos(); + if (ImGui.Button($"##{label}", new Vector2(bW, bH))) flag = !flag; + + ImGui.PopStyleVar(2); + ImGui.PopStyleColor(4); + + float actualWidth = ImGui.GetItemRectSize().X; + var textSize = ImGui.CalcTextSize(label); + + DrawIcon(icon, startPos + new Vector2(8, 6), wasOn ? ColTeal : ColTextMute, 16f); + + ImGui.SetCursorScreenPos(startPos + new Vector2(30, (bH - textSize.Y) / 2)); + ImGui.TextColored(wasOn ? ColTeal : ColTextDim, label); + + ImGui.SetCursorScreenPos(startPos + new Vector2(0, bH + 2)); + ImGui.Dummy(new Vector2(actualWidth, 0)); + } + + // ═════════════════════════════════════════════════════════════════════ + // WEAPONS & ITEMS WINDOW + // ═════════════════════════════════════════════════════════════════════ + private void RenderWeaponsWindow() + { + ImGui.SetNextWindowSize(new Vector2(480, 300), ImGuiCond.FirstUseEver); + if (ImGui.Begin("Weapons & Items##RynthAiWeapons", ref DashWindows.ShowWeapons)) + { + ImGui.TextColored(ColAmber, "Weapons / Wands / Shields / Pets"); + + if (ImGui.BeginTable("ItemsTable", 3, + ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.Resizable)) + { + ImGui.TableSetupColumn("Item Name", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Element", ImGuiTableColumnFlags.WidthFixed, 100); + ImGui.TableSetupColumn("Actions", ImGuiTableColumnFlags.WidthFixed, 60); + ImGui.TableHeadersRow(); + + for (int i = 0; i < Settings.ItemRules.Count; i++) + { + var rule = Settings.ItemRules[i]; + ImGui.TableNextRow(); + + ImGui.TableNextColumn(); + var wo = Core?.WorldFilter[rule.Id]; + if (wo != null) + ImGui.Text(rule.Name); + else + { + ImGui.TextColored(ColRed, rule.Name); + ImGui.SameLine(); + ImGui.TextColored(new Vector4(1f, 0.3f, 0.3f, 0.8f), "(Gone)"); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Weapon not in inventory!\nBot cannot equip this item.\nRemove and re-add the correct weapon."); + } + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + if (ImGui.BeginCombo($"##Elem{i}", rule.Element, ImGuiComboFlags.NoArrowButton)) + { + foreach (var el in _elements) + if (ImGui.Selectable(el, rule.Element == el)) + { rule.Element = el; OnSettingsChanged?.Invoke(); } + ImGui.EndCombo(); + } + + ImGui.TableNextColumn(); + if (ImGui.Button($"Del##{i}", new Vector2(-1, 0))) + { + foreach (var mr in Settings.MonsterRules) + { + if (mr.WeaponId == rule.Id) mr.WeaponId = 0; + if (mr.OffhandId == rule.Id) mr.OffhandId = 0; + } + Settings.ItemRules.RemoveAt(i); + OnSettingsChanged?.Invoke(); + } + } + ImGui.EndTable(); + } + + ImGui.Separator(); + if (ImGui.Button("Add Selected Item", new Vector2(150, 24))) + { + int sel = Core.Actions.CurrentSelection; + if (sel != 0) + { + var item = Core.WorldFilter[sel]; + if (item != null) + { + if (IsValidEquipment(item)) + { + if (!Settings.ItemRules.Any(x => x.Id == item.Id)) + { + Settings.ItemRules.Add(new ItemRule + { + Id = item.Id, + Name = item.Name, + Element = GetElement(item), + KeepBuffed = true + }); + OnSettingsChanged?.Invoke(); + } + else Core.Actions.AddChatText($"[RynthAi] Item ID {item.Id} already in list.", 1); + } + else Core.Actions.AddChatText("[RynthAi] Selected item must be a weapon, wand, or shield.", 1); + } + } + } + ImGui.SameLine(); + ImGui.TextDisabled("(Select item in-game first)"); + } + ImGui.End(); + } + + // ═════════════════════════════════════════════════════════════════════ + // NAVIGATION WINDOW + // ═════════════════════════════════════════════════════════════════════ + private void RenderNavigationWindow() + { + ImGui.SetNextWindowSize(new Vector2(360, 400), ImGuiCond.FirstUseEver); + if (ImGui.Begin("Navigation##RynthAiNav", ref DashWindows.ShowNavigation)) + RouteTab?.Render(); + ImGui.End(); + } + + // ═════════════════════════════════════════════════════════════════════ + // LUA SCRIPTS WINDOW + // ═════════════════════════════════════════════════════════════════════ + private void RenderLuaWindow() + { + ImGui.SetNextWindowSize(new Vector2(400, 300), ImGuiCond.FirstUseEver); + if (ImGui.Begin("Lua Scripts##RynthAiLua", ref DashWindows.ShowLua)) + { + if (LuaTab != null) + { + LuaTab.Render(); + } + else + { + ImGui.TextColored(ColTextDim, "Lua Engine is currently unavailable."); + } + } + ImGui.End(); + } + + // ── DRAKHUD LOGIC (Embedded) ────────────────────────────────────────── + private void UpdateTargetAppraisal() + { + int currentTarget = Core.Actions.CurrentSelection; + bool isMonster = false; + + if (currentTarget != 0) + { + try + { + WorldObject wo = Core.WorldFilter[currentTarget]; + if (wo != null && wo.ObjectClass == ObjectClass.Monster) + isMonster = true; + } + catch { } + } + + if (currentTarget != _lastTargetId) + { + _lastTargetId = currentTarget; + _retryTargetId = currentTarget; + _retryCount = 0; + if (currentTarget != 0 && isMonster) + { + try { Core.Actions.RequestId(currentTarget); _lastRequestTime = DateTime.Now; } catch { } + } + } + + if (currentTarget != 0 && isMonster && currentTarget == _retryTargetId && _retryCount < 3 && + !_maxHealthTracker.ContainsKey(currentTarget) && (DateTime.Now - _lastRequestTime).TotalSeconds >= 0.75) + { + try { Core.Actions.RequestId(currentTarget); _lastRequestTime = DateTime.Now; _retryCount++; } catch { } + } + } + + private void OnServerDispatch(object sender, NetworkMessageEventArgs e) + { + try + { + if (e.Message.Type == 0xF7B0) + { + int eventType = (int)e.Message[2]; + if (eventType == 0x1C0) + { + int targetId = (int)e.Message[3]; + object rawHealth = e.Message[4]; + float ratio = 1.0f; + if (rawHealth is float) ratio = (float)rawHealth; + else if (rawHealth is double) ratio = (float)(double)rawHealth; + else if (rawHealth is Single) ratio = (Single)rawHealth; + _healthRatioTracker[targetId] = ratio; + } + else if (eventType == 0xC9) + { + TryExtractVitals(e.Message); + } + } + } + catch { } + } + + private void TryExtractVitals(Decal.Adapter.Message msg) + { + try + { + Decal.Adapter.MessageStruct eventStruct = msg.Struct("event"); + if (eventStruct != null) + { + int health = 0, healthMax = 0; + try { health = eventStruct.Value<int>("health"); } catch { } + try { healthMax = eventStruct.Value<int>("healthMax"); } catch { } + + if (healthMax > 0) + { + int objectId = 0; + try { objectId = eventStruct.Value<int>("object"); } catch { } + if (objectId == 0) objectId = Core.Actions.CurrentSelection; + + if (objectId != 0) + { + _maxHealthTracker[objectId] = healthMax; + if (healthMax > 0) _healthRatioTracker[objectId] = (float)health / (float)healthMax; + return; + } + } + } + } + catch { } + + try + { + int health = 0, healthMax = 0; + try { health = msg.Value<int>("health"); } catch { } + try { healthMax = msg.Value<int>("healthMax"); } catch { } + + if (healthMax > 0) + { + int objectId = Core.Actions.CurrentSelection; + if (objectId != 0) + { + _maxHealthTracker[objectId] = healthMax; + _healthRatioTracker[objectId] = (float)health / (float)healthMax; + return; + } + } + } + catch { } + } + + // ── Drawing Math & Custom Shapes ────────────────────────────────────── + private void DrawIcon(string type, Vector2 pos, Vector4 color, float s) + { + var dl = ImGui.GetWindowDrawList(); + uint col = ImGui.ColorConvertFloat4ToU32(color); + + switch (type) + { + case "gear": + dl.AddCircle(pos + new Vector2(s / 2, s / 2), s / 3.5f, col, 12, 1.5f); + for (int i = 0; i < 8; i++) + { + float a = i * ((float)Math.PI * 2f / 8f); + dl.AddLine(pos + new Vector2(s / 2 + (float)Math.Cos(a) * s / 3, s / 2 + (float)Math.Sin(a) * s / 3), + pos + new Vector2(s / 2 + (float)Math.Cos(a) * s / 2, s / 2 + (float)Math.Sin(a) * s / 2), col, 2f); + } + break; + case "target": + dl.AddCircle(pos + new Vector2(s / 2, s / 2), s / 2.5f, col, 12, 1.5f); + dl.AddLine(pos + new Vector2(s / 2, 0), pos + new Vector2(s / 2, s), col, 1.5f); + dl.AddLine(pos + new Vector2(0, s / 2), pos + new Vector2(s, s / 2), col, 1.5f); + break; + case "wrench": + dl.AddCircle(pos + new Vector2(s * 0.3f, s * 0.3f), s * 0.25f, col, 8, 1.5f); + dl.AddLine(pos + new Vector2(s * 0.4f, s * 0.4f), pos + new Vector2(s * 0.9f, s * 0.9f), col, 2f); + break; + case "map": + dl.AddRect(pos, pos + new Vector2(s, s), col, 1.5f); + dl.AddLine(pos + new Vector2(s / 2, 2), pos + new Vector2(s / 2, s - 2), col, 1.5f); + dl.AddLine(pos + new Vector2(2, s / 2), pos + new Vector2(s - 2, s / 2), col, 1.5f); + break; + case "bag": + dl.AddRectFilled(pos + new Vector2(2, s / 3), pos + new Vector2(s - 2, s), col, 2f); + dl.AddCircle(pos + new Vector2(s / 2, s / 4), s / 5, col, 8, 1.5f); + break; + case "shield": + dl.AddLine(pos + new Vector2(s * 0.2f, 0), pos + new Vector2(s * 0.8f, 0), col, 1.5f); + dl.AddLine(pos + new Vector2(s * 0.8f, 0), pos + new Vector2(s * 0.8f, s * 0.6f), col, 1.5f); + dl.AddLine(pos + new Vector2(s * 0.8f, s * 0.6f), pos + new Vector2(s * 0.5f, s), col, 1.5f); + dl.AddLine(pos + new Vector2(s * 0.5f, s), pos + new Vector2(s * 0.2f, s * 0.6f), col, 1.5f); + dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.6f), pos + new Vector2(s * 0.2f, 0), col, 1.5f); + break; + case "code": + dl.AddLine(pos + new Vector2(s * 0.3f, 2), pos + new Vector2(0, s / 2), col, 1.5f); + dl.AddLine(pos + new Vector2(0, s / 2), pos + new Vector2(s * 0.3f, s - 2), col, 1.5f); + dl.AddLine(pos + new Vector2(s * 0.7f, 2), pos + new Vector2(s, s / 2), col, 1.5f); + dl.AddLine(pos + new Vector2(s, s / 2), pos + new Vector2(s * 0.7f, s - 2), col, 1.5f); + break; + case "heart": + dl.AddCircleFilled(pos + new Vector2(s * 0.3f, s * 0.3f), s * 0.25f, col); + dl.AddCircleFilled(pos + new Vector2(s * 0.7f, s * 0.3f), s * 0.25f, col); + dl.AddTriangleFilled(pos + new Vector2(s * 0.05f, s * 0.4f), pos + new Vector2(s * 0.95f, s * 0.4f), pos + new Vector2(s * 0.5f, s * 0.9f), col); + break; + case "run": + dl.AddCircle(pos + new Vector2(s * 0.5f, s * 0.2f), s * 0.15f, col, 8, 1.5f); + dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.35f), pos + new Vector2(s * 0.5f, s * 0.65f), col, 1.5f); + dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.65f), pos + new Vector2(s * 0.2f, s * 0.9f), col, 1.5f); + dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.65f), pos + new Vector2(s * 0.8f, s * 0.9f), col, 1.5f); + dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.4f), pos + new Vector2(s * 0.8f, s * 0.4f), col, 1.5f); + break; + case "drop": + dl.AddCircleFilled(pos + new Vector2(s * 0.5f, s * 0.7f), s * 0.25f, col); + dl.AddTriangleFilled(pos + new Vector2(s * 0.25f, s * 0.65f), pos + new Vector2(s * 0.75f, s * 0.65f), pos + new Vector2(s * 0.5f, s * 0.1f), col); + break; + case "sword": + dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.7f), pos + new Vector2(s * 0.9f, s * 0.1f), col, 2f); + dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.6f), pos + new Vector2(s * 0.4f, s * 0.8f), col, 2f); + dl.AddLine(pos + new Vector2(s * 0.1f, s * 0.9f), pos + new Vector2(s * 0.3f, s * 0.7f), col, 2f); + break; + case "shoe": + dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.2f), pos + new Vector2(s * 0.3f, s * 0.8f), col, 2f); + dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.8f), pos + new Vector2(s * 0.8f, s * 0.8f), col, 2f); + dl.AddLine(pos + new Vector2(s * 0.8f, s * 0.8f), pos + new Vector2(s * 0.8f, s * 0.6f), col, 2f); + dl.AddLine(pos + new Vector2(s * 0.8f, s * 0.6f), pos + new Vector2(s * 0.5f, s * 0.5f), col, 2f); + dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.5f), pos + new Vector2(s * 0.5f, s * 0.2f), col, 2f); + dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.2f), pos + new Vector2(s * 0.3f, s * 0.2f), col, 2f); + break; + case "buff": + dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.2f), pos + new Vector2(s * 0.5f, s * 0.8f), col, 2f); + dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.5f), pos + new Vector2(s * 0.8f, s * 0.5f), col, 2f); + dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.3f), pos + new Vector2(s * 0.5f, s * 0.1f), col, 1.5f); + dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.1f), pos + new Vector2(s * 0.7f, s * 0.3f), col, 1.5f); + break; + } + } + + private void DrawSquareToggle(string icon, ref bool state, Vector2 pos, string id) + { + var dl = ImGui.GetWindowDrawList(); + float s = 30f; + + Vector4 bgColor = state ? ColBtnOn : ColBarBg; + Vector4 iconColor = state ? ColTeal : ColTextMute; + + dl.AddRectFilled(pos, pos + new Vector2(s, s), ImGui.ColorConvertFloat4ToU32(bgColor), 4f); + if (state) dl.AddRect(pos, pos + new Vector2(s, s), ImGui.ColorConvertFloat4ToU32(ColTeal), 4f, ImDrawFlags.None, 1f); + + DrawIcon(icon, pos + new Vector2(6, 6), iconColor, 18f); + + ImGui.SetCursorScreenPos(pos); + if (ImGui.InvisibleButton($"##{id}", new Vector2(s, s))) + { + state = !state; + OnSettingsChanged?.Invoke(); + } + } + + private void DrawWideToggle(string label, string icon, ref bool state, Vector2 pos, string id, float width, float height) + { + var dl = ImGui.GetWindowDrawList(); + + Vector4 bgColor = state ? ColBtnOn : ColBarBg; + Vector4 iconColor = state ? ColTeal : ColTextMute; + + dl.AddRectFilled(pos, pos + new Vector2(width, height), ImGui.ColorConvertFloat4ToU32(bgColor), 4f); + if (state) dl.AddRect(pos, pos + new Vector2(width, height), ImGui.ColorConvertFloat4ToU32(ColTeal), 4f, ImDrawFlags.None, 1f); + + DrawIcon(icon, pos + new Vector2(4, (height - 12) / 2), iconColor, 12f); + + var textSize = ImGui.CalcTextSize(label); + dl.AddText(pos + new Vector2(18, (height - textSize.Y) / 2), ImGui.ColorConvertFloat4ToU32(state ? ColTeal : ColTextDim), label); + + ImGui.SetCursorScreenPos(pos); + if (ImGui.InvisibleButton($"##{id}", new Vector2(width, height))) + { + state = !state; + OnSettingsChanged?.Invoke(); + } + } + + private Vector4 GetGradientCol(float t) + { + if (t < 0.33f) { float f = t / 0.33f; return new Vector4(1f, f, 0f, 1f); } + else if (t < 0.66f) { float f = (t - 0.33f) / 0.33f; return new Vector4(1f - f, 1f, 0f, 1f); } + else { float f = (t - 0.66f) / 0.34f; return new Vector4(0f, 1f, f, 1f); } + } + + private void DrawSegmentedBar(float pct, float width) + { + var pos = ImGui.GetCursorScreenPos(); + var dl = ImGui.GetWindowDrawList(); + float h = 10f; int segments = 15; float gap = 2f; + float segW = (width - (segments - 1) * gap) / segments; + + for (int i = 0; i < segments; i++) + { + float t = (float)i / (segments - 1); + Vector4 drawCol = (i / (float)segments <= pct) ? GetGradientCol(t) : ColBarBg; + dl.AddRectFilled(pos + new Vector2(i * (segW + gap), 0), pos + new Vector2(i * (segW + gap) + segW, h), ImGui.ColorConvertFloat4ToU32(drawCol), 1f); + } + ImGui.Dummy(new Vector2(width, h + 2)); + } + + private void DrawVitalRow(string icon, string label, float pct, Vector4 color, string valText) + { + float width = ImGui.GetContentRegionAvail().X - 4f; + var pos = ImGui.GetCursorScreenPos(); + var dl = ImGui.GetWindowDrawList(); + float h = 16f; + + dl.AddRectFilled(pos, pos + new Vector2(width, h), ImGui.ColorConvertFloat4ToU32(ColBarBg), 4f); + float safePct = Math.Max(0, Math.Min(1, pct)); + dl.AddRectFilled(pos, pos + new Vector2(width * safePct, h), ImGui.ColorConvertFloat4ToU32(color), 4f); + + DrawIcon(icon, pos + new Vector2(4, 1), ColTextDim, 14f); + string display = $"{label}: {(int)(safePct * 100)}% ({valText})"; + dl.AddText(pos + new Vector2(24, 0), ImGui.ColorConvertFloat4ToU32(new Vector4(1, 1, 1, 1)), display); + + ImGui.Dummy(new Vector2(width, h)); + ImGui.Spacing(); + } + + private static string TruncateName(string s, int max) => s != null && s.Length > max ? s.Substring(0, max - 1) + "..." : (s ?? ""); + + // ── Backend Helpers ─────────────────────────────────────── + public void LoadSelectedNav() + { + if (_selectedNavIdx < 0 || _selectedNavIdx >= NavFiles.Count) return; + string sel = NavFiles[_selectedNavIdx]; + if (sel == "None") { Settings.CurrentNavPath = ""; Settings.CurrentRoute.Points.Clear(); Settings.ActiveNavIndex = 0; } + else + { + string fp = Path.Combine(_navFolder, sel + ".nav"); + Settings.CurrentNavPath = fp; Settings.CurrentRoute = VTankNavParser.Load(fp); + Settings.ActiveNavIndex = (Settings.CurrentRoute.RouteType == NavRouteType.Once || Settings.CurrentRoute.RouteType == NavRouteType.Follow) ? 0 : FindNearestWaypoint(Settings.CurrentRoute); + } + if (RouteTab != null) RouteTab.NeedsRouteGraphicsRefresh = true; OnSettingsChanged?.Invoke(); + } + + private int FindNearestWaypoint(VTankNavParser route) + { + if (route?.Points == null || route.Points.Count == 0) return 0; + try + { + var me = Core.WorldFilter[Core.CharacterFilter.Id]; if (me == null) return 0; + var pos = me.Coordinates(); int best = 0; double bestD = double.MaxValue; + for (int i = 0; i < route.Points.Count; i++) + { + var pt = route.Points[i]; if (pt.Type != NavPointType.Point) continue; + double d = Math.Sqrt(Math.Pow(pt.NS - pos.NorthSouth, 2) + Math.Pow(pt.EW - pos.EastWest, 2)); + if (d < bestD) { bestD = d; best = i; } + } + return best; + } + catch { return 0; } + } + + private bool IsValidEquipment(WorldObject item) + { + if (item.ObjectClass == ObjectClass.MeleeWeapon || + item.ObjectClass == ObjectClass.MissileWeapon || + item.ObjectClass == ObjectClass.WandStaffOrb) return true; + if (item.ObjectClass == ObjectClass.Armor && + (item.Name.IndexOf("Shield", StringComparison.OrdinalIgnoreCase) >= 0 || + item.Name.IndexOf("Defender", StringComparison.OrdinalIgnoreCase) >= 0)) return true; + return false; + } + + private string GetElement(WorldObject item) + { + switch (item.Values(LongValueKey.DamageType, 0)) + { + case 1: return "Slash"; + case 2: return "Pierce"; + case 4: return "Bludgeon"; + case 8: return "Cold"; + case 16: return "Fire"; + case 32: return "Acid"; + case 64: return "Lightning"; + default: return "Slash"; + } + } + + public void RefreshNavFiles() + { + NavFiles.Clear(); NavFiles.Add("None"); _selectedNavIdx = 0; + if (!Directory.Exists(_navFolder)) return; + foreach (var f in Directory.GetFiles(_navFolder, "*.nav")) + { + NavFiles.Add(Path.GetFileNameWithoutExtension(f)); + if (f.Equals(Settings.CurrentNavPath, StringComparison.OrdinalIgnoreCase)) _selectedNavIdx = NavFiles.Count - 1; + } + } + + public void RefreshLootFiles() + { + LootFiles.Clear(); LootFiles.Add("None"); + if (!Directory.Exists(_lootFolder)) return; + foreach (var f in Directory.GetFiles(_lootFolder, "*.utl")) + { + LootFiles.Add(Path.GetFileNameWithoutExtension(f)); + if (f.Equals(Settings.CurrentLootPath, StringComparison.OrdinalIgnoreCase)) Settings.LootProfileIdx = LootFiles.Count - 1; + } + } + + public void RefreshMetaFiles() + { + try + { + MetaFiles.Clear(); MetaFiles.Add("None"); + if (!Directory.Exists(_metaFolder)) Directory.CreateDirectory(_metaFolder); + foreach (var f in Directory.GetFiles(_metaFolder, "*.met")) MetaFiles.Add(Path.GetFileNameWithoutExtension(f)); + } + catch { } + } + + private void RefreshProfilesList() + { + try + { + Profiles.Clear(); + string srv = Core.CharacterFilter.Server ?? "UnknownServer"; + string chr = Core.CharacterFilter.Name ?? "UnknownCharacter"; + string path = Path.Combine(@"C:\Games\DecalPlugins\NexSuite\RynthAi\SettingsProfiles", srv, chr); + Directory.CreateDirectory(path); + foreach (string f in Directory.GetFiles(path, "*.json")) + { + string n = Path.GetFileNameWithoutExtension(f); + if (n.ToLower() != "settings") Profiles.Add(n); + } + if (Profiles.Count == 0) Profiles.Add("Default"); + } + catch { Profiles.Add("Default"); } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/UISettings.cs b/Plugins/RynthAi/UI/UISettings.cs new file mode 100644 index 0000000..0602da7 --- /dev/null +++ b/Plugins/RynthAi/UI/UISettings.cs @@ -0,0 +1,314 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using Newtonsoft.Json; + +namespace NexSuite.Plugins.RynthAi +{ + public class UISettings + { + // Core macro state + public bool IsMacroRunning = false; + public string CurrentState = "Default"; + public bool IsRecordingNav = false; + + // Subsystem Toggles + public bool EnableBuffing = true; + public bool EnableCombat = false; + public bool EnableNavigation = false; + public bool EnableLooting = false; + public bool EnableMeta = false; + public bool EnableRaycasting = true; + + // Movement Mode: 0 = Legacy (SetAutorun/SetClientMotion), + // 1 = Tier1 (CM_Movement direct calls), + // 2 = Tier2 (CPhysicsObj::MoveToPosition — planned), + // 3 = Tier3 (MoveToManager queue — planned) + public int MovementMode = 0; + + // ── Navigation Steering (all modes) ─────────────────────────────── + public float NavStopTurnAngle = 20f; // Stop and turn in place when error > X° + public float NavResumeTurnAngle = 10f; // Resume running when error < X° (must be < StopTurn) + public float NavDeadZone = 4f; // Ignore corrections smaller than X° + public float NavSweepMult = 2.5f; // Closest-approach detect radius = ArrivalYards * this + + // ── Tier 2 Tuning ───────────────────────────────────────────────── + public float T2Speed = 1.0f; // Movement speed multiplier + public float T2DistanceTo = 0.5f; // Stop this far from target (yards) + public float T2ReissueMs = 2000f; // Re-issue MoveToPosition if no progress (ms) + public float T2MaxRangeYd = 500f; // Clamp waypoint distance to this (yards) + public int T2MaxLandblocks = 3; // Skip if target is more than N landblocks away + public float T2WalkWithinYd = 5f; // Walk (not run) when within X yards of waypoint + + // Persistence + public string CurrentNavPath = ""; + public string CurrentLootPath = ""; + public string CurrentMetaPath = ""; + + + // Profile Selection Indices + public int MacroSettingsIdx = 1; + public int NavProfileIdx = 1; + public int LootProfileIdx = 0; + public int MetaProfileIdx = 1; + + // Automation Toggles + public bool EnableAutostack = true; + public bool EnableAutocram = true; + public bool EnableCombineSalvage = true; // If true, combine salvage bags of same material + + // --- Missile Crafting --- + public bool EnableMissileCrafting = false; // Master toggle for auto-crafting ammo from bundles + public int MissileCraftAmmoThreshold = 1000; // Craft when ammo count drops below this + + // --- Loot Timing (ms) — tunable in Advanced Settings → Looting --- + public int LootInterItemDelayMs = 100; // Delay between picking up items + public int LootContentSettleMs = 100; // Wait for corpse contents to populate + public int LootEmptyCorpseMs = 400; // Wait before declaring corpse empty + public int LootClosingDelayMs = 200; // Delay before closing corpse + public int LootAssessWindowMs = 800; // Max time to wait for item ID data + public int LootRetryTimeoutMs = 800; // Retry pickup after this long + public int LootOpenRetryMs = 3000; // Retry opening corpse if no response + + // --- Salvage Timing (ms) — first item / subsequent item --- + public int SalvageOpenDelayFirstMs = 400; // Panel open delay (first item) + public int SalvageOpenDelayFastMs = 50; // Panel open delay (subsequent) + public int SalvageAddDelayFirstMs = 600; // Add item delay (first) + public int SalvageAddDelayFastMs = 50; // Add item delay (subsequent) + public int SalvageSalvageDelayMs = 50; // Click salvage button delay + public int SalvageResultDelayFirstMs = 1000; // Wait for result (first) + public int SalvageResultDelayFastMs = 250; // Wait for result (subsequent) + public bool UseDispelItems = false; + public bool CastDispelSelf = false; + public bool AutoFellowMgmt = false; + public bool MChargesWhenOff = false; + + // Vitals (0-100) + public int HealAt = 60; + public int RestamAt = 30; + public int GetManaAt = 40; + public int TopOffHP = 95; + public int TopOffStam = 95; + public int TopOffMana = 95; + public int HealOthersAt = 50; + public int RestamOthersAt = 10; + public int InfuseOthersAt = 10; + + // Ranges & Misc + public int MonsterRange = 50; + public int RingRange = 5; + public int ApproachRange = 4; + public int MinRingTargets = 4; // Minimum monsters in ring range to use ring spells + public float FollowNavMin = 1.5f; + public double MaxMonRange = 12.0; + public bool SummonPets = false; + public int CustomPetRange = 5; + public int PetMinMonsters = 1; + public bool AdvancedOptions = false; + public bool MineOnly = true; + public bool ShowEditor = false; + public double CorpseApproachRangeMax = 0.04166667; // ~10 yards (10 / 240) + public double CorpseApproachRangeMin = 0.00833333; // ~2 yards (2 / 240) + + // Advanced Toggles + public bool BoostNavPriority = false; + public bool BoostLootPriority = false; + // Loot Ownership: 0=MyKillsOnly (default), 1=FellowshipKills, 2=AllCorpses + public int LootOwnership = 0; + public bool LootOnlyRareCorpses = false; + public bool PeaceModeWhenIdle = true; + public bool RebuffWhenIdle = false; + + // Blacklist Settings (Combat) + public int BlacklistAttempts = 3; // How many failed attacks before blacklisting + public int BlacklistTimeoutSec = 30; // How long a mob stays blacklisted (seconds) + + // Attack Power (0-100 percent, or -1 for auto) + // Auto: 100% power, or 80% if UseRecklessness is enabled and Recklessness is trained + public int MeleeAttackPower = -1; // -1 = auto, 0-100 = manual percent + public int MissileAttackPower = -1; // -1 = auto, 0-100 = manual percent + public bool UseRecklessness = false; // When true + Recklessness trained, auto power = 80% + + // Attack Height: 0=Low (Delete), 1=Medium (End), 2=High (Page Down) + public int MeleeAttackHeight = 1; // Default: Medium + public int MissileAttackHeight = 1; // Default: Medium + + //FPS Limits + public bool EnableFPSLimit = true; + public int TargetFPSFocused = 60; + public int TargetFPSBackground = 30; + + // Data Lists + public List<MonsterRule> MonsterRules = new List<MonsterRule>(); + public List<ItemRule> ItemRules = new List<ItemRule>(); + public List<BuffRule> BuffRules = new List<BuffRule>(); + public List<MetaRule> MetaRules = new List<MetaRule>(); // <--- NEW META LIST + public string LuaScript = "-- Enter your Lua script here\nprint('RynthAi Lua Loaded')"; + public string LuaConsoleOutput = "--- RynthAi Lua Console ---"; + + public string SelectedProfile = "Default"; + public VTankNavParser CurrentRoute = new VTankNavParser(); // Uncomment if you still use this + public int ActiveNavIndex = 0; + + // Advanced Settings Popup + // Inside UISettings.cs + public bool ShowAdvancedWindow = false; // Toggle this with your button + public int SelectedAdvancedTab = 0; // Tracks the left-hand selection + + // Define your tabs in an array for easy rendering + [JsonIgnore] + public readonly string[] AdvancedTabs = { + "Misc", "Recharge", "Melee Combat", "Spell Combat", + "Ranges", "Navigation", "Buffing", "Crafting", "Looting" +}; + + //Refresh state when selected + [JsonIgnore] + public bool ForceStateReset { get; set; } = false; + + public UISettings() + { + // REMOVED EnsureDefaultRule() from here to stop JSON deserialization from duplicating it. + } + + public void EnsureDefaultRule() + { + // Find any existing Default rules + var existingDefaults = MonsterRules.Where(m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)).ToList(); + MonsterRule trueDefault; + + if (existingDefaults.Count > 0) + { + // Keep the first one (it contains your saved weapon settings) + trueDefault = existingDefaults.First(); + // Erase all of them from the list to clean up any duplicates + MonsterRules.RemoveAll(m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + } + else + { + // If it truly doesn't exist, make a brand new one + trueDefault = new MonsterRule { Name = "Default", Priority = 1, DamageType = "Auto", WeaponId = 0 }; + } + + // Insert the one true Default safely at the very top + MonsterRules.Insert(0, trueDefault); + } + } + + public class MonsterRule + { + public string Name { get; set; } = "New Monster"; + public int Priority { get; set; } = 1; + public string DamageType { get; set; } = "Auto"; + public int WeaponId { get; set; } = 0; + + // Debuff Lights (cast on target before attacking) + public bool Fester { get; set; } = false; // F - Festering Curse + public bool Broadside { get; set; } = false; // B - Broadside of a Barn + public bool GravityWell { get; set; } = false; // G - Gravity Well + public bool Imperil { get; set; } = false; // I - Imperil + public bool Yield { get; set; } = false; // Y - Yield + public bool Vuln { get; set; } = false; // V - Vulnerability (element-matched) + + // Spell Type Lights (how to attack) + public bool UseArc { get; set; } = false; // A - Arc spells (war/void) + public bool UseRing { get; set; } = false; // R - Ring spells (uses RingRange) + public bool UseStreak { get; set; } = false; // S - Streak spells (war/void) + public bool UseBolt { get; set; } = true; // B - Bolt spells (default on) + // If none of A/R/S/B are set in magic mode = don't attack (buff bot) + + // Extra Vulnerability element (cast in addition to the V light) + public string ExVuln { get; set; } = "None"; + // Offhand weapon/shield ID (from ItemRules, for dual wield or shield) + public int OffhandId { get; set; } = 0; + // Pet damage element + public string PetDamage { get; set; } = "PAuto"; + } + + public class BuffRule { public string SpellName { get; set; } public int SpellId { get; set; } public bool Enabled { get; set; } = true; } + + public class ItemRule + { + public int Id { get; set; } + public string Name { get; set; } + public string Action { get; set; } = "Loot"; + public string Element { get; set; } = "Slash"; + public bool KeepBuffed { get; set; } = true; + } + + // ==================================================================== + // NEW META SYSTEM MODELS + // ==================================================================== + public enum MetaConditionType + { + Never, + Always, + All, + Any, + ChatMessage, + PackSlots_LE, + SecondsInState_GE, + CharacterDeath, + AnyVendorOpen, + VendorClosed, + InventoryItemCount_LE, + InventoryItemCount_GE, + MonsterNameCountWithinDistance, + MonsterPriorityCountWithinDistance, + NeedToBuff, + NoMonstersWithinDistance, + Landblock_EQ, + Landcell_EQ, + PortalspaceEntered, + PortalspaceExited, + Not, + SecondsInStateP_GE, + TimeLeftOnSpell_GE, + TimeLeftOnSpell_LE, + BurdenPercentage_GE, + DistAnyRoutePT_GE, + Expression, + ChatMessageCapture, + NavrouteEmpty, + MainHealthLE, + MainHealthPHE, + MainManaLE, + MainManaPHE, + MainStamLE + } + + public enum MetaActionType + { + None, + ChatCommand, + SetMetaState, + EmbeddedNavRoute, + All, + CallMetaState, // New + ReturnFromCall, // New + ExpressionAction, // New + ChatExpression, // New + SetWatchdog, // New + ClearWatchdog, // New + GetNTOption, // New + SetNTOption, // New + CreateView, // New + DestroyView, // New + DestroyAllViews // New + } + + public class MetaRule + { + public string State { get; set; } = "Default"; + public MetaConditionType Condition { get; set; } + public string ConditionData { get; set; } = ""; + public MetaActionType Action { get; set; } + public string ActionData { get; set; } = ""; + public List<MetaRule> Children { get; set; } = new List<MetaRule>(); + + // NEW: Temporary flag for the UI. JsonIgnore prevents it from saving to the file. + [JsonIgnore] + public bool HasFired { get; set; } = false; + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/app.config b/Plugins/RynthAi/app.config new file mode 100644 index 0000000..7c6760c --- /dev/null +++ b/Plugins/RynthAi/app.config @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<configuration> + <runtime> + <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> + <dependentAssembly> + <assemblyIdentity name="Decal.Adapter" publicKeyToken="bd1c8ce002ce221e" culture="neutral" /> + <bindingRedirect oldVersion="0.0.0.0-2.9.8.3" newVersion="2.9.8.3" /> + </dependentAssembly> + <dependentAssembly> + <assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> + <bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" /> + </dependentAssembly> + <dependentAssembly> + <assemblyIdentity name="Decal.FileService" publicKeyToken="bd1c8ce002ce221e" culture="neutral" /> + <bindingRedirect oldVersion="0.0.0.0-2.9.8.3" newVersion="2.9.8.3" /> + </dependentAssembly> + </assemblyBinding> + </runtime> +</configuration> \ No newline at end of file diff --git a/Plugins/RynthAi/packages.config b/Plugins/RynthAi/packages.config new file mode 100644 index 0000000..2a81485 --- /dev/null +++ b/Plugins/RynthAi/packages.config @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="KeraLua" version="1.4.9" targetFramework="net48" /> + <package id="Newtonsoft.Json" version="13.0.4" targetFramework="net48" /> + <package id="NLua" version="1.7.8" targetFramework="net48" /> +</packages> \ No newline at end of file diff --git a/Plugins/RynthAi/properties/AssemblyInfo.cs b/Plugins/RynthAi/properties/AssemblyInfo.cs new file mode 100644 index 0000000..b0b49ae --- /dev/null +++ b/Plugins/RynthAi/properties/AssemblyInfo.cs @@ -0,0 +1,16 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("RynthAi")] +[assembly: AssemblyDescription("Combat bot plugin for NexSuite")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("NexSuite")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: ComVisible(false)] +[assembly: Guid("33333333-3333-3333-3333-333333333333")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Plugins/RynthCore.Plugin.RynthAi/Nav/VTankNavParser.cs b/Plugins/RynthCore.Plugin.RynthAi/Nav/VTankNavParser.cs new file mode 100644 index 0000000..2800a97 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Nav/VTankNavParser.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; + +namespace RynthCore.Plugin.RynthAi.Nav; + +public enum NavRouteType +{ + Once = 4, + Circular = 1, + Linear = 2, + Follow = 3 +} + +public enum NavPointType +{ + Point = 0, + Recall = 2, + Pause = 3, + Chat = 4, + PortalNPC = 6 +} + +public class NavPoint +{ + public NavPointType Type { get; set; } + public double NS { get; set; } + public double EW { get; set; } + public double Z { get; set; } + + public int SpellId { get; set; } + public int PauseTimeMs { get; set; } + public string ChatCommand { get; set; } = ""; + public string TargetName { get; set; } = ""; + public int ObjectClass { get; set; } + public bool IsTie { get; set; } + + public double PortalExitNS { get; set; } + public double PortalExitEW { get; set; } + public double PortalExitZ { get; set; } + public double PortalLandNS { get; set; } + public double PortalLandEW { get; set; } + public double PortalLandZ { get; set; } + + public override string ToString() + { + return Type switch + { + NavPointType.Point => $"[Point] {NS:F3}, {EW:F3}", + NavPointType.Recall => $"[Recall] spell {SpellId}", + NavPointType.Pause => $"[Pause] {PauseTimeMs / 1000.0}s", + NavPointType.Chat => $"[Chat] {ChatCommand}", + NavPointType.PortalNPC => $"[Portal] {TargetName}", + _ => $"[Unknown] {Type}" + }; + } +} + +public class VTankNavParser +{ + public NavRouteType RouteType { get; set; } + public List<NavPoint> Points { get; set; } = new(); + + public static VTankNavParser Load(string filePath) + { + var route = new VTankNavParser(); + string[] lines = File.ReadAllLines(filePath); + + if (lines.Length < 3) return route; + if (!lines[0].Contains("uTank2 NAV 1.2")) + return route; + + route.RouteType = (NavRouteType)int.Parse(lines[1]); + int pointCount = int.Parse(lines[2]); + + int idx = 3; + for (int i = 0; i < pointCount && idx < lines.Length; i++) + { + var pt = new NavPoint(); + pt.Type = (NavPointType)int.Parse(lines[idx++]); + pt.EW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.NS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.Z = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + idx++; // spacer + + switch (pt.Type) + { + case NavPointType.Point: break; + case NavPointType.Recall: pt.SpellId = int.Parse(lines[idx++]); break; + case NavPointType.Pause: pt.PauseTimeMs = int.Parse(lines[idx++]); break; + case NavPointType.Chat: pt.ChatCommand = lines[idx++]; break; + case NavPointType.PortalNPC: + pt.TargetName = lines[idx++]; + pt.ObjectClass = int.Parse(lines[idx++]); + pt.IsTie = bool.Parse(lines[idx++]); + pt.PortalExitEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalExitNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalExitZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + idx++; // spacer + pt.PortalLandEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalLandNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalLandZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + idx++; // spacer + break; + } + + route.Points.Add(pt); + } + + return route; + } + + public void Save(string filePath) + { + using var writer = new StreamWriter(filePath, false); + writer.WriteLine("uTank2 NAV 1.2"); + writer.WriteLine((int)RouteType); + writer.WriteLine(Points.Count); + + foreach (var pt in Points) + { + writer.WriteLine((int)pt.Type); + writer.WriteLine(pt.EW.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.NS.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.Z.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + + switch (pt.Type) + { + case NavPointType.Recall: writer.WriteLine(pt.SpellId); break; + case NavPointType.Pause: writer.WriteLine(pt.PauseTimeMs); break; + case NavPointType.Chat: writer.WriteLine(pt.ChatCommand); break; + case NavPointType.PortalNPC: + writer.WriteLine(pt.TargetName); + writer.WriteLine(pt.ObjectClass); + writer.WriteLine(pt.IsTie.ToString()); + writer.WriteLine(pt.PortalExitEW.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalExitNS.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalExitZ.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + writer.WriteLine(pt.PortalLandEW.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalLandNS.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalLandZ.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + break; + } + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs new file mode 100644 index 0000000..b06b189 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -0,0 +1,95 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +public static unsafe class PluginExports +{ + private static readonly RynthPluginRuntime<RynthAiPlugin> Runtime = new(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Shutdown() => Runtime.Shutdown(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr Name() => RynthAiPlugin.NamePointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr Version() => RynthAiPlugin.VersionPointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUIInitialized", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUIInitialized() => Runtime.OnUIInitialized(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBusyCountIncremented", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnBusyCountIncremented() => Runtime.OnBusyCountIncremented(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBusyCountDecremented", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnBusyCountDecremented() => Runtime.OnBusyCountDecremented(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLoginComplete() => Runtime.OnLoginComplete(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBarAction", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnBarAction() => Runtime.OnBarAction(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Tick() => Runtime.OnTick(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Render() => Runtime.OnRender(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => + Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => + Runtime.OnChatBarEnter(textUtf16, eatFlag); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSelectedTargetChange", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnSelectedTargetChange(uint currentTargetId, uint previousTargetId) => + Runtime.OnSelectedTargetChange(currentTargetId, previousTargetId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatModeChange", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnCombatModeChange(int currentCombatMode, int previousCombatMode) => + Runtime.OnCombatModeChange(currentCombatMode, previousCombatMode); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSmartBoxEvent", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnSmartBoxEvent(uint opcode, uint blobSize, uint status) => + Runtime.OnSmartBoxEvent(opcode, blobSize, status); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUpdateObject(uint objectId) => Runtime.OnUpdateObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObjectInventory", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUpdateObjectInventory(uint objectId) => Runtime.OnUpdateObjectInventory(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnViewObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnViewObjectContents(uint objectId) => Runtime.OnViewObjectContents(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnStopViewingObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnStopViewingObjectContents(uint objectId) => Runtime.OnStopViewingObjectContents(objectId); + + [UnmanagedCallersOnly(EntryPoint = "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 = "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/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs new file mode 100644 index 0000000..7212a2d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -0,0 +1,429 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using RynthCore.Plugin.RynthAi.Nav; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +public sealed unsafe class RynthAiPlugin : RynthPluginBase +{ + internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthAi"); + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0"); + + private const float NavPointElevationOffset = 0.5f; + private const float UnitsPerCoord = 240.0f; + private const int RingSegments = 32; + private const float RingRadius = 3.0f; // game units (~1.25 yards) + + // ImGui colors (ABGR format for ImGui native) + private const uint ColorCyan = 0xFFFFFF00; // nav point rings + private const uint ColorRed = 0xFF2222FF; // active waypoint ring + private const uint ColorBlueLine = 0xFFFF8800; // lines between points + + private static RynthCoreApiNative _api; + private static RynthCoreHost _host; + private static bool _initialized; + private static bool _loginComplete; + private static bool _windowVisible; + private static bool _showRoute = true; + + // Route state + private static VTankNavParser? _currentRoute; + private static string _currentNavPath = ""; + private static int _activeNavIndex; + private static readonly string _navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles"; + + // Nav file browser state + private static string[] _navFiles = Array.Empty<string>(); + + // Cached cimgui function pointers + private static delegate* unmanaged[Cdecl]<IntPtr, void> _igSetCurrentContext; + private static delegate* unmanaged[Cdecl]<ImVec2, int, ImVec2, void> _igSetNextWindowPos; + private static delegate* unmanaged[Cdecl]<ImVec2, int, void> _igSetNextWindowSize; + private static delegate* unmanaged[Cdecl]<IntPtr, IntPtr, int, byte> _igBegin; + private static delegate* unmanaged[Cdecl]<void> _igEnd; + private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, byte> _igButton; + private static delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void> _igTextUnformatted; + private static delegate* unmanaged[Cdecl]<void> _igSeparator; + private static delegate* unmanaged[Cdecl]<IntPtr, byte*, byte> _igCheckbox; + private static delegate* unmanaged[Cdecl]<IntPtr> _igGetForegroundDrawList; + // ImDrawList_AddCircle(self, center, radius, col, num_segments, thickness) + private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, float, void> _igDrawListAddCircle; + // ImDrawList_AddLine(self, p1, p2, col, thickness) + private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, ImVec2, uint, float, void> _igDrawListAddLine; + // ImDrawList_AddCircleFilled(self, center, radius, col, num_segments) + private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, void> _igDrawListAddCircleFilled; + private static bool _imguiBound; + + public override int Initialize() + { + _api = Api; + _host = Host; + + if (_api.ImGuiContext == IntPtr.Zero) + return 11; + + if (!TryBindImGui(out string error)) + { + Log($"RynthAi: failed to bind cimgui ({error})"); + return 12; + } + + _initialized = true; + _loginComplete = false; + _windowVisible = false; + _showRoute = true; + _currentRoute = null; + _currentNavPath = ""; + _activeNavIndex = 0; + + RefreshNavFiles(); + Log("RynthAi: initialized."); + return 0; + } + + public override void Shutdown() + { + Log("RynthAi: shutting down."); + _initialized = false; + _loginComplete = false; + _currentRoute = null; + } + + public override void OnLoginComplete() + { + if (!_initialized) return; + _loginComplete = true; + } + + public override void OnBarAction() + { + if (!_initialized || !_loginComplete) return; + _windowVisible = !_windowVisible; + } + + public override void OnRender() + { + if (!_initialized || !_loginComplete || !_imguiBound || _api.ImGuiContext == IntPtr.Zero) + return; + + _igSetCurrentContext(_api.ImGuiContext); + + // Draw the 3D nav route overlay (always, even if UI window is hidden) + if (_showRoute && _currentRoute != null && _currentRoute.Points.Count > 0) + RenderNavRoute(); + + // Draw the UI panel + if (_windowVisible) + RenderNavPanel(); + } + + // ─── Precomputed ring geometry (unit circle on ground plane) ──────── + + private static readonly float[] _cosTable = new float[RingSegments]; + private static readonly float[] _sinTable = new float[RingSegments]; + private static bool _trigReady; + + private static void EnsureTrigTables() + { + if (_trigReady) return; + for (int i = 0; i < RingSegments; i++) + { + double angle = 2.0 * Math.PI * i / RingSegments; + _cosTable[i] = (float)Math.Cos(angle); + _sinTable[i] = (float)Math.Sin(angle); + } + _trigReady = true; + } + + // ─── 3D Nav Route Rendering ────────────────────────────────────────── + + private static void RenderNavRoute() + { + if (!_host.HasWorldToScreen || !_host.HasGetPlayerPose || !_host.HasGetCurCoords) + return; + + if (!_host.TryGetPlayerPose(out uint cell, out float px, out float py, out float pz, + out float _, out float _, out float _, out float _)) + return; + + if (!_host.TryGetCurCoords(out double playerNS, out double playerEW)) + return; + + IntPtr drawList = _igGetForegroundDrawList(); + if (drawList == IntPtr.Zero) + return; + + EnsureTrigTables(); + + var route = _currentRoute!; + int count = route.Points.Count; + + // Project center of each nav point for line drawing + Span<float> centerSx = stackalloc float[count]; + Span<float> centerSy = stackalloc float[count]; + Span<bool> centerOnScreen = stackalloc bool[count]; + + for (int i = 0; i < count; i++) + { + var pt = route.Points[i]; + float wx = px + (float)((pt.EW - playerEW) * UnitsPerCoord); + float wy = py + (float)((pt.NS - playerNS) * UnitsPerCoord); + float wz = (float)pt.Z + NavPointElevationOffset; + + centerOnScreen[i] = _host.WorldToScreen(wx, wy, wz, out centerSx[i], out centerSy[i]); + } + + // Draw lines between consecutive waypoints + for (int i = 0; i < count; i++) + { + int nextIdx = i + 1; + if (nextIdx >= count) + { + if (route.RouteType == NavRouteType.Circular) + nextIdx = 0; + else + continue; + } + + if (!centerOnScreen[i] && !centerOnScreen[nextIdx]) + continue; + + _igDrawListAddLine( + drawList, + new ImVec2(centerSx[i], centerSy[i]), + new ImVec2(centerSx[nextIdx], centerSy[nextIdx]), + ColorBlueLine, + 2.0f); + } + + // Draw 3D rings on the ground at each waypoint + // Each ring is a circle of world-space points projected to screen space + Span<float> ringSx = stackalloc float[RingSegments]; + Span<float> ringSy = stackalloc float[RingSegments]; + Span<bool> ringVis = stackalloc bool[RingSegments]; + + for (int i = 0; i < count; i++) + { + var pt = route.Points[i]; + float cx = px + (float)((pt.EW - playerEW) * UnitsPerCoord); + float cy = py + (float)((pt.NS - playerNS) * UnitsPerCoord); + float cz = (float)pt.Z + NavPointElevationOffset; + + // Project each vertex of the ring (lying flat on the ground plane) + int visCount = 0; + for (int s = 0; s < RingSegments; s++) + { + float wx = cx + _cosTable[s] * RingRadius; + float wy = cy + _sinTable[s] * RingRadius; + + ringVis[s] = _host.WorldToScreen(wx, wy, cz, out ringSx[s], out ringSy[s]); + if (ringVis[s]) visCount++; + } + + // Skip if no part of the ring is visible + if (visCount == 0) + continue; + + uint color = (i == _activeNavIndex) ? ColorRed : ColorCyan; + float thickness = (i == _activeNavIndex) ? 3.0f : 2.0f; + + // Draw the ring as connected line segments + for (int s = 0; s < RingSegments; s++) + { + int next = (s + 1) % RingSegments; + + // Draw segment if at least one end projected successfully + if (ringVis[s] || ringVis[next]) + { + _igDrawListAddLine( + drawList, + new ImVec2(ringSx[s], ringSy[s]), + new ImVec2(ringSx[next], ringSy[next]), + color, + thickness); + } + } + } + } + + // ─── Nav Control Panel ─────────────────────────────────────────────── + + private static void RenderNavPanel() + { + _igSetNextWindowPos(new ImVec2(48f, 140f), 1 << 2 /* ImGuiCond_FirstUseEver */, default); + _igSetNextWindowSize(new ImVec2(380f, 320f), 1 << 2); + + bool open = _igBegin( + Marshal.StringToHGlobalAnsi("RynthAi Nav##RynthAiNav"), + IntPtr.Zero, + 0) != 0; + + if (open) + { + // Show route toggle + byte showByte = _showRoute ? (byte)1 : (byte)0; + if (_igCheckbox(Marshal.StringToHGlobalAnsi("Show Route"), &showByte) != 0) + _showRoute = showByte != 0; + + _igSeparator(); + + // Current route info + string info = _currentRoute != null + ? $"Route: {Path.GetFileName(_currentNavPath)} ({_currentRoute.Points.Count} pts, {_currentRoute.RouteType})" + : "No route loaded"; + TextTemp(info); + + if (_currentRoute != null) + TextTemp($"Active waypoint: {_activeNavIndex}"); + + _igSeparator(); + + // Nav file list + TextTemp("Nav Files:"); + + for (int i = 0; i < _navFiles.Length; i++) + { + string fileName = Path.GetFileName(_navFiles[i]); + bool isCurrent = string.Equals(_navFiles[i], _currentNavPath, StringComparison.OrdinalIgnoreCase); + string label = isCurrent ? $">> {fileName}" : $" {fileName}"; + + IntPtr labelPtr = Marshal.StringToHGlobalAnsi($"{label}##{i}"); + try + { + if (_igButton(labelPtr, new ImVec2(340f, 0f)) != 0) + { + LoadNavFile(_navFiles[i]); + } + } + finally + { + Marshal.FreeHGlobal(labelPtr); + } + } + + _igSeparator(); + + if (_igButton(Marshal.StringToHGlobalAnsi("Refresh Files"), default) != 0) + RefreshNavFiles(); + } + + _igEnd(); + } + + // ─── Nav File Management ───────────────────────────────────────────── + + private static void RefreshNavFiles() + { + try + { + if (Directory.Exists(_navFolder)) + _navFiles = Directory.GetFiles(_navFolder, "*.nav"); + else + _navFiles = Array.Empty<string>(); + } + catch + { + _navFiles = Array.Empty<string>(); + } + } + + private static void LoadNavFile(string path) + { + try + { + _currentRoute = VTankNavParser.Load(path); + _currentNavPath = path; + _activeNavIndex = 0; + _host.Log($"RynthAi: Loaded route '{Path.GetFileName(path)}' with {_currentRoute.Points.Count} points"); + } + catch (Exception ex) + { + _host.Log($"RynthAi: Failed to load nav file: {ex.Message}"); + } + } + + // ─── ImGui Helpers ─────────────────────────────────────────────────── + + private static void TextTemp(string text) + { + IntPtr ptr = Marshal.StringToHGlobalAnsi(text); + try { _igTextUnformatted(ptr, IntPtr.Zero); } + finally { Marshal.FreeHGlobal(ptr); } + } + + private static bool TryBindImGui(out string error) + { + if (_imguiBound) { error = ""; return true; } + + IntPtr mod = GetModuleHandleA("RynthCore.cimgui.dll"); + if (mod == IntPtr.Zero) mod = GetModuleHandleA("cimgui.dll"); + if (mod == IntPtr.Zero) { error = "no cimgui module"; return false; } + + if (!TryGetProc(mod, "igSetCurrentContext", out IntPtr p)) { error = "missing igSetCurrentContext"; return false; } + _igSetCurrentContext = (delegate* unmanaged[Cdecl]<IntPtr, void>)p; + + if (!TryGetProc(mod, "igSetNextWindowPos", out p)) { error = "missing igSetNextWindowPos"; return false; } + _igSetNextWindowPos = (delegate* unmanaged[Cdecl]<ImVec2, int, ImVec2, void>)p; + + if (!TryGetProc(mod, "igSetNextWindowSize", out p)) { error = "missing igSetNextWindowSize"; return false; } + _igSetNextWindowSize = (delegate* unmanaged[Cdecl]<ImVec2, int, void>)p; + + if (!TryGetProc(mod, "igBegin", out p)) { error = "missing igBegin"; return false; } + _igBegin = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, int, byte>)p; + + if (!TryGetProc(mod, "igEnd", out p)) { error = "missing igEnd"; return false; } + _igEnd = (delegate* unmanaged[Cdecl]<void>)p; + + if (!TryGetProc(mod, "igButton", out p)) { error = "missing igButton"; return false; } + _igButton = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, byte>)p; + + if (!TryGetProc(mod, "igTextUnformatted", out p)) { error = "missing igTextUnformatted"; return false; } + _igTextUnformatted = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)p; + + if (!TryGetProc(mod, "igSeparator", out p)) { error = "missing igSeparator"; return false; } + _igSeparator = (delegate* unmanaged[Cdecl]<void>)p; + + if (!TryGetProc(mod, "igCheckbox", out p)) { error = "missing igCheckbox"; return false; } + _igCheckbox = (delegate* unmanaged[Cdecl]<IntPtr, byte*, byte>)p; + + if (!TryGetProc(mod, "igGetForegroundDrawList_Nil", out p)) { error = "missing igGetForegroundDrawList"; return false; } + _igGetForegroundDrawList = (delegate* unmanaged[Cdecl]<IntPtr>)p; + + if (!TryGetProc(mod, "ImDrawList_AddCircle", out p)) { error = "missing ImDrawList_AddCircle"; return false; } + _igDrawListAddCircle = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, float, void>)p; + + if (!TryGetProc(mod, "ImDrawList_AddLine", out p)) { error = "missing ImDrawList_AddLine"; return false; } + _igDrawListAddLine = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, ImVec2, uint, float, void>)p; + + if (!TryGetProc(mod, "ImDrawList_AddCircleFilled", out p)) { error = "missing ImDrawList_AddCircleFilled"; return false; } + _igDrawListAddCircleFilled = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, void>)p; + + _imguiBound = true; + error = ""; + return true; + } + + private static bool TryGetProc(IntPtr module, string exportName, out IntPtr address) + { + address = GetProcAddress(module, exportName); + return address != IntPtr.Zero; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] + private static extern IntPtr GetModuleHandleA(string lpModuleName); + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] + private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); + + [StructLayout(LayoutKind.Sequential)] + private readonly struct ImVec2 + { + public readonly float X; + public readonly float Y; + public ImVec2(float x, float y) { X = x; Y = y; } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj new file mode 100644 index 0000000..d18b071 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -0,0 +1,57 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>net10.0-windows</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <RuntimeIdentifier>win-x86</RuntimeIdentifier> + <OutputType>Library</OutputType> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <Nullable>enable</Nullable> + <PublishAot>true</PublishAot> + <NativeLib>Shared</NativeLib> + <InvariantGlobalization>true</InvariantGlobalization> + <IlcOptimizationPreference>Size</IlcOptimizationPreference> + <StripSymbols>false</StripSymbols> + <RootNamespace>RynthCore.Plugin.RynthAi</RootNamespace> + <AssemblyName>RynthCore.Plugin.RynthAi</AssemblyName> + <Platforms>x86</Platforms> + </PropertyGroup> + + <ItemGroup> + <ProjectReference Include="..\..\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" /> + <ProjectReference Include="..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" /> + </ItemGroup> + + <Target Name="CopyPublishedPluginToEngineOutputs" AfterTargets="Publish" Condition="'$(PublishDir)' != ''"> + <ItemGroup> + <_EnginePluginDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(Configuration)\net10.0-windows\win-x86\Plugins\" /> + <_EnginePluginDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(PlatformTarget)\$(Configuration)\net10.0-windows\win-x86\Plugins\" /> + <_EnginePluginPublishDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(Configuration)\net10.0-windows\win-x86\publish\Plugins\" /> + <_EnginePluginPublishDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(PlatformTarget)\$(Configuration)\net10.0-windows\win-x86\publish\Plugins\" /> + </ItemGroup> + + <MakeDir Directories="@(_EnginePluginDir)" /> + <MakeDir Directories="@(_EnginePluginPublishDir)" /> + <Copy + SourceFiles="$(PublishDir)$(AssemblyName).dll" + DestinationFolder="%(_EnginePluginDir.Identity)" + SkipUnchangedFiles="true" + Condition="Exists('$(PublishDir)$(AssemblyName).dll')" /> + <Copy + SourceFiles="$(PublishDir)$(AssemblyName).pdb" + DestinationFolder="%(_EnginePluginDir.Identity)" + SkipUnchangedFiles="true" + Condition="Exists('$(PublishDir)$(AssemblyName).pdb')" /> + <Copy + SourceFiles="$(PublishDir)$(AssemblyName).dll" + DestinationFolder="%(_EnginePluginPublishDir.Identity)" + SkipUnchangedFiles="true" + Condition="Exists('$(PublishDir)$(AssemblyName).dll')" /> + <Copy + SourceFiles="$(PublishDir)$(AssemblyName).pdb" + DestinationFolder="%(_EnginePluginPublishDir.Identity)" + SkipUnchangedFiles="true" + Condition="Exists('$(PublishDir)$(AssemblyName).pdb')" /> + </Target> + +</Project> diff --git a/RynthCore.sln b/RynthCore.sln index 971bb41..e450961 100644 --- a/RynthCore.sln +++ b/RynthCore.sln @@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Engine", "src\Ryn EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Injector", "src\RynthCore.Injector\RynthCore.Injector.csproj", "{A1B2C3D4-0002-0002-0002-000000000002}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.DesktopLog", "src\RynthCore.DesktopLog\RynthCore.DesktopLog.csproj", "{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Loader", "src\RynthCore.Loader\RynthCore.Loader.csproj", "{A1B2C3D4-0006-0006-0006-000000000006}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" @@ -63,6 +65,18 @@ Global {A1B2C3D4-0002-0002-0002-000000000002}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.ActiveCfg = Release|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.Build.0 = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x86.ActiveCfg = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x86.Build.0 = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x64.ActiveCfg = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x64.Build.0 = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x86.ActiveCfg = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x86.Build.0 = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|Any CPU.Build.0 = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x64.ActiveCfg = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x64.Build.0 = Release|Any CPU {A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.ActiveCfg = Debug|x86 {A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.Build.0 = Debug|x86 {A1B2C3D4-0006-0006-0006-000000000006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -179,6 +193,7 @@ Global {2B283E05-12BB-45F9-B8E5-8F53C1FAB737} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {BB0C5CB5-6C75-4C17-9348-5CA0C481B65C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {A72E31D3-5D91-4C39-A30C-A96A492BBE82} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {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} diff --git a/docs/ACCLIENT_HOOK_INVENTORY.md b/docs/ACCLIENT_HOOK_INVENTORY.md new file mode 100644 index 0000000..0251747 --- /dev/null +++ b/docs/ACCLIENT_HOOK_INVENTORY.md @@ -0,0 +1,91 @@ +# ACClient Hook Inventory + +This file tracks RynthCore hook targets against the user's real AC client binary, with the AC client decompile used for semantics and the live binary used as the source of truth for hook placement. + +## Client Fingerprint + +- Path: `C:\Turbine\Asheron's Call\acclient.exe` +- File size: `4,841,472` bytes +- SHA256: `BCA95BBEBED4B9ED1FF09D0DA83144E2FC4208F63AD7ADA5CB47C3CA207CCBA9` +- PE machine: `0x014C` (`x86`) +- PE image size: `0x0056D000` + +## Rules For This Inventory + +- Use the decompile to understand semantics, call order, and callback behavior. +- Use the live `acclient.exe` to derive patterns, validate uniqueness, and choose the real hook address. +- Do not ship fixed RVAs from the decompile unless they have been validated against the live binary. +- Prefer hooking the AC client function that already implements the desired behavior over lower-level memory access. +- Every production hook should eventually have: + - a primary binary pattern + - at least one fallback pattern or alternate seam when practical + - runtime validation + - an explicit unsupported-state log/UI message + +## Priority Inventory + +### Lifecycle And UI + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnLoginComplete` | `CPlayerSystem::SendLoginCompleteNotification` in `CPlayerSystem.cpp:4017-4031` | Pattern-scan the containing function using the unique `SetDisplayInventory(1)` plus `BroadcastGlobalMessage(..., 0xB, 0)` sequence, then hook the containing `thiscall` function. | Live in RynthCore | P0 | +| `OnUIInitialized` | `ClientUISystem::OnStartup` in `ClientUISystem.cpp:48` and `APIManager::SetUIReady(1)` in `APIManager.cpp:134` | Hook the tiny `OnStartup -> SetUIReady(1)` wrapper or the `SetUIReady(1)` transition path. Prefer the wrapper if the pattern is unique in the live binary. | Not implemented | P0 | +| `OnBusyCountIncremented` | `ClientUISystem::IncrementBusyCount` in `ClientUISystem.cpp:630` | Hook the wrapper that increments `m_cBusy` and updates cursor state when crossing `0 -> 1`. | Not implemented | P1 | +| `OnBusyCountDecremented` | `ClientUISystem::DecrementBusyCount` in `ClientUISystem.cpp:641` | Hook the wrapper that decrements `m_cBusy` and updates cursor state when crossing `1 -> 0`. | Not implemented | P1 | + +### Chat And Command + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnChatWindowText` | `ClientSystem.cpp:108` | Hook the function that allocates a BSTR from `i_text`, calls `GetACPlugin()->OnChatWindowText`, then checks `bEat` before continuing UI output. | Ready for binary patterning | P0 | +| `OnChatBarEnter` | `ClientCommunicationSystem.cpp:14407` | Hook the function that allocates a BSTR from the entered line, calls `GetACPlugin()->OnChatBarEnter`, and returns early when the plugin consumes the line. | Ready for binary patterning | P0 | + +### World, Target, And Object Flow + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnDeleteObject` | `ACCObjectMaint::DeleteObject` in `ACCObjectMaint.cpp:73-85` | Hook the clean wrapper that checks `APIIsReady`, calls `OnDeleteObject`, then calls `ACCWeenieObject::SetCorpseDeleted` and `CObjectMaint::DeleteObject`. | Ready for binary patterning | P0 | +| `OnSelectedTargetChange` | `ACCWeenieObject.cpp:710` and `ACCWeenieObject.cpp:1997` | Hook the selected-target setter path after `CM_UI::SendNotice_SelectionChanged` and before the direct plugin callback. | Ready for binary patterning | P0 | +| World/object dispatch | `ACSmartBox::DispatchSmartBoxEvent` in `ACSmartBox.cpp:37-171` | Hook the SmartBox dispatch seam as the high-value world/object/network filter layer. This is the likely replacement for many WorldFilter-style surfaces. | Ready for binary patterning | P0 | +| Object creation | `ACCObjectMaint::CreateObject` in `ACCObjectMaint.cpp:196` | Hook the object creation wrapper for higher-level object lifecycle callbacks when we need richer data than a raw SmartBox event. | Ready for binary patterning | P1 | +| Object inventory updates | `ACCObjectMaint::UpdateObjectInventory` in `ACCObjectMaint.cpp:377` | Hook the inventory update path for container/item-change compatibility events. | Ready for binary patterning | P1 | +| Update/create/delete server dispatch | `CM_Physics::DispatchSB_CreateObject`, `DispatchSB_UpdateObject`, `DispatchSB_DeleteObject` in `CM_Physics.cpp` | Use as fallback seams if the outer SmartBox dispatcher proves too broad or unstable. | Decompile-confirmed | P1 | + +### Combat And Trade + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnCombatModeChange` | `ClientCombatSystem.cpp:1564` | Hook the branch that invokes the plugin callback after the combat mode change resolves and auto-targeting logic runs. | Ready for binary patterning | P1 | +| Trade window opened | `ClientTradeSystem.cpp:525` | Hook `Handle_Trade__Recv_RegisterTrade` after `CM_Trade::SendNotice_RegisterTrade` and before the internal attempt-to-trade follow-up. | Ready for binary patterning | P1 | +| Trade item added | `ClientTradeSystem::Handle_Trade__Recv_AddToTrade` in `ClientTradeSystem.cpp:560+` | Hook the direct wrapper that calls `CM_Trade::SendNotice_AddItemToTrade` and then `OnTradeWindowItemAdded`. | Ready for binary patterning | P1 | +| Trade completed | `ClientCommunicationSystem.cpp:3106` | Hook the message-switch case for `0x529` (`Trade Complete!`) that directly invokes `OnTradeCompleted`. | Ready for binary patterning | P1 | +| Trade accept/decline/close/clear | `ClientTradeSystem.cpp` | Hook the direct trade-system wrappers that invoke the corresponding plugin callback. | Decompiled seam confirmed, binary anchor still needed | P1 | + +## Host Call Surface To Expose Through RynthCore + +These are not plugin callback hooks, but they are part of the host API surface we should expose once the callback layer is in place. + +| API surface | Decompiled seam | Notes | Priority | +| --- | --- | --- | --- | +| `WriteToChat` | `APIManager__IAsheronsCallImpl.cpp` | Safe early host helper. | P0 | +| Selection get/set | `APIManager__IAsheronsCallImpl.cpp` | Pairs naturally with target-change callbacks. | P0 | +| `UseObject`, `UseObjectOn`, `UseEquippedItem` | `APIManager__IAsheronsCallImpl.cpp` | Good interaction helpers once lifecycle is stable. | P1 | +| `MoveItemExternal`, `MoveItemInternal` | `APIManager__IAsheronsCallImpl.cpp` | Useful once inventory callbacks exist. | P1 | +| `IsStandingStill`, `StopCompletely`, `TurnToHeading`, `SetAutoRun` | `APIManager__IAsheronsCallImpl.cpp` | Movement helper layer. Some of this already overlaps with existing RynthCore action hooks. | P0 | +| `GetCurCoords`, `GetPlayerID`, `GetGroundContainerID` | `APIManager__IAsheronsCallImpl.cpp` | Good basic state helpers. | P0 | +| `GetScreenDimensions`, `ItemIsKnown`, `GetItemName` | `APIManager__IAsheronsCallImpl.cpp` | Low-risk host helpers. | P1 | +| `IssueChatBarCommand` | `APIManager__IAsheronsCallImpl.cpp` | Treat as stub-like until runtime behavior is validated against the live client. | Hold | +| `GetCombatMode`, `GetBusyCount`, salvage panel APIs | `APIManager__IAsheronsCallImpl_vtbl.cpp` | Declared but not yet fully validated in the split. | Hold | + +## Implementation Waves + +1. Finish lifecycle/UI: `OnLoginComplete`, `OnUIInitialized`, busy count. +2. Add chat interception: `OnChatWindowText`, `OnChatBarEnter`. +3. Add world/object seams: SmartBox dispatch, delete/create/inventory, selected target. +4. Add combat/trade callbacks. +5. Expose the confirmed `IAsheronsCall` subset through RynthCore-native host APIs. + +## Notes + +- The split decompile is still very useful, but the login-complete work already showed that its function RVAs do not always line up with the user's live client binary. +- For this reason, future hook work should be tracked here first against the fingerprint above, then implemented in RynthCore with pattern scanning rather than fixed addresses. diff --git a/docs/ub-hub-merge-playbook.md b/docs/ub-hub-merge-playbook.md new file mode 100644 index 0000000..780b48e --- /dev/null +++ b/docs/ub-hub-merge-playbook.md @@ -0,0 +1,117 @@ +# UB Hub → RynthCore / RynthSuite — Implementation Playbook + +**Audience:** George Blankenship +**Purpose:** Working checklist for the ILT Hub merge — what landed, what is still open. Assessment detail lives in the Cursor project store (`ub-hub-merge-plan.md`, `repo-remote-sync.md`). +**Hub code lives in RynthSuite** (`feat/ilt-hub`). This Core copy is tracking only. +**Repo tracking homes (keep uniform):** +- Suite: `Docs/ub-hub-merge-playbook.md` on **`feat/ilt-hub`** and **`SK-local`** +- Core: `docs/ub-hub-merge-playbook.md` on **`SK-local`** (Core has no `feat/ilt-hub`) +Do **not** put the playbook only on a docs-only PR branch — keep it with the Hub / SK worktrees. +**This doc does not implement more product code.** + +--- + +## Status (2026-10-04) + +| Track | State | +|-------|--------| +| Assessment + playbook | **Done** — plan + this playbook (Pet: SummonPets mechanics + breeding) | +| Remotes / aelrynth overlay | **Done on `main`** — Core [#1](https://github.com/BlankenshipG/RynthCore/pull/1), Suite [#1](https://github.com/BlankenshipG/RynthSuite/pull/1) | +| ILT Hub P0–P2 | **On Suite `feat/ilt-hub`** — `ad61194` (0.5.1 Hub) + `18b4579` (0.5.2 diagnostics/security). **Not on `main`. No Hub PR yet.** | +| SK-local unified (2026-10-04) | **Done** — Core + Suite `SK-local` contain `main`, `feat/full-installer`, `feat/ilt-hub`, `SK`, PR #2. RynthAi **0.6.10** fixes Hub creation on late settings load and the world-name wait in the login probe. ub-Rythai 3.1.10 is an optional installer component. | +| Pet: SummonPets / breeding | **Partial** — picker/charms/HealingBuddy/rosters + hardened empty-summon. **Still open:** deepen PetManager; bond/potency UI; **breeding** if `pet_breeding_enabled` | +| ACECustom `/ilt features` | **Not done** — still “Coming Soon” | +| In-AC smoke | **Not done in this project** | +| AutoXp / AutoTinker | **Out of scope** | + +**Next:** PR Suite `feat/ilt-hub` → `main`, smoke, then Pet follow-on (SummonPets + breeding). Keep this file current on **`feat/ilt-hub`** and **`SK-local`**. + +**Home:** Suite `Plugins/RynthCore.Plugin.RynthAi/IltHub/` + `Combat/PetManager.cs`. ACECustom breeding: `PET_BREEDING_PLAYER_GUIDE.md` / `PET_BREEDING_REFERENCE.md`. + +--- + +## When to use / desired result + +**Use when** reviewing, merging, or finishing leftover Hub work. + +**Desired result:** ImGui **ILT Hub** (Character · Pet · Banking · Gear · Games), server-option gated, per-char Hub state. Pet tab **updates** `SummonPets` / pet mechanics and adds **breeding only when `pet_breeding_enabled`**. + +--- + +## Prerequisites (locked) + +| Repo | Branches for this playbook | Notes | +|------|----------------------------|--------| +| **RynthSuite** | **`feat/ilt-hub`**, **`SK-local`** | Hub code + `Docs/ub-hub-merge-playbook.md` | +| **RynthCore** | **`SK-local`** | Tracking copy only (`docs/…`); no Hub product code | +| **UB** | `ILT_Customizations` (source) | Read-only for Hub | +| **ACECustom** | — | `/ilt features`, bond, potency, `pet_breeding_*` | + +**Locked decisions:** ImGui not Avalonia/VVS; `IltServerOptions` per feature; Hub state ≠ `/ra settings`; Games greenfield; Pet = update SummonPets + picker + item-check + breeding if server on; Guardian Hand on Gear. + +--- + +## Done vs remaining + +### Phase 1 — Shell + state + IltServerOptions — **coded** (PR + `/ilt features` dump open) + +### Phase 2 — Banking — **coded** (smoke open) + +### Phase 3 — Pet — **partial** + +| | | +|--|--| +| **Landed** | Essence picker → Pet rules; SummonPets / min-mobs / spirit refill; refill + mastery charms; hardened `AllowSummonOnEmpty`; HoldSummons; HealingBuddy; `/pets` `/shinies` | +| **Still to do** | Deepen PetManager (range UI, mastery usability, bond/potency columns); breeding panel iff `pet_breeding_enabled` (appraisal readiness, annex hint, dance QoL — no client litter math); smoke | + +### Phases 4–6 — Character / Gear / Games — **coded** (smoke, Guardian Hand WCID, quests.xml open) + +### Phase 7 — Hardening — **0.5.2 on branch** (diagnostics + security); ship/verify open + +--- + +## Remaining work + +1. PR Suite **`feat/ilt-hub`** → `main` +2. In-AC smoke on ILT +3. Pet follow-on: SummonPets mechanics + breeding when enabled → bump **0.5.3** +4. ACECustom `/ilt features` (include pet_breeding / bond / potency / refill) +5. Guardian Hand WCID when published +6. Optional: quests.xml, UB settings import, USD smoke +7. Keep playbook identical on Suite `feat/ilt-hub` + `SK-local` and Core `SK-local` + +--- + +## Explicit non-goals + +- Second pet summon system (update PetManager instead) +- Client breeding math when `pet_breeding_enabled` is false +- VVS XML / AutoXp / AutoTinker / Avalonia RynthAiPanel / force-replace `main` + +--- + +## Version / changelog + +- **0.5.1** — Hub landing · **0.5.2** — diagnostics + Hub security (on `feat/ilt-hub`) +- Next Pet wave: **0.5.3** + `Changelog/` note. Don’t bump Core API unless host APIs change. + +--- + +## Gate cheat sheet + +| Surface | Enable when | Keep off when | +|---------|-------------|----------------| +| Whole Hub | ILT-like or Force **and** ≥1 bit | Retail, Force off | +| Pet breeding | `pet_breeding_enabled` | Off / Unknown | +| Pet bond / potency | `pet_bond_enabled` / `pet_potency_enabled` | Flags false | +| Pet empty-summon | Charm + confirmed `pet_refill` | Not confirmed | +| Banking / Powerball / Quests / Clap | Per existing IltServerOptions rules | Unknown / Off | + +--- + +## Pointers + +- Plan/remotes (project store): `ub-hub-merge-plan.md`, `repo-remote-sync.md` +- Suite Hub branch: **`feat/ilt-hub`** @ `18b4579` (0.5.2) · also **`SK-local`** +- Changelogs: `Changelog/RynthAi-0.5.1-ilt-hub.md`, `Changelog/RynthAi-0.5.2-diagnostics-security.md` +- ACECustom: `pet_breeding_enabled`, `PetDevice_Breeding.cs` diff --git a/find_bytes.cs b/find_bytes.cs new file mode 100644 index 0000000..a60420b --- /dev/null +++ b/find_bytes.cs @@ -0,0 +1,20 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +public class Program { + public static void Main() { + byte[] pe = File.ReadAllBytes(@"C:\Games\NexCore\acclient.exe"); + int peOffset = BitConverter.ToInt32(pe, 0x3C); + int numSections = BitConverter.ToInt16(pe, peOffset + 6); + int sectionHeaders = peOffset + 24 + BitConverter.ToInt16(pe, peOffset + 20); + for (int i = 0; i < numSections; i++) { + int rva = BitConverter.ToInt32(pe, sectionHeaders + i * 40 + 12); + int size = BitConverter.ToInt32(pe, sectionHeaders + i * 40 + 16); + int ptr = BitConverter.ToInt32(pe, sectionHeaders + i * 40 + 20); + if (rva <= 0x1583F0 && rva + size > 0x1583F0) { + int fileOffset = ptr + (0x1583F0 - rva); + Console.WriteLine("Bytes at GetWeenieObject: " + BitConverter.ToString(pe, fileOffset, 32)); + } + } + } +} diff --git a/installer/Build-Installer.ps1 b/installer/Build-Installer.ps1 index 307d515..53f9912 100644 --- a/installer/Build-Installer.ps1 +++ b/installer/Build-Installer.ps1 @@ -1,33 +1,82 @@ #Requires -Version 5.1 <# .SYNOPSIS - Builds all RynthCore components and produces RynthCore-Setup.exe via Inno Setup. + Builds RynthCore + RynthSuite from source and produces the full installer + (RynthCore-Setup-<version>.exe) via Inno Setup. .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+3. The engine and the loader. 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) straight into staging\app\Runtime. - -NativeAot builds the old NativeAOT engine + loader instead. - 4. Publishes RynthCore.Plugin.RynthAi (NativeAOT, x86: the release plugins stay NativeAOT - - the CoreCLR engine loads them - until the update feed can carry a managed plugin's - dependency DLLs) - 5. Publishes the Loot Editor - 6. Stages all output under installer\staging\app\, plus the hand-built - RynthCore.SehTrampoline.dll and the Decal bridge (DecalBridge\RynthCore.DecalBridge.dll, - built here against Decal's reference assemblies), and checks every required file is there - 7. Invokes ISCC.exe to produce installer\Output\RynthCore-Setup.exe + 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 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) + 11. With -Version: assembles the deployment package installer\Output\Release-<version>\ + (installer, SHA256SUMS.txt, release-manifest.json with commits + component versions, + RELEASE-NOTES.md built from both repos' Changelog folders) and zips it to + installer\Output\RynthCore-<version>-deploy.zip, then re-verifies the hashes. + Release builds refuse uncommitted changes (see -AllowDirty) so a package always maps + to exact commits. + + The installer lets the user choose both the RynthCore and the RynthSuite folders; the + code resolves them at runtime from HKA\Software\Rynth (see src\RynthCore.App\RynthInstallPaths.cs). .PARAMETER Configuration Build configuration. Default: Release .PARAMETER IsccPath - Path to ISCC.exe (Inno Setup compiler). Default looks in the standard Inno Setup 6 location. + Path to ISCC.exe (Inno Setup compiler). Default looks in the standard Inno Setup 6 locations. Install Inno Setup from: https://jrsoftware.org/isdl.php +.PARAMETER RynthSuiteRoot + RynthSuite repo root. Default: the sibling ..\RynthSuite next to this RynthCore repo. + +.PARAMETER Version + Release version yyyy.m.d.n (e.g. 2026.10.4.2). Stamped into the launcher/engine/tools, + release.txt and the installer. Omit for a dev build. + .PARAMETER SkipBuild - Skip dotnet publish steps and just re-run ISCC against the existing staging directory. + Skip dotnet publish steps and just re-stage + re-run ISCC against existing publish output. + +.PARAMETER NoDotNetInstall + Fail instead of auto-installing when no .NET 10 SDK is found. By default a missing SDK is + installed per-user (no admin) to %LOCALAPPDATA%\Microsoft\dotnet via Microsoft's signed + dotnet-install.ps1, and used for this build. + +.PARAMETER AllowDirty + Build a -Version release even when RynthCore or RynthSuite has uncommitted changes to tracked + files. The package is still produced but its manifest and notes are flagged "dirty". + +.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 #> param( [string]$Configuration = "Release", @@ -35,19 +84,22 @@ param( # Explicit path to the RynthSuite repo root. When omitted, defaults to the # sibling directory of RynthCore (i.e. ..\RynthSuite relative to this repo). [string]$RynthSuiteRoot = "", - # Version string injected into the installer (e.g. "0.3"). When omitted, + # Version string injected into the installer (yyyy.m.d.n). When omitted, # the version defined in RynthCore.iss is used as-is. [string]$Version = "", [switch]$SkipBuild, + [switch]$NoDotNetInstall, + [switch]$AllowDirty, + [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 by default: every release ships it (experimental, opt-in per account; - # nothing registers it unless the player picks "Decal + RynthCore"). Building it needs - # Decal installed (its public reference assemblies); without Decal this script fails. - # -SkipDecalBridge leaves it out (dev builds on a machine without Decal; never a release). + # {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, - # Old opt-in switch, kept so existing command lines still work; the bridge is the default now. + # 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 = "" @@ -69,11 +121,66 @@ if ($Version) { $release = [int]$p[0] * 1000000 + [int]$p[1] * 10000 + [int]$p[2] * 100 + [int]$p[3] } -# Stamp every build with the release, so the launcher, the engine log and the in-game -# Status panel show it (RynthCore.App.BuildVersion); the SDK appends the git commit. +# Stamp the core builds and tools with the release, so the launcher, the engine log and the +# in-game Status panel show it (RynthCore.App.BuildVersion); the SDK appends the git commit. +# The RynthAi plugin keeps its own semantic version (RynthCore.Plugin.RynthAi.csproj), so it +# is published WITHOUT these args. $VersionArgs = @() if ($Version) { $VersionArgs = @("-p:Version=$Version") } +# ── .NET 10 SDK check (auto-install when missing) ─────────────────────────── +# Every project targets net10.0, so publishing needs a .NET 10 SDK. Returns $true when the +# 'dotnet' on PATH lists a 10.x SDK. +function Test-DotNet10Sdk { + $cmd = Get-Command dotnet -ErrorAction SilentlyContinue + if (-not $cmd) { return $false } + $sdks = & $cmd.Source --list-sdks 2>$null + return [bool]($sdks | Where-Object { $_ -match '^10\.' }) +} + +# Makes a .NET 10 SDK available for this build: uses the one on PATH, else a previous per-user +# auto-install, else installs one per-user (no admin) with Microsoft's dotnet-install.ps1, whose +# Authenticode signature must verify as Microsoft before it is run. +function Initialize-DotNet10Sdk { + if (Test-DotNet10Sdk) { Write-Host ".NET 10 SDK: found ($((Get-Command dotnet).Source))"; return } + + $userDotNet = Join-Path $env:LOCALAPPDATA "Microsoft\dotnet" + if (Test-Path (Join-Path $userDotNet "dotnet.exe")) { + $env:DOTNET_ROOT = $userDotNet + $env:PATH = "$userDotNet;$env:PATH" + if (Test-DotNet10Sdk) { Write-Host ".NET 10 SDK: found per-user install ($userDotNet)"; return } + } + + if ($NoDotNetInstall) { + throw "No .NET 10 SDK found. Install it from https://dotnet.microsoft.com/download/dotnet/10.0 or re-run without -NoDotNetInstall." + } + + Write-Host "" + Write-Host ".NET 10 SDK not found -- installing it per-user to $userDotNet ..." -ForegroundColor Yellow + $installScript = Join-Path $env:TEMP "dotnet-install.ps1" + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 + Invoke-WebRequest -Uri "https://dot.net/v1/dotnet-install.ps1" -OutFile $installScript -UseBasicParsing + $sig = Get-AuthenticodeSignature $installScript + if ($sig.Status -ne 'Valid' -or $sig.SignerCertificate.Subject -notmatch 'O=Microsoft Corporation') { + Remove-Item $installScript -Force -ErrorAction SilentlyContinue + throw "dotnet-install.ps1 signature check failed ($($sig.Status)); not running it." + } + + # Separate process so the script runs under Bypass regardless of this session's execution policy. + & powershell -NoProfile -ExecutionPolicy Bypass -File $installScript -Channel 10.0 -InstallDir $userDotNet + $installExit = $LASTEXITCODE + Remove-Item $installScript -Force -ErrorAction SilentlyContinue + if ($installExit -ne 0) { throw "dotnet-install.ps1 failed (exit $installExit)" } + + $env:DOTNET_ROOT = $userDotNet + $env:PATH = "$userDotNet;$env:PATH" + if (-not (Test-DotNet10Sdk)) { throw ".NET 10 SDK install finished but 'dotnet --list-sdks' still shows no 10.x SDK." } + Write-Host ".NET 10 SDK: installed ($userDotNet)" -ForegroundColor Green +} + +# Only the publish steps need the SDK; -SkipBuild just re-stages and re-runs ISCC. +if (-not $SkipBuild) { Initialize-DotNet10Sdk } + $ScriptDir = $PSScriptRoot $RepoRoot = Split-Path $ScriptDir -Parent # e.g. C:\Projects\RynthCore $ProjectsRoot = Split-Path $RepoRoot -Parent # e.g. C:\Projects @@ -83,22 +190,74 @@ if (-not $RynthSuiteRoot) { $RynthSuiteRoot = "$ProjectsRoot\RynthSuite" } -$LauncherProject = "$RepoRoot\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj" -$EngineProject = "$RepoRoot\src\RynthCore.Engine\RynthCore.Engine.csproj" -$LoaderProject = "$RepoRoot\src\RynthCore.Loader\RynthCore.Loader.csproj" -$PluginProject = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj" -$LootEditorProject = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\RynthCore.LootEditor.csproj" +# ── Source state (release builds) ─────────────────────────────────────────── +# A deployment package must map to exact commits. Tracked changes outside +# installer\previous-release\ (whose version marker this script rewrites) block a -Version +# build unless -AllowDirty; untracked files are ignored, as in Publish-Update.ps1. +function Get-RepoState([string]$Repo) { + $ErrorActionPreference = 'Continue' # native stderr must not become a terminating error on 5.1 + $dirty = @(git -C $Repo status --porcelain --untracked-files=no 2>$null | + Where-Object { $_ -and $_.Substring(3) -notlike 'installer/previous-release/*' }) + [ordered]@{ + path = $Repo + branch = (git -C $Repo rev-parse --abbrev-ref HEAD 2>$null) + commit = (git -C $Repo rev-parse HEAD 2>$null) + dirty = ($dirty.Count -gt 0) + changes = $dirty + } +} +$CoreState = Get-RepoState $RepoRoot +$SuiteState = Get-RepoState $RynthSuiteRoot +if ($Version -and -not $NoPackage) { + foreach ($s in $CoreState, $SuiteState) { + if (-not $s.commit) { throw "Not a git checkout: $($s.path) (a release package records exact commits)." } + if ($s.dirty -and -not $AllowDirty) { + throw "$($s.path) has uncommitted changes -- commit them or pass -AllowDirty:`n $($s.changes -join "`n ")" + } + } + Write-Host "Source: RynthCore $($CoreState.branch)@$($CoreState.commit.Substring(0,7)), RynthSuite $($SuiteState.branch)@$($SuiteState.commit.Substring(0,7))$(if ($CoreState.dirty -or $SuiteState.dirty) { ' (DIRTY)' })" +} -$LauncherPublish = "$RepoRoot\src\RynthCore.App.Avalonia\bin\$Configuration\net10.0-windows7.0\win-x86\publish" -$EnginePublish = "$RepoRoot\src\RynthCore.Engine\bin\$Configuration\net10.0-windows\win-x86\publish" -$LoaderPublish = "$RepoRoot\src\RynthCore.Loader\bin\$Configuration\net10.0-windows\win-x86\publish" -$PluginPublish = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\bin\$Configuration\net10.0-windows\win-x86\publish" -$LootEditorPublish = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\bin\$Configuration\net10.0\win-x86\publish" +$LauncherProject = "$RepoRoot\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj" +$EngineProject = "$RepoRoot\src\RynthCore.Engine\RynthCore.Engine.csproj" +$LoaderProject = "$RepoRoot\src\RynthCore.Loader\RynthCore.Loader.csproj" +$PluginProject = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj" +$LootEditorProject = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\RynthCore.LootEditor.csproj" +$MonsterEditorProject = "$RynthSuiteRoot\Tools\RynthCore.MonsterEditor\RynthCore.MonsterEditor.csproj" -$StagingDir = "$ScriptDir\staging\app" +$LauncherPublish = "$RepoRoot\src\RynthCore.App.Avalonia\bin\$Configuration\net10.0-windows7.0\win-x86\publish" +$EnginePublish = "$RepoRoot\src\RynthCore.Engine\bin\$Configuration\net10.0-windows\win-x86\publish" +$LoaderPublish = "$RepoRoot\src\RynthCore.Loader\bin\$Configuration\net10.0-windows\win-x86\publish" +$PluginPublish = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\bin\$Configuration\net10.0-windows\win-x86\publish" +$LootEditorPublish = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\bin\$Configuration\net10.0\win-x86\publish" +$MonsterEditorPublish = "$RynthSuiteRoot\Tools\RynthCore.MonsterEditor\bin\$Configuration\net10.0\win-x86\publish" + +# Experimental RynthSuite plugins (optional installer components). Each installs to +# <RynthSuite>\<Name>\RynthCore.Plugin.<Name>.dll and keeps its own semantic version. +$ExperimentalPlugins = @('RynthChat', 'RynthJuice', 'RynthNav', 'RynthTracker', 'RynthVision', 'UbRythai') +# Project folders that don't follow Plugins\RynthCore.Plugin.<Name>\ (ub-Rythai keeps its own sub-tree). +$ExperimentalProjectDirs = @{ 'UbRythai' = "$RynthSuiteRoot\Plugins\ub-Rythai\RynthCore.Plugin.UbRythai" } +function Get-ExperimentalDir([string]$Name) { + if ($ExperimentalProjectDirs.ContainsKey($Name)) { return $ExperimentalProjectDirs[$Name] } + return "$RynthSuiteRoot\Plugins\RynthCore.Plugin.$Name" +} +function Get-ExperimentalProject([string]$Name) { "$(Get-ExperimentalDir $Name)\RynthCore.Plugin.$Name.csproj" } +function Get-ExperimentalPublish([string]$Name) { "$(Get-ExperimentalDir $Name)\bin\$Configuration\net10.0-windows\win-x86\publish" } +# RynthNav's starter portal list (shipped into <RynthCore>\NavData, never overwritten). +$NavPortalsTsv = "$RynthSuiteRoot\Tools\RynthNav.PortalGraph\Data\portals.tsv" + +# staging\core → {app} (user-chosen RynthCore folder) +# staging\suite → {code:GetSuiteDir} (user-chosen RynthSuite folder) +$StagingRoot = "$ScriptDir\staging" +$CoreStaging = "$StagingRoot\core" +$SuiteStaging = "$StagingRoot\suite" # ── Validate projects ─────────────────────────────────────────────────────── -foreach ($p in @($LauncherProject, $EngineProject, $PluginProject, $LootEditorProject) + @(if ($NativeAot) { $LoaderProject })) { +# 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)) { throw "Project not found: $p`nUpdate paths in Build-Installer.ps1 if your repo layout differs." } @@ -107,68 +266,93 @@ foreach ($p in @($LauncherProject, $EngineProject, $PluginProject, $LootEditorPr if (-not $SkipBuild) { # ── 1. Launcher (self-contained Avalonia WinExe) ───────────────────────── Write-Host "" - Write-Host "[1/5] Publishing Launcher (self-contained, x86)..." -ForegroundColor Cyan + Write-Host "[1/7] Publishing Launcher (self-contained, x86)..." -ForegroundColor Cyan dotnet publish $LauncherProject -c $Configuration -r win-x86 --self-contained true @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Launcher publish failed (exit $LASTEXITCODE)" } if ($NativeAot) { # ── 2. Engine (NativeAOT — the slow one) ────────────────────────────── Write-Host "" - Write-Host "[2/5] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan + 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/5] Publishing Loader (NativeAOT)..." -ForegroundColor Cyan + 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. Plugin (NativeAOT) ───────────────────────────────────────────────── + # ── 4. RynthAi plugin (NativeAOT; keeps its own version) ───────────────── Write-Host "" - Write-Host "[4/5] Publishing Plugin (NativeAOT)..." -ForegroundColor Cyan - dotnet publish $PluginProject -c $Configuration @VersionArgs + Write-Host "[4/7] Publishing RynthAi plugin (NativeAOT)..." -ForegroundColor Cyan + dotnet publish $PluginProject -c $Configuration if ($LASTEXITCODE -ne 0) { throw "Plugin publish failed (exit $LASTEXITCODE)" } # ── 5. Loot Editor (self-contained Avalonia tool) ───────────────────────── Write-Host "" - Write-Host "[5/5] Publishing Loot Editor (self-contained, x86)..." -ForegroundColor Cyan + Write-Host "[5/7] Publishing Loot Editor (self-contained, x86)..." -ForegroundColor Cyan dotnet publish $LootEditorProject -c $Configuration -r win-x86 --self-contained true @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Loot Editor publish failed (exit $LASTEXITCODE)" } + + # ── 6. Monster Editor (self-contained Avalonia tool) ────────────────────── + Write-Host "" + Write-Host "[6/7] Publishing Monster Editor (self-contained, x86)..." -ForegroundColor Cyan + dotnet publish $MonsterEditorProject -c $Configuration -r win-x86 --self-contained true @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "Monster Editor publish failed (exit $LASTEXITCODE)" } + + # ── 7. Experimental plugins (NativeAOT; optional components) ────────────── + # RynthJuice/RynthNav/RynthVision set <PublishDir> to the live C:\Games\RynthSuite\<Name>\ + # folder for dev hot-reload; override it so an installer build never touches a live install. + # A trailing '/' (not '\') keeps the argument intact when the path contains spaces. + Write-Host "" + Write-Host "[7/7] Publishing experimental plugins (NativeAOT)..." -ForegroundColor Cyan + foreach ($name in $ExperimentalPlugins) { + Write-Host " $name" + $publishDir = (Get-ExperimentalPublish $name) + '/' + dotnet publish (Get-ExperimentalProject $name) -c $Configuration "-p:PublishDir=$publishDir" + if ($LASTEXITCODE -ne 0) { throw "$name publish failed (exit $LASTEXITCODE)" } + } } # ── Stage ──────────────────────────────────────────────────────────────────── Write-Host "" Write-Host "Staging files..." -ForegroundColor Cyan -if (Test-Path "$ScriptDir\staging") { - Remove-Item "$ScriptDir\staging" -Recurse -Force +if (Test-Path $StagingRoot) { + Remove-Item $StagingRoot -Recurse -Force +} +New-Item -ItemType Directory -Path "$CoreStaging\Runtime\Native" -Force | Out-Null +New-Item -ItemType Directory -Path "$CoreStaging\Tools\LootEditor" -Force | Out-Null +New-Item -ItemType Directory -Path "$SuiteStaging\RynthAi\MonsterEditor" -Force | Out-Null + +# Copies a publish folder (files + subfolders) without .pdb files. +function Copy-PublishTree([string]$Source, [string]$Dest) { + if (-not (Test-Path $Source)) { throw "Publish output not found: $Source" } + foreach ($file in (Get-ChildItem $Source -File)) { + if ($file.Extension -eq '.pdb') { continue } + Copy-Item $file.FullName (Join-Path $Dest $file.Name) -Force + } + foreach ($dir in (Get-ChildItem $Source -Directory)) { + Copy-Item $dir.FullName $Dest -Recurse -Force + Get-ChildItem (Join-Path $Dest $dir.Name) -Recurse -File -Filter '*.pdb' | Remove-Item -Force + } } -New-Item -ItemType Directory -Path "$StagingDir\Runtime\Native" -Force | Out-Null -New-Item -ItemType Directory -Path "$StagingDir\Tools\LootEditor" -Force | Out-Null -# Plugin DLLs are staged into a separate top-level folder (not under -# Runtime\) because the engine no longer auto-scans Runtime\Plugins\. -# The .iss file installs this folder to C:\Games\RynthSuite\<PluginName>\ -# (an absolute destination outside {app}) so the plugin lives next to its -# data dirs and the user adds the path via the launcher's Plugins tab. -$pluginStagingDir = "$ScriptDir\staging\plugins" -if (Test-Path $pluginStagingDir) { Remove-Item $pluginStagingDir -Recurse -Force } -New-Item -ItemType Directory -Path "$pluginStagingDir\RynthAi" -Force | Out-Null # Launcher root files (rename .exe → RynthCore.exe; drop .pdb) foreach ($file in (Get-ChildItem "$LauncherPublish" -File)) { if ($file.Extension -eq '.pdb') { continue } $destName = if ($file.Name -eq 'RynthCore.App.Avalonia.exe') { 'RynthCore.exe' } else { $file.Name } - Copy-Item $file.FullName "$StagingDir\$destName" -Force + Copy-Item $file.FullName "$CoreStaging\$destName" -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 "$StagingDir\Runtime\$($file.Name)" -Force + Copy-Item $file.FullName "$CoreStaging\Runtime\$($file.Name)" -Force } # Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it @@ -176,17 +360,17 @@ if ($NativeAot) { # 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 "$StagingDir\Runtime\" -Force + 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/5] Building the unloadable engine + native loader into staging..." -ForegroundColor Cyan - & "$RepoRoot\scripts\Publish-EngineCoreClr.ps1" -Target "$StagingDir\Runtime" -Configuration $Configuration -MsBuildArgs $VersionArgs + 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 "$StagingDir\Runtime\RynthCore.Loader.pdb", "$StagingDir\Runtime\RynthCore.Shim.pdb" -Force -ErrorAction SilentlyContinue + 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), @@ -197,45 +381,70 @@ if ($NativeAot) { $sehDll = "$RepoRoot\native\SehTrampoline\bin\RynthCore.SehTrampoline.dll" $sehSrc = "$RepoRoot\native\SehTrampoline\SehTrampoline.c" if (-not (Test-Path $sehDll)) { throw "SEH trampoline not found at: $sehDll`nBuild it with native\SehTrampoline\Build-SehTrampoline.ps1" } -if ((Test-Path $sehSrc) -and (Get-Item $sehSrc).LastWriteTime -gt (Get-Item $sehDll).LastWriteTime) { +# Source "age": checkouts and merges rewrite SehTrampoline.c and bump its mtime without changing it, +# so when the file matches HEAD its last commit time is used; local edits fall back to the mtime. +function Get-SehSourceTime { + $ErrorActionPreference = 'Continue' + $srcTime = (Get-Item $sehSrc).LastWriteTime + git -C $RepoRoot diff --quiet HEAD -- "native/SehTrampoline/SehTrampoline.c" 2>$null + if ($LASTEXITCODE -eq 0) { + $ct = git -C $RepoRoot log -1 --format=%ct -- "native/SehTrampoline/SehTrampoline.c" 2>$null + if ($ct -match '^\d+$') { $srcTime = [DateTimeOffset]::FromUnixTimeSeconds([long]$ct).LocalDateTime } + } + $srcTime +} +if ((Test-Path $sehSrc) -and (Get-SehSourceTime) -gt (Get-Item $sehDll).LastWriteTime) { throw "RynthCore.SehTrampoline.dll is STALE (SehTrampoline.c is newer). Rebuild with native\SehTrampoline\Build-SehTrampoline.ps1" } -Copy-Item $sehDll "$StagingDir\Runtime\" -Force +Copy-Item $sehDll "$CoreStaging\Runtime\" -Force # 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 "$StagingDir\Runtime\Native\$($file.Name)" -Force + Copy-Item $file.FullName "$CoreStaging\Runtime\Native\$($file.Name)" -Force } } -# Plugin DLL only — staged separately so the .iss file can install it to an -# absolute path outside {app}. The engine no longer auto-scans Runtime\Plugins\; -# the user explicitly adds the plugin path via the launcher's Plugins tab. +# Loot Editor → <RynthCore>\Tools\LootEditor (the launcher/engine look for it there) +Copy-PublishTree $LootEditorPublish "$CoreStaging\Tools\LootEditor" + +# RynthAi plugin DLL → <RynthSuite>\RynthAi (next to its data dirs; the installer hands the +# path to the launcher via HKA\Software\Rynth\PendingPluginRegistration). $pluginDll = "$PluginPublish\RynthCore.Plugin.RynthAi.dll" if (-not (Test-Path $pluginDll)) { throw "Plugin DLL not found at: $pluginDll" } -Copy-Item $pluginDll "$pluginStagingDir\RynthAi\" -Force +Copy-Item $pluginDll "$SuiteStaging\RynthAi\" -Force -# Loot Editor (self-contained — copy everything from publish, drop pdbs) -if (-not (Test-Path $LootEditorPublish)) { throw "Loot Editor publish not found at: $LootEditorPublish" } -foreach ($file in (Get-ChildItem "$LootEditorPublish" -File)) { - if ($file.Extension -eq '.pdb') { continue } - Copy-Item $file.FullName "$StagingDir\Tools\LootEditor\$($file.Name)" -Force -} -foreach ($dir in (Get-ChildItem "$LootEditorPublish" -Directory)) { - Copy-Item $dir.FullName "$StagingDir\Tools\LootEditor\" -Recurse -Force - # Drop pdbs from copied subdirs - Get-ChildItem "$StagingDir\Tools\LootEditor\$($dir.Name)" -Recurse -File -Filter '*.pdb' | Remove-Item -Force +# Monster Editor → <RynthSuite>\RynthAi\MonsterEditor (RynthAi's dashboard launches it from there) +Copy-PublishTree $MonsterEditorPublish "$SuiteStaging\RynthAi\MonsterEditor" + +# Experimental plugins → <RynthSuite>\<Name>\RynthCore.Plugin.<Name>.dll (the NativeAOT DLL is self-contained; +# cimgui.dll is provided by the engine's Runtime folder). +foreach ($name in $ExperimentalPlugins) { + $dll = Join-Path (Get-ExperimentalPublish $name) "RynthCore.Plugin.$name.dll" + if (-not (Test-Path $dll)) { throw "$name DLL not found at: $dll" } + New-Item -ItemType Directory -Path "$SuiteStaging\$name" -Force | Out-Null + Copy-Item $dll "$SuiteStaging\$name\" -Force } +# RynthNav starter data → <RynthCore>\NavData (staged apart from core so it is only installed with RynthNav). +if (-not (Test-Path $NavPortalsTsv)) { throw "RynthNav portals.tsv not found at: $NavPortalsTsv" } +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. Not for a release." + 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 @@ -247,57 +456,101 @@ if ($SkipDecalBridge) { 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 for a dev build)" } + 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 "$StagingDir\DecalBridge" -Force | Out-Null - Copy-Item $bridgeDll "$StagingDir\DecalBridge\" -Force - $staleDecal = @(Get-ChildItem "$StagingDir\DecalBridge" -File | Where-Object { $_.Name -ne "RynthCore.DecalBridge.dll" }) + 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 "$StagingDir\release.txt" -Value @($release, $Version) -Encoding ASCII +Set-Content -Path "$CoreStaging\release.txt" -Value @($release, $Version) -Encoding ASCII # Everything a working install needs. The 2026-09-25 public installer went out # without the Loader and the SEH trampoline because nothing checked. $required = @( - "$StagingDir\RynthCore.exe", - "$StagingDir\Runtime\RynthCore.Loader.dll", - "$StagingDir\Runtime\RynthCore.Engine.dll", - "$StagingDir\Runtime\RynthCore.SehTrampoline.dll", - "$StagingDir\Runtime\minhook.x86.dll", - "$StagingDir\Runtime\cimgui.dll", - "$pluginStagingDir\RynthAi\RynthCore.Plugin.RynthAi.dll" -) + "$CoreStaging\RynthCore.exe", + "$CoreStaging\RynthCore.App.Avalonia.dll", + "$CoreStaging\RynthCore.App.Avalonia.deps.json", + "$CoreStaging\RynthCore.App.Avalonia.runtimeconfig.json", + "$CoreStaging\Runtime\RynthCore.Loader.dll", + "$CoreStaging\Runtime\RynthCore.Engine.dll", + "$CoreStaging\Runtime\RynthCore.SehTrampoline.dll", + "$CoreStaging\Runtime\minhook.x86.dll", + "$CoreStaging\Runtime\cimgui.dll", + "$CoreStaging\Tools\LootEditor\RynthCore.LootEditor.exe", + "$SuiteStaging\RynthAi\RynthCore.Plugin.RynthAi.dll", + "$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 += @( - "$StagingDir\Runtime\RynthCore.Shim.dll", - "$StagingDir\Runtime\dotnet\coreclr.dll", - "$StagingDir\Runtime\dotnet\System.Private.CoreLib.dll" + "$CoreStaging\Runtime\RynthCore.Shim.dll", + "$CoreStaging\Runtime\dotnet\coreclr.dll", + "$CoreStaging\Runtime\dotnet\System.Private.CoreLib.dll" ) } -if (-not $SkipDecalBridge) { - $required += "$StagingDir\DecalBridge\RynthCore.DecalBridge.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 ")" } +# Every assembly the launcher's deps.json lists must be staged next to it — a launcher DLL whose +# deps.json doesn't match is exactly the "Could not load RynthCore.DesktopLog" failure of 2026-10-04. +$depsJson = Get-Content "$CoreStaging\RynthCore.App.Avalonia.deps.json" -Raw | ConvertFrom-Json +$projectLibs = $depsJson.libraries.PSObject.Properties | Where-Object { $_.Value.type -eq 'project' } | ForEach-Object { ($_.Name -split '/')[0] } +$missingLibs = @($projectLibs | Where-Object { -not (Test-Path "$CoreStaging\$_.dll") }) +if ($missingLibs.Count -gt 0) { throw "Launcher deps.json references project assemblies that were not staged:`n $($missingLibs -join "`n ")" } + # Report staged sizes -$engineDll = "$StagingDir\Runtime\RynthCore.Engine.dll" +$engineDll = "$CoreStaging\Runtime\RynthCore.Engine.dll" if (Test-Path $engineDll) { $sizeMb = [math]::Round((Get-Item $engineDll).Length / 1MB, 1) Write-Host " Engine.dll: ${sizeMb} MB" } -$totalMb = [math]::Round((Get-ChildItem "$StagingDir" -Recurse -File | Measure-Object Length -Sum).Sum / 1MB, 1) -Write-Host " Total staged: ${totalMb} MB" +$coreMb = [math]::Round((Get-ChildItem $CoreStaging -Recurse -File | Measure-Object Length -Sum).Sum / 1MB, 1) +$suiteMb = [math]::Round((Get-ChildItem $SuiteStaging -Recurse -File | Measure-Object Length -Sum).Sum / 1MB, 1) +Write-Host " Staged: RynthCore ${coreMb} MB, RynthSuite ${suiteMb} MB" -Write-Host "Staging complete: $StagingDir" -ForegroundColor Green +Write-Host "Staging complete: $StagingRoot" -ForegroundColor Green + +# ── Archive the previous installer when -Version bumps ───────────────────── +# installer\previous-release\last-built-version.txt records the last version built; when a new +# -Version is built, that version's installer is copied to previous-release\ first. +# Inno stamps AppVersion as the setup exe's ProductVersion, padded with spaces/NULs. +function Get-InstallerVersion([string]$Exe) { "$((Get-Item $Exe).VersionInfo.ProductVersion)".Trim([char[]]" `0") } + +$previousReleaseDir = Join-Path $ScriptDir "previous-release" +$lastVersionFile = Join-Path $previousReleaseDir "last-built-version.txt" +if ($Version) { + New-Item -ItemType Directory -Path $previousReleaseDir -Force | Out-Null + $lastVer = if (Test-Path $lastVersionFile) { (Get-Content $lastVersionFile -Raw).Trim() } else { "" } + if ($lastVer -and $lastVer -ne $Version) { + $prevExe = Join-Path $ScriptDir "Output\RynthCore-Setup-$lastVer.exe" + if (-not (Test-Path $prevExe)) { + # The canonical copy may be an older build (e.g. the previous version was built in + # another checkout); only archive it when its stamped ProductVersion really is $lastVer. + $canonical = Join-Path $ScriptDir "Output\RynthCore-Setup.exe" + $prevExe = $null + if ((Test-Path $canonical) -and ((Get-InstallerVersion $canonical) -eq $lastVer)) { $prevExe = $canonical } + elseif (Test-Path $canonical) { Write-Warning "Previous installer $lastVer not found in Output\ (RynthCore-Setup.exe is $(Get-InstallerVersion $canonical)); nothing archived." } + } + if ($prevExe -and (Test-Path $prevExe)) { + $archive = Join-Path $previousReleaseDir "RynthCore-Setup-$lastVer.exe" + Write-Host "Archiving previous installer ($lastVer) -> $archive" -ForegroundColor Cyan + Copy-Item $prevExe $archive -Force + } + } +} # ── Inno Setup ─────────────────────────────────────────────────────────────── # Auto-detect ISCC if not specified: try standard install location then user-local. @@ -327,8 +580,13 @@ $issSource = "$ScriptDir\RynthCore.iss" # Source, staging\) still resolve from the installer\ directory. $issTmp = "$ScriptDir\RynthCore.tmp.iss" $issContent = Get-Content $issSource -Raw +$outputName = "RynthCore-Setup" if ($Version) { + # Versioned .exe avoids Inno error 32 when Output\RynthCore-Setup.exe is open in Explorer or AV. + $outputName = "RynthCore-Setup-$Version" $issContent = $issContent -replace 'AppVersion=0\.0\.0', "AppVersion=$Version" + $issContent = $issContent -replace 'AppVerName=RynthCore \+ RynthSuite 0\.0\.0', "AppVerName=RynthCore + RynthSuite $Version" + $issContent = $issContent -replace 'OutputBaseFilename=RynthCore-Setup', "OutputBaseFilename=$outputName" Write-Host " Version override: $Version" } Set-Content -Path $issTmp -Value $issContent -Encoding UTF8 @@ -340,6 +598,202 @@ try { Remove-Item $issTmp -Force -ErrorAction SilentlyContinue } +$builtInstaller = "$ScriptDir\Output\$outputName.exe" +if ($Version) { + # Canonical name for the launcher updater / docs; best effort if the file is locked. + try { Copy-Item $builtInstaller "$ScriptDir\Output\RynthCore-Setup.exe" -Force } + catch { Write-Warning "Could not refresh Output\RynthCore-Setup.exe (in use?). Primary artifact: $builtInstaller" } +} + +# ── Deployment package (-Version builds) ──────────────────────────────────── +# installer\Output\Release-<version>\ holds everything a deployment needs, and +# RynthCore-<version>-deploy.zip is that folder zipped: +# RynthCore-Setup-<version>.exe the installer +# release-manifest.json version, commits, component versions, installer hash +# RELEASE-NOTES.md install steps + Changelog entries since the previous release +# SHA256SUMS.txt hashes of the three files above (sha256sum format) +# previous-release\last-release-manifest.json keeps the manifest so the next build can list only +# the Changelog files added or changed since this release's commits. + +# UTF-8 without BOM (Windows PowerShell's Set-Content -Encoding UTF8 writes a BOM). +function Write-Utf8([string]$Path, [string]$Text) { + [IO.File]::WriteAllText($Path, $Text, (New-Object System.Text.UTF8Encoding($false))) +} +function Get-Sha256([string]$Path) { (Get-FileHash $Path -Algorithm SHA256).Hash.ToLowerInvariant() } + +# Changelog\*.md files added/modified in $Repo since $SinceCommit (when that commit exists), +# else since $SinceDate (yyyy-mm-dd). Returns repo-relative paths that still exist. +function Get-ChangelogFiles([string]$Repo, [string]$SinceCommit, [string]$SinceDate) { + $ErrorActionPreference = 'Continue' # git writes "fatal:" to stderr for unknown commits + $names = @() + $known = $false + if ($SinceCommit) { + git -C $Repo cat-file -e "$SinceCommit^{commit}" 2>$null + $known = ($LASTEXITCODE -eq 0) + } + if ($known) { + $names = @(git -C $Repo diff --name-only --diff-filter=AM $SinceCommit HEAD -- Changelog 2>$null) + } elseif ($SinceDate) { + $names = @(git -C $Repo log "--since=$SinceDate 00:00" --name-only --diff-filter=AM --format= -- Changelog 2>$null) + } + @($names | Where-Object { $_ -like '*.md' -and (Test-Path (Join-Path $Repo $_)) } | Sort-Object -Unique) +} + +if ($Version -and -not $NoPackage) { + Write-Host "" + Write-Host "Assembling deployment package..." -ForegroundColor Cyan + + # The installer must carry this release's version (Inno stamps AppVersion as ProductVersion). + $stamped = Get-InstallerVersion $builtInstaller + if ($stamped -ne $Version) { throw "Installer ProductVersion is '$stamped', expected '$Version'." } + + $pkgName = "Release-$Version" + $pkgDir = Join-Path $ScriptDir "Output\$pkgName" + $zipPath = Join-Path $ScriptDir "Output\RynthCore-$Version-deploy.zip" + if (Test-Path $pkgDir) { Remove-Item $pkgDir -Recurse -Force } + if (Test-Path $zipPath) { Remove-Item $zipPath -Force } + New-Item -ItemType Directory -Path $pkgDir -Force | Out-Null + + $setupName = "RynthCore-Setup-$Version.exe" + Copy-Item $builtInstaller (Join-Path $pkgDir $setupName) -Force + $setupHash = Get-Sha256 (Join-Path $pkgDir $setupName) + + # Versions of what the installer ships, read from the staged files' version resources. + $componentFiles = [ordered]@{ + 'Launcher (RynthCore.exe)' = "$CoreStaging\RynthCore.exe" + 'Engine' = "$CoreStaging\Runtime\RynthCore.Engine.dll" + 'Loader' = "$CoreStaging\Runtime\RynthCore.Loader.dll" + 'Loot Editor' = "$CoreStaging\Tools\LootEditor\RynthCore.LootEditor.exe" + 'RynthAi plugin' = "$SuiteStaging\RynthAi\RynthCore.Plugin.RynthAi.dll" + 'Monster Editor' = "$SuiteStaging\RynthAi\MonsterEditor\RynthCore.MonsterEditor.exe" + } + foreach ($name in $ExperimentalPlugins) { $componentFiles["$name (experimental)"] = "$SuiteStaging\$name\RynthCore.Plugin.$name.dll" } + $components = foreach ($kv in $componentFiles.GetEnumerator()) { + $vi = (Get-Item $kv.Value).VersionInfo + $ver = if ($vi.ProductVersion) { $vi.ProductVersion } else { $vi.FileVersion } + [ordered]@{ name = $kv.Key; file = $kv.Value.Substring($StagingRoot.Length + 1); version = "$ver".Trim([char[]]" `0") } + } + + # Changelog entries since the previous release (its manifest's commits, else its build date). + $lastManifestFile = Join-Path $previousReleaseDir "last-release-manifest.json" + $prevManifest = $null + if (Test-Path $lastManifestFile) { + try { $prevManifest = Get-Content $lastManifestFile -Raw | ConvertFrom-Json } catch { $prevManifest = $null } + } + # Baseline for "changes since": a rebuild of the same version reuses that build's baseline; + # otherwise the previous release's commits, or (no manifest yet) the previous version's date. + function ConvertTo-SinceDate([string]$Ver) { + $vp = "$Ver".Split('.') + if ($vp.Count -eq 4) { return '{0:D4}-{1:D2}-{2:D2}' -f [int]$vp[0], [int]$vp[1], [int]$vp[2] } + return "" + } + $prevRelease = if ($lastVer -ne $Version) { $lastVer } else { "" } + $coreSince = ""; $suiteSince = ""; $sinceDate = "" + if ($prevManifest -and $prevManifest.version -eq $Version) { + $prevRelease = "$($prevManifest.previous)" + if ($prevManifest.changelogSince) { + $coreSince = "$($prevManifest.changelogSince.rynthCore)" + $suiteSince = "$($prevManifest.changelogSince.rynthSuite)" + $sinceDate = "$($prevManifest.changelogSince.date)" + } else { $sinceDate = ConvertTo-SinceDate $prevRelease } + } elseif ($prevManifest) { + $coreSince = "$($prevManifest.source.rynthCore.commit)" + $suiteSince = "$($prevManifest.source.rynthSuite.commit)" + } else { + $sinceDate = ConvertTo-SinceDate $prevRelease + } + $notesFrom = @( + @{ Repo = 'RynthCore'; Root = $RepoRoot; Files = (Get-ChangelogFiles $RepoRoot $coreSince $sinceDate) }, + @{ Repo = 'RynthSuite'; Root = $RynthSuiteRoot; Files = (Get-ChangelogFiles $RynthSuiteRoot $suiteSince $sinceDate) } + ) + + $manifest = [ordered]@{ + schema = 1 + product = 'RynthCore + RynthSuite' + version = $Version + release = $release + builtUtc = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + previous = $prevRelease + installer = [ordered]@{ file = $setupName; size = (Get-Item (Join-Path $pkgDir $setupName)).Length; sha256 = $setupHash } + source = [ordered]@{ + rynthCore = [ordered]@{ branch = $CoreState.branch; commit = $CoreState.commit; dirty = $CoreState.dirty } + rynthSuite = [ordered]@{ branch = $SuiteState.branch; commit = $SuiteState.commit; dirty = $SuiteState.dirty } + } + components = @($components) + changelog = @($notesFrom | ForEach-Object { $r = $_.Repo; $_.Files | ForEach-Object { "$r/$_" } }) + # Baseline the notes were built from (reused when this version is rebuilt). + changelogSince = [ordered]@{ rynthCore = $coreSince; rynthSuite = $suiteSince; date = $sinceDate } + } + $manifestJson = $manifest | ConvertTo-Json -Depth 6 + Write-Utf8 (Join-Path $pkgDir 'release-manifest.json') $manifestJson + + # RELEASE-NOTES.md: install/verify steps, component table, then the Changelog entries + # (their headings demoted two levels so they nest under "Changes"). + $sb = New-Object System.Text.StringBuilder + $short = { param($s) if ($s.commit) { "$($s.branch)@$($s.commit.Substring(0,7))$(if ($s.dirty) { ' (uncommitted changes!)' })" } else { 'unknown' } } + [void]$sb.AppendLine("# RynthCore + RynthSuite $Version") + [void]$sb.AppendLine() + [void]$sb.AppendLine("Release $release, built $($manifest.builtUtc). Previous release: $(if ($prevRelease) { $prevRelease } else { 'none recorded' }).") + [void]$sb.AppendLine("Source: RynthCore $(& $short $CoreState), RynthSuite $(& $short $SuiteState).") + [void]$sb.AppendLine() + [void]$sb.AppendLine("## Install") + [void]$sb.AppendLine("- Close Asheron's Call clients and the RynthCore launcher, then run ``$setupName``. It upgrades earlier RynthCore / RynthBundle installs in place.") + [void]$sb.AppendLine("- The installer asks for the RynthCore and RynthSuite folders; RynthAi, the Loot Editor and the Monster Editor are included, experimental plugins are optional components.") + [void]$sb.AppendLine("- When the .NET 10 Desktop Runtime (x86) is missing it is downloaded from Microsoft during setup.") + [void]$sb.AppendLine("- Silent install: ``$setupName /VERYSILENT /DIR=""C:\Games\RynthCore"" /SUITEDIR=""C:\Games\RynthSuite""``") + [void]$sb.AppendLine("- Verify the download: ``(Get-FileHash .\$setupName).Hash`` must equal ``$setupHash`` (also in SHA256SUMS.txt).") + [void]$sb.AppendLine() + [void]$sb.AppendLine("## Components") + [void]$sb.AppendLine("| Component | Version |") + [void]$sb.AppendLine("|---|---|") + foreach ($c in $components) { [void]$sb.AppendLine("| $($c.name) | $($c.version) |") } + [void]$sb.AppendLine() + [void]$sb.AppendLine("## Changes$(if ($prevRelease) { " since $prevRelease" })") + $anyNotes = $false + foreach ($src in $notesFrom) { + foreach ($rel in $src.Files) { + $anyNotes = $true + [void]$sb.AppendLine() + [void]$sb.AppendLine("### $($src.Repo): $([IO.Path]::GetFileName($rel))") + $text = [IO.File]::ReadAllText((Join-Path $src.Root $rel)) # UTF-8 (Get-Content would read ANSI on 5.1) + foreach ($line in ($text -split "`r?`n")) { + if ($line -match '^#') { [void]$sb.AppendLine("##$line") } else { [void]$sb.AppendLine($line) } + } + } + } + if (-not $anyNotes) { [void]$sb.AppendLine(); [void]$sb.AppendLine("_No Changelog entries were added since the previous release._") } + Write-Utf8 (Join-Path $pkgDir 'RELEASE-NOTES.md') $sb.ToString() + + # SHA256SUMS.txt in sha256sum format ("<hash> *<file>"), covering every other package file. + $sumLines = Get-ChildItem $pkgDir -File | Sort-Object Name | ForEach-Object { "$(Get-Sha256 $_.FullName) *$($_.Name)" } + Write-Utf8 (Join-Path $pkgDir 'SHA256SUMS.txt') (($sumLines -join "`n") + "`n") + + Compress-Archive -Path (Join-Path $pkgDir '*') -DestinationPath $zipPath -CompressionLevel Optimal + + # Re-verify: extract the zip and check every file against SHA256SUMS.txt. + $verifyDir = Join-Path $env:TEMP "RynthCore-deploy-verify-$([guid]::NewGuid().ToString('N'))" + try { + Expand-Archive -Path $zipPath -DestinationPath $verifyDir -Force + foreach ($line in $sumLines) { + $expected, $file = $line -split ' \*', 2 + $actual = Get-Sha256 (Join-Path $verifyDir $file) + if ($actual -ne $expected) { throw "Deployment zip verification failed for ${file}: $actual != $expected" } + } + } finally { + Remove-Item $verifyDir -Recurse -Force -ErrorAction SilentlyContinue + } + + Write-Utf8 $lastManifestFile $manifestJson + $zipMb = [math]::Round((Get-Item $zipPath).Length / 1MB, 1) + Write-Host " Package: $pkgDir" -ForegroundColor Green + Write-Host " Zip: $zipPath (${zipMb} MB, verified)" -ForegroundColor Green + Write-Host " Changelog entries: $($manifest.changelog.Count)" +} + +# Record the version last, so a failed package step is retried (not skipped) on the next run. +if ($Version) { [IO.File]::WriteAllText($lastVersionFile, $Version) } + Write-Host "" Write-Host "SUCCESS" -ForegroundColor Green -Write-Host "Installer: $ScriptDir\Output\RynthCore-Setup.exe" +Write-Host "Installer: $builtInstaller" +if ($Version -and -not $NoPackage) { Write-Host "Deploy: $zipPath" } diff --git a/installer/Publish-Update.ps1 b/installer/Publish-Update.ps1 index 82803d8..2008b62 100644 --- a/installer/Publish-Update.ps1 +++ b/installer/Publish-Update.ps1 @@ -125,14 +125,18 @@ 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 ships in every release (experimental, opt-in per account): the installer -# carries it, so a launcher that updates through this feed gets it as a fresh install does. -# Build-Installer.ps1 fails without Decal; this guards against a -SkipDecalBridge staging. -$bridgeStaged = Join-Path $ScriptDir "staging\app\DecalBridge\RynthCore.DecalBridge.dll" -if (-not (Test-Path $bridgeStaged)) { throw "The installer was built without the Decal bridge ($bridgeStaged missing) - not publishing." } -Write-Host " Decal bridge in the installer: $((Get-Item $bridgeStaged).VersionInfo.FileVersion)" -Copy-Item (Join-Path $ScriptDir "Output\RynthCore-Setup.exe") "$rel\RynthCore-Setup.exe" -Copy-Item (Join-Path $ScriptDir "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll") "$rel\plugins\" +# 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", "RynthLua", "RynthOracle", "RynthInventory" foreach ($name in $suitePlugins) { diff --git a/installer/RynthCore.iss b/installer/RynthCore.iss index 31f65c1..a1842da 100644 --- a/installer/RynthCore.iss +++ b/installer/RynthCore.iss @@ -1,7 +1,18 @@ -; RynthCore + RynthAi Installer -; Build with: Build-Installer.ps1 (requires Inno Setup 6) +; RynthCore + RynthSuite full installer +; Build with: Build-Installer.ps1 (requires Inno Setup 6) — it builds every component from source +; (launcher, engine, loader, RynthAi plugin, Loot Editor, Monster Editor) and stages them under +; installer\staging\core and installer\staging\suite before invoking ISCC on this file. ; Source: https://jrsoftware.org/isdl.php ; +; Install locations are user-defined: +; * RynthCore folder ({app}) — the standard "Select Destination Location" page +; * RynthSuite folder ({code:GetSuiteDir}) — a second folder page right after it +; Both are recorded under HKA\Software\Rynth (CoreDir / SuiteDir); the engine, launcher and plugins +; resolve every path from there (RynthInstallPaths.cs), so neither folder has to be under C:\Games. +; Silent installs: /DIR="<core folder>" /SUITEDIR="<suite folder>". +; Prerequisite: when the .NET 10 Desktop Runtime (x86) is missing, the "installdotnet" task (on by default) +; downloads it from Microsoft and installs it before the files are copied. A failure is reported, never fatal. +; ; NOTE: No ISPP (#define / {#...}) macros are used in this file. ; Build-Installer.ps1 replaces the AppVersion placeholder via text substitution ; before invoking ISCC, so the preprocessor has nothing to expand. @@ -9,13 +20,17 @@ ; APPVERSION_PLACEHOLDER=0.0.0 [Setup] +; Same AppId as every earlier RynthCore / RynthBundle installer, so this upgrades them in place. AppId={{A8B4C2D1-E3F5-4678-9ABC-DEF012345678} AppName=RynthCore +AppVerName=RynthCore + RynthSuite 0.0.0 AppVersion=0.0.0 AppPublisher=RynthCore -AppPublisherURL=https://aelrynth.com/git/rynth/RynthCore +AppPublisherURL=https://aelrynth.com/rynth.html +UninstallDisplayName=RynthCore + RynthSuite DefaultDirName=C:\Games\RynthCore DisableDirPage=no +UsePreviousAppDir=yes DefaultGroupName=RynthCore DisableProgramGroupPage=yes OutputDir=Output @@ -28,45 +43,112 @@ WizardStyle=modern ; the chosen install folder requires it (e.g. C:\Games\). PrivilegesRequired=lowest PrivilegesRequiredOverridesAllowed=dialog -; 32-bit app; works on 32/64-bit Windows -ArchitecturesAllowed=x86 x64 arm64 +; Close a running launcher / editors before replacing their files. +CloseApplications=yes +; 32-bit app; works on 32/64-bit Windows (HKA registry writes land in the 32-bit view, +; which is exactly where RynthInstallPaths reads HKLM from). +ArchitecturesAllowed=x86compatible ArchitecturesInstallIn64BitMode= [Languages] Name: "english"; MessagesFile: "compiler:Default.isl" +[Types] +Name: "full"; Description: "Full install (RynthCore + RynthSuite)" +Name: "core"; Description: "RynthCore only" +Name: "custom"; Description: "Custom"; Flags: iscustom + +[Components] +Name: "core"; Description: "RynthCore launcher, engine and Loot Editor"; Types: full core custom; Flags: fixed +Name: "rynthai"; Description: "RynthSuite: RynthAi plugin (installed and registered with the launcher)"; Types: full +Name: "monstereditor"; Description: "RynthSuite: Monster Editor"; Types: full +; Experimental plugins: unchecked by default in every install type (ticking one switches to Custom). +Name: "experimental"; Description: "RynthSuite: Experimental plugins (work in progress)" +Name: "experimental\rynthchat"; Description: "RynthChat - replacement chat window (classifies and owns game chat)" +Name: "experimental\rynthjuice"; Description: "RynthJuice - floating damage/heal numbers and kill bursts" +Name: "experimental\rynthnav"; Description: "RynthNav - navmesh pathing and portal routing (needs baked NavData tiles)" +Name: "experimental\rynthtracker"; Description: "RynthTracker - per-session kill tracker" +Name: "experimental\rynthvision"; Description: "RynthVision - unclimbable slope, water and radar-range overlays" +Name: "experimental\ubrythai"; Description: "ub-Rythai - Utility Belt tools ported to RynthCore (XP meter, portal gems, chat automation)" + [Tasks] Name: desktopicon; Description: "Create a &desktop shortcut"; GroupDescription: "Additional icons:" +; Only offered when the runtime is missing. RynthCore and its tools are self-contained / NativeAOT and run +; without it; it is installed for framework-dependent add-ons and tools. Skip silently with /MERGETASKS="!installdotnet". +Name: installdotnet; Description: "Download and install the Microsoft .NET 10 Desktop Runtime (x86, about 55 MB; may ask for administrator approval)"; GroupDescription: "Prerequisites:"; Check: DotNet10DesktopMissing + +; Files left by older layouts (the 0.4.x RynthBundle put a framework-dependent launcher, the engine +; and plugins straight into {app}). Mixing those with a newer launcher is what broke 2026-10-04's +; reinstall (RynthCore.App.Avalonia.dll from 0.4.7 + a newer deps.json → missing DesktopLog). +; Only loose top-level binaries/metadata are removed; every file the new build needs is copied back +; by [Files] right after. User data (Logs, AcClient, NavData, DecalBridge, ...) is never touched. +[InstallDelete] +Type: files; Name: "{app}\*.dll" +Type: files; Name: "{app}\*.json" +Type: files; Name: "{app}\*.pdb" +Type: files; Name: "{app}\*.exp" +Type: files; Name: "{app}\*.lib" +Type: files; Name: "{app}\*.previous" +Type: files; Name: "{app}\RynthCore.App.Avalonia.exe" +Type: files; Name: "{app}\RynthCore-Prerequisites.txt" +Type: files; Name: "{app}\Runtime\*.dll" +Type: files; Name: "{app}\Runtime\*.json" +Type: files; Name: "{app}\Runtime\*.pdb" +Type: files; Name: "{app}\Runtime\RynthCore.Injector.exe" +Type: filesandordirs; Name: "{app}\Runtime\Plugins" -; Program files [Files] -; Launcher + engine runtime + Loot Editor go to {app} (default C:\Games\RynthCore\) -Source: "staging\app\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs +; RynthCore: launcher, Runtime\ (engine, loader, native deps), Tools\LootEditor, release.txt +Source: "staging\core\*"; DestDir: "{app}"; Components: core; Flags: ignoreversion recursesubdirs createallsubdirs -; Plugin DLL goes to its canonical home next to plugin data dirs. -; Engine does NOT auto-scan this folder — user adds the full DLL path in the -; launcher's Plugins tab to enable the plugin. See BUILD.md "Deploy RynthAi Plugin". -Source: "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll"; DestDir: "C:\Games\RynthSuite\RynthAi"; Flags: ignoreversion +; RynthSuite: the RynthAi plugin lives next to its data folders in the chosen Suite folder. +Source: "staging\suite\RynthAi\RynthCore.Plugin.RynthAi.dll"; DestDir: "{code:GetSuiteDir}\RynthAi"; Components: rynthai; Flags: ignoreversion +; Monster Editor: RynthAi's dashboard launches it from <RynthAi>\MonsterEditor\. +Source: "staging\suite\RynthAi\MonsterEditor\*"; DestDir: "{code:GetSuiteDir}\RynthAi\MonsterEditor"; Components: monstereditor; Flags: ignoreversion recursesubdirs createallsubdirs -; Data directories (created once; never removed on uninstall) +; Experimental plugins: each in its own <RynthSuite>\<Name>\ folder (the layout the launcher already uses). +Source: "staging\suite\RynthChat\RynthCore.Plugin.RynthChat.dll"; DestDir: "{code:GetSuiteDir}\RynthChat"; Components: experimental\rynthchat; Flags: ignoreversion +Source: "staging\suite\RynthJuice\RynthCore.Plugin.RynthJuice.dll"; DestDir: "{code:GetSuiteDir}\RynthJuice"; Components: experimental\rynthjuice; Flags: ignoreversion +Source: "staging\suite\RynthNav\RynthCore.Plugin.RynthNav.dll"; DestDir: "{code:GetSuiteDir}\RynthNav"; Components: experimental\rynthnav; Flags: ignoreversion +Source: "staging\suite\RynthTracker\RynthCore.Plugin.RynthTracker.dll"; DestDir: "{code:GetSuiteDir}\RynthTracker"; Components: experimental\rynthtracker; Flags: ignoreversion +Source: "staging\suite\RynthVision\RynthCore.Plugin.RynthVision.dll"; DestDir: "{code:GetSuiteDir}\RynthVision"; Components: experimental\rynthvision; Flags: ignoreversion +Source: "staging\suite\UbRythai\RynthCore.Plugin.UbRythai.dll"; DestDir: "{code:GetSuiteDir}\UbRythai"; Components: experimental\ubrythai; Flags: ignoreversion +; RynthNav reads <RynthCore>\NavData. Starter portal list only; a newer one from RynthNav.PortalGraph is kept. +Source: "staging\navdata\portals.tsv"; DestDir: "{app}\NavData"; Components: experimental\rynthnav; Flags: onlyifdoesntexist uninsneveruninstall + +; RynthAi data directories (created once; never removed on uninstall — they hold user profiles) [Dirs] -Name: "C:\Games\RynthSuite\RynthAi"; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\NavProfiles"; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\LootProfiles"; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\MetaFiles"; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\MetaProfiles"; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\SettingsProfiles"; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\SettingsProfiles\ACEmulator"; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\LuaScripts"; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\Logs"; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\pvars"; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\ItemGiver"; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\NavProfiles"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\LootProfiles"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\MetaFiles"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\MetaProfiles"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\SettingsProfiles"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\SettingsProfiles\ACEmulator"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\MonsterProfiles"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\LuaScripts"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\Logs"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\pvars"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\ItemGiver"; Components: rynthai; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\AutoVendor"; Components: rynthai; Flags: uninsneveruninstall +; RynthNav tiles baked by RynthNav.Baker (default --out) go here; kept on uninstall. +Name: "{app}\NavData"; Components: experimental\rynthnav; Flags: uninsneveruninstall + +; Install locations for the engine / launcher / plugins (see RynthInstallPaths.cs), plus a one-shot +; hand-off the launcher consumes on next start to add the plugin to its Plugins list. +; HKA = HKCU for a per-user install, HKLM for an all-users (elevated) install. +[Registry] +Root: HKA; Subkey: "Software\Rynth"; ValueType: string; ValueName: "CoreDir"; ValueData: "{app}"; Flags: uninsdeletevalue uninsdeletekeyifempty +Root: HKA; Subkey: "Software\Rynth"; ValueType: string; ValueName: "SuiteDir"; ValueData: "{code:GetSuiteDir}"; Flags: uninsdeletevalue uninsdeletekeyifempty +Root: HKA; Subkey: "Software\Rynth"; ValueType: string; ValueName: "PendingPluginRegistration"; ValueData: "{code:GetPendingPlugins}"; Check: HasPendingPlugins; Flags: uninsdeletevalue ; Shortcuts [Icons] ; Start Menu Name: "{group}\RynthCore"; Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Comment: "Launch RynthCore and inject into Asheron's Call" Name: "{group}\Loot Editor"; Filename: "{app}\Tools\LootEditor\RynthCore.LootEditor.exe"; WorkingDir: "{app}\Tools\LootEditor"; Comment: "Edit VTank-style loot profiles" +Name: "{group}\Monster Editor"; Filename: "{code:GetSuiteDir}\RynthAi\MonsterEditor\RynthCore.MonsterEditor.exe"; WorkingDir: "{code:GetSuiteDir}\RynthAi\MonsterEditor"; Components: monstereditor; Comment: "Edit RynthAi monster profiles" +Name: "{group}\RynthSuite Folder"; Filename: "{code:GetSuiteDir}"; Components: rynthai Name: "{group}\Uninstall RynthCore"; Filename: "{uninstallexe}" ; Optional Desktop shortcut (created only when the desktopicon task is checked) @@ -81,8 +163,8 @@ Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Flags: nowait runasorigina [UninstallRun] ; Decal + RynthCore (experimental): remove the Decal bridge's registration, only -; what the launcher added (see docs/DECAL_BRIDGE_PLAN.md). Every release ships the bridge -; ({app}\DecalBridge, staged by Build-Installer.ps1), so this always runs; with nothing +; 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' @@ -90,6 +172,22 @@ Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Flags: nowait runasorigina Filename: "{app}\RynthCore.exe"; Parameters: "--decal-bridge-unregister"; Flags: runhidden waituntilterminated; RunOnceId: "RynthCoreDecalBridgeUnregister" [Code] +const + DefaultSuiteDir = 'C:\Games\RynthSuite'; + { Microsoft's permalink to the latest .NET 10 Desktop Runtime (x86 to match RynthCore's x86 binaries). } + DotNetDesktopUrl = 'https://aka.ms/dotnet/10.0/windowsdesktop-runtime-win-x86.exe'; + DotNetDesktopFile = 'windowsdesktop-runtime-10-win-x86.exe'; + DotNetManualUrl = 'https://dotnet.microsoft.com/download/dotnet/10.0'; + +var + SuiteDirPage: TInputDirWizardPage; + DotNetDownloadPage: TDownloadWizardPage; + { Set once the .NET step ran (interactive: on leaving the Ready page; silent: in PrepareToInstall). } + DotNetHandled: Boolean; + { True once the user (or /SUITEDIR / a previous install) chose the Suite folder explicitly; + until then it follows the RynthCore folder as a sibling "RynthSuite" folder. } + SuiteDirPinned: Boolean; + function CmdLineParamExists(const Value: string): Boolean; var I: Integer; @@ -103,6 +201,303 @@ begin end; end; +{ Returns the value of a /NAME=value command-line switch, or '' when absent. } +function CmdLineParamValue(const Name: string): string; +var + I: Integer; + Prefix: string; +begin + Result := ''; + Prefix := '/' + Name + '='; + for I := 1 to ParamCount do + if CompareText(Copy(ParamStr(I), 1, Length(Prefix)), Prefix) = 0 then + begin + Result := RemoveQuotes(Copy(ParamStr(I), Length(Prefix) + 1, MaxInt)); + Exit; + end; +end; + +{ Suite folder recorded by an earlier install in the SAME install mode (HKA: HKCU per-user, HKLM all-users), + or ''. Never adopt the other mode's folder: two installs sharing a Suite folder would delete each other's + files on uninstall. } +function RegisteredSuiteDir: string; +begin + Result := ''; + if not RegQueryStringValue(HKA, 'Software\Rynth', 'SuiteDir', Result) then + Result := ''; +end; + +{ Default Suite folder for a given RynthCore folder: its sibling "RynthSuite". } +function SiblingSuiteDir(const CoreDir: string): string; +begin + Result := AddBackslash(ExtractFileDir(RemoveBackslashUnlessRoot(CoreDir))) + 'RynthSuite'; +end; + +// {code:GetSuiteDir}: the chosen RynthSuite folder, without a trailing backslash. +function GetSuiteDir(Param: string): string; +begin + if SuiteDirPage = nil then + Result := DefaultSuiteDir + else if WizardSilent and not SuiteDirPinned then + { Silent installs never run NextButtonClick: follow /DIR= with a sibling RynthSuite folder. } + Result := SiblingSuiteDir(WizardDirValue) + else + Result := RemoveBackslashUnlessRoot(Trim(SuiteDirPage.Values[0])); +end; + +// Number of entries in ExperimentalPluginName; keep in sync with the [Components]/[Files] experimental rows. +const + ExperimentalCount = 6; + +// Experimental plugin names; component "experimental\<lowercase name>" installs <Suite>\<Name>\RynthCore.Plugin.<Name>.dll. +function ExperimentalPluginName(Index: Integer): string; +begin + case Index of + 0: Result := 'RynthChat'; + 1: Result := 'RynthJuice'; + 2: Result := 'RynthNav'; + 3: Result := 'RynthTracker'; + 4: Result := 'RynthVision'; + 5: Result := 'UbRythai'; + else + Result := ''; + end; +end; + +function ExperimentalSelected(Index: Integer): Boolean; +begin + Result := WizardIsComponentSelected('experimental\' + Lowercase(ExperimentalPluginName(Index))); +end; + +{ True when anything is going into the RynthSuite folder (controls the Suite folder page / memo line). } +function AnySuiteComponentSelected: Boolean; +var + I: Integer; +begin + Result := WizardIsComponentSelected('rynthai') or WizardIsComponentSelected('monstereditor'); + for I := 0 to ExperimentalCount - 1 do + if ExperimentalSelected(I) then + Result := True; +end; + +// {code:GetPendingPlugins}: ';'-separated plugin DLLs for the launcher to add to its Plugins list on next start. +function GetPendingPlugins(Param: string): string; +var + I: Integer; + Name: string; +begin + Result := ''; + if WizardIsComponentSelected('rynthai') then + Result := GetSuiteDir('') + '\RynthAi\RynthCore.Plugin.RynthAi.dll'; + for I := 0 to ExperimentalCount - 1 do + if ExperimentalSelected(I) then + begin + Name := ExperimentalPluginName(I); + if Result <> '' then + Result := Result + ';'; + Result := Result + GetSuiteDir('') + '\' + Name + '\RynthCore.Plugin.' + Name + '.dll'; + end; +end; + +function HasPendingPlugins: Boolean; +begin + Result := GetPendingPlugins('') <> ''; +end; + +{ ── .NET 10 Desktop Runtime (x86) ─────────────────────────────────────────── } + +{ True when Root (a ...\shared\Microsoft.WindowsDesktop.App folder) holds a 10.x version folder. } +function HasVersion10Folder(const Root: string): Boolean; +var + FindRec: TFindRec; +begin + Result := False; + if FindFirst(AddBackslash(Root) + '10.*', FindRec) then + try + repeat + if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY <> 0 then + begin + Result := True; + Exit; + end; + until not FindNext(FindRec); + finally + FindClose(FindRec); + end; +end; + +{ Detects the x86 Desktop Runtime 10.x the way the .NET host does: the shared framework folder under + Program Files (x86)\dotnet, or the installer's registration in the 32-bit registry view. } +function IsDotNet10DesktopX86Installed: Boolean; +var + Names: TArrayOfString; + I: Integer; +begin + Result := HasVersion10Folder(ExpandConstant('{commonpf32}\dotnet\shared\Microsoft.WindowsDesktop.App')); + if Result then Exit; + if RegGetValueNames(HKLM32, 'SOFTWARE\dotnet\Setup\InstalledVersions\x86\sharedfx\Microsoft.WindowsDesktop.App', Names) then + for I := 0 to GetArrayLength(Names) - 1 do + if Copy(Names[I], 1, 3) = '10.' then + begin + Result := True; + Exit; + end; +end; + +// Check function for the installdotnet task: offer it only when the runtime is missing. +function DotNet10DesktopMissing: Boolean; +begin + Result := not IsDotNet10DesktopX86Installed; +end; + +function OnDotNetDownloadProgress(const Url, FileName: String; const Progress, ProgressMax: Int64): Boolean; +begin + Result := True; { never cancel from code; the download page has its own Abort button } +end; + +{ Downloads and runs the .NET 10 Desktop Runtime installer when the task is selected and the runtime is + still missing. Returns '' on success / nothing to do, else a reason. Never blocks the RynthCore install. } +function InstallDotNetRuntime(UsePage: Boolean): string; +var + SetupPath: string; + ResultCode: Integer; +begin + Result := ''; + DotNetHandled := True; + if not WizardIsTaskSelected('installdotnet') or IsDotNet10DesktopX86Installed then + Exit; + + Log('.NET 10 Desktop Runtime (x86) missing; downloading ' + DotNetDesktopUrl); + try + if UsePage then + begin + DotNetDownloadPage.Clear; + DotNetDownloadPage.Add(DotNetDesktopUrl, DotNetDesktopFile, ''); + DotNetDownloadPage.Show; + try + DotNetDownloadPage.Download; + finally + DotNetDownloadPage.Hide; + end; + end + else + DownloadTemporaryFile(DotNetDesktopUrl, DotNetDesktopFile, '', @OnDotNetDownloadProgress); + except + Result := 'the download failed (' + GetExceptionMessage + ')'; + Exit; + end; + + { The runtime's own bundle asks for elevation (UAC) itself when this setup is not elevated. } + SetupPath := ExpandConstant('{tmp}\' + DotNetDesktopFile); + Log('Running ' + SetupPath + ' /install /quiet /norestart'); + if not ShellExec('', SetupPath, '/install /quiet /norestart', '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then + Result := 'its installer could not be started (' + SysErrorMessage(ResultCode) + ')' + { 0 = installed, 3010/1641 = installed (restart pending/started), 1638 = a newer version is already installed } + else if (ResultCode <> 0) and (ResultCode <> 3010) and (ResultCode <> 1641) and (ResultCode <> 1638) then + Result := 'its installer exited with code ' + IntToStr(ResultCode) + ' (1602 = cancelled)' + else + Log('.NET 10 Desktop Runtime installer finished, exit code ' + IntToStr(ResultCode)); +end; + +{ Runs the .NET step and reports (but never fails on) a problem. } +procedure HandleDotNetRuntime(UsePage: Boolean); +var + Problem: string; +begin + Problem := InstallDotNetRuntime(UsePage); + if Problem = '' then Exit; + Log('.NET 10 Desktop Runtime was not installed: ' + Problem); + if not WizardSilent then + MsgBox('The Microsoft .NET 10 Desktop Runtime could not be installed: ' + Problem + '.' + #13#10#13#10 + + 'RynthCore will still be installed and works without it (it is self-contained). ' + + 'You can install the runtime later from:' + #13#10 + DotNetManualUrl, mbInformation, MB_OK); +end; + +procedure InitializeWizard; +var + Initial: string; +begin + { After the Components page, so ShouldSkipPage knows whether any Suite component was picked. } + SuiteDirPage := CreateInputDirPage(wpSelectComponents, + 'Select RynthSuite Location', + 'Where should the RynthSuite plugins and their data be installed?', + 'RynthAi, the Monster Editor and any experimental plugins you picked will be installed into the RynthSuite folder below, and your ' + + 'profiles (nav, loot, meta, settings) are kept there. To continue, click Next. ' + + 'If you would like to select a different folder, click Browse.', + False, 'RynthSuite'); + SuiteDirPage.Add(''); + + { Priority: /SUITEDIR= → previous install of this setup → registry → C:\Games\RynthSuite. } + Initial := CmdLineParamValue('SUITEDIR'); + if Initial = '' then Initial := GetPreviousData('SuiteDir', ''); + if Initial = '' then Initial := RegisteredSuiteDir; + SuiteDirPinned := Initial <> ''; + if Initial = '' then Initial := DefaultSuiteDir; + SuiteDirPage.Values[0] := Initial; + + { Progress page for the optional .NET 10 Desktop Runtime download (shown only when that task runs). } + DotNetDownloadPage := CreateDownloadPage('Downloading Prerequisites', + 'Downloading the Microsoft .NET 10 Desktop Runtime (x86)...', @OnDotNetDownloadProgress); +end; + +procedure RegisterPreviousData(PreviousDataKey: Integer); +begin + SetPreviousData(PreviousDataKey, 'SuiteDir', GetSuiteDir('')); +end; + +function ShouldSkipPage(PageID: Integer): Boolean; +begin + { No Suite components selected → no Suite folder to choose. } + Result := (SuiteDirPage <> nil) and (PageID = SuiteDirPage.ID) and not AnySuiteComponentSelected; +end; + +function NextButtonClick(CurPageID: Integer): Boolean; +var + Dir: string; +begin + Result := True; + + { Leaving the RynthCore folder page: keep an un-pinned Suite folder beside the chosen Core folder. } + if (CurPageID = wpSelectDir) and not SuiteDirPinned then + SuiteDirPage.Values[0] := SiblingSuiteDir(WizardDirValue); + + if (SuiteDirPage <> nil) and (CurPageID = SuiteDirPage.ID) then + begin + Dir := GetSuiteDir(''); + { Require an absolute local or UNC path (e.g. D:\Games\RynthSuite or \\server\share\RynthSuite). } + if (Length(Dir) < 3) or not ((Copy(Dir, 2, 2) = ':\') or (Copy(Dir, 1, 2) = '\\')) then + begin + MsgBox('Please choose a full folder path for RynthSuite, for example D:\Games\RynthSuite.', mbError, MB_OK); + Result := False; + Exit; + end; + SuiteDirPinned := True; + end; + + { Leaving the Ready page: fetch/install the .NET runtime first (with a progress page) if that task is on. } + if CurPageID = wpReady then + HandleDotNetRuntime(True); +end; + +// Silent installs skip the wizard pages, so the .NET step runs here instead (no progress page). Never blocks. +function PrepareToInstall(var NeedsRestart: Boolean): String; +begin + if not DotNetHandled then + HandleDotNetRuntime(False); + Result := ''; +end; + +function UpdateReadyMemo(Space, NewLine, MemoUserInfoInfo, MemoDirInfo, MemoTypeInfo, + MemoComponentsInfo, MemoGroupInfo, MemoTasksInfo: String): String; +begin + Result := MemoDirInfo + NewLine; + if AnySuiteComponentSelected then + Result := Result + 'RynthSuite location:' + NewLine + Space + GetSuiteDir('') + NewLine; + Result := Result + NewLine + MemoComponentsInfo; + 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 diff --git a/installer/previous-release/last-built-version.txt b/installer/previous-release/last-built-version.txt new file mode 100644 index 0000000..cd573cf --- /dev/null +++ b/installer/previous-release/last-built-version.txt @@ -0,0 +1 @@ +2026.10.5.24 \ No newline at end of file diff --git a/installer/previous-release/last-release-manifest.json b/installer/previous-release/last-release-manifest.json new file mode 100644 index 0000000..b606957 --- /dev/null +++ b/installer/previous-release/last-release-manifest.json @@ -0,0 +1,104 @@ +{ + "schema": 1, + "product": "RynthCore + RynthSuite", + "version": "2026.10.5.24", + "release": 2026100524, + "builtUtc": "2026-10-11T13:39:50Z", + "previous": "2026.10.5.21", + "installer": { + "file": "RynthCore-Setup-2026.10.5.24.exe", + "size": 131607143, + "sha256": "377b3325f6bafc49bf0f892d14227cabc2f500af2c5465b152ccb25302fd6fa2" + }, + "source": { + "rynthCore": { + "branch": "main", + "commit": "75bac262088ee2436e74d5eb7187d9933a027a1c", + "dirty": false + }, + "rynthSuite": { + "branch": "main", + "commit": "fc0d7a0876f979b641bfb7721bd7bf14df819e81", + "dirty": false + } + }, + "components": [ + { + "name": "Launcher (RynthCore.exe)", + "file": "core\\RynthCore.exe", + "version": "2026.10.5.24+75bac262088ee2436e74d5eb7187d9933a027a1c" + }, + { + "name": "Engine", + "file": "core\\Runtime\\RynthCore.Engine.dll", + "version": "2026.10.5.24+75bac262088ee2436e74d5eb7187d9933a027a1c" + }, + { + "name": "Loader", + "file": "core\\Runtime\\RynthCore.Loader.dll", + "version": "" + }, + { + "name": "Loot Editor", + "file": "core\\Tools\\LootEditor\\RynthCore.LootEditor.exe", + "version": "2026.10.5.24+fc0d7a0876f979b641bfb7721bd7bf14df819e81" + }, + { + "name": "RynthAi plugin", + "file": "suite\\RynthAi\\RynthCore.Plugin.RynthAi.dll", + "version": "1.0.0+fc0d7a0876f979b641bfb7721bd7bf14df819e81" + }, + { + "name": "Monster Editor", + "file": "suite\\RynthAi\\MonsterEditor\\RynthCore.MonsterEditor.exe", + "version": "2026.10.5.24+fc0d7a0876f979b641bfb7721bd7bf14df819e81" + }, + { + "name": "RynthChat (experimental)", + "file": "suite\\RynthChat\\RynthCore.Plugin.RynthChat.dll", + "version": "1.0.0+fc0d7a0876f979b641bfb7721bd7bf14df819e81" + }, + { + "name": "RynthJuice (experimental)", + "file": "suite\\RynthJuice\\RynthCore.Plugin.RynthJuice.dll", + "version": "0.1.2-experimental+fc0d7a0876f979b641bfb7721bd7bf14df819e81" + }, + { + "name": "RynthNav (experimental)", + "file": "suite\\RynthNav\\RynthCore.Plugin.RynthNav.dll", + "version": "1.0.0+fc0d7a0876f979b641bfb7721bd7bf14df819e81" + }, + { + "name": "RynthTracker (experimental)", + "file": "suite\\RynthTracker\\RynthCore.Plugin.RynthTracker.dll", + "version": "1.0.0+fc0d7a0876f979b641bfb7721bd7bf14df819e81" + }, + { + "name": "RynthVision (experimental)", + "file": "suite\\RynthVision\\RynthCore.Plugin.RynthVision.dll", + "version": "1.0.0+fc0d7a0876f979b641bfb7721bd7bf14df819e81" + }, + { + "name": "UbRythai (experimental)", + "file": "suite\\UbRythai\\RynthCore.Plugin.UbRythai.dll", + "version": "3.1.10+fc0d7a0876f979b641bfb7721bd7bf14df819e81" + } + ], + "changelog": [ + "RynthCore/Changelog/2026-10-08-installer-2026.10.5.21-release.md", + "RynthCore/Changelog/2026-10-09-release-2026.10.5.22-buffs-picker.md", + "RynthCore/Changelog/2026-10-10-hookresolver-ui-1.0.1-tmds-dbus-security.md", + "RynthCore/Changelog/2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md", + "RynthSuite/Changelog/2026-10-07-release-0.5.25-enl-sigil-chain.md", + "RynthSuite/Changelog/2026-10-08-release-0.5.28-drawer-no-toggles.md", + "RynthSuite/Changelog/2026-10-08-release-0.5.29-profile-load-item-info.md", + "RynthSuite/Changelog/2026-10-08-release-0.5.30-bounty-tracker.md", + "RynthSuite/Changelog/2026-10-09-release-0.5.31-spells-buff-profiles.md", + "RynthSuite/Changelog/2026-10-09-release-0.5.32-mini-remote-lum-rate.md" + ], + "changelogSince": { + "rynthCore": "d46cd9114bf2330df4ae1fe4fc82b9e864603038", + "rynthSuite": "c60243cda397cc1b8fad4f3d51a13bd1ff7b98a8", + "date": "" + } +} \ No newline at end of file diff --git a/loot-port-plan.txt b/loot-port-plan.txt new file mode 100644 index 0000000..9c2ab1c --- /dev/null +++ b/loot-port-plan.txt @@ -0,0 +1,204 @@ +# Plan: Port Loot System from NexSuite2 NexAi to NexCore NexAi + +## Context + +Porting the Loot subsystem (LootManager + VTankLootParser) from the old Decal-dependent NexAi at C:\Projects\NexSuite2\Plugins\NexAi\Loot\ to the new NexCore-based NexAi at C:\Projects\NexSuite\Plugins\NexCore.Plugin.NexAi\. The goal is to copy the files and adapt them to use NexCore's API instead of Decal's. + +### Decisions +- Salvage: Implement now — find VAs for SalvagePanelAdd/SalvagePanelSalvage in acclient.exe +- Loot evaluation: VTankLootParser IS the reimplemented VTank loot engine (handles UTL rule trees). Remove VTClassic/uTank2 code — our parser is the sole evaluator. Can add more VTank node types later if profiles need them. +- NeedsID: Always call RequestId on corpse items, wait up to assess window + +--- + +## Files to Copy + +Source (NexSuite2) -> Destination (NexSuite) +Plugins\NexAi\Loot\VTankLootParser.cs (284 ln) -> Plugins\NexCore.Plugin.NexAi\Loot\VTankLootParser.cs +Plugins\NexAi\Loot\LootManager.cs (1149 ln) -> Plugins\NexCore.Plugin.NexAi\Loot\LootManager.cs + +--- + +## Gap Analysis: What NexCore Has vs. What Loot Needs + +### Already Available (no engine work needed) + +Loot Requirement -> NexCore Equivalent +WorldObject.Id, .Name, .ObjectClass -> WorldObjectCache[id] returns WorldObject +WorldObject.Values(LongValueKey, default) -> WorldObject.Values() -> WorldObjectCache.GetIntProperty() -> TryGetObjectIntProperty() +WorldFilter.GetInventory() -> WorldObjectCache.GetInventory() +WorldFilter.GetLandscape() -> WorldObjectCache.GetLandscape() +WorldFilter.Distance(id1, id2) -> WorldObjectCache.Distance(id1, id2) +Actions.SelectItem(id) -> Host.SelectItem(uint) +Actions.UseItem(id, param) -> Host.UseObject(uint) +Actions.RequestId(id) -> Host.RequestId(uint) +Actions.MoveItem(...) -> Host.MoveItemExternal() + Host.MoveItemInternal() +CharacterFilter.Id -> Host.GetPlayerId() +AddChatText(text, color) -> Host.WriteToChat(text, chatType) +OnCreateObject / OnDeleteObject -> NexPluginBase virtual methods +OnUpdateObjectInventory -> NexPluginBase virtual method +OnViewObjectContents / OnStopViewing -> NexPluginBase virtual methods +OnBusyCountIncremented/Decremented -> NexPluginBase virtual methods +FellowshipTracker -> Already in NexCore.Plugin.NexAi/Combat/FellowshipTracker.cs + +### Plugin-Side Tracking (no engine changes) + +BusyState (is player idle?) -> Track _busyCount via OnBusyCountIncremented/Decremented events +OpenedContainer (which corpse is open?) -> Track _openedContainerId via OnViewObjectContents/OnStopViewing events + +--- + +## Must Add to NexCore Engine + SDK + +### 1. InqString — String Property Reading +File: src/NexCore.Engine/Compatibility/ClientObjectHooks.cs + +Why: VTank rule type 1 (StringValueMatch) reads string properties. Corpse ownership reads StringValueKey 16 (LongDesc = "Killed by {name}."). + +- Find VA for CBaseQualities::InqString (near InqInt 0x00590C20 / InqBool 0x00590CA0) +- Add delegate: int InqString(IntPtr qualitiesPtr, uint stype, IntPtr* retval) (ThisCall) +- Add method: TryGetObjectStringProperty(uint objectId, uint stype, out string value) +- Wire through NexCoreApiNative.GetObjectStringPropertyFn -> NexCoreHost.TryGetObjectStringProperty() + +### 2. InqFloat — Float/Double Property Reading +File: src/NexCore.Engine/Compatibility/ClientObjectHooks.cs + +Why: VTank rule types 4 & 5 (DoubleValKeyLE/GE) compare double properties (weapon damage variance, attack mod, etc.). + +- Find VA for CBaseQualities::InqFloat (near InqInt/InqBool) +- Add delegate + method: TryGetObjectFloatProperty(uint objectId, uint stype, out double value) +- Wire through SDK + +### 3. Container Contents API +File: src/NexCore.Engine/Compatibility/ClientObjectHooks.cs or UpdateObjectInventoryHooks.cs + +Why: After opening a corpse, need to enumerate items inside via GetByContainer(corpseId). + +- Expose existing GetExhaustiveContainedItemsList as SDK function: GetContainerContents(uint containerId, uint* outIds, int maxCount) -> int +- Wire through NexCoreApiNative.GetContainerContentsFn -> NexCoreHost.GetContainerContents() + +### 4. Salvage Panel APIs +File: New src/NexCore.Engine/Compatibility/SalvagePanelHooks.cs (or add to ClientHelperHooks) + +Why: Auto-salvage system needs SalvagePanelAdd(itemId) and SalvagePanelSalvage(). + +- Find VAs in acclient.exe APIManager__IAsheronsCallImpl_vtbl (documented as "declared but not yet validated") +- Implement as direct function calls via delegates +- Wire through SDK + +### 5. ObjectClass Expansion +File: Plugins/NexCore.Plugin.NexAi/Combat/AcStubs.cs + WorldObjectCache.cs + +Why: Loot system checks ObjectClass.Corpse, .Salvage, .Container, .Foci. + +- Expand AcObjectClass enum with Corpse, Container, Salvage, Foci values +- Add ITEM_TYPE constants: TYPE_CORPSE=0x00000020, TYPE_CONTAINER=0x00000040 +- Update WorldObjectCache.ClassifyByItemType() to detect these types + +### 6. String + Double Property Access on WorldObject +File: Plugins/NexCore.Plugin.NexAi/Combat/AcStubs.cs + +- Add StringValueKey enum (at minimum key 16 = LongDesc) +- Add DoubleValueKey enum +- Add WorldObject.Values(StringValueKey, default) -> delegates to cache -> SDK +- Add WorldObject.Values(DoubleValueKey, default) -> delegates to cache -> SDK +- Add WorldObjectCache.GetStringProperty() and WorldObjectCache.GetFloatProperty() methods + +--- + +## LootManager Adaptation Summary + +When copying LootManager.cs, these are the specific changes: + +Old (Decal) -> New (NexCore) +CoreManager _core + PluginHost _host -> NexCoreHost _host + WorldObjectCache _cache +_core.Actions.BusyState -> _busyCount > 0 (tracked via events) +_core.Actions.OpenedContainer -> _openedContainerId (tracked via events) +_core.Actions.SelectItem(id) -> _host.SelectItem((uint)id) +_core.Actions.UseItem(id, 0) -> _host.UseObject((uint)id) +_core.Actions.RequestId(id) -> _host.RequestId((uint)id) +_core.Actions.MoveItem(id, dest, slot, true) -> _host.MoveItemInternal((uint)id, (uint)dest, slot, 0) for stacking +_host.Actions.AddChatText(text, color) -> _host.WriteToChat(text, color) +_host.Actions.SalvagePanelAdd(id) -> _host.SalvagePanelAdd((uint)id) (new SDK method) +_host.Actions.SalvagePanelSalvage() -> _host.SalvagePanelSalvage() (new SDK method) +_core.WorldFilter[id] -> _cache[id] +_core.WorldFilter.GetByContainer(id) -> _host.GetContainerContents(id, ...) (new SDK method) +_core.WorldFilter.GetInventory() -> _cache.GetInventory() +_core.WorldFilter.GetLandscape() -> _cache.GetLandscape() +_core.WorldFilter.Distance(a, b) -> _cache.Distance(a, b) +_core.CharacterFilter.Id -> (int)_host.GetPlayerId() +_core.CharacterFilter.Name -> _host.TryGetObjectName(_host.GetPlayerId(), out name) +VTClassic.LootCore (Path 1) -> REMOVED — VTankLootParser handles all UTL evaluation +uTank2.PluginCore.PC.* (Path 3) -> REMOVED — single evaluation path +FLootPluginQueryNeedsID(id) -> Always true — always RequestId +WorldObject.Values((StringValueKey)k, "") -> wo.Values((StringValueKey)k, "") (new method on WorldObject) +WorldObject.Values((DoubleValueKey)k, 0.0) -> wo.Values((DoubleValueKey)k, 0.0) (new method on WorldObject) + +--- + +## Implementation Order + +### Phase 1: Engine — Property APIs +1. Find VAs for CBaseQualities::InqString and CBaseQualities::InqFloat +2. Add to ClientObjectHooks.cs: delegates, TryGetObjectStringProperty(), TryGetObjectFloatProperty() +3. Add to NexCoreApiNative.cs: GetObjectStringPropertyFn, GetObjectFloatPropertyFn +4. Add to NexCoreHost.cs: wrapper methods +5. Wire function pointers in EntryPoint.cs + +### Phase 2: Engine — Container Contents API +1. Add GetContainerContents() wrapper around existing GetExhaustiveContainedItemsList +2. Wire through SDK + +### Phase 3: Engine — Salvage Panel APIs +1. Find VAs for salvage panel functions in acclient.exe vtable +2. Implement + wire through SDK + +### Phase 4: Plugin — Expand Type System +1. AcStubs.cs: Add StringValueKey, DoubleValueKey enums +2. AcStubs.cs: Expand AcObjectClass (Corpse, Container, Salvage, Foci) +3. WorldObject: Add Values(StringValueKey), Values(DoubleValueKey) methods +4. WorldObjectCache: Add GetStringProperty(), GetFloatProperty(), expand classification + +### Phase 5: Plugin — Copy & Adapt Loot Files +1. Copy VTankLootParser.cs -> update namespace, replace Decal types with local types +2. Copy LootManager.cs -> apply all substitutions from table above +3. Simplify to single loot evaluation path (VTankLootParser only) +4. Always-RequestId for NeedsID + +### Phase 6: Plugin — Integration +1. Wire LootManager into NexAiPlugin.cs +2. Add settings to LegacyUiSettings.cs +3. Add chat commands for profile loading + +--- + +## Key Files to Modify + +### Engine (C:\Projects\nexcore\src\NexCore.Engine\) +- Compatibility/ClientObjectHooks.cs — InqString, InqFloat +- Compatibility/UpdateObjectInventoryHooks.cs — GetContainerContents export +- Compatibility/SalvagePanelHooks.cs — NEW: salvage APIs +- EntryPoint.cs — Wire new API function pointers + +### SDK (C:\Projects\nexcore\src\NexCore.PluginSdk\) +- NexCoreApiNative.cs — New function pointer fields +- NexCoreHost.cs — New wrapper methods + +### Plugin (C:\Projects\NexSuite\Plugins\NexCore.Plugin.NexAi\) +- Combat/AcStubs.cs — StringValueKey, DoubleValueKey, expanded ObjectClass +- Combat/WorldObjectCache.cs — Classification expansion, container tracking, new property methods +- Loot/VTankLootParser.cs — NEW (copy + adapt) +- Loot/LootManager.cs — NEW (copy + adapt) +- NexAiPlugin.cs — Wire LootManager +- LegacyUi/LegacyUiSettings.cs — Loot settings + +--- + +## Verification +1. cd src\NexCore.Engine && dotnet publish -c Release — engine builds +2. cd Plugins\NexCore.Plugin.NexAi && dotnet publish -c Release — plugin builds +3. Deploy to C:\Games\NexCore\ + inject into AC client +4. Load a VTank UTL profile via /na lootprofile <path> +5. Verify: corpse detection -> item scanning -> RequestId -> loot evaluation -> pickup +6. Verify: salvage queue processes items correctly +7. Check %USERPROFILE%\Desktop\NexCore.log for errors diff --git a/native/SehTrampoline/SehTrampoline.c b/native/SehTrampoline/SehTrampoline.c index a458eeb..5b4bba8 100644 --- a/native/SehTrampoline/SehTrampoline.c +++ b/native/SehTrampoline/SehTrampoline.c @@ -26,12 +26,36 @@ #define WIN32_LEAN_AND_MEAN #include <windows.h> +/* File version of this native module (bump with every behavioural change). */ +#define RC_SEH_TRAMPOLINE_VERSION 3 /* v3: CoreCLR-hosted engine AVs logged immediately */ + +/* Crash-logger state that the SEH_* wrappers and DllMain also touch (defined below). */ +static __declspec(thread) int t_sehDepth; /* >0 while inside an SEH_* wrapper call */ +static void CrashLoggerFlushOnExit(void); + +/* Every SEH_* wrapper brackets its guarded call with these so the crash logger knows an + * access violation on this thread is about to be caught by our own __except. */ +#define RC_SEH_ENTER() (++t_sehDepth) +#define RC_SEH_LEAVE() (--t_sehDepth) + BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason, LPVOID lpReserved) { - (void)hModule; (void)ul_reason; (void)lpReserved; + (void)hModule; + /* lpReserved != NULL on DLL_PROCESS_DETACH means the process is exiting (ExitProcess), + * which is how AC's own crash handling ends the process: write out any recent + * first-chance AVs so a crash AC swallowed still leaves a trace. */ + if (ul_reason == DLL_PROCESS_DETACH && lpReserved != NULL) { + CrashLoggerFlushOnExit(); + } return TRUE; } +/* Diagnostic: native module version so the engine log can confirm which build is loaded. */ +__declspec(dllexport) unsigned int __cdecl RC_SehTrampolineVersion(void) +{ + return RC_SEH_TRAMPOLINE_VERSION; +} + /* ── Cdecl helpers ─────────────────────────────────────────────────────── */ /* void* __cdecl fn(unsigned int id) — e.g. GetWeenieObject */ @@ -40,14 +64,17 @@ __declspec(dllexport) int __cdecl SEH_CdeclPtrUint(Fn_CdeclPtrUint fn, unsigned int arg, void** out_result) { *out_result = NULL; + RC_SEH_ENTER(); __try { *out_result = fn(arg); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = NULL; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -57,14 +84,17 @@ __declspec(dllexport) int __cdecl SEH_CdeclPtrVoid(Fn_CdeclPtrVoid fn, void** out_result) { *out_result = NULL; + RC_SEH_ENTER(); __try { *out_result = fn(); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = NULL; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -73,13 +103,16 @@ typedef void (__cdecl *Fn_CdeclVoidUintByte)(unsigned int, unsigned char); __declspec(dllexport) int __cdecl SEH_CdeclVoidUintByte(Fn_CdeclVoidUintByte fn, unsigned int arg1, unsigned char arg2) { + RC_SEH_ENTER(); __try { fn(arg1, arg2); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); return 0; } + RC_SEH_LEAVE(); return 1; } @@ -95,13 +128,16 @@ typedef void (__fastcall *Fn_FreeHandsCast)(void* ecx, void* edx, unsigned int s __declspec(dllexport) int __cdecl SEH_FreeHandsCast(void* fn, void* this_ptr, unsigned int spellId, unsigned int targetId) { + RC_SEH_ENTER(); __try { ((Fn_FreeHandsCast)fn)(this_ptr, 0, spellId, targetId); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); return 0; } + RC_SEH_LEAVE(); return 1; } @@ -152,14 +188,17 @@ SEH_ThiscallByteUint(void* fn, void* this_ptr, unsigned int arg, unsigned char* out_result) { *out_result = 0; + RC_SEH_ENTER(); __try { *out_result = _helper_thiscall_byte_uint(fn, this_ptr, arg); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = 0; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -171,14 +210,17 @@ __declspec(dllexport) int __cdecl SEH_ThiscallUintNoArg(void* fn, void* this_ptr, unsigned int* out_result) { *out_result = 0; + RC_SEH_ENTER(); __try { *out_result = _helper_thiscall_uint_noarg(fn, this_ptr); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = 0; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -209,179 +251,480 @@ SEH_ThiscallIntUintPtr(void* fn, void* this_ptr, unsigned int arg1, void* arg2, int* out_result) { *out_result = 0; + RC_SEH_ENTER(); __try { *out_result = _helper_thiscall_int_uint_ptr(fn, this_ptr, arg1, arg2); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = 0; return 0; } + RC_SEH_LEAVE(); return 1; } -/* ── Process-wide native crash logger (VEH) ─────────────────────────────── - * Logs the faulting 32-bit context + a module-resolved stack sweep to a - * dedicated file BEFORE the process dies, for the fatal exceptions that bypass - * NativeAOT's managed handlers: 0xC0000005 (AV / corrupted-state) and - * 0xC0000602 (STATUS_FAIL_FAST from RaiseFailFastException — e.g. an unhandled - * managed exception or a stack-walk fail-fast in the plugin/engine). +/* ── Process-wide native crash logger (fatal-only, v2) ──────────────────── + * Goal: native-crash.log holds FATAL crashes only. v1 logged every first-chance AV + * (including ones AC or our own SEH_* wrappers handle) plus its own stack-sweep faults, + * so its 24-entry cap filled with noise before a real crash could be recorded. * - * This is PURE NATIVE: no managed callback / reverse-P/Invoke transition, so - * unlike the removed managed CrashLogger VEH it cannot itself re-trigger a - * NativeAOT fail-fast on an AC-owned thread. It only OBSERVES — returns - * EXCEPTION_CONTINUE_SEARCH so AC's own SEH / the runtime still proceed exactly - * as before. Uses only kernel32 APIs + hand-rolled formatting (no CRT stdio / - * user32) so the build link line stays unchanged. Hardened: stack sweep in - * __try/__except, capped log count, dedicated file (no contention with the - * managed log). x86 (32-bit) context fields only — matches the WOW64 target. + * All paths are PURE NATIVE (no managed callback / reverse-P/Invoke — that could itself + * trigger a NativeAOT fail-fast on an AC-owned thread) and observe-only: they always + * return EXCEPTION_CONTINUE_SEARCH or chain, so AC's SEH and the runtime proceed exactly + * as before. Only kernel32 APIs + hand-rolled, bounds-checked formatting (no CRT stdio). + * + * 1. Unhandled-exception filter (SetUnhandledExceptionFilter, chained to the previous + * filter): an exception nobody handled is written immediately as FATAL. + * 2. First-chance VEH, immediate: AVs whose faulting address is inside a NativeAOT + * module (engine / plugins). The runtime fail-fasts on those via + * RaiseFailFastException, which bypasses every handler including the filter in (1), + * so first chance is the only chance to record them. 0xC0000602 / 0xC0000409 too. + * 2b. (v3) Same for the CoreCLR-hosted engine (RynthCore.Shim): non-null AVs in JIT'd + * code (private executable memory, no module), coreclr.dll / clrjit.dll, or the + * framework's precompiled System.* / Microsoft.* images. CoreCLR treats a non-null + * AV in managed code as uncatchable and fail-fasts with HandleFatalError (the WER + * signature coreclr.dll+0x2c1c6e c0000005 is that fail-fast site, not the bug), so + * the deferred ring below was never flushed and native-crash.log stayed empty. AVs + * with a data address under 64K are skipped there: CoreCLR turns those into a + * catchable NullReferenceException. + * 3. First-chance VEH, deferred: every other AV (acclient.exe, drivers, DINPUT8, …) is + * formatted into an in-memory ring and written ONLY if the process then dies — via + * the filter in (1), or at ExitProcess (DllMain detach) when it happened within the + * last CL_EXIT_FLUSH_WINDOW_MS (AC's own crash handling ends with ExitProcess). + * AVs that AC handles and survives never reach the file. + * + * Skipped entirely: AVs raised inside our own SEH_* wrappers (t_sehDepth > 0 — our + * __except catches them) and any fault raised while the logger itself is running on + * that thread (t_inLogger — v1 logged its own sweep faults as SehTrampoline.dll+0x13E8). + * + * The stack sweep is bounded to [Esp, NtCurrentTeb()->NtTib.StackBase); v1 read 4096 + * slots past ESP unconditionally and ran off the top of the stack. + * x86 (32-bit) context fields only — matches the WOW64 target. */ +#define CL_SLOT_BYTES 8192 /* one formatted record */ +#define CL_RING_SLOTS 8 /* deferred first-chance records kept in memory */ +#define CL_MAX_IMMEDIATE 16 /* NativeAOT-module / fail-fast records per run */ +#define CL_MAX_FATAL 8 /* unhandled-exception records per run */ +#define CL_MAX_SWEEP_SLOTS 4096 /* stack slots scanned (also capped by StackBase) */ +#define CL_MAX_SWEEP_LINES 96 /* code pointers emitted per record */ +#define CL_EXIT_FLUSH_WINDOW_MS 30000 /* deferred AVs this recent are flushed at exit */ + +#define CL_SLOT_EMPTY 0 +#define CL_SLOT_WRITING 1 +#define CL_SLOT_PENDING 2 /* deferred first-chance AV, not in the file (yet) */ +#define CL_SLOT_DONE 3 /* written to the file, or discarded */ + +typedef struct { + volatile LONG state; + DWORD tid; + DWORD tick; + unsigned int exAddr; + int len; + char text[CL_SLOT_BYTES]; +} CL_SLOT; + static wchar_t g_crashLogPath[MAX_PATH]; -static volatile LONG g_crashCount = 0; -static PVOID g_vehHandle = NULL; +static PVOID g_vehHandle = NULL; +static CL_SLOT g_ring[CL_RING_SLOTS]; +static volatile LONG g_ringNext = 0; +static volatile LONG g_immediateCount = 0; +static volatile LONG g_fatalCount = 0; +static LPTOP_LEVEL_EXCEPTION_FILTER g_prevFilter = NULL; +static __declspec(thread) int t_inLogger; /* logger running on this thread */ +static __declspec(thread) int t_inUef; /* filter running (guards chain cycles) */ -static char* cl_str(char* p, const char* s) { while (*s) { *p++ = *s++; } return p; } +/* ── Bounds-checked text writer ── */ +typedef struct { char* p; char* end; } CL_W; -static char* cl_hex(char* p, unsigned int v) +static void cl_str(CL_W* w, const char* s) +{ + while (*s && w->p < w->end) { *w->p++ = *s++; } +} + +static void cl_hex(CL_W* w, unsigned int v) { const char* H = "0123456789ABCDEF"; int i; - *p++ = '0'; *p++ = 'x'; - for (i = 28; i >= 0; i -= 4) { *p++ = H[(v >> i) & 0xF]; } - return p; + cl_str(w, "0x"); + for (i = 28; i >= 0 && w->p < w->end; i -= 4) { *w->p++ = H[(v >> i) & 0xF]; } } -static char* cl_u(char* p, unsigned int v) +static void cl_u(CL_W* w, unsigned int v) { char tmp[12]; int n = 0; - if (v == 0) { *p++ = '0'; return p; } + if (v == 0) { cl_str(w, "0"); return; } while (v) { tmp[n++] = (char)('0' + (v % 10)); v /= 10; } - while (n) { *p++ = tmp[--n]; } - return p; + while (n && w->p < w->end) { *w->p++ = tmp[--n]; } +} + +/* Leaf file name of a loaded module, as narrow ASCII (lower-cased when lower != 0). */ +static int cl_module_leaf(HMODULE hm, char* out, int cap, int lower) +{ + wchar_t wpath[MAX_PATH]; + DWORD n = GetModuleFileNameW(hm, wpath, MAX_PATH); + DWORD i, leaf = 0; + int k = 0; + for (i = 0; i < n; i++) { if (wpath[i] == L'\\' || wpath[i] == L'/') { leaf = i + 1; } } + for (i = leaf; i < n && k < cap - 1; i++) { + char ch = (char)wpath[i]; + if (lower && ch >= 'A' && ch <= 'Z') { ch = (char)(ch - 'A' + 'a'); } + out[k++] = ch; + } + out[k] = 0; + return k; } /* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */ -static char* cl_sym(char* p, unsigned int addr) +static void cl_sym(CL_W* w, unsigned int addr) { HMODULE hm = NULL; /* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS(0x4) | UNCHANGED_REFCOUNT(0x2) */ if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) && hm) { - wchar_t wpath[MAX_PATH]; - DWORD n = GetModuleFileNameW(hm, wpath, MAX_PATH); - DWORD i, leaf = 0; - for (i = 0; i < n; i++) { if (wpath[i] == L'\\' || wpath[i] == L'/') leaf = i + 1; } - for (i = leaf; i < n; i++) { *p++ = (char)wpath[i]; } - p = cl_str(p, "+"); - p = cl_hex(p, addr - (unsigned int)(UINT_PTR)hm); + char leaf[MAX_PATH]; + cl_module_leaf(hm, leaf, MAX_PATH, 0); + cl_str(w, leaf); + cl_str(w, "+"); + cl_hex(w, addr - (unsigned int)(UINT_PTR)hm); } else { - p = cl_hex(p, addr); + cl_hex(w, addr); } - return p; } -static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) +static int cl_starts_with(const char* s, const char* prefix) { + while (*prefix) { if (*s++ != *prefix++) { return 0; } } + return 1; +} + +/* ── NativeAOT module detection (cached per module base) ── */ +#define CL_MOD_CACHE 16 +static volatile UINT_PTR g_modBase[CL_MOD_CACHE]; +static volatile LONG g_modManaged[CL_MOD_CACHE]; +static volatile LONG g_modNext = 0; + +/* True when addr lies in a NativeAOT image (engine / plugin). NativeAOT images export + * DotNetRuntimeDebugHeader; RynthCore.* names are a fallback (minus our native DLLs). */ +static int cl_is_nativeaot_address(unsigned int addr) +{ + HMODULE hm = NULL; + int i, managed; + if (!GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) || !hm) { return 0; } + + for (i = 0; i < CL_MOD_CACHE; i++) { + if (g_modBase[i] == (UINT_PTR)hm) { return (int)g_modManaged[i]; } + } + + managed = GetProcAddress(hm, "DotNetRuntimeDebugHeader") != NULL; + if (!managed) { + char leaf[MAX_PATH]; + cl_module_leaf(hm, leaf, MAX_PATH, 1); + managed = cl_starts_with(leaf, "rynthcore.") + && !cl_starts_with(leaf, "rynthcore.sehtrampoline") + && !cl_starts_with(leaf, "rynthcore.cimgui"); + } + + /* Benign race: base is cleared first and published last, so a concurrent reader + * either misses the entry (and recomputes) or sees a matching flag. */ + i = (int)((unsigned int)InterlockedIncrement(&g_modNext) % CL_MOD_CACHE); + g_modBase[i] = 0; + g_modManaged[i] = managed; + g_modBase[i] = (UINT_PTR)hm; + return managed; +} + +/* True when addr is code of the CoreCLR-hosted engine: JIT'd code (committed private + * executable memory outside any module), the runtime itself (coreclr.dll, clrjit.dll), + * or a precompiled framework image (System.* / Microsoft.*, e.g. Marshal.ReadIntPtr in + * System.Private.CoreLib.dll). Not cached: the JIT path has no module base to key on, + * and VirtualQuery is cheap next to formatting a record. */ +static int cl_is_coreclr_address(unsigned int addr) +{ + HMODULE hm = NULL; + if (!GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) || !hm) { + MEMORY_BASIC_INFORMATION mbi; + if (VirtualQuery((LPCVOID)(UINT_PTR)addr, &mbi, sizeof(mbi)) == 0) { return 0; } + return mbi.State == MEM_COMMIT && mbi.Type == MEM_PRIVATE + && (mbi.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE + | PAGE_EXECUTE_WRITECOPY)) != 0; + } + { + char leaf[MAX_PATH]; + cl_module_leaf(hm, leaf, MAX_PATH, 1); + return cl_starts_with(leaf, "coreclr.dll") + || cl_starts_with(leaf, "clrjit.dll") + || cl_starts_with(leaf, "system.") + || cl_starts_with(leaf, "microsoft."); + } +} + +/* ── Record formatting ── */ + +/* Formats one crash record (header, registers, bounded stack sweep) into buf. + * Returns the byte count. Reads of stack memory are guarded by __try. */ +static int cl_format(char* buf, int cap, PEXCEPTION_POINTERS ep, const char* banner) +{ + CL_W w; + CONTEXT* c = ep->ContextRecord; DWORD code = ep->ExceptionRecord->ExceptionCode; - if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) { - return EXCEPTION_CONTINUE_SEARCH; + unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + + w.p = buf; + w.end = buf + cap - 64; /* reserve room for the END line */ + + cl_str(&w, "\r\n==== NATIVE CRASH LOGGER: "); + cl_str(&w, banner); + cl_str(&w, " ====\r\n code="); + cl_hex(&w, code); + cl_str(&w, " exAddr="); + cl_sym(&w, exAddr); + cl_str(&w, " tid="); + cl_u(&w, GetCurrentThreadId()); + { + SYSTEMTIME st; GetLocalTime(&st); + cl_str(&w, " time="); + cl_u(&w, st.wHour); cl_str(&w, ":"); + if (st.wMinute < 10) { cl_str(&w, "0"); } cl_u(&w, st.wMinute); cl_str(&w, ":"); + if (st.wSecond < 10) { cl_str(&w, "0"); } cl_u(&w, st.wSecond); } - if (InterlockedIncrement(&g_crashCount) > 24) { - return EXCEPTION_CONTINUE_SEARCH; + if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) { + unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0]; + unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1]; + cl_str(&w, " access="); + cl_str(&w, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ")); + cl_str(&w, " dataAddr="); + cl_hex(&w, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */ } + cl_str(&w, "\r\n eip="); cl_sym(&w, c->Eip); + cl_str(&w, " esp="); cl_hex(&w, c->Esp); + cl_str(&w, " ebp="); cl_hex(&w, c->Ebp); + cl_str(&w, "\r\n eax="); cl_hex(&w, c->Eax); + cl_str(&w, " ebx="); cl_hex(&w, c->Ebx); + cl_str(&w, " ecx="); cl_hex(&w, c->Ecx); + cl_str(&w, " edx="); cl_hex(&w, c->Edx); + cl_str(&w, " esi="); cl_hex(&w, c->Esi); + cl_str(&w, " edi="); cl_hex(&w, c->Edi); + cl_str(&w, "\r\n stack code pointers (esp -> StackBase):\r\n"); { - HANDLE h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); - if (h == INVALID_HANDLE_VALUE) { return EXCEPTION_CONTINUE_SEARCH; } - SetFilePointer(h, 0, NULL, FILE_END); - - { - char buf[4096]; - char* p = buf; - CONTEXT* c = ep->ContextRecord; - unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; - DWORD wr; - - p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (SEH VEH) ====\r\n code="); - p = cl_hex(p, code); - p = cl_str(p, " exAddr="); - p = cl_sym(p, exAddr); - p = cl_str(p, " tid="); - p = cl_u(p, GetCurrentThreadId()); - { - SYSTEMTIME st; GetLocalTime(&st); - p = cl_str(p, " time="); - p = cl_u(p, st.wHour); p = cl_str(p, ":"); - if (st.wMinute < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wMinute); p = cl_str(p, ":"); - if (st.wSecond < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wSecond); - } - if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) { - unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0]; - unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1]; - p = cl_str(p, " access="); - p = cl_str(p, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ")); - p = cl_str(p, " dataAddr="); - p = cl_hex(p, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */ - } - p = cl_str(p, "\r\n eip="); p = cl_sym(p, c->Eip); - p = cl_str(p, " esp="); p = cl_hex(p, c->Esp); - p = cl_str(p, " ebp="); p = cl_hex(p, c->Ebp); - p = cl_str(p, "\r\n eax="); p = cl_hex(p, c->Eax); - p = cl_str(p, " ebx="); p = cl_hex(p, c->Ebx); - p = cl_str(p, " ecx="); p = cl_hex(p, c->Ecx); - p = cl_str(p, " edx="); p = cl_hex(p, c->Edx); - p = cl_str(p, " esi="); p = cl_hex(p, c->Esi); - p = cl_str(p, " edi="); p = cl_hex(p, c->Edi); - p = cl_str(p, "\r\n stack code pointers (esp -> up):\r\n"); - WriteFile(h, buf, (DWORD)(p - buf), &wr, NULL); + /* The handler runs on the faulting thread, so this TEB's stack bounds apply to + * the faulting ESP. Never read at or past StackBase (top of the stack). */ + NT_TIB* tib = (NT_TIB*)NtCurrentTeb(); + UINT_PTR base = (UINT_PTR)tib->StackBase; + UINT_PTR limit = (UINT_PTR)tib->StackLimit; + UINT_PTR esp = (UINT_PTR)c->Esp; + if (esp < limit || esp >= base) { + cl_str(&w, " <esp outside this thread's stack; sweep skipped>\r\n"); + } else { + unsigned int slots = (unsigned int)((base - esp) / sizeof(unsigned int)); + if (slots > CL_MAX_SWEEP_SLOTS) { slots = CL_MAX_SWEEP_SLOTS; } __try { - unsigned int* sp = (unsigned int*)c->Esp; - int i, emitted = 0; - for (i = 0; i < 4096 && emitted < 96; i++) { + const unsigned int* sp = (const unsigned int*)esp; + unsigned int i; + int emitted = 0; + /* 320 bytes of headroom = one full "+0xOFF module+0xRVA" line. */ + for (i = 0; i < slots && emitted < CL_MAX_SWEEP_LINES && (w.end - w.p) > 320; i++) { unsigned int v = sp[i]; if (v > 0x00401000u && v < 0x7FFF0000u) { HMODULE hm = NULL; if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)v, &hm) && hm) { - char* q = buf; - q = cl_str(q, " +"); - q = cl_hex(q, (unsigned int)(i * 4)); - q = cl_str(q, " "); - q = cl_sym(q, v); - q = cl_str(q, "\r\n"); - WriteFile(h, buf, (DWORD)(q - buf), &wr, NULL); + cl_str(&w, " +"); + cl_hex(&w, i * 4u); + cl_str(&w, " "); + cl_sym(&w, v); + cl_str(&w, "\r\n"); emitted++; } } } } __except (EXCEPTION_EXECUTE_HANDLER) { - const char* m = " <stack sweep faulted>\r\n"; - WriteFile(h, m, (DWORD)lstrlenA(m), &wr, NULL); - } - - { - const char* e = "==== END NATIVE CRASH ====\r\n"; - WriteFile(h, e, (DWORD)lstrlenA(e), &wr, NULL); + cl_str(&w, " <stack sweep faulted>\r\n"); } } - CloseHandle(h); } + + w.end = buf + cap; + cl_str(&w, "==== END NATIVE CRASH ====\r\n"); + return (int)(w.p - buf); +} + +/* ── Output ── */ + +static void cl_append_file(const char* data, int len) +{ + HANDLE h; + DWORD wr; + if (len <= 0 || g_crashLogPath[0] == 0) { return; } + h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); + if (h == INVALID_HANDLE_VALUE) { return; } + SetFilePointer(h, 0, NULL, FILE_END); + WriteFile(h, data, (DWORD)len, &wr, NULL); + CloseHandle(h); +} + +/* Claims a ring slot for writing. Rotates through the ring, overwriting the oldest + * PENDING/DONE record; never steals a slot another thread is mid-write on. */ +static CL_SLOT* cl_claim_slot(void) +{ + int tries; + for (tries = 0; tries < CL_RING_SLOTS * 2; tries++) { + CL_SLOT* s = &g_ring[(unsigned int)InterlockedIncrement(&g_ringNext) % CL_RING_SLOTS]; + LONG st = s->state; + if (st != CL_SLOT_WRITING && + InterlockedCompareExchange(&s->state, CL_SLOT_WRITING, st) == st) { + return s; + } + } + return NULL; +} + +/* Writes PENDING deferred records to the file. Skips the record matching skipTid/skipAddr + * (the same fault the caller is about to log) and, when maxAgeMs != 0, records older + * than maxAgeMs (handled AVs from long before the exit). */ +static void cl_flush_pending(DWORD skipTid, unsigned int skipAddr, DWORD maxAgeMs) +{ + DWORD now = GetTickCount(); + int i; + for (i = 0; i < CL_RING_SLOTS; i++) { + CL_SLOT* s = &g_ring[i]; + if (InterlockedCompareExchange(&s->state, CL_SLOT_WRITING, CL_SLOT_PENDING) != CL_SLOT_PENDING) { + continue; + } + if ((skipTid != 0 && s->tid == skipTid && s->exAddr == skipAddr) || + (maxAgeMs != 0 && now - s->tick > maxAgeMs)) { + InterlockedExchange(&s->state, CL_SLOT_DONE); + continue; + } + cl_append_file(s->text, s->len); + InterlockedExchange(&s->state, CL_SLOT_DONE); + } +} + +/* ── Handlers ── */ + +static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) +{ + DWORD code = ep->ExceptionRecord->ExceptionCode; + unsigned int exAddr; + int immediate; + int coreclr = 0; + CL_SLOT* s; + + if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) { + return EXCEPTION_CONTINUE_SEARCH; + } + if (t_inLogger) { + return EXCEPTION_CONTINUE_SEARCH; /* our own fault — the logger's __try handles it */ + } + if (code == 0xC0000005 && t_sehDepth > 0) { + return EXCEPTION_CONTINUE_SEARCH; /* an SEH_* wrapper's __except will catch it */ + } + + t_inLogger = 1; + exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + immediate = (code != 0xC0000005) || cl_is_nativeaot_address(exAddr); + if (!immediate) { + /* v3: CoreCLR-hosted engine. A data address under 64K is a null-ref that CoreCLR + * hands to managed code as NullReferenceException, so it stays deferred. */ + unsigned int dataAddr = ep->ExceptionRecord->NumberParameters >= 2 + ? (unsigned int)ep->ExceptionRecord->ExceptionInformation[1] : 0; + coreclr = dataAddr >= 0x10000 && cl_is_coreclr_address(exAddr); + immediate = coreclr; + } + + if (!immediate || InterlockedIncrement(&g_immediateCount) <= CL_MAX_IMMEDIATE) { + s = cl_claim_slot(); + if (s) { + s->tid = GetCurrentThreadId(); + s->tick = GetTickCount(); + s->exAddr = exAddr; + s->len = cl_format(s->text, CL_SLOT_BYTES, ep, + code != 0xC0000005 + ? "FAIL-FAST / STACK CHECK (always fatal)" + : (coreclr + ? "AV IN CORECLR-HOSTED CODE (JIT / runtime; fail-fast, non-null address)" + : immediate + ? "AV IN NATIVEAOT CODE (runtime fail-fasts unless it is a null-ref)" + : "FIRST-CHANCE AV (deferred; written because the process died or exited soon after)")); + if (immediate) { + cl_append_file(s->text, s->len); + InterlockedExchange(&s->state, CL_SLOT_DONE); + } else { + InterlockedExchange(&s->state, CL_SLOT_PENDING); + } + } + } + + t_inLogger = 0; return EXCEPTION_CONTINUE_SEARCH; } -/* Install the VEH once. logPath = wide path to the dedicated crash log. */ +/* Unhandled-exception filter: nobody caught this exception, so it is fatal. */ +static LONG WINAPI CrashUef(PEXCEPTION_POINTERS ep) +{ + LONG verdict = EXCEPTION_CONTINUE_SEARCH; + + /* A replaced-then-reasserted filter chain can loop back here; bail out of the cycle. */ + if (t_inUef) { + return EXCEPTION_CONTINUE_SEARCH; + } + t_inUef = 1; + + if (!t_inLogger && InterlockedIncrement(&g_fatalCount) <= CL_MAX_FATAL) { + unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + CL_SLOT* s; + t_inLogger = 1; + /* Earlier first-chance AVs (other threads, earlier faults) are context for this + * crash; the first-chance record of THIS fault is skipped as a duplicate. Flushed + * before claiming a slot so the claim can't overwrite one of them. */ + cl_flush_pending(GetCurrentThreadId(), exAddr, 0); + s = cl_claim_slot(); + if (s) { + s->len = cl_format(s->text, CL_SLOT_BYTES, ep, "UNHANDLED EXCEPTION (fatal)"); + cl_append_file(s->text, s->len); + InterlockedExchange(&s->state, CL_SLOT_DONE); + } + t_inLogger = 0; + } + + if (g_prevFilter) { + verdict = g_prevFilter(ep); + } + t_inUef = 0; + return verdict; +} + +/* DllMain (process exit): write deferred AVs from the last CL_EXIT_FLUSH_WINDOW_MS. */ +static void CrashLoggerFlushOnExit(void) +{ + if (g_crashLogPath[0] == 0) { return; } + cl_flush_pending(0, 0, CL_EXIT_FLUSH_WINDOW_MS); +} + +/* Installs the VEH once and (re-)asserts the unhandled-exception filter. + * logPath = wide path to the dedicated crash log. Safe to call more than once: + * a later call re-installs the filter if AC or a runtime replaced it. */ __declspec(dllexport) void __cdecl RC_InstallCrashLogger(const wchar_t* logPath) { - if (g_vehHandle) { return; } + LPTOP_LEVEL_EXCEPTION_FILTER prev; if (logPath) { int i = 0; for (; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; } g_crashLogPath[i] = 0; } - g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh); + if (!g_vehHandle) { + g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh); + } + prev = SetUnhandledExceptionFilter(CrashUef); + if (prev != CrashUef) { + g_prevFilter = prev; + } } /* ── Tagged-text parser guard (native MinHook detour body) ──────────────── diff --git a/src/RynthCore.App.Avalonia/App.axaml.cs b/src/RynthCore.App.Avalonia/App.axaml.cs index 150a5b9..d0fa2db 100644 --- a/src/RynthCore.App.Avalonia/App.axaml.cs +++ b/src/RynthCore.App.Avalonia/App.axaml.cs @@ -1,6 +1,8 @@ +using System; using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; +using RynthCore; namespace RynthCore.App.Avalonia; @@ -13,6 +15,18 @@ public partial class App : Application public override void OnFrameworkInitializationCompleted() { + try + { + string t = DateTime.Now.ToString("O"); + DesktopRollingLog.AppendLine(DesktopRollingLog.StemLauncher, + $"[{t}] [pid:{Environment.ProcessId}] RynthCore.App.Avalonia started (launcher)."); + // Detailed host + sidecar file layout (see LauncherHostDiagnostics) for runtime mis-detection triage. + LauncherHostDiagnostics.AppendDesktopLogBlock(t); + } + catch + { + } + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) desktop.MainWindow = new MainWindow(); diff --git a/src/RynthCore.App.Avalonia/EngineJsonStore.cs b/src/RynthCore.App.Avalonia/EngineJsonStore.cs index 69c07d2..2254a4e 100644 --- a/src/RynthCore.App.Avalonia/EngineJsonStore.cs +++ b/src/RynthCore.App.Avalonia/EngineJsonStore.cs @@ -120,4 +120,19 @@ internal static class EngineJsonStore fields[field] = doc.RootElement.Clone(); Write(fields); } + + /// <summary> + /// Sets a single string field (e.g. "LoggingLevel"), preserving every other field. + /// </summary> + public static void SetString(string field, string value) + { + Dictionary<string, JsonElement> fields = Read(); + + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms)) + w.WriteStringValue(value); + using var doc = JsonDocument.Parse(ms.ToArray()); + fields[field] = doc.RootElement.Clone(); + Write(fields); + } } diff --git a/src/RynthCore.App.Avalonia/LauncherDiag.cs b/src/RynthCore.App.Avalonia/LauncherDiag.cs index a73faf0..494e6d3 100644 --- a/src/RynthCore.App.Avalonia/LauncherDiag.cs +++ b/src/RynthCore.App.Avalonia/LauncherDiag.cs @@ -2,6 +2,7 @@ using System; using System.IO; using System.Text; using System.Threading; +using RynthCore.Install; namespace RynthCore.App.Avalonia; @@ -18,7 +19,8 @@ namespace RynthCore.App.Avalonia; /// </summary> internal static class LauncherDiag { - private const string UnifiedLogDirectory = @"C:\Games\RynthCore\Logs"; + // Installer-chosen RynthCore folder (falls back to C:\Games\RynthCore). + private static readonly string UnifiedLogDirectory = RynthInstallPaths.CoreLogsDir; private const string UnifiedLogFileName = "RynthCore.log"; private static readonly object LogLock = new(); diff --git a/src/RynthCore.App.Avalonia/LauncherHostDiagnostics.cs b/src/RynthCore.App.Avalonia/LauncherHostDiagnostics.cs new file mode 100644 index 0000000..4b1eed3 --- /dev/null +++ b/src/RynthCore.App.Avalonia/LauncherHostDiagnostics.cs @@ -0,0 +1,110 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore; + +namespace RynthCore.App.Avalonia; + +/// <summary> +/// One-shot host metadata for the Avalonia launcher: helps confirm the renamed apphost +/// (<c>RynthCore.exe</c>) sits next to matching <c>.runtimeconfig.json</c> / <c>.deps.json</c> after installer staging. +/// </summary> +internal static class LauncherHostDiagnostics +{ + /// <summary>Single line for the in-window activity feed (short).</summary> + internal static string BuildActivitySummaryLine() + { + string exe = TryGetHostExePath(); + string dir = Path.GetDirectoryName(exe) ?? AppContext.BaseDirectory; + HostSidecars side = DescribeSidecars(dir); + // x64 FDD tool prereq: same registry keys as installer/RynthCore.iss (see NetDesktopX64Prerequisite). + string suiteTools = NetDesktopX64Prerequisite.IsSatisfied() + ? "x64 suite tools: .NET 10+ OK (registry, same as setup)" + : "x64 suite tools: .NET 10+ not found — install x64 runtime from " + NetDesktopX64Prerequisite.DotNet10RuntimeDownloadUrl; + if (!Environment.Is64BitOperatingSystem) + suiteTools = "x64 suite tools: n/a on 32-bit OS (same as setup)"; + + return + $"Host: {RuntimeInformation.FrameworkDescription}, arch={RuntimeInformation.ProcessArchitecture}, " + + $"runtimeconfig={(side.RenamedRuntimeConfig ? "RynthCore" : side.LegacyRuntimeConfig ? "App.Avalonia (mismatch?)" : "missing")}, " + + $"deps={(side.RenamedDeps ? "RynthCore" : side.LegacyDeps ? "App.Avalonia (mismatch?)" : "missing")}; {suiteTools}"; + } + + /// <summary>Writes a detailed block to the desktop rolling launcher log.</summary> + internal static void AppendDesktopLogBlock(string timestampIso) + { + try + { + string exe = TryGetHostExePath(); + string dir = Path.GetDirectoryName(exe) ?? AppContext.BaseDirectory; + HostSidecars side = DescribeSidecars(dir); + + var sb = new StringBuilder(512); + sb.Append('[').Append(timestampIso).Append("] [pid:").Append(Environment.ProcessId).AppendLine("] Launcher host resolution:"); + sb.Append(" ProcessPath: ").AppendLine(exe); + sb.Append(" BaseDirectory: ").AppendLine(AppContext.BaseDirectory); + sb.Append(" Framework: ").AppendLine(RuntimeInformation.FrameworkDescription); + sb.Append(" OSDescription: ").AppendLine(RuntimeInformation.OSDescription); + sb.Append(" ProcessArchitecture: ").AppendLine(RuntimeInformation.ProcessArchitecture.ToString()); + sb.Append(" CLR: ").AppendLine(Environment.Version.ToString()); + sb.Append(" RynthCore.runtimeconfig.json: ").AppendLine(side.RenamedRuntimeConfig ? "present" : "absent"); + sb.Append(" RynthCore.App.Avalonia.runtimeconfig.json: ").AppendLine(side.LegacyRuntimeConfig ? "present (unexpected if exe is RynthCore.exe)" : "absent"); + sb.Append(" RynthCore.deps.json: ").AppendLine(side.RenamedDeps ? "present" : "absent"); + sb.Append(" RynthCore.App.Avalonia.deps.json: ").AppendLine(side.LegacyDeps ? "present (unexpected if exe is RynthCore.exe)" : "absent"); + // Loot/Monster editors are x64 FDD: probe matches RynthCore.iss prerequisite page (64-bit registry view). + sb.Append(" x64 FDD tool runtime (Loot/Monster, same checks as installer): ") + .AppendLine(NetDesktopX64Prerequisite.IsSatisfied() ? "present" : "not detected") + .Append(" .NET 10+ x64 download hub: ") + .AppendLine(NetDesktopX64Prerequisite.DotNet10RuntimeDownloadUrl); + + DesktopRollingLog.AppendLine(DesktopRollingLog.StemLauncher, sb.ToString()); + } + catch + { + // Logging must never prevent startup. + } + } + + private static string TryGetHostExePath() + { + try + { + // Prefer the actual apphost path (works for published rename to RynthCore.exe). + string? p = Environment.ProcessPath; + if (!string.IsNullOrWhiteSpace(p)) + return p; + } + catch + { + // ignore + } + + try + { + return typeof(App).Assembly.Location; + } + catch + { + return string.Empty; + } + } + + private static HostSidecars DescribeSidecars(string directory) + { + if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory)) + return new HostSidecars(false, false, false, false); + + bool renamedRc = File.Exists(Path.Combine(directory, "RynthCore.runtimeconfig.json")); + bool legacyRc = File.Exists(Path.Combine(directory, "RynthCore.App.Avalonia.runtimeconfig.json")); + bool renamedDeps = File.Exists(Path.Combine(directory, "RynthCore.deps.json")); + bool legacyDeps = File.Exists(Path.Combine(directory, "RynthCore.App.Avalonia.deps.json")); + return new HostSidecars(renamedRc, legacyRc, renamedDeps, legacyDeps); + } + + private readonly record struct HostSidecars( + bool RenamedRuntimeConfig, + bool LegacyRuntimeConfig, + bool RenamedDeps, + bool LegacyDeps); +} diff --git a/src/RynthCore.App.Avalonia/LoggingSettingsStore.cs b/src/RynthCore.App.Avalonia/LoggingSettingsStore.cs new file mode 100644 index 0000000..eb3b801 --- /dev/null +++ b/src/RynthCore.App.Avalonia/LoggingSettingsStore.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Text.Json.Nodes; +using RynthCore.Install; + +namespace RynthCore.App.Avalonia; + +/// <summary> +/// Launcher-side access to every live logging switch: +/// <list type="bullet"> +/// <item>Engine: engine.json "LoggingLevel" (global threshold) and "LogCategories" (per-category emit +/// level). The engine polls engine.json once a second, so edits apply to running clients.</item> +/// <item>RynthAi: Logs\Diagnostics\diagnostics.json "Categories" and "Events" (Off / Trace / Info). +/// RynthAi polls it every couple of seconds and rewrites it with the full catalog on load.</item> +/// </list> +/// </summary> +internal static class LoggingSettingsStore +{ + /// <summary>One engine log category as shown in the launcher.</summary> + internal readonly record struct EngineCategory(string Name, string DefaultLevel, string Description); + + /// <summary>One RynthAi category / event row read from diagnostics.json.</summary> + internal sealed record DiagnosticsRow(string Key, string Level, string Description); + + /// <summary>Global level choices (engine.json "LoggingLevel"), most to least quiet.</summary> + internal static readonly string[] GlobalLevels = { "Off", "Error", "Warning", "Info", "Debug", "Trace" }; + + /// <summary>Engine category emit levels. Info = normal log; Debug/Trace show only at that global level.</summary> + internal static readonly string[] EngineCategoryLevels = { "Off", "Trace", "Debug", "Info" }; + + /// <summary>RynthAi category / event levels: Off, Trace (trace file only), Info (also the normal log).</summary> + internal static readonly string[] RynthAiLevels = { "Off", "Trace", "Info" }; + + /// <summary>Must match RynthCore.Engine.LogCategory names and LogSettings defaults.</summary> + internal static readonly EngineCategory[] EngineCategories = + { + new("General", "Info", "Uncategorised engine lines."), + new("D3D9", "Info", "D3D9 hook, EndScene, bootstrapper, matrix capture, nav markers."), + new("Compat", "Info", "Client hooks: objects, combat, movement, vitals, chat."), + new("Render", "Off", "ImGui rendering and Win32 input (very chatty)."), + new("Plugin", "Info", "Plugin loader/manager and every plugin host Log line."), + new("UI", "Info", "Avalonia overlay and panels."), + new("Verbose", "Debug", "Detail lines across all subsystems (Info = always in the normal log)."), + }; + + private const string EngineCategoriesProperty = "LogCategories"; + + /// <summary>RynthAi's diagnostics.json (created by RynthAi on its first load).</summary> + internal static string DiagnosticsPath => + Path.Combine(RynthInstallPaths.RynthAiDir, "Logs", "Diagnostics", "diagnostics.json"); + + // ── Engine ────────────────────────────────────────────────────────── + + /// <summary>Current engine category levels; categories missing from engine.json get their defaults.</summary> + internal static Dictionary<string, string> ReadEngineCategoryLevels() + { + var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + foreach (EngineCategory c in EngineCategories) result[c.Name] = c.DefaultLevel; + + Dictionary<string, JsonElement> fields = EngineJsonStore.Read(); + if (fields.TryGetValue(EngineCategoriesProperty, out JsonElement cats) && cats.ValueKind == JsonValueKind.Object) + { + foreach (JsonProperty p in cats.EnumerateObject()) + { + if (p.Value.ValueKind == JsonValueKind.String && result.ContainsKey(p.Name)) + result[p.Name] = p.Value.GetString() ?? result[p.Name]; + } + } + return result; + } + + /// <summary>Sets one engine category level in engine.json, preserving every other field.</summary> + internal static void SetEngineCategoryLevel(string category, string level) + { + Dictionary<string, string> levels = ReadEngineCategoryLevels(); + levels[category] = level; + + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms)) + { + w.WriteStartObject(); + foreach (EngineCategory c in EngineCategories) + w.WriteString(c.Name, levels[c.Name]); + w.WriteEndObject(); + } + + Dictionary<string, JsonElement> fields = EngineJsonStore.Read(); + using var doc = JsonDocument.Parse(ms.ToArray()); + fields[EngineCategoriesProperty] = doc.RootElement.Clone(); + EngineJsonStore.Write(fields); + } + + // ── RynthAi ───────────────────────────────────────────────────────── + + /// <summary> + /// Reads RynthAi's category and event rows. Returns false (with empty lists) when diagnostics.json + /// does not exist yet or cannot be parsed (e.g. RynthAi is mid-write; retry later). + /// </summary> + internal static bool TryReadRynthAi(out List<DiagnosticsRow> categories, out List<DiagnosticsRow> events, out string? error) + { + categories = new List<DiagnosticsRow>(); + events = new List<DiagnosticsRow>(); + error = null; + try + { + if (!File.Exists(DiagnosticsPath)) + { + error = "diagnostics.json not found - start RynthAi once to create it."; + return false; + } + if (JsonNode.Parse(File.ReadAllText(DiagnosticsPath)) is not JsonObject root) + { + error = "diagnostics.json is not a JSON object."; + return false; + } + ReadRows(root["Categories"] as JsonArray, "Name", categories); + ReadRows(root["Events"] as JsonArray, "Key", events); + if (categories.Count == 0) + error = "diagnostics.json has no category list - update RynthAi to 0.6.18 or later."; + return true; + } + catch (Exception ex) + { + error = $"diagnostics.json unreadable ({ex.GetType().Name}: {ex.Message})."; + return false; + } + } + + /// <summary>Sets a RynthAi category level ("Off", "Trace", "Info") and keeps "Traces" in sync.</summary> + internal static void SetRynthAiCategoryLevel(string category, string level) + => UpdateDiagnostics("Categories", "Name", category, level); + + /// <summary>Sets a RynthAi key-event level ("Off", "Trace", "Info").</summary> + internal static void SetRynthAiEventLevel(string eventKey, string level) + => UpdateDiagnostics("Events", "Key", eventKey, level); + + private static void ReadRows(JsonArray? array, string keyField, List<DiagnosticsRow> into) + { + if (array == null) return; + foreach (JsonNode? node in array) + { + if (node is not JsonObject o) continue; + string key = o[keyField]?.GetValue<string>() ?? string.Empty; + if (key.Length == 0) continue; + into.Add(new DiagnosticsRow( + key, + o["Level"]?.GetValue<string>() ?? "Off", + o["Description"]?.GetValue<string>() ?? string.Empty)); + } + } + + /// <summary>Read-modify-write of one row's Level; every other field in the file is preserved.</summary> + private static void UpdateDiagnostics(string section, string keyField, string key, string level) + { + string path = DiagnosticsPath; + if (JsonNode.Parse(File.ReadAllText(path)) is not JsonObject root) + throw new InvalidDataException("diagnostics.json is not a JSON object."); + if (root[section] is not JsonArray rows) + throw new InvalidDataException($"diagnostics.json has no \"{section}\" list."); + + bool found = false; + foreach (JsonNode? node in rows) + { + if (node is JsonObject o && string.Equals(o[keyField]?.GetValue<string>(), key, StringComparison.OrdinalIgnoreCase)) + { + o["Level"] = level; + found = true; + } + } + if (!found) + throw new KeyNotFoundException($"\"{key}\" is not in diagnostics.json {section}."); + + // RynthAi reads Categories when present, but older readers (and /ra trace status) use Traces. + if (section == "Categories") + { + var traces = new JsonArray(); + foreach (JsonNode? node in rows) + { + if (node is JsonObject o && !string.Equals(o["Level"]?.GetValue<string>(), "Off", StringComparison.OrdinalIgnoreCase)) + traces.Add(o["Name"]?.GetValue<string>()); + } + root["Traces"] = traces; + } + + // Atomic swap so RynthAi's poll never reads a half-written file. + string tmp = path + ".tmp"; + File.WriteAllText(tmp, root.ToJsonString(new JsonSerializerOptions { WriteIndented = false })); + File.Move(tmp, path, overwrite: true); + } +} diff --git a/src/RynthCore.App.Avalonia/MainWindow.Logging.cs b/src/RynthCore.App.Avalonia/MainWindow.Logging.cs new file mode 100644 index 0000000..90abc2c --- /dev/null +++ b/src/RynthCore.App.Avalonia/MainWindow.Logging.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; + +namespace RynthCore.App.Avalonia; + +/// <summary> +/// Runtime tab → Logging card and the live global Logging level box. Every change is written +/// straight to engine.json / diagnostics.json (see <see cref="LoggingSettingsStore"/>); running +/// clients poll those files, so nothing needs a restart or the Save button. +/// </summary> +internal partial class MainWindow +{ + private static readonly IBrush LogNameBrush = new SolidColorBrush(Color.Parse("#EAF0F4")); + private static readonly IBrush LogMutedBrush = new SolidColorBrush(Color.Parse("#9AA8B3")); + + // Set while the rows are being (re)built so programmatic selections don't write files. + private bool _suppressLoggingEvents; + + /// <summary>Wires the Logging card and the live global level box. Called once after LoadRuntimeControls.</summary> + private void InitLoggingControls() + { + LoggingLevelComboBox.SelectionChanged += (_, _) => OnGlobalLoggingLevelChanged(); + ReloadLoggingButton.Click += (_, _) => BuildLoggingRows(); + BuildLoggingRows(); + } + + /// <summary>Global level changed: persist to the launcher settings and push to engine.json now.</summary> + private void OnGlobalLoggingLevelChanged() + { + if (_suppressLoggingEvents) return; + string level = GetSelectedLoggingLevel(); + if (string.Equals(level, _settings.LoggingLevel, StringComparison.OrdinalIgnoreCase)) return; + try + { + _settings.LoggingLevel = level; + SaveSettings(); + EngineJsonStore.SetString("LoggingLevel", level); + AppendActivity($"Logging level set to {level} (applied live to running clients)."); + } + catch (Exception ex) + { + AppendActivity($"Failed to save logging level: {ex.Message}"); + } + } + + /// <summary>(Re)builds the engine category, RynthAi category and RynthAi event rows from disk.</summary> + private void BuildLoggingRows() + { + _suppressLoggingEvents = true; + try + { + EngineLogCategoriesPanel.Children.Clear(); + Dictionary<string, string> engineLevels = LoggingSettingsStore.ReadEngineCategoryLevels(); + foreach (LoggingSettingsStore.EngineCategory cat in LoggingSettingsStore.EngineCategories) + { + string name = cat.Name; + EngineLogCategoriesPanel.Children.Add(BuildLoggingRow( + name, cat.Description, LoggingSettingsStore.EngineCategoryLevels, engineLevels[name], + level => + { + LoggingSettingsStore.SetEngineCategoryLevel(name, level); + AppendActivity($"Engine log category {name} set to {level} (applied live)."); + })); + } + + RynthAiLogCategoriesPanel.Children.Clear(); + RynthAiLogEventsPanel.Children.Clear(); + bool ok = LoggingSettingsStore.TryReadRynthAi( + out List<LoggingSettingsStore.DiagnosticsRow> categories, + out List<LoggingSettingsStore.DiagnosticsRow> events, + out string? error); + + foreach (LoggingSettingsStore.DiagnosticsRow row in categories) + { + string key = row.Key; + RynthAiLogCategoriesPanel.Children.Add(BuildLoggingRow( + key, row.Description, LoggingSettingsStore.RynthAiLevels, row.Level, + level => + { + LoggingSettingsStore.SetRynthAiCategoryLevel(key, level); + AppendActivity($"RynthAi log category {key} set to {level} (applied live)."); + })); + } + foreach (LoggingSettingsStore.DiagnosticsRow row in events) + { + string key = row.Key; + RynthAiLogEventsPanel.Children.Add(BuildLoggingRow( + key, row.Description, LoggingSettingsStore.RynthAiLevels, row.Level, + level => + { + LoggingSettingsStore.SetRynthAiEventLevel(key, level); + AppendActivity($"RynthAi log event {key} set to {level} (applied live)."); + })); + } + + LoggingStatusText.Text = ok && error == null + ? $"engine.json: {EngineJsonStore.Path}\ndiagnostics.json: {LoggingSettingsStore.DiagnosticsPath}" + : $"RynthAi: {error}"; + } + catch (Exception ex) + { + LoggingStatusText.Text = $"Failed to load logging settings: {ex.Message}"; + } + finally + { + _suppressLoggingEvents = false; + } + } + + /// <summary>One "Name | level box | description" row. <paramref name="apply"/> runs on user changes only.</summary> + private Control BuildLoggingRow(string name, string description, string[] levels, string current, Action<string> apply) + { + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("170,110,*") }; + + grid.Children.Add(new TextBlock + { + Text = name, + Foreground = LogNameBrush, + VerticalAlignment = VerticalAlignment.Center, + }); + + var combo = new ComboBox { ItemsSource = levels, MinWidth = 100, Margin = new global::Avalonia.Thickness(0, 0, 8, 0) }; + int index = Array.FindIndex(levels, l => string.Equals(l, current, StringComparison.OrdinalIgnoreCase)); + combo.SelectedIndex = index >= 0 ? index : 0; + combo.SelectionChanged += (_, _) => + { + if (_suppressLoggingEvents || combo.SelectedItem is not string level) return; + try { apply(level); } + catch (Exception ex) + { + AppendActivity($"Failed to set {name} to {level}: {ex.Message}"); + // Show what is actually on disk; posted so the combo raising this event isn't torn down mid-handler. + global::Avalonia.Threading.Dispatcher.UIThread.Post(BuildLoggingRows); + } + }; + Grid.SetColumn(combo, 1); + grid.Children.Add(combo); + + var desc = new TextBlock + { + Text = description, + Foreground = LogMutedBrush, + TextWrapping = TextWrapping.Wrap, + VerticalAlignment = VerticalAlignment.Center, + }; + Grid.SetColumn(desc, 2); + grid.Children.Add(desc); + return grid; + } +} diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml b/src/RynthCore.App.Avalonia/MainWindow.axaml index 4176226..31ba128 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml @@ -366,7 +366,17 @@ <CheckBox x:Name="OverrideWindowTitleCheckBox" Content="Rewrite AC window titles per account" ToolTip.Tip="Replaces "Asheron's Call" with "Account / Character @ Server" on tracked clients so multi-box taskbars are readable. Untracked external clients are left alone." /> - + <CheckBox x:Name="InjectAllRunningAcCheckBox" Content="Inject all running AC sessions" /> + <TextBlock Text="Logging level (applies live)" Foreground="#EAF0F4" Margin="0,4,0,0" /> + <ComboBox x:Name="LoggingLevelComboBox" SelectedIndex="3" + ToolTip.Tip="Engine log threshold. Written to engine.json immediately; running clients pick it up within a second. Off = errors only."> + <ComboBoxItem Content="Off" /> + <ComboBoxItem Content="Error" /> + <ComboBoxItem Content="Warning" /> + <ComboBoxItem Content="Info" /> + <ComboBoxItem Content="Debug" /> + <ComboBoxItem Content="Trace" /> + </ComboBox> <Grid ColumnDefinitions="*,Auto" RowDefinitions="Auto,Auto,Auto" Margin="0,8,0,0"> <TextBlock Grid.Row="0" Grid.Column="0" Text="Inter-launch stagger (ms)" Foreground="#EAF0F4" VerticalAlignment="Center" Margin="0,0,8,6" /> <NumericUpDown Grid.Row="0" Grid.Column="1" x:Name="LaunchStaggerMsBox" Minimum="0" Maximum="5000" Increment="50" Width="120" Margin="0,0,0,6" /> @@ -409,6 +419,42 @@ </StackPanel> </Border> + <!-- Live logging switches: engine categories (engine.json) and RynthAi categories/events + (diagnostics.json). Rows are built in code (MainWindow.Logging.cs). --> + <Border Background="#132028" CornerRadius="16" Padding="18"> + <StackPanel Spacing="8"> + <Grid ColumnDefinitions="*,Auto"> + <TextBlock Grid.Column="0" Text="Logging" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" VerticalAlignment="Center" /> + <Button Grid.Column="1" x:Name="ReloadLoggingButton" Content="Reload" /> + </Grid> + <TextBlock Text="Every change is saved immediately and applies to running clients without a restart (engine within 1 s, RynthAi within 2 s). Set any Trace or Debug item to Info to see it in the normal log; Off silences it." + TextWrapping="Wrap" + Foreground="#9AA8B3" /> + <Expander Header="Engine categories" IsExpanded="True" HorizontalAlignment="Stretch"> + <StackPanel Spacing="4"> + <TextBlock Text="The level each category's lines are written at. A line shows when its level is within the global Logging level above (Info = normal log)." + TextWrapping="Wrap" Foreground="#9AA8B3" /> + <StackPanel x:Name="EngineLogCategoriesPanel" Spacing="2" /> + </StackPanel> + </Expander> + <Expander Header="RynthAi categories" HorizontalAlignment="Stretch"> + <StackPanel Spacing="4"> + <TextBlock Text="Where each RynthAi category's trace lines go: Off = dropped, Trace = Logs\Diagnostics\Trace file only, Info = trace file and the normal log." + TextWrapping="Wrap" Foreground="#9AA8B3" /> + <StackPanel x:Name="RynthAiLogCategoriesPanel" Spacing="2" /> + </StackPanel> + </Expander> + <Expander Header="RynthAi key events" HorizontalAlignment="Stretch"> + <StackPanel Spacing="4"> + <TextBlock Text="Named milestones (Hub login, options refresh, ...). Off = dropped, Trace = trace file while that category is traced, Info = normal log." + TextWrapping="Wrap" Foreground="#9AA8B3" /> + <StackPanel x:Name="RynthAiLogEventsPanel" Spacing="2" /> + </StackPanel> + </Expander> + <TextBlock x:Name="LoggingStatusText" TextWrapping="Wrap" Foreground="#9AA8B3" /> + </StackPanel> + </Border> + <Border Background="#132028" CornerRadius="16" Padding="18"> <StackPanel Spacing="8"> <TextBlock Text="Recovery Actions" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" /> @@ -423,7 +469,7 @@ <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 targets the first detected acclient.exe session. Reset Overlay Bar signals all running RynthCore clients via the dispatch file." + <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" Foreground="#9AA8B3" /> </StackPanel> diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index 5a585cb..cecd02d 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -18,6 +18,7 @@ using Avalonia.Media; using Avalonia.Platform.Storage; using Avalonia.Threading; using RynthCore.Injector; +using RynthCore.Install; namespace RynthCore.App.Avalonia; @@ -136,6 +137,8 @@ internal partial class MainWindow : Window SessionList.ItemsSource = _sessionItems; LoadSettings(); LoadRuntimeControls(); + InitLoggingControls(); + ApplyInstallerPluginRegistration(); LoadPluginDllPaths(); BuildPluginLoadout(); WireEvents(); @@ -149,6 +152,8 @@ internal partial class MainWindow : Window Closing += (_, _) => SaveWindowLayout(); ShowVersion(); AppendActivity("Avalonia launcher preview ready."); + // One-line host/runtime sidecar check (full detail in Desktop RynthCore-Launcher.log). + AppendActivity(LauncherHostDiagnostics.BuildActivitySummaryLine()); _ = RefreshServerStatusesAsync(); _updateTimer.Tick += async (_, _) => await CheckForUpdatesAsync(); _updateTimer.Start(); @@ -307,6 +312,8 @@ internal partial class MainWindow : Window AutoLaunchHeaderCheckBox.IsChecked = _settings.AutoLaunch; AutoInjectAfterLaunchCheckBox.IsChecked = _settings.AutoInjectAfterLaunch; WatchForAcStartCheckBox.IsChecked = _settings.WatchForAcStart; + InjectAllRunningAcCheckBox.IsChecked = _settings.InjectAllRunningClients; + SetLoggingLevelSelection(_settings.LoggingLevel); OverrideWindowTitleCheckBox.IsChecked = _settings.OverrideWindowTitle; LaunchStaggerMsBox.Value = _settings.LaunchStaggerMs; CrashRelaunchLimitBox.Value = _settings.CrashRelaunchLimitInWindow; @@ -1309,6 +1316,8 @@ internal partial class MainWindow : Window _settings.AutoLaunch = AutoLaunchHeaderCheckBox.IsChecked == true; _settings.AutoInjectAfterLaunch = AutoInjectAfterLaunchCheckBox.IsChecked == true; _settings.WatchForAcStart = WatchForAcStartCheckBox.IsChecked == true; + _settings.InjectAllRunningClients = InjectAllRunningAcCheckBox.IsChecked == true; + _settings.LoggingLevel = GetSelectedLoggingLevel(); _settings.OverrideWindowTitle = OverrideWindowTitleCheckBox.IsChecked == true; if (LaunchStaggerMsBox.Value is decimal staggerMs) _settings.LaunchStaggerMs = (int)staggerMs; @@ -1323,8 +1332,12 @@ internal partial class MainWindow : Window if (_settings.EnabledPluginIds.Count == 0) _settings.EnabledPluginIds.Add("rynthcore-engine"); SaveSettings(); + SyncPluginPathsToEngineSettings(); if (appendActivity) + { + AppendActivity($"Logging level saved: {_settings.LoggingLevel}."); AppendActivity("Launch behavior saved."); + } } private void SaveAutoLaunchPreference() @@ -1981,6 +1994,78 @@ internal partial class MainWindow : Window AppendActivity($"Runtime loadout updated: {Path.GetFileName(dllPath)} {(enabled ? "enabled" : "disabled")} (engine.json synced)."); } + /// <summary> + /// Applies the installer's one-shot plugin hand-off: the full installer writes the plugin + /// DLL paths it placed in the user-chosen RynthSuite folder to + /// <c>Software\Rynth\PendingPluginRegistration</c> (';'-separated). Each existing DLL is added + /// to the Plugins list, and any entry with the same file name that no longer exists (e.g. the + /// old <c>C:\Games\RynthSuite\...</c> path after moving the Suite folder) is replaced. + /// Rows pointing inside the RynthCore folder whose file the installer removed are dropped too. + /// The value is consumed once (deleted from HKCU; remembered in settings for HKLM). + /// </summary> + private void ApplyInstallerPluginRegistration() + { + try + { + string? pending = RynthInstallPaths.ReadSetting("PendingPluginRegistration"); + if (string.IsNullOrWhiteSpace(pending) + || string.Equals(pending, _settings.AppliedInstallerPluginRegistration, StringComparison.OrdinalIgnoreCase)) + return; + + _settings.PluginDllPaths ??= []; + var added = new List<string>(); + + // The installer clears loose DLLs out of the RynthCore folder (old 0.4.x layouts kept plugins + // and SDK DLLs there), so drop rows that pointed inside it and are now gone. Rows elsewhere are + // left alone, since a missing file there may just be on a drive that isn't mounted. + string coreRoot = Path.TrimEndingDirectorySeparator(RynthInstallPaths.CoreDir) + Path.DirectorySeparatorChar; + bool IsRemovedCoreFile(string p) => + p.StartsWith(coreRoot, StringComparison.OrdinalIgnoreCase) && !File.Exists(p); + int pruned = _settings.PluginDllPaths.RemoveAll(IsRemovedCoreFile); + _settings.DisabledPluginDllPaths.RemoveAll(IsRemovedCoreFile); + + foreach (string raw in pending.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + string path; + try { path = Path.GetFullPath(raw); } catch { continue; } + if (!File.Exists(path)) continue; + + string fileName = Path.GetFileName(path); + // Drop stale rows for the same plugin that point at a file which is gone. + _settings.PluginDllPaths.RemoveAll(p => + string.Equals(Path.GetFileName(p), fileName, StringComparison.OrdinalIgnoreCase) + && !string.Equals(p, path, StringComparison.OrdinalIgnoreCase) + && !File.Exists(p)); + + if (!_settings.PluginDllPaths.Any(p => string.Equals(p, path, StringComparison.OrdinalIgnoreCase))) + { + _settings.PluginDllPaths.Add(path); + added.Add(fileName); + } + } + + _settings.AppliedInstallerPluginRegistration = pending; + SaveSettings(); + RynthInstallPaths.DeleteUserSetting("PendingPluginRegistration"); + + _pluginDllPaths.Clear(); + foreach (string p in _settings.PluginDllPaths) _pluginDllPaths.Add(p); + SyncPluginPathsToEngineSettings(); + + string msg = added.Count > 0 + ? $"Installer registered plugin(s): {string.Join(", ", added)} (engine.json synced)." + : "Installer plugin registration already up to date."; + if (pruned > 0) + msg += $" Removed {pruned} plugin path(s) for files the installer cleared from {RynthInstallPaths.CoreDir}."; + LauncherDiag.Info("PLUGINS: " + msg); + try { AppendActivity(msg); } catch { } + } + catch (Exception ex) + { + LauncherDiag.Info("PLUGINS: installer registration failed: " + ex.Message); + } + } + private void LoadPluginDllPaths() { _pluginDllPaths.Clear(); @@ -2069,6 +2154,8 @@ internal partial class MainWindow : Window .Where(p => !disabled.Contains(p)) .ToList(); EngineJsonStore.SetStringArray("PluginPaths", enabledPaths); + // The engine reads its log verbosity from engine.json on init (EngineSettings.LoggingLevel). + EngineJsonStore.SetString("LoggingLevel", GetSelectedLoggingLevel()); } catch (Exception ex) { @@ -2564,18 +2651,28 @@ internal partial class MainWindow : Window try { SetOperationState(true); - Process target = targets.OrderBy(process => process.Id).First(); - AppendActivity($"Applying selected loadout to running AC (PID {target.Id})."); + IReadOnlyList<Process> orderedTargets = targets.OrderBy(process => process.Id).ToList(); + bool injectAllSessions = InjectAllRunningAcCheckBox.IsChecked == true; + IReadOnlyList<Process> targetsToInject = injectAllSessions + ? orderedTargets + : [orderedTargets[0]]; + AppendActivity(injectAllSessions + ? $"Applying selected loadout to {targetsToInject.Count} running AC session(s)." + : $"Applying selected loadout to first running AC session (PID {targetsToInject[0].Id})."); - InjectionResult result = await Task.Run(() => _injector.InjectIntoProcess(target, enginePath, AppendActivity)); - if (result.Success) + foreach (Process target in targetsToInject) { - _launchedSessionPids.Add(target.Id); - AppendActivity($"Injection complete for PID {target.Id}."); - } - else - { - AppendActivity($"Injection failed: {result.Summary}"); + AppendActivity($"Injecting running AC (PID {target.Id})."); + InjectionResult result = await Task.Run(() => _injector.InjectIntoProcess(target, enginePath, AppendActivity)); + if (result.Success) + { + _launchedSessionPids.Add(target.Id); + AppendActivity($"Injection complete for PID {target.Id}."); + } + else + { + AppendActivity($"Injection failed for PID {target.Id}: {result.Summary}"); + } } } catch (Exception ex) @@ -2589,6 +2686,39 @@ internal partial class MainWindow : Window } } + private string GetSelectedLoggingLevel() + { + return LoggingLevelComboBox.SelectedItem is ComboBoxItem item + ? item.Content?.ToString() ?? "Info" + : "Info"; + } + + private void SetLoggingLevelSelection(string? loggingLevel) + { + string desiredLevel = string.IsNullOrWhiteSpace(loggingLevel) ? "Info" : loggingLevel.Trim(); + if (LoggingLevelComboBox.Items == null) + { + LoggingLevelComboBox.SelectedIndex = 0; + return; + } + + foreach (object? item in LoggingLevelComboBox.Items) + { + if (item is not ComboBoxItem comboItem) + continue; + + string candidate = comboItem.Content?.ToString() ?? string.Empty; + if (!string.Equals(candidate, desiredLevel, StringComparison.OrdinalIgnoreCase)) + continue; + + LoggingLevelComboBox.SelectedItem = comboItem; + return; + } + + // Unknown saved value: fall back to Info (index 3 after Off, Error, Warning), not the quietest level. + LoggingLevelComboBox.SelectedIndex = 3; + } + private void OnPrimarySelectionChanged() { if (_suppressPrimarySelectionChanged) @@ -2988,7 +3118,7 @@ internal partial class MainWindow : Window // Tail the per-PID log for the last heartbeat line. Cheap: seek to // the end, read ~2KB, FileShare-tolerant of the engine's writer. - string logPath = System.IO.Path.Combine(@"C:\Games\RynthCore\Logs", $"RynthCore.{pid}.log"); + string logPath = System.IO.Path.Combine(RynthInstallPaths.CoreLogsDir, $"RynthCore.{pid}.log"); string tail; try { diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index fdefb66..32276bc 100644 --- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj +++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj @@ -1,6 +1,12 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> + <!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.4. + No hard-coded InformationalVersion: release builds pass -p:Version=yyyy.m.d.n, and the + product version derived from it is what the launcher/About show (BuildVersion.Format). --> + <Version>0.1.5</Version> + <AssemblyVersion>0.1.5.0</AssemblyVersion> + <FileVersion>0.1.5.0</FileVersion> <OutputType>WinExe</OutputType> <TargetFramework>net10.0-windows7.0</TargetFramework> <PlatformTarget>x86</PlatformTarget> @@ -11,6 +17,8 @@ <RootNamespace>RynthCore.App.Avalonia</RootNamespace> <AssemblyName>RynthCore.App.Avalonia</AssemblyName> <RuntimeIdentifiers>win-x86</RuntimeIdentifiers> + <!-- Build-Installer.ps1 publishes self-contained so RynthCore.exe does not require a machine-wide + .NET 10 Desktop Runtime. Local dotnet build or dotnet run still use the SDK. --> <ApplicationIcon>LogoCore.ico</ApplicationIcon> <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract> </PropertyGroup> @@ -25,6 +33,12 @@ <PackageReference Include="Avalonia.Desktop" Version="11.2.3" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" /> <PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.3" /> + <!-- Direct reference overrides Avalonia's transitive 0.20.x (NU1903 / GHSA-xrw6-gwf8-vvr9). --> + <PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" /> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="..\RynthCore.DesktopLog\RynthCore.DesktopLog.csproj" /> </ItemGroup> <ItemGroup> @@ -53,4 +67,9 @@ <Compile Include="..\RynthCore.Injector\InjectionResult.cs" Link="Shared\InjectionResult.cs" /> </ItemGroup> + <ItemGroup> + <!-- Install-location resolver (installer-chosen RynthCore / RynthSuite folders). --> + <Compile Include="..\RynthCore.App\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" /> + </ItemGroup> + </Project> diff --git a/src/RynthCore.App/AppSettings.cs b/src/RynthCore.App/AppSettings.cs index fec333f..0da12e9 100644 --- a/src/RynthCore.App/AppSettings.cs +++ b/src/RynthCore.App/AppSettings.cs @@ -17,6 +17,8 @@ internal sealed class AppSettings public bool AutoLaunch { get; set; } public bool AutoInjectAfterLaunch { get; set; } = true; public bool WatchForAcStart { get; set; } = true; + public bool InjectAllRunningClients { get; set; } = true; + public string LoggingLevel { get; set; } = "Info"; public int LaunchStaggerMs { get; set; } = 250; public int CrashRelaunchLimitInWindow { get; set; } = 3; public int CrashRelaunchWindowMinutes { get; set; } = 5; @@ -62,6 +64,14 @@ internal sealed class AppSettings /// the UI), but is filtered out when syncing PluginPaths into engine.json. /// Case-insensitive set semantics; comparisons must use OrdinalIgnoreCase. public List<string> DisabledPluginDllPaths { get; set; } = []; + + /// <summary> + /// Last installer plugin hand-off (registry <c>Software\Rynth\PendingPluginRegistration</c>) + /// the launcher applied. Lets an all-users install, whose HKLM value the launcher cannot + /// delete, register its plugins once without re-adding a plugin the user later removed. + /// </summary> + public string? AppliedInstallerPluginRegistration { get; set; } + public List<LaunchServerProfile> ServerProfiles { get; set; } = []; public List<LaunchAccountProfile> AccountProfiles { get; set; } = []; diff --git a/src/RynthCore.App/RynthInstallPaths.cs b/src/RynthCore.App/RynthInstallPaths.cs new file mode 100644 index 0000000..ddf0554 --- /dev/null +++ b/src/RynthCore.App/RynthInstallPaths.cs @@ -0,0 +1,128 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; + +namespace RynthCore.Install; + +/// <summary> +/// Resolves where RynthCore and RynthSuite are installed. The installer lets the user pick +/// both folders and records them under <c>Software\Rynth</c> (HKCU for a per-user install, +/// HKLM for an all-users install), so nothing may assume <c>C:\Games\...</c> any more. +/// <para> +/// Resolution order per folder: environment override (<c>RYNTHCORE_DIR</c> / +/// <c>RYNTHSUITE_DIR</c>, for dev setups) → HKCU → HKLM (32-bit view, where the 32-bit +/// installer writes) → the historical default under <c>C:\Games</c>. Results are cached +/// for the life of the process. +/// </para> +/// Linked into every RynthCore project (Engine, Loader, Injector, launcher, StatusAgent); +/// RynthSuite keeps an identical copy in <c>Shared/RynthInstallPaths.cs</c> — change both together. +/// Registry access is a direct RegGetValueW P/Invoke so it works under NativeAOT and trimming +/// without pulling in Microsoft.Win32.Registry. +/// </summary> +internal static class RynthInstallPaths +{ + /// <summary>Default RynthCore folder (pre-2026.10.4.2 installs always used this).</summary> + public const string DefaultCoreDir = @"C:\Games\RynthCore"; + + /// <summary>Default RynthSuite folder (pre-2026.10.4.2 installs always used this).</summary> + public const string DefaultSuiteDir = @"C:\Games\RynthSuite"; + + /// <summary>Registry key (under HKCU or HKLM) written by the installer.</summary> + public const string RegistryKey = @"Software\Rynth"; + + private static string? _coreDir; + private static string? _suiteDir; + + /// <summary>RynthCore install folder (launcher, <c>Runtime\</c>, <c>Logs\</c>, <c>Tools\</c>).</summary> + public static string CoreDir => _coreDir ??= Resolve("RYNTHCORE_DIR", "CoreDir", DefaultCoreDir); + + /// <summary>RynthSuite folder (plugins and their data, e.g. <c>RynthAi\</c>).</summary> + public static string SuiteDir => _suiteDir ??= Resolve("RYNTHSUITE_DIR", "SuiteDir", DefaultSuiteDir); + + /// <summary>Unified RynthCore log folder (<c><CoreDir>\Logs</c>).</summary> + public static string CoreLogsDir => Path.Combine(CoreDir, "Logs"); + + /// <summary>RynthAi plugin home and data root (<c><SuiteDir>\RynthAi</c>).</summary> + public static string RynthAiDir => Path.Combine(SuiteDir, "RynthAi"); + + /// <summary>Reads a string value from <c>Software\Rynth</c> (HKCU first, then HKLM 32-bit view); null when absent.</summary> + public static string? ReadSetting(string valueName) + => ReadRegistryString(HKEY_CURRENT_USER, valueName, 0) + ?? ReadRegistryString(HKEY_LOCAL_MACHINE, valueName, RRF_SUBKEY_WOW6432KEY); + + /// <summary>Deletes a value from HKCU <c>Software\Rynth</c> (used for one-shot installer hand-offs). Best effort.</summary> + public static void DeleteUserSetting(string valueName) + { + try { RegDeleteKeyValueW(HKEY_CURRENT_USER, RegistryKey, valueName); } catch { } + } + + private static string Resolve(string envVar, string valueName, string fallback) + { + string? fromEnv = null; + try { fromEnv = Environment.GetEnvironmentVariable(envVar); } catch { } + + foreach (string? candidate in new[] { fromEnv, ReadSetting(valueName) }) + { + string? normalized = Normalize(candidate); + if (normalized != null) return normalized; + } + return fallback; + } + + /// <summary>Accepts only absolute paths; trims whitespace, quotes and trailing separators.</summary> + private static string? Normalize(string? path) + { + if (string.IsNullOrWhiteSpace(path)) return null; + string p = path.Trim().Trim('"').TrimEnd('\\', '/'); + if (p.Length == 2 && p[1] == ':') p += "\\"; // keep "D:" as the drive root "D:\" + try + { + if (!Path.IsPathFullyQualified(p)) return null; + string full = Path.GetFullPath(p); + return full.Length > 3 ? full.TrimEnd('\\') : full; // "D:\" stays a root + } + catch + { + return null; + } + } + + // ── Win32 registry (advapi32) ─────────────────────────────────────────── + + private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001)); + private static readonly IntPtr HKEY_LOCAL_MACHINE = new(unchecked((int)0x80000002)); + private const uint RRF_RT_REG_SZ = 0x00000002; + private const uint RRF_RT_REG_EXPAND_SZ = 0x00000004; + private const uint RRF_SUBKEY_WOW6432KEY = 0x00020000; + private const int ERROR_SUCCESS = 0; + + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + private static extern int RegGetValueW(IntPtr hkey, string lpSubKey, string lpValue, uint dwFlags, + IntPtr pdwType, char[]? pvData, ref uint pcbData); + + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + private static extern int RegDeleteKeyValueW(IntPtr hkey, string lpSubKey, string lpValueName); + + private static string? ReadRegistryString(IntPtr root, string valueName, uint viewFlags) + { + try + { + uint flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | viewFlags; + uint bytes = 0; + if (RegGetValueW(root, RegistryKey, valueName, flags, IntPtr.Zero, null, ref bytes) != ERROR_SUCCESS || bytes < 2) + return null; + + var buffer = new char[(bytes + 1) / 2]; + if (RegGetValueW(root, RegistryKey, valueName, flags, IntPtr.Zero, buffer, ref bytes) != ERROR_SUCCESS) + return null; + + int len = Array.IndexOf(buffer, '\0'); + return new string(buffer, 0, len >= 0 ? len : buffer.Length); + } + catch + { + // Missing advapi32 entry point or access denied — fall back to the defaults. + return null; + } + } +} diff --git a/src/RynthCore.DesktopLog/DesktopRollingLog.cs b/src/RynthCore.DesktopLog/DesktopRollingLog.cs new file mode 100644 index 0000000..ea43e85 --- /dev/null +++ b/src/RynthCore.DesktopLog/DesktopRollingLog.cs @@ -0,0 +1,130 @@ +using System.Globalization; +using System.Text; + +namespace RynthCore; + +/// <summary> +/// Desktop text logs with a fixed size cap and per-day roll retention. Active file lives on the user +/// desktop as <c>{fileStem}.log</c>. When the active file reaches <see cref="MaxActiveFileBytes"/>, +/// it is moved into <c>Desktop\RynthLogs\</c> with a time-stamped name, then a new active file is +/// created. For each <paramref name="fileStem"/> and each calendar day, at most +/// <see cref="MaxRolledFilesPerLocalDay"/> archived files are kept (oldest for that day deleted first). +/// </summary> +public static class DesktopRollingLog +{ + // 10 MB active segment, up to 10 rolled segments per local calendar day. + public const long MaxActiveFileBytes = 10L * 1024 * 1024; + public const int MaxRolledFilesPerLocalDay = 10; + + private static readonly string DesktopDir = + Environment.GetFolderPath(Environment.SpecialFolder.Desktop); + + private static readonly string ArchiveDir = Path.Combine(DesktopDir, "RynthLogs"); + + /// <summary>Pre-defined stems for the three Rynth products (one file each on the desktop).</summary> + public const string StemEngine = "RynthCore"; + public const string StemLauncher = "RynthCore-Launcher"; + public const string StemInjector = "RynthCore-Injector"; + + private static readonly object Gate = new(); + + /// <param name="fileStem">File name without extension, e.g. <see cref="StemEngine"/>.</param> + public static void AppendLine(string fileStem, string line) + { + string stem = SanitizeStem(fileStem); + string text = line ?? string.Empty; + if (text.Length > 0 && text[^1] is not '\n' and not '\r') + text += Environment.NewLine; + + lock (Gate) + { + try + { + string active = Path.Combine(DesktopDir, stem + ".log"); + Directory.CreateDirectory(ArchiveDir); + + if (File.Exists(active) && new FileInfo(active).Length + Encoding.UTF8.GetByteCount(text) > MaxActiveFileBytes) + RotateToArchive(stem, active); + + using var stream = new FileStream(active, FileMode.Append, FileAccess.Write, FileShare.Read); + var bytes = Encoding.UTF8.GetBytes(text); + stream.Write(bytes, 0, bytes.Length); + } + catch + { + // Intentionally silent: logging must not crash host. + } + } + } + + // Moves current active file to RynthLogs; trims same-day archives for this stem, then the move. + private static void RotateToArchive(string stem, string activePath) + { + string ymd = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture); + string prefix = stem + "-roll-" + ymd + "-"; + + PruneOldestRolledForPrefix(prefix); + + string destName = prefix + DateTime.Now.ToString("HHmmssfff", CultureInfo.InvariantCulture) + ".log"; + string destPath = Path.Combine(ArchiveDir, destName); + if (File.Exists(destPath)) File.Delete(destPath); + try + { + File.Move(activePath, destPath, overwrite: false); + } + catch + { + try + { + if (File.Exists(destPath)) File.Delete(destPath); + } + catch + { + // ignore + } + + if (File.Exists(activePath)) File.Delete(activePath); + } + } + + // Ensures that after a new file with this prefix is created, at most MaxRolledFilesPerLocalDay rolled files for this prefix+day exist. + private static void PruneOldestRolledForPrefix(string prefix) + { + if (!Directory.Exists(ArchiveDir)) return; + + var todaysRolled = new DirectoryInfo(ArchiveDir) + .GetFiles(prefix + "*.log", SearchOption.TopDirectoryOnly) + .OrderBy(f => f.CreationTimeUtc) + .ThenBy(f => f.Name, StringComparer.OrdinalIgnoreCase) + .ToList(); + + // Delete oldest rolled segments until a new one would not exceed the daily cap. + while (todaysRolled.Count >= MaxRolledFilesPerLocalDay) + { + try + { + todaysRolled[0].Delete(); + todaysRolled.RemoveAt(0); + } + catch + { + break; + } + } + } + + private static string SanitizeStem(string? stem) + { + if (string.IsNullOrWhiteSpace(stem)) return "RynthLog"; + var invalid = Path.GetInvalidFileNameChars(); + var b = new StringBuilder(stem.Length); + foreach (var ch in stem.Trim()) + { + if (!invalid.Contains(ch) && ch != Path.DirectorySeparatorChar && ch != Path.AltDirectorySeparatorChar) + b.Append(ch); + } + + string t = b.ToString(); + return t.Length == 0 ? "RynthLog" : t; + } +} diff --git a/src/RynthCore.DesktopLog/NetDesktopX64Prerequisite.cs b/src/RynthCore.DesktopLog/NetDesktopX64Prerequisite.cs new file mode 100644 index 0000000..a73d61d --- /dev/null +++ b/src/RynthCore.DesktopLog/NetDesktopX64Prerequisite.cs @@ -0,0 +1,105 @@ +// Detects the same "Suite tools" .NET 10+ x64 prerequisite as the Inno installer +// (installer\RynthCore.iss, IsNetDesktop* helpers). If you change registry checks here, +// update RynthCore.iss in lockstep and vice versa. + +using System; +using System.Globalization; +using System.Linq; +using System.Runtime.Versioning; +using Microsoft.Win32; + +namespace RynthCore; + +/// <summary> +/// Registry probe for the optional x64 framework-dependent tools (Loot Editor, Monster Editor). +/// Must match <c>IsNetDesktop10PlusX64Present</c> and its helpers in <c>installer/RynthCore.iss</c> +/// (Path A: <c>Microsoft.WindowsDesktop.App</c> shared folders; Path B: <c>sharedhost</c> Version; +/// Path C: <c>InstalledManifests\x64</c> manifest-10. bands). Uses 64-bit registry view from an x86 process. +/// </summary> +[SupportedOSPlatform("windows")] +public static class NetDesktopX64Prerequisite +{ + // Same string as RynthCore.iss DotNet10DesktopDownloadUrl (x64 runtime hub; user picks Desktop / ASP.NET as needed). + public const string DotNet10RuntimeDownloadUrl = "https://dotnet.microsoft.com/en-us/download/dotnet/10.0/runtime"; + + /// <summary>True if the x64 FDD tool prerequisite is met, or the OS is 32-bit (N/A, same as Inno skip).</summary> + public static bool IsSatisfied() + { + if (!Environment.Is64BitOperatingSystem) + return true; + + return + IsWindowsDesktopSharedFramework10Plus() + || IsDotNet10BandInInstalledManifestsX64() + || IsSharedHostVersion10PlusX64(); + } + + // Path A: HKLM\SOFTWARE\dotnet\shared\Microsoft.WindowsDesktop.App\10.x.y + private static bool IsWindowsDesktopSharedFramework10Plus() + { + using RegistryKey? base64 = OpenLocalMachine64(); + using RegistryKey? key = base64?.OpenSubKey(@"SOFTWARE\dotnet\shared\Microsoft.WindowsDesktop.App"); + if (key is null) + return false; + + foreach (string name in key.GetSubKeyNames()) + { + if (ParseMajorFromVersionFolder(name) >= 10) + return true; + } + + return false; + } + + // Path B: sharedhost Version 10+ under Setup\InstalledVersions\x64\sharedhost + private static bool IsSharedHostVersion10PlusX64() + { + if (ReadSharedHostMajor(@"SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost") >= 10) + return true; + if (ReadSharedHostMajor(@"SOFTWARE\Microsoft\dotnet\Setup\InstalledVersions\x64\sharedhost") >= 10) + return true; + return false; + } + + private static int ReadSharedHostMajor(string subKeyPath) + { + using RegistryKey? base64 = OpenLocalMachine64(); + using RegistryKey? key = base64?.OpenSubKey(subKeyPath); + if (key is null) + return 0; + string? v = key.GetValue("Version") as string; + if (string.IsNullOrWhiteSpace(v)) + return 0; + return ParseMajorFromVersionFolder(v.Trim()); + } + + // Path C: InstalledManifests x64, subkeys like ...Manifest-10.0.100 + private static bool IsDotNet10BandInInstalledManifestsX64() + { + using RegistryKey? base64 = OpenLocalMachine64(); + using RegistryKey? key = base64?.OpenSubKey(@"SOFTWARE\Microsoft\dotnet\InstalledManifests\x64"); + if (key is null) + return false; + + return key.GetSubKeyNames().Any(s => s != null + && s.IndexOf("Manifest-10.", StringComparison.OrdinalIgnoreCase) >= 0); + } + + private static RegistryKey? OpenLocalMachine64() => + RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); + + /// <summary>First numeric segment of a "10.0.5" style folder or version string (Pascal: Copy before first '.').</summary> + private static int ParseMajorFromVersionFolder(string name) + { + int dot = name.IndexOf('.'); + if (dot <= 0) + return 0; + return int.TryParse( + name.AsSpan(0, dot), + NumberStyles.Integer, + CultureInfo.InvariantCulture, + out int m) + ? m + : 0; + } +} diff --git a/src/RynthCore.DesktopLog/RynthCore.DesktopLog.csproj b/src/RynthCore.DesktopLog/RynthCore.DesktopLog.csproj new file mode 100644 index 0000000..76bf537 --- /dev/null +++ b/src/RynthCore.DesktopLog/RynthCore.DesktopLog.csproj @@ -0,0 +1,10 @@ +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFramework>net10.0</TargetFramework> + <ImplicitUsings>enable</ImplicitUsings> + <Nullable>enable</Nullable> + <RootNamespace>RynthCore</RootNamespace> + <AssemblyName>RynthCore.DesktopLog</AssemblyName> + <Version>1.0.1</Version> + </PropertyGroup> +</Project> diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index e034e41..a147ff2 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -641,12 +641,21 @@ internal static class ClientHelperHooks /// </summary> public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId) { + // Every exit records its outcome in MergeStackResults so the plugin can poll + // GetMergeStackResult instead of guessing from a later inventory snapshot. if (!MainThreadGuard.IsOnMainThread()) - return AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId); + { + bool queued = AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId); + MergeStackResults.Record(sourceObjectId, targetObjectId, + queued ? MergeStackResults.Queued : MergeStackResults.QueueFull); + return queued; + } - if (_eventStackableMerge == null) return false; - if (!IsValidObjectId(sourceObjectId)) return false; - if (!IsValidObjectId(targetObjectId)) return false; + if (_eventStackableMerge == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId)) + { + MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed); + return false; + } // Read counts via the PWD fast path (stypes 11/12 are served from // PublicWeenieDesc directly — no broken InqInt for inventory items). @@ -665,6 +674,7 @@ internal static class ClientHelperHooks if (room <= 0) { RynthLog.Verbose($"Compat: Event_StackableMerge skipped - target 0x{targetObjectId:X8}({targetCount}) is full (max={maxStack})"); + MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.TargetFull); return false; } amount = Math.Min(sourceCount, room); @@ -675,17 +685,24 @@ internal static class ClientHelperHooks amount = sourceCount; } - if (amount <= 0) return false; + if (amount <= 0) + { + MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed); + return false; + } try { byte rv = _eventStackableMerge(sourceObjectId, targetObjectId, amount); RynthLog.Verbose($"Compat: Event_StackableMerge from=0x{sourceObjectId:X8}({sourceCount}) to=0x{targetObjectId:X8}({targetCount}) amount={amount}/{maxStack} rv={rv}"); + MergeStackResults.Record(sourceObjectId, targetObjectId, + rv != 0 ? MergeStackResults.Sent : MergeStackResults.Failed, rv != 0 ? amount : 0); return rv != 0; } catch (Exception ex) { RynthLog.Compat($"Compat: Event_StackableMerge threw - {ex.Message}"); + MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed); return false; } } diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index f652df1..f3f8cca 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -241,6 +241,24 @@ internal static class ClientObjectHooks private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue; private static bool _loggedObjectIdentityServe; private const int ObjectIdentityPrefetchThrottleMs = 500; + + // Create-time identity seeds. ACCObjectMaint::CreateObject receives the server's + // PublicWeenieDesc, which already carries the object's name and ITEM_TYPE before + // qualities/appraisal exist. The main-thread snapshot above can't resolve names for + // ~10 s after login (qualities not populated yet), so off-thread readers fall back to + // these seeds when the snapshot has no entry (or reports type 0). Entries live from + // create until delete; the cap only guards against a missed delete hook. + private static readonly object _createSeedLock = new(); + private static readonly Dictionary<uint, string> _createSeedNames = new(1024); + private static readonly Dictionary<uint, uint> _createSeedTypes = new(1024); + 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 static int _createSeedCount; + private static bool _loggedCreateSeedServe; + // Every id the same walk visited, swapped whole (readers never see a half-built array). private static volatile uint[] _liveObjectIds = Array.Empty<uint>(); @@ -393,6 +411,7 @@ internal static class ClientObjectHooks private static readonly object _weeniePtrSwapLock = new(); private static Dictionary<uint, IntPtr> _weeniePtrFront = new(512); private static Dictionary<uint, IntPtr> _weeniePtrBack = new(512); + // 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. @@ -2019,8 +2038,9 @@ internal static class ClientObjectHooks value = 0; if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0) return false; + // Off-thread: served from the main-thread PWD byte snapshot, never from AC memory. if (!MainThreadGuard.IsOnMainThread()) - return false; + return TryGetPwdSnapshotRawInt32(objectId, pwdFieldOffset, out value); if (_getWeenieObject == null) { if (!Probe() || _getWeenieObject == null) @@ -2393,6 +2413,19 @@ internal static class ClientObjectHooks // Off-thread: serve from the main-thread snapshot populated by PrefetchObjectIdentity(). if (!MainThreadGuard.IsOnMainThread()) { + lock (_objectIdentityCacheLock) + { + // A zero snapshot value means qualities weren't populated when the walk + // ran; prefer the create-time descriptor type in that case. + if (_objectTypeCache.TryGetValue(objectId, out typeFlags) && typeFlags != 0) + return true; + } + if (TryGetCreateSeedType(objectId, out uint seeded)) + { + typeFlags = seeded; + return true; + } + // Snapshot hit with flags=0 is still an answer (static scenery often has no type). lock (_objectIdentityCacheLock) { if (_objectTypeCache.TryGetValue(objectId, out typeFlags)) @@ -2592,36 +2625,7 @@ internal static class ClientObjectHooks return TryGetPwdSnapshotInt(objectId, stype, out value); } - if (pwdFieldOffset >= 0 && _weeniePhysicsObjOffset >= 0) - { - try - { - IntPtr weeniePtr = _getWeenieObject(objectId); - if (weeniePtr == IntPtr.Zero) - return false; - - int pwdBase = _weeniePhysicsObjOffset + 4; - IntPtr fieldAddr = weeniePtr + pwdBase + pwdFieldOffset; - // Page-probe BOTH ends of the 4-byte read span (mirrors - // TryGetObjectOwnershipInfo's dual-end probe): a freed-but-decommitted - // weenie whose field straddles a committed/decommitted page boundary is - // an uncatchable AV under NativeAOT; the catch below only covers - // null-page faults. All stypes served here are Marshal.ReadInt32 - // (4 bytes), so the span is [fieldAddr, fieldAddr+3]. - if (!IsReadablePointer(fieldAddr) || !IsReadablePointer(fieldAddr + 3)) - return false; - - value = Marshal.ReadInt32(fieldAddr); - return true; - } - catch - { - return false; - } - } - - // Fall through to CBaseQualities::InqInt for stypes not in PWD. - // (IsOnMainThread already checked above, before the PWD fast path.) + // CBaseQualities::InqInt for stypes not in PWD. if (_inqInt == null) { if (!Probe() || _inqInt == null) @@ -3341,6 +3345,101 @@ internal static class ClientObjectHooks } } + /// <summary> + /// Records an object's name and ITEM_TYPE straight from the PublicWeenieDesc passed + /// to ACCObjectMaint::CreateObject. Called from the create hook on AC's main thread, + /// after the original returns. The descriptor is server data that exists before the + /// object's qualities do, so this makes names/types readable off-thread immediately + /// instead of after the first successful identity snapshot (~10 s at login). + /// Every read is pointer-validated; a bad descriptor simply records nothing. + /// </summary> + internal static void SeedIdentityFromCreate(uint objectId, IntPtr weenieDesc) + { + if (objectId == 0 || weenieDesc == IntPtr.Zero) + return; + + try + { + // PublicWeenieDesc derives from PackObj, so a real descriptor starts with an + // acclient.exe vtable; reject anything else before reading fields. + if (!LooksLikeAcHeapObject(weenieDesc)) + return; + + bool gotName = TryReadPwdString(weenieDesc, PwdNameOffset, out string name); + + uint typeFlags = 0; + IntPtr typeAddr = weenieDesc + PwdTypeOffset; + bool gotType = IsReadablePointer(typeAddr); + if (gotType) + typeFlags = unchecked((uint)Marshal.ReadInt32(typeAddr)); + + if (!gotName && (!gotType || typeFlags == 0)) + return; + + lock (_createSeedLock) + { + // Safety valve for a missed delete: drop everything rather than grow forever. + // The live snapshot covers anything still in the world. + if (_createSeedNames.Count >= CreateSeedCap || _createSeedTypes.Count >= CreateSeedCap) + { + _createSeedNames.Clear(); + _createSeedTypes.Clear(); + } + if (gotName) + _createSeedNames[objectId] = name; + if (gotType && typeFlags != 0) + _createSeedTypes[objectId] = typeFlags; + } + + int seedNo = System.Threading.Interlocked.Increment(ref _createSeedCount); + // First few samples let a log reader confirm the descriptor offsets resolve + // to sensible names/types on this client build. + if (seedNo <= 5) + RynthLog.Compat($"[CreateSeed] #{seedNo} 0x{objectId:X8} name='{(gotName ? name : "")}' type=0x{typeFlags:X8}"); + if (!_loggedCreateSeedServe && seedNo >= 50) + { + _loggedCreateSeedServe = true; + int names, types; + lock (_createSeedLock) { names = _createSeedNames.Count; types = _createSeedTypes.Count; } + RynthLog.Compat($"ClientObjectHooks: create-descriptor identity seeds active — {names} names, {types} types captured at CreateObject."); + } + } + catch + { + // Descriptor read failures are non-fatal; the periodic snapshot still runs. + } + } + + /// <summary>Drops create-time seeds for a deleted object (called from the delete hook).</summary> + internal static void ForgetCreateSeed(uint objectId) + { + lock (_createSeedLock) + { + _createSeedNames.Remove(objectId); + _createSeedTypes.Remove(objectId); + } + } + + private static bool TryGetCreateSeedName(uint objectId, out string name) + { + lock (_createSeedLock) + { + if (_createSeedNames.TryGetValue(objectId, out string? seeded) && seeded.Length > 0) + { + name = seeded; + return true; + } + } + name = string.Empty; + return false; + } + + private static bool TryGetCreateSeedType(uint objectId, out uint typeFlags) + { + lock (_createSeedLock) + return _createSeedTypes.TryGetValue(objectId, out typeFlags); + } + public static bool TryGetObjectName(uint objectId, out string name) { name = string.Empty; @@ -3356,6 +3455,10 @@ internal static class ClientObjectHooks return true; } } + // Snapshot miss (login burst / object newer than the last walk): serve the + // name captured from the create descriptor. + if (TryGetCreateSeedName(objectId, out name)) + return true; name = string.Empty; return false; } @@ -3809,6 +3912,21 @@ internal static class ClientObjectHooks && 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; diff --git a/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs b/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs index 9377b39..558a192 100644 --- a/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs @@ -81,6 +81,9 @@ internal static class CreateObjectHooks if (count <= 0) RynthLog.Verbose($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}"); + // Capture name/type from the create descriptor BEFORE the plugin is told about the + // object, so its off-thread classifier can read them on the very first attempt. + ClientObjectHooks.SeedIdentityFromCreate(objectId, weenieDesc); PluginManager.QueueCreateObject(objectId); AutoIdService.Enqueue(objectId); return result; diff --git a/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs b/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs index 3f8df11..151dffd 100644 --- a/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs @@ -71,6 +71,7 @@ internal static class DeleteObjectHooks if (objectId != 0) { PaletteCache.Remove(objectId); + ClientObjectHooks.ForgetCreateSeed(objectId); PluginManager.QueueDeleteObject(objectId); AutoIdService.Evict(objectId); } 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/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index 5a37c15..ba24a13 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -162,7 +162,8 @@ internal static class HeartbeatLogger // 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}"); + // Unfiltered on purpose: it is the launcher's liveness signal (see RynthLog.Heartbeat). + RynthLog.Heartbeat($"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 diff --git a/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentPatch.cs b/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentPatch.cs new file mode 100644 index 0000000..cc2d52c --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentPatch.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.Compatibility; + +/// <summary> +/// Rewrites acclient's signed "pointer % 4" padding (<see cref="LargeAddressAlignmentScan"/>) +/// to <c>and r, 3</c> in memory, so pack/unpack of buffers above 2 GB pads 0..3 bytes like +/// it does below 2 GB. Without it, a large-address-aware client corrupts dat and network +/// unpacks whenever the heap hands AC a buffer above 0x80000000 (long open-world sessions). +/// +/// The patch is never undone: an unloading engine generation leaves it in place and the next +/// generation finds every site already patched. acclient.exe on disk is not touched. +/// </summary> +internal static class LargeAddressAlignmentPatch +{ + private const uint PAGE_EXECUTE_READWRITE = 0x40; + private const ushort ImageDosSignature = 0x5A4D; + private const uint ImageNtSignature = 0x00004550; + private const int SectionHeaderSize = 40; + + private static string _statusMessage = "Not applied yet."; + + public static string StatusMessage => _statusMessage; + + /// <summary>Sites rewritten by this engine generation.</summary> + public static int PatchedCount { get; private set; } + + /// <summary>Sites a previous engine generation had already rewritten.</summary> + public static int AlreadyPatchedCount { get; private set; } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr GetModuleHandleW(string? lpModuleName); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); + + [DllImport("kernel32.dll")] + private static extern IntPtr GetCurrentProcess(); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool FlushInstructionCache(IntPtr hProcess, IntPtr lpBaseAddress, UIntPtr dwSize); + + public static void Initialize() + { + if (!Plugins.EngineSettings.EnableLargeAddressAlignmentFix) + { + _statusMessage = "Disabled via engine.json (EnableLargeAddressAlignmentFix=false)."; + RynthLog.Info($"Compat: large-address alignment fix - {_statusMessage}"); + return; + } + + IntPtr moduleBase = GetModuleHandleW("acclient.exe"); + if (moduleBase == IntPtr.Zero) + moduleBase = GetModuleHandleW(null); + if (moduleBase == IntPtr.Zero || !TryGetTextSection(moduleBase, out int textRva, out int textSize)) + { + _statusMessage = "acclient .text section not found."; + RynthLog.Compat($"Compat: large-address alignment fix skipped - {_statusMessage}"); + return; + } + + IntPtr textBase = IntPtr.Add(moduleBase, textRva); + byte[] text = new byte[textSize]; + Marshal.Copy(textBase, text, 0, textSize); + List<AlignmentSite> sites = LargeAddressAlignmentScan.Find(text, textBase.ToInt32()); + + int patched = 0, already = 0, failed = 0; + foreach (AlignmentSite site in sites) + { + if (site.AlreadyPatched) + { + already++; + continue; + } + if (TryWriteHighByte(new IntPtr(site.ImmHighByteVa))) + patched++; + else + failed++; + } + + if (patched > 0) + FlushInstructionCache(GetCurrentProcess(), textBase, (UIntPtr)(uint)textSize); + + PatchedCount = patched; + AlreadyPatchedCount = already; + _statusMessage = $"{patched} site(s) patched, {already} already patched, {failed} failed ({sites.Count} found)."; + if (sites.Count == 0 || failed > 0) + RynthLog.Compat($"Compat: large-address alignment fix - {_statusMessage}"); + else + RynthLog.Info($"Compat: large-address alignment fix - {_statusMessage}"); + } + + // One byte, protection restored per site: other hooks may hold different protections on + // neighbouring .text pages, so the whole section is never flipped at once. + private static bool TryWriteHighByte(IntPtr address) + { + if (!VirtualProtect(address, (UIntPtr)1u, PAGE_EXECUTE_READWRITE, out uint oldProtect)) + { + RynthLog.Compat($"Compat: large-address alignment fix - VirtualProtect 0x{address.ToInt32():X8} failed (error {Marshal.GetLastWin32Error()})."); + return false; + } + + try + { + // Re-check the live byte: the scan worked on a copy. + if (Marshal.ReadByte(address) != LargeAddressAlignmentScan.StockHighByte) + return false; + Marshal.WriteByte(address, LargeAddressAlignmentScan.PatchedHighByte); + return true; + } + finally + { + VirtualProtect(address, (UIntPtr)1u, oldProtect, out _); + } + } + + private static bool TryGetTextSection(IntPtr moduleBase, out int rva, out int size) + { + rva = 0; + size = 0; + if ((ushort)Marshal.ReadInt16(moduleBase) != ImageDosSignature) + return false; + int peOffset = Marshal.ReadInt32(moduleBase, 0x3C); + IntPtr nt = IntPtr.Add(moduleBase, peOffset); + if (peOffset <= 0 || (uint)Marshal.ReadInt32(nt) != ImageNtSignature) + return false; + + int sectionCount = (ushort)Marshal.ReadInt16(nt, 6); + int optionalHeaderSize = (ushort)Marshal.ReadInt16(nt, 20); + IntPtr section = IntPtr.Add(nt, 24 + optionalHeaderSize); + for (int i = 0; i < sectionCount; i++, section = IntPtr.Add(section, SectionHeaderSize)) + { + if (Marshal.PtrToStringAnsi(section, 8).TrimEnd('\0') != ".text") + continue; + size = Marshal.ReadInt32(section, 8); + rva = Marshal.ReadInt32(section, 12); + return size > 0 && rva > 0; + } + return false; + } +} diff --git a/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentScan.cs b/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentScan.cs new file mode 100644 index 0000000..b1ffa98 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentScan.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.Compatibility; + +/// <summary>One signed "pointer % 4" padding site in acclient's code.</summary> +/// <param name="AndVa">VA of the <c>and r32, imm32</c> instruction.</param> +/// <param name="ImmHighByteVa">VA of the immediate's top byte (0x80 stock, 0x00 once patched).</param> +/// <param name="Register">x86 register number (0 = eax ... 7 = edi).</param> +/// <param name="AlreadyPatched">True when the immediate is already 0x00000003.</param> +internal readonly record struct AlignmentSite(int AndVa, int ImmHighByteVa, int Register, bool AlreadyPatched); + +/// <summary> +/// Finds AC's 4-byte pack/unpack padding code, which MSVC compiled from a signed +/// <c>(int)ptr % 4</c>: +/// <code> +/// and r, 0x80000003 ; keep the sign bit +/// ... (0-12 bytes, no flag writes) +/// jns +5 +/// dec r / or r, -4 / inc r ; negative remainder fix-up +/// [pop r32] +/// je skip ; remainder 0: already aligned +/// ... pad 4 - r bytes +/// </code> +/// With large-address-aware acclient a buffer above 2 GB is a negative int, the remainder +/// comes out -3..-1, and AC pads 4 - r = 5..7 bytes instead of 1..3: the cursor runs 4 bytes +/// past the field, zeroes live data and parses garbage counts (kelpie's motion-table crashes). +/// Clearing the immediate's sign bit (<c>and r, 3</c>) makes the remainder 0..3 at any address. +/// Requiring the trailing <c>je</c> limits the patch to padding code: a signed modulo of a value +/// that can really be negative is left alone. +/// </summary> +internal static class LargeAddressAlignmentScan +{ + private const byte StockImmHighByte = 0x80; + private const byte PatchedImmHighByte = 0x00; + + // and r32, imm32 to the jns: MSVC interleaves at most a few movs; the largest gap in + // the retail client is 5 bytes. + private const int MaxGapBeforeJns = 12; + + /// <summary>Scans <paramref name="text"/> (the bytes of .text, which starts at + /// <paramref name="textVa"/>) for stock and already-patched padding sites.</summary> + public static List<AlignmentSite> Find(ReadOnlySpan<byte> text, int textVa) + { + var sites = new List<AlignmentSite>(); + // Leave room for the longest match: 6 (and) + 12 (gap) + 7 (fix-up) + 1 (pop) + 2 (je). + int last = text.Length - 28; + for (int i = 0; i < last; i++) + { + int reg, immOffset; + if (text[i] == 0x25) + { + reg = 0; // and eax, imm32 (short form) + immOffset = 1; + } + else if (text[i] == 0x81 && (text[i + 1] & 0xF8) == 0xE0) + { + reg = text[i + 1] & 0x07; // and r32, imm32 (81 /4, mod=11) + immOffset = 2; + } + else + { + continue; + } + + if (text[i + immOffset] != 0x03 || text[i + immOffset + 1] != 0x00 || text[i + immOffset + 2] != 0x00) + continue; + byte high = text[i + immOffset + 3]; + if (high != StockImmHighByte && high != PatchedImmHighByte) + continue; + + int andEnd = i + immOffset + 4; + if (!HasSignedFixupThenJe(text, andEnd, reg)) + continue; + + sites.Add(new AlignmentSite(textVa + i, textVa + i + immOffset + 3, reg, high == PatchedImmHighByte)); + } + return sites; + } + + /// <summary>The immediate's top byte value a site must hold before it is patched.</summary> + public static byte StockHighByte => StockImmHighByte; + + /// <summary>The immediate's top byte value after the patch (<c>and r, 3</c>).</summary> + public static byte PatchedHighByte => PatchedImmHighByte; + + // jns +5 ; dec r ; or r, 0xFC ; inc r ; [pop r32] ; je rel8|rel32 + private static bool HasSignedFixupThenJe(ReadOnlySpan<byte> text, int from, int reg) + { + for (int k = from; k <= from + MaxGapBeforeJns; k++) + { + if (text[k] != 0x79 || text[k + 1] != 0x05 || + text[k + 2] != 0x48 + reg || + text[k + 3] != 0x83 || text[k + 4] != 0xC8 + reg || text[k + 5] != 0xFC || + text[k + 6] != 0x40 + reg) + { + continue; + } + + int m = k + 7; + if (text[m] >= 0x58 && text[m] <= 0x5F) + m++; + return text[m] == 0x74 || (text[m] == 0x0F && text[m + 1] == 0x84); + } + return false; + } +} diff --git a/src/RynthCore.Engine/Compatibility/MergeStackResults.cs b/src/RynthCore.Engine/Compatibility/MergeStackResults.cs new file mode 100644 index 0000000..cd44aea --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/MergeStackResults.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.Compatibility; + +/// <summary> +/// Outcome of the most recent <see cref="ClientHelperHooks.MergeStackInternal"/> request per +/// (source, target) pair, so a plugin can learn what happened on AC's main thread instead of +/// only "queued". Before this, a merge the engine skipped (target already full) or that AC +/// rejected looked identical to one in flight, and RynthAi's AutoStack waited 10 s per pair +/// and logged a "confirmed failure". Thread-safe; bounded. +/// </summary> +internal static class MergeStackResults +{ + // ABI status codes (GetMergeStackResult return value). Never renumber. + public const int None = 0; // no request recorded for this pair (or it aged out) + public const int Queued = 1; // accepted onto the main-thread queue, not executed yet + public const int Sent = 2; // Event_StackableMerge sent for 'amount' units + public const int TargetFull = 3; // skipped: target stack already at max stack size + public const int Failed = 4; // invalid ids, merge API unavailable, AC returned 0, or threw + public const int QueueFull = 5; // main-thread queue full; request dropped before execution + + private struct Entry { public int Status; public int Amount; public long TickMs; } + + private const int MaxEntries = 512; // prune threshold + private const long PruneAgeMs = 120_000; // results older than this are dropped on prune + + private static readonly object _lock = new(); + private static readonly Dictionary<ulong, Entry> _results = new(); + + private static ulong Key(uint source, uint target) => ((ulong)source << 32) | target; + + /// <summary>Records the latest outcome for a pair (replaces any earlier one).</summary> + public static void Record(uint source, uint target, int status, int amount = 0) + { + long now = Environment.TickCount64; + lock (_lock) + { + if (_results.Count >= MaxEntries) + Prune(now); + _results[Key(source, target)] = new Entry { Status = status, Amount = amount, TickMs = now }; + } + } + + /// <summary>Latest outcome for the pair, or <see cref="None"/>. <paramref name="amount"/> + /// is the unit count sent (Sent only) and <paramref name="ageMs"/> how long ago it was recorded.</summary> + public static int Get(uint source, uint target, out int amount, out int ageMs) + { + amount = 0; + ageMs = 0; + lock (_lock) + { + if (!_results.TryGetValue(Key(source, target), out Entry e)) + return None; + amount = e.Amount; + long age = Environment.TickCount64 - e.TickMs; + ageMs = age > int.MaxValue ? int.MaxValue : (int)age; + return e.Status; + } + } + + // Drops aged results; if everything is recent, clears the map (callers re-request anyway). + private static void Prune(long now) + { + List<ulong>? old = null; + foreach (var kv in _results) + if (now - kv.Value.TickMs > PruneAgeMs) + (old ??= new List<ulong>()).Add(kv.Key); + if (old == null) + { + _results.Clear(); + return; + } + foreach (ulong k in old) + _results.Remove(k); + } +} diff --git a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs index b731a79..573da2e 100644 --- a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs +++ b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs @@ -43,12 +43,24 @@ internal static class SehTrampoline /// no managed callback / reverse-P/Invoke transition — so unlike the removed /// managed CrashLogger VEH it cannot itself re-trigger a NativeAOT fail-fast on an /// AC-owned thread. Writes the faulting 32-bit context + a module-resolved stack - /// sweep to <paramref name="logPath"/> for the 0xC0000005 (AV/CSE) and 0xC0000602 - /// (RaiseFailFast) classes that bypass managed handlers. Observes only. + /// sweep (bounded by the thread's StackBase) to <paramref name="logPath"/> for FATAL + /// crashes only: unhandled exceptions (chained unhandled-exception filter), AVs in + /// NativeAOT code (which the runtime fail-fasts past every filter), and other + /// first-chance AVs only if the process dies shortly after. AVs caught by the SEH_* + /// wrappers and the logger's own faults are never written. Observes only. /// </summary> public static void InstallCrashLogger(string logPath) { - try { _InstallCrashLogger(logPath); } + try + { + _InstallCrashLogger(logPath); + // v2+ logs fatal crashes only (unhandled-exception filter + NativeAOT-module AVs); + // v1 (no version export) logged every first-chance AV. + uint version = 1; + try { version = _SehTrampolineVersion(); } + catch (EntryPointNotFoundException) { } + RynthLog.Compat($"SehTrampoline: native crash logger installed (v{version}{(version >= 2 ? ", fatal-only" : ", logs every first-chance AV")}) -> {logPath}"); + } catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); } } @@ -104,6 +116,10 @@ internal static class SehTrampoline CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath); + [DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_SehTrampolineVersion", + CallingConvention = CallingConvention.Cdecl)] + private static extern uint _SehTrampolineVersion(); + [DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr _GetTagParserGuardAddress(); diff --git a/src/RynthCore.Engine/D3D9/EndSceneHook.cs b/src/RynthCore.Engine/D3D9/EndSceneHook.cs index 1c0274d..e572bdf 100644 --- a/src/RynthCore.Engine/D3D9/EndSceneHook.cs +++ b/src/RynthCore.Engine/D3D9/EndSceneHook.cs @@ -456,6 +456,11 @@ internal static class EndSceneHook if (_uiFrameCount < 30) RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}"); } + + // 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) { diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs index 27bc9e2..1f619e2 100644 --- a/src/RynthCore.Engine/EngineLifecycle.cs +++ b/src/RynthCore.Engine/EngineLifecycle.cs @@ -160,6 +160,7 @@ internal static class EngineLifecycle // tick pump and plugins go away — both otherwise keep firing in the old // generation's (intentionally still-mapped) module across hot-reloads. Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop()); + Step("LogSettings.StopWatcher", () => LogSettings.StopWatcher()); Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop()); // Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary. diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index a61602b..3f30b08 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -12,6 +12,7 @@ using System.Runtime.InteropServices; using System.Threading; using System.Collections.Generic; using ImGuiNET; +using RynthCore; using RynthCore.Engine.Compatibility; using RynthCore.Engine.D3D9; using RynthCore.Engine.Plugins; @@ -45,7 +46,21 @@ public static class EntryPoint private static readonly Queue<string> RecentLogLines = new(); private static long _recentLogSeq; - /// <summary>Set true to enable verbose startup logging (hook ready messages, plugin lifecycle, etc.).</summary> + internal enum EngineLogLevel + { + /// <summary>As a global threshold: nothing but errors. As a category level: never written.</summary> + Off = -1, + Error = 0, + Warning = 1, + Info = 2, + Debug = 3, + Trace = 4 + } + + /// <summary>Active engine logging threshold loaded from engine settings.</summary> + internal static EngineLogLevel LoggingLevel = EngineLogLevel.Info; + + /// <summary>Legacy convenience flag used by existing verbose call sites.</summary> internal static bool VerboseLogging = false; /// <summary>Set by EngineFrameController once the game window is confirmed. Read by AvaloniaOverlay.</summary> @@ -154,8 +169,14 @@ public static class EntryPoint } catch { } + // engine.json "LoggingLevel" + "LogCategories" (launcher Logging card) set the threshold + // and per-category levels first so every line written below honours them. The watcher + // started later re-reads them whenever the launcher edits the file. + string logSummary = LogSettings.Reload(); + // Set up the unified log sink BEFORE anything else so all - // subsequent failures are captured in C:\Games\RynthCore\Logs. + // subsequent failures are captured in <CoreDir>\Logs (installer-chosen; + // resolved here on the init worker, never under the loader lock). LogPaths.EnsureLogDirectory(); if (_initCount <= 1) { @@ -170,10 +191,18 @@ 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("================================================================"); + // 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. + LogSettings.StartWatcher(); CrashLogger.Install(); @@ -181,20 +210,15 @@ public static class EntryPoint // logging AC's main-thread native stack when its EndScene beat stalls. MainThreadHangWatchdog.Start(); - // MultiClientHooks.Initialize installs MinHook detours synchronously - // here, BEFORE InitWorker spawns and runs the main PreloadNativeDll - // pass. If we don't preload minhook.x86.dll first, the P/Invoke - // into minhook fails with DllNotFoundException and the multi- - // client hook silently skips — which means AC's - // Client::IsAlreadyRunning check fires unpatched on the second- - // and-later concurrent acclient.exe processes. - string? earlyEngineDir = GetEngineDirectory(); - if (!string.IsNullOrEmpty(earlyEngineDir)) - PreloadNativeDll(earlyEngineDir, "minhook.x86.dll"); - else - RynthLog.Info("Early-init: could not resolve engine directory — minhook may not be preloaded before MultiClientHooks."); + // MultiClientHooks installs MinHook-based detours immediately. P/Invoke resolves + // minhook.x86.dll before InitWorker runs, so preload it from the engine directory; + // otherwise Client::IsAlreadyRunning fires unpatched on second-and-later clients. + TryPreloadMinHookForEarlyInit(); RunInitStep("early multi-client hooks", MultiClientHooks.Initialize); + // Before AC's main thread resumes, so no dat or network unpack runs the stock + // signed padding; a hot reload finds every site already patched. + RunInitStep("large-address alignment fix", LargeAddressAlignmentPatch.Initialize); // DatFileShareHooks force-shares AC's data files at the CreateFile // layer so we can coexist with Decal-injected clients that other // launchers (Thwargle etc.) have already opened against the same @@ -300,6 +324,33 @@ public static class EntryPoint return new string(buffer, 0, (int)length); } + /// <summary> + /// Loads MinHook on the RynthCoreInit thread so <see cref="MultiClientHooks.Initialize"/> can + /// call <see cref="Hooking.MinHook"/> P/Invokes without relying on the default DLL search path + /// (which often resolves against the AC client directory, not <c>Runtime\</c>). + /// </summary> + private static void TryPreloadMinHookForEarlyInit() + { + try + { + string? engineDir = GetEngineDirectory(); + if (string.IsNullOrEmpty(engineDir)) + { + RynthLog.Info("Early MinHook preload skipped: could not resolve engine directory."); + return; + } + + if (PreloadNativeDll(engineDir, "minhook.x86.dll")) + RynthLog.Verbose($"Early MinHook preload OK (engine dir: {engineDir})"); + else + RynthLog.Info($"Early MinHook preload failed: minhook.x86.dll not found beside engine ({engineDir})."); + } + catch (Exception ex) + { + RynthLog.Info($"Early MinHook preload exception: {ex.Message}"); + } + } + /// <summary> /// No-op anchor whose address is taken via `&EngineDirAnchor` to give us a /// stable pointer inside the engine's own module image — used by @@ -656,6 +707,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()); @@ -1634,10 +1687,34 @@ public static class EntryPoint internal static void LogVerbose(string message) { - if (VerboseLogging) + if (ShouldLog(EngineLogLevel.Debug)) Log(message); } + /// <summary> + /// True when a line at <paramref name="level"/> passes the global threshold. Off-level lines + /// never pass; an Off threshold blocks everything (errors bypass this gate). + /// </summary> + internal static bool ShouldLog(EngineLogLevel level) + => level != EngineLogLevel.Off && level <= LoggingLevel; + + /// <summary>Parses the global level: Off, Error, Warning/Warn, Info, Debug/Verbose, Trace. Unknown → Info.</summary> + internal static EngineLogLevel ParseLoggingLevel(string? configuredLevel) + { + if (string.IsNullOrWhiteSpace(configuredLevel)) + return EngineLogLevel.Info; + + string normalized = configuredLevel.Trim(); + if (string.Equals(normalized, "Verbose", StringComparison.OrdinalIgnoreCase)) + return EngineLogLevel.Debug; + if (string.Equals(normalized, "Warn", StringComparison.OrdinalIgnoreCase)) + return EngineLogLevel.Warning; + + return Enum.TryParse(normalized, ignoreCase: true, out EngineLogLevel parsed) && Enum.IsDefined(parsed) + ? parsed + : EngineLogLevel.Info; + } + internal static string[] GetRecentLogLines() { lock (LogLock) diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 681d284..50cafa3 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -23,6 +23,7 @@ using System.Runtime.InteropServices; using ImGuiNET; using RynthCore.Engine.D3D9; using RynthCore.Engine.Plugins; +using RynthCore.Install; namespace RynthCore.Engine.ImGuiBackend; @@ -48,6 +49,9 @@ internal static class EngineFrameController 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; @@ -61,6 +65,25 @@ internal static class EngineFrameController /// </summary> internal static volatile IntPtr CachedDevice; private static int _pluginPumpInFrame; // re-entrancy guard for the pump + + // 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 long _engineErrorCount; + private static long _nextEngineErrorLogAt; + private static bool _loggedFirstSubmit; + private static int _loggedBranch = -1; + private static string _initFailStep = "unknown"; + 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; @@ -103,7 +126,10 @@ internal static class EngineFrameController return true; if (!EnsureCore(pDevice)) + { + _initFailStep = "EnsureCore (game window not found)"; 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. @@ -127,11 +153,11 @@ internal static class EngineFrameController // between launches. Allocated once, kept alive for the process lifetime. try { - const string iniPath = @"C:\Games\RynthSuite\RynthAi\imgui.ini"; - System.IO.Directory.CreateDirectory(@"C:\Games\RynthSuite\RynthAi"); + 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($"EngineFrameController: imgui.ini pinned to {iniPath}"); + RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}"); } catch (Exception ex) { @@ -155,10 +181,16 @@ internal static class EngineFrameController ImGuiFonts.Build(io, _uiScale); if (!Win32Backend.Init(_gameHwnd)) + { + _initFailStep = "Win32Backend.Init"; return false; + } if (!DX9Backend.InitImGui(pDevice)) + { + _initFailStep = "DX9Backend.InitImGui"; return false; + } _lastFrameTicks = Stopwatch.GetTimestamp(); _imguiInitialized = true; @@ -229,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 @@ -344,10 +378,10 @@ internal static class EngineFrameController // calls it at all. // ── ImGui-gated work ───────────────────────────────────────── - // The frame is BUILT here and SUBMITTED after the Nav3D fallback and - // the vital HUD, so ImGui windows sit above both. The Avalonia quad - // (EndSceneHook, after this returns) stays topmost while both stacks - // run, matching input order: Avalonia gets the first hit test. + // 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; @@ -370,17 +404,33 @@ internal static class EngineFrameController if (imguiEnabled) { long t0 = Stopwatch.GetTimestamp(); - if (imguiBuilt) - SubmitImGuiFrame(pDevice); // Popped-out panels: their own contexts, windows and render targets. if (_imguiInitialized) ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive); - UiFrameStats.Record(uiTicks + (Stopwatch.GetTimestamp() - t0)); + long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0); + if (imguiBuilt) + { + _deferredUiTicks = ticks; + _deferredSubmitDevice = pDevice; + } + else + { + UiFrameStats.Record(ticks); + } } } catch (Exception ex) { - RynthLog.Info($"EngineFrameController: frame {_frameCount} engine error: {ex.GetType().Name}: {ex.Message}"); + // An exception here skips everything after it this frame (including RunImGuiFrame), so + // the first one gets a stack trace; repeats are summarised every 30 s instead of per frame. + _engineErrorCount++; + long errNow = Environment.TickCount64; + if (_engineErrorCount == 1) + RynthLog.Error($"EngineFrameController: engine frame error (rest of this frame skipped): {ex}"); + else if (errNow >= _nextEngineErrorLogAt) + RynthLog.Error($"EngineFrameController: engine frame errors so far={_engineErrorCount}, latest {ex.GetType().Name}: {ex.Message}"); + if (errNow >= _nextEngineErrorLogAt) + _nextEngineErrorLogAt = errNow + HeartbeatIntervalMs; } finally { @@ -442,14 +492,26 @@ 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 - // (EnableImGuiShell, FORCE-gated). The engine's own ImGui panels - // don't need plugins to see it, and handing it over switched - // RynthAi into its legacy-ImGui setup (first ImGui-on test, - // 2026-09-28) - plugins must behave exactly as in Avalonia-only mode. - IntPtr pluginContext = Plugins.EngineSettings.EnableImGuiShell ? _context : IntPtr.Zero; + // 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(pluginContext, device, _gameHwnd); } @@ -500,9 +562,17 @@ internal static class EngineFrameController if (Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled) return true; if (!PanelsLive) return false; ImGuiPanelHost.RestoreOnce(); - return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame; + 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). Also off as soon as AC leaves the world screen @@ -543,7 +613,8 @@ internal static class EngineFrameController } private static bool HasImGuiContentNoRestore() => - Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame)); + 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. @@ -572,6 +643,7 @@ internal static class EngineFrameController if (!Init(pDevice)) { _imguiInitFailed = true; + RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session."); return false; } } @@ -595,7 +667,6 @@ internal static class EngineFrameController ImGuiNET.ImGui.SetCurrentContext(_context); bool frameStarted = false; bool frameEnded = false; - try { ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); @@ -643,6 +714,9 @@ internal static class EngineFrameController ImGuiNET.ImGui.NewFrame(); frameStarted = true; + // 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) { @@ -652,11 +726,29 @@ internal static class EngineFrameController } // 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) { + branch = 1; RynthCoreShell.Render(_frameCount); PluginManager.RenderAll(); } + else if (PluginOverlayWindowsLive) + { + branch = 2; + // Only the opt-in extra windows (RynthPluginRenderOverlay), never the + // plugins' full ImGui UIs. + PluginManager.RenderOverlayAll(); + } + else + { + branch = 0; + } + if (branch != _loggedBranch) + { + _loggedBranch = branch; + RynthLog.Info($"EngineFrameController: ImGui plugin branch = {(branch == 1 ? "shell (RenderAll)" : branch == 2 ? "overlay windows (RenderOverlayAll)" : "none")}."); + } if (PanelsLive) { // World overlays: built into UnderUiLayer's list, drawn next frame at @@ -736,6 +828,24 @@ internal static class EngineFrameController _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 <see cref="OnEndScene"/> built nothing this frame. Never throws. + /// </summary> + public static void RenderDeferredImGui() + { + IntPtr device = _deferredSubmitDevice; + if (device == IntPtr.Zero) + return; + _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) { @@ -743,7 +853,15 @@ internal static class EngineFrameController ImGuiNET.ImGui.SetCurrentContext(_context); try { - DX9Backend.RenderDrawData(ImGuiNET.ImGui.GetDrawData(), pDevice); + ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData(); + DX9Backend.RenderDrawData(drawData, pDevice); + _drawSubmits++; + if (!_loggedFirstSubmit) + { + _loggedFirstSubmit = true; + RynthLog.Info("EngineFrameController: first ImGui draw submitted."); + } + LogHeartbeatIfDue(drawData); } catch (Exception ex) { @@ -755,6 +873,29 @@ internal static class EngineFrameController } } + /// <summary> + /// 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> + private static void LogHeartbeatIfDue(ImDrawDataPtr drawData) + { + long now = Environment.TickCount64; + if (now < _nextHeartbeatAt) return; + bool first = _nextHeartbeatAt == 0; + _nextHeartbeatAt = now + HeartbeatIntervalMs; + if (first) return; // first interval starts now; the first-frame line already covers t=0 + + int lists = 0, vertices = 0; + unsafe + { + // ImDrawData: +4 CmdListsCount, +8 TotalIdxCount, +12 TotalVtxCount (see CLAUDE.md offsets). + byte* p = (byte*)drawData.NativePtr; + if (p != null) { lists = *(int*)(p + 4); vertices = *(int*)(p + 12); } + } + RynthLog.Info($"EngineFrameController: ImGui heartbeat frames={_framesBuilt} submits={_drawSubmits} lastFrame drawLists={lists} vertices={vertices} {PluginManager.DescribeOverlayState()}."); + } + internal static IntPtr FindGameWindow() { uint pid = GetCurrentProcessId(); diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index f153763..f55b35d 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -66,7 +66,11 @@ internal sealed record PanelSpec( 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); + 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 @@ -648,6 +652,10 @@ internal static class ImGuiPanelHost { 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; @@ -667,6 +675,104 @@ internal static class ImGuiPanelHost 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) 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/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index 5eb4e05..e07110c 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -79,6 +79,8 @@ internal sealed class ChatFiltersFace : IImGuiPanel "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() { @@ -118,6 +120,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel 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(); @@ -156,6 +159,58 @@ internal sealed class ChatFiltersFace : IImGuiPanel 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; @@ -216,6 +271,18 @@ internal sealed class ChatFiltersFace : IImGuiPanel 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)) @@ -484,7 +551,12 @@ internal sealed class ChatFiltersFace : IImGuiPanel 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 < 0 ? "Your name" : $"Rule {step.Rule + 1}") + ": " + step.What, Text)); + _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; diff --git a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs index 00af2e3..cca13f5 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs @@ -10,8 +10,8 @@ // // 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). +// big it is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files, +// Patrol and Mini Remote (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 diff --git a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs index 42b1e9f..558e47b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs @@ -44,7 +44,7 @@ internal sealed class DungeonMapFace : IImGuiPanel { 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), + new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true, OpenCentered: true), () => new DungeonMapFace()); } diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs index 807801e..ab31f00 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs @@ -620,7 +620,7 @@ internal sealed partial class InventoryFace _hover = it; if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) { - _selected = it.Id; + SelectItem(it); _pressItem = it; _pressAt = ImGuiNET.ImGui.GetMousePos(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs index 8203e1d..065b6b4 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs @@ -122,6 +122,7 @@ internal sealed partial class InventoryFace : IImGuiPanel InventoryModel.Hover(0); InventoryModel.Unsubscribe(); _dragItem = _pressItem = null; + ItemDragBridge.EndPopOutDrag(); _lootAdd.Cancel(); } @@ -475,7 +476,7 @@ internal sealed partial class InventoryFace : IImGuiPanel if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) { - _selected = hot.Id; + SelectItem(hot); _pressItem = hot; _pressAt = mouse; } @@ -749,6 +750,7 @@ internal sealed partial class InventoryFace : IImGuiPanel _dragItem = null; _pressItem = null; if (item == null) return; + ItemDragBridge.EndPopOutDrag(); Vector2 m = ImGuiNET.ImGui.GetMousePos(); foreach (Target t in _targets) { @@ -759,13 +761,50 @@ internal sealed partial class InventoryFace : IImGuiPanel } } - private void DrawDragGhost() + /// <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 ───────────────────────────────────────────────────────── @@ -892,6 +931,11 @@ internal sealed partial class InventoryFace : IImGuiPanel _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)"); } @@ -902,6 +946,36 @@ internal sealed partial class InventoryFace : IImGuiPanel } } + /// <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) diff --git a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs index 34b14fc..a0fe2b2 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs @@ -7,6 +7,9 @@ // // item its name and the profile the rule goes to // match name + class (default), name only, items like this +// T11 "Include T11 attributes": also require the item's T11 tier, +// grade, damage %, modifiers, slot special and Cast on Strike, +// each at least this item's (any match; 2026-10-07) // 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 @@ -48,6 +51,7 @@ internal sealed class LootAddDialog // What the popup asks for (0 / -1 = RynthAi's default). private int _match, _action, _keep = -1; + private bool _includeT11; private readonly byte[] _name = new byte[128]; private int _keepEdit = 1; @@ -88,6 +92,7 @@ internal sealed class LootAddDialog _match = 0; _action = 0; _keep = -1; + _includeT11 = false; Array.Clear(_name); _draft = null; _adding = false; @@ -113,7 +118,7 @@ internal sealed class LootAddDialog Item = new LootEditItemRequestDto { ItemId = _itemId, Match = _match, Action = _action, KeepCount = _keep, - RuleName = Utf8(_name).Trim(), ToOpenProfile = _toOpenProfile, Seq = _seq, + RuleName = Utf8(_name).Trim(), ToOpenProfile = _toOpenProfile, IncludeT11 = _includeT11, Seq = _seq, }, }); } @@ -255,6 +260,26 @@ internal sealed class LootAddDialog if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(MatchTips[i]); } + // T11 attributes. Shown for every item: a non-T11 item answers with a note saying so. + bool t11 = _includeT11; + if (ImGuiNET.ImGui.Checkbox("Include T11 attributes##la_t11", ref t11)) + { + _includeT11 = t11; + changed = true; + } + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip( + "Also require this item's T11 tier (the server's stamped tier when it sends one), weapon grade,\n" + + "damage %, gear grade, every modifier, slot special and Cast on Strike, each at least as good\n" + + "as this one. Works with any match.\n" + + "Not added: Can Wield (depends on your character), Zone Locked (depends on where it was assessed),\n" + + "and property slots / Tainted (bag state, not quality)."); + if (!d.IsT11) + { + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextDisabled("(not a T11 item)"); + } + // Action. ImGuiNET.ImGui.TextDisabled("Action:"); for (int i = 0; i < ActionIds.Length; i++) diff --git a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs index baa21e6..36d4235 100644 --- a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs @@ -1,21 +1,28 @@ // ============================================================================ // 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, 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). +// Start/Stop, route type and insert mode, the Breadcrumbs and Route overlay +// toggles, Add Waypoint / Portal (selected object) / +// Recall / Clear / Save / Dungeon Patrol, the route editor (move / duplicate / +// delete / set active / move here on the selection; nearest, reverse, snap to +// path, point at selection, pause, simplify; recording and trail -> route), +// 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, Ctrl/Shift-click multi-selects, double-click +// sets active, right-click edits, X or Delete 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. +// snapshot (requested right after) replaces the copy. Edits send indices into +// the route this face shows, so the selection is remapped locally as the copy +// changes. 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.Linq; using System.Numerics; using ImGuiNET; using RynthCore.Engine.UI.Data; @@ -28,7 +35,7 @@ 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 PanelSpec(new Vector2(400, 680), new Vector2(360, 440), EdgeToEdge: true), () => new NavFace()); private static readonly string[] Actions = @@ -38,12 +45,30 @@ internal sealed class NavFace : IImGuiPanel }; 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 }; + + // Route editor rows. Edit acts on the selected waypoints; Tools on the route. + private static readonly string[] EditActions = + { + PhosphorIcons.ArrowUp + " Up", PhosphorIcons.ArrowDown + " Down", PhosphorIcons.Copy + " Duplicate", + PhosphorIcons.Trash + " Delete", PhosphorIcons.Target + " Set Active", PhosphorIcons.Crosshair + " Move Here", + }; + private static readonly string[] ToolActions = + { + PhosphorIcons.NavigationArrow + " Nearest", PhosphorIcons.ArrowsClockwise + " Reverse", PhosphorIcons.Path + " Snap to Path", + PhosphorIcons.MapPin + " Point at Selected", PhosphorIcons.Hourglass + " Add Pause", PhosphorIcons.Scissors + " Simplify", + }; + private static readonly string[] RowMenu = + { "Set Active", "Move Here", "Move Up", "Move Down", "Duplicate", "Delete" }; + private const string FromTrail = PhosphorIcons.Footprints + " Route from Trail..."; + private readonly bool[] _editEnabled = new bool[6]; private NavPayload _data = new(); private long _seenVersion = -1; private readonly List<string> _pointText = new(); - private int _selected = -1, _addMode; + // _selected is the focus row (insert point, chat editing); _multi is every selected row, + // always containing _selected when it is set. _anchor starts Shift-click ranges. + private int _selected = -1, _anchor = -1, _addMode; + private readonly HashSet<int> _multi = new(); private bool _typing; private string _routeLabel = "Route: Once", _insertLabel = "Insert: End", _activeLabel = "Active Nav: None (Unsaved)"; private string _fileLabel = "Select nav file..."; @@ -130,13 +155,32 @@ internal sealed class NavFace : IImGuiPanel }); 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); + int action = WrapButtons("nav_act", Actions, w, 24); switch (action) { case 0: NavCommands.Send(new NavCmd { Cmd = "addWaypoint", AddMode = _addMode, InsertAt = _selected }); break; + case 1: NavCommands.Send(new NavCmd { Cmd = "addPortal", 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 })); @@ -144,13 +188,15 @@ internal sealed class NavFace : IImGuiPanel case 3: NavCommands.Send(new NavCmd { Cmd = "clearRoute" }); _data.Points.Clear(); - _selected = -1; + ClearSelection(); RebuildPointText(); break; case 4: NavCommands.Send(new NavCmd { Cmd = "saveRoute" }); break; case 5: NavCommands.Send(new NavCmd { Cmd = "dunPatrol" }); break; } + RouteEditor(w); + // 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 @@ -230,6 +276,9 @@ internal sealed class NavFace : IImGuiPanel ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1)); ImGuiNET.ImGui.BeginChild("##nav_points", new Vector2(w, listH)); Waypoints(ImGuiNET.ImGui.GetContentRegionAvail().X); + if (!typing && _multi.Count > 0 && ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Delete, false) + && (ImGuiNET.ImGui.IsWindowHovered() || ImGuiNET.ImGui.IsWindowFocused())) + DeleteSelected(); ImGuiNET.ImGui.EndChild(); ImGuiNET.ImGui.PopStyleVar(); ImGuiNET.ImGui.PopStyleColor(); @@ -239,6 +288,18 @@ internal sealed class NavFace : IImGuiPanel _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 @@ -303,20 +364,24 @@ internal sealed class NavFace : IImGuiPanel 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; + bool active = i == _data.ActiveNavIndex, selected = _multi.Contains(i); 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; + if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) ClickRow(i); + if (ImGuiNET.ImGui.IsItemHovered() && ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left)) + SetActive(i); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + { + if (!selected) SelectOnly(i); + _picker.Open(ImGuiNET.ImGui.GetIO().MousePos, RowMenu, -1, RowMenuPick, width: 140); + } 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(); + RemoveLocal(new HashSet<int> { i }); ImGuiNET.ImGui.PopID(); return; } @@ -331,6 +396,216 @@ internal sealed class NavFace : IImGuiPanel } } + /// <summary> + /// Route editor: Edit row (on the selection), Tools row (on the route), the Record toggle + /// with "Route from Trail...", and the last edit's result. Picker-backed buttons (pause, + /// simplify, trail) double as the confirmation for edits that can't be undone. + /// </summary> + private void RouteEditor(float w) + { + int n = _multi.Count, count = _data.Points.Count; + bool one = n == 1 && _selected >= 0; + _editEnabled[0] = n > 0 && _multi.Min() > 0; + _editEnabled[1] = n > 0 && _multi.Max() < count - 1; + _editEnabled[2] = _editEnabled[3] = n > 0; + _editEnabled[4] = _editEnabled[5] = one; + Label(n > 1 ? $"Edit ({n} selected)" : "Edit", Mute); + switch (WrapButtons("nav_edit", EditActions, w, 22, _editEnabled)) + { + case 0: MoveSelected(-1); break; + case 1: MoveSelected(+1); break; + case 2: DuplicateSelected(); break; + case 3: DeleteSelected(); break; + case 4: SetActive(_selected); break; + case 5: NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break; + } + + Vector2 at = ImGuiNET.ImGui.GetIO().MousePos; + switch (WrapButtons("nav_tools", ToolActions, w, 22)) + { + case 0: NavCommands.Send(new NavCmd { Cmd = "nearestActive" }); break; + case 1: + if (count < 2) break; + NavCommands.Send(new NavCmd { Cmd = "reverseRoute" }); + ReverseLocal(); + break; + case 2: NavCommands.Send(new NavCmd { Cmd = "snapToPath" }); break; + case 3: NavCommands.Send(new NavCmd { Cmd = "addPointAtSelected", AddMode = _addMode, InsertAt = _selected }); break; + case 4: + _picker.Open(at, NavCommands.PauseLabels, -1, i => NavCommands.Send(new NavCmd + { Cmd = "addPause", Seconds = NavCommands.PauseSeconds[i], AddMode = _addMode, InsertAt = _selected }), width: 140); + break; + case 5: + _picker.Open(at, NavCommands.SimplifyLabels, -1, i => + NavCommands.Send(new NavCmd { Cmd = "simplifyRoute", Yards = NavCommands.SimplifyYards[i] }), width: 300); + break; + } + + // Record | Route from Trail... + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float half = (w - 4) / 2; + if (OverlayToggle("##record", "Record route", _data.IsRecording, p, half, + "Add a point every few yards as you walk, and portal steps as you use portals\n(/ra navrec on|off). Points go into the current route.")) + { + bool on = !_data.IsRecording; + NavCommands.Send(new NavCmd { Cmd = "setRecording", On = on }); + _data.IsRecording = on; + } + Vector2 tp = new(p.X + half + 4, p.Y); + if (Button("##fromtrail", FromTrail, tp, new Vector2(half, 22), Text, BtnFill, enabled: _data.TrailPoints >= 2)) + _picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i => + NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300); + if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGuiNET.ImGui.SetTooltip(_data.TrailPoints >= 2 + ? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed." + : "Turn on Breadcrumbs and walk a while to build a trail."); + NextLine(p, 26); + + if (_data.EditStatus.Length > 0) Label(_data.EditStatus, Amber); + } + + /// <summary>Plain click selects one row, Ctrl toggles a row, Shift selects from the anchor.</summary> + private void ClickRow(int i) + { + var io = ImGuiNET.ImGui.GetIO(); + if (io.KeyShift && _anchor >= 0) + { + if (!io.KeyCtrl) _multi.Clear(); + for (int k = Math.Min(_anchor, i); k <= Math.Max(_anchor, i); k++) _multi.Add(k); + _selected = i; + } + else if (io.KeyCtrl) + { + if (!_multi.Remove(i)) { _multi.Add(i); _selected = i; } + else if (_selected == i) _selected = _multi.Count > 0 ? _multi.Min() : -1; + _anchor = i; + } + else SelectOnly(i); + } + + private void SelectOnly(int i) + { + _multi.Clear(); + _multi.Add(i); + _selected = _anchor = i; + } + + private void ClearSelection() + { + _multi.Clear(); + _selected = _anchor = -1; + } + + private List<int> SelectedIndices() + { + var list = new List<int>(_multi); + list.Sort(); + return list; + } + + private void RowMenuPick(int item) + { + switch (item) + { + case 0: if (_selected >= 0) SetActive(_selected); break; + case 1: if (_selected >= 0) NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break; + case 2: MoveSelected(-1); break; + case 3: MoveSelected(+1); break; + case 4: DuplicateSelected(); break; + case 5: DeleteSelected(); break; + } + } + + private void SetActive(int i) + { + if (i < 0 || i >= _data.Points.Count) return; + NavCommands.Send(new NavCmd { Cmd = "setActive", Index = i }); + _data.ActiveNavIndex = i; + } + + /// <summary>Moves the selected rows one slot, the way the plugin does (NavRouteEditing.Move).</summary> + private void MoveSelected(int delta) + { + if (_multi.Count == 0) return; + NavCommands.Send(new NavCmd { Cmd = "movePoints", Indices = SelectedIndices(), Delta = delta }); + var pts = _data.Points; + var sel = new HashSet<NavPoint>(); + foreach (int i in _multi) sel.Add(pts[i]); + NavPoint? focus = _selected >= 0 ? pts[_selected] : null, anchor = _anchor >= 0 && _anchor < pts.Count ? pts[_anchor] : null; + if (delta < 0) + { + for (int i = 1; i < pts.Count; i++) + if (sel.Contains(pts[i]) && !sel.Contains(pts[i - 1])) (pts[i - 1], pts[i]) = (pts[i], pts[i - 1]); + } + else + { + for (int i = pts.Count - 2; i >= 0; i--) + if (sel.Contains(pts[i]) && !sel.Contains(pts[i + 1])) (pts[i + 1], pts[i]) = (pts[i], pts[i + 1]); + } + _multi.Clear(); + for (int i = 0; i < pts.Count; i++) if (sel.Contains(pts[i])) _multi.Add(i); + _selected = focus != null ? pts.IndexOf(focus) : -1; + _anchor = anchor != null ? pts.IndexOf(anchor) : _selected; + RebuildPointText(); + } + + /// <summary>Each selected row gets a copy right after it (as the plugin does); the copies end up selected.</summary> + private void DuplicateSelected() + { + if (_multi.Count == 0) return; + NavCommands.Send(new NavCmd { Cmd = "duplicatePoints", Indices = SelectedIndices() }); + var result = new List<NavPoint>(_data.Points.Count + _multi.Count); + var copies = new HashSet<int>(); + for (int i = 0; i < _data.Points.Count; i++) + { + NavPoint pt = _data.Points[i]; + result.Add(pt); + if (!_multi.Contains(i)) continue; + copies.Add(result.Count); + result.Add(new NavPoint { Type = pt.Type, Desc = pt.Desc, Text = pt.Text, NS = pt.NS, EW = pt.EW, Z = pt.Z }); + } + _data.Points = result; + _multi.Clear(); + _multi.UnionWith(copies); + _selected = _anchor = _multi.Count > 0 ? _multi.Min() : -1; + RebuildPointText(); + } + + private void DeleteSelected() + { + if (_multi.Count == 0) return; + NavCommands.Send(new NavCmd { Cmd = "deletePoints", Indices = SelectedIndices() }); + RemoveLocal(new HashSet<int>(_multi)); + } + + /// <summary>Drops rows from the local copy and shifts the selection past them.</summary> + private void RemoveLocal(HashSet<int> removed) + { + int Shift(int i) { int s = 0; foreach (int r in removed) if (r < i) s++; return i - s; } + var keep = new List<int>(); + foreach (int i in _multi) if (!removed.Contains(i)) keep.Add(Shift(i)); + _selected = _selected >= 0 && !removed.Contains(_selected) ? Shift(_selected) : -1; + _anchor = _anchor >= 0 && !removed.Contains(_anchor) ? Shift(_anchor) : _selected; + _multi.Clear(); + _multi.UnionWith(keep); + if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min(); + for (int i = _data.Points.Count - 1; i >= 0; i--) if (removed.Contains(i)) _data.Points.RemoveAt(i); + RebuildPointText(); + } + + private void ReverseLocal() + { + int last = _data.Points.Count - 1; + _data.Points.Reverse(); + var flipped = new List<int>(); + foreach (int i in _multi) flipped.Add(last - i); + _multi.Clear(); + _multi.UnionWith(flipped); + if (_selected >= 0) _selected = last - _selected; + if (_anchor >= 0) _anchor = last - _anchor; + RebuildPointText(); + } + private void TakeSnapshot() { var snap = UiSources.Nav.Current; @@ -338,7 +613,11 @@ internal sealed class NavFace : IImGuiPanel _seenVersion = snap.Version; _data = snap.Value.Clone(); _navFiles = _data.NavFiles.ToArray(); - if (_selected >= _data.Points.Count) _selected = -1; + int count = _data.Points.Count; + _multi.RemoveWhere(i => i >= count); + if (_selected >= count) _selected = -1; + if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min(); + if (_anchor >= count) _anchor = _selected; RebuildPointText(); UpdateLabels(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs index cc3946b..4ce63ef 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs @@ -12,12 +12,19 @@ // 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). +// Mini Remote RynthAi's Mini Remote (session rates, target, summon, +// item slots, toggles, bank, rebuff, Translate, Guardian) +// with its Options menu. The plugin draws it here through +// RynthPluginRenderEmbed("miniremote") and says how big it +// wants the panel; the Hub launcher's right-click opens it +// (popped out: the floating Mini Remote instead). // AC thread only (inside the dashboard's Draw). // ============================================================================ using System; using System.Numerics; using ImGuiNET; +using RynthCore.Engine.Plugins; using RynthCore.Engine.UI; using RynthCore.Engine.UI.Data; @@ -25,7 +32,7 @@ namespace RynthCore.Engine.ImGuiBackend.Panels; internal sealed partial class RynthAiFace { - /// <summary>Meta state, bot activity and the four file pickers.</summary> + /// <summary>Meta state, bot activity and the five file pickers.</summary> private sealed class FilesDrawer : DashboardDrawer { private readonly RynthAiFace _face; @@ -40,9 +47,10 @@ internal sealed partial class RynthAiFace 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" + + return "Loaded files: the Profile, Nav, Loot, Meta and Buffs pickers, meta state and bot activity.\n" + "Profile: " + (v?.ProfileText ?? "Default") + "\nNav: " + (v?.NavText ?? "None") + "\nLoot: " + (v?.LootText ?? "None") + "\nMeta: " + (v?.MetaText ?? "None") + + "\nBuffs: " + (v?.BuffText ?? "Built-in") + (right ? "\n\nClick to slide them out (to the right: there's no room on the left)." : "\n\nClick to slide them out."); } @@ -50,7 +58,7 @@ internal sealed partial class RynthAiFace 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; + (Pad + TitleH + 4 + 2 * LineH + 6) * k + 5 * SelRow + 4 * SelGap + Pad * k; public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) { @@ -76,6 +84,8 @@ internal sealed partial class RynthAiFace _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); + y += SelRow + SelGap; + _face.Selector(4, "Buffs:", view?.BuffText ?? "Built-in", raw.BuffProfiles, raw.SelectedBuffIdx, 4, x, y, w, null, spellsButton: true); } private static void InfoLine(ImDrawListPtr dl, ImFontPtr f, float x, float y, float w, float lh, float labelW, string label, string value) @@ -136,4 +146,81 @@ internal sealed partial class RynthAiFace finally { ImGuiNET.ImGui.EndChild(); } } } + + /// <summary>RynthAi's Mini Remote, drawn by the plugin into this drawer (the Hub launcher's right-click).</summary> + private sealed class RemoteDrawer : DashboardDrawer + { + /// <summary>The plugin surface name, NUL-terminated for the export.</summary> + private static ReadOnlySpan<byte> Surface => "miniremote\0"u8; + + // Content bounds in unscaled pixels; the plugin's wish is clamped to them. + private const float MinW = 200, MaxW = 760, MinH = 60, DefaultH = 120; + + /// <summary>The content size the plugin last asked for (pixels); zero until it has drawn here.</summary> + private Vector2 _want; + + public override string Key => "remote"; + public override string Icon => PhosphorIcons.SquaresFour; + public override string Name => "Mini Remote drawer"; + public override bool SavedOpen => RynthAiDashboardState.RemoteOpen; + public override void SaveOpen(bool open) => RynthAiDashboardState.SetRemoteOpen(open); + + public override string TabTooltip(bool right) => + "Mini Remote: session rates, attack target, summon, item slots, toggles, bank, rebuff, Translate.\n" + + "Its Options button picks the sections and opens the ILT Hub windows (also: right-click Hub).\n" + + (right ? "Click to slide it out (to the right: there's no room on the left)." : "Click to slide it out."); + + public override float Width(float k) => + Math.Clamp(_want.X > 0 ? _want.X : MinW * k, MinW * k, MaxW * k) + 2 * Pad * k; + + public override float Height(float k) + { + float frame = (Pad + TitleH + 4 + Pad) * k; + // Never taller than the screen: the body scrolls instead. + float screen = ImGuiNET.ImGui.GetIO().DisplaySize.Y; + float maxBody = screen > 1 ? MathF.Max(MinH * k, screen - frame - 8 * k) : 900 * k; + return frame + Math.Clamp(_want.Y > 0 ? _want.Y : DefaultH * k, MinH * k, maxBody); + } + + public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) + { + float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.SquaresFour, "MINI REMOTE", null, "Hide the Mini Remote drawer"); + float x = origin.X + Pad * k; + 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("##remote_body", size, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (!open) return; + // The plugin's widgets use the default UI font, as in its floating Mini Remote. + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + try + { + int result = PluginManager.RenderEmbed("RynthAi", Surface, size, out Vector2 want); + if (result == PluginManager.EmbedDrawn) + { + if (want.X > 0 && want.Y > 0) _want = want; + } + else + { + _want = Vector2.Zero; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, DMute); + ImGuiNET.ImGui.TextWrapped(result switch + { + PluginManager.EmbedNoPlugin => + "This RynthAi can't draw its Mini Remote here (it needs RynthAi 0.5.27 or later). Left-click Hub for the floating Mini Remote.", + PluginManager.EmbedFailed => + "The Mini Remote failed to draw here (see the log). Left-click Hub for the floating Mini Remote.", + _ => "The Mini Remote shows here once RynthAi is ready: in the world, with plugin windows on (engine.json EnablePluginOverlayWindows).", + }); + ImGuiNET.ImGui.PopStyleColor(); + } + } + finally { ImGuiNET.ImGui.PopFont(); } + } + finally { ImGuiNET.ImGui.EndChild(); } + } + } } diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs index 6e0bb4b..415f2d8 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -18,7 +18,7 @@ // 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 +// (RangesSlideOut.cs), Loaded files, Patrol and Mini Remote // (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 @@ -76,13 +76,14 @@ internal sealed partial class RynthAiFace : IImGuiPanel // The drawers on the dashboard's left edge (their own window, placed against this one). private readonly DashboardDrawers _drawers; private readonly PatrolDrawer _patrol = new(); + private readonly RemoteDrawer _remote = 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]; + private readonly int[] _pickerShownFrame = { -10, -10, -10, -10, -10 }; + private readonly bool[] _pressedWhileOpen = new bool[5]; // 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; @@ -92,7 +93,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel public RynthAiFace() { // Tab order top to bottom; the first one saved open wins at load. - _drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol); + _drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol, _remote); } public Vector2? MinSize => new Vector2(MinWidth, _contentHeight > 0 ? _contentHeight @@ -145,6 +146,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel } 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(); @@ -248,7 +250,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + rowH)); } - // ── Header: macro + state (40%) | Profile/Nav/Loot/Meta pickers (60%) ── + // ── Header: macro + state (40%) | Profile/Nav/Loot/Meta/Buffs pickers (60%) ── private void HeaderGrid(RynthAiView? view, RynthAiSnapshot raw, float x0, float width) { @@ -266,7 +268,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel 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). + // Right: five 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; @@ -280,23 +282,39 @@ internal sealed partial class RynthAiFace : IImGuiPanel 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 + 3; + Selector(4, "Buffs:", view?.BuffText ?? "Built-in", raw.BuffProfiles, raw.SelectedBuffIdx, 4, rx, ry, rw, null, spellsButton: true); 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[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta", "##sel_buff" }; + private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta", "##pick_buff" }; private static readonly string[] NoneItems = { "None" }; + /// <summary> + /// One file picker row. <paramref name="kind"/> is RynthPluginSelectProfile's list (0 nav, + /// 1 loot, 2 meta, 3 settings profile, 4 buff profile). <paramref name="lootEdit"/> adds the + /// Loot Editor button, <paramref name="spellsButton"/> the RynthAi Spells window button. + /// </summary> private void Selector(int slot, string label, string text, string[] items, int selected, int kind, - float x, float y, float w, RynthAiSnapshot? lootEdit) + float x, float y, float w, RynthAiSnapshot? lootEdit, bool spellsButton = false) { 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 (spellsButton) + { + editW = 18; + var ep = new Vector2(x + w - editW, y); + if (IconButton("##buff_spells", ep, new Vector2(editW, 16), PhosphorIcons.Sparkle, UiFont.Dash11, SelectorBg, Mute, 0, 2)) + RynthAiCommands.ApplyRemoteCommand("spells", "toggle"); + ImGuiNET.ImGui.SetItemTooltip("RynthAi Spells: browse the spell list and build buff profiles."); + editW += 3; + } if (lootEdit != null) { editW = 18; @@ -431,7 +449,8 @@ internal sealed partial class RynthAiFace : IImGuiPanel 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."); + "\nBuffs: " + (view?.BuffText ?? "Built-in") + + "\n\nClick to show the Profile, Nav, Loot, Meta and Buffs pickers."); } // What the bot is doing, always in view (every mode, minimized too): between the toggles and FR. @@ -477,7 +496,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel private void Launchers(float x0, float width) { float y = ImGuiNET.ImGui.GetCursorScreenPos().Y; - const int buttons = 8; + 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; @@ -516,6 +535,32 @@ internal sealed partial class RynthAiFace : IImGuiPanel } 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; + // Right-click is the Mini Remote drawer, as Patrol's is its drawer; popped out there are + // no drawers, so it shows the floating Mini Remote. Inventory HUDs setup is in the + // Mini Remote's Options menu. + Launcher("##l_hub", PhosphorIcons.SquaresFour, "Hub", + popped ? "Hub. Left-click: floating Mini Remote (/ra remote). Right-click: show the floating Mini Remote." + : "Hub. Left-click: floating Mini Remote (/ra remote). Right-click: the Mini Remote drawer (left), with its Options.", + x, y, bw, labels, () => RynthAiCommands.ApplyRemoteCommand("remote", "toggle")); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + { + if (popped) RynthAiCommands.ApplyRemoteCommand("remote", "show"); + else _drawers.Toggle(_remote); + } ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + LauncherH)); } @@ -682,6 +727,46 @@ internal sealed partial class RynthAiFace : IImGuiPanel 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() diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs index bdf3135..de18c2d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs @@ -53,14 +53,27 @@ internal sealed class SettingsFace : IImGuiPanel public bool Active; // the box had keyboard focus last frame } private readonly Dictionary<SettingRow, NumberEdit> _edits = new(); + // Text rows being typed in (the saved value shows again once the box loses focus). + private readonly Dictionary<SettingRow, string> _textEdits = 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(); + public void OnHidden() + { + UiSources.Settings.Unsubscribe(); + UiSources.Charms.Unsubscribe(); + } public void Draw() { @@ -100,9 +113,9 @@ internal sealed class SettingsFace : IImGuiPanel var dl = ImGuiNET.ImGui.GetWindowDrawList(); float w = ImGuiNET.ImGui.GetContentRegionAvail().X; SettingsTab[] tabs = SettingsSchema.Tabs; - for (int i = 0; i < tabs.Length; i++) + for (int i = 0; i <= tabs.Length; i++) { - string tabName = tabs[i].Name; + 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); @@ -133,14 +146,23 @@ internal sealed class SettingsFace : IImGuiPanel float w = ImGuiNET.ImGui.GetContentRegionAvail().X; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - if (_tab >= SettingsSchema.Tabs.Length) _tab = 0; - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), Headers[_tab]); + 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++) { @@ -168,9 +190,132 @@ internal sealed class SettingsFace : IImGuiPanel 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; + case SettingKind.TraceCategories: TraceCategoriesRow(row, w); break; + case SettingKind.Text: TextRow(row, w); break; + case SettingKind.Status: StatusRow(row, w); break; } } + // [All on] [All off] [ILT Hub on], then a 3-column grid of square toggles, one per + // RynthAi trace category. Edits the copy's DiagCategories and saves like any other row. + private void TraceCategoriesRow(SettingRow row, float w) + { + var cats = TraceCategoryLevels.Parse(_data.DiagCategories); + if (cats.Count == 0) + { + Note("Waiting for RynthAi...", w); + return; + } + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + if (ImGuiNET.ImGui.Button("All on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true)); + ImGuiNET.ImGui.SameLine(0, 6); + if (ImGuiNET.ImGui.Button("All off")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", false)); + ImGuiNET.ImGui.SameLine(0, 6); + if (ImGuiNET.ImGui.Button("ILT Hub on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true, "Ilt")); + Tooltip(row); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float colW = Math.Max(80f, w / 3f); + int perRow = Math.Max(1, (int)(w / colW)); + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + for (int i = 0; i < cats.Count; i++) + { + var (name, level) = cats[i]; + bool on = level != TraceCategoryLevels.Off; + string label = TraceCategoryLevels.Label(name, level); + var p = start + new Vector2(i % perRow * colW, i / perRow * 18f); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.PushID(name); + if (ImGuiNET.ImGui.InvisibleButton("##cat", new Vector2(colW - 4, 16))) + SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, name, !on)); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + ImGuiNET.ImGui.PopID(); + dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2); + dl.PushClipRect(p, p + new Vector2(colW - 4, 16), true); + dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label); + dl.PopClipRect(); + } + int rowsUsed = (cats.Count + perRow - 1) / perRow; + ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(0, rowsUsed * 18f)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + } + + private void SaveCategories(string levels) + { + _data.DiagCategories = levels; + SettingsCommands.Save(_data.Clone()); + } + + // Label, then a full-width box; the value commits on Enter or focus loss (like the number boxes). + private void TextRow(SettingRow row, float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); + ImGuiNET.ImGui.TextUnformatted(row.Label); + ImGuiNET.ImGui.PopStyleColor(); + Tooltip(row); + + string saved = row.GetText?.Invoke(_data) ?? string.Empty; + string text = _textEdits.TryGetValue(row, out string? typing) ? typing : saved; + ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 4)); + 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.FrameRounding, 0f); + bool enter = ImGuiNET.ImGui.InputTextWithHint("##text", row.Hint ?? string.Empty, ref text, 512u, + ImGuiInputTextFlags.EnterReturnsTrue); + bool active = ImGuiNET.ImGui.IsItemActive(); + bool committed = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(3); + Tooltip(row); + _editing |= active; + + if (committed) + { + _textEdits.Remove(row); + if (!string.Equals(text, saved, StringComparison.Ordinal)) + { + row.SetText?.Invoke(_data, text); + SettingsCommands.Save(_data.Clone()); + } + } + else if (active) _textEdits[row] = text; + else _textEdits.Remove(row); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + // RynthAi's one-line status (teal), wrapped to the column. + private void StatusRow(SettingRow row, float w) + { + string text = row.GetText?.Invoke(_data) ?? string.Empty; + if (text.Length == 0) return; + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Teal); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(text); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + } + + // 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); @@ -382,6 +527,130 @@ internal sealed class SettingsFace : IImGuiPanel } } + // ── 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(); @@ -409,6 +678,8 @@ internal sealed class SettingsFace : IImGuiPanel ["Crafting"] = PhosphorIcons.Hammer, ["Looting"] = PhosphorIcons.Bag, ["Vendoring"] = PhosphorIcons.Storefront, + ["Diagnostics"] = PhosphorIcons.Wrench, + [CharmsTabName] = PhosphorIcons.Gift, }; private static readonly System.Collections.Generic.Dictionary<string, string> TabLabels = new(); 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..75dc197 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs @@ -0,0 +1,693 @@ +// ============================================================================ +// 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). +// - Attribute raiser: infinite attributes past the retail cap. RynthAi reads the +// server's costs ("/xp all") and raises with "/attr", by hand or on a timer from +// unassigned XP, in the order and mode set here. Laid out like UB's Leaftide XP +// tab: "+1 Level" / "+10 Levels" buttons labelled with their (projected) cost. +// - Augmentations: UB's Augs tab - Refresh current (/aug), Current / Target / Inc / +// Luminance / Coins with a totals row, Reset targets, Copy Discord / In-Game. +// - 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.Collections.Generic; +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; + } + DrawAttrRaiser(info.Attr, w); + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + 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" + + (ProgressionTabVisible ? ", or past the cap with the Attribute raiser below." : "."), 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 static readonly string[] AttrModes = + { + "Priority - top of the order first", + "Round robin - one level each, in order", + "Cheapest next level first", + }; + + private string? _attrKeepEdit; // reserve box being typed in (null = show RynthAi's value) + private int? _attrEveryEdit; // interval box being typed in + + private void DrawAttrRaiser(AttrRaiser? a, float w) + { + Section("Attribute raiser (infinite attributes)", w); + ImGuiNET.ImGui.Indent(8); + float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24; + ImGuiNET.ImGui.PushTextWrapPos(wrap); + try + { + if (a == null) { Label("Update RynthAi to use the attribute raiser.", Mute); return; } + if (a.Off) { Label(a.Reason, Mute); return; } + + Label(a.XpHeader.Length > 0 ? a.XpHeader : a.Unassigned, Teal); + if (a.XpHeader.Length > 0 && a.Unassigned.Contains("spendable", StringComparison.Ordinal)) Label(a.Unassigned, Dim); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (a.Running) + { + if (Button("##attr_stop", "Stop", p, new Vector2(90, 24), Text, StopBg)) SendProg("attrstop"); + } + else if (Button("##attr_run", "Raise now", p, new Vector2(110, 24), Text, StartBg, border: Teal)) + SendProg("attrrun"); + if (Button("##attr_costs", "Refresh XP", new Vector2(p.X + 116, p.Y), new Vector2(100, 24), Text, BtnFill, enabled: !a.Running)) + SendProg("attrcosts"); + ImGuiNET.ImGui.SetItemTooltip("Re-reads every next-level cost with /xp all."); + if (a.Updated.Length > 0) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 224, p.Y + 4)); + Label("Last updated: " + a.Updated, Dim); + } + NextLine(p, 28); + if (a.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(a.Status); + if (a.LastRun.Length > 0) Label("Last run: " + a.LastRun, Dim); + + ImGuiNET.ImGui.Separator(); + bool auto = a.Auto; + if (ImGuiNET.ImGui.Checkbox("Auto-raise from unassigned XP##attr_auto", ref auto)) + SendProg("attrauto " + (auto ? "on" : "off")); + ImGuiNET.ImGui.SameLine(); + // Commit on Enter, the +/- buttons or focus loss (not on every keystroke: each send + // restarts the auto-raise timer). + int every = _attrEveryEdit ?? a.Every; + ImGuiNET.ImGui.SetNextItemWidth(90); + bool everyCommit = ImGuiNET.ImGui.InputInt("every (min)##attr_every", ref every, 1, 10, ImGuiInputTextFlags.EnterReturnsTrue); + bool everyActive = ImGuiNET.ImGui.IsItemActive(); + if (everyCommit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _attrEveryEdit = null; + if (every != a.Every) SendProg("attrevery " + Math.Clamp(every, 1, 1440).ToString(CultureInfo.InvariantCulture)); + } + else _attrEveryEdit = everyActive ? every : null; + if (a.Auto && a.Next.Length > 0) Label($"Next auto-raise: {a.Next}", Dim); + + int mode = Math.Clamp(a.Mode, 0, AttrModes.Length - 1); + ImGuiNET.ImGui.SetNextItemWidth(260); + if (ImGuiNET.ImGui.Combo("Raise order##attr_mode", ref mode, AttrModes, AttrModes.Length)) + SendProg("attrmode " + mode.ToString(CultureInfo.InvariantCulture)); + + // The box holds the exact reserve (KeepFull); it is sent only when the text changed, so an + // Enter on an untouched box can't round the reserve. + string shownKeep = a.KeepFull.Length > 0 ? a.KeepFull : a.Keep; + string keep = _attrKeepEdit ?? shownKeep; + ImGuiNET.ImGui.SetNextItemWidth(140); + bool enter = ImGuiNET.ImGui.InputTextWithHint("Keep in reserve (XP)##attr_keep", "0, 500m, 2b", ref keep, 32u, + ImGuiInputTextFlags.EnterReturnsTrue); + bool keepActive = ImGuiNET.ImGui.IsItemActive(); + if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _attrKeepEdit = null; + if (!string.Equals(keep.Trim(), shownKeep, StringComparison.Ordinal)) + SendProg("attrkeep " + keep.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal)); + } + else _attrKeepEdit = keepActive ? keep : null; + ImGuiNET.ImGui.SetItemTooltip("Unassigned XP the raiser never spends. Accepts k / m / b / t suffixes."); + + DrawAttrTable(a, w); + Label("Auto: the stats Raise now / auto-raise may spend on; arrows set the order. " + + "+1 / +10 raise by hand (red = not enough unassigned XP). " + + "+10 is an estimate (7.7% dearer per level); the server charges the real cost. " + a.CostsAge + ".", Dim); + } + finally + { + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.Unindent(8); + } + } + + /// <summary> + /// UB Leaftide XP tab layout: Auto tick, stat, base, then "+1 Level" / "+10 Levels" buttons + /// labelled with what they cost, then the priority arrows. + /// </summary> + private void DrawAttrTable(AttrRaiser a, float w) + { + if (!ImGuiNET.ImGui.BeginTable("##prog_attr", 6, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp, + new Vector2(w - 16, 0))) + return; + ImGuiNET.ImGui.TableSetupColumn("Auto", ImGuiTableColumnFlags.WidthFixed, 34); + ImGuiNET.ImGui.TableSetupColumn("Stat"); + ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 56); + ImGuiNET.ImGui.TableSetupColumn("+1 Level", ImGuiTableColumnFlags.WidthFixed, 84); + ImGuiNET.ImGui.TableSetupColumn("+10 Levels", ImGuiTableColumnFlags.WidthFixed, 84); + ImGuiNET.ImGui.TableSetupColumn("Order", ImGuiTableColumnFlags.WidthFixed, 48); + ImGuiNET.ImGui.TableHeadersRow(); + for (int i = 0; i < a.Rows.Length; i++) + { + AttrRow r = a.Rows[i]; + ImGuiNET.ImGui.PushID("attr_" + r.Key); + ImGuiNET.ImGui.TableNextRow(); + + ImGuiNET.ImGui.TableNextColumn(); + bool on = r.On; + if (ImGuiNET.ImGui.Checkbox("##on", ref on)) SendProg($"attron {r.Key} {(on ? "on" : "off")}"); + + ImGuiNET.ImGui.TableNextColumn(); + Label($"{i + 1}. {r.Label}", r.On ? Text : Mute); + + ImGuiNET.ImGui.TableNextColumn(); + int clientBase = ClientBase(r); + Label(clientBase > 0 ? clientBase.ToString("N0", CultureInfo.InvariantCulture) + : r.Base >= 0 ? r.Base.ToString("N0", CultureInfo.InvariantCulture) : "-", Text); + + // Older RynthAi sends no cost10 / afford1: plain buttons, the server decides. + bool rich = r.Cost10.Length > 0; + ImGuiNET.ImGui.TableNextColumn(); + RaiseButton(a, r, 1, rich ? r.Cost : "+1", rich ? r.Afford1 : true, r.CostFull, rich); + ImGuiNET.ImGui.TableNextColumn(); + RaiseButton(a, r, 10, rich ? r.Cost10 : "+10", rich ? r.Afford10 : true, r.Cost10Full, rich); + + ImGuiNET.ImGui.TableNextColumn(); + ImGuiNET.ImGui.BeginDisabled(i == 0); + if (ImGuiNET.ImGui.ArrowButton("##up", ImGuiDir.Up)) SendProg($"attrmove {r.Key} up"); + ImGuiNET.ImGui.EndDisabled(); + ImGuiNET.ImGui.SameLine(0, 2); + ImGuiNET.ImGui.BeginDisabled(i == a.Rows.Length - 1); + if (ImGuiNET.ImGui.ArrowButton("##down", ImGuiDir.Down)) SendProg($"attrmove {r.Key} down"); + ImGuiNET.ImGui.EndDisabled(); + ImGuiNET.ImGui.PopID(); + } + ImGuiNET.ImGui.EndTable(); + } + + /// <summary> + /// One by-hand raise button filling its cell. Unknown cost ("?") stays clickable (the server + /// checks); a known cost over the unassigned XP is red and disabled. + /// </summary> + private static void RaiseButton(AttrRaiser a, AttrRow r, int levels, string label, bool afford, string exact, bool rich) + { + bool known = rich && r.Known; + bool enabled = !a.Running && (!known || afford); + uint fg = !known ? Text : afford ? Teal : Red; + Vector2 pos = ImGuiNET.ImGui.GetCursorScreenPos(); + float width = Math.Max(40f, ImGuiNET.ImGui.GetContentRegionAvail().X); + if (Button("##raise" + levels, label, pos, new Vector2(width, 20), fg, BtnFill, enabled, border: known && afford ? Teal : 0)) + SendProg($"attrraise {r.Key} {levels}"); + string what = $"{r.Label} +{levels} level{(levels > 1 ? "s" : "")}"; + string tip = !known ? $"{what}: cost not read yet (Refresh XP)." + : levels > 1 ? $"{what}: about {exact} XP (estimate)." + : $"{what}: {exact} XP."; + if (known && !afford) tip += " Not enough unassigned XP."; + if (a.Running) tip += " Wait for the raise run to finish."; + ImGuiNET.ImGui.SetItemTooltip(tip); + } + + /// <summary>The client's own base value for a raiser row (0 when the snapshot has none).</summary> + private int ClientBase(AttrRow r) + { + List<Row> rows = r.Vital ? _vitals : _attributes; + foreach (Row row in rows) + if (row.Name.Equals(r.Label, StringComparison.OrdinalIgnoreCase)) return row.Base; + return 0; + } + + 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; } + + // UB Augs tab buttons: Refresh Current, Reset Target, Copy Discord, Copy In-Game. + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float x = p.X; + if (Button("##aug_refresh", "Refresh current", new Vector2(x, p.Y), new Vector2(120, 22), Text, StartBg, border: Teal)) + SendProg("augload"); + ImGuiNET.ImGui.SetItemTooltip("Reads your augmentation levels with /aug (also done once when this tab first opens)."); + x += 124; + if (Button("##aug_reset", "Reset targets", new Vector2(x, p.Y), new Vector2(104, 22), Text, BtnFill)) + SendProg("augreset"); + ImGuiNET.ImGui.SetItemTooltip("Sets every target back to the current level."); + x += 108; + if (Button("##aug_discord", "Copy Discord", new Vector2(x, p.Y), new Vector2(100, 22), Text, BtnFill, enabled: a.CopyDiscord.Length > 0)) + ImGuiNET.ImGui.SetClipboardText(a.CopyDiscord); + ImGuiNET.ImGui.SetItemTooltip("Copies the plan as a Discord code-block table."); + x += 104; + if (Button("##aug_ingame", "Copy in-game", new Vector2(x, p.Y), new Vector2(100, 22), Text, BtnFill, enabled: a.CopyIngame.Length > 0)) + ImGuiNET.ImGui.SetClipboardText(a.CopyIngame); + ImGuiNET.ImGui.SetItemTooltip("Copies your current levels as one chat line."); + NextLine(p, 26); + Label("Status: " + a.Status, Dim); + + if (ImGuiNET.ImGui.BeginTable("##prog_augs", 6, 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, 124); + ImGuiNET.ImGui.TableSetupColumn("Inc", ImGuiTableColumnFlags.WidthFixed, 44); + ImGuiNET.ImGui.TableSetupColumn("Luminance", ImGuiTableColumnFlags.WidthFixed, 76); + ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 56); + 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("N0", CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.TableNextColumn(); + DrawAugTarget(row); + int inc = row.Increase > 0 ? row.Increase : Math.Max(0, row.Target - row.Current); + ImGuiNET.ImGui.TableNextColumn(); Label(inc > 0 ? inc.ToString("N0", CultureInfo.InvariantCulture) : "-", inc > 0 ? Teal : Dim); + ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Lum); + ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Coins > 0 ? row.Coins.ToString("N0", CultureInfo.InvariantCulture) : "-"); + } + if (a.TotalLum.Length > 0) + { + ImGuiNET.ImGui.TableNextRow(); + ImGuiNET.ImGui.TableNextColumn(); Label("TOTALS", Amber); + ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalCurrent.ToString("N0", CultureInfo.InvariantCulture), Amber); + ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalTarget.ToString("N0", CultureInfo.InvariantCulture), Amber); + ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalIncrease.ToString("N0", CultureInfo.InvariantCulture), Amber); + ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalLum, Amber); + ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalCoins.ToString("N0", CultureInfo.InvariantCulture), Amber); + } + ImGuiNET.ImGui.EndTable(); + } + + // Lum per coin commits on Enter / focus loss, not per keystroke. + string shownLpc = a.LumPerCoin.ToString(CultureInfo.InvariantCulture); + string lpc = _augLpcEdit ?? shownLpc; + ImGuiNET.ImGui.SetNextItemWidth(140); + bool lpcEnter = ImGuiNET.ImGui.InputTextWithHint("Lum per e-coin##prog_lpc", "0 = don't price coins", ref lpc, 24u, + ImGuiInputTextFlags.EnterReturnsTrue); + bool lpcActive = ImGuiNET.ImGui.IsItemActive(); + if (lpcEnter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _augLpcEdit = null; + string clean = lpc.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal); + if (!string.Equals(clean, shownLpc, StringComparison.Ordinal)) SendProg("lumpercoin " + clean); + } + else _augLpcEdit = lpcActive ? lpc : null; + ImGuiNET.ImGui.SetItemTooltip("Luminance one Enlightened Coin costs you. Accepts k / m / b / t suffixes."); + + if (a.CoinsLine.Length > 0) + { + Label(a.CoinsLine, Text); + Label(a.LumToBuy, Text); + } + else + { + Label(a.Total, Amber); + if (a.Short.Length > 0) Label(a.Short, Text); + } + Label(a.Banked, Dim); + if (a.Config != null) DrawAugCostSettings(a.Config, w); + } + finally + { + ImGuiNET.ImGui.Unindent(8); + } + } + + private static readonly string[] AugTierNames = { "Below S1", "From S1", "From S2", "From S3", "From S4" }; + + // Cost-settings boxes being typed in, by box id (committed on Enter / focus loss). + private readonly Dictionary<string, int> _augCfgIntEdit = new(StringComparer.Ordinal); + private readonly Dictionary<string, double> _augCfgDblEdit = new(StringComparer.Ordinal); + + /// <summary> + /// Collapsible editor for this world's aug cost rules (RynthAi saves them per world). The + /// defaults are UB's InfiniteLeaftide model; Reset puts a changed world back on them. + /// </summary> + private void DrawAugCostSettings(AugCostConfig cfg, float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + string head = $"Cost settings for {cfg.World}" + (cfg.Custom ? " (custom)" : " (InfiniteLeaftide defaults)"); + if (!ImGuiNET.ImGui.CollapsingHeader(head + "##aug_cfg")) return; + + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w - 24); + Label("Level i costs (Base + (i - 1) x Base x Growth% / 100) x the multiplier of its tier. " + + "A tier starts at its S level (UB's InfiniteLeaftide model). Changes apply to this world only.", Dim); + ImGuiNET.ImGui.PopTextWrapPos(); + + // Tier multipliers, one box each. + Label("Tier multipliers", Text); + for (int t = 0; t < AugTierNames.Length && t < cfg.Multipliers.Length; t++) + { + if (t > 0) ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.BeginGroup(); + Label(AugTierNames[t], Mute); + ImGuiNET.ImGui.SetNextItemWidth(62); + CfgDouble($"mult{t}", cfg.Multipliers[t], v => $"augmult {t} {v.ToString("R", CultureInfo.InvariantCulture)}"); + ImGuiNET.ImGui.EndGroup(); + } + + // Per-aug rules. + if (ImGuiNET.ImGui.BeginTable("##aug_cfg_rows", 9, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp, + new Vector2(w - 16, 0))) + { + ImGuiNET.ImGui.TableSetupColumn("Aug"); + ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 74); + ImGuiNET.ImGui.TableSetupColumn("Growth%", ImGuiTableColumnFlags.WidthFixed, 54); + ImGuiNET.ImGui.TableSetupColumn("S1", ImGuiTableColumnFlags.WidthFixed, 46); + ImGuiNET.ImGui.TableSetupColumn("S2", ImGuiTableColumnFlags.WidthFixed, 46); + ImGuiNET.ImGui.TableSetupColumn("S3", ImGuiTableColumnFlags.WidthFixed, 46); + ImGuiNET.ImGui.TableSetupColumn("S4", ImGuiTableColumnFlags.WidthFixed, 46); + ImGuiNET.ImGui.TableSetupColumn("Cap", ImGuiTableColumnFlags.WidthFixed, 50); + ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 42); + ImGuiNET.ImGui.TableHeadersRow(); + foreach (AugCostRule r in cfg.Rows) + { + ImGuiNET.ImGui.TableNextRow(); + ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Label); + ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.base", (int)Math.Min(r.Base, int.MaxValue), $"augcfg {r.Key} base"); + ImGuiNET.ImGui.TableNextColumn(); CfgDouble($"{r.Key}.pct", r.Percent, v => $"augcfg {r.Key} pct {v.ToString("R", CultureInfo.InvariantCulture)}"); + ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s1", r.S1, $"augcfg {r.Key} s1"); + ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s2", r.S2, $"augcfg {r.Key} s2"); + ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s3", r.S3, $"augcfg {r.Key} s3"); + ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s4", r.S4, $"augcfg {r.Key} s4"); + ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.cap", r.Cap, $"augcfg {r.Key} cap"); + ImGuiNET.ImGui.SetItemTooltip("Highest target level; 0 = no limit."); + ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.coins", r.Coins, $"augcfg {r.Key} coins"); + ImGuiNET.ImGui.SetItemTooltip("Enlightened Coins per level."); + } + ImGuiNET.ImGui.EndTable(); + } + + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (Button("##aug_cfg_reset", "Reset to InfiniteLeaftide defaults", p, new Vector2(230, 22), Text, BtnFill, enabled: cfg.Custom)) + SendProg("augcfgreset"); + ImGuiNET.ImGui.SetItemTooltip("Drops this world's changes; it goes back to UB's InfiniteLeaftide rules."); + NextLine(p, 26); + } + + /// <summary>Integer box that sends "<paramref name="verb"/> value" on Enter or focus loss.</summary> + private void CfgInt(string id, int value, string verb) + { + int v = _augCfgIntEdit.TryGetValue(id, out int typing) ? typing : value; + ImGuiNET.ImGui.SetNextItemWidth(-1); + bool enter = ImGuiNET.ImGui.InputInt("##cfg_" + id, ref v, 0, 0, ImGuiInputTextFlags.EnterReturnsTrue); + bool active = ImGuiNET.ImGui.IsItemActive(); + if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _augCfgIntEdit.Remove(id); + if (v != value) SendProg($"{verb} {Math.Max(0, v).ToString(CultureInfo.InvariantCulture)}"); + } + else if (active) _augCfgIntEdit[id] = v; + else _augCfgIntEdit.Remove(id); + } + + /// <summary>Decimal box (the caller sets its width) that sends <paramref name="command"/>(value) on Enter or focus loss.</summary> + private void CfgDouble(string id, double value, Func<double, string> command) + { + double v = _augCfgDblEdit.TryGetValue(id, out double typing) ? typing : value; + if (!id.StartsWith("mult", StringComparison.Ordinal)) ImGuiNET.ImGui.SetNextItemWidth(-1); + bool enter = ImGuiNET.ImGui.InputDouble("##cfg_" + id, ref v, 0, 0, "%.6g", ImGuiInputTextFlags.EnterReturnsTrue); + bool active = ImGuiNET.ImGui.IsItemActive(); + if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _augCfgDblEdit.Remove(id); + if (Math.Abs(v - value) > 1e-9 && double.IsFinite(v)) SendProg(command(Math.Max(0, v))); + } + else if (active) _augCfgDblEdit[id] = v; + else _augCfgDblEdit.Remove(id); + } + + private string? _augLpcEdit; // Lum per coin box being typed in + private readonly Dictionary<string, int> _augTargetEdit = new(StringComparer.Ordinal); // target boxes being typed in + + /// <summary> + /// Target cell: -/+ step one level (Ctrl: 100), typing commits on Enter or focus loss so a + /// half-typed number never reaches RynthAi. RynthAi clamps to current..cap. + /// </summary> + private void DrawAugTarget(AugRow row) + { + int tgt = _augTargetEdit.TryGetValue(row.Key, out int typing) ? typing : row.Target; + ImGuiNET.ImGui.SetNextItemWidth(-1); + bool commit = ImGuiNET.ImGui.InputInt("##prog_tgt_" + row.Key, ref tgt, 1, 100, ImGuiInputTextFlags.EnterReturnsTrue); + bool active = ImGuiNET.ImGui.IsItemActive(); + if (commit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _augTargetEdit.Remove(row.Key); + int clamped = Math.Clamp(tgt, row.Current, Math.Max(row.Cap, row.Current)); + if (clamped != row.Target) SendProg($"augtarget {row.Key} {clamped.ToString(CultureInfo.InvariantCulture)}"); + } + else if (active) _augTargetEdit[row.Key] = tgt; + else _augTargetEdit.Remove(row.Key); + ImGuiNET.ImGui.SetItemTooltip($"Target {row.Label} level (up to {row.Cap.ToString("N0", CultureInfo.InvariantCulture)})."); + } + + 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 index d4b55a0..beb9412 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs @@ -45,7 +45,7 @@ using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; namespace RynthCore.Engine.ImGuiBackend.Panels; -internal sealed class SkillsFace : IImGuiPanel +internal sealed partial class SkillsFace : IImGuiPanel { public const string Title = "Skills"; @@ -127,7 +127,7 @@ internal sealed class SkillsFace : IImGuiPanel } // ── State ─────────────────────────────────────────────────────────── - private int _tab; // 0 skills, 1 attributes & vitals + 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 }; @@ -193,18 +193,23 @@ internal sealed class SkillsFace : IImGuiPanel 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); - DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute"); + if (_tab != 2) DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute"); float bodyH = Math.Max(60, Remaining(origin, size) - GripOverlap()); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); @@ -212,7 +217,9 @@ internal sealed class SkillsFace : IImGuiPanel ImGuiNET.ImGui.BeginChild("##skills_body", new Vector2(w, bodyH)); float bw = ImGuiNET.ImGui.GetContentRegionAvail().X; EnsureWidths(); - if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead) + 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); @@ -228,6 +235,7 @@ internal sealed class SkillsFace : IImGuiPanel _picker.Draw(); DrawMulti(); DrawConfirm(); + DrawProgressionConfirm(); } // ── Data ──────────────────────────────────────────────────────────── @@ -691,13 +699,18 @@ internal sealed class SkillsFace : IImGuiPanel private void DrawTabs(float w) { Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - float half = (w - 4) * 0.5f; - if (Button("##tab_skills", "Skills", p, new Vector2(half, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill, + // 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 + half + 4, p.Y), new Vector2(half, 22), + 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); } diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs index 77193b7..23882a9 100644 --- a/src/RynthCore.Engine/ImGui/Win32Backend.cs +++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs @@ -84,13 +84,9 @@ internal static unsafe class Win32Backend /// HWNDs drop WM_LBUTTONDOWN on Win11 in some focus states).</summary> public const uint WM_RYNTH_RUN_ACTION = 0x8002; - /// <summary>UI deep-dive finding P0-1 belt-and-braces (2026-07-02): - /// posted (not sent) by LayeredWindow.Dispose to destroy an HWND on the - /// game thread without blocking the calling thread — DestroyWindow must - /// run on the owning thread, but the caller (often the Avalonia UI - /// thread, e.g. redocking a panel) doesn't need to wait for it to - /// finish. wParam carries the HWND to destroy.</summary> - public const uint WM_RYNTH_DESTROY_HWND = 0x8003; + // 0x8003 was WM_RYNTH_DESTROY_HWND (destroy a panel via the game window). + // 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). /// wParam != 0 includes this engine load's own panels (sent synchronously by @@ -396,36 +392,12 @@ internal static unsafe class Win32Backend } /// <summary> - /// UI deep-dive finding P0-1 (2026-07-02): posts (does not block on) a - /// DestroyWindow for <paramref name="hwnd"/> onto the game thread. - /// DestroyWindow must run on the HWND's owning thread, but unlike - /// RunOnGameThread this never needs the caller to observe a result — so - /// it uses a dedicated PostMessage instead of the shared - /// RunOnGameThread action slot, avoiding any risk of blocking the - /// caller (e.g. LayeredWindow.Dispose called from the Avalonia UI - /// thread while redocking a panel) on the game thread's WndProc. + /// True once the game window is known AND its WndProc is subclassed, i.e. + /// <see cref="RunOnGameThread{T}"/> can actually deliver work to AC's main + /// thread. Knowing the HWND alone is not enough: without the subclass, + /// WM_RYNTH_RUN_ACTION reaches AC's own WndProc, which ignores it. /// </summary> - public static void PostDestroyWindow(IntPtr hwnd) - { - if (hwnd == IntPtr.Zero) return; - if (_gameHwnd == IntPtr.Zero) - { - // No game thread to marshal to (e.g. very early/late in - // lifecycle) — best-effort inline as LayeredWindow.Dispose's own - // fallback already does for the RunOnGameThread-unavailable case. - DestroyWindow(hwnd); - return; - } - - GetWindowThreadProcessId(_gameHwnd, out uint gameThreadId); - if (gameThreadId == GetCurrentThreadId()) - { - DestroyWindow(hwnd); - return; - } - - PostMessage(_gameHwnd, WM_RYNTH_DESTROY_HWND, hwnd, IntPtr.Zero); - } + public static bool CanRunOnGameThread => _initialized && _gameHwnd != IntPtr.Zero; /// <summary>Deactivates chat capture. The game HWND retains focus throughout so no /// Win32 focus transfer is needed.</summary> @@ -597,10 +569,11 @@ internal static unsafe class Win32Backend if (!_initialized) return; // Destroy floating panels while our hook can still run on the game - // thread. LayeredWindow.Dispose only POSTS its destroy, and the game - // thread usually hasn't reached that post by the time we unhook below — - // AC's own WndProc then drops it and the panel outlives this engine - // load, frozen and unclickable (duplicate RynthAi dashboard after RL). + // thread. LayeredWindow.Dispose posts its destroy to the panel itself + // (handled by the panel's own WndProc, which survives this unhook), but + // any panel never disposed would outlive this engine load, frozen and + // unclickable (duplicate RynthAi dashboard after RL) — this sweep is the + // synchronous backstop for those. IntPtr swept = SendMessageTimeout(_gameHwnd, WM_RYNTH_SWEEP_PANELS, new IntPtr(1), IntPtr.Zero, SMTO_NORMAL, 2000, out _); if (swept == IntPtr.Zero) @@ -797,24 +770,6 @@ internal static unsafe class Win32Backend return IntPtr.Zero; } - if (msg == WM_RYNTH_DESTROY_HWND) - { - IntPtr target = wParam; - try - { - bool destroyed = DestroyWindow(target); - int err = destroyed ? 0 : Marshal.GetLastWin32Error(); - RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND DestroyWindow(0x{target.ToInt64():X}) = {destroyed} err={err}."); - // 5 = ACCESS_DENIED: the window belongs to another thread. At least - // take it off the screen so a closed panel can't linger beside a - // reopened one (ShowWindow works across threads). - if (!destroyed && err == 5) - ShowWindow(target, 0 /* SW_HIDE */); - } - catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND threw {ex.GetType().Name}: {ex.Message}"); } - return IntPtr.Zero; - } - if (msg == WM_RYNTH_SWEEP_PANELS) { try { UI.LayeredWindow.DestroyThreadPanelWindows(includeThisGeneration: wParam != IntPtr.Zero); } @@ -1025,11 +980,15 @@ internal static unsafe class Win32Backend // HUD drag (keeps our SetCapture from fighting NewFrame's). No-op // unless the HUD is drawn. 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 ──────────────── @@ -1040,7 +999,7 @@ internal static unsafe class Win32Backend { // fall through: AC gets the message } - else if (IsMouseMessage(msg)) + else if (IsMouseMessage(msg) && !ImGuiOwnsMouseOverAvalonia()) { bool handled = TryForwardToAvalonia(msg, wParam, lParam); if (handled) @@ -1129,6 +1088,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); } @@ -1139,6 +1106,17 @@ internal static unsafe class Win32Backend } } + /// <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 + /// instead of the Avalonia panel underneath. An Avalonia drag/resize that is already + /// in progress keeps its capture so the release is never lost. + /// </summary> + private static bool ImGuiOwnsMouseOverAvalonia() + { + 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). diff --git a/src/RynthCore.Engine/LogPaths.cs b/src/RynthCore.Engine/LogPaths.cs index 8cc3008..91095fb 100644 --- a/src/RynthCore.Engine/LogPaths.cs +++ b/src/RynthCore.Engine/LogPaths.cs @@ -21,13 +21,15 @@ using System; using System.IO; +using RynthCore.Install; namespace RynthCore.Engine; internal static class LogPaths { /// <summary>Unified log directory for all RynthCore components.</summary> - internal const string LogDirectory = @"C:\Games\RynthCore\Logs"; + // Installer-chosen RynthCore folder (registry Software\Rynth\CoreDir; falls back to C:\Games\RynthCore). + internal static readonly string LogDirectory = RynthInstallPaths.CoreLogsDir; /// <summary>Shared launch/orchestration log (injector + launcher + per-engine session pointer).</summary> internal const string SharedLogFileName = "RynthCore.log"; diff --git a/src/RynthCore.Engine/LogSettings.cs b/src/RynthCore.Engine/LogSettings.cs new file mode 100644 index 0000000..cda2df7 --- /dev/null +++ b/src/RynthCore.Engine/LogSettings.cs @@ -0,0 +1,245 @@ +using System; +using System.IO; +using System.Text; +using System.Text.Json; +using System.Threading; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine; + +/// <summary> +/// Engine log categories. Each one has a configurable emit level (see <see cref="LogSettings"/>). +/// Names are the keys of engine.json "LogCategories" and must stay stable. +/// </summary> +internal enum LogCategory +{ + /// <summary>Uncategorised RynthLog.Info lines.</summary> + General = 0, + /// <summary>D3D9: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary> + D3D9, + /// <summary>Compatibility hooks: client objects, combat, movement, vitals, chat, ...</summary> + Compat, + /// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary> + Render, + /// <summary>Plugin system, including every line plugins write through the host Log API.</summary> + Plugin, + /// <summary>UI / Avalonia overlay.</summary> + UI, + /// <summary>Verbose detail lines (RynthLog.Verbose / RynthLog.Debug).</summary> + Verbose, +} + +/// <summary> +/// Live engine logging configuration, read from %APPDATA%\RynthCore\engine.json: +/// <list type="bullet"> +/// <item><c>"LoggingLevel"</c> — global threshold: Off, Error, Warning, Info, Debug, Trace.</item> +/// <item><c>"LogCategories"</c> — per-category emit level: <c>{ "Compat": "Info", "Verbose": "Debug", ... }</c>. +/// The emit level is the level a category's lines are written AT, so a line shows when +/// its emit level is within the global threshold. Setting a Trace/Debug category to +/// Info puts it in the normal (Info) log; Off silences the category entirely.</item> +/// </list> +/// A background thread polls the file's timestamp once a second, so launcher edits apply to a +/// running client without a restart. Errors are always written, even when the level is Off. +/// </summary> +internal static class LogSettings +{ + /// <summary>engine.json property holding the per-category levels.</summary> + internal const string CategoriesProperty = "LogCategories"; + + private const int PollIntervalMs = 1000; + + // Default emit level per LogCategory (index = enum value): categories at Info, + // Render off, verbose lines at Debug. + private static readonly EntryPoint.EngineLogLevel[] Defaults = + { + EntryPoint.EngineLogLevel.Info, // General + EntryPoint.EngineLogLevel.Info, // D3D9 + EntryPoint.EngineLogLevel.Info, // Compat + EntryPoint.EngineLogLevel.Off, // Render + EntryPoint.EngineLogLevel.Info, // Plugin + EntryPoint.EngineLogLevel.Info, // UI + EntryPoint.EngineLogLevel.Debug, // Verbose + }; + + // Replaced wholesale on reload (never mutated after publish) so hot-path readers on any + // thread can index it without a lock. + private static EntryPoint.EngineLogLevel[] _levels = (EntryPoint.EngineLogLevel[])Defaults.Clone(); + + private static readonly object WatcherLock = new(); + private static Thread? _watcherThread; + private static ManualResetEventSlim? _stopSignal; + private static DateTime _stampUtc = DateTime.MinValue; + + private static string SettingsPath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "engine.json"); + + /// <summary>Current emit level for a category (cheap; safe on hot paths).</summary> + internal static EntryPoint.EngineLogLevel LevelFor(LogCategory category) + { + EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels); + int i = (int)category; + return (uint)i < (uint)levels.Length ? levels[i] : EntryPoint.EngineLogLevel.Info; + } + + /// <summary>True when a line in this category would be written right now.</summary> + internal static bool IsEnabled(LogCategory category) => EntryPoint.ShouldLog(LevelFor(category)); + + /// <summary>3-char severity tag written into each log line.</summary> + internal static string Tag(EntryPoint.EngineLogLevel level) => level switch + { + EntryPoint.EngineLogLevel.Error => "ERR", + EntryPoint.EngineLogLevel.Warning => "WRN", + EntryPoint.EngineLogLevel.Debug => "DBG", + EntryPoint.EngineLogLevel.Trace => "TRC", + _ => "INF", + }; + + /// <summary> + /// Reads the global level and category levels from engine.json and publishes them. + /// Called once at init (before the first log line) and again by the watcher on change. + /// Missing or unreadable values fall back to their defaults. Returns a one-line summary. + /// </summary> + internal static string Reload() + { + string? globalText = null; + var levels = (EntryPoint.EngineLogLevel[])Defaults.Clone(); + + try + { + string path = SettingsPath; + if (File.Exists(path)) + { + _stampUtc = File.GetLastWriteTimeUtc(path); + // ReadAllText strips a UTF-8/UTF-16 BOM that JsonDocument would choke on. + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + JsonElement root = doc.RootElement; + + if (root.TryGetProperty("LoggingLevel", out JsonElement levelEl) && levelEl.ValueKind == JsonValueKind.String) + globalText = levelEl.GetString(); + + if (root.TryGetProperty(CategoriesProperty, out JsonElement catsEl) && catsEl.ValueKind == JsonValueKind.Object) + { + foreach (JsonProperty p in catsEl.EnumerateObject()) + { + if (p.Value.ValueKind != JsonValueKind.String) continue; + if (!Enum.TryParse(p.Name, ignoreCase: true, out LogCategory cat) || !Enum.IsDefined(cat)) continue; + if (TryParseCategoryLevel(p.Value.GetString(), out EntryPoint.EngineLogLevel lvl)) + levels[(int)cat] = lvl; + } + } + } + } + catch + { + // Half-written / corrupt file: keep defaults for this pass; the next timestamp change retries. + globalText ??= EngineSettings.LoggingLevel; + } + + EntryPoint.LoggingLevel = EntryPoint.ParseLoggingLevel(globalText); + Volatile.Write(ref _levels, levels); + EntryPoint.VerboseLogging = IsEnabled(LogCategory.Verbose); + return Describe(); + } + + /// <summary>Human-readable "level=Info D3D9=Info Compat=Info ..." summary for the log.</summary> + internal static string Describe() + { + var sb = new StringBuilder(); + sb.Append("level=").Append(EntryPoint.LoggingLevel); + EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels); + for (int i = 0; i < levels.Length; i++) + sb.Append(' ').Append((LogCategory)i).Append('=').Append(levels[i]); + 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() + { + lock (WatcherLock) + { + if (_watcherThread != null) return; + _stopSignal = new ManualResetEventSlim(false); + ManualResetEventSlim stop = _stopSignal; + _watcherThread = new Thread(() => WatchLoop(stop)) + { + IsBackground = true, + Name = "RynthCore.LogSettingsWatcher", + }; + _watcherThread.Start(); + } + } + + /// <summary> + /// Stops and joins the poll thread. Called from EngineLifecycle.Shutdown so the thread never + /// runs inside an old engine generation after a hot reload. + /// </summary> + internal static void StopWatcher() + { + Thread? thread; + lock (WatcherLock) + { + thread = _watcherThread; + _stopSignal?.Set(); + _watcherThread = null; + } + thread?.Join(2000); + } + + private static void WatchLoop(ManualResetEventSlim stop) + { + while (!stop.Wait(PollIntervalMs)) + { + try + { + string path = SettingsPath; + if (!File.Exists(path) || File.GetLastWriteTimeUtc(path) == _stampUtc) + continue; + + string summary = Reload(); + // 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 + { + // Logging configuration must never take the client down; retry next poll. + } + } + } + + /// <summary> + /// Parses a category emit level: Off, Trace, Debug (or Verbose), Info, Warning (or Warn), Error. + /// </summary> + private static bool TryParseCategoryLevel(string? text, out EntryPoint.EngineLogLevel level) + { + level = EntryPoint.EngineLogLevel.Info; + if (string.IsNullOrWhiteSpace(text)) return false; + string t = text.Trim(); + if (t.Equals("Verbose", StringComparison.OrdinalIgnoreCase)) { level = EntryPoint.EngineLogLevel.Debug; return true; } + if (t.Equals("Warn", StringComparison.OrdinalIgnoreCase)) { level = EntryPoint.EngineLogLevel.Warning; return true; } + return Enum.TryParse(t, ignoreCase: true, out level) && Enum.IsDefined(level); + } +} diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index a9b1a31..8e91496 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -21,13 +21,17 @@ internal static class EngineSettings private static bool _enableImGuiShell = true; private static bool _enablePlugins = true; private static bool _enableDatShareHook = true; + // Read-only: Save() leaves it to CopyUnownedFields, so a hand-set false survives launcher saves. + private static bool _enableLargeAddressAlignmentFix = true; private static bool _enableAvaloniaOverlay = true; private static bool _enableD3D9Hook = true; private static bool _enableEngine = true; private static int _engineHookCount = int.MaxValue; private static bool _enableImGuiBackend = true; + private static bool _enablePluginOverlayWindows = true; private static bool _enableHangMinidump = 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; @@ -80,6 +84,19 @@ internal static class EngineSettings } } + /// <summary>When false, LargeAddressAlignmentPatch leaves acclient's signed "pointer % 4" + /// padding code alone (stock AC behaviour, which corrupts unpacks of buffers above 2 GB). + /// Default true. Diagnostic kill-switch only: set "EnableLargeAddressAlignmentFix": false + /// in engine.json by hand.</summary> + public static bool EnableLargeAddressAlignmentFix + { + get + { + EnsureLoaded(); + return _enableLargeAddressAlignmentFix; + } + } + /// <summary>When false, AvaloniaOverlay.Start() is skipped so the Avalonia STA thread, /// the offscreen overlay window, and all OverlayHost-registered panels never instantiate. /// Eliminates the entire Avalonia/Skia surface from the process. Compatibility hooks and @@ -178,6 +195,19 @@ internal static class EngineSettings } } + /// <summary>When true (default) and the ImGui shell is off, plugins that export + /// RynthPluginRenderOverlay draw their extra ImGui windows (RynthAi: ILT Hub, Item Info) + /// beside the Avalonia UI. engine.json "EnablePluginOverlayWindows": false hides them. + /// Needs <see cref="EnableImGuiBackend"/>.</summary> + public static bool EnablePluginOverlayWindows + { + get + { + EnsureLoaded(); + return _enablePluginOverlayWindows; + } + } + /// <summary>When true, MainThreadHangWatchdog writes a minidump to /// Logs\dumps\ the first time AC's main thread is confirmed permanently /// wedged — a targeted post-mortem to replace always-on procdump (which @@ -205,6 +235,18 @@ internal static class EngineSettings } } + /// <summary>Engine log threshold from engine.json "LoggingLevel", written by the launcher's + /// Logging level box: Error, Warning, Info (default), Debug/Verbose or Trace. Parsed by + /// EntryPoint.ParseLoggingLevel at init; unknown values fall back to Info.</summary> + public static string LoggingLevel + { + get + { + EnsureLoaded(); + return _loggingLevel; + } + } + /// <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 @@ -355,6 +397,12 @@ internal static class EngineSettings _enableDatShareHook = datEl.GetBoolean(); } + if (doc.RootElement.TryGetProperty("EnableLargeAddressAlignmentFix", out var laaEl) && + (laaEl.ValueKind == JsonValueKind.True || laaEl.ValueKind == JsonValueKind.False)) + { + _enableLargeAddressAlignmentFix = laaEl.GetBoolean(); + } + if (doc.RootElement.TryGetProperty("EnableAvaloniaOverlay", out var avEl) && (avEl.ValueKind == JsonValueKind.True || avEl.ValueKind == JsonValueKind.False)) { @@ -386,6 +434,12 @@ internal static class EngineSettings _enableImGuiBackend = ibEl.GetBoolean(); } + if (doc.RootElement.TryGetProperty("EnablePluginOverlayWindows", out var powEl) && + (powEl.ValueKind == JsonValueKind.True || powEl.ValueKind == JsonValueKind.False)) + { + _enablePluginOverlayWindows = powEl.GetBoolean(); + } + if (doc.RootElement.TryGetProperty("EnableHangMinidump", out var hmEl) && (hmEl.ValueKind == JsonValueKind.True || hmEl.ValueKind == JsonValueKind.False)) { @@ -429,6 +483,14 @@ internal static class EngineSettings _disabledUiHooks.Add(hookName.Trim()); } } + + if (doc.RootElement.TryGetProperty("LoggingLevel", out var logLevelEl) && + logLevelEl.ValueKind == JsonValueKind.String) + { + string? configuredLevel = logLevelEl.GetString(); + if (!string.IsNullOrWhiteSpace(configuredLevel)) + _loggingLevel = configuredLevel; + } } catch (Exception ex) { @@ -459,8 +521,12 @@ internal static class EngineSettings w.WriteBoolean("EnableEngine", _enableEngine); w.WriteNumber("EngineHookCount", _engineHookCount); w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend); + w.WriteBoolean("EnablePluginOverlayWindows", _enablePluginOverlayWindows); w.WriteBoolean("EnableHangMinidump", _enableHangMinidump); 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 @@ -485,6 +551,37 @@ internal static class EngineSettings RynthLog.Plugin($"EngineSettings: Failed to save: {ex.Message}"); } } + + // Fields Save() writes itself; everything else in engine.json belongs to the launcher + // (LogCategories, EnableDcompOverlay, ...) and is copied through untouched. + private static readonly string[] OwnedFields = + { + "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> + private static void CopyUnownedFields(Utf8JsonWriter w) + { + try + { + if (!File.Exists(SettingsPath)) return; + using var doc = JsonDocument.Parse(File.ReadAllText(SettingsPath)); + if (doc.RootElement.ValueKind != JsonValueKind.Object) return; + foreach (JsonProperty p in doc.RootElement.EnumerateObject()) + { + if (Array.IndexOf(OwnedFields, p.Name) >= 0) continue; + p.WriteTo(w); + } + } + catch + { + // Unreadable file: write only the owned fields (previous behaviour). + } + } } /// <summary>engine.json "DecalBridge" (see <see cref="EngineSettings.DecalBridgeMode"/>).</summary> diff --git a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs index 8d572a3..0ce3f41 100644 --- a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs +++ b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs @@ -54,6 +54,18 @@ internal sealed class LoadedPlugin public PluginOnEnchantmentRemovedDelegate? OnEnchantmentRemoved { get; set; } public PluginTickDelegate? Tick { get; set; } public PluginRenderDelegate? Render { get; set; } + /// <summary>Optional RynthPluginRenderOverlay: ImGui windows drawn while the ImGui shell is off.</summary> + public PluginRenderDelegate? RenderOverlay { get; set; } + + /// <summary>Set after the first RenderOverlay call has been logged (render thread only).</summary> + public bool RenderOverlayLogged { get; set; } + + /// <summary> + /// Optional <c>int RynthPluginRenderEmbed(const char* surface, float width, float height, + /// float* wantWidth, float* wantHeight)</c>, Cdecl: the plugin draws a named surface into the + /// engine's current ImGui window (PluginManager.RenderEmbed). Zeroed after it throws. + /// </summary> + public IntPtr RenderEmbedPtr { get; set; } // ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ─── public bool UiExportsResolved { get; set; } @@ -85,4 +97,45 @@ internal sealed class LoadedPlugin public RynthCore.PluginSdk.Manifest.RynthPluginManifest? Manifest { get; set; } /// <summary>Why the plugin was not started (a required plugin missing or failed); empty otherwise.</summary> public string NotStartedReason { get; set; } = ""; + + /// <summary> + /// Drops managed delegates wrapping exports so the native module can fully unload after + /// the host calls FreeLibrary (hot-reload / rescan). + /// </summary> + internal void ClearResolvedDelegates() + { + Init = null; + Shutdown = null; + GetName = null; + GetVersion = null; + OnLoginComplete = null; + OnUIInitialized = null; + OnBusyCountIncremented = null; + OnBusyCountDecremented = null; + OnSelectedTargetChange = null; + OnCombatModeChange = null; + OnSmartBoxEventPtr = IntPtr.Zero; + OnSmartBoxEvent = null; + OnDeleteObject = null; + OnCreateObject = null; + OnUpdateObjectPtr = IntPtr.Zero; + OnUpdateObject = null; + OnUpdateObjectInventory = null; + OnViewObjectContents = null; + OnStopViewingObjectContents = null; + OnVendorOpen = null; + OnVendorClose = null; + OnUpdateHealthPtr = IntPtr.Zero; + OnUpdateHealth = null; + OnChatWindowTextPtr = IntPtr.Zero; + OnChatWindowText = null; + OnChatBarEnter = null; + OnBarAction = null; + OnEnchantmentAdded = null; + OnEnchantmentRemoved = null; + Tick = null; + Render = null; + RenderOverlay = null; + RenderEmbedPtr = IntPtr.Zero; + } } diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index c2bdc06..9bf7aff 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -10,7 +10,18 @@ // const char* RynthPluginName() — human-readable name // const char* RynthPluginVersion() — version string (e.g. "1.0.0") // void RynthPluginTick() — per-frame logic (before render) -// void RynthPluginRender() — per-frame ImGui drawing +// void RynthPluginRender() — per-frame ImGui drawing (ImGui shell on) +// void RynthPluginRenderOverlay() — per-frame ImGui drawing while the ImGui shell is +// off (Avalonia mode): only windows that have no +// Avalonia panel. Gated by engine.json +// "EnablePluginOverlayWindows" (default true). +// int RynthPluginRenderEmbed(const char* surface, float width, float height, +// float* wantWidth, float* wantHeight) +// — draws a named surface (UTF-8, e.g. RynthAi's +// "miniremote") into the engine's current ImGui +// window on AC's render thread, inside a +// width x height child; reports the size it wants. +// 1 = drawn, 0 = not ready / unknown surface. // void RynthPluginOnServerMessage(uint opcode, byte* data, int length) // — v78, reassembled server messages the plugin // asked for with SetServerMessageInterestFn @@ -844,6 +855,15 @@ internal struct RynthCoreAPI /// must equal that price; 0 skips the comparison. Same results and threading as Raise. /// Requires API v79+.</summary> public IntPtr TrainSkillFn; + + /// <summary>v80: <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. + /// The thunk is cdecl. Any thread. Requires API v80+ (it was v77 on QOL-items before + /// upstream's v77-v79 landed; plugins built against that SDK must be rebuilt).</summary> + public IntPtr GetMergeStackResultFn; } /// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary> @@ -1634,6 +1654,10 @@ internal unsafe delegate uint VendorSellCallbackDelegate(uint vendorId, uint* it [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeStatusNative* status); +// Cdecl is mandatory on every API delegate: without it x86 marshals a stdcall thunk, the callee and +// 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); diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index 07f9bd6..0aabc31 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -15,5 +15,6 @@ namespace RynthCore.Engine.Plugins; /// <summary>Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative).</summary> internal static class PluginContractVersion { - public const uint Current = 79; + // v80: GetMergeStackResult (was v77 on QOL-items, renumbered after upstream's v77-v79). + public const uint Current = 80; } diff --git a/src/RynthCore.Engine/Plugins/PluginLoader.cs b/src/RynthCore.Engine/Plugins/PluginLoader.cs index 1b45302..b77b53e 100644 --- a/src/RynthCore.Engine/Plugins/PluginLoader.cs +++ b/src/RynthCore.Engine/Plugins/PluginLoader.cs @@ -89,6 +89,9 @@ internal static class PluginLoader /// </summary> public static void Unload(LoadedPlugin plugin) { + // 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 @@ -506,6 +509,13 @@ internal static class PluginLoader if (renderPtr != IntPtr.Zero) plugin.Render = Marshal.GetDelegateForFunctionPointer<PluginRenderDelegate>(renderPtr); + IntPtr renderOverlayPtr = GetProcAddress(handle, "RynthPluginRenderOverlay"); + if (renderOverlayPtr != IntPtr.Zero) + plugin.RenderOverlay = Marshal.GetDelegateForFunctionPointer<PluginRenderDelegate>(renderOverlayPtr); + + // Called through a function pointer (PluginManager.RenderEmbed), so no delegate here. + plugin.RenderEmbedPtr = GetProcAddress(handle, "RynthPluginRenderEmbed"); + // Read name/version from the plugin if available if (plugin.GetName != null) { diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 95775ba..f7a2697 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -269,6 +269,7 @@ internal static partial class PluginManager private static VendorBuyCallbackDelegate? _vendorBuyCallback; private static VendorSellCallbackDelegate? _vendorSellCallback; private static GetVendorTradeStatusCallbackDelegate? _getVendorTradeStatusCallback; + private static GetMergeStackResultCallbackDelegate? _getMergeStackResultCallback; private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback; private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback; private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback; @@ -1138,6 +1139,154 @@ internal static partial class PluginManager } } + /// <summary> + /// ImGui-shell-off counterpart of <see cref="RenderAll"/>: calls the optional + /// RynthPluginRenderOverlay export, where a plugin draws only the extra windows that have + /// no Avalonia panel (e.g. RynthAi's ILT Hub). They float beside the Avalonia UI and add to it. + /// A throw switches off just that plugin's overlay windows; the plugin is NOT marked Failed, + /// so its tick/automation and Avalonia panels keep running. + /// </summary> + public static void RenderOverlayAll() + { + _overlayCalls++; + if (!_loginCompleteObserved) + { + if (!_loggedOverlayWaitingForLogin) + { + _loggedOverlayWaitingForLogin = true; + RynthLog.Info("PluginManager: RenderOverlayAll called - waiting for login before drawing overlay windows."); + } + return; // same not-in-world crash zone guard as RenderAll + } + + LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot); + + // Count plugins that will actually be called; log whenever that set changes. + int bound = 0; + for (int i = 0; i < plugins.Length; i++) + { + var p = plugins[i]; + if (p.Initialized && !p.Failed && p.RenderOverlay != null) bound++; + } + _overlayBound = bound; + if (bound != _loggedOverlayBound || plugins.Length != _loggedOverlayTotal) + { + _loggedOverlayBound = bound; + _loggedOverlayTotal = plugins.Length; + var sb = new System.Text.StringBuilder(); + for (int i = 0; i < plugins.Length; i++) + { + var p = plugins[i]; + if (sb.Length > 0) sb.Append(", "); + sb.Append(p.DisplayName).Append('(') + .Append(p.RenderOverlay != null ? "overlay" : "no-overlay") + .Append(p.Initialized ? "" : ",not-init") + .Append(p.Failed ? ",failed" : "") + .Append(')'); + } + RynthLog.Info($"PluginManager: RenderOverlayAll login seen, {bound} of {plugins.Length} plugin(s) will draw overlay windows: {sb}."); + } + + for (int i = 0; i < plugins.Length; i++) + { + var plugin = plugins[i]; + var overlay = plugin.RenderOverlay; + if (!plugin.Initialized || plugin.Failed || overlay == null) + continue; + + if (!plugin.RenderOverlayLogged) + { + // One line per plugin per session: proves the engine is actually driving the overlay export. + plugin.RenderOverlayLogged = true; + RynthLog.Plugin($"PluginManager: first RenderOverlay call for {plugin.DisplayName}."); + } + + try + { + overlay(); + } + catch (Exception ex) + { + plugin.RenderOverlay = null; + RynthLog.Error($"PluginManager: {plugin.DisplayName} RenderOverlay threw {ex.GetType().Name}: {ex.Message} - overlay windows off for this session (plugin keeps running)."); + } + } + } + + // RenderOverlayAll diagnostics (render thread only). + private static long _overlayCalls; + private static int _overlayBound; + private static bool _loggedOverlayWaitingForLogin; + 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}"; + + /// <summary>RenderEmbed results.</summary> + internal const int EmbedDrawn = 1, EmbedNotReady = 0, EmbedNoPlugin = -1, EmbedFailed = -2; + + /// <summary> + /// Lets the plugin named <paramref name="pluginName"/> (display name contains it) draw the + /// surface <paramref name="surfaceUtf8"/> (NUL-terminated) into the current ImGui window, + /// through its optional RynthPluginRenderEmbed export. The caller has begun a child of + /// <paramref name="size"/> in the main ImGui context; the plugin draws only inside it and + /// reports the content size it wants in <paramref name="want"/> (zero when it didn't say). + /// Render thread only. Returns <see cref="EmbedDrawn"/>, <see cref="EmbedNotReady"/> (the + /// plugin isn't ready: before login, no ImGui context), <see cref="EmbedNoPlugin"/> (not + /// loaded, or too old to have the export) or <see cref="EmbedFailed"/> (it threw: the export + /// is switched off for this session; the plugin keeps running). + /// </summary> + internal static unsafe int RenderEmbed(string pluginName, ReadOnlySpan<byte> surfaceUtf8, System.Numerics.Vector2 size, out System.Numerics.Vector2 want) + { + want = System.Numerics.Vector2.Zero; + if (!_loginCompleteObserved) return EmbedNotReady; // same not-in-world guard as RenderAll + LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot); + for (int i = 0; i < plugins.Length; i++) + { + LoadedPlugin p = plugins[i]; + if (!p.Initialized || p.Failed || !p.DisplayName.Contains(pluginName, StringComparison.OrdinalIgnoreCase)) + continue; + IntPtr fn = p.RenderEmbedPtr; + if (fn == IntPtr.Zero) return EmbedNoPlugin; + float w = 0, h = 0; + try + { + int r; + fixed (byte* s = surfaceUtf8) + r = ((delegate* unmanaged[Cdecl]<byte*, float, float, float*, float*, int>)fn)(s, size.X, size.Y, &w, &h); + want = new System.Numerics.Vector2(float.IsFinite(w) ? MathF.Max(0, w) : 0, float.IsFinite(h) ? MathF.Max(0, h) : 0); + return r == 1 ? EmbedDrawn : EmbedNotReady; + } + catch (Exception ex) + { + p.RenderEmbedPtr = IntPtr.Zero; + RynthLog.Error($"PluginManager: {p.DisplayName} RenderEmbed threw {ex.GetType().Name}: {ex.Message} - embedded surfaces off for this session (plugin keeps running)."); + return EmbedFailed; + } + } + return EmbedNoPlugin; + } + public static void ShutdownAll() { RynthLog.Plugin($"PluginManager: Shutting down {_plugins.Count} plugin(s)..."); @@ -2333,6 +2482,14 @@ internal static partial class PluginManager // %APPDATA%\RynthCore\engine.json. The engine never auto-scans a // bundled Plugins\ folder — that historically caused stray DLLs to // load on next start (or after hot-reload) without the user knowing. + // + // Track DLL file names and canonical paths already staged this generation. engine.json can + // list the same plugin twice (e.g. a stale copy in another folder); a second File.Copy to the + // same shadow file name fails while the first copy is still mapped ("used by another process") + // and breaks hot-reload ordering for later DLLs. + var loadedBasenames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + var loadedCanonicalPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + var extraPaths = EngineSettings.PluginPaths; var candidates = new List<string>(extraPaths.Count); for (int i = 0; i < extraPaths.Count; i++) @@ -2344,30 +2501,21 @@ internal static partial class PluginManager continue; } - // Skip if a plugin with the same filename was already loaded from the default directory. - // Both paths share the same session shadow dir — loading the same filename twice would - // try to overwrite a locked shadow copy and crash. - string extraFileName = Path.GetFileName(dllPath); - bool alreadyLoaded = false; - for (int j = 0; j < _plugins.Count; j++) + string baseName = Path.GetFileName(dllPath); + if (loadedBasenames.Contains(baseName)) { - if (string.Equals(Path.GetFileName(_plugins[j].SourceFilePath), extraFileName, StringComparison.OrdinalIgnoreCase)) - { - alreadyLoaded = true; - break; - } + RynthLog.Plugin($"PluginManager: Skipping extra plugin (same file name already loaded from plugins directory or earlier extra path): {dllPath}"); + continue; } - for (int j = 0; j < candidates.Count && !alreadyLoaded; j++) + + if (TryGetCanonicalPath(dllPath, out string extraCanon) && loadedCanonicalPaths.Contains(extraCanon)) { - if (string.Equals(Path.GetFileName(candidates[j]), extraFileName, StringComparison.OrdinalIgnoreCase)) - alreadyLoaded = true; - } - if (alreadyLoaded) - { - RynthLog.Plugin($"PluginManager: Extra plugin {extraFileName} already loaded from default directory — skipping."); + RynthLog.Plugin($"PluginManager: Skipping extra plugin (same resolved path already loaded): {dllPath}"); continue; } candidates.Add(dllPath); + loadedBasenames.Add(baseName); + TryAddCanonicalPath(loadedCanonicalPaths, dllPath); } // Manifests (embedded in the DLLs, read without loading them): refuse a plugin that needs @@ -2400,7 +2548,29 @@ internal static partial class PluginManager } } + // RenderAll / RenderOverlayAll iterate only this snapshot; without it they see no plugins. PublishPluginsRenderSnapshot(); + RynthLog.Plugin($"PluginManager: render snapshot published ({_plugins.Count} plugin(s))."); + } + + private static void TryAddCanonicalPath(HashSet<string> set, string path) + { + if (TryGetCanonicalPath(path, out string canon)) + set.Add(canon); + } + + private static bool TryGetCanonicalPath(string path, out string canonical) + { + try + { + canonical = Path.GetFullPath(path); + return true; + } + catch + { + canonical = string.Empty; + return false; + } } // ── Plugin manifests ───────────────────────────────────────────────── @@ -2796,6 +2966,7 @@ internal static partial class PluginManager _vendorBuyCallback ??= VendorBuyAction; _vendorSellCallback ??= VendorSellAction; _getVendorTradeStatusCallback ??= GetVendorTradeStatusAction; + _getMergeStackResultCallback ??= GetMergeStackResultAction; _api.Version = PluginContractVersion.Current; _api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback); @@ -2939,6 +3110,7 @@ internal static partial class PluginManager _api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback); _api.VendorSellFn = Marshal.GetFunctionPointerForDelegate(_vendorSellCallback); _api.GetVendorTradeStatusFn = Marshal.GetFunctionPointerForDelegate(_getVendorTradeStatusCallback); + _api.GetMergeStackResultFn = Marshal.GetFunctionPointerForDelegate(_getMergeStackResultCallback); RouteApiThroughLoader(); } @@ -3656,6 +3828,22 @@ internal static partial class PluginManager return ToAbiBool(ClientHelperHooks.MergeStackInternal(sourceObjectId, targetObjectId)); } + // v68: outcome of the latest MergeStackInternal(source, target) (MergeStackResults codes). + private static unsafe int GetMergeStackResultAction(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs) + { + try + { + int status = MergeStackResults.Get(sourceObjectId, targetObjectId, out int sent, out int age); + if (amount != null) *amount = sent; + if (ageMs != null) *ageMs = age; + return status; + } + catch + { + return MergeStackResults.None; + } + } + private static int GiveObjectTo(uint objectId, uint targetId, int amount) { return ToAbiBool(ClientHelperHooks.GiveObjectTo(objectId, targetId, amount)); diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj index 3a15a25..bf8c366 100644 --- a/src/RynthCore.Engine/RynthCore.Engine.csproj +++ b/src/RynthCore.Engine/RynthCore.Engine.csproj @@ -6,6 +6,9 @@ <RuntimeIdentifier>win-x86</RuntimeIdentifier> <OutputType>Library</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <!-- Unreachable code (CS0162) is always a bug here: a misplaced statement after a return + once left the plugin render snapshot unpublished and silently disabled every overlay window. --> + <WarningsAsErrors>$(WarningsAsErrors);CS0162</WarningsAsErrors> <Nullable>enable</Nullable> <PublishAot>true</PublishAot> <NativeLib>Shared</NativeLib> @@ -66,6 +69,8 @@ <PackageReference Include="Avalonia.Desktop" Version="11.2.3" /> <PackageReference Include="Avalonia.Skia" Version="11.2.3" /> <PackageReference Include="Avalonia.Themes.Simple" Version="11.2.3" /> + <!-- Overrides Avalonia.FreeDesktop transitive Tmds.DBus.Protocol (NU1903 / GHSA-xrw6-gwf8-vvr9). --> + <PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" /> <PackageReference Include="Avalonia.AvaloniaEdit" Version="11.2.0" /> </ItemGroup> @@ -159,4 +164,9 @@ SkipUnchangedFiles="true" /> </Target> + <ItemGroup> + <!-- Install-location resolver (installer-chosen RynthCore / RynthSuite folders). --> + <Compile Include="..\RynthCore.App\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" /> + </ItemGroup> + </Project> diff --git a/src/RynthCore.Engine/RynthLog.cs b/src/RynthCore.Engine/RynthLog.cs index 6fe4d4d..a6fd341 100644 --- a/src/RynthCore.Engine/RynthLog.cs +++ b/src/RynthCore.Engine/RynthLog.cs @@ -4,73 +4,67 @@ namespace RynthCore.Engine; /// <summary> /// Centralised logging — every log call in the Engine routes through here. -/// Toggle categories on/off at runtime to suppress entire subsystems. -/// Messages keep their existing prefix text (e.g. "D3D9VTable: scanning…"). +/// Each category method writes at that category's emit level (engine.json "LogCategories", +/// editable live from the launcher; see <see cref="LogSettings"/>), gated by the global +/// "LoggingLevel". Messages keep their existing prefix text (e.g. "D3D9VTable: scanning…"). /// </summary> internal static class RynthLog { - // ── Category toggles (flip to false to silence a subsystem) ────────── - - internal static bool D3D9Enabled = true; - internal static bool CompatEnabled = true; - internal static bool RenderEnabled = false; // ImGui, DX9Backend, Win32Backend - internal static bool PluginEnabled = true; - internal static bool UIEnabled = true; - // ── Category methods ───────────────────────────────────────────────── /// <summary>D3D9 subsystem: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary> - internal static void D3D9(string msg) - { - if (D3D9Enabled) Write(msg); - } + internal static void D3D9(string msg) => WriteCategory(LogCategory.D3D9, msg); /// <summary>Compatibility hooks: SmartBox, client objects, combat, movement, vitals, chat, etc.</summary> - internal static void Compat(string msg) - { - if (CompatEnabled) Write(msg); - } + internal static void Compat(string msg) => WriteCategory(LogCategory.Compat, msg); /// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary> - internal static void Render(string msg) - { - if (RenderEnabled) Write(msg); - } + internal static void Render(string msg) => WriteCategory(LogCategory.Render, msg); - /// <summary>Plugin system: loader, manager, lifecycle callbacks.</summary> - internal static void Plugin(string msg) - { - if (PluginEnabled) Write(msg); - } + /// <summary>Plugin system: loader, manager, lifecycle callbacks, plugin host Log lines.</summary> + internal static void Plugin(string msg) => WriteCategory(LogCategory.Plugin, msg); /// <summary>UI / Avalonia overlay subsystem.</summary> - internal static void UI(string msg) - { - if (UIEnabled) Write(msg); - } + internal static void UI(string msg) => WriteCategory(LogCategory.UI, msg); - /// <summary>Verbose-only log (any category). Only written when VerboseLogging is on.</summary> - internal static void Verbose(string msg) - { - if (EntryPoint.VerboseLogging) Write(msg); - } + /// <summary>Verbose detail (any subsystem). Debug by default; set the Verbose category to Info to see it in the normal log.</summary> + internal static void Verbose(string msg) => WriteCategory(LogCategory.Verbose, msg); - /// <summary>Always-on log for critical / uncategorised messages (INFO).</summary> - internal static void Info(string msg) => Write(msg); + /// <summary>Same as <see cref="Verbose"/>.</summary> + internal static void Debug(string msg) => WriteCategory(LogCategory.Verbose, msg); + + /// <summary>Trace-level line: written only when the global level is Trace.</summary> + internal static void Trace(string msg) => WriteAt(EntryPoint.EngineLogLevel.Trace, msg); + + /// <summary>Uncategorised line (General category, Info by default).</summary> + internal static void Info(string msg) => WriteCategory(LogCategory.General, msg); + + /// <summary>Same as <see cref="Warn"/>.</summary> + internal static void Warning(string msg) => Warn(msg); // Most recent WRN/ERR text + when, surfaced via the GetEngineStatusJson host bridge so a stuck box - // can be diagnosed remotely without reading the PC log. + // can be diagnosed remotely without reading the PC log. Recorded even when the line is filtered. internal static volatile string? LastIssue; internal static DateTime LastIssueUtc; - /// <summary>Always-on WARN line — a recoverable problem worth grepping for.</summary> + /// <summary>WARN line — a recoverable problem worth grepping for. Hidden only at level Error/Off.</summary> internal static void Warn(string msg) { LastIssue = msg; LastIssueUtc = DateTime.UtcNow; - EntryPoint.LogTagged("engine", msg, "WRN"); + if (EntryPoint.ShouldLog(EntryPoint.EngineLogLevel.Warning)) + EntryPoint.LogTagged("engine", msg, "WRN"); } - /// <summary>Always-on ERROR line — a fault/crash/disable. Triage with grep "[ERR]".</summary> + /// <summary> + /// Always-on heartbeat line, written at every LoggingLevel (Off included). The launcher's + /// wedge watchdog reads RynthCore.<pid>.log going quiet for 120 s as a dead engine and + /// kills the client, so this line must never be filtered: on 2026-10-06 LoggingLevel=Info + /// with General=Trace dropped it and healthy in-world clients were killed and relaunched + /// every few minutes. + /// </summary> + internal static void Heartbeat(string msg) => EntryPoint.LogTagged("engine", msg, "INF"); + + /// <summary>Always-on ERROR line — a fault/crash/disable, written even at level Off. Triage with grep "[ERR]".</summary> internal static void Error(string msg) { LastIssue = msg; LastIssueUtc = DateTime.UtcNow; @@ -154,7 +148,24 @@ internal static class RynthLog : $"thread {Environment.CurrentManagedThreadId}"; } + /// <summary>True when a line in <paramref name="category"/> would be written (guard expensive messages).</summary> + internal static bool IsEnabled(LogCategory category) => LogSettings.IsEnabled(category); + // ── Sink ───────────────────────────────────────────────────────────── - private static void Write(string message) => EntryPoint.Log(message); + /// <summary>Uncategorised line (General category); used by the Move/UseDone traces.</summary> + private static void Write(string? message) + { + if (message != null) + WriteCategory(LogCategory.General, message); + } + + private static void WriteCategory(LogCategory category, string message) + => WriteAt(LogSettings.LevelFor(category), message); + + private static void WriteAt(EntryPoint.EngineLogLevel level, string message) + { + if (EntryPoint.ShouldLog(level)) + EntryPoint.LogTagged("engine", message, LogSettings.Tag(level)); + } } 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/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index e34b9d2..fc452d6 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -158,6 +158,19 @@ internal enum ChatRuleAction 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 @@ -173,6 +186,8 @@ internal sealed class ChatFilterRule 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> @@ -204,9 +219,16 @@ internal sealed class ChatFilterRule 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(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, + Compiled = new Regex(expr, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(TimeoutMs)); Error = null; Invalid = false; @@ -493,9 +515,12 @@ internal sealed class ChatRouter foreach (ChatFilterRule rule in _rules) Volatile.Write(ref rule.Hits, 0); } - /// <summary>One step of the editor's test: rule index (-1 = mention) and what it did.</summary> + /// <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); @@ -584,6 +609,28 @@ internal sealed class ChatRouter 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)) { @@ -874,6 +921,8 @@ internal static class ChatModel 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; @@ -944,6 +993,9 @@ internal static class ChatModel 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; @@ -960,6 +1012,9 @@ internal static class ChatModel 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(); } @@ -1102,6 +1157,7 @@ internal static class ChatModel // 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> @@ -1134,6 +1190,8 @@ internal static class ChatModel _ => ChatColorMode.None, }, ColorArgb = ParseColor(f.Color) ?? ChatFilterRule.DefaultColor, + // Absent (settings saved before match modes existed): Regex. + Mode = Enum.TryParse(f.Mode, ignoreCase: true, out ChatMatchMode mode) ? mode : ChatMatchMode.Regex, }; rule.Recompile(); return rule; @@ -1573,6 +1631,16 @@ internal static class ChatModel && !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); @@ -1624,6 +1692,11 @@ internal static class ChatModel 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", () => { @@ -1677,6 +1750,16 @@ internal sealed class RynthChatFilterDto [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 @@ -1697,6 +1780,7 @@ internal sealed class RynthChatSettingsDto [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> diff --git a/src/RynthCore.Engine/UI/Data/ItemsData.cs b/src/RynthCore.Engine/UI/Data/ItemsData.cs index 0c2ce98..26e55bf 100644 --- a/src/RynthCore.Engine/UI/Data/ItemsData.cs +++ b/src/RynthCore.Engine/UI/Data/ItemsData.cs @@ -63,11 +63,14 @@ internal sealed unsafe class ItemsSource : UiSource<ItemsSnapshot> internal static unsafe class ItemsCommands { private static delegate* unmanaged[Cdecl]<IntPtr, void> _set; - private static delegate* unmanaged[Cdecl]<void> _addWeapon, _addConsumable; + 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; _addConsumable = null; }; + PluginManager.PluginsUnloaded += () => { _set = null; _addWeapon = null; _addShield = null; _addConsumable = null; }; } public static readonly string[] Elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; @@ -94,6 +97,18 @@ internal static unsafe class ItemsCommands 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", () => { diff --git a/src/RynthCore.Engine/UI/Data/LootEditData.cs b/src/RynthCore.Engine/UI/Data/LootEditData.cs index 7148ea5..3a89213 100644 --- a/src/RynthCore.Engine/UI/Data/LootEditData.cs +++ b/src/RynthCore.Engine/UI/Data/LootEditData.cs @@ -139,6 +139,8 @@ internal sealed class LootEditItemRequestDto 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; } + /// <summary>Also require the item's T11 attributes (added 2026-10-07; an older RynthAi ignores it).</summary> + public bool IncludeT11 { get; set; } public int Seq { get; set; } } @@ -157,6 +159,10 @@ internal sealed class LootEditItemDraftDto public bool TargetInUse { get; set; } public string Format { get; set; } = string.Empty; public int Match { get; set; } + /// <summary>The rule includes the item's T11 attributes (added 2026-10-07; false from an older RynthAi).</summary> + public bool IncludeT11 { get; set; } + /// <summary>The item is T11 gear (added 2026-10-07; false from an older RynthAi).</summary> + public bool IsT11 { get; set; } public int Action { get; set; } public int KeepCount { get; set; } public string RuleName { get; set; } = string.Empty; diff --git a/src/RynthCore.Engine/UI/Data/MetaData.cs b/src/RynthCore.Engine/UI/Data/MetaData.cs index ee3c1b4..ecdfa8c 100644 --- a/src/RynthCore.Engine/UI/Data/MetaData.cs +++ b/src/RynthCore.Engine/UI/Data/MetaData.cs @@ -231,7 +231,8 @@ internal static unsafe class MetaCommands /// <summary>Names, hints and .af keywords shared by the Meta faces (mirror RynthSuite's MetaSchema).</summary> internal static class MetaVocabulary { - public const string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles"; + /// <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 = { diff --git a/src/RynthCore.Engine/UI/Data/NavData.cs b/src/RynthCore.Engine/UI/Data/NavData.cs index 8fd22c8..b6f1b8d 100644 --- a/src/RynthCore.Engine/UI/Data/NavData.cs +++ b/src/RynthCore.Engine/UI/Data/NavData.cs @@ -39,6 +39,17 @@ internal sealed class NavPayload 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>Route recording is on (points are added as you walk). Older plugins omit it.</summary> + public bool IsRecording { get; set; } + /// <summary>Breadcrumb trail size, for "Trail to route" / "Backtrack".</summary> + public int TrailPoints { get; set; } + public double TrailYards { get; set; } + /// <summary>The last route edit's result, for a few seconds after it (empty otherwise).</summary> + public string EditStatus { get; set; } = string.Empty; /// <summary>A copy a face may change (its own point list); the points themselves are shared.</summary> public NavPayload Clone() @@ -59,6 +70,12 @@ internal sealed class NavCmd 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 / setRecording + public List<int>? Indices { get; set; } // movePoints / duplicatePoints / deletePoints + public int Delta { get; set; } // movePoints: -1 up, +1 down + public double Seconds { get; set; } // addPause + public double Yards { get; set; } // simplifyRoute tolerance + public bool Reverse { get; set; } // trailToRoute: backtrack } [JsonSerializable(typeof(NavPayload))] @@ -104,6 +121,19 @@ internal static class NavCommands public static readonly string[] RouteTypes = { "Once", "Circular", "Linear", "Follow" }; public static readonly string[] AddModes = { "End", "Above", "Below" }; + public static readonly double[] PauseSeconds = { 1, 2, 3, 5, 10, 15, 30, 60 }; + public static readonly string[] PauseLabels = Array.ConvertAll(PauseSeconds, s => $"Pause {s:0} s"); + + public static readonly double[] SimplifyYards = { 0.5, 1, 2, 3, 5 }; + public static readonly string[] SimplifyLabels = + Array.ConvertAll(SimplifyYards, y => $"Drop points within {y:0.#} yd of a straight line"); + + public static readonly string[] TrailChoices = + { + "Replace route with the trail (walk it again)", + "Replace route with a backtrack (walk it back)", + }; + /// <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 }; diff --git a/src/RynthCore.Engine/UI/Data/ProgressionData.cs b/src/RynthCore.Engine/UI/Data/ProgressionData.cs new file mode 100644 index 0000000..84ef2d6 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ProgressionData.cs @@ -0,0 +1,206 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ProgressionData.cs +// RynthAi's ILT progression planners (augmentations, enlightenment) and the +// infinite-attribute raiser 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(); + /// <summary>Absent from an older RynthAi: stays empty and the section shows "update RynthAi".</summary> + [JsonPropertyName("attr")] public AttrRaiser? Attr { get; set; } +} + +/// <summary>RynthAi's IltAttributeRaiser: server costs ("/xp all") and the raise settings.</summary> +internal sealed class AttrRaiser +{ + /// <summary>The raiser can't run here; <see cref="Reason"/> says why.</summary> + [JsonPropertyName("off")] public bool Off { get; set; } + [JsonPropertyName("reason")] public string Reason { get; set; } = ""; + [JsonPropertyName("auto")] public bool Auto { get; set; } + /// <summary>Minutes between auto-raise runs.</summary> + [JsonPropertyName("every")] public int Every { get; set; } = 5; + /// <summary>0 priority, 1 round robin, 2 cheapest first.</summary> + [JsonPropertyName("mode")] public int Mode { get; set; } + [JsonPropertyName("running")] public bool Running { get; set; } + /// <summary>XP reserve, preformatted ("0", "1.50B").</summary> + [JsonPropertyName("keep")] public string Keep { get; set; } = "0"; + /// <summary>XP reserve in full ("1,234,567"): what the reserve box edits.</summary> + [JsonPropertyName("keepFull")] public string KeepFull { get; set; } = ""; + [JsonPropertyName("status")] public string Status { get; set; } = ""; + [JsonPropertyName("lastRun")] public string LastRun { get; set; } = ""; + [JsonPropertyName("unassigned")] public string Unassigned { get; set; } = ""; + /// <summary>Time to the next auto run ("" when auto is off).</summary> + [JsonPropertyName("next")] public string Next { get; set; } = ""; + [JsonPropertyName("costsAge")] public string CostsAge { get; set; } = ""; + /// <summary>Local time the costs were last read ("-" before the first read; "" from older RynthAi).</summary> + [JsonPropertyName("updated")] public string Updated { get; set; } = ""; + /// <summary>"Level N Total XP X Unassigned Y" ("" from older RynthAi).</summary> + [JsonPropertyName("xpHeader")] public string XpHeader { get; set; } = ""; + /// <summary>In raise-priority order.</summary> + [JsonPropertyName("rows")] public AttrRow[] Rows { get; set; } = Array.Empty<AttrRow>(); +} + +internal sealed class AttrRow +{ + /// <summary>/attr abbreviation: str end coo qui foc sel hea sta man.</summary> + [JsonPropertyName("key")] public string Key { get; set; } = ""; + [JsonPropertyName("label")] public string Label { get; set; } = ""; + [JsonPropertyName("vital")] public bool Vital { get; set; } + /// <summary>Ticked: "Raise now" and auto-raise may spend on it.</summary> + [JsonPropertyName("on")] public bool On { get; set; } + /// <summary>Base value RynthAi last saw in a server reply (-1 = unknown; the panel prefers the client's).</summary> + [JsonPropertyName("base")] public int Base { get; set; } = -1; + /// <summary>Next-level cost from "/xp all", preformatted ("?" until read).</summary> + [JsonPropertyName("cost")] public string Cost { get; set; } = "?"; + /// <summary>Next level fits the raiser's budget (unassigned minus the reserve).</summary> + [JsonPropertyName("afford")] public bool Afford { get; set; } + /// <summary>The next-level cost has been read (false from older RynthAi too).</summary> + [JsonPropertyName("known")] public bool Known { get; set; } + /// <summary>By hand: +1 fits the unassigned XP (no reserve).</summary> + [JsonPropertyName("afford1")] public bool Afford1 { get; set; } + /// <summary>By hand: the projected +10 fits the unassigned XP.</summary> + [JsonPropertyName("afford10")] public bool Afford10 { get; set; } + /// <summary>Projected cost of ten levels (7.7% growth per level), e.g. "~1.2T"; "" from older RynthAi.</summary> + [JsonPropertyName("cost10")] public string Cost10 { get; set; } = ""; + /// <summary>Exact next-level cost with separators, for the tooltip.</summary> + [JsonPropertyName("costFull")] public string CostFull { get; set; } = ""; + [JsonPropertyName("cost10Full")] public string Cost10Full { get; set; } = ""; +} + +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; } = ""; + // Totals row and e-coin summary (all empty / zero from older RynthAi). + [JsonPropertyName("totCur")] public long TotalCurrent { get; set; } + [JsonPropertyName("totTgt")] public long TotalTarget { get; set; } + [JsonPropertyName("totInc")] public long TotalIncrease { get; set; } + [JsonPropertyName("totLum")] public string TotalLum { get; set; } = ""; + [JsonPropertyName("totCoins")] public long TotalCoins { get; set; } + [JsonPropertyName("coinsLine")] public string CoinsLine { get; set; } = ""; + [JsonPropertyName("lumToBuy")] public string LumToBuy { get; set; } = ""; + /// <summary>Ready-made clipboard texts (UB's Copy Discord / Copy In-Game).</summary> + [JsonPropertyName("copyDiscord")] public string CopyDiscord { get; set; } = ""; + [JsonPropertyName("copyIngame")] public string CopyIngame { get; set; } = ""; + /// <summary>This world's cost rules for the Cost settings editor (null from older RynthAi).</summary> + [JsonPropertyName("cfg")] public AugCostConfig? Config { get; set; } +} + +/// <summary>Per-server aug cost rules: level i costs (Base + (i-1)*Base*Pct/100) x the multiplier of its tier.</summary> +internal sealed class AugCostConfig +{ + [JsonPropertyName("world")] public string World { get; set; } = ""; + /// <summary>The world has its own saved rules (false = UB / InfiniteLeaftide defaults).</summary> + [JsonPropertyName("custom")] public bool Custom { get; set; } + /// <summary>Tier multipliers: below S1, from S1, from S2, from S3, from S4.</summary> + [JsonPropertyName("mults")] public double[] Multipliers { get; set; } = Array.Empty<double>(); + [JsonPropertyName("rows")] public AugCostRule[] Rows { get; set; } = Array.Empty<AugCostRule>(); +} + +internal sealed class AugCostRule +{ + [JsonPropertyName("key")] public string Key { get; set; } = ""; + [JsonPropertyName("label")] public string Label { get; set; } = ""; + [JsonPropertyName("base")] public long Base { get; set; } + /// <summary>Percent of Base added per level.</summary> + [JsonPropertyName("pct")] public double Percent { get; set; } + [JsonPropertyName("coins")] public int Coins { get; set; } + [JsonPropertyName("s1")] public int S1 { get; set; } + [JsonPropertyName("s2")] public int S2 { get; set; } + [JsonPropertyName("s3")] public int S3 { get; set; } + [JsonPropertyName("s4")] public int S4 { get; set; } + /// <summary>Highest target (0 = no limit).</summary> + [JsonPropertyName("cap")] public int Cap { 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>Levels planned (target - current).</summary> + [JsonPropertyName("inc")] public int Increase { 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/RynthAiData.cs b/src/RynthCore.Engine/UI/Data/RynthAiData.cs index 28d58f2..59f93a1 100644 --- a/src/RynthCore.Engine/UI/Data/RynthAiData.cs +++ b/src/RynthCore.Engine/UI/Data/RynthAiData.cs @@ -41,6 +41,11 @@ internal sealed class RynthAiSnapshot [JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; } [JsonPropertyName("selectedMetaIdx")] public int SelectedMetaIdx { get; set; } [JsonPropertyName("selectedProfileIdx")] public int SelectedProfileIdx { get; set; } + // Buff profiles (RynthAi 0.5.31+): "Built-in" first, then BuffProfiles\*.json. Older plugins + // send none, and the Buffs picker then shows "Built-in" with nothing to pick. + [JsonPropertyName("buffProfiles")] public string[] BuffProfiles { get; set; } = Array.Empty<string>(); + [JsonPropertyName("currentBuffName")] public string CurrentBuffName { get; set; } = string.Empty; + [JsonPropertyName("selectedBuffIdx")] public int SelectedBuffIdx { get; set; } [JsonPropertyName("combatEnabled")] public bool CombatEnabled { get; set; } [JsonPropertyName("buffingEnabled")] public bool BuffingEnabled { get; set; } [JsonPropertyName("navigationEnabled")] public bool NavigationEnabled { get; set; } @@ -85,6 +90,8 @@ internal sealed class RynthAiView public required string NavText { get; init; } public required string LootText { get; init; } public required string MetaText { get; init; } + /// <summary>Buff profile buffing uses ("Built-in" without one).</summary> + public required string BuffText { get; init; } public required string TargetHeadline { get; init; } public required int TargetSegmentsLit { get; init; } public required bool ShowTargetSubBars { get; init; } @@ -164,6 +171,7 @@ internal sealed unsafe class RynthAiSource : UiSource<RynthAiView> NavText = Truncate(s.CurrentNavName, 16), LootText = Truncate(s.CurrentLootName, 16), MetaText = Truncate(s.CurrentMetaName, 16), + BuffText = Truncate(string.IsNullOrWhiteSpace(s.CurrentBuffName) ? "Built-in" : s.CurrentBuffName, 16), TargetHeadline = Truncate(label, 32), TargetSegmentsLit = lit, ShowTargetSubBars = showSub, @@ -265,6 +273,7 @@ internal static unsafe class RynthAiCommands 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() { @@ -272,6 +281,7 @@ internal static unsafe class RynthAiCommands { _toggleMacro = null; _setSubsystemEnabled = null; _selectProfile = null; _forceRebuff = null; _cancelForceRebuff = null; _adjustOpacity = null; _togglePanelLock = null; _sendNavCommand = null; + _applyRemoteCommand = null; }; } @@ -341,6 +351,29 @@ internal static unsafe class RynthAiCommands 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> diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index b3f0ca2..99f0f6f 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -11,6 +11,7 @@ // ============================================================================ using System; +using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text.Json; using System.Text.Json.Serialization; @@ -44,6 +45,13 @@ internal sealed class RynthAiSettings // 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; + // Server Features (RynthAi ServerFeatureGate): world names that turn on the ILT Hub, the + // Progression planners and the attribute raiser, plus a manual override. An older RynthAi + // doesn't send them; RynthAi lays a save over its current values, so these defaults are + // only ever shown, never applied. ServerFeaturesStatus is read-only (RynthAi ignores it). + public string FeatureServerNames { get; set; } = "InfiniteLeaftide, *Leaftide*"; + public bool ForceServerFeatures { get; set; } + public string ServerFeaturesStatus { get; set; } = string.Empty; public bool EnableRaycasting { get; set; } public bool UseArcs { get; set; } public float BowArcVelocity { get; set; } = 25f; @@ -202,6 +210,16 @@ internal sealed class RynthAiSettings public int SalvageSalvageDelayMs { get; set; } = 50; public int SalvageResultDelayFirstMs { get; set; } = 1000; public int SalvageResultDelayFastMs { get; set; } = 250; + // Ground loot and item info + public bool EnableGroundLoot { get; set; } + public bool ItemInfoOnSelect { get; set; } + // Diagnostics (RynthAi's RynthLog: per PC in Logs\Diagnostics\diagnostics.json, not the profile) + public bool DiagDebugToChat { get; set; } + public bool DiagFileLogAll { get; set; } = true; + /// <summary>"Name=Level" per trace category, ','-joined; Level 0 Off, 1 Trace, 2 Info. See <see cref="TraceCategoryLevels"/>.</summary> + public string DiagCategories { get; set; } = string.Empty; + /// <summary>Read-only (RynthAi ignores it on save): the diagnostics folder.</summary> + public string DiagFolder { get; set; } = string.Empty; /// <summary>A private copy for a face to edit (all members are values or strings).</summary> public RynthAiSettings Clone() => (RynthAiSettings)MemberwiseClone(); @@ -272,7 +290,60 @@ internal static unsafe class SettingsCommands // ── Schema ───────────────────────────────────────────────────────────────── -internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus } +internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, TraceCategories, Text, Status } + +/// <summary> +/// Reads and edits <see cref="RynthAiSettings.DiagCategories"/> ("Name=Level,..."). The category +/// list comes from RynthAi, so a category it adds shows up without an engine change. +/// </summary> +internal static class TraceCategoryLevels +{ + public const int Off = 0, Trace = 1, Info = 2; + + /// <summary>The categories in RynthAi's order; malformed entries are skipped.</summary> + public static List<(string Name, int Level)> Parse(string? levels) + { + var list = new List<(string, int)>(); + if (string.IsNullOrWhiteSpace(levels)) return list; + foreach (string entry in levels.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + int eq = entry.IndexOf('='); + if (eq <= 0 || !int.TryParse(entry[(eq + 1)..], out int level)) continue; + list.Add((entry[..eq], Math.Clamp(level, Off, Info))); + } + return list; + } + + private static string Format(List<(string Name, int Level)> list) + { + var parts = new string[list.Count]; + for (int i = 0; i < list.Count; i++) parts[i] = list[i].Name + "=" + list[i].Level; + return string.Join(",", parts); + } + + /// <summary> + /// Turns tracing on or off for one category (empty <paramref name="name"/> with a + /// <paramref name="prefix"/>: every category starting with it; both empty: all). On keeps + /// a category already at Info at Info, the same rule as /ra trace. + /// </summary> + public static string Set(string? levels, string name, bool on, string prefix = "") + { + List<(string Name, int Level)> list = Parse(levels); + for (int i = 0; i < list.Count; i++) + { + var (n, level) = list[i]; + bool match = name.Length > 0 + ? string.Equals(n, name, StringComparison.OrdinalIgnoreCase) + : n.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); + if (!match) continue; + list[i] = (n, !on ? Off : level == Off ? Trace : level); + } + return Format(list); + } + + /// <summary>Checkbox label: the name, plus " +log" at Info (trace lines also go to the normal log).</summary> + public static string Label(string name, int level) => level == Info ? name + " +log" : name; +} /// <summary> /// One row of a settings tab. Numeric values go through double (bools as @@ -290,7 +361,15 @@ internal sealed record SettingRow( double Step = 1, string[]? Items = null, Func<RynthAiSettings, bool>? VisibleWhen = null, - bool Gates = false) + 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, + // Text rows: the string value (committed on Enter / focus loss); Status rows: GetText only. + Func<RynthAiSettings, string>? GetText = null, + Action<RynthAiSettings, string>? SetText = null, + // Text rows: greyed hint shown while the box is empty. + string? Hint = null) { public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s); } @@ -368,6 +447,17 @@ internal static class SettingsSchema 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 Text(string label, Func<RynthAiSettings, string> get, Action<RynthAiSettings, string> set, + string? tip = null, string? hint = null) => + new(SettingKind.Text, label, tip, GetText: get, SetText: set, Hint: hint); + + // A one-line status RynthAi computes (read-only; empty = hidden). + private static SettingRow Status(Func<RynthAiSettings, string> get) => + new(SettingKind.Status, "", GetText: get, VisibleWhen: s => !string.IsNullOrEmpty(get(s))); + private static SettingRow[] Tiers(Func<RynthAiSettings, int>[] get, Action<RynthAiSettings, int>[] set) { var rows = new SettingRow[get.Length]; @@ -414,6 +504,12 @@ internal static class SettingsSchema TextSize("Status", "Status"), TextSize("Log", "Log"), TextSize("Tracker", "Tracker"), + Spacer(), + Section("Item Info"), + Bool("Describe Items When Selected", s => s.ItemInfoOnSelect, (s, v) => s.ItemInfoOnSelect = v, + "Print a Mag-style description of an item in chat when you select it.\nAlso: /ra iteminfo on|off."), + Button("Item Info Options", "Open...", () => RynthAiCommands.ApplyRemoteCommand("iteminfo", "window"), + "Which fields the description shows and which item types are described on select (/ra iteminfo window)."), }), new("UI", new[] @@ -458,6 +554,17 @@ internal static class SettingsSchema "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("Server Features (ILT / infinite attributes)"), + Status(s => s.ServerFeaturesStatus), + Text("Servers", s => s.FeatureServerNames, (s, v) => s.FeatureServerNames = v, + "Comma-separated world names that turn on the ILT Hub, the Skills panel's Progression planners\n" + + "and the attribute raiser. * is a wildcard (*Leaftide* matches any name containing Leaftide).\n" + + "Case does not matter. Saved with the RynthAi profile.", + hint: "InfiniteLeaftide, *Leaftide*"), + Bool("Force enable on this server (manual override)", s => s.ForceServerFeatures, (s, v) => s.ForceServerFeatures = v, + "Turn the features on for whatever world you are on, even if it is not in the list.\n" + + "Each feature still follows what the server reports (for example /xp off keeps the attribute raiser off)."), + 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), @@ -648,6 +755,8 @@ internal static class SettingsSchema new("Buffing", Concat( Bool("Enable Buffing", s => s.EnableBuffing, (s, v) => s.EnableBuffing = v), + Button("Buff Profiles", "Spells...", () => RynthAiCommands.ApplyRemoteCommand("spells", "show"), + "Open the RynthAi Spells window: browse the spell list by school, level and target,\nand build the buff profile buffing uses (pick it under Loaded Files > Buffs).\nAlso: /ra spells, /ra buffprofile <name>|none."), 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."), @@ -684,6 +793,8 @@ internal static class SettingsSchema "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), + Bool("Loot Items On Ground", s => s.EnableGroundLoot, (s, v) => s.EnableGroundLoot = v, + "Pick up loose items on the ground that match your loot profile, within Corpse Max range.\nCorpses always come first. Status and rescan: /ra groundloot."), Spacer(), Section("Corpse Ownership"), Combo("Loot From", LootOwnershipModes, s => s.LootOwnership, (s, v) => s.LootOwnership = v), @@ -700,6 +811,8 @@ internal static class SettingsSchema "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), @@ -742,5 +855,24 @@ internal static class SettingsSchema Spacer(), Note("Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match."), }), + + new("Diagnostics", new[] + { + Section("Logging & Debugging"), + Bool("Debug to chat", s => s.DiagDebugToChat, (s, v) => s.DiagDebugToChat = v, + "Echo trace lines and errors from the categories ticked below into the chat window.\nAlso: /ra debug on|off."), + Bool("Daily RynthAi log file", s => s.DiagFileLogAll, (s, v) => s.DiagFileLogAll = v, + "Mirror every RynthAi log line to rynthai_<date>.txt in the log folder (kept 7 days).\nAlso: /ra logs file on|off."), + Button("Log Folder", "Open", () => RynthAiCommands.ApplyRemoteCommand("logs", "open"), + "Open RynthAi's Logs\\Diagnostics folder in Explorer (/ra logs open)."), + Button("Old Log Files", "Prune", () => RynthAiCommands.ApplyRemoteCommand("logs", "prune"), + "Delete diagnostics files past the retention limit now (/ra logs prune)."), + Spacer(), + Section("Trace Per Category"), + new SettingRow(SettingKind.TraceCategories, "Categories", + "Ticked categories write their trace lines to Trace\\<Category>_<date>.txt (/ra trace <category> on|off)."), + Note("+log = the category is at Info: its trace lines also go to the normal log. The launcher's Logging page sets Off, Trace or Info."), + Note("Exceptions always go to exceptions_<date>.txt with full stack traces (throttled). Settings here are for this PC, not the profile."), + }), }; } diff --git a/src/RynthCore.Engine/UI/Data/UiSources.cs b/src/RynthCore.Engine/UI/Data/UiSources.cs index a4cdd47..4be0072 100644 --- a/src/RynthCore.Engine/UI/Data/UiSources.cs +++ b/src/RynthCore.Engine/UI/Data/UiSources.cs @@ -16,6 +16,8 @@ internal static class UiSources 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(); @@ -52,6 +54,8 @@ internal static class UiSources UiDataHub.Register(Radar); UiDataHub.Register(RynthAi); UiDataHub.Register(Patrol); + UiDataHub.Register(Progression); + UiDataHub.Register(Charms); UiDataHub.Register(PluginStatus); UiDataHub.Register(Log); UiDataHub.Register(Tracker); diff --git a/src/RynthCore.Engine/UI/LayeredWindow.cs b/src/RynthCore.Engine/UI/LayeredWindow.cs index 9ada298..ed1a32d 100644 --- a/src/RynthCore.Engine/UI/LayeredWindow.cs +++ b/src/RynthCore.Engine/UI/LayeredWindow.cs @@ -207,7 +207,7 @@ internal sealed unsafe class LayeredWindow : IDisposable [DllImport("user32.dll")] private static extern bool BringWindowToTop(IntPtr hWnd); private const uint GW_OWNER = 4; [DllImport("user32.dll")] private static extern bool ReleaseCapture(); - [DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + [DllImport("user32.dll", SetLastError = true)] private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach); [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); [DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT lpPoint); @@ -275,15 +275,20 @@ internal sealed unsafe class LayeredWindow : IDisposable /// 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) { + // Handled before the instance lookup: Dispose has already removed the + // instance by the time this posted message is dispatched. if (msg == WM_RYNTH_SELF_DESTROY) { - DestroyWindow(hwnd); + bool destroyed = DestroyWindow(hwnd); + int err = destroyed ? 0 : Marshal.GetLastWin32Error(); + RynthCore.Engine.RynthLog.Info($"LayeredWindow: self-destroy DestroyWindow(0x{hwnd.ToInt64():X}) = {destroyed} err={err} on thread=0x{GetCurrentThreadId():X}."); return IntPtr.Zero; } @@ -317,12 +322,11 @@ internal sealed unsafe class LayeredWindow : IDisposable /// FloatingPanelHost's RunOnGameThread) and DestroyWindow only works on /// the owning thread. /// - /// Dispose only posts the destroy, and Win32Backend.Shutdown unhooks the - /// game WndProc ~1 ms after the overlay stops — usually before the game - /// thread gets to the post. AC's own WndProc then drops it, and because - /// the engine module is never unloaded the panel lives on: frozen on its - /// last frame, deaf to input, and hidden under the next generation's copy - /// of it until that one is moved ("two RynthAi windows"). + /// Synchronous backstop for panels that were never disposed: because the + /// engine module is never unloaded, such a panel lives on after shutdown, + /// frozen on its last frame, deaf to input, and hidden under the next + /// generation's copy of it until that one is moved ("two RynthAi windows"). + /// (Disposed panels destroy themselves via WM_RYNTH_SELF_DESTROY.) /// /// <paramref name="includeThisGeneration"/>=false spares this engine /// load's own windows (class names carry a per-load Guid) and removes only @@ -367,6 +371,25 @@ internal sealed unsafe class LayeredWindow : IDisposable } } + /// <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) })] @@ -1482,34 +1505,51 @@ internal sealed unsafe class LayeredWindow : IDisposable // 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 - // silently no-ops it otherwise. The HWND was created on the game - // thread (see FloatingPanelHost ctor's RunOnGameThread wrap), so - // marshal the teardown there too. Without this, redocking left - // the original floating window visible but orphaned ("frozen - // duplicate"). - // - // UI deep-dive finding P0-1 (2026-07-02): this used to block via - // RunOnGameThread (a synchronous SendMessage) — Dispose is often - // called from the Avalonia UI thread (e.g. redocking a panel), - // and blocking it on the game thread's WndProc is part of the - // same AB-BA deadlock class the OnInput fix closes. Dispose - // doesn't need to observe the destroy completing, so post it - // instead — fire-and-forget, never blocks the caller. - try - { - RynthCore.Engine.ImGuiBackend.Win32Backend.PostDestroyWindow(hwnd); - } - catch (Exception ex) - { - RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: PostDestroyWindow threw {ex.GetType().Name}: {ex.Message}. Falling back to inline call on thread=0x{GetCurrentThreadId():X}."); - // Best-effort fallback if Win32Backend isn't available - // (e.g. early shutdown after it's already torn down). - bool destroyed = DestroyWindow(hwnd); - RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: fallback DestroyWindow(0x{hwnd.ToInt64():X}) = {destroyed}."); - } + // DestroyWindow MUST run on the thread that owns the HWND (Win32 + // fails it with ERROR_ACCESS_DENIED otherwise); a missed destroy + // leaves the floating window visible but orphaned ("frozen duplicate"). + DestroyOnOwnerThread(hwnd); } DisposeDib(); } + + /// <summary> + /// Destroys <paramref name="hwnd"/> on the thread that actually owns it, never + /// blocking the caller. Inline when the caller is the owner; otherwise posts + /// WM_RYNTH_SELF_DESTROY to the window itself so its own WndProc destroys it. + /// Posting to the panel (not the game window) works for panels created on + /// any thread, and still works after Win32Backend has unhooked the game + /// WndProc at shutdown — a post to the game window would be dropped by AC. + /// </summary> + private static void DestroyOnOwnerThread(IntPtr hwnd) + { + uint ownerThread = GetWindowThreadProcessId(hwnd, out _); + uint currentThread = GetCurrentThreadId(); + + if (ownerThread == 0) + { + // Window already gone (e.g. its owning thread exited, which destroys it). + RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: HWND=0x{hwnd.ToInt64():X} no longer exists — nothing to destroy."); + return; + } + + if (ownerThread == currentThread) + { + bool destroyed = DestroyWindow(hwnd); + int err = destroyed ? 0 : Marshal.GetLastWin32Error(); + RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: DestroyWindow(0x{hwnd.ToInt64():X}) inline on owner thread=0x{currentThread:X} = {destroyed} err={err}."); + return; + } + + if (PostMessage(hwnd, WM_RYNTH_SELF_DESTROY, IntPtr.Zero, IntPtr.Zero)) + { + RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: posted self-destroy to HWND=0x{hwnd.ToInt64():X} (owner thread=0x{ownerThread:X}, caller thread=0x{currentThread:X})."); + return; + } + + // Post failed (queue full or HWND destroyed in the meantime); a cross-thread + // DestroyWindow would only fail, so report it rather than attempt it. + RynthCore.Engine.RynthLog.Error($"LayeredWindow.Dispose: PostMessage(self-destroy) to HWND=0x{hwnd.ToInt64():X} failed err={Marshal.GetLastWin32Error()} (owner thread=0x{ownerThread:X})."); + } } diff --git a/src/RynthCore.Engine/UI/OverlayFrameBuffer.cs b/src/RynthCore.Engine/UI/OverlayFrameBuffer.cs new file mode 100644 index 0000000..f6669b6 --- /dev/null +++ b/src/RynthCore.Engine/UI/OverlayFrameBuffer.cs @@ -0,0 +1,72 @@ +// ============================================================================ +// RynthCore.Engine - UI/OverlayFrameBuffer.cs +// Lock-minimised pixel handoff from the Avalonia UI thread to the D3D9 +// render thread. Avalonia submits a captured BGRA frame; EndScene consumes +// it once, uploads to a D3D9 texture, then re-uses that texture until the +// next submit. +// +// Thread model: +// Writer: Avalonia STA thread (DispatcherTimer ~30 fps) +// Reader: D3D9 render thread (EndScene ~60 fps) +// +// The submitted buffer is replaced atomically (pointer swap). The reader +// holds a reference for the duration of the upload, preventing GC collection +// even if the writer has already posted a newer frame. +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Engine.UI; + +internal static class OverlayFrameBuffer +{ + private sealed class Frame + { + public readonly byte[] Pixels; + public readonly int Width; + public readonly int Height; + + public Frame(byte[] pixels, int w, int h) + { + Pixels = pixels; + Width = w; + Height = h; + } + } + + // Written by Avalonia thread, read by D3D9 thread. + // Interlocked.Exchange gives the sequential-consistency guarantee we need. + private static Frame? _pending; + + /// <summary> + /// Submit a new BGRA frame from the Avalonia UI thread. + /// The pixel array is copied so the caller can reuse its bitmap lock buffer. + /// </summary> + public static void Submit(IntPtr pixelData, int byteCount, int w, int h) + { + var buf = new byte[byteCount]; + System.Runtime.InteropServices.Marshal.Copy(pixelData, buf, 0, byteCount); + Interlocked.Exchange(ref _pending, new Frame(buf, w, h)); + } + + /// <summary> + /// Consume the latest pending frame from the D3D9 render thread. + /// Returns true if a new frame is available; the caller owns the byte array + /// until the next call (no further synchronisation required). + /// </summary> + public static bool TryConsume(out byte[]? pixels, out int w, out int h) + { + Frame? frame = Interlocked.Exchange(ref _pending, null); + if (frame == null) + { + pixels = null; w = 0; h = 0; + return false; + } + + pixels = frame.Pixels; + w = frame.Width; + h = frame.Height; + return true; + } +} diff --git a/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs b/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs index 533c2a2..a9e5c72 100644 --- a/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs @@ -2,8 +2,9 @@ // RynthCore.Engine — UI/Panels/ItemsPanel.cs // Avalonia replica of the ImGui Items tab (LegacyWeaponsUi.cs). // -// Three sections: -// Weapons — Name, Element picker, Delete +// Four sections: +// Weapons — Name, Element picker, Delete (ItemRules with Action != "Shield") +// Shields — Auto-equip toggle, Name, Delete (ItemRules with Action == "Shield") // Consumables — Name, Type picker, Delete // Mana Stones — Enable tapping toggle, keep count, min mana threshold // @@ -61,6 +62,8 @@ internal static class ItemsPanel [JsonPropertyName("manaTapMinMana")] public int ManaTapMinMana { get; set; } = 2500; [JsonPropertyName("manaStoneKeepCount")]public int ManaStoneKeepCount{ get; set; } = 5; [JsonPropertyName("currentTargetName")] public string CurrentTargetName { get; set; } = string.Empty; + // Null when the plugin predates shields (RynthAi < 0.6.20); the plugin then ignores it on write-back. + [JsonPropertyName("autoEquipShield")] public bool? AutoEquipShield { get; set; } } internal sealed class WeaponEntry @@ -68,6 +71,10 @@ internal static class ItemsPanel [JsonPropertyName("id")] public int Id { get; set; } [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; [JsonPropertyName("element")] public string Element { get; set; } = "Slash"; + // "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, ItemsCommands.ShieldAction, StringComparison.OrdinalIgnoreCase); } internal sealed class ConsumableEntry @@ -206,29 +213,33 @@ internal static class ItemsPanel { body.Children.Clear(); + // Weapons and shields share the plugin's ItemRules list (state.Data.Weapons); + // rows are split by Action, so deletes remove by reference, not by index. + void DeleteItem(WeaponEntry entry) + { + state.Data.Weapons.Remove(entry); + state.Dirty = true; + PushChanges(state); + Refresh(); + } + // ── Weapons ────────────────────────────────────────────────────── body.Children.Add(BuildSectionHeader("Weapons")); - if (state.Data.Weapons.Count == 0) + var weapons = state.Data.Weapons.Where(w => !w.IsShield).ToList(); + if (weapons.Count == 0) { body.Children.Add(BuildEmptyRow("No weapons configured")); } else { body.Children.Add(BuildTableHeader(new[] { "Item Name", "Element", "" }, new[] { true, false, false }, new double[] { 0, 100, 46 })); - for (int i = 0; i < state.Data.Weapons.Count; i++) + for (int i = 0; i < weapons.Count; i++) { - var w = state.Data.Weapons[i]; - int wi = i; - body.Children.Add(BuildWeaponRow(w, wi % 2 == 0, ShowPicker, + var w = weapons[i]; + body.Children.Add(BuildWeaponRow(w, i % 2 == 0, ShowPicker, onChanged: () => { state.Dirty = true; PushChanges(state); }, - onDelete: () => - { - state.Data.Weapons.RemoveAt(wi); - state.Dirty = true; - PushChanges(state); - Refresh(); - })); + onDelete: () => DeleteItem(w))); } } @@ -237,6 +248,45 @@ internal static class ItemsPanel body.Children.Add(BuildDivider()); + // ── Shields (off-hand) ─────────────────────────────────────────── + body.Children.Add(BuildSectionHeader("Shields (off-hand)")); + + // Plugins older than RynthAi 0.6.20 don't report the setting — hide the toggle then. + if (state.Data.AutoEquipShield is bool autoEquip) + { + body.Children.Add(BuildToggleRow("Auto-equip with one-handed melee weapons", autoEquip, + "On: in melee with a one-handed weapon, combat wields the first shield below unless the monster has its own off-hand (Damage panel or Monsters 'Offhand').\n" + + "Off: only per-monster off-hand choices are equipped.\n" + + "Never used with two-handed weapons, bows, crossbows, atlatls or casters.", + on => + { + state.Data.AutoEquipShield = on; + state.Dirty = true; + PushChanges(state); + Refresh(); + })); + } + + var shields = state.Data.Weapons.Where(w => w.IsShield).ToList(); + if (shields.Count == 0) + { + body.Children.Add(BuildEmptyRow("No shields configured")); + } + else + { + body.Children.Add(BuildTableHeader(new[] { "Shield Name", "" }, new[] { true, false }, new double[] { 0, 46 })); + for (int i = 0; i < shields.Count; i++) + { + var s = shields[i]; + body.Children.Add(BuildShieldRow(s, i % 2 == 0, onDelete: () => DeleteItem(s))); + } + } + + body.Children.Add(BuildAddButton("Add Selected Shield", "(select a shield in inventory first)", + ItemsCommands.AddSelectedShield)); + + body.Children.Add(BuildDivider()); + // ── Consumables ────────────────────────────────────────────────── body.Children.Add(BuildSectionHeader("Consumable Items")); @@ -290,7 +340,8 @@ internal static class ItemsPanel bool consumablesChanged = ConsumablesChanged(state.Data.Consumables, fresh.Consumables); bool manaChanged = state.Data.EnableManaTapping != fresh.EnableManaTapping || state.Data.ManaTapMinMana != fresh.ManaTapMinMana - || state.Data.ManaStoneKeepCount != fresh.ManaStoneKeepCount; + || state.Data.ManaStoneKeepCount != fresh.ManaStoneKeepCount + || state.Data.AutoEquipShield != fresh.AutoEquipShield; // UI deep-dive finding P0-4 (2026-07-02): state.Data = fresh used // to run unconditionally, EVERY poll tick, even when the @@ -509,6 +560,80 @@ internal static class ItemsPanel return grid; } + // ── Shield table row (name + delete; shields have no element) ───────────── + private static Control BuildShieldRow(WeaponEntry s, bool alt, Action onDelete) + { + var grid = new Grid + { + Background = alt ? ColRowAlt : ColPanelBg, + Height = 24, + ColumnDefinitions = new ColumnDefinitions("*, 46"), + }; + + var nameTb = new TextBlock + { + Text = s.Name, + Foreground = ColTextDim, + FontSize = 10, + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(6, 0), + TextTrimming = TextTrimming.CharacterEllipsis, + }; + Grid.SetColumn(nameTb, 0); + grid.Children.Add(nameTb); + + var del = new Button + { + Content = "Del", + Background = ColBtnFill, + Foreground = ColRed, + BorderBrush = ColBtnBord, + BorderThickness = new Thickness(1), + Padding = new Thickness(4, 2), + FontSize = 10, + Margin = new Thickness(2, 2), + }; + del.Click += (_, _) => onDelete(); + Grid.SetColumn(del, 1); + grid.Children.Add(del); + + return grid; + } + + // ── Labelled ON/OFF toggle row (same look as the mana-tapping toggle) ───── + private static Control BuildToggleRow(string label, bool value, string tooltip, Action<bool> onToggled) + { + var row = new WrapPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(4, 4, 4, 2) }; + + var btn = new Button + { + Content = value ? "ON" : "OFF", + Background = value ? new SolidColorBrush(Color.FromRgb(0x10, 0x40, 0x10)) : ColBtnFill, + Foreground = value ? new SolidColorBrush(Color.FromRgb(0x33, 0xFF, 0x33)) : ColMute, + BorderBrush = ColBtnBord, + BorderThickness = new Thickness(1), + Padding = new Thickness(8, 2), + FontSize = 10, + Width = 50, + Margin = new Thickness(0, 0, 8, 0), + }; + btn.Click += (_, _) => onToggled(!value); + ToolTip.SetTip(btn, tooltip); + row.Children.Add(btn); + + var lbl = new TextBlock + { + Text = label, + Foreground = ColTextDim, + FontSize = 10, + VerticalAlignment = VerticalAlignment.Center, + }; + ToolTip.SetTip(lbl, tooltip); + row.Children.Add(lbl); + + return row; + } + // ── Consumable table row ────────────────────────────────────────────────── private static Control BuildConsumableRow( ConsumableEntry c, bool alt, @@ -739,7 +864,8 @@ internal static class ItemsPanel { if (a.Count != b.Count) return true; for (int i = 0; i < a.Count; i++) - if (a[i].Id != b[i].Id || a[i].Name != b[i].Name || a[i].Element != b[i].Element) return true; + if (a[i].Id != b[i].Id || a[i].Name != b[i].Name || a[i].Element != b[i].Element + || !string.Equals(a[i].Action, b[i].Action, StringComparison.OrdinalIgnoreCase)) return true; return false; } diff --git a/src/RynthCore.Engine/UI/Panels/NavPanel.cs b/src/RynthCore.Engine/UI/Panels/NavPanel.cs index d69153c..62d46be 100644 --- a/src/RynthCore.Engine/UI/Panels/NavPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/NavPanel.cs @@ -171,9 +171,29 @@ internal static class NavPanel { e.Handled = true; picker.Close(); } }; + // Waypoint list controls live for the panel's lifetime. Rebuild() only refills + // waypointStack: a ScrollViewer recreated (or given a new Content) resets its + // offset to the top, which made the list jump back every poll and impossible to edit. + var waypointStack = new StackPanel { Spacing = 1 }; + var waypointScroll = new ScrollViewer + { + VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, + HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled, + Content = waypointStack, + }; + var waypointHost = new Border { Height = 200, Child = waypointScroll }; + + // Last plugin JSON the panel was built from. A rebuild from a user action + // (optimistic local edit) clears it so the next poll always resyncs with the plugin. + string lastJson = string.Empty; + bool rebuildFromPoll = false; + void Rebuild() { + if (!rebuildFromPoll) lastJson = string.Empty; + Vector keepOffset = waypointScroll.Offset; content.Children.Clear(); + waypointStack.Children.Clear(); var d = state.Data; bool navActive = d.MacroRunning && d.NavigationEnabled; @@ -439,7 +459,6 @@ internal static class NavPanel FontSize = 10, }); - var waypointStack = new StackPanel { Spacing = 1 }; for (int i = 0; i < d.Points.Count; i++) { int ci = i; @@ -516,16 +535,10 @@ internal static class NavPanel waypointStack.Children.Add(row); } - content.Children.Add(new Border - { - Height = 200, - Child = new ScrollViewer - { - VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, - HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled, - Content = waypointStack, - }, - }); + content.Children.Add(waypointHost); // same instance every rebuild — keeps scroll offset + // Re-apply after layout too: the re-attach / new row extent can coerce it to 0. + waypointScroll.Offset = keepOffset; + Dispatcher.UIThread.Post(() => waypointScroll.Offset = keepOffset, DispatcherPriority.Loaded); } // ── Poll timer ──────────────────────────────────────────────────────── @@ -536,6 +549,9 @@ internal static class NavPanel timer.Tick += (_, _) => { 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; var snap = UiSources.Nav.Current; if (snap == null || snap.Version == seenVersion) return; seenVersion = snap.Version; diff --git a/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs index 59ff065..bc2c0d4 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs @@ -558,7 +558,7 @@ internal static partial class RynthAiPanel var launcherGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), - RowDefinitions = new RowDefinitions("Auto,Auto"), + RowDefinitions = new RowDefinitions("Auto,Auto,Auto"), Margin = new Thickness(0, 4, 0, 0) }; AddSplitLauncher(launcherGrid, 0, 0, "Meta", "⚙", "Lua", "<>", @@ -567,8 +567,15 @@ internal static partial class RynthAiPanel AddMonstersLauncher(launcherGrid, 0, 1); AddLauncher(launcherGrid, 0, 2, "Settings", "⚒", onClick: () => PanelRouter.Toggle("Settings")); - AddSplitLauncher(launcherGrid, 1, 0, "Nav", "➤", "Map", "🗺", - onLeftClick: () => PanelRouter.Toggle("Nav")); + // 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: () => PanelRouter.Toggle("Nav"), + onRightClick: () => + { + ClosePicker(); + 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: () => PanelRouter.Toggle("Items")); var patrolBtn = AddLauncher(launcherGrid, 1, 2, "Patrol", "⬡", @@ -583,6 +590,33 @@ internal static partial class RynthAiPanel ShowPatrolFlyout(patrolBtn); } }; + // Char: same as typing "/ra hub show". The ILT Hub is an ImGui overlay window with no + // Avalonia panel, so this is the panel's way to open it. + var charBtn = AddLauncher(launcherGrid, 2, 0, "Char", "♥", + onClick: () => + { + ClosePicker(); + RynthAiCommands.ApplyRemoteCommand("hub", "show"); + }); + ToolTip.SetTip(charBtn, "Open the character hub (ILT Hub) window (/ra hub show)."); + + // Hub: the Mini Remote and the Inventory HUDs setup are ImGui windows inside RynthAi. + var hudBtn = AddLauncher(launcherGrid, 2, 1, "Hub", "▣", + onClick: () => + { + ClosePicker(); + 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) => + { + if (e.GetCurrentPoint(hudBtn).Properties.IsRightButtonPressed) + { + e.Handled = true; + ClosePicker(); + RynthAiCommands.ApplyRemoteCommand("huds", "show"); + } + }; dash.Children.Add(launcherGrid); @@ -1201,16 +1235,18 @@ internal static partial class RynthAiPanel /// by side. Used for Nav | Map so the user can pop the navigation panel /// or the dungeon map independently from the same row slot. /// </summary> - private static void AddSplitLauncher(Grid grid, int row, int col, + /// <returns>The left and right half buttons (e.g. for tooltips).</returns> + private static (Button Left, Button Right) AddSplitLauncher(Grid grid, int row, int col, string leftLabel, string leftIcon, string rightLabel, string rightIcon, Action? onLeftClick = null, Action? onRightClick = null) { var splitGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*") }; - AddLauncher(splitGrid, 0, 0, leftLabel, leftIcon, onLeftClick); - AddLauncher(splitGrid, 0, 1, rightLabel, rightIcon, onRightClick); + var left = AddLauncher(splitGrid, 0, 0, leftLabel, leftIcon, onLeftClick); + var right = AddLauncher(splitGrid, 0, 1, rightLabel, rightIcon, onRightClick); grid.Children.Add(splitGrid); Grid.SetRow(splitGrid, row); Grid.SetColumn(splitGrid, col); + return (left, right); } private static Button AddLauncher(Grid grid, int row, int col, string label, string icon, Action? onClick = null) diff --git a/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs index 600fa95..4588fba 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs @@ -6,7 +6,10 @@ // // Rule semantics (the rules live in ChatModel, UI/Data/ChatData.cs; the ImGui // face is ImGui/Panels/ChatFiltersFace.cs): -// • Regex, case-insensitive, matched against the formatted line. +// • 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. @@ -95,10 +98,24 @@ internal static class RynthChatFiltersPanel 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 = "regex (e.g. AutoRun)", + Watermark = PatternWatermark(r.Mode), FontSize = 10, MinWidth = 220, Height = 24, @@ -118,6 +135,15 @@ internal static class RynthChatFiltersPanel 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 { @@ -180,7 +206,7 @@ internal static class RynthChatFiltersPanel { Orientation = Orientation.Horizontal, Spacing = 4, - Children = { enabledCheck, patternBox, tabBox, upBtn, downBtn, delBtn }, + Children = { enabledCheck, modeBtn, patternBox, tabBox, upBtn, downBtn, delBtn }, }); } @@ -194,6 +220,80 @@ internal static class RynthChatFiltersPanel 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) + { + var check = new CheckBox + { + IsChecked = p.Enabled, + Content = new TextBlock { Text = p.Label, FontSize = 10, Foreground = Brushes.White }, + VerticalAlignment = VerticalAlignment.Center, + MinWidth = 220, + }; + ToolTip.SetTip(check, $"{p.Description}\nExample: {p.Example}"); + check.IsCheckedChanged += (_, _) => + { + p.Enabled = check.IsChecked == true; + ChatModel.FiltersChanged(); + }; + + 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(); + ChatModel.FiltersChanged(); + }; + + return new StackPanel + { + Orientation = Orientation.Horizontal, + Spacing = 4, + Margin = new Thickness(8, 0, 0, 0), + Children = { check, tabBox }, + }; } addBtn.Click += (_, _) => @@ -224,4 +324,15 @@ internal static class RynthChatFiltersPanel RebuildRows(); return layout; } + + /// <summary>Button captions, indexed by <see cref="ChatMatchMode"/>.</summary> + private static readonly string[] ModeLabels = { "Regex", "Contains", "Starts", "Ends" }; + + private static string PatternWatermark(ChatMatchMode mode) => mode switch + { + 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/RynthChatPresets.cs b/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs new file mode 100644 index 0000000..0df795c --- /dev/null +++ b/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs @@ -0,0 +1,250 @@ +// ============================================================================ +// RynthCore.Engine — UI/Panels/RynthChatPresets.cs +// Canned ("standard") RynthChat filters, modelled on UtilityBelt-IT's +// ChatFilter / Mag ChatFilter categories. Each preset is a tick-box in the +// ChatFilters panel that hides its lines or moves them to a tab. +// +// 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. 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; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; + +namespace RynthCore.Engine.UI.Panels; + +internal static class RynthChatPresets +{ + /// <summary>Which RynthChat channels a preset may match.</summary> + internal enum Scope + { + /// <summary>Anything except Chat / Channels (player-typed text).</summary> + NotPlayerChat, + /// <summary>Only the Combat channel (spell incantations arrive as chat type 0x11 → Combat).</summary> + CombatOnly, + /// <summary>Only the Channels tab (General / Trade / LFG / Roleplay / Society).</summary> + ChannelsOnly, + /// <summary>Every channel.</summary> + Any, + } + + internal sealed class Preset + { + internal string Id { get; } + internal string Group { get; } + internal string Label { get; } + internal string Description { get; } + internal string Example { get; } + internal Scope Where { get; } + internal Regex Pattern { get; } + + // 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) + { + Id = id; + Group = group; + Label = label; + Description = description; + Example = example; + Where = where; + Pattern = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(50)); + } + + /// <summary>True when this preset applies to a line on <paramref name="channel"/> with raw <paramref name="text"/>.</summary> + internal bool Matches(string text, string channel) + { + bool inScope = Where switch + { + Scope.NotPlayerChat => channel is not ("Chat" or "Channels"), + Scope.CombatOnly => channel == "Combat", + Scope.ChannelsOnly => channel == "Channels", + _ => true, + }; + if (!inScope) return false; + try { return Pattern.IsMatch(text); } + catch (RegexMatchTimeoutException) { return false; } + } + } + + // Kill flavour text (retail/ACE death messages). Damage lines ("... for N points of ...") + // share some verbs, so they are excluded up front. + private const string KillPattern = + @"^(?!.* for \d+ points? of )(?:" + + @"You (?:flatten|knock|split|cleave|slay|bring|beat|run|suffocate|smite|killed) .+!" + + @"|.+ is (?:reduced to cinders|torn to ribbons by your assault|shattered by your assault|incinerated by your assault|liquified by your attack|dessicated by your attack)!" + + @"|.+ catches your attack, with dire consequences!" + + @"|.+'s (?:seared corpse smolders before you|last strength dissolves before you)!" + + @"|Electricity tears .+ apart!|Blistered by lightning, .+ falls!" + + @"|Your killing blow nearly turns .+ inside-out!|The thunder of crushing .+ is followed by the deafening silence of death!" + + @"|Your attack stops .+ cold!)"; + + // Optional combat prefixes such as "Critical hit! " / "Sneak Attack! ". + private const string HitPrefix = @"^(?:[A-Z][\w ]{2,20}! )*"; + + private static readonly Preset[] _all = + { + // ── Combat ──────────────────────────────────────────────────────── + new("combat.attack_evades", "Combat", "Your attacks evaded", + "A monster evades your melee or missile attack.", + "Drudge Slinker evaded your attack.", Scope.NotPlayerChat, @" evaded your attack\.\s*$"), + new("combat.defense_evades", "Combat", "You evade attacks", + "You evade a monster's attack.", + "You evaded Drudge Slinker!", Scope.NotPlayerChat, @"^You evaded "), + new("combat.damage_dealt", "Combat", "Damage you deal", + "Your melee, missile and war-spell hits (including critical / sneak attack prefixes).", + "You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat, HitPrefix + @"You .+ for \d+ points? of "), + new("combat.damage_taken", "Combat", "Damage you take", + "Monster hits and spell damage landing on you.", + "Drudge Slinker slashes you for 12 points of slashing damage!", Scope.NotPlayerChat, HitPrefix + @"(?!You ).+ you (?:with .+ )?for \d+ points? of "), + new("combat.attack_resists", "Combat", "Your spells resisted", + "A target resists one of your spells.", + "Drudge Slinker resists your spell", Scope.NotPlayerChat, @" resists your spell"), + new("combat.defense_resists", "Combat", "You resist spells", + "You resist a spell, or a caster was out of range / had no valid target.", + "You resist the spell cast by Drudge Sorcerer", Scope.NotPlayerChat, + @"^You resist the spell cast by |^You have no appropriate target.*spell|^You are an invalid target for the spell|tried to cast a spell on you, but was too far away!"), + new("combat.npk", "Combat", "Not-a-PK failures", + "\"You fail to affect X, you are not a player killer!\" and the mirror message.", + "You fail to affect Bob because you are not a player killer!", Scope.NotPlayerChat, + @"^You fail to affect .+ you are not a player killer!|fails to affect you.+ is not a player killer!"), + new("combat.dirty_fighting", "Combat", "Dirty Fighting procs", + "Dirty Fighting assault announcements.", + "Dirty Fighting! Bob delivers a Traumatic Assault to Drudge!", Scope.NotPlayerChat, @"^Dirty Fighting! .+ delivers a "), + new("combat.monster_deaths", "Combat", "Monster death messages", + "Kill flavour text (\"You flatten…\", \"…is reduced to cinders!\").", + "Drudge Slinker is reduced to cinders!", Scope.NotPlayerChat, KillPattern), + + // ── Casting ─────────────────────────────────────────────────────── + new("cast.mine", "Casting", "Your spell words", + "Your own incantations (\"You say, \\\"Zojak…\\\"\"). Real Local chat is untouched.", + "You say, \"Zojak Equin\"", Scope.CombatOnly, @"^You say, """), + new("cast.others", "Casting", "Others' spell words", + "Incantations from other players and monsters.", + "Bob says, \"Cruath Quareth\"", Scope.CombatOnly, @"^(?!You say).+ says, """), + new("cast.fizzle", "Casting", "Spell fizzles", + "\"Your spell fizzled.\"", + "Your spell fizzled.", Scope.NotPlayerChat, @"^Your spell fizzled\."), + new("cast.components", "Casting", "Component usage", + "\"The spell consumed the following components: …\"", + "The spell consumed the following components: Lead Scarab", Scope.NotPlayerChat, @"^The spell consumed the following components"), + new("cast.self_buffs", "Casting", "Your buff casts", + "\"You cast X on yourself…\" confirmations.", + "You cast Strength Self VII on yourself", Scope.NotPlayerChat, @"^You cast .+ on yourself"), + new("cast.buffs_on_you", "Casting", "Buffs others cast on you", + "\"Bob cast X on you…\" lines from buff bots and fellows.", + "Bob cast Strength Other VII on you", Scope.NotPlayerChat, @"^(?!You ).+ cast .+ on you\b"), + new("cast.expires", "Casting", "Spell expiry", + "\"… has expired.\" — rares (Brilliance / Prodigal / Spectral) are kept.", + "Strength Self VII has expired.", Scope.NotPlayerChat, @"^(?!.*(?:Brilliance|Prodigal|Spectral)).*\b(?:has|have) expired\."), + + // ── Items & utility ─────────────────────────────────────────────── + new("item.heal_ok", "Items", "Healing kit success", + "\"You heal yourself for N Health points…\"", + "You heal yourself for 80 Health points.", Scope.NotPlayerChat, @"^You .*heal yourself for "), + new("item.heal_fail", "Items", "Healing kit failure", + "\"You fail to heal yourself.\"", + "You fail to heal yourself. ", Scope.NotPlayerChat, @"^You fail to heal yourself\."), + new("item.salvage", "Items", "Salvage results", + "\"You obtain … using your knowledge of …\"", + "You obtain 12 Steel (ws 7.00) using your knowledge of Weapon Tinkering.", Scope.NotPlayerChat, @"^You obtain .+ using your knowledge of "), + new("item.salvage_fail", "Items", "Salvage failures", + "\"Salvaging Failed!\" and unsuitable-item notices.", + "Salvaging Failed!", Scope.NotPlayerChat, @"^Salvaging Failed!|The following were not suitable for salvaging: "), + new("item.craftsman", "Items", "Aura of the Craftsman", + "The +5 skill augmentation notice on every craft.", + "Your Aura of the Craftman augmentation increased your skill by 5!", Scope.NotPlayerChat, @"^Your Aura of the Craftman augmentation increased your skill"), + new("item.mana_stone", "Items", "Mana stone usage", + "Mana stone give / drain / destroyed lines.", + "The Mana Stone gives 4,500 points of mana to the following items:", Scope.NotPlayerChat, + @"^The Mana Stone (?:gives|drains) |^You need .+ more mana to fully charge your items\.\s*$|^The .+ is destroyed\.\s*$"), + new("item.regen", "Items", "Periodic healing ticks", + "\"You receive N points of periodic healing.\"", + "You receive 12 points of periodic healing.", Scope.NotPlayerChat, @"^You receive .+ points of periodic healing"), + + // ── Social & trade ──────────────────────────────────────────────── + new("social.bot_spam", "Social", "Trade / buff bot spam", + "Lines ending in the bot tags -t- or -b-.", + "BuffBot says, \"Buffs at the Holtburg lifestone -b-\"", Scope.Any, @"-[tb]-""?\s*$"), + new("social.failed_assess", "Social", "Failed assess on you", + "\"Someone tried and failed to assess you!\"", + "Bob tried and failed to assess you!", Scope.NotPlayerChat, @"tried and failed to assess you!\s*$"), + new("social.kill_task", "Social", "Kill task complete", + "\"You have killed N Xs! Your task is complete!\"", + "You have killed 50 Drudges! Your task is complete!", Scope.NotPlayerChat, @"^You have killed \d+ .+Your task is complete!\s*$"), + new("social.general", "Social", "General channel", + "Everything said on General.", + "[General] Bob says, \"hi\"", Scope.ChannelsOnly, @"^\[General\]|says on the General channel"), + new("social.trade", "Social", "Trade channel", + "Everything said on Trade.", + "[Trade] Bob says, \"WTS\"", Scope.ChannelsOnly, @"^\[Trade\]|says on the Trade channel"), + new("social.lfg", "Social", "LFG channel", + "Everything said on LFG.", + "[LFG] Bob says, \"LF fellow\"", Scope.ChannelsOnly, @"^\[LFG\]|says on the LFG channel"), + new("social.roleplay", "Social", "Roleplay channel", + "Everything said on Roleplay.", + "[Roleplay] Bob says, \"…\"", Scope.ChannelsOnly, @"^\[Roleplay\]|says on the Roleplay channel"), + new("social.society", "Social", "Society channel", + "Everything said on your society channel.", + "[Society] Bob says, \"…\"", Scope.ChannelsOnly, @"^\[(?:Society|Celestial Hand|Eldrytch Web|Radiant Blood)\]|says on the (?:Society|Celestial Hand|Eldrytch Web|Radiant Blood) channel"), + + // ── NPCs ────────────────────────────────────────────────────────── + new("npc.arbitrator", "NPCs", "Master Arbitrator (Colosseum)", + "All Master Arbitrator speech and the fellowship-lock notice.", + "Master Arbitrator tells you, \"You shall be known…\"", Scope.Any, + @"^Master Arbitrator (?:says|tells you)|^Your fellowship is now locked\..*you have 15 minutes to be recruited"), + + // ── Pets (ACE custom combat pets) ───────────────────────────────── + new("pet.hit", "Pets", "Pet hits", + "\"[Pet] … hit …\" outgoing damage.", + "[Pet] Fire Banshee hit Drudge for 40 damage.", Scope.NotPlayerChat, @"^\[Pet\] .+ hit "), + new("pet.evade", "Pets", "Pet attacks evaded", + "\"[Pet] … evaded by …\"", + "[Pet] Fire Banshee's attack was evaded by Drudge.", Scope.NotPlayerChat, @"^\[Pet\] .+ evaded by "), + new("pet.damage_taken", "Pets", "Pet damage taken", + "\"[Pet] … took …\" incoming damage.", + "[Pet] Fire Banshee took 25 damage from Drudge.", Scope.NotPlayerChat, @"^\[Pet\] .+ took "), + new("pet.death", "Pets", "Pet died", + "\"[Pet] Your combat pet … has died.\"", + "[Pet] Your combat pet Fire Banshee has died.", Scope.NotPlayerChat, @"^\[Pet\] Your combat pet .+ has died\.\s*$"), + new("pet.recall_block", "Pets", "Pet recall blocked", + "\"Your pet was in combat recently; you cannot recall it…\"", + "Your pet was in combat recently; you cannot recall it for about 10 seconds.", Scope.NotPlayerChat, + @"^Your pet was in combat recently; you cannot recall it"), + new("pet.overflow", "Pets", "Pet heal overflow", + "\"… receives N excess … from …\" boost overflow.", + "Fire Banshee receives 20 excess health from Heal Other.", Scope.NotPlayerChat, @" receives .+ excess .+ from "), + }; + + private static readonly Dictionary<string, Preset> _byId = + _all.ToDictionary(p => p.Id, StringComparer.OrdinalIgnoreCase); + + /// <summary>Every preset in display order.</summary> + internal static IReadOnlyList<Preset> All => _all; + + /// <summary>Group names in display order.</summary> + internal static IEnumerable<string> Groups => _all.Select(p => p.Group).Distinct(); + + internal static Preset? Get(string id) => _byId.TryGetValue(id, out var p) ? p : null; + + /// <summary>First enabled preset that matches the line, or null.</summary> + internal static Preset? FirstMatch(string text, string channel) + { + foreach (var p in _all) + if (p.Enabled && p.Matches(text, channel)) + return p; + return null; + } + + /// <summary>Tabs named by enabled presets (tab names create tabs implicitly, like custom rules).</summary> + internal static IEnumerable<string> TargetTabs() + => _all.Where(p => p.Enabled && p.Tab.Length > 0).Select(p => p.Tab); +} diff --git a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs index 914160a..df6f44e 100644 --- a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs @@ -333,6 +333,25 @@ internal static class SettingsPanel 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.TraceCategories: + return TraceCategoriesRow(state, row); + case SettingKind.Text: + return TextRow(row.Label, row.GetText?.Invoke(d) ?? string.Empty, row.Hint, v => + { + row.SetText?.Invoke(state.Data, v); + Push(state); + }, row.Tooltip); + case SettingKind.Status: + { + string status = row.GetText?.Invoke(d) ?? string.Empty; + return status.Length == 0 ? null : new TextBlock + { + Text = status, Foreground = ColTeal, FontSize = 11, + TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 2), + }; + } case SettingKind.Note: return new TextBlock { @@ -416,6 +435,53 @@ internal static class SettingsPanel return row; } + /// <summary>Label above a full-width text box; commits on Enter or focus loss when the text changed.</summary> + private static Control TextRow(string label, string value, string? hint, Action<string> onChange, string? tooltip = null) + { + string committed = value; + var box = new StackPanel { Margin = new Thickness(0, 2, 0, 2) }; + box.Children.Add(new TextBlock { Text = label, Foreground = ColTextDim, FontSize = 11, Margin = new Thickness(0, 0, 0, 2) }); + var tb = new TextBox + { + Text = value, + Watermark = hint, + FontSize = 11, + Height = 22, + Padding = new Thickness(4, 2), + Background = ColPanelBg, + Foreground = ColAmber, + BorderBrush = ColBtnBord, + BorderThickness = new Thickness(1), + VerticalContentAlignment = VerticalAlignment.Center, + }; + DisableInnerScroll(tb); + void Commit() + { + string text = tb.Text ?? string.Empty; + if (string.Equals(text, committed, StringComparison.Ordinal)) return; + committed = text; + onChange(text); + } + // Same keyboard gate as the number boxes: typed keys go to Avalonia, not the game. + tb.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true; + tb.LostFocus += (_, _) => + { + Win32Backend.AvaloniaTextInputActive = false; + Commit(); + }; + tb.KeyDown += (_, e) => + { + if (e.Key == Avalonia.Input.Key.Enter) Commit(); + }; + box.Children.Add(tb); + if (tooltip != null) + { + ToolTip.SetTip(box, tooltip); + ToolTip.SetShowDelay(box, 400); + } + return box; + } + private static Control IntRow(string label, int value, int min, int max, int step, Action<int> onChange, string? tooltip = null) { int current = Math.Clamp(value, min, max); @@ -699,6 +765,96 @@ internal static class SettingsPanel return row; } + /// <summary>Label on the left, a single action button on the right.</summary> + private static Control ButtonRow(string label, string buttonText, Action onClick, string? tooltip = null) + { + var btn = new Button + { + Content = buttonText, + FontSize = 10, + Height = 20, + MinWidth = 160, + Padding = new Thickness(4, 1), + Background = ColBtnFill, + Foreground = ColTextDim, + BorderBrush = ColBtnBord, + BorderThickness = new Thickness(1), + HorizontalContentAlignment = HorizontalAlignment.Center, + }; + btn.Click += (_, _) => onClick(); + + var row = new Grid + { + ColumnDefinitions = new ColumnDefinitions("*,Auto"), + Margin = new Thickness(0, 2, 0, 2), + Height = 22, + }; + var lblBlock = new TextBlock { Text = label, Foreground = ColTextDim, FontSize = 11, VerticalAlignment = VerticalAlignment.Center }; + Grid.SetColumn(lblBlock, 0); + Grid.SetColumn(btn, 1); + row.Children.Add(lblBlock); + row.Children.Add(btn); + + if (tooltip != null) + { + ToolTip.SetTip(row, tooltip); + ToolTip.SetShowDelay(row, 400); + } + return row; + } + + /// <summary> + /// [All on] [All off] [ILT Hub on] over a 3-column grid of toggles, one per RynthAi trace + /// category. Each change edits DiagCategories, saves, and rebuilds the tab so the grid redraws. + /// </summary> + private static Control TraceCategoriesRow(PanelState state, SettingRow row) + { + var cats = TraceCategoryLevels.Parse(state.Data.DiagCategories); + if (cats.Count == 0) + return new TextBlock { Text = "Waiting for RynthAi...", Foreground = ColMute, FontSize = 10, Margin = new Thickness(0, 2, 0, 0) }; + + void Save(string levels) + { + state.Data.DiagCategories = levels; + Push(state); + state.Rebuild?.Invoke(); + } + + Button Bulk(string text, Func<string> next) + { + var b = new Button + { + Content = text, FontSize = 10, Height = 20, Padding = new Thickness(6, 1), + Background = ColBtnFill, Foreground = ColTextDim, BorderBrush = ColBtnBord, BorderThickness = new Thickness(1), + }; + b.Click += (_, _) => Save(next()); + return b; + } + + var box = new StackPanel { Margin = new Thickness(0, 2, 0, 2) }; + var buttons = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 0, 0, 4) }; + buttons.Children.Add(Bulk("All on", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", true))); + buttons.Children.Add(Bulk("All off", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", false))); + buttons.Children.Add(Bulk("ILT Hub on", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", true, "Ilt"))); + if (row.Tooltip != null) + { + ToolTip.SetTip(buttons, row.Tooltip); + ToolTip.SetShowDelay(buttons, 400); + } + box.Children.Add(buttons); + + var grid = new Avalonia.Controls.Primitives.UniformGrid { Columns = 3 }; + foreach (var (name, level) in cats) + { + string catName = name; + bool on = level != TraceCategoryLevels.Off; + grid.Children.Add(BoolRow(TraceCategoryLevels.Label(name, level), on, + v => Save(TraceCategoryLevels.Set(state.Data.DiagCategories, catName, v)))); + } + box.Children.Add(grid); + return box; + } + // SimpleTheme wraps TextBox content in a ScrollViewer, and its vertical // scrollbar's up RepeatButton is a filled triangle Path. On these short // (Height=20) single-line numeric fields that scrollbar shows and the diff --git a/src/RynthCore.Engine/UI/RynthAiDashboardState.cs b/src/RynthCore.Engine/UI/RynthAiDashboardState.cs index 31f2692..a39f9a2 100644 --- a/src/RynthCore.Engine/UI/RynthAiDashboardState.cs +++ b/src/RynthCore.Engine/UI/RynthAiDashboardState.cs @@ -6,7 +6,8 @@ // 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 +// drawer; line 11 remote|noremote, the Mini Remote 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 @@ -37,6 +38,7 @@ internal static class RynthAiDashboardState 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 + private static volatile bool _remoteOpen; // the Mini Remote 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; @@ -140,6 +142,19 @@ internal static class RynthAiDashboardState UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); } + /// <summary>The Mini Remote drawer (RynthAi's Mini Remote drawn by the plugin) is open beside the dashboard. Any thread.</summary> + public static bool RemoteOpen + { + get { EnsureLoaded(); return _remoteOpen; } + } + + public static void SetRemoteOpen(bool open) + { + EnsureLoaded(); + _remoteOpen = 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() { @@ -163,6 +178,7 @@ internal static class RynthAiDashboardState 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); + _remoteOpen = lines.Length >= 11 && lines[10].Trim().Equals("remote", StringComparison.OrdinalIgnoreCase); } } catch { /* corrupt cache: start expanded */ } @@ -180,7 +196,8 @@ internal static class RynthAiDashboardState + (_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"); + + (_rangesOpen ? "ranges" : "noranges") + "\n" + (_patrolOpen ? "patrol" : "nopatrol") + "\n" + + (_remoteOpen ? "remote" : "noremote") + "\n"); } catch { /* best-effort */ } } diff --git a/src/RynthCore.Injector/LaunchCommand.cs b/src/RynthCore.Injector/LaunchCommand.cs index 9039176..f1059f4 100644 --- a/src/RynthCore.Injector/LaunchCommand.cs +++ b/src/RynthCore.Injector/LaunchCommand.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; +using RynthCore.Install; namespace RynthCore.Injector; @@ -37,7 +38,7 @@ internal static class LaunchCommand { // The "bulletproof" private AC copy intended for RynthCore launches — a // separate DAT lock domain from the shared Turbine install. - private const string PrivateAcClientPath = @"C:\Games\RynthCore\AcClient\acclient.exe"; + private static readonly string PrivateAcClientPath = Path.Combine(RynthInstallPaths.CoreDir, "AcClient", "acclient.exe"); // Matches LaunchAccountProfile.NoneOption — explicit opt-out of auto-login. private const string NoneOption = "(None — no auto-login)"; diff --git a/src/RynthCore.Injector/Program.cs b/src/RynthCore.Injector/Program.cs index 1333323..918f949 100644 --- a/src/RynthCore.Injector/Program.cs +++ b/src/RynthCore.Injector/Program.cs @@ -2,13 +2,15 @@ using System; using System.IO; using System.Linq; using System.Text; +using RynthCore.Install; namespace RynthCore.Injector; internal static class Program { // Unified log path — must stay in sync with RynthCore.Engine.LogPaths. - private const string UnifiedLogDirectory = @"C:\Games\RynthCore\Logs"; + // Installer-chosen RynthCore folder (falls back to C:\Games\RynthCore). + private static readonly string UnifiedLogDirectory = RynthInstallPaths.CoreLogsDir; private const string UnifiedLogFileName = "RynthCore.log"; private static int Main(string[] args) diff --git a/src/RynthCore.Injector/RynthCore.Injector.csproj b/src/RynthCore.Injector/RynthCore.Injector.csproj index d52d682..b70a802 100644 --- a/src/RynthCore.Injector/RynthCore.Injector.csproj +++ b/src/RynthCore.Injector/RynthCore.Injector.csproj @@ -11,6 +11,8 @@ </PropertyGroup> <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" /> diff --git a/src/RynthCore.Loader/EntryPoint.cs b/src/RynthCore.Loader/EntryPoint.cs index 01fe674..4b76d41 100644 --- a/src/RynthCore.Loader/EntryPoint.cs +++ b/src/RynthCore.Loader/EntryPoint.cs @@ -19,6 +19,7 @@ using System; using System.IO; using System.Runtime.InteropServices; using System.Threading; +using RynthCore.Install; namespace RynthCore.Loader; @@ -31,7 +32,8 @@ public static class EntryPoint // Unified log path — must stay in sync with RynthCore.Engine.LogPaths. // The loader cannot reference the engine assembly (it loads it // dynamically), so the constants are mirrored here. - private const string UnifiedLogDirectory = @"C:\Games\RynthCore\Logs"; + // Installer-chosen RynthCore folder (falls back to C:\Games\RynthCore). + private static readonly string UnifiedLogDirectory = RynthInstallPaths.CoreLogsDir; private const string UnifiedLogFileName = "RynthCore.log"; /// <summary> /// Subdirectory beside the loader where reload-generation copies of the diff --git a/src/RynthCore.Loader/RynthCore.Loader.csproj b/src/RynthCore.Loader/RynthCore.Loader.csproj index f5f41d1..306faee 100644 --- a/src/RynthCore.Loader/RynthCore.Loader.csproj +++ b/src/RynthCore.Loader/RynthCore.Loader.csproj @@ -26,6 +26,11 @@ <Optimize>false</Optimize> </PropertyGroup> + <ItemGroup> + <!-- Install-location resolver (installer-chosen RynthCore / RynthSuite folders). --> + <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" /> diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 07920c2..f90550d 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -162,6 +162,8 @@ public struct RynthCoreApiNative public IntPtr GetTrainingInfoFn; // int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries, int max) -> entries there are public IntPtr RaiseFn; // int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent) -> RaiseResult public IntPtr TrainSkillFn; // int TrainSkill(uint stype, int expectedCredits) -> RaiseResult + // v80: outcome of the latest merge-stack request (cdecl thunk); was v77 on QOL-items + public IntPtr GetMergeStackResultFn; // int GetMergeStackResult(uint src, uint tgt, int* amount, int* ageMs) } /// <summary> diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 88010ac..34b6fc4 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -156,6 +156,8 @@ public readonly unsafe struct RynthCoreHost public bool HasTraining => _api.Version >= 79 && _api.GetTrainingInfoFn != IntPtr.Zero && _api.RaiseFn != IntPtr.Zero && _api.TrainSkillFn != 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. + public bool HasGetMergeStackResult => _api.Version >= 80 && _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; @@ -562,6 +564,37 @@ public readonly unsafe struct RynthCoreHost ((delegate* unmanaged[Cdecl]<uint, uint, int>)_api.MergeStackInternalFn)(sourceObjectId, targetObjectId) != 0; } + /// <summary>Outcome codes returned by <see cref="GetMergeStackResult"/>.</summary> + public static class MergeStackStatus + { + public const int None = 0; // no request recorded for this pair (or it aged out) + public const int Queued = 1; // accepted onto AC's main-thread queue, not executed yet + public const int Sent = 2; // merge sent to the server for 'amount' units + public const int TargetFull = 3; // skipped: the target stack was already full + public const int Failed = 4; // invalid ids, merge API unavailable, AC rejected, or threw + public const int QueueFull = 5; // dropped: main-thread queue full + } + + /// <summary> + /// What happened to the latest <see cref="MergeStackInternal"/> request for this pair + /// (a <see cref="MergeStackStatus"/> code). <paramref name="amount"/> = units sent + /// (Sent only); <paramref name="ageMs"/> = how long ago the outcome was recorded. + /// Returns <see cref="MergeStackStatus.None"/> on engines older than API v68. + /// </summary> + public int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, out int amount, out int ageMs) + { + amount = 0; + ageMs = 0; + if (!HasGetMergeStackResult) + return MergeStackStatus.None; + int a = 0, age = 0; + int status = ((delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)_api.GetMergeStackResultFn)( + sourceObjectId, targetObjectId, &a, &age); + amount = a; + ageMs = age; + return status; + } + /// <summary> /// Gives an item to an NPC or another player by sending the F7B1 give /// GameAction (CM_Inventory::Event_GiveObjectRequest). This is the correct diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index 76cf396..b3336b7 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -33,7 +33,7 @@ <PropertyGroup> <!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. --> - <RynthCoreSdkApiVersion>79</RynthCoreSdkApiVersion> + <RynthCoreSdkApiVersion>80</RynthCoreSdkApiVersion> <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn> </PropertyGroup> diff --git a/src/RynthCore.StatusAgent/AgentConfig.cs b/src/RynthCore.StatusAgent/AgentConfig.cs index 8610076..b0ed556 100644 --- a/src/RynthCore.StatusAgent/AgentConfig.cs +++ b/src/RynthCore.StatusAgent/AgentConfig.cs @@ -1,5 +1,6 @@ using System.Text.Json; using System.Text.Json.Serialization; +using RynthCore.Install; namespace RynthCore.StatusAgent; @@ -27,10 +28,10 @@ internal sealed class AgentConfig [JsonPropertyName("TimeoutSeconds")] public int TimeoutSeconds { get; set; } = 15; /// <summary>Directory holding the engine's per-client status files.</summary> - [JsonPropertyName("StatusDirectory")] public string StatusDirectory { get; set; } = @"C:\Games\RynthCore\Logs\status"; + [JsonPropertyName("StatusDirectory")] public string StatusDirectory { get; set; } = Path.Combine(RynthInstallPaths.CoreLogsDir, "status"); /// <summary>Directory holding per-client RynthCore.<pid>.log files (heartbeat fallback).</summary> - [JsonPropertyName("LogDirectory")] public string LogDirectory { get; set; } = @"C:\Games\RynthCore\Logs"; + [JsonPropertyName("LogDirectory")] public string LogDirectory { get; set; } = RynthInstallPaths.CoreLogsDir; /// <summary>When true and no status file exists for a running client, derive /// basic status from that client's heartbeat log line. Lets the agent work @@ -97,12 +98,12 @@ internal sealed class AgentConfig /// <summary>portal.dat used to decode item icons for GET /icon (read-only inventory viewer). Defaults to /// the RynthCore client's private copy. If the file is absent (e.g. an agent running off the game box) /// /icon 404s and the app falls back to text rows — no other feature is affected.</summary> - [JsonPropertyName("IconDatPath")] public string IconDatPath { get; set; } = @"C:\Games\RynthCore\AcClient\client_portal.dat"; + [JsonPropertyName("IconDatPath")] public string IconDatPath { get; set; } = Path.Combine(RynthInstallPaths.CoreDir, "AcClient", "client_portal.dat"); /// <summary>Directory of RynthAi's baked dungeon floor-plan maps ({landblock:X8}_{layer}.bin), served as /// PNGs via GET /map for the app's dungeon-map viewer. If the folder is absent (agent off the game box) /// /maps returns an empty list and /map 404s — no other feature is affected.</summary> - [JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps"; + [JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = Path.Combine(RynthInstallPaths.RynthAiDir, "Maps"); /// <summary>cell.dat the landscape map (GET /worldmap) is drawn from, once, then cached as worldmap-v1.jpg in /// <see cref="StatusDirectory"/>. Absent = no world map (capabilities.worldMap false); nothing else changes.</summary> diff --git a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj index 31cf6d9..49bc151 100644 --- a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj +++ b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj @@ -30,4 +30,9 @@ <PackageReference Include="SIPSorcery" Version="10.0.14" /> </ItemGroup> + <ItemGroup> + <!-- Install-location resolver (installer-chosen RynthCore / RynthSuite folders). --> + <Compile Include="..\RynthCore.App\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" /> + </ItemGroup> + </Project> diff --git a/tools/HookResolver.UI/RynthCore.HookResolver.UI.csproj b/tools/HookResolver.UI/RynthCore.HookResolver.UI.csproj index 899525f..b034d4f 100644 --- a/tools/HookResolver.UI/RynthCore.HookResolver.UI.csproj +++ b/tools/HookResolver.UI/RynthCore.HookResolver.UI.csproj @@ -11,6 +11,7 @@ <RootNamespace>RynthCore.HookResolver.UI</RootNamespace> <AssemblyName>RynthCore.HookResolver.UI</AssemblyName> <LangVersion>latest</LangVersion> + <Version>1.0.1</Version> </PropertyGroup> <ItemGroup> @@ -18,6 +19,8 @@ <PackageReference Include="Avalonia.Desktop" Version="11.2.3" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" /> <PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.3" /> + <!-- Direct reference overrides Avalonia's transitive 0.20.x (NU1903 / GHSA-xrw6-gwf8-vvr9). --> + <PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" /> </ItemGroup> <ItemGroup> diff --git a/tools/LargeAddressAlignmentTests/LargeAddressAlignmentTests.csproj b/tools/LargeAddressAlignmentTests/LargeAddressAlignmentTests.csproj new file mode 100644 index 0000000..ba581e5 --- /dev/null +++ b/tools/LargeAddressAlignmentTests/LargeAddressAlignmentTests.csproj @@ -0,0 +1,25 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the large-address alignment fix + (src\RynthCore.Engine\Compatibility\LargeAddressAlignmentScan.cs, compiled in): the site scan + against the .text of a real acclient.exe read from disk, idempotence once patched, refusal of + near-miss byte patterns, and the padding arithmetic above and below 2 GB. Nothing native: no + AC process, no engine state. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail); after the usual separator, an AC folder or an acclient.exe. + Default: C:\Turbine\Asheron's Call-ryn\acclient.exe. + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0-windows</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>LargeAddressAlignmentTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\LargeAddressAlignmentScan.cs" Link="Engine\LargeAddressAlignmentScan.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/LargeAddressAlignmentTests/Program.cs b/tools/LargeAddressAlignmentTests/Program.cs new file mode 100644 index 0000000..eec1fa7 --- /dev/null +++ b/tools/LargeAddressAlignmentTests/Program.cs @@ -0,0 +1,154 @@ +using System.Buffers.Binary; +using RynthCore.Engine.Compatibility; + +namespace LargeAddressAlignmentTests; + +/// <summary> +/// The large-address alignment fix, offline: which acclient code the scan picks, that a patched +/// image rescans as fully patched, that look-alike bytes are refused, and that the patched +/// remainder pads a cursor above 2 GB the same as below it. +/// </summary> +internal static class Program +{ + private static int _checks, _failed; + + private static int Main(string[] args) + { + string exe = FindExe(args.Length > 0 ? args[0] : @"C:\Turbine\Asheron's Call-ryn"); + RealClient(exe); + SyntheticPatterns(); + PaddingArithmetic(); + Console.WriteLine(); + Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks failed)"); + return _failed == 0 && _checks > 0 ? 0 : 1; + } + + private static string FindExe(string arg) => + File.Exists(arg) ? arg : Path.Combine(arg, "acclient.exe"); + + private static void RealClient(string path) + { + Section("acclient .text from " + path); + if (!File.Exists(path)) + { + Check(false, "acclient.exe exists"); + return; + } + + byte[] image = File.ReadAllBytes(path); + Check(TryReadText(image, out int textVa, out byte[] text), ".text section read"); + if (text.Length == 0) return; + + List<AlignmentSite> sites = LargeAddressAlignmentScan.Find(text, textVa); + Console.WriteLine($" {sites.Count} site(s), first 0x{sites.FirstOrDefault().AndVa:X8}, last 0x{sites.LastOrDefault().AndVa:X8}"); + Check(sites.Count == 190, "retail client has 190 padding sites"); + Check(sites.All(s => !s.AlreadyPatched), "none patched on disk"); + + // MotionData::UnPack (kelpie's 0x09000009 corruption) and the setup unpack under the + // 0x539153 crashes, plus the one site with a pop before its je. + foreach (int va in new[] { 0x005271A6, 0x00534B48, 0x00534C96, 0x00532E78, 0x004FD1B6, 0x006B394E }) + Check(sites.Any(s => s.AndVa == va), $"0x{va:X8} found"); + // A 16-bit ring index (movzx, never negative), not cursor padding: no trailing je. + Check(sites.All(s => s.AndVa != 0x00547029), "0x00547029 (ring index) left alone"); + + foreach (AlignmentSite s in sites) + text[s.ImmHighByteVa - textVa] = LargeAddressAlignmentScan.PatchedHighByte; + List<AlignmentSite> again = LargeAddressAlignmentScan.Find(text, textVa); + Check(again.Count == sites.Count && again.All(s => s.AlreadyPatched), "patched image rescans as all already patched"); + Check(again.Select(s => s.AndVa).SequenceEqual(sites.Select(s => s.AndVa)), "same sites after patching"); + } + + private static void SyntheticPatterns() + { + Section("synthetic byte patterns"); + // and eax, 0x80000003 ; jns +5 ; dec eax ; or eax, -4 ; inc eax ; je +0x18 + byte[] eax = { 0x25, 0x03, 0x00, 0x00, 0x80, 0x79, 0x05, 0x48, 0x83, 0xC8, 0xFC, 0x40, 0x74, 0x18 }; + Check(Scan(eax).Count == 1, "eax short form matches"); + Check(Scan(eax)[0].ImmHighByteVa == 0x1000 + 4, "immediate high byte located"); + + // and ecx, 0x80000003 ; mov [esp+0xC], eax ; jns ; dec ecx ; or ecx, -4 ; inc ecx ; pop ebx ; je + byte[] ecxGap = { 0x81, 0xE1, 0x03, 0x00, 0x00, 0x80, 0x89, 0x44, 0x24, 0x0C, 0x79, 0x05, 0x49, 0x83, 0xC9, 0xFC, 0x41, 0x5B, 0x74, 0x10 }; + Check(Scan(ecxGap).Count == 1 && Scan(ecxGap)[0].Register == 1, "ecx long form with gap and pop matches"); + + byte[] noJe = (byte[])eax.Clone(); + noJe[12] = 0x66; + Check(Scan(noJe).Count == 0, "no trailing je: refused"); + + byte[] wrongReg = (byte[])eax.Clone(); + wrongReg[7] = 0x49; // dec ecx after and eax + Check(Scan(wrongReg).Count == 0, "fix-up on another register: refused"); + + byte[] otherMask = (byte[])eax.Clone(); + otherMask[1] = 0x07; // % 8 + Check(Scan(otherMask).Count == 0, "and 0x80000007: refused"); + + byte[] patched = (byte[])eax.Clone(); + patched[4] = 0x00; + Check(Scan(patched) is [{ AlreadyPatched: true }], "and eax, 3 reported as already patched"); + } + + private static void PaddingArithmetic() + { + Section("padding above and below 2 GB"); + foreach (uint cursor in new uint[] { 0x2FDC98E1, 0x2FDC98E3, 0x80438035, 0x80438036, 0x8043A4C3, 0xFFFFFFFD }) + { + int stock = StockPad(cursor), fixedPad = FixedPad(cursor); + Check((cursor + (uint)fixedPad) % 4 == 0 && fixedPad < 4, $"0x{cursor:X8}: patched pad {fixedPad} aligns"); + if (cursor < 0x80000000) + Check(stock == fixedPad, $"0x{cursor:X8}: below 2 GB the patch changes nothing"); + else + Check(stock == fixedPad + 4, $"0x{cursor:X8}: stock pad {stock} overshoots by 4"); + } + } + + // AC's code: r = and(ptr, 0x80000003) with the sign fix-up, pad = r == 0 ? 0 : 4 - r. + private static int StockPad(uint cursor) + { + int r = (int)cursor % 4; + return r == 0 ? 0 : 4 - r; + } + + private static int FixedPad(uint cursor) + { + int r = (int)(cursor & 3); + return r == 0 ? 0 : 4 - r; + } + + private static List<AlignmentSite> Scan(byte[] code) + { + byte[] padded = new byte[code.Length + 64]; + code.CopyTo(padded, 0); + return LargeAddressAlignmentScan.Find(padded, 0x1000); + } + + private static bool TryReadText(byte[] image, out int textVa, out byte[] text) + { + textVa = 0; + text = Array.Empty<byte>(); + int pe = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(0x3C)); + int sections = BinaryPrimitives.ReadUInt16LittleEndian(image.AsSpan(pe + 6)); + int optSize = BinaryPrimitives.ReadUInt16LittleEndian(image.AsSpan(pe + 20)); + int imageBase = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(pe + 24 + 28)); + for (int i = 0; i < sections; i++) + { + int s = pe + 24 + optSize + i * 40; + if (System.Text.Encoding.ASCII.GetString(image, s, 8).TrimEnd('\0') != ".text") continue; + int virtualSize = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 8)); + int rva = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 12)); + int rawOffset = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 20)); + textVa = imageBase + rva; + text = image.AsSpan(rawOffset, virtualSize).ToArray(); + return true; + } + return false; + } + + private static void Section(string name) => Console.WriteLine($"\n== {name}"); + + private static void Check(bool ok, string what) + { + _checks++; + if (!ok) _failed++; + Console.WriteLine($" {(ok ? "ok " : "FAIL")} {what}"); + } +} diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index 5e63ac9..5e0ea72 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -468,11 +468,11 @@ internal static class Program Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingEntryNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingEntryNative>(f.Name), "TrainingEntryNative." + f.Name + " offset"); Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); - // The three v79 slots are the table's last three, in this order. - var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).TakeLast(3).ToArray(); - Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn" }), "v79 slots last: " + string.Join(",", names)); - var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).TakeLast(3).ToArray(); - Check(sdkNames.SequenceEqual(names), "SDK v79 slots in the same order"); + // The three v79 slots, then v80's GetMergeStackResultFn, end the table in this order. + var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).TakeLast(4).ToArray(); + Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetMergeStackResultFn" }), "v79 then v80 slots last: " + string.Join(",", names)); + var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).TakeLast(4).ToArray(); + Check(sdkNames.SequenceEqual(names), "SDK v79 and v80 slots in the same order"); } private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { }