Snapshot for release 2026.10.15.6 (internal eca8fa0)

This commit is contained in:
Tom Bohar 2026-10-15 23:44:40 -04:00
commit 8cf68da453
43 changed files with 4133 additions and 94 deletions

View file

@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.IO;
using DotRecast.Core;
using DotRecast.Detour;
using DotRecast.Detour.Io;
namespace RynthNav.Routing;
/// <summary>
/// A dungeon's navmesh, one file (NavData\dun_LLLL.tile) holding all its Detour tiles.
///
/// A dungeon's cells are not kept inside their landblock: they run into negative landblock-local x/y
/// (down to about -360 m) and out past 192 m (to about 390 m), over 190 m tiles that are no real
/// landblocks. So a dungeon is its own navmesh, laid out in the landblock-local frame shifted by
/// (ShiftX, ShiftY) metres, a multiple of 192 that makes every coordinate positive:
///
/// mesh position = landblock-local position + shift (x east, up, y north; the pose's x, y, z)
///
/// Tiles are 192 m squares on that frame (tile index = floor(mesh / 192), in each tile's header).
///
/// File: "RNDG" (0x47444E52), version 1, int shiftX, int shiftY, int count, then per tile
/// int length and the tile as DotRecast's DtMeshDataWriter writes it (little endian).
/// Host-free: the plugin, the baker and the tests share it.
/// </summary>
internal sealed class DungeonTileFile
{
public const string Prefix = "dun_";
public const string Extension = ".tile";
private const uint Magic = 0x47444E52; // "RNDG"
private const int Version = 1;
public const float TileSize = 192f;
public int ShiftX { get; }
public int ShiftY { get; }
public IReadOnlyList<DtMeshData> Tiles { get; }
public DungeonTileFile(int shiftX, int shiftY, IReadOnlyList<DtMeshData> tiles) { ShiftX = shiftX; ShiftY = shiftY; Tiles = tiles; }
public static string FileName(uint lb) => $"{Prefix}{lb:X4}{Extension}";
public static void Write(string path, int shiftX, int shiftY, IReadOnlyList<DtMeshData> tiles)
{
string tmp = path + ".tmp";
using (var fs = File.Create(tmp))
using (var bw = new BinaryWriter(fs))
{
bw.Write(Magic); bw.Write(Version); bw.Write(shiftX); bw.Write(shiftY); bw.Write(tiles.Count);
foreach (DtMeshData md in tiles)
{
using var ms = new MemoryStream();
using (var tw = new BinaryWriter(ms, System.Text.Encoding.UTF8, leaveOpen: true))
new DtMeshDataWriter().Write(tw, md, RcByteOrder.LITTLE_ENDIAN, false);
bw.Write((int)ms.Length);
bw.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
}
File.Move(tmp, path, overwrite: true); // a bake stopped half way never leaves a truncated file
}
/// <summary>Reads a dungeon file; null when it isn't one (or is cut short).</summary>
public static DungeonTileFile? Read(string path, int vertsPerPoly = 6)
{
try
{
using var fs = File.OpenRead(path);
using var br = new BinaryReader(fs);
if (br.ReadUInt32() != Magic || br.ReadInt32() != Version) return null;
int sx = br.ReadInt32(), sy = br.ReadInt32(), n = br.ReadInt32();
if (n < 0 || n > 4096) return null;
var tiles = new List<DtMeshData>(n);
for (int i = 0; i < n; i++)
{
int len = br.ReadInt32();
if (len <= 0 || len > fs.Length - fs.Position) return null;
using var ms = new MemoryStream(br.ReadBytes(len));
using var tr = new BinaryReader(ms);
tiles.Add(new DtMeshDataReader().Read(tr, vertsPerPoly));
}
return new DungeonTileFile(sx, sy, tiles);
}
catch (Exception ex) when (ex is IOException or EndOfStreamException or InvalidDataException or ArgumentException) { return null; }
}
/// <summary>A Detour navmesh of just these tiles (mesh frame: tile (x, y) at x * 192, y * 192).</summary>
public DtNavMesh BuildNavMesh()
{
var nav = new DtNavMesh();
var p = new DtNavMeshParams
{
orig = new DotRecast.Core.Numerics.RcVec3f(0, 0, 0), tileWidth = TileSize, tileHeight = TileSize,
maxTiles = Math.Max(1, Tiles.Count), maxPolys = 1 << 16,
};
nav.Init(ref p, 6);
foreach (DtMeshData md in Tiles) nav.AddTile(md, 0, 0, out _);
return nav;
}
}

View file

@ -0,0 +1,327 @@
using System;
using System.Collections.Generic;
using DotRecast.Detour;
using RynthCore.Plugin.Shared;
namespace RynthNav.Routing;
/// <summary>
/// The navmesh drawn in the world: where you can walk, and where the mesh ends.
///
/// - Floor: the walkable ground, as translucent triangles lying on it (the tile's detail mesh,
/// so they follow the terrain and the building floors).
/// - Walls: every polygon edge with no neighbour, as an upright strip of triangles. Those edges are
/// exactly where the baker said "not here": buildings, trees, rocks, cliffs, steep slopes, water,
/// and the body-width margin round them. Where there is no green and a red wall stands, nav
/// will not take you.
///
/// Host-free (it writes to an <see cref="INav3DSink"/>), so the tests cover it. Tick thread only.
/// The tiles are registered as the plugin loads them (just a reference); a tile's triangles are
/// worked out the first time it is within range. The engine's Nav3D buffer holds 8192 triangles
/// for every plugin, so a draw is capped (<see cref="Options.MaxTriangles"/>), nearest first.
/// </summary>
internal sealed class NavMeshView
{
public const float TileSize = 192f;
/// <summary>One tile's triangles, relative to the tile's south-west corner (precise in float at any landblock).</summary>
internal sealed class Tile
{
public int OriginX, OriginY; // world metres of the corner (landblock x/y * 192)
public float[] Floor = Array.Empty<float>(); // 9 per triangle: (east, up, north) x3
public float[] Walls = Array.Empty<float>(); // 6 per edge: (east, up, north) of its two ends
public int FloorCount => Floor.Length / 9;
public int WallCount => Walls.Length / 6;
}
internal readonly struct Options
{
public readonly float Radius; // metres from the character
public readonly int MaxTriangles; // for floor and walls together (a wall strip is two)
public readonly bool Floor, Walls;
public readonly float Lift; // floor and wall bottoms above the mesh, so they don't fight the ground
public readonly float WallHeight;
public readonly float MaxUpDown; // ignore mesh further above/below the character than this (other levels)
public readonly uint FloorColor, WallColor;
public readonly int Layer; // 0 = the outdoor tiles, 1 = the dungeon's: only one is drawn
public readonly double FrameX, FrameY; // world metres of the landblock whose local frame Nav3D is in; NaN = the one the character stands in (outdoors)
public Options(float radius, int maxTriangles, bool floor, bool walls, float lift = 0.15f, float wallHeight = 1.5f,
float maxUpDown = 20f, uint floorColor = DefaultFloorColor, uint wallColor = DefaultWallColor,
int layer = 0, double frameX = double.NaN, double frameY = double.NaN)
{
Radius = radius; MaxTriangles = maxTriangles; Floor = floor; Walls = walls; Lift = lift;
WallHeight = wallHeight; MaxUpDown = maxUpDown; FloorColor = floorColor; WallColor = wallColor;
Layer = layer; FrameX = frameX; FrameY = frameY;
}
}
public const uint DefaultFloorColor = 0x3A30E060; // translucent green
public const uint DefaultWallColor = 0x78FF3A2A; // translucent red
// A wall counts as nearer than it is when choosing what to keep under the cap: a wall is what
// you most want to see, and one strip costs two triangles.
private const float WallPriority = 0.25f;
// The pick is kept until the character moves this far (or a tile comes or goes).
private const float RepickMetres = 1.5f;
// One registered tile: its data, where its corner is on the mesh's own frame (what the vertices are
// measured from) and in the world, and which layer it is drawn in.
private sealed class Reg
{
public DtMeshData Md = null!;
public int MeshOx, MeshOy, WorldOx, WorldOy, Layer;
}
private const uint DungeonKeyBase = 0x100000;
private readonly Dictionary<uint, Reg> _data = new();
private readonly Dictionary<uint, Tile?> _built = new();
private readonly List<uint> _dungeonKeys = new();
private int _version;
private int _pickLayer = -1;
private readonly struct Pick
{
public readonly Tile T; public readonly int Index; public readonly bool Wall; public readonly float Key;
public Pick(Tile t, int index, bool wall, float key) { T = t; Index = index; Wall = wall; Key = key; }
}
private readonly List<Pick> _picks = new();
private readonly List<Pick> _cands = new();
private int _pickVersion = -1;
private double _pickX = double.NaN, _pickY;
private float _pickRadius;
private int _pickBudget;
private bool _pickFloor, _pickWalls;
private float _pickUp = float.NaN;
/// <summary>Triangles / wall strips submitted by the last <see cref="Emit"/>.</summary>
public int LastTriangles { get; private set; }
public int TileCount => _data.Count;
/// <summary>An outdoor tile (nav_LLLL.tile): its vertices are world metres, its corner is the landblock's.</summary>
public void Register(uint lb, DtMeshData md)
{
int ox = (int)((lb >> 8) & 0xFF) * (int)TileSize, oy = (int)(lb & 0xFF) * (int)TileSize;
_data[lb] = new Reg { Md = md, MeshOx = ox, MeshOy = oy, WorldOx = ox, WorldOy = oy, Layer = 0 };
_built.Remove(lb); _version++;
}
public void Unregister(uint lb)
{
if (_data.Remove(lb)) { _built.Remove(lb); _version++; }
}
/// <summary>The landblock whose dungeon is registered (0 = none).</summary>
public uint DungeonLandblock { get; private set; }
/// <summary>
/// A dungeon's tiles (dun_LLLL.tile), replacing any dungeon registered before. Their vertices are on the
/// file's shifted frame (landblock-local + shift); the world corner of a tile is the landblock's plus the
/// tile's mesh corner minus the shift.
/// </summary>
public void RegisterDungeon(uint lb, DungeonTileFile f)
{
UnregisterDungeon();
double lbX = ((lb >> 8) & 0xFF) * (double)TileSize, lbY = (lb & 0xFF) * (double)TileSize;
for (int i = 0; i < f.Tiles.Count; i++)
{
DtMeshData md = f.Tiles[i];
int mx = md.header.x * (int)TileSize, my = md.header.y * (int)TileSize;
uint key = DungeonKeyBase + (uint)i;
_data[key] = new Reg { Md = md, MeshOx = mx, MeshOy = my, WorldOx = (int)(lbX + mx - f.ShiftX), WorldOy = (int)(lbY + my - f.ShiftY), Layer = 1 };
_built.Remove(key); _dungeonKeys.Add(key);
}
DungeonLandblock = lb; _version++;
}
public void UnregisterDungeon()
{
foreach (uint k in _dungeonKeys) { _data.Remove(k); _built.Remove(k); }
if (_dungeonKeys.Count > 0 || DungeonLandblock != 0) _version++;
_dungeonKeys.Clear(); DungeonLandblock = 0;
}
public void Clear()
{
_data.Clear(); _built.Clear(); _dungeonKeys.Clear(); DungeonLandblock = 0; _picks.Clear(); _cands.Clear(); _version++; LastTriangles = 0;
}
// ── Reading a tile ───────────────────────────────────────────────────────
/// <summary>The floor triangles and wall edges of one baked tile.</summary>
internal static Tile BuildTile(uint lb, DtMeshData md)
{
int ox = (int)((lb >> 8) & 0xFF) * (int)TileSize, oy = (int)(lb & 0xFF) * (int)TileSize;
return BuildTile(md, ox, oy, ox, oy);
}
/// <summary>Vertices are measured from the tile's corner on the mesh's frame; the tile itself sits at its world corner.</summary>
internal static Tile BuildTile(DtMeshData md, int meshOx, int meshOy, int worldOx, int worldOy)
{
var t = new Tile { OriginX = worldOx, OriginY = worldOy };
float ox = meshOx, oy = meshOy;
var floor = new List<float>(md.header.detailTriCount * 9);
var walls = new List<float>();
void Vtx(List<float> to, float x, float up, float ns) { to.Add(x - ox); to.Add(up); to.Add(ns - oy); }
for (int i = 0; i < md.header.polyCount; i++)
{
DtPoly p = md.polys[i];
if (p.GetPolyType() != DtPolyTypes.DT_POLYTYPE_GROUND) continue;
int nv = p.vertCount;
// Edges nothing is joined to (not a tile border: those carry DT_EXT_LINK, so they're nonzero).
for (int j = 0; j < nv; j++)
{
if (p.neis[j] != 0) continue;
int a = p.verts[j] * 3, b = p.verts[(j + 1) % nv] * 3;
Vtx(walls, md.verts[a], md.verts[a + 1], md.verts[a + 2]);
Vtx(walls, md.verts[b], md.verts[b + 1], md.verts[b + 2]);
}
// The ground: the polygon's detail triangles (they follow the height), else a fan.
DtPolyDetail[]? dm = md.detailMeshes;
if (dm != null && i < dm.Length && dm[i].triCount > 0)
{
DtPolyDetail pd = dm[i];
for (int k = 0; k < pd.triCount; k++)
for (int c = 0; c < 3; c++)
{
int idx = md.detailTris[(pd.triBase + k) * 4 + c];
if (idx < nv) { int v = p.verts[idx] * 3; Vtx(floor, md.verts[v], md.verts[v + 1], md.verts[v + 2]); }
else { int v = (pd.vertBase + idx - nv) * 3; Vtx(floor, md.detailVerts[v], md.detailVerts[v + 1], md.detailVerts[v + 2]); }
}
}
else
{
for (int k = 1; k + 1 < nv; k++)
foreach (int idx in new[] { 0, k, k + 1 })
{ int v = p.verts[idx] * 3; Vtx(floor, md.verts[v], md.verts[v + 1], md.verts[v + 2]); }
}
}
t.Floor = floor.ToArray();
t.Walls = walls.ToArray();
return t;
}
private Tile? TileFor(uint key)
{
if (_built.TryGetValue(key, out Tile? t)) return t;
t = _data.TryGetValue(key, out Reg? r) ? BuildTile(r.Md, r.MeshOx, r.MeshOy, r.WorldOx, r.WorldOy) : null;
_built[key] = t;
return t;
}
// ── Choosing what to draw ────────────────────────────────────────────────
private void Repick(double px, double py, float pz, in Options o)
{
_picks.Clear(); _cands.Clear();
float r = o.Radius, r2 = r * r;
int cost = 0;
foreach (var kv in _data)
{
uint lb = kv.Key;
if (kv.Value.Layer != o.Layer) continue;
float x0 = kv.Value.WorldOx, y0 = kv.Value.WorldOy;
// Distance from the character to the tile's square.
double dx = Math.Max(Math.Max(x0 - px, px - (x0 + TileSize)), 0), dy = Math.Max(Math.Max(y0 - py, py - (y0 + TileSize)), 0);
if (dx * dx + dy * dy > (double)r2) continue;
Tile? t = TileFor(lb);
if (t == null) continue;
float ox = t.OriginX - (float)px, oy = t.OriginY - (float)py; // tile corner relative to the character
if (o.Floor)
{
float[] f = t.Floor;
for (int k = 0, n = t.FloorCount; k < n; k++)
{
int b = k * 9;
float cx = ox + (f[b] + f[b + 3] + f[b + 6]) / 3f, cy = oy + (f[b + 2] + f[b + 5] + f[b + 8]) / 3f;
float d2 = cx * cx + cy * cy;
if (d2 > r2) continue;
if (Math.Abs((f[b + 1] + f[b + 4] + f[b + 7]) / 3f - pz) > o.MaxUpDown) continue;
_cands.Add(new Pick(t, k, false, d2));
cost++;
}
}
if (o.Walls)
{
float[] w = t.Walls;
for (int k = 0, n = t.WallCount; k < n; k++)
{
int b = k * 6;
float cx = ox + (w[b] + w[b + 3]) * 0.5f, cy = oy + (w[b + 2] + w[b + 5]) * 0.5f;
float d2 = cx * cx + cy * cy;
if (d2 > r2) continue;
if (Math.Abs((w[b + 1] + w[b + 4]) * 0.5f - pz) > o.MaxUpDown) continue;
_cands.Add(new Pick(t, k, true, d2 * WallPriority));
cost += 2;
}
}
}
if (cost > o.MaxTriangles) _cands.Sort((a, b) => a.Key.CompareTo(b.Key));
int used = 0;
foreach (Pick c in _cands)
{
int c2 = c.Wall ? 2 : 1;
if (used + c2 > o.MaxTriangles) { if (cost > o.MaxTriangles) break; continue; }
_picks.Add(c);
used += c2;
}
_cands.Clear();
_pickVersion = _version; _pickX = px; _pickY = py; _pickUp = pz;
_pickRadius = o.Radius; _pickBudget = o.MaxTriangles; _pickFloor = o.Floor; _pickWalls = o.Walls; _pickLayer = o.Layer;
}
// ── Drawing ──────────────────────────────────────────────────────────────
/// <summary>
/// Submits the mesh near the character (world metres east/north/up) to the sink, in the Nav3D
/// frame: the character's landblock, X = east, Y = height, Z = north. Returns triangles submitted.
/// </summary>
public int Emit(INav3DSink sink, double px, double py, double pz, in Options o)
{
LastTriangles = 0;
if (_data.Count == 0 || o.MaxTriangles <= 0 || (!o.Floor && !o.Walls)) return 0;
double dxm = px - _pickX, dym = py - _pickY;
bool stale = _pickVersion != _version || double.IsNaN(_pickX) || dxm * dxm + dym * dym > RepickMetres * RepickMetres
|| Math.Abs(pz - _pickUp) > 2f || o.Radius != _pickRadius || o.MaxTriangles != _pickBudget
|| o.Floor != _pickFloor || o.Walls != _pickWalls || o.Layer != _pickLayer;
if (stale) Repick(px, py, (float)pz, o);
// Outdoors the character is inside its landblock, so its corner is the frame; in a dungeon the
// character's local x/y can be anywhere (down to -360), and the caller names the landblock.
double baseX = double.IsNaN(o.FrameX) ? Math.Floor(px / TileSize) * TileSize : o.FrameX;
double baseY = double.IsNaN(o.FrameY) ? Math.Floor(py / TileSize) * TileSize : o.FrameY;
int tris = 0;
foreach (Pick c in _picks)
{
Tile t = c.T;
float ox = (float)(t.OriginX - baseX), oy = (float)(t.OriginY - baseY);
if (!c.Wall)
{
float[] f = t.Floor; int b = c.Index * 9;
sink.Triangle(ox + f[b], f[b + 1] + o.Lift, oy + f[b + 2],
ox + f[b + 3], f[b + 4] + o.Lift, oy + f[b + 5],
ox + f[b + 6], f[b + 7] + o.Lift, oy + f[b + 8], o.FloorColor);
tris++;
}
else
{
float[] w = t.Walls; int b = c.Index * 6;
float ax = ox + w[b], ay = w[b + 1] + o.Lift, az = oy + w[b + 2];
float bx = ox + w[b + 3], by = w[b + 4] + o.Lift, bz = oy + w[b + 5];
sink.Triangle(ax, ay, az, bx, by, bz, bx, by + o.WallHeight, bz, o.WallColor);
sink.Triangle(ax, ay, az, bx, by + o.WallHeight, bz, ax, ay + o.WallHeight, az, o.WallColor);
tris += 2;
}
}
LastTriangles = tris;
return tris;
}
}

View file

@ -58,11 +58,12 @@ public sealed partial class RynthNavPlugin
{
_tileRegions[lb] = NavRegions.Build(md, out _);
_tilePrints[lb] = NavRegions.Fingerprint(md);
_meshView.Register(lb, md);
NavGraph? g = _graph;
if (g != null && ReferenceEquals(g, _graphChecked)) CheckTile(g, lb);
}
private void OnTileUnloaded(uint lb) { _tileRegions.Remove(lb); _tilePrints.Remove(lb); }
private void OnTileUnloaded(uint lb) { _tileRegions.Remove(lb); _tilePrints.Remove(lb); _meshView.Unregister(lb); }
private void CheckTile(NavGraph g, uint lb)
{

View file

@ -49,6 +49,55 @@ public sealed partial class RynthNavPlugin
_markerGuide = NavDataConfig.ReadSwitch("markerGuide", false);
}
// ── The walking path, for the engine's World Map ─────────────────────
// The trip's walks (and the walks inside the Town Network) as the status JSON's "path": an array of
// segments, each a flat list of ns, ew pairs in map degrees (4 decimals: 0.02 yd), thinned to about
// MaxPathPoints in all (a segment keeps its ends). Built once per TripPath and kept; empty (the field
// is left out) while the markers are off the ground or the path isn't worked out yet. Pump thread.
private const int MaxPathPoints = 800;
private TripPath? _pathJsonFor;
private string _pathJson = "";
private string PathJson()
{
TripPath? p = _tripPath;
if (p == null || !_tripShown) return "";
lock (_gate)
{
if (ReferenceEquals(p, _pathJsonFor)) return _pathJson;
var segs = new List<WorldPt[]>();
for (int i = 0; i < p.Walks.Length; i++)
{
if (p.Walks[i] is { Length: >= 2 } w) segs.Add(w);
if (i < p.Hub.Length && p.Hub[i] is { Length: >= 2 } h) segs.Add(h);
}
int total = 0;
foreach (WorldPt[] s in segs) total += s.Length;
int stride = Math.Max(1, (total + MaxPathPoints - 1) / MaxPathPoints);
var ci = System.Globalization.CultureInfo.InvariantCulture;
var sb = new System.Text.StringBuilder(total * 20 + 8);
sb.Append('[');
bool firstSeg = true;
foreach (WorldPt[] s in segs)
{
if (!firstSeg) sb.Append(',');
firstSeg = false;
sb.Append('[');
for (int i = 0; i < s.Length; i++)
{
if (i % stride != 0 && i != s.Length - 1) continue;
if (i > 0) sb.Append(',');
sb.Append(NavCoords.NsFromWorld(s[i].Y).ToString("F4", ci)).Append(',').Append(NavCoords.EwFromWorld(s[i].X).ToString("F4", ci));
}
sb.Append(']');
}
sb.Append(']');
_pathJsonFor = p;
_pathJson = segs.Count == 0 ? "" : sb.ToString();
return _pathJson;
}
}
// ── The trip ─────────────────────────────────────────────────────────
/// <summary>A new plan (Route) or goto (Go): its trip, shown, its path worked out. Tick thread.</summary>

View file

@ -0,0 +1,114 @@
using System;
using System.Globalization;
using RynthNav.Routing;
namespace RynthCore.Plugin.RynthNav;
// The navmesh on the ground (NavMeshView): green where nav can take you, red walls where the mesh
// ends (buildings, trees, rocks, cliffs, steep slopes, and the margin round them). Drawn on the
// engine's Nav3D buffer like the path markers. Off by default; it is a look-at-it tool, not part
// of walking. Switches in rynthnav.json: meshView, meshFloor, meshWalls, meshRadius, meshTriangles.
// /rnav mesh changes them. In a dungeon it draws NavData\dun_LLLL.tile (a dungeon's own mesh, baked by
// RynthNav.Baker --dungeons), the floor you're on; with no such file it draws nothing there. Not drawn while portaling.
public sealed partial class RynthNavPlugin
{
private const double MeshRadiusDefault = 40, MeshRadiusMin = 10, MeshRadiusMax = 150;
private const int MeshTrianglesDefault = 3000, MeshTrianglesMin = 200, MeshTrianglesMax = 7000;
private volatile bool _meshOn, _meshFloor = true, _meshWalls = true;
private double _meshRadius = MeshRadiusDefault;
private int _meshBudget = MeshTrianglesDefault;
private readonly NavMeshView _meshView = new();
private volatile int _meshDrawn;
private void LoadMeshSettings()
{
_meshOn = NavDataConfig.ReadSwitch("meshView", false);
_meshFloor = NavDataConfig.ReadSwitch("meshFloor", true);
_meshWalls = NavDataConfig.ReadSwitch("meshWalls", true);
_meshRadius = Math.Clamp(NavDataConfig.ReadNumber("meshRadius", MeshRadiusDefault), MeshRadiusMin, MeshRadiusMax);
_meshBudget = (int)Math.Clamp(NavDataConfig.ReadNumber("meshTriangles", MeshTrianglesDefault), MeshTrianglesMin, MeshTrianglesMax);
}
// A dungeon draws only the floor you're on, give or take: the floors above and below sit metres away.
private const float MeshDungeonUpDown = 8f;
private uint _meshDunLb; // the landblock a dungeon file was last looked for (0 = outdoors / none yet)
private string _meshDunStatus = "";
private void TickMeshView()
{
if (!_meshOn || !_hasPose || !Host.HasNav3D || !Host.HasNav3DTriangle) { _meshDrawn = 0; return; }
if ((_cellId >> 16) == 0 || (Host.HasIsPortaling && Host.IsPortaling())) { _meshDrawn = 0; return; }
try
{
// Cells from 0x100 up are buildings or a dungeon. A landblock with a dungeon file (dun_LLLL.tile)
// is drawn from it; a building in an outdoor landblock keeps the outdoor mesh.
uint lb = CurrentLandblock;
bool indoors = (_cellId & 0xFFFF) >= 0x100;
if (indoors && lb != _meshDunLb)
{
_meshDunLb = lb;
LoadMeshDungeon(lb);
}
else if (!indoors && _meshDunLb != 0)
{
_meshDunLb = 0;
_meshView.UnregisterDungeon();
_meshDunStatus = "";
}
bool dungeon = indoors && _meshView.DungeonLandblock == lb;
NavMeshView.Options opts = dungeon
? new NavMeshView.Options((float)_meshRadius, _meshBudget, _meshFloor, _meshWalls, maxUpDown: MeshDungeonUpDown,
layer: 1, frameX: ((lb >> 8) & 0xFF) * 192.0, frameY: (lb & 0xFF) * 192.0)
: new NavMeshView.Options((float)_meshRadius, _meshBudget, _meshFloor, _meshWalls);
_meshDrawn = _meshView.Emit(_markerSink ??= new HostMarkerSink(Host), _wx, _wy, _wz, opts);
}
catch (Exception ex) { _meshDrawn = 0; Host.Log($"[RynthNav] mesh view: {ex.Message}"); }
}
/// <summary>Reads NavData\dun_LLLL.tile into the mesh view's dungeon layer (none: the layer is emptied). Tick thread.</summary>
private void LoadMeshDungeon(uint lb)
{
_meshView.UnregisterDungeon();
string path = System.IO.Path.Combine(NavDataDir, DungeonTileFile.FileName(lb));
if (!System.IO.File.Exists(path)) { _meshDunStatus = $"no dungeon tile for 0x{lb:X4}"; return; }
DungeonTileFile? f = DungeonTileFile.Read(path);
if (f == null) { _meshDunStatus = $"dungeon tile 0x{lb:X4} unreadable"; Host.Log($"[RynthNav] {_meshDunStatus}"); return; }
_meshView.RegisterDungeon(lb, f);
_meshDunStatus = $"dungeon 0x{lb:X4}: {f.Tiles.Count} tiles";
Host.Log($"[RynthNav] mesh view: dungeon 0x{lb:X4} loaded ({f.Tiles.Count} tiles)");
}
/// <summary>/rnav mesh [on|off | floor on|off | walls on|off | radius &lt;m&gt; | triangles &lt;n&gt;]</summary>
private void CmdMesh(string rest)
{
string[] a = rest.ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries);
bool isNum = a.Length == 2 && double.TryParse(a[1], NumberStyles.Float, CultureInfo.InvariantCulture, out _);
double num = isNum ? double.Parse(a[1], CultureInfo.InvariantCulture) : 0;
if (a.Length == 1 && a[0] is "on" or "off")
{
_meshOn = a[0] == "on";
NavDataConfig.WriteSwitch("meshView", _meshOn);
}
else if (a.Length == 2 && a[0] == "floor" && a[1] is "on" or "off")
{ _meshFloor = a[1] == "on"; NavDataConfig.WriteSwitch("meshFloor", _meshFloor); }
else if (a.Length == 2 && a[0] == "walls" && a[1] is "on" or "off")
{ _meshWalls = a[1] == "on"; NavDataConfig.WriteSwitch("meshWalls", _meshWalls); }
else if (a.Length == 2 && a[0] == "radius" && isNum)
{ _meshRadius = Math.Clamp(num, MeshRadiusMin, MeshRadiusMax); NavDataConfig.WriteNumber("meshRadius", _meshRadius); }
else if (a.Length == 2 && a[0] == "triangles" && isNum)
{ _meshBudget = (int)Math.Clamp(num, MeshTrianglesMin, MeshTrianglesMax); NavDataConfig.WriteNumber("meshTriangles", _meshBudget); }
else if (a.Length > 0)
{
Say("/rnav mesh on|off, mesh floor on|off, mesh walls on|off, mesh radius <m> (10-150), mesh triangles <n> (200-7000)");
return;
}
bool inDungeonMesh = _hasPose && (_cellId & 0xFFFF) >= 0x100 && _meshView.DungeonLandblock == CurrentLandblock;
string where = !_hasPose ? ""
: (_cellId & 0xFFFF) >= 0x100 && _meshDunStatus.StartsWith("no dungeon tile", StringComparison.Ordinal) && InDungeon(_cellId) ? $" — {_meshDunStatus}: bake it with RynthNav.Baker --dungeons"
: inDungeonMesh ? (_meshOn ? $" — {_meshDunStatus}, {_meshDrawn} triangles drawn" : $" — {_meshDunStatus}")
: _meshView.TileCount == 0 ? " — no tiles loaded here" : _meshOn ? $" — {_meshDrawn} triangles drawn, {_meshView.TileCount} tiles loaded" : "";
Say($"navmesh view {(_meshOn ? "ON" : "OFF")}: green floor {(_meshFloor ? "on" : "off")}, red walls {(_meshWalls ? "on" : "off")}, " +
$"{_meshRadius:0} m, at most {_meshBudget} triangles{where}. Green = nav can walk here; red = the mesh ends (building, tree, cliff, steep ground).");
}
}

View file

@ -153,11 +153,16 @@ public sealed partial class RynthNavPlugin
.Append("\",\"tileHere\":").Append(_tileHere).Append(",\"indoors\":").Append(_hasPose && (cell & 0xFFFF) >= 0x100 ? 1 : 0)
.Append(",\"onDisk\":").Append(_tilesOnDisk)
.Append(",\"townNet\":").Append(_townNet != null ? 1 : 0).Append(",\"townNetStatus\":\"").Append(Esc(_townNetStatus)).Append("\"}");
// Path markers (RynthNavPlugin.Markers.cs) and "save as nav route" (RynthNavPlugin.SaveRoute.cs), 0.6.6+.
// Path markers (RynthNavPlugin.Markers.cs) and "save as nav route" (RynthNavPlugin.SaveRoute.cs), 0.6.6+. The mesh view (RynthNavPlugin.MeshView.cs), 0.6.7+.
sb.Append(",\"mesh\":{\"on\":").Append(_meshOn ? 1 : 0).Append(",\"floor\":").Append(_meshFloor ? 1 : 0)
.Append(",\"walls\":").Append(_meshWalls ? 1 : 0).Append(",\"radius\":").Append(_meshRadius.ToString("F0", ci))
.Append(",\"triangles\":").Append(_meshBudget).Append(",\"drawn\":").Append(_meshDrawn).Append('}');
PlannedTrip? trip = _trip;
sb.Append(",\"markers\":{\"on\":").Append(_markersOn ? 1 : 0).Append(",\"labels\":").Append(_markerLabels ? 1 : 0)
.Append(",\"guide\":").Append(_markerGuide ? 1 : 0).Append(",\"shown\":").Append(trip != null && _tripShown ? 1 : 0)
.Append(",\"status\":\"").Append(Esc(_markerStatus)).Append("\"}");
string pathJson = PathJson(); // the walking path, for the engine's World Map
if (pathJson.Length > 0) sb.Append(",\"path\":").Append(pathJson);
sb.Append(",\"save\":{\"can\":").Append(trip != null ? 1 : 0).Append(",\"for\":\"").Append(Esc(trip?.Goal ?? ""))
.Append("\",\"name\":\"").Append(Esc(_saveDefault)).Append("\",\"conflict\":\"").Append(Esc(_saveConflict))
.Append("\",\"busy\":").Append(_saveBusy ? 1 : 0).Append(",\"last\":\"").Append(Esc(_saveLast)).Append("\"}");

View file

@ -986,6 +986,7 @@ public sealed partial class RynthNavPlugin
"/rnav goto <coords> | preview <coords> | portals on|off | stop | here | load | test | navdata\n" +
"/rnav avoid — show; avoid portals on|off|<m> | walls on|off|<m> | corners <m>\n" +
"/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" +
"/rnav mesh on|off | floor on|off | walls on|off | radius <m> | triangles <n> — draw the navmesh: green floor, red walls\n" +
"/rnav saveroute [name] [overwrite] — save the last trip as a RynthAi nav route (NavProfiles)";
/// <summary>One /rnav command. Tick thread.</summary>
@ -1029,6 +1030,7 @@ public sealed partial class RynthNavPlugin
case "recalls": CmdRecalls(rest); break;
case "tie": CmdTie(rest); break;
case "markers": CmdMarkers(rest); break;
case "mesh": CmdMesh(rest); break;
case "saveroute": CmdSaveRoute(rest); break;
case "arrive":
if (double.TryParse(rest, NumberStyles.Float, CultureInfo.InvariantCulture, out double yd) && yd >= 2 && yd <= 200)

View file

@ -25,7 +25,7 @@ namespace RynthCore.Plugin.RynthNav;
public sealed partial class RynthNavPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthNav");
internal const string PluginVersion = "0.6.6";
internal const string PluginVersion = "0.6.7";
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginVersion);
/// <summary>Lets PluginExports log through this plugin's host (the base Log is protected).</summary>
@ -144,6 +144,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
_recallsEnabled = NavDataConfig.ReadSwitch("recalls", true);
LoadAvoidSettings();
LoadMarkerSettings();
LoadMeshSettings();
Host.Log($"[RynthNav] Initialized v{PluginVersion} (tiled streaming + long-range goto + portal/recall routing + arrow + atlas). Panel: RynthNav. Tiles: {NavDataDir} ({NavConfig.Source})");
InitTravel();
LoadGraph();
@ -185,6 +186,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
_chatOut.Clear();
_goNote = "";
HideMarkers("logged out");
_meshView.Clear(); _meshDunLb = 0;
_trip = null; _tripPath = null;
OnLogoutTravel();
}
@ -206,6 +208,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
ProcessRequests();
ApplyMovement();
TickMarkers();
TickMeshView();
UpdateGoLine();
FlushChat();
}
@ -1192,10 +1195,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
bool exists = File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile"));
int onDisk = 0;
try { if (Directory.Exists(NavDataDir)) onDisk = Directory.GetFiles(NavDataDir, "nav_*.tile").Length; } catch { }
bool indoors = (_cellId & 0xFFFF) >= 0x0100, dungeon = InDungeon(_cellId);
bool indoors = (_cellId & 0xFFFF) >= 0x0100;
bool dunFile = indoors && File.Exists(Path.Combine(NavDataDir, DungeonTileFile.FileName(lb)));
bool dungeon = InDungeon(_cellId) || dunFile;
string status; lock (_gate) status = _status;
return $"landblock 0x{lb:X4}{(dungeon ? " (a dungeon)" : indoors ? " (indoors)" : "")} — tile "
+ $"{(dungeon ? (exists ? "surface only, no dungeon navmesh" : "MISSING") : exists ? "FOUND" : "MISSING")}, {_tileCount} loaded, "
// Where exactly: the cell and the landblock-local position (what a dungeon's tile and its objects are placed in).
double lx = _wx - ((_cellId >> 24) & 0xFF) * 192.0, ly = _wy - ((_cellId >> 16) & 0xFF) * 192.0;
string at = $" cell {_cellId:X8} local ({lx:F1}, {ly:F1}, {_wz:F1}),";
return $"landblock 0x{lb:X4}{(dungeon ? " (a dungeon)" : indoors ? " (indoors)" : "")},{at} — tile "
+ $"{(dungeon ? (dunFile ? $"dungeon navmesh {DungeonTileFile.FileName(lb)} FOUND (the mesh view draws it; goto doesn't walk dungeons yet)" : "no dungeon navmesh baked") : exists ? "FOUND" : "MISSING")}, {_tileCount} loaded, "
+ $"{onDisk} tile(s) in {NavDataDir}; route graph: {_graphStatus}; Town Network: {_townNetStatus}; goto {(_gotoActive ? "ACTIVE" : "off")}"
+ $"{(_coarse != null ? $" (route {_coarse.Crossed}/{_coarse.Count})" : "")}, portals {(_portalsEnabled ? "on" : "off")}; status: {status}";
}