feat: port SK test branch (2026.10.18.24) onto sk

Squash of test/hotbuild-2026-10-16 as merged onto aelrynth main 2026.10.17.1, matching the
2026.10.18.24 test installer. The test branch wins where both changed the same lines; sk-only
changes kept; duplicate features cut to the test branch's copy. RynthAi HandWrittenVersion stays
0.5.0-legacy-ui on sk.

Highlights: RynthOracle 0.6.0 (Legendary, Markers, Dynamic Stamps and Temple guardians merged into
the Quests list, RynthNav Go to), RynthILT 0.2.20 (ub-IT auto-chunk rules, rating level,
RynthILT.Data v3), RynthAi ub-IT /ub and VT/MT meta compatibility and the loot attribute checklist,
RynthNav destination alternatives. Changelog/2026-10-18-sk-port-test-branch-2026.10.18.24.md.
This commit is contained in:
BlankenshipG 2026-10-18 16:22:40 -04:00
commit 7797901d69
287 changed files with 22602 additions and 1090 deletions

View file

@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.Install;
using RynthCore.Plugin.RynthAi.Raycasting; // DatDatabase lives in the RynthCore.TerrainData assembly under this namespace
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// Converts an INDOOR (dungeon) object's CELL-LOCAL origin into LANDBLOCK-RELATIVE
/// coordinates by reading the object's EnvCell transform (position + rotation)
/// from the client's cell.dat. The engine builds its view matrix in landblock
/// space even indoors (GameMatrixCapture reads AC's pre-composed viewer pose), so
/// once a mob's position is landblock-relative the existing WorldToScreen pipeline
/// projects it correctly inside dungeons.
///
/// Uses the shared TerrainData <see cref="DatDatabase"/> (the same parser
/// RynthVision uses) — this does NOT pull in RynthAi. Outdoor cells (low word
/// &lt; 0x100) pass through unchanged. cell.dat is opened lazily on first indoor
/// use, from the running client's own folder, and per-cell transforms are cached.
/// </summary>
internal sealed class EnvCellTransforms : IDisposable
{
private DatDatabase? _cellDat;
private bool _tried;
private bool _ready;
private readonly Dictionary<uint, Cell> _cache = new();
private struct Cell
{
public bool Ok;
public float Px, Py, Pz; // cell position within the landblock
public float Rw, Rx, Ry, Rz; // cell rotation quaternion
}
public bool Ready => _ready;
public string Status { get; private set; } = "uninitialized";
/// <summary>
/// If <paramref name="cellId"/> is indoor, rewrites (e,n,u) from cell-local to
/// landblock-relative and returns true; returns false if the transform can't be
/// resolved (no cell.dat / no record). Outdoor cells return true unchanged.
/// </summary>
public bool ToLandblockRelative(uint cellId, ref float e, ref float n, ref float u)
{
if ((cellId & 0xFFFF) < 0x100)
return true; // outdoor: origin is already landblock-local
if (!EnsureOpen())
return false;
if (!TryGetCell(cellId, out Cell c) || !c.Ok)
return false;
// world_landblock = rotate(local, quat) + cellPos (matches DungeonLOS.TransformVertex)
float lx = e, ly = n, lz = u;
float cx = c.Ry * lz - c.Rz * ly;
float cy = c.Rz * lx - c.Rx * lz;
float cz = c.Rx * ly - c.Ry * lx;
float cx2 = c.Ry * cz - c.Rz * cy;
float cy2 = c.Rz * cx - c.Rx * cz;
float cz2 = c.Rx * cy - c.Ry * cx;
e = lx + 2f * (c.Rw * cx + cx2) + c.Px;
n = ly + 2f * (c.Rw * cy + cy2) + c.Py;
u = lz + 2f * (c.Rw * cz + cz2) + c.Pz;
return true;
}
private bool EnsureOpen()
{
if (_tried) return _ready;
_tried = true;
// The running client's own folder may hold cell.dat with an exclusive lock
// (AC opened it first, before our share-hook, when launched by another tool).
// cell.dat is identical across installs, so fall back to any other AC copy
// whose handle isn't locked. Surface the exact per-path failure for diag.
var tried = new List<string>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string folder in CandidateFolders())
{
try
{
if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) continue;
string? path = FindDat(folder, "client_cell_1.dat", "cell.dat");
if (path == null) { tried.Add($"{folder}=no-dat"); continue; }
if (!seen.Add(Path.GetFullPath(path))) continue; // don't retry the same file
var db = new DatDatabase();
if (db.Open(path))
{
_cellDat = db;
_ready = true;
Status = $"ready: {path}";
return true;
}
string err = db.DiagLog.Count > 0 ? db.DiagLog[db.DiagLog.Count - 1] : "open=false";
tried.Add($"{path} -> {err}");
try { db.Dispose(); } catch { }
}
catch (Exception ex) { tried.Add($"{folder} -> {ex.Message}"); }
}
Status = "cell.dat open failed; tried: " + (tried.Count > 0 ? string.Join(" | ", tried) : "(no candidates)");
return false;
}
// cell.dat search locations, in priority order: the running client's folder
// first, then well-known AC installs. Identical data in each, so any that
// opens works.
private static IEnumerable<string> CandidateFolders()
{
string? exe = Environment.ProcessPath;
string? exeDir = string.IsNullOrEmpty(exe) ? null : Path.GetDirectoryName(exe);
if (!string.IsNullOrEmpty(exeDir)) yield return exeDir!;
yield return Path.Combine(RynthInstallPaths.CoreDir, "AcClient"); // RynthCore's private client copy
yield return @"C:\Turbine\Asheron's Call";
yield return @"C:\Games\Asheron's Call";
yield return @"C:\Program Files (x86)\Turbine\Asheron's Call";
yield return @"C:\Program Files\Turbine\Asheron's Call";
}
private bool TryGetCell(uint cellId, out Cell c)
{
if (_cache.TryGetValue(cellId, out c))
return true;
c = default;
try
{
byte[]? data = _cellDat!.GetFileData(cellId);
if (data != null && data.Length >= 0x30)
ParseEnvCell(data, ref c);
}
catch { c.Ok = false; }
_cache[cellId] = c; // cache failures too (avoid re-reading missing cells)
return true;
}
// EnvCell header (matches RynthAi DungeonLOS.ParseEnvCellHeader exactly):
// u32 id, u32 flags, u32 cellId, u8 numSurfaces, u8 numPortals,
// u16 numVisibleCells, [numSurfaces × u16], u16 envId, u16 cellStruct,
// f32 PosX, PosY, PosZ, RotW, RotX, RotY, RotZ
private static void ParseEnvCell(byte[] data, ref Cell c)
{
try
{
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); r.ReadUInt32(); r.ReadUInt32();
byte numSurfaces = r.ReadByte();
r.ReadByte(); // numPortals
r.ReadUInt16(); // numVisibleCells
ms.Seek(numSurfaces * 2, SeekOrigin.Current);
r.ReadUInt16(); // envId
r.ReadUInt16(); // cellStruct
c.Px = r.ReadSingle(); c.Py = r.ReadSingle(); c.Pz = r.ReadSingle();
c.Rw = r.ReadSingle(); c.Rx = r.ReadSingle(); c.Ry = r.ReadSingle(); c.Rz = r.ReadSingle();
c.Ok = true;
}
catch { c.Ok = false; }
}
private static string? FindDat(string folder, params string[] names)
{
foreach (string nm in names)
{
string p = Path.Combine(folder, nm);
if (File.Exists(p)) return p;
}
return null;
}
public void Dispose()
{
try { _cellDat?.Dispose(); } catch { }
_cellDat = null;
_ready = false;
}
}

View file

@ -0,0 +1,419 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// Owns the live combat-juice effects and renders them every tick through the
/// engine's Nav3D world-space API. Floating numbers are drawn as billboarded
/// vector-digit glyphs (quads built from <see cref="RynthCoreHost.Nav3DAddTriangle"/>);
/// kill bursts are expanding rings.
///
/// Coordinate frames (see GameMatrixCapture / RadarRingOverlay):
/// • Object/player positions are AC convention: x=EW(east), y=NS(north), z=height(up),
/// local to that object's LANDBLOCK (0–192), outdoors only.
/// • Nav3D and WorldToScreen want a Y-up player-landblock-local frame: (east, up, north).
/// • A target in a different landblock than the player is shifted by
/// (Δlandblock × 192) per axis before projecting — mirroring the engine's own
/// camera re-anchor in GameMatrixCapture.
/// </summary>
internal sealed class JuiceEffects
{
public enum Kind { MobDamage, Heal, PlayerDamage }
private sealed class Effect
{
public bool IsBurst;
public uint CellId;
public float E0, N0, U0; // anchor in the effect's own landblock-local frame (AC: E,N,U)
public string Text = "";
public uint Color;
public bool Crit;
public Kind Kind;
public long BirthMs;
public float Life; // seconds
}
private readonly List<Effect> _fx = new();
private readonly object _lock = new();
private EnvCellTransforms? _cells;
private const int MaxEffects = 48;
private const float CritScale = 1.5f;
/// <summary>Wires the dungeon EnvCell transform reader (enables indoor numbers).</summary>
public void SetCells(EnvCellTransforms cells) => _cells = cells;
// Diagnostics (read by /juice diag): why Render last bailed + what it emitted.
public string LastRenderStatus { get; private set; } = "(not ticked yet)";
public int LastDrawnEffects { get; private set; }
public int LastTriangles { get; private set; }
private int _frameDrawn, _frameTris;
// ── Spawning (called from event handlers) ────────────────────────────────
public void SpawnDamage(uint cellId, float e, float n, float u, int amount, bool crit)
=> Add(cellId, e, n, u, FormatAmount(amount, crit), crit ? Gold : DamageColor(amount), crit, Kind.MobDamage);
public void SpawnHeal(uint cellId, float e, float n, float u, int amount)
=> Add(cellId, e, n, u, "+" + amount.ToString(), Green, false, Kind.Heal);
public void SpawnPlayerDamage(uint cellId, float e, float n, float u, int amount, bool crit)
=> Add(cellId, e, n, u, FormatAmount(amount, crit), crit ? Gold : PlayerRed, crit, Kind.PlayerDamage);
public void SpawnKillBurst(uint cellId, float e, float n, float u, bool crit, long nowMs)
{
if (!Resolve(cellId, ref e, ref n, ref u)) return;
lock (_lock)
{
TrimLocked();
_fx.Add(new Effect
{
IsBurst = true,
CellId = cellId, E0 = e, N0 = n, U0 = u,
Color = 0xFF60FFFF, // bright cyan — max visibility for the "is it working?" test
BirthMs = nowMs,
Life = 1.6f,
});
}
}
/// <summary>Upgrade the most recent damage number to a crit (handles crit chat
/// arriving just after the health packet). Returns true if one was upgraded.</summary>
public bool UpgradeRecentToCrit(long nowMs, int windowMs)
{
lock (_lock)
{
for (int i = _fx.Count - 1; i >= 0; i--)
{
var f = _fx[i];
if (f.IsBurst || f.Kind == Kind.Heal || f.Crit) continue;
if (nowMs - f.BirthMs > windowMs) break; // list is append-ordered; older beyond window
f.Crit = true;
f.Color = Gold;
f.Text = EnsureBang(f.Text);
f.Life = MathF.Max(f.Life, 1.7f);
return true;
}
}
return false;
}
/// <summary>Overwrite the most recent matching damage number with the exact
/// amount parsed from the combat log (the health-packet anchor stays). Returns
/// true if one was updated within the window.</summary>
public bool ApplyExactToRecent(long nowMs, int windowMs, Kind kind, int amount, bool crit)
{
lock (_lock)
{
for (int i = _fx.Count - 1; i >= 0; i--)
{
var f = _fx[i];
if (nowMs - f.BirthMs > windowMs) break; // append-ordered → all earlier are older
if (f.IsBurst || f.Kind != kind) continue;
f.Crit = f.Crit || crit;
f.Text = FormatAmount(amount, f.Crit);
f.Color = f.Crit ? Gold : (kind == Kind.PlayerDamage ? PlayerRed : DamageColor(amount));
if (f.Crit) f.Life = MathF.Max(f.Life, 1.7f);
return true;
}
}
return false;
}
public void Clear() { lock (_lock) _fx.Clear(); }
public int Count { get { lock (_lock) return _fx.Count; } }
private void Add(uint cellId, float e, float n, float u, string text, uint color, bool crit, Kind kind)
{
if (string.IsNullOrEmpty(text)) return;
if (!Resolve(cellId, ref e, ref n, ref u)) return; // indoor w/o cell transform → skip
lock (_lock)
{
TrimLocked();
_fx.Add(new Effect
{
CellId = cellId, E0 = e, N0 = n, U0 = u,
Text = text, Color = color, Crit = crit, Kind = kind,
BirthMs = Environment.TickCount64,
Life = crit ? 1.7f : (kind == Kind.Heal ? 1.15f : 1.35f),
});
}
}
private void TrimLocked()
{
// Drop the oldest non-burst effect if we're at the cap (keep bursts; they're brief).
while (_fx.Count >= MaxEffects)
{
int idx = _fx.FindIndex(f => !f.IsBurst);
_fx.RemoveAt(idx >= 0 ? idx : 0);
}
}
// ── Rendering (called from OnTick) ───────────────────────────────────────
public void Render(RynthCoreHost host, JuiceSettings cfg, long nowMs)
{
if (!host.HasNav3D || !host.HasNav3DTriangle)
{ LastRenderStatus = $"no-nav3d (nav={host.HasNav3D} tri={host.HasNav3DTriangle})"; return; }
if (!host.TryGetPlayerPose(out uint pCell, out float pE, out float pN, out float pU,
out _, out _, out _, out _))
{ LastRenderStatus = "no-pose"; return; }
if ((pCell >> 16) == 0)
{ LastRenderStatus = "portalspace"; return; }
// Indoors, convert the player's cell-local pose to landblock-relative so
// distance math agrees with the (already landblock-relative) anchors.
if (!Resolve(pCell, ref pE, ref pN, ref pU))
{ LastRenderStatus = "player-resolve-fail (indoor cell.dat unavailable?)"; return; }
uint playerLb = pCell >> 16;
_frameDrawn = 0; _frameTris = 0;
int culFar = 0, culDist = 0;
lock (_lock)
{
for (int i = _fx.Count - 1; i >= 0; i--)
{
var f = _fx[i];
float age = (nowMs - f.BirthMs) / 1000f;
if (age >= f.Life) { _fx.RemoveAt(i); continue; }
if (f.CellId >> 16 == 0) { _fx.RemoveAt(i); continue; }
// Shift the effect's own-landblock anchor into the player's frame.
int dXb = (int)(((f.CellId >> 16 >> 8) & 0xFF)) - (int)((playerLb >> 8) & 0xFF);
int dYb = (int)(((f.CellId >> 16) & 0xFF)) - (int)(playerLb & 0xFF);
if (Math.Abs(dXb) > 3 || Math.Abs(dYb) > 3) { culFar++; continue; } // too far / region junk
float aE = f.E0 + dXb * 192f;
float aN = f.N0 + dYb * 192f;
// Distance cull (horizontal).
float dE = aE - pE, dN = aN - pN;
if (dE * dE + dN * dN > cfg.MaxDistance * cfg.MaxDistance) { culDist++; continue; }
if (f.IsBurst) { RenderBurst(host, f, aE, aN, age); _frameDrawn++; }
else RenderNumber(host, cfg, f, aE, aN, age); // self-counts _frameDrawn on success
}
}
LastDrawnEffects = _frameDrawn;
LastTriangles = _frameTris;
LastRenderStatus = $"ok fx={_fx.Count} drawn={_frameDrawn} tris={_frameTris} culFar={culFar} culDist={culDist}";
}
private static void RenderBurst(RynthCoreHost host, Effect f, float aE, float aN, float age)
{
float t = age / f.Life; // 0→1
float alpha = 1f - t;
uint col = WithAlpha(f.Color, alpha);
float baseU = f.U0 + 0.3f;
// Big expanding ground ring.
float groundR = 0.6f + 8f * t;
host.Nav3DAddRingEx(aE, baseU, aN, groundR, 0.6f, 0.5f, col);
// A tall bright PILLAR of stacked rings (~10 m), so a kill is unmistakable
// even if the subtle stuff isn't landing yet. Tapers toward the top.
const int rings = 11;
for (int i = 0; i < rings; i++)
{
float h = baseU + i * 1.0f;
float pr = 2.0f * (1f - i / (float)rings) + 0.4f;
host.Nav3DAddRingEx(aE, h, aN, pr, 0.35f, 0.3f, col);
}
}
private void RenderNumber(RynthCoreHost host, JuiceSettings cfg, Effect f, float aE, float aN, float age)
{
// Animation: rise in world-up, pop-scale early, fade late.
float rise = 1.15f * age;
float aU = f.U0 + cfg.HeightOffset + rise;
float pop = 1f + (f.Crit ? 0.6f : 0.35f) * MathF.Max(0f, 1f - age / (f.Crit ? 0.14f : 0.10f));
float kindScale = f.Kind == Kind.PlayerDamage ? 1.15f : 1f;
float critScale = f.Crit ? CritScale : 1f;
float alpha = 1f;
float fadeStart = 0.55f * f.Life;
if (age > fadeStart) alpha = MathF.Max(0f, 1f - (age - fadeStart) / (f.Life - fadeStart));
alpha *= MathF.Min(1f, age / 0.06f); // quick fade-in
uint col = WithAlpha(f.Color, alpha);
// Size, then draw via the shared glyph routine.
float heightPx = 22f * cfg.Scale * pop * kindScale * critScale;
DrawGlyphs(host, aE, aU, aN, f.Text, heightPx, col);
}
/// <summary>Live monster-health readout: a "NN" percentage floating over each
/// actively-damaged mob, green→red by ratio. Persistent (re-drawn every tick so
/// it tracks the mob and updates as it's hit), unlike the transient numbers.</summary>
public void RenderMobHealth(RynthCoreHost host, JuiceSettings cfg, List<MobHp> mobs)
{
if (mobs.Count == 0 || !host.HasNav3D || !host.HasNav3DTriangle) return;
if (!host.TryGetPlayerPose(out uint pCell, out float pE, out float pN, out float pU, out _, out _, out _, out _)) return;
if ((pCell >> 16) == 0) return;
if (!Resolve(pCell, ref pE, ref pN, ref pU)) return;
uint playerLb = pCell >> 16;
foreach (MobHp m in mobs)
{
if ((m.CellId >> 16) == 0) continue;
int dXb = (int)(((m.CellId >> 16 >> 8) & 0xFF)) - (int)((playerLb >> 8) & 0xFF);
int dYb = (int)(((m.CellId >> 16) & 0xFF)) - (int)(playerLb & 0xFF);
if (Math.Abs(dXb) > 3 || Math.Abs(dYb) > 3) continue;
float aE = m.E0 + dXb * 192f;
float aN = m.N0 + dYb * 192f;
float dE = aE - pE, dN = aN - pN;
if (dE * dE + dN * dN > cfg.MaxDistance * cfg.MaxDistance) continue;
int pct = (int)MathF.Round(Math.Clamp(m.Ratio, 0f, 1f) * 100f);
float aU = m.U0 + cfg.HeightOffset + 0.9f; // just above the damage-number lane
DrawGlyphs(host, aE, aU, aN, pct.ToString(), 15f * cfg.Scale, HealthColor(m.Ratio));
}
}
/// <summary>Billboarded vector-glyph text at a world anchor — shared by the
/// damage numbers and the live monster-health %. False if it couldn't project.</summary>
private bool DrawGlyphs(RynthCoreHost host, float aE, float aU, float aN, string text, float heightPx, uint col)
{
if (!ComputeBillboard(host, aE, aU, aN, out Vector3 uVec, out Vector3 vVec, out _, out _))
return false;
_frameDrawn++;
float cell = heightPx / VectorFont.GlyphHeight; // px per grid unit
float halfW = MathF.Max(1.0f, cell * 0.16f); // stroke half-thickness, px
float startGridX = -VectorFont.MeasureWidth(text) / 2f;
for (int ci = 0; ci < text.Length; ci++)
{
var strokes = VectorFont.Strokes(text[ci]);
float charX = startGridX + ci * VectorFont.Advance;
foreach (var s in strokes)
{
var p1 = new Vector2((charX + s.X) * cell, (s.Y - VectorFont.GlyphHeight / 2f) * cell);
var p2 = new Vector2((charX + s.Z) * cell, (s.W - VectorFont.GlyphHeight / 2f) * cell);
EmitStrokeQuad(host, aE, aU, aN, uVec, vVec, p1, p2, halfW, col);
_frameTris += 2;
}
}
return true;
}
public readonly record struct MobHp(uint CellId, float E0, float N0, float U0, float Ratio);
private static uint HealthColor(float ratio)
{
if (ratio > 0.6f) return 0xFF40FF40; // green
if (ratio > 0.3f) return 0xFFFFF040; // yellow
if (ratio > 0.12f) return 0xFFFFA030; // orange
return 0xFFFF3030; // red
}
/// <summary>Builds one rounded-cap stroke as two world-space triangles.</summary>
private static void EmitStrokeQuad(RynthCoreHost host, float aE, float aU, float aN,
Vector3 u, Vector3 v, Vector2 p1, Vector2 p2, float halfW, uint col)
{
Vector2 d = p2 - p1;
float len = d.Length();
if (len < 0.0001f) return;
d /= len;
Vector2 perp = new(-d.Y, d.X);
Vector2 ext = d * halfW; // extend ends so segments overlap at joints
perp *= halfW;
Vector2 c0 = p1 - ext + perp;
Vector2 c1 = p2 + ext + perp;
Vector2 c2 = p2 + ext - perp;
Vector2 c3 = p1 - ext - perp;
// px-offset → world (Nav3D frame x=E, y=U, z=N)
(float, float, float) W(Vector2 px) =>
(aE + px.X * u.X + px.Y * v.X,
aU + px.X * u.Y + px.Y * v.Y,
aN + px.X * u.Z + px.Y * v.Z);
var (w0e, w0u, w0n) = W(c0);
var (w1e, w1u, w1n) = W(c1);
var (w2e, w2u, w2n) = W(c2);
var (w3e, w3u, w3n) = W(c3);
host.Nav3DAddTriangle(w0e, w0u, w0n, w1e, w1u, w1n, w2e, w2u, w2n, col);
host.Nav3DAddTriangle(w0e, w0u, w0n, w2e, w2u, w2n, w3e, w3u, w3n, col);
}
/// <summary>
/// Finite-difference Jacobian of WorldToScreen at the anchor, then its
/// 2×3 pseudo-inverse, giving world vectors u,v that move the projection by
/// exactly +1px in screen x and y respectively. Constant on-screen size +
/// automatic camera-facing billboard, with no engine-side camera basis.
/// </summary>
private static bool ComputeBillboard(RynthCoreHost host, float aE, float aU, float aN,
out Vector3 u, out Vector3 v, out float sx, out float sy)
{
u = default; v = default; sx = sy = 0f;
if (!host.HasWorldToScreen) return false;
const float h = 0.1f;
if (!host.WorldToScreen(aE, aU, aN, out float s0x, out float s0y)) return false;
if (!host.WorldToScreen(aE + h, aU, aN, out float eX, out float eY)) return false;
if (!host.WorldToScreen(aE, aU + h, aN, out float uX, out float uY)) return false;
if (!host.WorldToScreen(aE, aU, aN + h, out float nX, out float nY)) return false;
sx = s0x; sy = s0y;
// Jacobian columns (screen px / metre) for the E, U, N axes.
float jEx = (eX - s0x) / h, jEy = (eY - s0y) / h;
float jUx = (uX - s0x) / h, jUy = (uY - s0y) / h;
float jNx = (nX - s0x) / h, jNy = (nY - s0y) / h;
// J Jᵀ (2×2, symmetric) and its inverse.
float a = jEx * jEx + jUx * jUx + jNx * jNx;
float b = jEx * jEy + jUx * jUy + jNx * jNy;
float dd = jEy * jEy + jUy * jUy + jNy * jNy;
float det = a * dd - b * b;
if (MathF.Abs(det) < 1e-7f) return false;
float i00 = dd / det, i01 = -b / det, i11 = a / det;
// u = Jᵀ·(i00,i01) (screen +x); v = Jᵀ·(i01,i11) (screen +y)
u = new Vector3(jEx * i00 + jEy * i01, jUx * i00 + jUy * i01, jNx * i00 + jNy * i01);
v = new Vector3(jEx * i01 + jEy * i11, jUx * i01 + jUy * i11, jNx * i01 + jNy * i11);
return true;
}
// ── Helpers ──────────────────────────────────────────────────────────────
// Anchor coords pass through unchanged. The diag PROVED the indoor camera/view
// matrix is CELL-LOCAL (the player's own raw cell-local pos projects to screen
// centre @799/1598), so RAW object coords project correctly for objects in the
// player's cell — the EnvCell→landblock transform actually moved them OFF
// (projXform was wrong, projRaw was right). Outdoor coords are landblock-local
// and the per-landblock shift in Render handles cross-landblock. Indoor
// cross-cell mobs (a different EnvCell than the player) land far away in raw
// coords and get distance-culled rather than mis-drawn — acceptable for v1.
private bool Resolve(uint cellId, ref float e, ref float n, ref float u) => true;
private const uint Gold = 0xFFFFD700;
private const uint Green = 0xFF50FF50;
private const uint PlayerRed = 0xFFFF2828;
private const uint BurstOrange = 0xFFFF8C20;
private static uint DamageColor(int amt)
{
if (amt < 25) return 0xFFFFFFFF; // white
if (amt < 60) return 0xFFFFF080; // pale yellow
if (amt < 120) return 0xFFFFA030; // orange
return 0xFFFF3828; // red
}
private static uint WithAlpha(uint argb, float a)
{
uint aa = (uint)Math.Clamp(a * 255f, 0f, 255f);
return (argb & 0x00FFFFFF) | (aa << 24);
}
private static string FormatAmount(int amount, bool crit) =>
crit ? amount.ToString() + "!" : amount.ToString();
private static string EnsureBang(string s) =>
s.EndsWith("!", StringComparison.Ordinal) ? s : s + "!";
}

View file

@ -0,0 +1,85 @@
using System;
using System.Globalization;
using System.IO;
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// RynthJuice tunables, persisted as a tiny key=value file at
/// %APPDATA%\RynthCore\rynthjuice.cfg. Plain text (no JSON serializer) to stay
/// trivially NativeAOT-safe and hand-editable.
/// </summary>
internal sealed class JuiceSettings
{
public bool Enabled = true;
public bool ShowHeals = true; // green "+N" when a target's health rises
public bool ShowPlayerDamage = true; // red numbers over your own character when hit
public float Scale = 1.0f; // global size multiplier for numbers
public float HeightOffset = 1.8f; // metres above the target origin to anchor numbers
public float MaxDistance = 55f; // metres; skip numbers for targets farther than this
public int MinDamage = 1; // ignore deltas below this (filters regen ticks)
private string _path = "";
public void Load()
{
try
{
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
_path = Path.Combine(dir, "rynthjuice.cfg");
if (!File.Exists(_path))
return;
foreach (string raw in File.ReadAllLines(_path))
{
string line = raw.Trim();
if (line.Length == 0 || line[0] == '#') continue;
int eq = line.IndexOf('=');
if (eq <= 0) continue;
string key = line.Substring(0, eq).Trim().ToLowerInvariant();
string val = line.Substring(eq + 1).Trim();
Apply(key, val);
}
}
catch { /* defaults stand */ }
}
public void Save()
{
try
{
if (string.IsNullOrEmpty(_path))
{
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
Directory.CreateDirectory(dir);
_path = Path.Combine(dir, "rynthjuice.cfg");
}
var ic = CultureInfo.InvariantCulture;
File.WriteAllText(_path,
"# RynthCore RynthJuice settings\n" +
$"enabled={(Enabled ? 1 : 0)}\n" +
$"heals={(ShowHeals ? 1 : 0)}\n" +
$"playerdamage={(ShowPlayerDamage ? 1 : 0)}\n" +
$"scale={Scale.ToString("0.##", ic)}\n" +
$"height={HeightOffset.ToString("0.##", ic)}\n" +
$"maxdist={MaxDistance.ToString("0.##", ic)}\n" +
$"mindamage={MinDamage}\n");
}
catch { /* non-fatal */ }
}
private void Apply(string key, string val)
{
var ic = CultureInfo.InvariantCulture;
switch (key)
{
case "enabled": Enabled = val is "1" or "true"; break;
case "heals": ShowHeals = val is "1" or "true"; break;
case "playerdamage": ShowPlayerDamage = val is "1" or "true"; break;
case "scale": if (float.TryParse(val, NumberStyles.Float, ic, out var s)) Scale = Math.Clamp(s, 0.3f, 4f); break;
case "height": if (float.TryParse(val, NumberStyles.Float, ic, out var h)) HeightOffset = Math.Clamp(h, 0f, 8f); break;
case "maxdist": if (float.TryParse(val, NumberStyles.Float, ic, out var m)) MaxDistance = Math.Clamp(m, 5f, 200f); break;
case "mindamage": if (int.TryParse(val, NumberStyles.Integer, ic, out var d)) MinDamage = Math.Max(0, d); break;
}
}
}

View file

@ -0,0 +1,62 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// C ABI exports the engine's PluginLoader resolves by name (GetProcAddress).
/// Note there is intentionally NO RynthPluginRender export: that drives plugin
/// ImGui drawing, which RynthJuice doesn't use. All geometry is submitted from
/// the tick (RynthPluginTick) through the engine's Nav3D renderer, which has its
/// own draw hook and runs regardless of the ImGui shell.
/// </summary>
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthJuicePlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthJuicePlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthJuicePlugin.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 = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[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 = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "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);
}

View file

@ -0,0 +1,50 @@
<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.RynthJuice</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthJuice</AssemblyName>
<Platforms>x86</Platforms>
<!-- Keep in step with VersionPointer in RynthJuicePlugin.cs. -->
<!-- Previous release: 0.1.2 (crit window passed before the first crit, so early hits drew as crits). -->
<Version>0.1.3</Version>
<AssemblyVersion>0.1.3.0</AssemblyVersion>
<FileVersion>0.1.3.0</FileVersion>
<InformationalVersion>0.1.3-experimental</InformationalVersion>
<!-- Publish straight into the launcher-registered deploy home so a bare
`dotnet publish` lands where the engine hot-reloads it (mirrors
RynthVision). Deploy-RynthCore.ps1 points its copy step here too and
detects source == dest to skip the redundant self-copy. -->
<PublishDir>C:\Games\RynthSuite\RynthJuice\</PublishDir>
</PropertyGroup>
<!-- No ImGui.NET: RynthJuice draws purely through the engine's Nav3D world-
space renderer (lines/rings/triangles), which has its own
DrawIndexedPrimitive hook independent of the ImGui shell. That keeps the
plugin alive in EnableImGuiShell=false mode and off the fragile ImGui
path entirely. -->
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<!-- Shared DAT reader (same lib RynthVision uses; carries NO RynthAi
dependency) — used to read per-EnvCell transforms from cell.dat for
dungeon (indoor) damage-number placement. -->
<ProjectReference Include="..\..\Shared\RynthCore.TerrainData\RynthCore.TerrainData.csproj" />
</ItemGroup>
<ItemGroup>
<!-- Install-folder resolver shared with RynthCore (Software\Rynth CoreDir/SuiteDir). -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,683 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// Combat "juice" for RynthCore: floating vector-digit damage numbers over
/// monsters (white→orange→red by size, GOLD + bigger on crit), green heal
/// numbers, red numbers over your own character when hit, and an expanding ring
/// burst when a damaged monster dies. Pure Nav3D — no ImGui — so it runs in
/// EnableImGuiShell=false mode and stays fully isolated from RynthAi. Outdoor
/// only in v1 (dungeon coords are cell-local). Toggle with /juice.
/// </summary>
public sealed class RynthJuicePlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthJuice");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.3");
private sealed class HState
{
public bool HasCurrent;
public uint LastCurrent;
public uint KnownMax;
public float LastRatio;
public uint Cell;
public float E, N, U; // last known position (own-landblock frame)
public long LastDmgMs;
public long LastSeenMs;
}
private readonly JuiceSettings _cfg = new();
private readonly JuiceEffects _fx = new();
private readonly EnvCellTransforms _cells = new();
private readonly Dictionary<uint, HState> _health = new();
private readonly HashSet<uint> _killedIds = new();
private readonly List<JuiceEffects.MobHp> _mobHpScratch = new();
// Object tracking is split in two so a busy area (~700 created objects, mostly items)
// can't starve mob polling:
// * candidates: dynamic objects not yet known to be attackable. Checked in ROTATION
// (queue: dequeue, decide, re-enqueue at the back) with a per-poll budget, so every
// candidate is reached within a few polls. Known non-creatures are dropped.
// * mobs: confirmed attackable. Polled every cycle (budgeted + rotated only if there
// are more than MobPollBudget) so health bars stay continuous.
// Membership lives in the sets; the queues may hold stale ids (deleted / moved), which
// are discarded lazily when dequeued.
private readonly HashSet<uint> _candidateSet = new();
private readonly Queue<uint> _candidateQueue = new();
private readonly HashSet<uint> _candidateQueued = new(); // ids physically in _candidateQueue (no duplicates after delete+recreate)
private readonly HashSet<uint> _mobSet = new();
private readonly Queue<uint> _mobQueue = new();
private readonly HashSet<uint> _mobQueued = new(); // ids physically in _mobQueue
private int _droppedNonCreatures;
private bool _trackCapLogged;
private int _pollLogCount;
private int _createLogCount;
private readonly Random _rng = new();
private uint _playerId;
private bool _loginComplete;
private long _lastCritMs = long.MinValue;
private int _tick;
private bool _debugChat;
private bool _autoDiagDone;
private PendingExact _pending;
private const int CritWindowMs = 450;
/// <summary>
/// True when the last crit line came at most <see cref="CritWindowMs"/> before <paramref name="now"/>.
/// <c>_lastCritMs</c> is <c>long.MinValue</c> until the first crit, and <c>now - long.MinValue</c>
/// wraps negative, which would pass the window test and draw every hit as a crit.
/// </summary>
private bool WithinCritWindow(long now) => _lastCritMs != long.MinValue && (now - _lastCritMs) <= CritWindowMs;
private const int ExactWindowMs = 600; // pair a combat-log amount with its health packet
private const int HealMinDelta = 8; // filters small regen ticks
private const long DeleteKillRecentDamageMs = 8_000; // delete counts as a kill only if we hit it this recently
private const long ForgetMs = 60_000; // prune untouched health entries
private const int CandidateCheckBudget = 80; // candidates classified per poll (rotating)
private const int MobPollBudget = 64; // confirmed mobs polled per poll (rotating if more)
private const int MaxTrackedObjects = 4096; // safety cap (candidates + mobs); non-creatures are dropped, so this is rarely reached
private const uint ItemTypeCreature = 0x10; // AC ITEM_TYPE.TYPE_CREATURE
// An exact combat-log amount whose health packet hasn't arrived yet (reverse order).
private struct PendingExact { public bool Has; public int Amount; public bool Crit; public bool Incoming; public long Ts; }
public override int Initialize()
{
_cfg.Load();
_fx.SetCells(_cells);
Host.Log("[RynthJuice] Initialized. /juice [on|off|test|heals|playerdmg|scale N|height N|help]. " +
"Needs a clean (no-Decal) client; works with the ImGui shell on or off; outdoors + dungeons.");
return 0;
}
public override void OnLoginComplete()
{
_playerId = Host.GetPlayerId();
_loginComplete = true;
_autoDiagDone = false;
_health.Clear();
_fx.Clear();
if (!Host.HasNav3DTriangle)
Host.Log("[RynthJuice] WARNING: engine has no Nav3D triangle API — numbers can't draw. Update the engine.");
Host.Log($"[RynthJuice] Ready (enabled={_cfg.Enabled}).");
}
public override void OnLogout()
{
_loginComplete = false;
_health.Clear();
_killedIds.Clear();
ClearTracking();
_fx.Clear();
}
public override void Shutdown() { _fx.Clear(); _cells.Dispose(); }
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
if (!_loginComplete || !_cfg.Enabled) return;
long now = Environment.TickCount64;
bool isPlayer = targetId == _playerId;
if (!_health.TryGetValue(targetId, out var st))
{
st = new HState();
_health[targetId] = st;
}
uint prevCur = st.LastCurrent;
float prevRatio = st.LastRatio;
bool hadPrev = st.HasCurrent;
// Update tracked state.
if (maxHealth > 0 && maxHealth > st.KnownMax) st.KnownMax = maxHealth;
st.LastRatio = healthRatio;
st.LastCurrent = currentHealth;
st.HasCurrent = true;
st.LastSeenMs = now;
// Cache the mob's current position every update — the live health readout and
// the kill effect both need a spot, and the position cache can be empty by the
// time the object is deleted.
if (!isPlayer && Host.TryGetObjectPosition(targetId, out uint upCell, out float upE, out float upN, out float upU))
{ st.Cell = upCell; st.E = upE; st.N = upN; st.U = upU; }
// Kill detection by HEALTH RATIO → 0. Fires at the killing blow (no
// OnDeleteObject corpse-removal delay) and works for ALL mobs — ratio is the
// reliable signal; absolute currentHealth reads 0 for unappraised mobs.
// _killedIds dedups (fires once); OnDeleteObject stays as a fallback.
if (!isPlayer && healthRatio < 0.001f)
{
if (_killedIds.Add(targetId))
{
int killAmt = (maxHealth > 0) ? (int)Math.Round(prevRatio * maxHealth) : 0;
bool kcrit = WithinCritWindow(now);
if (_pending.Has && (now - _pending.Ts) <= ExactWindowMs && !_pending.Incoming)
{
killAmt = _pending.Amount;
kcrit = kcrit || _pending.Crit;
_pending.Has = false;
}
// Verification scaffolding — chat only in debug mode, or every
// kill spams the chat window once this goes live.
if (_debugChat) Reply("[RynthJuice] *** KILL ***");
// Anchor: live position → last cached → player (so it ALWAYS fires).
uint kc; float ke, kn, ku;
bool gotPos = Host.TryGetObjectPosition(targetId, out kc, out ke, out kn, out ku);
if (!gotPos && (st.Cell >> 16) != 0) { kc = st.Cell; ke = st.E; kn = st.N; ku = st.U; gotPos = true; }
if (!gotPos) gotPos = Host.TryGetPlayerPose(out kc, out ke, out kn, out ku, out _, out _, out _, out _);
if (gotPos)
{
if (killAmt >= _cfg.MinDamage) _fx.SpawnDamage(kc, ke, kn, ku, killAmt, kcrit);
_fx.SpawnKillBurst(kc, ke, kn, ku, kcrit, now);
Host.Log($"[RynthJuice] KILL tgt=0x{targetId:X8} amt={killAmt} cell=0x{kc:X8} fx={_fx.Count}");
}
}
_health.Remove(targetId);
return;
}
if (!hadPrev) return; // first non-death packet — establish baseline only
// Resolve a damage/heal amount, preferring absolute HP when the server
// gave us real numbers, falling back to ratio × best-known max.
int delta;
bool isDamage;
if (maxHealth > 0 && (currentHealth > 0 || prevCur > 0))
{
long ad = (long)prevCur - currentHealth;
isDamage = ad > 0;
delta = (int)Math.Abs(ad);
}
else
{
float rd = prevRatio - healthRatio;
float baseMax = st.KnownMax > 0 ? st.KnownMax : 100f;
isDamage = rd > 0;
delta = (int)MathF.Round(Math.Abs(rd) * baseMax);
}
if (delta <= 0) return;
// Capture anchor position (mob via object cache, player via pose).
uint cell; float e, n, u;
if (isPlayer)
{
if (!Host.TryGetPlayerPose(out cell, out e, out n, out u, out _, out _, out _, out _))
return;
}
else if (!Host.TryGetObjectPosition(targetId, out cell, out e, out n, out u))
{
if (_debugChat) Host.Log($"[RynthJuice] dmg tgt=0x{targetId:X8} delta={delta} POS-FAIL (no anchor — skipped)");
return;
}
st.Cell = cell; st.E = e; st.N = n; st.U = u;
if (isDamage)
{
if (delta < _cfg.MinDamage) return;
st.LastDmgMs = now;
int amount = delta;
bool crit = WithinCritWindow(now);
// Prefer the exact combat-log value if its line already arrived (reverse order).
if (_pending.Has && (now - _pending.Ts) <= ExactWindowMs && _pending.Incoming == isPlayer)
{
amount = _pending.Amount;
crit = crit || _pending.Crit;
_pending.Has = false;
}
if (isPlayer)
{
if (_cfg.ShowPlayerDamage) _fx.SpawnPlayerDamage(cell, e, n, u, amount, crit);
}
else
{
_fx.SpawnDamage(cell, e, n, u, amount, crit);
}
if (_debugChat) Host.Log($"[RynthJuice] dmg tgt=0x{targetId:X8} amt={amount} crit={crit} isPlayer={isPlayer} cell=0x{cell:X8} indoor={(cell & 0xFFFF) >= 0x100} fx={_fx.Count}");
}
else if (_cfg.ShowHeals && delta >= HealMinDelta)
{
_fx.SpawnHeal(cell, e, n, u, delta);
}
}
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (!_loginComplete || !_cfg.Enabled || string.IsNullOrEmpty(text)) return;
if (_debugChat) Host.Log($"[RynthJuice] chat[{chatType}]: {text}");
long now = Environment.TickCount64;
bool isCrit = text.IndexOf("critical", StringComparison.OrdinalIgnoreCase) >= 0;
// Exact damage from the combat log: "... for N points of <type> damage".
// The health packet anchors it to the right object; this overwrites the
// estimate with the true value. Requires "damage" so heal/mana/stamina
// "points of" lines are ignored.
if (TryParseDamage(text, out int amount, out bool incoming))
{
bool crit = isCrit || WithinCritWindow(now);
if (isCrit) _lastCritMs = now;
var kind = incoming ? JuiceEffects.Kind.PlayerDamage : JuiceEffects.Kind.MobDamage;
// Correct an already-spawned number, else stash for the health packet.
if (!_fx.ApplyExactToRecent(now, ExactWindowMs, kind, amount, crit))
_pending = new PendingExact { Has = true, Amount = amount, Crit = crit, Incoming = incoming, Ts = now };
return;
}
// A standalone crit line (no parsable amount): mark window + retro-upgrade.
if (isCrit)
{
_lastCritMs = now;
_fx.UpgradeRecentToCrit(now, CritWindowMs);
}
}
// Parses AC combat-log damage lines, e.g.:
// "You slash the Drudge for 47 points of slashing damage!" (outgoing)
// "The Drudge Slinker hits you for 12 points of bludgeoning damage!" (incoming)
// Extracts the integer before "points" and the direction. Returns false for
// non-damage "points of" lines (heals/mana/stamina lack "damage").
private static bool TryParseDamage(string text, out int amount, out bool incoming)
{
amount = 0; incoming = false;
int pts = text.IndexOf("points of", StringComparison.OrdinalIgnoreCase);
if (pts < 0) return false;
if (text.IndexOf("damage", pts, StringComparison.OrdinalIgnoreCase) < 0) return false;
int i = pts - 1;
while (i >= 0 && text[i] == ' ') i--;
long val = 0, mult = 1; bool any = false;
while (i >= 0 && (char.IsDigit(text[i]) || text[i] == ','))
{
if (text[i] != ',') { val += (text[i] - '0') * mult; mult *= 10; any = true; }
i--;
}
if (!any || val <= 0 || val > 1_000_000) return false;
amount = (int)val;
// Defender (incoming) lines target "you for"; attacker lines start "You ".
incoming = text.IndexOf("you for", StringComparison.OrdinalIgnoreCase) >= 0;
return true;
}
// Exact per-hit damage from the structured AC packet (AttackerNotification /
// DefenderNotification), surfaced by the engine. This is the real damage value
// even for one-shots/overkill. It carries no object id (the packet identifies
// the target by name), so correlate it to the health packet — which has the id
// + position — by recency, reusing the same _pending mechanism.
public override void OnCombatDamage(uint damage, uint damageType, bool crit, bool isAttacker)
{
if (!_loginComplete || !_cfg.Enabled || damage == 0) return;
long now = Environment.TickCount64;
if (crit) _lastCritMs = now;
var kind = isAttacker ? JuiceEffects.Kind.MobDamage : JuiceEffects.Kind.PlayerDamage;
// Overwrite a number that already spawned from the health packet, else stash
// the exact value for the imminent health update / kill to pick up.
if (!_fx.ApplyExactToRecent(now, ExactWindowMs, kind, (int)damage, crit))
_pending = new PendingExact { Has = true, Amount = (int)damage, Crit = crit, Incoming = !isAttacker, Ts = now };
if (_debugChat) Host.Log($"[RynthJuice] COMBATDMG dmg={damage} type={damageType} crit={crit} atk={isAttacker}");
}
// Track dynamic objects so we can poll mob health — the streaming-health hook is
// dead on this client, so polling is how we read monster HP. New objects start as
// candidates; the poll promotes attackable ones to mobs and drops non-creatures.
public override void OnCreateObject(uint objectId)
{
// No login/enabled gate: the engine REPLAYS creates for pre-existing objects
// at plugin init (possibly before OnLoginComplete), and mobs already in the
// room must be tracked. Polling itself is gated by login/enabled in OnTick.
if ((objectId & 0x80000000u) == 0) return; // dynamic objects only
if (_mobSet.Contains(objectId)) return; // already a confirmed mob
// Known non-creature (item, portal, …): never a mob — don't track it at all.
if (IsKnownNonCreature(objectId)) { _droppedNonCreatures++; return; }
if (_candidateSet.Count + _mobSet.Count >= MaxTrackedObjects)
{
if (!_trackCapLogged)
{
_trackCapLogged = true;
Host.Log($"[RynthJuice] tracking cap {MaxTrackedObjects} reached — new objects not tracked until some are deleted");
}
return;
}
if (!_candidateSet.Add(objectId)) return;
EnqueueCandidate(objectId);
if (_createLogCount < 8) { _createLogCount++; Host.Log($"[RynthJuice] create 0x{objectId:X8} candidates={_candidateSet.Count}"); }
}
public override void OnDeleteObject(uint objectId)
{
// Queue entries for this id are discarded lazily (set membership is the truth).
_candidateSet.Remove(objectId);
_mobSet.Remove(objectId);
// Capture state BEFORE removing it — LastDmgMs is the recent-damage
// gate below; the old order destroyed it first.
bool hadState = _health.TryGetValue(objectId, out HState? st);
_health.Remove(objectId);
if (!_loginComplete || !_cfg.Enabled) return;
// An appraised mob already got its effect from the health=0 path — don't double.
if (_killedIds.Remove(objectId)) return;
if (_killedIds.Count > 1024) _killedIds.Clear();
// AC sends deletes for range-out / teleport / despawn too — only treat
// a delete as a DEATH if we damaged the creature recently. Without this
// gate, walking out of a spawn field or portaling fired a burst per
// nearby mob (anchored at the PLAYER via the old pose fallback, since
// the position cache was already empty).
long now = Environment.TickCount64;
if (!hadState || st!.LastDmgMs == 0 || now - st.LastDmgMs > DeleteKillRecentDamageMs)
return;
if (!Host.ObjectIsAttackable(objectId)) return;
// Anchor at the mob's live or last-cached position only — never the
// player. A delete with no known position gives a wrong-place burst.
uint kc; float ke, kn, ku;
if (!Host.TryGetObjectPosition(objectId, out kc, out ke, out kn, out ku))
{
if ((st.Cell >> 16) == 0) return;
kc = st.Cell; ke = st.E; kn = st.N; ku = st.U;
}
if (_debugChat) Reply("[RynthJuice] *** KILL ***");
_fx.SpawnKillBurst(kc, ke, kn, ku, crit: false, now);
}
public override void OnTick()
{
if (!_loginComplete) return;
_tick++;
// Auto-diagnostic: ~150 ticks after login, log the full pipeline state once
// (no command / on-screen output needed). Fires even when disabled so the
// log shows enabled=False if that's the cause.
if (!_autoDiagDone && _tick >= 150) { _autoDiagDone = true; RunDiag(); }
if (!_cfg.Enabled) return;
long now = Environment.TickCount64;
_fx.Render(Host, _cfg, now);
if ((_tick & 1) == 0) PollMobHealth(now); // poll mob vitals every other tick
if ((_tick & 0xFF) == 0) PruneHealth(now); // ~every 256 ticks
}
public override void OnChatBarEnter(string? text, ref int eat)
{
if (string.IsNullOrWhiteSpace(text) || !text.StartsWith("/juice", StringComparison.OrdinalIgnoreCase))
return;
eat = 1; // consume — never send to the server as chat
string rest = text.Length > 6 ? text.Substring(6).Trim() : "";
string[] parts = rest.Length == 0 ? Array.Empty<string>() : rest.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string cmd = parts.Length > 0 ? parts[0].ToLowerInvariant() : "";
switch (cmd)
{
case "":
case "toggle":
_cfg.Enabled = !_cfg.Enabled;
if (!_cfg.Enabled) _fx.Clear();
_cfg.Save();
Reply($"[RynthJuice] {(_cfg.Enabled ? "ON" : "OFF")}.");
break;
case "on": _cfg.Enabled = true; _cfg.Save(); Reply("[RynthJuice] ON."); break;
case "off": _cfg.Enabled = false; _fx.Clear(); _cfg.Save(); Reply("[RynthJuice] OFF."); break;
case "heals":
_cfg.ShowHeals = !_cfg.ShowHeals; _cfg.Save();
Host.Log($"[RynthJuice] heal numbers {(_cfg.ShowHeals ? "on" : "off")}.");
break;
case "playerdmg":
_cfg.ShowPlayerDamage = !_cfg.ShowPlayerDamage; _cfg.Save();
Host.Log($"[RynthJuice] player-damage numbers {(_cfg.ShowPlayerDamage ? "on" : "off")}.");
break;
case "scale":
if (parts.Length > 1 && float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float sc))
{ _cfg.Scale = Math.Clamp(sc, 0.3f, 4f); _cfg.Save(); Host.Log($"[RynthJuice] scale = {_cfg.Scale:0.##}."); }
else Host.Log("[RynthJuice] usage: /juice scale 1.5");
break;
case "height":
if (parts.Length > 1 && float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float hh))
{ _cfg.HeightOffset = Math.Clamp(hh, 0f, 8f); _cfg.Save(); Host.Log($"[RynthJuice] height = {_cfg.HeightOffset:0.##} m."); }
else Host.Log("[RynthJuice] usage: /juice height 1.8");
break;
case "test": SpawnTest(); break;
case "debug":
_debugChat = !_debugChat;
Host.Log($"[RynthJuice] combat-log debug {(_debugChat ? "ON" : "OFF")} (logs chat lines to RynthCore.log so we can verify the damage-text format).");
break;
case "help":
default:
Host.Log("[RynthJuice] /juice [on|off|toggle|test|heals|playerdmg|scale N|height N|debug|help]");
break;
}
}
// Command feedback to BOTH the unified log and the in-game chat window.
private void Reply(string msg)
{
Host.Log(msg);
if (Host.HasWriteToChat) Host.WriteToChat(msg, 1);
}
/// <summary>/juice diag — dumps the full render-pipeline state to chat + log so
/// we can pinpoint why numbers aren't appearing (especially indoors). Run it
/// outdoors AND inside a dungeon and compare.</summary>
private void RunDiag()
{
bool nav = Host.HasNav3D, tri = Host.HasNav3DTriangle, w2s = Host.HasWorldToScreen;
bool poseOk = Host.TryGetPlayerPose(out uint cell, out float e, out float n, out float u, out _, out _, out _, out _);
Host.TryGetViewportSize(out uint vpw, out uint vph);
bool indoor = poseOk && (cell & 0xFFFF) >= 0x100;
// Project a point ~2m ABOVE the player (where numbers anchor — not the
// player's feet, which sit at the camera and never project). Test BOTH the
// raw cell-local coords and the EnvCell-transformed landblock-relative
// coords; whichever projects tells us the frame the indoor camera uses.
float upU = u + 2f;
float rrx = 0, rry = 0, xsx = 0, xsy = 0;
bool projRaw = poseOk && w2s && Host.WorldToScreen(e, upU, n, out rrx, out rry);
float xe = e, xn = n, xu = upU;
bool resolveOk = poseOk && _cells.ToLandblockRelative(cell, ref xe, ref xn, ref xu);
bool projXform = resolveOk && w2s && Host.WorldToScreen(xe, xu, xn, out xsx, out xsy);
Reply($"[RynthJuice] DIAG enabled={_cfg.Enabled} tick={_tick} fx={_fx.Count} nav={nav} tri={tri} w2s={w2s} vp={vpw}x{vph}");
Reply($"[RynthJuice] DIAG pose={poseOk} cell=0x{cell:X8} indoor={indoor} cellsReady={_cells.Ready} resolve={resolveOk}");
Reply($"[RynthJuice] DIAG raw=({e:F1},{n:F1},{u:F1}) projRaw={projRaw}@({rrx:F0},{rry:F0}) | xform=({xe:F1},{xn:F1},{xu:F1}) projXform={projXform}@({xsx:F0},{xsy:F0})");
Reply($"[RynthJuice] DIAG render: {_fx.LastRenderStatus} | lastDrawn={_fx.LastDrawnEffects} lastTris={_fx.LastTriangles} writeToChat={Host.HasWriteToChat}");
if (indoor && !_cells.Ready) Reply($"[RynthJuice] DIAG cell.dat status: {_cells.Status}");
}
// Polls each tracked mob's vitals directly (TryGetTargetVitals) — the streaming
// health hook doesn't install on this client, so polling is how we read monster
// HP. Drives both the live health % and instant (no-delay) death detection.
private void PollMobHealth(long now)
{
if (_candidateSet.Count == 0 && _mobSet.Count == 0)
{
if ((_tick & 0x7F) == 0) Host.Log("[RynthJuice] pollcycle tracked=0 (OnCreateObject delivered no ids)");
return;
}
_mobHpScratch.Clear();
// 1) Classify a rotating slice of candidates first, so a mob promoted this poll is
// polled below in the same cycle.
int promoted = CheckCandidates();
// 2) Poll confirmed mobs. Each is dequeued and either re-enqueued at the back or
// dropped, so with more than MobPollBudget mobs the poll still rotates fairly.
int atk = 0, vit = 0;
int mobChecks = Math.Min(_mobQueue.Count, MobPollBudget);
for (int i = 0; i < mobChecks; i++)
{
uint id = _mobQueue.Dequeue();
_mobQueued.Remove(id);
if (!_mobSet.Contains(id)) continue; // stale entry (deleted / demoted)
if (id == _playerId) { _mobSet.Remove(id); continue; }
if (!Host.ObjectIsAttackable(id))
{
// No longer attackable (e.g. died between polls, became friendly): back to
// candidates so it is re-checked in rotation instead of polled every cycle.
_mobSet.Remove(id);
if (_candidateSet.Add(id)) EnqueueCandidate(id);
continue;
}
atk++;
EnqueueMob(id); // stays a mob unless the kill path below removes it
if (!Host.TryGetTargetVitals(id, out uint h, out uint mx, out _, out _, out _, out _) || (h == 0 && mx == 0))
continue; // can't read this tick
vit++;
if (_pollLogCount < 12)
{
_pollLogCount++;
Host.Log($"[RynthJuice] poll 0x{id:X8} h={h} mx={mx}");
}
if (!Host.TryGetObjectPosition(id, out uint cell, out float e, out float n, out float u))
continue;
// Death by poll: HP hit 0 — instant, no OnDeleteObject corpse-removal delay.
if (mx > 0 && h == 0)
{
if (_killedIds.Add(id))
{
if (_debugChat) Reply("[RynthJuice] *** KILL ***");
_fx.SpawnKillBurst(cell, e, n, u, crit: false, now);
Host.Log($"[RynthJuice] KILL(poll) tgt=0x{id:X8} cell=0x{cell:X8}");
}
_mobSet.Remove(id); // its re-enqueued queue entry is discarded lazily
continue;
}
float ratio = mx > 0 ? Math.Clamp((float)h / mx, 0f, 1f) : 1f;
_mobHpScratch.Add(new JuiceEffects.MobHp(cell, e, n, u, ratio));
}
if ((_tick & 0x3F) == 0)
Host.Log($"[RynthJuice] pollcycle candidates={_candidateSet.Count} mobs={_mobSet.Count} promoted={promoted} " +
$"droppedNonCreatures={_droppedNonCreatures} attackable={atk} vitals={vit} bars={_mobHpScratch.Count}");
if (_mobHpScratch.Count > 0) _fx.RenderMobHealth(Host, _cfg, _mobHpScratch);
}
/// <summary>
/// Checks up to <see cref="CandidateCheckBudget"/> candidates from the front of the
/// rotation queue. Each is dropped (player / known non-creature), promoted to a mob
/// (attackable), or re-enqueued at the back — so successive polls walk the whole list
/// instead of re-checking the same first slice. Returns the number promoted.
/// </summary>
private int CheckCandidates()
{
int promoted = 0;
int checks = Math.Min(_candidateQueue.Count, CandidateCheckBudget);
for (int i = 0; i < checks; i++)
{
uint id = _candidateQueue.Dequeue();
_candidateQueued.Remove(id);
if (!_candidateSet.Contains(id)) continue; // stale entry (deleted / promoted)
if (id == _playerId) { _candidateSet.Remove(id); continue; }
// Type can arrive after create; once it says "not a creature", stop checking.
if (IsKnownNonCreature(id))
{
_candidateSet.Remove(id);
_droppedNonCreatures++;
continue;
}
if (Host.ObjectIsAttackable(id))
{
_candidateSet.Remove(id);
if (_mobSet.Add(id)) EnqueueMob(id);
promoted++;
continue;
}
// Unknown type or a non-attackable creature (NPC, pet): keep in rotation —
// attackable state can lag behind create by several ticks.
EnqueueCandidate(id);
}
return promoted;
}
/// <summary>True when the object's ItemType is known and lacks TYPE_CREATURE.
/// Type 0 / unreadable counts as unknown (kept as a candidate).</summary>
private bool IsKnownNonCreature(uint id)
=> Host.HasGetItemType
&& Host.TryGetItemType(id, out uint typeFlags)
&& typeFlags != 0
&& (typeFlags & ItemTypeCreature) == 0;
private void EnqueueCandidate(uint id)
{
if (_candidateQueued.Add(id)) _candidateQueue.Enqueue(id);
}
private void EnqueueMob(uint id)
{
if (_mobQueued.Add(id)) _mobQueue.Enqueue(id);
}
private void ClearTracking()
{
_candidateSet.Clear();
_candidateQueue.Clear();
_candidateQueued.Clear();
_mobSet.Clear();
_mobQueue.Clear();
_mobQueued.Clear();
_droppedNonCreatures = 0;
_trackCapLogged = false;
}
private void PruneHealth(long now)
{
// Allocation-light prune of stale targets.
List<uint>? dead = null;
foreach (var kv in _health)
if (now - kv.Value.LastSeenMs > ForgetMs)
(dead ??= new List<uint>()).Add(kv.Key);
if (dead != null)
foreach (uint id in dead) _health.Remove(id);
}
/// <summary>/juice test — spawn a spread of demo numbers + a burst at the
/// player so the render path can be verified without combat.</summary>
private void SpawnTest()
{
if (!Host.TryGetPlayerPose(out uint cell, out float e, out float n, out float u, out _, out _, out _, out _))
{
Host.Log("[RynthJuice] test: player pose unavailable (are you in the world, outdoors?).");
return;
}
if ((cell >> 16) == 0)
{
Host.Log("[RynthJuice] test: not in the world yet.");
return;
}
long now = Environment.TickCount64;
_lastCritMs = long.MinValue; // don't accidentally crit the demo numbers
_fx.SpawnDamage(cell, e + 2f, n + 2f, u, 18, crit: false);
_fx.SpawnDamage(cell, e - 2f, n + 1f, u, 73, crit: false);
_fx.SpawnDamage(cell, e + 1f, n - 2f, u, 142, crit: false);
_fx.SpawnDamage(cell, e - 1f, n - 1f, u, 891, crit: true);
if (_cfg.ShowHeals) _fx.SpawnHeal(cell, e + 3f, n, u, 64);
_fx.SpawnKillBurst(cell, e, n + 3f, u, crit: true, now);
Host.Log("[RynthJuice] test numbers spawned around you.");
}
}

View file

@ -0,0 +1,74 @@
using System.Numerics;
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// A tiny stroke-based vector font. Nav3D has no text primitive, so each glyph
/// is defined as a set of line segments on a normalized 2×4 grid (x ∈ [0,2],
/// y ∈ [0,4], y increasing DOWNWARD to match screen space). The renderer
/// (<see cref="JuiceEffects"/>) turns every stroke into a thin billboarded quad.
///
/// Only the characters combat juice needs are defined: digits 0-9, '+' (heals),
/// '!' and the letters C R I T (for the "CRIT!" tag). Unknown chars render as a
/// blank advance.
/// </summary>
internal static class VectorFont
{
public const float GlyphWidth = 2f; // max x in grid units
public const float GlyphHeight = 4f; // max y in grid units
public const float Advance = 3f; // per-char horizontal step (glyph + gap)
// Seven-segment grid points:
// (0,0)──A──(2,0)
// │ │
// F B
// │ │
// (0,2)──G──(2,2)
// │ │
// E C
// │ │
// (0,4)──D──(2,4)
private static readonly Vector4 A = new(0, 0, 2, 0); // top
private static readonly Vector4 B = new(2, 0, 2, 2); // upper-right
private static readonly Vector4 C = new(2, 2, 2, 4); // lower-right
private static readonly Vector4 D = new(0, 4, 2, 4); // bottom
private static readonly Vector4 E = new(0, 2, 0, 4); // lower-left
private static readonly Vector4 F = new(0, 0, 0, 2); // upper-left
private static readonly Vector4 G = new(0, 2, 2, 2); // middle
private static readonly Vector4[] Zero = { A, B, C, D, E, F };
private static readonly Vector4[] One = { B, C };
private static readonly Vector4[] Two = { A, B, G, E, D };
private static readonly Vector4[] Three = { A, B, G, C, D };
private static readonly Vector4[] Four = { F, G, B, C };
private static readonly Vector4[] Five = { A, F, G, C, D };
private static readonly Vector4[] Six = { A, F, G, E, C, D };
private static readonly Vector4[] Seven = { A, B, C };
private static readonly Vector4[] Eight = { A, B, C, D, E, F, G };
private static readonly Vector4[] Nine = { A, B, C, D, F, G };
private static readonly Vector4[] Plus = { new(0, 2, 2, 2), new(1, 1, 1, 3) };
private static readonly Vector4[] Bang = { new(1, 0, 1, 2.6f), new(1, 3.4f, 1, 4f) };
private static readonly Vector4[] LetterC = { A, F, E, D };
// R: left bar + top + upper-right + middle + diagonal leg
private static readonly Vector4[] LetterR = { F, E, A, B, G, new(1, 2, 2, 4) };
private static readonly Vector4[] LetterI = { new(1, 0, 1, 4) };
private static readonly Vector4[] LetterT = { A, new(1, 0, 1, 4) };
private static readonly Vector4[] Empty = System.Array.Empty<Vector4>();
/// <summary>Strokes for a glyph, in grid units. Empty array = blank advance.</summary>
public static Vector4[] Strokes(char c) => c switch
{
'0' => Zero, '1' => One, '2' => Two, '3' => Three, '4' => Four,
'5' => Five, '6' => Six, '7' => Seven, '8' => Eight, '9' => Nine,
'+' => Plus, '!' => Bang,
'C' => LetterC, 'R' => LetterR, 'I' => LetterI, 'T' => LetterT,
_ => Empty,
};
/// <summary>Total grid width of a string (for centering): N chars × Advance, trimmed of the trailing gap.</summary>
public static float MeasureWidth(string s) =>
s.Length == 0 ? 0f : s.Length * Advance - (Advance - GlyphWidth);
}