RynthSuite as of 2026-09-05 (internal a5ff5c2)

A snapshot of the working tree for aelrynth.com/git/: the code, build files
and public docs. Internal review notes and agent instructions are left out.
MIT licensed; see LICENSE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-09-25 21:23:05 -04:00
commit 0a4b611a90
166 changed files with 186537 additions and 0 deletions

View file

@ -0,0 +1,78 @@
using System;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthVision.Overlays;
/// <summary>
/// Draws a horizontal ring on the ground centred on the player at the radar
/// detection range. Needs no terrain data — just the player pose — so it's the
/// reference for the Nav3D render path being wired correctly.
/// </summary>
internal sealed class RadarRingOverlay
{
private readonly RynthCoreHost _host;
private readonly VisionSettings _settings;
// Auto-diagnostic: log the first submit per landblock so the user can
// verify the ring centre matches the character (not the camera) without
// having to remember the `/rv debug` opt-in.
private uint _lastLoggedLandblock;
public RadarRingOverlay(RynthCoreHost host, VisionSettings settings)
{
_host = host;
_settings = settings;
}
public void Submit()
{
if (!_settings.ShowRadarRing)
return;
try
{
if (!_host.TryGetPlayerPose(out uint cellId, out float east, out float north, out float up,
out _, out _, out _, out _))
return;
if ((cellId >> 16) == 0) return; // portalspace / not in the world
if ((cellId & 0xFFFF) >= 0x100) return; // indoor — pose is cell-local, not landblock-local
// Nav3D world frame is Y-up: (x=east, y=up, z=north). The player
// pose is AC convention (x=east, y=north, z=up), so swap y/z here.
// (See RynthAi's TerrainPassabilityOverlay for the same mapping.)
float radius = MathF.Max(5f, _settings.RadarRangeWorld);
_host.Nav3DAddRingEx(east, up, north, radius,
_settings.RadarRingThickness, _settings.RadarRingHeight,
_settings.RadarRingColorArgb);
uint landblock = cellId >> 16;
if (landblock != _lastLoggedLandblock)
{
_lastLoggedLandblock = landblock;
LogRingPlacement(cellId, east, north, up, radius);
}
}
catch (Exception ex)
{
_host.Log($"[RynthVision] RadarRing: {ex.Message}");
}
}
// Reports where the ring centre projects on screen. If the projected centre
// is near the viewport's horizontal middle and roughly at the character's
// feet, the ring is anchored to the player. If it tracks the camera-look
// direction instead, either TryGetPlayerPose is returning the wrong object
// (e.g. SmartBox+0xF8 reassigned during freelook) or the engine view matrix
// (built from SmartBox+0x08 'viewer' Position) is misaligned with what AC
// is actually rendering. The screen X/Y in the log makes either case
// obvious without needing to enable /rv debug.
private void LogRingPlacement(uint cellId, float east, float north, float up, float radius)
{
string screen = "n/a";
if (_host.HasWorldToScreen && _host.WorldToScreen(east, up, north, out float sx, out float sy))
screen = $"({sx:F0},{sy:F0})";
string vp = _host.TryGetViewportSize(out uint vpW, out uint vpH) ? $"{vpW}x{vpH}" : "n/a";
_host.Log($"[RynthVision] RadarRing placed cell=0x{cellId:X8} centre=({east:F1},{north:F1},{up:F1}) " +
$"r={radius:F0} screen={screen} vp={vp}");
}
}

View file

@ -0,0 +1,159 @@
using System;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.PluginSdk;
using RynthCore.TerrainData;
namespace RynthCore.Plugin.RynthVision.Overlays;
/// <summary>
/// Highlights unclimbable (too-steep) terrain triangles around the player by
/// submitting each unwalkable triangle as a filled Nav3D triangle whose
/// vertices are the actual landblock mesh corners. The face sits exactly on
/// the slope so the player sees precisely the area they can't traverse.
///
/// Coverage extends past the player's landblock — at high radii the iteration
/// reaches into the neighbouring 8 landblocks and renders their slopes too.
/// All coordinates are emitted in PLAYER-landblock-local space; the engine's
/// view-matrix capture shifts the camera into the same frame so the markers
/// stay anchored to the world even when the camera orbits across a landblock
/// boundary and AC re-anchors its rendering origin to a different landblock.
///
/// Each 24 m cell is split along an AC-PRNG-selected diagonal (SW→NE or
/// SE→NW — <see cref="TerrainSampler.SwToNeCut"/>); only the unwalkable half
/// or halves are painted.
/// </summary>
internal sealed class SlopeOverlay
{
private const float Cell = 24f;
private const int CellsPerSide = 8;
private readonly RynthCoreHost _host;
private readonly VisionSettings _settings;
private readonly TerrainSampler _terrain;
public SlopeOverlay(RynthCoreHost host, VisionSettings settings, TerrainSampler terrain)
{
_host = host;
_settings = settings;
_terrain = terrain;
}
public void Submit()
{
if (!_settings.ShowUnclimbableSlopes || !_host.HasNav3D || !_terrain.IsReady)
return;
if (!_host.HasNav3DTriangle) // requires API v60+
return;
if (!_host.TryGetPlayerPose(out uint cellId, out float px, out float py, out _,
out _, out _, out _, out _))
return;
if ((cellId & 0xFFFF) >= 0x100) return; // indoor
if ((cellId >> 16) == 0) return; // portalspace
int playerLbX = (int)((cellId >> 24) & 0xFF);
int playerLbY = (int)((cellId >> 16) & 0xFF);
// Player's cell within their landblock.
int playerCX = Math.Clamp((int)(px / Cell), 0, CellsPerSide - 1);
int playerCY = Math.Clamp((int)(py / Cell), 0, CellsPerSide - 1);
int radius = Math.Clamp(_settings.SlopeRenderRadius, 1, 24);
uint color = _settings.SlopeColorArgb;
float floorZ = Math.Clamp(_settings.SlopeFloorZ, 0.05f, 0.999f);
float bias = Math.Clamp(_settings.SlopeHeightBias, 0f, 5f);
// Per-tick landblock cache so a single Submit doesn't reload the same
// landblock 50 times. The TerrainSampler also caches, but that's a
// dictionary lookup per cell — this is a small local array indexed by
// (lbDX+2, lbDY+2) covering up to ±2 landblocks (24-cell radius caps
// at 3-landblock extent each direction).
const int LbSpan = 5; // -2..+2
var lbCache = new LandblockData?[LbSpan * LbSpan];
var lbCacheLoaded = new bool[LbSpan * LbSpan];
// Iterate outward in cell rings so the nearest cells are submitted
// first — they survive if the engine's triangle budget is hit.
for (int r = 0; r <= radius; r++)
{
for (int dx = -r; dx <= r; dx++)
{
for (int dy = -r; dy <= r; dy++)
{
if (Math.Abs(dx) < r && Math.Abs(dy) < r) continue;
int absCellX = playerCX + dx;
int absCellY = playerCY + dy;
// Decompose into (landblock-delta, local-cell) using
// arithmetic that handles negative values cleanly.
int lbDX = FloorDiv(absCellX, CellsPerSide);
int lbDY = FloorDiv(absCellY, CellsPerSide);
int localCX = absCellX - lbDX * CellsPerSide;
int localCY = absCellY - lbDY * CellsPerSide;
int lbX = playerLbX + lbDX;
int lbY = playerLbY + lbDY;
if (lbX < 0 || lbX > 0xFF || lbY < 0 || lbY > 0xFF) continue;
if (lbDX < -2 || lbDX > 2 || lbDY < -2 || lbDY > 2) continue;
int cacheIdx = (lbDX + 2) * LbSpan + (lbDY + 2);
LandblockData? lb;
if (lbCacheLoaded[cacheIdx])
{
lb = lbCache[cacheIdx];
}
else
{
uint lbKey = (uint)((lbX << 8) | lbY);
lb = _terrain.LoadLandblock(lbKey);
lbCache[cacheIdx] = lb;
lbCacheLoaded[cacheIdx] = true;
}
if (lb == null) continue;
bool swToNe = TerrainSampler.SwToNeCut(lb.LandblockKey, localCX, localCY);
TerrainSampler.GetTrianglePassability(lb, localCX, localCY, swToNe,
out bool t1ok, out bool t2ok, floorZ);
if (t1ok && t2ok) continue;
// World coords in PLAYER-landblock-local frame: cell SW
// corner is (lbDX*192 + localCX*24, lbDY*192 + localCY*24).
float x0 = lbDX * 192f + localCX * Cell;
float x1 = x0 + Cell;
float z0 = lbDY * 192f + localCY * Cell;
float z1 = z0 + Cell;
float h00 = lb.GetVertexZ(localCX, localCY) + bias;
float h10 = lb.GetVertexZ(localCX + 1, localCY) + bias;
float h01 = lb.GetVertexZ(localCX, localCY + 1) + bias;
float h11 = lb.GetVertexZ(localCX + 1, localCY + 1) + bias;
if (swToNe)
{
// SE half (SW, SE, NE) below the SW→NE diagonal
if (!t1ok)
_host.Nav3DAddTriangle(x0, h00, z0, x1, h10, z0, x1, h11, z1, color);
// NW half (SW, NE, NW) above the SW→NE diagonal
if (!t2ok)
_host.Nav3DAddTriangle(x0, h00, z0, x1, h11, z1, x0, h01, z1, color);
}
else
{
// SW half (SW, SE, NW) below the SE→NW diagonal
if (!t1ok)
_host.Nav3DAddTriangle(x0, h00, z0, x1, h10, z0, x0, h01, z1, color);
// NE half (SE, NE, NW) above the SE→NW diagonal
if (!t2ok)
_host.Nav3DAddTriangle(x1, h10, z0, x1, h11, z1, x0, h01, z1, color);
}
}
}
}
}
// Floor division that handles negatives the way we need: FloorDiv(-1, 8) = -1, not 0.
private static int FloorDiv(int a, int b)
{
int q = a / b;
if ((a % b != 0) && ((a < 0) != (b < 0))) q--;
return q;
}
}

View file

@ -0,0 +1,222 @@
using System;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.PluginSdk;
using RynthCore.TerrainData;
namespace RynthCore.Plugin.RynthVision.Overlays;
/// <summary>
/// Highlights LANDBLOCKS that AC's physics treats as fully impassable water
/// — every vertex is a water terrain type (the "EntirelyWater" branch of
/// ACE LandblockStruct.CalcWater). When a regular character enters such a
/// landblock, LandCell.find_terrain_poly returns TransitionState.Collided
/// outright — no depth check needed, the player can't enter at all. Those
/// are the open-ocean / deep-lake landblocks the user can't walk through.
///
/// Partial-water landblocks (shorelines, wadeable rivers/ponds) are
/// intentionally NOT painted here: AC determines passability per position
/// via get_water_depth() against a water surface Z we don't have access
/// to from the dat files alone, so any heuristic over-marks or
/// under-marks. Use the SLOPE overlay alongside for shoreline drop-offs.
///
/// Iterates landblocks in a cell-radius around the player that can extend
/// into the 8 surrounding landblocks; emits triangles in PLAYER-landblock-
/// local coordinates so the engine's view-matrix shift keeps them anchored
/// when the camera crosses a landblock boundary.
/// </summary>
internal sealed class WaterOverlay
{
// Water cells get a slightly larger bias than slopes because the water
// surface usually sits exactly at the mesh Z, so even tiny z-fighting
// here is visible.
private const float HeightBias = 0.20f;
private const float Cell = 24f;
private const int CellsPerSide = 8;
private readonly RynthCoreHost _host;
private readonly VisionSettings _settings;
private readonly TerrainSampler _terrain;
// Auto-diagnostic: one log per landblock entry summarising what we found
// (cell count, types present, types matched). Mirrors RadarRingOverlay's
// pattern — saves the user from having to type /rv watertypes when water
// isn't being marked where they expect it.
private uint _lastDiagLandblock;
public WaterOverlay(RynthCoreHost host, VisionSettings settings, TerrainSampler terrain)
{
_host = host;
_settings = settings;
_terrain = terrain;
}
public void Submit()
{
if (!_settings.ShowImpassableWater || !_host.HasNav3D || !_terrain.IsReady)
return;
if (!_host.HasNav3DTriangle) // requires API v60+
return;
if (!_host.TryGetPlayerPose(out uint cellId, out float px, out float py, out _,
out _, out _, out _, out _))
return;
if ((cellId & 0xFFFF) >= 0x100) return; // indoor
if ((cellId >> 16) == 0) return; // portalspace
int playerLbX = (int)((cellId >> 24) & 0xFF);
int playerLbY = (int)((cellId >> 16) & 0xFF);
int playerCX = Math.Clamp((int)(px / Cell), 0, CellsPerSide - 1);
int playerCY = Math.Clamp((int)(py / Cell), 0, CellsPerSide - 1);
int radius = Math.Clamp(_settings.WaterRenderRadius, 1, 24);
uint color = _settings.WaterColorArgb;
const int LbSpan = 5; // -2..+2
var lbCache = new LandblockData?[LbSpan * LbSpan];
var lbCacheLoaded = new bool[LbSpan * LbSpan];
// Per-landblock "fully water" flag — when every one of the 81 vertices
// in a landblock matches a water terrain type, the entire 192×192 m
// area is open sea / impassable lake. Paint all 64 cells regardless
// of the per-cell corner rule, so deep open-water landblocks fill
// solidly instead of leaving gaps where the per-cell filter is too
// strict.
var lbFullyWater = new bool[LbSpan * LbSpan];
int submittedCells = 0;
uint playerLandblock = cellId >> 16;
for (int dx = -radius; dx <= radius; dx++)
{
for (int dy = -radius; dy <= radius; dy++)
{
int absCellX = playerCX + dx;
int absCellY = playerCY + dy;
int lbDX = FloorDiv(absCellX, CellsPerSide);
int lbDY = FloorDiv(absCellY, CellsPerSide);
int localCX = absCellX - lbDX * CellsPerSide;
int localCY = absCellY - lbDY * CellsPerSide;
int lbX = playerLbX + lbDX;
int lbY = playerLbY + lbDY;
if (lbX < 0 || lbX > 0xFF || lbY < 0 || lbY > 0xFF) continue;
if (lbDX < -2 || lbDX > 2 || lbDY < -2 || lbDY > 2) continue;
int cacheIdx = (lbDX + 2) * LbSpan + (lbDY + 2);
LandblockData? lb;
if (lbCacheLoaded[cacheIdx])
{
lb = lbCache[cacheIdx];
}
else
{
uint lbKey = (uint)((lbX << 8) | lbY);
lb = _terrain.LoadLandblock(lbKey);
lbCache[cacheIdx] = lb;
lbCacheLoaded[cacheIdx] = true;
if (lb != null) lbFullyWater[cacheIdx] = ComputeFullyWater(lb);
}
if (lb == null) continue;
// Only paint fully-water (EntirelyWater) landblocks — that's
// the precise AC condition for "physics collides immediately,
// no depth math". Partial-water landblocks deliberately skipped
// (see class-summary).
if (!lbFullyWater[cacheIdx]) continue;
float x0 = lbDX * 192f + localCX * Cell;
float x1 = x0 + Cell;
float z0 = lbDY * 192f + localCY * Cell;
float z1 = z0 + Cell;
float h00 = lb.GetVertexZ(localCX, localCY) + HeightBias;
float h10 = lb.GetVertexZ(localCX + 1, localCY) + HeightBias;
float h01 = lb.GetVertexZ(localCX, localCY + 1) + HeightBias;
float h11 = lb.GetVertexZ(localCX + 1, localCY + 1) + HeightBias;
// Water cells get both triangles filled — we don't care which
// diagonal AC's PRNG picked; either pair of triangles covers
// the same flat-ish square. Use SW→NE split for simplicity.
_host.Nav3DAddTriangle(x0, h00, z0, x1, h10, z0, x1, h11, z1, color);
_host.Nav3DAddTriangle(x0, h00, z0, x1, h11, z1, x0, h01, z1, color);
submittedCells++;
}
}
// One-shot per-landblock diagnostic. Whenever we cross to a new
// landblock, log what we found: which terrain types are present in
// the player's landblock, and how many cells we painted as water.
// If the user expects water marked here but submittedCells=0, the
// log will show what types ARE present so they can adjust
// VisionSettings.WaterTerrainTypes.
if (playerLandblock != _lastDiagLandblock)
{
_lastDiagLandblock = playerLandblock;
LogWaterDiag(_terrain.LoadLandblock(playerLandblock), submittedCells, radius);
}
}
private void LogWaterDiag(LandblockData? lb, int submittedCells, int radius)
{
if (lb == null) return;
var seen = new System.Collections.Generic.SortedSet<int>();
for (int ix = 0; ix < 9; ix++)
for (int iy = 0; iy < 9; iy++)
seen.Add(TerrainSampler.GetTerrainType(lb, ix, iy));
string types = string.Join(",", seen);
string configured = string.Join(",", _settings.WaterTerrainTypes);
string anyMatch = "false";
foreach (int t in seen)
foreach (int w in _settings.WaterTerrainTypes)
if (t == w) { anyMatch = "true"; goto done; }
done:
bool fullyWater = ComputeFullyWater(lb);
_host.Log($"[RynthVision] Water lb=0x{lb.LandblockKey:X4} cellsPainted={submittedCells} r={radius} " +
$"presentTypes=[{types}] configured=[{configured}] anyMatch={anyMatch} " +
$"anyCorner={_settings.WaterAnyCorner} fullyWaterLb={fullyWater}");
}
// VisionSettings.WaterAnyCorner toggles between "any corner is water" (catches
// shorelines, default) and "all four corners are water" (skips shoreline
// cells, marks only fully-water cells). AC's own impassability check is
// depth-based and not derivable from terrain types alone — for the
// "actually impassable" signal, enable the SLOPE overlay alongside; the
// overlap of red (slope-blocked) and blue (water) is where you can't walk.
private bool IsWaterCell(LandblockData lb, int cx, int cy)
{
bool sw = IsWater(lb, cx, cy);
bool se = IsWater(lb, cx + 1, cy);
bool nw = IsWater(lb, cx, cy + 1);
bool ne = IsWater(lb, cx + 1, cy + 1);
return _settings.WaterAnyCorner
? (sw || se || nw || ne)
: (sw && se && nw && ne);
}
private bool IsWater(LandblockData lb, int ix, int iy)
{
int type = TerrainSampler.GetTerrainType(lb, ix, iy);
int[] set = _settings.WaterTerrainTypes;
for (int i = 0; i < set.Length; i++)
if (set[i] == type) return true;
return false;
}
// True only when every one of the landblock's 81 vertices is a configured
// water-type. That means there's NO dry land anywhere in the landblock,
// so the entire 192×192 m area is open water and the player can't enter
// any of it — paint the whole thing solid rather than risking gaps.
private bool ComputeFullyWater(LandblockData lb)
{
for (int ix = 0; ix < 9; ix++)
for (int iy = 0; iy < 9; iy++)
if (!IsWater(lb, ix, iy)) return false;
return true;
}
private static int FloorDiv(int a, int b)
{
int q = a / b;
if ((a % b != 0) && ((a < 0) != (b < 0))) q--;
return q;
}
}

View file

@ -0,0 +1,82 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthVision;
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthVisionPlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthVisionPlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthVisionPlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Render() => Runtime.OnRender();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
// ── Avalonia settings-panel bridge (engine RynthVisionPanel) ──────────────
// The panel reads RynthVisionGetSettingsJson to populate its controls and
// pushes changes via RynthVisionSetSettings. The pointer swap (alloc-new →
// swap → free-old) keeps the UI-thread caller safe without a lock, matching
// the RynthChat scrollback bridge.
private static IntPtr _settingsPtr = IntPtr.Zero;
[UnmanagedCallersOnly(EntryPoint = "RynthVisionGetSettingsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetSettingsJson()
{
try
{
string json = Runtime.Plugin?.BuildSettingsJson() ?? "{}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _settingsPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "RynthVisionSetSettings", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetSettings(IntPtr ansiJson)
{
try
{
if (ansiJson == IntPtr.Zero) return;
string? json = Marshal.PtrToStringAnsi(ansiJson);
if (!string.IsNullOrEmpty(json))
Runtime.Plugin?.ApplySettingsJson(json);
}
catch { }
}
[UnmanagedCallersOnly(EntryPoint = "RynthVisionInspectTerrain", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void InspectTerrain() => Runtime.Plugin?.InspectTerrain();
}

View file

@ -0,0 +1,47 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthVision</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthVision</AssemblyName>
<Platforms>x86</Platforms>
<!-- Publish straight to the plugin's launcher-registered home so a bare
`dotnet publish` lands where the engine hot-reloads it. Build still
uses bin\; only publish is redirected. Deploy-RynthCore.ps1 points its
copy step at this same path and skips the redundant self-copy. -->
<PublishDir>C:\Games\RynthSuite\RynthVision\</PublishDir>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
</ItemGroup>
<ItemGroup>
<TrimmerRootAssembly Include="ImGui.NET" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<ProjectReference Include="..\..\Shared\RynthCore.TerrainData\RynthCore.TerrainData.csproj" />
</ItemGroup>
<Target Name="RemoveBundledImGuiNativeFromBuild" AfterTargets="Build">
<Delete Files="$(OutputPath)cimgui.dll" Condition="Exists('$(OutputPath)cimgui.dll')" />
</Target>
<Target Name="RemoveBundledImGuiNativeFromPublish" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
<Delete Files="$(PublishDir)cimgui.dll" Condition="Exists('$(PublishDir)cimgui.dll')" />
</Target>
</Project>

View file

@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.Plugin.RynthVision.Overlays;
using RynthCore.PluginCore;
using RynthCore.TerrainData;
namespace RynthCore.Plugin.RynthVision;
/// <summary>
/// World-space visualization plugin (a RynthCore-native take on Decal's
/// SkunkVision): highlights unclimbable slopes, impassable water, and a
/// radar-range ring using the engine's Nav3D overlay API. Settings are driven by
/// the engine's Avalonia "Vision" panel (via the bridge methods below) or the
/// /rv chat command, and persist to %APPDATA%\RynthCore\rynthvision.json.
/// </summary>
public sealed class RynthVisionPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthVision");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0");
private readonly VisionSettings _settings = new();
private readonly TerrainSampler _terrain = new();
private RadarRingOverlay? _radarRing;
private SlopeOverlay? _slopes;
private WaterOverlay? _water;
// Diagnostic: /rv debug streams the player pose so we can tell whether it
// tracks the character or the camera (the radar-ring placement bug).
private bool _debugPose;
private int _dbgTick;
public override int Initialize()
{
_settings.Load();
_radarRing = new RadarRingOverlay(Host, _settings);
_slopes = new SlopeOverlay(Host, _settings, _terrain);
_water = new WaterOverlay(Host, _settings, _terrain);
Host.Log("[RynthVision] Initialized. Use the Vision panel, or /rv [radar|slopes|water|watertypes|debug].");
return 0;
}
public override void OnLoginComplete()
{
if (_terrain.Initialize())
Host.Log("[RynthVision] Terrain data ready.");
else
Host.Log($"[RynthVision] Terrain data unavailable: {_terrain.Status} (slopes/water disabled).");
}
public override void OnLogout() => Host.Log("[RynthVision] Logout.");
public override void Shutdown() => _terrain.Dispose();
// Nav3D geometry is buffered every tick and drawn by the engine at end of
// frame (after the 3D pass). Submitting from OnTick rather than OnRender
// keeps overlays alive even when the ImGui shell is disabled.
public override void OnTick()
{
if (!Host.HasNav3D)
return;
_radarRing?.Submit();
_slopes?.Submit();
_water?.Submit();
if (_debugPose && (++_dbgTick % 30 == 0))
LogPose();
}
public override void OnChatBarEnter(string? text, ref int eat)
{
if (string.IsNullOrWhiteSpace(text) || !text.StartsWith("/rv", StringComparison.OrdinalIgnoreCase))
return;
eat = 1; // consume — don't send to the server as chat
string arg = text.Length > 3 ? text.Substring(3).Trim().ToLowerInvariant() : string.Empty;
switch (arg)
{
case "radar": _settings.ShowRadarRing = !_settings.ShowRadarRing; break;
case "slopes": _settings.ShowUnclimbableSlopes = !_settings.ShowUnclimbableSlopes; break;
case "water": _settings.ShowImpassableWater = !_settings.ShowImpassableWater; break;
case "watertypes": InspectTerrain(); return;
case "debug": _debugPose = !_debugPose; Host.Log($"[RynthVision] pose debug = {_debugPose}"); return;
case "": break;
default:
Host.Log($"[RynthVision] Unknown option '{arg}'. Use radar | slopes | water | watertypes | debug.");
return;
}
_settings.Save();
Host.Log($"[RynthVision] radar={_settings.ShowRadarRing} slopes={_settings.ShowUnclimbableSlopes} water={_settings.ShowImpassableWater}");
}
// ── Bridge methods called from PluginExports (engine Avalonia panel) ───────
internal string BuildSettingsJson() => _settings.ToJson();
internal void ApplySettingsJson(string json)
{
_settings.ApplyJson(json);
_settings.Save();
}
// Streams pose + the terrain height under the player + the screen projection
// of the exact ring-centre coords. Lets us tell whether the ring's height
// (pose.z) matches the ground (terrainZ) and whether the centre projects to
// where the player actually is on screen (≈ viewport centre).
private void LogPose()
{
if (!Host.TryGetPlayerPose(out uint cellId, out float x, out float y, out float z,
out _, out _, out _, out _))
{
Host.Log("[RynthVision] DBG pose unavailable");
return;
}
float terrainZ = float.NaN;
if (_terrain.IsReady && (cellId & 0xFFFF) < 0x100 && (cellId >> 16) != 0)
{
LandblockData? lb = _terrain.LoadLandblock(cellId >> 16);
if (lb != null)
terrainZ = lb.GetVertexZ(Math.Clamp((int)(x / 24f), 0, 8), Math.Clamp((int)(y / 24f), 0, 8));
}
// Project the exact ring-centre coords (east=x, up=z, north=y) to screen.
string w2s = "n/a";
if (Host.HasWorldToScreen && Host.WorldToScreen(x, z, y, out float sx, out float sy))
w2s = $"({sx:F0},{sy:F0})";
Host.TryGetViewportSize(out uint vpW, out uint vpH);
Host.Log($"[RynthVision] DBG cell=0x{cellId:X8} pose=({x:F1},{y:F1},{z:F1}) terrainZ={terrainZ:F1} w2s={w2s} vp={vpW}x{vpH}");
}
/// <summary>
/// Logs the terrain-type index at the player's exact cell plus all distinct
/// types in the landblock — stand on impassable vs passable water to find
/// which indices belong in VisionSettings.WaterTerrainTypes.
/// </summary>
internal void InspectTerrain()
{
if (!_terrain.IsReady)
{
Host.Log($"[RynthVision] Terrain not ready: {_terrain.Status}");
return;
}
if (!Host.TryGetPlayerPose(out uint cellId, out float px, out float py, out _, out _, out _, out _, out _) ||
(cellId & 0xFFFF) >= 0x100 || (cellId >> 16) == 0)
{
Host.Log("[RynthVision] Stand outdoors to inspect terrain types.");
return;
}
LandblockData? lb = _terrain.LoadLandblock(cellId >> 16);
if (lb == null)
{
Host.Log("[RynthVision] No terrain data for this landblock.");
return;
}
int cx = Math.Clamp((int)(px / 24f), 0, 8);
int cy = Math.Clamp((int)(py / 24f), 0, 8);
int hereType = TerrainSampler.GetTerrainType(lb, cx, cy);
var seen = new SortedSet<int>();
for (int ix = 0; ix < 9; ix++)
for (int iy = 0; iy < 9; iy++)
seen.Add(TerrainSampler.GetTerrainType(lb, ix, iy));
Host.Log($"[RynthVision] At cell ({cx},{cy}) terrain type = {hereType}. Landblock types: {string.Join(", ", seen)}");
}
}

View file

@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.Json;
namespace RynthCore.Plugin.RynthVision;
/// <summary>
/// Feature toggles and colours for RynthVision overlays. Colours are ARGB
/// (0xAARRGGBB) to match the engine's Nav3D API. Persists to
/// %APPDATA%\RynthCore\rynthvision.json; the engine's Avalonia panel reads and
/// writes these through the plugin's JSON bridge exports.
/// </summary>
internal sealed class VisionSettings
{
public bool ShowRadarRing = true;
public bool ShowUnclimbableSlopes = false;
public bool ShowImpassableWater = false;
public bool ShowDungeonLighting = false;
public uint SlopeColorArgb = 0x60FF2020; // semi-transparent red
public uint WaterColorArgb = 0x600060FF; // semi-transparent blue
public uint RadarRingColorArgb = 0x80FFD000; // semi-transparent gold
public float RadarRangeWorld = 192f;
public float RadarRingThickness = 2.0f;
// Cylinder-wall height for the radar ring, in world meters. Independent
// of thickness — a thin ring at e.g. 6 m height stands out against the
// landscape without becoming visually heavy. Default 3 m, range 0.5–30.
public float RadarRingHeight = 3.0f;
// Cell-radius around the player. 1 cell = 24 m. Slopes can extend across
// adjacent landblocks (see SlopeOverlay), so values above 8 cross
// landblock boundaries and pull in extra terrain data on demand. Default
// 12 cells (~288 m) gives roughly one landblock of look-ahead each
// direction; 24 cells is the practical max before the triangle budget
// becomes the bottleneck.
public int SlopeRenderRadius = 12;
// Same cell-radius idea as SlopeRenderRadius — extends across landblock
// boundaries when set large. Default 12 matches slopes for parity.
public int WaterRenderRadius = 12;
// Cell normal.Z threshold below which a triangle is treated as
// unwalkable. Matches ACE PhysicsGlobals.FloorZ (= cos 48.4°). Lower
// values are more permissive (only steeper slopes painted); higher
// values are stricter (gentler slopes start painting). Range roughly
// 0.3 (cos 72°, only near-cliffs) to 0.9 (cos 25°, mild hills).
public float SlopeFloorZ = 0.66417414618662751f;
// Vertical offset between the painted triangle and the actual terrain
// mesh. Higher values reduce z-fight flicker on steep faces but make
// the paint visibly hover above the ground. 0.05–0.3 m is the usable
// range.
public float SlopeHeightBias = 0.15f;
// AC terrain-type indices treated as water. This MUST mirror ACE's
// SurfChar[type]==1 lookup (LandblockStruct.cs:62-68) — indices 16..20:
// 0x10 = 16 WaterRunning
// 0x11 = 17 WaterStandingFresh
// 0x12 = 18 WaterShallowSea
// 0x13 = 19 WaterShallowStillSea
// 0x14 = 20 WaterDeepSea
// The overlay only paints landblocks whose every vertex is one of these
// types ("EntirelyWater" landblocks per ACE LandblockStruct.CalcWater),
// because that's exactly the condition AC's LandCell.find_terrain_poly
// turns into TransitionState.Collided for a regular character. Partial-
// water landblocks rely on per-position depth checks we don't have
// surface-Z data for, so we don't speculate.
public int[] WaterTerrainTypes = { 0x10, 0x11, 0x12, 0x13, 0x14 };
// Default true: a cell counts as water if ANY of its four corners is a
// water-type. With WaterImpassableOnly=true (also default), the cell
// additionally needs a too-steep triangle — so the visible result is
// "shoreline cells where the seafloor drops below walkable angle", i.e.
// the actual spots AC blocks you. all-four-corners was too strict at
// typical shorelines where only 1-2 vertices fall in deep water.
public bool WaterAnyCorner = true;
// When true, the water overlay only paints cells that are BOTH water
// AND have an unwalkable triangle (steep underwater slope). That's
// the actual "impassable water" — the deep parts where AC's slope
// physics blocks you at the shore drop-off. When false, every cell
// matching WaterTerrainTypes is painted regardless of walkability —
// useful as a "where is water" awareness overlay but does not signal
// impassability. Uses SlopeFloorZ as the steepness threshold.
public bool WaterImpassableOnly = true;
// ── JSON bridge (manual build + JsonDocument parse — both AOT-safe) ───────
public string ToJson()
{
var ci = CultureInfo.InvariantCulture;
return "{"
+ $"\"radar\":{(ShowRadarRing ? 1 : 0)},"
+ $"\"slopes\":{(ShowUnclimbableSlopes ? 1 : 0)},"
+ $"\"water\":{(ShowImpassableWater ? 1 : 0)},"
+ $"\"slopeColor\":{SlopeColorArgb},"
+ $"\"waterColor\":{WaterColorArgb},"
+ $"\"radarColor\":{RadarRingColorArgb},"
+ $"\"radarRange\":{RadarRangeWorld.ToString("R", ci)},"
+ $"\"ringThick\":{RadarRingThickness.ToString("R", ci)},"
+ $"\"ringHeight\":{RadarRingHeight.ToString("R", ci)},"
+ $"\"slopeRadius\":{SlopeRenderRadius},"
+ $"\"slopeFloorZ\":{SlopeFloorZ.ToString("R", ci)},"
+ $"\"slopeBias\":{SlopeHeightBias.ToString("R", ci)},"
+ $"\"waterRadius\":{WaterRenderRadius},"
+ $"\"waterAnyCorner\":{(WaterAnyCorner ? 1 : 0)},"
+ $"\"waterImpassableOnly\":{(WaterImpassableOnly ? 1 : 0)},"
+ $"\"waterTypes\":[{string.Join(",", WaterTerrainTypes)}]"
+ "}";
}
public void ApplyJson(string json)
{
using var doc = JsonDocument.Parse(json);
var r = doc.RootElement;
if (r.TryGetProperty("radar", out var v)) ShowRadarRing = v.GetInt32() != 0;
if (r.TryGetProperty("slopes", out v)) ShowUnclimbableSlopes = v.GetInt32() != 0;
if (r.TryGetProperty("water", out v)) ShowImpassableWater = v.GetInt32() != 0;
if (r.TryGetProperty("slopeColor", out v)) SlopeColorArgb = v.GetUInt32();
if (r.TryGetProperty("waterColor", out v)) WaterColorArgb = v.GetUInt32();
if (r.TryGetProperty("radarColor", out v)) RadarRingColorArgb = v.GetUInt32();
if (r.TryGetProperty("radarRange", out v)) RadarRangeWorld = (float)v.GetDouble();
if (r.TryGetProperty("ringThick", out v)) RadarRingThickness = (float)v.GetDouble();
if (r.TryGetProperty("ringHeight", out v)) RadarRingHeight = (float)v.GetDouble();
if (r.TryGetProperty("slopeRadius", out v)) SlopeRenderRadius = v.GetInt32();
if (r.TryGetProperty("slopeFloorZ", out v)) SlopeFloorZ = (float)v.GetDouble();
if (r.TryGetProperty("slopeBias", out v)) SlopeHeightBias = (float)v.GetDouble();
if (r.TryGetProperty("waterRadius", out v)) WaterRenderRadius = v.GetInt32();
if (r.TryGetProperty("waterAnyCorner", out v)) WaterAnyCorner = v.GetInt32() != 0;
if (r.TryGetProperty("waterImpassableOnly", out v)) WaterImpassableOnly = v.GetInt32() != 0;
if (r.TryGetProperty("waterTypes", out v) && v.ValueKind == JsonValueKind.Array)
{
var list = new List<int>();
foreach (var e in v.EnumerateArray())
if (e.TryGetInt32(out int n)) list.Add(n);
// Self-heal: an earlier version of the panel could push an empty
// array on first-edit (Populate race) which then persisted. An
// empty array means "match nothing" → no water ever painted. If
// the JSON has zero entries, keep the constructor defaults
// instead so the overlay works out-of-the-box.
if (list.Count > 0)
WaterTerrainTypes = list.ToArray();
}
}
// ── Persistence ───────────────────────────────────────────────────────────
private static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore", "rynthvision.json");
public void Save()
{
try
{
string path = FilePath;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, ToJson());
}
catch { }
}
public void Load()
{
try
{
string path = FilePath;
if (File.Exists(path)) ApplyJson(File.ReadAllText(path));
}
catch { }
}
}