merge: bring Aelrynth main and the 2026.10.5.x work into SK-local
Merges merge/aelrynth-2026.10.5.1 (Aelrynth main + local merge + installer 2026.10.5.11) so SK-local shares history with main for the PR. Conflicts resolved to the merge branch: - installer/previous-release version files: 2026.10.5.11 - EntryPoint.ImGuiNativeHandle: same property, merge-branch comment - ImGuiStackRecovery removed (and ImGuiController deletion kept): the shipped cimgui is now 1.91.6 with asserts routed to ImGuiAssertLog; it no longer exports igErrorCheckEndFrameRecover and EndFrame recovers open scopes itself Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
commit
b5dc4a3237
366 changed files with 88931 additions and 8874 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -55,3 +55,4 @@ installer/previous-release/*.exe
|
|||
# Local publish/bundle output (SK-era Build-Installer staging and old bundle exes)
|
||||
installer/_toolpublish/
|
||||
build_out/
|
||||
out/
|
||||
|
|
|
|||
38
BUILD.md
38
BUILD.md
|
|
@ -9,6 +9,35 @@ RynthCore is the injection framework. RynthSuite (separate repo) contains the pl
|
|||
- Visual Studio 2022 Build Tools with the **.NET desktop** and **C++ desktop** workloads (required by the NativeAOT ILC linker)
|
||||
- Asheron's Call client installed
|
||||
|
||||
## The unloadable engine (the default since 2026-09-29)
|
||||
|
||||
The engine now runs on CoreCLR, and a hot reload really frees the old engine and its plugins
|
||||
(`docs/UNLOADABLE_ENGINE_PLAN.md`, Status section). What ships and deploys:
|
||||
|
||||
```
|
||||
C:\Games\RynthCore\Runtime\
|
||||
├── RynthCore.Loader.dll ← native loader (native\Loader, C/cl.exe): injection target, hosts CoreCLR once
|
||||
├── RynthCore.Shim.dll ← the only RynthCore code in CoreCLR's default context
|
||||
├── RynthCore.Engine.dll(+pdb)← the engine, a managed assembly (-p:EngineHost=coreclr, ReadyToRun)
|
||||
├── Avalonia.*, ImGui.NET ... ← the engine's own dependencies (load and unload with each engine)
|
||||
├── cimgui, minhook, Skia ... ← native libraries (loaded once)
|
||||
└── dotnet\ ← the app-local x86 .NET runtime (from the NuGet runtime pack)
|
||||
C:\Games\RynthSuite\<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.
|
||||
|
||||
|
|
@ -239,6 +268,7 @@ If your AC client ever gets a real-world patch, apply it to both copies (or `rob
|
|||
- **Clean before plugin publish.** Incremental NativeAOT builds can silently reuse stale output. Delete `obj\Release` and `bin\Release` before every plugin publish to guarantee a fresh compile.
|
||||
- **Engine deploy path is `Runtime\`**, not `C:\Games\RynthCore\` directly. The injector resolves `Runtime\RynthCore.Loader.dll` (preferred) and `Runtime\RynthCore.Engine.dll` (legacy) by default.
|
||||
- **Close AC before redeploying Loader or Engine.** Both are loaded into `acclient.exe` and locked while the game is running. Plugins are shadow-copied so they can be hot-swapped without closing AC.
|
||||
- **cimgui.dll version must match ImGui.NET NuGet.** Post-1.90 struct layouts changed. A mismatched cimgui.dll causes `DisplaySize = <1, 1>` or font crashes on frame 2.
|
||||
- **cimgui.dll is built by us, not taken from NuGet.** `scripts\Build-Cimgui.ps1` fetches cimgui 1.91.6dock into `native\cimgui\_src` (git-ignored), builds it with MSVC (VS 2022 Build Tools, C++ workload) and writes `src\RynthCore.Engine\Native\cimgui.dll`, which is committed. The stock NuGet x86 DLL does not match ImGui.NET's structs (64-bit `ImTextureID`); the engine's `ImGuiSelfTest` refuses it and any other non-matching build. Only rerun the script when changing the cimgui build itself.
|
||||
- **vswhere.exe must be on PATH** for the NativeAOT link step. Add `C:\Program Files (x86)\Microsoft Visual Studio\Installer` to PATH if missing.
|
||||
- **Decal coexistence mode.** If `decal.dll`, `UBLoader.dll`, `Decal.Adapter.dll`, or `phatacd.dll` is loaded into acclient.exe, the engine skips the entire D3D9/ImGui path and runs plugins on a 30 Hz worker tick with Avalonia floating panels via `LayeredWindow` (GDI). This is intentional — two D3D9 hookers can't symmetrically save/restore render state. Check `RynthCore.log` for `D3D9: Decal coexistence` to confirm.
|
||||
- **Decal.** `src\RynthCore.DecalBridge` (net48) builds with the solution when Decal is installed (an empty assembly and a warning otherwise); every installer stages it (`Build-Installer.ps1` fails without Decal; `-SkipDecalBridge` for a dev build). The launcher registers it only for accounts set to "Decal + RynthCore (experimental)"; their choice is kept in `%APPDATA%\RynthCore\decal-accounts.json`, never in the shared `appsettings.json`. Bridge mode and in-game ImGui under Decal: `docs/DECAL_BRIDGE_PLAN.md`.
|
||||
- **Decal coexistence mode.** If `decal.dll`, `UBLoader.dll`, `Decal.Adapter.dll`, or `phatacd.dll` is loaded into acclient.exe and neither bridge mode nor `DecalInGameImGui` applies, the engine skips the entire D3D9/ImGui path and runs plugins on a 30 Hz worker tick with Avalonia floating panels via `LayeredWindow` (GDI). This is intentional — two D3D9 hookers can't symmetrically save/restore render state. Check `RynthCore.log` for `D3D9: Decal coexistence` to confirm.
|
||||
|
|
|
|||
131
Changelog/2026-10-05-aelrynth-2026.10.5.1-merge.md
Normal file
131
Changelog/2026-10-05-aelrynth-2026.10.5.1-merge.md
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
# Merge: upstream aelrynth RynthCore 2026.10.5.1 into SK-local
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Branch:** `merge/aelrynth-2026.10.5.1` (local only, not pushed)
|
||||
**Upstream:** https://aelrynth.com/git/rynth/RynthCore (`upstream/main`, c3e1548)
|
||||
**Component:** RynthCore (engine, plugin SDK, launcher, installer). RynthSuite is not part of this merge.
|
||||
|
||||
## Summary
|
||||
|
||||
Brings the upstream 2026.10.5.1 snapshot into our fork. Upstream publishes squashed
|
||||
snapshots with no shared history, so the snapshot we had already ported (9b5e276,
|
||||
2026.9.27.2) was recorded first as the merge base. This merge is a 3-way merge on top of it.
|
||||
|
||||
Upstream's architecture wins wherever the two sides overlapped. Our features were ported
|
||||
into the new structure rather than kept beside it.
|
||||
|
||||
## What upstream brings
|
||||
|
||||
- **UI data hub:** panels now read from `UiSources` and act through command classes
|
||||
(`RynthAiCommands`, `ItemsCommands`, `NavCommands`, `SettingsCommands`). Plugin exports
|
||||
are bound through `PluginExportBinder` and run on the pump thread (`UiDataHub.Post`).
|
||||
- **ImGui "faces":** ImGui versions of the panels (`ImGui/Panels/*Face.cs`).
|
||||
- **Chat:** chat model and router in `UI/Data/ChatData.cs`, with rules that have an
|
||||
action, a "when" condition and a colour.
|
||||
- **Settings:** data-driven settings (`SettingsSchema` / `SettingRow`).
|
||||
- **Frame pipeline:** `EngineFrameController` replaces `ImGuiController` (deleted).
|
||||
ImGui is now drawn *before* the Avalonia overlay, so draw order matches mouse hit-testing.
|
||||
- **Unloadable engine:** a CoreCLR engine hosted by a native C loader (`native/Loader`,
|
||||
`RynthCore.Shim`, app-local .NET runtime in `Runtime\dotnet`). The NativeAOT engine
|
||||
is still available.
|
||||
- **Plugin API stubs:** every plugin API slot is routed through native loader stubs.
|
||||
- **Decal bridge (experimental):** a Decal network filter that lets an account run as
|
||||
"Decal + RynthCore", with installer and launcher registration.
|
||||
- **Item data:** a full PublicWeenieDesc byte snapshot (`PwdLayout`) for off-thread item reads.
|
||||
- **Monster HUD, Lua panel**, plus many other fixes in the snapshot.
|
||||
|
||||
## Our features kept
|
||||
|
||||
- **Plugin API v77 (ABI change):** `GetMergeStackResultFn` moves to the end of the
|
||||
API struct, after upstream's v68–v76 slots. Our previous slot position collided with
|
||||
upstream's, so `PluginContract.Current`, `RynthCoreApiNative` and
|
||||
`RynthCoreHost.CurrentApiVersion` are now 77. `HasGetMergeStackResult` requires v77.
|
||||
- **Plugin overlay windows:** the ILT Hub, Item Info, Lua and Map overlay windows still
|
||||
render when the ImGui shell is off. This is a new branch in
|
||||
`EngineFrameController`, using `PluginManager.HasOverlayPlugins` and the
|
||||
`EnablePluginOverlayWindows` setting.
|
||||
- **Engine settings:** `LoggingLevel` is kept next to upstream's Decal settings.
|
||||
The Decal keys were added to `OwnedFields` so settings.json never gets duplicate keys.
|
||||
- **Window messages:** the layered-window self-destroy message moved from 0x8005 to
|
||||
0x8051. Upstream now uses 0x8005 for `WM_RYNTH_POST_ACTION` on the game window.
|
||||
- **Chat standard filters and match modes:** ported into upstream's `ChatModel` and
|
||||
`ChatRouter`.
|
||||
- Contains / Starts with / Ends with / Regex modes for each rule.
|
||||
- Standard (canned) filters run after custom rules and can hide lines or move them to a tab.
|
||||
- Both the Avalonia filters panel and the ImGui `ChatFiltersFace` have the mode picker
|
||||
and the Standard filters section.
|
||||
- Settings JSON is unchanged (`filters[].mode`, `presets[]`). `RynthChatPresets`
|
||||
state is `volatile` because routing runs on the pump thread.
|
||||
- **Items panel Shields:** the Shields section is now backed by
|
||||
`ItemsCommands.AddSelectedShield` (`RynthPluginAddSelectedShield`).
|
||||
- **Inventory HUDs button:** a new `SettingKind.Button` row type in `SettingsSchema`
|
||||
(Avalonia panel and ImGui face). It opens the HUD / Mini Remote window through
|
||||
`RynthAiCommands.ApplyRemoteCommand("huds", "show")`.
|
||||
- **RynthAi dashboard:**
|
||||
- Char → `hub show`.
|
||||
- Hub → `remote toggle`; right-click → `huds show`.
|
||||
- The Map half of the Nav/Map button → `map toggle`.
|
||||
- All four go through `RynthAiCommands.ApplyRemoteCommand`.
|
||||
- **Meta folder:** `MetaData.MetaFolder` follows the install path
|
||||
(`RynthInstallPaths.RynthAiDir\MetaFiles`) instead of a hard-coded `C:\Games` path.
|
||||
- **Nav panel:** waypoint list polling pauses while the pointer is over the list.
|
||||
|
||||
## Dropped in favour of upstream
|
||||
|
||||
- `PropertyUpdateHooks` int/bool caches and `AppraisalHooks.PatchCachedInt/Bool`.
|
||||
Upstream folds property updates into its appraisal cache.
|
||||
- Our duplicate PublicWeenieDesc int snapshot in `ClientObjectHooks`. Off-thread
|
||||
`TryReadPwdInt32` now reads upstream's byte snapshot via `TryGetPwdSnapshotRawInt32`.
|
||||
- The deferred ImGui draw path (`RenderDeferredImGui`) and the multi-viewport experiment
|
||||
(`ViewportProbe`, `ViewportPlatformBackend`, `ViewportRendererBackend`, `ViewportOffsets`).
|
||||
- The launcher's "allow multiple clients" bypass of the duplicate-session check.
|
||||
Upstream now keys sessions by account and server.
|
||||
|
||||
## Installer and release scripts
|
||||
|
||||
- `Build-Installer.ps1` keeps our layout: two install folders (`staging\core` /
|
||||
`staging\suite`), experimental plugins, Monster Editor, release package and manifest.
|
||||
New options:
|
||||
- **Default engine is now upstream's unloadable CoreCLR engine** plus the native loader
|
||||
(`scripts\Publish-EngineCoreClr.ps1`; needs the Visual Studio C++ tools).
|
||||
`-NativeAot` builds the previous NativeAOT engine and loader.
|
||||
- **Decal bridge:** built and staged to `{app}\DecalBridge` when Decal 3.0 is installed
|
||||
(or `-DecalDir`). Without Decal the build continues with a warning.
|
||||
`-IncludeDecalBridge` makes a missing Decal an error; `-SkipDecalBridge` leaves it out.
|
||||
- The required-files check also covers the CoreCLR shim and runtime, and the bridge when built.
|
||||
- `RynthCore.iss`: our Suite-folder pages and publisher info, plus upstream's Decal bridge
|
||||
registration on install/update (`CurStepChanged`) and unregistration on uninstall.
|
||||
- `Publish-Update.ps1`: our paths. A missing Decal bridge now only gives a warning
|
||||
instead of blocking the publish.
|
||||
|
||||
## Verification
|
||||
|
||||
- `dotnet build RynthCore.sln -c Release`: 0 errors.
|
||||
- NativeAOT publish of `RynthCore.Engine` and `RynthCore.Loader`: OK.
|
||||
- `scripts\Publish-EngineCoreClr.ps1` (CoreCLR engine, native loader, shim, .NET 10.0.5
|
||||
app-local runtime) to a scratch folder: OK.
|
||||
- Not yet tested in game.
|
||||
|
||||
### RynthSuite against the v77 SDK
|
||||
|
||||
- RynthSuite's own upstream merge (`merge/aelrynth-2026.10.5.1`, 532fa67) was checked out
|
||||
next to this worktree (`D:\rynth-merge\RynthSuite`), so its `..\RynthCore` project
|
||||
references resolve to this branch's SDK.
|
||||
- RynthAi NativeAOT publish: OK. Full `RynthSuite.slnx` Release build: 0 errors.
|
||||
- `RynthCore.RynthAiHostTests`: 356 passed, 0 failed (5 known failures).
|
||||
- No RynthSuite code changes were needed. That branch's `InventoryManager` uses
|
||||
upstream's `MergeStackInternal` and no longer calls `GetMergeStackResult`, so it needs
|
||||
no v77 gate.
|
||||
- A RynthAi built from SK-local RynthSuite (0.6.32 and earlier) reads
|
||||
`GetMergeStackResultFn` at its old v68 slot, which upstream now uses for something else.
|
||||
Only pair this engine with a RynthAi built from the merged RynthSuite.
|
||||
|
||||
## Follow-ups
|
||||
|
||||
- The installer's default engine is upstream's CoreCLR engine (confirmed). Test it in
|
||||
game before releasing; `-NativeAot` is the fallback.
|
||||
- Several new upstream paths are hard-coded to `C:\Games\...` (native loader log dir,
|
||||
`RynthUpdater` default Suite dir, NavData, usage-stats dumps, ImGui pop-outs,
|
||||
Decal bridge log dir). Installs in other folders may be affected.
|
||||
- The ImGui `ItemsFace` has no Shields section yet (the Avalonia Items panel does).
|
||||
- The `ImGuiStackRecovery` work in the main checkout is uncommitted and not part of this branch.
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
# Char panel rework: Progression on the Skills panel, Pets and Quests windows (RynthAi 0.5.4-legacy-ui)
|
||||
|
||||
Date: 2026-10-05
|
||||
Branches (local): RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands`
|
||||
Previous plugin version: 0.5.3-legacy-ui
|
||||
|
||||
## Why
|
||||
|
||||
The ILT Hub's Character tab mixed three different things:
|
||||
|
||||
- live session stats;
|
||||
- character progression (XP, augmentations, enlightenment), which belongs with skills;
|
||||
- quests.
|
||||
|
||||
Pets and quests are things you keep open while playing, so they get their own windows.
|
||||
|
||||
## Skills panel: new Progression tab (ILT worlds only)
|
||||
|
||||
The engine's Skills panel gains a third tab, **Progression**, next to Skills and Attributes &
|
||||
Vitals. It shows only when RynthAi reports an ILT-like world. It has three sections:
|
||||
|
||||
- **XP planner**: XP for the next raise and for the next N raises (slider 1-100) of every attribute
|
||||
and vital. Costs are computed exactly from the client's XP tables (`SkillDat.CostOf`). The Hub's
|
||||
version used `/xp all` and +7.5-7.7% per-level estimates. Raising stays on the Attributes & Vitals
|
||||
tab.
|
||||
- **Augmentations**: the Hub's planner with the same controls. It has Load /aug, Lum per Enlightened
|
||||
Coin, and per-aug targets. It shows luminance and coin totals, coins short and banked luminance.
|
||||
- **Enlightenment**: same controls as the Hub had:
|
||||
- next step, plan-to-level totals, coins per token and tokens short;
|
||||
- the requirement checklist;
|
||||
- Enlighten now, auto-enlighten (arm / spend XP first / check interval).
|
||||
- "Enlighten now" and arming auto-enlighten ask in a Skills-panel confirmation first. The server
|
||||
still shows its own Yes/No dialog.
|
||||
|
||||
How it works:
|
||||
|
||||
- RynthAi still owns the planner math and the saved inputs, so the numbers can't drift from the
|
||||
Hub's.
|
||||
- New export `RynthPluginGetProgressionJson` (built by `IltHubController.BuildProgressionJson` and
|
||||
`IltProgression.AppendSnapshotJson`). The engine polls it through the new
|
||||
`UiSources.Progression` (once a second while the Skills panel is open).
|
||||
- Edits go back as the remote command `prog <sub> <args>`, handled by `IltProgression.HandleRemote`
|
||||
on the pump thread. The subcommands are `augload`, `augtarget`, `lumpercoin`, `enltarget`,
|
||||
`coinspertoken`, `enlighten`, `autoenl on|off|arm`, `spendfirst` and `checkevery`.
|
||||
|
||||
## Pets and Quests windows
|
||||
|
||||
- **Pets**: new undocked "Pets" window. Open it with `/ra pets [show|hide|toggle]`, the Pet tab's
|
||||
"Pop out" button, or Char right-click > Pets window. Closing it docks the roster back into the Pet
|
||||
tab. It draws only on ILT worlds. The open state is saved per character (`PetsWindowOpen`).
|
||||
- **Quests**: the existing undocked quest window now carries Quest bonus (`/qb`) above the tracker.
|
||||
Open it with `/ra quests window [show|hide|toggle]` or Char right-click > Quests window.
|
||||
|
||||
## ILT Hub layout
|
||||
|
||||
- Tabs: **Character · Quests · Pet · Banking · Gear · Games**. Tab buttons are narrower (92 px) so
|
||||
all six fit the Hub's width.
|
||||
- **Character**: Session rates, plus a note pointing to the Skills panel's Progression tab.
|
||||
- **Quests** (new tab): Quest tracker + Quest bonus. It shows "open in its own window / Dock back"
|
||||
while the Quests window is open.
|
||||
- **Pet**: the roster with a "Pop out" button. It shows "Dock back" while the Pets window is open.
|
||||
- Saved tab selections still open the same tab. New tabs are appended to the persisted index list,
|
||||
and only the display order changed.
|
||||
- Removed from the Hub: the XP calculator (replaced by the exact Skills-panel planner) and the Hub's
|
||||
copies of the Augmentations / Enlightenment UI. Unused `/xp all` capture and `/attr` raise code
|
||||
went with them. The spend-XP-before-auto-enlighten loop is unchanged.
|
||||
|
||||
## Dashboard
|
||||
|
||||
- **Char** launcher, left-click: ILT Hub (unchanged).
|
||||
- **Char** launcher, right-click (new menu): ILT Hub, Pets window, Quests window, and
|
||||
Progression (Skills panel). Progression opens the Skills panel on the Progression tab
|
||||
(`SkillsFace.ShowProgression`).
|
||||
58
Changelog/2026-10-05-charms-tracking-tab.md
Normal file
58
Changelog/2026-10-05-charms-tracking-tab.md
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
# Charms Tracking tab (Settings) - RynthAi 0.5.10-legacy-ui
|
||||
|
||||
Date: 2026-10-05
|
||||
Previous RynthAi version: 0.5.9-legacy-ui
|
||||
Next installer: 2026.10.5.9 (not built yet; includes the Nav breadcrumb / route overlay toggles)
|
||||
|
||||
## Charm list check against ACECustom
|
||||
|
||||
RynthAi's charm registry (`IltHub/IltInventory.cs`, `Charms`) was compared with ACECustom's
|
||||
`CharmAbilityRegistry.cs`. All 13 registry charms are present with every tier WCID:
|
||||
|
||||
| Charm | WCIDs | Player ability flag |
|
||||
|-------|-------|---------------------|
|
||||
| Mana Barrier | 777700001, 777700054, 777710004, 777720004 | 50010 |
|
||||
| Infinite Casting Stone | 777700019, 777700055 | 50028 |
|
||||
| Asheron's Favor | 777700020, 777710002, 777720002 | 50030 |
|
||||
| Artisan's | 777700021, 777710003, 777720003 | 50031 |
|
||||
| Shrapnel | 777700022 | 50032 |
|
||||
| Agony | 777700023 | 50033 |
|
||||
| Split Cast | 777700024 | 50035 |
|
||||
| Explosive Arrow | 777700025, 777710005, 777720005 | 50036 |
|
||||
| Omni Strike | 777700026 | 50037 |
|
||||
| Fork | 777700027, 777710007, 777720007 | 50039 |
|
||||
| Auto-Rebuff | 777700300 | none (server keeps it in memory) |
|
||||
| Summon Essence Refill | 78780030 | 9049 |
|
||||
| Universal Summoning Mastery (universal pet charm) | 78780031 | 50038 |
|
||||
|
||||
Guardian Hand is not an ACECustom registry charm; RynthAi still recognises it by name on the Gear window.
|
||||
|
||||
## New: Settings > Charms Tracking
|
||||
|
||||
The engine Settings panel has a new last sidebar tab, **Charms Tracking**, with one row per charm:
|
||||
|
||||
- **Acquired**: `Carried` (in your pack or equipped, with a count when you have several),
|
||||
`Stored` (this character carried it before; RynthAi remembers it per character in
|
||||
`ilt-hub.json`, because the client only sees carried items) or `Not yet`.
|
||||
- **Status**: `ON` / `OFF` from the charm's appraisal text ("Status: ON"), falling back to the
|
||||
character's ability flag. Appraisal is requested automatically (throttled to every 30 s per item).
|
||||
- **Tier**: current / max tier (CharmLevel / CharmMaxLevel, or "Charm [Tier x/y]" from the appraisal).
|
||||
- **Server**: `Disabled` when the server refused the charm (Auto-Rebuff, Universal Summoning
|
||||
Mastery) or a feature dump reported it off, `Enabled` when reported on, otherwise `-`
|
||||
(players can't query the server's /charms list).
|
||||
- Hover a charm name for its effect. A summary line shows how many are acquired and active.
|
||||
- Off ILT worlds the tab says so and points to `/ra hub force on`.
|
||||
|
||||
## Fix
|
||||
|
||||
- Pets: an Infinite Casting Stone that is switched OFF no longer counts as "casting supplies"
|
||||
(an OFF stone doesn't waive spell components).
|
||||
|
||||
## Files
|
||||
|
||||
- RynthSuite: `IltHub/IltCharmTracker.cs` (new), `IltHub/IltInventory.cs` (charm flags, effects,
|
||||
tier reader, casting-stone check), `IltHub/IltHubState.cs` / `IltHubStore.cs` (`CharmsSeen`),
|
||||
`IltHub/IltHubController.cs`, `PluginExports.cs` (`RynthPluginGetCharmsJson`),
|
||||
`RynthAiPlugin.LocalFeatures.cs`, `RynthAiVersionCommand.cs` (0.5.10-legacy-ui).
|
||||
- RynthCore: `UI/Data/CharmsData.cs` (new `CharmsSource`), `UI/Data/UiSources.cs`,
|
||||
`ImGui/Panels/SettingsFace.cs` (Charms Tracking tab).
|
||||
63
Changelog/2026-10-05-floating-window-placement.md
Normal file
63
Changelog/2026-10-05-floating-window-placement.md
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
# Floating windows open where they can be seen (RynthAi 0.5.5-legacy-ui)
|
||||
|
||||
Date: 2026-10-05
|
||||
Branches (local): RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands`
|
||||
Previous plugin version: 0.5.4-legacy-ui
|
||||
|
||||
## Problem
|
||||
|
||||
New windows with no saved position opened in the top-left corner of the game view:
|
||||
|
||||
- the Pets window at ImGui's default (60,60);
|
||||
- the Item HUD at (20,220);
|
||||
- the Mini Remote at (20,120);
|
||||
- the Dungeon Map in the panel cascade (100,100 and onwards).
|
||||
|
||||
Popped-out panels are separate Windows windows above the game window. They often sit in that
|
||||
corner, and nothing drawn inside the game frame (ImGui windows included) can appear over them. So
|
||||
the new windows opened hidden underneath. The draw-order fix (`2026-10-05-imgui-over-avalonia-port.md`)
|
||||
only covers the Avalonia layer painted inside the game frame.
|
||||
|
||||
## Changes
|
||||
|
||||
### RynthAi (plugin)
|
||||
|
||||
- New `UiPlacement` helper:
|
||||
- `CenterFirstUse(offset)`: before `Begin`, sets a `FirstUseEver` position centred in the game
|
||||
view (pivot 0.5,0.5). It only applies when imgui.ini has nothing saved for the window.
|
||||
- `RescueOncePerShow(ref checked)`: once per show, moves the window to the middle if less than
|
||||
40 px of it is on screen. The test is the ILT Hub's existing off-screen check, now shared as
|
||||
`UiPlacement.IsOnScreen`.
|
||||
- First-use spots (centre plus offset):
|
||||
|
||||
| Window | First-use spot |
|
||||
| --- | --- |
|
||||
| ILT Hub | centre |
|
||||
| Pets | centre |
|
||||
| Quests (popped out) | centre + (40,40) |
|
||||
| Item HUD | centre + (220,-160) |
|
||||
| Mini Remote | centre + (-220,-160) |
|
||||
|
||||
All five also get the off-screen check each time they're shown.
|
||||
- The ILT Hub's off-screen rescue now moves the window to the middle of the game view instead of
|
||||
(40,40), which is where popped-out panels usually sit.
|
||||
|
||||
### Engine
|
||||
|
||||
- `PanelSpec.OpenCentered`: a panel with nothing saved and no `DefaultPos` opens centred in the game
|
||||
view instead of the cascade. The Dungeon Map uses it.
|
||||
- Docked panels open clear of popped-out windows.
|
||||
- When an engine panel opens docked, `ImGuiPanelHost` checks the visible popped-out windows
|
||||
(`LayeredWindow.VisibleContentRects`: every Avalonia and ImGui pop-out and the floating bar).
|
||||
- If more than half of the panel would be hidden, it opens at the nearest spot on a 9x9 grid over
|
||||
the game view that's hidden the least. The open's normal save records that spot.
|
||||
- Each move is logged as `ImGuiPanelHost: <title> would open under a popped-out window; moved from
|
||||
(x,y) to (x,y).`
|
||||
|
||||
## Limits
|
||||
|
||||
- Plugin windows (Pets, Quests, Item HUD, Mini Remote, Hub) are centred on first use and pulled back
|
||||
if off-screen. They don't yet avoid popped-out panels: the plugin can't see where those are. That
|
||||
would need a new PluginSdk host call.
|
||||
- ImGui windows still can't draw above popped-out panels. To keep both visible, dock the panel, or
|
||||
move it away from where the windows open.
|
||||
58
Changelog/2026-10-05-guardian-and-remote-slots.md
Normal file
58
Changelog/2026-10-05-guardian-and-remote-slots.md
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
# 2026-10-05 - ILT Guardian window, Mini Remote slot assignment
|
||||
|
||||
RynthAi 0.5.11-legacy-ui (previous 0.5.10-legacy-ui) with the RynthCore engine changes below.
|
||||
Ships in installer 2026.10.5.10.
|
||||
|
||||
## Guardian window (ported from UB-IT's Guardian tab)
|
||||
|
||||
Open it from the Mini Remote's Options, the dashboard Char button's right-click menu, or
|
||||
`/ra hub open guardian` (`/ra guardian window`).
|
||||
|
||||
- **Riddle translator.** Translates incoming "Guardian of the Temple of Enlightenment" and
|
||||
"Guardian of Attribute Enlightenment" tells and says (all 18 Temple spell words and the full
|
||||
attribute-riddle table, typo-tolerant), plus a paste box for manual translation. The answer
|
||||
shows in the window and as a "Guardian:" row on the Mini Remote for 10 minutes, with a
|
||||
Give button.
|
||||
- **Hand-in.** Gives one of the answer item to the guardian (whole item when it isn't a stack).
|
||||
For the Temple guardian, when you carry none and "Buy if missing" is on, it first buys one
|
||||
from the open or nearest vendor through the engine's vendor trade API. It waits out the busy
|
||||
hourglass, has per-step timeouts, and reports every failure in chat. "Auto hand-in" runs it
|
||||
after each chat answer (off by default).
|
||||
- **Attribute turn-ins.** One row per Fiun attribute NPC plus the riddle. Counts and cooldowns
|
||||
come from /myquests when the server reports the flag, otherwise from "/qb list" wait stamps
|
||||
(a stamp appearing counts a turn-in and starts an estimated cooldown; "Assumed cooldown"
|
||||
sets its length). Rows can be overridden with `infi attribute.csv` in the RynthAi folder or
|
||||
UB's `Documents\Asheron's Call` location.
|
||||
- **Commands:** `/ra guardian [window|translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status]`.
|
||||
- **Not ported:** UB's `/fillcomps` + "buy all" spell-component restock during the Temple
|
||||
hand-in. It is unrelated to the guardian quest, and the engine buys specific items rather
|
||||
than the client's buy list.
|
||||
|
||||
New files: `IltHub/IltGuardian.cs`, `IltHub/IltGuardianPhrasebook.cs`, `IltHub/IltTempleAttributes.cs`.
|
||||
Settings persist per character in `ilt-hub.json` (`Guardian` block, `GuardianWindowOpen`).
|
||||
|
||||
## Mini Remote slot assignment
|
||||
|
||||
Previously, items could not be put into Mini Remote slots from the game inventory or from a
|
||||
popped-out RynthCore Inventory.
|
||||
|
||||
- **Game inventory drag-and-drop (engine `ItemDragBridge`).** A left drag that starts on a
|
||||
carried item in AC's own inventory is now published to ImGui. Releasing it on an **empty**
|
||||
Mini Remote slot assigns it. A game drag released over any RynthCore window is handed back
|
||||
to AC at its starting point, so the item is never dropped on the ground.
|
||||
- **Popped-out RynthCore Inventory.** Drags from a popped-out Inventory window now reach the
|
||||
Mini Remote (the pop-out runs in its own ImGui context).
|
||||
- **Click to assign.** Clicking an item in the RynthCore Inventory also selects it in the game.
|
||||
The Mini Remote remembers the last carried item you selected for 2 minutes, so the combat
|
||||
bot re-selecting monsters no longer loses it before you click an empty slot.
|
||||
- **Inventory right-click: "Add to Mini Remote".** Adds the item to the first empty slot or a
|
||||
chosen slot (remote command `remoteslot <slot|first> <objectId>`).
|
||||
- Empty-slot tooltips explain all three ways to assign.
|
||||
|
||||
### Known limits
|
||||
|
||||
- The engine infers a game-inventory drag from AC's selection. Dragging an AC panel while a
|
||||
pack item is selected looks the same, which is why game drags only fill empty slots.
|
||||
Dragging from the RynthCore Inventory can replace a filled slot.
|
||||
- If an AC panel is dragged and released over a RynthCore window while a pack item is selected,
|
||||
the panel returns to where the drag started.
|
||||
38
Changelog/2026-10-05-guardian-vendor-and-item-lookup.md
Normal file
38
Changelog/2026-10-05-guardian-vendor-and-item-lookup.md
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
# ILT Guardian: hand-in finds the vendor and the item in your pack
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Component:** RynthAi 0.5.13-legacy-ui (previous 0.5.12-legacy-ui), `IltHub/IltGuardian.cs`
|
||||
|
||||
## Problem
|
||||
|
||||
The riddle was translated correctly, but the hand-in never got further:
|
||||
|
||||
- **Temple guardian** (Myrrh, Saffron): every attempt failed within ~30 ms with
|
||||
"no Myrrh carried and no vendor nearby", while Archmage Yuzai Zhen (`0x77F15002`) stood next to you.
|
||||
- **Attribute guardian** (Ashwood Talisman): after buying the talisman, every attempt failed with
|
||||
"no Ashwood Talisman in your packs".
|
||||
|
||||
## Causes
|
||||
|
||||
1. The vendor search looked for `ObjectClass == Vendor`. The world cache classifies every creature,
|
||||
vendors included, as Monster (or Npc later); nothing is ever classed Vendor, so no vendor could match.
|
||||
2. The item search used the world cache's inventory set. That set is filled asynchronously (a fresh
|
||||
purchase can be missing), and items from an open vendor's stock land in it too (they have no
|
||||
position), so it isn't a reliable "what's in my pack" list.
|
||||
|
||||
## Fix
|
||||
|
||||
- Vendors are recognised by the weenie **BF_VENDOR** bitfield flag (`0x200`) through
|
||||
`TryGetObjectBitfield` (a cache entry classed Vendor still counts).
|
||||
- The hand-in item is looked up in a **live walk of your pack and side packs**
|
||||
(`GetDirectInventory(forceRefresh: true)`, AC's container contents with live names). Worn items are skipped.
|
||||
- Item and vendor-stock names are compared ignoring case and extra spaces.
|
||||
- When something isn't found, the IltHub log says why:
|
||||
- `[IltGuardian] no '<item>' among N carried items; similar names: ...`
|
||||
- `[IltGuardian] vendor search: N landscape objects, bitfield=yes, vendors: '<name>' 0x... <dist> m`
|
||||
- `[IltGuardian] vendor for '<item>': <name> 0x...` when a vendor is picked.
|
||||
|
||||
## Not changed
|
||||
|
||||
- Buying applies to the Temple guardian only (Attribute guardian items must be carried).
|
||||
- Search range stays 60 m for the vendor and the guardian.
|
||||
59
Changelog/2026-10-05-ilt-hub-context-char-hub-logging.md
Normal file
59
Changelog/2026-10-05-ilt-hub-context-char-hub-logging.md
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
# ILT Hub windows draw again, Char/Hub on the ImGui dashboard, hidden-log warning
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Component:** RynthCore Engine (merge branch `merge/aelrynth-2026.10.5.1`, after installer 2026.10.5.2)
|
||||
|
||||
## Summary
|
||||
|
||||
Fixes three problems found testing installer 2026.10.5.2.
|
||||
|
||||
## ILT Hub (and the other RynthAi windows) never appeared
|
||||
|
||||
RynthAi logged `[Overlay] OnRenderOverlay skipped: no ImGui context.` on both clients.
|
||||
|
||||
- **Cause:** the merged engine handed plugins the ImGui context only when the ImGui shell is on.
|
||||
In this build the shell can only be turned on through an environment variable. RynthAi's own
|
||||
ImGui windows (ILT Hub, Mini Remote, Inventory HUDs, Item Info, translator window, nav overlay)
|
||||
draw only with that context, so they all skipped. UbRythai also refused to start without it
|
||||
(its `Initialize` returns 11).
|
||||
- **Fix (`ImGui/EngineFrameController.cs`):** plugins also get the context when plugin overlay
|
||||
windows are enabled (`EnablePluginOverlayWindows`, default on) and the ImGui layer is on.
|
||||
The plugin host copies the context once at init, so plugin init waits for the first ImGui
|
||||
frame. The wait is capped at about 5 s (300 pump frames). If ImGui init fails or stalls,
|
||||
plugins start anyway and a warning is logged.
|
||||
- The merged RynthAi reads the context only for those windows, so this does not switch it into
|
||||
its old legacy ImGui UI (the reason upstream withheld it).
|
||||
|
||||
## Char and Hub buttons were missing
|
||||
|
||||
With the ImGui layer on, the engine always shows upstream's ImGui RynthAi dashboard
|
||||
(`RynthAiFace`) in the game window. Char and Hub had only been ported to the Avalonia dashboard,
|
||||
which is no longer shown there.
|
||||
|
||||
- **Fix (`ImGui/Panels/RynthAiFace.cs`):** the launcher row now has 10 buttons. After Patrol:
|
||||
- **Char:** opens the ILT Hub (`/ra hub show`).
|
||||
- **Hub:** left-click toggles the Mini Remote (`/ra remote`); right-click opens the Inventory
|
||||
HUDs setup (`/ra huds`).
|
||||
|
||||
## Engine log nearly empty
|
||||
|
||||
The 2026.10.5.2 session logs had only loader lines and two warnings.
|
||||
|
||||
- **Cause:** `engine.json` had `LoggingLevel: Info` with every `LogCategories` entry at
|
||||
`Trace`. A category's value is the level its lines are written at, so every engine and
|
||||
plugin line became a Trace line and was dropped by the Info global level. The startup banner
|
||||
went through the same filter.
|
||||
- **Fix (`EntryPoint.cs`, `LogSettings.cs`):**
|
||||
- The startup banner (build, OS/CLR, logging summary) is always written.
|
||||
- A new warning names any category set above the global level. It is logged at startup and
|
||||
whenever `engine.json` changes, e.g. `LogSettings: General=Trace, ... write above the
|
||||
global LoggingLevel (Info), so those lines are NOT logged.`
|
||||
- Your `engine.json` now has `LoggingLevel: Trace` (changed at 09:10), so the next session
|
||||
logs everything as-is.
|
||||
|
||||
## Files
|
||||
|
||||
- `src/RynthCore.Engine/ImGui/EngineFrameController.cs`
|
||||
- `src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs`
|
||||
- `src/RynthCore.Engine/LogSettings.cs`
|
||||
- `src/RynthCore.Engine/EntryPoint.cs`
|
||||
41
Changelog/2026-10-05-imgui-over-avalonia-port.md
Normal file
41
Changelog/2026-10-05-imgui-over-avalonia-port.md
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
# ImGui windows draw over the Avalonia panels again (merge branch)
|
||||
|
||||
Date: 2026-10-05
|
||||
Branch: RynthCore `merge/aelrynth-2026.10.5.1` (local)
|
||||
Restores: SK-local 6b94752 (draw order part)
|
||||
|
||||
## Problem
|
||||
|
||||
In 2026.10.5.4 the ILT Hub, Mini Remote and Inventory HUDs open, but an Avalonia panel covering
|
||||
the same screen area hides them. The Hub, saved at about (540,105), 633x786, only shows where no
|
||||
panel covers it.
|
||||
|
||||
SK-local 6b94752 submitted ImGui draw data after the Avalonia blit. The aelrynth merge took
|
||||
upstream's `EngineFrameController`. Upstream builds the ImGui frame in `BuildImGuiFrame` and
|
||||
submits it inside `OnEndScene`, before `EndSceneHook` blits the Avalonia quad. So the panels drew
|
||||
on top again.
|
||||
|
||||
## Fix
|
||||
|
||||
- `EngineFrameController.OnEndScene` keeps the built frame (device + timing) instead of submitting
|
||||
it. The pending frame is cleared at the start of every `OnEndScene`, so a frame that throws early
|
||||
never resubmits stale draw data.
|
||||
- New `EngineFrameController.RenderDeferredImGui()` submits it once. `UiFrameStats` gets build +
|
||||
pop-out + submit time, as before.
|
||||
- `EndSceneHook` calls `RenderDeferredImGui()` after `OverlayTextureRenderer.Render`. It runs even
|
||||
when the Avalonia blit doesn't (character select), so ImGui draws exactly as before there.
|
||||
- Popped-out panels still render inside `OnEndScene`. They use their own render targets and restore
|
||||
AC's target and viewport.
|
||||
|
||||
## Mouse priority (checked, unchanged)
|
||||
|
||||
6b94752's `Win32Backend.ImGuiOwnsMouseOverAvalonia` survived the merge. A mouse message skips the
|
||||
Avalonia forward while ImGui wants the mouse (`io.WantCaptureMouse` or a monster nameplate), unless
|
||||
an Avalonia drag/resize holds pointer capture. So clicks on a visible ImGui window go to ImGui, not
|
||||
to the panel underneath. Only a misplaced doc comment was fixed.
|
||||
|
||||
## Notes
|
||||
|
||||
- ImGui windows and in-client ImGui panels now cover any Avalonia panel or popup they overlap.
|
||||
Avalonia gets the click only where no ImGui window is under the cursor.
|
||||
- Engine build only; not in an installer yet.
|
||||
22
Changelog/2026-10-05-inventory-add-to-item-count-hud.md
Normal file
22
Changelog/2026-10-05-inventory-add-to-item-count-hud.md
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
# Inventory: "Add to item count HUD" (RynthAi 0.5.3-legacy-ui)
|
||||
|
||||
Date: 2026-10-05
|
||||
Branches (local): RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands`
|
||||
Previous plugin version: 0.5.2-legacy-ui
|
||||
|
||||
## What's new
|
||||
|
||||
- The in-client **Inventory** panel's right-click menu has **Add to item count HUD** for any item
|
||||
that isn't a pack. It adds the item, by name, to RynthAi's floating item count HUD and shows the
|
||||
HUD. You no longer have to select the item in the game first and use the HUD setup window.
|
||||
- Typed equivalent: `/ra itemhud add <item name>`.
|
||||
- RynthAi confirms in chat: `Added <name> to the item count HUD.` or `<name> is already on the item
|
||||
count HUD.` The icon and WCID fill in on the HUD's next pack scan.
|
||||
|
||||
## How it works
|
||||
|
||||
- Engine `InventoryFace` sends the remote command `itemhudadd=<item name>` through
|
||||
`RynthAiCommands.ApplyRemoteCommand`.
|
||||
- RynthAi's `ApplyRemoteCommand` queues it to the pump thread and calls
|
||||
`HudController.AddToItemHudAndShow` (new). `/ra itemhud add` uses the same handler.
|
||||
- `/ra itemhud [show|hide|toggle]` is unchanged.
|
||||
63
Changelog/2026-10-05-mini-remote-is-ilt-hub.md
Normal file
63
Changelog/2026-10-05-mini-remote-is-ilt-hub.md
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
# Mini Remote is the ILT Hub (RynthAi 0.5.8-legacy-ui)
|
||||
|
||||
Date: 2026-10-05
|
||||
Branches: RynthCore `merge/aelrynth-2026.10.5.1`, RynthSuite `fix/rynthai-launcher-remote-commands`
|
||||
|
||||
## What changed
|
||||
|
||||
The tabbed **ILT Hub** window is retired. The **Mini Remote** is now the Hub, the same way
|
||||
UtilityBelt's ILT Mini Remote works.
|
||||
|
||||
### Mini Remote
|
||||
- New top row with two buttons:
|
||||
- **V/H** switches between stacked sections (vertical) and three side-by-side columns
|
||||
(horizontal). The columns are: status (stats, target, pet, Reset XP / Report), actions
|
||||
(item slots, toggles) and economy (bank, rebuff, translate). The choice is saved
|
||||
(`HudState.MiniRemoteHorizontal`).
|
||||
- **Options** opens the same menu as right-clicking the remote.
|
||||
- The Options menu has a new **ILT Hub** group at the top:
|
||||
- Character, Quests, Pets, Banking, Gear and Games each open or close their own window.
|
||||
An item is ticked while its window is open, and greyed out until the server reports the
|
||||
feature on.
|
||||
- A pointer to the Skills panel for Progression.
|
||||
- On non-ILT worlds: the world status, **Treat this world as ILT** and **Refresh server
|
||||
features**.
|
||||
- The Options menu also has a **Horizontal layout** checkbox (same as V/H).
|
||||
- The empty-bank hint now reads "Options > Banking".
|
||||
|
||||
### Hub section windows
|
||||
- Each former tab is its own window. Each one opens near the centre the first time and is
|
||||
moved back on screen if its saved position leaves it off-screen.
|
||||
- **ILT Character**: world / server-options header (Refresh, Force ILT, Profiles), session
|
||||
rates, and the Progression note. This window also explains why the Hub is idle on other
|
||||
worlds.
|
||||
- **Quests**: quest bonus and quest tracker. The old "Pop out" button is gone, because this
|
||||
window is now the tracker's only home.
|
||||
- **Pets**, **Banking**, **Gear**, **Games**.
|
||||
- Open/closed state is saved per character (`IltCharacterState.CharacterWindowOpen`,
|
||||
`BankingWindowOpen`, `GearWindowOpen`, `GamesWindowOpen`, plus the existing
|
||||
`PetsWindowOpen` and `QuestTrackerPoppedOut`).
|
||||
- The Games HUD, the quest favorites HUD and the confirmation dialog are unchanged.
|
||||
- Bank auto-refresh and the gear / split-arrow scans used to run only while the Hub window was
|
||||
open. They now run while the Mini Remote or any Hub section window is open.
|
||||
|
||||
### Commands
|
||||
- `/ra hub` and `/ra hub show|hide|toggle` now show, hide or toggle the Mini Remote.
|
||||
- New: `/ra hub open character|quests|pets|banking|gear|games [show|hide|toggle]`.
|
||||
Aliases: `char`, `rates`, `quest`, `pet`, `bank`, `game`.
|
||||
- `/ra pets` and `/ra quests window` still work. They are the same as `/ra hub open pets` and
|
||||
`/ra hub open quests`.
|
||||
|
||||
### Engine dashboard (RynthAiFace)
|
||||
- **Char** left-click opens the Mini Remote (the Hub).
|
||||
- **Char** right-click menu: Mini Remote (ILT Hub), then Character, Quests, Pets, Banking,
|
||||
Gear and Games (each toggles its window), then Progression (Skills panel).
|
||||
|
||||
## Not ported from UtilityBelt's Mini Remote
|
||||
- Storm and Reset Storm, the Guardian textbox, and the Fellow toggle.
|
||||
- The LumS, KillL, PassL and Conv rate lines (RynthAi doesn't track these yet).
|
||||
- Loot-profile and character-profile pickers on the remote.
|
||||
|
||||
## Versions
|
||||
- RynthAi plugin: 0.5.8-legacy-ui (previous 0.5.7-legacy-ui).
|
||||
- The next installer is 2026.10.5.8 (previous 2026.10.5.7).
|
||||
49
Changelog/2026-10-05-native-drag-real-item.md
Normal file
49
Changelog/2026-10-05-native-drag-real-item.md
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
# Mini Remote: dragging from the game inventory uses the item you dragged
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Components:** RynthCore.Engine (next installer 2026.10.5.11), RynthAi 0.5.12-legacy-ui (previous 0.5.11-legacy-ui)
|
||||
|
||||
## Problem
|
||||
|
||||
Dragging an item from AC's own inventory onto a Mini Remote slot assigned whatever item was
|
||||
selected before the drag, not the item being dragged. AC does not change the selected object
|
||||
when a drag starts, and the engine's drag bridge read the dragged item from the selection.
|
||||
|
||||
Log evidence (session pid 33152): three drags of different items all published
|
||||
`0x803AAE1B` (Frozen Valley Everlasting Portal Gem, the last clicked item), which landed in slot 17.
|
||||
|
||||
## Fix
|
||||
|
||||
- **New `Compatibility/DragDropHooks.cs`** hooks `UIElementManager::StartDragandDrop`
|
||||
(`0x0045E120`, thiscall). It resolves the dragged UI element to an object id with AC's own
|
||||
`UIElement_ItemList::InqDropIconInfo` (`0x004E3380`, cdecl). Same approach as Chorizite's UIHooks.
|
||||
- Both addresses are resolved by byte patterns that are unique in the shipped client. If either
|
||||
pattern misses, the hook is skipped (no hard-coded fallback) and the old behavior remains.
|
||||
- **`ItemDragBridge`**
|
||||
- `OnNativeDragStart(itemId)` takes the hooked item while a game-owned left press is held, for
|
||||
carried items only (pack, side pack or worn). Spell-bar drags are ignored.
|
||||
- Hooked drags are published as `RYNTH_INV_ITEM`, so they can go on **any** slot (and replace an
|
||||
assigned one), exactly like drags from the RynthCore Inventory.
|
||||
- The selection guess (`RYNTH_GAME_ITEM`, empty slots only) now runs only when the hook is not installed.
|
||||
- Released over an ImGui window, the drop is still handed back to AC at the drag's start, so the
|
||||
item never lands on the ground.
|
||||
- **RynthAi** — `MiniRemoteHud` comment updated to describe both payloads; version 0.5.12-legacy-ui.
|
||||
|
||||
## Verifying
|
||||
|
||||
The engine log shows, at startup:
|
||||
|
||||
- `HookResolver[DragDrop.InqDropIconInfo]: RESOLVED via pattern-unique @ 0x004E3380`
|
||||
- `HookResolver[DragDrop.StartDragandDrop]: RESOLVED via pattern-unique @ 0x0045E120`
|
||||
- `Compat: drag-start hook ready`
|
||||
|
||||
Then, on each AC inventory drag:
|
||||
|
||||
- `DragDropHooks: AC drag start item=0x........` (first 20 drags)
|
||||
- `ItemDragBridge: native inventory drag 0x........ published to ImGui.`
|
||||
|
||||
## Unchanged
|
||||
|
||||
- Click an item (game inventory or RynthCore Inventory), then click an empty Mini Remote slot.
|
||||
- RynthCore Inventory right-click **Add to Mini Remote**.
|
||||
- Drag from the RynthCore Inventory or a popped-out Inventory.
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
# Nav panel: Breadcrumbs and Route overlay toggles (RynthAi 0.5.9-legacy-ui)
|
||||
|
||||
Date: 2026-10-05
|
||||
Branches: RynthCore `merge/aelrynth-2026.10.5.1`, RynthSuite `fix/rynthai-launcher-remote-commands`
|
||||
|
||||
## What changed
|
||||
|
||||
### Nav panel (engine, `NavFace`)
|
||||
A new row under Route / Insert has two checkbox-style toggles. A ticked box and teal text means
|
||||
on. Both are saved per character in RynthAi's settings.
|
||||
- **Breadcrumbs**: records the trail you walk and draws it on the ground. Turning it off stops
|
||||
recording and hides the trail. Turning it back on starts a new trail segment, so the trail
|
||||
never draws a line across the stretch you walked while it was off.
|
||||
- **Route overlay**: draws the route in the world: waypoint rings and connecting lines, waypoint
|
||||
labels, and the guide line to the active waypoint. The waypoint HUD window keeps its own
|
||||
switch (`/ra navhud`).
|
||||
|
||||
### RynthAi
|
||||
- `NavOverlaySettings.ShowRouteMarkers` now does something. It was saved but never read, so
|
||||
route rings always drew. `NavMarkerRenderer` now skips the rings and lines when it is off,
|
||||
and the waypoint labels and guide line follow it too.
|
||||
- `NavOverlaySettings.TrackBreadcrumbs` now also hides the drawn trail when off.
|
||||
- Nav bridge: the snapshot carries `TrackBreadcrumbs` and `ShowRouteOverlay`. New commands
|
||||
`setBreadcrumbs` and `setRouteOverlay` (with `On`) save the settings.
|
||||
- Chat commands:
|
||||
- `/ra navtrail on|off|toggle` (the existing `clear` and the status report still work; the
|
||||
report now says whether tracking is on).
|
||||
- New `/ra navoverlay [on|off]` (no argument toggles).
|
||||
|
||||
### Compatibility
|
||||
- An older RynthAi doesn't send the two flags, so both toggles show off; clicking them does
|
||||
nothing until RynthAi is updated.
|
||||
|
||||
## Versions
|
||||
- RynthAi plugin: 0.5.9-legacy-ui (previous 0.5.8-legacy-ui).
|
||||
- The next installer is 2026.10.5.9 (previous 2026.10.5.8).
|
||||
25
Changelog/2026-10-05-release-2026.10.5.10.md
Normal file
25
Changelog/2026-10-05-release-2026.10.5.10.md
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
# Release 2026.10.5.10
|
||||
|
||||
Date: 2026-10-05
|
||||
Previous release: 2026.10.5.9
|
||||
RynthAi plugin: 0.5.11-legacy-ui
|
||||
|
||||
## Installer
|
||||
|
||||
- File: `installer/Output/RynthCore-Setup-2026.10.5.10.exe` (130748020 bytes)
|
||||
- SHA256: `F63859E43033581B9BC90CB92663F2B2BD9233C6E24E5893775E3DCF1BB4FAAD`
|
||||
- Deploy zip: `installer/Output/RynthCore-2026.10.5.10-deploy.zip`
|
||||
|
||||
## Included changes
|
||||
|
||||
- ILT Guardian window, ported from UB-IT's Guardian tab: Temple / Attribute guardian riddle
|
||||
translator (chat auto-detect and paste box), hand-in to the guardian with an optional vendor
|
||||
buy for the Temple guardian, and the attribute turn-in tracker (/myquests, falling back to
|
||||
/qb wait stamps). The last answer also shows on the Mini Remote with a Give button.
|
||||
`/ra guardian ...`.
|
||||
- Mini Remote slots can now be filled by dragging from AC's own inventory (empty slots) or from
|
||||
a popped-out RynthCore Inventory. Clicking an item in the RynthCore Inventory selects it in the
|
||||
game, the remote remembers the last selected pack item for 2 minutes, and the Inventory's
|
||||
right-click menu has "Add to Mini Remote".
|
||||
|
||||
See `2026-10-05-guardian-and-remote-slots.md` for details and known limits.
|
||||
30
Changelog/2026-10-05-release-2026.10.5.11.md
Normal file
30
Changelog/2026-10-05-release-2026.10.5.11.md
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
# Release 2026.10.5.11
|
||||
|
||||
Date: 2026-10-05
|
||||
Previous release: 2026.10.5.10 (saved in `installer/previous-release/`)
|
||||
RynthAi plugin: 0.5.13-legacy-ui
|
||||
|
||||
## Installer
|
||||
|
||||
- File: `installer/Output/RynthCore-Setup-2026.10.5.11.exe` (130761857 bytes)
|
||||
- SHA256: `9BE7F21A15C0D175F5F00C252EEA7BF4CAADAF798676EA96B3673E47267C424E`
|
||||
- Deploy zip: `installer/Output/RynthCore-2026.10.5.11-deploy.zip`
|
||||
|
||||
## Included changes
|
||||
|
||||
- **Mini Remote: drags from AC's own inventory use the dragged item.** The engine hooks AC's
|
||||
drag start (`UIElementManager::StartDragandDrop`) instead of reading the selection, which AC
|
||||
leaves on the last clicked item. These drags can now go on any slot, including assigned ones.
|
||||
See `2026-10-05-native-drag-real-item.md`.
|
||||
- **ILT Guardian hand-in finds the vendor and the item.** Vendors are recognised by the weenie
|
||||
vendor flag (nothing was ever classed Vendor, so the nearby vendor was never found), and the
|
||||
hand-in item is looked up in a live walk of your packs (a fresh purchase was missed).
|
||||
See `2026-10-05-guardian-vendor-and-item-lookup.md`.
|
||||
|
||||
## What to check in game
|
||||
|
||||
- Engine log at startup: `Compat: drag-start hook ready`.
|
||||
- Drag an item from the game inventory onto a Mini Remote slot; the log shows
|
||||
`DragDropHooks: AC drag start item=0x...` with that item's id.
|
||||
- Temple guardian answer with the item not carried: the IltHub log shows
|
||||
`[IltGuardian] vendor for '<item>': <vendor>`, then the buy and the give.
|
||||
33
Changelog/2026-10-05-release-2026.10.5.2.md
Normal file
33
Changelog/2026-10-05-release-2026.10.5.2.md
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
# Release 2026.10.5.2: first build on the aelrynth 2026.10.5.1 merge
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Installer:** `RynthCore-Setup-2026.10.5.2.exe` (previous release: 2026.10.4.22)
|
||||
**Sources:** RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `merge/aelrynth-2026.10.5.1` (532fa67)
|
||||
|
||||
## Summary
|
||||
|
||||
The first installer built from the merge of upstream aelrynth 2026.10.5.1 with SK-local.
|
||||
The version sorts above upstream's 2026.10.5.1, so the launcher's updater sees it as newer.
|
||||
This is a test build of the merge: it has not been tested in game yet.
|
||||
|
||||
## What's in it
|
||||
|
||||
- **Engine:** upstream's unloadable CoreCLR engine, hosted by the native loader, with an
|
||||
app-local .NET 10 runtime in `Runtime\dotnet`. This is the installer's new default;
|
||||
the previous NativeAOT engine is still available via `Build-Installer.ps1 -NativeAot`.
|
||||
- **Plugin API v77:** the RynthAi in this installer is built against it. Do not use an
|
||||
older SK-local RynthAi (0.6.32 or earlier) with this engine. It reads the
|
||||
merge-stack-result entry from a slot that upstream now uses for something else.
|
||||
- **RynthAi:** the upstream plugin with the SK-local features wired on (ILT Hub, HUDs,
|
||||
translation, item info, ground loot, nav overlay). It reports `0.5.1-legacy-ui`.
|
||||
- **Upstream features and SK-local ports:** see
|
||||
`2026-10-05-aelrynth-2026.10.5.1-merge.md` for the full list.
|
||||
- **Decal bridge:** not included in this build (Decal 3.0 is not installed on the build
|
||||
machine). "Decal + RynthCore" accounts can't run from this installer.
|
||||
|
||||
## Known gaps
|
||||
|
||||
- Several new upstream paths are hard-coded to `C:\Games\...`. Installs in other folders
|
||||
may log or save to the wrong place.
|
||||
- The ImGui Items view has no Shields section yet; the Avalonia Items panel has one.
|
||||
- RynthAi's 0.6.33 augmentation clamp fix is still stashed on SK-local and is not in this build.
|
||||
30
Changelog/2026-10-05-release-2026.10.5.3.md
Normal file
30
Changelog/2026-10-05-release-2026.10.5.3.md
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
# Release 2026.10.5.3: ILT Hub windows, Char/Hub buttons, logging warning
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Installer:** `RynthCore-Setup-2026.10.5.3.exe` (previous release: 2026.10.5.2)
|
||||
**Sources:** RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `merge/aelrynth-2026.10.5.1` (532fa67, unchanged)
|
||||
|
||||
## Summary
|
||||
|
||||
A second test build of the aelrynth 2026.10.5.1 merge, fixing what 2026.10.5.2 got wrong in game.
|
||||
Details: `2026-10-05-ilt-hub-context-char-hub-logging.md`.
|
||||
|
||||
## Fixes
|
||||
|
||||
- **ILT Hub and RynthAi's other ImGui windows** (Mini Remote, Inventory HUDs, Item Info,
|
||||
translator, nav overlay) draw again. Plugins now get the engine's ImGui context when plugin
|
||||
overlay windows are enabled. **UbRythai** starts again too; it refuses to start without that context.
|
||||
- **Char and Hub buttons** are back on the in-game RynthAi dashboard (the ImGui one):
|
||||
- Char opens the ILT Hub.
|
||||
- Hub: left-click toggles the Mini Remote; right-click opens the Inventory HUDs setup.
|
||||
- **Logging:**
|
||||
- The engine's startup banner is always written.
|
||||
- A warning names any log category set above the global LoggingLevel; those categories
|
||||
are not logged at all.
|
||||
|
||||
## Still open
|
||||
|
||||
- No Decal bridge in this build (Decal 3.0 is not installed on the build machine).
|
||||
- Several new upstream paths are hard-coded to `C:\Games\...`.
|
||||
- The ImGui Items view has no Shields section yet.
|
||||
- RynthAi's 0.6.33 augmentation clamp fix is still stashed on SK-local.
|
||||
29
Changelog/2026-10-05-release-2026.10.5.4.md
Normal file
29
Changelog/2026-10-05-release-2026.10.5.4.md
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
# Release 2026.10.5.4: Char/Hub buttons open their windows
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Installer:** `RynthCore-Setup-2026.10.5.4.exe` (previous release: 2026.10.5.3)
|
||||
**SHA-256:** `0546B00D544DF8C97899C62F47FB96EF4655CD0E9662A9E43CE43C962E98F494`
|
||||
**Sources:** RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands` (8a25c5f, on top of 532fa67)
|
||||
**Engine:** CoreCLR (app-local runtime)
|
||||
|
||||
## Summary
|
||||
|
||||
A third test build of the aelrynth 2026.10.5.1 merge. Details:
|
||||
`2026-10-05-rynthai-launcher-remote-commands.md`.
|
||||
|
||||
## Fixes
|
||||
|
||||
- **Char / Hub dashboard buttons** open their windows. 2026.10.5.3 showed the buttons, but RynthAi
|
||||
threw away the commands they send. The aelrynth merge had dropped `hub` / `huds` / `remote` from
|
||||
RynthAi's remote-command switch.
|
||||
- Char opens the ILT Hub (`/ra hub show`).
|
||||
- Hub: left-click toggles the Mini Remote (`/ra remote toggle`); right-click opens Inventory HUDs (`/ra huds show`).
|
||||
- RynthAi logs an unknown remote command as `ignored`, not `applied`.
|
||||
- RynthAi plugin version is 0.5.2-legacy-ui (previous: 0.5.1-legacy-ui).
|
||||
|
||||
## Still open
|
||||
|
||||
- No Decal bridge in this build (Decal 3.0 is not installed on the build machine).
|
||||
- Several new upstream paths are hard-coded to `C:\Games\...`.
|
||||
- The ImGui Items view has no Shields section yet.
|
||||
- RynthAi's 0.6.33 augmentation clamp fix is still stashed on SK-local.
|
||||
39
Changelog/2026-10-05-release-2026.10.5.5.md
Normal file
39
Changelog/2026-10-05-release-2026.10.5.5.md
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
# Release 2026.10.5.5: ImGui draws over Avalonia, Char panel rework, inventory to item count HUD
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Installer:** `RynthCore-Setup-2026.10.5.5.exe` (previous release: 2026.10.5.4)
|
||||
**SHA-256:** `5343A879A06C308094E840C49E14B2F86A4D5E8111E9FE150FE06B7ED4CD09C5`
|
||||
**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (69cfe75); RynthSuite `fix/rynthai-launcher-remote-commands` (52f8f95)
|
||||
**Engine:** CoreCLR (app-local runtime)
|
||||
**RynthAi:** 0.5.4-legacy-ui
|
||||
|
||||
## Summary
|
||||
|
||||
The fourth test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game.
|
||||
|
||||
## Fixes
|
||||
|
||||
- **ImGui windows draw on top of Avalonia panels.** The ImGui frame is still built in
|
||||
`EndScene`, but its draw data is now submitted after `OverlayTextureRenderer.Render`. Before
|
||||
this, the ILT Hub and other ImGui windows could be hidden behind a docked Avalonia panel. Mouse
|
||||
priority over ImGui windows (`Win32Backend.ImGuiOwnsMouseOverAvalonia`) survived the merge
|
||||
unchanged. Details: `2026-10-05-imgui-over-avalonia-port.md`.
|
||||
|
||||
## Features
|
||||
|
||||
- **Inventory panel > right-click > "Add to item count HUD"** adds the item (by name) to the
|
||||
floating item count HUD and shows it. Typed equivalent: `/ra itemhud add <name>`. Details:
|
||||
`2026-10-05-inventory-add-to-item-count-hud.md`.
|
||||
- **Char panel rework**. Details: `2026-10-05-char-panel-rework-progression-pets-quests.md`.
|
||||
- The Skills panel has a Progression tab (ILT worlds) with:
|
||||
- an exact XP planner;
|
||||
- the Augmentation and Enlightenment planners.
|
||||
- Pets has its own window (`/ra pets`). The Quests window (`/ra quests window`) now includes
|
||||
Quest bonus.
|
||||
- ILT Hub tabs: Character (Session rates), Quests, Pet, Banking, Gear, Games.
|
||||
- Char launcher right-click menu: ILT Hub, Pets window, Quests window, Progression.
|
||||
|
||||
## Build notes
|
||||
|
||||
- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge;
|
||||
and CS0618 in `EntryPoint.cs`.
|
||||
29
Changelog/2026-10-05-release-2026.10.5.6.md
Normal file
29
Changelog/2026-10-05-release-2026.10.5.6.md
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
# Release 2026.10.5.6: Floating windows open where they can be seen
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Installer:** `RynthCore-Setup-2026.10.5.6.exe` (previous release: 2026.10.5.5)
|
||||
**SHA-256:** `B4F4410EBC67AAD91CE8FCEAD402CAA046446A3C28501921A350B1E3CCDA77FE`
|
||||
**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (3f06ed3); RynthSuite `fix/rynthai-launcher-remote-commands` (871c5d9)
|
||||
**Engine:** CoreCLR (app-local runtime)
|
||||
**RynthAi:** 0.5.5-legacy-ui
|
||||
|
||||
## Summary
|
||||
|
||||
The fifth test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game.
|
||||
Details: `2026-10-05-floating-window-placement.md`.
|
||||
|
||||
## Fixes
|
||||
|
||||
- **Plugin windows open near the middle the first time.** This covers Pets, the popped-out Quests
|
||||
window, the Item HUD, the Mini Remote and the ILT Hub. Before, they opened in the top-left corner,
|
||||
hidden under popped-out panels.
|
||||
- **Off-screen check.** Each time one of those windows is shown, it moves to the middle if less than
|
||||
40 px of it is on screen. The ILT Hub's rescue now uses the middle instead of (40,40).
|
||||
- **Dungeon Map** opens centred when nothing is saved for it.
|
||||
- **Engine panels open clear of popped-out windows.** A docked panel that would be more than half
|
||||
hidden opens at the nearest clearer spot. The move is saved and logged by `ImGuiPanelHost`.
|
||||
|
||||
## Build notes
|
||||
|
||||
- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge;
|
||||
and CS0618 in `EntryPoint.cs`.
|
||||
29
Changelog/2026-10-05-release-2026.10.5.7.md
Normal file
29
Changelog/2026-10-05-release-2026.10.5.7.md
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
# Release 2026.10.5.7: RynthAi windows appear again
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Installer:** `RynthCore-Setup-2026.10.5.7.exe` (previous release: 2026.10.5.6)
|
||||
**SHA-256:** `14CD10DAC7F7245528C7BE94A35395A21FA6EDD5679B5EA3A51FA23EB28D4BED`
|
||||
**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (b63b9fe); RynthSuite `fix/rynthai-launcher-remote-commands` (3ddd7ea)
|
||||
**Engine:** CoreCLR (app-local runtime)
|
||||
**RynthAi:** 0.5.7-legacy-ui
|
||||
|
||||
## Summary
|
||||
|
||||
The sixth test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game.
|
||||
Details: `2026-10-05-rynthai-cimgui-binding.md`.
|
||||
|
||||
## Fixes
|
||||
|
||||
- **RynthAi's own windows draw again.** This covers the Mini Remote, Pets, Quests, ILT Hub, Item HUD
|
||||
and Inventory HUDs.
|
||||
- Cause: since the merge, the engine loads `RynthCore.cimgui.dll`, so RynthAi's ImGui calls went to
|
||||
a second `cimgui.dll` that the engine never draws.
|
||||
- Fix: RynthAi now binds to the engine's module, as ub-Rythai does. The RynthAi UI log should show
|
||||
`[ImGui] cimgui bound to loaded RynthCore.cimgui.dll`.
|
||||
- **Two clients no longer overwrite each other's RynthAi logs.** The second client writes
|
||||
`{name}.{pid}.txt` beside the first client's file.
|
||||
|
||||
## Build notes
|
||||
|
||||
- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge;
|
||||
and CS0618 in `EntryPoint.cs`.
|
||||
35
Changelog/2026-10-05-release-2026.10.5.8.md
Normal file
35
Changelog/2026-10-05-release-2026.10.5.8.md
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
# Release 2026.10.5.8: the Mini Remote is the ILT Hub
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Installer:** `RynthCore-Setup-2026.10.5.8.exe` (previous release: 2026.10.5.7)
|
||||
**SHA-256:** `DBB04B9A5FF1B8DC986B4C50421E42814F64DF072BFB805634ECE0F2BBD5A784`
|
||||
**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (9408852); RynthSuite `fix/rynthai-launcher-remote-commands` (4d700e3)
|
||||
**Engine:** CoreCLR (app-local runtime)
|
||||
**RynthAi:** 0.5.8-legacy-ui
|
||||
|
||||
## Summary
|
||||
|
||||
The seventh test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game.
|
||||
Details: `2026-10-05-mini-remote-is-ilt-hub.md`.
|
||||
|
||||
## Changes
|
||||
|
||||
- **The tabbed ILT Hub window is gone; the Mini Remote is the Hub** (UtilityBelt style).
|
||||
- The new **V/H** button switches between stacked sections and three columns.
|
||||
- The new **Options** button (or right-click) opens the Hub's windows: Character, Quests, Pets,
|
||||
Banking, Gear and Games. Each is its own window.
|
||||
- `/ra hub` and the dashboard's **Char** button now open the Mini Remote.
|
||||
- New command: `/ra hub open <section>`.
|
||||
- Char's right-click menu lists the section windows.
|
||||
- Bank auto-refresh and the gear scans now run while the Mini Remote or any Hub window is open.
|
||||
|
||||
## Not yet ported from UtilityBelt's Mini Remote
|
||||
|
||||
- Storm and Reset Storm, the Guardian textbox, and the Fellow toggle.
|
||||
- The LumS, KillL, PassL and Conv rate lines.
|
||||
- The loot-profile and character-profile pickers.
|
||||
|
||||
## Build notes
|
||||
|
||||
- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge;
|
||||
CS0618 in `EntryPoint.cs`; and the existing nullable warnings.
|
||||
21
Changelog/2026-10-05-release-2026.10.5.9.md
Normal file
21
Changelog/2026-10-05-release-2026.10.5.9.md
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
# Release 2026.10.5.9
|
||||
|
||||
Date: 2026-10-05
|
||||
Previous release: 2026.10.5.8
|
||||
RynthAi plugin: 0.5.10-legacy-ui
|
||||
|
||||
## Installer
|
||||
|
||||
- File: `installer/Output/RynthCore-Setup-2026.10.5.9.exe` (130756527 bytes)
|
||||
- SHA256: `E59D61BF61DE7089D56731F40273661FEF9DF1CEA548759C333DF1077CE138E9`
|
||||
- Deploy zip: `installer/Output/RynthCore-2026.10.5.9-deploy.zip`
|
||||
|
||||
## Included changes
|
||||
|
||||
- Settings > Charms Tracking tab: every ACECustom registry charm with acquired (Carried / Stored /
|
||||
Not yet), ON/OFF status, tier and server state. See `2026-10-05-charms-tracking-tab.md`.
|
||||
The charm list was checked against ACECustom: all 13 charms, including the Infinite Casting Stone
|
||||
and Universal Summoning Mastery, are present with every tier WCID.
|
||||
- Nav: Breadcrumbs on/off and Route overlay on/off toggles (Nav panel, `/ra navtrail on|off`,
|
||||
`/ra navoverlay on|off`). See `2026-10-05-nav-breadcrumbs-route-overlay-toggles.md`.
|
||||
- Pets: an Infinite Casting Stone switched OFF no longer counts as casting supplies.
|
||||
52
Changelog/2026-10-05-rynthai-cimgui-binding.md
Normal file
52
Changelog/2026-10-05-rynthai-cimgui-binding.md
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
# RynthAi overlay windows draw again: bind to the engine's cimgui (RynthAi 0.5.6-legacy-ui)
|
||||
|
||||
Date: 2026-10-05
|
||||
Branches (local): RynthSuite `fix/rynthai-launcher-remote-commands`
|
||||
Previous plugin version: 0.5.5-legacy-ui
|
||||
|
||||
## Problem
|
||||
|
||||
Since the aelrynth merge, none of RynthAi's own ImGui windows appear. That covers the ILT Hub, the
|
||||
Pets and Quests windows, the Mini Remote, the Item HUD and the Inventory HUDs setup. The launcher
|
||||
buttons and `/ra` commands reach the plugin (`applied remote command: remote=toggle` /
|
||||
`pets=toggle`), but nothing shows.
|
||||
|
||||
## Cause
|
||||
|
||||
The engine now loads its ImGui build as `RynthCore.cimgui.dll` (log: `ImGuiNative: Loading
|
||||
...\Runtime\RynthCore.cimgui.dll`).
|
||||
|
||||
RynthAi is NativeAOT. Its ImGui.NET P/Invokes ask for `cimgui`, which no loaded module is named.
|
||||
Windows therefore loaded a second, different `cimgui.dll` from the install's `Runtime` folder. RynthAi
|
||||
set that module's context pointer to the engine's context and built its windows through a separate
|
||||
ImGui instance, so they never reached the engine's draw data. The engine heartbeat shows this: the
|
||||
plugin's overlay call runs every frame (`overlayCalls` = frames), but `drawLists=3` doesn't change
|
||||
after `/ra hub show` or `/ra remote toggle`.
|
||||
|
||||
ub-Rythai already avoids this with a DllImport resolver bound to the engine's module (log:
|
||||
`ub-Rythai: ImGui native resolver bound to engine cimgui.`). RynthAi had no such resolver.
|
||||
|
||||
## Fix
|
||||
|
||||
- New `ImGuiNativeBinding`, called at the top of `RynthAiPlugin.Initialize` before any ImGui call. It
|
||||
registers `NativeLibrary.SetDllImportResolver` for the ImGui.NET assembly.
|
||||
- `cimgui` resolves to the loaded `RynthCore.cimgui.dll`, else a loaded `cimgui.dll`, else the
|
||||
default search (the old behaviour).
|
||||
- It's registered once per process, so a reused plugin DLL copy doesn't throw.
|
||||
- Logged in the UI log as `[ImGui] native resolver registered ...` and, on the first ImGui call,
|
||||
`[ImGui] cimgui bound to loaded RynthCore.cimgui.dll (0x...)`.
|
||||
- No changes to the windows themselves. The Mini Remote looks as it did before the merge: stats,
|
||||
ResetXP / Report, item buttons, toggles, profile pickers, Guardian, Translate, Chat XL and Rebuff.
|
||||
|
||||
## Two clients no longer overwrite each other's RynthAi logs (RynthAi 0.5.7-legacy-ui)
|
||||
|
||||
- Before: with two clients running, RynthAi's shared log files (`Logs\Diagnostics\rynthai_*.txt`,
|
||||
`exceptions_*.txt`, `Trace\*.txt`) lost and garbled lines. Each process opened the file in Append
|
||||
mode once with `FileShare.ReadWrite`, kept a buffered writer, and wrote at its own end-of-file
|
||||
offset, overwriting the other client's lines.
|
||||
- Now each file has one writing process. `RynthLog.OpenWriter` opens it with `FileShare.Read`, so
|
||||
readers are fine but a second writer is refused. When another client already holds the file, this
|
||||
process writes `{name}.{pid}.txt` beside it, e.g. `rynthai_2026-10-05.30060.txt`. The engine's own
|
||||
logs (`RynthCore.{pid}.log`) are per process the same way.
|
||||
- Retention and pruning are unchanged. The per-process files are `*.txt` in the same folders, so
|
||||
they age out with the rest.
|
||||
44
Changelog/2026-10-05-rynthai-launcher-remote-commands.md
Normal file
44
Changelog/2026-10-05-rynthai-launcher-remote-commands.md
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
# RynthAi 0.5.2-legacy-ui: Char / Hub launchers open their windows again
|
||||
|
||||
Date: 2026-10-05
|
||||
Branch: RynthSuite `fix/rynthai-launcher-remote-commands` (local, based on `merge/aelrynth-2026.10.5.1` @ 532fa67)
|
||||
Previous plugin version: 0.5.1-legacy-ui
|
||||
|
||||
## Problem
|
||||
|
||||
On 2026.10.5.3 the dashboard's **Char** and **Hub** launcher buttons showed, but clicking them did
|
||||
nothing: no ILT Hub, no Mini Remote, no Inventory HUDs window.
|
||||
|
||||
The engine log showed every click arriving at RynthAi
|
||||
(`[RynthAi] applied remote command: hub=show`, `remote=toggle`, `huds=show`), and the overlay was
|
||||
drawing (`OnRenderOverlay drawing (iltHub=ready)`). The ILT Hub diagnostics had no
|
||||
`command: /ra hub ...` line for any click.
|
||||
|
||||
## Cause
|
||||
|
||||
The launchers send remote commands through the engine broker into `RynthAiPlugin.ApplyRemoteCommand`.
|
||||
The aelrynth 2026.10.5.1 version of that switch has no `hub` / `quests` / `huds` / `itemhud` /
|
||||
`remote` / `miniremote` cases. SK-local had them, and the merge dropped them. The commands fell
|
||||
through the switch untouched, and the trailing log line still reported them as "applied".
|
||||
|
||||
Typed `/ra hub ...` commands use a separate dispatcher (`DispatchRaCommand`) that still had the cases.
|
||||
That is why `/ra hub status`, `force on` and `refresh` worked, but no button did.
|
||||
|
||||
## Fix
|
||||
|
||||
- `ApplyRemoteCommand` routes `hub` / `quests` to `IltHubController.HandleCommand`, and routes
|
||||
`huds` / `itemhud` / `remote` / `miniremote` to `HandleHudCommand`. These are the same handlers as
|
||||
the typed commands, and both run on the pump thread.
|
||||
- Unknown remote commands log `ignored unknown remote command: ...` instead of falsely logging
|
||||
"applied".
|
||||
- `map` / `lua` were not restored. Upstream's engine owns those windows now.
|
||||
|
||||
## Typed equivalents
|
||||
|
||||
- `/ra hub show`: ILT Hub (the Char button)
|
||||
- `/ra remote toggle`: Mini Remote (Hub button, left-click)
|
||||
- `/ra huds show`: Inventory HUDs setup (Hub button, right-click)
|
||||
|
||||
## Not yet shipped
|
||||
|
||||
Built locally; not in an installer yet (next would be 2026.10.5.4). Nothing pushed.
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
RynthCore is a modern .NET 10 modding host for Asheron's Call. It combines an x86 NativeAOT in-process engine, a hot-reload-capable loader, an injector, an Avalonia desktop launcher, and a plugin surface that replaces the legacy Decal + UBService + VTank stack with a self-contained RynthCore-native API.
|
||||
|
||||
The plugin code (RynthAi etc.) lives in a sibling repository: [RynthSuite](https://aelrynth.com/rynth.html) (`git clone https://aelrynth.com/git/RynthSuite.git`).
|
||||
The plugin code (RynthAi etc.) lives in a sibling repository: [RynthSuite](https://aelrynth.com/git/rynth/RynthSuite).
|
||||
|
||||
## What it does
|
||||
|
||||
|
|
@ -86,7 +86,7 @@ For full deploy details, the Inno Setup installer, and gotchas, see [`BUILD.md`]
|
|||
## Repository notes
|
||||
|
||||
- Local settings, machine-specific files, generated `bin/`, `obj/`, `.vs/`, `.dotnet-home/` content, and launcher data (profiles, runtime state) are kept out of source control via `.gitignore`
|
||||
- Plugin code lives in the [RynthSuite](https://aelrynth.com/rynth.html) repo as a sibling clone (`git clone https://aelrynth.com/git/RynthSuite.git`)
|
||||
- Plugin code lives in the [RynthSuite](https://aelrynth.com/git/rynth/RynthSuite) repo as a sibling clone
|
||||
|
||||
## Security and secrets
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.31903.59
|
||||
|
|
@ -29,6 +29,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.Core
|
|||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.UI", "tools\HookResolver.UI\RynthCore.HookResolver.UI.csproj", "{C1A2B3D4-0009-0009-0009-000000000009}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.DecalBridge", "src\RynthCore.DecalBridge\RynthCore.DecalBridge.csproj", "{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|x86 = Debug|x86
|
||||
|
|
@ -135,6 +137,18 @@ Global
|
|||
{C1A2B3D4-0007-0007-0007-000000000007}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
|
|
@ -159,18 +173,18 @@ Global
|
|||
{C1A2B3D4-0009-0009-0009-000000000009}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.Build.0 = Release|Any CPU
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x86.ActiveCfg = Debug|x86
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x86.Build.0 = Debug|x86
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x86.ActiveCfg = Release|x86
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x86.Build.0 = Release|x86
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x64.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
|
@ -183,5 +197,6 @@ Global
|
|||
{C1A2B3D4-0007-0007-0007-000000000007} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{C1A2B3D4-0008-0008-0008-000000000008} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}
|
||||
{C1A2B3D4-0009-0009-0009-000000000009} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}
|
||||
{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
|
|
|||
34
THIRD-PARTY-NOTICES.md
Normal file
34
THIRD-PARTY-NOTICES.md
Normal 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.
|
||||
```
|
||||
|
|
@ -7,16 +7,20 @@
|
|||
.DESCRIPTION
|
||||
0. Makes sure a .NET 10 SDK is available; installs one per-user when missing (see -NoDotNetInstall)
|
||||
1. Publishes the Avalonia launcher (self-contained, x86)
|
||||
2. Publishes RynthCore.Engine (NativeAOT, x86 -- ~2 min)
|
||||
3. Publishes RynthCore.Loader (NativeAOT, x86) -- the DLL the launcher injects
|
||||
2+3. The engine and the loader (the DLL the launcher injects). By default the unloadable
|
||||
engine (docs/UNLOADABLE_ENGINE_PLAN.md): scripts\Publish-EngineCoreClr.ps1 stages the
|
||||
native loader (native\Loader), RynthCore.Shim, the CoreCLR engine (ReadyToRun) and the
|
||||
app-local .NET runtime (Runtime\dotnet) into staging\core\Runtime; needs Visual Studio's
|
||||
C++ tools. -NativeAot publishes the NativeAOT engine + loader instead (~2 min).
|
||||
4. Publishes RynthCore.Plugin.RynthAi (NativeAOT, x86) from RynthSuite
|
||||
5. Publishes the Loot Editor (self-contained, x86)
|
||||
6. Publishes the Monster Editor (self-contained, x86) from RynthSuite
|
||||
7. Publishes the experimental plugins (RynthChat, RynthJuice, RynthNav, RynthTracker,
|
||||
RynthVision, UbRythai; NativeAOT, x86) -- optional components in the installer
|
||||
8. Stages RynthCore under installer\staging\core\ and RynthSuite under
|
||||
installer\staging\suite\, plus the hand-built RynthCore.SehTrampoline.dll,
|
||||
and checks every required runtime file is there
|
||||
installer\staging\suite\, plus the hand-built RynthCore.SehTrampoline.dll and the
|
||||
Decal bridge (staging\core\DecalBridge, built against Decal's reference assemblies when
|
||||
Decal is installed), and checks every required runtime file is there
|
||||
9. Archives the previous installer (installer\previous-release\) when -Version changes
|
||||
10. Invokes ISCC.exe to produce installer\Output\RynthCore-Setup-<version>.exe
|
||||
(and a RynthCore-Setup.exe copy)
|
||||
|
|
@ -59,6 +63,18 @@
|
|||
.PARAMETER NoPackage
|
||||
With -Version, stop after the installer .exe (skip the Release-<version> package and zip).
|
||||
|
||||
.PARAMETER NativeAot
|
||||
Build the NativeAOT engine + loader instead of the default unloadable CoreCLR engine.
|
||||
|
||||
.PARAMETER SkipDecalBridge
|
||||
Leave the Decal bridge out even when Decal is installed.
|
||||
|
||||
.PARAMETER IncludeDecalBridge
|
||||
Require the Decal bridge: a missing Decal install fails the build instead of skipping it.
|
||||
|
||||
.PARAMETER DecalDir
|
||||
Decal's install folder, when not the default C:\Program Files (x86)\Decal 3.0.
|
||||
|
||||
.EXAMPLE
|
||||
.\Build-Installer.ps1 -Version 2026.10.4.7
|
||||
#>
|
||||
|
|
@ -74,7 +90,19 @@ param(
|
|||
[switch]$SkipBuild,
|
||||
[switch]$NoDotNetInstall,
|
||||
[switch]$AllowDirty,
|
||||
[switch]$NoPackage
|
||||
[switch]$NoPackage,
|
||||
# The old NativeAOT engine + loader (a hot reload leaks every engine generation).
|
||||
[switch]$NativeAot,
|
||||
# The Decal bridge (src\RynthCore.DecalBridge, docs/DECAL_BRIDGE_PLAN.md) is staged into
|
||||
# {app}\DecalBridge when Decal is installed (experimental, opt-in per account; nothing
|
||||
# registers it unless the player picks "Decal + RynthCore"). Building it needs Decal's
|
||||
# public reference assemblies; without Decal it is skipped with a warning.
|
||||
# -SkipDecalBridge leaves it out even when Decal is present.
|
||||
[switch]$SkipDecalBridge,
|
||||
# Makes the bridge mandatory: no Decal means a failed build rather than a skipped bridge.
|
||||
[switch]$IncludeDecalBridge,
|
||||
# Decal's install folder, when not the default C:\Program Files (x86)\Decal 3.0.
|
||||
[string]$DecalDir = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
|
@ -225,7 +253,9 @@ $CoreStaging = "$StagingRoot\core"
|
|||
$SuiteStaging = "$StagingRoot\suite"
|
||||
|
||||
# ── Validate projects ───────────────────────────────────────────────────────
|
||||
$allProjects = @($LauncherProject, $EngineProject, $LoaderProject, $PluginProject, $LootEditorProject, $MonsterEditorProject) +
|
||||
# The managed loader project is only built for -NativeAot; the default uses the native C loader.
|
||||
$allProjects = @($LauncherProject, $EngineProject, $PluginProject, $LootEditorProject, $MonsterEditorProject) +
|
||||
@(if ($NativeAot) { $LoaderProject }) +
|
||||
@($ExperimentalPlugins | ForEach-Object { Get-ExperimentalProject $_ })
|
||||
foreach ($p in $allProjects) {
|
||||
if (-not (Test-Path $p)) {
|
||||
|
|
@ -240,17 +270,20 @@ if (-not $SkipBuild) {
|
|||
dotnet publish $LauncherProject -c $Configuration -r win-x86 --self-contained true @VersionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Launcher publish failed (exit $LASTEXITCODE)" }
|
||||
|
||||
# ── 2. Engine (NativeAOT — the slow one) ──────────────────────────────────
|
||||
Write-Host ""
|
||||
Write-Host "[2/7] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan
|
||||
dotnet publish $EngineProject -c $Configuration @VersionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Engine publish failed (exit $LASTEXITCODE)" }
|
||||
if ($NativeAot) {
|
||||
# ── 2. Engine (NativeAOT — the slow one) ──────────────────────────────
|
||||
Write-Host ""
|
||||
Write-Host "[2/7] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan
|
||||
dotnet publish $EngineProject -c $Configuration @VersionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Engine publish failed (exit $LASTEXITCODE)" }
|
||||
|
||||
# ── 3. Loader (NativeAOT, small) ──────────────────────────────────────────
|
||||
Write-Host ""
|
||||
Write-Host "[3/7] Publishing Loader (NativeAOT)..." -ForegroundColor Cyan
|
||||
dotnet publish $LoaderProject -c $Configuration @VersionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Loader publish failed (exit $LASTEXITCODE)" }
|
||||
# ── 3. Loader (NativeAOT, small) ──────────────────────────────────────
|
||||
Write-Host ""
|
||||
Write-Host "[3/7] Publishing Loader (NativeAOT)..." -ForegroundColor Cyan
|
||||
dotnet publish $LoaderProject -c $Configuration @VersionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Loader publish failed (exit $LASTEXITCODE)" }
|
||||
}
|
||||
# (Default: the CoreCLR engine and native loader are built straight into staging below.)
|
||||
|
||||
# ── 4. RynthAi plugin (NativeAOT; keeps its own version) ─────────────────
|
||||
Write-Host ""
|
||||
|
|
@ -315,18 +348,30 @@ foreach ($file in (Get-ChildItem "$LauncherPublish" -File)) {
|
|||
Copy-Item $file.FullName "$CoreStaging\$destName" -Force
|
||||
}
|
||||
|
||||
# Engine runtime files (into Runtime\, skip .pdb)
|
||||
foreach ($file in (Get-ChildItem "$EnginePublish" -File)) {
|
||||
if ($file.Extension -eq '.pdb') { continue }
|
||||
Copy-Item $file.FullName "$CoreStaging\Runtime\$($file.Name)" -Force
|
||||
}
|
||||
if ($NativeAot) {
|
||||
# Engine runtime files (into Runtime\, skip .pdb)
|
||||
foreach ($file in (Get-ChildItem "$EnginePublish" -File)) {
|
||||
if ($file.Extension -eq '.pdb') { continue }
|
||||
Copy-Item $file.FullName "$CoreStaging\Runtime\$($file.Name)" -Force
|
||||
}
|
||||
|
||||
# Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it
|
||||
# maps RynthCore.Engine.dll and provides hot-reload. Without it a fresh install's
|
||||
# launcher can't auto-find an engine to inject.
|
||||
$loaderDll = "$LoaderPublish\RynthCore.Loader.dll"
|
||||
if (-not (Test-Path $loaderDll)) { throw "Loader DLL not found at: $loaderDll" }
|
||||
Copy-Item $loaderDll "$CoreStaging\Runtime\" -Force
|
||||
# Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it
|
||||
# maps RynthCore.Engine.dll and provides hot-reload. Without it a fresh install's
|
||||
# launcher can't auto-find an engine to inject.
|
||||
$loaderDll = "$LoaderPublish\RynthCore.Loader.dll"
|
||||
if (-not (Test-Path $loaderDll)) { throw "Loader DLL not found at: $loaderDll" }
|
||||
Copy-Item $loaderDll "$CoreStaging\Runtime\" -Force
|
||||
} else {
|
||||
# The unloadable engine: native loader (same RynthCoreInit contract with the launcher's
|
||||
# injector), RynthCore.Shim, the CoreCLR engine (ReadyToRun) + its dependencies, and
|
||||
# Runtime\dotnet (the app-local x86 .NET runtime). Needs Visual Studio's C++ tools (cl.exe)
|
||||
# for the loader, like the SEH trampoline.
|
||||
Write-Host ""
|
||||
Write-Host "[2+3/7] Building the unloadable engine + native loader into staging..." -ForegroundColor Cyan
|
||||
& "$RepoRoot\scripts\Publish-EngineCoreClr.ps1" -Target "$CoreStaging\Runtime" -Configuration $Configuration -MsBuildArgs $VersionArgs
|
||||
# Keep the engine's pdb (its stack traces get line numbers); drop the loader's and shim's.
|
||||
Remove-Item "$CoreStaging\Runtime\RynthCore.Loader.pdb", "$CoreStaging\Runtime\RynthCore.Shim.pdb" -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
# SEH trampoline — hand-built native DLL (native\SehTrampoline\Build-SehTrampoline.ps1),
|
||||
# NOT part of the engine publish output. Without it SehTrampoline.IsAvailable stays
|
||||
|
|
@ -353,8 +398,8 @@ if ((Test-Path $sehSrc) -and (Get-SehSourceTime) -gt (Get-Item $sehDll).LastWrit
|
|||
}
|
||||
Copy-Item $sehDll "$CoreStaging\Runtime\" -Force
|
||||
|
||||
# Engine Native subfolder
|
||||
if (Test-Path "$EnginePublish\Native") {
|
||||
# Engine Native subfolder (NativeAOT layout)
|
||||
if ($NativeAot -and (Test-Path "$EnginePublish\Native")) {
|
||||
foreach ($file in (Get-ChildItem "$EnginePublish\Native" -File)) {
|
||||
if ($file.Extension -eq '.pdb') { continue }
|
||||
Copy-Item $file.FullName "$CoreStaging\Runtime\Native\$($file.Name)" -Force
|
||||
|
|
@ -387,6 +432,44 @@ if (-not (Test-Path $NavPortalsTsv)) { throw "RynthNav portals.tsv not found at:
|
|||
New-Item -ItemType Directory -Path "$StagingRoot\navdata" -Force | Out-Null
|
||||
Copy-Item $NavPortalsTsv "$StagingRoot\navdata\" -Force
|
||||
|
||||
# Decal bridge (docs/DECAL_BRIDGE_PLAN.md, experimental): the net48 x86 Decal network filter
|
||||
# goes to {app}\DecalBridge\, the folder the launcher registers for "Decal + RynthCore"
|
||||
# accounts (and only for those). Built against Decal's public reference assemblies, so the
|
||||
# build machine needs Decal; -p:RequireDecal=true turns "no Decal" into a build error rather
|
||||
# than the empty assembly a plain solution build makes. Never ships any Decal file.
|
||||
# Same probe as the bridge csproj (DecalAvailable): Decal.Adapter.dll in the Decal folder.
|
||||
$decalProbeDir = if ($DecalDir) { $DecalDir } else { "${env:ProgramFiles(x86)}\Decal 3.0" }
|
||||
$decalInstalled = Test-Path (Join-Path $decalProbeDir "Decal.Adapter.dll")
|
||||
$buildDecalBridge = -not $SkipDecalBridge -and ($decalInstalled -or $IncludeDecalBridge)
|
||||
if ($SkipDecalBridge) {
|
||||
Write-Warning "-SkipDecalBridge: this build has no Decal bridge; 'Decal + RynthCore' accounts can't launch with it."
|
||||
} elseif (-not $buildDecalBridge) {
|
||||
Write-Warning "Decal not found in '$decalProbeDir': this build has no Decal bridge; 'Decal + RynthCore' accounts can't launch with it. (-DecalDir for another folder, -IncludeDecalBridge to make this an error.)"
|
||||
} else {
|
||||
Write-Host ""
|
||||
Write-Host "Building the Decal bridge (net48 x86, against Decal's reference assemblies)..." -ForegroundColor Cyan
|
||||
$bridgeProject = "$RepoRoot\src\RynthCore.DecalBridge\RynthCore.DecalBridge.csproj"
|
||||
$bridgeDll = "$RepoRoot\src\RynthCore.DecalBridge\bin\$Configuration\RynthCore.DecalBridge.dll"
|
||||
$decalArgs = @("-p:RequireDecal=true")
|
||||
if ($DecalDir) { $decalArgs += "-p:DecalDir=$DecalDir" }
|
||||
# A DLL left over from an earlier build must never be shipped in place of this one.
|
||||
Remove-Item $bridgeDll -Force -ErrorAction SilentlyContinue
|
||||
if (Test-Path $bridgeDll) { throw "Could not remove the old $bridgeDll (in use by a Decal client?)" }
|
||||
dotnet build $bridgeProject -c $Configuration -nologo -v q @decalArgs @VersionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Decal bridge build failed (exit $LASTEXITCODE). Is Decal 3.0 installed? (-DecalDir for another folder, -SkipDecalBridge to leave it out)" }
|
||||
if (-not (Test-Path $bridgeDll)) { throw "Decal bridge not built at $bridgeDll" }
|
||||
# The real bridge has its filter type; the no-Decal build is an empty assembly.
|
||||
$bridgeBytes = [System.IO.File]::ReadAllBytes($bridgeDll)
|
||||
if ([System.Text.Encoding]::ASCII.GetString($bridgeBytes).IndexOf("BridgeFilter") -lt 0) {
|
||||
throw "$bridgeDll has no BridgeFilter type - it was built without Decal's reference assemblies."
|
||||
}
|
||||
New-Item -ItemType Directory -Path "$CoreStaging\DecalBridge" -Force | Out-Null
|
||||
Copy-Item $bridgeDll "$CoreStaging\DecalBridge\" -Force
|
||||
$staleDecal = @(Get-ChildItem "$CoreStaging\DecalBridge" -File | Where-Object { $_.Name -ne "RynthCore.DecalBridge.dll" })
|
||||
if ($staleDecal.Count -gt 0) { throw "Unexpected files in the staged DecalBridge folder: $($staleDecal.Name -join ', ')" }
|
||||
Write-Host " RynthCore.DecalBridge.dll $((Get-Item $bridgeDll).VersionInfo.FileVersion)"
|
||||
}
|
||||
|
||||
# release.txt — which core release this install is ($release, from -Version at the top).
|
||||
Set-Content -Path "$CoreStaging\release.txt" -Value @($release, $Version) -Encoding ASCII
|
||||
|
||||
|
|
@ -407,6 +490,17 @@ $required = @(
|
|||
"$SuiteStaging\RynthAi\MonsterEditor\RynthCore.MonsterEditor.exe",
|
||||
"$StagingRoot\navdata\portals.tsv"
|
||||
) + @($ExperimentalPlugins | ForEach-Object { "$SuiteStaging\$_\RynthCore.Plugin.$_.dll" })
|
||||
# The unloadable engine also needs its shim and the app-local CoreCLR runtime.
|
||||
if (-not $NativeAot) {
|
||||
$required += @(
|
||||
"$CoreStaging\Runtime\RynthCore.Shim.dll",
|
||||
"$CoreStaging\Runtime\dotnet\coreclr.dll",
|
||||
"$CoreStaging\Runtime\dotnet\System.Private.CoreLib.dll"
|
||||
)
|
||||
}
|
||||
if ($buildDecalBridge) {
|
||||
$required += "$CoreStaging\DecalBridge\RynthCore.DecalBridge.dll"
|
||||
}
|
||||
$missing = @($required | Where-Object { -not (Test-Path $_) })
|
||||
if ($missing.Count -gt 0) { throw "Staging is missing required files:`n $($missing -join "`n ")" }
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@
|
|||
One command per release:
|
||||
1. Refuses if the signing key isn't set up or isn't trusted by the launcher being shipped,
|
||||
if either repo has uncommitted changes, or if -Version isn't newer than the live feed.
|
||||
2. Builds the installer (Build-Installer.ps1 -Version) and the RynthSuite plugins into
|
||||
2. Builds the installer (Build-Installer.ps1 -Version; it includes the Decal bridge, so the
|
||||
build machine needs Decal installed) and the RynthSuite plugins into
|
||||
installer\Releases\<release>\ — never into the live C:\Games folders.
|
||||
3. Writes the manifest (sizes + SHA-256 of every file), signs it with the DPAPI key
|
||||
(Sign-Update.ps1, no prompt) and checks the signature the way the launcher will.
|
||||
|
|
@ -37,7 +38,12 @@ param(
|
|||
[string]$BaseUrl = "https://aelrynth.com/downloads/rynth",
|
||||
[string]$KeyDir = (Join-Path $env:USERPROFILE ".rynthcore-update-signing"),
|
||||
[string]$RynthSuiteRoot = "",
|
||||
[string]$TrustFile = "" # defaults to the launcher's UpdateTrust.cs; override for tests
|
||||
[string]$TrustFile = "", # defaults to the launcher's UpdateTrust.cs; override for tests
|
||||
# RynthNav's data shipped to launchers as the signed "navdata" archive: tiles (nav_XXXX.tile),
|
||||
# portals.tsv and locations.json from this folder. Only re-uploaded when the set changes
|
||||
# (its id is a hash of every file); otherwise the live feed's entry is carried over.
|
||||
[string]$NavDataDir = "C:\Games\RynthCore\NavData",
|
||||
[switch]$SkipNavData # leave navdata out of this feed (launchers then keep what they have)
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
|
@ -48,6 +54,7 @@ if (-not $TrustFile) { $TrustFile = Join-Path $RepoRoot "src\RynthCore.App.Avalo
|
|||
|
||||
function Step($m) { Write-Host ""; Write-Host "== $m" -ForegroundColor Cyan }
|
||||
function Sha256([string]$path) { (Get-FileHash $path -Algorithm SHA256).Hash.ToLowerInvariant() }
|
||||
function Sha256Text([string]$text) { [Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($text))).ToLowerInvariant() }
|
||||
|
||||
# Same check as RynthUpdater.VerifyEnvelope: any trusted key's signature over the payload bytes.
|
||||
function Test-Envelope([string]$path, [string[]]$keys) {
|
||||
|
|
@ -99,9 +106,11 @@ if (-not $AllowDirty) {
|
|||
Write-Host " RynthCore $(git -C $RepoRoot rev-parse --short HEAD), RynthSuite $(git -C $RynthSuiteRoot rev-parse --short HEAD)"
|
||||
}
|
||||
|
||||
$liveManifest = $null
|
||||
try {
|
||||
$live = Invoke-RestMethod "$BaseUrl/update.json" -TimeoutSec 20
|
||||
$liveRelease = ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($live.payload)) | ConvertFrom-Json).release
|
||||
$liveManifest = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($live.payload)) | ConvertFrom-Json
|
||||
$liveRelease = $liveManifest.release
|
||||
if ($release -le $liveRelease) { throw "Release $release is not newer than the live feed's $liveRelease — bump -Version." }
|
||||
Write-Host " live feed is at $liveRelease; publishing $release"
|
||||
} catch [Microsoft.PowerShell.Commands.HttpResponseException] {
|
||||
|
|
@ -116,12 +125,20 @@ New-Item -ItemType Directory -Force "$rel\plugins", "$rel\build" | Out-Null
|
|||
Step "Building the installer ($Version)"
|
||||
& (Join-Path $ScriptDir "Build-Installer.ps1") -Version $Version -RynthSuiteRoot $RynthSuiteRoot
|
||||
if (-not $?) { throw "Build-Installer.ps1 failed" }
|
||||
# The Decal bridge (experimental, opt-in per account) is only in installers built where Decal is
|
||||
# installed; a launcher updating through this feed without it can't run "Decal + RynthCore" accounts.
|
||||
$bridgeStaged = Join-Path $ScriptDir "staging\core\DecalBridge\RynthCore.DecalBridge.dll"
|
||||
if (Test-Path $bridgeStaged) {
|
||||
Write-Host " Decal bridge in the installer: $((Get-Item $bridgeStaged).VersionInfo.FileVersion)"
|
||||
} else {
|
||||
Write-Warning "This installer has no Decal bridge ($bridgeStaged missing); 'Decal + RynthCore' accounts won't work from it."
|
||||
}
|
||||
# The versioned installer is the primary artifact (the RynthCore-Setup.exe copy is best effort).
|
||||
Copy-Item (Join-Path $ScriptDir "Output\RynthCore-Setup-$Version.exe") "$rel\RynthCore-Setup.exe"
|
||||
# Build-Installer.ps1 stages RynthSuite files under staging\suite\ (RynthAi -> staging\suite\RynthAi\).
|
||||
Copy-Item (Join-Path $ScriptDir "staging\suite\RynthAi\RynthCore.Plugin.RynthAi.dll") "$rel\plugins\"
|
||||
|
||||
$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision"
|
||||
$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory"
|
||||
foreach ($name in $suitePlugins) {
|
||||
Step "Building $name"
|
||||
$proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj"
|
||||
|
|
@ -136,11 +153,26 @@ $zipRoot = "$rel\build\zip"
|
|||
foreach ($name in $suitePlugins) {
|
||||
New-Item -ItemType Directory -Force "$zipRoot\RynthSuite\$name" | Out-Null
|
||||
Copy-Item "$rel\plugins\RynthCore.Plugin.$name.dll" "$zipRoot\RynthSuite\$name\"
|
||||
# Third-party licence notices travel with the plugin (RynthOracle: Oracle of Dereth, MIT).
|
||||
$notice = "$rel\build\$name\THIRD_PARTY_NOTICES.md"
|
||||
if (Test-Path $notice) { Copy-Item $notice "$zipRoot\RynthSuite\$name\" }
|
||||
}
|
||||
$navSrc = "C:\Games\RynthCore\NavData"
|
||||
$navSrc = $NavDataDir
|
||||
New-Item -ItemType Directory -Force "$zipRoot\RynthCore\NavData" | Out-Null
|
||||
Get-ChildItem $navSrc -File | Where-Object { $_.Extension -eq ".tile" -or $_.Name -eq "portals.tsv" } |
|
||||
# The route planner's portals.tsv and the Atlas's locations.json (both made by
|
||||
# tools\navdata\gen_locations.py from the world database), and the Town Network's townnet.json
|
||||
# (tools\navdata\Build-TownNet.ps1: the world database plus the walks inside from the dats).
|
||||
# Never the player's own files
|
||||
# there (atlas.txt, recalls.txt, _player.txt). The tiles are no longer in this zip (the whole
|
||||
# world is ~40,000 of them): the launcher installs them from the feed's navdata archive.
|
||||
Get-ChildItem $navSrc -File | Where-Object { $_.Name -eq "portals.tsv" -or $_.Name -eq "locations.json" -or $_.Name -eq "townnet.json" } |
|
||||
Copy-Item -Destination "$zipRoot\RynthCore\NavData\"
|
||||
if (-not (Test-Path "$navSrc\locations.json")) {
|
||||
Write-Warning "NavData has no locations.json: RynthNav's Atlas ships empty. Run tools\navdata\gen_locations.py and copy its output there."
|
||||
}
|
||||
if (-not (Test-Path "$navSrc\townnet.json")) {
|
||||
Write-Warning "NavData has no townnet.json: routes won't use the Town Network. Run tools\navdata\Build-TownNet.ps1 and copy its townnet.json there."
|
||||
}
|
||||
@"
|
||||
RynthSuite plugins for RynthCore (Asheron's Call, retail client) - $Version
|
||||
|
||||
|
|
@ -149,28 +181,108 @@ Extract this zip into C:\Games - it creates:
|
|||
C:\Games\RynthSuite\RynthNav\ RynthNav plugin
|
||||
C:\Games\RynthSuite\RynthTracker\ RynthTracker plugin
|
||||
C:\Games\RynthSuite\RynthVision\ RynthVision plugin
|
||||
C:\Games\RynthCore\NavData\ RynthNav's baked navmesh tiles
|
||||
C:\Games\RynthSuite\RynthLua\ RynthLua plugin (Lua scripting; was part of RynthAi)
|
||||
C:\Games\RynthSuite\RynthOracle\ RynthOracle plugin (quests, character, titles; based on Oracle of Dereth by Advis Eveldan)
|
||||
C:\Games\RynthSuite\RynthInventory\ RynthInventory plugin (search every character's items)
|
||||
C:\Games\RynthCore\NavData\ RynthNav's portals and Atlas
|
||||
|
||||
Then, in the RynthCore launcher's Plugins tab, add the full path of each
|
||||
plugin DLL you want. Install RynthCore first (RynthCore-Setup.exe), which
|
||||
also installs RynthAi and the Loot Editor. After that the launcher keeps
|
||||
the plugins up to date by itself.
|
||||
the plugins up to date by itself, and once RynthNav is in the list it also
|
||||
downloads RynthNav's navmesh tiles into C:\Games\RynthCore\NavData.
|
||||
|
||||
MIT licensed. https://aelrynth.com/projects.html
|
||||
"@ -replace "`n", "`r`n" | Set-Content "$zipRoot\README.txt" -NoNewline
|
||||
Compress-Archive -Path "$zipRoot\*" -DestinationPath "$rel\RynthSuite-Plugins.zip" -CompressionLevel Optimal
|
||||
|
||||
# RynthNav's data for the launchers (RynthUpdater.NavData.cs): one archive, flat, only the file
|
||||
# names RynthNav reads. Its id is a hash over every file's name and SHA-256, so an unchanged
|
||||
# set reuses the live entry (and the archive already on the server) instead of re-uploading.
|
||||
$navData = $null
|
||||
$navZip = $null
|
||||
if (-not $SkipNavData) {
|
||||
Step "RynthNav data (tiles, route graph, portals, Atlas, Town Network) from $NavDataDir"
|
||||
$navFiles = @(Get-ChildItem $NavDataDir -File | Where-Object { $_.Name -match '^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json)$' } | Sort-Object Name)
|
||||
$tileCount = @($navFiles | Where-Object { $_.Extension -eq ".tile" }).Count
|
||||
if ($tileCount -eq 0) { throw "$NavDataDir has no tiles. Pass -NavDataDir, or -SkipNavData to publish without them." }
|
||||
# The long-range route graph (RynthNav.Baker --graph) must come from these very tiles: the
|
||||
# plugin ignores a graph whose tiles don't match (long gotos then walk the straight line).
|
||||
$graph = $navFiles | Where-Object { $_.Name -eq "navgraph.bin" }
|
||||
$newestTile = ($navFiles | Where-Object { $_.Extension -eq ".tile" } | Measure-Object LastWriteTimeUtc -Maximum).Maximum
|
||||
if (-not $graph) { Write-Warning "No navgraph.bin in ${NavDataDir}: long gotos will walk the straight line. Run: RynthNav.Baker --graph $NavDataDir" }
|
||||
elseif ($graph.LastWriteTimeUtc -lt $newestTile) { Write-Warning "navgraph.bin is older than the newest tile: rebuild it (RynthNav.Baker --graph $NavDataDir), or RynthNav will ignore it." }
|
||||
$idText = ($navFiles | ForEach-Object { "$($_.Name) $(Sha256 $_.FullName)" }) -join "`n"
|
||||
$navId = (Sha256Text $idText).Substring(0, 32)
|
||||
# [long]: Measure-Object's Sum is a double, which ConvertTo-Json writes as 1383002945.0, and the
|
||||
# launcher reads "bytes" with GetInt64 - a ".0" failed every launcher's update check (2026.10.3.1/2).
|
||||
$navBytes = [long](($navFiles | Measure-Object Length -Sum).Sum)
|
||||
if ($liveManifest -and $liveManifest.navdata -and $liveManifest.navdata.id -eq $navId) {
|
||||
$navData = $liveManifest.navdata
|
||||
# Carried over from the live feed (ConvertFrom-Json): force the whole numbers back to integers.
|
||||
$navData = [ordered]@{
|
||||
id = [string]$navData.id
|
||||
release = [long]$navData.release
|
||||
url = [string]$navData.url
|
||||
size = [long]$navData.size
|
||||
sha256 = [string]$navData.sha256
|
||||
files = [long]$navData.files
|
||||
bytes = [long]$navData.bytes
|
||||
}
|
||||
Write-Host " unchanged ($($navFiles.Count) files, id $navId): the live archive from release $($navData.release) stays"
|
||||
} else {
|
||||
$navZip = "$rel\RynthNav-NavData.zip"
|
||||
Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem
|
||||
$fs = [IO.File]::Open($navZip, 'CreateNew')
|
||||
try {
|
||||
$za = New-Object IO.Compression.ZipArchive($fs, [IO.Compression.ZipArchiveMode]::Create)
|
||||
foreach ($f in $navFiles) {
|
||||
[void][IO.Compression.ZipFileExtensions]::CreateEntryFromFile($za, $f.FullName, $f.Name, [IO.Compression.CompressionLevel]::Optimal)
|
||||
}
|
||||
$za.Dispose()
|
||||
} finally { $fs.Dispose() }
|
||||
$zi = Get-Item $navZip
|
||||
$navData = [ordered]@{
|
||||
id = $navId
|
||||
release = $release
|
||||
url = "$BaseUrl/releases/$release/RynthNav-NavData.zip"
|
||||
size = $zi.Length
|
||||
sha256 = Sha256 $zi.FullName
|
||||
files = $navFiles.Count
|
||||
bytes = $navBytes
|
||||
}
|
||||
Write-Host (" new set: {0} files ({1} tiles), {2:N0} MB packed into {3:N0} MB, id {4}" -f $navFiles.Count, $tileCount, ($navBytes / 1MB), ($zi.Length / 1MB), $navId)
|
||||
}
|
||||
}
|
||||
|
||||
# ── 3. Manifest + signature ──────────────────────────────────────────────────
|
||||
Step "Writing and signing the manifest"
|
||||
$setup = Get-Item "$rel\RynthCore-Setup.exe"
|
||||
# One line per plugin for the launcher's Available plugins list (launchers from 2026.10.5 on;
|
||||
# older ones ignore the field, and a plugin without one falls back to the launcher's own table
|
||||
# in RynthUpdater.Available.cs). Plain English for players, no names.
|
||||
$pluginDescriptions = @{
|
||||
RynthAi = "The bot: combat, buffs, looting, navigation routes and metas."
|
||||
RynthChat = "A chat window that sorts messages into tabs."
|
||||
RynthTracker = "Kills, experience and luminance per hour for each session."
|
||||
RynthNav = "Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB)."
|
||||
RynthVision = "Shows unclimbable slopes, impassable water and your radar range in the world."
|
||||
RynthLua = "Lua scripting for metas and your own scripts."
|
||||
RynthOracle = "Quests, character, titles and leaderboards."
|
||||
RynthInventory = "Search every character's items."
|
||||
}
|
||||
$plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Name) {
|
||||
[ordered]@{
|
||||
name = $dll.BaseName -replace '^RynthCore\.Plugin\.', ''
|
||||
$pluginName = $dll.BaseName -replace '^RynthCore\.Plugin\.', ''
|
||||
$entry = [ordered]@{
|
||||
name = $pluginName
|
||||
file = $dll.Name
|
||||
url = "$BaseUrl/releases/$release/plugins/$($dll.Name)"
|
||||
size = $dll.Length
|
||||
sha256 = Sha256 $dll.FullName
|
||||
}
|
||||
if ($pluginDescriptions[$pluginName]) { $entry.description = $pluginDescriptions[$pluginName] }
|
||||
else { Write-Warning "No description for $pluginName - the launcher shows its own (or none). Add one to `$pluginDescriptions." }
|
||||
$entry
|
||||
}
|
||||
$manifest = [ordered]@{
|
||||
schema = 1
|
||||
|
|
@ -178,6 +290,9 @@ $manifest = [ordered]@{
|
|||
version = $Version
|
||||
published = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||
notes = $Notes
|
||||
# The changes, one line each: the launcher's update card shows a few as "What's new"
|
||||
# (signed with the rest; launchers before 2026.10.5 ignore it and show the notes).
|
||||
changes = @($Changes)
|
||||
core = [ordered]@{
|
||||
release = $release
|
||||
version = $Version
|
||||
|
|
@ -187,6 +302,7 @@ $manifest = [ordered]@{
|
|||
}
|
||||
plugins = @($plugins)
|
||||
}
|
||||
if ($navData) { $manifest.navdata = $navData }
|
||||
Set-Content "$rel\update.payload.json" ($manifest | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM
|
||||
& (Join-Path $ScriptDir "Sign-Update.ps1") -PayloadPath "$rel\update.payload.json" -OutPath "$rel\update.json" -KeyDir $KeyDir
|
||||
if (-not (Test-Envelope "$rel\update.json" $trusted)) { throw "Signed feed does not verify against UpdateTrust.cs" }
|
||||
|
|
@ -215,9 +331,16 @@ scp -q "$rel\RynthCore-Setup.exe" "${SshHost}:$remoteRel/RynthCore-Setup.exe"
|
|||
if ($LASTEXITCODE -ne 0) { throw "scp of the installer failed" }
|
||||
scp -q (Get-ChildItem "$rel\plugins\*.dll").FullName "${SshHost}:$remoteRel/plugins/"
|
||||
if ($LASTEXITCODE -ne 0) { throw "scp of the plugins failed" }
|
||||
$navSum = ""
|
||||
if ($navZip) {
|
||||
scp -q $navZip "${SshHost}:$remoteRel/RynthNav-NavData.zip"
|
||||
if ($LASTEXITCODE -ne 0) { throw "scp of the RynthNav data archive failed" }
|
||||
$navSum = " RynthNav-NavData.zip"
|
||||
}
|
||||
|
||||
$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll"
|
||||
$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll$navSum"
|
||||
$expect = @{ "RynthCore-Setup.exe" = $manifest.core.sha256 }
|
||||
if ($navZip) { $expect["RynthNav-NavData.zip"] = $navData.sha256 }
|
||||
foreach ($pl in $plugins) { $expect["plugins/$($pl.file)"] = $pl.sha256 }
|
||||
foreach ($line in $remoteSums) {
|
||||
$sum, $name = $line -split '\s+', 2
|
||||
|
|
|
|||
|
|
@ -161,6 +161,16 @@ Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Description: "Launch Rynth
|
|||
; bring it back when the upgrade is done.
|
||||
Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Flags: nowait runasoriginaluser; Check: CmdLineParamExists('/RELAUNCH')
|
||||
|
||||
[UninstallRun]
|
||||
; Decal + RynthCore (experimental): remove the Decal bridge's registration, only
|
||||
; what the launcher added (see docs/DECAL_BRIDGE_PLAN.md). Builds made with Decal installed ship
|
||||
; the bridge ({app}\DecalBridge, staged by Build-Installer.ps1); this always runs; with nothing
|
||||
; registered it changes nothing. Runs before the files are removed. It removes both entries
|
||||
; the installer writes (see RegisterDecalBridge in [Code]): the per-user one, and the
|
||||
; machine-wide one - directly when the uninstaller is elevated, otherwise after Windows'
|
||||
; administrator prompt, which appears only when a machine-wide entry exists.
|
||||
Filename: "{app}\RynthCore.exe"; Parameters: "--decal-bridge-unregister"; Flags: runhidden waituntilterminated; RunOnceId: "RynthCoreDecalBridgeUnregister"
|
||||
|
||||
[Code]
|
||||
const
|
||||
DefaultSuiteDir = 'C:\Games\RynthSuite';
|
||||
|
|
@ -487,3 +497,106 @@ begin
|
|||
if MemoTasksInfo <> '' then
|
||||
Result := Result + NewLine + MemoTasksInfo;
|
||||
end;
|
||||
|
||||
(* -------------------------------------------------------------------------------------
|
||||
Decal + RynthCore (experimental): register the RynthCore Decal bridge on every install
|
||||
AND every update (the launcher's updater runs this installer with /SILENT), in BOTH
|
||||
places a Decal client can read its filter list from:
|
||||
|
||||
1. Machine-wide: HKLM\SOFTWARE\WOW6432Node\Decal\NetworkFilters\{5B3E0D57-...}
|
||||
(32-bit view). An elevated AC (RynthCore or AC run as administrator), or any AC when
|
||||
UAC or its registry virtualization is off, reads ONLY this key - the per-user entry
|
||||
is invisible to it (a player's Decal + RynthCore client never loaded the bridge,
|
||||
2026-10-03). A non-elevated AC without a per-user copy reads it too.
|
||||
2. Per-user: this user's VirtualStore copy of that key, ONLY if the copy already exists.
|
||||
A non-elevated AC is virtualized and, once a copy exists, reads nothing but the copy.
|
||||
A missing copy is never created: it would hide every HKLM filter added later from
|
||||
this user's non-elevated clients.
|
||||
|
||||
Both entries are harmless while no account uses Decal + RynthCore: every Decal client
|
||||
loads the bridge, which stays idle (no hooks, no threads) unless the RynthCore loader is
|
||||
in the same client. Uninstall removes both ([UninstallRun] --decal-bridge-unregister).
|
||||
|
||||
Rights. This installer runs with the lowest privileges (PrivilegesRequired=lowest; the
|
||||
updater starts it without elevation). Writing HKLM needs administrator rights, so:
|
||||
- Setup already elevated (installed "for all users", or started by an elevated
|
||||
launcher): written directly, no prompt.
|
||||
- Not elevated: Windows' administrator prompt is shown ONCE - only when Decal is
|
||||
installed, the machine-wide entry is missing or points at another folder, and this
|
||||
user has a Decal + RynthCore account (decal-accounts.json). Saying no is harmless:
|
||||
the launcher checks before every Decal + RynthCore launch and repairs it (writing it
|
||||
directly when it runs elevated, the case that needs it).
|
||||
The commands are RynthCore.exe's own (Program.cs): --decal-bridge-register-machine and
|
||||
--decal-bridge-install-user, so the installer and the launcher write identical entries.
|
||||
------------------------------------------------------------------------------------- *)
|
||||
const
|
||||
BridgeEntryKey = 'SOFTWARE\Decal\NetworkFilters\{5B3E0D57-2C41-4F8A-9D6E-8C1B70DECA11}';
|
||||
BridgeObject = 'RynthCore.DecalBridge.BridgeFilter';
|
||||
|
||||
function DecalInstalled: Boolean;
|
||||
begin
|
||||
Result := RegKeyExists(HKLM32, 'SOFTWARE\Decal\Agent');
|
||||
end;
|
||||
|
||||
function BridgeDir: String;
|
||||
begin
|
||||
Result := ExpandConstant('{app}\DecalBridge');
|
||||
end;
|
||||
|
||||
function MachineBridgeEntryCurrent: Boolean;
|
||||
var
|
||||
P, O: String;
|
||||
E: Cardinal;
|
||||
begin
|
||||
Result := RegQueryStringValue(HKLM32, BridgeEntryKey, 'Path', P) and
|
||||
(CompareText(RemoveBackslashUnlessRoot(P), BridgeDir) = 0) and
|
||||
RegQueryStringValue(HKLM32, BridgeEntryKey, 'Object', O) and (O = BridgeObject) and
|
||||
RegQueryDWordValue(HKLM32, BridgeEntryKey, 'Enabled', E) and (E = 1);
|
||||
end;
|
||||
|
||||
function UsesDecalBridge: Boolean;
|
||||
begin
|
||||
Result := FileExists(ExpandConstant('{userappdata}\RynthCore\decal-accounts.json'));
|
||||
end;
|
||||
|
||||
procedure RegisterDecalBridge;
|
||||
var
|
||||
Exe, Params: String;
|
||||
Code: Integer;
|
||||
begin
|
||||
if not DecalInstalled then Exit;
|
||||
if not FileExists(BridgeDir + '\RynthCore.DecalBridge.dll') then Exit;
|
||||
Exe := ExpandConstant('{app}\RynthCore.exe');
|
||||
Params := '--decal-bridge-register-machine "' + BridgeDir + '"';
|
||||
if not MachineBridgeEntryCurrent then
|
||||
begin
|
||||
if IsAdmin then
|
||||
begin
|
||||
if not Exec(Exe, Params, ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, Code) then
|
||||
Log('Decal bridge: machine-wide registration did not start: ' + SysErrorMessage(Code))
|
||||
else
|
||||
Log('Decal bridge: machine-wide registration exit code ' + IntToStr(Code));
|
||||
end
|
||||
else if UsesDecalBridge then
|
||||
begin
|
||||
if not ShellExec('runas', Exe, Params, ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, Code) then
|
||||
Log('Decal bridge: elevated machine-wide registration not done (declined or failed): ' + SysErrorMessage(Code))
|
||||
else
|
||||
Log('Decal bridge: elevated machine-wide registration exit code ' + IntToStr(Code));
|
||||
end
|
||||
else
|
||||
Log('Decal bridge: machine-wide entry missing; not elevated and no Decal + RynthCore account - left to the launcher.');
|
||||
end;
|
||||
{ Per-user half, as the user who started Setup (the same user unless Setup was elevated
|
||||
with other credentials). }
|
||||
if not ExecAsOriginalUser(Exe, '--decal-bridge-install-user "' + BridgeDir + '"', ExpandConstant('{app}'),
|
||||
SW_HIDE, ewWaitUntilTerminated, Code) then
|
||||
Log('Decal bridge: per-user step did not start: ' + SysErrorMessage(Code));
|
||||
end;
|
||||
|
||||
procedure CurStepChanged(CurStep: TSetupStep);
|
||||
begin
|
||||
{ After the files, before [Run] (which relaunches the launcher after an update). }
|
||||
if CurStep = ssPostInstall then
|
||||
RegisterDecalBridge;
|
||||
end;
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
2026.10.4.22
|
||||
2026.10.5.11
|
||||
|
|
@ -1,24 +1,24 @@
|
|||
{
|
||||
"schema": 1,
|
||||
"product": "RynthCore + RynthSuite",
|
||||
"version": "2026.10.4.22",
|
||||
"release": 2026100422,
|
||||
"builtUtc": "2026-10-05T05:05:36Z",
|
||||
"previous": "2026.10.4.21",
|
||||
"version": "2026.10.5.11",
|
||||
"release": 2026100511,
|
||||
"builtUtc": "2026-10-05T17:09:44Z",
|
||||
"previous": "2026.10.5.10",
|
||||
"installer": {
|
||||
"file": "RynthCore-Setup-2026.10.4.22.exe",
|
||||
"size": 108550595,
|
||||
"sha256": "9e29c47918dfae7cbcf6def51386e55d9ecb9b7d410d9e2fea5d29ce86911379"
|
||||
"file": "RynthCore-Setup-2026.10.5.11.exe",
|
||||
"size": 130761857,
|
||||
"sha256": "9be7f21a15c0d175f5f00c252eea7bf4caadaf798676ea96b3673e47267c424e"
|
||||
},
|
||||
"source": {
|
||||
"rynthCore": {
|
||||
"branch": "SK-local",
|
||||
"commit": "ae775110769b1367288ff8979525bbb3a1a55535",
|
||||
"branch": "merge/aelrynth-2026.10.5.1",
|
||||
"commit": "1c75df5351ab20b05bbd0493f6a4097e72f0ddcf",
|
||||
"dirty": false
|
||||
},
|
||||
"rynthSuite": {
|
||||
"branch": "SK-local",
|
||||
"commit": "dc9b6a48849161866d90a252303b6ff9b2d610b2",
|
||||
"branch": "fix/rynthai-launcher-remote-commands",
|
||||
"commit": "27f962fa89daac495fc5c92cd252225d1b237b45",
|
||||
"dirty": false
|
||||
}
|
||||
},
|
||||
|
|
@ -26,71 +26,72 @@
|
|||
{
|
||||
"name": "Launcher (RynthCore.exe)",
|
||||
"file": "core\\RynthCore.exe",
|
||||
"version": "2026.10.4.22+ae775110769b1367288ff8979525bbb3a1a55535"
|
||||
"version": "2026.10.5.11+1c75df5351ab20b05bbd0493f6a4097e72f0ddcf"
|
||||
},
|
||||
{
|
||||
"name": "Engine",
|
||||
"file": "core\\Runtime\\RynthCore.Engine.dll",
|
||||
"version": "2026.10.4.22+ae775110769b1367288ff8979525bbb3a1a55535"
|
||||
"version": "2026.10.5.11+1c75df5351ab20b05bbd0493f6a4097e72f0ddcf"
|
||||
},
|
||||
{
|
||||
"name": "Loader",
|
||||
"file": "core\\Runtime\\RynthCore.Loader.dll",
|
||||
"version": "2026.10.4.22+ae775110769b1367288ff8979525bbb3a1a55535"
|
||||
"version": ""
|
||||
},
|
||||
{
|
||||
"name": "Loot Editor",
|
||||
"file": "core\\Tools\\LootEditor\\RynthCore.LootEditor.exe",
|
||||
"version": "2026.10.4.22+dc9b6a48849161866d90a252303b6ff9b2d610b2"
|
||||
"version": "2026.10.5.11+27f962fa89daac495fc5c92cd252225d1b237b45"
|
||||
},
|
||||
{
|
||||
"name": "RynthAi plugin",
|
||||
"file": "suite\\RynthAi\\RynthCore.Plugin.RynthAi.dll",
|
||||
"version": "0.6.32-legacy-ui+dc9b6a48849161866d90a252303b6ff9b2d610b2"
|
||||
"version": "1.0.0+27f962fa89daac495fc5c92cd252225d1b237b45"
|
||||
},
|
||||
{
|
||||
"name": "Monster Editor",
|
||||
"file": "suite\\RynthAi\\MonsterEditor\\RynthCore.MonsterEditor.exe",
|
||||
"version": "2026.10.4.22+dc9b6a48849161866d90a252303b6ff9b2d610b2"
|
||||
"version": "2026.10.5.11+27f962fa89daac495fc5c92cd252225d1b237b45"
|
||||
},
|
||||
{
|
||||
"name": "RynthChat (experimental)",
|
||||
"file": "suite\\RynthChat\\RynthCore.Plugin.RynthChat.dll",
|
||||
"version": "0.1.1-experimental+dc9b6a48849161866d90a252303b6ff9b2d610b2"
|
||||
"version": "1.0.0+27f962fa89daac495fc5c92cd252225d1b237b45"
|
||||
},
|
||||
{
|
||||
"name": "RynthJuice (experimental)",
|
||||
"file": "suite\\RynthJuice\\RynthCore.Plugin.RynthJuice.dll",
|
||||
"version": "0.1.2-experimental+dc9b6a48849161866d90a252303b6ff9b2d610b2"
|
||||
"version": "0.1.2-experimental+27f962fa89daac495fc5c92cd252225d1b237b45"
|
||||
},
|
||||
{
|
||||
"name": "RynthNav (experimental)",
|
||||
"file": "suite\\RynthNav\\RynthCore.Plugin.RynthNav.dll",
|
||||
"version": "0.5.5-experimental+dc9b6a48849161866d90a252303b6ff9b2d610b2"
|
||||
"version": "1.0.0+27f962fa89daac495fc5c92cd252225d1b237b45"
|
||||
},
|
||||
{
|
||||
"name": "RynthTracker (experimental)",
|
||||
"file": "suite\\RynthTracker\\RynthCore.Plugin.RynthTracker.dll",
|
||||
"version": "0.1.1-experimental+dc9b6a48849161866d90a252303b6ff9b2d610b2"
|
||||
"version": "1.0.0+27f962fa89daac495fc5c92cd252225d1b237b45"
|
||||
},
|
||||
{
|
||||
"name": "RynthVision (experimental)",
|
||||
"file": "suite\\RynthVision\\RynthCore.Plugin.RynthVision.dll",
|
||||
"version": "0.1.1-experimental+dc9b6a48849161866d90a252303b6ff9b2d610b2"
|
||||
"version": "1.0.0+27f962fa89daac495fc5c92cd252225d1b237b45"
|
||||
},
|
||||
{
|
||||
"name": "UbRythai (experimental)",
|
||||
"file": "suite\\UbRythai\\RynthCore.Plugin.UbRythai.dll",
|
||||
"version": "3.1.10+dc9b6a48849161866d90a252303b6ff9b2d610b2"
|
||||
"version": "3.1.10+27f962fa89daac495fc5c92cd252225d1b237b45"
|
||||
}
|
||||
],
|
||||
"changelog": [
|
||||
"RynthCore/Changelog/2026-10-05-chat-translation.md",
|
||||
"RynthCore/Changelog/2026-10-05-installer-2026.10.4.21-release.md"
|
||||
"RynthCore/Changelog/2026-10-05-guardian-vendor-and-item-lookup.md",
|
||||
"RynthCore/Changelog/2026-10-05-native-drag-real-item.md",
|
||||
"RynthCore/Changelog/2026-10-05-release-2026.10.5.10.md"
|
||||
],
|
||||
"changelogSince": {
|
||||
"rynthCore": "51307657d971ff81c61aa6532fb1ad941c54ca7f",
|
||||
"rynthSuite": "a7754b972b26a78a2e28f3d0938c68e522cea0af",
|
||||
"rynthCore": "0bff4931842c0cc0bd67057fb4b670b204e6e1a8",
|
||||
"rynthSuite": "e3982b4d5171cd1339745fa464bd86d0aab721dc",
|
||||
"date": ""
|
||||
}
|
||||
}
|
||||
36
native/Loader/Build-Loader.ps1
Normal file
36
native/Loader/Build-Loader.ps1
Normal 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
175
native/Loader/Clr.c
Normal 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
332
native/Loader/Hooks.c
Normal 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
407
native/Loader/Loader.c
Normal 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
16
native/Loader/Loader.def
Normal 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
26
native/Loader/Loader.h
Normal 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
176
native/Loader/Services.c
Normal 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
2
native/cimgui/.gitattributes
vendored
Normal 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
3
native/cimgui/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
_src/
|
||||
_build/
|
||||
_textedit/
|
||||
47
native/cimgui/CMakeLists.txt
Normal file
47
native/cimgui/CMakeLists.txt
Normal 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)
|
||||
118
native/cimgui/rynth_cimgui_ext.cpp
Normal file
118
native/cimgui/rynth_cimgui_ext.cpp
Normal 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;
|
||||
}
|
||||
26
native/cimgui/rynth_imconfig.h
Normal file
26
native/cimgui/rynth_imconfig.h
Normal 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)
|
||||
308
native/cimgui/rynth_textedit_ext.cpp
Normal file
308
native/cimgui/rynth_textedit_ext.cpp
Normal 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();
|
||||
}
|
||||
129
native/cimgui/textedit-rynth.patch
Normal file
129
native/cimgui/textedit-rynth.patch
Normal 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; }
|
||||
13
native/cimgui/textedit_shim/boost/regex.hpp
Normal file
13
native/cimgui/textedit_shim/boost/regex.hpp
Normal 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
93
scripts/Build-Cimgui.ps1
Normal 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"
|
||||
|
|
@ -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"
|
||||
|
|
|
|||
122
scripts/Publish-EngineCoreClr.ps1
Normal file
122
scripts/Publish-EngineCoreClr.ps1
Normal 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"
|
||||
28
scripts/Publish-PluginsCoreClr.ps1
Normal file
28
scripts/Publish-PluginsCoreClr.ps1
Normal 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"
|
||||
}
|
||||
62
scripts/Test-ClrReload.ps1
Normal file
62
scripts/Test-ClrReload.ps1
Normal 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
97
scripts/Test-ClrWorld.ps1
Normal 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" }
|
||||
|
|
@ -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)
|
||||
#
|
||||
|
|
|
|||
52
spikes/CoreClrHost/Build.ps1
Normal file
52
spikes/CoreClrHost/Build.ps1
Normal 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"
|
||||
8
spikes/CoreClrHost/Contracts/Contracts.csproj
Normal file
8
spikes/CoreClrHost/Contracts/Contracts.csproj
Normal 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>
|
||||
17
spikes/CoreClrHost/Contracts/IPayload.cs
Normal file
17
spikes/CoreClrHost/Contracts/IPayload.cs
Normal 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();
|
||||
}
|
||||
153
spikes/CoreClrHost/Payload/Payload.cs
Normal file
153
spikes/CoreClrHost/Payload/Payload.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
14
spikes/CoreClrHost/Payload/Payload.csproj
Normal file
14
spikes/CoreClrHost/Payload/Payload.csproj
Normal 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>
|
||||
134
spikes/CoreClrHost/Shim/Entry.cs
Normal file
134
spikes/CoreClrHost/Shim/Entry.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
14
spikes/CoreClrHost/Shim/Shim.csproj
Normal file
14
spikes/CoreClrHost/Shim/Shim.csproj
Normal 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>
|
||||
216
spikes/CoreClrHost/native/SpikeHost.c
Normal file
216
spikes/CoreClrHost/native/SpikeHost.c
Normal 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;
|
||||
}
|
||||
19
spikes/CoreClrHost/native/SpikeHostExe.c
Normal file
19
spikes/CoreClrHost/native/SpikeHostExe.c
Normal 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);
|
||||
}
|
||||
53
spikes/CoreClrHost/native/SpikeInject.c
Normal file
53
spikes/CoreClrHost/native/SpikeInject.c
Normal 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;
|
||||
}
|
||||
169
spikes/DecalBridge/AcWindow.py
Normal file
169
spikes/DecalBridge/AcWindow.py
Normal 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))
|
||||
157
spikes/DecalBridge/BridgeProbePlugin/BridgeProbePlugin.cs
Normal file
157
spikes/DecalBridge/BridgeProbePlugin/BridgeProbePlugin.cs
Normal 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);
|
||||
}
|
||||
|
|
@ -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>
|
||||
65
spikes/DecalBridge/Inject-BridgeRecords.py
Normal file
65
spikes/DecalBridge/Inject-BridgeRecords.py
Normal 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()
|
||||
30
spikes/DecalBridge/Measure-HookRace.ps1
Normal file
30
spikes/DecalBridge/Measure-HookRace.ps1
Normal 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
|
||||
}
|
||||
37
spikes/DecalBridge/Register-DecalBridge.ps1
Normal file
37
spikes/DecalBridge/Register-DecalBridge.ps1
Normal 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
|
||||
59
spikes/DecalBridge/Start-DecalTestClient.ps1
Normal file
59
spikes/DecalBridge/Start-DecalTestClient.ps1
Normal 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"
|
||||
168
spikes/DecalBridge/Test-DecalBridgeInWorld.ps1
Normal file
168
spikes/DecalBridge/Test-DecalBridgeInWorld.ps1
Normal 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"
|
||||
|
|
@ -27,9 +27,11 @@ internal partial class AccountProfileDialog : Window
|
|||
AccountBox.Text = profile.AccountName;
|
||||
AliasBox.Text = profile.Alias;
|
||||
UserPrefsPathBox.Text = profile.UserPrefsPath;
|
||||
PasswordHintText.Text = string.IsNullOrEmpty(profile.Password)
|
||||
? "No password is saved for this profile yet."
|
||||
: "A password is already saved for this profile. It stays hidden unless you replace or clear it.";
|
||||
PasswordHintText.Text = profile.PasswordNeedsReentry
|
||||
? "Password needs re-entering: the saved one can't be read on this Windows user (settings copied from another user or PC?). Type it again to launch this account."
|
||||
: !profile.HasSavedPassword
|
||||
? "No password is saved for this profile yet."
|
||||
: "A password is saved for this profile, encrypted for this Windows user. It stays hidden unless you replace or clear it.";
|
||||
|
||||
SaveButton.Click += (_, _) => SaveAndClose();
|
||||
CancelButton.Click += (_, _) => Close(false);
|
||||
|
|
@ -116,12 +118,14 @@ internal partial class AccountProfileDialog : Window
|
|||
_profile.AccountName = AccountBox.Text.Trim();
|
||||
if (ClearPasswordCheckBox.IsChecked == true)
|
||||
{
|
||||
_profile.Password = string.Empty;
|
||||
_profile.ClearPassword();
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(PasswordBox.Text))
|
||||
{
|
||||
_profile.Password = PasswordBox.Text;
|
||||
// Encrypted at once (DPAPI, this Windows user); the plain text isn't kept on the profile.
|
||||
_profile.SetPassword(PasswordBox.Text);
|
||||
}
|
||||
PasswordBox.Text = string.Empty;
|
||||
|
||||
_profile.Alias = AliasBox.Text?.Trim() ?? string.Empty;
|
||||
_profile.UserPrefsPath = UserPrefsPathBox.Text?.Trim() ?? string.Empty;
|
||||
|
|
|
|||
128
src/RynthCore.App.Avalonia/DecalBridgeDialog.cs
Normal file
128
src/RynthCore.App.Avalonia/DecalBridgeDialog.cs
Normal 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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
146
src/RynthCore.App.Avalonia/DownloadProgress.cs
Normal file
146
src/RynthCore.App.Avalonia/DownloadProgress.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -108,10 +108,39 @@
|
|||
</Border>
|
||||
|
||||
<Grid Grid.Row="1" ColumnDefinitions="3*,Auto,2*">
|
||||
<TabControl Grid.Column="0" Margin="14,0,0,0" Padding="0">
|
||||
<TabControl x:Name="MainTabs" Grid.Column="0" Margin="14,0,0,0" Padding="0">
|
||||
<TabItem Header="Launcher">
|
||||
<ScrollViewer>
|
||||
<StackPanel Spacing="12" Margin="6">
|
||||
<!-- Updates: the card is built by UpdateCardModel (MainWindow.RefreshUpdateCard). -->
|
||||
<Border x:Name="UpdateCardBorder" Background="#132028" CornerRadius="16" Padding="18"
|
||||
BorderBrush="#243742" BorderThickness="1">
|
||||
<StackPanel Spacing="8">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel Grid.Column="0" Spacing="4" VerticalAlignment="Center">
|
||||
<TextBlock x:Name="UpdateCardTitle" Text="Updates" FontSize="16" FontWeight="SemiBold"
|
||||
Foreground="#26C1A6" TextWrapping="Wrap" />
|
||||
<TextBlock x:Name="UpdateCardDetail" Text="Not checked yet." TextWrapping="Wrap" Foreground="#9AA8B3" />
|
||||
</StackPanel>
|
||||
<WrapPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Top" Margin="12,0,0,0">
|
||||
<Button x:Name="UpdateCardActionButton" IsVisible="False" Margin="0,0,8,6"
|
||||
Background="#26C1A6" Foreground="#0B1218" FontWeight="SemiBold" />
|
||||
<Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,0,6" />
|
||||
</WrapPanel>
|
||||
</Grid>
|
||||
<StackPanel x:Name="UpdateCardWhatsNewPanel" Spacing="2" IsVisible="False" />
|
||||
<Grid x:Name="DownloadArea" ColumnDefinitions="*,Auto" IsVisible="False">
|
||||
<ProgressBar x:Name="DownloadProgressBar" Grid.Column="0" Minimum="0" Maximum="100"
|
||||
Height="10" MinHeight="10" VerticalAlignment="Center"
|
||||
Foreground="#26C1A6" Background="#0F161D" />
|
||||
<Button x:Name="CancelDownloadButton" Grid.Column="1" Content="Cancel" Margin="10,0,0,0"
|
||||
ToolTip.Tip="Stops the download. Nothing half-installed is left behind: the partial file is deleted and what you have stays as it is." />
|
||||
</Grid>
|
||||
<Button x:Name="UpdateCardNewPluginsButton" IsVisible="False" HorizontalAlignment="Left"
|
||||
Background="Transparent" BorderThickness="0" Padding="0" Foreground="#F2C14E" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border Background="#132028" CornerRadius="16" Padding="18">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Launch Targets" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
|
|
@ -170,7 +199,7 @@
|
|||
<Grid RowDefinitions="Auto,Auto,*,Auto">
|
||||
<TextBlock Text="Account Profiles" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
<TextBlock Grid.Row="1"
|
||||
Text="Passwords stay persisted in settings."
|
||||
Text="Passwords are saved encrypted for this Windows user."
|
||||
TextWrapping="Wrap"
|
||||
Foreground="#9AA8B3"
|
||||
Margin="0,8,0,0" />
|
||||
|
|
@ -234,36 +263,58 @@
|
|||
</ScrollViewer>
|
||||
</TabItem>
|
||||
|
||||
<TabItem Header="Plugins">
|
||||
<ScrollViewer>
|
||||
<TabItem x:Name="PluginsTab" Header="Plugins">
|
||||
<ScrollViewer x:Name="PluginsScroll">
|
||||
<StackPanel Spacing="12" Margin="6">
|
||||
<Border Background="#132028" CornerRadius="16" Padding="18">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Updates" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
<!-- Compact: the update card with its buttons is on the Launcher tab. -->
|
||||
<TextBlock x:Name="UpdateStatusText"
|
||||
Text="Not checked yet."
|
||||
TextWrapping="Wrap"
|
||||
Foreground="#9AA8B3" />
|
||||
<WrapPanel Orientation="Horizontal">
|
||||
<Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,8,6" />
|
||||
<Button x:Name="UpdatePluginsButton" Content="Update plugins" IsVisible="False" Margin="0,0,8,6" />
|
||||
<Button x:Name="InstallCoreUpdateButton" Content="Install RynthCore update" IsVisible="False" Margin="0,0,8,6" />
|
||||
</WrapPanel>
|
||||
<ProgressBar x:Name="PluginsTabProgressBar" Minimum="0" Maximum="100" Height="6" MinHeight="6"
|
||||
IsVisible="False" Foreground="#26C1A6" Background="#0F161D" />
|
||||
<Button x:Name="ShowUpdateCardButton" Content="Updates on the Launcher tab" HorizontalAlignment="Left"
|
||||
Background="Transparent" BorderThickness="0" Padding="0" Foreground="#26C1A6" />
|
||||
<CheckBox x:Name="AutoUpdatePluginsCheckBox"
|
||||
Content="Update plugins automatically (a running bot keeps its version until AC restarts)"
|
||||
Foreground="#EAF0F4" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Background="#132028" CornerRadius="16" Padding="18">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Usage statistics" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
<CheckBox x:Name="UsageStatsCheckBox"
|
||||
Content="Help improve RynthCore: send an anonymous usage report once a day"
|
||||
Foreground="#EAF0F4" />
|
||||
<TextBlock x:Name="UsageStatsWhatText" TextWrapping="Wrap" Foreground="#9AA8B3" />
|
||||
<TextBlock x:Name="UsageStatsNeverText" TextWrapping="Wrap" Foreground="#9AA8B3" />
|
||||
<TextBlock x:Name="UsageStatsStopText" TextWrapping="Wrap" Foreground="#9AA8B3" />
|
||||
<Button x:Name="ShowUsageReportButton" Content="Show what is sent" HorizontalAlignment="Left" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Background="#132028" CornerRadius="16" Padding="18">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Plugins" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
<TextBlock Text="Manage the runtime modules loaded into RynthCore. Add plugins by browsing for their DLL file."
|
||||
<TextBlock Text="The plugins RynthCore loads. Untick one to skip it; the X takes it out of the list (its files stay on disk). RynthSuite plugins you don't have are under Available plugins below; Add Plugin is for any other plugin DLL."
|
||||
TextWrapping="Wrap"
|
||||
Foreground="#9AA8B3" />
|
||||
<StackPanel x:Name="PluginLoadoutPanel" Spacing="10" />
|
||||
<Button x:Name="AddPluginDllButton" Content="Add Plugin" HorizontalAlignment="Left" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border x:Name="AvailablePluginsBorder" Background="#132028" CornerRadius="16" Padding="18">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Available plugins" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
<TextBlock x:Name="AvailablePluginsHint"
|
||||
Text="Plugins you can add appear here after the first update check."
|
||||
TextWrapping="Wrap"
|
||||
Foreground="#9AA8B3" />
|
||||
<StackPanel x:Name="AvailablePluginsPanel" Spacing="10" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</TabItem>
|
||||
|
|
@ -362,6 +413,9 @@
|
|||
<CheckBox x:Name="EnableDcompOverlayCheckBox"
|
||||
Content="Use DComp overlay (experimental, GPU-rendered)"
|
||||
ToolTip.Tip="When ON, the engine starts the new DirectComposition overlay instead of the production AvaloniaOverlay. Mutually exclusive — Avalonia is single-app-per-process. Toggle takes effect on next AC client launch (a hot reload won't switch overlays)." />
|
||||
<CheckBox x:Name="EnableImGuiBackendCheckBox"
|
||||
Content="ImGui panels (preview)"
|
||||
ToolTip.Tip="When ON, the engine runs its in-client ImGui layer, which docked panels move to as their ImGui versions are finished (choose per panel with /rc ui). Popped-out panels stay Avalonia windows. Costs nothing while no ImGui panel is open. Takes effect on next AC client launch or engine reload (RL)." />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
|
|
@ -412,6 +466,8 @@
|
|||
<Button x:Name="RefreshSessionsButton" Content="Refresh Sessions" Margin="0,0,8,8" />
|
||||
<Button x:Name="ResetOverlayBarButton" Content="Reset Overlay Bar" Margin="0,0,8,8"
|
||||
ToolTip.Tip="Drags the in-game RynthCore overlay bar back to the top-left corner. Use this if the bar was moved off-screen and can no longer be reached. Applies to every running RynthCore client." />
|
||||
<Button x:Name="CheckDecalBridgeButton" Content="Check Decal bridge" Margin="0,0,8,8"
|
||||
ToolTip.Tip="For Decal + RynthCore (experimental): checks whether a client started now will load the RynthCore Decal bridge - where Decal reads its plugin list on this PC, whether the bridge is listed and enabled there, Decal's version and its .NET part. Changes nothing unless you press Repair." />
|
||||
</WrapPanel>
|
||||
<TextBlock Text="Manual inject target scope follows the 'Inject all running AC sessions' launch behavior toggle. Reset Overlay Bar signals all running RynthCore clients via the dispatch file."
|
||||
TextWrapping="Wrap"
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -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>()
|
||||
|
|
|
|||
|
|
@ -44,8 +44,12 @@
|
|||
<ItemGroup>
|
||||
<Compile Include="..\RynthCore.App\LaunchServerProfile.cs" Link="Shared\LaunchServerProfile.cs" />
|
||||
<Compile Include="..\RynthCore.App\LaunchAccountProfile.cs" Link="Shared\LaunchAccountProfile.cs" />
|
||||
<Compile Include="..\RynthCore.App\AccountPasswordProtection.cs" Link="Shared\AccountPasswordProtection.cs" />
|
||||
<Compile Include="..\RynthCore.App\InjectionMode.cs" Link="Shared\InjectionMode.cs" />
|
||||
<Compile Include="..\RynthCore.App\DecalLocator.cs" Link="Shared\DecalLocator.cs" />
|
||||
<Compile Include="..\RynthCore.App\DecalBridgeRegistration.cs" Link="Shared\DecalBridgeRegistration.cs" />
|
||||
<Compile Include="..\RynthCore.App\DecalBridgeCheck.cs" Link="Shared\DecalBridgeCheck.cs" />
|
||||
<Compile Include="..\RynthCore.App\RealDecalCheckHost.cs" Link="Shared\RealDecalCheckHost.cs" />
|
||||
<Compile Include="..\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="Shared\AcLaunchArgumentBuilder.cs" />
|
||||
<Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" />
|
||||
<Compile Include="..\RynthCore.App\AcClientLoginAutomationService.cs" Link="Shared\AcClientLoginAutomationService.cs" />
|
||||
|
|
@ -55,6 +59,7 @@
|
|||
<Compile Include="..\RynthCore.App\BuildVersion.cs" Link="Shared\BuildVersion.cs" />
|
||||
<Compile Include="..\RynthCore.App\AppSettings.cs" Link="Shared\AppSettings.cs" />
|
||||
<Compile Include="..\RynthCore.App\AppSettingsStore.cs" Link="Shared\AppSettingsStore.cs" />
|
||||
<Compile Include="..\RynthCore.App\DecalAccountModes.cs" Link="Shared\DecalAccountModes.cs" />
|
||||
<Compile Include="..\RynthCore.App\PluginDefinition.cs" Link="Shared\PluginDefinition.cs" />
|
||||
<Compile Include="..\RynthCore.Injector\EngineInjectionService.cs" Link="Shared\EngineInjectionService.cs" />
|
||||
<Compile Include="..\RynthCore.Injector\InjectionResult.cs" Link="Shared\InjectionResult.cs" />
|
||||
|
|
|
|||
301
src/RynthCore.App.Avalonia/RynthUpdater.Available.cs
Normal file
301
src/RynthCore.App.Avalonia/RynthUpdater.Available.cs
Normal 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\<Name>\<File> - the folder beside RynthAi's, or the
|
||||
/// default - and the caller adds it to the plugin list. Only plugins named in the signed manifest
|
||||
/// can be installed, from the URLs it carries; nothing else.
|
||||
///
|
||||
/// Removing a plugin from the list never deletes its files; a feed plugin that leaves the list is
|
||||
/// simply available again.
|
||||
///
|
||||
/// "New": a plugin the launcher sees in the feed for the first time is marked New for a month and
|
||||
/// said once in the activity log. The first time this runs (no update-seen-plugins.json yet),
|
||||
/// what the feed already had counts as old except <see cref="RecentlyAdded"/>, which a player
|
||||
/// who never got them should hear about.
|
||||
/// </summary>
|
||||
internal sealed partial class RynthUpdater
|
||||
{
|
||||
public const string DefaultSuiteDir = @"C:\Games\RynthSuite";
|
||||
private const string RynthAiFile = "RynthCore.Plugin.RynthAi.dll";
|
||||
private const int MaxDescriptionLength = 160;
|
||||
private const int MaxChanges = 20;
|
||||
private static readonly TimeSpan NewBadgeFor = TimeSpan.FromDays(30);
|
||||
private static readonly Regex SafeFolderName = new(@"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>A feed plugin the player can install: where it would go, what it is, and whether it's new.</summary>
|
||||
public sealed record AvailablePlugin(PluginEntry Entry, string Path, string Description, string Version, bool IsNew);
|
||||
|
||||
/// <summary>What <see cref="InstallPluginAsync"/> did: Downloaded is false when a good copy was already there.</summary>
|
||||
public sealed record PluginInstall(PluginEntry Entry, string Path, string Description, bool Downloaded);
|
||||
|
||||
/// <summary>
|
||||
/// Plugins new in the feed before this list existed (2026.10.3.4). 2026.10.4.3 installed them
|
||||
/// beside RynthAi automatically; from this launcher on they are offered, not forced.
|
||||
/// </summary>
|
||||
private static readonly string[] RecentlyAdded = { "RynthOracle", "RynthInventory" };
|
||||
|
||||
/// <summary>One line per plugin for feeds that carry no "description" (every feed before 2026.10.5).</summary>
|
||||
private static readonly Dictionary<string, string> BuiltInDescriptions = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["RynthAi"] = "The bot: combat, buffs, looting, navigation routes and metas.",
|
||||
["RynthChat"] = "A chat window that sorts messages into tabs.",
|
||||
["RynthTracker"] = "Kills, experience and luminance per hour for each session.",
|
||||
["RynthNav"] = "Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB).",
|
||||
["RynthVision"] = "Shows unclimbable slopes, impassable water and your radar range in the world.",
|
||||
["RynthLua"] = "Lua scripting for metas and your own scripts.",
|
||||
["RynthOracle"] = "Quests, character, titles and leaderboards.",
|
||||
["RynthInventory"] = "Search every character's items.",
|
||||
};
|
||||
|
||||
/// <summary>The feed's description, else the launcher's own line, else "".</summary>
|
||||
public static string DescribePlugin(PluginEntry e) =>
|
||||
e.Description.Length > 0 ? e.Description
|
||||
: BuiltInDescriptions.TryGetValue(e.Name, out string? d) ? d : "";
|
||||
|
||||
private string? _suiteDirOverride;
|
||||
/// <summary>Tests: the folder to use when no plugin in the list shows where RynthSuite lives.</summary>
|
||||
internal void SetDefaultSuiteDir(string dir) => _suiteDirOverride = dir;
|
||||
/// <summary>Tests: the clock for the New badge.</summary>
|
||||
internal Func<DateTime> UtcNow { get; set; } = () => DateTime.UtcNow;
|
||||
|
||||
/// <summary>
|
||||
/// Where RynthSuite plugins go: beside RynthAi (C:\Games\RynthSuite\RynthAi\x.dll -> C:\Games\RynthSuite),
|
||||
/// else beside any feed plugin that sits in a folder named after it, else the default.
|
||||
/// </summary>
|
||||
public string SuiteDir(Manifest manifest, IEnumerable<string> pluginPaths)
|
||||
{
|
||||
List<string> paths = pluginPaths.ToList();
|
||||
string? FromPlugin(string path)
|
||||
{
|
||||
string? folder = Path.GetDirectoryName(path);
|
||||
string? suite = Path.GetDirectoryName(folder);
|
||||
return string.IsNullOrEmpty(folder) || string.IsNullOrEmpty(suite) ? null : suite;
|
||||
}
|
||||
string? ai = paths.FirstOrDefault(p => string.Equals(Path.GetFileName(p), RynthAiFile, StringComparison.OrdinalIgnoreCase));
|
||||
if (ai != null && FromPlugin(ai) is { } s1) return s1;
|
||||
foreach (string p in paths)
|
||||
{
|
||||
PluginEntry? e = manifest.Plugins.FirstOrDefault(x => string.Equals(x.File, Path.GetFileName(p), StringComparison.OrdinalIgnoreCase));
|
||||
if (e != null && string.Equals(Path.GetFileName(Path.GetDirectoryName(p)), e.Name, StringComparison.OrdinalIgnoreCase)
|
||||
&& FromPlugin(p) is { } s2)
|
||||
return s2;
|
||||
}
|
||||
return _suiteDirOverride ?? DefaultSuiteDir;
|
||||
}
|
||||
|
||||
/// <summary>C:\Games\RynthSuite\<Name>\<File>; null for a name that isn't a plain folder name.</summary>
|
||||
private static string? TargetPath(PluginEntry e, string suiteDir) =>
|
||||
SafeFolderName.IsMatch(e.Name) && e.Name != "." && e.Name != ".." ? Path.Combine(suiteDir, e.Name, e.File) : null;
|
||||
|
||||
/// <summary>
|
||||
/// Every feed plugin whose file isn't in <paramref name="pluginPaths"/> (by file name, like the
|
||||
/// updates), except companions about to be installed anyway.
|
||||
/// </summary>
|
||||
public List<AvailablePlugin> GetAvailable(Manifest manifest, IEnumerable<string> pluginPaths, IEnumerable<CompanionInstall>? pending = null)
|
||||
{
|
||||
List<string> paths = pluginPaths.ToList();
|
||||
var listed = new HashSet<string>(paths.Select(Path.GetFileName).OfType<string>(), StringComparer.OrdinalIgnoreCase);
|
||||
var skip = new HashSet<string>((pending ?? Array.Empty<CompanionInstall>()).Select(c => c.Entry.File), StringComparer.OrdinalIgnoreCase);
|
||||
string suite = SuiteDir(manifest, paths);
|
||||
Dictionary<string, DateTime> seen = ReadSeenPlugins(out _);
|
||||
DateTime now = UtcNow();
|
||||
var result = new List<AvailablePlugin>();
|
||||
foreach (PluginEntry e in manifest.Plugins)
|
||||
{
|
||||
if (listed.Contains(e.File) || skip.Contains(e.File)) continue;
|
||||
if (TargetPath(e, suite) is not { } target) continue;
|
||||
bool isNew = seen.TryGetValue(e.Name, out DateTime first) && now - first < NewBadgeFor;
|
||||
result.Add(new AvailablePlugin(e, target, DescribePlugin(e), manifest.Version, isNew));
|
||||
}
|
||||
// New ones first, then by name.
|
||||
return result.OrderByDescending(a => a.IsNew).ThenBy(a => a.Entry.Name, StringComparer.OrdinalIgnoreCase).ToList();
|
||||
}
|
||||
|
||||
/// <summary>The Available list for a check, against the plugin list as it is now.</summary>
|
||||
public List<AvailablePlugin> GetAvailable(CheckResult check, IEnumerable<string> pluginPaths) =>
|
||||
GetAvailable(check.Manifest, pluginPaths, check.Companions);
|
||||
|
||||
/// <summary>
|
||||
/// Installs one plugin from the signed feed for the caller to add to the plugin list. A file
|
||||
/// already at the target is kept when it is the release build or newer (someone's own build);
|
||||
/// an older one is replaced and kept beside it as .previous. Throws, with nothing changed,
|
||||
/// when the download doesn't match the signed size and hash or is cancelled.
|
||||
/// </summary>
|
||||
public async Task<PluginInstall> InstallPluginAsync(CheckResult check, string name, IEnumerable<string> pluginPaths,
|
||||
IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
|
||||
{
|
||||
List<string> paths = pluginPaths.ToList();
|
||||
PluginEntry e = check.Manifest.Plugins.FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))
|
||||
?? throw new InvalidOperationException($"{name} is not in the update feed");
|
||||
if (paths.Any(p => string.Equals(Path.GetFileName(p), e.File, StringComparison.OrdinalIgnoreCase)))
|
||||
throw new InvalidOperationException($"{e.Name} is already in your plugin list");
|
||||
string target = TargetPath(e, SuiteDir(check.Manifest, paths))
|
||||
?? throw new InvalidDataException($"bad plugin name '{e.Name}' in the feed");
|
||||
|
||||
if (File.Exists(target))
|
||||
{
|
||||
bool same = string.Equals(Sha256File(target), e.Sha256, StringComparison.OrdinalIgnoreCase);
|
||||
bool localBuild = File.GetLastWriteTimeUtc(target) > check.Manifest.PublishedUtc.AddMinutes(1);
|
||||
if (same || localBuild)
|
||||
return new PluginInstall(e, target, DescribePlugin(e), Downloaded: false);
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll");
|
||||
try
|
||||
{
|
||||
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct, e.Name, progress);
|
||||
progress?.Report(new DownloadProgress(e.Name, DownloadStage.Installing, 0, 0));
|
||||
// Stamp the release time so a later check never mistakes it for a local build.
|
||||
File.SetLastWriteTimeUtc(temp, check.Manifest.PublishedUtc);
|
||||
if (File.Exists(target)) File.Copy(target, target + ".previous", overwrite: true);
|
||||
File.Move(temp, target, overwrite: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { File.Delete(temp); } catch { }
|
||||
}
|
||||
return new PluginInstall(e, target, DescribePlugin(e), Downloaded: true);
|
||||
}
|
||||
|
||||
// ── Manifest fields (optional, backward-compatible) ───────────────────────
|
||||
|
||||
/// <summary>The plugin entry's optional "description": one line, plain text, at most 160 characters.</summary>
|
||||
private static string ReadDescription(JsonElement p)
|
||||
{
|
||||
if (!p.TryGetProperty("description", out JsonElement d) || d.ValueKind != JsonValueKind.String) return "";
|
||||
return OneLine(d.GetString(), MaxDescriptionLength);
|
||||
}
|
||||
|
||||
/// <summary>The manifest's optional "changes": up to 20 lines.</summary>
|
||||
private static IReadOnlyList<string> ReadChanges(JsonElement r)
|
||||
{
|
||||
if (!r.TryGetProperty("changes", out JsonElement c) || c.ValueKind != JsonValueKind.Array) return Array.Empty<string>();
|
||||
var list = new List<string>();
|
||||
foreach (JsonElement e in c.EnumerateArray())
|
||||
{
|
||||
if (e.ValueKind != JsonValueKind.String) continue;
|
||||
string line = OneLine(e.GetString(), 300);
|
||||
if (line.Length > 0) list.Add(line);
|
||||
if (list.Count >= MaxChanges) break;
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static string OneLine(string? s, int max)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(s)) return "";
|
||||
var sb = new StringBuilder(Math.Min(s.Length, max + 1));
|
||||
bool space = false;
|
||||
foreach (char ch in s)
|
||||
{
|
||||
if (char.IsWhiteSpace(ch) || char.IsControl(ch)) { space = sb.Length > 0; continue; }
|
||||
if (space) { sb.Append(' '); space = false; }
|
||||
sb.Append(ch);
|
||||
if (sb.Length > max) break;
|
||||
}
|
||||
string line = sb.ToString();
|
||||
return line.Length > max ? line[..(max - 1)].TrimEnd() + "…" : line;
|
||||
}
|
||||
|
||||
// ── Seen plugins (the New badge) ──────────────────────────────────────────
|
||||
|
||||
private string SeenPath => Path.Combine(_stateDir, "update-seen-plugins.json");
|
||||
|
||||
private Dictionary<string, DateTime> ReadSeenPlugins(out bool existed)
|
||||
{
|
||||
var map = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
|
||||
existed = false;
|
||||
try
|
||||
{
|
||||
if (!File.Exists(SeenPath)) return map;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(SeenPath));
|
||||
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
|
||||
if (p.Value.ValueKind == JsonValueKind.String && DateTime.TryParse(p.Value.GetString(), null,
|
||||
System.Globalization.DateTimeStyles.AdjustToUniversal | System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime t))
|
||||
map[p.Name] = t;
|
||||
existed = true;
|
||||
}
|
||||
catch { map.Clear(); existed = false; }
|
||||
return map;
|
||||
}
|
||||
|
||||
/// <summary>Records the feed's plugins as seen; returns the ones seen for the first time that count as new.</summary>
|
||||
private HashSet<string> RecordSeenPlugins(Manifest manifest)
|
||||
{
|
||||
var fresh = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
Dictionary<string, DateTime> seen = ReadSeenPlugins(out bool existed);
|
||||
HashSet<string> offered = ReadOfferedCompanions();
|
||||
DateTime now = UtcNow();
|
||||
bool changed = !existed;
|
||||
foreach (PluginEntry e in manifest.Plugins)
|
||||
{
|
||||
if (seen.ContainsKey(e.Name)) continue;
|
||||
// First run of this list: only the recent additions are news, and not to a player who
|
||||
// already had them offered (2026.10.4.3 installed them; removing one keeps it removed).
|
||||
bool isNew = existed || (RecentlyAdded.Contains(e.Name, StringComparer.OrdinalIgnoreCase) && !offered.Contains(e.Name));
|
||||
seen[e.Name] = isNew ? now : DateTime.UnixEpoch;
|
||||
if (isNew) fresh.Add(e.Name);
|
||||
changed = true;
|
||||
}
|
||||
if (changed)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(_stateDir);
|
||||
string tmp = SeenPath + ".tmp";
|
||||
var ordered = seen.OrderBy(kv => kv.Key, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(kv => kv.Key, kv => kv.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"));
|
||||
File.WriteAllText(tmp, JsonSerializer.Serialize(ordered, new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8);
|
||||
File.Move(tmp, SeenPath, overwrite: true);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Edits to the launcher's plugin list (kept apart from the window so tests can run them).</summary>
|
||||
internal static class PluginListEdits
|
||||
{
|
||||
/// <summary>Adds <paramref name="path"/> once; false when it was already listed.</summary>
|
||||
public static bool Add(IList<string> paths, string path)
|
||||
{
|
||||
if (paths.Any(p => string.Equals(p, path, StringComparison.OrdinalIgnoreCase))) return false;
|
||||
paths.Add(path);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes <paramref name="path"/> out of the list, and out of the disabled list so adding it back
|
||||
/// later starts it enabled. Never touches the file.
|
||||
/// </summary>
|
||||
public static bool Remove(IList<string> paths, IList<string>? disabled, string path)
|
||||
{
|
||||
bool removed = RemoveAll(paths, path) > 0;
|
||||
if (disabled != null) RemoveAll(disabled, path);
|
||||
return removed;
|
||||
}
|
||||
|
||||
private static int RemoveAll(IList<string> list, string path)
|
||||
{
|
||||
int n = 0;
|
||||
for (int i = list.Count - 1; i >= 0; i--)
|
||||
if (string.Equals(list[i], path, StringComparison.OrdinalIgnoreCase)) { list.RemoveAt(i); n++; }
|
||||
return n;
|
||||
}
|
||||
}
|
||||
298
src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs
Normal file
298
src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs
Normal 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); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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()
|
||||
{
|
||||
|
|
|
|||
153
src/RynthCore.App.Avalonia/UpdateCardModel.cs
Normal file
153
src/RynthCore.App.Avalonia/UpdateCardModel.cs
Normal 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}";
|
||||
}
|
||||
}
|
||||
292
src/RynthCore.App.Avalonia/UsageStats.cs
Normal file
292
src/RynthCore.App.Avalonia/UsageStats.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
121
src/RynthCore.App.Avalonia/UsageStatsDialog.cs
Normal file
121
src/RynthCore.App.Avalonia/UsageStatsDialog.cs
Normal 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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -6,6 +6,14 @@ namespace RynthCore.App;
|
|||
|
||||
internal sealed class AcLaunchArgumentBuilder
|
||||
{
|
||||
/// <summary>Text shown in place of the password in previews.</summary>
|
||||
public const string PasswordMask = "********";
|
||||
|
||||
/// <summary>
|
||||
/// The client's command line, with the saved password decrypted now. The result carries the
|
||||
/// password: hand it to the process and never log, display or keep it. Throws when the saved
|
||||
/// password can't be decrypted on this Windows user (never launches with an empty one instead).
|
||||
/// </summary>
|
||||
public string BuildArguments(LaunchServerProfile server, LaunchAccountProfile account)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(server);
|
||||
|
|
@ -13,17 +21,42 @@ internal sealed class AcLaunchArgumentBuilder
|
|||
|
||||
Validate(server, account);
|
||||
|
||||
if (!account.TryGetPasswordForLaunch(out string password, out string problem))
|
||||
throw new InvalidOperationException(problem);
|
||||
|
||||
return Build(server, account, password);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The same command line for display: the password is never decrypted, a saved one shows as
|
||||
/// <see cref="PasswordMask"/>.
|
||||
/// </summary>
|
||||
public string BuildMaskedArguments(LaunchServerProfile server, LaunchAccountProfile account)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(server);
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
|
||||
Validate(server, account);
|
||||
|
||||
if (account.PasswordNeedsReentry)
|
||||
return LaunchAccountProfile.PasswordNeedsReentryMessage(account.AccountName);
|
||||
|
||||
return Build(server, account, account.HasSavedPassword ? PasswordMask : string.Empty);
|
||||
}
|
||||
|
||||
private static string Build(LaunchServerProfile server, LaunchAccountProfile account, string password)
|
||||
{
|
||||
return server.Emulator switch
|
||||
{
|
||||
AcEmulatorKind.Ace => string.Join(" ",
|
||||
"-a", Quote(account.AccountName),
|
||||
"-v", Quote(account.Password),
|
||||
"-v", Quote(password),
|
||||
"-h", Quote(server.ConnectionString),
|
||||
"-rodat", server.RodatEnabled ? "on" : "off"),
|
||||
AcEmulatorKind.Gdle => string.Join(" ",
|
||||
"-h", Quote(server.Host),
|
||||
"-p", server.Port.ToString(CultureInfo.InvariantCulture),
|
||||
"-a", Quote($"{account.AccountName}:{account.Password}"),
|
||||
"-a", Quote($"{account.AccountName}:{password}"),
|
||||
"-rodat", server.RodatEnabled ? "on" : "off"),
|
||||
_ => throw new InvalidOperationException($"Unsupported emulator type '{server.Emulator}'.")
|
||||
};
|
||||
|
|
|
|||
138
src/RynthCore.App/AccountPasswordProtection.cs
Normal file
138
src/RynthCore.App/AccountPasswordProtection.cs
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.App;
|
||||
|
||||
/// <summary>
|
||||
/// Saved account passwords are encrypted with Windows DPAPI (CryptProtectData, CurrentUser
|
||||
/// scope, the same call System.Security.Cryptography.ProtectedData makes) plus an app-specific
|
||||
/// entropy constant, and kept in settings as base64 (LaunchAccountProfile.PasswordProtected).
|
||||
/// Only the Windows user that saved a password can decrypt it; settings copied to another user
|
||||
/// or PC can't be decrypted, and such an account shows "password needs re-entering".
|
||||
///
|
||||
/// Decrypt only at the moment of use (building the client's launch arguments) and never keep
|
||||
/// the result in a long-lived object. Never log, display or copy a password.
|
||||
///
|
||||
/// Shared source: compiled into the launcher, RynthCore.Injector (--launch) and
|
||||
/// tools\LauncherSettingsTests.
|
||||
/// </summary>
|
||||
internal static class AccountPasswordProtection
|
||||
{
|
||||
// Changing this makes every saved password unreadable. Bump the suffix only with a migration.
|
||||
private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("RynthCore.Launcher.AccountPassword.v1");
|
||||
|
||||
private const int CryptProtectUiForbidden = 0x1;
|
||||
|
||||
/// <summary>Encrypts a password for this Windows user. Empty in, empty out.</summary>
|
||||
public static string Protect(string? plainText)
|
||||
{
|
||||
if (string.IsNullOrEmpty(plainText))
|
||||
return string.Empty;
|
||||
|
||||
byte[] plain = Encoding.UTF8.GetBytes(plainText);
|
||||
try
|
||||
{
|
||||
return Convert.ToBase64String(Transform(plain, protect: true));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Array.Clear(plain);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decrypts a value written by <see cref="Protect"/>. False when it can't be read on this
|
||||
/// Windows user (copied from another user or PC, damaged base64, wrong entropy).
|
||||
/// </summary>
|
||||
public static bool TryUnprotect(string? protectedBase64, out string plainText)
|
||||
{
|
||||
plainText = string.Empty;
|
||||
if (string.IsNullOrEmpty(protectedBase64))
|
||||
return false;
|
||||
|
||||
byte[] blob;
|
||||
try
|
||||
{
|
||||
blob = Convert.FromBase64String(protectedBase64);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
byte[]? plain = null;
|
||||
try
|
||||
{
|
||||
plain = Transform(blob, protect: false);
|
||||
plainText = Encoding.UTF8.GetString(plain);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is Win32Exception or PlatformNotSupportedException or EntryPointNotFoundException or DllNotFoundException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (plain != null)
|
||||
Array.Clear(plain);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when the value decrypts on this Windows user (the password itself is discarded).</summary>
|
||||
public static bool CanUnprotect(string? protectedBase64) => TryUnprotect(protectedBase64, out _);
|
||||
|
||||
private static byte[] Transform(byte[] input, bool protect)
|
||||
{
|
||||
GCHandle inputHandle = GCHandle.Alloc(input, GCHandleType.Pinned);
|
||||
GCHandle entropyHandle = GCHandle.Alloc(Entropy, GCHandleType.Pinned);
|
||||
var output = new DataBlob();
|
||||
try
|
||||
{
|
||||
var inputBlob = new DataBlob { cbData = input.Length, pbData = inputHandle.AddrOfPinnedObject() };
|
||||
var entropyBlob = new DataBlob { cbData = Entropy.Length, pbData = entropyHandle.AddrOfPinnedObject() };
|
||||
|
||||
bool ok = protect
|
||||
? CryptProtectData(ref inputBlob, null, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output)
|
||||
: CryptUnprotectData(ref inputBlob, IntPtr.Zero, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output);
|
||||
if (!ok)
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
|
||||
byte[] result = new byte[output.cbData];
|
||||
if (output.cbData > 0)
|
||||
Marshal.Copy(output.pbData, result, 0, output.cbData);
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (output.pbData != IntPtr.Zero)
|
||||
{
|
||||
// Wipe the native copy (the plain text, when decrypting) before freeing it.
|
||||
for (int i = 0; i < output.cbData; i++)
|
||||
Marshal.WriteByte(output.pbData, i, 0);
|
||||
LocalFree(output.pbData);
|
||||
}
|
||||
inputHandle.Free();
|
||||
entropyHandle.Free();
|
||||
}
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct DataBlob
|
||||
{
|
||||
public int cbData;
|
||||
public IntPtr pbData;
|
||||
}
|
||||
|
||||
[DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
private static extern bool CryptProtectData(ref DataBlob pDataIn, string? szDataDescr, ref DataBlob pOptionalEntropy,
|
||||
IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut);
|
||||
|
||||
[DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
private static extern bool CryptUnprotectData(ref DataBlob pDataIn, IntPtr ppszDataDescr, ref DataBlob pOptionalEntropy,
|
||||
IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern IntPtr LocalFree(IntPtr hMem);
|
||||
}
|
||||
|
|
@ -29,6 +29,13 @@ internal sealed class AppSettings
|
|||
/// with; the new one loads on the next AC start. Core updates always ask first.
|
||||
public bool AutoUpdatePlugins { get; set; } = true;
|
||||
|
||||
/// "Help improve RynthCore": one anonymous usage report a day (see the launcher's
|
||||
/// UsageStats.cs for exactly what is sent). OFF unless the player turns it on.
|
||||
public bool UsageStatsEnabled { get; set; }
|
||||
|
||||
/// True once the launcher has explained usage statistics and asked (shown once).
|
||||
public bool UsageStatsAsked { get; set; }
|
||||
|
||||
/// When true, the launcher kills any RynthCore-mode acclient.exe it
|
||||
/// launched that hasn't reached IsLoggedIn within
|
||||
/// <see cref="StuckClientTimeoutSeconds"/>. Catches stuck char-select,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
|
|
@ -12,15 +14,22 @@ internal static class AppSettingsStore
|
|||
WriteIndented = true,
|
||||
Converters =
|
||||
{
|
||||
// Before the general enum converter: InjectionMode is written so that every
|
||||
// launcher can read it ("Decal + RynthCore" lives in decal-accounts.json).
|
||||
new SharedInjectionModeConverter(),
|
||||
new JsonStringEnumConverter()
|
||||
}
|
||||
};
|
||||
|
||||
private static string SettingsDirectory =>
|
||||
/// <summary>Tests only (tools\LauncherSettingsTests): a folder used instead of %APPDATA%\RynthCore.</summary>
|
||||
internal static string? DirectoryOverride { get; set; }
|
||||
|
||||
private static string SettingsDirectory => DirectoryOverride ??
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
|
||||
|
||||
private static string SettingsPath => Path.Combine(SettingsDirectory, "appsettings.json");
|
||||
private static string BackupPath => SettingsPath + ".bak";
|
||||
private static string DecalAccountsPath => DecalAccountModes.PathIn(SettingsDirectory);
|
||||
|
||||
/// <summary>
|
||||
/// Set when the last Load() hit a corrupt/unreadable file (quarantined it,
|
||||
|
|
@ -30,10 +39,123 @@ internal static class AppSettingsStore
|
|||
/// </summary>
|
||||
public static string? LastLoadDiagnostic { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Set when the last Load() moved "Decal + RynthCore" accounts out of appsettings.json
|
||||
/// into decal-accounts.json (a file written by a pre-release Decal bridge build), or found
|
||||
/// decal-accounts.json unreadable. Null otherwise.
|
||||
/// </summary>
|
||||
public static string? LastMigrationNote { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Set when the last Load() encrypted plain-text account passwords from an older settings
|
||||
/// file ("migrated N account password(s) to encrypted storage"), or could not. Never holds a
|
||||
/// password. Null otherwise.
|
||||
/// </summary>
|
||||
public static string? LastPasswordMigrationNote { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Set when the last Load() found saved passwords this Windows user can't decrypt (settings
|
||||
/// copied from another user or PC); those accounts have PasswordNeedsReentry set. Null otherwise.
|
||||
/// </summary>
|
||||
public static string? LastPasswordProblemNote { get; private set; }
|
||||
|
||||
public static AppSettings Load()
|
||||
{
|
||||
LastLoadDiagnostic = null;
|
||||
LastMigrationNote = null;
|
||||
LastPasswordMigrationNote = null;
|
||||
LastPasswordProblemNote = null;
|
||||
// Passwords after the Decal accounts: a save before ApplyDecalAccounts would drop
|
||||
// decal-accounts.json (every account still reads as RynthCore at that point).
|
||||
AppSettings settings = ApplyDecalAccounts(LoadShared());
|
||||
MigratePasswords(settings);
|
||||
return settings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Encrypts plain-text passwords from an older appsettings.json (LaunchAccountProfile
|
||||
/// "Password") into PasswordProtected and saves once, .bak included, so the plain text is
|
||||
/// gone from both files. Also marks accounts whose encrypted password this Windows user can't
|
||||
/// decrypt. Never logs or reports a password.
|
||||
/// </summary>
|
||||
private static void MigratePasswords(AppSettings settings)
|
||||
{
|
||||
int migrated = 0, cleared = 0, failed = 0;
|
||||
var unreadable = new List<string>();
|
||||
foreach (LaunchAccountProfile account in settings.AccountProfiles ?? new List<LaunchAccountProfile>())
|
||||
{
|
||||
if (account.LegacyPlainPassword != null)
|
||||
{
|
||||
if (account.LegacyPlainPassword.Length == 0)
|
||||
{
|
||||
account.LegacyPlainPassword = null;
|
||||
cleared++;
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
account.PasswordProtected = AccountPasswordProtection.Protect(account.LegacyPlainPassword);
|
||||
account.LegacyPlainPassword = null;
|
||||
account.PasswordNeedsReentry = false;
|
||||
migrated++;
|
||||
}
|
||||
catch
|
||||
{
|
||||
failed++; // kept as it was (still usable); the next load tries again
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(account.PasswordProtected) &&
|
||||
!AccountPasswordProtection.CanUnprotect(account.PasswordProtected))
|
||||
{
|
||||
account.PasswordNeedsReentry = true;
|
||||
unreadable.Add(string.IsNullOrWhiteSpace(account.AccountName) ? account.Id : account.AccountName);
|
||||
}
|
||||
}
|
||||
|
||||
if (unreadable.Count > 0)
|
||||
{
|
||||
LastPasswordProblemNote = $"{unreadable.Count} saved account password(s) can't be decrypted on this Windows user " +
|
||||
$"(settings copied from another user or PC?) and need re-entering: {string.Join(", ", unreadable)}.";
|
||||
}
|
||||
|
||||
if (migrated + cleared == 0)
|
||||
{
|
||||
if (failed > 0)
|
||||
LastPasswordMigrationNote = $"Could not encrypt {failed} account password(s); they stay as they were and the next start tries again.";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Save(settings);
|
||||
// Save() moved the old file (plain text) to .bak: replace it with the encrypted one.
|
||||
File.Copy(SettingsPath, BackupPath, overwrite: true);
|
||||
if (migrated == 0 && failed == 0)
|
||||
return; // only empty plain-text fields removed
|
||||
LastPasswordMigrationNote = $"migrated {migrated} account password(s) to encrypted storage";
|
||||
if (failed > 0)
|
||||
LastPasswordMigrationNote += $"; {failed} could not be encrypted and stay as they were";
|
||||
int quarantined = CountQuarantinedFiles();
|
||||
if (quarantined > 0)
|
||||
LastPasswordMigrationNote += $". {quarantined} older appsettings.json.corrupt-* file(s) in {SettingsDirectory} " +
|
||||
"may still hold plain-text passwords; delete them when no longer needed";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LastPasswordMigrationNote = $"Could not save the encrypted account passwords ({ex.GetType().Name}); the next save retries.";
|
||||
}
|
||||
}
|
||||
|
||||
private static int CountQuarantinedFiles()
|
||||
{
|
||||
try { return Directory.GetFiles(SettingsDirectory, "appsettings.json.corrupt-*").Length; }
|
||||
catch { return 0; }
|
||||
}
|
||||
|
||||
private static AppSettings LoadShared()
|
||||
{
|
||||
if (!File.Exists(SettingsPath))
|
||||
return new AppSettings();
|
||||
|
||||
|
|
@ -85,13 +207,56 @@ internal static class AppSettingsStore
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts back the "Decal + RynthCore" accounts listed in decal-accounts.json (those that
|
||||
/// appsettings.json still lists as RynthCore). An appsettings.json that itself says
|
||||
/// "DecalBridge" (written by a pre-release bridge build) is rewritten at once, .bak
|
||||
/// included, so no launcher finds that value there again.
|
||||
/// </summary>
|
||||
private static AppSettings ApplyDecalAccounts(AppSettings settings)
|
||||
{
|
||||
List<LaunchAccountProfile> accounts = settings.AccountProfiles ?? new List<LaunchAccountProfile>();
|
||||
int legacy = accounts.Count(a => a.InjectionMode == InjectionMode.DecalBridge);
|
||||
|
||||
HashSet<string> ids = DecalAccountModes.ReadIds(DecalAccountsPath, out string? error);
|
||||
if (error != null)
|
||||
LastMigrationNote = error;
|
||||
foreach (LaunchAccountProfile account in accounts)
|
||||
if (DecalAccountModes.IsDecalBridge(ids, account.Id, account.InjectionMode))
|
||||
account.InjectionMode = InjectionMode.DecalBridge;
|
||||
|
||||
if (legacy > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
Save(settings);
|
||||
File.Copy(SettingsPath, BackupPath, overwrite: true);
|
||||
LastMigrationNote = $"Moved {legacy} \"Decal + RynthCore\" account(s) from appsettings.json to " +
|
||||
$"{DecalAccountModes.FileName}, so older launchers can still read appsettings.json.";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LastMigrationNote = $"Could not move \"Decal + RynthCore\" accounts to {DecalAccountModes.FileName} " +
|
||||
$"({ex.GetType().Name}: {ex.Message}); the next save retries.";
|
||||
}
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
public static void Save(AppSettings settings)
|
||||
{
|
||||
// "Decal + RynthCore" accounts go to decal-accounts.json first; appsettings.json
|
||||
// lists them as RynthCore (SharedInjectionModeConverter).
|
||||
Directory.CreateDirectory(SettingsDirectory);
|
||||
DecalAccountModes.WriteIds(DecalAccountsPath,
|
||||
(settings.AccountProfiles ?? new List<LaunchAccountProfile>())
|
||||
.Where(a => a.InjectionMode == InjectionMode.DecalBridge)
|
||||
.Select(a => a.Id));
|
||||
|
||||
// Atomic write: serialize to a temp file, then swap it in. A crash or
|
||||
// power cut mid-write can no longer truncate the live file (which holds
|
||||
// every server/account profile and is rewritten constantly); the swap
|
||||
// also maintains a .bak Load() can recover from.
|
||||
Directory.CreateDirectory(SettingsDirectory);
|
||||
string tmp = SettingsPath + ".tmp";
|
||||
File.WriteAllText(tmp, JsonSerializer.Serialize(settings, JsonOptions));
|
||||
if (File.Exists(SettingsPath))
|
||||
|
|
@ -99,4 +264,32 @@ internal static class AppSettingsStore
|
|||
else
|
||||
File.Move(tmp, SettingsPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// InjectionMode in appsettings.json. Writes only names every launcher knows: DecalBridge is
|
||||
/// written as <see cref="DecalAccountModes.SharedMode"/> (decal-accounts.json holds the real
|
||||
/// choice). Reads names and numbers; a name or number this build doesn't know reads as RynthCore
|
||||
/// instead of making the whole file unreadable.
|
||||
/// </summary>
|
||||
private sealed class SharedInjectionModeConverter : JsonConverter<InjectionMode>
|
||||
{
|
||||
public override InjectionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt32(out int number))
|
||||
return Enum.IsDefined((InjectionMode)number) ? (InjectionMode)number : InjectionMode.RynthCore;
|
||||
if (reader.TokenType == JsonTokenType.String)
|
||||
{
|
||||
return Enum.TryParse(reader.GetString(), ignoreCase: true, out InjectionMode mode) && Enum.IsDefined(mode)
|
||||
? mode
|
||||
: InjectionMode.RynthCore;
|
||||
}
|
||||
throw new JsonException($"InjectionMode: unexpected {reader.TokenType}.");
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, InjectionMode value, JsonSerializerOptions options)
|
||||
{
|
||||
InjectionMode shared = value == InjectionMode.DecalBridge ? DecalAccountModes.SharedMode : value;
|
||||
writer.WriteStringValue(shared.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
|
||||
|
|
|
|||
113
src/RynthCore.App/DecalAccountModes.cs
Normal file
113
src/RynthCore.App/DecalAccountModes.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
495
src/RynthCore.App/DecalBridgeCheck.cs
Normal file
495
src/RynthCore.App/DecalBridgeCheck.cs
Normal 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\<group>: the per-user
|
||||
/// VirtualStore copy when it is virtualized and the copy exists, else the real HKLM key.
|
||||
/// </summary>
|
||||
public static (RegRoot Root, string Path, bool PerUser) WhereDecalReads(IDecalCheckHost host, bool clientVirtualized, string group)
|
||||
{
|
||||
if (clientVirtualized)
|
||||
{
|
||||
string vs = VirtualStoreDecalPath(host.Is64BitOs, group);
|
||||
using IRegKey? k = host.OpenReal(RegRoot.User64, vs);
|
||||
if (k != null)
|
||||
return (RegRoot.User64, vs, true);
|
||||
}
|
||||
return (RegRoot.Machine32, MachineDecalPath(group), false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the installer (and every update) writes, so a client finds the bridge whatever
|
||||
/// its rights (installer\RynthCore.iss: <see cref="DecalBridgeRegistration.RegisterMachineWide"/>
|
||||
/// elevated, <see cref="DecalBridgeRegistration.InstallPerUser"/> as the installing user):
|
||||
/// - Machine: always (when Decal is installed). Elevated and unvirtualized clients read
|
||||
/// only HKLM; a virtualized client without a per-user copy reads HKLM too.
|
||||
/// - PerUser: only into a per-user copy that ALREADY exists. A virtualized client then
|
||||
/// reads that copy and nothing else, so the HKLM entry is hidden from it. Creating a
|
||||
/// copy that doesn't exist would be harmful: it would hide every HKLM filter added later
|
||||
/// (a Decal plugin installed for all users) from this user's non-elevated clients.
|
||||
/// </summary>
|
||||
public static (bool Machine, bool PerUser) PlanInstall(IDecalCheckHost host)
|
||||
{
|
||||
bool decal = StringOf(host, RegRoot.Machine32, MachineDecalPath("Agent"), "AgentPath") != null;
|
||||
if (!decal) return (false, false);
|
||||
using IRegKey? copy = host.OpenReal(RegRoot.User64, VirtualStoreDecalPath(host.Is64BitOs, "NetworkFilters"));
|
||||
return (true, copy != null);
|
||||
}
|
||||
|
||||
public static string Describe(bool is64BitOs, RegRoot root, string path) => root switch
|
||||
{
|
||||
RegRoot.Machine32 => is64BitOs ? @"HKLM\SOFTWARE\WOW6432Node\" + path.Substring("SOFTWARE\\".Length) : @"HKLM\" + path,
|
||||
RegRoot.Machine64 => @"HKLM\" + path,
|
||||
_ => @"HKCU\" + path,
|
||||
};
|
||||
|
||||
/// <summary>Runs every check. Reads only; changes nothing.</summary>
|
||||
public static Result Run(IDecalCheckHost host, string bridgeDirectory, string? acClientPath, string? engineJsonPath)
|
||||
{
|
||||
var r = new Result();
|
||||
string dir = bridgeDirectory.TrimEnd('\\');
|
||||
|
||||
// 1. Decal and its version.
|
||||
string? agentPath = StringOf(host, RegRoot.Machine32, MachineDecalPath("Agent"), "AgentPath");
|
||||
r.DecalInstalled = agentPath != null && host.FileExists(Path.Combine(agentPath, "Inject.dll"));
|
||||
if (!r.DecalInstalled)
|
||||
{
|
||||
r.Add(Level.Fail, @"Decal is not installed (HKLM\SOFTWARE\Decal\Agent AgentPath\Inject.dll not found).");
|
||||
return r;
|
||||
}
|
||||
string adapter = Path.Combine(agentPath!, "Decal.Adapter.dll");
|
||||
Version? installed = host.FileExists(adapter) ? host.AssemblyVersionOf(adapter) : null;
|
||||
string bridgeDll = Path.Combine(dir, DecalBridgeRegistration.AssemblyFile);
|
||||
bool bridgePresent = host.FileExists(bridgeDll);
|
||||
Version? needed = bridgePresent ? host.ReferenceVersionOf(bridgeDll, "Decal.Adapter") : null;
|
||||
r.DecalVersion = installed?.ToString();
|
||||
if (installed == null)
|
||||
r.Add(Level.Fail, $"Decal.Adapter.dll is missing or unreadable in {agentPath} - reinstall Decal.");
|
||||
else if (needed != null && installed < needed)
|
||||
r.Add(Level.Fail, $"Decal {installed} is older than the {needed} the bridge is built for - update Decal (decaldev.com), then check again.");
|
||||
else
|
||||
r.Add(Level.Ok, $"Decal {installed} in {agentPath}" + (needed != null ? $" (bridge built for {needed})." : "."));
|
||||
|
||||
// 2. The bridge DLL itself.
|
||||
if (!bridgePresent)
|
||||
r.Add(Level.Fail, $"{DecalBridgeRegistration.AssemblyFile} is missing from {dir} - reinstall RynthCore.");
|
||||
else if (host.HasZoneIdentifier(bridgeDll))
|
||||
r.Add(Level.Warn, $"{bridgeDll} is marked as downloaded from the internet; .NET may refuse to load it. Repair removes the mark (or: right-click > Properties > Unblock).");
|
||||
else
|
||||
r.Add(Level.Ok, $"Bridge DLL present: {bridgeDll}.");
|
||||
|
||||
// 3. How the client will see the registry.
|
||||
r.ClientVirtualized = PredictClientVirtualized(host, acClientPath, out string why);
|
||||
r.ClientReason = why;
|
||||
r.Add(Level.Info, "AC client: " + why + ".");
|
||||
|
||||
// 4. Where Decal reads its filters, and our entry there.
|
||||
var where = WhereDecalReads(host, r.ClientVirtualized, "NetworkFilters");
|
||||
r.ReadsPerUserCopy = where.PerUser;
|
||||
string whereText = Describe(host.Is64BitOs, where.Root, where.Path);
|
||||
r.FiltersReadFrom = "Decal reads its filters from " + whereText + (where.PerUser ? " (your Windows user's copy)" : "");
|
||||
r.Add(Level.Info, r.FiltersReadFrom + ".");
|
||||
|
||||
string? entryProblem = EntryProblem(host, where.Root, where.Path + "\\" + DecalBridgeRegistration.FilterGuid, out string? registeredPath);
|
||||
if (entryProblem == null)
|
||||
{
|
||||
r.BridgeVisibleToDecal = true;
|
||||
r.Add(Level.Ok, $"RynthCore Decal Bridge is registered there and enabled ({registeredPath}).");
|
||||
}
|
||||
else
|
||||
{
|
||||
r.NeedsMachineWideRegistration = !where.PerUser;
|
||||
r.Add(Level.Fail, $"Decal will not load the bridge: {entryProblem} in {whereText}." +
|
||||
(where.PerUser
|
||||
? " Repair (or a Decal + RynthCore launch) registers it for your Windows user."
|
||||
: " That key is shared by all users: Repair adds it there once and Windows asks for administrator permission."));
|
||||
}
|
||||
|
||||
// Other places, for people (a registration Decal won't read explains a "registered but nothing happens").
|
||||
if (where.PerUser)
|
||||
{
|
||||
using IRegKey? m = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
|
||||
if (m != null && IsOurs(m) && entryProblem != null)
|
||||
r.Add(Level.Info, "(A machine-wide entry exists, but your per-user copy hides it from AC.)");
|
||||
}
|
||||
else
|
||||
{
|
||||
using IRegKey? u = host.OpenReal(RegRoot.User64, VirtualStoreDecalPath(host.Is64BitOs, "NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
|
||||
if (u != null && IsOurs(u) && entryProblem != null)
|
||||
r.Add(Level.Info, "(A per-user registration exists, but this AC client doesn't read it: " + why + ".)");
|
||||
}
|
||||
|
||||
// 5. The same entry through this process's own view, when that view IS the client's.
|
||||
bool sameView = host.LauncherVirtualized == r.ClientVirtualized;
|
||||
if (sameView)
|
||||
{
|
||||
using IRegKey? live = host.OpenOwnViewMachine32(MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
|
||||
bool liveOk = live != null && IsOurs(live) && IsEnabled(live);
|
||||
if (liveOk == r.BridgeVisibleToDecal)
|
||||
r.Add(Level.Ok, $"Read back as AC will see it: {(liveOk ? "bridge listed and enabled" : "bridge not listed")}.");
|
||||
else
|
||||
r.Add(liveOk ? Level.Warn : Level.Fail,
|
||||
$"Read back as AC will see it: {(liveOk ? "bridge listed" : "bridge NOT listed")}, which disagrees with {whereText}. Windows serves this PC's registry differently than expected.");
|
||||
}
|
||||
else
|
||||
{
|
||||
r.Add(Level.Info, "Not read back live: AC will run with other rights than this launcher.");
|
||||
}
|
||||
|
||||
// 6. Hidden machine filters (a per-user list hides every HKLM entry it lacks).
|
||||
if (where.PerUser)
|
||||
{
|
||||
List<string> hidden = HiddenMachineFilters(host, where.Path);
|
||||
if (hidden.Count > 0)
|
||||
r.Add(Level.Warn, "Hidden from AC by your per-user filter list (in HKLM, not in the copy): " + string.Join(", ", hidden) +
|
||||
". If 'World Object Filter' is among them, VTank won't start.");
|
||||
}
|
||||
|
||||
// 7. Decal's .NET surrogate: Decal must be able to create it, and must not have it disabled.
|
||||
var surWhere = WhereDecalReads(host, r.ClientVirtualized, "Surrogates");
|
||||
using (IRegKey? s = host.OpenReal(surWhere.Root, surWhere.Path + "\\" + SurrogateClsid))
|
||||
{
|
||||
if (s == null)
|
||||
r.Add(Level.Fail, $"Decal's .NET surrogate is not listed in {Describe(host.Is64BitOs, surWhere.Root, surWhere.Path)} - no .NET filter or plugin can load. Reinstall Decal.");
|
||||
else if (!IsEnabled(s))
|
||||
r.Add(Level.Fail, "Decal's .NET surrogate (Decal.Adapter Surrogate) is disabled in Decal - enable it in Decal's agent (or reinstall Decal).");
|
||||
else
|
||||
r.Add(Level.Ok, "Decal's .NET surrogate is enabled.");
|
||||
}
|
||||
string? comProblem = SurrogateComProblem(host, clientElevated: !r.ClientVirtualized && IsClientElevated(host, acClientPath), out string comWhere);
|
||||
if (comProblem != null)
|
||||
r.Add(Level.Fail, comProblem);
|
||||
else
|
||||
r.Add(Level.Ok, $"Decal.Adapter's COM class resolves ({comWhere}). The bridge itself needs no COM registration: Decal.Adapter loads it from Path\\Assembly.");
|
||||
|
||||
// 8. .NET Framework 4.8.
|
||||
int? release = DwordOf(host, RegRoot.Machine32, @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", "Release");
|
||||
if (release == null)
|
||||
r.Add(Level.Fail, ".NET Framework 4 is not installed (Decal needs it).");
|
||||
else if (release < Net48Release)
|
||||
r.Add(Level.Warn, $".NET Framework older than 4.8 (Release {release}); the bridge targets 4.8 - install .NET Framework 4.8.");
|
||||
|
||||
// 9. engine.json settings that turn bridge mode off.
|
||||
if (engineJsonPath != null)
|
||||
{
|
||||
(string? mode, bool? inGame) = ReadEngineSettings(host, engineJsonPath);
|
||||
if (mode != null && (mode.Equals("Off", StringComparison.OrdinalIgnoreCase) || mode.Equals("false", StringComparison.OrdinalIgnoreCase)))
|
||||
r.Add(Level.Fail, $"engine.json has \"DecalBridge\": {mode} - bridge mode is off for every client. Remove that line ({engineJsonPath}).");
|
||||
if (inGame == false)
|
||||
r.Add(Level.Warn, "engine.json has \"DecalInGameImGui\": false - no RynthCore overlay under Decal (by choice).");
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// ── pieces (internal for the tests) ─────────────────────────────────────
|
||||
|
||||
internal static string? EntryProblem(IDecalCheckHost host, RegRoot root, string entryPath, out string? registeredPath)
|
||||
{
|
||||
registeredPath = null;
|
||||
using IRegKey? k = host.OpenReal(root, entryPath);
|
||||
if (k == null) return "the RynthCore Decal Bridge is not registered";
|
||||
if (!IsOurs(k)) return "another filter uses the bridge's id";
|
||||
registeredPath = k.GetValue("Path") as string;
|
||||
if (!IsEnabled(k)) return "the RynthCore Decal Bridge is registered but disabled";
|
||||
if (!string.Equals(k.GetValue("Surrogate") as string, SurrogateClsid, StringComparison.OrdinalIgnoreCase))
|
||||
return "the bridge entry has the wrong Surrogate";
|
||||
string? file = k.GetValue("Assembly") as string;
|
||||
if (string.IsNullOrEmpty(registeredPath) || string.IsNullOrEmpty(file))
|
||||
return "the bridge entry has no Path/Assembly";
|
||||
if (!host.FileExists(Path.Combine(registeredPath, file)))
|
||||
return $"the registered bridge DLL is missing ({Path.Combine(registeredPath, file)})";
|
||||
return null;
|
||||
}
|
||||
|
||||
internal static List<string> HiddenMachineFilters(IDecalCheckHost host, string perUserPath)
|
||||
{
|
||||
var hidden = new List<string>();
|
||||
using IRegKey? machine = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters"));
|
||||
using IRegKey? user = host.OpenReal(RegRoot.User64, perUserPath);
|
||||
if (machine == null || user == null) return hidden;
|
||||
var seen = new HashSet<string>(user.GetSubKeyNames(), StringComparer.OrdinalIgnoreCase);
|
||||
foreach (string name in machine.GetSubKeyNames())
|
||||
{
|
||||
if (seen.Contains(name) || string.Equals(name, DecalBridgeRegistration.FilterGuid, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
using IRegKey? k = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters") + "\\" + name);
|
||||
hidden.Add(k?.GetValue("") is string friendly && friendly.Length > 0 ? friendly : name);
|
||||
}
|
||||
return hidden;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decal.Adapter's surrogate is an mscoree COM class. A non-elevated client resolves it
|
||||
/// per-user first (HKCU\Software\Classes), then machine-wide; an elevated one ignores
|
||||
/// per-user COM registrations.
|
||||
/// </summary>
|
||||
internal static string? SurrogateComProblem(IDecalCheckHost host, bool clientElevated, out string where)
|
||||
{
|
||||
where = string.Empty;
|
||||
string sub = @"\CLSID\" + SurrogateClsid + @"\InprocServer32";
|
||||
var candidates = new List<(RegRoot Root, string Path, string Label)>();
|
||||
if (!clientElevated) candidates.Add((RegRoot.User32, @"Software\Classes" + sub, "per-user"));
|
||||
candidates.Add((RegRoot.Machine32, @"SOFTWARE\Classes" + sub, "machine-wide"));
|
||||
foreach (var c in candidates)
|
||||
{
|
||||
using IRegKey? k = host.OpenReal(c.Root, c.Path);
|
||||
if (k == null) continue;
|
||||
where = c.Label;
|
||||
string server = k.GetValue("") as string ?? string.Empty;
|
||||
if (!server.EndsWith("mscoree.dll", StringComparison.OrdinalIgnoreCase))
|
||||
return $"Decal.Adapter's COM class ({c.Label}) points at '{server}', not mscoree.dll - reinstall Decal.";
|
||||
if (string.IsNullOrEmpty(k.GetValue("Assembly") as string))
|
||||
return $"Decal.Adapter's COM class ({c.Label}) names no assembly - reinstall Decal.";
|
||||
if (k.GetValue("CodeBase") is string cb && cb.Length > 0)
|
||||
{
|
||||
string file = cb.StartsWith("file:", StringComparison.OrdinalIgnoreCase) ? cb.Substring(5).TrimStart('/') : cb;
|
||||
if (!host.FileExists(file.Replace('/', '\\')))
|
||||
return $"Decal.Adapter's COM class ({c.Label}) points at a missing file ({file}) - reinstall Decal.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
bool perUserOnly = clientElevated && OpenExists(host, RegRoot.User32, @"Software\Classes" + sub);
|
||||
return perUserOnly
|
||||
? "Decal.Adapter's COM class is registered only for your Windows user, and an AC running as administrator ignores per-user COM classes - reinstall Decal for all users."
|
||||
: "Decal.Adapter's COM class (Decal.Adapter.Surrogate) is not registered - reinstall Decal.";
|
||||
}
|
||||
|
||||
private static bool IsClientElevated(IDecalCheckHost host, string? acClientPath)
|
||||
{
|
||||
if (host.LauncherElevated) return true;
|
||||
if (string.IsNullOrEmpty(acClientPath)) return false;
|
||||
string? level = host.ExecutionLevelOf(acClientPath);
|
||||
if (level != null && (level.Equals("requireAdministrator", StringComparison.OrdinalIgnoreCase) || level.Equals("highestAvailable", StringComparison.OrdinalIgnoreCase)))
|
||||
return true;
|
||||
if (RunAsAdminLayer(host, acClientPath) != null) return true;
|
||||
// UAC off: an administrator's programs run with the full token.
|
||||
return DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableLUA") == 0;
|
||||
}
|
||||
|
||||
private static string? RunAsAdminLayer(IDecalCheckHost host, string exePath)
|
||||
{
|
||||
foreach ((RegRoot root, string key) in new[]
|
||||
{
|
||||
(RegRoot.User64, @"Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"),
|
||||
(RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"),
|
||||
})
|
||||
{
|
||||
using IRegKey? k = host.OpenReal(root, key);
|
||||
if (k == null) continue;
|
||||
foreach (string name in k.GetValueNames())
|
||||
{
|
||||
if (!string.Equals(name, exePath, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
string flags = k.GetValue(name) as string ?? string.Empty;
|
||||
string[] parts = flags.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Any(p => p.Equals("RUNASADMIN", StringComparison.OrdinalIgnoreCase) || p.Equals("RUNASHIGHEST", StringComparison.OrdinalIgnoreCase)))
|
||||
return (root == RegRoot.User64 ? "your compatibility settings" : "compatibility settings for all users") + ": " + flags.Trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static (string? Mode, bool? InGame) ReadEngineSettings(IDecalCheckHost host, string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
string? text = host.ReadTextFile(path);
|
||||
if (text == null) return (null, null);
|
||||
using JsonDocument doc = JsonDocument.Parse(text, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
|
||||
string? mode = null;
|
||||
bool? inGame = null;
|
||||
if (doc.RootElement.TryGetProperty("DecalBridge", out JsonElement m))
|
||||
mode = m.ValueKind switch { JsonValueKind.String => m.GetString(), JsonValueKind.True => "true", JsonValueKind.False => "false", _ => null };
|
||||
if (doc.RootElement.TryGetProperty("DecalInGameImGui", out JsonElement g) && (g.ValueKind == JsonValueKind.True || g.ValueKind == JsonValueKind.False))
|
||||
inGame = g.GetBoolean();
|
||||
return (mode, inGame);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (null, null);
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool IsOurs(IRegKey k) =>
|
||||
string.Equals(k.GetValue("Object") as string, DecalBridgeRegistration.FilterObject, StringComparison.Ordinal);
|
||||
|
||||
internal static bool IsEnabled(IRegKey k) => k.GetValue("Enabled") is int e && e != 0;
|
||||
|
||||
private static bool OpenExists(IDecalCheckHost host, RegRoot root, string path)
|
||||
{
|
||||
using IRegKey? k = host.OpenReal(root, path);
|
||||
return k != null;
|
||||
}
|
||||
|
||||
private static int? DwordOf(IDecalCheckHost host, RegRoot root, string path, string name)
|
||||
{
|
||||
using IRegKey? k = host.OpenReal(root, path);
|
||||
return k?.GetValue(name) is int v ? v : null;
|
||||
}
|
||||
|
||||
private static string? StringOf(IDecalCheckHost host, RegRoot root, string path, string name)
|
||||
{
|
||||
using IRegKey? k = host.OpenReal(root, path);
|
||||
return k?.GetValue(name) is string s && s.Length > 0 ? s : null;
|
||||
}
|
||||
}
|
||||
810
src/RynthCore.App/DecalBridgeRegistration.cs
Normal file
810
src/RynthCore.App/DecalBridgeRegistration.cs
Normal 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: <install>\DecalBridge.</summary>
|
||||
public static string DefaultBridgeDirectory => Path.Combine(AppContext.BaseDirectory, "DecalBridge");
|
||||
|
||||
public sealed class Status
|
||||
{
|
||||
public bool DecalInstalled;
|
||||
public bool PerUserKeyExists;
|
||||
public bool PerUserKeyCreatedByUs;
|
||||
public bool RegisteredPerUser;
|
||||
public bool RegisteredMachineWide;
|
||||
public bool Enabled;
|
||||
public bool MachineEnabled;
|
||||
public string? RegisteredPath;
|
||||
public bool DllPresent;
|
||||
/// <summary>A client started by this process gets UAC registry virtualization (reads the per-user copy when it exists).</summary>
|
||||
public bool ClientVirtualized = true;
|
||||
public string ClientReason = string.Empty;
|
||||
/// <summary>HKLM filters a Decal client of this user can't see (hidden by the per-user key).</summary>
|
||||
public List<string> HiddenMachineFilters = new();
|
||||
|
||||
/// <summary>What a Decal client started now will load (see DecalBridgeCheck for the full check).</summary>
|
||||
public bool EffectiveForClients => ClientVirtualized && PerUserKeyExists
|
||||
? RegisteredPerUser && Enabled
|
||||
: RegisteredMachineWide && MachineEnabled;
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append($"Decal installed: {DecalInstalled}. ");
|
||||
sb.Append($"Bridge registered for clients started now: {(EffectiveForClients ? "yes" : "no")}");
|
||||
if (RegisteredPerUser) sb.Append(" (per-user entry present)");
|
||||
if (RegisteredMachineWide) sb.Append(" (machine-wide entry present)");
|
||||
if (RegisteredPath != null) sb.Append($", path {RegisteredPath}{(DllPresent ? "" : " (DLL MISSING)")}");
|
||||
sb.Append('.');
|
||||
if (ClientReason.Length > 0) sb.Append($" Client: {ClientReason}.");
|
||||
if (PerUserKeyExists)
|
||||
sb.Append($" Per-user filter list: {(PerUserKeyCreatedByUs ? "created by RynthCore" : "existed before RynthCore")}.");
|
||||
if (HiddenMachineFilters.Count > 0)
|
||||
sb.Append($" Hidden from Decal clients (in HKLM, not in the per-user list): {string.Join(", ", HiddenMachineFilters)}.");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class State
|
||||
{
|
||||
public bool CreatedFiltersKey { get; set; }
|
||||
public string BridgePath { get; set; } = string.Empty;
|
||||
public DateTime RegisteredUtc { get; set; }
|
||||
/// <summary>Mirrored HKLM subkey -> fingerprint of the copy as written.</summary>
|
||||
public Dictionary<string, string> MirroredKeys { get; set; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
/// <summary>Mirrored values of the NetworkFilters key itself -> fingerprint.</summary>
|
||||
public Dictionary<string, string> MirroredValues { get; set; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
// ── public API ───────────────────────────────────────────────────────────
|
||||
|
||||
public static Status GetStatus(string? acClientPath = null)
|
||||
{
|
||||
bool virt = RealDecalCheckHost.PredictClientVirtualized(acClientPath ?? DecalLocator.TryGetDecalAcClientPath(), out string reason, out _);
|
||||
Status s;
|
||||
using (RealRegistryView.Enter()) s = GetStatusCore();
|
||||
s.ClientVirtualized = virt;
|
||||
s.ClientReason = reason;
|
||||
return s;
|
||||
}
|
||||
|
||||
private static Status GetStatusCore()
|
||||
{
|
||||
var s = new Status { DecalInstalled = DecalLocator.IsInstalled() };
|
||||
State? state = LoadState();
|
||||
using RegistryKey? machine = OpenMachineFilters();
|
||||
using RegistryKey? user = OpenUserFilters(writable: false);
|
||||
s.PerUserKeyExists = user != null;
|
||||
s.PerUserKeyCreatedByUs = user != null && state?.CreatedFiltersKey == true;
|
||||
|
||||
using (RegistryKey? m = machine?.OpenSubKey(FilterGuid))
|
||||
{
|
||||
if (m != null && IsOurs(m))
|
||||
{
|
||||
s.RegisteredMachineWide = true;
|
||||
s.MachineEnabled = Enabled(m);
|
||||
if (user == null) ReadEntry(m, s);
|
||||
}
|
||||
}
|
||||
using (RegistryKey? u = user?.OpenSubKey(FilterGuid))
|
||||
{
|
||||
if (u != null && IsOurs(u))
|
||||
{
|
||||
s.RegisteredPerUser = true;
|
||||
ReadEntry(u, s);
|
||||
}
|
||||
}
|
||||
if (machine != null && user != null)
|
||||
{
|
||||
HashSet<string> seen = new(user.GetSubKeyNames(), StringComparer.OrdinalIgnoreCase);
|
||||
foreach (string name in machine.GetSubKeyNames())
|
||||
if (!seen.Contains(name))
|
||||
s.HiddenMachineFilters.Add(DescribeFilter(machine, name));
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
public enum Outcome { Registered, NeedsAdmin, Failed }
|
||||
|
||||
/// <summary>
|
||||
/// Registers the bridge where a Decal client started now reads its filter list, then
|
||||
/// verifies it with <see cref="DecalBridgeCheck"/> (reading back from that place, and
|
||||
/// through this process's own view when it is the client's).
|
||||
/// - Client virtualized (non-elevated AC, the usual case): the per-user VirtualStore copy,
|
||||
/// as before (no administrator rights needed).
|
||||
/// - Client not virtualized (RynthCore/AC run as administrator, UAC off, a manifest,
|
||||
/// virtualization off by policy): Decal reads the real
|
||||
/// HKLM\SOFTWARE\(WOW6432Node\)Decal\NetworkFilters, where a per-user entry is
|
||||
/// invisible. Written directly when this process may; otherwise <see cref="Outcome.NeedsAdmin"/>,
|
||||
/// and the caller runs <c>--decal-bridge-register-machine</c> elevated (<see cref="RunElevated"/>).
|
||||
/// Idempotent. Also removes a "downloaded from the internet" mark from the bridge DLL.
|
||||
/// </summary>
|
||||
public static Outcome RegisterForClients(string bridgeDirectory, string? acClientPath, string? engineJsonPath,
|
||||
out string report, out DecalBridgeCheck.Result? check)
|
||||
{
|
||||
check = null;
|
||||
var log = new List<string>();
|
||||
string dir;
|
||||
try { dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\'); }
|
||||
catch (Exception ex) { report = $"Bad bridge folder '{bridgeDirectory}': {ex.Message}"; return Outcome.Failed; }
|
||||
|
||||
string dll = Path.Combine(dir, AssemblyFile);
|
||||
if (File.Exists(dll) && File.Exists(dll + ":Zone.Identifier"))
|
||||
log.Add(RealDecalCheckHost.RemoveZoneIdentifier(dll)
|
||||
? "removed the 'downloaded from the internet' mark from the bridge DLL"
|
||||
: "could not remove the 'downloaded from the internet' mark from the bridge DLL");
|
||||
|
||||
bool virtualized = RealDecalCheckHost.PredictClientVirtualized(acClientPath, out string why, out _);
|
||||
bool ok;
|
||||
string step;
|
||||
if (virtualized)
|
||||
{
|
||||
ok = RegisterPerUser(dir, out step);
|
||||
}
|
||||
else
|
||||
{
|
||||
Outcome mw = RegisterMachineWide(dir, out step);
|
||||
if (mw == Outcome.NeedsAdmin)
|
||||
{
|
||||
log.Add($"AC reads Decal's filter list for all users on this PC ({why}); adding the bridge there needs administrator rights once.");
|
||||
report = string.Join(" ", log);
|
||||
return Outcome.NeedsAdmin;
|
||||
}
|
||||
ok = mw == Outcome.Registered;
|
||||
step = $"({why}) " + step;
|
||||
}
|
||||
log.Add(step);
|
||||
|
||||
check = RealDecalCheckHost.Check(dir, acClientPath, engineJsonPath);
|
||||
log.Add(check.Summary);
|
||||
report = string.Join(" ", log);
|
||||
if (!ok) return Outcome.Failed;
|
||||
if (check.Blocking) return check.NeedsMachineWideRegistration ? Outcome.NeedsAdmin : Outcome.Failed;
|
||||
return Outcome.Registered;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="RegisterForClients"/> for Decal's own acclient.exe (PortalPath). False (with
|
||||
/// the reason) when it needs administrator rights or the check fails.
|
||||
/// </summary>
|
||||
public static bool Register(string bridgeDirectory, out string report) =>
|
||||
RegisterForClients(bridgeDirectory, DecalLocator.TryGetDecalAcClientPath(), null, out report, out _) == Outcome.Registered;
|
||||
|
||||
/// <summary>
|
||||
/// Adds the bridge to the machine-wide list, HKLM\SOFTWARE\(WOW6432Node\)Decal\NetworkFilters
|
||||
/// (32-bit view). Needs administrator rights: run elevated (--decal-bridge-register-machine).
|
||||
/// Virtualization is off while it writes, so a non-elevated process gets "access denied"
|
||||
/// (NeedsAdmin) instead of a silent write into the per-user copy. Idempotent; nothing to mirror
|
||||
/// (the machine list is the one every other filter is in).
|
||||
/// </summary>
|
||||
public static Outcome RegisterMachineWide(string bridgeDirectory, out string report)
|
||||
{
|
||||
var log = new List<string>();
|
||||
using (RealRegistryView.Enter())
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!DecalLocator.IsInstalled())
|
||||
{
|
||||
report = "Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent) - nothing registered.";
|
||||
return Outcome.Failed;
|
||||
}
|
||||
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
|
||||
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
|
||||
{
|
||||
report = $"{AssemblyFile} not found in {dir} - nothing registered.";
|
||||
return Outcome.Failed;
|
||||
}
|
||||
using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView);
|
||||
using RegistryKey filters = hklm.CreateSubKey(DecalFiltersSubKey, writable: true);
|
||||
using (RegistryKey? existing = filters.OpenSubKey(FilterGuid))
|
||||
{
|
||||
if (existing != null && !IsOurs(existing))
|
||||
{
|
||||
report = $"another filter uses the bridge's id {FilterGuid} in the machine-wide list - nothing changed.";
|
||||
return Outcome.Failed;
|
||||
}
|
||||
}
|
||||
using (RegistryKey entry = filters.CreateSubKey(FilterGuid, writable: true))
|
||||
{
|
||||
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
|
||||
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
|
||||
}
|
||||
report = log.Count == 0
|
||||
? $"Decal bridge already registered for all users ({dir}); nothing changed."
|
||||
: $"Decal bridge registered for all users ({dir}): {string.Join("; ", log)}.";
|
||||
return Outcome.Registered;
|
||||
}
|
||||
catch (Exception ex) when (ex is UnauthorizedAccessException or System.Security.SecurityException)
|
||||
{
|
||||
report = "Registering the Decal bridge for all users needs administrator rights.";
|
||||
return Outcome.NeedsAdmin;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
report = $"Decal bridge registration for all users failed: {Describe(ex)}";
|
||||
return Outcome.Failed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The installer's per-user half (installer\RynthCore.iss, run as the installing user on
|
||||
/// every install and update; the elevated half is <see cref="RegisterMachineWide"/>).
|
||||
/// Writes our entry into this user's VirtualStore copy of Decal's filter list ONLY when
|
||||
/// that copy already exists - see <see cref="DecalBridgeCheck.PlanInstall"/> for why both
|
||||
/// places are written and why a missing copy is never created here. The entry is ours
|
||||
/// (Object = <see cref="FilterObject"/>), so <see cref="Unregister"/> removes it.
|
||||
/// </summary>
|
||||
public static bool InstallPerUser(string bridgeDirectory, out string report)
|
||||
{
|
||||
try
|
||||
{
|
||||
var plan = RealDecalCheckHost.PlanInstall();
|
||||
if (!plan.Machine)
|
||||
{
|
||||
report = "Decal is not installed - nothing to do for this user.";
|
||||
return true;
|
||||
}
|
||||
if (!plan.PerUser)
|
||||
{
|
||||
report = "This user has no per-user copy of Decal's filter list - the machine-wide entry is the one AC reads; nothing written.";
|
||||
return true;
|
||||
}
|
||||
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
|
||||
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
|
||||
{
|
||||
report = $"{AssemblyFile} not found in {dir} - nothing written.";
|
||||
return false;
|
||||
}
|
||||
var log = new List<string>();
|
||||
using (RealRegistryView.Enter())
|
||||
{
|
||||
using RegistryKey? user = OpenUserFilters(writable: true);
|
||||
if (user == null)
|
||||
{
|
||||
report = "The per-user copy disappeared - nothing written.";
|
||||
return true;
|
||||
}
|
||||
using (RegistryKey? existing = user.OpenSubKey(FilterGuid))
|
||||
{
|
||||
if (existing != null && !IsOurs(existing))
|
||||
{
|
||||
report = $"another filter uses the bridge's id {FilterGuid} in the per-user copy - nothing changed.";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
using RegistryKey entry = user.CreateSubKey(FilterGuid, writable: true);
|
||||
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
|
||||
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
|
||||
}
|
||||
report = log.Count == 0
|
||||
? $"Decal bridge already in this user's per-user copy ({dir}); nothing changed."
|
||||
: $"Decal bridge added to this user's existing per-user copy ({dir}): {string.Join("; ", log)}.";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
report = $"Per-user Decal bridge entry failed: {Describe(ex)}";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The machine-wide list holds our entry (the launcher/injector never adds it without being asked).</summary>
|
||||
public static bool MachineEntryIsOurs()
|
||||
{
|
||||
using (RealRegistryView.Enter())
|
||||
{
|
||||
try
|
||||
{
|
||||
using RegistryKey? machine = OpenMachineFilters();
|
||||
using RegistryKey? m = machine?.OpenSubKey(FilterGuid);
|
||||
return m != null && IsOurs(m);
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Removes our machine-wide entry (only ours). Needs administrator rights.</summary>
|
||||
public static Outcome UnregisterMachineWide(out string report)
|
||||
{
|
||||
using (RealRegistryView.Enter())
|
||||
{
|
||||
try
|
||||
{
|
||||
using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView);
|
||||
using RegistryKey? probe = hklm.OpenSubKey(DecalFiltersSubKey);
|
||||
using RegistryKey? m = probe?.OpenSubKey(FilterGuid);
|
||||
if (m == null || !IsOurs(m))
|
||||
{
|
||||
report = "No machine-wide Decal bridge entry; nothing to remove.";
|
||||
return Outcome.Registered;
|
||||
}
|
||||
using RegistryKey filters = hklm.OpenSubKey(DecalFiltersSubKey, writable: true)!;
|
||||
filters.DeleteSubKeyTree(FilterGuid, throwOnMissingSubKey: false);
|
||||
report = "Removed the machine-wide Decal bridge entry.";
|
||||
return Outcome.Registered;
|
||||
}
|
||||
catch (Exception ex) when (ex is UnauthorizedAccessException or System.Security.SecurityException)
|
||||
{
|
||||
report = "Removing the machine-wide Decal bridge entry needs administrator rights.";
|
||||
return Outcome.NeedsAdmin;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
report = $"Removing the machine-wide Decal bridge entry failed: {Describe(ex)}";
|
||||
return Outcome.Failed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="exePath"/> elevated (Windows shows its administrator prompt) and
|
||||
/// waits for it. NeedsAdmin when the person said no at the prompt.
|
||||
/// </summary>
|
||||
public static Outcome RunElevated(string exePath, string arguments, out string report)
|
||||
{
|
||||
try
|
||||
{
|
||||
var psi = new System.Diagnostics.ProcessStartInfo(exePath, arguments)
|
||||
{
|
||||
UseShellExecute = true,
|
||||
Verb = "runas",
|
||||
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
|
||||
};
|
||||
using System.Diagnostics.Process? p = System.Diagnostics.Process.Start(psi);
|
||||
if (p == null)
|
||||
{
|
||||
report = "Windows did not start the administrator step.";
|
||||
return Outcome.Failed;
|
||||
}
|
||||
if (!p.WaitForExit(120_000))
|
||||
{
|
||||
report = "The administrator step did not finish within 2 minutes.";
|
||||
return Outcome.Failed;
|
||||
}
|
||||
report = p.ExitCode == 0 ? "The administrator step finished." : $"The administrator step failed (exit code {p.ExitCode}).";
|
||||
return p.ExitCode == 0 ? Outcome.Registered : Outcome.Failed;
|
||||
}
|
||||
catch (System.ComponentModel.Win32Exception ex) when (ex.NativeErrorCode == 1223)
|
||||
{
|
||||
report = "Cancelled at the Windows administrator prompt.";
|
||||
return Outcome.NeedsAdmin;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
report = $"Could not start the administrator step: {ex.Message}";
|
||||
return Outcome.Failed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes Decal clients of this user load the bridge from <paramref name="bridgeDirectory"/>
|
||||
/// through the per-user VirtualStore copy (virtualized clients only: see
|
||||
/// <see cref="RegisterForClients"/>). Idempotent. Returns false (with the reason in
|
||||
/// <paramref name="report"/>) when Decal isn't installed or the bridge DLL isn't there.
|
||||
/// </summary>
|
||||
public static bool RegisterPerUser(string bridgeDirectory, out string report)
|
||||
{
|
||||
using (RealRegistryView.Enter()) return RegisterCore(bridgeDirectory, out report);
|
||||
}
|
||||
|
||||
private static bool RegisterCore(string bridgeDirectory, out string report)
|
||||
{
|
||||
var log = new List<string>();
|
||||
try
|
||||
{
|
||||
if (!DecalLocator.IsInstalled())
|
||||
{
|
||||
report = "Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent) - nothing registered.";
|
||||
return false;
|
||||
}
|
||||
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
|
||||
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
|
||||
{
|
||||
report = $"{AssemblyFile} not found in {dir} - nothing registered.";
|
||||
return false;
|
||||
}
|
||||
|
||||
State state = LoadState() ?? new State();
|
||||
using RegistryKey? machine = OpenMachineFilters();
|
||||
using RegistryKey? existingUser = OpenUserFilters(writable: true);
|
||||
if (existingUser == null && state.CreatedFiltersKey)
|
||||
{
|
||||
// Someone removed the key we created; start the record over.
|
||||
state = new State();
|
||||
}
|
||||
|
||||
RegistryKey? user = existingUser;
|
||||
try
|
||||
{
|
||||
if (user == null)
|
||||
{
|
||||
// No per-user list yet. If an administrator already registered the bridge in
|
||||
// HKLM with this path, clients see it without us creating anything.
|
||||
using (RegistryKey? m = machine?.OpenSubKey(FilterGuid))
|
||||
{
|
||||
if (m != null && IsOurs(m) && Enabled(m) &&
|
||||
string.Equals((m.GetValue("Path") as string)?.TrimEnd('\\'), dir, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
report = "Already registered machine-wide (HKLM) with this path; nothing changed.";
|
||||
return true;
|
||||
}
|
||||
}
|
||||
user = UserHive().CreateSubKey(VirtualStoreFiltersSubKey, writable: true);
|
||||
state.CreatedFiltersKey = true;
|
||||
log.Add($"created HKCU\\{VirtualStoreFiltersSubKey}");
|
||||
}
|
||||
|
||||
if (state.CreatedFiltersKey && machine != null)
|
||||
SyncMirror(machine, user, state, log);
|
||||
|
||||
using (RegistryKey entry = user.CreateSubKey(FilterGuid, writable: true))
|
||||
{
|
||||
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
|
||||
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
|
||||
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!ReferenceEquals(user, existingUser)) user?.Dispose();
|
||||
}
|
||||
|
||||
state.BridgePath = dir;
|
||||
state.RegisteredUtc = DateTime.UtcNow;
|
||||
SaveState(state);
|
||||
report = log.Count == 0
|
||||
? $"Decal bridge already registered for this user ({dir}); nothing changed."
|
||||
: $"Decal bridge registered for this user ({dir}): {string.Join("; ", log)}.";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
report = $"Decal bridge registration failed: {ex.GetType().Name}: {ex.Message}" +
|
||||
(log.Count > 0 ? $" (done before the failure: {string.Join("; ", log)})" : "");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes what <see cref="Register"/> added: the bridge's entry, the mirrored copies of
|
||||
/// HKLM filters, and the per-user key if this class created it and nothing foreign is
|
||||
/// left in it. A mirrored copy that changed since (Decal plugins write to "HKLM" through
|
||||
/// UAC virtualization, so their writes land in our per-user copy) is removed as well when
|
||||
/// RynthCore created the key: HKLM still holds the original, and a per-user list left with
|
||||
/// a few entries would hide every other HKLM filter from Decal clients (VTank then has no
|
||||
/// WorldFilter). Anything RynthCore didn't add is left in place and reported, and the
|
||||
/// record (%APPDATA%\RynthCore\decal-bridge-registration.json) is kept until nothing of
|
||||
/// ours remains, so a later unregister can finish the job.
|
||||
/// </summary>
|
||||
public static bool Unregister(out string report)
|
||||
{
|
||||
using (RealRegistryView.Enter()) return UnregisterCore(out report);
|
||||
}
|
||||
|
||||
private static bool UnregisterCore(out string report)
|
||||
{
|
||||
var log = new List<string>();
|
||||
var failed = new List<string>();
|
||||
try
|
||||
{
|
||||
State? state = LoadState();
|
||||
bool done = true;
|
||||
using RegistryKey? user = OpenUserFilters(writable: true);
|
||||
if (user != null)
|
||||
{
|
||||
foreach (string name in user.GetSubKeyNames())
|
||||
{
|
||||
try
|
||||
{
|
||||
bool ours;
|
||||
using (RegistryKey? k = user.OpenSubKey(name))
|
||||
ours = k != null && IsOurs(k);
|
||||
if (!ours) continue;
|
||||
user.DeleteSubKeyTree(name, throwOnMissingSubKey: false);
|
||||
log.Add($"removed bridge entry {name}");
|
||||
}
|
||||
catch (Exception ex) { failed.Add($"{name}: {Describe(ex)}"); }
|
||||
}
|
||||
|
||||
if (state?.CreatedFiltersKey == true)
|
||||
{
|
||||
int same = 0, changed = 0;
|
||||
foreach (KeyValuePair<string, string> kv in state.MirroredKeys)
|
||||
{
|
||||
try
|
||||
{
|
||||
bool unchanged;
|
||||
using (RegistryKey? k = user.OpenSubKey(kv.Key))
|
||||
{
|
||||
if (k == null) continue;
|
||||
unchanged = Fingerprint(k) == kv.Value;
|
||||
}
|
||||
user.DeleteSubKeyTree(kv.Key, throwOnMissingSubKey: false);
|
||||
if (unchanged) same++; else changed++;
|
||||
}
|
||||
catch (Exception ex) { failed.Add($"{kv.Key}: {Describe(ex)}"); }
|
||||
}
|
||||
foreach (KeyValuePair<string, string> kv in state.MirroredValues)
|
||||
{
|
||||
try { user.DeleteValue(kv.Key, throwOnMissingValue: false); }
|
||||
catch (Exception ex) { failed.Add($"value {kv.Key}: {Describe(ex)}"); }
|
||||
}
|
||||
log.Add($"removed {same + changed} mirrored filter entr{(same + changed == 1 ? "y" : "ies")}" +
|
||||
(changed > 0 ? $" ({changed} changed by Decal plugins since; HKLM keeps the originals)" : ""));
|
||||
|
||||
var foreign = new List<string>();
|
||||
foreach (string n in user.GetSubKeyNames()) foreign.Add(n);
|
||||
foreach (string n in user.GetValueNames()) if (n.Length > 0) foreign.Add(n);
|
||||
if (foreign.Count == 0 && failed.Count == 0)
|
||||
{
|
||||
user.Dispose();
|
||||
UserHive().DeleteSubKey(VirtualStoreFiltersSubKey, throwOnMissingSubKey: false);
|
||||
log.Add($"removed HKCU\\{VirtualStoreFiltersSubKey} (created by RynthCore)");
|
||||
}
|
||||
else
|
||||
{
|
||||
done = false;
|
||||
log.Add($"left HKCU\\{VirtualStoreFiltersSubKey} in place" +
|
||||
(foreign.Count > 0 ? $": it holds entries RynthCore didn't add ({string.Join(", ", foreign)})" : ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (failed.Count > 0)
|
||||
done = false;
|
||||
if (done && File.Exists(StatePath))
|
||||
File.Delete(StatePath);
|
||||
else if (!done)
|
||||
log.Add($"kept {StatePath} for the next unregister");
|
||||
if (failed.Count > 0)
|
||||
{
|
||||
report = $"Decal bridge unregistration incomplete: {string.Join("; ", failed)}" +
|
||||
(log.Count > 0 ? $" (done: {string.Join("; ", log)})" : "");
|
||||
return false;
|
||||
}
|
||||
report = log.Count == 0 ? "Decal bridge was not registered for this user; nothing to remove." : string.Join("; ", log) + ".";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
report = $"Decal bridge unregistration failed: {Describe(ex)}" +
|
||||
(log.Count > 0 ? $" (done before the failure: {string.Join("; ", log)})" : "");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Exception type, message and the innermost frame, for a one-line report.
|
||||
private static string Describe(Exception ex)
|
||||
{
|
||||
string? frame = ex.StackTrace?.Split('\n').Select(l => l.Trim()).FirstOrDefault(l => l.Length > 0);
|
||||
return $"{ex.GetType().Name}: {ex.Message}" + (frame != null ? $" [{frame}]" : "");
|
||||
}
|
||||
|
||||
// ── mirror ───────────────────────────────────────────────────────────────
|
||||
|
||||
// Copies HKLM entries the per-user list lacks, and refreshes copies nobody changed
|
||||
// since we wrote them (so a filter the user enables/disables machine-wide follows).
|
||||
private static void SyncMirror(RegistryKey machine, RegistryKey user, State state, List<string> log)
|
||||
{
|
||||
int added = 0, refreshed = 0;
|
||||
foreach (string name in machine.GetValueNames())
|
||||
{
|
||||
if (name.Length == 0) continue;
|
||||
object? v = machine.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
|
||||
if (v == null) continue;
|
||||
RegistryValueKind kind = machine.GetValueKind(name);
|
||||
object? have = user.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
|
||||
bool ours = state.MirroredValues.TryGetValue(name, out string? print);
|
||||
if (have == null || (ours && ValuePrint(user.GetValueKind(name), have) == print))
|
||||
{
|
||||
user.SetValue(name, v, kind);
|
||||
state.MirroredValues[name] = ValuePrint(kind, v);
|
||||
}
|
||||
}
|
||||
foreach (string name in machine.GetSubKeyNames())
|
||||
{
|
||||
if (string.Equals(name, FilterGuid, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
using RegistryKey? src = machine.OpenSubKey(name);
|
||||
if (src == null) continue;
|
||||
string srcPrint = Fingerprint(src);
|
||||
using RegistryKey? existing = user.OpenSubKey(name);
|
||||
if (existing == null)
|
||||
{
|
||||
using RegistryKey dst = user.CreateSubKey(name, writable: true);
|
||||
CopyTree(src, dst);
|
||||
state.MirroredKeys[name] = Fingerprint(dst);
|
||||
added++;
|
||||
}
|
||||
else if (state.MirroredKeys.TryGetValue(name, out string? written) &&
|
||||
Fingerprint(existing) == written && srcPrint != written)
|
||||
{
|
||||
existing.Dispose();
|
||||
user.DeleteSubKeyTree(name, throwOnMissingSubKey: false);
|
||||
using RegistryKey dst = user.CreateSubKey(name, writable: true);
|
||||
CopyTree(src, dst);
|
||||
state.MirroredKeys[name] = Fingerprint(dst);
|
||||
refreshed++;
|
||||
}
|
||||
}
|
||||
if (added > 0) log.Add($"mirrored {added} HKLM filter entr{(added == 1 ? "y" : "ies")} (so Decal still sees them)");
|
||||
if (refreshed > 0) log.Add($"refreshed {refreshed} mirrored entr{(refreshed == 1 ? "y" : "ies")} from HKLM");
|
||||
}
|
||||
|
||||
private static void CopyTree(RegistryKey src, RegistryKey dst)
|
||||
{
|
||||
foreach (string name in src.GetValueNames())
|
||||
{
|
||||
object? v = src.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
|
||||
if (v != null) dst.SetValue(name, v, src.GetValueKind(name));
|
||||
}
|
||||
foreach (string sub in src.GetSubKeyNames())
|
||||
{
|
||||
using RegistryKey? s = src.OpenSubKey(sub);
|
||||
if (s == null) continue;
|
||||
using RegistryKey d = dst.CreateSubKey(sub, writable: true);
|
||||
CopyTree(s, d);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A stable text form of a key's values and subkeys, to tell "still as we wrote it".</summary>
|
||||
private static string Fingerprint(RegistryKey key)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
foreach (string name in key.GetValueNames().OrderBy(n => n, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
object? v = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
|
||||
if (v == null) continue;
|
||||
RegistryValueKind kind;
|
||||
try { kind = key.GetValueKind(name); }
|
||||
catch (IOException) { continue; } // removed between the listing and the read
|
||||
sb.Append(name.ToLowerInvariant()).Append('=').Append(ValuePrint(kind, v)).Append(';');
|
||||
}
|
||||
foreach (string sub in key.GetSubKeyNames().OrderBy(n => n, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
using RegistryKey? s = key.OpenSubKey(sub);
|
||||
if (s != null) sb.Append('[').Append(sub.ToLowerInvariant()).Append(':').Append(Fingerprint(s)).Append(']');
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string ValuePrint(RegistryValueKind kind, object v) => kind + ":" + v switch
|
||||
{
|
||||
byte[] b => Convert.ToHexString(b),
|
||||
string[] a => string.Join("\u0001", a),
|
||||
_ => Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty,
|
||||
};
|
||||
|
||||
// ── registry helpers ─────────────────────────────────────────────────────
|
||||
|
||||
private static RegistryKey UserHive() => RegistryKey.OpenBaseKey(RegistryHive.CurrentUser,
|
||||
Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Default);
|
||||
|
||||
private static RegistryKey? OpenUserFilters(bool writable) => UserHive().OpenSubKey(VirtualStoreFiltersSubKey, writable);
|
||||
|
||||
private static RegistryKey? OpenMachineFilters() =>
|
||||
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView).OpenSubKey(DecalFiltersSubKey);
|
||||
|
||||
private static bool IsOurs(RegistryKey k) =>
|
||||
string.Equals(k.GetValue("Object") as string, FilterObject, StringComparison.Ordinal);
|
||||
|
||||
private static bool Enabled(RegistryKey k) => k.GetValue("Enabled") is int e && e != 0;
|
||||
|
||||
private static void ReadEntry(RegistryKey k, Status s)
|
||||
{
|
||||
s.Enabled = Enabled(k);
|
||||
s.RegisteredPath = k.GetValue("Path") as string;
|
||||
s.DllPresent = s.RegisteredPath != null && File.Exists(Path.Combine(s.RegisteredPath, AssemblyFile));
|
||||
}
|
||||
|
||||
private static string DescribeFilter(RegistryKey parent, string name)
|
||||
{
|
||||
using RegistryKey? k = parent.OpenSubKey(name);
|
||||
return k?.GetValue("") is string friendly && friendly.Length > 0 ? friendly : name;
|
||||
}
|
||||
|
||||
private static void SetIfDifferent(RegistryKey key, string name, object value, RegistryValueKind kind, List<string> log)
|
||||
{
|
||||
object? have = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
|
||||
if (have != null && key.GetValueKind(name) == kind && Equals(have, value))
|
||||
return;
|
||||
key.SetValue(name, value, kind);
|
||||
log.Add($"set {(name.Length == 0 ? "(default)" : name)}");
|
||||
}
|
||||
|
||||
private static State? LoadState()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(StatePath)) return null;
|
||||
State? s = JsonSerializer.Deserialize<State>(File.ReadAllText(StatePath));
|
||||
if (s == null) return null;
|
||||
// Dictionary comparers don't survive serialization.
|
||||
s.MirroredKeys = new Dictionary<string, string>(s.MirroredKeys, StringComparer.OrdinalIgnoreCase);
|
||||
s.MirroredValues = new Dictionary<string, string>(s.MirroredValues, StringComparer.OrdinalIgnoreCase);
|
||||
return s;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void SaveState(State s)
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(StatePath);
|
||||
if (dir != null) Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(StatePath, JsonSerializer.Serialize(s, new JsonSerializerOptions { WriteIndented = true }));
|
||||
}
|
||||
}
|
||||
|
|
@ -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,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace RynthCore.App;
|
||||
|
||||
|
|
@ -12,7 +13,26 @@ internal sealed class LaunchAccountProfile
|
|||
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString("N");
|
||||
public string AccountName { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
|
||||
/// The saved password, DPAPI-encrypted for the current Windows user (base64, see
|
||||
/// AccountPasswordProtection). Empty = no password saved. Decrypt only when launching:
|
||||
/// TryGetPasswordForLaunch.
|
||||
public string PasswordProtected { get; set; } = string.Empty;
|
||||
|
||||
/// Plain-text "Password" from a settings file written before passwords were encrypted.
|
||||
/// Read only: AppSettingsStore.Load encrypts it into PasswordProtected and clears this, so it
|
||||
/// is never written again (null is skipped on save). Stays set only if encryption failed.
|
||||
[JsonPropertyName("Password")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? LegacyPlainPassword { get; set; }
|
||||
|
||||
/// Set when the saved password can't be decrypted on this Windows user (settings copied
|
||||
/// from another user or PC). The UI asks for the password again; launching is refused.
|
||||
[JsonIgnore]
|
||||
public bool PasswordNeedsReentry { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public bool HasSavedPassword => !string.IsNullOrEmpty(PasswordProtected) || !string.IsNullOrEmpty(LegacyPlainPassword);
|
||||
public string CharacterName { get; set; } = string.Empty;
|
||||
public string Alias { get; set; } = string.Empty;
|
||||
public string ServerId { get; set; } = string.Empty;
|
||||
|
|
@ -65,7 +85,9 @@ internal sealed class LaunchAccountProfile
|
|||
{
|
||||
Id = Id,
|
||||
AccountName = AccountName,
|
||||
Password = Password,
|
||||
PasswordProtected = PasswordProtected,
|
||||
LegacyPlainPassword = LegacyPlainPassword,
|
||||
PasswordNeedsReentry = PasswordNeedsReentry,
|
||||
CharacterName = CharacterName,
|
||||
Alias = Alias,
|
||||
ServerId = ServerId,
|
||||
|
|
@ -84,7 +106,9 @@ internal sealed class LaunchAccountProfile
|
|||
{
|
||||
Id = source.Id;
|
||||
AccountName = source.AccountName;
|
||||
Password = source.Password;
|
||||
PasswordProtected = source.PasswordProtected;
|
||||
LegacyPlainPassword = source.LegacyPlainPassword;
|
||||
PasswordNeedsReentry = source.PasswordNeedsReentry;
|
||||
CharacterName = source.CharacterName;
|
||||
Alias = source.Alias;
|
||||
ServerId = source.ServerId;
|
||||
|
|
@ -98,6 +122,55 @@ internal sealed class LaunchAccountProfile
|
|||
OnLoginWaitMs = source.OnLoginWaitMs;
|
||||
}
|
||||
|
||||
/// <summary>Saves a new password (encrypted at once; the plain text is not kept).</summary>
|
||||
public void SetPassword(string? plainText)
|
||||
{
|
||||
PasswordProtected = AccountPasswordProtection.Protect(plainText);
|
||||
LegacyPlainPassword = null;
|
||||
PasswordNeedsReentry = false;
|
||||
}
|
||||
|
||||
public void ClearPassword()
|
||||
{
|
||||
PasswordProtected = string.Empty;
|
||||
LegacyPlainPassword = null;
|
||||
PasswordNeedsReentry = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The password to hand the client, decrypted now. True with "" when none is saved. False
|
||||
/// (and PasswordNeedsReentry set) when the saved one can't be decrypted on this Windows user;
|
||||
/// the caller must not launch with an empty password instead. Use the result at once and
|
||||
/// don't store it.
|
||||
/// </summary>
|
||||
public bool TryGetPasswordForLaunch(out string password, out string problem)
|
||||
{
|
||||
problem = string.Empty;
|
||||
if (!string.IsNullOrEmpty(LegacyPlainPassword))
|
||||
{
|
||||
password = LegacyPlainPassword;
|
||||
return true;
|
||||
}
|
||||
if (string.IsNullOrEmpty(PasswordProtected))
|
||||
{
|
||||
password = string.Empty;
|
||||
return true;
|
||||
}
|
||||
if (AccountPasswordProtection.TryUnprotect(PasswordProtected, out password))
|
||||
{
|
||||
PasswordNeedsReentry = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
PasswordNeedsReentry = true;
|
||||
problem = PasswordNeedsReentryMessage(AccountName);
|
||||
return false;
|
||||
}
|
||||
|
||||
public static string PasswordNeedsReentryMessage(string? accountName) =>
|
||||
$"The saved password for account '{accountName}' can't be read on this Windows user " +
|
||||
"(settings copied from another user or PC?). Password needs re-entering: edit the account and type it again.";
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return DisplayName;
|
||||
|
|
|
|||
274
src/RynthCore.App/RealDecalCheckHost.cs
Normal file
274
src/RynthCore.App/RealDecalCheckHost.cs
Normal 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);
|
||||
}
|
||||
394
src/RynthCore.DecalBridge/BridgeFilter.cs
Normal file
394
src/RynthCore.DecalBridge/BridgeFilter.cs
Normal 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 { }
|
||||
}
|
||||
}
|
||||
}
|
||||
302
src/RynthCore.DecalBridge/BridgeProtocol.cs
Normal file
302
src/RynthCore.DecalBridge/BridgeProtocol.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue