RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:27 -04:00
commit a24ed6df7c
322 changed files with 83009 additions and 7504 deletions

1
.gitignore vendored
View file

@ -49,3 +49,4 @@ installer/Releases/
# Process Monitor / debug log dumps (session junk)
*.PML
Logfile*.XML
out/

View file

@ -9,6 +9,35 @@ RynthCore is the injection framework. RynthSuite (separate repo) contains the pl
- Visual Studio 2022 Build Tools with the **.NET desktop** and **C++ desktop** workloads (required by the NativeAOT ILC linker)
- Asheron's Call client installed
## The unloadable engine (the default since 2026-09-29)
The engine now runs on CoreCLR, and a hot reload really frees the old engine and its plugins
(`docs/UNLOADABLE_ENGINE_PLAN.md`, Status section). What ships and deploys:
```
C:\Games\RynthCore\Runtime\
├── RynthCore.Loader.dll ← native loader (native\Loader, C/cl.exe): injection target, hosts CoreCLR once
├── RynthCore.Shim.dll ← the only RynthCore code in CoreCLR's default context
├── RynthCore.Engine.dll(+pdb)← the engine, a managed assembly (-p:EngineHost=coreclr, ReadyToRun)
├── Avalonia.*, ImGui.NET ... ← the engine's own dependencies (load and unload with each engine)
├── cimgui, minhook, Skia ... ← native libraries (loaded once)
└── dotnet\ ← the app-local x86 .NET runtime (from the NuGet runtime pack)
C:\Games\RynthSuite\<Plugin>\ ← each plugin as a managed assembly + its dependency DLLs
```
| Task | Command |
|---|---|
| Full local deploy (engine, loader, managed plugins, launcher) | `scripts\Deploy-RynthCore.ps1` (close every client first; `-SkipLauncher` while the launcher runs) |
| Engine change, clients running | `scripts\Publish-EngineCoreClr.ps1 -EngineOnly` — each running client hot-reloads onto it by itself |
| Loader/Shim change, clients running | `scripts\Publish-EngineCoreClr.ps1` — the in-use copies are renamed aside; new launches get the new ones |
| Installer | `installer\Build-Installer.ps1` (release plugins stay NativeAOT: the new engine loads them) |
| Hot-reload test on a local server | `scripts\Test-ClrWorld.ps1 -Reloads 3` (see its header) |
| Why didn't a generation unload? | `tools\AlcRoots <pid>` (build it: `dotnet build tools\AlcRoots -c Release`) |
`-NativeAot` on `Deploy-RynthCore.ps1` and `Build-Installer.ps1` builds the old NativeAOT engine,
loader and plugins; the sections below describe that path. The engine and plugins use the same
source either way. Rules that keep an engine or plugin unloadable are in `CLAUDE.md` ("Unloadable engine").
## Projects
| Project | Type | Output |
@ -92,7 +121,7 @@ C:\Games\RynthCore\
├── RynthCore.Loader.dll ← Loader (NativeAOT x86) — injection target
├── RynthCore.Engine.dll ← Engine (NativeAOT x86)
├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint
├── cimgui.dll ← ImGui C bindings (x86, docking branch)
├── cimgui.dll ← ImGui C bindings (x86, docking branch; our build)
└── Plugins\
└── *.dll ← Built-in plugin directory
@ -162,7 +191,7 @@ If AC is already running, click **RL** on the RynthCore overlay bar to hot-reloa
| `Runtime\RynthCore.Loader.dll` | small (~1–2 MB) | NativeAOT didn't run — check for `Generating native code` in build output |
| `Runtime\RynthCore.Engine.dll` | ~26 MB | NativeAOT didn't run — same diagnosis |
| `RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` | ~7 MB | Built `dotnet build` instead of `dotnet publish` |
| `Runtime\cimgui.dll` | ~1.5 MB | Must match ImGui.NET 1.91.6.1 |
| `Runtime\cimgui.dll` | ~1.2 MB | Must be our build (`scripts\Build-Cimgui.ps1`); with ImGui on, the log shows `ImGuiSelfTest: OK` |
To confirm NativeAOT actually ran, check that `.lib` and `.exp` files exist alongside the DLL in the publish output's `native\` directory.
@ -235,6 +264,7 @@ If your AC client ever gets a real-world patch, apply it to both copies (or `rob
- **Clean before plugin publish.** Incremental NativeAOT builds can silently reuse stale output. Delete `obj\Release` and `bin\Release` before every plugin publish to guarantee a fresh compile.
- **Engine deploy path is `Runtime\`**, not `C:\Games\RynthCore\` directly. The injector resolves `Runtime\RynthCore.Loader.dll` (preferred) and `Runtime\RynthCore.Engine.dll` (legacy) by default.
- **Close AC before redeploying Loader or Engine.** Both are loaded into `acclient.exe` and locked while the game is running. Plugins are shadow-copied so they can be hot-swapped without closing AC.
- **cimgui.dll version must match ImGui.NET NuGet.** Post-1.90 struct layouts changed. A mismatched cimgui.dll causes `DisplaySize = <1, 1>` or font crashes on frame 2.
- **cimgui.dll is built by us, not taken from NuGet.** `scripts\Build-Cimgui.ps1` fetches cimgui 1.91.6dock into `native\cimgui\_src` (git-ignored), builds it with MSVC (VS 2022 Build Tools, C++ workload) and writes `src\RynthCore.Engine\Native\cimgui.dll`, which is committed. The stock NuGet x86 DLL does not match ImGui.NET's structs (64-bit `ImTextureID`); the engine's `ImGuiSelfTest` refuses it and any other non-matching build. Only rerun the script when changing the cimgui build itself.
- **vswhere.exe must be on PATH** for the NativeAOT link step. Add `C:\Program Files (x86)\Microsoft Visual Studio\Installer` to PATH if missing.
- **Decal coexistence mode.** If `decal.dll`, `UBLoader.dll`, `Decal.Adapter.dll`, or `phatacd.dll` is loaded into acclient.exe, the engine skips the entire D3D9/ImGui path and runs plugins on a 30 Hz worker tick with Avalonia floating panels via `LayeredWindow` (GDI). This is intentional — two D3D9 hookers can't symmetrically save/restore render state. Check `RynthCore.log` for `D3D9: Decal coexistence` to confirm.
- **Decal.** `src\RynthCore.DecalBridge` (net48) builds with the solution when Decal is installed (an empty assembly and a warning otherwise); every installer stages it (`Build-Installer.ps1` fails without Decal; `-SkipDecalBridge` for a dev build). The launcher registers it only for accounts set to "Decal + RynthCore (experimental)"; their choice is kept in `%APPDATA%\RynthCore\decal-accounts.json`, never in the shared `appsettings.json`. Bridge mode and in-game ImGui under Decal: `docs/DECAL_BRIDGE_PLAN.md`.
- **Decal coexistence mode.** If `decal.dll`, `UBLoader.dll`, `Decal.Adapter.dll`, or `phatacd.dll` is loaded into acclient.exe and neither bridge mode nor `DecalInGameImGui` applies, the engine skips the entire D3D9/ImGui path and runs plugins on a 30 Hz worker tick with Avalonia floating panels via `LayeredWindow` (GDI). This is intentional — two D3D9 hookers can't symmetrically save/restore render state. Check `RynthCore.log` for `D3D9: Decal coexistence` to confirm.

View file

@ -2,7 +2,7 @@
RynthCore is a modern .NET 10 modding host for Asheron's Call. It combines an x86 NativeAOT in-process engine, a hot-reload-capable loader, an injector, an Avalonia desktop launcher, and a plugin surface that replaces the legacy Decal + UBService + VTank stack with a self-contained RynthCore-native API.
The plugin code (RynthAi etc.) lives in a sibling repository: [RynthSuite](https://github.com/tombohar/RynthSuite).
The plugin code (RynthAi etc.) lives in a sibling repository: [RynthSuite](https://aelrynth.com/git/rynth/RynthSuite).
## What it does
@ -86,7 +86,7 @@ For full deploy details, the Inno Setup installer, and gotchas, see [`BUILD.md`]
## Repository notes
- Local settings, machine-specific files, generated `bin/`, `obj/`, `.vs/`, `.dotnet-home/` content, and launcher data (profiles, runtime state) are kept out of source control via `.gitignore`
- Plugin code lives in the [RynthSuite](https://github.com/tombohar/RynthSuite) repo as a sibling clone
- Plugin code lives in the [RynthSuite](https://aelrynth.com/git/rynth/RynthSuite) repo as a sibling clone
## Security and secrets

View file

@ -1,4 +1,4 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
@ -27,6 +27,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.Core
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.UI", "tools\HookResolver.UI\RynthCore.HookResolver.UI.csproj", "{C1A2B3D4-0009-0009-0009-000000000009}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.DecalBridge", "src\RynthCore.DecalBridge\RynthCore.DecalBridge.csproj", "{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
@ -121,6 +123,18 @@ Global
{C1A2B3D4-0007-0007-0007-000000000007}.Release|Any CPU.Build.0 = Release|Any CPU
{C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.ActiveCfg = Release|Any CPU
{C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.Build.0 = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.ActiveCfg = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.Build.0 = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.ActiveCfg = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.Build.0 = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.ActiveCfg = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.Build.0 = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.Build.0 = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.ActiveCfg = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.Build.0 = Release|Any CPU
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.ActiveCfg = Debug|Any CPU
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.Build.0 = Debug|Any CPU
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
@ -145,18 +159,18 @@ Global
{C1A2B3D4-0009-0009-0009-000000000009}.Release|Any CPU.Build.0 = Release|Any CPU
{C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.ActiveCfg = Release|Any CPU
{C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.Build.0 = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.ActiveCfg = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.Build.0 = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.ActiveCfg = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.Build.0 = Debug|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.ActiveCfg = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.Build.0 = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.Build.0 = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.ActiveCfg = Release|Any CPU
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.Build.0 = Release|Any CPU
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x86.ActiveCfg = Debug|x86
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x86.Build.0 = Debug|x86
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x64.ActiveCfg = Debug|Any CPU
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x64.Build.0 = Debug|Any CPU
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x86.ActiveCfg = Release|x86
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x86.Build.0 = Release|x86
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|Any CPU.Build.0 = Release|Any CPU
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x64.ActiveCfg = Release|Any CPU
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -168,5 +182,6 @@ Global
{C1A2B3D4-0007-0007-0007-000000000007} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{C1A2B3D4-0008-0008-0008-000000000008} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}
{C1A2B3D4-0009-0009-0009-000000000009} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
EndGlobalSection
EndGlobal

34
THIRD-PARTY-NOTICES.md Normal file
View file

@ -0,0 +1,34 @@
# Third-party notices
RynthCore ships the following third-party material inside its own files.
## Phosphor Icons
- What: the Phosphor icon font (`Phosphor.ttf`, version 2.1, regular weight), used for the icons in the ImGui panels.
- Where: `src/RynthCore.Engine/Assets/Fonts/Phosphor.ttf`, embedded in `RynthCore.Engine.dll` as a resource.
- Source: https://phosphoricons.com (Tobias Fried and Helena Zhang)
- Licence: MIT, reproduced below and in `src/RynthCore.Engine/Assets/Fonts/Phosphor.LICENSE`.
```
MIT License
Copyright (c) 2020-2021 Phosphor Icons
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

View file

@ -5,12 +5,18 @@
.DESCRIPTION
1. Publishes the Avalonia launcher (self-contained, x86)
2. Publishes RynthCore.Engine (NativeAOT, x86 -- ~2 min)
3. Publishes RynthCore.Loader (NativeAOT, x86) -- the DLL the launcher injects
4. Publishes RynthCore.Plugin.RynthAi (NativeAOT, 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 checks every required runtime file is there
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
.PARAMETER Configuration
@ -32,7 +38,19 @@ param(
# Version string injected into the installer (e.g. "0.3"). When omitted,
# the version defined in RynthCore.iss is used as-is.
[string]$Version = "",
[switch]$SkipBuild
[switch]$SkipBuild,
# 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).
[switch]$SkipDecalBridge,
# Old opt-in switch, kept so existing command lines still work; the bridge is the default now.
[switch]$IncludeDecalBridge,
# Decal's install folder, when not the default C:\Program Files (x86)\Decal 3.0.
[string]$DecalDir = ""
)
$ErrorActionPreference = "Stop"
@ -80,7 +98,7 @@ $LootEditorPublish = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\bin\$Configurat
$StagingDir = "$ScriptDir\staging\app"
# ── Validate projects ───────────────────────────────────────────────────────
foreach ($p in @($LauncherProject, $EngineProject, $LoaderProject, $PluginProject, $LootEditorProject)) {
foreach ($p in @($LauncherProject, $EngineProject, $PluginProject, $LootEditorProject) + @(if ($NativeAot) { $LoaderProject })) {
if (-not (Test-Path $p)) {
throw "Project not found: $p`nUpdate paths in Build-Installer.ps1 if your repo layout differs."
}
@ -93,17 +111,20 @@ if (-not $SkipBuild) {
dotnet publish $LauncherProject -c $Configuration -r win-x86 --self-contained true @VersionArgs
if ($LASTEXITCODE -ne 0) { throw "Launcher publish failed (exit $LASTEXITCODE)" }
# ── 2. Engine (NativeAOT — the slow one) ──────────────────────────────────
Write-Host ""
Write-Host "[2/5] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan
dotnet publish $EngineProject -c $Configuration @VersionArgs
if ($LASTEXITCODE -ne 0) { throw "Engine publish failed (exit $LASTEXITCODE)" }
if ($NativeAot) {
# ── 2. Engine (NativeAOT — the slow one) ──────────────────────────────
Write-Host ""
Write-Host "[2/5] 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
dotnet publish $LoaderProject -c $Configuration @VersionArgs
if ($LASTEXITCODE -ne 0) { throw "Loader publish failed (exit $LASTEXITCODE)" }
# ── 3. Loader (NativeAOT, small) ──────────────────────────────────────
Write-Host ""
Write-Host "[3/5] 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) ─────────────────────────────────────────────────
Write-Host ""
@ -143,18 +164,30 @@ foreach ($file in (Get-ChildItem "$LauncherPublish" -File)) {
Copy-Item $file.FullName "$StagingDir\$destName" -Force
}
# Engine runtime files (into Runtime\, skip .pdb)
foreach ($file in (Get-ChildItem "$EnginePublish" -File)) {
if ($file.Extension -eq '.pdb') { continue }
Copy-Item $file.FullName "$StagingDir\Runtime\$($file.Name)" -Force
}
if ($NativeAot) {
# Engine runtime files (into Runtime\, skip .pdb)
foreach ($file in (Get-ChildItem "$EnginePublish" -File)) {
if ($file.Extension -eq '.pdb') { continue }
Copy-Item $file.FullName "$StagingDir\Runtime\$($file.Name)" -Force
}
# Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it
# maps RynthCore.Engine.dll and provides hot-reload. Without it a fresh install's
# launcher can't auto-find an engine to inject.
$loaderDll = "$LoaderPublish\RynthCore.Loader.dll"
if (-not (Test-Path $loaderDll)) { throw "Loader DLL not found at: $loaderDll" }
Copy-Item $loaderDll "$StagingDir\Runtime\" -Force
# Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it
# maps RynthCore.Engine.dll and provides hot-reload. Without it a fresh install's
# launcher can't auto-find an engine to inject.
$loaderDll = "$LoaderPublish\RynthCore.Loader.dll"
if (-not (Test-Path $loaderDll)) { throw "Loader DLL not found at: $loaderDll" }
Copy-Item $loaderDll "$StagingDir\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
# 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
}
# SEH trampoline — hand-built native DLL (native\SehTrampoline\Build-SehTrampoline.ps1),
# NOT part of the engine publish output. Without it SehTrampoline.IsAvailable stays
@ -169,8 +202,8 @@ if ((Test-Path $sehSrc) -and (Get-Item $sehSrc).LastWriteTime -gt (Get-Item $seh
}
Copy-Item $sehDll "$StagingDir\Runtime\" -Force
# Engine Native subfolder
if (Test-Path "$EnginePublish\Native") {
# Engine Native subfolder (NativeAOT layout)
if ($NativeAot -and (Test-Path "$EnginePublish\Native")) {
foreach ($file in (Get-ChildItem "$EnginePublish\Native" -File)) {
if ($file.Extension -eq '.pdb') { continue }
Copy-Item $file.FullName "$StagingDir\Runtime\Native\$($file.Name)" -Force
@ -196,6 +229,38 @@ foreach ($dir in (Get-ChildItem "$LootEditorPublish" -Directory)) {
Get-ChildItem "$StagingDir\Tools\LootEditor\$($dir.Name)" -Recurse -File -Filter '*.pdb' | Remove-Item -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.
if ($SkipDecalBridge) {
Write-Warning "-SkipDecalBridge: this build has no Decal bridge; 'Decal + RynthCore' accounts can't launch with it. Not for a release."
} else {
Write-Host ""
Write-Host "Building the Decal bridge (net48 x86, against Decal's reference assemblies)..." -ForegroundColor Cyan
$bridgeProject = "$RepoRoot\src\RynthCore.DecalBridge\RynthCore.DecalBridge.csproj"
$bridgeDll = "$RepoRoot\src\RynthCore.DecalBridge\bin\$Configuration\RynthCore.DecalBridge.dll"
$decalArgs = @("-p:RequireDecal=true")
if ($DecalDir) { $decalArgs += "-p:DecalDir=$DecalDir" }
# A DLL left over from an earlier build must never be shipped in place of this one.
Remove-Item $bridgeDll -Force -ErrorAction SilentlyContinue
if (Test-Path $bridgeDll) { throw "Could not remove the old $bridgeDll (in use by a Decal client?)" }
dotnet build $bridgeProject -c $Configuration -nologo -v q @decalArgs @VersionArgs
if ($LASTEXITCODE -ne 0) { throw "Decal bridge build failed (exit $LASTEXITCODE). Is Decal 3.0 installed? (-DecalDir for another folder, -SkipDecalBridge for a dev build)" }
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" })
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
@ -210,6 +275,16 @@ $required = @(
"$StagingDir\Runtime\cimgui.dll",
"$pluginStagingDir\RynthAi\RynthCore.Plugin.RynthAi.dll"
)
if (-not $NativeAot) {
$required += @(
"$StagingDir\Runtime\RynthCore.Shim.dll",
"$StagingDir\Runtime\dotnet\coreclr.dll",
"$StagingDir\Runtime\dotnet\System.Private.CoreLib.dll"
)
}
if (-not $SkipDecalBridge) {
$required += "$StagingDir\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 ")" }

View file

@ -7,7 +7,8 @@
One command per release:
1. Refuses if the signing key isn't set up or isn't trusted by the launcher being shipped,
if either repo has uncommitted changes, or if -Version isn't newer than the live feed.
2. Builds the installer (Build-Installer.ps1 -Version) and the RynthSuite plugins into
2. Builds the installer (Build-Installer.ps1 -Version; it includes the Decal bridge, so the
build machine needs Decal installed) and the RynthSuite plugins into
installer\Releases\<release>\ — never into the live C:\Games folders.
3. Writes the manifest (sizes + SHA-256 of every file), signs it with the DPAPI key
(Sign-Update.ps1, no prompt) and checks the signature the way the launcher will.
@ -37,7 +38,12 @@ param(
[string]$BaseUrl = "https://aelrynth.com/downloads/rynth",
[string]$KeyDir = (Join-Path $env:USERPROFILE ".rynthcore-update-signing"),
[string]$RynthSuiteRoot = "",
[string]$TrustFile = "" # defaults to the launcher's UpdateTrust.cs; override for tests
[string]$TrustFile = "", # defaults to the launcher's UpdateTrust.cs; override for tests
# RynthNav's data shipped to launchers as the signed "navdata" archive: tiles (nav_XXXX.tile),
# portals.tsv and locations.json from this folder. Only re-uploaded when the set changes
# (its id is a hash of every file); otherwise the live feed's entry is carried over.
[string]$NavDataDir = "C:\Games\RynthCore\NavData",
[switch]$SkipNavData # leave navdata out of this feed (launchers then keep what they have)
)
$ErrorActionPreference = "Stop"
@ -48,6 +54,7 @@ if (-not $TrustFile) { $TrustFile = Join-Path $RepoRoot "src\RynthCore.App.Avalo
function Step($m) { Write-Host ""; Write-Host "== $m" -ForegroundColor Cyan }
function Sha256([string]$path) { (Get-FileHash $path -Algorithm SHA256).Hash.ToLowerInvariant() }
function Sha256Text([string]$text) { [Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($text))).ToLowerInvariant() }
# Same check as RynthUpdater.VerifyEnvelope: any trusted key's signature over the payload bytes.
function Test-Envelope([string]$path, [string[]]$keys) {
@ -99,9 +106,11 @@ if (-not $AllowDirty) {
Write-Host " RynthCore $(git -C $RepoRoot rev-parse --short HEAD), RynthSuite $(git -C $RynthSuiteRoot rev-parse --short HEAD)"
}
$liveManifest = $null
try {
$live = Invoke-RestMethod "$BaseUrl/update.json" -TimeoutSec 20
$liveRelease = ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($live.payload)) | ConvertFrom-Json).release
$liveManifest = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($live.payload)) | ConvertFrom-Json
$liveRelease = $liveManifest.release
if ($release -le $liveRelease) { throw "Release $release is not newer than the live feed's $liveRelease — bump -Version." }
Write-Host " live feed is at $liveRelease; publishing $release"
} catch [Microsoft.PowerShell.Commands.HttpResponseException] {
@ -116,10 +125,16 @@ 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\"
$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision"
$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory"
foreach ($name in $suitePlugins) {
Step "Building $name"
$proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj"
@ -134,11 +149,26 @@ $zipRoot = "$rel\build\zip"
foreach ($name in $suitePlugins) {
New-Item -ItemType Directory -Force "$zipRoot\RynthSuite\$name" | Out-Null
Copy-Item "$rel\plugins\RynthCore.Plugin.$name.dll" "$zipRoot\RynthSuite\$name\"
# Third-party licence notices travel with the plugin (RynthOracle: Oracle of Dereth, MIT).
$notice = "$rel\build\$name\THIRD_PARTY_NOTICES.md"
if (Test-Path $notice) { Copy-Item $notice "$zipRoot\RynthSuite\$name\" }
}
$navSrc = "C:\Games\RynthCore\NavData"
$navSrc = $NavDataDir
New-Item -ItemType Directory -Force "$zipRoot\RynthCore\NavData" | Out-Null
Get-ChildItem $navSrc -File | Where-Object { $_.Extension -eq ".tile" -or $_.Name -eq "portals.tsv" } |
# The route planner's portals.tsv and the Atlas's locations.json (both made by
# tools\navdata\gen_locations.py from the world database), and the Town Network's townnet.json
# (tools\navdata\Build-TownNet.ps1: the world database plus the walks inside from the dats).
# Never the player's own files
# there (atlas.txt, recalls.txt, _player.txt). The tiles are no longer in this zip (the whole
# world is ~40,000 of them): the launcher installs them from the feed's navdata archive.
Get-ChildItem $navSrc -File | Where-Object { $_.Name -eq "portals.tsv" -or $_.Name -eq "locations.json" -or $_.Name -eq "townnet.json" } |
Copy-Item -Destination "$zipRoot\RynthCore\NavData\"
if (-not (Test-Path "$navSrc\locations.json")) {
Write-Warning "NavData has no locations.json: RynthNav's Atlas ships empty. Run tools\navdata\gen_locations.py and copy its output there."
}
if (-not (Test-Path "$navSrc\townnet.json")) {
Write-Warning "NavData has no townnet.json: routes won't use the Town Network. Run tools\navdata\Build-TownNet.ps1 and copy its townnet.json there."
}
@"
RynthSuite plugins for RynthCore (Asheron's Call, retail client) - $Version
@ -147,28 +177,108 @@ Extract this zip into C:\Games - it creates:
C:\Games\RynthSuite\RynthNav\ RynthNav plugin
C:\Games\RynthSuite\RynthTracker\ RynthTracker plugin
C:\Games\RynthSuite\RynthVision\ RynthVision plugin
C:\Games\RynthCore\NavData\ RynthNav's baked navmesh tiles
C:\Games\RynthSuite\RynthLua\ RynthLua plugin (Lua scripting; was part of RynthAi)
C:\Games\RynthSuite\RynthOracle\ RynthOracle plugin (quests, character, titles; based on Oracle of Dereth by Advis Eveldan)
C:\Games\RynthSuite\RynthInventory\ RynthInventory plugin (search every character's items)
C:\Games\RynthCore\NavData\ RynthNav's portals and Atlas
Then, in the RynthCore launcher's Plugins tab, add the full path of each
plugin DLL you want. Install RynthCore first (RynthCore-Setup.exe), which
also installs RynthAi and the Loot Editor. After that the launcher keeps
the plugins up to date by itself.
the plugins up to date by itself, and once RynthNav is in the list it also
downloads RynthNav's navmesh tiles into C:\Games\RynthCore\NavData.
MIT licensed. https://aelrynth.com/projects.html
"@ -replace "`n", "`r`n" | Set-Content "$zipRoot\README.txt" -NoNewline
Compress-Archive -Path "$zipRoot\*" -DestinationPath "$rel\RynthSuite-Plugins.zip" -CompressionLevel Optimal
# RynthNav's data for the launchers (RynthUpdater.NavData.cs): one archive, flat, only the file
# names RynthNav reads. Its id is a hash over every file's name and SHA-256, so an unchanged
# set reuses the live entry (and the archive already on the server) instead of re-uploading.
$navData = $null
$navZip = $null
if (-not $SkipNavData) {
Step "RynthNav data (tiles, route graph, portals, Atlas, Town Network) from $NavDataDir"
$navFiles = @(Get-ChildItem $NavDataDir -File | Where-Object { $_.Name -match '^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json)$' } | Sort-Object Name)
$tileCount = @($navFiles | Where-Object { $_.Extension -eq ".tile" }).Count
if ($tileCount -eq 0) { throw "$NavDataDir has no tiles. Pass -NavDataDir, or -SkipNavData to publish without them." }
# The long-range route graph (RynthNav.Baker --graph) must come from these very tiles: the
# plugin ignores a graph whose tiles don't match (long gotos then walk the straight line).
$graph = $navFiles | Where-Object { $_.Name -eq "navgraph.bin" }
$newestTile = ($navFiles | Where-Object { $_.Extension -eq ".tile" } | Measure-Object LastWriteTimeUtc -Maximum).Maximum
if (-not $graph) { Write-Warning "No navgraph.bin in ${NavDataDir}: long gotos will walk the straight line. Run: RynthNav.Baker --graph $NavDataDir" }
elseif ($graph.LastWriteTimeUtc -lt $newestTile) { Write-Warning "navgraph.bin is older than the newest tile: rebuild it (RynthNav.Baker --graph $NavDataDir), or RynthNav will ignore it." }
$idText = ($navFiles | ForEach-Object { "$($_.Name) $(Sha256 $_.FullName)" }) -join "`n"
$navId = (Sha256Text $idText).Substring(0, 32)
# [long]: Measure-Object's Sum is a double, which ConvertTo-Json writes as 1383002945.0, and the
# launcher reads "bytes" with GetInt64 - a ".0" failed every launcher's update check (2026.10.3.1/2).
$navBytes = [long](($navFiles | Measure-Object Length -Sum).Sum)
if ($liveManifest -and $liveManifest.navdata -and $liveManifest.navdata.id -eq $navId) {
$navData = $liveManifest.navdata
# Carried over from the live feed (ConvertFrom-Json): force the whole numbers back to integers.
$navData = [ordered]@{
id = [string]$navData.id
release = [long]$navData.release
url = [string]$navData.url
size = [long]$navData.size
sha256 = [string]$navData.sha256
files = [long]$navData.files
bytes = [long]$navData.bytes
}
Write-Host " unchanged ($($navFiles.Count) files, id $navId): the live archive from release $($navData.release) stays"
} else {
$navZip = "$rel\RynthNav-NavData.zip"
Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem
$fs = [IO.File]::Open($navZip, 'CreateNew')
try {
$za = New-Object IO.Compression.ZipArchive($fs, [IO.Compression.ZipArchiveMode]::Create)
foreach ($f in $navFiles) {
[void][IO.Compression.ZipFileExtensions]::CreateEntryFromFile($za, $f.FullName, $f.Name, [IO.Compression.CompressionLevel]::Optimal)
}
$za.Dispose()
} finally { $fs.Dispose() }
$zi = Get-Item $navZip
$navData = [ordered]@{
id = $navId
release = $release
url = "$BaseUrl/releases/$release/RynthNav-NavData.zip"
size = $zi.Length
sha256 = Sha256 $zi.FullName
files = $navFiles.Count
bytes = $navBytes
}
Write-Host (" new set: {0} files ({1} tiles), {2:N0} MB packed into {3:N0} MB, id {4}" -f $navFiles.Count, $tileCount, ($navBytes / 1MB), ($zi.Length / 1MB), $navId)
}
}
# ── 3. Manifest + signature ──────────────────────────────────────────────────
Step "Writing and signing the manifest"
$setup = Get-Item "$rel\RynthCore-Setup.exe"
# One line per plugin for the launcher's Available plugins list (launchers from 2026.10.5 on;
# older ones ignore the field, and a plugin without one falls back to the launcher's own table
# in RynthUpdater.Available.cs). Plain English for players, no names.
$pluginDescriptions = @{
RynthAi = "The bot: combat, buffs, looting, navigation routes and metas."
RynthChat = "A chat window that sorts messages into tabs."
RynthTracker = "Kills, experience and luminance per hour for each session."
RynthNav = "Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB)."
RynthVision = "Shows unclimbable slopes, impassable water and your radar range in the world."
RynthLua = "Lua scripting for metas and your own scripts."
RynthOracle = "Quests, character, titles and leaderboards."
RynthInventory = "Search every character's items."
}
$plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Name) {
[ordered]@{
name = $dll.BaseName -replace '^RynthCore\.Plugin\.', ''
$pluginName = $dll.BaseName -replace '^RynthCore\.Plugin\.', ''
$entry = [ordered]@{
name = $pluginName
file = $dll.Name
url = "$BaseUrl/releases/$release/plugins/$($dll.Name)"
size = $dll.Length
sha256 = Sha256 $dll.FullName
}
if ($pluginDescriptions[$pluginName]) { $entry.description = $pluginDescriptions[$pluginName] }
else { Write-Warning "No description for $pluginName - the launcher shows its own (or none). Add one to `$pluginDescriptions." }
$entry
}
$manifest = [ordered]@{
schema = 1
@ -176,6 +286,9 @@ $manifest = [ordered]@{
version = $Version
published = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
notes = $Notes
# The changes, one line each: the launcher's update card shows a few as "What's new"
# (signed with the rest; launchers before 2026.10.5 ignore it and show the notes).
changes = @($Changes)
core = [ordered]@{
release = $release
version = $Version
@ -185,6 +298,7 @@ $manifest = [ordered]@{
}
plugins = @($plugins)
}
if ($navData) { $manifest.navdata = $navData }
Set-Content "$rel\update.payload.json" ($manifest | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM
& (Join-Path $ScriptDir "Sign-Update.ps1") -PayloadPath "$rel\update.payload.json" -OutPath "$rel\update.json" -KeyDir $KeyDir
if (-not (Test-Envelope "$rel\update.json" $trusted)) { throw "Signed feed does not verify against UpdateTrust.cs" }
@ -213,9 +327,16 @@ scp -q "$rel\RynthCore-Setup.exe" "${SshHost}:$remoteRel/RynthCore-Setup.exe"
if ($LASTEXITCODE -ne 0) { throw "scp of the installer failed" }
scp -q (Get-ChildItem "$rel\plugins\*.dll").FullName "${SshHost}:$remoteRel/plugins/"
if ($LASTEXITCODE -ne 0) { throw "scp of the plugins failed" }
$navSum = ""
if ($navZip) {
scp -q $navZip "${SshHost}:$remoteRel/RynthNav-NavData.zip"
if ($LASTEXITCODE -ne 0) { throw "scp of the RynthNav data archive failed" }
$navSum = " RynthNav-NavData.zip"
}
$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll"
$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll$navSum"
$expect = @{ "RynthCore-Setup.exe" = $manifest.core.sha256 }
if ($navZip) { $expect["RynthNav-NavData.zip"] = $navData.sha256 }
foreach ($pl in $plugins) { $expect["plugins/$($pl.file)"] = $pl.sha256 }
foreach ($line in $remoteSums) {
$sum, $name = $line -split '\s+', 2

View file

@ -13,7 +13,7 @@ AppId={{A8B4C2D1-E3F5-4678-9ABC-DEF012345678}
AppName=RynthCore
AppVersion=0.0.0
AppPublisher=RynthCore
AppPublisherURL=https://github.com/tombohar/RynthCore
AppPublisherURL=https://aelrynth.com/git/rynth/RynthCore
DefaultDirName=C:\Games\RynthCore
DisableDirPage=no
DefaultGroupName=RynthCore
@ -79,6 +79,16 @@ Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Description: "Launch Rynth
; bring it back when the upgrade is done.
Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Flags: nowait runasoriginaluser; Check: CmdLineParamExists('/RELAUNCH')
[UninstallRun]
; Decal + RynthCore (experimental): remove the Decal bridge's registration, only
; what the launcher added (see docs/DECAL_BRIDGE_PLAN.md). Every release ships the bridge
; ({app}\DecalBridge, staged by Build-Installer.ps1), so this always runs; with nothing
; registered it changes nothing. Runs before the files are removed. It removes both entries
; the installer writes (see RegisterDecalBridge in [Code]): the per-user one, and the
; machine-wide one - directly when the uninstaller is elevated, otherwise after Windows'
; administrator prompt, which appears only when a machine-wide entry exists.
Filename: "{app}\RynthCore.exe"; Parameters: "--decal-bridge-unregister"; Flags: runhidden waituntilterminated; RunOnceId: "RynthCoreDecalBridgeUnregister"
[Code]
function CmdLineParamExists(const Value: string): Boolean;
var
@ -92,3 +102,106 @@ begin
Exit;
end;
end;
(* -------------------------------------------------------------------------------------
Decal + RynthCore (experimental): register the RynthCore Decal bridge on every install
AND every update (the launcher's updater runs this installer with /SILENT), in BOTH
places a Decal client can read its filter list from:
1. Machine-wide: HKLM\SOFTWARE\WOW6432Node\Decal\NetworkFilters\{5B3E0D57-...}
(32-bit view). An elevated AC (RynthCore or AC run as administrator), or any AC when
UAC or its registry virtualization is off, reads ONLY this key - the per-user entry
is invisible to it (a player's Decal + RynthCore client never loaded the bridge,
2026-10-03). A non-elevated AC without a per-user copy reads it too.
2. Per-user: this user's VirtualStore copy of that key, ONLY if the copy already exists.
A non-elevated AC is virtualized and, once a copy exists, reads nothing but the copy.
A missing copy is never created: it would hide every HKLM filter added later from
this user's non-elevated clients.
Both entries are harmless while no account uses Decal + RynthCore: every Decal client
loads the bridge, which stays idle (no hooks, no threads) unless the RynthCore loader is
in the same client. Uninstall removes both ([UninstallRun] --decal-bridge-unregister).
Rights. This installer runs with the lowest privileges (PrivilegesRequired=lowest; the
updater starts it without elevation). Writing HKLM needs administrator rights, so:
- Setup already elevated (installed "for all users", or started by an elevated
launcher): written directly, no prompt.
- Not elevated: Windows' administrator prompt is shown ONCE - only when Decal is
installed, the machine-wide entry is missing or points at another folder, and this
user has a Decal + RynthCore account (decal-accounts.json). Saying no is harmless:
the launcher checks before every Decal + RynthCore launch and repairs it (writing it
directly when it runs elevated, the case that needs it).
The commands are RynthCore.exe's own (Program.cs): --decal-bridge-register-machine and
--decal-bridge-install-user, so the installer and the launcher write identical entries.
------------------------------------------------------------------------------------- *)
const
BridgeEntryKey = 'SOFTWARE\Decal\NetworkFilters\{5B3E0D57-2C41-4F8A-9D6E-8C1B70DECA11}';
BridgeObject = 'RynthCore.DecalBridge.BridgeFilter';
function DecalInstalled: Boolean;
begin
Result := RegKeyExists(HKLM32, 'SOFTWARE\Decal\Agent');
end;
function BridgeDir: String;
begin
Result := ExpandConstant('{app}\DecalBridge');
end;
function MachineBridgeEntryCurrent: Boolean;
var
P, O: String;
E: Cardinal;
begin
Result := RegQueryStringValue(HKLM32, BridgeEntryKey, 'Path', P) and
(CompareText(RemoveBackslashUnlessRoot(P), BridgeDir) = 0) and
RegQueryStringValue(HKLM32, BridgeEntryKey, 'Object', O) and (O = BridgeObject) and
RegQueryDWordValue(HKLM32, BridgeEntryKey, 'Enabled', E) and (E = 1);
end;
function UsesDecalBridge: Boolean;
begin
Result := FileExists(ExpandConstant('{userappdata}\RynthCore\decal-accounts.json'));
end;
procedure RegisterDecalBridge;
var
Exe, Params: String;
Code: Integer;
begin
if not DecalInstalled then Exit;
if not FileExists(BridgeDir + '\RynthCore.DecalBridge.dll') then Exit;
Exe := ExpandConstant('{app}\RynthCore.exe');
Params := '--decal-bridge-register-machine "' + BridgeDir + '"';
if not MachineBridgeEntryCurrent then
begin
if IsAdmin then
begin
if not Exec(Exe, Params, ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, Code) then
Log('Decal bridge: machine-wide registration did not start: ' + SysErrorMessage(Code))
else
Log('Decal bridge: machine-wide registration exit code ' + IntToStr(Code));
end
else if UsesDecalBridge then
begin
if not ShellExec('runas', Exe, Params, ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, Code) then
Log('Decal bridge: elevated machine-wide registration not done (declined or failed): ' + SysErrorMessage(Code))
else
Log('Decal bridge: elevated machine-wide registration exit code ' + IntToStr(Code));
end
else
Log('Decal bridge: machine-wide entry missing; not elevated and no Decal + RynthCore account - left to the launcher.');
end;
{ Per-user half, as the user who started Setup (the same user unless Setup was elevated
with other credentials). }
if not ExecAsOriginalUser(Exe, '--decal-bridge-install-user "' + BridgeDir + '"', ExpandConstant('{app}'),
SW_HIDE, ewWaitUntilTerminated, Code) then
Log('Decal bridge: per-user step did not start: ' + SysErrorMessage(Code));
end;
procedure CurStepChanged(CurStep: TSetupStep);
begin
{ After the files, before [Run] (which relaunches the launcher after an update). }
if CurStep = ssPostInstall then
RegisterDecalBridge;
end;

View file

@ -0,0 +1,36 @@
# Build-Loader.ps1
# Compiles the native RynthCore.Loader.dll (x86 MSVC) into native\Loader\bin.
# Does not deploy: copy it to Runtime\ yourself (a running client keeps the old loader
# until it restarts; the loader is injected once per process).
$ErrorActionPreference = "Stop"
$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" `
-latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 `
-property installationPath 2>$null
if (-not $vsPath) { Write-Error "Visual Studio with C++ tools not found."; exit 1 }
$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name
$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer"
$cl = "$vcBase\bin\Hostx86\x86\cl.exe"
$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name
$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer"
$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer"
$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared"
$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86"
$src = $PSScriptRoot
$out = Join-Path $src "bin"
$obj = Join-Path $out "obj"
New-Item -ItemType Directory -Path $out, $obj -Force | Out-Null
Write-Host "Compiling RynthCore.Loader.dll (MSVC $vcVer, x86)..."
Push-Location $obj
try {
& $cl /nologo /O2 /MT /GS /W4 /wd4100 /LD /Zi "$src\Loader.c" "$src\Hooks.c" "$src\Clr.c" "$src\Services.c" user32.lib `
/link /MACHINE:X86 /DEF:"$src\Loader.def" /DEBUG /OPT:REF /OUT:"$out\RynthCore.Loader.dll" /PDB:"$out\RynthCore.Loader.pdb"
if ($LASTEXITCODE -ne 0) { Write-Error "Compilation failed."; exit $LASTEXITCODE }
} finally { Pop-Location }
$size = (Get-Item "$out\RynthCore.Loader.dll").Length
Write-Host "Built: $out\RynthCore.Loader.dll ($size bytes)"

175
native/Loader/Clr.c Normal file
View file

@ -0,0 +1,175 @@
// ============================================================================
// Clr.c - hosts CoreCLR once, from the app-local runtime in Runtime\dotnet\, and
// talks to RynthCore.Shim.dll (default ALC), which owns the collectible
// AssemblyLoadContext each engine generation lives in.
//
// The raw coreclr_* API is used (no hostfxr, runtimeconfig.json or deps.json): the
// TPA list is every managed DLL in Runtime\dotnet\ plus the Shim. The engine and its
// own dependencies (Avalonia, ImGui.NET, ...) are NOT on the TPA list: the Shim loads
// them into the engine's collectible ALC, so they go away with it.
// ============================================================================
#include "Loader.h"
#include <stdio.h>
typedef int (__stdcall *coreclr_initialize_fn)(const char* exePath, const char* appDomainFriendlyName,
int propertyCount, const char** propertyKeys, const char** propertyValues,
void** hostHandle, unsigned int* domainId);
typedef int (__stdcall *coreclr_create_delegate_fn)(void* hostHandle, unsigned int domainId,
const char* assemblyName, const char* typeName, const char* methodName, void** fn);
// Shared with RynthCore.Shim (ShimHost.cs): keep the layouts in step.
typedef struct LoaderApi {
int size;
void (__stdcall *log)(const char* level, const char* utf8);
int (__stdcall *freeMb)(int* largestMb);
const char* loaderDir;
int (__stdcall *hookCount)(void);
} LoaderApi;
typedef struct ShimApi {
int size;
int (__stdcall *loadEngine)(int generation, const char* stagedPathUtf8);
int (__stdcall *unloadEngine)(void); // 1 = the ALC was freed
void* (__stdcall *engineExport)(const char* nameUtf8);
} ShimApi;
typedef int (__stdcall *shim_init_fn)(LoaderApi* api, ShimApi* out);
static LoaderApi g_loaderApi;
static ShimApi g_shim;
static int g_started;
int __stdcall RcHooks_Count(void);
static void __stdcall ShimLog(const char* level, const char* utf8) { LoaderLog(level ? level : "INF", "[shim] %s", utf8); }
static int __stdcall ShimFreeMb(int* largestMb)
{
long largest;
long free = LoaderFreeAddressSpaceMb(&largest);
if (largestMb) *largestMb = (int)largest;
return (int)free;
}
static int IsNativeRuntimeFile(const char* n)
{
static const char* natives[] = {
"coreclr.dll", "clrjit.dll", "clrgc.dll", "clrgcexp.dll", "hostfxr.dll", "hostpolicy.dll",
"mscordaccore.dll", "mscordbi.dll", "mscorrc.dll", "clretwrc.dll", "msquic.dll",
"System.IO.Compression.Native.dll", "Microsoft.DiaSymReader.Native.x86.dll",
};
for (int i = 0; i < (int)(sizeof natives / sizeof natives[0]); i++)
if (!_stricmp(n, natives[i])) return 1;
return !_strnicmp(n, "mscordaccore_", 13);
}
static int AppendDlls(char* tpa, size_t cap, const char* dir)
{
char pattern[MAX_PATH];
_snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\*.dll", dir);
WIN32_FIND_DATAA fd;
HANDLE h = FindFirstFileA(pattern, &fd);
if (h == INVALID_HANDLE_VALUE) return 0;
int n = 0;
do {
if (IsNativeRuntimeFile(fd.cFileName)) continue;
strcat_s(tpa, cap, dir);
strcat_s(tpa, cap, "\\");
strcat_s(tpa, cap, fd.cFileName);
strcat_s(tpa, cap, ";");
n++;
} while (FindNextFileA(h, &fd));
FindClose(h);
return n;
}
int ClrStart(const char* loaderDir)
{
if (g_started) return 0;
char runtimeDir[MAX_PATH], coreclrPath[MAX_PATH], shimPath[MAX_PATH];
_snprintf_s(runtimeDir, sizeof runtimeDir, _TRUNCATE, "%s\\dotnet", loaderDir);
_snprintf_s(coreclrPath, sizeof coreclrPath, _TRUNCATE, "%s\\coreclr.dll", runtimeDir);
_snprintf_s(shimPath, sizeof shimPath, _TRUNCATE, "%s\\RynthCore.Shim.dll", loaderDir);
if (GetFileAttributesA(shimPath) == INVALID_FILE_ATTRIBUTES) {
LoaderLog("ERR", "CLR: %s is missing", shimPath);
return 1;
}
long free0 = LoaderFreeAddressSpaceMb(NULL);
DWORD t0 = GetTickCount();
HMODULE clr = LoadLibraryExA(coreclrPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!clr) {
LoaderLog("ERR", "CLR: LoadLibrary %s failed (error %lu)", coreclrPath, GetLastError());
return 2;
}
coreclr_initialize_fn init = (coreclr_initialize_fn)GetProcAddress(clr, "coreclr_initialize");
coreclr_create_delegate_fn create = (coreclr_create_delegate_fn)GetProcAddress(clr, "coreclr_create_delegate");
if (!init || !create) return 3;
static char tpa[128 * 1024];
tpa[0] = 0;
int count = AppendDlls(tpa, sizeof tpa, runtimeDir);
strcat_s(tpa, sizeof tpa, shimPath);
strcat_s(tpa, sizeof tpa, ";");
char nativeDirs[2 * MAX_PATH + 4], baseDir[MAX_PATH + 2];
_snprintf_s(nativeDirs, sizeof nativeDirs, _TRUNCATE, "%s;%s;", loaderDir, runtimeDir);
_snprintf_s(baseDir, sizeof baseDir, _TRUNCATE, "%s\\", loaderDir);
const char* keys[] = {
"TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "APP_CONTEXT_BASE_DIRECTORY",
"System.GC.Server", "System.GC.Concurrent", "System.Globalization.Invariant", "System.GC.RetainVM",
};
// Concurrent (background) GC on: the engine and the managed plugins share this one GC,
// and with it off every gen2 (~every 10 s, driven by large allocations) was a fully
// blocking 55-66 ms pause that AC's main thread hit whenever it was in managed code.
const char* values[] = {
tpa, "", nativeDirs, baseDir,
"false", "true", "true", "false",
};
char exePath[MAX_PATH];
GetModuleFileNameA(NULL, exePath, MAX_PATH);
void* hostHandle = NULL;
unsigned int domainId = 0;
int hr = init(exePath, "RynthCore", (int)(sizeof keys / sizeof keys[0]), keys, values, &hostHandle, &domainId);
if (hr < 0) {
LoaderLog("ERR", "CLR: coreclr_initialize failed 0x%08x", hr);
return 4;
}
shim_init_fn shimInit = NULL;
hr = create(hostHandle, domainId, "RynthCore.Shim", "RynthCore.Shim.ShimHost", "Init", (void**)&shimInit);
if (hr < 0 || !shimInit) {
LoaderLog("ERR", "CLR: RynthCore.Shim.ShimHost.Init not found (0x%08x)", hr);
return 5;
}
g_loaderApi.size = sizeof g_loaderApi;
g_loaderApi.log = ShimLog;
g_loaderApi.freeMb = ShimFreeMb;
g_loaderApi.loaderDir = LoaderDirectory();
g_loaderApi.hookCount = RcHooks_Count;
g_shim.size = sizeof g_shim;
int rc = shimInit(&g_loaderApi, &g_shim);
if (rc != 0 || !g_shim.loadEngine || !g_shim.unloadEngine || !g_shim.engineExport) {
LoaderLog("ERR", "CLR: Shim init failed (rc=%d)", rc);
return 6;
}
g_started = 1;
LoaderLog("INF", "CLR: CoreCLR up in %lu ms from %s (%d framework assemblies), %ld MB of address space used.",
GetTickCount() - t0, runtimeDir, count, free0 - LoaderFreeAddressSpaceMb(NULL));
return 0;
}
int ClrLoadEngine(int generation, const char* stagedPath)
{
return g_started ? g_shim.loadEngine(generation, stagedPath) : -1;
}
void ClrUnloadEngine(void)
{
if (g_started) g_shim.unloadEngine();
}
void* ClrEngineExport(const char* name)
{
return g_started ? g_shim.engineExport(name) : NULL;
}

332
native/Loader/Hooks.c Normal file
View file

@ -0,0 +1,332 @@
// ============================================================================
// Hooks.c - MinHook facade with permanent stubs
//
// Exports MinHook's API (MH_Initialize, MH_CreateHook, MH_EnableHook, ...) with the
// same signatures and status codes, so the engine's Hooking/MinHook.cs can call either
// this facade or minhook.x86.dll.
//
// The difference: nothing native ever points at engine code directly. For every target
// the facade allocates a permanent 6-byte stub, `jmp dword ptr [slot]`, and installs the
// real MinHook hook once, with the stub as the detour. The slot holds either the
// engine's detour (hook enabled) or MinHook's trampoline (hook disabled: a transparent
// pass-through to the original, whatever the calling convention). A reload only
// re-points slots, so an engine generation can be unloaded as soon as no thread is
// inside its code, and the next generation's MH_CreateHook for the same target reuses
// the same stub and gets the same trampoline back.
//
// Hooks are "owned" by the generation that created them: MH_CreateHook on a target
// created by an earlier generation succeeds (no MH_ERROR_ALREADY_CREATED), and
// HooksPassThroughAll() (every reload) turns every slot back into a pass-through and
// takes the patch out of the target (MinHook disable: original bytes back), so the next
// generation's pattern scans see AC's real prologues; its MH_CreateHook puts it back.
// The stub and trampoline are never freed, so a thread still returning through them is
// safe.
//
// Patching is batched. Every MinHook enable/disable freezes all the process's threads
// (a system-wide thread snapshot, ~100 ms here), and an engine installs ~60 hooks: one
// freeze each made up ~7 s of every reload. The facade records which targets should be
// patched and applies them in one queued MinHook freeze: straight after the engine's
// init export returns (HooksFlush; on a first launch AC's main thread is still suspended
// then), on every reload, and ~20 ms after the last change otherwise (a background
// flusher). A hook's slot is set at once; its patch follows within that window.
// ============================================================================
#include "Loader.h"
#include <stdio.h>
#define MH_OK 0
#define MH_ERROR_ALREADY_INITIALIZED 1
#define MH_ERROR_NOT_INITIALIZED 2
#define MH_ERROR_ALREADY_CREATED 3
#define MH_ERROR_NOT_CREATED 4
#define MH_ERROR_ENABLED 5
#define MH_ERROR_DISABLED 6
#define MH_ERROR_MEMORY_ALLOC 9
#define MH_UNKNOWN -1
#define MAX_HOOKS 1024
#define STUB_SIZE 8
typedef int (__stdcall *mh_init_fn)(void);
typedef int (__stdcall *mh_create_fn)(void* target, void* detour, void** original);
typedef int (__stdcall *mh_target_fn)(void* target);
typedef const char* (__stdcall *mh_status_fn)(int status);
typedef struct HookEntry {
void* target;
void* trampoline; // MinHook's call-the-original trampoline (never freed)
void* detour; // the owning generation's detour, or NULL once removed
int generation; // generation that last created it
int created; // created (and not removed) by `generation`
int enabled; // slot == detour
int patched; // MinHook's jump is in the target
int want; // it should be (applied by the next flush)
} HookEntry;
static CRITICAL_SECTION g_lock;
static int g_ready;
static int g_generation;
static HMODULE g_minhook;
static mh_init_fn p_init;
static mh_create_fn p_create;
static mh_target_fn p_enable;
static mh_target_fn p_disable;
static mh_target_fn p_queueDisable;
static mh_target_fn p_queueEnable;
static mh_init_fn p_applyQueued;
static mh_status_fn p_status;
static HookEntry g_hooks[MAX_HOOKS];
static void* volatile g_slots[MAX_HOOKS];
static unsigned char* g_stubs;
static int g_count;
static HANDLE g_dirtyEvent;
static volatile DWORD g_lastChange;
static void FlushLocked(const char* why);
static DWORD WINAPI Flusher(LPVOID unused)
{
(void)unused;
for (;;) {
WaitForSingleObject(g_dirtyEvent, INFINITE);
do Sleep(20); while (GetTickCount() - g_lastChange < 20); // settle: one freeze per burst
EnterCriticalSection(&g_lock);
FlushLocked("batched");
LeaveCriticalSection(&g_lock);
}
}
int HooksInit(const char* loaderDir)
{
InitializeCriticalSection(&g_lock);
char path[MAX_PATH];
_snprintf_s(path, sizeof path, _TRUNCATE, "%s\\minhook.x86.dll", loaderDir);
g_minhook = LoadLibraryA(path);
if (!g_minhook) g_minhook = LoadLibraryA("minhook.x86.dll");
if (!g_minhook) return 0;
p_init = (mh_init_fn)GetProcAddress(g_minhook, "MH_Initialize");
p_create = (mh_create_fn)GetProcAddress(g_minhook, "MH_CreateHook");
p_enable = (mh_target_fn)GetProcAddress(g_minhook, "MH_EnableHook");
p_disable = (mh_target_fn)GetProcAddress(g_minhook, "MH_DisableHook");
p_queueDisable = (mh_target_fn)GetProcAddress(g_minhook, "MH_QueueDisableHook");
p_queueEnable = (mh_target_fn)GetProcAddress(g_minhook, "MH_QueueEnableHook");
p_applyQueued = (mh_init_fn)GetProcAddress(g_minhook, "MH_ApplyQueued");
p_status = (mh_status_fn)GetProcAddress(g_minhook, "MH_StatusToString");
if (!p_init || !p_create || !p_enable || !p_disable) return 0;
int st = p_init();
if (st != MH_OK && st != MH_ERROR_ALREADY_INITIALIZED) {
LoaderLog("ERR", "Hooks: MH_Initialize = %d", st);
return 0;
}
g_stubs = (unsigned char*)VirtualAlloc(NULL, MAX_HOOKS * STUB_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (!g_stubs) return 0;
g_dirtyEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
if (p_queueEnable && p_queueDisable && p_applyQueued && g_dirtyEvent) {
HANDLE t = CreateThread(NULL, 0, Flusher, NULL, 0, NULL);
if (t) CloseHandle(t);
}
g_ready = 1;
LoaderLog("INF", "Hooks: MinHook facade ready (%s, %d stub slots, %s patching).", path, MAX_HOOKS,
p_queueEnable ? "batched" : "per-hook");
return 1;
}
void HooksBeginGeneration(int generation)
{
EnterCriticalSection(&g_lock);
g_generation = generation;
LeaveCriticalSection(&g_lock);
}
static void SetPatched(int i, int patched)
{
HookEntry* e = &g_hooks[i];
if (e->patched == patched) return;
int st = patched ? p_enable(e->target) : p_disable(e->target);
if (st == MH_OK) e->patched = patched;
else LoaderLog("ERR", "Hooks: MinHook %s %p failed: %d", patched ? "enable" : "disable", e->target, st);
}
// Records whether target i should be patched; the next flush applies it. (Caller holds g_lock.)
static void Want(int i, int patched)
{
HookEntry* e = &g_hooks[i];
e->want = patched;
if (e->want == e->patched) return;
if (!p_queueEnable || !p_queueDisable || !p_applyQueued || !g_dirtyEvent) {
SetPatched(i, patched); // no queue in this MinHook: one at a time
return;
}
g_lastChange = GetTickCount();
SetEvent(g_dirtyEvent);
}
// Applies every pending patch/unpatch in one MinHook freeze. (Caller holds g_lock.)
static void FlushLocked(const char* why)
{
static int queued[MAX_HOOKS];
int n = 0;
for (int i = 0; i < g_count; i++) {
HookEntry* e = &g_hooks[i];
if (e->want == e->patched) continue;
int st = e->want ? p_queueEnable(e->target) : p_queueDisable(e->target);
if (st == MH_OK) queued[n++] = i;
else SetPatched(i, e->want);
}
if (n == 0) return;
DWORD t0 = GetTickCount();
int st = p_applyQueued();
if (st == MH_OK) {
for (int k = 0; k < n; k++) g_hooks[queued[k]].patched = g_hooks[queued[k]].want;
LoaderLog("INF", "Hooks: %d patch(es) applied in one freeze (%lu ms, %s).", n, GetTickCount() - t0, why);
} else {
LoaderLog("ERR", "Hooks: MH_ApplyQueued (%d, %s) = %d; applying one at a time.", n, why, st);
for (int k = 0; k < n; k++) SetPatched(queued[k], g_hooks[queued[k]].want);
}
}
void HooksFlush(void)
{
if (!g_ready) return;
EnterCriticalSection(&g_lock);
FlushLocked("engine init");
LeaveCriticalSection(&g_lock);
}
static void SetSlot(int i, int enabled)
{
HookEntry* e = &g_hooks[i];
e->enabled = enabled;
InterlockedExchangePointer((PVOID volatile*)&g_slots[i], enabled ? e->detour : e->trampoline);
}
void HooksPassThroughAll(void)
{
if (!g_ready) return;
EnterCriticalSection(&g_lock);
int live = 0;
for (int i = 0; i < g_count; i++) {
if (g_hooks[i].enabled) live++;
SetSlot(i, 0);
Want(i, 0);
g_hooks[i].created = 0;
g_hooks[i].detour = NULL;
}
FlushLocked("reload"); // AC's own prologues back, now
LeaveCriticalSection(&g_lock);
LoaderLog("INF", "Hooks: %d hook(s) now pass straight through (%d were still enabled).", g_count, live);
}
static int Find(void* target)
{
for (int i = 0; i < g_count; i++)
if (g_hooks[i].target == target) return i;
return -1;
}
// --- MinHook API ------------------------------------------------------------
int __stdcall MH_Initialize(void) { return g_ready ? MH_ERROR_ALREADY_INITIALIZED : MH_ERROR_NOT_INITIALIZED; }
// Hooks outlive every engine generation; "uninitialize" only turns them into pass-throughs.
int __stdcall MH_Uninitialize(void) { HooksPassThroughAll(); return MH_OK; }
int __stdcall MH_CreateHook(void* target, void* detour, void** original)
{
if (!g_ready) return MH_ERROR_NOT_INITIALIZED;
int st = MH_OK;
EnterCriticalSection(&g_lock);
int i = Find(target);
if (i >= 0) {
HookEntry* e = &g_hooks[i];
if (e->created && e->generation == g_generation) {
st = MH_ERROR_ALREADY_CREATED;
} else {
e->detour = detour;
e->generation = g_generation;
e->created = 1;
SetSlot(i, 0);
Want(i, 1);
if (original) *original = e->trampoline;
}
} else if (g_count >= MAX_HOOKS) {
st = MH_ERROR_MEMORY_ALLOC;
} else {
i = g_count;
unsigned char* stub = g_stubs + i * STUB_SIZE;
void* volatile* slot = &g_slots[i];
stub[0] = 0xFF; stub[1] = 0x25; // jmp dword ptr [slot]
*(void* volatile**)(stub + 2) = slot;
stub[6] = 0xCC; stub[7] = 0xCC;
FlushInstructionCache(GetCurrentProcess(), stub, STUB_SIZE);
void* tramp = NULL;
st = p_create(target, stub, &tramp);
if (st == MH_OK) {
HookEntry* e = &g_hooks[i];
e->target = target;
e->trampoline = tramp;
e->detour = detour;
e->generation = g_generation;
e->created = 1;
e->enabled = 0;
*slot = tramp; // pass-through until the engine enables it
g_count++;
e->patched = 0;
Want(i, 1); // the patch goes in (slot passes through)
st = MH_OK;
if (original) *original = tramp;
}
}
LeaveCriticalSection(&g_lock);
return st;
}
int __stdcall MH_RemoveHook(void* target)
{
if (!g_ready) return MH_ERROR_NOT_INITIALIZED;
int st = MH_OK;
EnterCriticalSection(&g_lock);
int i = Find(target);
if (i < 0 || !g_hooks[i].created) st = MH_ERROR_NOT_CREATED;
else {
SetSlot(i, 0);
Want(i, 0); // original bytes back, like MinHook's remove
g_hooks[i].created = 0;
g_hooks[i].detour = NULL;
}
LeaveCriticalSection(&g_lock);
return st;
}
static int SetEnabled(void* target, int enable)
{
if (!g_ready) return MH_ERROR_NOT_INITIALIZED;
int st = MH_OK;
EnterCriticalSection(&g_lock);
if (target == NULL) { // MH_ALL_HOOKS
for (int i = 0; i < g_count; i++)
if (g_hooks[i].created && g_hooks[i].enabled != enable) SetSlot(i, enable);
} else {
int i = Find(target);
if (i < 0 || !g_hooks[i].created) st = MH_ERROR_NOT_CREATED;
else if (g_hooks[i].enabled == enable) st = enable ? MH_ERROR_ENABLED : MH_ERROR_DISABLED;
else SetSlot(i, enable);
}
LeaveCriticalSection(&g_lock);
return st;
}
int __stdcall MH_EnableHook(void* target) { return SetEnabled(target, 1); }
int __stdcall MH_DisableHook(void* target) { return SetEnabled(target, 0); }
const char* __stdcall MH_StatusToString(int status)
{
if (p_status) return p_status(status);
return status == MH_OK ? "MH_OK" : "MH_UNKNOWN";
}
// Lets the engine tell this facade from minhook.x86.dll (and an old NativeAOT loader).
int __stdcall RcHooks_Version(void) { return 1; }
int __stdcall RcHooks_Count(void) { return g_count; }

407
native/Loader/Loader.c Normal file
View file

@ -0,0 +1,407 @@
// ============================================================================
// RynthCore.Loader.dll - native loader (docs/UNLOADABLE_ENGINE_PLAN.md, Phase 1)
//
// Injected into acclient.exe by RynthCore.Injector / the launcher, which call the
// RynthCoreInit export on a remote thread (same contract as the old NativeAOT loader).
//
// Two engine hosts, chosen by looking at Runtime\RynthCore.Engine.dll:
// - NativeAOT engine (a native DLL exporting RynthCoreEngineInit): staged to
// .engine_loads\, LoadLibrary'd, never freed. Today's behaviour.
// - Managed engine (a PE with a CLR header): the loader starts CoreCLR once from
// Runtime\dotnet\ and hands the engine to RynthCore.Shim.dll (default ALC), which
// loads each generation into a collectible AssemblyLoadContext and unloads it on
// reload, so a reload gives its memory back.
//
// Either way the loader owns the reload event, the file watcher, the address-space
// guard and a MinHook facade (Hooks.c): every hook is installed once, through a
// permanent stub, and a reload only re-points the stub.
// ============================================================================
#include "Loader.h"
#include <stdio.h>
#include <stdarg.h>
#define ENGINE_DLL_NAME "RynthCore.Engine.dll"
#define ENGINE_INIT_EXPORT "RynthCoreEngineInit"
#define ENGINE_SHUTDOWN_EXPORT "RynthCoreShutdown"
#define ENGINE_REFUSED_EXPORT "RynthCoreReloadRefused"
#define LOG_DIR "C:\\Games\\RynthCore\\Logs"
#define STAGING_SUBDIR ".engine_loads"
#define MIN_RELOAD_INTERVAL_MS 1500
// A managed engine gives its memory back on reload, so the guard only has to keep
// room for one more generation; the NativeAOT engine leaks every generation.
#define MIN_FREE_MB_AOT 1200
#define MIN_FREE_MB_CLR 500
typedef unsigned int (__stdcall *engine_u32_fn)(void* param);
typedef unsigned int (__stdcall *engine_refused_fn)(int freeMb);
static volatile LONG g_initialized;
static char g_loaderDir[MAX_PATH];
static char g_enginePath[MAX_PATH];
static int g_engineIsManaged;
static HMODULE g_engineModule; // NativeAOT host only
static int g_initCount;
static HANDLE g_reloadEvent;
static FILETIME g_canonicalWrite;
static volatile LONG g_reloadInFlight;
static volatile ULONGLONG g_lastReloadDone;
static CRITICAL_SECTION g_logLock;
// ---------------------------------------------------------------------------
// Logging: same per-client file and line format as the engine (LogPaths.cs).
// ---------------------------------------------------------------------------
void LoaderLog(const char* level, const char* fmt, ...)
{
char msg[3072];
va_list ap;
va_start(ap, fmt);
_vsnprintf_s(msg, sizeof msg, _TRUNCATE, fmt, ap);
va_end(ap);
SYSTEMTIME t;
GetLocalTime(&t);
char line[3300];
int n = _snprintf_s(line, sizeof line, _TRUNCATE, "[%02d:%02d:%02d.%03d] [pid:%lu] [%s] [loader] %s\r\n",
t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, GetCurrentProcessId(), level, msg);
if (n < 0) n = (int)strlen(line);
char path[MAX_PATH];
_snprintf_s(path, sizeof path, _TRUNCATE, LOG_DIR "\\RynthCore.%lu.log", GetCurrentProcessId());
EnterCriticalSection(&g_logLock);
CreateDirectoryA("C:\\Games\\RynthCore", NULL);
CreateDirectoryA(LOG_DIR, NULL);
for (int attempt = 0; attempt < 4; attempt++) {
HANDLE h = CreateFileA(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (h != INVALID_HANDLE_VALUE) {
DWORD written;
WriteFile(h, line, (DWORD)n, &written, NULL);
CloseHandle(h);
break;
}
Sleep(5);
}
LeaveCriticalSection(&g_logLock);
OutputDebugStringA(line);
}
// ---------------------------------------------------------------------------
// Address space
// ---------------------------------------------------------------------------
long LoaderFreeAddressSpaceMb(long* largestMb)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
unsigned char* p = (unsigned char*)si.lpMinimumApplicationAddress;
unsigned char* end = (unsigned char*)si.lpMaximumApplicationAddress;
unsigned long long total = 0, largest = 0;
MEMORY_BASIC_INFORMATION mbi;
while (p < end && VirtualQuery(p, &mbi, sizeof mbi) == sizeof mbi) {
if (mbi.RegionSize == 0) break;
if (mbi.State == MEM_FREE) {
total += mbi.RegionSize;
if (mbi.RegionSize > largest) largest = mbi.RegionSize;
}
p = (unsigned char*)mbi.BaseAddress + mbi.RegionSize;
}
if (largestMb) *largestMb = (long)(largest / (1024 * 1024));
return (long)(total / (1024 * 1024));
}
// ---------------------------------------------------------------------------
// Engine file: staging and kind
// ---------------------------------------------------------------------------
static int FileLastWrite(const char* path, FILETIME* out)
{
WIN32_FILE_ATTRIBUTE_DATA d;
if (!GetFileAttributesExA(path, GetFileExInfoStandard, &d)) return 0;
*out = d.ftLastWriteTime;
return 1;
}
// 1 = the file is a .NET assembly (PE with a CLR header), 0 = native, -1 = unreadable.
static int IsManagedPe(const char* path)
{
HANDLE h = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) return -1;
unsigned char buf[4096];
DWORD read = 0;
BOOL ok = ReadFile(h, buf, sizeof buf, &read, NULL);
CloseHandle(h);
if (!ok || read < sizeof(IMAGE_DOS_HEADER)) return -1;
IMAGE_DOS_HEADER* dos = (IMAGE_DOS_HEADER*)buf;
if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew <= 0 ||
(DWORD)dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32) > read) return -1;
IMAGE_NT_HEADERS32* nt = (IMAGE_NT_HEADERS32*)(buf + dos->e_lfanew);
if (nt->Signature != IMAGE_NT_SIGNATURE) return -1;
if (nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return 0;
if (nt->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR) return 0;
return nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress != 0;
}
static void CleanStaleStagingFiles(const char* stagingDir)
{
char pattern[MAX_PATH];
_snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\RynthCore.Engine.p*.gen*.*", stagingDir); // .dll + .pdb
WIN32_FIND_DATAA fd;
HANDLE f = FindFirstFileA(pattern, &fd);
if (f == INVALID_HANDLE_VALUE) return;
do {
char p[MAX_PATH];
_snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", stagingDir, fd.cFileName);
DeleteFileA(p); // fails for files a live process still maps: fine
} while (FindNextFileA(f, &fd));
FindClose(f);
}
// Copies the canonical engine to .engine_loads\RynthCore.Engine.p<pid>.gen<N>.dll so the
// canonical file is never locked (a developer can copy over it) and every generation is
// a distinct module/assembly path.
static int StageEngine(int generation, char* stagedPath, size_t cap)
{
char stagingDir[MAX_PATH];
_snprintf_s(stagingDir, sizeof stagingDir, _TRUNCATE, "%s\\" STAGING_SUBDIR, g_loaderDir);
CreateDirectoryA(stagingDir, NULL);
CleanStaleStagingFiles(stagingDir);
_snprintf_s(stagedPath, cap, _TRUNCATE, "%s\\RynthCore.Engine.p%lu.gen%d.dll",
stagingDir, GetCurrentProcessId(), generation);
if (!CopyFileA(g_enginePath, stagedPath, FALSE)) {
LoaderLog("ERR", "StageEngine: copy to %s failed (error %lu)", stagedPath, GetLastError());
return 0;
}
if (g_engineIsManaged) {
// The debug symbols travel with the assembly so stack traces keep line numbers.
char srcPdb[MAX_PATH], dstPdb[MAX_PATH];
_snprintf_s(srcPdb, sizeof srcPdb, _TRUNCATE, "%s\\RynthCore.Engine.pdb", g_loaderDir);
_snprintf_s(dstPdb, sizeof dstPdb, _TRUNCATE, "%.*s.pdb", (int)(strlen(stagedPath) - 4), stagedPath);
CopyFileA(srcPdb, dstPdb, FALSE);
}
LoaderLog("INF", "Staged engine for gen %d at %s", generation, stagedPath);
return 1;
}
// ---------------------------------------------------------------------------
// Engine calls, whichever host
// ---------------------------------------------------------------------------
static void* EngineExport(const char* name)
{
if (g_engineIsManaged) return ClrEngineExport(name);
return g_engineModule ? (void*)GetProcAddress(g_engineModule, name) : NULL;
}
static unsigned int LoadAndInitEngine(void)
{
g_initCount++;
HooksBeginGeneration(g_initCount);
char staged[MAX_PATH];
if (!StageEngine(g_initCount, staged, sizeof staged)) return 11;
if (!FileLastWrite(g_enginePath, &g_canonicalWrite)) GetSystemTimeAsFileTime(&g_canonicalWrite);
if (g_engineIsManaged) {
int rc = ClrLoadEngine(g_initCount, staged);
if (rc != 0) {
LoaderLog("ERR", "Managed engine gen %d failed to load (rc=%d)", g_initCount, rc);
return 4;
}
} else {
HMODULE m = LoadLibraryA(staged);
if (!m) {
LoaderLog("ERR", "LoadLibrary failed for engine (path=%s, error %lu)", staged, GetLastError());
return 4;
}
g_engineModule = m;
LoaderLog("INF", "Engine module loaded at 0x%08p from %s", (void*)m, staged);
}
engine_u32_fn init = (engine_u32_fn)EngineExport(ENGINE_INIT_EXPORT);
if (!init) {
LoaderLog("ERR", "Engine missing export '%s'", ENGINE_INIT_EXPORT);
return 5;
}
unsigned int rc = init((void*)(INT_PTR)g_initCount);
// The hooks the engine installed during init go in now, in one freeze, before the
// injector resumes AC's main thread (first launch) or the new generation runs.
HooksFlush();
LoaderLog("INF", ENGINE_INIT_EXPORT "(initCount=%d) returned %u.", g_initCount, rc);
return rc;
}
static void Reload(void)
{
long largest;
long freeBefore = LoaderFreeAddressSpaceMb(&largest);
LoaderLog("INF", "Reload requested (gen %d, %ld MB free, largest %ld MB).", g_initCount, freeBefore, largest);
engine_u32_fn shutdown = (engine_u32_fn)EngineExport(ENGINE_SHUTDOWN_EXPORT);
if (shutdown) {
unsigned int rc = shutdown(NULL);
LoaderLog("INF", ENGINE_SHUTDOWN_EXPORT " returned %u.", rc);
} else {
LoaderLog("WRN", "Engine has no '%s' export; skipping graceful shutdown.", ENGINE_SHUTDOWN_EXPORT);
}
// Whatever the engine left enabled now passes straight through to AC.
HooksPassThroughAll();
ServicesReleaseAll();
Sleep(150);
if (g_engineIsManaged) {
ClrUnloadEngine();
} else if (g_engineModule) {
// A NativeAOT module can't be freed (its runtime keeps threads with frames in it).
LoaderLog("INF", "Reload: NativeAOT engine 0x%08p left mapped (can't unload).", (void*)g_engineModule);
g_engineModule = NULL;
}
unsigned int rc = LoadAndInitEngine();
long freeAfter = LoaderFreeAddressSpaceMb(&largest);
LoaderLog(rc == 0 ? "INF" : "ERR", "Reload: %s (gen %d, %ld MB free, %+ld MB vs before the reload).",
rc == 0 ? "complete" : "re-init FAILED", g_initCount, freeAfter, freeAfter - freeBefore);
}
// ---------------------------------------------------------------------------
// Reload triggers: the engine's named event, and the canonical DLL changing on disk
// ---------------------------------------------------------------------------
static DWORD WINAPI ReloadWatcher(LPVOID unused)
{
(void)unused;
for (;;) {
if (WaitForSingleObject(g_reloadEvent, INFINITE) != WAIT_OBJECT_0) { Sleep(100); continue; }
ULONGLONG last = g_lastReloadDone;
if (last != 0 && GetTickCount64() - last < MIN_RELOAD_INTERVAL_MS) {
LoaderLog("INF", "ReloadWatcher: signal %llu ms after the last reload; coalesced.", GetTickCount64() - last);
continue;
}
long minFree = g_engineIsManaged ? MIN_FREE_MB_CLR : MIN_FREE_MB_AOT;
long freeMb = LoaderFreeAddressSpaceMb(NULL);
if (freeMb < minFree) {
LoaderLog("WRN", "ReloadWatcher: reload REFUSED - only %ld MB of address space free (need %ld MB). "
"Restart the client to load the new engine.", freeMb, minFree);
engine_refused_fn refused = (engine_refused_fn)EngineExport(ENGINE_REFUSED_EXPORT);
if (refused) refused((int)freeMb);
continue;
}
if (InterlockedCompareExchange(&g_reloadInFlight, 1, 0) != 0) {
LoaderLog("INF", "ReloadWatcher: reload already in flight; coalesced.");
continue;
}
Reload();
g_lastReloadDone = GetTickCount64();
InterlockedExchange(&g_reloadInFlight, 0);
int drained = 0;
while (WaitForSingleObject(g_reloadEvent, 0) == WAIT_OBJECT_0) drained++;
if (drained) LoaderLog("INF", "ReloadWatcher: drained %d signal(s) received during the reload.", drained);
}
}
static DWORD WINAPI FileWatcher(LPVOID unused)
{
(void)unused;
for (;;) {
Sleep(1000);
FILETIME now;
if (!FileLastWrite(g_enginePath, &now) || CompareFileTime(&now, &g_canonicalWrite) <= 0) continue;
// Let the writer (cp, dotnet publish) finish before staging from it.
Sleep(500);
FILETIME stable;
if (!FileLastWrite(g_enginePath, &stable) || CompareFileTime(&stable, &now) != 0) continue;
LoaderLog("INF", "FileWatcher: %s changed; signaling reload.", g_enginePath);
g_canonicalWrite = stable;
SetEvent(g_reloadEvent);
}
}
// ---------------------------------------------------------------------------
// Exports
// ---------------------------------------------------------------------------
const char* LoaderDirectory(void) { return g_loaderDir; }
int LoaderGeneration(void) { return g_initCount; }
unsigned int __stdcall RynthCoreInit(void* param)
{
(void)param;
if (InterlockedCompareExchange(&g_initialized, 1, 0) != 0) {
LoaderLog("WRN", "RynthCoreInit called twice; ignoring the second call.");
return 1;
}
HMODULE self = NULL;
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR)&RynthCoreInit, &self);
GetModuleFileNameA(self, g_loaderDir, MAX_PATH);
char* slash = strrchr(g_loaderDir, '\\');
if (slash) *slash = 0;
LoaderLog("INF", "RynthCoreInit (native loader %s) starting in %s.", LOADER_VERSION, g_loaderDir);
{
// Test clients (tools\TestClient, scripts\Test-Clr*.ps1) say so first, so monitors can skip them.
char tag[128];
if (GetEnvironmentVariableA("RYNTHCORE_TEST_CLIENT", tag, sizeof tag) > 0)
LoaderLog("INF", "TestClient: %s", tag);
}
_snprintf_s(g_enginePath, sizeof g_enginePath, _TRUNCATE, "%s\\" ENGINE_DLL_NAME, g_loaderDir);
int managed = IsManagedPe(g_enginePath);
if (managed < 0) {
LoaderLog("ERR", "FATAL: engine DLL not found or unreadable at %s", g_enginePath);
return 3;
}
g_engineIsManaged = managed;
long largest;
long freeMb = LoaderFreeAddressSpaceMb(&largest);
LoaderLog("INF", "Engine is %s; %ld MB of address space free (largest %ld MB).",
managed ? "a managed assembly: hosting CoreCLR" : "NativeAOT", freeMb, largest);
if (!HooksInit(g_loaderDir)) {
LoaderLog("ERR", "FATAL: MinHook could not be loaded from %s", g_loaderDir);
return 6;
}
if (managed) {
int rc = ClrStart(g_loaderDir);
if (rc != 0) {
LoaderLog("ERR", "FATAL: CoreCLR did not start (rc=%d)", rc);
return 7;
}
}
unsigned int rc = LoadAndInitEngine();
if (rc != 0) return rc;
char eventName[128];
_snprintf_s(eventName, sizeof eventName, _TRUNCATE, "Local\\RynthCore.Engine.RequestReload.p%lu", GetCurrentProcessId());
g_reloadEvent = CreateEventA(NULL, FALSE, FALSE, eventName);
if (!g_reloadEvent) {
LoaderLog("WRN", "CreateEvent failed (error %lu); reload disabled.", GetLastError());
return 0;
}
HANDLE t = CreateThread(NULL, 0, ReloadWatcher, NULL, 0, NULL);
if (t) CloseHandle(t);
t = CreateThread(NULL, 0, FileWatcher, NULL, 0, NULL);
if (t) CloseHandle(t);
LoaderLog("INF", "Reload watcher armed on '%s'; file watcher on '%s' (poll 1 s).", eventName, g_enginePath);
return 0;
}
BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID reserved)
{
(void)h; (void)reserved;
if (reason == DLL_PROCESS_ATTACH) {
InitializeCriticalSection(&g_logLock);
DisableThreadLibraryCalls(h);
}
return TRUE;
}

16
native/Loader/Loader.def Normal file
View file

@ -0,0 +1,16 @@
LIBRARY "RynthCore.Loader.dll"
EXPORTS
RynthCoreInit
MH_Initialize
MH_Uninitialize
MH_CreateHook
MH_RemoveHook
MH_EnableHook
MH_DisableHook
MH_StatusToString
RcHooks_Version
RcHooks_Count
RcSubclass_Install
RcSubclass_Release
RcApiStub
RcServices_Version

26
native/Loader/Loader.h Normal file
View file

@ -0,0 +1,26 @@
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define LOADER_VERSION "2.0"
// Loader.c
void LoaderLog(const char* level, const char* fmt, ...);
long LoaderFreeAddressSpaceMb(long* largestMb);
const char* LoaderDirectory(void);
int LoaderGeneration(void);
// Hooks.c: MinHook facade (see the header comment there)
int HooksInit(const char* loaderDir);
void HooksBeginGeneration(int generation);
void HooksPassThroughAll(void);
void HooksFlush(void);
// Services.c: permanent window subclass + plugin API stubs
void ServicesReleaseAll(void);
// Clr.c: CoreCLR host for a managed engine
int ClrStart(const char* loaderDir);
int ClrLoadEngine(int generation, const char* stagedPath);
void ClrUnloadEngine(void);
void* ClrEngineExport(const char* name);

176
native/Loader/Services.c Normal file
View file

@ -0,0 +1,176 @@
// ============================================================================
// Services.c - the other native entry points the engine hands out, made permanent
// (docs/UNLOADABLE_ENGINE_PLAN.md: "nothing native points into collectible code").
//
// 1. Window subclass: RcSubclass_Install puts the loader's own WndProc on a window,
// once for the life of the process, and forwards to the current engine's handler.
// RcSubclass_Release (and every reload) makes it a pure pass-through to the window's
// previous proc. The engine never has to unhook, so a foreign subclasser stacked on
// top of us (Decal, DirectInput) can never be ripped out of the chain, and nothing
// in the chain ever points at an unloaded engine.
//
// 2. Plugin API stubs: RcApiStub(index, fn) returns a permanent stub for table slot
// `index` that jumps to `fn`. Plugins copy the table and can't give it back; after a
// reload the slots are empty until the next engine fills them, and a plugin thread
// that calls one in between waits (any calling convention: registers and stack are
// untouched) and then runs the new engine's function.
// ============================================================================
#include "Loader.h"
// --- 1. window subclass --------------------------------------------------------
#define MAX_SUBCLASSED 16
typedef LRESULT (CALLBACK *wndproc_fn)(HWND, UINT, WPARAM, LPARAM);
typedef struct Subclass {
HWND hwnd;
WNDPROC previous; // the proc we replaced (AC's, or whoever was there)
wndproc_fn volatile handler; // current engine's handler, or NULL = pass-through
} Subclass;
static Subclass g_subclassed[MAX_SUBCLASSED];
static volatile LONG g_subclassCount;
static CRITICAL_SECTION g_servicesLock;
static int g_servicesReady;
static void EnsureServices(void)
{
if (!g_servicesReady) {
InitializeCriticalSection(&g_servicesLock);
g_servicesReady = 1;
}
}
static Subclass* FindSubclass(HWND hwnd)
{
LONG n = g_subclassCount;
for (LONG i = 0; i < n; i++)
if (g_subclassed[i].hwnd == hwnd) return &g_subclassed[i];
return NULL;
}
static LRESULT CALLBACK LoaderWndProc(HWND hwnd, UINT msg, WPARAM w, LPARAM l)
{
Subclass* s = FindSubclass(hwnd);
if (!s) return DefWindowProcA(hwnd, msg, w, l);
wndproc_fn h = s->handler;
if (h) return h(hwnd, msg, w, l);
return CallWindowProcA(s->previous, hwnd, msg, w, l);
}
// Returns 1 and the window's previous proc (what the engine's handler must forward to).
int __stdcall RcSubclass_Install(HWND hwnd, void* handler, void** previousOut)
{
EnsureServices();
int ok = 1;
EnterCriticalSection(&g_servicesLock);
Subclass* s = FindSubclass(hwnd);
if (!s) {
if (g_subclassCount >= MAX_SUBCLASSED) ok = 0;
else {
s = &g_subclassed[g_subclassCount];
s->hwnd = hwnd;
s->handler = NULL;
SetLastError(0);
s->previous = (WNDPROC)SetWindowLongA(hwnd, GWL_WNDPROC, (LONG)(LONG_PTR)LoaderWndProc);
if (!s->previous) {
LoaderLog("ERR", "Subclass: SetWindowLong on 0x%p failed (error %lu)", (void*)hwnd, GetLastError());
ok = 0;
} else {
InterlockedIncrement(&g_subclassCount);
LoaderLog("INF", "Subclass: 0x%p subclassed for good (previous proc 0x%p).", (void*)hwnd, (void*)s->previous);
}
}
}
if (ok) {
s->handler = (wndproc_fn)handler;
if (previousOut) *previousOut = (void*)s->previous;
}
LeaveCriticalSection(&g_servicesLock);
return ok;
}
int __stdcall RcSubclass_Release(HWND hwnd)
{
Subclass* s = FindSubclass(hwnd);
if (!s) return 0;
s->handler = NULL;
return 1;
}
// --- 2. plugin API stubs --------------------------------------------------------
#define MAX_API_STUBS 512
#define API_STUB_SIZE 32
static void* volatile g_apiSlots[MAX_API_STUBS];
static unsigned char* g_apiStubs;
static volatile LONG g_apiWaitLogged;
// Called from a stub whose slot is empty (between engine generations). Blocks until the
// next engine fills the table. stdcall, one argument; the stub saves every register.
static void __stdcall ApiWait(int index)
{
DWORD start = GetTickCount();
int logged = 0;
while (g_apiSlots[index] == NULL) {
Sleep(10);
if (!logged && GetTickCount() - start > 10000) {
logged = 1;
LoaderLog("WRN", "ApiStub: a plugin thread has waited 10 s for API slot %d (no engine loaded?).", index);
}
}
}
static void BuildApiStub(int i)
{
unsigned char* p = g_apiStubs + i * API_STUB_SIZE;
unsigned char* start = p;
void* volatile* slot = &g_apiSlots[i];
*p++ = 0xA1; *(void* volatile**)p = slot; p += 4; // mov eax, [slot]
*p++ = 0x85; *p++ = 0xC0; // test eax, eax
*p++ = 0x74; *p++ = 0x02; // jz +2 (wait)
*p++ = 0xFF; *p++ = 0xE0; // jmp eax
*p++ = 0x60; // pushad
*p++ = 0x68; *(int*)p = i; p += 4; // push i
*p++ = 0xE8; *(int*)p = (int)((unsigned char*)ApiWait - (p + 4)); p += 4; // call ApiWait
*p++ = 0x61; // popad
*p++ = 0xE9; *(int*)p = (int)(start - (p + 4)); p += 4; // jmp start
while (p < start + API_STUB_SIZE) *p++ = 0xCC;
}
void* __stdcall RcApiStub(int index, void* fn)
{
EnsureServices();
if (index < 0 || index >= MAX_API_STUBS) return fn;
EnterCriticalSection(&g_servicesLock);
if (!g_apiStubs) {
g_apiStubs = (unsigned char*)VirtualAlloc(NULL, MAX_API_STUBS * API_STUB_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (g_apiStubs) {
for (int i = 0; i < MAX_API_STUBS; i++) BuildApiStub(i);
FlushInstructionCache(GetCurrentProcess(), g_apiStubs, MAX_API_STUBS * API_STUB_SIZE);
}
}
LeaveCriticalSection(&g_servicesLock);
if (!g_apiStubs) return fn;
// Already one of ours (a table wrapped twice): never point a slot at a stub.
if ((unsigned char*)fn >= g_apiStubs && (unsigned char*)fn < g_apiStubs + MAX_API_STUBS * API_STUB_SIZE)
return fn;
InterlockedExchangePointer((PVOID volatile*)&g_apiSlots[index], fn);
return g_apiStubs + index * API_STUB_SIZE;
}
// Every reload: nothing we hand out may keep pointing into the old engine.
void ServicesReleaseAll(void)
{
EnsureServices();
EnterCriticalSection(&g_servicesLock);
for (LONG i = 0; i < g_subclassCount; i++) g_subclassed[i].handler = NULL;
for (int i = 0; i < MAX_API_STUBS; i++) g_apiSlots[i] = NULL;
LeaveCriticalSection(&g_servicesLock);
LoaderLog("INF", "Services: %ld window subclass(es) pass through, plugin API slots emptied until the next engine.", g_subclassCount);
}
int __stdcall RcServices_Version(void) { return 1; }

2
native/cimgui/.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
# Applied with git apply to an LF checkout: keep the bytes as committed.
*.patch -text

3
native/cimgui/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
_src/
_build/
_textedit/

View file

@ -0,0 +1,47 @@
# RynthCore cimgui build: upstream cimgui 1.91.6dock (fetched into _src by
# scripts/Build-Cimgui.ps1) plus rynth_imconfig.h and rynth_cimgui_ext.cpp,
# and ImGuiColorTextEdit (fetched into _textedit, patched by
# textedit-rynth.patch) with its C exports in rynth_textedit_ext.cpp.
# Output: a 32-bit cimgui.dll whose structs match ImGui.NET 1.91.6.1.
cmake_minimum_required(VERSION 3.15)
cmake_policy(SET CMP0091 NEW)
project(rynth_cimgui CXX)
set(CMAKE_CXX_STANDARD 17)
# Static CRT, like the stock ImGui.NET native build: no VC++ redistributable needed.
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
set(SRC ${CMAKE_CURRENT_SOURCE_DIR}/_src)
set(TEXTEDIT ${CMAKE_CURRENT_SOURCE_DIR}/_textedit)
add_library(cimgui SHARED
${SRC}/cimgui.cpp
${SRC}/imgui/imgui.cpp
${SRC}/imgui/imgui_draw.cpp
${SRC}/imgui/imgui_demo.cpp
${SRC}/imgui/imgui_tables.cpp
${SRC}/imgui/imgui_widgets.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rynth_cimgui_ext.cpp
${TEXTEDIT}/TextEditor.cpp
${TEXTEDIT}/LanguageDefinitions.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rynth_textedit_ext.cpp
)
# Same defines as upstream cimgui's CMakeLists, except the user config.
target_compile_definitions(cimgui PRIVATE
IMGUI_USER_CONFIG=\"rynth_imconfig.h\"
IMGUI_DISABLE_OBSOLETE_FUNCTIONS=1
"IMGUI_IMPL_API=extern \"C\" __declspec(dllexport)"
)
target_include_directories(cimgui PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${SRC}
${SRC}/imgui
${TEXTEDIT}
${CMAKE_CURRENT_SOURCE_DIR}/textedit_shim
)
# ImGuiColorTextEdit uses std::string/printf-style code MSVC warns about.
set_source_files_properties(${TEXTEDIT}/TextEditor.cpp ${TEXTEDIT}/LanguageDefinitions.cpp
PROPERTIES COMPILE_OPTIONS "/wd4244;/wd4267;/wd4018;/wd4305")
set_target_properties(cimgui PROPERTIES PREFIX "")
target_link_libraries(cimgui imm32)

View file

@ -0,0 +1,118 @@
// ============================================================================
// RynthCore cimgui build - extra exports compiled into cimgui.dll.
//
// RynthImGui_BuildTag identifies this build (the engine refuses others).
// RynthImGui_GetLayout sizes/offsets/enum counts the engine compares
// against ImGui.NET's structs before creating a
// context (see ImGuiSelfTest.cs; same index order).
// RynthImGui_ReportAssert IM_ASSERT target (rynth_imconfig.h); records into
// a ring buffer the engine polls from AC's thread.
// ============================================================================
#include "imgui.h"
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#define RYNTH_EXPORT extern "C" __declspec(dllexport)
// ---- Build tag -------------------------------------------------------------
// Bump the trailing number whenever the layout table or config changes.
RYNTH_EXPORT const char* RynthImGui_BuildTag(void)
{
return "rynth-cimgui 1.91.6dock ImTextureID=void* soft-assert layout-1 textedit-264bee4";
}
// ---- Layout table ------------------------------------------------------------
// Index order is a contract with ImGuiSelfTest.ExpectedLayout(); append only.
RYNTH_EXPORT int RynthImGui_GetLayout(int* out, int capacity)
{
const int values[] =
{
1, // 0 table version
(int)sizeof(ImTextureID), // 1
(int)sizeof(ImWchar), // 2
(int)sizeof(ImDrawIdx), // 3
(int)sizeof(ImDrawVert), // 4
(int)sizeof(ImDrawCmd), // 5
(int)offsetof(ImDrawCmd, TextureId), // 6
(int)offsetof(ImDrawCmd, VtxOffset), // 7
(int)offsetof(ImDrawCmd, IdxOffset), // 8
(int)offsetof(ImDrawCmd, ElemCount), // 9
(int)offsetof(ImDrawCmd, UserCallback), // 10
(int)sizeof(ImDrawList), // 11
(int)offsetof(ImDrawList, VtxBuffer), // 12
(int)sizeof(ImDrawData), // 13
(int)offsetof(ImDrawData, CmdLists), // 14
(int)offsetof(ImDrawData, DisplayPos), // 15
(int)offsetof(ImDrawData, DisplaySize), // 16
(int)sizeof(ImFontAtlas), // 17
(int)offsetof(ImFontAtlas, TexID), // 18
(int)sizeof(ImFont), // 19
(int)sizeof(ImFontGlyph), // 20
(int)sizeof(ImFontConfig), // 21
(int)sizeof(ImGuiIO), // 22
(int)offsetof(ImGuiIO, Fonts), // 23
(int)offsetof(ImGuiIO, WantCaptureMouse), // 24
(int)offsetof(ImGuiIO, WantTextInput), // 25
(int)sizeof(ImGuiStyle), // 26
(int)sizeof(ImGuiViewport), // 27
(int)sizeof(ImGuiPlatformIO), // 28
(int)sizeof(ImGuiInputTextCallbackData), // 29
(int)sizeof(ImGuiListClipper), // 30
(int)sizeof(ImGuiPayload), // 31
(int)sizeof(ImGuiTableSortSpecs), // 32
(int)sizeof(ImGuiTableColumnSortSpecs), // 33
(int)sizeof(ImGuiStorage), // 34
(int)sizeof(ImGuiWindowClass), // 35
(int)sizeof(ImGuiSizeCallbackData), // 36
(int)ImGuiCol_COUNT, // 37
(int)ImGuiKey_NamedKey_END, // 38
(int)ImGuiStyleVar_COUNT, // 39
(int)ImGuiMouseCursor_COUNT, // 40
};
const int count = (int)(sizeof(values) / sizeof(values[0]));
if (out != NULL)
for (int i = 0; i < count && i < capacity; i++)
out[i] = values[i];
return count;
}
// ---- Soft asserts ------------------------------------------------------------
// ImGui runs on one thread (AC's render thread); the engine polls on the same
// thread, so plain statics are enough. The ring keeps the last 16 failures.
static const int kAssertSlots = 16;
static const int kAssertTextLen = 256;
static int g_assertCount;
static char g_assertText[kAssertSlots][kAssertTextLen];
extern "C" void RynthImGui_ReportAssert(const char* expr, const char* file, int line)
{
const char* base = file;
for (const char* p = file; *p; p++)
if (*p == '\\' || *p == '/')
base = p + 1;
char* slot = g_assertText[g_assertCount % kAssertSlots];
_snprintf_s(slot, kAssertTextLen, _TRUNCATE, "%s:%d: %s", base, line, expr);
g_assertCount++;
}
// Total failures since load (monotonic; wraps only after 2^31).
RYNTH_EXPORT int RynthImGui_GetAssertCount(void)
{
return g_assertCount;
}
// Copies failure number `index` (0-based, < count) into buf. Returns the
// length copied, or -1 when that entry was already overwritten or not yet made.
RYNTH_EXPORT int RynthImGui_GetAssertText(int index, char* buf, int capacity)
{
if (buf == NULL || capacity <= 0 || index < 0 || index >= g_assertCount || index < g_assertCount - kAssertSlots)
return -1;
const char* src = g_assertText[index % kAssertSlots];
int len = (int)strnlen(src, kAssertTextLen);
if (len >= capacity) len = capacity - 1;
memcpy(buf, src, (size_t)len);
buf[len] = '\0';
return len;
}

View file

@ -0,0 +1,26 @@
// ============================================================================
// RynthCore cimgui build - Dear ImGui user config (IMGUI_USER_CONFIG).
// Replaces upstream cimgui's cimconfig.h (which only did #undef NDEBUG).
// ============================================================================
#pragma once
// ImGui.NET 1.91.6.1 declares ImTextureID as IntPtr (pointer-sized). Dear ImGui
// 1.91.4+ defaults it to ImU64, which on x86 makes ImDrawCmd, ImDrawList and
// ImFontAtlas wider than ImGui.NET's structs and shifts every by-value texture
// argument (SetTexID, Image, AddImage, ...). This is why the stock NuGet x86
// cimgui.dll does not match its own wrapper. A named typedef (not a bare
// "void*" macro) keeps functional casts like ImTextureID() valid.
typedef void* RynthImTextureID;
#define ImTextureID RynthImTextureID
// Soft asserts. A failed IM_ASSERT is recorded in a small native ring buffer
// (rynth_cimgui_ext.cpp) that the engine polls and logs; control flow then
// continues exactly as in a release build with asserts compiled out. The
// handler never calls into managed code (a managed exception inside a native
// frame fail-fasts the process).
#ifdef __cplusplus
extern "C"
#endif
void RynthImGui_ReportAssert(const char* expr, const char* file, int line);
#define IM_ASSERT(_EXPR) do { if (!(_EXPR)) RynthImGui_ReportAssert(#_EXPR, __FILE__, __LINE__); } while (0)

View file

@ -0,0 +1,308 @@
// ============================================================================
// RynthCore cimgui build - C exports for ImGuiColorTextEdit (santaclose fork,
// fetched into _textedit and patched by textedit-rynth.patch).
//
// The engine P/Invokes these by hand (ImGui/TextEditorNative.cs). Every call
// is made on AC's render thread inside an ImGui frame (Create reads the style,
// so it needs a current context too). Strings are UTF-8; returned pointers
// stay valid until the next call of the same export.
//
// Languages: 1 = Meta (.af source: coloured by the tokenizer below from the
// vocabulary the engine passes in), 2 = Lua (the fork's own definition).
// ============================================================================
#include <algorithm>
#include <string>
#include <unordered_set>
#include "TextEditor.h"
#define RYNTH_EXPORT extern "C" __declspec(dllexport)
struct RynthTextEditAccess
{
typedef TextEditor::PaletteIndex PI;
static std::unordered_set<std::string>& StructWords() { static std::unordered_set<std::string> s; return s; }
static std::unordered_set<std::string>& ConditionWords() { static std::unordered_set<std::string> s; return s; }
static std::unordered_set<std::string>& ActionWords() { static std::unordered_set<std::string> s; return s; }
static bool IsWordStart(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; }
static bool IsDigit(char c) { return c >= '0' && c <= '9'; }
static bool IsWordChar(char c) { return IsWordStart(c) || IsDigit(c); }
// Mirrors MetaSourceEditor.MetaColorizer: "~~" comments to the end of the
// line, braces, numbers (hex and signed too), STATE:/IF:/DO:/NAV: (the
// colon included), condition keywords, action keywords.
static bool TokenizeMeta(const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end, PI& color)
{
while (in_begin < in_end && (*in_begin == ' ' || *in_begin == '\t'))
in_begin++;
if (in_begin == in_end)
{
out_begin = out_end = in_end;
color = PI::Default;
return true;
}
const char* p = in_begin;
out_begin = p;
char c = *p;
if (c == '~' && p + 1 < in_end && p[1] == '~')
{
out_end = in_end;
color = PI::Comment;
return true;
}
if (c == '{' || c == '}')
{
out_end = p + 1;
color = PI::Punctuation;
return true;
}
if (IsDigit(c) || (c == '-' && p + 1 < in_end && IsDigit(p[1])))
{
p++;
while (p < in_end && (IsWordChar(*p) || *p == '.'))
p++;
out_end = p;
color = PI::Number;
return true;
}
if (IsWordStart(c))
{
p++;
while (p < in_end && IsWordChar(*p))
p++;
std::string word(in_begin, p);
std::transform(word.begin(), word.end(), word.begin(), [](char ch) { return (char)::toupper((unsigned char)ch); });
color = PI::Default;
if (p < in_end && *p == ':' && StructWords().count(word) != 0)
{
p++;
color = PI::Keyword;
}
else if (ConditionWords().count(word) != 0)
color = PI::KnownIdentifier;
else if (ActionWords().count(word) != 0)
color = PI::PreprocIdentifier;
out_end = p;
return true;
}
// Anything else (punctuation, UTF-8 bytes): one byte, default colour.
out_end = p + 1;
color = PI::Default;
return true;
}
static const TextEditor::LanguageDefinition& MetaLanguage()
{
static TextEditor::LanguageDefinition def;
static bool built = false;
if (!built)
{
built = true;
def.mName = "Meta";
def.mTokenize = &TokenizeMeta;
def.mSingleLineComment = "~~"; // Ctrl+/ toggles "~~"
// An empty block-comment start matches everywhere in ColorizeInternal,
// so give it one that never occurs in text.
def.mCommentStart = "\x01\x02";
def.mCommentEnd = "\x02\x01";
def.mPreprocChar = '\x01';
def.mCaseSensitive = false;
def.mTokenizerOwnsComments = true; // TokenizeMeta colours "~~" itself
}
return def;
}
static void SetLanguage(TextEditor* ed, int language)
{
if (language == 1)
{
ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::None);
ed->mLanguageDefinition = &MetaLanguage();
ed->Colorize();
}
else if (language == 2)
ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::Lua);
else
ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::None);
}
static void SetPalette(TextEditor* ed, const ImU32* colors, int count)
{
int n = std::min(count, (int)PI::Max);
for (int i = 0; i < n; i++)
ed->mPalette[i] = colors[i];
}
static void CursorScreenPos(TextEditor* ed, float* x, float* y)
{
TextEditor::Coordinates at = ed->GetSanitizedCursorCoordinates();
*x = ed->mTextOrigin.x + ed->mTextStart + ed->TextDistanceToLineStart(at);
*y = ed->mTextOrigin.y + (at.mLine + 1) * ed->mCharAdvance.y;
}
static std::string LinePrefix(TextEditor* ed)
{
TextEditor::Coordinates at = ed->GetSanitizedCursorCoordinates();
return ed->GetText(TextEditor::Coordinates(at.mLine, 0), at);
}
// Completion: replace the `bytes` characters before the cursor with `text`,
// as one undo step.
static void ReplaceBeforeCursor(TextEditor* ed, int bytes, const char* text)
{
if (ed->mReadOnly)
return;
ed->ClearExtraCursors();
ed->ClearSelections();
TextEditor::Coordinates end = ed->GetSanitizedCursorCoordinates();
int endIndex = ed->GetCharacterIndexR(end);
int startIndex = std::max(0, endIndex - std::max(0, bytes));
TextEditor::Coordinates start(end.mLine, ed->GetCharacterColumn(end.mLine, startIndex));
TextEditor::UndoRecord u;
u.mBefore = ed->mState;
if (start < end)
{
ed->SetSelection(start, end);
u.mOperations.push_back({ ed->GetSelectedText(), start, end, TextEditor::UndoOperationType::Delete });
ed->DeleteSelection();
}
TextEditor::Coordinates insertAt = ed->GetSanitizedCursorCoordinates();
ed->InsertTextAtCursor(text);
u.mOperations.push_back({ std::string(text), insertAt, ed->GetSanitizedCursorCoordinates(), TextEditor::UndoOperationType::Add });
u.mAfter = ed->mState;
ed->AddUndo(u);
}
};
static void FillWordSet(std::unordered_set<std::string>& set, const char* words)
{
set.clear();
if (words == nullptr)
return;
std::string current;
for (const char* p = words;; p++)
{
if (*p == '\n' || *p == '\0')
{
if (!current.empty())
set.insert(current);
current.clear();
if (*p == '\0')
break;
}
else
current.push_back((char)::toupper((unsigned char)*p));
}
}
RYNTH_EXPORT TextEditor* RynthTE_Create(void)
{
TextEditor* ed = new TextEditor();
ed->SetShowWhitespacesEnabled(false);
return ed;
}
RYNTH_EXPORT void RynthTE_Destroy(TextEditor* ed)
{
delete ed;
}
/// Newline-separated words, matched case-insensitively. Applies to every Meta editor.
RYNTH_EXPORT void RynthTE_SetMetaVocabulary(const char* structWords, const char* conditionWords, const char* actionWords)
{
FillWordSet(RynthTextEditAccess::StructWords(), structWords);
FillWordSet(RynthTextEditAccess::ConditionWords(), conditionWords);
FillWordSet(RynthTextEditAccess::ActionWords(), actionWords);
}
RYNTH_EXPORT void RynthTE_SetLanguage(TextEditor* ed, int language)
{
RynthTextEditAccess::SetLanguage(ed, language);
}
/// `count` ImU32 colours in TextEditor::PaletteIndex order.
RYNTH_EXPORT void RynthTE_SetPalette(TextEditor* ed, const ImU32* colors, int count)
{
RynthTextEditAccess::SetPalette(ed, colors, count);
}
RYNTH_EXPORT void RynthTE_SetOptions(TextEditor* ed, int readOnly, int showWhitespaces, int showLineNumbers, int tabSize)
{
ed->SetReadOnlyEnabled(readOnly != 0);
ed->SetShowWhitespacesEnabled(showWhitespaces != 0);
ed->SetShowLineNumbersEnabled(showLineNumbers != 0);
ed->SetTabSize(tabSize);
}
RYNTH_EXPORT void RynthTE_SetText(TextEditor* ed, const char* utf8)
{
ed->SetText(utf8 != nullptr ? std::string(utf8) : std::string());
}
RYNTH_EXPORT const char* RynthTE_GetText(TextEditor* ed, int* length)
{
static std::string text;
text = ed->GetText();
if (length != nullptr)
*length = (int)text.size();
return text.c_str();
}
RYNTH_EXPORT unsigned RynthTE_GetChangeCount(TextEditor* ed)
{
return ed->GetChangeCount();
}
/// Draws the editor as a child window; returns whether it has keyboard focus.
RYNTH_EXPORT int RynthTE_Render(TextEditor* ed, const char* id, float width, float height, int border)
{
return ed->Render(id, false, ImVec2(width, height), border != 0) ? 1 : 0;
}
RYNTH_EXPORT void RynthTE_GetCursor(TextEditor* ed, int* line, int* column)
{
ed->GetCursorPosition(*line, *column);
}
RYNTH_EXPORT void RynthTE_SetCursor(TextEditor* ed, int line, int charIndex)
{
ed->SetCursorPosition(line, charIndex);
}
/// Screen position of the bottom-left corner of the cursor's cell (valid after Render).
RYNTH_EXPORT void RynthTE_GetCursorScreenPos(TextEditor* ed, float* x, float* y)
{
RynthTextEditAccess::CursorScreenPos(ed, x, y);
}
/// The cursor's line up to the cursor.
RYNTH_EXPORT const char* RynthTE_GetLinePrefix(TextEditor* ed, int* length)
{
static std::string prefix;
prefix = RynthTextEditAccess::LinePrefix(ed);
if (length != nullptr)
*length = (int)prefix.size();
return prefix.c_str();
}
RYNTH_EXPORT void RynthTE_ReplaceBeforeCursor(TextEditor* ed, int bytes, const char* utf8)
{
RynthTextEditAccess::ReplaceBeforeCursor(ed, bytes, utf8 != nullptr ? utf8 : "");
}
/// While set, the editor ignores Up/Down/PageUp/PageDown/Enter/Tab/Escape (the host's completion list uses them).
RYNTH_EXPORT void RynthTE_SetCompletionKeysHeld(TextEditor* ed, int held)
{
ed->SetCompletionKeysHeld(held != 0);
}
RYNTH_EXPORT void RynthTE_RequestFocus(TextEditor* ed)
{
ed->RequestFocus();
}

View file

@ -0,0 +1,129 @@
diff --git a/TextEditor.cpp b/TextEditor.cpp
index 013111f..9cd55a1 100644
--- a/TextEditor.cpp
+++ b/TextEditor.cpp
@@ -325,13 +325,19 @@ void TextEditor::Paste()
void TextEditor::Undo(int aSteps)
{
while (CanUndo() && aSteps-- > 0)
+ {
mUndoBuffer[--mUndoIndex].Undo(this);
+ ++mChangeCount;
+ }
}
void TextEditor::Redo(int aSteps)
{
while (CanRedo() && aSteps-- > 0)
+ {
mUndoBuffer[mUndoIndex++].Redo(this);
+ ++mChangeCount;
+ }
}
void TextEditor::SetText(const std::string& aText)
@@ -355,6 +361,7 @@ void TextEditor::SetText(const std::string& aText)
mUndoBuffer.clear();
mUndoIndex = 0;
+ ++mChangeCount;
Colorize();
}
@@ -392,6 +399,7 @@ void TextEditor::SetTextLines(const std::vector<std::string>& aLines)
mUndoBuffer.clear();
mUndoIndex = 0;
+ ++mChangeCount;
Colorize();
}
@@ -428,6 +436,11 @@ bool TextEditor::Render(const char* aTitle, bool aParentIsFocused, const ImVec2&
ImGui::BeginChild(aTitle, aSize, aBorder, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNavInputs);
+ if (mFocusRequested)
+ {
+ ImGui::SetWindowFocus();
+ mFocusRequested = false;
+ }
bool isFocused = ImGui::IsWindowFocused();
HandleKeyboardInputs(aParentIsFocused);
HandleMouseInputs();
@@ -1993,7 +2006,12 @@ void TextEditor::HandleKeyboardInputs(bool aParentIsFocused)
io.WantCaptureKeyboard = true;
io.WantTextInput = true;
- if (!mReadOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Z))
+ if (mCompletionKeysHeld && (ImGui::IsKeyPressed(ImGuiKey_UpArrow) || ImGui::IsKeyPressed(ImGuiKey_DownArrow) ||
+ ImGui::IsKeyPressed(ImGuiKey_PageUp) || ImGui::IsKeyPressed(ImGuiKey_PageDown) ||
+ ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter) ||
+ ImGui::IsKeyPressed(ImGuiKey_Tab) || ImGui::IsKeyPressed(ImGuiKey_Escape)))
+ ; // the host's completion list owns these keys
+ else if (!mReadOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Z))
Undo();
else if (!mReadOnly && isAltOnly && ImGui::IsKeyPressed(ImGuiKey_Backspace))
Undo();
@@ -2238,6 +2256,7 @@ void TextEditor::Render(bool aParentIsFocused)
}
ImVec2 cursorScreenPos = ImGui::GetCursorScreenPos();
+ mTextOrigin = cursorScreenPos;
mScrollX = ImGui::GetScrollX();
mScrollY = ImGui::GetScrollY();
UpdateViewVariables(mScrollX, mScrollY);
@@ -2549,6 +2568,7 @@ void TextEditor::AddUndo(UndoRecord& aValue)
mUndoBuffer.resize((size_t)(mUndoIndex + 1));
mUndoBuffer.back() = aValue;
++mUndoIndex;
+ ++mChangeCount;
}
// TODO
@@ -2687,6 +2707,8 @@ void TextEditor::ColorizeInternal()
if (mLines.empty() || mLanguageDefinition == nullptr)
return;
+ if (mCheckComments && mLanguageDefinition->mTokenizerOwnsComments)
+ mCheckComments = false;
if (mCheckComments)
{
auto endLine = mLines.size();
diff --git a/TextEditor.h b/TextEditor.h
index 19ad61b..6883412 100644
--- a/TextEditor.h
+++ b/TextEditor.h
@@ -97,6 +97,14 @@ public:
void ImGuiDebugPanel(const std::string& panelName = "Debug");
void UnitTests();
+ // RynthCore (native/cimgui/textedit-rynth.patch): a text change counter, a
+ // hold-off on the keys the host's completion list uses, a focus request,
+ // and access for the C exports in rynth_textedit_ext.cpp.
+ inline unsigned GetChangeCount() const { return mChangeCount; }
+ inline void SetCompletionKeysHeld(bool aValue) { mCompletionKeysHeld = aValue; }
+ inline void RequestFocus() { mFocusRequested = true; }
+ friend struct RynthTextEditAccess;
+
private:
// ------------- Generic utils ------------- //
@@ -280,6 +288,7 @@ private:
TokenizeCallback mTokenize = nullptr;
std::vector<TokenRegexString> mTokenRegexStrings;
bool mCaseSensitive = true;
+ bool mTokenizerOwnsComments = false; // RynthCore: skip the whole-text comment scan
static const LanguageDefinition& Cpp();
static const LanguageDefinition& Hlsl();
@@ -452,6 +461,10 @@ private:
Palette mPalette;
LanguageDefinitionId mLanguageDefinitionId;
const LanguageDefinition* mLanguageDefinition = nullptr;
+ unsigned mChangeCount = 0;
+ bool mCompletionKeysHeld = false;
+ bool mFocusRequested = false;
+ ImVec2 mTextOrigin;
inline bool IsHorizontalScrollbarVisible() const { return mCurrentSpaceWidth > mContentWidth; }
inline bool IsVerticalScrollbarVisible() const { return mCurrentSpaceHeight > mContentHeight; }

View file

@ -0,0 +1,13 @@
// RynthCore: ImGuiColorTextEdit (santaclose fork) includes <boost/regex.hpp>.
// Its regex path only runs for languages without a hand-written tokenizer, and
// the two we use (Meta, Lua) both have one, so std::regex stands in for Boost.
#pragma once
#include <regex>
namespace boost
{
using std::regex;
using std::cmatch;
using std::regex_search;
namespace regex_constants = std::regex_constants;
}

93
scripts/Build-Cimgui.ps1 Normal file
View file

@ -0,0 +1,93 @@
<#
.SYNOPSIS
Builds the engine's 32-bit cimgui.dll from pinned upstream sources.
.DESCRIPTION
Fetches cimgui at tag 1.91.6dock (and its Dear ImGui submodule) into
native\cimgui\_src, verifies both commits, fetches ImGuiColorTextEdit
(santaclose fork, the Meta/Lua source editor) into native\cimgui\_textedit
at a pinned commit and applies native\cimgui\textedit-rynth.patch, builds
with MSVC via CMake (Win32, Release, static CRT) using
native\cimgui\CMakeLists.txt, and copies
the result to src\RynthCore.Engine\Native\cimgui.dll.
Why a custom build: ImGui.NET 1.91.6.1 treats ImTextureID as a pointer,
but Dear ImGui 1.91.6 defaults it to a 64-bit integer, so on x86 the stock
NuGet cimgui.dll does not match the wrapper (see native\cimgui\rynth_imconfig.h).
Needs git and Visual Studio 2022 (Build Tools is enough) with the C++
workload; CMake is taken from PATH or from the VS install.
.PARAMETER Clean
Delete the CMake build directory first.
#>
[CmdletBinding()]
param(
[switch]$Clean
)
$ErrorActionPreference = 'Stop'
$Tag = '1.91.6dock'
$CimguiCommit = '970c614802935f51f451aa21ae06e838bdcf9349'
$ImguiCommit = '947aa9c9722bd6ff740dd757da609ff41f4d3ba3'
$TextEditCommit = '264bee49ddc3c789b05d928d09c628649458da47'
$repoRoot = Split-Path -Parent $PSScriptRoot
$nativeDir = Join-Path $repoRoot 'native\cimgui'
$srcDir = Join-Path $nativeDir '_src'
$textEditDir = Join-Path $nativeDir '_textedit'
$textEditPatch = Join-Path $nativeDir 'textedit-rynth.patch'
$buildDir = Join-Path $nativeDir '_build'
$outDll = Join-Path $repoRoot 'src\RynthCore.Engine\Native\cimgui.dll'
function Invoke-Checked([string]$What, [scriptblock]$Command) {
& $Command
if ($LASTEXITCODE -ne 0) { throw "$What failed (exit $LASTEXITCODE)" }
}
# ---- Sources ----
if (-not (Test-Path -LiteralPath $srcDir)) {
Write-Host "Fetching cimgui $Tag ..."
Invoke-Checked 'git clone' { git clone -q --depth 1 --branch $Tag --recurse-submodules --shallow-submodules https://github.com/cimgui/cimgui $srcDir }
}
$head = (git -C $srcDir rev-parse HEAD).Trim()
$imguiHead = (git -C (Join-Path $srcDir 'imgui') rev-parse HEAD).Trim()
if ($head -ne $CimguiCommit) { throw "native\cimgui\_src is at $head, expected $CimguiCommit ($Tag). Delete _src and rerun." }
if ($imguiHead -ne $ImguiCommit) { throw "native\cimgui\_src\imgui is at $imguiHead, expected $ImguiCommit. Delete _src and rerun." }
# ImGuiColorTextEdit: no submodules (its Boost.Regex is replaced by
# textedit_shim\boost\regex.hpp). LF checkout so the committed patch applies.
if (-not (Test-Path -LiteralPath $textEditDir)) {
Write-Host "Fetching ImGuiColorTextEdit $TextEditCommit ..."
Invoke-Checked 'git clone (textedit)' { git -c core.autocrlf=false clone -q --no-checkout https://github.com/santaclose/ImGuiColorTextEdit $textEditDir }
Invoke-Checked 'git checkout (textedit)' { git -C $textEditDir -c core.autocrlf=false checkout -q $TextEditCommit }
}
$teHead = (git -C $textEditDir rev-parse HEAD).Trim()
if ($teHead -ne $TextEditCommit) { throw "native\cimgui\_textedit is at $teHead, expected $TextEditCommit. Delete _textedit and rerun." }
git -C $textEditDir apply --reverse --check $textEditPatch 2>$null
if ($LASTEXITCODE -ne 0) {
Invoke-Checked 'git apply (textedit patch)' { git -C $textEditDir apply $textEditPatch }
}
# ---- CMake ----
$cmake = (Get-Command cmake -ErrorAction SilentlyContinue).Source
if (-not $cmake) {
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
if (-not $vs) { throw 'Visual Studio with the C++ x86/x64 tools was not found.' }
$cmake = Join-Path $vs 'Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'
if (-not (Test-Path -LiteralPath $cmake)) { throw "CMake not found on PATH or at $cmake" }
}
if ($Clean -and (Test-Path -LiteralPath $buildDir)) { Remove-Item -LiteralPath $buildDir -Recurse -Force }
Invoke-Checked 'cmake configure' { & $cmake -S $nativeDir -B $buildDir -G 'Visual Studio 17 2022' -A Win32 }
Invoke-Checked 'cmake build' { & $cmake --build $buildDir --config Release }
$built = Join-Path $buildDir 'Release\cimgui.dll'
if (-not (Test-Path -LiteralPath $built)) { throw "Build produced no $built" }
Copy-Item -LiteralPath $built -Destination $outDll -Force
$size = (Get-Item -LiteralPath $outDll).Length
Write-Host "cimgui.dll ($size bytes) -> $outDll"

View file

@ -15,7 +15,13 @@ param(
# -AcClient overrides the binary it checks (default: auto-detect the private
# copy under $Destination\AcClient, else C:\Turbine\Asheron's Call).
[switch]$SkipPatternCheck,
[string]$AcClient = ""
[string]$AcClient = "",
# The old deploy: NativeAOT loader, engine and plugins (a hot reload leaks every
# generation). The default since 2026-09-29 is the unloadable engine
# (docs/UNLOADABLE_ENGINE_PLAN.md): native loader + CoreCLR engine + app-local runtime
# in Runtime\ (scripts\Publish-EngineCoreClr.ps1), and managed plugins, all of which
# a hot reload frees. Releases (installer\) still ship NativeAOT: players run that engine.
[switch]$NativeAot
)
$ErrorActionPreference = "Stop"
@ -38,7 +44,6 @@ $loaderProject = Join-Path $repoRoot "src\RynthCore.Loader\RynthCore.Loader.cspr
$rynthAiSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi"
$rynthChatSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthChat"
$rynthVisionSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthVision"
$rynthJuiceSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthJuice"
$pluginProjects = @(
@{
Project = Join-Path $rynthAiSourceRoot "RynthCore.Plugin.RynthAi.csproj"
@ -67,15 +72,6 @@ $pluginProjects = @(
DllName = "RynthCore.Plugin.RynthTracker.dll"
DestSubdir = "RynthTracker"
},
# RynthJuice sets <PublishDir> to its deploy home (like RynthVision), so
# publish lands directly in $PluginsDestination\RynthJuice and the copy step
# below detects source == dest and skips the redundant self-copy.
@{
Project = Join-Path $rynthJuiceSourceRoot "RynthCore.Plugin.RynthJuice.csproj"
Publish = Join-Path $PluginsDestination "RynthJuice"
DllName = "RynthCore.Plugin.RynthJuice.dll"
DestSubdir = "RynthJuice"
},
# RynthNav also publishes straight to its deploy home via <PublishDir>.
# It was missing from this list entirely, so full deploys never refreshed it.
@{
@ -83,6 +79,13 @@ $pluginProjects = @(
Publish = Join-Path $PluginsDestination "RynthNav"
DllName = "RynthCore.Plugin.RynthNav.dll"
DestSubdir = "RynthNav"
},
# RynthLua: Lua scripting, split out of RynthAi on 2026-09-29.
@{
Project = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthLua\RynthCore.Plugin.RynthLua.csproj"
Publish = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthLua\bin\Release\net10.0-windows\win-x86\publish"
DllName = "RynthCore.Plugin.RynthLua.dll"
DestSubdir = "RynthLua"
}
)
@ -158,6 +161,13 @@ function Invoke-Publish {
}
}
# Managed plugins publish to (and deploy from) out\plugins-clr\<name>, -SkipPublish too.
if (-not $NativeAot) {
foreach ($plugin in $pluginProjects) {
$plugin.Publish = Join-Path $repoRoot ("out\plugins-clr\" + $plugin.DestSubdir)
}
}
if (-not $SkipPublish) {
$env:DOTNET_CLI_HOME = Join-Path $repoRoot ".dotnet-home-deploy-clean"
$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = "1"
@ -166,10 +176,24 @@ if (-not $SkipPublish) {
# --self-contained false is required: omitting it with the launcher's IncludeNativeLibrariesForSelfExtract=true produces a broken half-payload (apphost + coreclr.dll, no framework) that reports ".NET is not installed".
Invoke-Publish -What "launcher" -Arguments @('publish', $launcherProject, '-c', 'Release', '-r', 'win-x86', '--self-contained', 'false')
}
Invoke-Publish -What "engine" -Arguments @('publish', $engineProject, '-c', 'Release')
Invoke-Publish -What "loader" -Arguments @('publish', $loaderProject, '-c', 'Release')
if ($NativeAot) {
Invoke-Publish -What "engine" -Arguments @('publish', $engineProject, '-c', 'Release')
Invoke-Publish -What "loader" -Arguments @('publish', $loaderProject, '-c', 'Release')
}
# (CoreCLR: the engine, loader and shim are built by Publish-EngineCoreClr.ps1 below,
# after Runtime\ is wiped.)
foreach ($plugin in $pluginProjects) {
Invoke-Publish -What $plugin.DllName -Arguments @('publish', $plugin.Project, '-c', 'Release')
if ($NativeAot) {
Invoke-Publish -What $plugin.DllName -Arguments @('publish', $plugin.Project, '-c', 'Release')
} else {
# Same source, managed: loads into its own collectible context in the CoreCLR
# engine (Plugins/ManagedPlugins.cs). Staged under out\plugins-clr, then copied.
$stage = $plugin.Publish
if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force }
Invoke-Publish -What "$($plugin.DllName) (managed)" -Arguments @('publish', $plugin.Project, '-c', 'Release',
'-p:PublishAot=false', '-p:NativeLib=', '-p:SelfContained=false', '-p:RuntimeIdentifier=win-x86',
'-p:GenerateRuntimeConfigurationFiles=false', '-o', $stage)
}
}
}
@ -256,13 +280,20 @@ if (-not $SkipLauncher) {
Copy-FilteredChildren -Source $launcherPublish -Target $Destination -ExcludeNames @("RynthCore.App.Avalonia.exe") -ExcludeExtensions @(".pdb")
}
# Engine payload to Runtime\. Skip the bundled Plugins\ subfolder - plugins
# are deployed separately to $PluginsDestination so they have a single home.
Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeNames @("Plugins") -ExcludeExtensions @(".pdb")
if ($NativeAot) {
# Engine payload to Runtime\. Skip the bundled Plugins\ subfolder - plugins
# are deployed separately to $PluginsDestination so they have a single home.
Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeNames @("Plugins") -ExcludeExtensions @(".pdb")
# Loader DLL - this is what RynthCore.Injector loads into acclient.exe; the
# Loader then maps RynthCore.Engine.dll and provides hot-reload support.
Copy-Item -LiteralPath (Join-Path $loaderPublish "RynthCore.Loader.dll") -Destination (Join-Path $runtimeDir "RynthCore.Loader.dll") -Force
# Loader DLL - this is what RynthCore.Injector loads into acclient.exe; the
# Loader then maps RynthCore.Engine.dll and provides hot-reload support.
Copy-Item -LiteralPath (Join-Path $loaderPublish "RynthCore.Loader.dll") -Destination (Join-Path $runtimeDir "RynthCore.Loader.dll") -Force
} else {
# Native loader (native\Loader) + RynthCore.Shim + CoreCLR engine (ReadyToRun) + its
# dependencies + Runtime\dotnet (app-local CoreCLR x86). Same contract with the
# injector (RynthCoreInit); the loader also hosts a NativeAOT engine if one is dropped in.
& (Join-Path $PSScriptRoot "Publish-EngineCoreClr.ps1") -Target $runtimeDir
}
# SEH trampoline - small native x86 MSVC DLL providing __try/__except wrappers
# around dangerous AC API calls so object-teardown AVs are caught instead of
@ -302,6 +333,16 @@ foreach ($plugin in $pluginProjects) {
New-Item -ItemType Directory -Path $pluginTargetDir -Force | Out-Null
}
if (-not $NativeAot) {
# A managed plugin is its DLL plus its dependencies (RynthCore.PluginSdk,
# PluginCore, MoonSharp, ImGui.NET...) and pdbs; copy those, leave user data.
foreach ($f in Get-ChildItem -LiteralPath $plugin.Publish -File | Where-Object { $_.Extension -in '.dll', '.pdb' }) {
Copy-Item -LiteralPath $f.FullName -Destination (Join-Path $pluginTargetDir $f.Name) -Force
}
Write-Host "Plugin $($plugin.DllName) (managed) deployed to $pluginTargetDir"
continue
}
# Only the DLL - leave any user data (LootProfiles\, imgui.ini, etc.)
# in place by not touching anything else under $pluginTargetDir.
$pluginDest = Join-Path $pluginTargetDir $plugin.DllName
@ -318,7 +359,10 @@ foreach ($plugin in $pluginProjects) {
# Scoped pdb sweep: root + Runtime\ only. A $Destination-wide recurse walked
# the ~1.4 GB private AcClient copy on every deploy for nothing.
Get-ChildItem -Path $Destination -Filter *.pdb -File | Remove-Item -Force
Get-ChildItem -Path $runtimeDir -Recurse -Filter *.pdb -File | Remove-Item -Force
# (The CoreCLR engine's own pdbs stay: they give its stack traces line numbers.)
Get-ChildItem -Path $runtimeDir -Recurse -Filter *.pdb -File |
Where-Object { $NativeAot -or $_.Name -notin 'RynthCore.Engine.pdb', 'RynthCore.Shim.pdb', 'RynthCore.Loader.pdb' } |
Remove-Item -Force
if (-not $SkipLauncher) {
Write-Host "Launcher deployed to $Destination"

View file

@ -0,0 +1,122 @@
# Publish-EngineCoreClr.ps1
# Builds the CoreCLR-hosted engine (docs/UNLOADABLE_ENGINE_PLAN.md) and lays it out in a
# Runtime folder:
# RynthCore.Loader.dll native loader (native\Loader), hosts CoreCLR
# RynthCore.Shim.dll default-ALC shim (src\RynthCore.Shim)
# RynthCore.Engine.dll (+pdb) the engine as a managed assembly (-p:EngineHost=coreclr)
# Avalonia*, ImGui.NET, ... the engine's managed dependencies (load into its collectible ALC)
# cimgui, minhook, Skia, ... native libraries (process-wide, loaded once)
# dotnet\ app-local CoreCLR x86 (from the NuGet runtime pack)
#
# Default target is the live install; a running client hot-reloads onto a new engine by itself:
# .\scripts\Publish-EngineCoreClr.ps1 -> C:\Games\RynthCore\Runtime
# .\scripts\Publish-EngineCoreClr.ps1 -Target <dir> -EngineOnly (engine + deps only: a hot reload)
param(
[string]$Target = "C:\Games\RynthCore\Runtime",
[string]$Configuration = "Release",
[switch]$EngineOnly,
# The engine is precompiled (ReadyToRun) unless -NoReadyToRun: each generation then
# loads in ~130 ms instead of ~750 (less JIT); the DLL is ~5 MB instead of ~2.
[switch]$NoReadyToRun,
# Extra MSBuild arguments for the engine and shim builds (the installer passes -p:Version=...).
[string[]]$MsBuildArgs = @(),
# Deploy to the live Runtime even though status-export has commits this checkout lacks.
[switch]$AllowBehind
)
$ErrorActionPreference = "Stop"
$repo = Split-Path $PSScriptRoot -Parent
# Deploying to the live install from a checkout that lacks status-export's commits rolls
# back other sessions' engine fixes on every running client (2026-09-29, API v70). Refuse.
$liveRuntime = "C:\Games\RynthCore\Runtime"
if ([IO.Path]::GetFullPath($Target).TrimEnd('\') -ieq $liveRuntime -and -not $AllowBehind) {
git -C $repo merge-base --is-ancestor status-export HEAD 2>$null
if ($LASTEXITCODE -ne 0) {
$missing = git -C $repo log --oneline HEAD..status-export
throw "This checkout is missing status-export commits; deploying it to the live Runtime would roll them back:`n$($missing -join "`n")`nMerge status-export first (or pass -AllowBehind if you really mean it)."
}
}
$env:PATH += ";C:\Program Files (x86)\Microsoft Visual Studio\Installer"
New-Item -ItemType Directory -Force -Path $Target | Out-Null
$stage = Join-Path $repo "out\engine-clr"
if (Test-Path $stage) { Remove-Item $stage -Recurse -Force }
Write-Host "Building the engine (EngineHost=coreclr)..."
$r2r = if (-not $NoReadyToRun) { "-p:PublishReadyToRun=true" } else { "-p:PublishReadyToRun=false" }
dotnet publish "$repo\src\RynthCore.Engine\RynthCore.Engine.csproj" -c $Configuration -p:EngineHost=coreclr $r2r -o $stage -nologo -v q @MsBuildArgs
if ($LASTEXITCODE -ne 0) { throw "engine build failed" }
if (-not $EngineOnly) {
Write-Host "Building the native loader..."
& "$repo\native\Loader\Build-Loader.ps1"
Write-Host "Building the shim..."
dotnet build "$repo\src\RynthCore.Shim\RynthCore.Shim.csproj" -c $Configuration -nologo -v q @MsBuildArgs
if ($LASTEXITCODE -ne 0) { throw "shim build failed" }
# The loader and the shim load once per client: a running client keeps its copy (and
# locks the file) until it restarts. Skip them with a warning rather than fail.
$hostFiles = @(
"$repo\native\Loader\bin\RynthCore.Loader.dll", "$repo\native\Loader\bin\RynthCore.Loader.pdb",
"$repo\src\RynthCore.Shim\bin\$Configuration\net10.0-windows\RynthCore.Shim.dll",
"$repo\src\RynthCore.Shim\bin\$Configuration\net10.0-windows\RynthCore.Shim.pdb")
# A running client holds these files; Windows lets a loaded DLL be renamed, so the old
# copy is moved aside (the client keeps using it) and the new one goes in for the next
# launch. Earlier moved-aside copies are deleted once no client holds them.
Get-ChildItem $Target -Filter "RynthCore.*.old-*" -ErrorAction SilentlyContinue |
ForEach-Object { Remove-Item $_.FullName -Force -ErrorAction SilentlyContinue }
foreach ($f in $hostFiles) {
$dest = Join-Path $Target (Split-Path $f -Leaf)
try { Copy-Item $f $dest -Force -ErrorAction Stop }
catch {
try {
Rename-Item $dest ("{0}.old-{1:yyyyMMddHHmmss}" -f (Split-Path $dest -Leaf), (Get-Date)) -ErrorAction Stop
Copy-Item $f $dest -Force -ErrorAction Stop
Write-Host "$(Split-Path $f -Leaf) was in use: moved the old one aside; new launches get the new one."
}
catch { Write-Warning "$(Split-Path $f -Leaf) is in use by a running client; it keeps the old one until it restarts." }
}
}
$seh = "$repo\native\SehTrampoline\bin\RynthCore.SehTrampoline.dll"
if (-not (Test-Path $seh)) { $seh = "C:\Games\RynthCore\Runtime\RynthCore.SehTrampoline.dll" }
$sehDest = Join-Path (Resolve-Path $Target).Path "RynthCore.SehTrampoline.dll"
$sameSeh = (Test-Path $sehDest) -and ((Resolve-Path $seh).Path -eq $sehDest -or
(Get-FileHash $seh).Hash -eq (Get-FileHash $sehDest).Hash)
if (-not $sameSeh) {
try { Copy-Item $seh $sehDest -Force -ErrorAction Stop }
catch { Write-Warning "RynthCore.SehTrampoline.dll changed but is in use by a running client; it gets the new one when it restarts." }
}
# App-local runtime: the win-x86 runtime pack the SDK restores (same version the engine was built against).
$dotnet = Join-Path $Target "dotnet"
if (-not (Test-Path "$dotnet\coreclr.dll")) {
$pack = Join-Path $env:USERPROFILE ".nuget\packages\microsoft.netcore.app.runtime.win-x86"
$ver = (Get-ChildItem $pack | Where-Object Name -like "10.*" | Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1).Name
if (-not $ver) { throw "microsoft.netcore.app.runtime.win-x86 10.x not in the NuGet cache (restore any win-x86 self-contained project once)" }
$rt = "$pack\$ver\runtimes\win-x86"
New-Item -ItemType Directory -Force -Path $dotnet | Out-Null
Copy-Item "$rt\native\*" $dotnet -Force
Copy-Item "$rt\lib\net10.0\*.dll" $dotnet -Force
# Diagnostics-only natives the host never loads.
Remove-Item "$dotnet\createdump.exe", "$dotnet\mscordaccore_*.dll", "$dotnet\msquic.dll" -Force -ErrorAction SilentlyContinue
Write-Host "App-local runtime $ver -> $dotnet"
}
}
# Engine + dependencies. The canonical RynthCore.Engine.dll goes last: the loader's file
# watcher reloads on its timestamp, so everything it needs must already be in place.
# Only what changed. Native libraries (cimgui, Skia...) are loaded once per client and
# locked while it runs; they rarely change, so a locked unchanged one is simply skipped.
foreach ($f in Get-ChildItem $stage -File | Where-Object { $_.Name -notlike "RynthCore.Engine.*" -and $_.Name -ne "minhook.x86.dll" }) {
$dest = Join-Path $Target $f.Name
if ((Test-Path $dest) -and (Get-Item $dest).Length -eq $f.Length -and
(Get-FileHash $dest).Hash -eq (Get-FileHash $f.FullName).Hash) { continue }
try { Copy-Item $f.FullName $dest -Force -ErrorAction Stop }
catch { Write-Warning "$($f.Name) changed but is in use by a running client; it gets the new one when it restarts." }
}
if (-not (Test-Path "$Target\minhook.x86.dll")) { Copy-Item "$stage\minhook.x86.dll" $Target -Force }
Copy-Item "$stage\RynthCore.Engine.pdb" $Target -Force
Copy-Item "$stage\RynthCore.Engine.dll" $Target -Force
Write-Host "Published the CoreCLR engine to $Target"

View file

@ -0,0 +1,28 @@
# Publish-PluginsCoreClr.ps1
# Builds RynthSuite plugins as MANAGED assemblies for the CoreCLR engine (plan Phase 4): the
# same source as the NativeAOT build, with PublishAot off (command-line properties override
# the csproj). Each plugin lands in its own folder with its dependencies (RynthCore.PluginSdk,
# PluginCore, MoonSharp, ...), which the engine loads into the plugin's collectible context.
#
# For a test build into a separate folder; scripts\Deploy-RynthCore.ps1 is what deploys the
# managed plugins to C:\Games\RynthSuite. The plugins reference ..\..\..\RynthCore\src\... (the
# SDK), so they build against whatever RynthCore checkout sits next to -RynthSuite.
# .\scripts\Publish-PluginsCoreClr.ps1 [-Plugins RynthAi,RynthChat] [-Out <dir>]
param(
[string]$RynthSuite = "C:\Projects\RynthSuite",
[string]$Out = "C:\Games\RynthCore\Test\plugins-clr",
[string[]]$Plugins = @("RynthAi", "RynthChat", "RynthNav", "RynthTracker", "RynthLua", "RynthVision")
)
$ErrorActionPreference = "Stop"
foreach ($name in $Plugins) {
$proj = Join-Path $RynthSuite "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj"
if (-not (Test-Path $proj)) { Write-Warning "${name}: no project at $proj"; continue }
$dest = Join-Path $Out $name
if (Test-Path $dest) { Remove-Item $dest -Recurse -Force }
Write-Host "Building $name (managed)..."
dotnet publish $proj -c Release -p:PublishAot=false -p:NativeLib= -p:SelfContained=false `
-p:RuntimeIdentifier=win-x86 -p:GenerateRuntimeConfigurationFiles=false -o $dest -nologo -v q
if ($LASTEXITCODE -ne 0) { throw "$name build failed" }
Write-Host " -> $dest\RynthCore.Plugin.$name.dll"
}

View file

@ -0,0 +1,62 @@
# Test-ClrReload.ps1 - hot-reload test for the CoreCLR-hosted engine in a throwaway client.
#
# Starts acclient from the private copy against -Server (default: a closed local port, so
# nothing logs in), with its own engine.json (-Settings), reloads it -Reloads times,
# and after each reload prints the loader/shim lines. If a generation did not unload,
# runs tools\AlcRoots against the client to show what still holds it. Kills the client at
# the end unless -Keep.
param(
[string]$Runtime = "C:\Games\RynthCore\Runtime",
[string]$Settings = "C:\Games\RynthCore\Test\engine-noplugins.json",
[int]$Reloads = 1,
[int]$WarmupSeconds = 20,
[int]$SettleSeconds = 15,
[string[]]$ClientArgs = @("-h", "127.0.0.1", "-p", "9", "-a", "spike", "-v", "spike"),
[switch]$Keep,
[switch]$AlwaysRoots
)
$ErrorActionPreference = "Stop"
$repo = Split-Path $PSScriptRoot -Parent
$testClient = "$repo\tools\TestClient\bin\TestClient.exe"
$alcRoots = "$repo\tools\AlcRoots\bin\Release\net10.0\win-x86\AlcRoots.exe"
$env:RYNTHCORE_ENGINE_SETTINGS = $Settings
$env:RYNTHCORE_TEST_CLIENT = "Test-ClrReload" # the loader logs "TestClient: ..." (monitors skip test clients)
# Panel layout (panel_state.txt) lives in %LOCALAPPDATA%\RynthCore and is shared with real
# clients: a test client gets its own so it never moves the player's bar or panels.
$env:LOCALAPPDATA = "C:\Games\RynthCore\Test\localappdata"
New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null
$out = & $testClient "C:\Games\RynthCore\AcClient\acclient.exe" "$Runtime\RynthCore.Loader.dll" RynthCoreInit 0 @ClientArgs
$clientPid = [int](($out | Select-String "TEST_PID=(\d+)").Matches[0].Groups[1].Value)
$log = "C:\Games\RynthCore\Logs\RynthCore.$clientPid.log"
Write-Host "client pid $clientPid, log $log"
Start-Sleep $WarmupSeconds
$seen = 0
function Show-NewLoaderLines {
$lines = @(Get-Content $log | Select-String "\[loader\]|\[ERR\]|\[WRN\]")
$lines[$script:seen..($lines.Count - 1)] | ForEach-Object { $_.Line }
$script:seen = $lines.Count
}
Show-NewLoaderLines
for ($i = 1; $i -le $Reloads; $i++) {
if (-not (Get-Process -Id $clientPid -ErrorAction SilentlyContinue)) { Write-Host "client died"; break }
Write-Host "---- reload $i"
$ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$clientPid")
[void]$ev.Set()
$ev.Dispose()
Start-Sleep $SettleSeconds
Show-NewLoaderLines
$notFreed = Select-String -Path $log -Pattern "NOT unloaded" -Quiet
if ($AlwaysRoots -or ($notFreed -and $i -eq 1)) {
Write-Host "---- AlcRoots"
& $alcRoots $clientPid 30
}
}
if (-not $Keep) {
Stop-Process -Id $clientPid -Force -ErrorAction SilentlyContinue
Write-Host "client $clientPid stopped"
}

97
scripts/Test-ClrWorld.ps1 Normal file
View file

@ -0,0 +1,97 @@
# Test-ClrWorld.ps1 - logs a test character into a LOCAL server with the CoreCLR engine and
# hot-reloads it N times, reporting per generation: unloaded or not, pattern misses, hangs,
# and the frame rate afterwards. Runs tools\AlcRoots when a generation doesn't unload.
#
# Uses the injector's headless --launch with a saved account profile (the password stays in
# the launcher's settings). Only point it at a server you run yourself.
# .\scripts\Test-ClrWorld.ps1 -Account Buffi -Server ACEmulator -Character "+Buffi" -Reloads 5
param(
[string]$Account = "Buffi",
[string]$Server = "ACEmulator",
[string]$Character = "+Buffi",
[string]$Runtime = "C:\Games\RynthCore\Runtime",
[string]$Settings = "C:\Games\RynthCore\Test\engine-plugins.json",
[int]$Reloads = 3,
[int]$WarmupSeconds = 45,
[int]$SettleSeconds = 25,
# Chat commands to run after login and again after every reload (through the test
# client's own dispatch file), e.g. "/rc ui popout Radar".
[string[]]$Commands = @(),
[switch]$Keep
)
$ErrorActionPreference = "Stop"
$repo = Split-Path $PSScriptRoot -Parent
$injector = "$repo\out\injector\RynthCore.Injector.exe"
if (-not (Test-Path $injector)) {
dotnet publish "$repo\src\RynthCore.Injector\RynthCore.Injector.csproj" -c Release -o "$repo\out\injector" -nologo -v q | Out-Null
if (-not (Test-Path $injector)) { throw "could not build the injector" }
}
$alcRoots = "$repo\tools\AlcRoots\bin\Release\net10.0\win-x86\AlcRoots.exe"
$pidFile = "C:\Games\RynthCore\Test\current-pid.txt"
# A client killed without logging off keeps its session on the server for about a minute.
if (Test-Path $pidFile) {
$old = [int](Get-Content $pidFile)
if (Get-Process -Id $old -ErrorAction SilentlyContinue) {
Stop-Process -Id $old -Force
Write-Host "stopped previous test client $old; waiting 65 s for the server to drop its session"
Start-Sleep 65
}
}
$env:RYNTHCORE_ENGINE_SETTINGS = $Settings
$env:RYNTHCORE_TEST_CLIENT = "Test-ClrWorld" # the loader logs "TestClient: ..." (monitors skip test clients)
# Panel layout (panel_state.txt) lives in %LOCALAPPDATA%\RynthCore and is shared with real
# clients: a test client gets its own so it never moves the player's bar or panels.
$env:LOCALAPPDATA = "C:\Games\RynthCore\Test\localappdata"
New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null
$dispatch = "C:\Games\RynthCore\Test\dispatch.txt"
$env:RYNTHCORE_DISPATCH_FILE = $dispatch
Set-Content $dispatch "# test dispatch file"
function Send-Commands {
foreach ($c in $Commands) {
Set-Content $dispatch "force:$c"
Start-Sleep 2
}
}
$out = & $injector --launch --account $Account --server $Server --engine "$Runtime\RynthCore.Loader.dll" --character $Character 2>&1
$clientPid = [int](($out | Select-String "LAUNCHED_PID=(\d+)").Matches[0].Groups[1].Value)
Set-Content $pidFile $clientPid
$log = "C:\Games\RynthCore\Logs\RynthCore.$clientPid.log"
Write-Host "client $clientPid, log $log"
Start-Sleep $WarmupSeconds
function Summarize([int]$from) {
$lines = @(Get-Content $log | Select-Object -Skip $from)
$lines | Select-String "unloaded in|NOT unloaded|unloaded since|Reload: |PATTERN MISS|HANG DETECTED|prologue not found|\[ERR\]|still running|ChatFileDispatcher: dispatching|PopOut|pop-out" |
ForEach-Object { Write-Host (" " + ($_.Line -replace '^\[(\S+)\] \[pid:\d+\] ', '$1 ')) }
$fps = $lines | Select-String "hb #\d+ .*fps=(\d+).*login=(\d)" | Select-Object -Last 8 |
ForEach-Object { $_.Matches[0].Groups[1].Value }
Write-Host " fps (last 8 heartbeats): $($fps -join ' ')"
return (Get-Content $log).Count
}
Send-Commands
Start-Sleep 5
$mark = 0
Write-Host "---- gen 1"
$mark = Summarize $mark
for ($i = 1; $i -le $Reloads; $i++) {
if (-not (Get-Process -Id $clientPid -ErrorAction SilentlyContinue)) { Write-Host "CLIENT DIED"; break }
Write-Host "---- reload $i"
$ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$clientPid")
[void]$ev.Set(); $ev.Dispose()
Start-Sleep $SettleSeconds
Send-Commands
Start-Sleep 5
$before = $mark
$mark = Summarize $mark
if (Get-Content $log | Select-Object -Skip $before | Select-String "NOT unloaded" -Quiet) {
Write-Host "---- AlcRoots"
& $alcRoots $clientPid 15
}
}
$p = Get-Process -Id $clientPid -ErrorAction SilentlyContinue
Write-Host ("client " + $(if ($p) { "alive, responding=$($p.Responding)" } else { "DEAD" }))
if (-not $Keep -and $p) { Stop-Process -Id $clientPid -Force; Write-Host "client stopped" }

View file

@ -7,7 +7,8 @@
# (MaybeRestartWedgedClients), so it can run with the launcher closed:
#
# * fps=0 with login=1 sustained >= WedgeHoldSeconds (render dead, alive)
# * main-thread queue qd > QueueWedgeDepth with login=1 (queue not draining)
# * (inert since 2026-10-01: the engine reports qdrop, a running total of dropped
# actions, not a queue depth; healthy clients were being killed on it)
# * combat-mode "stuck Ns" >= StanceStuckSeconds (item-action hard-lock)
# * heartbeat file silent > HbStaleSeconds while alive (engine died in-proc)
#

View file

@ -0,0 +1,52 @@
# Build.ps1 - builds the Phase 0 CoreCLR hosting spike into .\bin
# bin\SpikeHostExe.exe, SpikeHost.dll native x86 (cl.exe)
# bin\Shim.dll, Contracts.dll default ALC (in the TPA list)
# bin\payload\Payload.dll loaded into a collectible ALC per generation
# bin\runtime\ app-local CoreCLR x86 from the NuGet runtime pack
# Run: .\bin\SpikeHostExe.exe <cycles> <mode> (mode bits: see Payload.cs)
$ErrorActionPreference = "Stop"
$root = $PSScriptRoot
$bin = Join-Path $root "bin"
New-Item -ItemType Directory -Force -Path $bin, "$bin\payload", "$bin\runtime", "$bin\obj" | Out-Null
# --- native ---
$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" `
-latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name
$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer"
$cl = "$vcBase\bin\Hostx86\x86\cl.exe"
$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name
$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer"
$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer"
$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared"
$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86"
Push-Location "$bin\obj"
try {
& $cl /nologo /O2 /MT /W3 /LD "$root\native\SpikeHost.c" /link /MACHINE:X86 /OUT:"$bin\SpikeHost.dll"
if ($LASTEXITCODE -ne 0) { throw "SpikeHost.dll failed" }
& $cl /nologo /O2 /MT /W3 "$root\native\SpikeHostExe.c" /link /MACHINE:X86 /LARGEADDRESSAWARE /OUT:"$bin\SpikeHostExe.exe"
if ($LASTEXITCODE -ne 0) { throw "SpikeHostExe.exe failed" }
& $cl /nologo /O2 /MT /W3 "$root\native\SpikeInject.c" /link /MACHINE:X86 /OUT:"$bin\SpikeInject.exe"
if ($LASTEXITCODE -ne 0) { throw "SpikeInject.exe failed" }
} finally { Pop-Location }
# --- managed ---
foreach ($p in "Contracts", "Shim", "Payload") {
dotnet build "$root\$p\$p.csproj" -c Release -nologo -v q
if ($LASTEXITCODE -ne 0) { throw "$p build failed" }
}
Copy-Item "$root\Shim\bin\Release\net10.0\Shim.dll" $bin -Force
Copy-Item "$root\Contracts\bin\Release\net10.0\Contracts.dll" $bin -Force
Copy-Item "$root\Payload\bin\Release\net10.0\Payload.dll" "$bin\payload" -Force
# --- app-local runtime ---
$pack = Join-Path $env:USERPROFILE ".nuget\packages\microsoft.netcore.app.runtime.win-x86"
$ver = (Get-ChildItem $pack | Where-Object Name -like "10.*" | Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1).Name
$rt = "$pack\$ver\runtimes\win-x86"
if (-not (Test-Path "$bin\runtime\coreclr.dll")) {
Copy-Item "$rt\native\*" "$bin\runtime" -Force
Copy-Item "$rt\lib\net10.0\*.dll" "$bin\runtime" -Force
}
Write-Host "Built spike with runtime $ver into $bin"

View file

@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<Nullable>enable</Nullable>
<AssemblyName>Contracts</AssemblyName>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,17 @@
namespace Contracts;
/// <summary>What the Shim (default ALC) sees of a payload living in a collectible ALC.</summary>
public interface IPayload
{
/// <summary>Address of an [UnmanagedCallersOnly] stdcall (int,int)->int method, or 0 with an error.</summary>
nint GetUcoPointer(out string? error);
/// <summary>Marshal.GetFunctionPointerForDelegate of a stdcall (int,int)->int delegate the payload keeps alive.</summary>
nint GetDelegatePointer();
/// <summary>Does the work selected by the mode bits; returns a short description.</summary>
string Work(int mode);
/// <summary>Stops everything Work started.</summary>
void Shutdown();
}

View file

@ -0,0 +1,153 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.Json;
using Contracts;
namespace Payload;
// Mode bits (the Shim passes the host's mode through):
// 0x01 System.Text.Json reflection serialize/deserialize of payload types
// 0x02 start a Thread and join it in Shutdown
// 0x04 Task.Run work + a System.Threading.Timer, both finished/disposed in Shutdown
// 0x08 hold a 32 MB static array (the GC heap should give it back)
// 0x10 LEAK ON PURPOSE: subscribe to AppDomain.ProcessExit and never unsubscribe
// 0x20 JIT a lot of code (many generic instantiations over payload types)
// 0x40 allocate 8 MB with NativeMemory and free it in Shutdown
// 0x80 System.Text.Json reflection with a JsonSerializerOptions the payload owns
// 0x100 (Shim side) load a private copy of System.Text.Json into the collectible ALC
public sealed class Entry : IPayload
{
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int BinaryFn(int a, int b);
private static byte[]? s_big;
private static BinaryFn? s_mul;
private Thread? _thread;
private volatile bool _stop;
private Timer? _timer;
private Task? _task;
private unsafe void* _native;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
private static int Add(int a, int b) => a + b;
public unsafe nint GetUcoPointer(out string? error)
{
try
{
error = null;
return (nint)(delegate* unmanaged[Stdcall]<int, int, int>)&Add;
}
catch (Exception ex)
{
error = ex.GetType().Name + ": " + ex.Message;
return 0;
}
}
public nint GetDelegatePointer()
{
s_mul = (a, b) => a * b;
return Marshal.GetFunctionPointerForDelegate(s_mul);
}
public unsafe string Work(int mode)
{
var did = new List<string>();
if ((mode & 0x01) != 0)
{
var rec = new Record { Name = "gen", Values = Enumerable.Range(0, 100).ToList(), Child = new Record { Name = "c" } };
string json = JsonSerializer.Serialize(rec);
var back = JsonSerializer.Deserialize<Record>(json)!;
did.Add($"json {json.Length}b {back.Values.Count} stj alc {System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(typeof(JsonSerializer).Assembly)?.Name}");
}
if ((mode & 0x80) != 0)
{
var opts = new JsonSerializerOptions { WriteIndented = false };
var rec = new Record { Name = "own", Values = Enumerable.Range(0, 10).ToList() };
string json = JsonSerializer.Serialize(rec, opts);
var back = JsonSerializer.Deserialize<Record>(json, opts)!;
did.Add($"json(own opts) {json.Length}b {back.Values.Count} stj@{typeof(JsonSerializer).Assembly.GetName().Name}:{System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(typeof(JsonSerializer).Assembly)?.Name}");
}
if ((mode & 0x02) != 0)
{
_thread = new Thread(() => { while (!_stop) Thread.Sleep(5); }) { IsBackground = true, Name = "payload" };
_thread.Start();
did.Add("thread");
}
if ((mode & 0x04) != 0)
{
_task = Task.Run(() => Thread.Sleep(20));
_timer = new Timer(_ => { }, null, 0, 10);
did.Add("task+timer");
}
if ((mode & 0x08) != 0)
{
s_big = new byte[32 * 1024 * 1024];
s_big[^1] = 1;
did.Add("32MB static");
}
if ((mode & 0x10) != 0)
{
AppDomain.CurrentDomain.ProcessExit += OnExit;
did.Add("LEAK ProcessExit");
}
if ((mode & 0x20) != 0)
{
int n = JitMany();
did.Add($"jit {n}");
}
if ((mode & 0x40) != 0)
{
_native = NativeMemory.Alloc(8 * 1024 * 1024);
did.Add("native 8MB");
}
return did.Count == 0 ? "basic" : string.Join(", ", did);
}
private void OnExit(object? s, EventArgs e) { }
[MethodImpl(MethodImplOptions.NoInlining)]
private static int JitMany()
{
int sum = 0;
sum += Gen<A1>.Run(); sum += Gen<A2>.Run(); sum += Gen<A3>.Run(); sum += Gen<A4>.Run();
sum += Gen<A5>.Run(); sum += Gen<A6>.Run(); sum += Gen<A7>.Run(); sum += Gen<A8>.Run();
var d = new Dictionary<A1, List<A2>>(); d[new A1()] = new List<A2> { new() };
sum += d.Count + d.Values.SelectMany(x => x).Count();
return sum;
}
public unsafe void Shutdown()
{
_stop = true;
_thread?.Join();
_timer?.Dispose();
_task?.Wait();
if (_native != null) { NativeMemory.Free(_native); _native = null; }
s_big = null;
// s_mul stays: a static in the collectible ALC, it dies with the ALC.
}
public sealed class Record
{
public string Name { get; set; } = "";
public List<int> Values { get; set; } = new();
public Record? Child { get; set; }
}
private sealed class A1 { } private sealed class A2 { } private sealed class A3 { } private sealed class A4 { }
private sealed class A5 { } private sealed class A6 { } private sealed class A7 { } private sealed class A8 { }
private static class Gen<T> where T : new()
{
public static int Run()
{
var list = new List<T>();
for (int i = 0; i < 16; i++) list.Add(new T());
var set = new HashSet<T>(list);
var dict = list.Select((x, i) => (x, i)).ToDictionary(p => p.x, p => p.i);
return list.Where(x => x != null).OrderBy(x => x!.GetHashCode()).Count() + set.Count + dict.Count;
}
}
}

View file

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>Payload</AssemblyName>
</PropertyGroup>
<ItemGroup>
<!-- Contracts must come from the default ALC: don't copy it next to the payload. -->
<ProjectReference Include="..\Contracts\Contracts.csproj" Private="false" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,134 @@
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Text;
using Contracts;
namespace Shim;
[StructLayout(LayoutKind.Sequential)]
public unsafe struct HostApi
{
public int Size;
public delegate* unmanaged[Stdcall]<double*, double> FreeMb;
public delegate* unmanaged[Stdcall]<byte*, void> Log;
public delegate* unmanaged[Stdcall]<nint, int, int, int> CallBinary;
public delegate* unmanaged[Stdcall]<uint> CommittedMb;
}
public static unsafe class Entry
{
private static HostApi* s_api;
private static void Log(string msg)
{
byte[] bytes = Encoding.UTF8.GetBytes(msg + "\0");
fixed (byte* p = bytes) s_api->Log(p);
}
private static (double free, double largest) Free()
{
double largest;
double free = s_api->FreeMb(&largest);
return (free, largest);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
public static int Run(HostApi* api, int cycles, int mode)
{
s_api = api;
try
{
string dir = Path.GetDirectoryName(typeof(Entry).Assembly.Location)!;
string payloadPath = Path.Combine(dir, "payload", "Payload.dll");
Log($"Shim up: CLR {Environment.Version}, {RuntimeInformation.ProcessArchitecture}, mode 0x{mode:x}, {cycles} cycles, payload {payloadPath}");
var (free0, _) = Free();
uint commit0 = s_api->CommittedMb();
double firstGenFree = 0;
int failures = 0;
for (int i = 1; i <= cycles; i++)
{
var sw = Stopwatch.StartNew();
WeakReference alcRef = RunGeneration(i, payloadPath, mode, out string report);
long loadMs = sw.ElapsedMilliseconds;
sw.Restart();
int collections = 0;
while (alcRef.IsAlive && sw.ElapsedMilliseconds < 5000)
{
GC.Collect();
GC.WaitForPendingFinalizers();
collections++;
if (alcRef.IsAlive) Thread.Sleep(5);
}
GC.Collect();
bool freed = !alcRef.IsAlive;
if (!freed) failures++;
var (free, largest) = Free();
if (i == 1) firstGenFree = free;
Log($"gen {i,2}: {report} | load+run {loadMs} ms | alc {(freed ? "freed" : "NOT freed")} after {collections} GCs, {sw.ElapsedMilliseconds} ms | free {free:F0} MB (largest {largest:F0}), vs gen1 {free - firstGenFree:+0;-0} MB | commit {s_api->CommittedMb()} MB | gc heap {GC.GetTotalMemory(false) / 1048576.0:F1} MB");
}
var (freeEnd, _) = Free();
Log($"done: {cycles} cycles, {failures} not freed; free {free0:F0} -> {freeEnd:F0} MB ({freeEnd - free0:+0;-0}), after gen1 {freeEnd - firstGenFree:+0;-0} MB; commit {commit0} -> {s_api->CommittedMb()} MB");
return failures;
}
catch (Exception ex)
{
Log("Shim.Run failed: " + ex);
return -100;
}
}
// NoInlining so no local in Run keeps the ALC, the assembly or the payload alive.
[MethodImpl(MethodImplOptions.NoInlining)]
private static WeakReference RunGeneration(int gen, string payloadPath, int mode, out string report)
{
var alc = new PayloadAlc($"gen{gen}", Path.GetDirectoryName(payloadPath)!, (mode & 0x100) != 0);
Assembly asm;
using (var fs = File.OpenRead(payloadPath)) asm = alc.LoadFromStream(fs);
var payload = (IPayload)Activator.CreateInstance(asm.GetType("Payload.Entry", throwOnError: true)!)!;
var parts = new List<string>();
nint uco = payload.GetUcoPointer(out string? ucoError);
parts.Add(uco != 0 ? $"uco 2+3={s_api->CallBinary(uco, 2, 3)}" : $"uco FAILED {ucoError}");
nint del = payload.GetDelegatePointer();
parts.Add($"delegate 6*7={s_api->CallBinary(del, 6, 7)}");
parts.Add(payload.Work(mode));
payload.Shutdown();
report = string.Join("; ", parts);
alc.Unload();
return new WeakReference(alc, trackResurrection: true);
}
private sealed class PayloadAlc : AssemblyLoadContext
{
private static readonly string s_runtimeDir = Path.GetDirectoryName(typeof(object).Assembly.Location)!;
private static readonly HashSet<string> s_private = new(StringComparer.OrdinalIgnoreCase)
{
"System.Text.Json", "System.Text.Encodings.Web", "System.IO.Pipelines",
};
private readonly string _dir;
private readonly bool _privateFramework;
public PayloadAlc(string name, string dir, bool privateFramework) : base(name, isCollectible: true)
{
_dir = dir;
_privateFramework = privateFramework;
}
protected override Assembly? Load(AssemblyName name)
{
// Contracts and the framework come from the default ALC; anything else next to the payload loads here.
if (name.Name == "Contracts") return null;
if (_privateFramework && s_private.Contains(name.Name!))
return LoadFromAssemblyPath(Path.Combine(s_runtimeDir, name.Name + ".dll"));
string candidate = Path.Combine(_dir, name.Name + ".dll");
if (!File.Exists(candidate)) return null;
using var fs = File.OpenRead(candidate);
return LoadFromStream(fs);
}
}
}

View file

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>Shim</AssemblyName>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Contracts\Contracts.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,216 @@
// SpikeHost: Phase 0 spike for docs/UNLOADABLE_ENGINE_PLAN.md.
//
// Starts an app-local CoreCLR (x86) through the raw coreclr_* hosting API, loads
// Shim.dll into the default ALC and calls Shim.Entry.Run, which loads Payload.dll
// into a collectible ALC N times, calls into it from native code, unloads it and
// measures free address space through the HostApi below.
//
// Built as a DLL (SpikeHost.dll, export SpikeRun) so the same code can be injected
// into acclient; SpikeHostExe.exe is a console driver that LoadLibrary's it.
#include <windows.h>
#include <stdio.h>
#include <stdarg.h>
typedef int (__stdcall *coreclr_initialize_fn)(const char* exePath, const char* appDomainFriendlyName,
int propertyCount, const char** propertyKeys, const char** propertyValues,
void** hostHandle, unsigned int* domainId);
typedef int (__stdcall *coreclr_create_delegate_fn)(void* hostHandle, unsigned int domainId,
const char* assemblyName, const char* typeName, const char* methodName, void** fn);
typedef struct HostApi {
int size;
double (__stdcall *freeMb)(double* largestFreeMb);
void (__stdcall *log)(const char* utf8);
int (__stdcall *callBinary)(void* fn, int a, int b); // native frame -> managed fn pointer
unsigned int (__stdcall *committedMb)(void);
} HostApi;
typedef int (__stdcall *shim_run_fn)(HostApi* api, int cycles, int mode);
static char g_dir[MAX_PATH];
static FILE* g_log;
static void LogLine(const char* fmt, ...)
{
char buf[2048];
va_list ap;
va_start(ap, fmt);
_vsnprintf_s(buf, sizeof buf, _TRUNCATE, fmt, ap);
va_end(ap);
SYSTEMTIME t;
GetLocalTime(&t);
char line[2200];
_snprintf_s(line, sizeof line, _TRUNCATE, "[%02d:%02d:%02d.%03d] [pid:%lu] %s\n",
t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, GetCurrentProcessId(), buf);
fputs(line, stdout);
fflush(stdout);
if (g_log) { fputs(line, g_log); fflush(g_log); }
OutputDebugStringA(line);
}
static double __stdcall FreeMb(double* largestFreeMb)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
unsigned char* p = (unsigned char*)si.lpMinimumApplicationAddress;
unsigned char* end = (unsigned char*)si.lpMaximumApplicationAddress;
unsigned long long total = 0, largest = 0;
MEMORY_BASIC_INFORMATION mbi;
while (p < end && VirtualQuery(p, &mbi, sizeof mbi) == sizeof mbi) {
if (mbi.State == MEM_FREE) {
total += mbi.RegionSize;
if (mbi.RegionSize > largest) largest = mbi.RegionSize;
}
p = (unsigned char*)mbi.BaseAddress + mbi.RegionSize;
}
if (largestFreeMb) *largestFreeMb = largest / (1024.0 * 1024.0);
return total / (1024.0 * 1024.0);
}
static unsigned int __stdcall CommittedMb(void)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
unsigned char* p = (unsigned char*)si.lpMinimumApplicationAddress;
unsigned char* end = (unsigned char*)si.lpMaximumApplicationAddress;
unsigned long long total = 0;
MEMORY_BASIC_INFORMATION mbi;
while (p < end && VirtualQuery(p, &mbi, sizeof mbi) == sizeof mbi) {
if (mbi.State == MEM_COMMIT && mbi.Type == MEM_PRIVATE) total += mbi.RegionSize;
p = (unsigned char*)mbi.BaseAddress + mbi.RegionSize;
}
return (unsigned int)(total / (1024 * 1024));
}
static void __stdcall ManagedLog(const char* utf8) { LogLine("[shim] %s", utf8); }
static int __stdcall CallBinary(void* fn, int a, int b)
{
typedef int (__stdcall *bin_fn)(int, int);
return ((bin_fn)fn)(a, b);
}
// Appends every *.dll in dir to the ';'-separated TPA list.
static void AppendDlls(char* tpa, size_t cap, const char* dir)
{
char pattern[MAX_PATH];
_snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\*.dll", dir);
WIN32_FIND_DATAA fd;
HANDLE h = FindFirstFileA(pattern, &fd);
if (h == INVALID_HANDLE_VALUE) return;
do {
// Native runtime DLLs sit in the same folder; skip what isn't managed.
const char* n = fd.cFileName;
if (!_stricmp(n, "coreclr.dll") || !_stricmp(n, "clrjit.dll") || !_stricmp(n, "clrgc.dll") ||
!_stricmp(n, "hostfxr.dll") || !_stricmp(n, "hostpolicy.dll") || !_stricmp(n, "mscordaccore.dll") ||
!_stricmp(n, "mscordbi.dll") || !_stricmp(n, "mscorrc.dll") || !_stricmp(n, "clretwrc.dll") ||
!_strnicmp(n, "mscordaccore_", 13) || !_stricmp(n, "msquic.dll") ||
!_stricmp(n, "System.IO.Compression.Native.dll") || !_stricmp(n, "Microsoft.DiaSymReader.Native.x86.dll") ||
!_stricmp(n, "SpikeHost.dll"))
continue;
strcat_s(tpa, cap, dir);
strcat_s(tpa, cap, "\\");
strcat_s(tpa, cap, n);
strcat_s(tpa, cap, ";");
} while (FindNextFileA(h, &fd));
FindClose(h);
}
__declspec(dllexport) int __stdcall SpikeRun(int cycles, int mode)
{
HMODULE self;
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR)&SpikeRun, &self);
GetModuleFileNameA(self, g_dir, MAX_PATH);
*strrchr(g_dir, '\\') = 0;
char logPath[MAX_PATH];
_snprintf_s(logPath, sizeof logPath, _TRUNCATE, "%s\\spike.%lu.log", g_dir, GetCurrentProcessId());
fopen_s(&g_log, logPath, "a");
double largest;
double free0 = FreeMb(&largest);
LogLine("host: start, free %.0f MB (largest %.0f), private commit %u MB", free0, largest, CommittedMb());
char runtimeDir[MAX_PATH], coreclrPath[MAX_PATH];
_snprintf_s(runtimeDir, sizeof runtimeDir, _TRUNCATE, "%s\\runtime", g_dir);
_snprintf_s(coreclrPath, sizeof coreclrPath, _TRUNCATE, "%s\\coreclr.dll", runtimeDir);
DWORD t0 = GetTickCount();
HMODULE clr = LoadLibraryExA(coreclrPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!clr) { LogLine("host: LoadLibrary coreclr failed %lu", GetLastError()); return -1; }
coreclr_initialize_fn init = (coreclr_initialize_fn)GetProcAddress(clr, "coreclr_initialize");
coreclr_create_delegate_fn create = (coreclr_create_delegate_fn)GetProcAddress(clr, "coreclr_create_delegate");
if (!init || !create) { LogLine("host: coreclr exports missing"); return -2; }
static char tpa[64 * 1024];
tpa[0] = 0;
AppendDlls(tpa, sizeof tpa, runtimeDir);
AppendDlls(tpa, sizeof tpa, g_dir); // Shim.dll + Contracts.dll (default ALC)
// Mode bit 0x200: concurrent (background) GC on.
const char* keys[] = {
"TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES",
"System.GC.Server", "System.GC.Concurrent", "System.Globalization.Invariant",
"System.GC.RetainVM",
};
char nativeDirs[2 * MAX_PATH + 4];
_snprintf_s(nativeDirs, sizeof nativeDirs, _TRUNCATE, "%s;%s;", runtimeDir, g_dir);
const char* values[] = {
tpa, "", nativeDirs,
"false", (mode & 0x200) ? "true" : "false", "true",
"false",
};
int count = sizeof keys / sizeof keys[0];
char exePath[MAX_PATH];
GetModuleFileNameA(NULL, exePath, MAX_PATH);
void* hostHandle = NULL;
unsigned int domainId = 0;
int hr = init(exePath, "RynthCoreSpike", count, keys, values, &hostHandle, &domainId);
if (hr < 0) { LogLine("host: coreclr_initialize failed 0x%08x", hr); return -3; }
LogLine("host: CoreCLR up in %lu ms, free %.0f MB (cost %.0f MB), private commit %u MB",
GetTickCount() - t0, FreeMb(&largest), free0 - FreeMb(NULL), CommittedMb());
shim_run_fn run = NULL;
hr = create(hostHandle, domainId, "Shim", "Shim.Entry", "Run", (void**)&run);
if (hr < 0 || !run) { LogLine("host: create_delegate Shim.Entry.Run failed 0x%08x", hr); return -4; }
static HostApi api;
api.size = sizeof api;
api.freeMb = FreeMb;
api.log = ManagedLog;
api.callBinary = CallBinary;
api.committedMb = CommittedMb;
int rc = run(&api, cycles, mode);
LogLine("host: Shim.Run returned %d, free %.0f MB (largest %.0f)", rc, FreeMb(&largest), largest);
if (g_log) { fclose(g_log); g_log = NULL; }
return rc;
}
// Injected use: RYNTH_SPIKE_AUTORUN="cycles,mode,delayMs" in the target's environment
// makes DllMain start a worker (no CLR work under the loader lock).
static int g_autoCycles = 20, g_autoMode = 0, g_autoDelay = 3000;
static DWORD WINAPI AutoRun(LPVOID p)
{
(void)p;
Sleep(g_autoDelay);
SpikeRun(g_autoCycles, g_autoMode);
return 0;
}
BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID reserved)
{
(void)h; (void)reserved;
if (reason == DLL_PROCESS_ATTACH) {
char v[64];
if (GetEnvironmentVariableA("RYNTH_SPIKE_AUTORUN", v, sizeof v) > 0) {
sscanf_s(v, "%d,%i,%d", &g_autoCycles, &g_autoMode, &g_autoDelay);
HANDLE t = CreateThread(NULL, 0, AutoRun, NULL, 0, NULL);
if (t) CloseHandle(t);
}
}
return TRUE;
}

View file

@ -0,0 +1,19 @@
// Console driver: SpikeHostExe.exe [cycles] [mode]. LoadLibrary's SpikeHost.dll the
// way an injected loader would and calls SpikeRun.
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
typedef int (__stdcall *spike_run_fn)(int cycles, int mode);
int main(int argc, char** argv)
{
int cycles = argc > 1 ? atoi(argv[1]) : 20;
int mode = argc > 2 ? (int)strtol(argv[2], NULL, 0) : 0;
HMODULE h = LoadLibraryA("SpikeHost.dll");
if (!h) { printf("LoadLibrary SpikeHost.dll failed %lu\n", GetLastError()); return 1; }
spike_run_fn run = (spike_run_fn)GetProcAddress(h, "_SpikeRun@8");
if (!run) run = (spike_run_fn)GetProcAddress(h, "SpikeRun");
if (!run) { printf("SpikeRun export missing\n"); return 2; }
return run(cycles, mode);
}

View file

@ -0,0 +1,53 @@
// SpikeInject: starts acclient.exe suspended, LoadLibrary's SpikeHost.dll into it with
// RYNTH_SPIKE_AUTORUN set, resumes it, waits, then terminates it.
// SpikeInject.exe <acclient.exe> <SpikeHost.dll> <cycles,mode,delayMs> <waitSeconds> [acclient args...]
#include <windows.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
if (argc < 5) { printf("usage: SpikeInject <acclient.exe> <SpikeHost.dll> <cycles,mode,delayMs> <waitSeconds> [args]\n"); return 1; }
const char* exe = argv[1];
const char* dll = argv[2];
int waitSeconds = atoi(argv[4]);
SetEnvironmentVariableA("RYNTH_SPIKE_AUTORUN", argv[3]);
char cmd[4096];
_snprintf_s(cmd, sizeof cmd, _TRUNCATE, "\"%s\"", exe);
for (int i = 5; i < argc; i++) { strcat_s(cmd, sizeof cmd, " "); strcat_s(cmd, sizeof cmd, argv[i]); }
char dir[MAX_PATH];
strcpy_s(dir, sizeof dir, exe);
*strrchr(dir, '\\') = 0;
STARTUPINFOA si = { sizeof si };
PROCESS_INFORMATION pi;
if (!CreateProcessA(exe, cmd, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, dir, &si, &pi)) {
printf("CreateProcess failed %lu\n", GetLastError()); return 2;
}
printf("SPIKE_PID=%lu\n", pi.dwProcessId);
size_t len = strlen(dll) + 1;
void* remote = VirtualAllocEx(pi.hProcess, NULL, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
WriteProcessMemory(pi.hProcess, remote, dll, len, NULL);
FARPROC loadLib = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
HANDLE t = CreateRemoteThread(pi.hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)loadLib, remote, 0, NULL);
if (!t) { printf("CreateRemoteThread failed %lu\n", GetLastError()); TerminateProcess(pi.hProcess, 1); return 3; }
WaitForSingleObject(t, 30000);
DWORD mod = 0;
GetExitCodeThread(t, &mod);
printf("LoadLibrary in target -> 0x%08lx\n", mod);
CloseHandle(t);
ResumeThread(pi.hThread);
DWORD r = WaitForSingleObject(pi.hProcess, waitSeconds * 1000);
if (r == WAIT_OBJECT_0) {
DWORD code = 0;
GetExitCodeProcess(pi.hProcess, &code);
printf("acclient exited by itself, code 0x%08lx\n", code);
} else {
TerminateProcess(pi.hProcess, 0);
printf("acclient terminated after %d s\n", waitSeconds);
}
return 0;
}

View file

@ -0,0 +1,169 @@
"""AcWindow.py - look at and click ONE test client's game window, by its process id.
Spike helper (Decal bridge): used once, to drive the retail character-creation screen of a
test client. Everything goes to the HWND of the given pid (PostMessage), so no other window
- and no other client - is touched, and nothing moves the real mouse or keyboard.
python AcWindow.py shot <pid> <out.png>
python AcWindow.py click <pid> <x> <y> client coordinates of the game window
python AcWindow.py type <pid> <text>
python AcWindow.py key <pid> <vk> e.g. 0x0D (Enter), 0x08 (Backspace)
"""
import ctypes
import ctypes.wintypes as wt
import sys
import time
user32 = ctypes.WinDLL("user32", use_last_error=True)
gdi32 = ctypes.WinDLL("gdi32", use_last_error=True)
user32.PostMessageW.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p]
user32.GetClientRect.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.RECT)]
user32.GetWindowThreadProcessId.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.DWORD)]
user32.GetClassNameW.argtypes = [ctypes.c_void_p, wt.LPWSTR, ctypes.c_int]
user32.IsWindowVisible.argtypes = [ctypes.c_void_p]
user32.PrintWindow.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint]
user32.GetDC.argtypes = [ctypes.c_void_p]
user32.GetDC.restype = ctypes.c_void_p
user32.ReleaseDC.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
gdi32.CreateCompatibleDC.argtypes = [ctypes.c_void_p]
gdi32.CreateCompatibleDC.restype = ctypes.c_void_p
gdi32.CreateCompatibleBitmap.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
gdi32.CreateCompatibleBitmap.restype = ctypes.c_void_p
gdi32.SelectObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
gdi32.GetDIBits.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint]
gdi32.DeleteObject.argtypes = [ctypes.c_void_p]
gdi32.DeleteDC.argtypes = [ctypes.c_void_p]
WM_MOUSEMOVE, WM_LBUTTONDOWN, WM_LBUTTONUP = 0x0200, 0x0201, 0x0202
WM_KEYDOWN, WM_KEYUP, WM_CHAR = 0x0100, 0x0101, 0x0102
def game_window(pid):
found = []
proto = ctypes.WINFUNCTYPE(wt.BOOL, ctypes.c_void_p, ctypes.c_void_p)
def cb(hwnd, _):
owner = wt.DWORD()
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner))
if owner.value == pid and user32.IsWindowVisible(hwnd):
cls = ctypes.create_unicode_buffer(128)
user32.GetClassNameW(hwnd, cls, 128)
if cls.value == "Turbine Device Class":
found.append(hwnd)
return True
user32.EnumWindows(proto(cb), None)
if not found:
raise SystemExit(f"no game window for pid {pid}")
return found[0]
def dialogs(pid):
"""Message boxes (#32770) the process has open, with their static text."""
proto = ctypes.WINFUNCTYPE(wt.BOOL, ctypes.c_void_p, ctypes.c_void_p)
user32.GetWindowTextW.argtypes = [ctypes.c_void_p, wt.LPWSTR, ctypes.c_int]
out = []
def top(hwnd, _):
owner = wt.DWORD()
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner))
cls = ctypes.create_unicode_buffer(64)
user32.GetClassNameW(hwnd, cls, 64)
if owner.value == pid and cls.value == "#32770" and user32.IsWindowVisible(hwnd):
texts = []
def child(ch, _):
c = ctypes.create_unicode_buffer(64)
user32.GetClassNameW(ch, c, 64)
t = ctypes.create_unicode_buffer(1024)
user32.GetWindowTextW(ch, t, 1024)
if t.value:
texts.append(f"{c.value}: {t.value}")
return True
user32.EnumChildWindows(ctypes.c_void_p(hwnd), proto(child), None)
out.append((hwnd, texts))
return True
user32.EnumWindows(proto(top), None)
for hwnd, texts in out:
print(f"dialog 0x{hwnd:X}: " + " | ".join(texts))
if not out:
print("no dialogs")
def shot(pid, out):
from PIL import Image
hwnd = game_window(pid)
r = wt.RECT()
user32.GetClientRect(hwnd, ctypes.byref(r))
w, h = r.right, r.bottom
hdc = user32.GetDC(hwnd)
mdc = gdi32.CreateCompatibleDC(hdc)
bmp = gdi32.CreateCompatibleBitmap(hdc, w, h)
gdi32.SelectObject(mdc, bmp)
user32.PrintWindow(hwnd, mdc, 3) # PW_CLIENTONLY | PW_RENDERFULLCONTENT
bmi = (ctypes.c_byte * 40)()
ctypes.memmove(bmi, (ctypes.c_int * 3)(40, w, -h), 12)
ctypes.memmove(ctypes.byref(bmi, 12), (ctypes.c_short * 2)(1, 32), 4)
buf = (ctypes.c_byte * (w * h * 4))()
gdi32.GetDIBits(mdc, bmp, 0, h, buf, bmi, 0)
Image.frombuffer("RGB", (w, h), bytes(buf), "raw", "BGRX", 0, 1).save(out)
gdi32.DeleteObject(bmp)
gdi32.DeleteDC(mdc)
user32.ReleaseDC(hwnd, hdc)
print(f"{w}x{h} -> {out}")
def click(pid, x, y):
hwnd = game_window(pid)
lp = (y << 16) | (x & 0xFFFF)
user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp)
time.sleep(0.05)
user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, lp)
time.sleep(0.08)
user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp)
def drag(pid, x0, y0, x1, y1):
hwnd = game_window(pid)
user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, (y0 << 16) | x0)
time.sleep(0.05)
user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, (y0 << 16) | x0)
for i in range(1, 11):
x = x0 + (x1 - x0) * i // 10
y = y0 + (y1 - y0) * i // 10
time.sleep(0.03)
user32.PostMessageW(hwnd, WM_MOUSEMOVE, 1, (y << 16) | x)
time.sleep(0.05)
user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, (y1 << 16) | x1)
def type_text(pid, text):
hwnd = game_window(pid)
for ch in text:
user32.PostMessageW(hwnd, WM_CHAR, ord(ch), 1)
time.sleep(0.04)
def key(pid, vk):
hwnd = game_window(pid)
user32.PostMessageW(hwnd, WM_KEYDOWN, vk, 1)
time.sleep(0.05)
user32.PostMessageW(hwnd, WM_KEYUP, vk, 0xC0000001)
if __name__ == "__main__":
cmd, pid = sys.argv[1], int(sys.argv[2])
if cmd == "shot":
shot(pid, sys.argv[3])
elif cmd == "click":
click(pid, int(sys.argv[3]), int(sys.argv[4]))
elif cmd == "dialogs":
dialogs(pid)
elif cmd == "drag":
drag(pid, *(int(v) for v in sys.argv[3:7]))
elif cmd == "type":
type_text(pid, sys.argv[3])
elif cmd == "key":
key(pid, int(sys.argv[3], 0))

View file

@ -0,0 +1,157 @@
// BridgeProbe - a trivial RynthCore plugin for the Decal-bridge spike. It logs the first
// few of every event it receives, and a count per event every 15 s, through the host log,
// so the engine log shows what reached a plugin in bridge mode.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.BridgeProbe;
public sealed class BridgeProbePlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("BridgeProbe");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0");
private int _raLines;
private int _chat, _chatBar, _create, _delete, _update, _health, _damage, _enchAdd, _enchRem, _kill, _ticks;
private long _lastSummary;
private const int FirstN = 5;
// Every chat line, for reading command output on a test client: BRIDGEPROBE_ALLCHAT=1, or a
// file "bridgeprobe-allchat.flag" next to the client's dispatch file (read at plugin load).
private static readonly bool AllChat = Environment.GetEnvironmentVariable("BRIDGEPROBE_ALLCHAT") == "1" || FlagFileExists();
private static bool FlagFileExists()
{
try
{
string? dispatch = Environment.GetEnvironmentVariable("RYNTHCORE_DISPATCH_FILE");
string? dir = string.IsNullOrEmpty(dispatch) ? null : System.IO.Path.GetDirectoryName(dispatch);
return dir != null && System.IO.File.Exists(System.IO.Path.Combine(dir, "bridgeprobe-allchat.flag"));
}
catch { return false; }
}
public override int Initialize()
{
Log("BridgeProbe: initialized.");
return 0;
}
public override void OnLoginComplete() => Log("BridgeProbe: OnLoginComplete");
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
// BRIDGEPROBE_ALLCHAT=1: log every chat line (reading command output on a test client).
if (_chat++ < FirstN || AllChat) Log($"BridgeProbe: OnChatWindowText type={chatType} '{text?.TrimEnd('\n')}'");
// RynthAi's answers to the harness's "/ra cache": its object cache, as seen in chat.
else if (text != null && text.Contains("[RynthAi]") && _raLines++ < 30)
Log($"BridgeProbe: RynthAi said: '{text.TrimEnd('\n')}'");
}
public override void OnChatBarEnter(string? text, ref int eat)
{
if (_chatBar++ < FirstN) Log($"BridgeProbe: OnChatBarEnter '{text}'");
}
public override void OnCreateObject(uint objectId)
{
if (_create++ < FirstN) Log($"BridgeProbe: OnCreateObject 0x{objectId:X8}");
}
public override void OnDeleteObject(uint objectId)
{
if (_delete++ < FirstN) Log($"BridgeProbe: OnDeleteObject 0x{objectId:X8}");
}
public override void OnUpdateObject(uint objectId) => _update++;
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
if (_health++ < FirstN) Log($"BridgeProbe: OnUpdateHealth 0x{targetId:X8} ratio={healthRatio:0.00} {currentHealth}/{maxHealth}");
}
public override void OnCombatDamage(uint damage, uint damageType, bool crit, bool isAttacker)
{
if (_damage++ < FirstN) Log($"BridgeProbe: OnCombatDamage {damage} type={damageType} crit={crit} attacker={isAttacker}");
}
public override void OnKillNotification(string? deathMessage)
{
if (_kill++ < FirstN) Log($"BridgeProbe: OnKillNotification '{deathMessage}'");
}
public override void OnEnchantmentAdded(uint spellId, double durationSeconds)
{
if (_enchAdd++ < FirstN) Log($"BridgeProbe: OnEnchantmentAdded spell={spellId} dur={durationSeconds:0}");
}
public override void OnEnchantmentRemoved(uint enchantmentId)
{
if (_enchRem++ < FirstN) Log($"BridgeProbe: OnEnchantmentRemoved {enchantmentId}");
}
public override void OnTick()
{
_ticks++;
long now = Environment.TickCount64;
if (now - _lastSummary < 15000) return;
_lastSummary = now;
Log($"BridgeProbe: counts ticks={_ticks} chat={_chat} chatBar={_chatBar} create={_create} delete={_delete} update={_update} " +
$"health={_health} damage={_damage} kill={_kill} enchAdd={_enchAdd} enchRem={_enchRem}");
}
}
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<BridgeProbePlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCore.PluginSdk.RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => BridgeProbePlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => BridgeProbePlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateObject(uint objectId) => Runtime.OnUpdateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
=> Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatDamage", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCombatDamage(uint damage, uint damageType, uint crit, uint isAttacker) => Runtime.OnCombatDamage(damage, damageType, crit, isAttacker);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnKillNotification", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnKillNotification(IntPtr textUtf16) => Runtime.OnKillNotification(textUtf16);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentAdded", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnEnchantmentAdded(uint spellId, double durationSeconds) => Runtime.OnEnchantmentAdded(spellId, durationSeconds);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentRemoved", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnEnchantmentRemoved(uint enchantmentId) => Runtime.OnEnchantmentRemoved(enchantmentId);
}

View file

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Spike (Decal bridge): a managed plugin for the CoreCLR engine that logs what it receives.
dotnet publish -c Release -o C:\Games\RynthCore\Test\plugins-decal\BridgeProbe -->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<GenerateRuntimeConfigurationFiles>false</GenerateRuntimeConfigurationFiles>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<AssemblyName>RynthCore.Plugin.BridgeProbe</AssemblyName>
<RootNamespace>RynthCore.Plugin.BridgeProbe</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,65 @@
"""Inject-BridgeRecords.py <pid> - append SYNTHETIC records to a test client's Decal-bridge ring.
For testing the engine half of the bridge while no server is available: it writes the same
records the bridge would (BridgeProtocol.cs layout) into Local\\RynthCore.DecalBridge.p<pid>.
Only use it on a test client whose bridge is idle (pre-login), or the two writers race.
"""
import mmap
import struct
import sys
# BridgeProtocol.cs version 2: header, 64 KB command ring, then the event ring.
HEADER, CMD, RING = 4096, 64 * 1024, 16 * 1024 * 1024
RING_BASE = HEADER + CMD
OFF_WRITE, OFF_READ, OFF_RECORDS = 16, 24, 40
K_CHAT, K_CHATBAR, K_CREATE, K_RELEASE, K_CHANGE, K_SERVER = 2, 3, 4, 5, 6, 7
def main():
pid = int(sys.argv[1])
m = mmap.mmap(-1, RING_BASE + RING, tagname=f"Local\\RynthCore.DecalBridge.p{pid}")
magic, version = struct.unpack_from("<II", m, 0)
assert magic == 0x42444352 and version == 2, (hex(magic), version)
def write(kind, a0=0, a1=0, payload=b""):
w, r = struct.unpack_from("<qq", m, OFF_WRITE)
rec = 16 + len(payload)
rec = (rec + 3) & ~3
pad = rec - 16 - len(payload)
pos = w % RING
assert RING - pos >= rec and RING - (w - r) > rec
base = RING_BASE + pos
struct.pack_into("<iHHII", m, base, rec, kind, pad, a0, a1)
m[base + 16: base + 16 + len(payload)] = payload
struct.pack_into("<q", m, OFF_WRITE, w + rec) # publish
struct.pack_into("<q", m, OFF_RECORDS, struct.unpack_from("<q", m, OFF_RECORDS)[0] + 1)
def game_event(ev, body):
return struct.pack("<IIII", 0xF7B0, 0x50000001, 7, ev) + body
write(K_CHAT, 0x03, 0, "[synthetic] You say, \"hello from the bridge test\"\n".encode("utf-16-le"))
write(K_CHAT, 0x17, 0, "[synthetic] Welcome to Asheron's Call\n".encode("utf-16-le"))
write(K_CHATBAR, 0, 0, "[synthetic] hello world".encode("utf-16-le"))
for oid in (0x80000101, 0x80000102, 0x80000103):
write(K_CREATE, oid)
write(K_CHANGE, 0x80000102, 2)
write(K_RELEASE, 0x80000103)
# Game events, as Decal's Message.RawData: [F7B0][objectId][sequence][eventType][payload]
write(K_SERVER, 0xF7B0, 0, game_event(0x01C7, struct.pack("<I", 0))) # UseDone, no error
write(K_SERVER, 0xF7B0, 0, game_event(0x028A, struct.pack("<I", 0x0402))) # WeenieError
write(K_SERVER, 0xF7B0, 0, game_event(0x01C0, struct.pack("<If", 0x80000101, 0.5))) # UpdateHealth 50 %
# spellId, layer, category, hasSpellSet, powerLevel, startTime, duration (+20), then 32 bytes
ench = struct.pack("<HHHHI", 2, 1, 0, 0, 1) + struct.pack("<dd", 0.0, 1800.0) + b"\0" * 32
assert len(ench) == 60
write(K_SERVER, 0xF7B0, 0, game_event(0x02C2, ench)) # UpdateEnchantment spell 2
write(K_SERVER, 0xF7B0, 0, game_event(0x02C3, struct.pack("<HH", 2, 1))) # RemoveEnchantment spell 2
name = b"Drudge"
s16 = struct.pack("<H", len(name)) + name
s16 += b"\0" * (((len(s16) + 3) // 4) * 4 - len(s16))
write(K_SERVER, 0xF7B0, 0, game_event(0x01B1, s16 + struct.pack("<IdII", 4, 0.3, 57, 1))) # we hit: 57, crit
write(K_SERVER, 0xF745, 0, struct.pack("<II", 0xF745, 0x80000104)) # some other message
print("wrote synthetic records; ring now", struct.unpack_from("<qq", m, OFF_WRITE))
if __name__ == "__main__":
main()

View file

@ -0,0 +1,30 @@
# Measure-HookRace.ps1 - how often Decal's patch ends up on top of ours at the entry points
# both of us detour (old coexistence mode, no bridge), and what a hot reload then does.
# No server needed (the race is decided in the first seconds). TEST clients only.
param([int]$Launches = 6, [string]$Runtime = "C:\Games\RynthCore\Test\rt-decal")
$ErrorActionPreference = "Stop"
$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$watch = "$repo\tools\WatchPatch.py"
$addrs = @("0x005649F0", "0x004CBF70", "0x005821A0") # AddTextToScroll, gmSalvageUI::OpenSalvagePanel, outgoing chat
for ($i = 1; $i -le $Launches; $i++) {
& "$PSScriptRoot\Start-DecalTestClient.ps1" -Mode Both -NoBridge -Runtime $Runtime *> $null
$tp = [int]((Get-Content C:\Games\RynthCore\Test\decal-spike-pids.txt -Tail 1).Split(' ')[2])
Write-Host "==== launch $i pid $tp"
$lines = python $watch $tp 25 @addrs 2>&1
$lines | ForEach-Object { Write-Host " $_" }
$final = @{}
foreach ($l in $lines) { if ($l -match '^\S+ (0x[0-9A-F]{8}) \S+ -> (.*)$') { $final[$Matches[1]] = $Matches[2] } }
$lost = $addrs[0..1] | Where-Object { $final[$_] -like "Decal*" }
Write-Host " final: $(($addrs | ForEach-Object { "$_=$($final[$_])" }) -join '; ')"
if ($lost) {
Write-Host " Decal is on top at $($lost -join ', ') -> hot reload, watching"
$job = Start-Job { python $using:watch $using:tp 14 @using:addrs 2>&1 }
Start-Sleep 1
$ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$tp")
[void]$ev.Set(); $ev.Dispose()
Wait-Job $job -Timeout 30 | Out-Null
Receive-Job $job | ForEach-Object { Write-Host " $_" }
}
Stop-Process -Id $tp -Force -ErrorAction SilentlyContinue
Start-Sleep 2
}

View file

@ -0,0 +1,37 @@
# Register-DecalBridge.ps1 - registers (or removes) the RynthCore Decal bridge for this
# Windows user, for TEST clients. A thin wrapper over the real code
# (src\RynthCore.App\DecalBridgeRegistration.cs, the same class the launcher uses for
# "Decal + RynthCore" accounts), reached through RynthCore.Injector --decal-bridge.
#
# What it does (docs\DECAL_BRIDGE_PLAN.md, "Registration"): no admin rights, nothing under
# HKLM. The bridge's entry goes into the per-user registry VirtualStore copy of Decal's
# NetworkFilters key, which the virtualized 32-bit acclient.exe reads instead of HKLM's. If
# that per-user key has to be created, every HKLM filter entry is mirrored into it first
# (otherwise Decal would see only the bridge: no WorldFilter, VTank refuses to start).
# Everything added is recorded in %APPDATA%\RynthCore\decal-bridge-registration.json and
# -Remove takes away exactly that.
#
# The bridge idles in every Decal client of this user until RynthCore is in the same client.
#
# .\Register-DecalBridge.ps1 build the bridge, copy it to Test\decal-bridge, register
# .\Register-DecalBridge.ps1 -Status show what a Decal client would load
# .\Register-DecalBridge.ps1 -Remove remove what the registration added
param([switch]$Remove, [switch]$Status)
$ErrorActionPreference = "Stop"
$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$dir = "C:\Games\RynthCore\Test\decal-bridge"
$injector = "$repo\out\injector-spike\RynthCore.Injector.exe"
dotnet publish "$repo\src\RynthCore.Injector\RynthCore.Injector.csproj" -c Release -o "$repo\out\injector-spike" -nologo -v q | Out-Null
if ($LASTEXITCODE -ne 0) { throw "injector build failed" }
if ($Status) { & $injector --decal-bridge status; return }
if ($Remove) { & $injector --decal-bridge unregister; return }
dotnet build "$repo\src\RynthCore.DecalBridge\RynthCore.DecalBridge.csproj" -c Release -nologo -v q | Out-Null
if ($LASTEXITCODE -ne 0) { throw "bridge build failed" }
$built = "$repo\src\RynthCore.DecalBridge\bin\Release\RynthCore.DecalBridge.dll"
if (-not (Test-Path $built)) { throw "bridge not built (is Decal installed?)" }
New-Item -ItemType Directory -Force $dir | Out-Null
# Decal clients that loaded the old copy keep it locked until they exit.
Copy-Item $built $dir -Force
& $injector --decal-bridge register --dir $dir

View file

@ -0,0 +1,59 @@
# Start-DecalTestClient.ps1 - Decal-bridge spike: start ONE test client with Decal and/or
# the CoreCLR RynthCore engine from a TEST runtime folder, against Tom's local server.
#
# -Mode DecalOnly Decal alone (Inject.dll + DecalStartup) - baseline
# -Mode EngineOnly RynthCore alone - baseline
# -Mode Both Decal first, then RynthCore (the coexistence case)
#
# Same isolation as scripts\Test-ClrWorld.ps1: its own engine settings, LOCALAPPDATA and
# dispatch file; RYNTHCORE_TEST_CLIENT marks it. -Bridge sets the engine's bridge mode for this
# client only (RYNTHCORE_DECAL_BRIDGE: Auto = unset, the engine.json default; On = 1; Off = 0,
# which also keeps the bridge filter itself idle); -InGameUi does the same for DecalInGameImGui.
# The bridge arms by itself when the RynthCore loader is in the client, so it must be registered
# (RynthCore.Injector --decal-bridge register).
# Never point -Runtime at C:\Games\RynthCore\Runtime (the live runtime every client shares).
param(
[ValidateSet("DecalOnly", "EngineOnly", "Both")] [string]$Mode = "Both",
[string]$Account = "Buffi",
[string]$Server = "ACEmulator",
[string]$Character = "+Buffi",
[string]$Runtime = "C:\Games\RynthCore\Test\rt-decal",
[string]$Settings = "C:\Games\RynthCore\Test\engine-decal.json",
# Override the server profile's host/port for this launch (the profile is not changed).
[string]$HostName = "",
[int]$Port = 0,
[ValidateSet("Auto", "On", "Off")] [string]$Bridge = "Auto",
[switch]$NoBridge, # = -Bridge Off
# In-game ImGui under Decal (engine.json DecalInGameImGui, default on): Default leaves
# RYNTHCORE_DECAL_IMGUI unset; On = 1; Off = 0 (the old coexistence path, no D3D9).
[ValidateSet("Default", "On", "Off")] [string]$InGameUi = "Default"
)
$ErrorActionPreference = "Stop"
if ([IO.Path]::GetFullPath($Runtime).TrimEnd('\') -ieq "C:\Games\RynthCore\Runtime") { throw "refusing the live runtime" }
$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$injector = "$repo\out\injector-spike\RynthCore.Injector.exe"
if (-not (Test-Path $injector)) {
dotnet publish "$repo\src\RynthCore.Injector\RynthCore.Injector.csproj" -c Release -o "$repo\out\injector-spike" -nologo -v q | Out-Null
}
$env:RYNTHCORE_ENGINE_SETTINGS = $Settings
$env:RYNTHCORE_TEST_CLIENT = "DecalBridgeSpike"
$env:LOCALAPPDATA = "C:\Games\RynthCore\Test\localappdata"
New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null
$env:RYNTHCORE_DISPATCH_FILE = "C:\Games\RynthCore\Test\dispatch-decal.txt"
Set-Content $env:RYNTHCORE_DISPATCH_FILE "# decal spike dispatch file"
# Set or clear both every time: a script run in the same session must not inherit the last run's.
if ($NoBridge) { $Bridge = "Off" }
$env:RYNTHCORE_DECAL_BRIDGE = switch ($Bridge) { "On" { "1" } "Off" { "0" } default { $null } }
$env:RYNTHCORE_DECAL_IMGUI = switch ($InGameUi) { "On" { "1" } "Off" { "0" } default { $null } }
$launchArgs = @("--launch", "--account", $Account, "--server", $Server, "--engine", "$Runtime\RynthCore.Loader.dll", "--character", $Character)
if ($Mode -eq "DecalOnly") { $launchArgs += "--decal-only" } elseif ($Mode -eq "Both") { $launchArgs += "--decal" }
if ($HostName) { $launchArgs += @("--host", $HostName) }
if ($Port -gt 0) { $launchArgs += @("--port", "$Port") }
$out = & $injector $launchArgs 2>&1
$out | ForEach-Object { Write-Host " $_" }
$m = $out | Select-String "LAUNCHED_PID=(\d+)"
if (-not $m) { throw "launch failed" }
$clientPid = [int]$m.Matches[0].Groups[1].Value
Add-Content "C:\Games\RynthCore\Test\decal-spike-pids.txt" "$(Get-Date -Format s) $Mode $clientPid"
Write-Host "TEST_PID=$clientPid"

View file

@ -0,0 +1,168 @@
# Test-DecalBridgeInWorld.ps1 - the in-world half of the Decal-bridge spike, in one command.
# Needs Tom's LOCAL server running and the bridge registered (Register-DecalBridge.ps1, or
# RynthCore.Injector --decal-bridge register --dir <folder with RynthCore.DecalBridge.dll>).
# TEST CLIENTS ONLY: it starts its own clients from C:\Games\RynthCore\AcClient and kills only
# the PIDs it started. Three runs, one test client at a time:
# A Decal only (opt-in: -Runs A,B,C; nothing auto-selects the character without the
# engine, so pick it by hand) -> which code Decal + its plugins patch in world
# B Decal + RynthCore, bridge (DecalBridge=Auto) -> bridge traffic, a plugin receiving it,
# a TYPED chat-bar command, a line sent to AC through
# Decal (/loc), 2 hot reloads, VTank loaded, the own-device
# ImGui pop-out (snapshot BMP)
# C Decal + RynthCore, DecalBridge=Off (the old coexistence mode) -> who owns the contested hooks
# D RynthCore only, no Decal (normal hook mode must be unchanged)
# Everything lands in C:\Games\RynthCore\Test\decal-bridge\inworld-<time>\.
#
# .\spikes\DecalBridge\Test-DecalBridgeInWorld.ps1 -Account Buffi -Server ACEmulator -Character "+Buffi"
param(
[string]$Account = "Buffi",
[string]$Server = "ACEmulator",
[string]$Character = "+Buffi",
[string]$HostName = "",
[int]$Port = 0,
[string[]]$Runs = @("B", "C", "D"),
[int]$LoginTimeout = 150,
[string]$Runtime = "C:\Games\RynthCore\Test\rt-decal",
[string]$Settings = "C:\Games\RynthCore\Test\engine-decal.json",
[int]$Settle = 30
)
$ErrorActionPreference = "Stop"
$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$start = "$PSScriptRoot\Start-DecalTestClient.ps1"
$diff = "$repo\tools\ProcPatchDiff.py"
$out = "C:\Games\RynthCore\Test\decal-bridge\inworld-$(Get-Date -Format yyyyMMdd-HHmmss)"
New-Item -ItemType Directory -Force $out | Out-Null
$report = "$out\report.txt"
function Say([string]$s) { Write-Host $s; Add-Content $report $s }
$checkPort = if ($Port -gt 0) { $Port } else { 9000 }
if (-not (Get-NetUDPEndpoint -ErrorAction SilentlyContinue | Where-Object LocalPort -eq $checkPort)) {
throw "Nothing listens on UDP ${checkPort}: start the local ACE server first."
}
$vs = "HKCU:\Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\NetworkFilters"
if (-not (Get-ChildItem $vs -ErrorAction SilentlyContinue | Where-Object { (Get-ItemProperty $_.PSPath).Object -eq "RynthCore.DecalBridge.BridgeFilter" })) {
throw "The bridge is not registered: run Register-DecalBridge.ps1 first."
}
function Start-One([string]$mode, [string[]]$extra) {
$opts = @{ Mode = $mode; Account = $Account; Server = $Server; Character = $Character; HostName = $HostName; Port = $Port; Runtime = $Runtime; Settings = $Settings }
foreach ($e in $extra) { $opts[$e] = $true }
& $start @opts *> $null
return [int]((Get-Content C:\Games\RynthCore\Test\decal-spike-pids.txt -Tail 1).Split(' ')[2])
}
function Wait-Match([string]$path, [string]$pattern, [int]$seconds) {
$t0 = Get-Date
while (((Get-Date) - $t0).TotalSeconds -lt $seconds) {
if ((Test-Path $path) -and (Select-String -Path $path -Pattern $pattern -Quiet)) { return $true }
Start-Sleep 2
}
return $false
}
function Stop-One([int]$tp) {
Stop-Process -Id $tp -Force -ErrorAction SilentlyContinue
Say "stopped $tp; waiting 65 s for the server to drop the session"
Start-Sleep 65
}
function Grab([string]$path, [string]$pattern, [int]$max = 60) {
if (Test-Path $path) {
Select-String -Path $path -Pattern $pattern | Select-Object -Last $max |
ForEach-Object { Say (" " + $_.Line.Substring(0, [Math]::Min(300, $_.Line.Length))) }
}
}
function Send([string]$cmd) {
# Through the test client's dispatch file -> AC's main thread -> plugins' OnChatBarEnter.
Set-Content "C:\Games\RynthCore\Test\dispatch-decal.txt" "force:$cmd"
Start-Sleep 4
}
function Typed([int]$tp, [string]$cmd) {
# Into the test client's own window (PostMessage by pid): Enter, the text, Enter.
python "$PSScriptRoot\AcWindow.py" key $tp 0x0D | Out-Null
Start-Sleep -Milliseconds 400
python "$PSScriptRoot\AcWindow.py" type $tp $cmd | Out-Null
python "$PSScriptRoot\AcWindow.py" key $tp 0x0D | Out-Null
Start-Sleep 4
}
function HasModule([int]$tp, [string]$name) {
$p = Get-Process -Id $tp -ErrorAction SilentlyContinue
return [bool]($p -and ($p.Modules | Where-Object { $_.ModuleName -ieq $name }))
}
function Reload([int]$tp) {
$ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$tp")
[void]$ev.Set(); $ev.Dispose()
}
if ($Runs -contains "A") {
Say "==== A: Decal only"
$tp = Start-One "DecalOnly" @()
$blog = "C:\Games\RynthCore\Logs\DecalBridge.$tp.log"
Say "pid $tp; in world: $(Wait-Match $blog 'LoginComplete' $LoginTimeout)"
Start-Sleep $Settle
python $diff $tp --json "$out\A-decal-only.json" *> "$out\A-decal-only.txt"
Say "patch diff -> $out\A-decal-only.txt"
Grab $blog "." 30
Stop-One $tp
}
if ($Runs -contains "B") {
Say "==== B: Decal + RynthCore, bridge mode Auto (in-game ImGui: engine.json default)"
$tp = Start-One "Both" @()
$log = "C:\Games\RynthCore\Logs\RynthCore.$tp.log"
Say "pid $tp; in world: $(Wait-Match $log 'starting plugin tick pump|BridgeProbe: OnLoginComplete' $LoginTimeout)"
Start-Sleep $Settle
python $diff $tp --names $log --json "$out\B-bridge.json" *> "$out\B-bridge.txt"
Say " VTank loaded (uTank2.dll): $(HasModule $tp 'uTank2.dll')"
Send "/ra cache"
Say "-- typed /ra cache (Decal CommandLineText -> bridge -> engine)"
Typed $tp "/ra cache"
Say "-- /loc through the engine's dispatcher -> bridge -> Decal InvokeChatParser"
Send "/loc"
for ($i = 1; $i -le 2; $i++) {
Say "-- reload $i"
Reload $tp
Start-Sleep 30
Send "/ra cache"
}
Grab $log "BRIDGE MODE|bridge is up|skipped - bridge|bridge fallback|DecalBridge:|BridgeProbe:|location|unloaded|Reload: complete|EndSceneHook: INSTALLED|tick pump|UseTime \(no EndScene|\[ERR\]" 140
$fps = Select-String -Path $log -Pattern "hb #\d+ .*fps=(\d+)" | Select-Object -Last 10 | ForEach-Object { $_.Matches[0].Groups[1].Value }
Say " fps (last 10 heartbeats): $($fps -join ' ')"
Grab "C:\Games\RynthCore\Logs\DecalBridge.$tp.log" "." 40
$p = Get-Process -Id $tp -ErrorAction SilentlyContinue
Say " client alive=$([bool]$p) responding=$($p.Responding)"
Stop-One $tp
}
if ($Runs -contains "C") {
Say "==== C: Decal + RynthCore, DecalBridge=Off (old coexistence mode)"
$tp = Start-One "Both" @("NoBridge")
$log = "C:\Games\RynthCore\Logs\RynthCore.$tp.log"
Say "pid $tp; in world: $(Wait-Match $log 'starting plugin tick pump' $LoginTimeout)"
Start-Sleep $Settle
python $diff $tp --names $log --json "$out\C-coexistence.json" *> "$out\C-coexistence.txt"
Send "/ra cache"
Say "-- reload"
Reload $tp
Start-Sleep 30
Send "/ra cache"
Grab $log "PATTERN MISS|Decal|unloaded|Reload: complete|tick pump|BridgeProbe:|\[ERR\]" 80
$p = Get-Process -Id $tp -ErrorAction SilentlyContinue
Say " client alive=$([bool]$p) responding=$($p.Responding)"
Stop-One $tp
}
if ($Runs -contains "D") {
Say "==== D: RynthCore only, no Decal (normal hook mode)"
$tp = Start-One "EngineOnly" @()
$log = "C:\Games\RynthCore\Logs\RynthCore.$tp.log"
Say "pid $tp; in world: $(Wait-Match $log 'OnLoginComplete observed' $LoginTimeout)"
Start-Sleep $Settle
Send "/ra cache"
Say "-- reload"
Reload $tp
Start-Sleep 30
Send "/ra cache"
# Bridge code must stay silent here: no "DecalBridge:" line, no skipped step.
Grab $log "DecalBridge|skipped - bridge|Decal coexistence|Cache:|unloaded|Reload: complete|\[ERR\]" 60
$p = Get-Process -Id $tp -ErrorAction SilentlyContinue
Say " client alive=$([bool]$p) responding=$($p.Responding)"
Stop-One $tp
}
Say "done: $out"

View file

@ -0,0 +1,128 @@
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using RynthCore.App;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Small code-built dialogs for the Decal bridge: the "Check Decal bridge" report (with
/// Repair / Copy) and the yes/no before the one administrator step.
/// </summary>
internal static class DecalBridgeDialog
{
private static readonly IBrush Back = new SolidColorBrush(Color.Parse("#132028"));
private static readonly IBrush Text = new SolidColorBrush(Color.Parse("#EAF0F4"));
private static readonly IBrush Muted = new SolidColorBrush(Color.Parse("#9AA8B3"));
private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#26C1A6"));
/// <summary>Yes/no. True = the person pressed <paramref name="yes"/>.</summary>
public static async Task<bool> AskAsync(Window owner, string title, string message, string yes, string no)
{
var dialog = NewWindow(title, 560);
var yesButton = new Button { Content = yes, IsDefault = true };
var noButton = new Button { Content = no, IsCancel = true };
yesButton.Click += (_, _) => dialog.Close(true);
noButton.Click += (_, _) => dialog.Close(false);
dialog.Content = Layout(title,
new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap, Foreground = Text },
yesButton, noButton);
bool? result = await dialog.ShowDialog<bool?>(owner);
return result == true;
}
/// <summary>
/// Shows the check's report. With <paramref name="offerRepair"/>, a Repair button; returns
/// true when the person pressed it.
/// </summary>
public static async Task<bool> ShowReportAsync(Window owner, DecalBridgeCheck.Result check, bool offerRepair)
{
string title = check.Blocking ? "Decal bridge check: it would NOT load" : "Decal bridge check: OK";
string report = check.ToReport();
var dialog = NewWindow(title, 760);
var body = new TextBox
{
Text = report,
IsReadOnly = true,
TextWrapping = TextWrapping.Wrap,
FontFamily = new FontFamily("Consolas, Cascadia Mono, monospace"),
FontSize = 12,
MaxHeight = 420,
Foreground = Text,
Background = new SolidColorBrush(Color.Parse("#0F161D")),
};
var copy = new Button { Content = "Copy report" };
copy.Click += async (_, _) =>
{
try
{
var clipboard = TopLevel.GetTopLevel(dialog)?.Clipboard;
if (clipboard != null) await clipboard.SetTextAsync(report);
copy.Content = "Copied";
}
catch { copy.Content = "Copy failed"; }
};
var close = new Button { Content = "Close", IsCancel = true };
close.Click += (_, _) => dialog.Close(false);
Control[] buttons;
if (offerRepair)
{
var repair = new Button { Content = check.NeedsMachineWideRegistration ? "Repair (asks for administrator)" : "Repair", IsDefault = true };
repair.Click += (_, _) => dialog.Close(true);
buttons = new Control[] { repair, copy, close };
}
else
{
buttons = new Control[] { copy, close };
}
string hint = check.Blocking
? "A Decal + RynthCore client started now would run without the bridge: no RynthCore overlay, then a crash. " +
(offerRepair ? "Repair registers the bridge where Decal reads on this PC and checks again." : "Fix the FAIL lines, then check again.")
: "A Decal + RynthCore client started now will load the bridge.";
dialog.Content = Layout(title,
new StackPanel
{
Spacing = 8,
Children =
{
new TextBlock { Text = hint, TextWrapping = TextWrapping.Wrap, Foreground = Muted },
body,
},
},
buttons);
bool? result = await dialog.ShowDialog<bool?>(owner);
return result == true;
}
private static Window NewWindow(string title, double width) => new()
{
Title = title,
Width = width,
SizeToContent = SizeToContent.Height,
CanResize = false,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Background = Back,
};
private static Control Layout(string title, Control body, params Control[] buttons)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right };
foreach (Control b in buttons) row.Children.Add(b);
return new StackPanel
{
Margin = new Thickness(18),
Spacing = 12,
Children =
{
new TextBlock { Text = title, FontSize = 16, FontWeight = FontWeight.SemiBold, Foreground = Accent },
body,
row,
},
};
}
}

View file

@ -0,0 +1,146 @@
using System;
using System.Diagnostics;
using System.Globalization;
namespace RynthCore.App.Avalonia;
/// <summary>The step a launcher download is on.</summary>
public enum DownloadStage
{
/// <summary>Bytes arriving: Done/Total are bytes, against the signed size from the feed.</summary>
Downloading,
/// <summary>The download finished and matched the signed size and SHA-256.</summary>
Verified,
/// <summary>Unpacking an archive: Done/Total are files.</summary>
Unpacking,
/// <summary>Putting the files in place (no measurable progress).</summary>
Installing,
}
/// <summary>
/// One progress report for the launcher's download area. <see cref="What"/> names the download
/// ("RynthNav map", "RynthOracle", "RynthCore 2026.10.5.1"). Reports come from the updater at a
/// few a second at most (<see cref="DownloadMeter"/>); the first, the last and every stage change
/// always come through.
/// </summary>
public sealed record DownloadProgress(string What, DownloadStage Stage, long Done, long Total,
double BytesPerSecond = 0, TimeSpan? Remaining = null, TimeSpan Elapsed = default)
{
/// <summary>0..100, or null when the step has no measurable progress.</summary>
public double? Percent => Total > 0 ? Math.Clamp(Done * 100.0 / Total, 0, 100) : null;
/// <summary>The line under the progress bar.</summary>
public string Detail => Stage switch
{
DownloadStage.Downloading => FormatDownloading(),
DownloadStage.Verified => $"{FormatMb(Total)} downloaded and verified against the signed feed.",
DownloadStage.Unpacking => Total > 0
? $"Unpacking {Done.ToString("N0", CultureInfo.InvariantCulture)} of {Total.ToString("N0", CultureInfo.InvariantCulture)} files…"
: "Unpacking…",
_ => "Installing…",
};
/// <summary>The activity-log line when a download is done: "RynthNav map: 539 MB in 2m10s, verified".</summary>
public string Summary => $"{What}: {FormatMb(Total)} in {FormatDuration(Elapsed)}, verified";
private string FormatDownloading()
{
string s = $"{FormatMb(Done, withUnit: false)} of {FormatMb(Total)}";
if (BytesPerSecond > 0) s += $" · {FormatMb((long)BytesPerSecond)}/s";
if (Remaining is { } r) s += $" · about {FormatDuration(r)} left";
return s;
}
/// <summary>"539 MB", "12.4 MB", "0.3 MB" (one decimal under 100 MB).</summary>
public static string FormatMb(long bytes, bool withUnit = true)
{
double mb = bytes / (1024.0 * 1024.0);
string n = mb >= 100 ? mb.ToString("N0", CultureInfo.InvariantCulture) : mb.ToString("0.0", CultureInfo.InvariantCulture);
return withUnit ? n + " MB" : n;
}
/// <summary>"8s", "2m10s", "1h05m".</summary>
public static string FormatDuration(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h{t.Minutes:00}m";
if (t.TotalMinutes >= 1) return $"{(int)t.TotalMinutes}m{t.Seconds:00}s";
return $"{Math.Max(0, (int)Math.Round(t.TotalSeconds))}s";
}
}
/// <summary>
/// Measures one download: speed over the last few seconds, time left, and throttling so the UI
/// gets a handful of reports a second rather than one per 80 KB read. The clock is injectable
/// for tests.
/// </summary>
public sealed class DownloadMeter
{
public static readonly TimeSpan ReportEvery = TimeSpan.FromMilliseconds(250);
private static readonly TimeSpan SpeedWindow = TimeSpan.FromSeconds(4);
private readonly string _what;
private readonly long _total;
private readonly IProgress<DownloadProgress>? _progress;
private readonly Func<TimeSpan> _clock;
private readonly TimeSpan _start;
private TimeSpan _lastReport = TimeSpan.MinValue;
// A ring of (time, bytes) samples for the speed over the last few seconds.
private readonly (TimeSpan T, long Bytes)[] _samples = new (TimeSpan, long)[32];
private int _sampleCount, _sampleHead;
public DownloadMeter(string what, long total, IProgress<DownloadProgress>? progress, Func<TimeSpan>? clock = null)
{
_what = what;
_total = total;
_progress = progress;
if (clock == null)
{
var sw = Stopwatch.StartNew();
clock = () => sw.Elapsed;
}
_clock = clock;
_start = _clock();
AddSample(_start, 0);
}
public TimeSpan Elapsed => _clock() - _start;
/// <summary>Called after each read; reports at most every <see cref="ReportEvery"/>, and always at the end.</summary>
public void Report(long done)
{
if (_progress == null) return;
TimeSpan now = _clock();
bool last = done >= _total;
if (!last && _lastReport != TimeSpan.MinValue && now - _lastReport < ReportEvery) return;
_lastReport = now;
AddSample(now, done);
double speed = Speed(now, done);
TimeSpan? remaining = speed > 0 && !last ? TimeSpan.FromSeconds((_total - done) / speed) : last ? TimeSpan.Zero : null;
_progress.Report(new DownloadProgress(_what, DownloadStage.Downloading, done, _total, speed, remaining, now - _start));
}
/// <summary>The download matched the signed size and hash.</summary>
public void Verified() =>
_progress?.Report(new DownloadProgress(_what, DownloadStage.Verified, _total, _total, 0, TimeSpan.Zero, Elapsed));
private void AddSample(TimeSpan t, long bytes)
{
_samples[_sampleHead] = (t, bytes);
_sampleHead = (_sampleHead + 1) % _samples.Length;
if (_sampleCount < _samples.Length) _sampleCount++;
}
private double Speed(TimeSpan now, long done)
{
// The oldest sample still inside the window (or the oldest kept) is the baseline.
(TimeSpan T, long Bytes) baseline = (now, done);
for (int i = 0; i < _sampleCount; i++)
{
var s = _samples[(_sampleHead - _sampleCount + i + _samples.Length) % _samples.Length];
if (now - s.T <= SpeedWindow || i == _sampleCount - 1) { baseline = s; break; }
}
double secs = (now - baseline.T).TotalSeconds;
return secs > 0.05 ? (done - baseline.Bytes) / secs : 0;
}
}

View file

@ -108,10 +108,39 @@
</Border>
<Grid Grid.Row="1" ColumnDefinitions="3*,Auto,2*">
<TabControl Grid.Column="0" Margin="14,0,0,0" Padding="0">
<TabControl x:Name="MainTabs" Grid.Column="0" Margin="14,0,0,0" Padding="0">
<TabItem Header="Launcher">
<ScrollViewer>
<StackPanel Spacing="12" Margin="6">
<!-- Updates: the card is built by UpdateCardModel (MainWindow.RefreshUpdateCard). -->
<Border x:Name="UpdateCardBorder" Background="#132028" CornerRadius="16" Padding="18"
BorderBrush="#243742" BorderThickness="1">
<StackPanel Spacing="8">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Grid.Column="0" Spacing="4" VerticalAlignment="Center">
<TextBlock x:Name="UpdateCardTitle" Text="Updates" FontSize="16" FontWeight="SemiBold"
Foreground="#26C1A6" TextWrapping="Wrap" />
<TextBlock x:Name="UpdateCardDetail" Text="Not checked yet." TextWrapping="Wrap" Foreground="#9AA8B3" />
</StackPanel>
<WrapPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Top" Margin="12,0,0,0">
<Button x:Name="UpdateCardActionButton" IsVisible="False" Margin="0,0,8,6"
Background="#26C1A6" Foreground="#0B1218" FontWeight="SemiBold" />
<Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,0,6" />
</WrapPanel>
</Grid>
<StackPanel x:Name="UpdateCardWhatsNewPanel" Spacing="2" IsVisible="False" />
<Grid x:Name="DownloadArea" ColumnDefinitions="*,Auto" IsVisible="False">
<ProgressBar x:Name="DownloadProgressBar" Grid.Column="0" Minimum="0" Maximum="100"
Height="10" MinHeight="10" VerticalAlignment="Center"
Foreground="#26C1A6" Background="#0F161D" />
<Button x:Name="CancelDownloadButton" Grid.Column="1" Content="Cancel" Margin="10,0,0,0"
ToolTip.Tip="Stops the download. Nothing half-installed is left behind: the partial file is deleted and what you have stays as it is." />
</Grid>
<Button x:Name="UpdateCardNewPluginsButton" IsVisible="False" HorizontalAlignment="Left"
Background="Transparent" BorderThickness="0" Padding="0" Foreground="#F2C14E" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Launch Targets" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
@ -234,36 +263,58 @@
</ScrollViewer>
</TabItem>
<TabItem Header="Plugins">
<ScrollViewer>
<TabItem x:Name="PluginsTab" Header="Plugins">
<ScrollViewer x:Name="PluginsScroll">
<StackPanel Spacing="12" Margin="6">
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Updates" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<!-- Compact: the update card with its buttons is on the Launcher tab. -->
<TextBlock x:Name="UpdateStatusText"
Text="Not checked yet."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<WrapPanel Orientation="Horizontal">
<Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,8,6" />
<Button x:Name="UpdatePluginsButton" Content="Update plugins" IsVisible="False" Margin="0,0,8,6" />
<Button x:Name="InstallCoreUpdateButton" Content="Install RynthCore update" IsVisible="False" Margin="0,0,8,6" />
</WrapPanel>
<ProgressBar x:Name="PluginsTabProgressBar" Minimum="0" Maximum="100" Height="6" MinHeight="6"
IsVisible="False" Foreground="#26C1A6" Background="#0F161D" />
<Button x:Name="ShowUpdateCardButton" Content="Updates on the Launcher tab" HorizontalAlignment="Left"
Background="Transparent" BorderThickness="0" Padding="0" Foreground="#26C1A6" />
<CheckBox x:Name="AutoUpdatePluginsCheckBox"
Content="Update plugins automatically (a running bot keeps its version until AC restarts)"
Foreground="#EAF0F4" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Usage statistics" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<CheckBox x:Name="UsageStatsCheckBox"
Content="Help improve RynthCore: send an anonymous usage report once a day"
Foreground="#EAF0F4" />
<TextBlock x:Name="UsageStatsWhatText" TextWrapping="Wrap" Foreground="#9AA8B3" />
<TextBlock x:Name="UsageStatsNeverText" TextWrapping="Wrap" Foreground="#9AA8B3" />
<TextBlock x:Name="UsageStatsStopText" TextWrapping="Wrap" Foreground="#9AA8B3" />
<Button x:Name="ShowUsageReportButton" Content="Show what is sent" HorizontalAlignment="Left" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Plugins" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<TextBlock Text="Manage the runtime modules loaded into RynthCore. Add plugins by browsing for their DLL file."
<TextBlock Text="The plugins RynthCore loads. Untick one to skip it; the X takes it out of the list (its files stay on disk). RynthSuite plugins you don't have are under Available plugins below; Add Plugin is for any other plugin DLL."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<StackPanel x:Name="PluginLoadoutPanel" Spacing="10" />
<Button x:Name="AddPluginDllButton" Content="Add Plugin" HorizontalAlignment="Left" />
</StackPanel>
</Border>
<Border x:Name="AvailablePluginsBorder" Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Available plugins" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<TextBlock x:Name="AvailablePluginsHint"
Text="Plugins you can add appear here after the first update check."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<StackPanel x:Name="AvailablePluginsPanel" Spacing="10" />
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</TabItem>
@ -352,6 +403,9 @@
<CheckBox x:Name="EnableDcompOverlayCheckBox"
Content="Use DComp overlay (experimental, GPU-rendered)"
ToolTip.Tip="When ON, the engine starts the new DirectComposition overlay instead of the production AvaloniaOverlay. Mutually exclusive — Avalonia is single-app-per-process. Toggle takes effect on next AC client launch (a hot reload won't switch overlays)." />
<CheckBox x:Name="EnableImGuiBackendCheckBox"
Content="ImGui panels (preview)"
ToolTip.Tip="When ON, the engine runs its in-client ImGui layer, which docked panels move to as their ImGui versions are finished (choose per panel with /rc ui). Popped-out panels stay Avalonia windows. Costs nothing while no ImGui panel is open. Takes effect on next AC client launch or engine reload (RL)." />
</StackPanel>
</Border>
@ -366,6 +420,8 @@
<Button x:Name="RefreshSessionsButton" Content="Refresh Sessions" Margin="0,0,8,8" />
<Button x:Name="ResetOverlayBarButton" Content="Reset Overlay Bar" Margin="0,0,8,8"
ToolTip.Tip="Drags the in-game RynthCore overlay bar back to the top-left corner. Use this if the bar was moved off-screen and can no longer be reached. Applies to every running RynthCore client." />
<Button x:Name="CheckDecalBridgeButton" Content="Check Decal bridge" Margin="0,0,8,8"
ToolTip.Tip="For Decal + RynthCore (experimental): checks whether a client started now will load the RynthCore Decal bridge - where Decal reads its plugin list on this PC, whether the bridge is listed and enabled there, Decal's version and its .NET part. Changes nothing unless you press Repair." />
</WrapPanel>
<TextBlock Text="Manual inject targets the first detected acclient.exe session. Reset Overlay Bar signals all running RynthCore clients via the dispatch file."
TextWrapping="Wrap"

File diff suppressed because it is too large Load diff

View file

@ -7,7 +7,67 @@ namespace RynthCore.App.Avalonia;
internal static class Program
{
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
public static int Main(string[] args)
{
// The uninstaller removes the Decal bridge registration (docs/DECAL_BRIDGE_PLAN.md):
// no window, just the per-user registry entries this launcher added.
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-unregister", StringComparison.OrdinalIgnoreCase)))
{
bool ok = RynthCore.App.DecalBridgeRegistration.Unregister(out string report);
LauncherDiag.Info($"DECALBRIDGE: unregister (command line): {report}");
// A machine-wide entry (added with administrator rights when AC runs elevated on this
// PC) goes too: the uninstaller removes the DLL it points at. Ask for the rights only
// when there is one.
if (RynthCore.App.DecalBridgeRegistration.MachineEntryIsOurs())
{
var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string mReport);
if (outcome == RynthCore.App.DecalBridgeRegistration.Outcome.NeedsAdmin && Environment.ProcessPath is string self)
outcome = RynthCore.App.DecalBridgeRegistration.RunElevated(self, "--decal-bridge-unregister-machine", out mReport);
LauncherDiag.Info($"DECALBRIDGE: unregister machine-wide (command line): {mReport}");
ok &= outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered;
}
return ok ? 0 : 1;
}
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-unregister-machine", StringComparison.OrdinalIgnoreCase)))
{
var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string report);
LauncherDiag.Info($"DECALBRIDGE: unregister machine-wide (elevated step): {report}");
return outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered ? 0 : 1;
}
// The launcher's elevated step for "AC reads Decal's filter list for all users"
// (MainWindow.EnsureDecalBridgeAsync): --decal-bridge-register-machine "<bridge folder>".
int rm = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge-register-machine", StringComparison.OrdinalIgnoreCase));
if (rm >= 0)
{
string dir = rm + 1 < args.Length ? args[rm + 1] : RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory;
var outcome = RynthCore.App.DecalBridgeRegistration.RegisterMachineWide(dir, out string report);
LauncherDiag.Info($"DECALBRIDGE: register machine-wide (elevated step): {report}");
return outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered ? 0 : 1;
}
// The installer's per-user half (installer\RynthCore.iss, as the installing user, every
// install and update): our entry into an EXISTING per-user copy of Decal's filter list.
int iu = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge-install-user", StringComparison.OrdinalIgnoreCase));
if (iu >= 0)
{
string dir = iu + 1 < args.Length ? args[iu + 1] : RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory;
bool ok = RynthCore.App.DecalBridgeRegistration.InstallPerUser(dir, out string report);
LauncherDiag.Info($"DECALBRIDGE: install per-user (installer): {report}");
return ok ? 0 : 1;
}
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-status", StringComparison.OrdinalIgnoreCase)))
{
LauncherDiag.Info($"DECALBRIDGE: status (command line): {RynthCore.App.DecalBridgeRegistration.GetStatus()}");
return 0;
}
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-check", StringComparison.OrdinalIgnoreCase)))
{
var check = RynthCore.App.RealDecalCheckHost.Check(RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory,
RynthCore.App.DecalLocator.TryGetDecalAcClientPath(), EngineJsonStore.Path);
LauncherDiag.Info($"DECALBRIDGE: check (command line):{Environment.NewLine}{check.ToReport()}");
return check.Blocking ? 1 : 0;
}
return BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()

View file

@ -32,6 +32,9 @@
<Compile Include="..\RynthCore.App\LaunchAccountProfile.cs" Link="Shared\LaunchAccountProfile.cs" />
<Compile Include="..\RynthCore.App\InjectionMode.cs" Link="Shared\InjectionMode.cs" />
<Compile Include="..\RynthCore.App\DecalLocator.cs" Link="Shared\DecalLocator.cs" />
<Compile Include="..\RynthCore.App\DecalBridgeRegistration.cs" Link="Shared\DecalBridgeRegistration.cs" />
<Compile Include="..\RynthCore.App\DecalBridgeCheck.cs" Link="Shared\DecalBridgeCheck.cs" />
<Compile Include="..\RynthCore.App\RealDecalCheckHost.cs" Link="Shared\RealDecalCheckHost.cs" />
<Compile Include="..\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="Shared\AcLaunchArgumentBuilder.cs" />
<Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" />
<Compile Include="..\RynthCore.App\AcClientLoginAutomationService.cs" Link="Shared\AcClientLoginAutomationService.cs" />
@ -41,6 +44,7 @@
<Compile Include="..\RynthCore.App\BuildVersion.cs" Link="Shared\BuildVersion.cs" />
<Compile Include="..\RynthCore.App\AppSettings.cs" Link="Shared\AppSettings.cs" />
<Compile Include="..\RynthCore.App\AppSettingsStore.cs" Link="Shared\AppSettingsStore.cs" />
<Compile Include="..\RynthCore.App\DecalAccountModes.cs" Link="Shared\DecalAccountModes.cs" />
<Compile Include="..\RynthCore.App\PluginDefinition.cs" Link="Shared\PluginDefinition.cs" />
<Compile Include="..\RynthCore.Injector\EngineInjectionService.cs" Link="Shared\EngineInjectionService.cs" />
<Compile Include="..\RynthCore.Injector\InjectionResult.cs" Link="Shared\InjectionResult.cs" />

View file

@ -0,0 +1,301 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.App.Avalonia;
/// <summary>
/// "Available plugins": every plugin in the signed feed that isn't in the player's plugin list,
/// for the player to install or not.
///
/// Install downloads the feed's file (verified against the signed size and SHA-256, like every
/// update) into C:\Games\RynthSuite\&lt;Name&gt;\&lt;File&gt; - the folder beside RynthAi's, or the
/// default - and the caller adds it to the plugin list. Only plugins named in the signed manifest
/// can be installed, from the URLs it carries; nothing else.
///
/// Removing a plugin from the list never deletes its files; a feed plugin that leaves the list is
/// simply available again.
///
/// "New": a plugin the launcher sees in the feed for the first time is marked New for a month and
/// said once in the activity log. The first time this runs (no update-seen-plugins.json yet),
/// what the feed already had counts as old except <see cref="RecentlyAdded"/>, which a player
/// who never got them should hear about.
/// </summary>
internal sealed partial class RynthUpdater
{
public const string DefaultSuiteDir = @"C:\Games\RynthSuite";
private const string RynthAiFile = "RynthCore.Plugin.RynthAi.dll";
private const int MaxDescriptionLength = 160;
private const int MaxChanges = 20;
private static readonly TimeSpan NewBadgeFor = TimeSpan.FromDays(30);
private static readonly Regex SafeFolderName = new(@"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", RegexOptions.CultureInvariant);
/// <summary>A feed plugin the player can install: where it would go, what it is, and whether it's new.</summary>
public sealed record AvailablePlugin(PluginEntry Entry, string Path, string Description, string Version, bool IsNew);
/// <summary>What <see cref="InstallPluginAsync"/> did: Downloaded is false when a good copy was already there.</summary>
public sealed record PluginInstall(PluginEntry Entry, string Path, string Description, bool Downloaded);
/// <summary>
/// Plugins new in the feed before this list existed (2026.10.3.4). 2026.10.4.3 installed them
/// beside RynthAi automatically; from this launcher on they are offered, not forced.
/// </summary>
private static readonly string[] RecentlyAdded = { "RynthOracle", "RynthInventory" };
/// <summary>One line per plugin for feeds that carry no "description" (every feed before 2026.10.5).</summary>
private static readonly Dictionary<string, string> BuiltInDescriptions = new(StringComparer.OrdinalIgnoreCase)
{
["RynthAi"] = "The bot: combat, buffs, looting, navigation routes and metas.",
["RynthChat"] = "A chat window that sorts messages into tabs.",
["RynthTracker"] = "Kills, experience and luminance per hour for each session.",
["RynthNav"] = "Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB).",
["RynthVision"] = "Shows unclimbable slopes, impassable water and your radar range in the world.",
["RynthLua"] = "Lua scripting for metas and your own scripts.",
["RynthOracle"] = "Quests, character, titles and leaderboards.",
["RynthInventory"] = "Search every character's items.",
};
/// <summary>The feed's description, else the launcher's own line, else "".</summary>
public static string DescribePlugin(PluginEntry e) =>
e.Description.Length > 0 ? e.Description
: BuiltInDescriptions.TryGetValue(e.Name, out string? d) ? d : "";
private string? _suiteDirOverride;
/// <summary>Tests: the folder to use when no plugin in the list shows where RynthSuite lives.</summary>
internal void SetDefaultSuiteDir(string dir) => _suiteDirOverride = dir;
/// <summary>Tests: the clock for the New badge.</summary>
internal Func<DateTime> UtcNow { get; set; } = () => DateTime.UtcNow;
/// <summary>
/// Where RynthSuite plugins go: beside RynthAi (C:\Games\RynthSuite\RynthAi\x.dll -> C:\Games\RynthSuite),
/// else beside any feed plugin that sits in a folder named after it, else the default.
/// </summary>
public string SuiteDir(Manifest manifest, IEnumerable<string> pluginPaths)
{
List<string> paths = pluginPaths.ToList();
string? FromPlugin(string path)
{
string? folder = Path.GetDirectoryName(path);
string? suite = Path.GetDirectoryName(folder);
return string.IsNullOrEmpty(folder) || string.IsNullOrEmpty(suite) ? null : suite;
}
string? ai = paths.FirstOrDefault(p => string.Equals(Path.GetFileName(p), RynthAiFile, StringComparison.OrdinalIgnoreCase));
if (ai != null && FromPlugin(ai) is { } s1) return s1;
foreach (string p in paths)
{
PluginEntry? e = manifest.Plugins.FirstOrDefault(x => string.Equals(x.File, Path.GetFileName(p), StringComparison.OrdinalIgnoreCase));
if (e != null && string.Equals(Path.GetFileName(Path.GetDirectoryName(p)), e.Name, StringComparison.OrdinalIgnoreCase)
&& FromPlugin(p) is { } s2)
return s2;
}
return _suiteDirOverride ?? DefaultSuiteDir;
}
/// <summary>C:\Games\RynthSuite\&lt;Name&gt;\&lt;File&gt;; null for a name that isn't a plain folder name.</summary>
private static string? TargetPath(PluginEntry e, string suiteDir) =>
SafeFolderName.IsMatch(e.Name) && e.Name != "." && e.Name != ".." ? Path.Combine(suiteDir, e.Name, e.File) : null;
/// <summary>
/// Every feed plugin whose file isn't in <paramref name="pluginPaths"/> (by file name, like the
/// updates), except companions about to be installed anyway.
/// </summary>
public List<AvailablePlugin> GetAvailable(Manifest manifest, IEnumerable<string> pluginPaths, IEnumerable<CompanionInstall>? pending = null)
{
List<string> paths = pluginPaths.ToList();
var listed = new HashSet<string>(paths.Select(Path.GetFileName).OfType<string>(), StringComparer.OrdinalIgnoreCase);
var skip = new HashSet<string>((pending ?? Array.Empty<CompanionInstall>()).Select(c => c.Entry.File), StringComparer.OrdinalIgnoreCase);
string suite = SuiteDir(manifest, paths);
Dictionary<string, DateTime> seen = ReadSeenPlugins(out _);
DateTime now = UtcNow();
var result = new List<AvailablePlugin>();
foreach (PluginEntry e in manifest.Plugins)
{
if (listed.Contains(e.File) || skip.Contains(e.File)) continue;
if (TargetPath(e, suite) is not { } target) continue;
bool isNew = seen.TryGetValue(e.Name, out DateTime first) && now - first < NewBadgeFor;
result.Add(new AvailablePlugin(e, target, DescribePlugin(e), manifest.Version, isNew));
}
// New ones first, then by name.
return result.OrderByDescending(a => a.IsNew).ThenBy(a => a.Entry.Name, StringComparer.OrdinalIgnoreCase).ToList();
}
/// <summary>The Available list for a check, against the plugin list as it is now.</summary>
public List<AvailablePlugin> GetAvailable(CheckResult check, IEnumerable<string> pluginPaths) =>
GetAvailable(check.Manifest, pluginPaths, check.Companions);
/// <summary>
/// Installs one plugin from the signed feed for the caller to add to the plugin list. A file
/// already at the target is kept when it is the release build or newer (someone's own build);
/// an older one is replaced and kept beside it as .previous. Throws, with nothing changed,
/// when the download doesn't match the signed size and hash or is cancelled.
/// </summary>
public async Task<PluginInstall> InstallPluginAsync(CheckResult check, string name, IEnumerable<string> pluginPaths,
IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
List<string> paths = pluginPaths.ToList();
PluginEntry e = check.Manifest.Plugins.FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))
?? throw new InvalidOperationException($"{name} is not in the update feed");
if (paths.Any(p => string.Equals(Path.GetFileName(p), e.File, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"{e.Name} is already in your plugin list");
string target = TargetPath(e, SuiteDir(check.Manifest, paths))
?? throw new InvalidDataException($"bad plugin name '{e.Name}' in the feed");
if (File.Exists(target))
{
bool same = string.Equals(Sha256File(target), e.Sha256, StringComparison.OrdinalIgnoreCase);
bool localBuild = File.GetLastWriteTimeUtc(target) > check.Manifest.PublishedUtc.AddMinutes(1);
if (same || localBuild)
return new PluginInstall(e, target, DescribePlugin(e), Downloaded: false);
}
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll");
try
{
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct, e.Name, progress);
progress?.Report(new DownloadProgress(e.Name, DownloadStage.Installing, 0, 0));
// Stamp the release time so a later check never mistakes it for a local build.
File.SetLastWriteTimeUtc(temp, check.Manifest.PublishedUtc);
if (File.Exists(target)) File.Copy(target, target + ".previous", overwrite: true);
File.Move(temp, target, overwrite: true);
}
finally
{
try { File.Delete(temp); } catch { }
}
return new PluginInstall(e, target, DescribePlugin(e), Downloaded: true);
}
// ── Manifest fields (optional, backward-compatible) ───────────────────────
/// <summary>The plugin entry's optional "description": one line, plain text, at most 160 characters.</summary>
private static string ReadDescription(JsonElement p)
{
if (!p.TryGetProperty("description", out JsonElement d) || d.ValueKind != JsonValueKind.String) return "";
return OneLine(d.GetString(), MaxDescriptionLength);
}
/// <summary>The manifest's optional "changes": up to 20 lines.</summary>
private static IReadOnlyList<string> ReadChanges(JsonElement r)
{
if (!r.TryGetProperty("changes", out JsonElement c) || c.ValueKind != JsonValueKind.Array) return Array.Empty<string>();
var list = new List<string>();
foreach (JsonElement e in c.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.String) continue;
string line = OneLine(e.GetString(), 300);
if (line.Length > 0) list.Add(line);
if (list.Count >= MaxChanges) break;
}
return list;
}
private static string OneLine(string? s, int max)
{
if (string.IsNullOrWhiteSpace(s)) return "";
var sb = new StringBuilder(Math.Min(s.Length, max + 1));
bool space = false;
foreach (char ch in s)
{
if (char.IsWhiteSpace(ch) || char.IsControl(ch)) { space = sb.Length > 0; continue; }
if (space) { sb.Append(' '); space = false; }
sb.Append(ch);
if (sb.Length > max) break;
}
string line = sb.ToString();
return line.Length > max ? line[..(max - 1)].TrimEnd() + "…" : line;
}
// ── Seen plugins (the New badge) ──────────────────────────────────────────
private string SeenPath => Path.Combine(_stateDir, "update-seen-plugins.json");
private Dictionary<string, DateTime> ReadSeenPlugins(out bool existed)
{
var map = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
existed = false;
try
{
if (!File.Exists(SeenPath)) return map;
using var doc = JsonDocument.Parse(File.ReadAllText(SeenPath));
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
if (p.Value.ValueKind == JsonValueKind.String && DateTime.TryParse(p.Value.GetString(), null,
System.Globalization.DateTimeStyles.AdjustToUniversal | System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime t))
map[p.Name] = t;
existed = true;
}
catch { map.Clear(); existed = false; }
return map;
}
/// <summary>Records the feed's plugins as seen; returns the ones seen for the first time that count as new.</summary>
private HashSet<string> RecordSeenPlugins(Manifest manifest)
{
var fresh = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, DateTime> seen = ReadSeenPlugins(out bool existed);
HashSet<string> offered = ReadOfferedCompanions();
DateTime now = UtcNow();
bool changed = !existed;
foreach (PluginEntry e in manifest.Plugins)
{
if (seen.ContainsKey(e.Name)) continue;
// First run of this list: only the recent additions are news, and not to a player who
// already had them offered (2026.10.4.3 installed them; removing one keeps it removed).
bool isNew = existed || (RecentlyAdded.Contains(e.Name, StringComparer.OrdinalIgnoreCase) && !offered.Contains(e.Name));
seen[e.Name] = isNew ? now : DateTime.UnixEpoch;
if (isNew) fresh.Add(e.Name);
changed = true;
}
if (changed)
{
try
{
Directory.CreateDirectory(_stateDir);
string tmp = SeenPath + ".tmp";
var ordered = seen.OrderBy(kv => kv.Key, StringComparer.OrdinalIgnoreCase)
.ToDictionary(kv => kv.Key, kv => kv.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"));
File.WriteAllText(tmp, JsonSerializer.Serialize(ordered, new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8);
File.Move(tmp, SeenPath, overwrite: true);
}
catch { }
}
return fresh;
}
}
/// <summary>Edits to the launcher's plugin list (kept apart from the window so tests can run them).</summary>
internal static class PluginListEdits
{
/// <summary>Adds <paramref name="path"/> once; false when it was already listed.</summary>
public static bool Add(IList<string> paths, string path)
{
if (paths.Any(p => string.Equals(p, path, StringComparison.OrdinalIgnoreCase))) return false;
paths.Add(path);
return true;
}
/// <summary>
/// Takes <paramref name="path"/> out of the list, and out of the disabled list so adding it back
/// later starts it enabled. Never touches the file.
/// </summary>
public static bool Remove(IList<string> paths, IList<string>? disabled, string path)
{
bool removed = RemoveAll(paths, path) > 0;
if (disabled != null) RemoveAll(disabled, path);
return removed;
}
private static int RemoveAll(IList<string> list, string path)
{
int n = 0;
for (int i = list.Count - 1; i >= 0; i--)
if (string.Equals(list[i], path, StringComparison.OrdinalIgnoreCase)) { list.RemoveAt(i); n++; }
return n;
}
}

View file

@ -0,0 +1,298 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.App.Avalonia;
/// <summary>
/// RynthNav's data folder (C:\Games\RynthCore\NavData by default): the navmesh tiles, portals.tsv
/// and locations.json, shipped as one archive.
///
/// Feed: an optional "navdata" object in the signed manifest —
/// {"id": hash of the tile set, "release": n, "url", "size", "sha256", "files": file count,
/// "bytes": unpacked size}.
/// The signature covers it exactly like the plugins; the archive is checked against the signed
/// size and SHA-256 before it is opened, and only plain file names RynthNav reads
/// (nav_XXXX.tile, portals.tsv, locations.json, navgraph.bin: the long-range route graph,
/// townnet.json: the Town Network's portals and the walks inside) are
/// accepted from it.
///
/// Install: only when RynthNav is in the plugin list and the folder's navdata.id differs from the
/// feed's id. The archive is unpacked beside the folder (NavData.new), the player's own files there
/// (atlas.txt, recalls.txt, anything else not shipped) are copied across, then the folders swap:
/// the old one is kept as NavData.previous (one generation). Old tiles never mix with new ones —
/// tiles from different bakes don't link. A folder with a navdata.local file in it is never touched
/// (someone baking their own tiles). Running clients keep the tiles they already loaded; new ones
/// load as they move (a relog picks up everything).
/// </summary>
internal sealed partial class RynthUpdater
{
public const string NavDataDefaultDir = @"C:\Games\RynthCore\NavData";
public const string NavDataIdFile = "navdata.id";
public const string NavDataLocalMarker = "navdata.local";
private const string RynthNavFile = "RynthCore.Plugin.RynthNav.dll";
private const long MaxNavDataBytes = 3L << 30; // the archive
private const long MaxNavDataEntryBytes = 32L << 20; // one file in it
private static readonly Regex ShippedName = new(@"^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json)$", RegexOptions.CultureInvariant);
private static readonly Regex IdPattern = new(@"^[0-9a-f]{16,64}$", RegexOptions.CultureInvariant);
public sealed record NavDataEntry(string Id, int Release, string Url, long Size, string Sha256, int Files, long Bytes);
public enum NavDataState { UpToDate, NeedsUpdate, LocalTiles }
public sealed record NavDataStatus(NavDataEntry Entry, string Dir, string InstalledId, NavDataState State);
/// <summary>True for a file name the archive may carry (and that an update replaces).</summary>
public static bool IsShippedNavFile(string name) => ShippedName.IsMatch(name);
/// <summary>
/// A whole number written either way: 1383002945 or 1383002945.0. PowerShell's ConvertTo-Json writes
/// a double with ".0", and GetInt64 refused it - which failed the whole update check for every
/// launcher on 2026.10.3.1/2 ("One of the identified items was in an invalid format").
/// </summary>
private static long WholeNumber(JsonElement e)
{
if (e.TryGetInt64(out long l)) return l;
double d = e.GetDouble();
if (d < 0 || d > long.MaxValue || d != Math.Floor(d)) throw new InvalidDataException($"not a whole number: {e.GetRawText()}");
return (long)d;
}
/// <summary>A navdata entry that can't be read leaves the tiles out of this check; the core and plugins still update.</summary>
private NavDataEntry? TryParseNavData(JsonElement nd)
{
try { return ParseNavData(nd); }
catch (Exception ex) when (ex is InvalidDataException or FormatException or InvalidOperationException or KeyNotFoundException)
{
System.Diagnostics.Debug.WriteLine($"RynthUpdater: navdata entry unreadable ({ex.Message}); tiles skipped this check.");
return null;
}
}
private NavDataEntry ParseNavData(JsonElement nd)
{
string id = (nd.GetProperty("id").GetString() ?? "").ToLowerInvariant();
if (!IdPattern.IsMatch(id)) throw new InvalidDataException($"bad navdata id '{id}'");
int files = (int)WholeNumber(nd.GetProperty("files"));
if (files <= 0) throw new InvalidDataException("navdata lists no files");
return new NavDataEntry(id, (int)WholeNumber(nd.GetProperty("release")), CheckUrl(nd.GetProperty("url").GetString()),
WholeNumber(nd.GetProperty("size")), nd.GetProperty("sha256").GetString() ?? "", files,
nd.TryGetProperty("bytes", out JsonElement b) ? WholeNumber(b) : 0);
}
/// <summary>
/// Where RynthNav reads its data: "navDataDir" in %APPDATA%\RynthCore\rynthnav.json (the same
/// file the plugin reads; see the plugin's NavDataConfig), else the default.
/// </summary>
public string NavDataDir
{
get
{
try
{
string settings = Path.Combine(_stateDir, "rynthnav.json");
if (File.Exists(settings))
{
using var doc = JsonDocument.Parse(File.ReadAllText(settings),
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
if (doc.RootElement.ValueKind == JsonValueKind.Object)
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
if (p.Name.Equals("navDataDir", StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.String
&& p.Value.GetString() is { } dir && Path.IsPathFullyQualified(dir.Trim()))
return dir.Trim().TrimEnd('\\', '/');
}
}
catch { }
return _navDataDirOverride ?? NavDataDefaultDir;
}
}
private string? _navDataDirOverride;
/// <summary>Where the archive is downloaded to; null = %LOCALAPPDATA%\RynthCore\updates (tests set their own).</summary>
internal string? NavDataCacheDir { get; set; }
/// <summary>Tests: the folder to use when rynthnav.json doesn't name one.</summary>
internal void SetDefaultNavDataDir(string dir) => _navDataDirOverride = dir;
private NavDataStatus? CheckNavData(Manifest manifest, IEnumerable<string> pluginPaths)
{
if (manifest.NavData is not { } e) return null;
bool hasNav = pluginPaths.Any(p => string.Equals(Path.GetFileName(p), RynthNavFile, StringComparison.OrdinalIgnoreCase) && File.Exists(p));
if (!hasNav) return null;
string dir = NavDataDir;
string installed = "";
try { if (File.Exists(Path.Combine(dir, NavDataIdFile))) installed = File.ReadAllText(Path.Combine(dir, NavDataIdFile)).Trim().ToLowerInvariant(); }
catch { }
NavDataState state = File.Exists(Path.Combine(dir, NavDataLocalMarker)) ? NavDataState.LocalTiles
: installed == e.Id ? NavDataState.UpToDate : NavDataState.NeedsUpdate;
return new NavDataStatus(e, dir, installed, state);
}
/// <summary>
/// Downloads, verifies and installs the feed's RynthNav data (see the class notes). Returns a
/// line for the activity log. Throws on anything wrong, leaving the installed folder as it was.
/// </summary>
public const string NavDataDisplayName = "RynthNav map";
/// <summary>
/// Cancel is safe at any point before the folder swap: the partial download is deleted, an
/// unpacked staging folder is removed, and the installed tiles stay as they were. A fully
/// downloaded, verified archive stays in the cache and is reused by the next try. The swap
/// itself (two folder renames) doesn't stop half way.
/// </summary>
public async Task<string> UpdateNavDataAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
if (check.NavData is not { State: NavDataState.NeedsUpdate } st) return "";
NavDataEntry e = st.Entry;
string dir = st.Dir.TrimEnd('\\', '/');
string parent = Path.GetDirectoryName(dir) ?? throw new InvalidOperationException($"bad NavData folder {dir}");
Directory.CreateDirectory(parent);
// Room for the archive, the unpacked copy and the old folder kept as .previous.
long need = e.Size + Math.Max(e.Bytes, e.Size * 3) + (64L << 20);
long free = new DriveInfo(Path.GetPathRoot(Path.GetFullPath(dir))!).AvailableFreeSpace;
if (free < need)
throw new IOException($"not enough disk space for the navmesh tiles: {need >> 20} MB needed, {free >> 20} MB free on {Path.GetPathRoot(dir)}");
string cache = NavDataCacheDir ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "updates");
Directory.CreateDirectory(cache);
string zip = Path.Combine(cache, $"navdata-{e.Id}.zip");
if (!(File.Exists(zip) && new FileInfo(zip).Length == e.Size && string.Equals(Sha256File(zip), e.Sha256, StringComparison.OrdinalIgnoreCase)))
{
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxNavDataBytes, zip + ".part", ct, NavDataDisplayName, progress);
File.Move(zip + ".part", zip, overwrite: true);
}
// Unpacking tens of thousands of files takes a while: off the caller's (UI) thread.
await Task.Run(() =>
{
progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Unpacking, 0, e.Files));
string staging = dir + ".new";
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
Directory.CreateDirectory(staging);
try
{
int count = ExtractNavData(zip, staging, ct,
n => progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Unpacking, n, e.Files)));
if (count != e.Files) throw new InvalidDataException($"the tile archive has {count} files, the feed says {e.Files}");
// The player's own files (atlas.txt, recalls.txt, …) and anything else not shipped come along.
if (Directory.Exists(dir)) CopyUnshipped(dir, staging);
File.WriteAllText(Path.Combine(staging, NavDataIdFile), e.Id);
// Last chance to cancel: from here the swap runs to the end.
ct.ThrowIfCancellationRequested();
progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Installing, 0, 0));
SwapNavData(dir, staging);
}
catch
{
try { if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true); } catch { }
throw;
}
}, ct);
try { File.Delete(zip); } catch { }
return $"RynthNav navmesh tiles updated: {e.Files} files into {dir} (the old ones are in {Path.GetFileName(dir)}.previous). Running clients load the new tiles as they move; a relog picks up all of them.";
}
/// <summary>Unpacks only plain, known file names; returns how many files were written.</summary>
internal static int ExtractNavData(string zipPath, string dest, CancellationToken ct = default, Action<int>? unpacked = null)
{
int n = 0;
var sinceReport = System.Diagnostics.Stopwatch.StartNew();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
using ZipArchive za = ZipFile.OpenRead(zipPath);
foreach (ZipArchiveEntry z in za.Entries)
{
ct.ThrowIfCancellationRequested();
if (z.FullName.EndsWith('/') && z.Length == 0) continue; // a folder entry
string name = z.FullName;
if (name != z.Name || !IsShippedNavFile(name))
throw new InvalidDataException($"unexpected file in the tile archive: '{name}'");
if (!seen.Add(name)) throw new InvalidDataException($"'{name}' is in the tile archive twice");
if (z.Length > MaxNavDataEntryBytes) throw new InvalidDataException($"'{name}' is too large ({z.Length} bytes)");
string target = Path.Combine(dest, name);
using (Stream src = z.Open())
using (var f = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
byte[] buf = new byte[81920];
long total = 0; int r;
while ((r = src.Read(buf, 0, buf.Length)) > 0)
{
total += r;
if (total > MaxNavDataEntryBytes) throw new InvalidDataException($"'{name}' unpacks larger than it says");
f.Write(buf, 0, r);
}
}
n++;
if (unpacked != null && sinceReport.Elapsed >= DownloadMeter.ReportEvery)
{
unpacked(n);
sinceReport.Restart();
}
}
unpacked?.Invoke(n);
return n;
}
private static void CopyUnshipped(string from, string to)
{
foreach (string f in Directory.GetFiles(from))
{
string name = Path.GetFileName(f);
if (IsShippedNavFile(name) || name.Equals(NavDataIdFile, StringComparison.OrdinalIgnoreCase)) continue;
string target = Path.Combine(to, name);
if (!File.Exists(target)) File.Copy(f, target);
}
foreach (string d in Directory.GetDirectories(from))
{
string target = Path.Combine(to, Path.GetFileName(d));
Directory.CreateDirectory(target);
CopyTree(d, target);
}
}
private static void CopyTree(string from, string to)
{
foreach (string f in Directory.GetFiles(from)) File.Copy(f, Path.Combine(to, Path.GetFileName(f)), overwrite: false);
foreach (string d in Directory.GetDirectories(from))
{
string t = Path.Combine(to, Path.GetFileName(d));
Directory.CreateDirectory(t);
CopyTree(d, t);
}
}
// dir -> dir.previous, staging -> dir. A client reading a tile at that moment holds it open for
// a few milliseconds, so each move is retried; if the second fails the first is undone.
private static void SwapNavData(string dir, string staging)
{
string previous = dir + ".previous";
bool hadOld = Directory.Exists(dir);
if (hadOld)
{
if (Directory.Exists(previous)) Directory.Delete(previous, recursive: true);
Retry(() => Directory.Move(dir, previous));
}
try { Retry(() => Directory.Move(staging, dir)); }
catch
{
if (hadOld && !Directory.Exists(dir)) { try { Directory.Move(previous, dir); } catch { } }
throw;
}
}
private static void Retry(Action a)
{
for (int i = 0; ; i++)
{
try { a(); return; }
catch (IOException) when (i < 9) { Thread.Sleep(500); }
catch (UnauthorizedAccessException) when (i < 9) { Thread.Sleep(500); }
}
}
}

View file

@ -25,8 +25,12 @@ namespace RynthCore.App.Avalonia;
/// touches a running bot: the new version loads the next time AC starts, or on RL if the player
/// chooses — the updater never reloads anything. The core (engine, Loader, launcher) updates by
/// running the release's installer, and only while no RynthCore client is running.
///
/// RynthNav's data (navmesh tiles, portals.tsv, locations.json) is an optional signed archive in
/// the same manifest ("navdata"), installed only for players who have RynthNav in their plugin
/// list, and only when its id (a hash of the tile set) changes. See RynthUpdater.NavData.cs.
/// </summary>
internal sealed class RynthUpdater
internal sealed partial class RynthUpdater
{
public const string DefaultFeedUrl = "https://aelrynth.com/downloads/rynth/update.json";
@ -34,21 +38,60 @@ internal sealed class RynthUpdater
private const long MaxPluginBytes = 64L << 20;
private const long MaxInstallerBytes = 256L << 20;
public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256);
/// <summary>
/// One plugin in the feed. <paramref name="Description"/> is the optional one-line "description"
/// (written since 2026.10.5); older feeds have none and the launcher's own table fills in
/// (<see cref="DescribePlugin"/>). Launchers before it ignore the field.
/// </summary>
public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256, string Description = "");
public sealed record InstallerEntry(int Release, string Version, string Url, long Size, string Sha256);
public sealed record Manifest(int Release, string Version, DateTime PublishedUtc, string Notes,
InstallerEntry Core, IReadOnlyList<PluginEntry> Plugins);
InstallerEntry Core, IReadOnlyList<PluginEntry> Plugins, NavDataEntry? NavData = null)
{
/// <summary>
/// The release's changes, one line each: the optional "changes" array (written since 2026.10.5;
/// signed with the rest). Empty for older feeds, which only have <see cref="Notes"/>.
/// </summary>
public IReadOnlyList<string> Changes { get; init; } = Array.Empty<string>();
}
/// <summary>One installed copy of a plugin the feed knows.</summary>
public sealed record PluginStatus(PluginEntry Entry, string Path, PluginState State);
public enum PluginState { UpToDate, NeedsUpdate, LocalBuild }
/// <summary>A plugin split out of one the player has, to be installed beside it (see <see cref="Companions"/>).</summary>
public sealed record CompanionInstall(PluginEntry Entry, string Path, string Reason);
public sealed record CheckResult(Manifest Manifest, int InstalledCoreRelease, IReadOnlyList<PluginStatus> Plugins)
{
public bool CoreUpdateAvailable => Manifest.Core.Release > InstalledCoreRelease;
public IEnumerable<PluginStatus> PluginsToUpdate => Plugins.Where(p => p.State == PluginState.NeedsUpdate);
/// <summary>New plugins that came out of an installed one; installed with the plugin updates.</summary>
public IReadOnlyList<CompanionInstall> Companions { get; init; } = Array.Empty<CompanionInstall>();
/// <summary>Feed plugins not in the plugin list, for the player to install or not (see <see cref="GetAvailable"/>).</summary>
public IReadOnlyList<AvailablePlugin> Available { get; init; } = Array.Empty<AvailablePlugin>();
/// <summary>Available plugins this launcher sees in the feed for the first time: said once in the activity log.</summary>
public IReadOnlyList<AvailablePlugin> NewlyAnnounced { get; init; } = Array.Empty<AvailablePlugin>();
/// <summary>RynthNav's tiles: null when the feed has none or RynthNav isn't in the plugin list.</summary>
public NavDataStatus? NavData { get; init; }
public bool NavDataUpdateAvailable => NavData is { State: NavDataState.NeedsUpdate };
}
/// <summary>
/// Features that moved out of a plugin into their own. When the player has the parent and not the
/// child, the child is installed in a sibling folder and registered, once: a player who removes it
/// afterwards keeps it removed.
///
/// Only for a split, where the player's scripts stop working without the child. A plugin that is
/// simply new (RynthOracle, RynthInventory: 2026.10.4.3 auto-installed them this way) is offered
/// instead, under Available plugins with a "New" badge (<see cref="RecentlyAdded"/>); players who
/// already got them keep them.
/// </summary>
private static readonly (string ParentFile, string ChildName, string Reason)[] Companions =
{
("RynthCore.Plugin.RynthAi.dll", "RynthLua", "Lua scripting, which moved out of RynthAi"),
};
private static readonly HttpClient Http = CreateHttp();
private readonly string _feedUrl;
@ -124,7 +167,71 @@ internal sealed class RynthUpdater
statuses.Add(new PluginStatus(entry, path, state));
}
return new CheckResult(manifest, InstalledCoreRelease, statuses);
List<CompanionInstall> companions = FindCompanions(manifest, pluginPaths);
HashSet<string> fresh = RecordSeenPlugins(manifest); // before GetAvailable: it reads the New badges
List<AvailablePlugin> available = GetAvailable(manifest, pluginPaths, companions);
return new CheckResult(manifest, InstalledCoreRelease, statuses)
{
Companions = companions,
NavData = CheckNavData(manifest, pluginPaths),
Available = available,
NewlyAnnounced = available.Where(a => fresh.Contains(a.Entry.Name)).ToList(),
};
}
private List<CompanionInstall> FindCompanions(Manifest manifest, IEnumerable<string> pluginPaths)
{
var result = new List<CompanionInstall>();
List<string> paths = pluginPaths.ToList();
HashSet<string> offered = ReadOfferedCompanions();
foreach (var (parentFile, childName, reason) in Companions)
{
if (offered.Contains(childName)) continue;
string? parent = paths.FirstOrDefault(p =>
string.Equals(Path.GetFileName(p), parentFile, StringComparison.OrdinalIgnoreCase) && File.Exists(p));
PluginEntry? child = manifest.Plugins.FirstOrDefault(e => string.Equals(e.Name, childName, StringComparison.OrdinalIgnoreCase));
if (parent == null || child == null) continue;
if (paths.Any(p => string.Equals(Path.GetFileName(p), child.File, StringComparison.OrdinalIgnoreCase)))
{
MarkCompanionOffered(childName); // already there: nothing to do, ever
continue;
}
// C:\Games\RynthSuite\RynthAi\x.dll -> C:\Games\RynthSuite\RynthLua\<file>
string? suiteDir = Path.GetDirectoryName(Path.GetDirectoryName(parent));
if (string.IsNullOrEmpty(suiteDir)) continue;
result.Add(new CompanionInstall(child, Path.Combine(suiteDir, childName, child.File), reason));
}
return result;
}
/// <summary>
/// Installs <see cref="CheckResult.Companions"/> (verified like every plugin; an existing file at the
/// target is kept) and returns their paths for the caller to register in the plugin list.
/// </summary>
public async Task<List<CompanionInstall>> InstallCompanionsAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
var done = new List<CompanionInstall>();
foreach (CompanionInstall c in check.Companions)
{
if (!File.Exists(c.Path))
{
Directory.CreateDirectory(Path.GetDirectoryName(c.Path)!);
string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll");
try
{
await DownloadVerifiedAsync(c.Entry.Url, c.Entry.Size, c.Entry.Sha256, MaxPluginBytes, temp, ct, c.Entry.Name, progress);
File.SetLastWriteTimeUtc(temp, check.Manifest.PublishedUtc);
File.Move(temp, c.Path, overwrite: false);
}
finally
{
try { File.Delete(temp); } catch { }
}
}
MarkCompanionOffered(c.Entry.Name);
done.Add(c);
}
return done;
}
// ── Plugins ───────────────────────────────────────────────────────────────
@ -133,7 +240,7 @@ internal sealed class RynthUpdater
/// Swaps each outdated plugin DLL for the verified release build. The previous file is kept
/// beside it as .previous. Running clients keep the version they started with.
/// </summary>
public async Task<List<string>> UpdatePluginsAsync(CheckResult check, CancellationToken ct = default)
public async Task<List<string>> UpdatePluginsAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
var done = new List<string>();
foreach (var group in check.PluginsToUpdate.GroupBy(p => p.Entry))
@ -142,7 +249,7 @@ internal sealed class RynthUpdater
string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll");
try
{
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct);
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct, e.Name, progress);
foreach (PluginStatus p in group)
{
string staged = p.Path + ".new";
@ -165,7 +272,7 @@ internal sealed class RynthUpdater
// ── Core ──────────────────────────────────────────────────────────────────
/// <summary>Downloads (or reuses) the release installer, verified, and returns its path.</summary>
public async Task<string> DownloadInstallerAsync(CheckResult check, CancellationToken ct = default)
public async Task<string> DownloadInstallerAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
InstallerEntry core = check.Manifest.Core;
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
@ -177,7 +284,7 @@ internal sealed class RynthUpdater
return path;
string temp = path + ".part";
await DownloadVerifiedAsync(core.Url, core.Size, core.Sha256, MaxInstallerBytes, temp, ct);
await DownloadVerifiedAsync(core.Url, core.Size, core.Sha256, MaxInstallerBytes, temp, ct, $"RynthCore {core.Version}", progress);
File.Move(temp, path, overwrite: true);
return path;
}
@ -238,12 +345,17 @@ internal sealed class RynthUpdater
if (file.Length == 0 || file != Path.GetFileName(file) || !file.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException($"bad plugin file name '{file}'");
plugins.Add(new PluginEntry(p.GetProperty("name").GetString() ?? file, file,
CheckUrl(p.GetProperty("url").GetString()), p.GetProperty("size").GetInt64(), p.GetProperty("sha256").GetString() ?? ""));
CheckUrl(p.GetProperty("url").GetString()), p.GetProperty("size").GetInt64(), p.GetProperty("sha256").GetString() ?? "",
ReadDescription(p)));
}
return new Manifest(r.GetProperty("release").GetInt32(), r.GetProperty("version").GetString() ?? "",
r.GetProperty("published").GetDateTime().ToUniversalTime(),
r.TryGetProperty("notes", out JsonElement n) ? n.GetString() ?? "" : "", core, plugins);
r.TryGetProperty("notes", out JsonElement n) ? n.GetString() ?? "" : "", core, plugins,
r.TryGetProperty("navdata", out JsonElement nd) && nd.ValueKind == JsonValueKind.Object ? TryParseNavData(nd) : null)
{
Changes = ReadChanges(r),
};
}
private string CheckUrl(string? url)
@ -271,31 +383,49 @@ internal sealed class RynthUpdater
return ms.ToArray();
}
private static async Task DownloadVerifiedAsync(string url, long size, string sha256, long max, string dest, CancellationToken ct)
/// <summary>
/// Downloads to <paramref name="dest"/> and checks it against the signed size and SHA-256. On any
/// failure (a wrong hash, a lost connection, Cancel) the partial file is deleted. Progress, when
/// asked for, goes to <paramref name="progress"/> a few times a second (<see cref="DownloadMeter"/>),
/// then one <see cref="DownloadStage.Verified"/> report once the hash matched.
/// </summary>
private static async Task DownloadVerifiedAsync(string url, long size, string sha256, long max, string dest, CancellationToken ct,
string? what = null, IProgress<DownloadProgress>? progress = null)
{
if (size <= 0 || size > max) throw new InvalidDataException($"{url}: size {size} out of range");
using var resp = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
resp.EnsureSuccessStatusCode();
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
long total = 0;
await using (var s = await resp.Content.ReadAsStreamAsync(ct))
await using (var f = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None))
var meter = new DownloadMeter(what ?? Path.GetFileName(url), size, progress);
try
{
byte[] buf = new byte[81920];
int n;
while ((n = await s.ReadAsync(buf, ct)) > 0)
using var resp = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
resp.EnsureSuccessStatusCode();
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
long total = 0;
meter.Report(0);
await using (var s = await resp.Content.ReadAsStreamAsync(ct))
await using (var f = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None))
{
total += n;
if (total > size) throw new InvalidDataException($"{url} is larger than the signed size");
hash.AppendData(buf, 0, n);
await f.WriteAsync(buf.AsMemory(0, n), ct);
byte[] buf = new byte[81920];
int n;
while ((n = await s.ReadAsync(buf, ct)) > 0)
{
ct.ThrowIfCancellationRequested();
total += n;
if (total > size) throw new InvalidDataException($"{url} is larger than the signed size");
hash.AppendData(buf, 0, n);
await f.WriteAsync(buf.AsMemory(0, n), ct);
meter.Report(total);
}
}
string got = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
if (total != size || !string.Equals(got, sha256, StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException($"{Path.GetFileName(url)} does not match the signed hash — not installed");
meter.Verified();
}
string got = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
if (total != size || !string.Equals(got, sha256, StringComparison.OrdinalIgnoreCase))
catch
{
// The file stream is closed by now (its using block ended), so the delete can't be refused by it.
try { File.Delete(dest); } catch { }
throw new InvalidDataException($"{Path.GetFileName(url)} does not match the signed hash — not installed");
throw;
}
}
@ -315,6 +445,35 @@ internal sealed class RynthUpdater
// ── State ─────────────────────────────────────────────────────────────────
private string StatePath => Path.Combine(_stateDir, "update-state.json");
private string CompanionsPath => Path.Combine(_stateDir, "update-companions.json");
private HashSet<string> ReadOfferedCompanions()
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
try
{
if (!File.Exists(CompanionsPath)) return set;
using var doc = JsonDocument.Parse(File.ReadAllText(CompanionsPath));
foreach (JsonElement e in doc.RootElement.EnumerateArray())
if (e.GetString() is { Length: > 0 } s) set.Add(s);
}
catch { }
return set;
}
private void MarkCompanionOffered(string name)
{
try
{
HashSet<string> set = ReadOfferedCompanions();
if (!set.Add(name)) return;
Directory.CreateDirectory(_stateDir);
string tmp = CompanionsPath + ".tmp";
File.WriteAllText(tmp, "[" + string.Join(", ", set.OrderBy(s => s).Select(s => JsonSerializer.Serialize(s))) + "]", Encoding.UTF8);
File.Move(tmp, CompanionsPath, overwrite: true);
}
catch { }
}
private int ReadHighestRelease()
{

View file

@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace RynthCore.App.Avalonia;
/// <summary>What the update card on the launcher's front page is showing.</summary>
public enum UpdateCardKind { NotConfigured, NotChecked, Checking, Error, UpToDate, CoreUpdate, PluginUpdates, Downloading }
/// <summary>Everything the card needs to know, gathered by the window (no UI types, so tests can build it).</summary>
public sealed record UpdateCardInput
{
public bool Configured { get; init; } = true;
public bool Checking { get; init; }
/// <summary>The last check's error; null when it worked.</summary>
public string? Error { get; init; }
/// <summary>When the last check succeeded (local time); null before the first.</summary>
public DateTime? LastChecked { get; init; }
/// <summary>True once a check has succeeded this session.</summary>
public bool HasCheck { get; init; }
public string InstalledVersion { get; init; } = "";
public bool CoreUpdateAvailable { get; init; }
public string AvailableVersion { get; init; } = "";
public string Notes { get; init; } = "";
public IReadOnlyList<string> Changes { get; init; } = Array.Empty<string>();
/// <summary>Plugin updates (and new companions, the RynthNav map) waiting to be installed.</summary>
public IReadOnlyList<string> PendingPluginUpdates { get; init; } = Array.Empty<string>();
/// <summary>Available plugins with the New badge.</summary>
public IReadOnlyList<string> NewPlugins { get; init; } = Array.Empty<string>();
/// <summary>Game clients running RynthCore (a RynthCore update waits for them to close).</summary>
public int ClientsRunning { get; init; }
/// <summary>The download in progress, if any.</summary>
public DownloadProgress? Download { get; init; }
public bool CanCancel { get; init; }
}
/// <summary>The card's text and which buttons show.</summary>
public sealed record UpdateCard(
UpdateCardKind Kind,
string Title,
string Detail,
IReadOnlyList<string> WhatsNew,
bool ShowCheckButton,
string? ActionButton,
bool ShowProgress,
double? ProgressPercent,
bool ShowCancel,
string? NewPluginsLine,
/// <summary>One line for the Plugins tab and the header.</summary>
string Compact);
/// <summary>
/// The front page's update card as a pure function of <see cref="UpdateCardInput"/>: up to date,
/// RynthCore update (installs once every game client is closed), plugin updates, downloading
/// (bar, MB, speed, time left, step), errors, and a line about new plugins.
/// </summary>
public static class UpdateCardModel
{
public const int MaxWhatsNew = 4;
public const string UpdateCoreButton = "Update RynthCore";
public const string UpdatePluginsButton = "Update plugins";
public static UpdateCard Build(UpdateCardInput i)
{
string? newLine = i.NewPlugins.Count > 0
? $"New plugins available: {string.Join(", ", i.NewPlugins)}. See Available plugins on the Plugins tab."
: null;
string installed = i.InstalledVersion.Length > 0 ? i.InstalledVersion : "unknown";
if (!i.Configured)
return new UpdateCard(UpdateCardKind.NotConfigured, "Updates", "Updates aren't set up in this build.",
Array.Empty<string>(), false, null, false, null, false, null, "Updates aren't set up in this build.");
if (i.Download is { } d)
{
string title = d.Stage switch
{
DownloadStage.Downloading => $"Downloading {d.What}",
DownloadStage.Verified => $"{d.What}: verified",
DownloadStage.Unpacking => $"Unpacking {d.What}",
_ => $"Installing {d.What}",
};
// Installing is the last step (files moving into place): it always runs to the end.
bool cancel = i.CanCancel && d.Stage != DownloadStage.Installing;
return new UpdateCard(UpdateCardKind.Downloading, title, d.Detail, Array.Empty<string>(), false, null,
true, d.Percent, cancel, newLine, $"{title}: {d.Detail}");
}
if (i.Checking)
return new UpdateCard(UpdateCardKind.Checking, "Checking for updates…", $"RynthCore {installed}",
Array.Empty<string>(), false, null, false, null, false, newLine, "Checking for updates…");
if (i.Error != null)
{
string when = i.LastChecked is { } t ? $" Last good check: {FormatWhen(t)}." : "";
return new UpdateCard(UpdateCardKind.Error, "Couldn't check for updates", i.Error.TrimEnd('.', ' ') + "." + when,
Array.Empty<string>(), true, null, false, null, false, newLine, $"Update check failed: {i.Error}");
}
if (!i.HasCheck)
return new UpdateCard(UpdateCardKind.NotChecked, $"RynthCore {installed}", "Not checked for updates yet.",
Array.Empty<string>(), true, null, false, null, false, newLine, "Not checked yet.");
string checkedLine = i.LastChecked is { } lc ? $"Last checked {FormatWhen(lc)}." : "";
IReadOnlyList<string> whatsNew = WhatsNew(i.Changes, i.Notes);
if (i.CoreUpdateAvailable)
{
var detail = new List<string> { $"You have {installed}. The update installs once every game client is closed." };
if (i.ClientsRunning > 0)
detail.Add($"Close your {i.ClientsRunning} game client{(i.ClientsRunning == 1 ? "" : "s")} running RynthCore first.");
if (i.PendingPluginUpdates.Count > 0)
detail.Add($"Plugin updates ready too: {string.Join(", ", i.PendingPluginUpdates)}.");
if (checkedLine.Length > 0) detail.Add(checkedLine);
return new UpdateCard(UpdateCardKind.CoreUpdate, $"RynthCore {i.AvailableVersion} is available", string.Join(" ", detail),
whatsNew, true, UpdateCoreButton, false, null, false, newLine, $"Update available: RynthCore {i.AvailableVersion}");
}
if (i.PendingPluginUpdates.Count > 0)
{
string detail = $"{string.Join(", ", i.PendingPluginUpdates)}. Running bots keep their version until AC restarts.";
if (checkedLine.Length > 0) detail += " " + checkedLine;
return new UpdateCard(UpdateCardKind.PluginUpdates, "Plugin updates ready", detail,
whatsNew, true, UpdatePluginsButton, false, null, false, newLine, $"Plugin updates ready: {string.Join(", ", i.PendingPluginUpdates)}");
}
return new UpdateCard(UpdateCardKind.UpToDate, $"RynthCore {installed} - up to date", checkedLine,
Array.Empty<string>(), true, null, false, null, false, newLine, $"RynthCore {installed} - up to date.");
}
/// <summary>A few of the release's changes; the notes when the feed has no list (feeds before 2026.10.5).</summary>
public static IReadOnlyList<string> WhatsNew(IReadOnlyList<string> changes, string notes)
{
if (changes.Count > 0)
{
var list = changes.Take(MaxWhatsNew).ToList();
if (changes.Count > MaxWhatsNew) list.Add($"…and {changes.Count - MaxWhatsNew} more.");
return list;
}
if (string.IsNullOrWhiteSpace(notes)) return Array.Empty<string>();
string n = notes.Trim();
return new[] { n.Length > 300 ? n[..299].TrimEnd() + "…" : n };
}
/// <summary>"at 14:05" today, else "Oct 3 at 14:05".</summary>
public static string FormatWhen(DateTime local, DateTime? now = null)
{
DateTime today = (now ?? DateTime.Now).Date;
string time = local.ToString("HH:mm", CultureInfo.InvariantCulture);
return local.Date == today ? $"at {time}" : $"{local.ToString("MMM d", CultureInfo.InvariantCulture)} at {time}";
}
}

View file

@ -0,0 +1,292 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Opt-in, anonymous usage statistics ("Help improve RynthCore"). OFF unless the player turns it on.
///
/// When on, at most one small report a day goes to aelrynth.com (never to a game server), sent
/// after a successful update check. The report holds exactly:
/// - a random install ID (a GUID made when the player opts in, stored only in usage-stats.json,
/// tied to nothing else);
/// - the RynthCore version;
/// - the enabled plugins the update feed ships (RynthSuite), with their versions; other plugins
/// only as a count, never by name (a private plugin's name could identify its author);
/// - how many crash_*.dmp files the engine wrote since the last report (a count only);
/// - the Windows major version ("10" or "11").
/// Never: character, account or server names, file paths, or anything else identifying.
///
/// Turning it off deletes usage-stats.json (and with it the install ID) and cancels a report in
/// flight. Every failure is silent, and nothing here ever delays or fails the update check.
/// </summary>
internal sealed class UsageStats
{
public const string DefaultEndpoint = "https://aelrynth.com/rynth/ping";
/// <summary>Where the engine writes crash/hang minidumps (RynthCore.Engine CrashDump / LogPaths).</summary>
public const string DefaultDumpDirectory = @"C:\Games\RynthCore\Logs\dumps";
public const int Schema = 1;
private const int MaxCrashes = 1000;
private const int MaxPlugins = 32;
public sealed record PluginInfo(string Name, string Version);
private static readonly HttpClient Http = CreateHttp();
private static readonly Regex ReleaseVersion = new(@"^\d{4}\.\d{1,2}\.\d{1,2}(\.\d{1,4})?$", RegexOptions.CultureInvariant);
private static readonly Regex SafeName = new(@"^[A-Za-z0-9 ._-]{1,40}$", RegexOptions.CultureInvariant);
private readonly string _endpoint;
private readonly string _stateDir;
private readonly string _dumpDir;
private CancellationTokenSource _cts = new();
private int _sending;
public UsageStats(string endpoint = DefaultEndpoint, string? stateDir = null, string dumpDir = DefaultDumpDirectory)
{
_endpoint = endpoint;
_stateDir = stateDir ?? Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
_dumpDir = dumpDir;
}
public string StatePath => Path.Combine(_stateDir, "usage-stats.json");
// ── Opt in / out ──────────────────────────────────────────────────────────
/// <summary>Called when the player turns statistics on: makes the install ID if there is none.</summary>
public void OptIn(DateTime utcNow)
{
if (ReadState() != null) return;
// Crashes count from the moment of opting in, never from before.
WriteState(new State(Guid.NewGuid().ToString("D"), "", utcNow));
}
/// <summary>Called when the player turns statistics off: cancels a report in flight and deletes the ID.</summary>
public void OptOut()
{
try { _cts.Cancel(); } catch { }
_cts = new CancellationTokenSource();
try { File.Delete(StatePath); } catch { }
try { File.Delete(StatePath + ".tmp"); } catch { }
}
/// <summary>The install ID, or null when the player hasn't opted in (or it was deleted).</summary>
public string? InstallId => ReadState()?.InstallId;
// ── Report ────────────────────────────────────────────────────────────────
/// <summary>
/// Sends today's report if one hasn't gone out yet (UTC day). <paramref name="stillEnabled"/> is
/// asked again right before sending, so turning it off mid-way stops it. Returns true only
/// when a report was accepted. Never throws.
/// </summary>
public async Task<bool> MaybeSendAsync(Func<bool> stillEnabled, string coreVersion,
IReadOnlyList<PluginInfo> plugins, int otherPlugins, DateTime utcNow)
{
if (Interlocked.Exchange(ref _sending, 1) == 1) return false;
try
{
if (!stillEnabled()) return false;
State? state = ReadState();
if (state == null)
{
OptIn(utcNow); // enabled but the file is gone (deleted by hand): start a new ID
state = ReadState();
if (state == null) return false;
}
string today = utcNow.ToString("yyyy-MM-dd");
if (state.LastPingDay == today) return false;
int crashes = CountCrashDumps(_dumpDir, state.CrashesSinceUtc, utcNow);
string json = BuildPayload(state.InstallId, coreVersion, plugins, otherPlugins, crashes, WindowsMajor());
CancellationToken ct = _cts.Token;
if (!stillEnabled() || ct.IsCancellationRequested) return false;
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var resp = await Http.PostAsync(_endpoint, content, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode) return false;
// Opted out while the request was out: the file is gone, keep it gone.
if (!stillEnabled() || ct.IsCancellationRequested || ReadState()?.InstallId != state.InstallId) return true;
WriteState(state with { LastPingDay = today, CrashesSinceUtc = utcNow });
return true;
}
catch
{
return false;
}
finally
{
Interlocked.Exchange(ref _sending, 0);
}
}
/// <summary>The report that would go out now (for "Show what is sent"); nothing is sent or saved.</summary>
public string Preview(string coreVersion, IReadOnlyList<PluginInfo> plugins, int otherPlugins, DateTime utcNow)
{
State? state = ReadState();
string id = state?.InstallId ?? "(a random ID, made when you turn this on)";
int crashes = state == null ? 0 : CountCrashDumps(_dumpDir, state.CrashesSinceUtc, utcNow);
return BuildPayload(id, coreVersion, plugins, otherPlugins, crashes, WindowsMajor());
}
/// <summary>The report body, exactly as sent. Public for the launcher's "Show what is sent" and the tests.</summary>
public static string BuildPayload(string installId, string coreVersion, IReadOnlyList<PluginInfo> plugins,
int otherPlugins, int crashes, string windows)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("schema", Schema);
w.WriteString("install", installId);
w.WriteString("version", ShortVersion(coreVersion));
w.WriteString("windows", windows);
w.WriteNumber("crashes", Math.Clamp(crashes, 0, MaxCrashes));
w.WriteStartArray("plugins");
foreach (PluginInfo p in plugins
.Where(p => SafeName.IsMatch(p.Name))
.GroupBy(p => p.Name, StringComparer.OrdinalIgnoreCase).Select(g => g.First())
.OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
.Take(MaxPlugins))
{
w.WriteStartObject();
w.WriteString("name", p.Name);
w.WriteString("version", ShortVersion(p.Version));
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteNumber("otherPlugins", Math.Clamp(otherPlugins, 0, 100));
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
/// <summary>
/// The enabled plugins to report: those whose file name the update feed ships (by the feed's name
/// for them, with the DLL's own version), and a count of every other enabled plugin.
/// </summary>
public static (List<PluginInfo> Known, int Other) DescribePlugins(IEnumerable<string> enabledPaths,
IReadOnlyDictionary<string, string> feedNameByFile)
{
var known = new List<PluginInfo>();
int other = 0;
foreach (string path in enabledPaths.Distinct(StringComparer.OrdinalIgnoreCase))
{
string file = Path.GetFileName(path);
if (feedNameByFile.TryGetValue(file, out string? name) && File.Exists(path))
{
string version;
try { version = FileVersionInfo.GetVersionInfo(path).ProductVersion ?? ""; }
catch { version = ""; }
known.Add(new PluginInfo(name, version));
}
else
{
other++;
}
}
return (known, other);
}
/// <summary>"2026.10.2.1" for a release build, "dev" for an unversioned build, else "unknown". Drops the commit.</summary>
public static string ShortVersion(string? productVersion)
{
string v = (productVersion ?? "").Trim();
int plus = v.IndexOf('+');
if (plus >= 0) v = v[..plus];
int space = v.IndexOf(' ');
if (space >= 0) v = v[..space];
if (v is "1.0.0" or "1.0.0.0" or "dev") return "dev";
return ReleaseVersion.IsMatch(v) ? v : "unknown";
}
/// <summary>"11" (build 22000 and up), "10", or "other".</summary>
public static string WindowsMajor()
{
Version os = Environment.OSVersion.Version;
if (!OperatingSystem.IsWindows()) return "other";
if (os.Major == 10) return os.Build >= 22000 ? "11" : "10";
return "other";
}
/// <summary>crash_*.dmp files written after <paramref name="sinceUtc"/> (hang dumps are not crashes).</summary>
public static int CountCrashDumps(string dir, DateTime sinceUtc, DateTime utcNow)
{
try
{
if (!Directory.Exists(dir)) return 0;
int n = 0;
foreach (string f in Directory.EnumerateFiles(dir, "crash_*.dmp"))
{
DateTime t = File.GetLastWriteTimeUtc(f);
if (t > sinceUtc && t <= utcNow.AddMinutes(5)) n++;
if (n >= MaxCrashes) break;
}
return n;
}
catch { return 0; }
}
// ── State file ────────────────────────────────────────────────────────────
private sealed record State(string InstallId, string LastPingDay, DateTime CrashesSinceUtc);
private State? ReadState()
{
try
{
if (!File.Exists(StatePath)) return null;
using var doc = JsonDocument.Parse(File.ReadAllText(StatePath));
JsonElement r = doc.RootElement;
string id = r.GetProperty("installId").GetString() ?? "";
if (!Guid.TryParseExact(id, "D", out _)) return null;
string last = r.TryGetProperty("lastPingDay", out JsonElement l) ? l.GetString() ?? "" : "";
DateTime since = r.TryGetProperty("crashesSinceUtc", out JsonElement s) && s.TryGetDateTime(out DateTime d)
? d.ToUniversalTime() : DateTime.UtcNow;
return new State(id, last, since);
}
catch { return null; }
}
private void WriteState(State s)
{
try
{
Directory.CreateDirectory(_stateDir);
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteString("about", "RynthCore usage statistics (opt-in). Deleted when you turn them off.");
w.WriteString("installId", s.InstallId);
w.WriteString("lastPingDay", s.LastPingDay);
w.WriteString("crashesSinceUtc", DateTime.SpecifyKind(s.CrashesSinceUtc, DateTimeKind.Utc));
w.WriteEndObject();
}
string tmp = StatePath + ".tmp";
File.WriteAllBytes(tmp, ms.ToArray());
File.Move(tmp, StatePath, overwrite: true);
}
catch { }
}
private static HttpClient CreateHttp()
{
// Short: a slow stats server must never hold anything up (and nothing awaits this anyway).
var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
http.DefaultRequestHeaders.UserAgent.ParseAdd("RynthCore-Launcher");
return http;
}
}

View file

@ -0,0 +1,121 @@
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace RynthCore.App.Avalonia;
/// <summary>
/// The one-time "Help improve RynthCore?" question and the "Show what is sent" window.
/// Plain words; "No thanks" is the safe answer (Escape and closing the window both mean no).
/// </summary>
internal static class UsageStatsDialog
{
private static readonly IBrush Back = new SolidColorBrush(Color.Parse("#132028"));
private static readonly IBrush Text = new SolidColorBrush(Color.Parse("#EAF0F4"));
private static readonly IBrush Muted = new SolidColorBrush(Color.Parse("#9AA8B3"));
private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#26C1A6"));
public const string WhatIsSent =
"Sent once a day, only if you turn it on: a random ID made just for this, the RynthCore version, " +
"which RynthSuite plugins you have enabled and their versions (other plugins only as a number), " +
"how many times RynthCore crashed since the last report (a number), and whether you run Windows 10 or 11.";
public const string NeverSent =
"Never sent: character, account or server names, file paths, or anything else about you or your game. " +
"It goes to aelrynth.com only, never to a game server.";
public const string HowToStop =
"Turning it off stops the reports at once and deletes the random ID from this PC.";
/// <summary>True when the player chose to turn statistics on.</summary>
public static async Task<bool> AskAsync(Window owner)
{
var dialog = NewWindow("Help improve RynthCore?", 560);
var on = new Button { Content = "Turn it on" };
var off = new Button { Content = "No thanks", IsCancel = true };
on.Click += (_, _) => dialog.Close(true);
off.Click += (_, _) => dialog.Close(false);
dialog.Content = Layout("Help improve RynthCore?",
new StackPanel
{
Spacing = 10,
Children =
{
Para("RynthCore can send a small anonymous report once a day, so we can see how many people use it, " +
"which versions and plugins are in use, and whether a new release crashes more than the last one.", Text),
Para(WhatIsSent, Muted),
Para(NeverSent, Muted),
Para("It stays off unless you turn it on. You can change your mind any time on the Plugins tab, " +
"under Usage statistics. " + HowToStop, Muted),
},
},
on, off);
bool? result = await dialog.ShowDialog<bool?>(owner);
return result == true;
}
/// <summary>Shows the report exactly as it would be sent now.</summary>
public static async Task ShowPayloadAsync(Window owner, string json, bool enabled)
{
var dialog = NewWindow("Usage statistics: what is sent", 620);
var body = new TextBox
{
Text = json,
IsReadOnly = true,
TextWrapping = TextWrapping.Wrap,
FontFamily = new FontFamily("Consolas, Cascadia Mono, monospace"),
FontSize = 12,
MaxHeight = 380,
Foreground = Text,
Background = new SolidColorBrush(Color.Parse("#0F161D")),
};
var close = new Button { Content = "Close", IsCancel = true, IsDefault = true };
close.Click += (_, _) => dialog.Close(null);
dialog.Content = Layout("Usage statistics: what is sent",
new StackPanel
{
Spacing = 8,
Children =
{
Para(enabled
? "This is today's report, exactly as it goes to aelrynth.com (at most once a day)."
: "Statistics are off, so nothing is sent. If you turned them on, this is what would go out.", Muted),
body,
},
},
close);
await dialog.ShowDialog<object?>(owner);
}
private static TextBlock Para(string text, IBrush brush) =>
new() { Text = text, TextWrapping = TextWrapping.Wrap, Foreground = brush };
private static Window NewWindow(string title, double width) => new()
{
Title = title,
Width = width,
SizeToContent = SizeToContent.Height,
CanResize = false,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Background = Back,
};
private static Control Layout(string title, Control body, params Control[] buttons)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right };
foreach (Control b in buttons) row.Children.Add(b);
return new StackPanel
{
Margin = new Thickness(18),
Spacing = 12,
Children =
{
new TextBlock { Text = title, FontSize = 16, FontWeight = FontWeight.SemiBold, Foreground = Accent },
body,
row,
},
};
}
}

View file

@ -27,6 +27,13 @@ internal sealed class AppSettings
/// with; the new one loads on the next AC start. Core updates always ask first.
public bool AutoUpdatePlugins { get; set; } = true;
/// "Help improve RynthCore": one anonymous usage report a day (see the launcher's
/// UsageStats.cs for exactly what is sent). OFF unless the player turns it on.
public bool UsageStatsEnabled { get; set; }
/// True once the launcher has explained usage statistics and asked (shown once).
public bool UsageStatsAsked { get; set; }
/// When true, the launcher kills any RynthCore-mode acclient.exe it
/// launched that hasn't reached IsLoggedIn within
/// <see cref="StuckClientTimeoutSeconds"/>. Catches stuck char-select,

View file

@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
@ -12,15 +14,22 @@ internal static class AppSettingsStore
WriteIndented = true,
Converters =
{
// Before the general enum converter: InjectionMode is written so that every
// launcher can read it ("Decal + RynthCore" lives in decal-accounts.json).
new SharedInjectionModeConverter(),
new JsonStringEnumConverter()
}
};
private static string SettingsDirectory =>
/// <summary>Tests only (tools\LauncherSettingsTests): a folder used instead of %APPDATA%\RynthCore.</summary>
internal static string? DirectoryOverride { get; set; }
private static string SettingsDirectory => DirectoryOverride ??
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
private static string SettingsPath => Path.Combine(SettingsDirectory, "appsettings.json");
private static string BackupPath => SettingsPath + ".bak";
private static string DecalAccountsPath => DecalAccountModes.PathIn(SettingsDirectory);
/// <summary>
/// Set when the last Load() hit a corrupt/unreadable file (quarantined it,
@ -30,10 +39,22 @@ internal static class AppSettingsStore
/// </summary>
public static string? LastLoadDiagnostic { get; private set; }
/// <summary>
/// Set when the last Load() moved "Decal + RynthCore" accounts out of appsettings.json
/// into decal-accounts.json (a file written by a pre-release Decal bridge build), or found
/// decal-accounts.json unreadable. Null otherwise.
/// </summary>
public static string? LastMigrationNote { get; private set; }
public static AppSettings Load()
{
LastLoadDiagnostic = null;
LastMigrationNote = null;
return ApplyDecalAccounts(LoadShared());
}
private static AppSettings LoadShared()
{
if (!File.Exists(SettingsPath))
return new AppSettings();
@ -85,13 +106,56 @@ internal static class AppSettingsStore
}
}
/// <summary>
/// Puts back the "Decal + RynthCore" accounts listed in decal-accounts.json (those that
/// appsettings.json still lists as RynthCore). An appsettings.json that itself says
/// "DecalBridge" (written by a pre-release bridge build) is rewritten at once, .bak
/// included, so no launcher finds that value there again.
/// </summary>
private static AppSettings ApplyDecalAccounts(AppSettings settings)
{
List<LaunchAccountProfile> accounts = settings.AccountProfiles ?? new List<LaunchAccountProfile>();
int legacy = accounts.Count(a => a.InjectionMode == InjectionMode.DecalBridge);
HashSet<string> ids = DecalAccountModes.ReadIds(DecalAccountsPath, out string? error);
if (error != null)
LastMigrationNote = error;
foreach (LaunchAccountProfile account in accounts)
if (DecalAccountModes.IsDecalBridge(ids, account.Id, account.InjectionMode))
account.InjectionMode = InjectionMode.DecalBridge;
if (legacy > 0)
{
try
{
Save(settings);
File.Copy(SettingsPath, BackupPath, overwrite: true);
LastMigrationNote = $"Moved {legacy} \"Decal + RynthCore\" account(s) from appsettings.json to " +
$"{DecalAccountModes.FileName}, so older launchers can still read appsettings.json.";
}
catch (Exception ex)
{
LastMigrationNote = $"Could not move \"Decal + RynthCore\" accounts to {DecalAccountModes.FileName} " +
$"({ex.GetType().Name}: {ex.Message}); the next save retries.";
}
}
return settings;
}
public static void Save(AppSettings settings)
{
// "Decal + RynthCore" accounts go to decal-accounts.json first; appsettings.json
// lists them as RynthCore (SharedInjectionModeConverter).
Directory.CreateDirectory(SettingsDirectory);
DecalAccountModes.WriteIds(DecalAccountsPath,
(settings.AccountProfiles ?? new List<LaunchAccountProfile>())
.Where(a => a.InjectionMode == InjectionMode.DecalBridge)
.Select(a => a.Id));
// Atomic write: serialize to a temp file, then swap it in. A crash or
// power cut mid-write can no longer truncate the live file (which holds
// every server/account profile and is rewritten constantly); the swap
// also maintains a .bak Load() can recover from.
Directory.CreateDirectory(SettingsDirectory);
string tmp = SettingsPath + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(settings, JsonOptions));
if (File.Exists(SettingsPath))
@ -99,4 +163,32 @@ internal static class AppSettingsStore
else
File.Move(tmp, SettingsPath);
}
/// <summary>
/// InjectionMode in appsettings.json. Writes only names every launcher knows: DecalBridge is
/// written as <see cref="DecalAccountModes.SharedMode"/> (decal-accounts.json holds the real
/// choice). Reads names and numbers; a name or number this build doesn't know reads as RynthCore
/// instead of making the whole file unreadable.
/// </summary>
private sealed class SharedInjectionModeConverter : JsonConverter<InjectionMode>
{
public override InjectionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt32(out int number))
return Enum.IsDefined((InjectionMode)number) ? (InjectionMode)number : InjectionMode.RynthCore;
if (reader.TokenType == JsonTokenType.String)
{
return Enum.TryParse(reader.GetString(), ignoreCase: true, out InjectionMode mode) && Enum.IsDefined(mode)
? mode
: InjectionMode.RynthCore;
}
throw new JsonException($"InjectionMode: unexpected {reader.TokenType}.");
}
public override void Write(Utf8JsonWriter writer, InjectionMode value, JsonSerializerOptions options)
{
InjectionMode shared = value == InjectionMode.DecalBridge ? DecalAccountModes.SharedMode : value;
writer.WriteStringValue(shared.ToString());
}
}
}

View file

@ -46,6 +46,13 @@ internal static class CharacterCacheStore
List<string> serverCharacters = ReadCharacterFile(GetServerScopedPath(safeServer, safeAccount));
if (serverCharacters.Count > 0)
return serverCharacters;
// The same account name can exist on several servers. The legacy
// account-only file predates server scoping, so it is only trusted
// while no server-scoped file exists for this account at all;
// otherwise it would hand one server's characters to another.
if (HasAnyServerScopedFile(safeAccount))
return [];
}
return ReadCharacterFile(GetAccountScopedPath(safeAccount));
@ -84,7 +91,11 @@ internal static class CharacterCacheStore
if (string.IsNullOrWhiteSpace(accountName) || string.IsNullOrWhiteSpace(characterName))
return;
List<string> characters = Read(accountName, serverName);
// With a server, seed only from that server's own file so a legacy
// account-only list cannot be merged into the wrong server.
List<string> characters = string.IsNullOrWhiteSpace(serverName)
? Read(accountName, serverName)
: ReadStrict(accountName, serverName);
if (!characters.Any(existing => IsSameCharacter(existing, characterName)))
characters.Add(characterName);
@ -96,27 +107,34 @@ internal static class CharacterCacheStore
private static bool IsSameCharacter(string a, string b) =>
string.Equals(a.Trim().TrimStart('+'), b.Trim().TrimStart('+'), StringComparison.OrdinalIgnoreCase);
public static void DeleteForAccount(string accountName)
/// Deletes the character cache for one (account, server) pair. Other servers'
/// files for the same account name are left alone. The legacy account-only
/// file is removed only when <paramref name="includeLegacy"/> is set (the
/// caller knows whether another profile still uses this account name).
public static void DeleteForAccount(string accountName, string serverName, bool includeLegacy)
{
if (string.IsNullOrWhiteSpace(accountName))
return;
try
{
string rootDirectory = GetRootDirectory();
if (!Directory.Exists(rootDirectory))
return;
string safeAccount = SanitizeFileName(accountName);
foreach (string file in Directory.GetFiles(rootDirectory, $"characters_*_{safeAccount}.json"))
if (!string.IsNullOrWhiteSpace(serverName))
{
try { File.Delete(file); } catch { }
string serverScopedPath = GetServerScopedPath(SanitizeFileName(serverName), safeAccount);
if (File.Exists(serverScopedPath))
{
try { File.Delete(serverScopedPath); } catch { }
}
}
string accountScopedPath = GetAccountScopedPath(safeAccount);
if (File.Exists(accountScopedPath))
if (includeLegacy)
{
try { File.Delete(accountScopedPath); } catch { }
string accountScopedPath = GetAccountScopedPath(safeAccount);
if (File.Exists(accountScopedPath))
{
try { File.Delete(accountScopedPath); } catch { }
}
}
}
catch
@ -124,6 +142,20 @@ internal static class CharacterCacheStore
}
}
private static bool HasAnyServerScopedFile(string safeAccountName)
{
try
{
string rootDirectory = GetRootDirectory();
return Directory.Exists(rootDirectory) &&
Directory.EnumerateFiles(rootDirectory, $"characters_*_{safeAccountName}.json").Any();
}
catch
{
return false;
}
}
private static string GetRootDirectory() =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");

View file

@ -0,0 +1,113 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace RynthCore.App;
/// <summary>
/// Which accounts run as "Decal + RynthCore" (<see cref="InjectionMode.DecalBridge"/>), kept in
/// <c>decal-accounts.json</c> next to <c>%APPDATA%\RynthCore\appsettings.json</c> and keyed by
/// account profile id.
///
/// Why a file of its own: every launcher of this Windows user shares appsettings.json, and a
/// launcher released before the Decal bridge has no "DecalBridge" value in its InjectionMode.
/// Its AppSettingsStore takes a file with that value for corrupt, quarantines it and falls back
/// to the .bak, or to empty defaults (and then saves those). So appsettings.json always lists a
/// "Decal + RynthCore" account as <see cref="SharedMode"/> (RynthCore), and this file says which
/// of those are really "Decal + RynthCore".
///
/// An entry only counts while appsettings.json still says RynthCore for that account: an older
/// launcher that switched the account to Decal (or that deleted it) wins, and the next save of a
/// newer launcher drops the stale entry. Shared with the injector (LaunchCommand).
/// </summary>
internal static class DecalAccountModes
{
public const string FileName = "decal-accounts.json";
/// <summary>What appsettings.json says for a "Decal + RynthCore" account.</summary>
public const InjectionMode SharedMode = InjectionMode.RynthCore;
private const int SchemaVersion = 1;
private const string Note =
"Accounts the RynthCore launcher runs as \"Decal + RynthCore\" (experimental). " +
"appsettings.json lists them as RynthCore, so launchers without that mode can still read it. " +
"Delete this file to set them all back to RynthCore.";
private sealed class FileModel
{
public int Version { get; set; } = SchemaVersion;
public string Note { get; set; } = DecalAccountModes.Note;
public List<string> DecalBridgeAccountIds { get; set; } = new();
}
private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true };
public static string PathIn(string settingsDirectory) => Path.Combine(settingsDirectory, FileName);
/// <summary>
/// The account ids listed in <paramref name="path"/>. An absent file is an empty set; an
/// unreadable one too, with the reason in <paramref name="error"/> (the accounts then run
/// as appsettings.json says, which is RynthCore).
/// </summary>
public static HashSet<string> ReadIds(string path, out string? error)
{
error = null;
var ids = new HashSet<string>(StringComparer.Ordinal);
try
{
if (!File.Exists(path))
return ids;
FileModel? model = JsonSerializer.Deserialize<FileModel>(File.ReadAllText(path));
foreach (string id in model?.DecalBridgeAccountIds ?? new List<string>())
if (!string.IsNullOrWhiteSpace(id))
ids.Add(id);
}
catch (Exception ex)
{
error = $"{FileName} could not be read ({ex.GetType().Name}: {ex.Message}); " +
"its accounts run as RynthCore until the mode is picked again.";
ids.Clear();
}
return ids;
}
/// <summary>
/// True when an account that appsettings.json lists with <paramref name="sharedMode"/> is a
/// "Decal + RynthCore" account: it is in <paramref name="ids"/> and still says RynthCore.
/// </summary>
public static bool IsDecalBridge(IReadOnlySet<string> ids, string? accountId, InjectionMode sharedMode) =>
sharedMode == SharedMode && !string.IsNullOrEmpty(accountId) && ids.Contains(accountId);
/// <summary>
/// Records <paramref name="ids"/> as the "Decal + RynthCore" accounts. Writes only when the
/// list changed; with no accounts left, the file is removed. Atomic (temp file + swap).
/// </summary>
public static void WriteIds(string path, IEnumerable<string> ids)
{
List<string> sorted = ids.Where(id => !string.IsNullOrWhiteSpace(id))
.Distinct(StringComparer.Ordinal)
.OrderBy(id => id, StringComparer.Ordinal)
.ToList();
if (sorted.Count == 0)
{
if (File.Exists(path))
File.Delete(path);
return;
}
if (File.Exists(path))
{
HashSet<string> current = ReadIds(path, out string? error);
if (error == null && current.SetEquals(sorted))
return;
}
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(new FileModel { DecalBridgeAccountIds = sorted }, WriteOptions));
File.Move(tmp, path, overwrite: true);
}
}

View file

@ -0,0 +1,495 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
namespace RynthCore.App;
/// <summary>Registry roots the Decal check reads. "32" = the 32-bit view (WOW6432Node on 64-bit Windows).</summary>
internal enum RegRoot { Machine32, Machine64, User32, User64 }
/// <summary>A read-only registry key (real one, or a fake in tools\DecalBridgeCheckTests).</summary>
internal interface IRegKey : IDisposable
{
object? GetValue(string name);
string[] GetSubKeyNames();
string[] GetValueNames();
}
/// <summary>
/// Everything <see cref="DecalBridgeCheck"/> reads from the machine. The real one is
/// <see cref="RealDecalCheckHost"/>; the offline tests use a fake.
/// </summary>
internal interface IDecalCheckHost
{
bool Is64BitOs { get; }
/// <summary>The launcher (or injector) runs elevated. A client it starts is elevated too.</summary>
bool LauncherElevated { get; }
/// <summary>UAC registry virtualization is on for this process (as it is for a non-elevated AC).</summary>
bool LauncherVirtualized { get; }
/// <summary>The real registry: no UAC virtualization (HKLM is HKLM, the VirtualStore is its own key).</summary>
IRegKey? OpenReal(RegRoot root, string subKey);
/// <summary>
/// HKLM (32-bit view) as THIS process sees it, virtualized when the process is. Only the
/// bridge's own entry is asked for (the real host snapshots it before virtualization is
/// switched off for the rest of the check).
/// </summary>
IRegKey? OpenOwnViewMachine32(string subKey);
bool FileExists(string path);
/// <summary>The file carries a Zone.Identifier stream ("downloaded from the internet").</summary>
bool HasZoneIdentifier(string path);
Version? AssemblyVersionOf(string path);
Version? ReferenceVersionOf(string assemblyPath, string referenceName);
/// <summary>requestedExecutionLevel from the exe's embedded manifest or its .manifest file, null if none.</summary>
string? ExecutionLevelOf(string exePath);
string? ReadTextFile(string path);
}
/// <summary>
/// "Check Decal bridge": can a Decal + RynthCore client started now load the RynthCore Decal
/// bridge? (docs/DECAL_BRIDGE_PLAN.md, "Where Decal reads its filters").
///
/// Decal lists network filters from HKLM\SOFTWARE\Decal\NetworkFilters (decalnet.dll), read
/// by the 32-bit client through the 32-bit view (WOW6432Node), and Decal.Adapter reads each
/// .NET filter's Path/Assembly/Object from SOFTWARE\Decal\NetworkFilters\{id}. Which key that
/// really is depends on the CLIENT's token:
/// - a non-elevated acclient.exe (no manifest, UAC on) is virtualized: when the per-user copy
/// HKCU\Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\NetworkFilters
/// exists, Decal reads ONLY that copy; otherwise the real HKLM key;
/// - an elevated client (the launcher runs as administrator, acclient.exe set to "Run as
/// administrator", UAC off), or one with a manifest, or with virtualization off by policy,
/// is not virtualized and reads the real HKLM key - a per-user registration is invisible.
/// The check predicts that, reads our entry from where Decal will read it, and where it can
/// (the launcher's token is virtualized exactly when the client's will be) reads it again
/// through the launcher's own view, which is the client's view.
/// </summary>
internal static class DecalBridgeCheck
{
public enum Level { Ok, Info, Warn, Fail }
public sealed record Line(Level Level, string Text);
public sealed class Result
{
public List<Line> Lines { get; } = new();
public bool DecalInstalled { get; set; }
public string? DecalVersion { get; set; }
public bool ClientVirtualized { get; set; }
public string ClientReason { get; set; } = string.Empty;
/// <summary>Where Decal reads its filter list on this machine, for people.</summary>
public string FiltersReadFrom { get; set; } = string.Empty;
public bool ReadsPerUserCopy { get; set; }
/// <summary>Our entry is where Decal reads, enabled, with the DLL in place.</summary>
public bool BridgeVisibleToDecal { get; set; }
/// <summary>Not registered where Decal reads, and that place is HKLM: needs administrator rights once.</summary>
public bool NeedsMachineWideRegistration { get; set; }
public bool Blocking => Lines.Any(l => l.Level == Level.Fail);
public void Add(Level level, string text) => Lines.Add(new Line(level, text));
public string Summary => Blocking
? "Decal bridge check: FAILED - " + string.Join(" ", Lines.Where(l => l.Level == Level.Fail).Select(l => l.Text))
: "Decal bridge check: OK - " + FiltersReadFrom + (DecalVersion != null ? $"; Decal {DecalVersion}" : "");
public string ToReport()
{
var sb = new StringBuilder();
foreach (Line l in Lines)
{
string tag = l.Level switch { Level.Ok => "OK ", Level.Info => " ", Level.Warn => "WARN", _ => "FAIL" };
sb.Append(tag).Append(" ").AppendLine(l.Text);
}
sb.AppendLine();
sb.AppendLine(Blocking
? "Result: a Decal + RynthCore client started now would NOT load the bridge (no RynthCore overlay, then a crash). Fix the FAIL lines first."
: "Result: a Decal + RynthCore client started now will load the bridge.");
return sb.ToString();
}
}
/// <summary>Decal's .NET surrogate CLSID (Decal.Adapter.Surrogate).</summary>
public const string SurrogateClsid = "{71A69713-6593-47EC-0002-0000000DECA1}";
/// <summary>The bridge targets .NET Framework 4.8 (Release key 528040).</summary>
private const int Net48Release = 528040;
public static string VirtualStoreDecalPath(bool is64BitOs, string group) => is64BitOs
? @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\" + group
: @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\Decal\" + group;
public static string MachineDecalPath(string group) => @"SOFTWARE\Decal\" + group;
/// <summary>
/// Will a client started by this launcher get UAC registry virtualization? False when it
/// runs elevated or Windows doesn't virtualize it (reason says which).
/// </summary>
public static bool PredictClientVirtualized(IDecalCheckHost host, string? acClientPath, out string reason)
{
int? lua = DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableLUA");
if (lua == 0)
{
reason = "UAC is turned off on this PC (EnableLUA=0), so Windows gives every program the real machine registry";
return false;
}
int? virt = DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableVirtualization");
if (virt == 0)
{
reason = "UAC registry virtualization is turned off by policy (EnableVirtualization=0)";
return false;
}
if (host.LauncherElevated)
{
reason = "RynthCore runs as administrator, so the AC client it starts does too, and Windows gives it the real machine registry";
return false;
}
if (!string.IsNullOrEmpty(acClientPath))
{
string? level = host.ExecutionLevelOf(acClientPath);
if (level != null)
{
reason = $"{Path.GetFileName(acClientPath)} has a manifest (requestedExecutionLevel={level}), so Windows doesn't virtualize it";
return false;
}
string? layer = RunAsAdminLayer(host, acClientPath);
if (layer != null)
{
reason = $"{acClientPath} is set to \"Run this program as an administrator\" ({layer})";
return false;
}
}
reason = "AC runs without administrator rights, so Windows virtualizes its registry";
return true;
}
/// <summary>
/// Where a client (virtualized or not) reads SOFTWARE\Decal\&lt;group&gt;: the per-user
/// VirtualStore copy when it is virtualized and the copy exists, else the real HKLM key.
/// </summary>
public static (RegRoot Root, string Path, bool PerUser) WhereDecalReads(IDecalCheckHost host, bool clientVirtualized, string group)
{
if (clientVirtualized)
{
string vs = VirtualStoreDecalPath(host.Is64BitOs, group);
using IRegKey? k = host.OpenReal(RegRoot.User64, vs);
if (k != null)
return (RegRoot.User64, vs, true);
}
return (RegRoot.Machine32, MachineDecalPath(group), false);
}
/// <summary>
/// What the installer (and every update) writes, so a client finds the bridge whatever
/// its rights (installer\RynthCore.iss: <see cref="DecalBridgeRegistration.RegisterMachineWide"/>
/// elevated, <see cref="DecalBridgeRegistration.InstallPerUser"/> as the installing user):
/// - Machine: always (when Decal is installed). Elevated and unvirtualized clients read
/// only HKLM; a virtualized client without a per-user copy reads HKLM too.
/// - PerUser: only into a per-user copy that ALREADY exists. A virtualized client then
/// reads that copy and nothing else, so the HKLM entry is hidden from it. Creating a
/// copy that doesn't exist would be harmful: it would hide every HKLM filter added later
/// (a Decal plugin installed for all users) from this user's non-elevated clients.
/// </summary>
public static (bool Machine, bool PerUser) PlanInstall(IDecalCheckHost host)
{
bool decal = StringOf(host, RegRoot.Machine32, MachineDecalPath("Agent"), "AgentPath") != null;
if (!decal) return (false, false);
using IRegKey? copy = host.OpenReal(RegRoot.User64, VirtualStoreDecalPath(host.Is64BitOs, "NetworkFilters"));
return (true, copy != null);
}
public static string Describe(bool is64BitOs, RegRoot root, string path) => root switch
{
RegRoot.Machine32 => is64BitOs ? @"HKLM\SOFTWARE\WOW6432Node\" + path.Substring("SOFTWARE\\".Length) : @"HKLM\" + path,
RegRoot.Machine64 => @"HKLM\" + path,
_ => @"HKCU\" + path,
};
/// <summary>Runs every check. Reads only; changes nothing.</summary>
public static Result Run(IDecalCheckHost host, string bridgeDirectory, string? acClientPath, string? engineJsonPath)
{
var r = new Result();
string dir = bridgeDirectory.TrimEnd('\\');
// 1. Decal and its version.
string? agentPath = StringOf(host, RegRoot.Machine32, MachineDecalPath("Agent"), "AgentPath");
r.DecalInstalled = agentPath != null && host.FileExists(Path.Combine(agentPath, "Inject.dll"));
if (!r.DecalInstalled)
{
r.Add(Level.Fail, @"Decal is not installed (HKLM\SOFTWARE\Decal\Agent AgentPath\Inject.dll not found).");
return r;
}
string adapter = Path.Combine(agentPath!, "Decal.Adapter.dll");
Version? installed = host.FileExists(adapter) ? host.AssemblyVersionOf(adapter) : null;
string bridgeDll = Path.Combine(dir, DecalBridgeRegistration.AssemblyFile);
bool bridgePresent = host.FileExists(bridgeDll);
Version? needed = bridgePresent ? host.ReferenceVersionOf(bridgeDll, "Decal.Adapter") : null;
r.DecalVersion = installed?.ToString();
if (installed == null)
r.Add(Level.Fail, $"Decal.Adapter.dll is missing or unreadable in {agentPath} - reinstall Decal.");
else if (needed != null && installed < needed)
r.Add(Level.Fail, $"Decal {installed} is older than the {needed} the bridge is built for - update Decal (decaldev.com), then check again.");
else
r.Add(Level.Ok, $"Decal {installed} in {agentPath}" + (needed != null ? $" (bridge built for {needed})." : "."));
// 2. The bridge DLL itself.
if (!bridgePresent)
r.Add(Level.Fail, $"{DecalBridgeRegistration.AssemblyFile} is missing from {dir} - reinstall RynthCore.");
else if (host.HasZoneIdentifier(bridgeDll))
r.Add(Level.Warn, $"{bridgeDll} is marked as downloaded from the internet; .NET may refuse to load it. Repair removes the mark (or: right-click > Properties > Unblock).");
else
r.Add(Level.Ok, $"Bridge DLL present: {bridgeDll}.");
// 3. How the client will see the registry.
r.ClientVirtualized = PredictClientVirtualized(host, acClientPath, out string why);
r.ClientReason = why;
r.Add(Level.Info, "AC client: " + why + ".");
// 4. Where Decal reads its filters, and our entry there.
var where = WhereDecalReads(host, r.ClientVirtualized, "NetworkFilters");
r.ReadsPerUserCopy = where.PerUser;
string whereText = Describe(host.Is64BitOs, where.Root, where.Path);
r.FiltersReadFrom = "Decal reads its filters from " + whereText + (where.PerUser ? " (your Windows user's copy)" : "");
r.Add(Level.Info, r.FiltersReadFrom + ".");
string? entryProblem = EntryProblem(host, where.Root, where.Path + "\\" + DecalBridgeRegistration.FilterGuid, out string? registeredPath);
if (entryProblem == null)
{
r.BridgeVisibleToDecal = true;
r.Add(Level.Ok, $"RynthCore Decal Bridge is registered there and enabled ({registeredPath}).");
}
else
{
r.NeedsMachineWideRegistration = !where.PerUser;
r.Add(Level.Fail, $"Decal will not load the bridge: {entryProblem} in {whereText}." +
(where.PerUser
? " Repair (or a Decal + RynthCore launch) registers it for your Windows user."
: " That key is shared by all users: Repair adds it there once and Windows asks for administrator permission."));
}
// Other places, for people (a registration Decal won't read explains a "registered but nothing happens").
if (where.PerUser)
{
using IRegKey? m = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
if (m != null && IsOurs(m) && entryProblem != null)
r.Add(Level.Info, "(A machine-wide entry exists, but your per-user copy hides it from AC.)");
}
else
{
using IRegKey? u = host.OpenReal(RegRoot.User64, VirtualStoreDecalPath(host.Is64BitOs, "NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
if (u != null && IsOurs(u) && entryProblem != null)
r.Add(Level.Info, "(A per-user registration exists, but this AC client doesn't read it: " + why + ".)");
}
// 5. The same entry through this process's own view, when that view IS the client's.
bool sameView = host.LauncherVirtualized == r.ClientVirtualized;
if (sameView)
{
using IRegKey? live = host.OpenOwnViewMachine32(MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
bool liveOk = live != null && IsOurs(live) && IsEnabled(live);
if (liveOk == r.BridgeVisibleToDecal)
r.Add(Level.Ok, $"Read back as AC will see it: {(liveOk ? "bridge listed and enabled" : "bridge not listed")}.");
else
r.Add(liveOk ? Level.Warn : Level.Fail,
$"Read back as AC will see it: {(liveOk ? "bridge listed" : "bridge NOT listed")}, which disagrees with {whereText}. Windows serves this PC's registry differently than expected.");
}
else
{
r.Add(Level.Info, "Not read back live: AC will run with other rights than this launcher.");
}
// 6. Hidden machine filters (a per-user list hides every HKLM entry it lacks).
if (where.PerUser)
{
List<string> hidden = HiddenMachineFilters(host, where.Path);
if (hidden.Count > 0)
r.Add(Level.Warn, "Hidden from AC by your per-user filter list (in HKLM, not in the copy): " + string.Join(", ", hidden) +
". If 'World Object Filter' is among them, VTank won't start.");
}
// 7. Decal's .NET surrogate: Decal must be able to create it, and must not have it disabled.
var surWhere = WhereDecalReads(host, r.ClientVirtualized, "Surrogates");
using (IRegKey? s = host.OpenReal(surWhere.Root, surWhere.Path + "\\" + SurrogateClsid))
{
if (s == null)
r.Add(Level.Fail, $"Decal's .NET surrogate is not listed in {Describe(host.Is64BitOs, surWhere.Root, surWhere.Path)} - no .NET filter or plugin can load. Reinstall Decal.");
else if (!IsEnabled(s))
r.Add(Level.Fail, "Decal's .NET surrogate (Decal.Adapter Surrogate) is disabled in Decal - enable it in Decal's agent (or reinstall Decal).");
else
r.Add(Level.Ok, "Decal's .NET surrogate is enabled.");
}
string? comProblem = SurrogateComProblem(host, clientElevated: !r.ClientVirtualized && IsClientElevated(host, acClientPath), out string comWhere);
if (comProblem != null)
r.Add(Level.Fail, comProblem);
else
r.Add(Level.Ok, $"Decal.Adapter's COM class resolves ({comWhere}). The bridge itself needs no COM registration: Decal.Adapter loads it from Path\\Assembly.");
// 8. .NET Framework 4.8.
int? release = DwordOf(host, RegRoot.Machine32, @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", "Release");
if (release == null)
r.Add(Level.Fail, ".NET Framework 4 is not installed (Decal needs it).");
else if (release < Net48Release)
r.Add(Level.Warn, $".NET Framework older than 4.8 (Release {release}); the bridge targets 4.8 - install .NET Framework 4.8.");
// 9. engine.json settings that turn bridge mode off.
if (engineJsonPath != null)
{
(string? mode, bool? inGame) = ReadEngineSettings(host, engineJsonPath);
if (mode != null && (mode.Equals("Off", StringComparison.OrdinalIgnoreCase) || mode.Equals("false", StringComparison.OrdinalIgnoreCase)))
r.Add(Level.Fail, $"engine.json has \"DecalBridge\": {mode} - bridge mode is off for every client. Remove that line ({engineJsonPath}).");
if (inGame == false)
r.Add(Level.Warn, "engine.json has \"DecalInGameImGui\": false - no RynthCore overlay under Decal (by choice).");
}
return r;
}
// ── pieces (internal for the tests) ─────────────────────────────────────
internal static string? EntryProblem(IDecalCheckHost host, RegRoot root, string entryPath, out string? registeredPath)
{
registeredPath = null;
using IRegKey? k = host.OpenReal(root, entryPath);
if (k == null) return "the RynthCore Decal Bridge is not registered";
if (!IsOurs(k)) return "another filter uses the bridge's id";
registeredPath = k.GetValue("Path") as string;
if (!IsEnabled(k)) return "the RynthCore Decal Bridge is registered but disabled";
if (!string.Equals(k.GetValue("Surrogate") as string, SurrogateClsid, StringComparison.OrdinalIgnoreCase))
return "the bridge entry has the wrong Surrogate";
string? file = k.GetValue("Assembly") as string;
if (string.IsNullOrEmpty(registeredPath) || string.IsNullOrEmpty(file))
return "the bridge entry has no Path/Assembly";
if (!host.FileExists(Path.Combine(registeredPath, file)))
return $"the registered bridge DLL is missing ({Path.Combine(registeredPath, file)})";
return null;
}
internal static List<string> HiddenMachineFilters(IDecalCheckHost host, string perUserPath)
{
var hidden = new List<string>();
using IRegKey? machine = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters"));
using IRegKey? user = host.OpenReal(RegRoot.User64, perUserPath);
if (machine == null || user == null) return hidden;
var seen = new HashSet<string>(user.GetSubKeyNames(), StringComparer.OrdinalIgnoreCase);
foreach (string name in machine.GetSubKeyNames())
{
if (seen.Contains(name) || string.Equals(name, DecalBridgeRegistration.FilterGuid, StringComparison.OrdinalIgnoreCase))
continue;
using IRegKey? k = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters") + "\\" + name);
hidden.Add(k?.GetValue("") is string friendly && friendly.Length > 0 ? friendly : name);
}
return hidden;
}
/// <summary>
/// Decal.Adapter's surrogate is an mscoree COM class. A non-elevated client resolves it
/// per-user first (HKCU\Software\Classes), then machine-wide; an elevated one ignores
/// per-user COM registrations.
/// </summary>
internal static string? SurrogateComProblem(IDecalCheckHost host, bool clientElevated, out string where)
{
where = string.Empty;
string sub = @"\CLSID\" + SurrogateClsid + @"\InprocServer32";
var candidates = new List<(RegRoot Root, string Path, string Label)>();
if (!clientElevated) candidates.Add((RegRoot.User32, @"Software\Classes" + sub, "per-user"));
candidates.Add((RegRoot.Machine32, @"SOFTWARE\Classes" + sub, "machine-wide"));
foreach (var c in candidates)
{
using IRegKey? k = host.OpenReal(c.Root, c.Path);
if (k == null) continue;
where = c.Label;
string server = k.GetValue("") as string ?? string.Empty;
if (!server.EndsWith("mscoree.dll", StringComparison.OrdinalIgnoreCase))
return $"Decal.Adapter's COM class ({c.Label}) points at '{server}', not mscoree.dll - reinstall Decal.";
if (string.IsNullOrEmpty(k.GetValue("Assembly") as string))
return $"Decal.Adapter's COM class ({c.Label}) names no assembly - reinstall Decal.";
if (k.GetValue("CodeBase") is string cb && cb.Length > 0)
{
string file = cb.StartsWith("file:", StringComparison.OrdinalIgnoreCase) ? cb.Substring(5).TrimStart('/') : cb;
if (!host.FileExists(file.Replace('/', '\\')))
return $"Decal.Adapter's COM class ({c.Label}) points at a missing file ({file}) - reinstall Decal.";
}
return null;
}
bool perUserOnly = clientElevated && OpenExists(host, RegRoot.User32, @"Software\Classes" + sub);
return perUserOnly
? "Decal.Adapter's COM class is registered only for your Windows user, and an AC running as administrator ignores per-user COM classes - reinstall Decal for all users."
: "Decal.Adapter's COM class (Decal.Adapter.Surrogate) is not registered - reinstall Decal.";
}
private static bool IsClientElevated(IDecalCheckHost host, string? acClientPath)
{
if (host.LauncherElevated) return true;
if (string.IsNullOrEmpty(acClientPath)) return false;
string? level = host.ExecutionLevelOf(acClientPath);
if (level != null && (level.Equals("requireAdministrator", StringComparison.OrdinalIgnoreCase) || level.Equals("highestAvailable", StringComparison.OrdinalIgnoreCase)))
return true;
if (RunAsAdminLayer(host, acClientPath) != null) return true;
// UAC off: an administrator's programs run with the full token.
return DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableLUA") == 0;
}
private static string? RunAsAdminLayer(IDecalCheckHost host, string exePath)
{
foreach ((RegRoot root, string key) in new[]
{
(RegRoot.User64, @"Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"),
(RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"),
})
{
using IRegKey? k = host.OpenReal(root, key);
if (k == null) continue;
foreach (string name in k.GetValueNames())
{
if (!string.Equals(name, exePath, StringComparison.OrdinalIgnoreCase)) continue;
string flags = k.GetValue(name) as string ?? string.Empty;
string[] parts = flags.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Any(p => p.Equals("RUNASADMIN", StringComparison.OrdinalIgnoreCase) || p.Equals("RUNASHIGHEST", StringComparison.OrdinalIgnoreCase)))
return (root == RegRoot.User64 ? "your compatibility settings" : "compatibility settings for all users") + ": " + flags.Trim();
}
}
return null;
}
private static (string? Mode, bool? InGame) ReadEngineSettings(IDecalCheckHost host, string path)
{
try
{
string? text = host.ReadTextFile(path);
if (text == null) return (null, null);
using JsonDocument doc = JsonDocument.Parse(text, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
string? mode = null;
bool? inGame = null;
if (doc.RootElement.TryGetProperty("DecalBridge", out JsonElement m))
mode = m.ValueKind switch { JsonValueKind.String => m.GetString(), JsonValueKind.True => "true", JsonValueKind.False => "false", _ => null };
if (doc.RootElement.TryGetProperty("DecalInGameImGui", out JsonElement g) && (g.ValueKind == JsonValueKind.True || g.ValueKind == JsonValueKind.False))
inGame = g.GetBoolean();
return (mode, inGame);
}
catch
{
return (null, null);
}
}
internal static bool IsOurs(IRegKey k) =>
string.Equals(k.GetValue("Object") as string, DecalBridgeRegistration.FilterObject, StringComparison.Ordinal);
internal static bool IsEnabled(IRegKey k) => k.GetValue("Enabled") is int e && e != 0;
private static bool OpenExists(IDecalCheckHost host, RegRoot root, string path)
{
using IRegKey? k = host.OpenReal(root, path);
return k != null;
}
private static int? DwordOf(IDecalCheckHost host, RegRoot root, string path, string name)
{
using IRegKey? k = host.OpenReal(root, path);
return k?.GetValue(name) is int v ? v : null;
}
private static string? StringOf(IDecalCheckHost host, RegRoot root, string path, string name)
{
using IRegKey? k = host.OpenReal(root, path);
return k?.GetValue(name) is string s && s.Length > 0 ? s : null;
}
}

View file

@ -0,0 +1,810 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using Microsoft.Win32;
namespace RynthCore.App;
/// <summary>
/// Registers (and cleanly unregisters) the RynthCore Decal bridge - the small Decal
/// network filter in src\RynthCore.DecalBridge - in Decal's filter list. See
/// docs\DECAL_BRIDGE_PLAN.md, "Where Decal reads its filters".
///
/// <see cref="RegisterForClients"/> picks the place: the per-user copy below when the AC
/// client will be virtualized (the usual, non-elevated case), the machine-wide HKLM list
/// (administrator rights, once) when it won't be. An elevated or unvirtualized client never
/// reads the per-user copy (2026-10-03: a player's Decal + RynthCore client never loaded the
/// bridge). <see cref="DecalBridgeCheck"/> verifies the result.
///
/// Per-user. The launcher runs without admin rights, so it can't write Decal's own
/// key (HKLM\SOFTWARE\WOW6432Node\Decal\NetworkFilters). acclient.exe is a legacy 32-bit
/// program that Windows "virtualizes": its reads of that HKLM key are served from the
/// per-user copy under HKCU\Software\Classes\VirtualStore when one exists. Registering
/// there makes every Decal client this user starts load the bridge (it stays idle unless
/// RynthCore is in the same client).
///
/// The trap (measured 2026-09-29): once the per-user NetworkFilters key exists, Decal
/// sees ONLY its entries - HKLM's filters (World Object Filter, Echo Filter, ...) vanish,
/// Decal's WorldFilter is null and VTank refuses to start. So when this class has to
/// create that key, it first mirrors every HKLM filter entry into it, and on each
/// Register call it copies over HKLM entries added since.
///
/// What it adds is recorded in %APPDATA%\RynthCore\decal-bridge-registration.json;
/// Unregister removes exactly that: the bridge's own entry, the mirrored copies nobody has
/// changed since, and the per-user key itself only if this class created it and nothing
/// else is left in it. Register is idempotent.
///
/// Opt-in only: nothing calls Register unless the user picked "Decal + RynthCore" for an
/// account (or ran the injector's --decal-bridge register).
/// </summary>
internal static class DecalBridgeRegistration
{
/// <summary>The bridge's fixed filter id (one entry, whatever the install path).</summary>
public const string FilterGuid = "{5B3E0D57-2C41-4F8A-9D6E-8C1B70DECA11}";
public const string FilterObject = "RynthCore.DecalBridge.BridgeFilter";
public const string AssemblyFile = "RynthCore.DecalBridge.dll";
public const string FilterName = "RynthCore Decal Bridge";
/// <summary>Decal's .NET surrogate, the value every Decal.Adapter filter registers with.</summary>
private const string DotNetSurrogate = "{71A69713-6593-47EC-0002-0000000DECA1}";
private const string DecalFiltersSubKey = @"SOFTWARE\Decal\NetworkFilters"; // seen through the 32-bit view
private const RegistryView MachineView = RegistryView.Registry32; // what the 32-bit client reads
private static string StatePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "decal-bridge-registration.json");
/// <summary>HKCU path of the per-user copy the virtualized 32-bit client reads.</summary>
public static string VirtualStoreFiltersSubKey => Environment.Is64BitOperatingSystem
? @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\NetworkFilters"
: @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\Decal\NetworkFilters";
/// <summary>The folder the launcher registers: &lt;install&gt;\DecalBridge.</summary>
public static string DefaultBridgeDirectory => Path.Combine(AppContext.BaseDirectory, "DecalBridge");
public sealed class Status
{
public bool DecalInstalled;
public bool PerUserKeyExists;
public bool PerUserKeyCreatedByUs;
public bool RegisteredPerUser;
public bool RegisteredMachineWide;
public bool Enabled;
public bool MachineEnabled;
public string? RegisteredPath;
public bool DllPresent;
/// <summary>A client started by this process gets UAC registry virtualization (reads the per-user copy when it exists).</summary>
public bool ClientVirtualized = true;
public string ClientReason = string.Empty;
/// <summary>HKLM filters a Decal client of this user can't see (hidden by the per-user key).</summary>
public List<string> HiddenMachineFilters = new();
/// <summary>What a Decal client started now will load (see DecalBridgeCheck for the full check).</summary>
public bool EffectiveForClients => ClientVirtualized && PerUserKeyExists
? RegisteredPerUser && Enabled
: RegisteredMachineWide && MachineEnabled;
public override string ToString()
{
var sb = new StringBuilder();
sb.Append($"Decal installed: {DecalInstalled}. ");
sb.Append($"Bridge registered for clients started now: {(EffectiveForClients ? "yes" : "no")}");
if (RegisteredPerUser) sb.Append(" (per-user entry present)");
if (RegisteredMachineWide) sb.Append(" (machine-wide entry present)");
if (RegisteredPath != null) sb.Append($", path {RegisteredPath}{(DllPresent ? "" : " (DLL MISSING)")}");
sb.Append('.');
if (ClientReason.Length > 0) sb.Append($" Client: {ClientReason}.");
if (PerUserKeyExists)
sb.Append($" Per-user filter list: {(PerUserKeyCreatedByUs ? "created by RynthCore" : "existed before RynthCore")}.");
if (HiddenMachineFilters.Count > 0)
sb.Append($" Hidden from Decal clients (in HKLM, not in the per-user list): {string.Join(", ", HiddenMachineFilters)}.");
return sb.ToString();
}
}
private sealed class State
{
public bool CreatedFiltersKey { get; set; }
public string BridgePath { get; set; } = string.Empty;
public DateTime RegisteredUtc { get; set; }
/// <summary>Mirrored HKLM subkey -> fingerprint of the copy as written.</summary>
public Dictionary<string, string> MirroredKeys { get; set; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Mirrored values of the NetworkFilters key itself -> fingerprint.</summary>
public Dictionary<string, string> MirroredValues { get; set; } = new(StringComparer.OrdinalIgnoreCase);
}
// ── public API ───────────────────────────────────────────────────────────
public static Status GetStatus(string? acClientPath = null)
{
bool virt = RealDecalCheckHost.PredictClientVirtualized(acClientPath ?? DecalLocator.TryGetDecalAcClientPath(), out string reason, out _);
Status s;
using (RealRegistryView.Enter()) s = GetStatusCore();
s.ClientVirtualized = virt;
s.ClientReason = reason;
return s;
}
private static Status GetStatusCore()
{
var s = new Status { DecalInstalled = DecalLocator.IsInstalled() };
State? state = LoadState();
using RegistryKey? machine = OpenMachineFilters();
using RegistryKey? user = OpenUserFilters(writable: false);
s.PerUserKeyExists = user != null;
s.PerUserKeyCreatedByUs = user != null && state?.CreatedFiltersKey == true;
using (RegistryKey? m = machine?.OpenSubKey(FilterGuid))
{
if (m != null && IsOurs(m))
{
s.RegisteredMachineWide = true;
s.MachineEnabled = Enabled(m);
if (user == null) ReadEntry(m, s);
}
}
using (RegistryKey? u = user?.OpenSubKey(FilterGuid))
{
if (u != null && IsOurs(u))
{
s.RegisteredPerUser = true;
ReadEntry(u, s);
}
}
if (machine != null && user != null)
{
HashSet<string> seen = new(user.GetSubKeyNames(), StringComparer.OrdinalIgnoreCase);
foreach (string name in machine.GetSubKeyNames())
if (!seen.Contains(name))
s.HiddenMachineFilters.Add(DescribeFilter(machine, name));
}
return s;
}
public enum Outcome { Registered, NeedsAdmin, Failed }
/// <summary>
/// Registers the bridge where a Decal client started now reads its filter list, then
/// verifies it with <see cref="DecalBridgeCheck"/> (reading back from that place, and
/// through this process's own view when it is the client's).
/// - Client virtualized (non-elevated AC, the usual case): the per-user VirtualStore copy,
/// as before (no administrator rights needed).
/// - Client not virtualized (RynthCore/AC run as administrator, UAC off, a manifest,
/// virtualization off by policy): Decal reads the real
/// HKLM\SOFTWARE\(WOW6432Node\)Decal\NetworkFilters, where a per-user entry is
/// invisible. Written directly when this process may; otherwise <see cref="Outcome.NeedsAdmin"/>,
/// and the caller runs <c>--decal-bridge-register-machine</c> elevated (<see cref="RunElevated"/>).
/// Idempotent. Also removes a "downloaded from the internet" mark from the bridge DLL.
/// </summary>
public static Outcome RegisterForClients(string bridgeDirectory, string? acClientPath, string? engineJsonPath,
out string report, out DecalBridgeCheck.Result? check)
{
check = null;
var log = new List<string>();
string dir;
try { dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\'); }
catch (Exception ex) { report = $"Bad bridge folder '{bridgeDirectory}': {ex.Message}"; return Outcome.Failed; }
string dll = Path.Combine(dir, AssemblyFile);
if (File.Exists(dll) && File.Exists(dll + ":Zone.Identifier"))
log.Add(RealDecalCheckHost.RemoveZoneIdentifier(dll)
? "removed the 'downloaded from the internet' mark from the bridge DLL"
: "could not remove the 'downloaded from the internet' mark from the bridge DLL");
bool virtualized = RealDecalCheckHost.PredictClientVirtualized(acClientPath, out string why, out _);
bool ok;
string step;
if (virtualized)
{
ok = RegisterPerUser(dir, out step);
}
else
{
Outcome mw = RegisterMachineWide(dir, out step);
if (mw == Outcome.NeedsAdmin)
{
log.Add($"AC reads Decal's filter list for all users on this PC ({why}); adding the bridge there needs administrator rights once.");
report = string.Join(" ", log);
return Outcome.NeedsAdmin;
}
ok = mw == Outcome.Registered;
step = $"({why}) " + step;
}
log.Add(step);
check = RealDecalCheckHost.Check(dir, acClientPath, engineJsonPath);
log.Add(check.Summary);
report = string.Join(" ", log);
if (!ok) return Outcome.Failed;
if (check.Blocking) return check.NeedsMachineWideRegistration ? Outcome.NeedsAdmin : Outcome.Failed;
return Outcome.Registered;
}
/// <summary>
/// <see cref="RegisterForClients"/> for Decal's own acclient.exe (PortalPath). False (with
/// the reason) when it needs administrator rights or the check fails.
/// </summary>
public static bool Register(string bridgeDirectory, out string report) =>
RegisterForClients(bridgeDirectory, DecalLocator.TryGetDecalAcClientPath(), null, out report, out _) == Outcome.Registered;
/// <summary>
/// Adds the bridge to the machine-wide list, HKLM\SOFTWARE\(WOW6432Node\)Decal\NetworkFilters
/// (32-bit view). Needs administrator rights: run elevated (--decal-bridge-register-machine).
/// Virtualization is off while it writes, so a non-elevated process gets "access denied"
/// (NeedsAdmin) instead of a silent write into the per-user copy. Idempotent; nothing to mirror
/// (the machine list is the one every other filter is in).
/// </summary>
public static Outcome RegisterMachineWide(string bridgeDirectory, out string report)
{
var log = new List<string>();
using (RealRegistryView.Enter())
{
try
{
if (!DecalLocator.IsInstalled())
{
report = "Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent) - nothing registered.";
return Outcome.Failed;
}
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
{
report = $"{AssemblyFile} not found in {dir} - nothing registered.";
return Outcome.Failed;
}
using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView);
using RegistryKey filters = hklm.CreateSubKey(DecalFiltersSubKey, writable: true);
using (RegistryKey? existing = filters.OpenSubKey(FilterGuid))
{
if (existing != null && !IsOurs(existing))
{
report = $"another filter uses the bridge's id {FilterGuid} in the machine-wide list - nothing changed.";
return Outcome.Failed;
}
}
using (RegistryKey entry = filters.CreateSubKey(FilterGuid, writable: true))
{
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
}
report = log.Count == 0
? $"Decal bridge already registered for all users ({dir}); nothing changed."
: $"Decal bridge registered for all users ({dir}): {string.Join("; ", log)}.";
return Outcome.Registered;
}
catch (Exception ex) when (ex is UnauthorizedAccessException or System.Security.SecurityException)
{
report = "Registering the Decal bridge for all users needs administrator rights.";
return Outcome.NeedsAdmin;
}
catch (Exception ex)
{
report = $"Decal bridge registration for all users failed: {Describe(ex)}";
return Outcome.Failed;
}
}
}
/// <summary>
/// The installer's per-user half (installer\RynthCore.iss, run as the installing user on
/// every install and update; the elevated half is <see cref="RegisterMachineWide"/>).
/// Writes our entry into this user's VirtualStore copy of Decal's filter list ONLY when
/// that copy already exists - see <see cref="DecalBridgeCheck.PlanInstall"/> for why both
/// places are written and why a missing copy is never created here. The entry is ours
/// (Object = <see cref="FilterObject"/>), so <see cref="Unregister"/> removes it.
/// </summary>
public static bool InstallPerUser(string bridgeDirectory, out string report)
{
try
{
var plan = RealDecalCheckHost.PlanInstall();
if (!plan.Machine)
{
report = "Decal is not installed - nothing to do for this user.";
return true;
}
if (!plan.PerUser)
{
report = "This user has no per-user copy of Decal's filter list - the machine-wide entry is the one AC reads; nothing written.";
return true;
}
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
{
report = $"{AssemblyFile} not found in {dir} - nothing written.";
return false;
}
var log = new List<string>();
using (RealRegistryView.Enter())
{
using RegistryKey? user = OpenUserFilters(writable: true);
if (user == null)
{
report = "The per-user copy disappeared - nothing written.";
return true;
}
using (RegistryKey? existing = user.OpenSubKey(FilterGuid))
{
if (existing != null && !IsOurs(existing))
{
report = $"another filter uses the bridge's id {FilterGuid} in the per-user copy - nothing changed.";
return false;
}
}
using RegistryKey entry = user.CreateSubKey(FilterGuid, writable: true);
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
}
report = log.Count == 0
? $"Decal bridge already in this user's per-user copy ({dir}); nothing changed."
: $"Decal bridge added to this user's existing per-user copy ({dir}): {string.Join("; ", log)}.";
return true;
}
catch (Exception ex)
{
report = $"Per-user Decal bridge entry failed: {Describe(ex)}";
return false;
}
}
/// <summary>The machine-wide list holds our entry (the launcher/injector never adds it without being asked).</summary>
public static bool MachineEntryIsOurs()
{
using (RealRegistryView.Enter())
{
try
{
using RegistryKey? machine = OpenMachineFilters();
using RegistryKey? m = machine?.OpenSubKey(FilterGuid);
return m != null && IsOurs(m);
}
catch { return false; }
}
}
/// <summary>Removes our machine-wide entry (only ours). Needs administrator rights.</summary>
public static Outcome UnregisterMachineWide(out string report)
{
using (RealRegistryView.Enter())
{
try
{
using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView);
using RegistryKey? probe = hklm.OpenSubKey(DecalFiltersSubKey);
using RegistryKey? m = probe?.OpenSubKey(FilterGuid);
if (m == null || !IsOurs(m))
{
report = "No machine-wide Decal bridge entry; nothing to remove.";
return Outcome.Registered;
}
using RegistryKey filters = hklm.OpenSubKey(DecalFiltersSubKey, writable: true)!;
filters.DeleteSubKeyTree(FilterGuid, throwOnMissingSubKey: false);
report = "Removed the machine-wide Decal bridge entry.";
return Outcome.Registered;
}
catch (Exception ex) when (ex is UnauthorizedAccessException or System.Security.SecurityException)
{
report = "Removing the machine-wide Decal bridge entry needs administrator rights.";
return Outcome.NeedsAdmin;
}
catch (Exception ex)
{
report = $"Removing the machine-wide Decal bridge entry failed: {Describe(ex)}";
return Outcome.Failed;
}
}
}
/// <summary>
/// Runs <paramref name="exePath"/> elevated (Windows shows its administrator prompt) and
/// waits for it. NeedsAdmin when the person said no at the prompt.
/// </summary>
public static Outcome RunElevated(string exePath, string arguments, out string report)
{
try
{
var psi = new System.Diagnostics.ProcessStartInfo(exePath, arguments)
{
UseShellExecute = true,
Verb = "runas",
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
};
using System.Diagnostics.Process? p = System.Diagnostics.Process.Start(psi);
if (p == null)
{
report = "Windows did not start the administrator step.";
return Outcome.Failed;
}
if (!p.WaitForExit(120_000))
{
report = "The administrator step did not finish within 2 minutes.";
return Outcome.Failed;
}
report = p.ExitCode == 0 ? "The administrator step finished." : $"The administrator step failed (exit code {p.ExitCode}).";
return p.ExitCode == 0 ? Outcome.Registered : Outcome.Failed;
}
catch (System.ComponentModel.Win32Exception ex) when (ex.NativeErrorCode == 1223)
{
report = "Cancelled at the Windows administrator prompt.";
return Outcome.NeedsAdmin;
}
catch (Exception ex)
{
report = $"Could not start the administrator step: {ex.Message}";
return Outcome.Failed;
}
}
/// <summary>
/// Makes Decal clients of this user load the bridge from <paramref name="bridgeDirectory"/>
/// through the per-user VirtualStore copy (virtualized clients only: see
/// <see cref="RegisterForClients"/>). Idempotent. Returns false (with the reason in
/// <paramref name="report"/>) when Decal isn't installed or the bridge DLL isn't there.
/// </summary>
public static bool RegisterPerUser(string bridgeDirectory, out string report)
{
using (RealRegistryView.Enter()) return RegisterCore(bridgeDirectory, out report);
}
private static bool RegisterCore(string bridgeDirectory, out string report)
{
var log = new List<string>();
try
{
if (!DecalLocator.IsInstalled())
{
report = "Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent) - nothing registered.";
return false;
}
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
{
report = $"{AssemblyFile} not found in {dir} - nothing registered.";
return false;
}
State state = LoadState() ?? new State();
using RegistryKey? machine = OpenMachineFilters();
using RegistryKey? existingUser = OpenUserFilters(writable: true);
if (existingUser == null && state.CreatedFiltersKey)
{
// Someone removed the key we created; start the record over.
state = new State();
}
RegistryKey? user = existingUser;
try
{
if (user == null)
{
// No per-user list yet. If an administrator already registered the bridge in
// HKLM with this path, clients see it without us creating anything.
using (RegistryKey? m = machine?.OpenSubKey(FilterGuid))
{
if (m != null && IsOurs(m) && Enabled(m) &&
string.Equals((m.GetValue("Path") as string)?.TrimEnd('\\'), dir, StringComparison.OrdinalIgnoreCase))
{
report = "Already registered machine-wide (HKLM) with this path; nothing changed.";
return true;
}
}
user = UserHive().CreateSubKey(VirtualStoreFiltersSubKey, writable: true);
state.CreatedFiltersKey = true;
log.Add($"created HKCU\\{VirtualStoreFiltersSubKey}");
}
if (state.CreatedFiltersKey && machine != null)
SyncMirror(machine, user, state, log);
using (RegistryKey entry = user.CreateSubKey(FilterGuid, writable: true))
{
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
}
}
finally
{
if (!ReferenceEquals(user, existingUser)) user?.Dispose();
}
state.BridgePath = dir;
state.RegisteredUtc = DateTime.UtcNow;
SaveState(state);
report = log.Count == 0
? $"Decal bridge already registered for this user ({dir}); nothing changed."
: $"Decal bridge registered for this user ({dir}): {string.Join("; ", log)}.";
return true;
}
catch (Exception ex)
{
report = $"Decal bridge registration failed: {ex.GetType().Name}: {ex.Message}" +
(log.Count > 0 ? $" (done before the failure: {string.Join("; ", log)})" : "");
return false;
}
}
/// <summary>
/// Removes what <see cref="Register"/> added: the bridge's entry, the mirrored copies of
/// HKLM filters, and the per-user key if this class created it and nothing foreign is
/// left in it. A mirrored copy that changed since (Decal plugins write to "HKLM" through
/// UAC virtualization, so their writes land in our per-user copy) is removed as well when
/// RynthCore created the key: HKLM still holds the original, and a per-user list left with
/// a few entries would hide every other HKLM filter from Decal clients (VTank then has no
/// WorldFilter). Anything RynthCore didn't add is left in place and reported, and the
/// record (%APPDATA%\RynthCore\decal-bridge-registration.json) is kept until nothing of
/// ours remains, so a later unregister can finish the job.
/// </summary>
public static bool Unregister(out string report)
{
using (RealRegistryView.Enter()) return UnregisterCore(out report);
}
private static bool UnregisterCore(out string report)
{
var log = new List<string>();
var failed = new List<string>();
try
{
State? state = LoadState();
bool done = true;
using RegistryKey? user = OpenUserFilters(writable: true);
if (user != null)
{
foreach (string name in user.GetSubKeyNames())
{
try
{
bool ours;
using (RegistryKey? k = user.OpenSubKey(name))
ours = k != null && IsOurs(k);
if (!ours) continue;
user.DeleteSubKeyTree(name, throwOnMissingSubKey: false);
log.Add($"removed bridge entry {name}");
}
catch (Exception ex) { failed.Add($"{name}: {Describe(ex)}"); }
}
if (state?.CreatedFiltersKey == true)
{
int same = 0, changed = 0;
foreach (KeyValuePair<string, string> kv in state.MirroredKeys)
{
try
{
bool unchanged;
using (RegistryKey? k = user.OpenSubKey(kv.Key))
{
if (k == null) continue;
unchanged = Fingerprint(k) == kv.Value;
}
user.DeleteSubKeyTree(kv.Key, throwOnMissingSubKey: false);
if (unchanged) same++; else changed++;
}
catch (Exception ex) { failed.Add($"{kv.Key}: {Describe(ex)}"); }
}
foreach (KeyValuePair<string, string> kv in state.MirroredValues)
{
try { user.DeleteValue(kv.Key, throwOnMissingValue: false); }
catch (Exception ex) { failed.Add($"value {kv.Key}: {Describe(ex)}"); }
}
log.Add($"removed {same + changed} mirrored filter entr{(same + changed == 1 ? "y" : "ies")}" +
(changed > 0 ? $" ({changed} changed by Decal plugins since; HKLM keeps the originals)" : ""));
var foreign = new List<string>();
foreach (string n in user.GetSubKeyNames()) foreign.Add(n);
foreach (string n in user.GetValueNames()) if (n.Length > 0) foreign.Add(n);
if (foreign.Count == 0 && failed.Count == 0)
{
user.Dispose();
UserHive().DeleteSubKey(VirtualStoreFiltersSubKey, throwOnMissingSubKey: false);
log.Add($"removed HKCU\\{VirtualStoreFiltersSubKey} (created by RynthCore)");
}
else
{
done = false;
log.Add($"left HKCU\\{VirtualStoreFiltersSubKey} in place" +
(foreign.Count > 0 ? $": it holds entries RynthCore didn't add ({string.Join(", ", foreign)})" : ""));
}
}
}
if (failed.Count > 0)
done = false;
if (done && File.Exists(StatePath))
File.Delete(StatePath);
else if (!done)
log.Add($"kept {StatePath} for the next unregister");
if (failed.Count > 0)
{
report = $"Decal bridge unregistration incomplete: {string.Join("; ", failed)}" +
(log.Count > 0 ? $" (done: {string.Join("; ", log)})" : "");
return false;
}
report = log.Count == 0 ? "Decal bridge was not registered for this user; nothing to remove." : string.Join("; ", log) + ".";
return true;
}
catch (Exception ex)
{
report = $"Decal bridge unregistration failed: {Describe(ex)}" +
(log.Count > 0 ? $" (done before the failure: {string.Join("; ", log)})" : "");
return false;
}
}
// Exception type, message and the innermost frame, for a one-line report.
private static string Describe(Exception ex)
{
string? frame = ex.StackTrace?.Split('\n').Select(l => l.Trim()).FirstOrDefault(l => l.Length > 0);
return $"{ex.GetType().Name}: {ex.Message}" + (frame != null ? $" [{frame}]" : "");
}
// ── mirror ───────────────────────────────────────────────────────────────
// Copies HKLM entries the per-user list lacks, and refreshes copies nobody changed
// since we wrote them (so a filter the user enables/disables machine-wide follows).
private static void SyncMirror(RegistryKey machine, RegistryKey user, State state, List<string> log)
{
int added = 0, refreshed = 0;
foreach (string name in machine.GetValueNames())
{
if (name.Length == 0) continue;
object? v = machine.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v == null) continue;
RegistryValueKind kind = machine.GetValueKind(name);
object? have = user.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
bool ours = state.MirroredValues.TryGetValue(name, out string? print);
if (have == null || (ours && ValuePrint(user.GetValueKind(name), have) == print))
{
user.SetValue(name, v, kind);
state.MirroredValues[name] = ValuePrint(kind, v);
}
}
foreach (string name in machine.GetSubKeyNames())
{
if (string.Equals(name, FilterGuid, StringComparison.OrdinalIgnoreCase)) continue;
using RegistryKey? src = machine.OpenSubKey(name);
if (src == null) continue;
string srcPrint = Fingerprint(src);
using RegistryKey? existing = user.OpenSubKey(name);
if (existing == null)
{
using RegistryKey dst = user.CreateSubKey(name, writable: true);
CopyTree(src, dst);
state.MirroredKeys[name] = Fingerprint(dst);
added++;
}
else if (state.MirroredKeys.TryGetValue(name, out string? written) &&
Fingerprint(existing) == written && srcPrint != written)
{
existing.Dispose();
user.DeleteSubKeyTree(name, throwOnMissingSubKey: false);
using RegistryKey dst = user.CreateSubKey(name, writable: true);
CopyTree(src, dst);
state.MirroredKeys[name] = Fingerprint(dst);
refreshed++;
}
}
if (added > 0) log.Add($"mirrored {added} HKLM filter entr{(added == 1 ? "y" : "ies")} (so Decal still sees them)");
if (refreshed > 0) log.Add($"refreshed {refreshed} mirrored entr{(refreshed == 1 ? "y" : "ies")} from HKLM");
}
private static void CopyTree(RegistryKey src, RegistryKey dst)
{
foreach (string name in src.GetValueNames())
{
object? v = src.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v != null) dst.SetValue(name, v, src.GetValueKind(name));
}
foreach (string sub in src.GetSubKeyNames())
{
using RegistryKey? s = src.OpenSubKey(sub);
if (s == null) continue;
using RegistryKey d = dst.CreateSubKey(sub, writable: true);
CopyTree(s, d);
}
}
/// <summary>A stable text form of a key's values and subkeys, to tell "still as we wrote it".</summary>
private static string Fingerprint(RegistryKey key)
{
var sb = new StringBuilder();
foreach (string name in key.GetValueNames().OrderBy(n => n, StringComparer.OrdinalIgnoreCase))
{
object? v = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v == null) continue;
RegistryValueKind kind;
try { kind = key.GetValueKind(name); }
catch (IOException) { continue; } // removed between the listing and the read
sb.Append(name.ToLowerInvariant()).Append('=').Append(ValuePrint(kind, v)).Append(';');
}
foreach (string sub in key.GetSubKeyNames().OrderBy(n => n, StringComparer.OrdinalIgnoreCase))
{
using RegistryKey? s = key.OpenSubKey(sub);
if (s != null) sb.Append('[').Append(sub.ToLowerInvariant()).Append(':').Append(Fingerprint(s)).Append(']');
}
return sb.ToString();
}
private static string ValuePrint(RegistryValueKind kind, object v) => kind + ":" + v switch
{
byte[] b => Convert.ToHexString(b),
string[] a => string.Join("\u0001", a),
_ => Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty,
};
// ── registry helpers ─────────────────────────────────────────────────────
private static RegistryKey UserHive() => RegistryKey.OpenBaseKey(RegistryHive.CurrentUser,
Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Default);
private static RegistryKey? OpenUserFilters(bool writable) => UserHive().OpenSubKey(VirtualStoreFiltersSubKey, writable);
private static RegistryKey? OpenMachineFilters() =>
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView).OpenSubKey(DecalFiltersSubKey);
private static bool IsOurs(RegistryKey k) =>
string.Equals(k.GetValue("Object") as string, FilterObject, StringComparison.Ordinal);
private static bool Enabled(RegistryKey k) => k.GetValue("Enabled") is int e && e != 0;
private static void ReadEntry(RegistryKey k, Status s)
{
s.Enabled = Enabled(k);
s.RegisteredPath = k.GetValue("Path") as string;
s.DllPresent = s.RegisteredPath != null && File.Exists(Path.Combine(s.RegisteredPath, AssemblyFile));
}
private static string DescribeFilter(RegistryKey parent, string name)
{
using RegistryKey? k = parent.OpenSubKey(name);
return k?.GetValue("") is string friendly && friendly.Length > 0 ? friendly : name;
}
private static void SetIfDifferent(RegistryKey key, string name, object value, RegistryValueKind kind, List<string> log)
{
object? have = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (have != null && key.GetValueKind(name) == kind && Equals(have, value))
return;
key.SetValue(name, value, kind);
log.Add($"set {(name.Length == 0 ? "(default)" : name)}");
}
private static State? LoadState()
{
try
{
if (!File.Exists(StatePath)) return null;
State? s = JsonSerializer.Deserialize<State>(File.ReadAllText(StatePath));
if (s == null) return null;
// Dictionary comparers don't survive serialization.
s.MirroredKeys = new Dictionary<string, string>(s.MirroredKeys, StringComparer.OrdinalIgnoreCase);
s.MirroredValues = new Dictionary<string, string>(s.MirroredValues, StringComparer.OrdinalIgnoreCase);
return s;
}
catch
{
return null;
}
}
private static void SaveState(State s)
{
string? dir = Path.GetDirectoryName(StatePath);
if (dir != null) Directory.CreateDirectory(dir);
File.WriteAllText(StatePath, JsonSerializer.Serialize(s, new JsonSerializerOptions { WriteIndented = true }));
}
}

View file

@ -14,4 +14,10 @@ internal enum InjectionMode
/// account runs against Decal + UBService + VTank or whatever Decal plugins
/// the user has registered.</summary>
Decal = 1,
/// <summary>Decal first, then RynthCore in the same client ("Decal + RynthCore"). The
/// engine takes chat from Decal through the RynthCore Decal bridge, which the launcher
/// registers for this Windows user before the launch (DecalBridgeRegistration;
/// docs/DECAL_BRIDGE_PLAN.md).</summary>
DecalBridge = 2,
}

View file

@ -0,0 +1,274 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
namespace RynthCore.App;
/// <summary>A registry key copied into memory (also the tests' fake key).</summary>
internal sealed class RegSnapshot : IRegKey
{
public Dictionary<string, object> Values { get; } = new(StringComparer.OrdinalIgnoreCase);
public List<string> SubKeys { get; } = new();
public object? GetValue(string name) => Values.TryGetValue(name, out object? v) ? v : null;
public string[] GetSubKeyNames() => SubKeys.ToArray();
public string[] GetValueNames() => new List<string>(Values.Keys).ToArray();
public void Dispose() { }
public static RegSnapshot? Of(RegistryKey? key)
{
if (key == null) return null;
var s = new RegSnapshot();
foreach (string n in key.GetValueNames())
{
object? v = key.GetValue(n, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v != null) s.Values[n] = v;
}
s.SubKeys.AddRange(key.GetSubKeyNames());
return s;
}
}
/// <summary>The real machine for <see cref="DecalBridgeCheck"/>.</summary>
internal sealed class RealDecalCheckHost : IDecalCheckHost
{
private const int TokenElevation = 20, TokenVirtualizationEnabled = 24;
private static readonly string BridgeEntryMachinePath =
DecalBridgeCheck.MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid;
private readonly RegSnapshot? _ownViewBridgeEntry;
private readonly Dictionary<string, string?> _levels = new(StringComparer.OrdinalIgnoreCase);
public bool Is64BitOs => Environment.Is64BitOperatingSystem;
public bool LauncherElevated { get; }
public bool LauncherVirtualized { get; }
/// <summary>Construct OUTSIDE a <see cref="RealRegistryView"/> scope: it reads the process's own view.</summary>
private RealDecalCheckHost()
{
LauncherElevated = TokenFlag(TokenElevation);
LauncherVirtualized = TokenFlag(TokenVirtualizationEnabled);
try
{
using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default);
using RegistryKey? k = hklm.OpenSubKey(BridgeEntryMachinePath);
_ownViewBridgeEntry = RegSnapshot.Of(k);
}
catch { _ownViewBridgeEntry = null; }
}
/// <summary>Runs the check against this machine. Reads only.</summary>
public static DecalBridgeCheck.Result Check(string bridgeDirectory, string? acClientPath, string? engineJsonPath)
{
var host = new RealDecalCheckHost();
using (RealRegistryView.Enter())
return DecalBridgeCheck.Run(host, bridgeDirectory, acClientPath, engineJsonPath);
}
/// <summary>Only the client-virtualization prediction (registration uses it to pick the key).</summary>
public static bool PredictClientVirtualized(string? acClientPath, out string reason, out bool launcherElevated)
{
var host = new RealDecalCheckHost();
launcherElevated = host.LauncherElevated;
using (RealRegistryView.Enter())
return DecalBridgeCheck.PredictClientVirtualized(host, acClientPath, out reason);
}
public static bool IsProcessElevated() => TokenFlag(TokenElevation);
/// <summary><see cref="DecalBridgeCheck.PlanInstall"/> on this machine.</summary>
public static (bool Machine, bool PerUser) PlanInstall()
{
var host = new RealDecalCheckHost();
using (RealRegistryView.Enter())
return DecalBridgeCheck.PlanInstall(host);
}
public IRegKey? OpenReal(RegRoot root, string subKey)
{
try
{
(RegistryHive hive, RegistryView view) = root switch
{
RegRoot.Machine32 => (RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default),
RegRoot.Machine64 => (RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry64 : RegistryView.Default),
RegRoot.User32 => (RegistryHive.CurrentUser, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default),
_ => (RegistryHive.CurrentUser, Is64BitOs ? RegistryView.Registry64 : RegistryView.Default),
};
using RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, view);
using RegistryKey? k = baseKey.OpenSubKey(subKey);
return RegSnapshot.Of(k);
}
catch
{
return null;
}
}
public IRegKey? OpenOwnViewMachine32(string subKey) =>
string.Equals(subKey, BridgeEntryMachinePath, StringComparison.OrdinalIgnoreCase) ? _ownViewBridgeEntry : null;
public bool FileExists(string path)
{
try { return File.Exists(path); } catch { return false; }
}
public bool HasZoneIdentifier(string path)
{
try { return File.Exists(path + ":Zone.Identifier"); } catch { return false; }
}
/// <summary>Removes the "downloaded from the internet" mark. True if none is left.</summary>
public static bool RemoveZoneIdentifier(string path)
{
try
{
string ads = path + ":Zone.Identifier";
if (File.Exists(ads)) File.Delete(ads);
return !File.Exists(ads);
}
catch { return false; }
}
public Version? AssemblyVersionOf(string path)
{
try { return AssemblyName.GetAssemblyName(path).Version; } catch { return null; }
}
public Version? ReferenceVersionOf(string assemblyPath, string referenceName)
{
try
{
using FileStream fs = File.OpenRead(assemblyPath);
using var pe = new PEReader(fs);
if (!pe.HasMetadata) return null;
MetadataReader md = pe.GetMetadataReader();
foreach (AssemblyReferenceHandle h in md.AssemblyReferences)
{
AssemblyReference r = md.GetAssemblyReference(h);
if (string.Equals(md.GetString(r.Name), referenceName, StringComparison.OrdinalIgnoreCase))
return r.Version;
}
}
catch { }
return null;
}
public string? ExecutionLevelOf(string exePath)
{
if (_levels.TryGetValue(exePath, out string? cached)) return cached;
string? level = null;
try
{
if (File.Exists(exePath))
level = LevelIn(Encoding.UTF8.GetString(File.ReadAllBytes(exePath)));
// An external manifest counts only when the exe has none embedded.
if (level == null && File.Exists(exePath + ".manifest"))
level = LevelIn(File.ReadAllText(exePath + ".manifest"));
}
catch { }
_levels[exePath] = level;
return level;
}
/// <summary>The level="..." of a requestedExecutionLevel element, or null.</summary>
internal static string? LevelIn(string text)
{
int i = text.IndexOf("requestedExecutionLevel", StringComparison.Ordinal);
if (i < 0) return null;
int end = text.IndexOf('>', i);
string element = end > i ? text.Substring(i, end - i) : text.Substring(i, Math.Min(200, text.Length - i));
int l = element.IndexOf("level=", StringComparison.Ordinal);
if (l < 0) return null;
int q = l + 6;
if (q >= element.Length) return null;
char quote = element[q];
int close = element.IndexOf(quote, q + 1);
return close > q ? element.Substring(q + 1, close - q - 1) : null;
}
public string? ReadTextFile(string path)
{
try { return File.Exists(path) ? File.ReadAllText(path) : null; } catch { return null; }
}
private static bool TokenFlag(int infoClass)
{
try
{
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out IntPtr token)) return false;
try
{
int v = 0;
return GetTokenInformation(token, infoClass, ref v, sizeof(int), out _) && v != 0;
}
finally { CloseHandle(token); }
}
catch { return false; }
}
private const uint TOKEN_QUERY = 0x0008;
[DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool GetTokenInformation(IntPtr token, int infoClass, ref int info, int length, out int returned);
}
/// <summary>
/// The launcher has no requestedExecutionLevel in its manifest, so Windows runs it with UAC
/// registry virtualization: its HKLM reads return the per-user VirtualStore copy where one
/// exists, and its HKLM writes land there silently (measured 2026-09-30). Registration and
/// the check have to see (and write) the real HKLM and the real per-user copy, so
/// virtualization is switched off for this process while they run and switched back on
/// after. A process without virtualization (the injector, an elevated launcher) is left alone.
/// </summary>
internal sealed class RealRegistryView : IDisposable
{
private const int TokenVirtualizationEnabled = 24;
private const uint TOKEN_QUERY = 0x0008, TOKEN_ADJUST_DEFAULT = 0x0080;
private IntPtr _token;
public static IDisposable Enter()
{
var scope = new RealRegistryView();
try
{
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_DEFAULT, out IntPtr token))
return scope;
int on = 0;
if (GetTokenInformation(token, TokenVirtualizationEnabled, ref on, sizeof(int), out _) && on != 0)
{
int off = 0;
if (SetTokenInformation(token, TokenVirtualizationEnabled, ref off, sizeof(int)))
{
scope._token = token; // restored in Dispose
return scope;
}
}
CloseHandle(token);
}
catch { }
return scope;
}
public void Dispose()
{
if (_token == IntPtr.Zero) return;
int on = 1;
SetTokenInformation(_token, TokenVirtualizationEnabled, ref on, sizeof(int));
CloseHandle(_token);
_token = IntPtr.Zero;
}
[DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool GetTokenInformation(IntPtr token, int infoClass, ref int info, int length, out int returned);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool SetTokenInformation(IntPtr token, int infoClass, ref int info, int length);
}

View file

@ -0,0 +1,394 @@
// ============================================================================
// RynthCore.DecalBridge - BridgeFilter.cs
//
// A Decal network filter written only against Decal's PUBLIC plugin API
// (Decal.Adapter: FilterBase, CoreManager, WorldFilter, CharacterFilter, HooksWrapper).
// It lets the RynthCore engine run in the same acclient.exe as Decal without the two
// patching the same AC functions ("bridge mode", docs/DECAL_BRIDGE_PLAN.md):
//
// events -> engine: chat lines, chat-bar commands (and eats the engine's own
// commands), login/logoff; optionally object create/release/change and
// raw server messages. The engine says which kinds it wants (want mask).
// commands <- engine: run on AC's main thread through Decal's public API - chat lines
// (InvokeChatParser) and the salvage panel (SalvagePanelAdd/Salvage).
//
// A network filter (not a plugin) so it starts with Decal, before login.
//
// Idle unless RynthCore is in the same client: registering it (the launcher does, for
// "Decal + RynthCore" accounts) makes every Decal client of that Windows user load it,
// but until the RynthCore loader shows up in the process it only counts frames. It never
// blocks, never throws into Decal, and holds nothing of the engine's.
// RYNTHCORE_DECAL_BRIDGE=0 in a client's environment keeps it off entirely.
// ============================================================================
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Decal.Adapter;
using Decal.Adapter.Wrappers;
namespace RynthCore.DecalBridge
{
[FriendlyName("RynthCore Decal Bridge")]
public sealed unsafe class BridgeFilter : FilterBase
{
private const string LogDir = @"C:\Games\RynthCore\Logs";
private const string LoaderModule = "RynthCore.Loader.dll";
private const int ArmCheckEveryFrames = 120; // ~2 s at 60 fps
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr GetModuleHandleW(string name);
private BridgeChannel _ch;
private int _pid;
private bool _disabled;
private bool _worldWired;
private bool _invoking; // true while a command of ours runs InvokeChatParser
private int _frames;
private string[] _prefixes = new string[0];
private int _prefixStamp = -1;
private long _serverMessages;
private int _loggedServer;
private int _loggedChatBar;
private bool _devicePublished;
protected override void Startup()
{
_pid = Process.GetCurrentProcess().Id;
if (Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_BRIDGE") == "0")
{
_disabled = true;
return;
}
try
{
Core.RenderFrame += OnRenderFrame;
TryArm();
}
catch (Exception ex)
{
Log("startup failed: " + ex);
}
}
protected override void Shutdown()
{
if (_disabled)
return;
try
{
Core.RenderFrame -= OnRenderFrame;
if (_ch != null)
{
ServerDispatch -= OnServerDispatch;
Core.ChatBoxMessage -= OnChatBoxMessage;
Core.CommandLineText -= OnCommandLineText;
Core.ItemSelected -= OnItemSelected;
Core.FilterInitComplete -= OnFilterInitComplete;
Core.PluginInitComplete -= OnFilterInitComplete;
}
if (_worldWired)
{
Core.WorldFilter.CreateObject -= OnCreateObject;
Core.WorldFilter.ReleaseObject -= OnReleaseObject;
Core.WorldFilter.ChangeObject -= OnChangeObject;
Core.CharacterFilter.LoginComplete -= OnLoginComplete;
Core.CharacterFilter.Logoff -= OnLogoff;
}
}
catch { }
if (_ch != null)
{
Log("shutdown after " + _serverMessages + " server messages, " +
_ch.ReadLong(BridgeLayout.OffRecords) + " records, " + _ch.ReadLong(BridgeLayout.OffDropped) + " dropped, " +
_ch.ReadLong(BridgeLayout.OffCmdDone) + " commands run");
_ch.WriteInt(BridgeLayout.OffBridgeState, 0);
_ch.Dispose();
_ch = null;
}
}
// Arms once the RynthCore loader is in this client (injected with Decal, or later).
private void TryArm()
{
if (_ch != null || GetModuleHandleW(LoaderModule) == IntPtr.Zero)
return;
BridgeChannel ch = BridgeChannel.OpenOrCreate(_pid);
if (!ch.Valid)
{
Log("mapping has another protocol version (magic 0x" + ch.ReadInt(BridgeLayout.OffMagic).ToString("X8") +
", version " + ch.ReadInt(BridgeLayout.OffVersion) + ", ours " + BridgeLayout.Version +
") - the engine and the bridge are from different builds; staying idle.");
ch.Dispose();
_disabled = true;
return;
}
_ch = ch;
_ch.WriteInt(BridgeLayout.OffBridgePid, _pid);
_ch.WriteString(BridgeRecordKind.Hello, BridgeLayout.Version, 0,
"RynthCore Decal Bridge " + typeof(BridgeFilter).Assembly.GetName().Version + " on " +
Environment.Version + " (" + (IntPtr.Size * 8) + "-bit)");
ServerDispatch += OnServerDispatch;
Core.ChatBoxMessage += OnChatBoxMessage;
Core.CommandLineText += OnCommandLineText;
Core.ItemSelected += OnItemSelected;
// WorldFilter / CharacterFilter exist once Decal's filters are up.
Core.FilterInitComplete += OnFilterInitComplete;
Core.PluginInitComplete += OnFilterInitComplete;
TryWireWorld();
_ch.WriteInt(BridgeLayout.OffBridgeState, 1); // the engine waits for this
Log("armed (RynthCore is in this client); mapping " + BridgeLayout.MappingName(_pid) + ", world wired=" + _worldWired);
}
private void OnFilterInitComplete(object sender, EventArgs e)
{
TryWireWorld();
}
private void TryWireWorld()
{
if (_worldWired) return;
try
{
WorldFilter wf = Core.WorldFilter;
CharacterFilter cf = Core.CharacterFilter;
if (wf == null || cf == null) return;
wf.CreateObject += OnCreateObject;
wf.ReleaseObject += OnReleaseObject;
wf.ChangeObject += OnChangeObject;
cf.LoginComplete += OnLoginComplete;
cf.Logoff += OnLogoff;
_worldWired = true;
Log("WorldFilter and CharacterFilter wired (Decal's world filters are up).");
}
catch (Exception ex)
{
Log("wiring WorldFilter failed: " + ex.Message);
}
}
// ── once per frame, AC's main thread ─────────────────────────────────
private void OnRenderFrame(object sender, EventArgs e)
{
try
{
if (_disabled)
return;
if (_ch == null)
{
if (++_frames % ArmCheckEveryFrames == 0)
TryArm();
return;
}
if (!_devicePublished)
PublishDevice();
if (_ch.HasCommands)
_ch.DrainCommands(RunCommand, 64);
ServeReplay();
}
catch (Exception ex)
{
Log("frame handler failed: " + ex.Message);
}
}
// The device Decal renders with, through Decal's public IDecalCore.GetD3DDevice: an
// address for the engine to read (its vtable says whether Decal wraps AC's device).
// No reference is kept and nothing is called on it here.
private void PublishDevice()
{
_devicePublished = true;
try
{
Guid iid = new Guid("D0223B96-BF7A-43FD-92BD-A43B0D82B9EB"); // IID_IDirect3DDevice9
object dev = Core.Decal.Underlying.GetD3DDevice(ref iid);
if (dev == null) { Log("GetD3DDevice returned null"); return; }
IntPtr unk = Marshal.GetIUnknownForObject(dev);
IntPtr d3d;
int hr = Marshal.QueryInterface(unk, ref iid, out d3d);
if (hr >= 0 && d3d != IntPtr.Zero)
{
_ch.WriteInt(BridgeLayout.OffD3DDevice, d3d.ToInt32());
Marshal.Release(d3d);
}
Marshal.Release(unk);
Marshal.ReleaseComObject(dev);
_ch.WriteInt(BridgeLayout.OffDecalHwnd, Core.Decal.Hwnd.ToInt32());
Log("Decal's D3D device 0x" + _ch.ReadInt(BridgeLayout.OffD3DDevice).ToString("X8") + " (QI hr=0x" + hr.ToString("X8") +
"), hwnd 0x" + Core.Decal.Hwnd.ToInt32().ToString("X"));
}
catch (Exception ex)
{
Log("GetD3DDevice failed: " + ex.GetType().Name + ": " + ex.Message);
}
}
// An engine generation that takes objects from the bridge starts with none (a hot
// reload, or an engine injected late): it bumps the replay request.
private void ServeReplay()
{
int want = _ch.ReadInt(BridgeLayout.OffReplayRequest);
if (want == 0 || want == _ch.ReadInt(BridgeLayout.OffReplayDone) || !_worldWired)
return;
int n = 0;
if (_ch.Wants(BridgeRecordKind.CreateObject))
{
foreach (WorldObject o in Core.WorldFilter.GetAll())
{
_ch.Write(BridgeRecordKind.CreateObject, unchecked((uint)o.Id), 1, null, 0);
n++;
}
}
_ch.WriteInt(BridgeLayout.OffReplayDone, want);
Log("replayed " + n + " world objects for engine request " + want);
}
private void RunCommand(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int len)
{
string failure = null;
try
{
switch (kind)
{
case BridgeRecordKind.CmdInvokeChatParser:
string line = len >= 2 ? new string((char*)payload, 0, len / 2) : string.Empty;
_invoking = true;
try { Core.Actions.InvokeChatParser(line); }
finally { _invoking = false; }
break;
case BridgeRecordKind.CmdSalvagePanelAdd:
Core.Actions.SalvagePanelAdd(unchecked((int)arg0));
break;
case BridgeRecordKind.CmdSalvagePanelSalvage:
Core.Actions.SalvagePanelSalvage();
break;
default:
failure = "unknown command " + (int)kind;
break;
}
}
catch (Exception ex)
{
failure = ex.GetType().Name + ": " + ex.Message;
}
if (failure != null)
{
Log("command " + kind + " failed: " + failure);
_ch.WriteString(BridgeRecordKind.CommandResult, (uint)kind, 0, failure);
}
}
// ── forwarders (AC's main thread; never block, never throw) ──────────
private void OnServerDispatch(object sender, NetworkMessageEventArgs e)
{
try
{
_serverMessages++;
if (!_ch.Wants(BridgeRecordKind.ServerMessage))
return; // the engine reads these from its own hooks: don't copy them
Message m = e.Message;
byte[] raw = m.RawData;
if (_loggedServer < 4)
{
_loggedServer++;
Log("server message type=0x" + m.Type.ToString("X4") + " len=" + (raw == null ? 0 : raw.Length));
}
_ch.WriteBytes(BridgeRecordKind.ServerMessage, unchecked((uint)m.Type), 0, raw);
}
catch { }
}
private void OnChatBoxMessage(object sender, ChatTextInterceptEventArgs e)
{
try { _ch.WriteString(BridgeRecordKind.ChatText, unchecked((uint)e.Color), unchecked((uint)e.Target), e.Text); }
catch { }
}
private void OnCommandLineText(object sender, ChatParserInterceptEventArgs e)
{
try
{
// A line the engine sent through InvokeChatParser: it already went through the
// engine's own dispatch; let Decal and AC have it.
if (_invoking)
return;
string text = e.Text ?? string.Empty;
// The engine's commands (and its plugins') must not reach the server: eat the
// lines whose prefix the engine published; forward every line either way.
bool eat = MatchesPrefix(text);
if (eat) e.Eat = true;
if (_loggedChatBar < 10)
{
_loggedChatBar++;
Log("chat bar: '" + text + "' eaten=" + eat);
}
_ch.WriteString(BridgeRecordKind.ChatBarEnter, eat ? 1u : 0u, 0, text);
}
catch { }
}
private void OnItemSelected(object sender, ItemSelectedEventArgs e)
{
try { _ch.Write(BridgeRecordKind.ItemSelected, unchecked((uint)e.ItemGuid), 0, null, 0); } catch { }
}
private void OnCreateObject(object sender, CreateObjectEventArgs e)
{
try { _ch.Write(BridgeRecordKind.CreateObject, unchecked((uint)e.New.Id), 0, null, 0); } catch { }
}
private void OnReleaseObject(object sender, ReleaseObjectEventArgs e)
{
try { _ch.Write(BridgeRecordKind.ReleaseObject, unchecked((uint)e.Released.Id), 0, null, 0); } catch { }
}
private void OnChangeObject(object sender, ChangeObjectEventArgs e)
{
try { _ch.Write(BridgeRecordKind.ChangeObject, unchecked((uint)e.Changed.Id), (uint)e.Change, null, 0); } catch { }
}
private void OnLoginComplete(object sender, EventArgs e)
{
try { _ch.Write(BridgeRecordKind.LoginComplete, unchecked((uint)Core.CharacterFilter.Id), 0, null, 0); } catch { }
}
private void OnLogoff(object sender, LogoffEventArgs e)
{
try { _ch.Write(BridgeRecordKind.Logoff, (uint)e.Type, 0, null, 0); } catch { }
}
// ── helpers ────────────────────────────────────────────────────────────
private bool MatchesPrefix(string text)
{
if (_ch.ReadInt(BridgeLayout.OffEngineAttached) == 0)
return false; // no engine to run it: let AC have the line
// The engine rewrites the prefix list when it attaches; re-read it when it changes.
int gen = _ch.ReadInt(BridgeLayout.OffEngineGeneration);
if (gen != _prefixStamp)
{
_prefixStamp = gen;
char* p = (char*)(_ch.Header + BridgeLayout.OffPrefixes);
int n = 0;
while (n < BridgeLayout.PrefixChars && p[n] != '\0') n++;
_prefixes = new string(p, 0, n).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
}
foreach (string pre in _prefixes)
{
if (text.StartsWith(pre, StringComparison.OrdinalIgnoreCase) &&
(text.Length == pre.Length || text[pre.Length] == ' '))
return true;
}
return false;
}
private void Log(string msg)
{
try
{
File.AppendAllText(System.IO.Path.Combine(LogDir, "DecalBridge." + _pid + ".log"),
"[" + DateTime.Now.ToString("HH:mm:ss.fff") + "] " + msg + Environment.NewLine);
}
catch { }
}
}
}

View file

@ -0,0 +1,302 @@
// ============================================================================
// RynthCore.DecalBridge - BridgeProtocol.cs
//
// The in-process channel between the Decal bridge filter (.NET Framework, Decal's
// desktop CLR) and the RynthCore engine (CoreCLR, unloadable). Compiled into BOTH
// assemblies (the engine links this file), so it stays C# 9 / net48-compatible.
// docs/DECAL_BRIDGE_PLAN.md has the design.
//
// A named, pagefile-backed file mapping holds a header and two single-producer /
// single-consumer byte rings:
// event ring (bridge -> engine): producer = the bridge, on AC's main thread (Decal
// raises its events there); consumer = the engine's plugin pump thread.
// command ring (engine -> bridge): producer = the engine (any thread, serialised by
// the engine); consumer = the bridge, on AC's main thread (RenderFrame),
// which runs each command through Decal's public API.
// Nothing crosses the runtimes but bytes: no function pointer, delegate or COM object
// is ever handed from one runtime to the other. That is what makes it safe with the
// unloadable engine - a generation that goes away leaves nothing behind that the
// bridge could call into, and neither side ever blocks on the other (a full ring
// drops the record and counts it). The mapping lives as long as either side holds it,
// so the read positions survive an engine hot reload.
//
// The engine publishes which event kinds it wants (OffWantMask); the bridge writes
// only those, so a stream the engine takes from its own hooks costs Decal nothing.
//
// Record: [int length (multiple of 4, header included)][ushort kind][ushort pad bytes]
// [uint arg0][uint arg1][payload...]
// Write/read positions are monotonic byte counts (64-bit, Interlocked on x86).
//
// Version 2 (2026-09-30): want mask, command ring, bridge hello/state fields.
// ============================================================================
#nullable disable
using System;
using System.IO.MemoryMappedFiles;
using System.Threading;
namespace RynthCore.DecalBridge
{
internal enum BridgeRecordKind : ushort
{
Pad = 0,
// ── events, bridge -> engine ──
Hello = 1, // arg0 = protocol version, payload = UTF-16 bridge description (always written)
ChatText = 2, // arg0 = Decal ChatBoxMessage.Color (AC chat type), arg1 = Target, payload = UTF-16 text
ChatBarEnter = 3, // arg0 = 1 when the bridge ate the line, payload = UTF-16 text
CreateObject = 4, // arg0 = object id, arg1 = 1 when part of a replay (WorldFilter.GetAll)
ReleaseObject = 5, // arg0 = object id
ChangeObject = 6, // arg0 = object id, arg1 = WorldChangeType
ServerMessage = 7, // arg0 = message type (opcode), payload = Message.RawData
LoginComplete = 8, // arg0 = character id
Logoff = 9, // arg0 = LogoffEventType
ItemSelected = 10, // arg0 = object id
CommandResult = 11, // arg0 = command kind, arg1 = 1 ok / 0 failed, payload = UTF-16 detail (failures only)
// ── commands, engine -> bridge (run on AC's main thread through Decal's public API) ──
CmdInvokeChatParser = 100, // payload = UTF-16 line -> Actions.InvokeChatParser
CmdSalvagePanelAdd = 101, // arg0 = item id -> Actions.SalvagePanelAdd
CmdSalvagePanelSalvage = 102,// -> Actions.SalvagePanelSalvage
}
internal static unsafe class BridgeLayout
{
public const uint Magic = 0x42444352; // "RCDB"
public const int Version = 2;
public const int HeaderSize = 4096;
public const int CommandRingSize = 64 * 1024;
public const int EventRingSize = 16 * 1024 * 1024;
public const int TotalSize = HeaderSize + CommandRingSize + EventRingSize;
public const int RecordHeaderSize = 16;
public const int MaxRecord = 256 * 1024;
// Header offsets.
public const int OffMagic = 0;
public const int OffVersion = 4;
public const int OffBridgeState = 8; // 1 while a bridge is started (its "hello")
public const int OffBridgeBeats = 12; // bridge: bumped per record written
public const int OffWritePos = 16; // long, event ring, producer-owned
public const int OffReadPos = 24; // long, event ring, consumer-owned
public const int OffDropped = 32; // long, event records the bridge dropped (ring full)
public const int OffRecords = 40; // long, event records written
public const int OffEngineAttached = 48; // 1 while an engine generation drains
public const int OffEngineGeneration = 52;
public const int OffBridgePid = 56;
public const int OffReplayRequest = 60; // engine -> bridge: bump to get WorldFilter.GetAll() as CreateObject records
public const int OffReplayDone = 64; // bridge -> engine: the request value last served
public const int OffWantMask = 68; // engine -> bridge: bit (1 << kind) for each event kind to forward
public const int OffCmdWritePos = 72; // long, command ring, engine-owned
public const int OffCmdReadPos = 80; // long, command ring, bridge-owned
public const int OffCmdDropped = 88; // long, commands the engine dropped (ring full)
public const int OffCmdDone = 96; // long, commands the bridge ran
// Added in v2 without a version bump (zero from an older bridge = unknown):
public const int OffD3DDevice = 104; // bridge -> engine: IDirect3DDevice9* Decal renders with (IDecalCore.GetD3DDevice), 0 = unknown
public const int OffDecalHwnd = 108; // bridge -> engine: the game window as Decal knows it
public const int OffPrefixes = 256; // engine -> bridge: ';'-separated chat prefixes to eat, UTF-16, 0-terminated
public const int PrefixChars = 1024;
public static string MappingName(int pid) { return "Local\\RynthCore.DecalBridge.p" + pid; }
public static int Align4(int n) { return (n + 3) & ~3; }
public static uint Bit(BridgeRecordKind kind) { return (uint)kind < 32 ? 1u << (int)kind : 0u; }
}
/// <summary>One side's view of the mapping (the bridge and the engine each open their own).</summary>
internal sealed unsafe class BridgeChannel : IDisposable
{
private MemoryMappedFile _file;
private MemoryMappedViewAccessor _view;
private byte* _base;
public byte* Header { get { return _base; } }
private byte* CommandRing { get { return _base + BridgeLayout.HeaderSize; } }
private byte* EventRing { get { return _base + BridgeLayout.HeaderSize + BridgeLayout.CommandRingSize; } }
public static BridgeChannel OpenOrCreate(int pid)
{
var c = new BridgeChannel();
c._file = MemoryMappedFile.CreateOrOpen(BridgeLayout.MappingName(pid), BridgeLayout.TotalSize);
c._view = c._file.CreateViewAccessor(0, BridgeLayout.TotalSize);
byte* p = null;
c._view.SafeMemoryMappedViewHandle.AcquirePointer(ref p);
c._base = p + c._view.PointerOffset;
// The first opener stamps the header; the pages start zeroed either way.
Interlocked.CompareExchange(ref *(int*)(c._base + BridgeLayout.OffVersion), BridgeLayout.Version, 0);
Interlocked.CompareExchange(ref *(int*)(c._base + BridgeLayout.OffMagic), unchecked((int)BridgeLayout.Magic), 0);
return c;
}
/// <summary>True when some side already created the mapping for <paramref name="pid"/>.</summary>
public static bool Exists(int pid)
{
try
{
using (MemoryMappedFile f = MemoryMappedFile.OpenExisting(BridgeLayout.MappingName(pid)))
return true;
}
catch
{
return false;
}
}
public int ReadInt(int off) { return Volatile.Read(ref *(int*)(_base + off)); }
public void WriteInt(int off, int v) { Volatile.Write(ref *(int*)(_base + off), v); }
public long ReadLong(int off) { return Interlocked.Read(ref *(long*)(_base + off)); }
public void WriteLong(int off, long v) { Interlocked.Exchange(ref *(long*)(_base + off), v); }
public void AddLong(int off, long v) { Interlocked.Add(ref *(long*)(_base + off), v); }
public bool Valid { get { return (uint)ReadInt(BridgeLayout.OffMagic) == BridgeLayout.Magic && ReadInt(BridgeLayout.OffVersion) == BridgeLayout.Version; } }
/// <summary>Whether the engine asked for <paramref name="kind"/> (Hello always goes).</summary>
public bool Wants(BridgeRecordKind kind)
{
return kind == BridgeRecordKind.Hello || (unchecked((uint)ReadInt(BridgeLayout.OffWantMask)) & BridgeLayout.Bit(kind)) != 0;
}
// ── event ring (bridge -> engine) ─────────────────────────────────────
public bool Write(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen)
{
if (!Wants(kind))
return false;
bool ok = Put(EventRing, BridgeLayout.EventRingSize, BridgeLayout.OffWritePos, BridgeLayout.OffReadPos,
BridgeLayout.OffDropped, kind, arg0, arg1, payload, payloadLen);
if (ok)
{
AddLong(BridgeLayout.OffRecords, 1);
Interlocked.Increment(ref *(int*)(_base + BridgeLayout.OffBridgeBeats));
}
return ok;
}
public bool WriteString(BridgeRecordKind kind, uint arg0, uint arg1, string text)
{
if (text == null) text = string.Empty;
fixed (char* c = text)
return Write(kind, arg0, arg1, (byte*)c, text.Length * 2);
}
public bool WriteBytes(BridgeRecordKind kind, uint arg0, uint arg1, byte[] data)
{
if (data == null || data.Length == 0)
return Write(kind, arg0, arg1, null, 0);
fixed (byte* b = data)
return Write(kind, arg0, arg1, b, data.Length);
}
public delegate void RecordHandler(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen);
/// <summary>Hands every event written so far to <paramref name="handler"/> (payload valid only during the call).</summary>
public int Drain(RecordHandler handler, int maxRecords)
{
return Take(EventRing, BridgeLayout.EventRingSize, BridgeLayout.OffWritePos, BridgeLayout.OffReadPos, handler, maxRecords);
}
// ── command ring (engine -> bridge) ───────────────────────────────────
/// <summary>Queues a command for the bridge. One producer at a time (the engine serialises).</summary>
public bool WriteCommand(BridgeRecordKind kind, uint arg0, uint arg1, string text)
{
if (text == null)
return Put(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos,
BridgeLayout.OffCmdDropped, kind, arg0, arg1, null, 0);
fixed (char* c = text)
return Put(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos,
BridgeLayout.OffCmdDropped, kind, arg0, arg1, (byte*)c, text.Length * 2);
}
/// <summary>Bridge: runs every queued command through <paramref name="handler"/>.</summary>
public int DrainCommands(RecordHandler handler, int maxRecords)
{
int n = Take(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos, handler, maxRecords);
if (n > 0) AddLong(BridgeLayout.OffCmdDone, n);
return n;
}
public bool HasCommands { get { return ReadLong(BridgeLayout.OffCmdWritePos) != ReadLong(BridgeLayout.OffCmdReadPos); } }
// ── ring primitives ───────────────────────────────────────────────────
private bool Put(byte* ring, int size, int offWrite, int offRead, int offDropped,
BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen)
{
if (payloadLen < 0 || payloadLen > BridgeLayout.MaxRecord || payloadLen > size / 4)
{
AddLong(offDropped, 1);
return false;
}
int recLen = BridgeLayout.Align4(BridgeLayout.RecordHeaderSize + payloadLen);
long w = ReadLong(offWrite);
long r = ReadLong(offRead);
int pos = (int)(w % size);
int tail = size - pos;
int need = recLen + (tail < recLen ? tail : 0);
if (need > size - (w - r))
{
AddLong(offDropped, 1);
return false;
}
if (tail < recLen)
{
// Doesn't fit before the end: pad to the end, start again at 0. A tail shorter
// than a record header is skipped by the reader without being read.
if (tail >= BridgeLayout.RecordHeaderSize)
{
*(int*)(ring + pos) = tail;
*(ushort*)(ring + pos + 4) = (ushort)BridgeRecordKind.Pad;
}
pos = 0;
}
byte* rec = ring + pos;
*(int*)rec = recLen;
*(ushort*)(rec + 4) = (ushort)kind;
*(ushort*)(rec + 6) = (ushort)(recLen - BridgeLayout.RecordHeaderSize - payloadLen); // pad bytes
*(uint*)(rec + 8) = arg0;
*(uint*)(rec + 12) = arg1;
for (int i = 0; i < payloadLen; i++)
rec[BridgeLayout.RecordHeaderSize + i] = payload[i];
WriteLong(offWrite, w + need); // publish (full fence)
return true;
}
private int Take(byte* ring, int size, int offWrite, int offRead, RecordHandler handler, int maxRecords)
{
long r = ReadLong(offRead);
long w = ReadLong(offWrite);
int n = 0;
while (r < w && n < maxRecords)
{
int pos = (int)(r % size);
int tail = size - pos;
if (tail < BridgeLayout.RecordHeaderSize) { r += tail; continue; }
int len = *(int*)(ring + pos);
if (len < BridgeLayout.RecordHeaderSize || len > tail || (len & 3) != 0)
{
r = w; // corrupt: resynchronise at the writer
break;
}
var kind = (BridgeRecordKind)(*(ushort*)(ring + pos + 4));
if (kind != BridgeRecordKind.Pad)
{
int pad = *(ushort*)(ring + pos + 6) & 3;
handler(kind, *(uint*)(ring + pos + 8), *(uint*)(ring + pos + 12),
ring + pos + BridgeLayout.RecordHeaderSize, len - BridgeLayout.RecordHeaderSize - pad);
n++;
}
r += len;
}
WriteLong(offRead, r);
return n;
}
public void Dispose()
{
if (_view != null)
{
if (_base != null) _view.SafeMemoryMappedViewHandle.ReleasePointer();
_view.Dispose();
_view = null;
}
_base = null;
if (_file != null) { _file.Dispose(); _file = null; }
}
}
}

View file

@ -0,0 +1,71 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
RynthCore Decal Bridge: a Decal network filter that lets the RynthCore engine run in
the same acclient.exe as Decal (docs/DECAL_BRIDGE_PLAN.md).
net48 / x86: it loads into Decal's desktop CLR inside the 32-bit client. Built only
against Decal's public reference assemblies (Decal.Adapter and the interop PIAs it
exposes in its signatures), never shipped with them (Private=false).
dotnet build -c Release (also part of RynthCore.sln)
Needs Decal installed (default C:\Program Files (x86)\Decal 3.0, or -p:DecalDir=...).
Without it the project builds nothing useful: a warning, and an empty assembly under
bin\<Configuration>-NoDecal\ (never the real output folder), so a machine without
Decal can still build the whole solution.
-->
<PropertyGroup>
<TargetFramework>net48</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<Platforms>AnyCPU;x86</Platforms>
<OutputType>Library</OutputType>
<AssemblyName>RynthCore.DecalBridge</AssemblyName>
<RootNamespace>RynthCore.DecalBridge</RootNamespace>
<LangVersion>9.0</LangVersion>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
<Deterministic>true</Deterministic>
<Version>0.2.0</Version>
<DecalDir Condition="'$(DecalDir)' == ''">C:\Program Files (x86)\Decal 3.0</DecalDir>
<DecalAvailable Condition="Exists('$(DecalDir)\Decal.Adapter.dll')">true</DecalAvailable>
<OutputPath>bin\$(Configuration)\</OutputPath>
<OutputPath Condition="'$(DecalAvailable)' != 'true'">bin\$(Configuration)-NoDecal\</OutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
</ItemGroup>
<ItemGroup Condition="'$(DecalAvailable)' == 'true'">
<Reference Include="Decal.Adapter">
<HintPath>$(DecalDir)\Decal.Adapter.dll</HintPath>
<Private>false</Private>
</Reference>
<!-- Public interop assemblies that appear in Decal.Adapter's own signatures. -->
<Reference Include="Decal.Interop.Core"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Core.DLL</HintPath><Private>false</Private></Reference>
<Reference Include="Decal.Interop.Filters"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Filters.DLL</HintPath><Private>false</Private></Reference>
<Reference Include="Decal.Interop.Net"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Net.DLL</HintPath><Private>false</Private></Reference>
<Reference Include="Decal.Interop.Inject"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Inject.dll</HintPath><Private>false</Private></Reference>
<Reference Include="Decal.Interop.D3DService"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.D3DService.DLL</HintPath><Private>false</Private></Reference>
<Reference Include="Decal.Interop.Render"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Render.DLL</HintPath><Private>false</Private></Reference>
<Reference Include="System.Drawing" />
</ItemGroup>
<ItemGroup Condition="'$(DecalAvailable)' != 'true'">
<Compile Remove="**\*.cs" />
</ItemGroup>
<Target Name="WarnNoDecal" BeforeTargets="CoreCompile" Condition="'$(DecalAvailable)' != 'true' and '$(RequireDecal)' != 'true'">
<Warning Text="RynthCore.DecalBridge: Decal.Adapter.dll not found in '$(DecalDir)' - the Decal bridge is not built (install Decal or pass -p:DecalDir=...)." />
</Target>
<!-- Release builds (installer\Build-Installer.ps1) pass -p:RequireDecal=true: no Decal, no build. -->
<Target Name="RequireDecal" BeforeTargets="BeforeBuild" Condition="'$(RequireDecal)' == 'true' and '$(DecalAvailable)' != 'true'">
<Error Text="RynthCore.DecalBridge: Decal.Adapter.dll not found in '$(DecalDir)'. The release ships the Decal bridge, so it must be built against Decal's reference assemblies: install Decal 3.0 or pass -p:DecalDir=..." />
</Target>
</Project>

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-2021 Phosphor Icons
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Binary file not shown.

View file

@ -106,6 +106,46 @@ internal static class AcMainThreadQueue
// class. Carries the 5 hold-flags packed into A (bit0=shift, bit1=W,
// bit2=X, bit3=Z, bit4=C).
LaunchJumpWithMotion,
// v70 WieldItem: CM_Inventory::Event_GetAndWieldItem (the 0x001A GetAndWieldItem
// game action) is an inventory send like GiveObjectTo, so it runs here too.
WieldItem,
// v72 player-to-player trade: CM_Trade::Event_* / ClientTradeSystem::Accept/DeclineTrade
// send trade game actions (and Accept/Decline touch the client's Trade object), so they
// run here too. A = PlayerTrade.TradeOp, B/C = its arguments.
Trade,
// Salvage panel marshalled 2026-09-29: CM_Inventory::SendNotice_OpenSalvagePanel,
// gmSalvageUI::AddNewItem and gmSalvageUI::Salvage were called straight from
// the plugin pump (RynthAi SalvageManager, Meta expressions). AddNewItem and
// Salvage are thiscall on the live gmSalvageUI and mutate its UIElement tree
// (same class as the SetSelectedObject 0x60D1D AV). A = toolId / itemId.
// The instance pointer is NOT carried: the drain re-enters the helper, which
// re-reads SalvageHooks.GmSalvageUIInstance on the main thread.
SalvageOpen,
SalvageAddItem,
SalvageExecute,
// CancelAttack marshalled 2026-09-29: CM_Combat::Event_CancelAttack (0x1B7) is
// the same CM_Combat game-action sender class as Melee/Missile/ChangeCombatMode
// but was called straight from the plugin pump. It rides the RING (not a side
// queue) on purpose: every RynthAi caller pairs it with ring actions
// (StopCompletely, ChangeCombatMode, MoveItemInternal) and it must land after
// any attack already queued, so FIFO order with those is what matters. When a
// gesture defers the ring, the paired actions wait too, so the teardown stays
// one ordered group.
CancelAttack,
// SetAutonomyLevel marshalled 2026-09-29: CM_Movement::Event_AutonomyLevel
// (0xF752 game-action send) is exported to plugins as SetAutonomyLevelFn and
// was the only movement sender still called straight from the plugin pump.
// Rides the ring beside DoMovement/StopMovement/Jump so it stays ordered with
// them. A = level.
SetAutonomyLevel,
// DropItem (2026-09-30, Inventory panel): CM_Inventory::Event_DropItem (0x001B game
// action) is an inventory send like WieldItem / GiveObjectTo. A = item id.
DropItem,
// Skills panel raises (2026-09-30): CM_Train::Event_TrainAttribute / _TrainAttribute2nd /
// _TrainSkill send the RaiseAttribute / RaiseVital / RaiseSkill game actions. A game-action
// send like Trade, so it rides the ring too. A = PlayerTraining.TrainKind, B = stype, C = XP
// (skill credits for TrainKind.TrainWithCredits: Event_TrainSkillAdvancementClass, 0x0047).
Train,
}
// Four payload slots cover every routed action (the 4th was added for
@ -167,6 +207,9 @@ internal static class AcMainThreadQueue
Enqueue(ActionKind.MissileAttack, targetId, unchecked((uint)attackHeight),
BitConverter.SingleToUInt32Bits(accuracyLevel));
public static bool EnqueueCancelAttack() =>
Enqueue(ActionKind.CancelAttack, 0, 0, 0);
public static bool EnqueueDoMovement(uint motion, float speed, int holdKey) =>
Enqueue(ActionKind.DoMovement, motion, unchecked((uint)holdKey),
BitConverter.SingleToUInt32Bits(speed));
@ -183,12 +226,82 @@ internal static class AcMainThreadQueue
public static bool EnqueueStopCompletely() =>
Enqueue(ActionKind.StopCompletely, 0, 0, 0);
// ── Direct-heading slot (coalesced, latest value wins) ──────────────────────
// PlayerPhysicsHooks.SetPlayerHeadingDirect snaps the player's CPhysicsObj
// orientation quaternion with two raw stores (qw, then qz). Plugins call it
// (Host.TurnToHeading) from the pump thread on every nav tick; run there it
// raced AC's own physics integration and could leave a torn, non-unit
// quaternion (new qw with old qz). Off-thread callers now park the heading
// here and Drain applies it on the main thread. One slot, not a ring entry:
// nav re-issues the heading every tick and only the newest one matters, so a
// steering bot can never fill the action ring with headings. Lock-free and
// allocation-free; never drops (a newer heading simply replaces an older one).
// Deliberately NOT ActionKind.TurnToHeading: that dispatches the gradual
// CommandInterpreter turn, which would change the steering behaviour.
private static int _directHeadingPending;
private static uint _directHeadingBits;
public static bool EnqueueDirectHeading(float headingDegrees)
{
Volatile.Write(ref _directHeadingBits, BitConverter.SingleToUInt32Bits(headingDegrees));
Volatile.Write(ref _directHeadingPending, 1);
return true;
}
// Main thread only (from Drain). Same order as the pre-queue code: the direct
// snap first, the CommandInterpreter turn only when there is no player.
private static void DrainDirectHeading()
{
if (Interlocked.Exchange(ref _directHeadingPending, 0) == 0) return;
float heading = BitConverter.UInt32BitsToSingle(Volatile.Read(ref _directHeadingBits));
try
{
if (!PlayerPhysicsHooks.SetPlayerHeadingDirect(heading))
CommandInterpreterHooks.TurnToHeading(heading);
}
catch { }
}
// ── Overlay click-to-select slot (coalesced, latest click wins) ─────────────
// A click on a Radar dot or a monster nameplate (ImGui overlays, 2026-09-30)
// parks the object id here; Drain runs ClientHelperHooks.SelectFromOverlay on
// the main thread, which re-checks that the object still exists and that the
// client isn't portaling or logging out right before AC's SetSelectedObject.
// The faces always park here (never select inside the ImGui frame build), so
// the select runs in the same main-thread phase as every other queued action.
// One slot, not a ring entry: a click is one select, two clicks in one frame
// collapse to the newer one, and the slot sits before the ring's gesture
// defer (a selection is a UI change, not a motion; a click in the 3D world
// selects mid-gesture too). Lock-free and allocation-free.
private static int _overlaySelectPending;
private static uint _overlaySelectId;
public static bool EnqueueOverlaySelect(uint objectId)
{
if (objectId == 0) return false;
Volatile.Write(ref _overlaySelectId, objectId);
Volatile.Write(ref _overlaySelectPending, 1);
return true;
}
// Main thread only (from Drain).
private static void DrainOverlaySelect()
{
if (Interlocked.Exchange(ref _overlaySelectPending, 0) == 0) return;
uint id = Volatile.Read(ref _overlaySelectId);
try { ClientHelperHooks.SelectFromOverlay(id); }
catch { }
}
public static bool EnqueueSetMotion(uint motion, bool enabled) =>
Enqueue(ActionKind.SetMotion, motion, enabled ? 1u : 0u, 0);
public static bool EnqueueJump(float extent) =>
Enqueue(ActionKind.Jump, BitConverter.SingleToUInt32Bits(extent), 0, 0);
public static bool EnqueueSetAutonomyLevel(uint level) =>
Enqueue(ActionKind.SetAutonomyLevel, level, 0, 0);
public static bool EnqueueUseObject(uint objectId) =>
Enqueue(ActionKind.UseObject, objectId, 0, 0);
@ -213,6 +326,27 @@ internal static class AcMainThreadQueue
public static bool EnqueueGiveObjectTo(uint objectId, uint targetId, int amount) =>
Enqueue(ActionKind.GiveObjectTo, objectId, targetId, unchecked((uint)amount));
public static bool EnqueueWieldItem(uint objectId, uint equipMask) =>
Enqueue(ActionKind.WieldItem, objectId, equipMask, 0);
public static bool EnqueueDropItem(uint objectId) =>
Enqueue(ActionKind.DropItem, objectId, 0, 0);
public static bool EnqueueTrade(uint op, uint a, uint b) =>
Enqueue(ActionKind.Trade, op, a, b);
public static bool EnqueueTrain(uint kind, uint stype, uint xp) =>
Enqueue(ActionKind.Train, kind, stype, xp);
public static bool EnqueueSalvageOpen(uint toolId) =>
Enqueue(ActionKind.SalvageOpen, toolId, 0, 0);
public static bool EnqueueSalvageAddItem(uint itemId) =>
Enqueue(ActionKind.SalvageAddItem, itemId, 0, 0);
public static bool EnqueueSalvageExecute() =>
Enqueue(ActionKind.SalvageExecute, 0, 0, 0);
public static bool EnqueueSetSelectedObject(uint objectId) =>
Enqueue(ActionKind.SetSelectedObject, objectId, 0, 0);
@ -243,6 +377,9 @@ internal static class AcMainThreadQueue
/// <summary>Stop executing queued actions/casts permanently (engine teardown).</summary>
public static void Disarm() => _disarmed = true;
/// <summary>Engine teardown has begun (ChatCallbackHooks stops holding chat).</summary>
public static bool IsDisarmed => _disarmed;
// Single-consumer drain on AC's main thread (EngineFrameController.OnEndScene).
// Re-invokes the public action methods; on the main thread they execute the
// real AC call directly (their IsOnMainThread gate is satisfied here).
@ -254,7 +391,25 @@ internal static class AcMainThreadQueue
public static void Drain()
{
if (_disarmed) return;
if (_disarmed)
{
// Held incoming chat still prints during teardown (the AddTextToScroll detour
// stays live until MH_DisableHook(ALL)): it is AC's own line, not a plugin action.
try { ChatCallbackHooks.OnMainThreadDrain(disarmed: true); } catch { }
return;
}
// We are on AC's main thread by definition. Latch it here too: after a hot
// reload the first SmartBox/combat detour (the other latches) can come well
// after the first drain, and until the latch is set every dispatch below
// thinks it's off-thread and re-queues itself. A chat command a plugin queued
// straight after the reload then spun the main thread forever
// (DrainChatCommands -> Dispatch -> EnqueueChatCommand, 2026-09-29).
MainThreadGuard.RecordIfFirst();
// Incoming chat held for the plugins' verdict prints first, before anything below
// writes its own lines, so the chat window keeps the order lines arrived in.
try { ChatCallbackHooks.OnMainThreadDrain(disarmed: false); } catch { }
// Deep-audit finding #22 (2026-06-18): these three queues are
// documented as deliberately separate from the gesture-gated action
@ -268,12 +423,27 @@ internal static class AcMainThreadQueue
DrainChat();
DrainChatCommands();
DrainRequestIds();
DrainQueryHealth();
// Vendor buy/sell: a packet send through the client's own SendShopEvent, not a
// motion, so it sits with the non-gesture queues above. Also polls whether the
// vendor window is still open. Idle fast path when no vendor is open.
try { VendorTrade.MainThreadTick(); } catch { }
// Char-select service: publishes the UIFlow mode, runs a pending auto-login
// LogOnCharacter request and snapshots the native character list (throttled).
// Pre-login this runs from the Client::UseTime drain (EndScene is not hooked
// until after login). Idle in the world.
try { CharacterManagementHooks.MainThreadTick(); } catch { }
int head = _head; // only the main thread writes _head
// Plugin heading snap (coalesced slot). Before the ring and its gesture
// defer: the pre-queue raw write landed immediately, gesture or not, and
// ahead of the SetAutoRun a nav tick queues right after it. Keep both.
DrainDirectHeading();
// Overlay click-to-select (Radar dot / nameplate click): also before the
// gesture defer, so a click selects at once even while the bot swings.
DrainOverlaySelect();
int head = _head; // only the main thread writes _head
int tail = Volatile.Read(ref _tail);
// ── Gesture-phase serialization (extends the 56e6946 anim-walk guard
@ -315,6 +485,9 @@ internal static class AcMainThreadQueue
CombatActionHooks.MissileAttack(e.A, unchecked((int)e.B),
BitConverter.UInt32BitsToSingle(e.C));
break;
case ActionKind.CancelAttack:
CombatActionHooks.CancelAttack();
break;
case ActionKind.DoMovement:
MovementActionHooks.DoMovement(e.A,
BitConverter.UInt32BitsToSingle(e.C), unchecked((int)e.B));
@ -325,6 +498,9 @@ internal static class AcMainThreadQueue
case ActionKind.Jump:
MovementActionHooks.JumpNonAutonomous(BitConverter.UInt32BitsToSingle(e.A));
break;
case ActionKind.SetAutonomyLevel:
MovementActionHooks.SetAutonomyLevel(e.A);
break;
case ActionKind.UseObject:
ClientHelperHooks.UseObject(e.A);
break;
@ -349,6 +525,27 @@ internal static class AcMainThreadQueue
case ActionKind.GiveObjectTo:
ClientHelperHooks.GiveObjectTo(e.A, e.B, unchecked((int)e.C));
break;
case ActionKind.WieldItem:
ClientHelperHooks.WieldItem(e.A, e.B);
break;
case ActionKind.DropItem:
ClientHelperHooks.DropItem(e.A);
break;
case ActionKind.Trade:
PlayerTrade.RunQueued(e.A, e.B, e.C);
break;
case ActionKind.Train:
PlayerTraining.RunQueued(e.A, e.B, e.C);
break;
case ActionKind.SalvageOpen:
ClientHelperHooks.SalvagePanelOpen(e.A);
break;
case ActionKind.SalvageAddItem:
ClientHelperHooks.SalvagePanelAddItem(e.A);
break;
case ActionKind.SalvageExecute:
ClientHelperHooks.SalvagePanelExecute();
break;
case ActionKind.SetSelectedObject:
// On the main thread now -> SetSelectedObjectId's gate is
// satisfied and it calls AC's SetSelectedObject directly.
@ -400,7 +597,9 @@ internal static class AcMainThreadQueue
}
}
// ── RequestId slot (0xC8 appraisal sends from AutoIdService) ──────────────────
// ── RequestId slot (0xC8 appraisal sends from AutoIdService, and every other
// off-thread CombatActionHooks.RequestId caller: plugin RequestIdFn, the
// PluginManager.TickAll login self-identify) ─────────────────────────────
// AutoIdService runs on a Timer thread; sending 0xC8 directly there does AC heap
// allocation + a non-atomic shared UI-counter increment off AC's main thread (the
// off-thread-send class flagged for RequestId). Marshal onto the main thread here.
@ -431,7 +630,10 @@ internal static class AcMainThreadQueue
// CombatActionHooks.RequestId sends the 0xC8 directly.
private static void DrainRequestIds()
{
while (true)
// Bounded like DrainChatCommands: a re-queue never spins the main thread.
int budget;
lock (_requestIdLock) budget = _requestIdQueue.Count;
while (budget-- > 0)
{
uint id;
lock (_requestIdLock)
@ -443,6 +645,58 @@ internal static class AcMainThreadQueue
}
}
// ── QueryHealth slot (0x1BF CM_Combat::Event_QueryHealth sends) ─────────────────
// Plugins (RynthAi CombatManager, once per fight target) call QueryHealthFn from the
// plugin pump; the send allocates an AC blob and pushes AC's send queue, so it is
// main-thread-only like 0xC8. Same shape as the RequestId slot: its own small
// queue, NOT the gesture-deferred action ring (a packet send doesn't perturb the
// motion graph and a health query must not wait out a swing). Callers ignore the
// result and only want the async 0x01C0 reply, so a target already waiting here is
// not queued twice. Pre-sized, so enqueue does not allocate.
private const int MaxQueryHealthQueue = 64;
private static readonly System.Collections.Generic.Queue<uint> _queryHealthQueue = new(MaxQueryHealthQueue);
private static readonly object _queryHealthLock = new();
private static int _queryHealthPending; // lock-free "anything queued?" for the per-frame drain
// Pump-thread enqueue. Drops (returns false) if the queue is full.
public static bool EnqueueQueryHealth(uint targetId)
{
if (targetId == 0) return false;
lock (_queryHealthLock)
{
if (_queryHealthQueue.Contains(targetId))
return true; // already pending; one reply answers both
if (_queryHealthQueue.Count >= MaxQueryHealthQueue)
{
Interlocked.Increment(ref _dropped);
return false;
}
_queryHealthQueue.Enqueue(targetId);
Volatile.Write(ref _queryHealthPending, _queryHealthQueue.Count);
return true;
}
}
// Single-consumer drain on AC's main thread (from Drain()). On the main thread
// CombatActionHooks.QueryHealth sends the 0x1BF directly.
private static void DrainQueryHealth()
{
if (Volatile.Read(ref _queryHealthPending) == 0) return;
int budget;
lock (_queryHealthLock) budget = _queryHealthQueue.Count;
while (budget-- > 0)
{
uint id;
lock (_queryHealthLock)
{
if (_queryHealthQueue.Count == 0) { Volatile.Write(ref _queryHealthPending, 0); return; }
id = _queryHealthQueue.Dequeue();
Volatile.Write(ref _queryHealthPending, _queryHealthQueue.Count);
}
try { CombatActionHooks.QueryHealth(id); } catch { }
}
}
// ── Chat slot (WriteToChat strings) ──────────────────────────────────────────
// WriteToChat carries a string, which can't ride the uint Entry queue. Off-thread
// AddTextToScroll races AC's chat-scroll buffer and corrupts it (the recurring
@ -473,7 +727,10 @@ internal static class AcMainThreadQueue
// IsOnMainThread gate is satisfied here so it runs AddTextToScroll directly.
private static void DrainChat()
{
while (true)
// Bounded like DrainChatCommands: a re-queue never spins the main thread.
int budget;
lock (_chatLock) budget = _chatQueue.Count;
while (budget-- > 0)
{
(string Text, int ChatType) item;
lock (_chatLock)
@ -522,7 +779,11 @@ internal static class AcMainThreadQueue
// instead of re-enqueuing.
private static void DrainChatCommands()
{
while (true)
// Only what was queued before this drain: anything a dispatch queues again
// waits for the next frame instead of spinning here.
int budget;
lock (_chatCommandLock) budget = _chatCommandQueue.Count;
while (budget-- > 0)
{
string text;
lock (_chatCommandLock)

View file

@ -75,6 +75,7 @@ internal static class AccountHooks
private static SendNoticeWorldNameDelegate? _sendNoticeWorldNameDetour;
private static string? _cachedAccountName;
private static string? _cachedWorldName;
private static volatile string? _announcedWorldName;
public static bool IsInitialized { get; private set; }
public static bool WorldHookInstalled { get; private set; }
@ -153,6 +154,7 @@ internal static class AccountHooks
if (!string.IsNullOrEmpty(name))
{
_cachedWorldName = name;
_announcedWorldName = name;
RynthLog.Verbose($"Compat: world name captured - \"{name}\".");
}
}
@ -161,9 +163,21 @@ internal static class AccountHooks
}
catch { }
// The account id is set by now (login): warm the account-name cache here
// on the main thread so off-thread readers find it filled.
try { WarmFromMainThread(); }
catch { }
return result;
}
/// <summary>
/// The world name the server itself announced at login (the SendNotice_WorldName hook),
/// or null. Unlike TryGetWorldName it never falls back to the launcher's profile name,
/// which the player chose (ServerInfo's detection wants what the server said). Any thread.
/// </summary>
public static string? AnnouncedWorldName => _announcedWorldName;
/// <summary>
/// Returns the current account name. Result is cached after the first successful read.
/// </summary>
@ -171,12 +185,50 @@ internal static class AccountHooks
{
name = string.Empty;
if (_cachedAccountName != null)
string? cached = Volatile.Read(ref _cachedAccountName);
if (cached != null)
{
name = _cachedAccountName;
name = cached;
return true;
}
// Cold cache off AC's main thread (host GetAccountNameFn on the plugin pump:
// RynthNet identity push, meta expressions, RynthLua): report "not yet".
// Client::GetInstance / Client::GetAccountName and the PSRefBuffer read run
// on the main thread only (WarmFromMainThread), which fills the cache
// during login, normally before any plugin asks.
if (!MainThreadGuard.IsOnMainThread())
return false;
return TryReadAccountNameNative(out name);
}
private static long _nextAccountNameWarmMs;
/// <summary>
/// Main thread only (MainThreadSnapshots.Tick, and the end of the
/// SendNotice_WorldName detour). Fills the account-name cache while it is cold,
/// at most every 500 ms; a single null check once it is warm.
/// </summary>
internal static void WarmFromMainThread()
{
if (Volatile.Read(ref _cachedAccountName) != null || !MainThreadGuard.IsOnMainThread())
return;
long now = Environment.TickCount64;
if (now < _nextAccountNameWarmMs)
return;
_nextAccountNameWarmMs = now + 500;
TryReadAccountNameNative(out _);
}
// The native read (body unchanged). MAIN THREAD ONLY.
private static bool TryReadAccountNameNative(out string name)
{
name = string.Empty;
if (!MainThreadGuard.IsOnMainThread())
return false;
if (_getClientInstance == null || _getAccountName == null)
return false;
@ -205,7 +257,7 @@ internal static class AccountHooks
if (string.IsNullOrEmpty(str))
return false;
_cachedAccountName = str;
Volatile.Write(ref _cachedAccountName, str);
name = str;
return true;
}

View file

@ -0,0 +1,403 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AelrynthWire.cs
//
// Pure parsing for the Aelrynth-only features: no AC, no engine state, so the
// offline tests (tools/AelrynthTests) compile this file as is.
//
// ServerDetect which server the client is on, from the launch command line
// (-h host[:port] -p port), the world name the server announced
// at login, and the Bank mod's custom player properties.
// MasteryWire the SkillMastery mod's /mastery-data reply: ONE chat line,
// "~ael1 " + a JSON object (Mods/src/Aeshnidae.SkillMastery,
// DataCommand.cs + CompanionFeed.cs), and ACE's "Unknown
// command: <name>" refusal.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.Json;
namespace RynthCore.Engine.Compatibility;
/// <summary>Where the launch command line says the client connects.</summary>
internal enum ServerHostKind
{
/// <summary>No -h on the command line (or it couldn't be read).</summary>
Unknown,
/// <summary>aelrynth.com (or a subdomain) / 144.217.84.148, any port.</summary>
Aelrynth,
/// <summary>Loopback or a private LAN address: a developer's own server.</summary>
Local,
/// <summary>Any other host: somebody else's server.</summary>
Other,
}
/// <summary>One detection result. Immutable.</summary>
internal sealed class ServerVerdict
{
public bool IsAelrynth { get; init; }
public bool IsStaging { get; init; }
/// <summary>Plain-English why, for /rc server and the log.</summary>
public string Reason { get; init; } = "";
public static readonly ServerVerdict Unknown = new() { Reason = "nothing known yet" };
}
internal static class ServerDetect
{
public const string AelrynthDomain = "aelrynth.com";
public const string AelrynthIp = "144.217.84.148";
/// <summary>The live world (9020, 9021 the second socket ACE opens).</summary>
public const int LivePortLow = 9020, LivePortHigh = 9021;
/// <summary>The staging world on the same VPS (ops/staging.sh).</summary>
public const int StagingPort = 9030;
/// <summary>The Bank mod's custom PropertyInt64 ids (Aeshnidae.Bank ClientTotals): Radiance earned, Luminance banked, Luminance drawn this session.</summary>
public const uint RadianceEarnedProperty = 9101, LuminanceBankedProperty = 9102, LuminanceDrawnProperty = 9103;
/// <summary>
/// The host and port from acclient's command line: "-h host:port" (the RynthCore
/// launcher's ACE form) or "-h host -p port" (GDLE form, other launchers). Only
/// -h and -p are read; the rest (account, password) is never kept.
/// </summary>
public static bool TryParseLaunchHost(string? commandLine, out string host, out int port)
{
host = "";
port = 0;
if (string.IsNullOrEmpty(commandLine))
return false;
List<string> args = SplitArgs(commandLine);
for (int i = 0; i + 1 < args.Count; i++)
{
if (string.Equals(args[i], "-h", StringComparison.OrdinalIgnoreCase))
{
string v = args[i + 1].Trim();
int colon = v.LastIndexOf(':');
if (colon > 0 && v.IndexOf(':') == colon
&& int.TryParse(v.AsSpan(colon + 1), NumberStyles.None, CultureInfo.InvariantCulture, out int p))
{
host = v.Substring(0, colon);
if (port == 0) port = p;
}
else
{
host = v;
}
}
else if (string.Equals(args[i], "-p", StringComparison.OrdinalIgnoreCase)
&& int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out int p))
{
port = p;
}
}
host = host.Trim().TrimEnd('.').ToLowerInvariant();
return host.Length > 0;
}
/// <summary>Windows command-line splitting, enough for the launchers' quoting (quotes group, \" is a quote).</summary>
private static List<string> SplitArgs(string s)
{
var list = new List<string>();
var cur = new System.Text.StringBuilder();
bool inQuotes = false, any = false;
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (c == '\\' && i + 1 < s.Length && s[i + 1] == '"') { cur.Append('"'); i++; any = true; continue; }
if (c == '"') { inQuotes = !inQuotes; any = true; continue; }
if (!inQuotes && char.IsWhiteSpace(c))
{
if (any) { list.Add(cur.ToString()); cur.Clear(); any = false; }
continue;
}
cur.Append(c);
any = true;
}
if (any) list.Add(cur.ToString());
return list;
}
public static ServerHostKind ClassifyHost(string? host)
{
if (string.IsNullOrWhiteSpace(host))
return ServerHostKind.Unknown;
string h = host.Trim().TrimEnd('.').ToLowerInvariant();
if (h == AelrynthDomain || h.EndsWith("." + AelrynthDomain, StringComparison.Ordinal) || h == AelrynthIp)
return ServerHostKind.Aelrynth;
if (h == "localhost" || h == "::1" || h == "[::1]" || h.StartsWith("127.", StringComparison.Ordinal)
|| h.StartsWith("10.", StringComparison.Ordinal) || h.StartsWith("192.168.", StringComparison.Ordinal)
|| IsPrivate172(h))
return ServerHostKind.Local;
return ServerHostKind.Other;
}
private static bool IsPrivate172(string h)
{
if (!h.StartsWith("172.", StringComparison.Ordinal)) return false;
int dot = h.IndexOf('.', 4);
return dot > 4 && int.TryParse(h.AsSpan(4, dot - 4), NumberStyles.None, CultureInfo.InvariantCulture, out int b)
&& b >= 16 && b <= 31;
}
/// <summary>The server's own name for the world: Aelrynth, or Aeshnidae (its earlier name, still in the live config).</summary>
public static bool IsAelrynthWorldName(string? name)
{
if (string.IsNullOrWhiteSpace(name)) return false;
string n = name.Trim();
return n.StartsWith("Aelrynth", StringComparison.OrdinalIgnoreCase)
|| n.StartsWith("Aeshnidae", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Combines the signals. Unknown means not Aelrynth.
/// - Aelrynth's host (domain or IP, any port): yes. Port 9030 or a world name
/// with "Staging" in it is the staging world (same mods, IsStaging).
/// - Somebody else's public host: no, unless BOTH server-sent signals agree
/// (the announced world name and the Bank mod's properties) - Aelrynth on a
/// new address before this list knows it.
/// - A local/LAN host or no host at all: yes when the server announced an
/// Aelrynth world name or sends the Bank mod's properties (a dev copy).
/// </summary>
public static ServerVerdict Decide(ServerHostKind hostKind, string? host, int port, string? announcedWorld, bool bankProperties)
{
bool worldMatch = IsAelrynthWorldName(announcedWorld);
bool stagingName = announcedWorld != null && announcedWorld.IndexOf("staging", StringComparison.OrdinalIgnoreCase) >= 0;
string where = host is { Length: > 0 } ? (port > 0 ? $"{host}:{port}" : host) : "no host on the command line";
string world = announcedWorld is { Length: > 0 } ? $"world \"{announcedWorld}\"" : "no world name yet";
string bank = bankProperties ? "Bank properties seen" : "no Bank properties";
switch (hostKind)
{
case ServerHostKind.Aelrynth:
{
bool staging = port == StagingPort || stagingName;
return new ServerVerdict
{
IsAelrynth = true,
IsStaging = staging,
Reason = $"Aelrynth{(staging ? " staging" : "")}: connected to {where} ({world}, {bank})",
};
}
case ServerHostKind.Other:
if (worldMatch && bankProperties)
return new ServerVerdict
{
IsAelrynth = true,
IsStaging = stagingName,
Reason = $"Aelrynth: {where} is not a known Aelrynth address, but the server says {world} and sends Bank properties",
};
return new ServerVerdict { Reason = $"not Aelrynth: connected to {where} ({world}, {bank})" };
default:
if (worldMatch || bankProperties)
return new ServerVerdict
{
IsAelrynth = true,
IsStaging = stagingName,
Reason = $"Aelrynth (local copy): {where}, {world}, {bank}",
};
return new ServerVerdict { Reason = $"not Aelrynth: {where}, {world}, {bank}" };
}
}
}
/// <summary>One trained skill's mastery, as /mastery-data sends it.</summary>
internal sealed class MasterySkill
{
public int Id; // STypeSkill
public string Key = ""; // Skill enum name, lower case: what /raise takes
public string Name = "";
public bool Specialized;
public long Base, Current; // the server's, mastery bonus included
public int Ranks; // mastery ranks bought (RanksPerSkillPoint of them make a point)
public string Points = ""; // ranks as points, "3.7"
public int Bonus; // whole points on the skill now
public long Next; // Radiance for the next raise; 0 at the ceiling
public int Afford; // raises in a row the banked Radiance pays for (capped at 999)
public bool Ceiling; // at the server's mastery ceiling
public bool Locked; // the server wants the retail maximum first
}
/// <summary>One /mastery-data reply. Immutable once parsed.</summary>
internal sealed class MasteryData
{
public bool Ok;
public string Why = "";
public bool Enabled;
public long Radiance; // banked Radiance on the account: what a raise spends
public int PerPoint = 1; // raises per skill point
public int CeilingPoints; // 0 = no ceiling
public bool RequireCap;
public Dictionary<int, MasterySkill> Skills = new();
}
internal static class MasteryWire
{
/// <summary>The Companion wire prefix (CompanionFeed.Prefix in the server mods).</summary>
public const string Prefix = "~ael1 ";
public const string DataCommand = "mastery-data";
/// <summary>
/// The prefix within the line's first 32 characters (in case the client puts
/// something in front), with no quote before it: a player who SAYS "~ael1 {...}"
/// arrives as Name says, "~ael1 ..." and is not a server line.
/// </summary>
public static bool IsDataLine(string? line) => PrefixAt(line) >= 0;
private static int PrefixAt(string? line)
{
if (line == null || line.Length < Prefix.Length) return -1;
int at = line.IndexOf(Prefix, StringComparison.Ordinal);
return at >= 0 && at <= 32 && line.LastIndexOf('"', at) < 0 ? at : -1;
}
/// <summary>The data line's "t" (what it is), or "" when it isn't one or can't be read.</summary>
public static string TypeOf(string? line)
{
int at = PrefixAt(line);
if (at < 0) return "";
try
{
using JsonDocument doc = JsonDocument.Parse(Body(line!, at));
return doc.RootElement.ValueKind == JsonValueKind.Object ? Str(doc.RootElement, "t") : "";
}
catch { return ""; }
}
private static string Body(string line, int at)
{
string body = line.Substring(at + Prefix.Length);
int end = body.LastIndexOf('}');
return end >= 0 ? body.Substring(0, end + 1) : body;
}
/// <summary>
/// Parses a /mastery-data line ("t":"mastery"). False for any other line, another
/// "t", or JSON that can't be read. Fields the server adds later are ignored;
/// missing ones keep their defaults.
/// </summary>
public static bool TryParse(string? line, out MasteryData? data)
{
data = null;
int at = PrefixAt(line);
if (at < 0) return false;
try
{
using JsonDocument doc = JsonDocument.Parse(Body(line!, at));
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object || Str(root, "t") != "mastery")
return false;
var d = new MasteryData
{
Ok = Bool(root, "ok"),
Why = Str(root, "why"),
Enabled = Bool(root, "enabled"),
Radiance = Math.Max(0, Long(root, "radiance")),
PerPoint = (int)Math.Clamp(Long(root, "perPoint", 1), 1, 1_000_000),
CeilingPoints = (int)Math.Clamp(Long(root, "ceiling"), 0, int.MaxValue),
RequireCap = Bool(root, "requireCap"),
};
if (root.TryGetProperty("skills", out JsonElement skills) && skills.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement s in skills.EnumerateArray())
{
if (s.ValueKind != JsonValueKind.Object) continue;
int id = (int)Math.Clamp(Long(s, "id"), 0, int.MaxValue);
string key = Str(s, "k");
if (id <= 0 || !IsSkillKey(key)) continue;
d.Skills[id] = new MasterySkill
{
Id = id,
Key = key,
Name = Str(s, "name"),
Specialized = Str(s, "adv") == "spec",
Base = Long(s, "base"),
Current = Long(s, "cur"),
Ranks = (int)Math.Clamp(Long(s, "ranks"), 0, int.MaxValue),
Points = Str(s, "points"),
Bonus = (int)Math.Clamp(Long(s, "bonus"), 0, int.MaxValue),
Next = Math.Max(0, Long(s, "next")),
Afford = (int)Math.Clamp(Long(s, "afford"), 0, int.MaxValue),
Ceiling = Bool(s, "ceiling"),
Locked = Bool(s, "locked"),
};
}
}
data = d;
return true;
}
catch
{
return false;
}
}
/// <summary>
/// ACE's refusal of a command it doesn't have: "Unknown command: &lt;name&gt;"
/// (GameActionTalk). True when <paramref name="line"/> is that for <paramref name="command"/>.
/// </summary>
public static bool IsUnknownCommand(string? line, string command)
{
const string marker = "Unknown command: ";
if (line == null) return false;
int at = line.IndexOf(marker, StringComparison.Ordinal);
if (at < 0 || at > 32 || (at > 0 && line.LastIndexOf('"', at - 1) >= 0)) return false;
return string.Equals(line.Substring(at + marker.Length).Trim(), command, StringComparison.OrdinalIgnoreCase);
}
/// <summary>A Skill enum name in lower case ("meleedefense"): what the mod's /raise matches.</summary>
public static bool IsSkillKey(string? key)
{
if (string.IsNullOrEmpty(key) || key.Length > 40) return false;
foreach (char c in key)
if (c < 'a' || c > 'z') return false;
return true;
}
/// <summary>
/// The server command text for a raise, as the client sends a typed "/raise ..."
/// (ACE runs Talk text that starts with '@' as a command): "@raise meleedefense 1".
/// Null when the key or count isn't one the mod's parser reads unambiguously.
/// </summary>
public static string? RaiseCommand(string? key, int count)
{
if (!IsSkillKey(key) || count < 1 || count > 999) return null;
return "@raise " + key + " " + count.ToString(CultureInfo.InvariantCulture);
}
/// <summary>The server command text that asks for the data line.</summary>
public const string DataRequest = "@" + DataCommand;
// ── JSON helpers: tolerant of type drift (a number sent as a string, and the reverse) ──
private static string Str(JsonElement o, string name)
{
if (!o.TryGetProperty(name, out JsonElement v)) return "";
return v.ValueKind switch
{
JsonValueKind.String => v.GetString() ?? "",
JsonValueKind.Number => v.GetRawText(),
JsonValueKind.True => "true",
JsonValueKind.False => "false",
_ => "",
};
}
private static long Long(JsonElement o, string name, long fallback = 0)
{
if (!o.TryGetProperty(name, out JsonElement v)) return fallback;
if (v.ValueKind == JsonValueKind.Number)
{
if (v.TryGetInt64(out long l)) return l;
if (v.TryGetDouble(out double d)) return d >= long.MaxValue ? long.MaxValue : d <= long.MinValue ? long.MinValue : (long)d;
return fallback;
}
if (v.ValueKind == JsonValueKind.String
&& long.TryParse(v.GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out long s))
return s;
return fallback;
}
private static bool Bool(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True;
}

View file

@ -1,10 +1,13 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AppraisalHooks.cs
//
// Hooks CM_Examine::SendNotice_SetAppraiseInfo to cache appraisal bool
// properties for inventory items whose m_pQualities is null.
// CBaseQualities::InqBool returns 0 for such items because the property
// setter skips CBaseQualities storage when m_pQualities is null.
// Caches what the last identify of each object carried, for objects whose
// m_pQualities is null (CBaseQualities::Inq* return 0 for them) and for every
// read off AC's main thread (where no Inq* may run). Two feeds: the identify
// message itself (OnIdentifyWire, from SmartBoxHooks.ParseGameEvent: all six
// tables plus the armour/weapon/hook profiles, see PropertyWire) and, merged
// over it, AC's parsed AppraisalProfile via a hook on
// CM_Examine::SendNotice_SetAppraiseInfo (int, bool, string, spells, vitals).
//
// VA derivation (map_offset + 0x00401000 = live VA):
// 002AF5B0 CM_Examine::SendNotice_SetAppraiseInfo → 0x006B05B0
@ -57,12 +60,23 @@ internal static class AppraisalHooks
private static readonly HashSet<uint> _appraisedGuids = new();
// Unix timestamp (seconds) of last appraisal receipt per guid
private static readonly Dictionary<uint, long> _lastIdTime = new();
// Int property cache: guid → (stype → value)
private static readonly Dictionary<uint, Dictionary<uint, int>> _intCache = new();
// Bool property cache: guid → (stype → value)
private static readonly Dictionary<uint, Dictionary<uint, bool>> _boolCache = new();
// String property cache: guid → (stype → value)
private static readonly Dictionary<uint, Dictionary<uint, string>> _stringCache = new();
// Every property the last identify of an object carried: guid → bag (2026-09-30).
// Two sources, both on AC's main thread inside UIQueueManager::ProcessNetBlobData:
// - the identify message itself (SmartBoxHooks.ParseGameEvent → OnIdentifyWire, before
// AC handles it): all six tables (int, int64, bool, float, string, data id) plus the
// armour/weapon/hook profile values filed under their property ids (PropertyWire);
// - AC's parsed AppraisalProfile (SendNoticeDetour, after): int, bool and string, the
// long-proven path, merged over the wire values.
// Before, only the second existed, so int64, float and data id properties never answered
// off the main thread (the float capture of 2026-09-30 sat in a parser nothing called).
private static readonly Dictionary<uint, PropertyBag> _bags = new();
// The guid whose wire record ParseGameEvent stored in the current dispatch (main thread only):
// SendNoticeDetour then merges AC's tables into it instead of replacing them.
private static uint _wireGuidThisDispatch;
private static int _wireLogCount, _wireMissLogCount;
// Hard cap on identified objects kept (they are also evicted on delete and cleared on
// logout). Past it the oldest identify is dropped.
private const int MaxAppraisedObjects = 4096;
// Spell book cache: guid → spell ID array (from AppraisalProfile._spellBook PSmartArray<UInt32> at +0x30)
private static readonly Dictionary<uint, uint[]> _spellIdCache = new();
private static readonly object _cacheLock = new();
@ -97,14 +111,138 @@ internal static class AppraisalHooks
{
_appraisedGuids.Clear();
_lastIdTime.Clear();
_intCache.Clear();
_boolCache.Clear();
_stringCache.Clear();
_bags.Clear();
_spellIdCache.Clear();
_failedRollLogged.Clear();
}
}
/// <summary>Drops everything cached for an object AC deleted (PropertyUpdateHooks' BeingDeleted hook).</summary>
public static void EvictObject(uint guid)
{
lock (_cacheLock)
{
_appraisedGuids.Remove(guid);
_lastIdTime.Remove(guid);
_bags.Remove(guid);
_spellIdCache.Remove(guid);
_failedRollLogged.Remove(guid);
}
}
public static int CachedObjectCount
{
get { lock (_cacheLock) return _bags.Count; }
}
// Caller holds _cacheLock. Keeps the bag count under MaxAppraisedObjects by dropping the
// object identified longest ago (a scan, only when the cap is hit).
private static void EnforceCapLocked(uint keep)
{
while (_bags.Count >= MaxAppraisedObjects)
{
uint oldest = 0;
long oldestTime = long.MaxValue;
foreach (uint g in _bags.Keys)
{
if (g == keep) continue;
long t = _lastIdTime.TryGetValue(g, out long v) ? v : 0;
if (t < oldestTime) { oldestTime = t; oldest = g; }
}
if (oldest == 0) return;
_bags.Remove(oldest);
_appraisedGuids.Remove(oldest);
_lastIdTime.Remove(oldest);
_spellIdCache.Remove(oldest);
}
}
// Caller holds _cacheLock.
private static PropertyBag GetOrAddBagLocked(uint guid)
{
if (!_bags.TryGetValue(guid, out PropertyBag? bag))
{
EnforceCapLocked(guid);
_bags[guid] = bag = new PropertyBag();
}
return bag;
}
/// <summary>
/// Stores what an identify message carried (PropertyWire.TryParseIdentify), replacing the
/// object's previous identify. AC's main thread, from SmartBoxHooks.ParseGameEvent, just
/// before AC handles the message; SendNoticeDetour then merges AC's own tables in.
/// </summary>
internal static void StoreIdentify(IdentifyRecord rec)
{
lock (_cacheLock)
{
if (!_bags.ContainsKey(rec.ObjectId))
EnforceCapLocked(rec.ObjectId);
_bags[rec.ObjectId] = rec.Properties;
}
_wireGuidThisDispatch = rec.ObjectId;
if (_wireLogCount < 20)
{
_wireLogCount++;
PropertyBag b = rec.Properties;
RynthLog.Compat($"Compat: identify wire obj=0x{rec.ObjectId:X8} flags=0x{rec.Flags:X4} ok={rec.Success} " +
$"int={b.Ints.Count} int64={b.Int64s.Count} bool={b.Bools.Count} float={b.Floats.Count} " +
$"string={b.Strings.Count} did={b.DataIds.Count} armor={rec.HasArmorProfile} weapon={rec.HasWeaponProfile} " +
$"hook={rec.HasHookProfile} creature={rec.HasCreatureProfile}{(rec.Truncated ? " TRUNCATED" : "")}");
}
}
/// <summary>
/// The identify message (game event 0xC9) as UIQueueManager::ProcessNetBlobData received it,
/// from its event type on. AC's main thread, before AC handles it. Never touches AC state.
/// </summary>
internal static unsafe void OnIdentifyWire(IntPtr data, int size)
{
_wireGuidThisDispatch = 0;
if (data == IntPtr.Zero || size < 16)
return;
if (PropertyWire.TryParseIdentify(new ReadOnlySpan<byte>((void*)data, size), out IdentifyRecord rec))
StoreIdentify(rec);
}
/// <summary>
/// Folds a property update into an already-identified object so the cache doesn't keep
/// serving the value from the last identify (a used pet essence's Structure, a changed
/// float or string). Objects never identified are left alone; PropertyUpdateHooks keeps
/// their updates.
/// </summary>
internal static void ApplyUpdate(uint guid, in PropertyUpdate u)
{
lock (_cacheLock)
{
if (_bags.TryGetValue(guid, out PropertyBag? bag))
bag.Apply(u);
}
}
public static bool TryGetCachedInt64Property(uint guid, uint stype, out long value)
{
value = 0;
lock (_cacheLock)
return _bags.TryGetValue(guid, out PropertyBag? b) && b.Int64s.TryGetValue(stype, out value);
}
public static bool TryGetCachedDataIdProperty(uint guid, uint stype, out uint value)
{
value = 0;
lock (_cacheLock)
return _bags.TryGetValue(guid, out PropertyBag? b) && b.DataIds.TryGetValue(stype, out value);
}
public static bool TryGetCachedInstanceIdProperty(uint guid, uint stype, out uint value)
{
value = 0;
lock (_cacheLock)
return _bags.TryGetValue(guid, out PropertyBag? b) && b.InstanceIds.TryGetValue(stype, out value);
}
/// <summary>
/// Returns the Unix timestamp (seconds) of when appraisal data was last received for this guid, or 0 if never.
/// </summary>
@ -122,11 +260,7 @@ internal static class AppraisalHooks
{
value = 0;
lock (_cacheLock)
{
if (!_intCache.TryGetValue(guid, out Dictionary<uint, int>? props))
return false;
return props.TryGetValue(stype, out value);
}
return _bags.TryGetValue(guid, out PropertyBag? b) && b.Ints.TryGetValue(stype, out value);
}
/// <summary>
@ -137,11 +271,15 @@ internal static class AppraisalHooks
{
value = false;
lock (_cacheLock)
{
if (!_boolCache.TryGetValue(guid, out Dictionary<uint, bool>? props))
return false;
return props.TryGetValue(stype, out value);
}
return _bags.TryGetValue(guid, out PropertyBag? b) && b.Bools.TryGetValue(stype, out value);
}
/// <summary>A float (double) property from the last server appraisal of this object.</summary>
public static bool TryGetCachedDoubleProperty(uint guid, uint stype, out double value)
{
value = 0;
lock (_cacheLock)
return _bags.TryGetValue(guid, out PropertyBag? b) && b.Floats.TryGetValue(stype, out value);
}
/// <summary>
@ -153,9 +291,27 @@ internal static class AppraisalHooks
value = string.Empty;
lock (_cacheLock)
{
if (!_stringCache.TryGetValue(guid, out Dictionary<uint, string>? props))
return false;
return props.TryGetValue(stype, out value!);
if (_bags.TryGetValue(guid, out PropertyBag? b) && b.Strings.TryGetValue(stype, out string? s))
{
value = s;
return true;
}
return false;
}
}
// SendNoticeDetour's tables from AC's AppraisalProfile. When this dispatch's wire record is
// in place they are merged over it (same keys win, the profile-derived values stay); when
// the wire parse didn't run, they replace the table as they always did.
private static void StoreProfileTable<T>(uint guid, Dictionary<uint, T> props, Func<PropertyBag, Dictionary<uint, T>> table)
{
lock (_cacheLock)
{
PropertyBag bag = GetOrAddBagLocked(guid);
Dictionary<uint, T> dst = table(bag);
if (_wireGuidThisDispatch != guid)
dst.Clear();
foreach (var kv in props) dst[kv.Key] = kv.Value;
}
}
@ -218,6 +374,14 @@ internal static class AppraisalHooks
_lastIdTime[guid] = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
}
if (_wireGuidThisDispatch != guid && _wireMissLogCount < 5 && SmartBoxHooks.IsGameEventHookInstalled)
{
// The identify reached AC's handler without its wire record: int64, float and data
// id properties (and the profile values) are missing for it. Seen once per few ids.
_wireMissLogCount++;
RynthLog.Compat($"Compat: identify 0x{guid:X8} reached SetAppraiseInfo without its wire record - only int/bool/string cached.");
}
try
{
CacheIntProps(guid, profilePtr);
@ -263,6 +427,7 @@ internal static class AppraisalHooks
try { RynthLog.Compat($"Compat: appraisal creature-vitals error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
_wireGuidThisDispatch = 0;
return result;
}
@ -315,10 +480,7 @@ internal static class AppraisalHooks
if (props.Count == 0)
return;
lock (_cacheLock)
{
_intCache[guid] = props;
}
StoreProfileTable(guid, props, b => b.Ints);
RynthLog.Verbose($"Compat: cached {props.Count} int prop(s) for guid=0x{guid:X8}");
}
@ -372,10 +534,7 @@ internal static class AppraisalHooks
if (props.Count == 0)
return;
lock (_cacheLock)
{
_boolCache[guid] = props;
}
StoreProfileTable(guid, props, b => b.Bools);
RynthLog.Verbose($"Compat: cached {props.Count} bool prop(s) for guid=0x{guid:X8}");
}
@ -447,10 +606,7 @@ internal static class AppraisalHooks
if (props.Count == 0)
return;
lock (_cacheLock)
{
_stringCache[guid] = props;
}
StoreProfileTable(guid, props, b => b.Strings);
RynthLog.Verbose($"Compat: cached {props.Count} string prop(s) for guid=0x{guid:X8}");
}
@ -564,6 +720,10 @@ internal static class AppraisalHooks
}
else
{
// CreatureAppraisalProfile.enchantment_bitfield (+0x34): low 9 bits = attribute / vital
// modified, bits 16..24 = modified upward. The nameplates' "debuffed by others" marker.
ImGuiBackend.Hud.HudFeed.OnAppraisal(guid, unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x34)));
int log = Interlocked.Increment(ref _creatureVitalsLogCount);
if (log <= 50)
RynthLog.Compat($"Compat: appraisal creature vitals guid=0x{guid:X8} hp={health}/{maxHealth} stam={stamina}/{maxStamina} mana={mana}/{maxMana}");

View file

@ -113,6 +113,13 @@ internal static class AutoIdService
// Object may have been destroyed between enqueue and drain
if (objectId == 0)
continue;
// Deleted since it was queued: Evict took it out of _sent. Skip it without
// spending one of the 3 requests per tick. After a big landblock change (the
// 585 deletes of 2026-10-02) the queue otherwise kept asking the server to
// appraise gone objects at 30 a second for half a minute, and live ones waited.
// A delete-then-recreate is queued again by Enqueue, so nothing live is lost.
if (!_sent.ContainsKey(objectId))
continue;
// Marshal onto AC's main thread (EndScene drain) — the Timer thread must
// not call the native 0xC8 send directly (off-thread heap alloc + non-atomic

View file

@ -132,10 +132,17 @@ internal static class BusyCountHooks
int was = _netBusyCount;
if (_originalDecrementBusyCount != null)
// Decrement exactly what the REAL field holds, never past zero. This used
// to call the original decrement max(shadow, 3) times: with the real field
// already 0 (AC's UseDone decrements it inline, which the shadow never
// sees) that walked it to -1..-3 before the write below put it back.
// m_cBusy only drives the cursor (UpdateCursorState: != 0 = busy cursor),
// so this was never the item-action lock, but there is no reason to
// write below zero. See ClientActionGates for the gates AC really checks.
int real = Marshal.ReadInt32(_lastThisPtr + OffsetMCBusy);
if (_originalDecrementBusyCount != null && real > 0)
{
int calls = Math.Max(was, 3);
for (int i = 0; i < calls && i < 20; i++)
for (int i = 0; i < real && i < 20; i++)
_originalDecrementBusyCount(_lastThisPtr);
}
@ -171,11 +178,72 @@ internal static class BusyCountHooks
catch { /* non-fatal */ }
}
RynthLog.Verbose($"Compat: force-reset busy count (was {was})");
RynthLog.Verbose($"Compat: force-reset busy count (was real {real}, shadow {was})");
}
// ── Negative m_cBusy repair ─────────────────────────────────────────────
// AC never takes m_cBusy below what it added; only a zeroing of ours can:
// a force-clear (or the direct-action reconciler) zeroes a count whose
// action is still in flight, then the server's UseDone decrements it
// inline (Handle_Item::UseDone, not through DecrementBusyCount) to -1.
// The real-field watchdog only looks at > 0, so the negative value stayed
// for the session: a permanent busy cursor. Repair it after a short grace.
private static long _realBusyNegativeSince;
private static long _negativeRepairCount;
private const long NegativeBusyRepairMs = 2_000;
public static long NegativeRepairCount => Interlocked.Read(ref _negativeRepairCount);
public static int ShadowBusyCount => Volatile.Read(ref _netBusyCount);
public static int PendingReconcileDelta => _pendingCastBusyDelta;
/// <summary>Read AC's real m_cBusy. False when the ClientUISystem isn't known/readable.</summary>
public static bool TryReadRealBusy(out int value)
{
value = 0;
IntPtr p = _lastThisPtr;
if (p == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(p + OffsetMCBusy))
return false;
try { value = Marshal.ReadInt32(p + OffsetMCBusy); return true; }
catch { return false; }
}
/// <summary>
/// If AC's m_cBusy is negative, set it to 0 and refresh the cursor. Main
/// thread only (returns false elsewhere). <paramref name="was"/> is the
/// value found.
/// </summary>
public static bool RepairNegativeBusy(out int was)
{
was = 0;
if (!MainThreadGuard.IsOnMainThread())
return false;
IntPtr p = _lastThisPtr;
if (!TryReadRealBusy(out was) || was >= 0)
return false;
if (!ClientObjectHooks.IsWritablePointer(p + OffsetMCBusy))
return false;
Marshal.WriteInt32(p + OffsetMCBusy, 0);
Interlocked.Exchange(ref _netBusyCount, 0);
Interlocked.Increment(ref _negativeRepairCount);
if (_updateCursorStateAddress != IntPtr.Zero)
{
try
{
var updateCursor = Marshal.GetDelegateForFunctionPointer<UpdateCursorStateDelegate>(_updateCursorStateAddress);
updateCursor(p);
}
catch { /* non-fatal */ }
}
return true;
}
public static void Initialize()
{
// The item-action gates (pending request / attacking flag) resolve on
// their own; they don't need the busy-count hooks below.
try { ClientActionGates.Initialize(); }
catch (Exception ex) { RynthLog.Compat($"ClientActionGates: init threw {ex.GetType().Name}: {ex.Message}"); }
if (IsInstalled)
return;
@ -290,8 +358,10 @@ internal static class BusyCountHooks
{
_lastThisPtr = IntPtr.Zero;
Volatile.Write(ref _realBusyPositiveTickMs, 0);
_realBusyNegativeSince = 0;
_pendingCastBusyDelta = 0;
_pendingCastGestureSeen = false;
try { ClientActionGates.ResetTracking(); } catch { }
}
// ── Direct-action busy reconciliation (source fix for the per-action leak) ──
@ -398,6 +468,29 @@ internal static class BusyCountHooks
{
long now = Environment.TickCount64;
// The gates AC actually checks before an item use/move/equip (pending
// inventory request, attacking flag). Runs on every call — before each
// inbound game event and after each tick — so the attacking flag's
// zero window between AttackDone and the next CommenceAttack is seen.
if (MainThreadGuard.IsOnMainThread())
{
try { ClientActionGates.Tick(now, PlayerLifecycleLog.InWorldTransition); }
catch { }
}
// Dead or portaling (and just after): the busy count moves on its own
// while AC rebuilds the world, and force-clearing it then writes into
// AC mid-transition — every death today crashed inside AC during the
// death portal (2026-09-28). Restart the timers so a genuinely stuck
// count is judged afresh once the world has settled.
if (PlayerLifecycleLog.InWorldTransition)
{
Volatile.Write(ref _realBusyPositiveTickMs, 0);
if (Volatile.Read(ref _busyBecamePositiveTickMs) != 0)
Volatile.Write(ref _busyBecamePositiveTickMs, now);
return;
}
// ── Real-field watchdog (catches counter desync) ─────────────────────
// Trust AC's REAL m_cBusy over our shadow counter: when they diverge a
// pinned real field is what actually wedges the client (mode-change /
@ -445,6 +538,40 @@ internal static class BusyCountHooks
// (e.g. first beat after the next login).
Volatile.Write(ref _realBusyPositiveTickMs, 0);
}
// Negative real field (ReadRealBusy folds every negative into its -1
// "unreadable" sentinel, so read it directly). See RepairNegativeBusy.
bool haveReal = TryReadRealBusy(out int signedBusy);
if (haveReal && signedBusy < 0)
{
if (_realBusyNegativeSince == 0)
_realBusyNegativeSince = now;
else if (now - _realBusyNegativeSince >= NegativeBusyRepairMs && RepairNegativeBusy(out int neg))
{
_realBusyNegativeSince = 0;
RynthLog.Compat($"BusyCountHooks: REAL m_cBusy was negative ({neg}) — reset to 0 (a zeroed count's own UseDone arrived later).");
}
}
else
{
_realBusyNegativeSince = 0;
}
// Counter-based watchdog below: the shadow counter never sees AC's
// inline UseDone decrement, so it reads "stuck" after nearly every use
// and cast even though the real field is back at 0. When the real
// field is readable and idle, just resync the shadow — force-clearing
// there only zeroed the next in-flight action (thousands of needless
// force-clears a session). A real field > 0 is the real-field
// watchdog's job above.
long shadowSince = Volatile.Read(ref _busyBecamePositiveTickMs);
if (shadowSince != 0 && haveReal && signedBusy <= 0
&& now - shadowSince >= BusyWatchdogTimeoutMs)
{
Interlocked.Exchange(ref _netBusyCount, 0);
Volatile.Write(ref _busyBecamePositiveTickMs, 0);
return;
}
}
// ── Counter-based watchdog (original) ────────────────────────────────

View file

@ -89,29 +89,7 @@ internal static class CObjectMaintHooks
int count = 0;
try
{
for (uint i = 0; i < tableSize; i++)
{
IntPtr bucketSlot = buckets + (int)(i * 4);
if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
break;
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
{
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
break;
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
if (id != 0)
{
visit(id);
count++;
}
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
break;
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
}
}
WalkBuckets(buckets, tableSize, visit, ref count);
}
catch (Exception ex)
{
@ -122,6 +100,44 @@ internal static class CObjectMaintHooks
return count;
}
/// <summary>
/// The bucket/chain walk both enumerators share. One probe covers the whole bucket array
/// and one covers each node's hash_next + id (adjacent, +4..+12), where the walk used to
/// probe every bucket slot and each node twice: a table of 4096 buckets cost 4096+ probes
/// per walk, ten walks a second (2026-10-02 flood fix; see MemoryProbe). When a combined
/// probe fails it falls back to the old per-slot / per-field probes, so the walk stops at
/// exactly the same place as before on bad memory. <paramref name="count"/> is by ref so a
/// visitor that throws still leaves the partial count (the callers' old behaviour).
/// </summary>
private static void WalkBuckets(IntPtr buckets, uint tableSize, Action<uint> visit, ref int count)
{
bool arrayReadable = SmartBoxLocator.IsMemoryReadable(buckets, (int)(tableSize * 4));
for (uint i = 0; i < tableSize; i++)
{
IntPtr bucketSlot = buckets + (int)(i * 4);
if (!arrayReadable && !SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
break;
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
{
bool nodeReadable = SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 8);
if (!nodeReadable && !SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
break;
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
if (id != 0)
{
visit(id);
count++;
}
if (!nodeReadable && !SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
break;
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
}
}
}
// DIAGNOSTIC (temporary): same walk as EnumerateLiveWeenieObjectIds but over
// an arbitrary CObjectMaint table (object_table +0x84 / null_object_table
// +0x9C / weenie_object_table +0xB4). Duplicated rather than refactoring the
@ -151,29 +167,7 @@ internal static class CObjectMaintHooks
int count = 0;
try
{
for (uint i = 0; i < tableSize; i++)
{
IntPtr bucketSlot = buckets + (int)(i * 4);
if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
break;
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
{
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
break;
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
if (id != 0)
{
visit(id);
count++;
}
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
break;
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
}
}
WalkBuckets(buckets, tableSize, visit, ref count);
}
catch (Exception ex)
{

View file

@ -19,9 +19,10 @@ namespace RynthCore.Engine.Compatibility;
/// <see cref="PlayerPhysicsHooks.TryGetCastGestureInProgress"/>).
///
/// This is a SAMPLED gate — no acclient.exe hook is installed. <see cref="Sample"/>
/// runs on the existing 30 Hz NormalPluginPump heartbeat (PluginManager.TickAll)
/// and reads a single CMotionInterp scalar through the already-proven
/// PlayerPhysicsHooks accessor. No new detour, no pattern-scan-and-call (the
/// runs on AC's main thread (MainThreadSnapshots.Tick, from the Client::UseTime
/// drain and EndScene; it ran on the 30 Hz plugin pump until 2026-09-30, which
/// walked the player's MovementManager chain off-thread) and reads a single
/// CMotionInterp scalar through the already-proven PlayerPhysicsHooks accessor. No new detour, no pattern-scan-and-call (the
/// ACE crash class), no list walk (UAF-safe). The consumer polls the gate at
/// the same tick rate, so the busy→idle edge is observed without any new
/// engine→plugin callback (avoids the NativeAOT reverse-P/Invoke crash class).
@ -46,7 +47,7 @@ internal static class CastGate
public static int GetCastBusyState() => Volatile.Read(ref _castBusy);
/// <summary>
/// Sampled from the 30 Hz plugin pump (PluginManager.TickAll). Cheap, fully
/// Sampled on AC's main thread (MainThreadSnapshots.Tick). Cheap, fully
/// guarded, never throws. If CMotionInterp isn't reachable (pre-login /
/// between worlds) the gate reports "clear to cast" so the consumer falls
/// back to its own throttle/park, which is the hard anti-spam guarantee.

View file

@ -122,12 +122,7 @@ internal static class CharacterCaptureHooks
if (Interlocked.Exchange(ref _autoLoginPollStarted, 1) != 0)
return;
var thread = new Thread(AutoLoginPollLoop)
{
Name = "RynthCore.AutoLoginPoll",
IsBackground = true
};
thread.Start();
EngineThreads.Start("RynthCore.AutoLoginPoll", AutoLoginPollLoop);
RynthLog.Info($"CharacterCapture: Poll-driven auto-login armed for '{targetCharacter}'.");
}
@ -139,6 +134,10 @@ internal static class CharacterCaptureHooks
/// Hard-stops the instant mode==GamePlayUI or LoginComplete is observed:
/// poking LogOn pointers while in-game has been correlated with AC self-
/// exiting (see ScheduleAutoLoginIfRequested's notes).
/// Thread note (2026-09-30): this thread never touches AC itself any more.
/// CharacterManagementHooks serves the mode and the character list from its
/// main-thread snapshot, and TryLogOnCharacter hands the real LogOnCharacter
/// to AC's main thread and waits at most ~1.5 s for the result.
/// </summary>
private static void AutoLoginPollLoop()
{
@ -152,9 +151,8 @@ internal static class CharacterCaptureHooks
try
{
while (true)
while (EngineThreads.Sleep(AutoLoginPollIntervalMs))
{
Thread.Sleep(AutoLoginPollIntervalMs);
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
@ -254,21 +252,15 @@ internal static class CharacterCaptureHooks
if (Interlocked.Exchange(ref _characterListCapturePollStarted, 1) != 0)
return;
var thread = new Thread(CharacterListCapturePollLoop)
{
Name = "RynthCore.CharacterListCapture",
IsBackground = true
};
thread.Start();
EngineThreads.Start("RynthCore.CharacterListCapture", CharacterListCapturePollLoop);
}
private static void CharacterListCapturePollLoop()
{
try
{
while (!EngineLifecycle.IsShuttingDown)
while (!EngineLifecycle.IsShuttingDown && EngineThreads.Sleep(CharacterListCapturePollIntervalMs))
{
Thread.Sleep(CharacterListCapturePollIntervalMs);
// In the world: no native reads at all.
if (LoginLifecycleHooks.HasObservedLoginComplete)
@ -529,7 +521,16 @@ internal static class CharacterCaptureHooks
return (sessionHint.AccountName, sessionHint.ServerName, sessionHint.TargetCharacter);
}
return ReadLaunchContextFile(Path.Combine(rootDir, "launch_context.json"));
// The shared launch_context.json names whatever the launcher last started.
// Only trust it for a client started at about that moment (an old launcher
// that wrote no per-process file). A client the launcher didn't start - one
// from ThwargLauncher that "watch for AC start" injected into - otherwise
// auto-logged into the launcher's last character and was knocked back to
// the desktop (2026-09-30, a player's Thwarg main closing seconds after login).
string sharedPath = Path.Combine(rootDir, "launch_context.json");
if (!SharedContextIsForThisLaunch(sharedPath))
return (string.Empty, string.Empty, string.Empty);
return ReadLaunchContextFile(sharedPath);
}
catch
{
@ -537,6 +538,29 @@ internal static class CharacterCaptureHooks
}
}
private static int _sharedContextLogged;
/// <summary>True when the shared launch_context.json was written within two minutes of this process starting.</summary>
private static bool SharedContextIsForThisLaunch(string sharedPath)
{
if (!File.Exists(sharedPath)) return false;
DateTime? created = null;
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(sharedPath));
if (doc.RootElement.TryGetProperty("CreatedAtUtc", out JsonElement c) && c.TryGetDateTime(out DateTime t))
created = t.ToUniversalTime();
}
catch { }
DateTime started = System.Diagnostics.Process.GetCurrentProcess().StartTime.ToUniversalTime();
bool ours = created.HasValue && created.Value >= started.AddMinutes(-2) && created.Value <= started.AddSeconds(30);
if (Interlocked.Exchange(ref _sharedContextLogged, 1) == 0)
RynthLog.Info(ours
? $"CharacterCapture: no per-process launch context; using the shared one (written {created:HH:mm:ss}Z, this client started {started:HH:mm:ss}Z)."
: $"CharacterCapture: no launch context for this client (not started by the RynthCore launcher; shared one from {(created.HasValue ? created.Value.ToString("HH:mm:ss") + "Z" : "?")} is another launch) - no auto-login.");
return ours;
}
private static (string accountName, string serverName, string targetCharacter) ReadLaunchContextFile(string filePath)
{
if (!File.Exists(filePath))
@ -623,8 +647,8 @@ internal static class CharacterCaptureHooks
{
try
{
Thread.Sleep(scheduledDelayMs);
PerformAutoLogin(fallbackCharacters, finalSlots, targetCharacter);
if (EngineThreads.Sleep(scheduledDelayMs))
PerformAutoLogin(fallbackCharacters, finalSlots, targetCharacter);
}
finally
{
@ -635,6 +659,7 @@ internal static class CharacterCaptureHooks
Name = "RynthCore.AutoLogin",
IsBackground = true
};
EngineThreads.Track(thread);
thread.Start();
RynthLog.Verbose(

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
@ -77,8 +78,226 @@ internal static class CharacterManagementHooks
public static string StatusMessage => _statusMessage;
// ── Main-thread char-select service (2026-09-30 main-thread audit) ─────────
// The two char-select poll threads (RynthCore.AutoLoginPoll and
// RynthCore.CharacterListCapture, plus the dormant RynthCore.AutoLogin) used to
// call UIFlow::GetPersistantData, the CharacterSet GetIdentity/GetName/GetGid
// accessors and CPlayerSystem::LogOnCharacter straight from their own threads,
// and PtrToStringAnsi'd name buffers AC frees when char-select rebuilds the
// set (create / delete / reconnect). A freed buffer there is an uncatchable
// AV. Now:
// * MainThreadTick (AcMainThreadQueue.Drain, AC's main thread; pre-login it
// runs from the Client::UseTime drain) publishes the UIFlow mode every call
// and, at char-select, an immutable name/slot-count snapshot every 250 ms.
// * Off-thread TryReadCharacterNames / GetNativeCharacterSetSlotCount serve
// that snapshot; off-thread TryGetCurrentMode serves the published mode.
// * Off-thread TryLogOnCharacter parks the target in a one-request slot and
// waits a bounded time for the main thread to run the real call; on a
// timeout it withdraws the request (it can never fire late) and reports
// failure, which the poll loops already retry.
// The main thread never waits on anyone: it only consumes what is there.
private sealed class CharSelectSnapshot
{
public static readonly CharSelectSnapshot Empty = new(Array.Empty<string>(), 0);
public readonly string[] Names;
public readonly int SlotCount;
public CharSelectSnapshot(string[] names, int slotCount) { Names = names; SlotCount = slotCount; }
}
private sealed class LogOnResult
{
public bool Ok;
public string Matched = string.Empty;
public uint AvatarId;
public int SlotIndex = -1;
public string Status = string.Empty;
}
private const int CharSelectSnapshotIntervalMs = 250;
private const int LogOnRequestWaitMs = 500; // one frame at char-select is ~16-50 ms
private const int LogOnRunningGraceMs = 1000; // extra wait once the main thread has taken it
private static volatile CharSelectSnapshot _charSelectSnapshot = CharSelectSnapshot.Empty;
private static long _nextCharSelectSnapshotMs;
private static int _publishedMode;
private static int _modePublished; // 1 once MainThreadTick has read the mode
// Login request slot: 0 idle, 1 pending (off-thread caller armed it),
// 2 running (main thread took it), 3 done (result published).
private static int _logOnState;
private static string _logOnTarget = string.Empty;
private static LogOnResult? _logOnResult;
private static readonly object LogOnCallerLock = new(); // serialises OFF-thread callers only
private static int _loggedNoMainThreadService;
/// <summary>
/// Main thread only (AcMainThreadQueue.Drain). Publishes the UIFlow mode, runs a
/// pending login request, and refreshes the char-select snapshot (throttled).
/// Idle in the world: a flag check and one aligned read.
/// </summary>
public static void MainThreadTick()
{
if (!MainThreadGuard.IsOnMainThread())
return;
if (TryReadModeRaw(out int mode))
{
Volatile.Write(ref _publishedMode, mode);
Volatile.Write(ref _modePublished, 1);
}
else
{
Volatile.Write(ref _modePublished, 0);
}
// A pending login request is serviced on the next drain, not throttled.
if (Volatile.Read(ref _logOnState) == 1)
RunPendingLogOn();
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
if (_charSelectSnapshot.Names.Length != 0)
_charSelectSnapshot = CharSelectSnapshot.Empty;
return;
}
long now = Environment.TickCount64;
if (now < Volatile.Read(ref _nextCharSelectSnapshotMs))
return;
Volatile.Write(ref _nextCharSelectSnapshotMs, now + CharSelectSnapshotIntervalMs);
// Never bind here: EnsureBound pattern-scans .text under a lock the poll
// threads also take. They bind on their first pass; until then, skip.
if (!Volatile.Read(ref _bound) || mode != CharacterManagementUI)
{
if (_charSelectSnapshot.Names.Length != 0 || _charSelectSnapshot.SlotCount != 0)
_charSelectSnapshot = CharSelectSnapshot.Empty;
return;
}
try
{
var names = new List<string>();
ReadCharacterNamesCore(names);
int slotCount = SlotCountCore();
_charSelectSnapshot = new CharSelectSnapshot(names.ToArray(), slotCount);
}
catch
{
_charSelectSnapshot = CharSelectSnapshot.Empty;
}
}
// Main thread: take the request (1 -> 2), run the real call, publish (-> 3).
private static void RunPendingLogOn()
{
if (Interlocked.CompareExchange(ref _logOnState, 2, 1) != 1)
return; // withdrawn by its caller in the meantime
var result = new LogOnResult();
try
{
string target = Volatile.Read(ref _logOnTarget);
result.Ok = TryLogOnCharacterCore(target, out result.Matched, out result.AvatarId, out result.SlotIndex, out result.Status);
}
catch (Exception ex)
{
result.Ok = false;
result.Status = $"LogOnCharacter threw {ex.GetType().Name}: {ex.Message}";
}
Volatile.Write(ref _logOnResult, result);
Volatile.Write(ref _logOnState, 3);
}
// Off-thread: arm the slot and wait (bounded) for the main thread's result.
private static bool RequestLogOnFromMainThread(string targetCharacter, out string matchedCharacter, out uint avatarId, out int slotIndex, out string status)
{
matchedCharacter = string.Empty;
avatarId = 0;
slotIndex = -1;
lock (LogOnCallerLock)
{
// A result a previous caller gave up on: discard it, the slot is ours.
if (Volatile.Read(ref _logOnState) == 3)
Volatile.Write(ref _logOnState, 0);
if (Volatile.Read(ref _logOnState) != 0)
{
status = "Main thread is still running the previous LogOnCharacter request.";
return false;
}
Volatile.Write(ref _logOnResult, null);
Volatile.Write(ref _logOnTarget, targetCharacter);
Volatile.Write(ref _logOnState, 1);
long start = Environment.TickCount64;
while (true)
{
int state = Volatile.Read(ref _logOnState);
if (state == 3)
{
LogOnResult? r = Volatile.Read(ref _logOnResult);
Volatile.Write(ref _logOnState, 0);
if (r == null) { status = "LogOnCharacter produced no result."; return false; }
matchedCharacter = r.Matched;
avatarId = r.AvatarId;
slotIndex = r.SlotIndex;
status = r.Status;
return r.Ok;
}
long waited = Environment.TickCount64 - start;
if (state == 1 && waited >= LogOnRequestWaitMs)
{
// Not taken yet: withdraw it so it can never run late.
if (Interlocked.CompareExchange(ref _logOnState, 0, 1) == 1)
{
if (Interlocked.Exchange(ref _loggedNoMainThreadService, 1) == 0)
RynthLog.Compat("CharacterManagement: LogOnCharacter request not serviced by AC's main thread within 500 ms (is the Client::UseTime drain hooked?); retrying on the next poll.");
status = "AC's main thread did not service the LogOnCharacter request in time.";
return false;
}
continue; // taken just now; wait for it
}
if (state == 2 && waited >= LogOnRequestWaitMs + LogOnRunningGraceMs)
{
// Running on the main thread; its result is picked up (and
// discarded) by the next caller. Never blocks longer than this.
status = "LogOnCharacter still running on AC's main thread.";
return false;
}
if (!EngineThreads.Sleep(10))
{
Interlocked.CompareExchange(ref _logOnState, 0, 1);
status = "Engine shutting down.";
return false;
}
}
}
}
private static bool TryReadModeRaw(out int mode)
{
mode = 0;
IntPtr uiFlowPtr = GetUiFlowPointer();
if (uiFlowPtr == IntPtr.Zero)
return false;
mode = Marshal.ReadInt32(IntPtr.Add(uiFlowPtr, UIFlowCurModeOffset));
return true;
}
public static bool TryGetCurrentMode(out int mode)
{
// Off the main thread, serve the mode MainThreadTick published (at most a
// frame old). Before the first tick has run, fall back to the raw read:
// one aligned 4-byte load from the long-lived UIFlow singleton.
if (!MainThreadGuard.IsOnMainThread() && Volatile.Read(ref _modePublished) != 0)
{
mode = Volatile.Read(ref _publishedMode);
return true;
}
mode = 0;
IntPtr uiFlowPtr = GetUiFlowPointer();
if (uiFlowPtr == IntPtr.Zero)
@ -109,12 +328,49 @@ internal static class CharacterManagementHooks
return false;
}
// Bind here, on the caller's thread: pattern resolve reads only acclient's
// .text, and doing it off-thread keeps the scan off AC's main thread.
if (!EnsureBound())
{
status = _statusMessage;
return false;
}
// Off AC's main thread (the auto-login poll threads): the CharacterSet reads
// and CPlayerSystem::LogOnCharacter run on the main thread via the request
// slot; this thread waits a bounded time for the result.
if (!MainThreadGuard.IsOnMainThread())
return RequestLogOnFromMainThread(targetCharacter, out matchedCharacter, out avatarId, out slotIndex, out status);
return TryLogOnCharacterCore(targetCharacter, out matchedCharacter, out avatarId, out slotIndex, out status);
}
// The real lookup + LogOnCharacter. MAIN THREAD ONLY (MainThreadTick's request
// slot, or a caller already on AC's main thread).
private static bool TryLogOnCharacterCore(string targetCharacter, out string matchedCharacter, out uint avatarId, out int slotIndex, out string status)
{
matchedCharacter = string.Empty;
avatarId = 0;
slotIndex = -1;
if (!MainThreadGuard.IsOnMainThread())
{
status = "Off AC's main thread.";
return false;
}
if (string.IsNullOrWhiteSpace(targetCharacter))
{
status = "No target character requested.";
return false;
}
if (!Volatile.Read(ref _bound))
{
status = _statusMessage;
return false;
}
bool hasMode = TryGetCurrentMode(out int mode);
if (hasMode && mode == GamePlayUI)
{
@ -198,12 +454,35 @@ internal static class CharacterManagementHooks
if (!EnsureBound())
return false;
// Off AC's main thread (the capture/auto-login polls): the main-thread
// snapshot, taken only while CharacterManagementUI was up (<= 250 ms old).
if (!MainThreadGuard.IsOnMainThread())
{
CharSelectSnapshot snap = _charSelectSnapshot;
if (snap.Names.Length == 0)
return false;
if (!TryGetCurrentMode(out int offMode) || offMode != CharacterManagementUI)
return false;
names.AddRange(snap.Names);
return true;
}
if (!TryGetCurrentMode(out int mode) || mode != CharacterManagementUI)
return false;
ReadCharacterNamesCore(names);
return names.Count > 0;
}
// MAIN THREAD ONLY. Appends the native set's names in slot order.
private static void ReadCharacterNamesCore(List<string> names)
{
if (!MainThreadGuard.IsOnMainThread())
return;
IntPtr charSetPtr = GetCharacterSetPointer();
if (charSetPtr == IntPtr.Zero)
return false;
return;
for (int index = 0; index < MaxCharacterSlots; index++)
{
@ -218,8 +497,6 @@ internal static class CharacterManagementHooks
names.Add(name.Trim());
}
return names.Count > 0;
}
/// <summary>
@ -234,6 +511,19 @@ internal static class CharacterManagementHooks
if (!EnsureBound())
return 0;
// Off AC's main thread: the slot count from the main-thread snapshot.
if (!MainThreadGuard.IsOnMainThread())
return _charSelectSnapshot.SlotCount;
return SlotCountCore();
}
// MAIN THREAD ONLY.
private static int SlotCountCore()
{
if (!MainThreadGuard.IsOnMainThread())
return 0;
IntPtr charSetPtr = GetCharacterSetPointer();
if (charSetPtr == IntPtr.Zero)
return 0;
@ -289,8 +579,10 @@ internal static class CharacterManagementHooks
_uiFlowAddr = HookResolver.ResolveData(text, "CharMgmt.UIFlow", PatXrefUIFlow, 2, UIFlowInstanceVa).Address.ToInt32();
_playerSystemAddr = HookResolver.ResolveData(text, "CharMgmt.CPlayerSystem", PatXrefCPlayerSystem, 2, PlayerSystemVa).Address.ToInt32();
_bound = _uiFlowGetPersistantData != null && _getPlayerSystem != null && _logOnCharacter != null
&& _characterSetGetIdentity != null && _characterSetGetName != null && _characterSetGetGid != null;
// Published last (volatile): MainThreadTick reads _bound without the
// lock and then uses the delegates, so they must be visible first.
Volatile.Write(ref _bound, _uiFlowGetPersistantData != null && _getPlayerSystem != null && _logOnCharacter != null
&& _characterSetGetIdentity != null && _characterSetGetName != null && _characterSetGetGid != null);
_statusMessage = _bound ? "Bound." : "One or more character-management addresses failed to resolve.";
if (_bound)
RynthLog.Verbose("CharacterManagement: Bound UIFlow and direct LogOnCharacter entry points.");
@ -322,6 +614,11 @@ internal static class CharacterManagementHooks
private static IntPtr GetCharacterSetPointer()
{
// Calls UIFlow::GetPersistantData; the set it returns is rebuilt by the
// main thread. Main thread only (every caller is a *Core method).
if (!MainThreadGuard.IsOnMainThread())
return IntPtr.Zero;
IntPtr uiFlowPtr = GetUiFlowPointer();
if (uiFlowPtr == IntPtr.Zero)
return IntPtr.Zero;
@ -355,6 +652,9 @@ internal static class CharacterManagementHooks
private static IntPtr GetPlayerSystemPointer()
{
if (!MainThreadGuard.IsOnMainThread())
return IntPtr.Zero;
try
{
IntPtr playerSystemPtr = _getPlayerSystem!();

View file

@ -0,0 +1,192 @@
// ============================================================================
// RynthCore.Engine - Compatibility/CharacterTitles.cs
//
// The titles the character holds, for plugins (API v75 GetCharacterTitles).
// The server sends them only in game events, never as properties:
// 0x0029 CharacterTitle at login (ACE GameEventCharacterTitle):
// [u32 1][u32 current title][u32 count][count x u32 title id]
// 0x002B UpdateTitle for each new or newly displayed title (GameEventUpdateTitle):
// [u32 title id][u32 set as display title]
// Both reach SmartBoxHooks.ParseGameEvent ([event type][payload]) on AC's main
// thread, or the Decal bridge's copy on the pump. Parsing only: nothing here
// touches AC.
//
// Owner: a 0x0029 is sent once per login, so it belongs to whoever is logging
// in; the player id is noted when known and adopted at the first read when it
// wasn't yet. A list for another character is never served.
//
// Survives a hot reload: the list is mirrored into this process's environment
// (RYNTHCORE_CHAR_TITLES), as VTankWatch does, because the server won't send
// it again until the next login.
// ============================================================================
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class CharacterTitles
{
public const uint EventCharacterTitle = 0x0029;
public const uint EventUpdateTitle = 0x002B;
private const int MaxTitles = 4096;
private const string EnvName = "RYNTHCORE_CHAR_TITLES";
private static readonly object Lock = new();
private static uint _owner;
private static uint _current;
private static List<uint>? _titles; // null = nothing received for this process yet
private static int _seq;
private static bool _restored;
public static bool IsTitleEvent(uint eventType) => eventType is EventCharacterTitle or EventUpdateTitle;
/// <summary>A title game event: <paramref name="data"/> is [event type][payload], <paramref name="size"/> bytes.</summary>
public static unsafe void OnGameEvent(uint eventType, IntPtr data, uint size, uint playerId)
{
if (data == IntPtr.Zero || size < 4 || size > 0x10000) return;
var span = new ReadOnlySpan<byte>((void*)data, (int)size);
lock (Lock)
{
RestoreOnce();
if (eventType == EventCharacterTitle)
{
if (!TryParseTitleList(span, out uint current, out List<uint> titles)) return;
_owner = playerId;
_current = current;
_titles = titles;
}
else
{
if (!TryParseUpdate(span, out uint title, out bool display)) return;
if (_titles == null || (_owner != 0 && playerId != 0 && _owner != playerId)) return;
if (!_titles.Contains(title) && _titles.Count < MaxTitles) _titles.Add(title);
if (display) _current = title;
}
_seq++;
Persist();
}
}
/// <summary>
/// For the plugin API: copies up to <paramref name="max"/> title ids and returns how many
/// the character holds (which may be more than were copied), or -1 when the list for this
/// character isn't known (not received since the client started, or another character's).
/// </summary>
public static unsafe int Copy(uint playerId, uint* ids, int max, uint* current)
{
lock (Lock)
{
RestoreOnce();
if (_titles == null || playerId == 0) return -1;
if (_owner == 0) _owner = playerId; // received before the id was known
else if (_owner != playerId) return -1;
if (current != null) *current = _current;
if (ids != null)
for (int i = 0; i < _titles.Count && i < max; i++) ids[i] = _titles[i];
return _titles.Count;
}
}
public static int Sequence => Volatile.Read(ref _seq);
/// <summary>For /rc: what the engine holds.</summary>
public static string Describe()
{
lock (Lock)
{
RestoreOnce();
return _titles == null
? "no title list received since this client started"
: $"{_titles.Count} titles for 0x{_owner:X8}, current {_current}";
}
}
// ── Wire (pure) ─────────────────────────────────────────────────────────
/// <summary>0x0029: [type][u32 1][u32 current][u32 count][count x u32]. False when it doesn't fit.</summary>
internal static bool TryParseTitleList(ReadOnlySpan<byte> msg, out uint current, out List<uint> titles)
{
current = 0;
titles = new List<uint>();
if (msg.Length < 16) return false;
current = BinaryPrimitives.ReadUInt32LittleEndian(msg[8..]);
uint count = BinaryPrimitives.ReadUInt32LittleEndian(msg[12..]);
if (count > MaxTitles || 16 + (long)count * 4 > msg.Length) return false;
for (int i = 0; i < (int)count; i++)
{
uint id = BinaryPrimitives.ReadUInt32LittleEndian(msg[(16 + i * 4)..]);
if (!titles.Contains(id)) titles.Add(id);
}
return true;
}
/// <summary>0x002B: [type][u32 title][u32 set as display title].</summary>
internal static bool TryParseUpdate(ReadOnlySpan<byte> msg, out uint title, out bool display)
{
title = 0;
display = false;
if (msg.Length < 12) return false;
title = BinaryPrimitives.ReadUInt32LittleEndian(msg[4..]);
display = BinaryPrimitives.ReadUInt32LittleEndian(msg[8..]) != 0;
return true;
}
// ── Hot-reload mirror: "owner;current;id,id,..." (hex owner, decimal ids) ──
private static void Persist()
{
try
{
var sb = new StringBuilder();
sb.Append(_owner.ToString("X8", CultureInfo.InvariantCulture)).Append(';')
.Append(_current.ToString(CultureInfo.InvariantCulture)).Append(';');
for (int i = 0; i < _titles!.Count; i++)
{
if (i > 0) sb.Append(',');
sb.Append(_titles[i].ToString(CultureInfo.InvariantCulture));
}
Environment.SetEnvironmentVariable(EnvName, sb.ToString());
}
catch { }
}
private static void RestoreOnce()
{
if (_restored) return;
_restored = true;
try
{
if (TryParseMirror(Environment.GetEnvironmentVariable(EnvName), out uint owner, out uint current, out List<uint> titles))
{
_owner = owner;
_current = current;
_titles = titles;
_seq++;
}
}
catch { }
}
internal static bool TryParseMirror(string? s, out uint owner, out uint current, out List<uint> titles)
{
owner = 0;
current = 0;
titles = new List<uint>();
if (string.IsNullOrEmpty(s)) return false;
string[] parts = s.Split(';');
if (parts.Length != 3) return false;
if (!uint.TryParse(parts[0], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out owner)) return false;
if (!uint.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out current)) return false;
foreach (string p in parts[2].Split(',', StringSplitOptions.RemoveEmptyEntries))
{
if (!uint.TryParse(p, NumberStyles.None, CultureInfo.InvariantCulture, out uint id)) return false;
if (titles.Count < MaxTitles && !titles.Contains(id)) titles.Add(id);
}
return true;
}
}

View file

@ -18,6 +18,7 @@ internal static class ChatCallbackHooks
private const int PsRefBufferWideDataOffset = 20;
private const int MaxIncomingChatChars = 1024;
private const int MaxDataLineChars = 65536;
private const int IncomingChatAddTextToScrollVa = 0x005649F0;
private const int IncomingChatWrapperVa = 0x0058A000;
private const int OutgoingChatVa = 0x005821A0;
@ -70,6 +71,19 @@ internal static class ChatCallbackHooks
private static int _incomingChatSuppressionEnabled;
private static int _incomingCallCount;
// ── Held incoming chat (IncomingChatHold.cs) ─────────────────────────────
// AddTextToScroll lines wait for the plugins' verdict before AC prints them, so a
// line a plugin eats never reaches AC's chat window. Main-thread only, except the
// beats and the switch.
private static readonly HeldChatQueue _held = new();
private static readonly Action<HeldChatLine> _printHeld = PrintHeldLine;
private static bool _incomingByPattern; // AddTextToScroll itself was found by its pattern
private static bool _replayReady; // PStringBase<wchar_t> ctor/dtor/null buffer found by pattern
private static int _holdSwitch = 1; // /rc chathold on|off (not saved; on at every start)
private static long _drainBeatMs; // last AcMainThreadQueue.Drain on AC's main thread
private static int _eatLogCount;
[ThreadStatic] private static int _replayDepth; // inside our own print of a held line
// Captured live from the outgoing-chat detour so we can re-invoke AC's outgoing
// chat function DIRECTLY (deterministic) instead of simulating keystrokes into
// the native chat bar. Keystroke simulation depends on the bar's open/closed
@ -116,6 +130,9 @@ internal static class ChatCallbackHooks
{
incomingVerified = true;
incomingStatus = $"0x{_incomingAddress.ToInt32():X8} ({incomingMode})";
if (_originalIncomingChatAddTextPtr != IntPtr.Zero)
_replayReady = _incomingByPattern && TryPrepareReplay(textSection);
RynthLog.Compat($"Compat: incoming chat hold {(_replayReady ? "ready" : "unavailable (lines print before plugins hear them, as before)")}.");
}
if (EnableOutgoingHook && !OutgoingInstalled)
@ -237,6 +254,7 @@ internal static class ChatCallbackHooks
unsafe
{
_incomingAddress = resolved.Address;
_incomingByPattern = resolved.Source == HookResolver.ResolveSource.PatternScan;
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int> pDetour = &IncomingChatAddTextDetour;
MinHook.Hook(_incomingAddress, (IntPtr)pDetour, out _originalIncomingChatAddTextPtr);
}
@ -277,23 +295,199 @@ internal static class ChatCallbackHooks
private static unsafe int IncomingChatAddTextDetour(IntPtr thisPtr, IntPtr text, uint chatType, uint unknown, IntPtr stringInfo)
{
RecursionGuard.Tick("ChatCallbackHooks.IncomingChatAddText");
// 1. Read string BEFORE original — buffer may be freed after
string? line = (text != IntPtr.Zero) ? ReadIncomingChatLine(text, chatType) : null;
// 2. Call original
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int>)_originalIncomingChatAddTextPtr;
// 1. Read string BEFORE original — buffer may be freed after
bool truncated = false;
string? raw = (text != IntPtr.Zero) ? ReadIncomingChatRaw(text, chatType, out truncated) : null;
string? line = raw?.TrimEnd('\r', '\n');
// 1b. The engine's own server-data replies (Aelrynth /mastery-data it asked for):
// not drawn, not held and not passed on. Every caller of AddTextToScroll ignores its
// return value (all 394 call sites in the retail client, checked 2026-10-01).
// Not inside our own reprint of a held line: that line was already offered here when
// it first arrived (and wasn't ours, or it wouldn't have been held), so offering it
// again could take a stale line for the answer to a request sent since.
if (line != null && _replayDepth == 0 && EatOwnReply(line))
return 0;
// 2. Hold the line until the plugins have heard it (IncomingChatHold.cs): AC prints it
// from the next main-thread drain unless a plugin eats it. Anything unexpected here
// falls through to the old path: print now, plugins hear it afterwards.
ChatHoldDecision decision = ChatHoldDecision.PassThrough;
bool handedOver = false; // QueueChatWindowText already saw the line (engine HUD feed and plugins)
try
{
decision = DecideHold(raw, truncated, stringInfo);
if (decision == ChatHoldDecision.Hold)
{
var held = new HeldChatLine(raw!, chatType, unknown, thisPtr, Environment.TickCount64);
handedOver = true;
if (PluginManager.QueueChatWindowText(line, chatType, held))
{
_held.Add(held);
return 1; // what AddTextToScroll returns for a line it handled
}
decision = ChatHoldDecision.FlushThenPassThrough; // plugins aren't taking chat right now
}
if (decision == ChatHoldDecision.FlushThenPassThrough)
ReleaseHeld(flushAll: true);
}
catch
{
// Fall through and print. (If the line was handed over, it isn't handed over twice.)
}
// 3. Call original
int result = pOriginal(thisPtr, text, chatType, unknown, stringInfo);
// 3. Queue AFTER original returns — game state is consistent
if (line != null)
// 4. Queue AFTER original returns — game state is consistent
if (line != null && !handedOver)
QueueIncomingChatLine(line, chatType);
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static string? ReadIncomingChatLine(IntPtr pStringBase, uint chatType)
private static bool EatOwnReply(string line)
{
try { return MasteryFeed.OnIncomingLine(line); }
catch { return false; }
}
/// <summary>Hold this line, print it now, or print everything held and then it. AC's main thread or not.</summary>
private static ChatHoldDecision DecideHold(string? raw, bool truncated, IntPtr stringInfo)
{
bool onMain = MainThreadGuard.IsOnMainThread();
bool replaying = _replayDepth > 0;
// Lines whose verdict is in print first, so a line printed now keeps its place after them.
if (onMain && !replaying && _held.Count > 0)
ReleaseHeld(flushAll: false);
var inputs = new ChatHoldInputs(
Enabled: HoldActive,
Disarmed: AcMainThreadQueue.IsDisarmed,
OnMainThread: onMain,
Replaying: replaying,
HasText: !string.IsNullOrEmpty(raw),
Truncated: truncated,
HasStringInfo: stringInfo != IntPtr.Zero,
NowMs: Environment.TickCount64,
PumpBeatMs: PluginManager.ChatPumpBeatMs,
DrainBeatMs: Volatile.Read(ref _drainBeatMs),
HeldCount: _held.Count);
return HeldChatQueue.Decide(inputs);
}
private static bool HoldActive => _replayReady && Volatile.Read(ref _holdSwitch) != 0;
/// <summary>
/// Called by AcMainThreadQueue.Drain (Client::UseTime and EndScene, AC's main thread): the
/// beat that says held lines will be printed, then prints the ones that may print now.
/// After teardown starts it prints everything still held.
/// </summary>
internal static void OnMainThreadDrain(bool disarmed)
{
if (!MainThreadGuard.IsOnMainThread())
return;
if (!disarmed)
Volatile.Write(ref _drainBeatMs, Environment.TickCount64);
if (_held.Count == 0 || _replayDepth > 0)
return;
try { ReleaseHeld(flushAll: disarmed || !HoldActive); }
catch { }
}
/// <summary>Prints held lines that may print now (AC's main thread, never inside our own print).</summary>
private static void ReleaseHeld(bool flushAll)
{
long eatenBefore = _held.EatenTotal;
long lateBefore = _held.TimedOutTotal;
_held.Release(Environment.TickCount64, flushAll, _printHeld);
if (_held.EatenTotal != eatenBefore && _eatLogCount < 5)
{
_eatLogCount++;
RynthLog.Compat($"Compat: chat hold kept {_held.EatenTotal - eatenBefore} line(s) a plugin ate out of AC's chat window (total {_held.EatenTotal}).");
}
if (_held.TimedOutTotal != lateBefore && _held.TimedOutTotal <= 5)
RynthLog.Compat($"Compat: chat hold printed {_held.TimedOutTotal - lateBefore} line(s) without a plugin verdict after {HeldChatQueue.HoldTimeoutMs} ms (plugin pump slow; total {_held.TimedOutTotal}).");
}
/// <summary>Prints one held line through AC's own AddTextToScroll, exactly as it came in.</summary>
private static unsafe void PrintHeldLine(HeldChatLine h)
{
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int>)_originalIncomingChatAddTextPtr;
_replayDepth++;
try
{
fixed (char* chars = h.Raw) // .NET strings end in a NUL, as the PStringBase ctor needs
{
var wide = OutgoingWidePString.Create((ushort*)chars);
try
{
// StringInfo is always null here: lines that came with one are never held.
pOriginal(h.This, (IntPtr)(&wide), h.ChatType, h.Unknown, IntPtr.Zero);
}
finally { wide.Dispose(); }
}
}
finally { _replayDepth--; }
}
/// <summary>
/// Holding needs to build AC strings itself to print a held line: the PStringBase&lt;wchar_t&gt;
/// ctor, dtor and empty buffer, all found by pattern (never a guessed address).
/// </summary>
private static bool TryPrepareReplay(AcClientTextSection textSection)
{
try
{
var ctor = HookResolver.Resolve(textSection, "ChatCallback.PStringW_ctor", PatWidePStringCtor, 0x00402730);
var dtor = HookResolver.Resolve(textSection, "ChatCallback.PStringW_dtor", PatWidePStringDtor, 0x004011B0);
var nul = HookResolver.ResolveData(textSection, "ChatCallback.PStringW_NullBuffer", PatXrefWideNullBuffer, 2, 0x00818340);
if (ctor.Source != HookResolver.ResolveSource.PatternScan
|| dtor.Source != HookResolver.ResolveSource.PatternScan
|| nul.Source != HookResolver.ResolveSource.PatternScan)
return false;
// Resolve OutgoingWidePString's statics now, not on AC's thread at the first held line.
return OutgoingWidePString.Warm();
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: chat hold setup failed - {ex.GetType().Name}: {ex.Message}");
return false;
}
}
/// <summary>/rc chathold on|off.</summary>
internal static void SetHoldEnabled(bool on) => Volatile.Write(ref _holdSwitch, on ? 1 : 0);
internal static bool HoldSwitchOn => Volatile.Read(ref _holdSwitch) != 0;
/// <summary>One line for /rc chathold status.</summary>
internal static string HoldStatusText()
{
string state = !IncomingInstalled ? "unavailable (incoming chat isn't hooked; in Decal bridge mode Decal owns it)"
: !_replayReady ? "unavailable (the client's string functions weren't found, or another hook sits on AddTextToScroll)"
: HoldSwitchOn ? "ON" : "OFF";
return $"Chat hold is {state}. Since start: {_held.HeldTotal} held, {_held.ShownTotal} shown, " +
$"{_held.EatenTotal} eaten by plugins, {_held.TimedOutTotal} shown late (no verdict in {HeldChatQueue.HoldTimeoutMs} ms), " +
$"{_held.PrintFailedTotal} print errors; {_held.Count} waiting now.";
}
/// <summary>
/// Reads the line exactly as AC got it (line breaks kept). <paramref name="truncated"/> is
/// true when it is longer than <see cref="MaxIncomingChatChars"/>: plugins get the first
/// part, as before, but such a line is never held (it couldn't be printed back whole).
/// A server data line ("~ael1 ...") is read in full instead (up to
/// <see cref="MaxDataLineChars"/>) but still reports truncated, so it is never held either.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private static string? ReadIncomingChatRaw(IntPtr pStringBase, uint chatType, out bool truncated)
{
truncated = false;
try
{
// PStringBase<ushort> is a 4-byte struct: a single pointer to
@ -311,16 +505,32 @@ internal static class ChatCallbackHooks
break;
length++;
}
// Lines this long are never held (chat-eat's limit, unchanged): they print at once
// and plugins hear them afterwards, as before. Set from the usual cap BEFORE the
// data-line read below, so a long data line read in full still counts as too long.
truncated = length >= MaxIncomingChatChars;
string? line = length > 0
? Marshal.PtrToStringUni(charData, length)?.TrimEnd('\r', '\n')
: null;
// A server data line ("~ael1 {json}", one line for every skill) runs past the
// usual cap: read it to its terminator, up to 64K characters.
if (length == MaxIncomingChatChars
&& MasteryWire.IsDataLine(Marshal.PtrToStringUni(charData, 40)))
{
while (length < MaxDataLineChars)
{
short ch = Marshal.ReadInt16(charData, length * 2);
if (ch == 0)
break;
length++;
}
}
string? raw = length > 0 ? Marshal.PtrToStringUni(charData, length) : null;
int count = Interlocked.Increment(ref _incomingCallCount);
if (count <= 0)
RynthLog.Verbose($"Compat: incoming chat #{count} type={chatType} len={length}");
return line;
return raw;
}
catch { return null; }
}
@ -642,6 +852,17 @@ internal static class ChatCallbackHooks
return value;
}
/// <summary>From a NUL-terminated buffer the caller keeps pinned for the call.</summary>
public static OutgoingWidePString Create(ushort* chars)
{
var value = new OutgoingWidePString { CharBuffer = Marshal.ReadIntPtr(NullWideBufferVa) };
Ctor(&value, chars);
return value;
}
/// <summary>Runs the static resolution now; true when all three addresses are set.</summary>
public static bool Warm() => NullWideBufferVa != IntPtr.Zero && Ctor != null && Dtor != null;
public void Dispose()
{
fixed (OutgoingWidePString* ptr = &this)

View file

@ -211,6 +211,35 @@ internal static unsafe class ChatCommandDispatcher
}
}
/// <summary>
/// Sends a server command quietly: Talk text that starts with '@', which ACE runs as
/// a command (GameActionTalk) exactly as it runs a typed "/command" the client
/// forwards. Straight to CM_Communication::Event_Talk: no plugin pre-dispatch, no
/// chat-bar keystrokes, nothing said aloud. Printable ASCII only. AC's main thread
/// only (the Aelrynth mastery feed calls it from MainThreadSnapshots.Tick); refuses
/// anywhere else rather than queueing.
/// </summary>
public static bool SendServerCommand(string atCommand)
{
if (!MainThreadGuard.IsOnMainThread())
return false;
if (string.IsNullOrEmpty(atCommand) || atCommand.Length < 2 || atCommand[0] != '@' || atCommand.Length > 200)
return false;
foreach (char c in atCommand)
if (c < 0x20 || c > 0x7E)
return false;
try
{
LogoffOriginProbe.RecordChat("ServerCommand", atCommand);
return DispatchSay(atCommand);
}
catch (Exception ex)
{
RynthLog.Compat($"ChatDispatch: server command '{atCommand}' failed - {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static string ExpandShorthand(string text)
{
if (StartsWithCmd(text, "/s ")) return "/say " + text.Substring(3);
@ -310,6 +339,11 @@ internal static unsafe class ChatCommandDispatcher
/// </summary>
private static bool DispatchRaw(string command)
{
// Decal bridge mode: AC's outgoing-chat function belongs to Decal (our hook is not
// installed) and there is no window subclass for keystrokes, so the line goes to
// Decal's InvokeChatParser, which the bridge runs on AC's main thread.
if (DecalBridgeHost.Active)
return DecalBridgeHost.TryInvokeChatParser(command);
if (ChatCallbackHooks.TryDispatchDirect(command))
return true;
return SimulateChatInput(command);

View file

@ -41,10 +41,15 @@ internal static class ChatFileDispatcher
private const int DebounceMs = 200;
public static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"dispatch.txt");
// RYNTHCORE_DISPATCH_FILE gives a test client its own file: the default one is
// watched by every running client.
public static string FilePath =>
Environment.GetEnvironmentVariable("RYNTHCORE_DISPATCH_FILE") is { Length: > 0 } overridePath
? overridePath
: Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"dispatch.txt");
public static void Start()
{

View file

@ -52,6 +52,11 @@ internal static class ChatHooks
private static ListenToElementMessageDelegate? _listenDetour;
private static IntPtr _gmMainChatInstance;
private static IntPtr _gmMainChatVtable; // the instance's vtable when captured
// Set when a logoff is requested, cleared when the logout completes: AC frees
// the chatbox during the logoff, and ListenToElementMessage can still fire on
// the dying one, so it is not captured again in between.
private static volatile bool _logoffInProgress;
private static IntPtr _uiElementSetVisibleAddress;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
@ -123,8 +128,11 @@ internal static class ChatHooks
private static void ListenDetour(IntPtr thisPtr, IntPtr msgInfo)
{
RecursionGuard.Tick("ChatHooks.Listen");
if (thisPtr != IntPtr.Zero)
if (thisPtr != IntPtr.Zero && !_logoffInProgress && thisPtr != _gmMainChatInstance)
{
_gmMainChatVtable = ClientObjectHooks.IsReadablePointer(thisPtr) ? Marshal.ReadIntPtr(thisPtr) : IntPtr.Zero;
_gmMainChatInstance = thisPtr;
}
if (++_listenFires <= 3)
RynthLog.Compat($"ChatHooks: Listen fired #{_listenFires} this=0x{thisPtr.ToInt32():X8}");
try { _originalListen!(thisPtr, msgInfo); }
@ -145,6 +153,12 @@ internal static class ChatHooks
IntPtr inst = _gmMainChatInstance;
if (inst == IntPtr.Zero) return;
if (_uiElementSetVisibleAddress == IntPtr.Zero) return;
if (!StillAlive(inst))
{
RynthLog.Compat($"ChatHooks: chatbox 0x{inst.ToInt32():X8} is gone (freed); dropped until it is captured again.");
_gmMainChatInstance = IntPtr.Zero;
return;
}
if (RynthChatOwnsChat)
{
@ -168,9 +182,40 @@ internal static class ChatHooks
}
}
/// <summary>
/// Second guard against a freed chatbox: its memory must still be readable
/// and still start with the vtable it had when captured. (A freed object's
/// first bytes are overwritten by the heap; the 2026-09-28 14:41 crash called
/// SetVisible on one and jumped to 0x0000FFFF.)
/// </summary>
private static bool StillAlive(IntPtr inst)
{
if (!ClientObjectHooks.IsReadablePointer(inst)) return false;
IntPtr vtable = Marshal.ReadIntPtr(inst);
if (_gmMainChatVtable == IntPtr.Zero) _gmMainChatVtable = vtable;
return vtable == _gmMainChatVtable;
}
/// <summary>
/// A logoff was requested (LogoffOriginProbe): drop the chatbox now. The logout
/// notice (ResetCachedInstance) comes after AC has already freed it, and the
/// per-frame SetVisible in between crashed on the freed object (2026-09-28).
/// AC's main thread.
/// </summary>
public static void OnLogoffRequested()
{
_logoffInProgress = true;
_gmMainChatInstance = IntPtr.Zero;
_gmMainChatVtable = IntPtr.Zero;
_isHiddenAsserted = true;
}
/// <summary>The logout completed (PluginManager's logout dispatch): the next chatbox is a new one.</summary>
public static void ResetCachedInstance()
{
_gmMainChatInstance = IntPtr.Zero;
_gmMainChatVtable = IntPtr.Zero;
_logoffInProgress = false;
_isHiddenAsserted = true; // re-assert on the next instance, as at start-up
}
}

View file

@ -0,0 +1,572 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ClientActionGates.cs
//
// The acclient's own item-action gates, which lock the player out of using,
// equipping and moving items while chat, clicks and the inventory still work.
//
// Every item action the client makes (double-click use, equip, drag to a pack,
// pick up, drop, give, split, merge, vendor buy/sell) first asks
// ACCWeenieObject::IsPlayerReadyToMakeInventoryRequest. That refuses when
// either of two globals is set, and prints a line in chat:
//
// 1. The PENDING INVENTORY REQUEST slot (4 dwords in .data, 0x00871ED0..DC on
// the 4,841,472-byte client): request type, object id and the time it was
// sent. ACCWeenieObject::RecordRequest (and the UIAttempt* callers, inline)
// fill it when the client sends an inventory request. Only the server's
// answer ABOUT THAT SAME OBJECT empties it: ServerSaysMoveItem,
// ServerSaysSetStackSize, ServerSaysAttemptFailed (0x00A0), the ground
// container view/close (RecordResponse) or the vendor list re-send. Those
// are ACCWeenieObject methods, so when the object is no longer in the
// client's object table (the corpse decayed, a later corpse open queued the
// previous corpse's contents for destruction, a stack merged away) the
// answer finds nothing and the slot is never emptied. The time field is
// written and never read: there is no timeout. Logging off does not empty
// it either, and CPlayerSystem::LogOffCharacter/UseTime wait for it, so the
// logoff sits at "Logging off..." forever. Refusal text:
// "You can only move or use one item at a time".
//
// 2. The ATTACKING flag (0x00871EE0): set by
// ClientCombatSystem::HandleCommenceAttackEvent (0x01B8), cleared only by
// HandleAttackDoneEvent (0x01A7). A lost AttackDone leaves it set for the
// rest of the process. Refusal text:
// "You cannot move or use an item while attacking".
//
// Neither is the busy count (ClientUISystem m_cBusy): AC only reads m_cBusy to
// pick the cursor (UpdateCursorState: != 0 shows the busy cursor), so a zeroed
// or negative count changes the cursor and nothing else. That is why every
// busy-count reset (/ra clearbusy, /ra panic, the watchdogs) left this lock
// in place.
//
// This file:
// * resolves both gates by pattern (two independent code sites each, which
// must agree, or the gate is left alone);
// * reads them for /rc actionstate and the heartbeat (read-only, any thread);
// * on AC's main thread, empties a pending request whose object has been
// gone from the client for MissingObjectGraceMs, or that has had no answer
// for PendingTimeoutMs, and clears an attacking flag that has stayed set
// with no AttackDone for AttackStaleMs. Emptying the slot is exactly what
// AC's own RecordResponse does when an answer arrives; a late real answer
// after that finds nothing pending and changes nothing;
// * does the same on demand for /rc unlockactions (latched when off-thread).
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class ClientActionGates
{
// ACCWeenieObject::RecordRequest(objectId, type) — the whole function:
// mov eax,[esp+4]; mov ecx,[esp+8]; mov edx,[TimerCurTime]; mov [reqObj],eax;
// mov eax,[TimerCurTime+4]; mov [reqType],ecx; mov [reqTime],edx; mov [reqTime+4],eax; ret
private static readonly byte?[] RecordRequestPattern =
[
0x8B, 0x44, 0x24, 0x04,
0x8B, 0x4C, 0x24, 0x08,
0x8B, 0x15, null, null, null, null, // +10 TimerCurTime (low dword)
0xA3, null, null, null, null, // +15 reqObj
0xA1, null, null, null, null, // +20 TimerCurTime (high dword)
0x89, 0x0D, null, null, null, null, // +26 reqType
0x89, 0x15, null, null, null, null, // +32 reqTime (low)
0xA3, null, null, null, null, // +37 reqTime (high)
0xC3
];
// ACCWeenieObject::RecordResponse(objectId) — clears the slot when the id matches:
// mov eax,[esp+4]; cmp eax,[reqObj]; jne +16h; xor eax,eax;
// mov [reqObj],eax; mov [reqType],eax; mov [reqTime],eax; mov [reqTime+4],eax; ret
private static readonly byte?[] RecordResponsePattern =
[
0x8B, 0x44, 0x24, 0x04,
0x3B, 0x05, null, null, null, null, // +6 reqObj
0x75, 0x16,
0x33, 0xC0,
0xA3, null, null, null, null, // +15 reqObj
0xA3, null, null, null, null, // +20 reqType
0xA3, null, null, null, null, // +25 reqTime (low)
0xA3, null, null, null, null, // +30 reqTime (high)
0xC3
];
// ClientCombatSystem::HandleAttackDoneEvent: mov [esi+3C],bl; cmp [esp+0C],ebx;
// mov [esi+3D],bl; mov [attacking],ebx
private static readonly byte?[] AttackDonePattern =
[
0x88, 0x5E, 0x3C, 0x39, 0x5C, 0x24, 0x0C, 0x88, 0x5E, 0x3D,
0x89, 0x1D, null, null, null, null // +12 attacking
];
// ClientCombatSystem::HandleCommenceAttackEvent tail: mov [attacking],1;
// call GetUISystem; mov ecx,eax; pop esi; add esp,4; jmp IncrementBusyCount
private static readonly byte?[] CommenceAttackPattern =
[
0xC7, 0x05, null, null, null, null, // +2 attacking
0x01, 0x00, 0x00, 0x00,
0xE8, null, null, null, null,
0x8B, 0xC8, 0x5E, 0x83, 0xC4, 0x04, 0xE9
];
// Resolved addresses (0 = not resolved; the gate is then read-only-unavailable).
private static int _reqTypeVa, _reqObjVa, _reqTimeVa, _timerVa, _attackVa;
private static bool _requestReady, _attackReady, _initialized;
private static string _status = "Not initialized.";
// Repair policy. A normal request is answered within a network round trip
// (a ground pickup adds the walk to the item); a single attack swing lasts a
// few seconds and every AttackDone empties the flag between swings. CheckWatchdog
// runs before every inbound game event and after every game tick, so the
// flag's zero window between AttackDone and the next CommenceAttack is always
// sampled at least once.
// 10 s (was 60): a real answer comes within about a second, and with healing interrupting
// melee/looting (2026.10.4.2) a lost answer locked every item action for a full minute.
private const long PendingTimeoutMs = 10_000;
private const long MissingObjectGraceMs = 5_000;
// 12 s in melee/missile (was 30); outside them no attack can be running, so 1.5 s.
private const long AttackStaleMs = 12_000;
private const long AttackStaleOutOfStanceMs = 1_500;
private const long PendingCheckIntervalMs = 500;
private const long ChatNoticeCooldownMs = 10 * 60_000;
// Main-thread tracking state.
private static long _trackedKey;
private static long _pendingSeenAt;
private static long _objectMissingSince;
private static long _lastPendingCheck;
private static long _attackSetSince;
private static long _lastChatNoticeAt = long.MinValue / 2;
private static long _pendingClears;
private static long _attackClears;
private static int _unlockRequested;
public static bool IsRequestGateAvailable => _requestReady;
public static bool IsAttackGateAvailable => _attackReady;
public static string StatusMessage => _status;
public static long PendingClearCount => Interlocked.Read(ref _pendingClears);
public static long AttackClearCount => Interlocked.Read(ref _attackClears);
public static void Initialize()
{
if (_initialized)
return;
_initialized = true;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
_status = "acclient .text not readable.";
RynthLog.Compat($"ClientActionGates: {_status}");
return;
}
string req = ResolveRequestSlot(text);
string atk = ResolveAttackFlag(text);
_status = $"request slot: {req}; attack flag: {atk}.";
RynthLog.Compat($"ClientActionGates: {_status}");
}
private static string ResolveRequestSlot(AcClientTextSection text)
{
if (!TryFindUnique(text, RecordRequestPattern, out int a))
return "RecordRequest pattern not found (unique)";
if (!TryFindUnique(text, RecordResponsePattern, out int b))
return "RecordResponse pattern not found (unique)";
byte[] t = text.Bytes;
int obj = BitConverter.ToInt32(t, a + 15);
int type = BitConverter.ToInt32(t, a + 26);
int time = BitConverter.ToInt32(t, a + 32);
int timeHi = BitConverter.ToInt32(t, a + 37);
int timerLo = BitConverter.ToInt32(t, a + 10);
int timerHi = BitConverter.ToInt32(t, a + 20);
bool consistent =
type == obj - 4 && time == obj + 4 && timeHi == obj + 8 && timerHi == timerLo + 4
&& BitConverter.ToInt32(t, b + 6) == obj && BitConverter.ToInt32(t, b + 15) == obj
&& BitConverter.ToInt32(t, b + 20) == type && BitConverter.ToInt32(t, b + 25) == time
&& BitConverter.ToInt32(t, b + 30) == timeHi;
if (!consistent)
return $"code sites disagree (obj=0x{obj:X8} type=0x{type:X8})";
if (!ClientObjectHooks.IsWritablePointer(new IntPtr(type))
|| !ClientObjectHooks.IsWritablePointer(new IntPtr(timeHi))
|| !ClientObjectHooks.IsReadablePointer(new IntPtr(timerLo)))
return $"globals not mapped (type=0x{type:X8})";
_reqTypeVa = type;
_reqObjVa = obj;
_reqTimeVa = time;
_timerVa = timerLo;
_requestReady = true;
return $"0x{type:X8} (type) / 0x{obj:X8} (object)";
}
private static string ResolveAttackFlag(AcClientTextSection text)
{
if (!TryFindUnique(text, AttackDonePattern, out int a))
return "HandleAttackDoneEvent pattern not found (unique)";
if (!TryFindUnique(text, CommenceAttackPattern, out int b))
return "HandleCommenceAttackEvent pattern not found (unique)";
int flagA = BitConverter.ToInt32(text.Bytes, a + 12);
int flagB = BitConverter.ToInt32(text.Bytes, b + 2);
if (flagA != flagB)
return $"code sites disagree (0x{flagA:X8} vs 0x{flagB:X8})";
if (!ClientObjectHooks.IsWritablePointer(new IntPtr(flagA)))
return $"global 0x{flagA:X8} not mapped";
_attackVa = flagA;
_attackReady = true;
return $"0x{flagA:X8}";
}
private static bool TryFindUnique(AcClientTextSection text, byte?[] pattern, out int offset)
{
offset = PatternScanner.FindPattern(text.Bytes, pattern);
if (offset < 0)
return false;
return PatternScanner.FindPatternInRegion(text.Bytes, pattern, offset + 1, text.Bytes.Length) < 0;
}
// ── Reads (any thread: plain loads from acclient .data, which never unmaps) ──
public static bool TryReadPending(out uint type, out uint objectId, out double ageSeconds)
{
type = 0;
objectId = 0;
ageSeconds = -1;
if (!_requestReady)
return false;
type = unchecked((uint)Marshal.ReadInt32(new IntPtr(_reqTypeVa)));
objectId = unchecked((uint)Marshal.ReadInt32(new IntPtr(_reqObjVa)));
double issued = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(new IntPtr(_reqTimeVa)));
double now = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(new IntPtr(_timerVa)));
if (type != 0 && issued > 0 && now >= issued && now - issued < 1e7)
ageSeconds = now - issued;
return true;
}
public static bool TryReadAttacking(out bool attacking)
{
attacking = false;
if (!_attackReady)
return false;
attacking = Marshal.ReadInt32(new IntPtr(_attackVa)) != 0;
return true;
}
public static string RequestTypeName(uint type) => type switch
{
0 => "none",
1 => "merge",
2 => "split",
3 => "move",
4 => "pick up",
5 => "put in container",
6 => "drop",
7 => "wield",
9 => "give",
10 => "vendor buy/sell",
_ => $"request {type}",
};
/// <summary>Short heartbeat field, empty when both gates are open.</summary>
public static string HeartbeatField()
{
try
{
string s = string.Empty;
if (TryReadPending(out uint type, out _, out double age) && type != 0)
s = age >= 0 ? $" req={type}/{age:0}s" : $" req={type}";
if (TryReadAttacking(out bool attacking) && attacking)
s += " atk=1";
return s;
}
catch { return string.Empty; }
}
// ── Main-thread watchdog ─────────────────────────────────────────────────
/// <summary>Drop the tracking state at logout / client close (the slot itself is AC's).</summary>
public static void ResetTracking()
{
_trackedKey = 0;
_pendingSeenAt = 0;
_objectMissingSince = 0;
_attackSetSince = 0;
}
/// <summary>
/// Called from BusyCountHooks.CheckWatchdog on every game tick and before every
/// inbound game event. Main thread only; any other thread returns at once.
/// </summary>
public static void Tick(long now, bool inWorldTransition)
{
if (!MainThreadGuard.IsOnMainThread())
return;
if (Interlocked.Exchange(ref _unlockRequested, 0) == 1)
{
foreach (string line in UnlockNow("manual (/rc unlockactions)"))
RynthLog.Compat($"ClientActionGates: {line}");
}
TickAttackFlag(now, inWorldTransition);
if (now - _lastPendingCheck < PendingCheckIntervalMs)
return;
_lastPendingCheck = now;
TickPendingRequest(now, inWorldTransition);
}
private static void TickAttackFlag(long now, bool inWorldTransition)
{
if (!_attackReady)
return;
bool attacking = Marshal.ReadInt32(new IntPtr(_attackVa)) != 0;
if (!attacking || inWorldTransition)
{
_attackSetSince = 0;
return;
}
if (_attackSetSince == 0)
{
_attackSetSince = now;
return;
}
// Peace or Magic mode (kits, looting, casting happen here): no melee/missile attack
// can be in progress, so a set flag is a lost AttackDone. Clear it quickly.
int mode = CombatModeHooks.ReadCurrentCombatMode();
bool attackStance = mode == CombatActionHooks.CombatModeMelee || mode == CombatActionHooks.CombatModeMissile;
if (now - _attackSetSince < (attackStance ? AttackStaleMs : AttackStaleOutOfStanceMs))
return;
long heldMs = now - _attackSetSince;
_attackSetSince = 0;
if (ClearAttackFlag())
{
RynthLog.Compat($"ClientActionGates: attacking flag held {heldMs / 1000}s with no AttackDone — cleared. AC was refusing every item use/move ('while attacking').");
NotifyChat("Item actions were locked (the client never got the end of an attack). Unlocked.");
}
}
private static void TickPendingRequest(long now, bool inWorldTransition)
{
if (!_requestReady)
return;
TryReadPending(out uint type, out uint objectId, out double acAge);
if (type == 0)
{
_trackedKey = 0;
_objectMissingSince = 0;
return;
}
long issuedBits = Marshal.ReadInt64(new IntPtr(_reqTimeVa));
long key = unchecked(((long)type << 56) ^ ((long)objectId << 24) ^ issuedBits);
if (key != _trackedKey || _pendingSeenAt == 0)
{
_trackedKey = key;
_pendingSeenAt = now;
_objectMissingSince = 0;
}
// Portal / death: objects leave and re-enter the client wholesale and
// answers can arrive after the world settles. Judge afresh afterwards.
if (inWorldTransition)
{
_pendingSeenAt = now;
_objectMissingSince = 0;
return;
}
string? reason = null;
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
bool exists = objectId != 0 && ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out _);
if (exists)
_objectMissingSince = 0;
else if (_objectMissingSince == 0)
_objectMissingSince = now;
else if (now - _objectMissingSince >= MissingObjectGraceMs)
reason = "its object is no longer in the client, so no answer can clear it";
}
if (reason == null && now - _pendingSeenAt >= PendingTimeoutMs)
reason = $"no answer for {(now - _pendingSeenAt) / 1000}s";
if (reason == null)
return;
if (ClearPendingRequest())
{
RynthLog.Compat(
$"ClientActionGates: cleared a stuck item request — {RequestTypeName(type)} (type {type}) on 0x{objectId:X8}" +
$"{(acAge >= 0 ? $", sent {acAge:0}s ago" : string.Empty)}: {reason}. AC was refusing every item use/move/equip ('one item at a time').");
NotifyChat("Item actions were locked (the client was still waiting on an old item request). Unlocked.");
}
_trackedKey = 0;
_objectMissingSince = 0;
}
private static void NotifyChat(string text)
{
// Called from the main-thread watchdog only; the chat line itself is
// written by the queue's drain.
if (!MainThreadGuard.IsOnMainThread())
return;
long now = Environment.TickCount64;
if (now - _lastChatNoticeAt < ChatNoticeCooldownMs)
return;
_lastChatNoticeAt = now;
AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, 1);
}
/// <summary>
/// Empty AC's pending-inventory-request slot, the same four stores
/// RecordResponse makes when the server answers. Main thread only.
/// </summary>
private static bool ClearPendingRequest()
{
if (!MainThreadGuard.IsOnMainThread() || !_requestReady)
return false;
Marshal.WriteInt32(new IntPtr(_reqObjVa), 0);
Marshal.WriteInt32(new IntPtr(_reqTypeVa), 0);
Marshal.WriteInt32(new IntPtr(_reqTimeVa), 0);
Marshal.WriteInt32(new IntPtr(_reqTimeVa + 4), 0);
Interlocked.Increment(ref _pendingClears);
return true;
}
/// <summary>Clear AC's attacking flag, as HandleAttackDoneEvent does. Main thread only.</summary>
private static bool ClearAttackFlag()
{
if (!MainThreadGuard.IsOnMainThread() || !_attackReady)
return false;
Marshal.WriteInt32(new IntPtr(_attackVa), 0);
Interlocked.Increment(ref _attackClears);
return true;
}
/// <summary>
/// /rc unlockactions: open both gates now and repair a negative busy count.
/// On AC's main thread it runs at once and returns what it did; elsewhere it
/// latches for the next watchdog tick and says so.
/// </summary>
public static string[] RequestUnlock()
{
if (!MainThreadGuard.IsOnMainThread())
{
Interlocked.Exchange(ref _unlockRequested, 1);
return ["Unlock queued for the next game tick."];
}
return UnlockNow("manual (/rc unlockactions)");
}
private static string[] UnlockNow(string why)
{
if (!MainThreadGuard.IsOnMainThread())
return ["Unlock skipped: not on the game thread."];
var done = new System.Collections.Generic.List<string>();
if (TryReadPending(out uint type, out uint objectId, out double age) && type != 0)
{
if (ClearPendingRequest())
done.Add($"cleared the pending item request ({RequestTypeName(type)} on 0x{objectId:X8}{(age >= 0 ? $", {age:0}s old" : string.Empty)})");
}
if (TryReadAttacking(out bool attacking) && attacking)
{
if (ClearAttackFlag())
done.Add("cleared the attacking flag");
}
if (BusyCountHooks.RepairNegativeBusy(out int was))
done.Add($"reset a negative busy count ({was} -> 0)");
ResetTracking();
string summary = done.Count == 0
? "Nothing to unlock: no pending item request, no attacking flag, busy count not negative."
: "Unlocked: " + string.Join("; ", done) + ".";
RynthLog.Compat($"ClientActionGates: {why}: {summary}");
return [summary];
}
// ── /rc actionstate ─────────────────────────────────────────────────────
public static string[] DescribeLines()
{
var lines = new System.Collections.Generic.List<string>();
lines.Add("Action state (what the client checks before a use, equip or move):");
// 1. Pending inventory request.
if (!_requestReady)
{
lines.Add($" Item request: unavailable ({_status})");
}
else
{
TryReadPending(out uint type, out uint objectId, out double age);
if (type == 0)
{
lines.Add(" Item request: none (open)");
}
else
{
string name = string.Empty;
bool exists = false;
if (MainThreadGuard.IsOnMainThread() && objectId != 0)
{
exists = ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out _);
if (exists) ClientObjectHooks.TryGetObjectName(objectId, out name);
}
lines.Add($" Item request: WAITING - {RequestTypeName(type)} (type {type}) on 0x{objectId:X8}" +
$"{(name.Length > 0 ? $" '{name}'" : string.Empty)}" +
$"{(age >= 0 ? $", sent {age:0.0}s ago" : string.Empty)}, object {(exists ? "still in client" : "GONE from client")}.");
lines.Add(" While this is set the client refuses every use/equip/move ('You can only move or use one item at a time') and a logoff waits forever.");
}
}
// 2. Attacking flag.
if (!_attackReady)
lines.Add(" Attacking flag: unavailable");
else
{
TryReadAttacking(out bool attacking);
long held = _attackSetSince == 0 ? 0 : (Environment.TickCount64 - _attackSetSince) / 1000;
lines.Add(attacking
? $" Attacking flag: SET{(held > 0 ? $" ({held}s)" : string.Empty)} - item use/move refused ('while attacking') until the server's AttackDone."
: " Attacking flag: clear");
}
// 3. Busy count (cursor only).
string busy = BusyCountHooks.TryReadRealBusy(out int real) ? real.ToString() : "unreadable";
lines.Add($" Busy count m_cBusy: {busy} (engine shadow {BusyCountHooks.ShadowBusyCount}, pending reconcile {BusyCountHooks.PendingReconcileDelta}, force-clears {BusyCountHooks.ForceClearCount}, reconciles {BusyCountHooks.ReconcileCount}, negative repairs {BusyCountHooks.NegativeRepairCount}). Non-zero only shows the busy cursor.");
// 4. ClientUISystem: target mode / open container / vendor.
IntPtr ui = ClientHelperHooks.ReadUiSystemPtr();
if (ui != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(ui, 0x40))
{
uint ground = unchecked((uint)Marshal.ReadInt32(ui + 0x18));
uint vendor = unchecked((uint)Marshal.ReadInt32(ui + 0x20));
int targetMode = Marshal.ReadInt32(ui + 0x2C);
string tm = targetMode switch { 0 => "none", 1 => "1 (use: pick an object)", 3 => "3 (choose a target for an item: next click is the target, Esc cancels)", _ => targetMode.ToString() };
lines.Add($" Target mode: {tm}; open container 0x{ground:X8}; vendor 0x{vendor:X8}");
}
else
{
lines.Add(" UI system: not available");
}
// 5. Combat system.
IntPtr combat = CombatModeHooks.ReadCombatSystemPtr();
if (combat != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(combat, 0x48))
{
int mode = Marshal.ReadInt32(combat + 0x1C);
string modeName = mode switch { 1 => "NonCombat", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => mode.ToString() };
byte busyHeld = Marshal.ReadByte(combat + 0x3C);
byte inAttack = Marshal.ReadByte(combat + 0x3D);
byte autoRepeat = Marshal.ReadByte(combat + 0x44);
lines.Add($" Combat: mode {modeName}; attack holds busy {busyHeld}; attack in progress {inAttack}; auto-repeat {autoRepeat}");
}
lines.Add($" World transition (portal/death): {(PlayerLifecycleLog.InWorldTransition ? "yes" : "no")}; logged in: {(LoginLifecycleHooks.HasObservedLoginComplete ? "yes" : "no")}");
lines.Add($" Auto-unlocks this session: item request {PendingClearCount}, attacking flag {AttackClearCount}. Unlock now: /rc unlockactions");
return lines.ToArray();
}
}

View file

@ -165,6 +165,9 @@ internal static class ClientActionHooks
{
// Direct quaternion write — instant snap, most reliable (uses proven SmartBox offsets).
// Equivalent to old Decal Actions.Heading = value.
// Off AC's main thread (plugin pump) SetPlayerHeadingDirect only parks the
// heading in AcMainThreadQueue's coalesced slot and returns true; the snap
// (and the no-player CommandInterpreter fallback below) run in Drain.
if (PlayerPhysicsHooks.SetPlayerHeadingDirect(headingDegrees))
return true;

View file

@ -1,5 +1,6 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
@ -212,10 +213,53 @@ internal static class ClientCombatHooks
if (_playerInReadyPosition == null || _getCombatSystem == null)
return false;
// Off AC's main thread (host IsPlayerReadyFn: RynthNet's login probe polls it
// every 2 s from the plugin pump): the value sampled on the main thread
// (<= ~200 ms old). ClientCombatSystem::PlayerInReadyPosition walks the
// player's motion state and the combat singleton, both freed and rebuilt
// around login / logout, exactly when this is polled.
if (!MainThreadGuard.IsOnMainThread())
return Volatile.Read(ref _readySnapshot) != 0;
bool ready = ReadPlayerReadyLive();
Volatile.Write(ref _readySnapshot, ready ? 1 : 0);
return ready;
}
// 1 = the main thread last saw the player in a ready position.
private static int _readySnapshot;
private static long _nextReadySampleMs;
private const int ReadySampleIntervalMs = 200;
/// <summary>
/// Main thread only (MainThreadSnapshots.Tick). Samples PlayerInReadyPosition for
/// off-thread IsPlayerReady callers, about five times a second. With no player
/// object (char-select, portal teardown) it publishes "not ready" without
/// calling into the combat system.
/// </summary>
internal static void SampleReady()
{
if (!MainThreadGuard.IsOnMainThread() || _playerInReadyPosition == null || _getCombatSystem == null)
return;
long now = Environment.TickCount64;
if (now < _nextReadySampleMs)
return;
_nextReadySampleMs = now + ReadySampleIntervalMs;
bool ready = ClientHelperHooks.GetPlayerId() != 0 && ReadPlayerReadyLive();
Volatile.Write(ref _readySnapshot, ready ? 1 : 0);
}
// MAIN THREAD ONLY.
private static bool ReadPlayerReadyLive()
{
if (!MainThreadGuard.IsOnMainThread() || _playerInReadyPosition == null || _getCombatSystem == null)
return false;
try
{
IntPtr cs = _getCombatSystem();
if (cs == IntPtr.Zero) return false;
if (!ClientObjectHooks.IsReadablePointer(cs)) return false;
return _playerInReadyPosition(cs, 1) != 0;
}
catch { return false; }
@ -257,5 +301,6 @@ internal static class ClientCombatHooks
_autoTarget = null;
_sendAttackHeightChanged = null;
_initialized = false;
Volatile.Write(ref _readySnapshot, 0);
}
}

View file

@ -66,10 +66,33 @@ internal static class ClientHelperHooks
// Byte-identical sibling of Event_StackableMerge (differs only in the action
// opcode immediate: give writes 0xCD, merge 0x54). Cdecl, returns bool.
// Chorizite map: 002ACA60 -> live VA 0x006ACA60. Sends the F7B1 give
// GameAction. amount = stack count to give (0 = whole object).
// Args (live-disasm + call-site UIAttemptGive confirmed): item, targetNpc, amount.
// GameAction. amount = stack count to give (ACE refuses amount <= 0).
// Args: TARGET FIRST, then the item, then amount. The function writes 0xCD, then
// [esp+0x1C], [esp+0x20], [esp+0x24] in that order, and ACE's GiveObjectRequest reads
// targetGuid, objectGuid, amount. Its one caller, ACCWeenieObject::UIAttemptGive
// (call at 0x0058E46F), pushes amount, this->id (the item, [esi+8]), then the target.
// (Re-checked 2026-10-01; the old delegate had the two ids swapped.)
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte EventGiveObjectRequestDelegate(uint objectId, uint targetId, int amount);
private delegate byte EventGiveObjectRequestDelegate(uint targetId, uint objectId, int amount);
// CM_Inventory::Event_GetAndWieldItem(ulong itemId, ulong equipMask) — the 0x001A
// GetAndWieldItem game action ("wield this item at these locations"). Same generated
// shape as its two siblings above (cdecl, returns bool), opcode immediate 0x1A.
// Chorizite map: 002AB950 -> live VA 0x006AC950 (the "FUN_006AC950" once mistaken for
// the merge helper, which is why that attempt tried to equip Pyreals). Arg order from
// the disassembly (itemId at [esp+0x1C], mask at [esp+0x20] after the prologue) and the
// one caller, ACCWeenieObject::UIAttemptWield @0x0058E3C0: push mask; push this->id.
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte EventGetAndWieldItemDelegate(uint objectId, uint equipMask);
// CM_Inventory::Event_DropItem(ulong itemId) — the 0x001B DropItem game action (put the
// item on the ground at the player's feet). Same generated shape as the three above
// (cdecl, returns bool) with one argument, so +0x08 after the first inner call and the
// 0x1B opcode as the last pattern byte. Chorizite map entrypoint 0x006AC880; its caller
// is ACCWeenieObject::UIAttemptPutIn3D (call at 0x0058E545). Arg: itemId at [esp+0x1C]
// after the prologue (sub esp,0Ch + three pushes).
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte EventDropItemDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void UseObjectDelegate(IntPtr clientUiSystem, uint objectId);
@ -105,6 +128,10 @@ internal static class ClientHelperHooks
private const int EventStackableMergeVa = 0x006ACDD0;
// CM_Inventory::Event_GiveObjectRequest — public give-to-NPC API (FALLBACK only; pattern-scanned).
private const int EventGiveObjectRequestVa = 0x006ACA60;
// CM_Inventory::Event_GetAndWieldItem — wield into a chosen slot (FALLBACK only; pattern-scanned).
private const int EventGetAndWieldItemVa = 0x006AC950;
// CM_Inventory::Event_DropItem — drop an item on the ground (FALLBACK only; pattern-scanned).
private const int EventDropItemVa = 0x006AC880;
private const int UseObjectVa = 0x00565750;
private const int PlayerSystemVa = 0x0087119C;
private const int InqPlayerCoordsVa = 0x00560E00;
@ -126,6 +153,8 @@ internal static class ClientHelperHooks
private static MoveItemInternalDelegate? _moveItemInternal;
private static EventStackableMergeDelegate? _eventStackableMerge;
private static EventGiveObjectRequestDelegate? _eventGiveObjectRequest;
private static EventGetAndWieldItemDelegate? _eventGetAndWieldItem;
private static EventDropItemDelegate? _eventDropItem;
private static InqPlayerCoordsDelegate? _inqPlayerCoords;
private static GetPlayerIdDelegate? _getPlayerId;
private static AddTextToScrollDelegate? _addTextToScroll;
@ -151,6 +180,8 @@ internal static class ClientHelperHooks
public static bool HasSplitStackInternal => _moveItemInternal != null;
public static bool HasMergeStackInternal => _eventStackableMerge != null;
public static bool HasGiveObjectTo => _eventGiveObjectRequest != null;
public static bool HasWieldItem => _eventGetAndWieldItem != null;
public static bool HasDropItem => _eventDropItem != null;
public static bool HasGetCurCoords => _inqPlayerCoords != null;
public static bool HasGetPlayerId => _getPlayerId != null;
public static bool HasGetGroundContainerId => true;
@ -178,7 +209,17 @@ internal static class ClientHelperHooks
// so do NOT trim it. Generated + verified unique (1 match @0x006ACA60) via
// pe_pattern.py GEN against both acclient copies.
private static readonly byte?[] PatEventGiveObjectRequest = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x10, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0xCD ];
private static readonly byte?[] PatInqPlayerCoords = [ 0x83, 0xEC, 0x10, 0x53, 0x8B, 0x5C, 0x24, 0x1C, 0x55, 0x56 ];
// CM_Inventory::Event_GetAndWieldItem @0x006AC950. Same template as the two above but with
// one fewer argument (so +0x0C, not +0x10, after the first inner call) and the 0x1A opcode
// as the last byte. Generated + verified unique (1 match @0x006AC950) via pe_pattern.py GEN
// against both acclient copies (C:\Turbine and C:\Games\RynthCore\AcClient).
private static readonly byte?[] PatEventGetAndWieldItem = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x1A ];
// CM_Inventory::Event_DropItem @0x006AC880. The same template again with one argument
// (+0x08 after the first inner call) and the 0x1B opcode as the last byte. Verified
// unique (1 match @0x006AC880) over the engine's scan window against both acclient
// copies (C:\Turbine and C:\Games\RynthCore\AcClient), 2026-09-30.
private static readonly byte?[] PatEventDropItem = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x1B ];
private static readonly byte?[] PatInqPlayerCoords =[ 0x83, 0xEC, 0x10, 0x53, 0x8B, 0x5C, 0x24, 0x1C, 0x55, 0x56 ];
private static readonly byte?[] PatGetPlayerId = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x85, 0xC0, 0x74, 0x07 ];
private static readonly byte?[] PatAddTextToScroll = [ 0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84 ];
private static readonly byte?[] PatUseWithTargetEvent = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x35 ];
@ -238,6 +279,8 @@ internal static class ClientHelperHooks
_moveItemInternal = Bind<MoveItemInternalDelegate>(text, "ClientHelper.MoveItemInternal", PatMoveItemInternal, MoveItemInternalVa);
_eventStackableMerge = Bind<EventStackableMergeDelegate>(text, "ClientHelper.Event_StackableMerge", PatEventStackableMerge, EventStackableMergeVa);
_eventGiveObjectRequest = Bind<EventGiveObjectRequestDelegate>(text, "ClientHelper.Event_GiveObjectRequest", PatEventGiveObjectRequest, EventGiveObjectRequestVa);
_eventGetAndWieldItem = Bind<EventGetAndWieldItemDelegate>(text, "ClientHelper.Event_GetAndWieldItem", PatEventGetAndWieldItem, EventGetAndWieldItemVa);
_eventDropItem = Bind<EventDropItemDelegate>(text, "ClientHelper.Event_DropItem", PatEventDropItem, EventDropItemVa);
_inqPlayerCoords = Bind<InqPlayerCoordsDelegate>(text, "ClientHelper.InqPlayerCoords", PatInqPlayerCoords, InqPlayerCoordsVa);
_getPlayerId = Bind<GetPlayerIdDelegate>(text, "ClientHelper.GetPlayerId", PatGetPlayerId, GetPlayerIdVa);
_addTextToScroll = Bind<AddTextToScrollDelegate>(text, "ClientHelper.AddTextToScroll", PatAddTextToScroll, AddTextToScrollVa);
@ -252,6 +295,12 @@ internal static class ClientHelperHooks
_totalStackAddr = HookResolver.ResolveData(text, "ClientHelper.total_stack", PatXrefTotalStack, 2, TotalStackVa).Address.ToInt32();
_playerSystemAddr = HookResolver.ResolveData(text, "ClientHelper.CPlayerSystem", PatXrefPlayerSystem, 2, PlayerSystemVa).Address.ToInt32();
_commSystemAddr = HookResolver.ResolveData(text, "ClientHelper.CommunicationSystem", PatXrefCommunicationSystem, 2, CommunicationSystemVa).Address.ToInt32();
// v72 player-to-player trade actions (CM_Trade / ClientTradeSystem).
try { PlayerTrade.Probe(text); }
catch (Exception ex) { RynthLog.Compat($"Compat: player trade binding failed - {ex.Message}"); }
// Skills panel raises (CM_Train senders).
try { PlayerTraining.Probe(text); }
catch (Exception ex) { RynthLog.Compat($"Compat: raise senders binding failed - {ex.Message}"); }
_initialized = true;
_statusMessage = "Ready.";
RynthLog.Verbose("Compat: helper hooks ready - validated select/state/chat helpers plus mapped interaction and inventory helpers.");
@ -300,6 +349,35 @@ internal static class ClientHelperHooks
}
}
/// <summary>
/// Click-to-select from an ImGui overlay (a Radar dot, a monster nameplate):
/// selects <paramref name="objectId"/> the way a click on it in the 3D world
/// does. The faces park the id with AcMainThreadQueue.EnqueueOverlaySelect;
/// its drain lands here on AC's main thread, where the checks run right
/// before the select: the client is in the world (logged in, no logout or
/// DB-cache teardown under way, not portaling) and the object still exists
/// (the client still resolves its weenie). Off-thread it marshals like
/// every other mutator. False when nothing was selected.
/// </summary>
public static bool SelectFromOverlay(uint objectId)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueOverlaySelect(objectId);
if (objectId == 0 || _setSelectedObject == null)
return false;
if (!LoginLifecycleHooks.HasObservedLoginComplete || LogoutLifecycleHooks.HasObservedLogout
|| DbCacheTeardownHooks.TeardownActive || TeleportStateHooks.IsPortaling || GetPlayerId() == 0)
return false;
if (!ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out _))
return false; // despawned / died / left range since the click
if (GetSelectedItemId() == objectId)
return true; // already the selection: nothing to redo
AcActionTrace.Record("OverlaySelect", objectId);
return SetSelectedObjectId(objectId);
}
public static uint GetSelectedItemId()
{
return ReadUInt32(_selectedIdAddr);
@ -593,7 +671,9 @@ internal static class ClientHelperHooks
/// CM_Inventory::Event_GiveObjectRequest (cdecl) at 0x006ACA60 — the F7B1 give
/// GameAction, the same path the drag-onto-NPC UI uses. This is the CORRECT
/// give-to-NPC primitive; MoveItemExternal is move-to-container and does not
/// give. amount=0 gives the whole object; positive = partial stack.
/// give. amount=0 gives the whole object; positive = partial stack. The wire needs a
/// real count (ACE answers "Give amount not valid!" to 0), so 0 is turned into the
/// item's stack size here (1 for a single item).
/// </summary>
public static bool GiveObjectTo(uint objectId, uint targetId, int amount = 0)
{
@ -610,7 +690,9 @@ internal static class ClientHelperHooks
try
{
byte rv = _eventGiveObjectRequest(objectId, targetId, amount);
if (amount == 0)
amount = WholeStackAmount(objectId);
byte rv = _eventGiveObjectRequest(targetId, objectId, amount);
RynthLog.Verbose($"Compat: Event_GiveObjectRequest item=0x{objectId:X8} -> target=0x{targetId:X8} amount={amount} rv={rv}");
return rv != 0;
}
@ -621,6 +703,79 @@ internal static class ClientHelperHooks
}
}
/// <summary>
/// The count that gives a whole object: its stack size, or 1 for a single item (or
/// when the item can't be read). Main thread (TryReadItemFields is false off it).
/// </summary>
internal static int WholeStackAmount(uint objectId) =>
ClientObjectHooks.TryReadItemFields(objectId, out ClientObjectHooks.ItemPwdFields f) && f.StackSize > 1
? (int)Math.Min(f.StackSize, int.MaxValue)
: 1;
/// <summary>
/// Wield an item into the given equip slot(s) through CM_Inventory::Event_GetAndWieldItem
/// (cdecl) at 0x006AC950 — the 0x001A GetAndWieldItem game action, the packet the
/// paperdoll drag sends (ACCWeenieObject::UIAttemptWield calls it). equipMask is an
/// EquipMask / INVENTORY_LOC value (e.g. 0x00100000 MeleeWeapon, 0x00200000 Shield,
/// 0x00400000 MissileWeapon, 0x01000000 Held, 0x02000000 TwoHanded; rings/bracelets
/// have a left and a right bit). The server checks the slot against the item's
/// ValidLocations and answers with the wield, or InventoryServerSaveFailed (0x00A0) plus
/// a WeenieError. Unlike UIAttemptWield this sends the packet only: no client busy count,
/// no pending-wield UI state — the same raw-send contract as GiveObjectTo.
/// </summary>
public static bool WieldItem(uint objectId, uint equipMask)
{
// Inventory sends run on AC's main thread, like MoveItemExternal / GiveObjectTo.
if (!MainThreadGuard.IsOnMainThread())
return _eventGetAndWieldItem != null && IsValidObjectId(objectId) && equipMask != 0
&& AcMainThreadQueue.EnqueueWieldItem(objectId, equipMask);
if (_eventGetAndWieldItem == null) return false;
if (!IsValidObjectId(objectId) || equipMask == 0) return false;
try
{
byte rv = _eventGetAndWieldItem(objectId, equipMask);
RynthLog.Verbose($"Compat: Event_GetAndWieldItem item=0x{objectId:X8} mask=0x{equipMask:X8} rv={rv}");
return rv != 0;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Event_GetAndWieldItem threw - {ex.Message}");
return false;
}
}
/// <summary>
/// Drop an item on the ground through CM_Inventory::Event_DropItem (cdecl) at 0x006AC880,
/// the 0x001B DropItem game action that ACCWeenieObject::UIAttemptPutIn3D sends. The
/// server walks nothing (it drops at the player's feet) and answers with the item's new
/// place, or InventoryServerSaveFailed (0x00A0). Packet only, like WieldItem: no client
/// busy count, no pending-request UI state. Used by the Inventory panel.
/// </summary>
public static bool DropItem(uint objectId)
{
// Inventory sends run on AC's main thread, like WieldItem / GiveObjectTo.
if (!MainThreadGuard.IsOnMainThread())
return _eventDropItem != null && IsValidObjectId(objectId)
&& AcMainThreadQueue.EnqueueDropItem(objectId);
if (_eventDropItem == null) return false;
if (!IsValidObjectId(objectId)) return false;
try
{
byte rv = _eventDropItem(objectId);
RynthLog.Verbose($"Compat: Event_DropItem item=0x{objectId:X8} rv={rv}");
return rv != 0;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Event_DropItem threw - {ex.Message}");
return false;
}
}
public static bool TryGetCurCoords(out double northSouth, out double eastWest)
{
northSouth = 0;
@ -629,6 +784,15 @@ internal static class ClientHelperHooks
if (_inqPlayerCoords == null)
return false;
// Off AC's main thread: no coords. The only caller (PluginManager.GetCurCoords,
// on the plugin pump) reaches this as the fallback when the raw SmartBox pose
// read fails, i.e. during login/portal/logout while AC's player state is
// changing. Calling CPlayerSystem::InqPlayerCoords there runs AC code
// off-thread and try/catch cannot stop a native AV. Plugins already handle
// "no coords", and InqPlayerCoords only returns cached data anyway.
if (!MainThreadGuard.IsOnMainThread())
return false;
try
{
IntPtr playerSystem = ReadPointer(_playerSystemAddr);
@ -653,14 +817,29 @@ internal static class ClientHelperHooks
}
}
// Last player id read on AC's main thread. The native leaf (0x0048E5F0) reads
// the SmartBox global and then a field of it; off-thread that dereferences an
// AC object the main thread can free during logout/teardown, and try/catch
// cannot stop a native AV. Off-thread callers (host GetPlayerIdFn on the pump,
// snapshot owner checks, HUDs) get this value instead: at most one frame old,
// refreshed every EndScene by EngineFrameController, 0 = no player / not ready.
private static int _cachedPlayerId;
public static uint GetPlayerId()
{
if (_getPlayerId == null)
return 0;
// Main-thread callers (PrefetchPlayerStats, IsFullOwnedContainer, the EndScene
// prefetches) keep the live native read exactly as before, and publish it.
if (!MainThreadGuard.IsOnMainThread())
return unchecked((uint)Volatile.Read(ref _cachedPlayerId));
try
{
return _getPlayerId();
uint id = _getPlayerId();
Volatile.Write(ref _cachedPlayerId, unchecked((int)id));
return id;
}
catch
{
@ -716,6 +895,12 @@ internal static class ClientHelperHooks
// MoveItemInternal/External early-return-enqueue off-thread), so the PWD ownership
// read, ITEMS_CAPACITY read, and GetNumContainedItems walk are all authoritative
// and the off-thread read-AV class does not apply.
/// <summary>
/// The full-pack guard MoveItemInternal / MoveItemExternal apply, for callers that send
/// through another path (the Inventory panel's split). Main thread.
/// </summary>
internal static bool IsOwnedContainerFull(uint target) => IsFullOwnedContainer(target);
private static bool IsFullOwnedContainer(uint target)
{
uint player = GetPlayerId();
@ -854,6 +1039,15 @@ internal static class ClientHelperHooks
if (_sendNoticeOpenSalvagePanel == null || toolId == 0)
return false;
// Off AC's main thread (RynthAi SalvageManager / Meta tick on the plugin
// pump): marshal. The salvage trio posts a UI notice and mutates the live
// gmSalvageUI UIElement tree; off-thread it races AC's own UI walk, the
// same class as the SetSelectedObject 0x60D1D AV. The ring is FIFO with
// one consumer, so open -> add -> execute keep their order. Drain calls
// back into this method on the main thread, where the gate is satisfied.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSalvageOpen(toolId);
try
{
_sendNoticeOpenSalvagePanel(toolId);
@ -874,6 +1068,10 @@ internal static class ClientHelperHooks
/// </summary>
public static bool SalvagePanelAddItem(uint itemId)
{
// Decal bridge mode: salvage is left to Decal (our OpenSalvagePanel hook isn't
// installed, so the instance is never captured) - Decal's SalvagePanelAdd instead.
if (DecalBridgeHost.Active && !SalvageHooks.IsInstalled)
return DecalBridgeHost.TrySalvagePanelAdd(itemId);
if (_gmSalvageUIAddNewItem == null || itemId == 0)
return false;
@ -884,6 +1082,14 @@ internal static class ClientHelperHooks
return false;
}
// Off-thread: enqueue AFTER the instance pre-check, so a false still means
// "panel not captured" (SalvageManager re-queues the item on it). The
// queued entry carries only the item id: on the main thread this method
// runs again and re-reads the instance, since the panel may have closed
// or been rebuilt in between.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSalvageAddItem(itemId);
try
{
_gmSalvageUIAddNewItem(inst, itemId);
@ -902,6 +1108,8 @@ internal static class ClientHelperHooks
/// </summary>
public static bool SalvagePanelExecute()
{
if (DecalBridgeHost.Active && !SalvageHooks.IsInstalled)
return DecalBridgeHost.TrySalvagePanelSalvage(); // bridge mode: Decal's SalvagePanelSalvage
if (_gmSalvageUISalvage == null)
return false;
@ -912,6 +1120,11 @@ internal static class ClientHelperHooks
return false;
}
// Off-thread: same shape as SalvagePanelAddItem (instance re-read on the
// main thread when the entry drains).
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSalvageExecute();
try
{
_gmSalvageUISalvage(inst);
@ -957,8 +1170,11 @@ internal static class ClientHelperHooks
_moveItemInternal = null;
_eventStackableMerge = null;
_eventGiveObjectRequest = null;
_eventGetAndWieldItem = null;
_eventDropItem = null;
_inqPlayerCoords = null;
_getPlayerId = null;
Volatile.Write(ref _cachedPlayerId, 0);
_addTextToScroll = null;
_useWithTargetEvent = null;
_sendNoticeOpenSalvagePanel = null;
@ -1001,6 +1217,13 @@ internal static class ClientHelperHooks
return Marshal.ReadIntPtr(new IntPtr(address));
}
/// <summary>The ClientUISystem singleton, or Zero before the UI exists. Read-only (diagnostics).</summary>
internal static IntPtr ReadUiSystemPtr()
{
IntPtr slot = new IntPtr(_uiSystemAddr);
return ClientObjectHooks.IsReadablePointer(slot) ? Marshal.ReadIntPtr(slot) : IntPtr.Zero;
}
// WidePString (AC1Legacy::PStringBase<ushort>) helper fns — pattern-resolved (1a, 2026-06-05).
private static readonly byte?[] PatWidePStringCtor = [ 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x85, 0xFF, 0x8B, 0xF1, 0x74, 0x2C ];
private static readonly byte?[] PatWidePStringDtor = [ 0x56, 0x8B, 0x31, 0x83, 0xEE, 0x14, 0x8D, 0x46 ];

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
@ -407,6 +408,13 @@ internal static class CombatActionHooks
if (_cancelAttack == null)
return false;
// 0x1B7 CM_Combat::Event_CancelAttack: same sender class as MeleeAttack, so the
// same gate. Queued in the action ring so it keeps FIFO order after an attack
// that is already queued (it used to run at once and could overtake it). The
// drain re-enters here on the main thread, where the gate passes.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueCancelAttack();
try
{
return _cancelAttack();
@ -422,6 +430,14 @@ internal static class CombatActionHooks
if (_queryHealth == null)
return false;
// 0x1BF CM_Combat::Event_QueryHealth is a game-action send (AC blob alloc +
// send queue): main thread only. The plugin QueryHealthFn arrives on the pump,
// so off-thread calls go to the non-gesture QueryHealth queue and the drain
// re-enters here on the main thread. Callers ignore the result and read the
// async 0x01C0 reply, so "queued" is enough.
if (!MainThreadGuard.IsOnMainThread())
return targetId != 0 && AcMainThreadQueue.EnqueueQueryHealth(targetId);
try
{
return _queryHealth(targetId);
@ -437,6 +453,17 @@ internal static class CombatActionHooks
if (_requestId == null || objectId == 0)
return false;
// The 0xC8 IdentifyObject send allocates on AC's heap and bumps the
// ClientUISystem busy count (non-atomic, via BusyCountHooks) - main thread
// only. Plugin RequestIdFn calls and the PluginManager.TickAll login
// self-identify arrive on the plugin pump, so off-thread callers go through
// the same non-gesture queue AutoIdService uses. DrainRequestIds re-enters
// here on the main thread, where this gate passes and the packet is sent.
// Fire-and-forget: the appraisal reply is async anyway, so "queued" keeps
// the bool's meaning ("requested").
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueRequestId(objectId);
try
{
return _requestId(objectId);
@ -451,6 +478,8 @@ internal static class CombatActionHooks
{
if (spellId <= 0) return false;
if (_castSpellClient == null) return false;
// Nameplate debuffs: pairs "You cast <spell> on <name>" with this target id.
ImGuiBackend.Hud.HudFeed.OnCast(targetId, spellId);
// P2 cast marshalling — drain-BEFORE-tick variant (2026-06-03, attempt 2).
// Off the main thread, enqueue the cast; GameTickHooks drains it on AC's
@ -615,8 +644,13 @@ internal static class CombatActionHooks
_castSpellClientPtr = IntPtr.Zero;
_getMagicSystemPtr = IntPtr.Zero;
_freeHandsCastPtr = IntPtr.Zero;
_queryHealthResponseDetour = null;
_originalQueryHealthResponse = null;
// _queryHealthResponseDetour / _originalQueryHealthResponse are deliberately
// NOT cleared (2026-09-30): the MinHook detour on Handle_Combat__QueryHealthResponse
// stays enabled across a re-probe, so clearing them unrooted the detour
// delegate while AC could still jump to it, made a detour call in that
// window skip AC's original handler, and let InstallQueryHealthResponseHook
// re-run HookCreate on a live target (the remove-and-retry path, safe only
// after shutdown joined every caller). Kept, the install guard is a no-op.
_identifyObjectDetour = null;
_originalIdentifyObject = null;
IsInitialized = false;
@ -757,10 +791,6 @@ internal static class CombatActionHooks
if (success == 0 || objectId == 0)
return;
const uint CreatureProfile = 0x0100;
if ((flags & CreatureProfile) == 0)
return;
int offset = 16; // Past the header
int iSize = (int)size;
@ -773,6 +803,13 @@ internal static class CombatActionHooks
return; // BoolStatsTable
if ((flags & 0x0004) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 12))
return; // FloatStatsTable
// The identify's properties (every table and profile) are cached from the live
// seam, SmartBoxHooks.ParseGameEvent -> PropertyWire (2026-09-30); this parser only
// runs from the disabled inner-dispatcher hook and reads the creature vitals.
const uint CreatureProfile = 0x0100;
if ((flags & CreatureProfile) == 0)
return;
if ((flags & 0x0008) != 0 && !SkipStringHashTable(buffer, iSize, ref offset))
return; // StringStatsTable
if ((flags & 0x1000) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))

View file

@ -49,6 +49,13 @@ internal static class CombatModeHooks
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
/// <summary>The ClientCombatSystem singleton, or Zero. Read-only (diagnostics).</summary>
internal static IntPtr ReadCombatSystemPtr()
{
IntPtr slot = (IntPtr)_combatSystemPtrAddr;
return ClientObjectHooks.IsReadablePointer(slot) ? Marshal.ReadIntPtr(slot) : IntPtr.Zero;
}
// Deep-audit finding #4 (2026-06-18): this used to raw-dereference the
// ClientCombatSystem singleton unconditionally, including off AC's main
// thread — a teardown-window read (relog/portal, singleton being torn

View file

@ -0,0 +1,570 @@
// ============================================================================
// RynthCore.Engine - Compatibility/DecalBridgeHost.cs
//
// "Bridge mode" (docs/DECAL_BRIDGE_PLAN.md): when Decal runs in the same acclient.exe
// AND the RynthCore Decal bridge (src/RynthCore.DecalBridge, a Decal network filter)
// is loaded, the engine leaves the AC functions Decal itself patches to Decal and
// gets what it needed from them through the bridge instead:
//
// AC function (Decal patches it too) bridge mode
// ClientSystem::AddTextToScroll 0x005649F0 chat lines <- Decal ChatBoxMessage
// OutgoingChat 0x005821A0 chat-bar lines <- Decal CommandLineText
// sending lines -> Decal InvokeChatParser
// gmSalvageUI::OpenSalvagePanel 0x004CBF70 salvage add/go -> Decal SalvagePanelAdd/Salvage
//
// Every other hook stays native: Decal doesn't patch those functions (measured patch
// map, 2026-09-29), and the native hooks run on AC's main thread with the live reads
// the bridge can't do. RYNTHCORE_DECAL_BRIDGE_STREAMS=all brings back the spike's
// routing (object create/delete/change and game events from Decal too) for A/B tests.
//
// Transport: BridgeProtocol.cs (byte rings in a named mapping). Events are drained on
// the plugin pump thread, before ProcessPendingActions, into the same queues the hooks
// feed. Commands are queued here and run by the bridge on AC's main thread. No thread,
// timer or callback the bridge could hold: Shutdown just unmaps the view.
//
// Cost without Decal: Initialize makes two GetModuleHandle calls and returns; nothing
// else here runs (every other entry point checks Active first).
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using RynthCore.DecalBridge;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class DecalBridgeHost
{
// Chat-bar prefixes the bridge eats for us. NOT /vt, /ub, /mt: RynthAi answers those
// as compat commands, but with Decal loaded they belong to the real VTank/UB/MagTools.
private const string EatPrefixes = "/rc;/ra;/rv;/rn;/rnav;/lua";
// Same id DecalBridgeRegistration writes (RynthCore.App).
private const string FilterKey = @"SOFTWARE\Decal\NetworkFilters\{5B3E0D57-2C41-4F8A-9D6E-8C1B70DECA11}";
private const int HelloWaitMs = 20000;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr GetModuleHandleW(string name);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern uint GetModuleFileNameW(IntPtr module, char* buffer, uint size);
private static readonly object Sync = new();
private static readonly object CommandSync = new();
private static BridgeChannel? _ch;
private static DecalBridgeMode _mode;
private static bool _allStreams;
private static long _lastSummaryTick;
private static readonly long[] _kindCounts = new long[16];
private static readonly Dictionary<uint, long> _opcodeCounts = new();
private static readonly Dictionary<uint, long> _gameEventCounts = new();
private static long _serverBytes;
private static int _logged;
private static bool _sawHello;
private static int _salvageLogged;
private static int _commandDropLogged;
/// <summary>Bridge mode is on for this generation (decided at init; false without Decal).</summary>
public static bool Active { get; private set; }
/// <summary>
/// Init steps bridge mode leaves to Decal: the two whose AC functions Decal patches.
/// With RYNTHCORE_DECAL_BRIDGE_STREAMS=all, also the spike's create/delete/game-event/raw sources.
/// </summary>
public static bool SkipsInitStep(string step) => Active && (step switch
{
"chat callback hooks" => true, // AddTextToScroll + OutgoingChat: Decal patches both entries
"salvage hooks" => true, // gmSalvageUI::OpenSalvagePanel: Decal patches it
"create-object hooks" or "delete-object hooks" or "smartbox hooks" or "raw packet hooks" => _allStreams,
_ => false,
});
/// <summary>Decides bridge mode. Top of InitWorker, before any hook step.</summary>
public static void Initialize()
{
Active = false;
InactiveReason = null;
string? decal = FindDecalModule();
if (decal == null)
return; // no Decal: nothing below ever runs
_mode = ModeFromEnvironment() ?? EngineSettings.DecalBridgeMode;
if (_mode == DecalBridgeMode.Off)
{
RynthLog.Info($"DecalBridge: Decal in the process ({decal}) and DecalBridge=Off - old coexistence mode (every hook installs).");
NoteInactive("DecalBridge=Off (engine.json or RYNTHCORE_DECAL_BRIDGE=0)",
"RynthCore: the Decal bridge is switched off (DecalBridge Off in engine.json), so RynthCore's overlay is off in this Decal client.");
return;
}
int pid = Environment.ProcessId;
bool mappingExists = BridgeChannel.Exists(pid);
bool registered = IsBridgeRegistered(out string registration);
if (_mode == DecalBridgeMode.Auto && !registered && !mappingExists)
{
RynthLog.Info($"DecalBridge: Decal in the process ({decal}) but the RynthCore Decal bridge isn't registered ({registration}) - old coexistence mode. " +
"Set the account to \"Decal + RynthCore\" in the launcher to use bridge mode.");
NoteInactive($"Decal won't load the bridge in this client (its entry, read as this client sees the registry: {registration})", NotLoadedChat);
return;
}
_allStreams = string.Equals(Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_BRIDGE_STREAMS"), "all", StringComparison.OrdinalIgnoreCase);
try
{
var ch = BridgeChannel.OpenOrCreate(pid);
if (!ch.Valid)
{
RynthLog.Warn($"DecalBridge: the bridge mapping has another protocol version ({ch.ReadInt(BridgeLayout.OffVersion)}, engine {BridgeLayout.Version}) - " +
"the bridge and the engine are from different builds; old coexistence mode.");
ch.Dispose();
NoteInactive("the Decal bridge and the engine are from different builds (protocol version)",
"RynthCore: the Decal bridge and the engine are from different builds - restart the client once the update has finished, or reinstall RynthCore.");
return;
}
uint want = BridgeLayout.Bit(BridgeRecordKind.ChatText) | BridgeLayout.Bit(BridgeRecordKind.ChatBarEnter) |
BridgeLayout.Bit(BridgeRecordKind.LoginComplete) | BridgeLayout.Bit(BridgeRecordKind.Logoff) |
BridgeLayout.Bit(BridgeRecordKind.CommandResult);
if (_allStreams)
want |= BridgeLayout.Bit(BridgeRecordKind.CreateObject) | BridgeLayout.Bit(BridgeRecordKind.ReleaseObject) |
BridgeLayout.Bit(BridgeRecordKind.ChangeObject) | BridgeLayout.Bit(BridgeRecordKind.ServerMessage);
ch.WriteInt(BridgeLayout.OffWantMask, unchecked((int)want));
WritePrefixes(ch, EatPrefixes);
ch.WriteInt(BridgeLayout.OffEngineGeneration, EntryPoint.InitCount);
ch.WriteInt(BridgeLayout.OffEngineAttached, 1);
if (_allStreams)
{
// A new generation has no objects (a hot reload, or an engine injected late):
// ask the bridge to replay Decal's WorldFilter. Duplicates are harmless.
ch.WriteInt(BridgeLayout.OffReplayRequest, ch.ReadInt(BridgeLayout.OffReplayRequest) + 1);
}
lock (Sync) _ch = ch;
Active = true;
RynthLog.Info($"DecalBridge: BRIDGE MODE ({_mode}; Decal: {decal}; bridge {registration}; gen {EntryPoint.InitCount}). " +
$"Bridge state={ch.ReadInt(BridgeLayout.OffBridgeState)}, records so far={ch.ReadLong(BridgeLayout.OffRecords)}. " +
(_allStreams
? "Streams=all: chat, salvage, create/delete, game-event and raw-packet hooks are left to Decal."
: "The chat and salvage hooks are left to Decal; every other hook installs as usual."));
}
catch (Exception ex)
{
RynthLog.Warn($"DecalBridge: could not open the bridge mapping ({ex.GetType().Name}: {ex.Message}) - old coexistence mode.");
NoteInactive($"could not open the bridge mapping ({ex.GetType().Name})", NotLoadedChat);
}
}
/// <summary>
/// After the hook steps: waits (bounded) for the bridge to say hello. True = bridge mode
/// stands. False = it fell back (Auto only) and the caller installs the skipped steps.
/// </summary>
public static bool WaitForBridge(Func<bool> aborted)
{
BridgeChannel? ch;
lock (Sync) ch = _ch;
if (!Active || ch == null)
return true;
long start = Environment.TickCount64;
while (ch.ReadInt(BridgeLayout.OffBridgeState) != 1)
{
if (aborted() || Environment.TickCount64 - start >= HelloWaitMs)
break;
Thread.Sleep(100);
}
long waited = Environment.TickCount64 - start;
if (ch.ReadInt(BridgeLayout.OffBridgeState) == 1)
{
RynthLog.Info($"DecalBridge: bridge is up (bridge pid {ch.ReadInt(BridgeLayout.OffBridgePid)}, waited {waited} ms).");
return true;
}
if (_mode == DecalBridgeMode.On)
{
RynthLog.Warn($"DecalBridge: no hello from the bridge after {waited} ms and DecalBridge=On - staying in bridge mode; " +
"chat, chat commands and salvage stay dark until the bridge loads.");
NoteInactive($"registered, but Decal didn't load the bridge (no hello after {waited} ms; DecalBridge=On keeps bridge mode)", NotLoadedChat);
return true;
}
RynthLog.Warn($"DecalBridge: no hello from the bridge after {waited} ms - falling back to the old coexistence mode " +
"(the chat and salvage hooks install now). Check Logs\\DecalBridge.<pid>.log and the registration (RynthCore.Injector --decal-bridge status).");
Detach(logSummary: false);
NoteInactive($"registered, but Decal didn't load the bridge (no hello after {waited} ms) - see Logs\\DecalBridge.<pid>.log", NotLoadedChat);
return false;
}
/// <summary>
/// The IDirect3DDevice9* Decal renders with, as the bridge read it from Decal's public
/// IDecalCore.GetD3DDevice on its first frame. Zero when not in bridge mode or not yet
/// known. Never waits (read on AC's thread at login).
/// </summary>
public static IntPtr DecalDevice
{
get
{
BridgeChannel? ch;
lock (Sync) ch = _ch;
return ch == null ? IntPtr.Zero : new IntPtr(ch.ReadInt(BridgeLayout.OffD3DDevice));
}
}
/// <summary>Feeds everything the bridge wrote since the last call into the plugin queues. Pump thread.</summary>
public static int Drain()
{
BridgeChannel? ch;
lock (Sync) ch = _ch;
if (ch == null)
return 0;
int n = 0;
try
{
n = ch.Drain(Handle, 20000);
}
catch (Exception ex)
{
RynthLog.Warn($"DecalBridge: drain threw {ex.GetType().Name}: {ex.Message}");
}
long now = Environment.TickCount64;
if (now - _lastSummaryTick >= 60000)
{
_lastSummaryTick = now;
LogSummary(ch);
}
return n;
}
public static void Shutdown() => Detach(logSummary: true);
private static void Detach(bool logSummary)
{
BridgeChannel? ch;
lock (Sync) { ch = _ch; _ch = null; }
Active = false;
if (ch == null)
return;
try
{
if (logSummary) LogSummary(ch);
ch.WriteInt(BridgeLayout.OffEngineAttached, 0);
ch.WriteInt(BridgeLayout.OffWantMask, 0);
}
catch { }
lock (CommandSync) ch.Dispose();
if (logSummary)
RynthLog.Info("DecalBridge: detached (mapping view released; the bridge keeps the rings for the next generation).");
}
// ── "Decal is here but the bridge isn't" (2026-10-03) ────────────────────────
//
// Without the bridge a Decal client takes the old coexistence path (no overlay; it has
// ended in crashes). The launcher's pre-launch check blocks that, but a client started
// another way (an older launcher, the injector, a registration Decal doesn't read) still
// gets here, so say it once: one clear log line, and one chat line after login.
private const string NotLoadedChat =
"RynthCore: the Decal bridge isn't loaded - open the launcher's Decal check (Recovery Actions > Check Decal bridge). RynthCore's overlay is off in this client.";
private const string NoticeShownVar = "RYNTHCORE_DECAL_BRIDGE_NOTICE_SHOWN"; // once per client, across hot reloads
private static int _noticeScheduled;
private static string? _noticeText;
/// <summary>
/// Why bridge mode is off although Decal is in this client (null: bridge mode, or no
/// Decal). Set at init by <see cref="Initialize"/> or the <see cref="WaitForBridge"/> fallback.
/// </summary>
public static string? InactiveReason { get; private set; }
/// <summary>
/// The engine should stand down in this client (EntryPoint.InitWorker): Decal is here, the
/// bridge isn't active, the mode isn't an explicit DecalBridge=Off (engine.json or
/// RYNTHCORE_DECAL_BRIDGE=0 - the old coexistence path, for tests), and engine.json
/// DecalStandDown isn't false. Never true without Decal.
/// </summary>
public static bool ShouldStandDown =>
InactiveReason != null && !Active && _mode != DecalBridgeMode.Off && EngineSettings.DecalStandDown;
private static void NoteInactive(string reason, string chatLine)
{
InactiveReason = reason;
RynthLog.Warn($"DecalBridge: NOT ACTIVE in this Decal client - {reason}. No RynthCore overlay here: the old coexistence path runs " +
"(known to end in a crash). Fix: the launcher's Recovery Actions > Check Decal bridge (or RynthCore.Injector --decal-bridge check).");
if (Environment.GetEnvironmentVariable(NoticeShownVar) == "1")
return;
if (Interlocked.Exchange(ref _noticeScheduled, 1) != 0)
return;
_noticeText = chatLine;
if (LoginLifecycleHooks.HasObservedLoginComplete)
PostNotice();
else
LoginLifecycleHooks.LoginComplete += OnLoginForNotice;
}
private static void OnLoginForNotice()
{
LoginLifecycleHooks.LoginComplete -= OnLoginForNotice;
PostNotice();
}
// Queued for AC's main thread (drained from Client::UseTime); never calls AC from here.
private static void PostNotice()
{
string? text = _noticeText;
if (text == null) return;
try
{
if (AcMainThreadQueue.EnqueueWriteToChat(text, 2))
Environment.SetEnvironmentVariable(NoticeShownVar, "1");
}
catch { }
}
// ── commands (engine -> bridge -> Decal's public API on AC's main thread) ─────
/// <summary>Sends a chat line as if typed, through Decal's InvokeChatParser. Any thread.</summary>
public static bool TryInvokeChatParser(string line)
{
if (!Active || string.IsNullOrEmpty(line))
return false;
bool sent = SendCommand(BridgeRecordKind.CmdInvokeChatParser, 0, line);
// The bridge doesn't echo our own lines back as ChatBarEnter, so a /vt start|stop
// the engine or a plugin sends is noted here.
if (sent)
VTankWatch.ObserveSentLine(line);
return sent;
}
/// <summary>Salvage panel add, left to Decal in bridge mode (SalvagePanelAdd). Any thread.</summary>
public static bool TrySalvagePanelAdd(uint itemId)
{
if (!Active || itemId == 0)
return false;
NoteSalvage();
return SendCommand(BridgeRecordKind.CmdSalvagePanelAdd, itemId, null);
}
/// <summary>Salvage button, left to Decal in bridge mode (SalvagePanelSalvage). Any thread.</summary>
public static bool TrySalvagePanelSalvage()
{
if (!Active)
return false;
NoteSalvage();
return SendCommand(BridgeRecordKind.CmdSalvagePanelSalvage, 0, null);
}
private static void NoteSalvage()
{
if (Interlocked.Exchange(ref _salvageLogged, 1) == 0)
RynthLog.Info("DecalBridge: salvage is left to Decal in bridge mode (our OpenSalvagePanel hook is not installed): " +
"adding items and pressing Salvage go through Decal's SalvagePanelAdd/SalvagePanelSalvage. The panel must be open (use an Ust).");
}
private static bool SendCommand(BridgeRecordKind kind, uint arg0, string? text)
{
lock (CommandSync)
{
BridgeChannel? ch;
lock (Sync) ch = _ch;
if (ch == null)
return false;
bool ok = ch.WriteCommand(kind, arg0, 0, text);
if (!ok && Interlocked.Exchange(ref _commandDropLogged, 1) == 0)
RynthLog.Warn($"DecalBridge: command ring full - {kind} dropped (is the bridge running? it drains once per frame).");
return ok;
}
}
// ── record handling ──────────────────────────────────────────────────────
private static void Handle(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int len)
{
int k = (int)kind;
if (k >= 0 && k < _kindCounts.Length) _kindCounts[k]++;
switch (kind)
{
case BridgeRecordKind.Hello:
_sawHello = true;
RynthLog.Info($"DecalBridge: hello from bridge v{arg0}: {Utf16(payload, len)}");
break;
case BridgeRecordKind.ChatText:
{
string text = Utf16(payload, len);
FirstFew($"chat type={arg0} target={arg1} '{Trim(text)}'");
VTankWatch.ObserveChatText(text); // diagnostic log only
PluginManager.QueueChatWindowText(text, arg0);
break;
}
case BridgeRecordKind.ChatBarEnter:
{
// Runs on the pump thread (the hook ran it on AC's thread, synchronously,
// so it could eat the line; the bridge now does the eating by prefix).
string text = Utf16(payload, len);
FirstFew($"chat-bar '{Trim(text)}' eatenByBridge={arg0 != 0}");
// Every parser line, eaten or not: /vt start|stop went on to VTank, and is
// how RynthAi learns that VTank's macro runs (one bot per client).
VTankWatch.ObserveParserLine(text);
// Only the lines the bridge ate (our prefixes) are ours to run. Every other
// line already went on to Decal and AC: handing it to the plugins too would
// run it twice (RynthAi answers /vt, /ub and /mt as compat commands, and
// VTank, UB and MagTools already ran them).
if (arg0 == 0)
break;
if (RynthCoreChatCommands.TryHandle(text))
break;
PluginManager.DispatchChatBarEnter(text);
break;
}
case BridgeRecordKind.CommandResult:
RynthLog.Warn($"DecalBridge: command {(BridgeRecordKind)arg0} failed in the bridge: {Utf16(payload, len)}");
break;
// Streams=all only (the spike's routing). Same side effects as CreateObjectHooks /
// DeleteObjectHooks: the auto-appraisal queue is what gives RynthAi its creature
// classification (measured in world 2026-09-29).
case BridgeRecordKind.CreateObject:
PluginManager.QueueCreateObject(arg0);
AutoIdService.Enqueue(arg0);
break;
case BridgeRecordKind.ReleaseObject:
PaletteCache.Remove(arg0);
PluginManager.QueueDeleteObject(arg0);
AutoIdService.Evict(arg0);
break;
case BridgeRecordKind.ChangeObject:
PluginManager.QueueUpdateObject(arg0);
break;
case BridgeRecordKind.ServerMessage:
{
_serverBytes += len;
_opcodeCounts[arg0] = _opcodeCounts.TryGetValue(arg0, out long c) ? c + 1 : 1;
// Decal's Message.RawData for a game event: [F7B0][objectId][sequence][eventType][payload].
if (arg0 == 0xF7B0 && len >= 16 && *(uint*)payload == 0xF7B0)
{
uint ev = *(uint*)(payload + 12);
_gameEventCounts[ev] = _gameEventCounts.TryGetValue(ev, out long g) ? g + 1 : 1;
SmartBoxHooks.ProcessBridgeGameEvent(payload + 12, len - 12);
}
break;
}
case BridgeRecordKind.LoginComplete:
RynthLog.Info($"DecalBridge: Decal LoginComplete (character 0x{arg0:X8}); engine login seen={LoginLifecycleHooks.HasObservedLoginComplete}.");
break;
case BridgeRecordKind.Logoff:
RynthLog.Info($"DecalBridge: Decal Logoff type={arg0}.");
VTankWatch.OnLogoff();
break;
}
}
private static void LogSummary(BridgeChannel ch)
{
var sb = new StringBuilder();
sb.Append($"DecalBridge: summary - hello={_sawHello} records={ch.ReadLong(BridgeLayout.OffRecords)} dropped={ch.ReadLong(BridgeLayout.OffDropped)} ");
sb.Append($"chat={_kindCounts[2]} chatBar={_kindCounts[3]} commands sent={ch.ReadLong(BridgeLayout.OffCmdWritePos) > 0} run={ch.ReadLong(BridgeLayout.OffCmdDone)} dropped={ch.ReadLong(BridgeLayout.OffCmdDropped)}");
if (_allStreams)
{
sb.Append($" create={_kindCounts[4]} release={_kindCounts[5]} change={_kindCounts[6]} server={_kindCounts[7]} ({_serverBytes / 1024} KB); top opcodes:");
foreach (var kv in Top(_opcodeCounts, 8)) sb.Append($" {kv.Key:X4}x{kv.Value}");
sb.Append("; game events:");
foreach (var kv in Top(_gameEventCounts, 12)) sb.Append($" {kv.Key:X4}x{kv.Value}");
}
sb.Append($"; plugins live objects={PluginManager.LiveObjectCount}");
RynthLog.Info(sb.ToString());
}
private static IEnumerable<KeyValuePair<uint, long>> Top(Dictionary<uint, long> d, int n)
{
var list = new List<KeyValuePair<uint, long>>(d);
list.Sort((a, b) => b.Value.CompareTo(a.Value));
return list.Count > n ? list.GetRange(0, n) : list;
}
private static void FirstFew(string line)
{
if (_logged >= 20) return;
_logged++;
RynthLog.Info("DecalBridge: " + line);
}
private static string Trim(string s) => s.Length > 80 ? s.Substring(0, 80) + "..." : s.TrimEnd('\n', '\r');
private static string Utf16(byte* p, int len) => len >= 2 ? new string((char*)p, 0, len / 2) : string.Empty;
private static void WritePrefixes(BridgeChannel ch, string prefixes)
{
char* dst = (char*)(ch.Header + BridgeLayout.OffPrefixes);
int n = Math.Min(prefixes.Length, BridgeLayout.PrefixChars - 1);
for (int i = 0; i < n; i++) dst[i] = prefixes[i];
dst[n] = '\0';
}
// ── decisions ────────────────────────────────────────────────────────────
/// <summary>RYNTHCORE_DECAL_BRIDGE (test override): 1/on, 0/off, auto.</summary>
private static DecalBridgeMode? ModeFromEnvironment()
{
string? v = Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_BRIDGE");
if (string.IsNullOrWhiteSpace(v)) return null;
v = v.Trim();
if (v == "1" || v.Equals("on", StringComparison.OrdinalIgnoreCase)) return DecalBridgeMode.On;
if (v == "0" || v.Equals("off", StringComparison.OrdinalIgnoreCase)) return DecalBridgeMode.Off;
if (v.Equals("auto", StringComparison.OrdinalIgnoreCase)) return DecalBridgeMode.Auto;
return null;
}
/// <summary>
/// Whether Decal will load the bridge in this client: its filter entry, read through
/// this (virtualized, 32-bit) process's own view of HKLM - the view Decal reads, which
/// includes the per-user copy the launcher writes.
/// </summary>
private static bool IsBridgeRegistered(out string detail)
{
try
{
using Microsoft.Win32.RegistryKey? k = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(FilterKey);
if (k == null) { detail = "not registered"; return false; }
bool enabled = k.GetValue("Enabled") is int e && e != 0;
string? dir = k.GetValue("Path") as string;
string? file = k.GetValue("Assembly") as string;
bool present = dir != null && file != null && File.Exists(Path.Combine(dir, file));
detail = $"registered, {(enabled ? "enabled" : "DISABLED")}, {(present ? dir : $"DLL missing at {dir}")}";
return enabled && present;
}
catch (Exception ex)
{
detail = $"registry read failed: {ex.GetType().Name}";
return false;
}
}
/// <summary>
/// Decal in this process? Two GetModuleHandle calls (no module walk). decal.dll, or
/// Decal's Inject.dll (the first thing a Decal launch loads) next to Decal.Adapter.dll.
/// Deliberately not DecalDetection: that caches its first answer, and asking it this
/// early (before decal.dll loads) would cache "no Decal" for the post-login check.
/// </summary>
private static string? FindDecalModule()
{
try
{
IntPtr m = GetModuleHandleW("decal.dll");
if (m == IntPtr.Zero)
{
m = GetModuleHandleW("Inject.dll");
if (m == IntPtr.Zero)
return null;
}
char* buf = stackalloc char[520];
uint n = GetModuleFileNameW(m, buf, 520);
string path = new string(buf, 0, (int)n);
string? dir = Path.GetDirectoryName(path);
return dir != null && File.Exists(Path.Combine(dir, "Decal.Adapter.dll")) ? path : null;
}
catch
{
return null;
}
}
}

View file

@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
@ -80,7 +82,14 @@ internal static class EnchantmentHooks
IntPtr qualPtr = PlayerVitalsHooks.KnownPlayerQualitiesPtr;
if (qualPtr == IntPtr.Zero) return -1;
int count = ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount);
// Off AC's main thread (plugin pump: RynthAi BuffManager, meta expressions,
// RynthLua): copy the main-thread snapshot. Walking the registry's linked
// lists here raced AC adding/removing/expiring buffs on its own thread (a
// freed node on a still-committed page passes every probe), which the
// double walk only detected, never prevented.
int count = MainThreadGuard.IsOnMainThread()
? ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount)
: CopyPlayerSnapshot(qualPtr, spellIds, expiryTimes, maxCount);
if (_enchReadLogCount < 8)
{
@ -92,6 +101,262 @@ internal static class EnchantmentHooks
}
private static int _enchReadLogCount;
// ── Main-thread enchantment snapshots (2026-09-30 main-thread audit) ─────────
// Player: MainThreadSnapshots.Tick walks the player's registry every 250 ms (at
// once after an enchantment game event marks it dirty) into preallocated
// back buffers, then swaps them in under _playerEnchLock. Zero-alloc.
private const int MaxSnapshotEnchantments = 1024;
private const int PlayerEnchRefreshMs = 250;
private static readonly object _playerEnchLock = new();
private static uint[] _pEnchIdsFront = new uint[MaxSnapshotEnchantments];
private static double[] _pEnchExpFront = new double[MaxSnapshotEnchantments];
private static uint[] _pEnchIdsBack = new uint[MaxSnapshotEnchantments];
private static double[] _pEnchExpBack = new double[MaxSnapshotEnchantments];
// The same entries' StatMod (type, key, value) and spell category, for the Skills
// panel's per-stat buff lists (CopyPlayerStatMods). Swapped with the arrays above.
private static uint[] _pEnchTypeFront = new uint[MaxSnapshotEnchantments];
private static uint[] _pEnchKeyFront = new uint[MaxSnapshotEnchantments];
private static float[] _pEnchValFront = new float[MaxSnapshotEnchantments];
private static uint[] _pEnchCatFront = new uint[MaxSnapshotEnchantments];
private static uint[] _pEnchTypeBack = new uint[MaxSnapshotEnchantments];
private static uint[] _pEnchKeyBack = new uint[MaxSnapshotEnchantments];
private static float[] _pEnchValBack = new float[MaxSnapshotEnchantments];
private static uint[] _pEnchCatBack = new uint[MaxSnapshotEnchantments];
private static int _pEnchCountFront = -1; // -1 = nothing valid published
private static IntPtr _pEnchOwnerFront;
private static long _nextPlayerEnchRefreshMs;
private static int _playerEnchDirty;
/// <summary>
/// Main thread only: an enchantment game event was just applied by AC. Refresh
/// the player snapshot immediately (SmartBoxHooks calls this before it queues
/// the event to plugins, so their re-read sees the change).
/// </summary>
internal static void RefreshPlayerSnapshotNow()
{
Volatile.Write(ref _playerEnchDirty, 1);
PrefetchPlayerEnchantments(allowWalk: !LogoutLifecycleHooks.HasObservedLogout);
}
// Off-thread copy of the player snapshot; -1 when it is missing, belongs to
// another qualities object, or a DB-cache teardown is running.
private static unsafe int CopyPlayerSnapshot(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount)
{
if (DbCacheTeardownHooks.TeardownActive)
return -1;
lock (_playerEnchLock)
{
int n = _pEnchCountFront;
if (n < 0 || _pEnchOwnerFront != qualPtr)
return -1;
if (n > maxCount) n = maxCount;
for (int i = 0; i < n; i++)
{
spellIds[i] = _pEnchIdsFront[i];
expiryTimes[i] = _pEnchExpFront[i];
}
return n;
}
}
/// <summary>
/// The player snapshot with each entry's StatMod and spell category (the Skills
/// panel). Fills up to the arrays' length; returns the count, or -1 when nothing
/// valid is published (no player, another qualities object, a teardown). Any thread.
/// </summary>
internal static int CopyPlayerStatMods(uint[] spellIds, double[] expiryTimes, uint[] modTypes, uint[] modKeys,
float[] modVals, uint[] categories)
{
if (DbCacheTeardownHooks.TeardownActive)
return -1;
IntPtr qualPtr = PlayerVitalsHooks.KnownPlayerQualitiesPtr;
lock (_playerEnchLock)
{
int n = _pEnchCountFront;
if (n < 0 || qualPtr == IntPtr.Zero || _pEnchOwnerFront != qualPtr)
return -1;
n = Math.Min(n, Math.Min(Math.Min(spellIds.Length, expiryTimes.Length), Math.Min(modTypes.Length,
Math.Min(modKeys.Length, Math.Min(modVals.Length, categories.Length)))));
Array.Copy(_pEnchIdsFront, spellIds, n);
Array.Copy(_pEnchExpFront, expiryTimes, n);
Array.Copy(_pEnchTypeFront, modTypes, n);
Array.Copy(_pEnchKeyFront, modKeys, n);
Array.Copy(_pEnchValFront, modVals, n);
Array.Copy(_pEnchCatFront, categories, n);
return n;
}
}
/// <summary>
/// Main thread only (MainThreadSnapshots.Tick). Refreshes the player snapshot
/// every 250 ms, or on the next tick after an enchantment event. With
/// <paramref name="allowWalk"/> false (no live player: logout window, teardown)
/// it publishes "nothing valid" instead of walking the cached qualities pointer.
/// </summary>
internal static unsafe void PrefetchPlayerEnchantments(bool allowWalk)
{
if (!MainThreadGuard.IsOnMainThread())
return;
long now = Environment.TickCount64;
bool dirty = Volatile.Read(ref _playerEnchDirty) != 0;
if (!dirty && now < _nextPlayerEnchRefreshMs)
return;
Volatile.Write(ref _playerEnchDirty, 0);
_nextPlayerEnchRefreshMs = now + PlayerEnchRefreshMs;
IntPtr qualPtr = PlayerVitalsHooks.KnownPlayerQualitiesPtr;
int count = -1;
if (qualPtr != IntPtr.Zero && allowWalk)
{
fixed (uint* ids = _pEnchIdsBack)
fixed (double* exp = _pEnchExpBack)
fixed (uint* types = _pEnchTypeBack)
fixed (uint* keys = _pEnchKeyBack)
fixed (float* vals = _pEnchValBack)
fixed (uint* cats = _pEnchCatBack)
count = ReadEnchantmentsFromQualities(qualPtr, ids, exp, MaxSnapshotEnchantments, types, keys, vals, cats);
}
lock (_playerEnchLock)
{
(_pEnchIdsFront, _pEnchIdsBack) = (_pEnchIdsBack, _pEnchIdsFront);
(_pEnchExpFront, _pEnchExpBack) = (_pEnchExpBack, _pEnchExpFront);
(_pEnchTypeFront, _pEnchTypeBack) = (_pEnchTypeBack, _pEnchTypeFront);
(_pEnchKeyFront, _pEnchKeyBack) = (_pEnchKeyBack, _pEnchKeyFront);
(_pEnchValFront, _pEnchValBack) = (_pEnchValBack, _pEnchValFront);
(_pEnchCatFront, _pEnchCatBack) = (_pEnchCatBack, _pEnchCatFront);
_pEnchCountFront = count;
_pEnchOwnerFront = qualPtr;
}
}
// Objects: request-driven. An off-thread ReadObjectEnchantments registers the
// id and gets -1 (every caller already treats -1 as "skip this tick") until the
// main thread has walked it; after that it gets the last main-thread result,
// refreshed every 500 ms while it keeps being asked for. Ids not asked for in
// 5 s are dropped. At most 64 watched ids.
private sealed class ObjEnchEntry
{
public uint[] Ids = Array.Empty<uint>();
public double[] Exp = Array.Empty<double>();
public int Count = -1; // -1 = not walked yet / unreadable
public long LastRequestMs;
}
private const int MaxWatchedObjects = 64;
private const int ObjectEnchRefreshMs = 500;
private const int ObjectEnchIdleDropMs = 5000;
private static readonly object _objEnchLock = new();
private static readonly Dictionary<uint, ObjEnchEntry> _objEnch = new(MaxWatchedObjects);
private static readonly uint[] _objEnchWork = new uint[MaxWatchedObjects];
private static readonly uint[] _objEnchScratchIds = new uint[MaxSnapshotEnchantments];
private static readonly double[] _objEnchScratchExp = new double[MaxSnapshotEnchantments];
private static long _nextObjectEnchRefreshMs;
private static IntPtr _objEnchSessionOwner;
private static unsafe int CopyObjectSnapshot(uint objectId, uint* spellIds, double* expiryTimes, int maxCount)
{
if (DbCacheTeardownHooks.TeardownActive)
return -1;
long now = Environment.TickCount64;
lock (_objEnchLock)
{
if (!_objEnch.TryGetValue(objectId, out ObjEnchEntry? e))
{
if (_objEnch.Count >= MaxWatchedObjects)
{
// Full: evict the id asked for least recently.
uint oldest = 0; long oldestMs = long.MaxValue;
foreach (KeyValuePair<uint, ObjEnchEntry> kv in _objEnch)
if (kv.Value.LastRequestMs < oldestMs) { oldestMs = kv.Value.LastRequestMs; oldest = kv.Key; }
_objEnch.Remove(oldest);
}
_objEnch[objectId] = new ObjEnchEntry { LastRequestMs = now };
return -1;
}
e.LastRequestMs = now;
int n = e.Count;
if (n < 0)
return -1;
if (n > maxCount) n = maxCount;
for (int i = 0; i < n; i++)
{
spellIds[i] = e.Ids[i];
expiryTimes[i] = e.Exp[i];
}
return n;
}
}
/// <summary>
/// Main thread only (MainThreadSnapshots.Tick). Walks the watched objects'
/// registries every 500 ms. Idle (one lock, empty dictionary) when nothing asks.
/// </summary>
internal static unsafe void PrefetchWatchedObjectEnchantments()
{
if (!MainThreadGuard.IsOnMainThread())
return;
long now = Environment.TickCount64;
if (now < _nextObjectEnchRefreshMs)
return;
_nextObjectEnchRefreshMs = now + ObjectEnchRefreshMs;
int n = 0;
lock (_objEnchLock)
{
// A new character (or none): nothing watched belongs to it.
IntPtr owner = PlayerVitalsHooks.KnownPlayerQualitiesPtr;
if (owner != _objEnchSessionOwner)
{
_objEnch.Clear();
_objEnchSessionOwner = owner;
}
if (_objEnch.Count == 0)
return;
// Live ids fill the work buffer from the front, idle ones from the back
// (Count <= MaxWatchedObjects, so the two never meet); then drop the idle.
int drop = 0;
foreach (KeyValuePair<uint, ObjEnchEntry> kv in _objEnch)
{
if (now - kv.Value.LastRequestMs <= ObjectEnchIdleDropMs)
_objEnchWork[n++] = kv.Key;
else
_objEnchWork[_objEnchWork.Length - 1 - drop++] = kv.Key;
}
for (int i = 0; i < drop; i++)
_objEnch.Remove(_objEnchWork[_objEnchWork.Length - 1 - i]);
}
if (DbCacheTeardownHooks.TeardownActive)
return;
for (int i = 0; i < n; i++)
{
uint id = _objEnchWork[i];
int count;
fixed (uint* ids = _objEnchScratchIds)
fixed (double* exp = _objEnchScratchExp)
count = ReadObjectEnchantmentsLive(id, ids, exp, MaxSnapshotEnchantments);
lock (_objEnchLock)
{
if (!_objEnch.TryGetValue(id, out ObjEnchEntry? e))
continue; // dropped meanwhile
if (count > 0 && e.Ids.Length < count)
{
// Grow once per object (rare: only when its buff count rises).
e.Ids = new uint[Math.Max(count, 16)];
e.Exp = new double[e.Ids.Length];
}
for (int k = 0; k < count; k++)
{
e.Ids[k] = _objEnchScratchIds[k];
e.Exp[k] = _objEnchScratchExp[k];
}
e.Count = count;
}
}
}
/// <summary>
/// Reads active enchantments from any game object's CEnchantmentRegistry.
/// Path: GetWeenieObject(objectId) → weenie+qualitiesOffset → CACQualities+0x70.
@ -104,6 +369,22 @@ internal static class EnchantmentHooks
{
if (maxCount <= 0) return 0;
// Off AC's main thread (host ReadObjectEnchantmentsFn: RynthAi's opt-in
// registry diagnostic, RynthLua): the request-driven main-thread snapshot.
// The live walk below started from a cached, possibly freed weenie pointer.
if (!MainThreadGuard.IsOnMainThread())
return CopyObjectSnapshot(objectId, spellIds, expiryTimes, maxCount);
return ReadObjectEnchantmentsLive(objectId, spellIds, expiryTimes, maxCount);
}
// MAIN THREAD ONLY: resolve the weenie natively and walk its registry.
private static unsafe int ReadObjectEnchantmentsLive(uint objectId, uint* spellIds, double* expiryTimes, int maxCount)
{
if (maxCount <= 0) return 0;
if (!MainThreadGuard.IsOnMainThread())
return -1;
if (!ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out IntPtr weeniePtr))
return -1;
@ -141,8 +422,13 @@ internal static class EnchantmentHooks
/// <summary>
/// Core: reads enchantments from a CACQualities pointer's enchantment registry.
/// </summary>
private static unsafe int ReadEnchantmentsFromQualities(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount)
private static unsafe int ReadEnchantmentsFromQualities(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount,
uint* modTypes = null, uint* modKeys = null, float* modVals = null, uint* categories = null)
{
// MAIN THREAD ONLY: see the note at the end of this method.
if (!MainThreadGuard.IsOnMainThread())
return -1;
// While AC is inside a DB object-cache teardown (DbCacheTeardownHooks sets this
// on AC's main thread for the duration of DestroyObjectCaches — which fires at
// world-load, zone change, logout, AND final close), refuse to walk the
@ -180,43 +466,36 @@ internal static class EnchantmentHooks
if (!SmartBoxLocator.IsPointerInModule(registryVtable))
return -1;
// Stability check (2026-09-02 "infinite buffing loop" bug): AC's own
// main thread mutates these linked lists as buffs land/expire, and in
// Decal-coexistence mode this reader runs off-thread on the 30Hz
// plugin pump (no EndScene-driven main-thread tick exists there) — a
// walk here can race that mutation. A torn/truncated walk silently
// under-reports the active buff set; BuffManager.RefreshFromLiveMemory
// treats a short read as "buffs expired" and clears its timers,
// making a just-completed rebuff pass look like nothing landed and
// instantly restarting it. Walk twice and only trust an exact match;
// on a mismatch, skip this tick (return -1, already a safe no-op for
// every caller) rather than report a truncated set.
int countA = WalkAllLists(registryPtr, spellIds, expiryTimes, maxCount);
uint* idsB = stackalloc uint[maxCount];
double* expB = stackalloc double[maxCount];
int countB = WalkAllLists(registryPtr, idsB, expB, maxCount);
if (countA != countB)
return -1;
for (int i = 0; i < countA; i++)
{
if (spellIds[i] != idsB[i] || expiryTimes[i] != expB[i])
return -1;
}
return countA;
// Stability check history (2026-09-02 "infinite buffing loop" bug): when this
// walk ran off-thread on the plugin pump it could race AC mutating these
// lists as buffs landed/expired, so it walked twice and trusted only an
// exact match. Since 2026-09-30 it only runs on AC's main thread (the
// snapshot prefetches and main-thread callers), where nothing mutates the
// lists during the walk, so one walk is exact.
return WalkAllLists(registryPtr, spellIds, expiryTimes, maxCount, modTypes, modKeys, modVals, categories);
}
private static unsafe int WalkAllLists(IntPtr registryPtr, uint* spellIds, double* expiryTimes, int maxCount)
private static unsafe int WalkAllLists(IntPtr registryPtr, uint* spellIds, double* expiryTimes, int maxCount,
uint* modTypes, uint* modKeys, float* modVals, uint* categories)
{
int count = 0;
count = WalkEnchantList(registryPtr + RegistryMultListOffset, spellIds, expiryTimes, maxCount, count);
count = WalkEnchantList(registryPtr + RegistryAddListOffset, spellIds, expiryTimes, maxCount, count);
count = WalkEnchantList(registryPtr + RegistryCooldownListOffset, spellIds, expiryTimes, maxCount, count);
count = WalkEnchantList(registryPtr + RegistryMultListOffset, spellIds, expiryTimes, maxCount, count, modTypes, modKeys, modVals, categories);
count = WalkEnchantList(registryPtr + RegistryAddListOffset, spellIds, expiryTimes, maxCount, count, modTypes, modKeys, modVals, categories);
count = WalkEnchantList(registryPtr + RegistryCooldownListOffset, spellIds, expiryTimes, maxCount, count, modTypes, modKeys, modVals, categories);
return count;
}
private static unsafe int WalkEnchantList(IntPtr listPtrAddress, uint* spellIds, double* expiryTimes, int maxCount, int count)
// Optional per-enchantment detail (the Skills panel's buffs): the spell category and
// the StatMod. With the pack(8) padding after _power_level and after _degrade_limit,
// _last_time_degraded sits at +56 and the StatMod at +64: vtable, type +68, key +72,
// val +76 (float); sizeof 80 = NodeNextOffset. All inside the node span checked below.
private const int EnchantmentCategoryOffset = 12;
private const int EnchantmentStatModTypeOffset = 68;
private const int EnchantmentStatModKeyOffset = 72;
private const int EnchantmentStatModValOffset = 76;
private static unsafe int WalkEnchantList(IntPtr listPtrAddress, uint* spellIds, double* expiryTimes, int maxCount, int count,
uint* modTypes, uint* modKeys, float* modVals, uint* categories)
{
if (!SmartBoxLocator.IsMemoryReadable(listPtrAddress, 4))
return count;
@ -245,6 +524,13 @@ internal static class EnchantmentHooks
{
spellIds[count] = spellId;
expiryTimes[count] = duration > 0 ? start + duration : double.MaxValue;
if (modTypes != null)
{
modTypes[count] = unchecked((uint)Marshal.ReadInt32(nodePtr + EnchantmentStatModTypeOffset));
modKeys[count] = unchecked((uint)Marshal.ReadInt32(nodePtr + EnchantmentStatModKeyOffset));
modVals[count] = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(nodePtr + EnchantmentStatModValOffset));
categories[count] = unchecked((uint)Marshal.ReadInt32(nodePtr + EnchantmentCategoryOffset));
}
count++;
}

View file

@ -87,6 +87,10 @@ internal static class EngineStatusMetrics
w.WriteString("ts", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'"));
w.WriteString("host", SafeMachineName());
w.WriteNumber("pid", Environment.ProcessId);
// The engine's build ("2026.9.26.3 (8ca322f)", "dev (...)") and plugin API version, so a
// plugin can say which engine it runs on (RynthAi /ra version). Additive fields.
w.WriteString("engineVersion", EntryPoint.BuildStamp);
w.WriteNumber("apiVersion", Plugins.PluginContractVersion.Current);
w.WriteString("account", SessionStateRegistry.LastAccountName ?? string.Empty);
w.WriteString("character", SessionStateRegistry.LastCharacterName ?? string.Empty);

View file

@ -30,6 +30,11 @@ namespace RynthCore.Engine.Compatibility;
/// </summary>
internal static class GameTickHooks
{
/// <summary>Set once the Decal-coexistence plugin pump starts (no EndScene hook in that
/// client): the UseTime detour then also runs EngineFrameController.RunHeadlessPrefetch.
/// Never set in a client without Decal.</summary>
internal static volatile bool HeadlessPrefetch;
private const int UseTimeVa = 0x00411FA0; // Client::UseTime — thiscall, returns bool in AL
// Client::UseTime returns a bool (AL): AC's main loop drives it as
@ -118,7 +123,12 @@ internal static class GameTickHooks
// off-thread callers of IsPortaling in coexistence mode would see a
// perpetually stale cache since nothing else ever reads it on-thread.
// The getter itself does the guarded read + cache write; discard the value.
try { _ = TeleportStateHooks.IsPortaling; }
bool portaling = false;
try { portaling = TeleportStateHooks.IsPortaling; }
catch { }
// Death / portal space / teleport lines, for lining crashes up with what
// the character was doing (PlayerLifecycleLog).
try { PlayerLifecycleLog.SampleOnGameThread(portaling); }
catch { }
// Run AC's own game-logic + physics + animation pass.
@ -174,6 +184,17 @@ internal static class GameTickHooks
// requirement, and they go through the separate cast slot.)
try { AcMainThreadQueue.Drain(); }
catch { }
// Main-thread snapshots the pump reads instead of AC memory (player id,
// cast gate, pose, ...). Post-tick, so they reflect this tick's physics.
try { MainThreadSnapshots.Tick(); }
catch { }
// Decal clients only (no EndScene hook): the prefetches EngineFrameController
// runs per frame. False for every other client - one flag check.
if (HeadlessPrefetch)
{
try { ImGuiBackend.EngineFrameController.RunHeadlessPrefetch(); }
catch { }
}
// Busy watchdog: also post-tick now. Its decrement / cursor-refresh
// touch m_cBusy, not the motion sequence, so order is immaterial here;
// keeping all engine-issued mutations after AC's pass is the invariant.

View file

@ -1,4 +1,5 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
@ -22,10 +23,40 @@ internal static class HeartbeatLogger
private static int _exited;
private static Thread? _thread;
[StructLayout(LayoutKind.Sequential)]
private struct MEMORYSTATUSEX
{
public uint dwLength, dwMemoryLoad;
public ulong ullTotalPhys, ullAvailPhys, ullTotalPageFile, ullAvailPageFile,
ullTotalVirtual, ullAvailVirtual, ullAvailExtendedVirtual;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer);
/// <summary>
/// Free and total user address space of this (32-bit) process, in MB, or
/// (-1, -1). Every reload leaks the old engine and plugin copies, each a
/// NativeAOT runtime with its own reservations, so this only goes down;
/// 2026-09-28 13:57 a client vanished while its 5th engine loaded plugins.
/// </summary>
public static (long FreeMb, long TotalMb) AddressSpaceMb()
{
var m = new MEMORYSTATUSEX { dwLength = (uint)Marshal.SizeOf<MEMORYSTATUSEX>() };
if (!GlobalMemoryStatusEx(ref m)) return (-1, -1);
return ((long)(m.ullAvailVirtual >> 20), (long)(m.ullTotalVirtual >> 20));
}
public static void Start()
{
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
return;
try
{
var (free, total) = AddressSpaceMb();
RynthLog.Info($"HeartbeatLogger: address space at engine start: {free} MB free of {total} MB (initCount={EntryPoint.InitCount}).");
}
catch { }
_thread = new Thread(Run)
{
@ -62,6 +93,7 @@ internal static class HeartbeatLogger
{
long tick = 0;
int lastFrames = 0;
int lastDrawn = 0;
int lastPlugTicks = 0;
long lastMs = Environment.TickCount64;
long startMs = lastMs;
@ -83,15 +115,24 @@ internal static class HeartbeatLogger
int fps = (int)((frames - lastFrames) * 1000L / dtMs);
int pps = (int)((plug - lastPlugTicks) * 1000L / dtMs);
lastFrames = frames; lastPlugTicks = plug; lastMs = nowMs;
// fps counts every EndScene, including the offscreen passes Decal's views,
// VVS and UB render each frame (2-3 per frame in bridge mode), so it read
// 40-130 while the game drew 19-42 (2026-10-03). draw= is frames on screen.
int drawn = D3D9.EndSceneHook.BackBufferFrames;
int draw = drawn >= lastDrawn ? (int)((drawn - lastDrawn) * 1000L / dtMs) : 0;
lastDrawn = drawn;
long wsMb = 0;
try { wsMb = Environment.WorkingSet / (1024 * 1024); } catch { }
int login = 0;
try { login = LoginLifecycleHooks.HasObservedLoginComplete ? 1 : 0; } catch { }
// qd = marshalled actions silently dropped (ring full). A
// climbing qd with healthy fps means the consumer phase is
// dead — exactly the silent blackhole class the review found.
// qdrop = marshalled actions dropped (ring full) since start: a running
// TOTAL, not a queue depth. Named qdrop, not qd, since 2026-10-01: launchers
// read "qd" as a depth and killed healthy 60 fps clients once the total
// passed 2000 (a loot loop had flooded the ring), and an old launcher
// doesn't parse qdrop. A total climbing with healthy fps = a producer
// flooding the ring; flat = fine.
long dropped = 0;
try { dropped = AcMainThreadQueue.DroppedCount; } catch { }
// rec = busy reconciles (cast/item-action), fcl = force-clears.
@ -103,7 +144,38 @@ internal static class HeartbeatLogger
int idle = -1;
try { idle = LogoffOriginProbe.IdleSecondsForHeartbeat; } catch { }
string idleField = idle >= 0 ? $" idle={idle}s" : "";
RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} plug={pps}/s ws={wsMb}MB login={login} qd={dropped} rec={rec} fcl={fcl}{idleField}");
// ui = ImGui cost on AC's render thread per frame, p95/max over the
// last second (docs/IMGUI_PARITY_PLAN.md §4.5). Only while ImGui is on.
string uiField = "";
try
{
if (Plugins.EngineSettings.EnableImGuiBackend)
uiField = $" ui={ImGuiBackend.UiFrameStats.P95Ms:0.0}/{ImGuiBackend.UiFrameStats.MaxMs:0.0}ms";
}
catch { }
// vafree = free address space (MB): reloads leak engine/plugin copies,
// so a client that dies mid-reload can be checked for running out.
string vaField = "";
try { long free = AddressSpaceMb().FreeMb; if (free >= 0) vaField = $" vafree={free}MB"; }
catch { }
// req=<type>/<age>s = the client is waiting on an item request (it refuses
// every use/move/equip meanwhile); atk=1 = its attacking flag is set. Both
// omitted while open, so a long run of req= in a log is the item-action lock.
string gateField = ClientActionGates.HeartbeatField();
RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}");
// Every 60 s: garbage collections and the time they paused the process.
// Under the CoreCLR host the engine and managed plugins share one GC, so a
// blocking gen2 stalls AC's main thread whenever it is in managed code.
if (tick % 60 == 0)
LogGcStats();
// Every 5 s: hide and destroy any panel window no live panel owns
// (the "double UI" orphans).
if (tick % 5 == 0)
{
try { RynthCore.Engine.UI.LayeredWindow.SweepOrphans(); } catch { }
}
// Cache this client's live metrics so the GetEngineStatusJson host bridge can serve
// them to a plugin (the RynthRemote status export). No file write, no networking.
@ -140,4 +212,22 @@ internal static class HeartbeatLogger
Interlocked.Exchange(ref _exited, 1);
}
}
private static int _gc0, _gc1, _gc2;
private static TimeSpan _gcPause;
private static void LogGcStats()
{
try
{
int g0 = GC.CollectionCount(0), g1 = GC.CollectionCount(1), g2 = GC.CollectionCount(2);
TimeSpan pause = GC.GetTotalPauseDuration();
GCMemoryInfo info = GC.GetGCMemoryInfo(GCKind.Any);
RynthLog.Info($"gc: last 60s g0={g0 - _gc0} g1={g1 - _gc1} g2={g2 - _gc2} paused={(pause - _gcPause).TotalMilliseconds:0}ms " +
$"(last GC gen{info.Generation}{(info.Concurrent ? " background" : "")} {info.PauseDurations[0].TotalMilliseconds:0}ms) " +
$"heap={GC.GetTotalMemory(false) / 1048576}MB concurrent={System.Runtime.GCSettings.LatencyMode != System.Runtime.GCLatencyMode.Batch}");
_gc0 = g0; _gc1 = g1; _gc2 = g2; _gcPause = pause;
}
catch { }
}
}

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