RynthSuite as of 2026-10-04 (internal c94715f): RynthOracle (based on Oracle of Dereth by Advis Eveldan) and RynthInventory, RynthAi patrol doorways and rooms, healing priority, strict monster priority, finish the wounded target, slayer weapons, arcs when clear, blasts like rings, learn unknown spells, looting fixes, release 2026.10.4.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c33e24a610
commit
12ca25f911
426 changed files with 108239 additions and 7521 deletions
290
Tools/RynthNav.TownNet/CellDat.cs
Normal file
290
Tools/RynthNav.TownNet/CellDat.cs
Normal file
|
|
@ -0,0 +1,290 @@
|
|||
using System.Numerics;
|
||||
using DatDb = RynthCore.Plugin.RynthAi.Raycasting.DatDatabase;
|
||||
|
||||
namespace RynthNav.TownNet;
|
||||
|
||||
// Reads indoor cells from the dats: each EnvCell's frame, its cell portals (which cell is on the
|
||||
// other side of which doorway polygon) and static objects, and the Environment's CellStruct for it
|
||||
// (render polygons with the doorway polygons, physics polygons with the floors).
|
||||
//
|
||||
// Formats as in ACE (EnvCell.Unpack, Environment/CellStruct.Unpack, Polygon.Unpack, BSP trees);
|
||||
// the polygon, vertex and BSP readers are ported from RynthAi's Raycasting/DungeonLOS.cs, which
|
||||
// reads the same structures for the dungeon map and missile LOS.
|
||||
|
||||
internal sealed class CellPortal
|
||||
{
|
||||
public ushort Flags; // 0x2 PortalSide
|
||||
public ushort PolygonId; // key into the CellStruct's render polygons
|
||||
public ushort OtherCell; // low 16 bits of the cell on the other side; 0xFFFF = outdoors
|
||||
public ushort OtherPortal;
|
||||
public Vector3[] Polygon = Array.Empty<Vector3>(); // the doorway, landblock-local
|
||||
}
|
||||
|
||||
internal sealed class Stab
|
||||
{
|
||||
public uint Id; // a GfxObj (0x01..) or Setup (0x02..)
|
||||
public Vector3 Origin; // landblock-local
|
||||
public Quaternion Rotation;
|
||||
}
|
||||
|
||||
internal sealed class EnvCell
|
||||
{
|
||||
public uint Id; // full cell id 0xLLLLCCCC
|
||||
public uint Flags;
|
||||
public uint EnvironmentId;
|
||||
public ushort CellStructure;
|
||||
public Vector3 Origin; // landblock-local
|
||||
public Quaternion Rotation;
|
||||
public List<CellPortal> Portals = new();
|
||||
public List<ushort> VisibleCells = new();
|
||||
public List<Stab> Stabs = new();
|
||||
public List<Vector3[]> Floors = new(); // physics polygons facing up, landblock-local
|
||||
public List<Vector3[]> Walls = new(); // every other physics polygon
|
||||
public bool GeometryOk;
|
||||
|
||||
public ushort Short => (ushort)(Id & 0xFFFF);
|
||||
}
|
||||
|
||||
internal static class CellDat
|
||||
{
|
||||
/// <summary>A walkable floor: ACE's PhysicsGlobals.FloorZ (cos 48.4 degrees).</summary>
|
||||
public const float FloorZ = 0.66417414f;
|
||||
|
||||
public static List<EnvCell> LoadLandblock(DatDb cellDat, DatDb portalDat, uint landblock)
|
||||
{
|
||||
var envCache = new Dictionary<uint, Dictionary<uint, RawCellStruct>>();
|
||||
var cells = new List<EnvCell>();
|
||||
foreach (uint id in cellDat.GetLandblockCellIds(landblock))
|
||||
{
|
||||
byte[]? data = cellDat.GetFileData(id);
|
||||
if (data == null) continue;
|
||||
EnvCell? c = ParseEnvCell(data);
|
||||
if (c == null) continue;
|
||||
c.Id = id;
|
||||
if (!envCache.TryGetValue(c.EnvironmentId, out var structs))
|
||||
{
|
||||
byte[]? env = portalDat.GetFileData(c.EnvironmentId);
|
||||
structs = env == null ? new() : ParseEnvironment(env);
|
||||
envCache[c.EnvironmentId] = structs;
|
||||
}
|
||||
if (structs.TryGetValue(c.CellStructure, out RawCellStruct? cs))
|
||||
Attach(c, cs);
|
||||
cells.Add(c);
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
|
||||
public static Vector3 ToLandblock(EnvCell c, Vector3 local) => Vector3.Transform(local, c.Rotation) + c.Origin;
|
||||
|
||||
private static void Attach(EnvCell c, RawCellStruct cs)
|
||||
{
|
||||
c.GeometryOk = cs.PhysicsOk;
|
||||
foreach (var poly in cs.Physics)
|
||||
{
|
||||
var w = poly.Select(v => ToLandblock(c, v)).ToArray();
|
||||
Vector3 n = Normal(w);
|
||||
if (n.Z >= FloorZ) c.Floors.Add(w); else c.Walls.Add(w);
|
||||
}
|
||||
foreach (var p in c.Portals)
|
||||
if (cs.Render.TryGetValue(p.PolygonId, out var poly))
|
||||
p.Polygon = poly.Select(v => ToLandblock(c, v)).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Unit normal by the vertex order (ACE Polygon.make_plane: sum of fan cross products).</summary>
|
||||
public static Vector3 Normal(IReadOnlyList<Vector3> v)
|
||||
{
|
||||
Vector3 n = Vector3.Zero;
|
||||
for (int i = 1; i < v.Count - 1; i++)
|
||||
n += Vector3.Cross(v[i] - v[0], v[i + 1] - v[0]);
|
||||
float len = n.Length();
|
||||
return len < 1e-6f ? Vector3.Zero : n / len;
|
||||
}
|
||||
|
||||
// ── EnvCell ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static EnvCell? ParseEnvCell(byte[] data)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var r = new BinaryReader(new MemoryStream(data));
|
||||
var c = new EnvCell();
|
||||
r.ReadUInt32(); // id
|
||||
c.Flags = r.ReadUInt32();
|
||||
r.ReadUInt32(); // id again
|
||||
byte numSurfaces = r.ReadByte();
|
||||
byte numPortals = r.ReadByte();
|
||||
ushort numVisible = r.ReadUInt16();
|
||||
for (int i = 0; i < numSurfaces; i++) r.ReadUInt16();
|
||||
c.EnvironmentId = 0x0D000000u | r.ReadUInt16();
|
||||
c.CellStructure = r.ReadUInt16();
|
||||
c.Origin = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
|
||||
float w = r.ReadSingle(), x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
|
||||
c.Rotation = new Quaternion(x, y, z, w);
|
||||
for (int i = 0; i < numPortals; i++)
|
||||
c.Portals.Add(new CellPortal { Flags = r.ReadUInt16(), PolygonId = r.ReadUInt16(), OtherCell = r.ReadUInt16(), OtherPortal = r.ReadUInt16() });
|
||||
for (int i = 0; i < numVisible; i++) c.VisibleCells.Add(r.ReadUInt16());
|
||||
if ((c.Flags & 0x2) != 0)
|
||||
{
|
||||
uint n = r.ReadUInt32();
|
||||
for (uint i = 0; i < n && i < 4096; i++)
|
||||
{
|
||||
// A stab's frame is landblock-local, like the cell's own (not relative to the cell).
|
||||
var s = new Stab { Id = r.ReadUInt32(), Origin = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()) };
|
||||
float sw = r.ReadSingle(), sx = r.ReadSingle(), sy = r.ReadSingle(), sz = r.ReadSingle();
|
||||
s.Rotation = new Quaternion(sx, sy, sz, sw);
|
||||
c.Stabs.Add(s);
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
catch (EndOfStreamException) { return null; }
|
||||
}
|
||||
|
||||
// ── Environment / CellStruct ─────────────────────────────────────────────
|
||||
|
||||
private sealed class RawCellStruct
|
||||
{
|
||||
public Dictionary<ushort, Vector3[]> Render = new();
|
||||
public List<Vector3[]> Physics = new();
|
||||
public bool PhysicsOk;
|
||||
}
|
||||
|
||||
private static Dictionary<uint, RawCellStruct> ParseEnvironment(byte[] data)
|
||||
{
|
||||
var result = new Dictionary<uint, RawCellStruct>();
|
||||
var ms = new MemoryStream(data);
|
||||
using var r = new BinaryReader(ms);
|
||||
r.ReadUInt32(); // id
|
||||
uint n = r.ReadUInt32();
|
||||
for (uint i = 0; i < n && i < 512; i++)
|
||||
{
|
||||
uint key = r.ReadUInt32();
|
||||
var cs = ParseCellStruct(r, ms, out bool toEnd);
|
||||
if (cs == null) break;
|
||||
result[key] = cs;
|
||||
if (!toEnd) break; // stream position unknown after this one
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static RawCellStruct? ParseCellStruct(BinaryReader r, MemoryStream ms, out bool toEnd)
|
||||
{
|
||||
toEnd = false;
|
||||
uint numPolys = r.ReadUInt32(), numPhys = r.ReadUInt32(), numPortals = r.ReadUInt32();
|
||||
if (numPolys > 5000 || numPhys > 5000) return null;
|
||||
var verts = ReadVertexArray(r, ms);
|
||||
if (verts == null) return null;
|
||||
var cs = new RawCellStruct();
|
||||
foreach (var (key, ids) in ReadPolygons(r, ms, numPolys))
|
||||
cs.Render[key] = Resolve(ids, verts);
|
||||
for (uint i = 0; i < numPortals; i++) r.ReadUInt16();
|
||||
Align(ms);
|
||||
if (!SkipBsp(r, ms, Bsp.Cell)) return cs;
|
||||
foreach (var (_, ids) in ReadPolygons(r, ms, numPhys))
|
||||
{
|
||||
var p = Resolve(ids, verts);
|
||||
if (p.Length >= 3) cs.Physics.Add(p);
|
||||
}
|
||||
cs.PhysicsOk = cs.Physics.Count > 0;
|
||||
if (!SkipBsp(r, ms, Bsp.Physics)) return cs;
|
||||
if (ms.Position + 4 <= ms.Length && r.ReadUInt32() != 0 && !SkipBsp(r, ms, Bsp.Drawing)) return cs;
|
||||
Align(ms);
|
||||
toEnd = true;
|
||||
return cs;
|
||||
}
|
||||
|
||||
internal static Vector3[] Resolve(List<ushort> ids, Dictionary<ushort, Vector3> verts)
|
||||
{
|
||||
var list = new List<Vector3>(ids.Count);
|
||||
foreach (var id in ids) if (verts.TryGetValue(id, out var v)) list.Add(v);
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
private static void Align(MemoryStream ms)
|
||||
{
|
||||
long a = (ms.Position + 3) & ~3L;
|
||||
if (a <= ms.Length) ms.Position = a;
|
||||
}
|
||||
|
||||
internal static Dictionary<ushort, Vector3>? ReadVertexArray(BinaryReader r, MemoryStream ms)
|
||||
{
|
||||
if (r.ReadInt32() != 1) return null;
|
||||
uint n = r.ReadUInt32();
|
||||
if (n > 50000) return null;
|
||||
var verts = new Dictionary<ushort, Vector3>();
|
||||
for (uint i = 0; i < n; i++)
|
||||
{
|
||||
ushort key = r.ReadUInt16();
|
||||
ushort numUv = r.ReadUInt16();
|
||||
var v = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
|
||||
ms.Seek(12 + numUv * 8L, SeekOrigin.Current); // normal + UVs
|
||||
verts[key] = v;
|
||||
}
|
||||
return verts;
|
||||
}
|
||||
|
||||
internal static List<(ushort, List<ushort>)> ReadPolygons(BinaryReader r, MemoryStream ms, uint count)
|
||||
{
|
||||
var polys = new List<(ushort, List<ushort>)>();
|
||||
for (uint i = 0; i < count; i++)
|
||||
{
|
||||
ushort key = r.ReadUInt16();
|
||||
byte numPts = r.ReadByte();
|
||||
byte stippling = r.ReadByte();
|
||||
int sides = r.ReadInt32();
|
||||
r.ReadInt16(); r.ReadInt16(); // surfaces
|
||||
if (numPts == 0 || numPts > 50) throw new InvalidDataException("bad polygon");
|
||||
var ids = new List<ushort>(numPts);
|
||||
for (int v = 0; v < numPts; v++) ids.Add((ushort)r.ReadInt16());
|
||||
if ((stippling & 0x04) == 0) ms.Seek(numPts, SeekOrigin.Current);
|
||||
if (sides == 2 && (stippling & 0x08) == 0) ms.Seek(numPts, SeekOrigin.Current);
|
||||
polys.Add((key, ids));
|
||||
}
|
||||
return polys;
|
||||
}
|
||||
|
||||
private enum Bsp { Cell, Physics, Drawing }
|
||||
|
||||
private const uint PORT = 0x504F5254, LEAF = 0x4C454146, BPnn = 0x42506E6E, BPIn = 0x4250496E, BpIN = 0x4270494E,
|
||||
BpnN = 0x42706E4E, BPIN = 0x4250494E, BPnN = 0x42506E4E, BPFL = 0x4250464C, BPOL = 0x42504F4C, BpIn = 0x4270496E;
|
||||
|
||||
private static bool SkipBsp(BinaryReader r, MemoryStream ms, Bsp t)
|
||||
{
|
||||
if (ms.Position + 4 > ms.Length) return false;
|
||||
uint tag = r.ReadUInt32();
|
||||
if (tag == LEAF || tag == PORT)
|
||||
{
|
||||
r.ReadInt32(); // leaf index
|
||||
if (t == Bsp.Physics)
|
||||
{
|
||||
r.ReadInt32(); // solid
|
||||
ms.Seek(16, SeekOrigin.Current); // sphere
|
||||
uint np = r.ReadUInt32();
|
||||
if (np > 100000) return false;
|
||||
ms.Seek(np * 2L, SeekOrigin.Current);
|
||||
}
|
||||
return ms.Position <= ms.Length;
|
||||
}
|
||||
ms.Seek(16, SeekOrigin.Current); // splitting plane
|
||||
switch (tag)
|
||||
{
|
||||
case BPnn: case BPIn: case BpIN: case BpnN:
|
||||
if (!SkipBsp(r, ms, t)) return false;
|
||||
break;
|
||||
case BPIN: case BPnN:
|
||||
if (!SkipBsp(r, ms, t) || !SkipBsp(r, ms, t)) return false;
|
||||
break;
|
||||
case BPFL: case BPOL: case BpIn:
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
if (t == Bsp.Cell) return true;
|
||||
ms.Seek(16, SeekOrigin.Current); // sphere
|
||||
if (t == Bsp.Physics) return true;
|
||||
uint n = r.ReadUInt32();
|
||||
if (n > 100000) return false;
|
||||
ms.Seek(n * 2L, SeekOrigin.Current);
|
||||
return ms.Position <= ms.Length;
|
||||
}
|
||||
}
|
||||
92
Tools/RynthNav.TownNet/Geometry.cs
Normal file
92
Tools/RynthNav.TownNet/Geometry.cs
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
using System.Numerics;
|
||||
|
||||
namespace RynthNav.TownNet;
|
||||
|
||||
/// <summary>Small geometry helpers: 2D tests on the floor plan, 3D segment-through-polygon.</summary>
|
||||
internal static class Geo
|
||||
{
|
||||
/// <summary>Is (x, y) inside the polygon's outline seen from above (edges count as inside within eps)?</summary>
|
||||
public static bool InsideXY(IReadOnlyList<Vector3> poly, float x, float y, float eps = 0.01f)
|
||||
{
|
||||
bool inside = false;
|
||||
int n = poly.Count;
|
||||
for (int i = 0, j = n - 1; i < n; j = i++)
|
||||
{
|
||||
Vector3 a = poly[i], b = poly[j];
|
||||
if ((a.Y > y) != (b.Y > y))
|
||||
{
|
||||
float xc = (b.X - a.X) * (y - a.Y) / (b.Y - a.Y) + a.X;
|
||||
if (x < xc) inside = !inside;
|
||||
}
|
||||
}
|
||||
if (inside || eps <= 0) return inside;
|
||||
return DistToOutlineXY(poly, x, y) <= eps;
|
||||
}
|
||||
|
||||
/// <summary>Distance from (x, y) to the polygon's outline seen from above (0 inside when filled).</summary>
|
||||
public static float DistXY(IReadOnlyList<Vector3> poly, float x, float y, bool filled)
|
||||
{
|
||||
if (filled && poly.Count >= 3 && AreaXY(poly) > 1e-4f && InsideXY(poly, x, y, 0)) return 0;
|
||||
return DistToOutlineXY(poly, x, y);
|
||||
}
|
||||
|
||||
public static float DistToOutlineXY(IReadOnlyList<Vector3> poly, float x, float y)
|
||||
{
|
||||
float best = float.MaxValue;
|
||||
int n = poly.Count;
|
||||
for (int i = 0, j = n - 1; i < n; j = i++)
|
||||
best = MathF.Min(best, DistToSegXY(poly[j].X, poly[j].Y, poly[i].X, poly[i].Y, x, y));
|
||||
return best;
|
||||
}
|
||||
|
||||
public static float DistToSegXY(float ax, float ay, float bx, float by, float px, float py)
|
||||
{
|
||||
float dx = bx - ax, dy = by - ay;
|
||||
float len2 = dx * dx + dy * dy;
|
||||
float t = len2 < 1e-12f ? 0 : Math.Clamp(((px - ax) * dx + (py - ay) * dy) / len2, 0, 1);
|
||||
float ex = ax + t * dx - px, ey = ay + t * dy - py;
|
||||
return MathF.Sqrt(ex * ex + ey * ey);
|
||||
}
|
||||
|
||||
public static float AreaXY(IReadOnlyList<Vector3> poly)
|
||||
{
|
||||
float a = 0;
|
||||
for (int i = 0, j = poly.Count - 1; i < poly.Count; j = i++)
|
||||
a += poly[j].X * poly[i].Y - poly[i].X * poly[j].Y;
|
||||
return MathF.Abs(a) * 0.5f;
|
||||
}
|
||||
|
||||
/// <summary>Height of a (non-vertical) planar polygon's plane at (x, y).</summary>
|
||||
public static float PlaneZ(IReadOnlyList<Vector3> poly, float x, float y)
|
||||
{
|
||||
Vector3 n = CellDat.Normal(poly);
|
||||
if (MathF.Abs(n.Z) < 1e-4f) return poly[0].Z;
|
||||
Vector3 p = poly[0];
|
||||
return p.Z - (n.X * (x - p.X) + n.Y * (y - p.Y)) / n.Z;
|
||||
}
|
||||
|
||||
/// <summary>Does the segment a-b pass through the planar polygon (edges included within eps)?</summary>
|
||||
public static bool SegmentCrosses(IReadOnlyList<Vector3> poly, Vector3 a, Vector3 b, float eps = 0.02f)
|
||||
{
|
||||
if (poly.Count < 3) return false;
|
||||
Vector3 n = CellDat.Normal(poly);
|
||||
if (n == Vector3.Zero) return false;
|
||||
float da = Vector3.Dot(n, a - poly[0]), db = Vector3.Dot(n, b - poly[0]);
|
||||
if ((da > 0 && db > 0) || (da < 0 && db < 0)) return false;
|
||||
float denom = da - db;
|
||||
if (MathF.Abs(denom) < 1e-7f) return false; // in the plane: not a crossing
|
||||
Vector3 p = a + (b - a) * (da / denom);
|
||||
// Inside test in the polygon's plane: project away its dominant axis.
|
||||
int drop = MathF.Abs(n.X) > MathF.Abs(n.Y) ? (MathF.Abs(n.X) > MathF.Abs(n.Z) ? 0 : 2) : (MathF.Abs(n.Y) > MathF.Abs(n.Z) ? 1 : 2);
|
||||
var flat = poly.Select(v => Flatten(v, drop)).ToArray();
|
||||
Vector3 fp = Flatten(p, drop);
|
||||
return InsideXY(flat, fp.X, fp.Y, eps);
|
||||
}
|
||||
|
||||
private static Vector3 Flatten(Vector3 v, int drop) => drop switch
|
||||
{
|
||||
0 => new Vector3(v.Y, v.Z, 0),
|
||||
1 => new Vector3(v.X, v.Z, 0),
|
||||
_ => new Vector3(v.X, v.Y, 0),
|
||||
};
|
||||
}
|
||||
194
Tools/RynthNav.TownNet/Indoor.cs
Normal file
194
Tools/RynthNav.TownNet/Indoor.cs
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
using System.Numerics;
|
||||
|
||||
namespace RynthNav.TownNet;
|
||||
|
||||
/// <summary>Something solid seen from above: a polygon outline (or a disc), between two heights.</summary>
|
||||
internal sealed class Footprint
|
||||
{
|
||||
public Vector3[] Poly = Array.Empty<Vector3>();
|
||||
public bool Filled; // the outline has area: inside counts as touching
|
||||
public Vector2 Center; public float Radius; // a disc when Poly is empty
|
||||
public float ZMin, ZMax;
|
||||
public string Source = "";
|
||||
public float MinX, MinY, MaxX, MaxY;
|
||||
|
||||
public float Dist(float x, float y) =>
|
||||
Poly.Length == 0 ? MathF.Max(0, Vector2.Distance(Center, new Vector2(x, y)) - Radius) : Geo.DistXY(Poly, x, y, Filled);
|
||||
|
||||
/// <summary>Does it stand in the way of someone whose feet are at z (step over below +0.45, head at +1.8)?</summary>
|
||||
public bool Blocks(float z) => ZMax > z + Indoor.StepUp && ZMin < z + Indoor.BodyHeight;
|
||||
|
||||
public void Bounds()
|
||||
{
|
||||
if (Poly.Length == 0) { MinX = Center.X - Radius; MaxX = Center.X + Radius; MinY = Center.Y - Radius; MaxY = Center.Y + Radius; return; }
|
||||
MinX = Poly.Min(v => v.X); MaxX = Poly.Max(v => v.X); MinY = Poly.Min(v => v.Y); MaxY = Poly.Max(v => v.Y);
|
||||
}
|
||||
|
||||
public static Footprint FromPolygon(Vector3[] p, string source)
|
||||
{
|
||||
var f = new Footprint { Poly = p, Filled = Geo.AreaXY(p) > 0.01f, ZMin = p.Min(v => v.Z), ZMax = p.Max(v => v.Z), Source = source };
|
||||
f.Bounds();
|
||||
return f;
|
||||
}
|
||||
|
||||
public static Footprint Disc(float x, float y, float r, float zmin, float zmax, string source)
|
||||
{
|
||||
var f = new Footprint { Center = new Vector2(x, y), Radius = r, ZMin = zmin, ZMax = zmax, Source = source };
|
||||
f.Bounds();
|
||||
return f;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A portal object inside the network: walking into it uses it, so the walks keep clear of all but their own.</summary>
|
||||
internal sealed class PortalZone
|
||||
{
|
||||
public string Guid = "";
|
||||
public string Name = "";
|
||||
public uint Cell;
|
||||
public Vector3 Pos;
|
||||
public float Radius; // its collision radius
|
||||
}
|
||||
|
||||
/// <summary>The indoor world the walks are planned in: cells, solid things, portal objects.</summary>
|
||||
internal sealed class Indoor
|
||||
{
|
||||
public const float StepUp = 0.45f;
|
||||
public const float BodyHeight = 1.8f;
|
||||
public const float StepZ = 0.45f; // largest height change between neighbouring floor samples
|
||||
|
||||
public readonly Dictionary<uint, EnvCell> Cells = new();
|
||||
public readonly List<Footprint> Solids = new();
|
||||
public readonly List<PortalZone> Portals = new();
|
||||
public float AgentRadius = 0.5f;
|
||||
public readonly List<string> Notes = new();
|
||||
|
||||
public EnvCell Cell(uint id) => Cells[id];
|
||||
|
||||
/// <summary>The floor height of a cell at (x, y), or null when (x, y) is not on its floor.</summary>
|
||||
public float? FloorZ(EnvCell c, float x, float y, float? near = null, float eps = 0.01f)
|
||||
{
|
||||
float? best = null;
|
||||
foreach (var f in c.Floors)
|
||||
{
|
||||
if (!Geo.InsideXY(f, x, y, eps)) continue;
|
||||
float z = Geo.PlaneZ(f, x, y);
|
||||
if (best == null || (near != null && MathF.Abs(z - near.Value) < MathF.Abs(best.Value - near.Value))) best = z;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>The portal polygons of cell a that open into cell b.</summary>
|
||||
public IEnumerable<Vector3[]> Doorways(EnvCell a, uint b)
|
||||
{
|
||||
ushort bs = (ushort)(b & 0xFFFF);
|
||||
foreach (var p in a.Portals)
|
||||
if (p.OtherCell == bs && p.Polygon.Length >= 3) yield return p.Polygon;
|
||||
}
|
||||
|
||||
public uint Full(EnvCell from, ushort other) => (from.Id & 0xFFFF0000u) | other;
|
||||
|
||||
/// <summary>
|
||||
/// Follows the straight segment a-b along the floor from cell <paramref name="start"/>, sampling every
|
||||
/// <paramref name="step"/>: every sample must be on the floor of the cell it is in, and the walk may only
|
||||
/// change cell where the segment passes through a doorway (cell portal) between the two. Returns the cells
|
||||
/// visited, or null with a reason when the segment leaves the floor or goes through a wall.
|
||||
/// </summary>
|
||||
public List<uint>? Trace(Vector3 a, Vector3 b, uint start, out string why, float step = 0.05f)
|
||||
{
|
||||
why = "";
|
||||
var cells = new List<uint> { start };
|
||||
EnvCell cur = Cells[start];
|
||||
float len = Vector2.Distance(new Vector2(a.X, a.Y), new Vector2(b.X, b.Y));
|
||||
int n = Math.Max(1, (int)MathF.Ceiling(len / step));
|
||||
Vector3 prev = a;
|
||||
float prevZ = FloorZ(cur, a.X, a.Y, a.Z, 0.02f) ?? float.NaN;
|
||||
if (float.IsNaN(prevZ)) { why = $"start ({a.X:F2},{a.Y:F2}) is not on the floor of {start:X8}"; return null; }
|
||||
for (int i = 1; i <= n; i++)
|
||||
{
|
||||
Vector3 p = Vector3.Lerp(a, b, i / (float)n);
|
||||
// A doorway crossed between the last sample and this one moves us into the next cell.
|
||||
EnvCell? next = null;
|
||||
float lift = 0.6f;
|
||||
var pa = new Vector3(prev.X, prev.Y, prevZ + lift);
|
||||
foreach (var cp in cur.Portals)
|
||||
{
|
||||
if (cp.OtherCell == 0xFFFF || cp.Polygon.Length < 3) continue;
|
||||
uint oid = Full(cur, cp.OtherCell);
|
||||
if (!Cells.TryGetValue(oid, out var other)) continue;
|
||||
float? oz = FloorZ(other, p.X, p.Y, prevZ, 0.02f);
|
||||
if (oz == null || MathF.Abs(oz.Value - prevZ) > StepZ) continue;
|
||||
if (Geo.SegmentCrosses(cp.Polygon, pa, new Vector3(p.X, p.Y, oz.Value + lift))) { next = other; break; }
|
||||
}
|
||||
if (next != null)
|
||||
{
|
||||
cur = next;
|
||||
cells.Add(cur.Id);
|
||||
prevZ = FloorZ(cur, p.X, p.Y, prevZ, 0.02f)!.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
float? z = FloorZ(cur, p.X, p.Y, prevZ, 0.02f);
|
||||
if (z == null) { why = $"({p.X:F2},{p.Y:F2}) is off the floor of {cur.Id:X8}"; return null; }
|
||||
if (MathF.Abs(z.Value - prevZ) > StepZ) { why = $"({p.X:F2},{p.Y:F2}) height jump {prevZ:F2} -> {z:F2} in {cur.Id:X8}"; return null; }
|
||||
prevZ = z.Value;
|
||||
}
|
||||
prev = p;
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
|
||||
/// <summary>The nearest solid thing (that blocks at the floor height z) to (x, y), within limit.</summary>
|
||||
public float SolidDist(float x, float y, float z, float limit, out Footprint? which)
|
||||
{
|
||||
which = null;
|
||||
float best = limit;
|
||||
if (_buckets == null) Index();
|
||||
int bx0 = (int)MathF.Floor((x - limit) / Bucket), bx1 = (int)MathF.Floor((x + limit) / Bucket);
|
||||
int by0 = (int)MathF.Floor((y - limit) / Bucket), by1 = (int)MathF.Floor((y + limit) / Bucket);
|
||||
var seen = new HashSet<Footprint>();
|
||||
for (int bx = bx0; bx <= bx1; bx++)
|
||||
for (int by = by0; by <= by1; by++)
|
||||
{
|
||||
if (!_buckets!.TryGetValue((bx, by), out var list)) continue;
|
||||
foreach (var f in list)
|
||||
{
|
||||
if (!seen.Add(f)) continue;
|
||||
if (x < f.MinX - best || x > f.MaxX + best || y < f.MinY - best || y > f.MaxY + best) continue;
|
||||
if (!f.Blocks(z)) continue;
|
||||
float d = f.Dist(x, y);
|
||||
if (d < best) { best = d; which = f; }
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private const float Bucket = 4f;
|
||||
private Dictionary<(int, int), List<Footprint>>? _buckets;
|
||||
|
||||
/// <summary>A coarse spatial index of the solids (call again after changing <see cref="Solids"/>).</summary>
|
||||
public void Index()
|
||||
{
|
||||
_buckets = new();
|
||||
foreach (var f in Solids)
|
||||
for (int bx = (int)MathF.Floor(f.MinX / Bucket); bx <= (int)MathF.Floor(f.MaxX / Bucket); bx++)
|
||||
for (int by = (int)MathF.Floor(f.MinY / Bucket); by <= (int)MathF.Floor(f.MaxY / Bucket); by++)
|
||||
{
|
||||
if (!_buckets.TryGetValue((bx, by), out var l)) _buckets[(bx, by)] = l = new List<Footprint>();
|
||||
l.Add(f);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Clearance from portal objects other than <paramref name="except"/>: distance minus the portal's radius.</summary>
|
||||
public float PortalDist(float x, float y, float z, string? except, out PortalZone? which)
|
||||
{
|
||||
which = null;
|
||||
float best = float.MaxValue;
|
||||
foreach (var p in Portals)
|
||||
{
|
||||
if (p.Guid == except || MathF.Abs(p.Pos.Z - z) > 2.5f) continue;
|
||||
float d = Vector2.Distance(new Vector2(p.Pos.X, p.Pos.Y), new Vector2(x, y)) - p.Radius;
|
||||
if (d < best) { best = d; which = p; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
55
Tools/RynthNav.TownNet/MapSvg.cs
Normal file
55
Tools/RynthNav.TownNet/MapSvg.cs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace RynthNav.TownNet;
|
||||
|
||||
/// <summary>
|
||||
/// A floor plan of the network as SVG, for looking the walks over: floors (grey, one shade per
|
||||
/// height), walls and solid objects (dark), portals (blue rings: the reach that uses them), arrival
|
||||
/// points (green), and the walks from one arrival (or all).
|
||||
/// </summary>
|
||||
internal static class MapSvg
|
||||
{
|
||||
public static string Draw(Indoor w, IEnumerable<uint> cells, JsonObject doc, string? onlyFrom, float level)
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
var cellList = cells.Select(id => w.Cells[id]).Where(c => c.Floors.Any(f => MathF.Abs(f[0].Z - level) < 3f)).ToList();
|
||||
var all = cellList.SelectMany(c => c.Floors).SelectMany(f => f).ToList();
|
||||
float minX = all.Min(v => v.X) - 3, maxX = all.Max(v => v.X) + 3, minY = all.Min(v => v.Y) - 3, maxY = all.Max(v => v.Y) + 3;
|
||||
const float S = 6f; // pixels per metre
|
||||
string P(float x, float y) => ((x - minX) * S).ToString("F1", ci) + "," + ((maxY - y) * S).ToString("F1", ci);
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(ci, $"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{(maxX - minX) * S:F0}\" height=\"{(maxY - minY) * S:F0}\" style=\"background:#fff\">\n");
|
||||
foreach (var c in cellList)
|
||||
foreach (var f in c.Floors.Where(f => MathF.Abs(f[0].Z - level) < 3f))
|
||||
sb.Append($"<polygon points=\"{string.Join(" ", f.Select(v => P(v.X, v.Y)))}\" fill=\"{(MathF.Abs(f[0].Z - level) < 0.5f ? "#ddd" : "#eee")}\" stroke=\"#ccc\" stroke-width=\"0.5\"/>\n");
|
||||
foreach (var s in w.Solids.Where(s => s.Blocks(level)))
|
||||
{
|
||||
if (s.Poly.Length == 0)
|
||||
sb.Append(ci, $"<circle cx=\"{(s.Center.X - minX) * S:F1}\" cy=\"{(maxY - s.Center.Y) * S:F1}\" r=\"{s.Radius * S:F1}\" fill=\"#a33\"/>\n");
|
||||
else
|
||||
sb.Append($"<polygon points=\"{string.Join(" ", s.Poly.Select(v => P(v.X, v.Y)))}\" fill=\"{(s.Filled ? "#a33" : "none")}\" stroke=\"{(s.Source.StartsWith("wall") ? "#222" : "#a33")}\" stroke-width=\"1.5\"/>\n");
|
||||
}
|
||||
foreach (var p in w.Portals)
|
||||
{
|
||||
sb.Append(ci, $"<circle cx=\"{(p.Pos.X - minX) * S:F1}\" cy=\"{(maxY - p.Pos.Y) * S:F1}\" r=\"{(p.Radius + w.AgentRadius) * S:F1}\" fill=\"none\" stroke=\"#36c\" stroke-width=\"1\"/>\n");
|
||||
sb.Append(ci, $"<text x=\"{(p.Pos.X - minX) * S:F1}\" y=\"{(maxY - p.Pos.Y) * S + 3:F1}\" font-size=\"8\" text-anchor=\"middle\" fill=\"#036\">{System.Security.SecurityElement.Escape(p.Name.Replace("Portal to ", "").Replace(" Portal", ""))}</text>\n");
|
||||
}
|
||||
foreach (var wk in doc["walks"]?.AsArray() ?? new JsonArray())
|
||||
{
|
||||
if (wk!["points"] is not JsonArray pts || (onlyFrom != null && (string?)wk["from"] != onlyFrom)) continue;
|
||||
var xy = pts.Select(p => P((float)(double)p![1]!, (float)(double)p[2]!));
|
||||
sb.Append($"<polyline points=\"{string.Join(" ", xy)}\" fill=\"none\" stroke=\"#2a2\" stroke-width=\"1.2\" opacity=\"0.7\"/>\n");
|
||||
}
|
||||
foreach (var a in doc["arrivals"]!.AsArray())
|
||||
{
|
||||
float x = (float)(double)a!["x"]!, y = (float)(double)a["y"]!;
|
||||
sb.Append(ci, $"<circle cx=\"{(x - minX) * S:F1}\" cy=\"{(maxY - y) * S:F1}\" r=\"5\" fill=\"#2a2\"/>\n");
|
||||
sb.Append(ci, $"<text x=\"{(x - minX) * S + 7:F1}\" y=\"{(maxY - y) * S - 6:F1}\" font-size=\"11\" fill=\"#060\">{(string)a["id"]!}</text>\n");
|
||||
}
|
||||
sb.Append("</svg>\n");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
136
Tools/RynthNav.TownNet/Models.cs
Normal file
136
Tools/RynthNav.TownNet/Models.cs
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
using System.Numerics;
|
||||
using DatDb = RynthCore.Plugin.RynthAi.Raycasting.DatDatabase;
|
||||
|
||||
namespace RynthNav.TownNet;
|
||||
|
||||
/// <summary>
|
||||
/// The solid shape of a model (a Setup 0x02.. or a GfxObj 0x01..) in its own frame: the physics
|
||||
/// polygons of its parts, its collision cylinders and spheres, and the Setup's own radius and height.
|
||||
/// Formats as in ACE (SetupModel.Unpack, GfxObj.Unpack); a model with no physics has no polygons.
|
||||
/// </summary>
|
||||
internal sealed class ModelShape
|
||||
{
|
||||
public List<Vector3[]> Polygons = new(); // model space
|
||||
public List<(Vector3 Origin, float Radius, float Height)> Cylinders = new();
|
||||
public List<(Vector3 Center, float Radius)> Spheres = new();
|
||||
public float Radius, Height;
|
||||
public bool Parsed;
|
||||
|
||||
public bool IsEmpty => Polygons.Count == 0 && Cylinders.Count == 0 && Spheres.Count == 0;
|
||||
}
|
||||
|
||||
internal sealed class ModelReader
|
||||
{
|
||||
private readonly DatDb _portal;
|
||||
private readonly Dictionary<uint, ModelShape> _cache = new();
|
||||
|
||||
public ModelReader(DatDb portalDat) { _portal = portalDat; }
|
||||
|
||||
public ModelShape Get(uint id)
|
||||
{
|
||||
if (_cache.TryGetValue(id, out var s)) return s;
|
||||
s = new ModelShape();
|
||||
try
|
||||
{
|
||||
if ((id >> 24) == 0x01) { s.Parsed = ReadGfxObj(id, s.Polygons, Matrix4x4.Identity); }
|
||||
else if ((id >> 24) == 0x02) { s.Parsed = ReadSetup(id, s); }
|
||||
}
|
||||
catch (Exception) { s.Parsed = false; }
|
||||
_cache[id] = s;
|
||||
return s;
|
||||
}
|
||||
|
||||
private bool ReadGfxObj(uint id, List<Vector3[]> into, Matrix4x4 m)
|
||||
{
|
||||
byte[]? data = _portal.GetFileData(id);
|
||||
if (data == null) return false;
|
||||
var ms = new MemoryStream(data);
|
||||
using var r = new BinaryReader(ms);
|
||||
r.ReadUInt32();
|
||||
uint flags = r.ReadUInt32();
|
||||
uint numSurfaces = ReadCompressed(r);
|
||||
ms.Seek(numSurfaces * 4L, SeekOrigin.Current);
|
||||
var verts = CellDat.ReadVertexArray(r, ms);
|
||||
if (verts == null) return false;
|
||||
if ((flags & 1) == 0) return true; // no physics: walk through it
|
||||
uint numPhys = ReadCompressed(r);
|
||||
foreach (var (_, ids) in CellDat.ReadPolygons(r, ms, numPhys))
|
||||
{
|
||||
var p = CellDat.Resolve(ids, verts);
|
||||
if (p.Length >= 3) into.Add(p.Select(v => Vector3.Transform(v, m)).ToArray());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool ReadSetup(uint id, ModelShape s)
|
||||
{
|
||||
byte[]? data = _portal.GetFileData(id);
|
||||
if (data == null) return false;
|
||||
var ms = new MemoryStream(data);
|
||||
using var r = new BinaryReader(ms);
|
||||
r.ReadUInt32();
|
||||
uint flags = r.ReadUInt32();
|
||||
uint numParts = r.ReadUInt32();
|
||||
if (numParts > 1000) return false;
|
||||
var parts = new uint[numParts];
|
||||
for (int i = 0; i < numParts; i++) parts[i] = r.ReadUInt32();
|
||||
if ((flags & 1) != 0) ms.Seek(numParts * 4L, SeekOrigin.Current); // parents
|
||||
var scale = Enumerable.Repeat(Vector3.One, (int)numParts).ToArray();
|
||||
if ((flags & 2) != 0)
|
||||
for (int i = 0; i < numParts; i++) scale[i] = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
|
||||
SkipLocations(r, ms); // holding locations
|
||||
SkipLocations(r, ms); // connection points
|
||||
int placements = r.ReadInt32();
|
||||
Matrix4x4[]? frames = null;
|
||||
bool hooksSeen = false;
|
||||
for (int p = 0; p < placements && !hooksSeen; p++)
|
||||
{
|
||||
int key = r.ReadInt32();
|
||||
var f = new Matrix4x4[numParts];
|
||||
for (int i = 0; i < numParts; i++) f[i] = ReadFrame(r);
|
||||
if (frames == null || key == 0) frames = f;
|
||||
if (r.ReadUInt32() != 0) hooksSeen = true; // variable-size hooks: stop here
|
||||
}
|
||||
for (int i = 0; i < numParts; i++)
|
||||
{
|
||||
Matrix4x4 m = Matrix4x4.CreateScale(scale[i]) * (frames != null ? frames[i] : Matrix4x4.Identity);
|
||||
if ((parts[i] >> 24) == 0x01) ReadGfxObj(parts[i], s.Polygons, m);
|
||||
}
|
||||
if (hooksSeen) return true;
|
||||
uint numCyl = r.ReadUInt32();
|
||||
for (uint i = 0; i < numCyl && i < 64; i++)
|
||||
s.Cylinders.Add((new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()), r.ReadSingle(), r.ReadSingle()));
|
||||
uint numSph = r.ReadUInt32();
|
||||
for (uint i = 0; i < numSph && i < 64; i++)
|
||||
s.Spheres.Add((new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()), r.ReadSingle()));
|
||||
s.Height = r.ReadSingle();
|
||||
s.Radius = r.ReadSingle();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Matrix4x4 ReadFrame(BinaryReader r)
|
||||
{
|
||||
var o = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
|
||||
float w = r.ReadSingle(), x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
|
||||
var q = new Quaternion(x, y, z, w);
|
||||
if (q.LengthSquared() < 1e-6f) q = Quaternion.Identity;
|
||||
return Matrix4x4.CreateFromQuaternion(Quaternion.Normalize(q)) * Matrix4x4.CreateTranslation(o);
|
||||
}
|
||||
|
||||
private static void SkipLocations(BinaryReader r, MemoryStream ms)
|
||||
{
|
||||
int n = r.ReadInt32();
|
||||
if (n < 0 || n > 1000) throw new InvalidDataException("bad location table");
|
||||
ms.Seek(n * 36L, SeekOrigin.Current); // key, part id, frame
|
||||
}
|
||||
|
||||
private static uint ReadCompressed(BinaryReader r)
|
||||
{
|
||||
byte b0 = r.ReadByte();
|
||||
if ((b0 & 0x80) == 0) return b0;
|
||||
byte b1 = r.ReadByte();
|
||||
if ((b0 & 0x40) == 0) return (uint)(((b0 & 0x7F) << 8) | b1);
|
||||
ushort s = r.ReadUInt16();
|
||||
return (uint)((((b0 & 0x3F) << 8 | b1) << 16) | s);
|
||||
}
|
||||
}
|
||||
218
Tools/RynthNav.TownNet/NavGrid.cs
Normal file
218
Tools/RynthNav.TownNet/NavGrid.cs
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
using System.Numerics;
|
||||
|
||||
namespace RynthNav.TownNet;
|
||||
|
||||
/// <summary>
|
||||
/// A walk grid over the indoor floors: one node per (cell, 0.25 m square) whose centre is on that
|
||||
/// cell's floor. Neighbouring nodes in the same cell connect; nodes in two cells connect only where
|
||||
/// the step between them passes through a doorway (cell portal) of the two. Every node knows its
|
||||
/// clearance: the distance to the nearest wall, solid object or floor edge.
|
||||
/// </summary>
|
||||
internal sealed class NavGrid
|
||||
{
|
||||
public const float Cell = 0.25f;
|
||||
private const float ClearMax = 3.0f;
|
||||
|
||||
public sealed class Node
|
||||
{
|
||||
public int Index;
|
||||
public uint CellId;
|
||||
public int Ix, Iy;
|
||||
public float X, Y, Z;
|
||||
public float Clear = ClearMax; // min(wall / object / floor edge)
|
||||
public float PortalClear = float.MaxValue;
|
||||
public string? NearPortal;
|
||||
public int[] Nbr = Array.Empty<int>();
|
||||
}
|
||||
|
||||
public readonly List<Node> Nodes = new();
|
||||
private readonly Dictionary<long, List<int>> _at = new();
|
||||
private readonly Indoor _w;
|
||||
|
||||
private static long Key(int ix, int iy) => ((long)ix << 32) | (uint)iy;
|
||||
public static int Idx(float v) => (int)MathF.Floor(v / Cell);
|
||||
|
||||
public NavGrid(Indoor world, IEnumerable<uint> cells)
|
||||
{
|
||||
_w = world;
|
||||
foreach (uint id in cells) AddCell(world.Cells[id]);
|
||||
Link();
|
||||
Clearance();
|
||||
}
|
||||
|
||||
private void AddCell(EnvCell c)
|
||||
{
|
||||
var mine = new Dictionary<long, Node>();
|
||||
foreach (var f in c.Floors)
|
||||
{
|
||||
int x0 = Idx(f.Min(v => v.X)), x1 = Idx(f.Max(v => v.X)), y0 = Idx(f.Min(v => v.Y)), y1 = Idx(f.Max(v => v.Y));
|
||||
for (int ix = x0; ix <= x1; ix++)
|
||||
for (int iy = y0; iy <= y1; iy++)
|
||||
{
|
||||
float x = (ix + 0.5f) * Cell, y = (iy + 0.5f) * Cell;
|
||||
if (!Geo.InsideXY(f, x, y, 0)) continue;
|
||||
long k = Key(ix, iy);
|
||||
if (mine.ContainsKey(k)) continue;
|
||||
var n = new Node { Index = Nodes.Count, CellId = c.Id, Ix = ix, Iy = iy, X = x, Y = y, Z = Geo.PlaneZ(f, x, y) };
|
||||
mine[k] = n;
|
||||
Nodes.Add(n);
|
||||
if (!_at.TryGetValue(k, out var list)) _at[k] = list = new List<int>();
|
||||
list.Add(n.Index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly (int dx, int dy)[] Dirs = { (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1) };
|
||||
|
||||
private void Link()
|
||||
{
|
||||
var edgeNodes = new List<int>();
|
||||
foreach (var n in Nodes)
|
||||
{
|
||||
var nbr = new List<int>(8);
|
||||
int dirsCovered = 0;
|
||||
var cell = _w.Cells[n.CellId];
|
||||
foreach (var (dx, dy) in Dirs)
|
||||
{
|
||||
if (!_at.TryGetValue(Key(n.Ix + dx, n.Iy + dy), out var list)) continue;
|
||||
bool any = false;
|
||||
foreach (int mi in list)
|
||||
{
|
||||
var m = Nodes[mi];
|
||||
if (MathF.Abs(m.Z - n.Z) > Indoor.StepZ) continue;
|
||||
if (m.CellId != n.CellId)
|
||||
{
|
||||
bool through = false;
|
||||
foreach (var door in _w.Doorways(cell, m.CellId))
|
||||
if (Geo.SegmentCrosses(door, new Vector3(n.X, n.Y, n.Z + 0.6f), new Vector3(m.X, m.Y, m.Z + 0.6f))) { through = true; break; }
|
||||
if (!through) continue;
|
||||
}
|
||||
nbr.Add(mi);
|
||||
any = true;
|
||||
}
|
||||
if (any) dirsCovered++;
|
||||
}
|
||||
n.Nbr = nbr.ToArray();
|
||||
if (dirsCovered < 8) n.Clear = Cell * 0.5f; // a floor edge (wall, drop or pit) next to it
|
||||
}
|
||||
}
|
||||
|
||||
private void Clearance()
|
||||
{
|
||||
// Solid things: exact distance for the nodes near each one.
|
||||
foreach (var f in _w.Solids)
|
||||
{
|
||||
int x0 = Idx(f.MinX - ClearMax), x1 = Idx(f.MaxX + ClearMax), y0 = Idx(f.MinY - ClearMax), y1 = Idx(f.MaxY + ClearMax);
|
||||
for (int ix = x0; ix <= x1; ix++)
|
||||
for (int iy = y0; iy <= y1; iy++)
|
||||
{
|
||||
if (!_at.TryGetValue(Key(ix, iy), out var list)) continue;
|
||||
foreach (int i in list)
|
||||
{
|
||||
var n = Nodes[i];
|
||||
if (!f.Blocks(n.Z)) continue;
|
||||
float d = f.Dist(n.X, n.Y);
|
||||
if (d < n.Clear) n.Clear = d;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Floor edges: spread the distance over the grid (Dijkstra from every node's own value).
|
||||
var pq = new PriorityQueue<int, float>();
|
||||
var dist = Nodes.Select(n => n.Clear).ToArray();
|
||||
for (int i = 0; i < Nodes.Count; i++) if (dist[i] < ClearMax) pq.Enqueue(i, dist[i]);
|
||||
while (pq.TryDequeue(out int i, out float d))
|
||||
{
|
||||
if (d > dist[i]) continue;
|
||||
var n = Nodes[i];
|
||||
foreach (int j in n.Nbr)
|
||||
{
|
||||
var m = Nodes[j];
|
||||
float nd = d + Vector2.Distance(new Vector2(n.X, n.Y), new Vector2(m.X, m.Y));
|
||||
if (nd < dist[j]) { dist[j] = nd; pq.Enqueue(j, nd); }
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < Nodes.Count; i++) Nodes[i].Clear = MathF.Min(Nodes[i].Clear, dist[i]);
|
||||
// Portal objects (kept apart: a walk ignores its own exit portal).
|
||||
foreach (var n in Nodes)
|
||||
{
|
||||
n.PortalClear = _w.PortalDist(n.X, n.Y, n.Z, null, out var p);
|
||||
n.NearPortal = p?.Guid;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The node of cell <paramref name="cell"/> nearest to (x, y) that passes <paramref name="ok"/>.</summary>
|
||||
public Node? Nearest(uint cell, float x, float y, Func<Node, bool> ok, float within = 3f)
|
||||
{
|
||||
Node? best = null; float bd = within;
|
||||
int r = (int)MathF.Ceiling(within / Cell);
|
||||
int cx = Idx(x), cy = Idx(y);
|
||||
for (int ix = cx - r; ix <= cx + r; ix++)
|
||||
for (int iy = cy - r; iy <= cy + r; iy++)
|
||||
{
|
||||
if (!_at.TryGetValue(Key(ix, iy), out var list)) continue;
|
||||
foreach (int i in list)
|
||||
{
|
||||
var n = Nodes[i];
|
||||
if (n.CellId != cell && cell != 0) continue;
|
||||
float d = Vector2.Distance(new Vector2(n.X, n.Y), new Vector2(x, y));
|
||||
if (d < bd && ok(n)) { bd = d; best = n; }
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public IEnumerable<Node> Around(float x, float y, float within)
|
||||
{
|
||||
int r = (int)MathF.Ceiling(within / Cell);
|
||||
int cx = Idx(x), cy = Idx(y);
|
||||
for (int ix = cx - r; ix <= cx + r; ix++)
|
||||
for (int iy = cy - r; iy <= cy + r; iy++)
|
||||
if (_at.TryGetValue(Key(ix, iy), out var list))
|
||||
foreach (int i in list) yield return Nodes[i];
|
||||
}
|
||||
|
||||
/// <summary>Shortest walking distances from one node over the nodes that pass <paramref name="ok"/>,
|
||||
/// with a mild extra cost near walls (so walks keep to the middle of corridors).</summary>
|
||||
public (float[] cost, int[] prev) Dijkstra(Node start, Func<Node, bool> ok)
|
||||
{
|
||||
var cost = new float[Nodes.Count];
|
||||
var prev = new int[Nodes.Count];
|
||||
Array.Fill(cost, float.MaxValue);
|
||||
Array.Fill(prev, -1);
|
||||
var pq = new PriorityQueue<int, float>();
|
||||
cost[start.Index] = 0;
|
||||
pq.Enqueue(start.Index, 0);
|
||||
while (pq.TryDequeue(out int i, out float c))
|
||||
{
|
||||
if (c > cost[i]) continue;
|
||||
var n = Nodes[i];
|
||||
foreach (int j in n.Nbr)
|
||||
{
|
||||
var m = Nodes[j];
|
||||
if (!ok(m)) continue;
|
||||
float step = Vector3.Distance(new Vector3(n.X, n.Y, n.Z), new Vector3(m.X, m.Y, m.Z));
|
||||
float near = MathF.Max(0, 1.5f - MathF.Min(m.Clear, m.PortalClear));
|
||||
float nc = c + step * (1 + near);
|
||||
if (nc < cost[j]) { cost[j] = nc; prev[j] = i; pq.Enqueue(j, nc); }
|
||||
}
|
||||
}
|
||||
return (cost, prev);
|
||||
}
|
||||
|
||||
public List<Node> PathTo(int goal, int[] prev)
|
||||
{
|
||||
var path = new List<Node>();
|
||||
for (int i = goal; i >= 0; i = prev[i]) path.Add(Nodes[i]);
|
||||
path.Reverse();
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>The clearance of the grid node under p (at about its height), 0 where there is none.</summary>
|
||||
public float ClearAt(Vector3 p)
|
||||
{
|
||||
Node? m = null;
|
||||
if (_at.TryGetValue(Key(Idx(p.X), Idx(p.Y)), out var list))
|
||||
foreach (int k in list) if (m == null || MathF.Abs(Nodes[k].Z - p.Z) < MathF.Abs(m.Z - p.Z)) m = Nodes[k];
|
||||
return m == null || MathF.Abs(m.Z - p.Z) > 1.0f ? 0 : m.Clear;
|
||||
}
|
||||
}
|
||||
211
Tools/RynthNav.TownNet/Program.cs
Normal file
211
Tools/RynthNav.TownNet/Program.cs
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using System.Text.Json.Nodes;
|
||||
using RynthNav.TownNet;
|
||||
using DatDb = RynthCore.Plugin.RynthAi.Raycasting.DatDatabase;
|
||||
|
||||
// RynthNav.TownNet: the walks inside the Town Network, for townnet.json.
|
||||
//
|
||||
// build --in <townnet.json> [--out <file>] [--ac <dats>]
|
||||
// plans a walk from every arrival point to every exit portal, checks each one, and writes
|
||||
// them into the file (default: back into --in) as "walks", with "walkInfo".
|
||||
// check --in <townnet.json> [--ac <dats>]
|
||||
// checks the walks already in the file against the dats; exit 1 when any fails or is missing.
|
||||
// dump [--lb 0x0007] [--ac <dats>] [--stabs 1]
|
||||
// lists a landblock's cells: floors, walls, doorways, static objects.
|
||||
// map --in <townnet.json> --out <file.svg> [--from A1] [--z 0]
|
||||
// a floor plan with the walls, objects, portals and walks, to look them over.
|
||||
// test geometry self-tests on a made-up two-room floor (no dats); exit 0 = pass.
|
||||
//
|
||||
// --ac defaults to C:\Games\ACE\Dats (client_cell_1.dat + client_portal.dat, opened read only).
|
||||
// The portal list in townnet.json comes from RynthCore's tools/navdata/gen_townnet.py.
|
||||
|
||||
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
|
||||
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
|
||||
|
||||
string? Arg(string name)
|
||||
{
|
||||
for (int i = 0; i < args.Length - 1; i++)
|
||||
if (string.Equals(args[i], name, StringComparison.OrdinalIgnoreCase)) return args[i + 1];
|
||||
return null;
|
||||
}
|
||||
|
||||
string cmd = args.Length > 0 ? args[0].ToLowerInvariant() : "";
|
||||
string acDir = Arg("--ac") ?? @"C:\Games\ACE\Dats";
|
||||
|
||||
if (cmd == "test") return SelfTest.Run();
|
||||
|
||||
if (cmd is not ("build" or "check" or "dump" or "map"))
|
||||
{
|
||||
Console.Error.WriteLine("usage: RynthNav.TownNet build|check|map|dump|test (see Program.cs)");
|
||||
return 2;
|
||||
}
|
||||
|
||||
using var cellDat = new DatDb();
|
||||
using var portalDat = new DatDb();
|
||||
string cellPath = Path.Combine(acDir, "client_cell_1.dat"), portalPath = Path.Combine(acDir, "client_portal.dat");
|
||||
if (!cellDat.Open(cellPath) || !portalDat.Open(portalPath))
|
||||
{
|
||||
Console.Error.WriteLine("cannot open the dats in " + acDir);
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (cmd == "dump" && Arg("--model") is string model)
|
||||
{
|
||||
uint mid = Convert.ToUInt32(model.Replace("0x", ""), 16);
|
||||
var shape = new ModelReader(portalDat).Get(mid);
|
||||
Console.WriteLine($"model {mid:X8}: parsed {shape.Parsed}, radius {shape.Radius:F2}, height {shape.Height:F2}, {shape.Polygons.Count} physics polygons");
|
||||
foreach (var c in shape.Cylinders) Console.WriteLine($" cylinder at ({c.Origin.X:F2},{c.Origin.Y:F2},{c.Origin.Z:F2}) r {c.Radius:F2} h {c.Height:F2}");
|
||||
foreach (var s in shape.Spheres) Console.WriteLine($" sphere at ({s.Center.X:F2},{s.Center.Y:F2},{s.Center.Z:F2}) r {s.Radius:F2}");
|
||||
if (shape.Polygons.Count > 0)
|
||||
Console.WriteLine($" polygons span x {shape.Polygons.Min(p => p.Min(v => v.X)):F2}..{shape.Polygons.Max(p => p.Max(v => v.X)):F2}, " +
|
||||
$"y {shape.Polygons.Min(p => p.Min(v => v.Y)):F2}..{shape.Polygons.Max(p => p.Max(v => v.Y)):F2}, z {shape.Polygons.Min(p => p.Min(v => v.Z)):F2}..{shape.Polygons.Max(p => p.Max(v => v.Z)):F2}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (cmd == "dump")
|
||||
{
|
||||
uint lb = Convert.ToUInt32((Arg("--lb") ?? "0x0007").Replace("0x", ""), 16);
|
||||
var cells = CellDat.LoadLandblock(cellDat, portalDat, lb);
|
||||
Console.WriteLine($"landblock {lb:X4}: {cells.Count} cells");
|
||||
foreach (var c in cells)
|
||||
{
|
||||
string fz = c.Floors.Count == 0 ? "-" : $"{c.Floors.Min(f => f.Min(v => v.Z)):F2}..{c.Floors.Max(f => f.Max(v => v.Z)):F2}";
|
||||
Console.WriteLine($"{c.Id:X8} env {c.EnvironmentId:X8}/{c.CellStructure} at ({c.Origin.X:F1},{c.Origin.Y:F1},{c.Origin.Z:F2}) " +
|
||||
$"floors {c.Floors.Count} z {fz} walls {c.Walls.Count} stabs {c.Stabs.Count} doorways " +
|
||||
string.Join(" ", c.Portals.Select(p => $"{p.OtherCell:X4}")));
|
||||
if (Arg("--stabs") != null)
|
||||
foreach (var s in c.Stabs) Console.WriteLine($" object {s.Id:X8} at ({s.Origin.X:F1},{s.Origin.Y:F1},{s.Origin.Z:F2})");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
string inPath = Arg("--in") ?? throw new ArgumentException("--in <townnet.json> is required");
|
||||
var doc = TownNetFile.Load(inPath);
|
||||
var sw = Stopwatch.StartNew();
|
||||
var world = WorldLoader.Load(doc, cellDat, portalDat, out var reachable);
|
||||
var grid = new NavGrid(world, reachable);
|
||||
var planner = new WalkPlanner(world, grid);
|
||||
Console.WriteLine($"{reachable.Count} cells, {grid.Nodes.Count:N0} floor samples, {world.Solids.Count:N0} solid shapes, " +
|
||||
$"{world.Portals.Count} exit portals; walker radius {world.AgentRadius:F2} m ({sw.Elapsed.TotalSeconds:F1} s)");
|
||||
foreach (var n in world.Notes) Console.WriteLine(" " + n);
|
||||
var radii = world.Portals.GroupBy(p => MathF.Round(p.Radius, 2)).Select(g => $"{g.Key:F2} m x{g.Count()}");
|
||||
Console.WriteLine(" portal radii: " + string.Join(", ", radii));
|
||||
|
||||
var arrivals = doc["arrivals"]!.AsArray().Select(a => (
|
||||
Id: (string)a!["id"]!, Cell: WorldLoader.Hex(a["cell"]), P: new Vector3(WorldLoader.F(a["x"]), WorldLoader.F(a["y"]), WorldLoader.F(a["z"])))).ToList();
|
||||
|
||||
if (cmd == "map")
|
||||
{
|
||||
string svgPath = Arg("--out") ?? throw new ArgumentException("--out <file.svg> is required");
|
||||
float level = Arg("--z") is string zs ? float.Parse(zs, CultureInfo.InvariantCulture) : 0f;
|
||||
File.WriteAllText(svgPath, MapSvg.Draw(world, reachable, doc, Arg("--from"), level));
|
||||
Console.WriteLine("wrote " + svgPath);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (cmd == "build")
|
||||
{
|
||||
var walks = new List<Walk>();
|
||||
foreach (var a in arrivals)
|
||||
{
|
||||
var ws = planner.PlanFrom(a.Id, a.Cell, a.P, world.Portals);
|
||||
walks.AddRange(ws);
|
||||
var ok = ws.Where(w => w.Error == null).ToList();
|
||||
Console.WriteLine($"{a.Id} {a.Cell:X8} ({a.P.X:F1},{a.P.Y:F1}): {ok.Count}/{ws.Count} exits, " +
|
||||
(ok.Count > 0 ? $"length {ok.Min(w => w.Length):F1}..{ok.Max(w => w.Length):F1} m, avg {ok.Average(w => w.Length):F1} m, " +
|
||||
$"{ok.Average(w => w.Points.Count):F1} waypoints avg, min clearance {ok.Min(w => w.MinClear):F2} m" : ""));
|
||||
foreach (var w in ws.Where(w => w.Error != null)) Console.WriteLine($" {w.ExitName}: {w.Error}");
|
||||
if (Arg("--verbose") != null)
|
||||
foreach (var w in ok) Console.WriteLine($" {w.ExitName}: {w.Length:F1} m, {w.Points.Count} points, clear {w.MinClear:F2} ({w.MinClearAt}), portals {w.MinPortalClear:F2}");
|
||||
}
|
||||
var jw = new JsonArray();
|
||||
foreach (var w in walks) jw.Add(ToJson(w));
|
||||
var good = walks.Where(w => w.Error == null).ToList();
|
||||
var info = new JsonObject
|
||||
{
|
||||
["tool"] = "RynthNav.TownNet build",
|
||||
["dats"] = new JsonArray(DatInfo(cellPath), DatInfo(portalPath)),
|
||||
["grid"] = NavGrid.Cell,
|
||||
["walkerRadius"] = R2(world.AgentRadius),
|
||||
["clearance"] = R2(planner.MustClear),
|
||||
["portalClearance"] = R2(planner.MustPortal),
|
||||
["cells"] = reachable.Count,
|
||||
["walks"] = walks.Count,
|
||||
["walkable"] = good.Count,
|
||||
["lengthMin"] = good.Count > 0 ? R2(good.Min(w => w.Length)) : null,
|
||||
["lengthMax"] = good.Count > 0 ? R2(good.Max(w => w.Length)) : null,
|
||||
["lengthAvg"] = good.Count > 0 ? R2(good.Average(w => w.Length)) : null,
|
||||
};
|
||||
doc["walkInfo"] = info;
|
||||
doc["walks"] = jw;
|
||||
string outPath = Arg("--out") ?? inPath;
|
||||
// The live NavData folder and the bake folders are never written by accident.
|
||||
string outFull = Path.GetFullPath(outPath);
|
||||
if (outFull.StartsWith(@"C:\Games\RynthCore\Nav", StringComparison.OrdinalIgnoreCase) && !args.Contains("--force-live"))
|
||||
{
|
||||
Console.Error.WriteLine($"refusing to write {outFull}: that is RynthCore's live NavData (or a bake). Pass --force-live to mean it.");
|
||||
return 2;
|
||||
}
|
||||
TownNetFile.Save(outPath, doc);
|
||||
Console.WriteLine($"{good.Count}/{walks.Count} walks; wrote {outPath} (set {(string)doc["setId"]!}) in {sw.Elapsed.TotalSeconds:F1} s");
|
||||
return good.Count == walks.Count ? 0 : 1;
|
||||
}
|
||||
|
||||
// check
|
||||
{
|
||||
int bad = 0, n = 0;
|
||||
string stored = (string?)doc["setId"] ?? "", actual = TownNetFile.SetId(File.ReadAllText(inPath));
|
||||
if (stored != actual) { Console.WriteLine($"set id {stored} does not match the file's content ({actual})"); bad++; }
|
||||
var have = new HashSet<(string, string)>();
|
||||
foreach (var j in doc["walks"]?.AsArray() ?? new JsonArray())
|
||||
{
|
||||
string from = (string)j!["from"]!, to = (string)j["to"]!;
|
||||
have.Add((from, to));
|
||||
if (j["error"] != null) { Console.WriteLine($"{from} -> {(string?)j["exit"]}: no walk ({(string?)j["error"]})"); bad++; continue; }
|
||||
var target = world.Portals.FirstOrDefault(p => p.Guid == to);
|
||||
if (target == null) { Console.WriteLine($"{from} -> {to}: no such exit portal"); bad++; continue; }
|
||||
var w = new Walk { From = from, To = to, ExitName = target.Name };
|
||||
foreach (var p in j["points"]!.AsArray())
|
||||
{
|
||||
var a = p!.AsArray();
|
||||
w.Points.Add(new Waypoint(WorldLoader.Hex(a[0]), new Vector3(WorldLoader.F(a[1]), WorldLoader.F(a[2]), WorldLoader.F(a[3]))));
|
||||
}
|
||||
var arr = arrivals.FirstOrDefault(x => x.Id == from);
|
||||
if (arr.Id == null) { Console.WriteLine($"{from} -> {to}: no such arrival"); bad++; continue; }
|
||||
if (w.Points.Count < 2 || Vector2.Distance(new Vector2(w.Points[0].P.X, w.Points[0].P.Y), new Vector2(arr.P.X, arr.P.Y)) > 0.05f
|
||||
|| Vector2.Distance(new Vector2(w.Points[^1].P.X, w.Points[^1].P.Y), new Vector2(target.Pos.X, target.Pos.Y)) > target.Radius)
|
||||
{ Console.WriteLine($"{from} -> {target.Name}: does not start at the arrival or end in the portal"); bad++; continue; }
|
||||
planner.Check(w, target);
|
||||
n++;
|
||||
if (w.Error != null) { Console.WriteLine($"{from} -> {target.Name}: {w.Error}"); bad++; }
|
||||
}
|
||||
foreach (var a in arrivals)
|
||||
foreach (var p in world.Portals)
|
||||
if (!have.Contains((a.Id, p.Guid))) { Console.WriteLine($"{a.Id} -> {p.Name}: missing"); bad++; }
|
||||
Console.WriteLine($"checked {n} walks against the dats: {(bad == 0 ? "all pass" : bad + " problem(s)")}");
|
||||
return bad == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
static JsonNode R2(float v) => JsonValue.Create(Math.Round(v, 2))!;
|
||||
|
||||
static JsonObject ToJson(Walk w)
|
||||
{
|
||||
var o = new JsonObject { ["from"] = w.From, ["to"] = w.To, ["exit"] = w.ExitName };
|
||||
if (w.Error != null) { o["error"] = w.Error; return o; }
|
||||
o["length"] = R2(w.Length);
|
||||
o["minClear"] = R2(w.MinClear);
|
||||
o["cells"] = w.Cells;
|
||||
var pts = new JsonArray();
|
||||
foreach (var p in w.Points)
|
||||
pts.Add(new JsonArray($"{p.Cell:X8}", Math.Round(p.P.X, 2), Math.Round(p.P.Y, 2), Math.Round(p.P.Z, 2)));
|
||||
o["points"] = pts;
|
||||
return o;
|
||||
}
|
||||
|
||||
static JsonNode DatInfo(string path)
|
||||
{
|
||||
var fi = new FileInfo(path);
|
||||
return $"{fi.Name} {fi.Length} bytes {fi.LastWriteTimeUtc:yyyy-MM-dd}";
|
||||
}
|
||||
25
Tools/RynthNav.TownNet/RynthNav.TownNet.csproj
Normal file
25
Tools/RynthNav.TownNet/RynthNav.TownNet.csproj
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
RynthNav.TownNet: the walking paths inside the Town Network (landblock 0x0007), built offline
|
||||
from the retail dats (client_cell_1.dat + client_portal.dat, read only), for townnet.json.
|
||||
The portal list in townnet.json comes from RynthCore's tools/navdata/gen_townnet.py (the
|
||||
world database); this tool adds the indoor walks from every arrival point to every exit
|
||||
portal, and checks them.
|
||||
Commands (build, check, dump, test): see Program.cs.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>RynthNav.TownNet</RootNamespace>
|
||||
<AssemblyName>RynthNav.TownNet</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- DatDatabase: the read-only dat container reader RynthAi and the baker use -->
|
||||
<ProjectReference Include="..\..\Shared\RynthCore.TerrainData\RynthCore.TerrainData.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
125
Tools/RynthNav.TownNet/SelfTest.cs
Normal file
125
Tools/RynthNav.TownNet/SelfTest.cs
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
using System.Numerics;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace RynthNav.TownNet;
|
||||
|
||||
/// <summary>
|
||||
/// Geometry self-tests on a made-up floor, no dats: two 10 x 10 m rooms side by side, joined by a
|
||||
/// 2 m doorway in the wall between them, a pillar in the second room, and an exit portal in its far
|
||||
/// corner with another portal near the doorway. Exit code 0 = all pass.
|
||||
/// </summary>
|
||||
internal static class SelfTest
|
||||
{
|
||||
private const uint A = 0x00010100, B = 0x00010101;
|
||||
private static int _fail;
|
||||
|
||||
public static int Run()
|
||||
{
|
||||
var w = MakeWorld();
|
||||
var grid = new NavGrid(w, new[] { A, B });
|
||||
var planner = new WalkPlanner(w, grid);
|
||||
|
||||
// The cell trace: through the doorway is fine, through the wall is not, off the floor is not.
|
||||
Expect(w.Trace(new Vector3(5, 5, 0), new Vector3(15, 5, 0), A, out _)?.SequenceEqual(new[] { A, B }) == true, "through the doorway: A then B");
|
||||
Expect(w.Trace(new Vector3(5, 1, 0), new Vector3(15, 1, 0), A, out var why) == null, "through the wall is refused (" + why + ")");
|
||||
Expect(w.Trace(new Vector3(5, 5, 0), new Vector3(5, 12, 0), A, out why) == null, "off the floor is refused (" + why + ")");
|
||||
|
||||
// Clearance: the pillar and the walls show up in the grid.
|
||||
var nearPillar = grid.Nearest(B, 15f, 2.6f, _ => true)!;
|
||||
Expect(nearPillar.Clear < 0.2f, $"next to the pillar the clearance is small ({nearPillar.Clear:F2})");
|
||||
var middle = grid.Nearest(A, 5f, 5f, _ => true)!;
|
||||
Expect(middle.Clear > 2.9f, $"mid-room clearance is large (capped at 3 m) ({middle.Clear:F2})");
|
||||
|
||||
// A walk from the first room to the exit portal in the second: it exists, passes the check,
|
||||
// goes through the doorway, keeps clear of the pillar and of the other portal.
|
||||
var exit = w.Portals[0];
|
||||
var walks = planner.PlanFrom("A1", A, new Vector3(2, 8.5f, 0.005f), w.Portals);
|
||||
var walk = walks.First(x => x.To == exit.Guid);
|
||||
Expect(walk.Error == null, "a walk to the exit portal exists (" + walk.Error + ")");
|
||||
if (walk.Error == null)
|
||||
{
|
||||
Expect(walk.Points.Count >= 3, $"it turns at least once ({walk.Points.Count} points)");
|
||||
Expect(walk.Cells == 2, $"it crosses into the second room ({walk.Cells} cells)");
|
||||
bool door = false;
|
||||
for (int i = 1; i < walk.Points.Count; i++)
|
||||
{
|
||||
var a = walk.Points[i - 1].P; var b = walk.Points[i].P;
|
||||
if ((a.X - 10) * (b.X - 10) <= 0 && b.X != a.X)
|
||||
{
|
||||
float y = a.Y + (b.Y - a.Y) * (10 - a.X) / (b.X - a.X);
|
||||
door = y > 4f && y < 6f;
|
||||
}
|
||||
}
|
||||
Expect(door, "it crosses the wall line inside the doorway");
|
||||
Expect(walk.MinClear >= w.AgentRadius, $"it keeps the walker's radius from walls and the pillar ({walk.MinClear:F2})");
|
||||
Expect(walk.MinPortalClear >= planner.MustPortal, $"it keeps clear of the other portal ({walk.MinPortalClear:F2})");
|
||||
Expect(Vector2.Distance(new Vector2(walk.Points[^1].P.X, walk.Points[^1].P.Y), new Vector2(exit.Pos.X, exit.Pos.Y)) < 0.01f, "it ends in the portal");
|
||||
|
||||
// The check catches a shortcut through the wall.
|
||||
var cut = new Walk { From = "A1", To = exit.Guid, Points = { new Waypoint(A, new Vector3(2, 2, 0)), new Waypoint(B, new Vector3(18, 2, 0)), walk.Points[^1] } };
|
||||
planner.Check(cut, exit);
|
||||
Expect(cut.Error != null, "the check refuses a walk through the wall (" + cut.Error + ")");
|
||||
}
|
||||
|
||||
// A portal behind a wall with no way round is reported, not faked.
|
||||
var shut = MakeWorld(doorway: false);
|
||||
var shutPlanner = new WalkPlanner(shut, new NavGrid(shut, new[] { A, B }));
|
||||
var none = shutPlanner.PlanFrom("A1", A, new Vector3(2, 2, 0), shut.Portals);
|
||||
Expect(none.All(x => x.Error != null), "with the doorway walled up there is no walk (" + none[0].Error + ")");
|
||||
|
||||
// The file: the set id ignores the timestamp and changes with the data.
|
||||
var doc = new JsonObject { ["version"] = 1, ["setId"] = "", ["generated"] = "2026-01-01T00:00:00Z", ["arrivals"] = new JsonArray(new JsonObject { ["id"] = "A1" }) };
|
||||
string id1 = TownNetFile.SetId(TownNetFile.Serialize(doc));
|
||||
doc["generated"] = "2027-01-01T00:00:00Z";
|
||||
string id2 = TownNetFile.SetId(TownNetFile.Serialize(doc));
|
||||
doc["arrivals"]!.AsArray().Add(new JsonObject { ["id"] = "A2" });
|
||||
string id3 = TownNetFile.SetId(TownNetFile.Serialize(doc));
|
||||
Expect(id1 == id2 && id1 != id3 && id1.Length == 16, "set id: same data same id, new data new id");
|
||||
Expect(TownNetFile.SetId(TownNetFile.Serialize(doc).Replace("\n", "\r\n")) == id3, "set id: a CRLF checkout gives the same id");
|
||||
Expect(TownNetFile.Serialize(doc).Contains(" {\"id\":\"A2\"}\n"), "lists hold one item per line");
|
||||
|
||||
Console.WriteLine(_fail == 0 ? "all self-tests pass" : $"{_fail} self-test(s) FAILED");
|
||||
return _fail == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Expect(bool ok, string what)
|
||||
{
|
||||
Console.WriteLine((ok ? " ok " : " FAIL ") + what);
|
||||
if (!ok) _fail++;
|
||||
}
|
||||
|
||||
private static Vector3[] Quad(float x0, float y0, float x1, float y1, float z) =>
|
||||
new[] { new Vector3(x0, y0, z), new Vector3(x1, y0, z), new Vector3(x1, y1, z), new Vector3(x0, y1, z) };
|
||||
|
||||
/// <summary>A vertical wall from (x0, y0) to (x1, y1), 4 m high.</summary>
|
||||
private static Vector3[] Wall(float x0, float y0, float x1, float y1) =>
|
||||
new[] { new Vector3(x0, y0, 0), new Vector3(x1, y1, 0), new Vector3(x1, y1, 4), new Vector3(x0, y0, 4) };
|
||||
|
||||
private static Indoor MakeWorld(bool doorway = true)
|
||||
{
|
||||
var w = new Indoor { AgentRadius = 0.5f };
|
||||
var a = new EnvCell { Id = A, Floors = { Quad(0, 0, 10, 10, 0) } };
|
||||
var b = new EnvCell { Id = B, Floors = { Quad(10, 0, 20, 10, 0) } };
|
||||
foreach (var c in new[] { a, b })
|
||||
{
|
||||
float x0 = c == a ? 0 : 10, x1 = x0 + 10;
|
||||
c.Walls.Add(Wall(x0, 0, x1, 0)); c.Walls.Add(Wall(x0, 10, x1, 10));
|
||||
c.Walls.Add(Wall(c == a ? 0 : 20, 0, c == a ? 0 : 20, 10));
|
||||
c.Walls.Add(Wall(10, 0, 10, 4)); c.Walls.Add(Wall(10, 6, 10, 10));
|
||||
if (!doorway) c.Walls.Add(Wall(10, 4, 10, 6));
|
||||
}
|
||||
if (doorway)
|
||||
{
|
||||
var door = Wall(10, 4, 10, 6);
|
||||
a.Portals.Add(new CellPortal { OtherCell = (ushort)(B & 0xFFFF), Polygon = door });
|
||||
b.Portals.Add(new CellPortal { OtherCell = (ushort)(A & 0xFFFF), Polygon = door });
|
||||
}
|
||||
w.Cells[A] = a; w.Cells[B] = b;
|
||||
foreach (var c in new[] { a, b })
|
||||
foreach (var wall in c.Walls) w.Solids.Add(Footprint.FromPolygon(wall, $"wall {c.Id:X8}"));
|
||||
w.Solids.Add(Footprint.Disc(15, 3, 0.5f, 0, 3, "pillar"));
|
||||
w.Portals.Add(new PortalZone { Guid = "EXIT", Name = "Exit", Cell = B, Pos = new Vector3(18, 8, 0), Radius = 1f });
|
||||
w.Portals.Add(new PortalZone { Guid = "OTHER", Name = "Other", Cell = B, Pos = new Vector3(13, 8.5f, 0), Radius = 1f });
|
||||
return w;
|
||||
}
|
||||
}
|
||||
83
Tools/RynthNav.TownNet/TownNetFile.cs
Normal file
83
Tools/RynthNav.TownNet/TownNetFile.cs
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace RynthNav.TownNet;
|
||||
|
||||
/// <summary>
|
||||
/// townnet.json, as gen_townnet.py writes it: an object whose lists hold one item per line. This
|
||||
/// tool keeps everything it does not own and replaces "walks" and "walkInfo". The set id is the
|
||||
/// first 16 hex digits of the SHA-256 of the file's text without its "setId" and "generated" lines
|
||||
/// (carriage returns dropped, so a CRLF checkout gives the same id; gen_townnet.py computes it
|
||||
/// the same way), so equal ids mean equal data.
|
||||
/// </summary>
|
||||
internal static class TownNetFile
|
||||
{
|
||||
private static readonly string[] HeadKeys = { "version", "setId", "generated", "source", "landblocks", "counts", "notes", "walkInfo" };
|
||||
private static readonly string[] ListKeys = { "arrivals", "entries", "exits", "npcs", "walks" };
|
||||
|
||||
private static readonly JsonSerializerOptions Compact = new()
|
||||
{
|
||||
WriteIndented = false,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
};
|
||||
|
||||
public static JsonObject Load(string path) =>
|
||||
JsonNode.Parse(File.ReadAllText(path), documentOptions: new JsonDocumentOptions { AllowTrailingCommas = true })!.AsObject();
|
||||
|
||||
public static string Serialize(JsonObject doc)
|
||||
{
|
||||
var keys = HeadKeys.Where(doc.ContainsKey).Concat(ListKeys.Where(doc.ContainsKey))
|
||||
.Concat(doc.Select(kv => kv.Key).Where(k => !HeadKeys.Contains(k) && !ListKeys.Contains(k))).ToList();
|
||||
var sb = new StringBuilder("{\n");
|
||||
for (int i = 0; i < keys.Count; i++)
|
||||
{
|
||||
string k = keys[i];
|
||||
bool last = i == keys.Count - 1;
|
||||
JsonNode? v = doc[k];
|
||||
if (ListKeys.Contains(k) && v is JsonArray arr)
|
||||
{
|
||||
sb.Append(" ").Append(JsonSerializer.Serialize(k)).Append(": [\n");
|
||||
for (int j = 0; j < arr.Count; j++)
|
||||
sb.Append(" ").Append(arr[j]!.ToJsonString(Compact)).Append(j < arr.Count - 1 ? ",\n" : "\n");
|
||||
sb.Append(" ]").Append(last ? "\n" : ",\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.Append(" ").Append(JsonSerializer.Serialize(k)).Append(": ").Append(SpacedJson(v)).Append(last ? "\n" : ",\n");
|
||||
}
|
||||
}
|
||||
sb.Append("}\n");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Head values the way Python's json.dumps writes them (", " and ": " separators).</summary>
|
||||
private static string SpacedJson(JsonNode? v)
|
||||
{
|
||||
if (v == null) return "null";
|
||||
if (v is JsonArray a) return "[" + string.Join(", ", a.Select(SpacedJson)) + "]";
|
||||
if (v is JsonObject o) return "{" + string.Join(", ", o.Select(kv => JsonSerializer.Serialize(kv.Key) + ": " + SpacedJson(kv.Value))) + "}";
|
||||
return v.ToJsonString(Compact);
|
||||
}
|
||||
|
||||
public static string SetId(string text)
|
||||
{
|
||||
var kept = text.Replace("\r", "").Split('\n').Where(l => !l.StartsWith(" \"setId\":") && !l.StartsWith(" \"generated\":"));
|
||||
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(string.Join("\n", kept)));
|
||||
return Convert.ToHexString(hash, 0, 8).ToLowerInvariant();
|
||||
}
|
||||
|
||||
public static void Save(string path, JsonObject doc)
|
||||
{
|
||||
if (!doc.ContainsKey("setId")) doc["setId"] = "";
|
||||
string text = Serialize(doc);
|
||||
string id = SetId(text);
|
||||
doc["setId"] = id;
|
||||
text = Serialize(doc);
|
||||
string tmp = path + ".tmp";
|
||||
File.WriteAllText(tmp, text, new UTF8Encoding(false));
|
||||
File.Move(tmp, path, overwrite: true);
|
||||
}
|
||||
}
|
||||
208
Tools/RynthNav.TownNet/Walks.cs
Normal file
208
Tools/RynthNav.TownNet/Walks.cs
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
using System.Numerics;
|
||||
|
||||
namespace RynthNav.TownNet;
|
||||
|
||||
internal sealed record Waypoint(uint Cell, Vector3 P);
|
||||
|
||||
internal sealed class Walk
|
||||
{
|
||||
public string From = "", To = "", ExitName = "";
|
||||
public List<Waypoint> Points = new();
|
||||
public float Length;
|
||||
public float MinClear; // nearest wall / object / floor edge along the walk (centre of the walker)
|
||||
public float MinPortalClear; // nearest other portal's edge along the walk
|
||||
public string MinClearAt = ""; // where MinClear is (for the build log)
|
||||
public int Cells;
|
||||
public string? Error;
|
||||
}
|
||||
|
||||
/// <summary>Plans and checks the walks from an arrival point to an exit portal.</summary>
|
||||
internal sealed class WalkPlanner
|
||||
{
|
||||
private readonly Indoor _w;
|
||||
private readonly NavGrid _g;
|
||||
public readonly float PassClear, PassPortal, SmoothClear, MustClear, MustPortal;
|
||||
|
||||
/// <summary>The grid's floor-edge distances are good to about one grid square; walls and objects are
|
||||
/// checked exactly, so this slack only matters at drops with no wall.</summary>
|
||||
public const float EdgeSlack = NavGrid.Cell;
|
||||
|
||||
public WalkPlanner(Indoor w, NavGrid g)
|
||||
{
|
||||
_w = w; _g = g;
|
||||
float r = w.AgentRadius;
|
||||
PassClear = r + 0.25f; // grid search: keep this far from walls and objects
|
||||
PassPortal = r + 0.5f; // ... and from other portals (touching one uses it)
|
||||
SmoothClear = r + 0.15f; // straightened segments
|
||||
MustClear = r; // the check: the walker's body never touches a wall or object
|
||||
MustPortal = r + 0.25f; // ... and stays a step away from every other portal
|
||||
}
|
||||
|
||||
private bool Passable(NavGrid.Node n) => n.Clear >= PassClear && n.PortalClear >= PassPortal;
|
||||
|
||||
public List<Walk> PlanFrom(string arrivalId, uint cell, Vector3 at, IReadOnlyList<PortalZone> exits)
|
||||
{
|
||||
var walks = new List<Walk>();
|
||||
float? fz = _w.Cells.TryGetValue(cell, out var c) ? _w.FloorZ(c, at.X, at.Y, at.Z, 0.05f) : null;
|
||||
if (fz == null)
|
||||
{
|
||||
foreach (var e in exits) walks.Add(new Walk { From = arrivalId, To = e.Guid, ExitName = e.Name, Error = "the arrival point is not on a floor" });
|
||||
return walks;
|
||||
}
|
||||
var start = new Vector3(at.X, at.Y, fz.Value);
|
||||
// The first grid node: the nearest passable one that a straight step from the arrival reaches.
|
||||
var first = _g.Nearest(cell, at.X, at.Y, n => Passable(n) && SegmentOk(start, cell, Pos(n), null, SmoothClear, out _), 4f);
|
||||
if (first == null)
|
||||
{
|
||||
foreach (var e in exits) walks.Add(new Walk { From = arrivalId, To = e.Guid, ExitName = e.Name, Error = "no clear floor within 4 m of the arrival point" });
|
||||
return walks;
|
||||
}
|
||||
var (cost, prev) = _g.Dijkstra(first, Passable);
|
||||
foreach (var e in exits) walks.Add(PlanTo(arrivalId, cell, start, cost, prev, e));
|
||||
return walks;
|
||||
}
|
||||
|
||||
private static Vector3 Pos(NavGrid.Node n) => new(n.X, n.Y, n.Z);
|
||||
|
||||
private Walk PlanTo(string arrivalId, uint startCell, Vector3 start, float[] cost, int[] prev, PortalZone exit)
|
||||
{
|
||||
var walk = new Walk { From = arrivalId, To = exit.Guid, ExitName = exit.Name };
|
||||
// Where the walk ends: the portal's centre on the floor (walking into it uses it).
|
||||
var ec = _w.Cells[exit.Cell];
|
||||
float? ez = _w.FloorZ(ec, exit.Pos.X, exit.Pos.Y, exit.Pos.Z, 0.05f);
|
||||
Vector3 end;
|
||||
uint endCell = exit.Cell;
|
||||
if (ez != null) end = new Vector3(exit.Pos.X, exit.Pos.Y, ez.Value);
|
||||
else
|
||||
{
|
||||
// Off the floor (in a niche): end at the nearest floor inside the portal's reach.
|
||||
var n = _g.Nearest(exit.Cell, exit.Pos.X, exit.Pos.Y, _ => true, exit.Radius);
|
||||
if (n == null) { walk.Error = "the portal does not stand on a floor"; return walk; }
|
||||
end = Pos(n);
|
||||
}
|
||||
// The last grid node: reached from the arrival, with a clear straight step into the portal. A roomy
|
||||
// approach first (so the walker comes in square, not grazing the alcove's corner), then a tight one.
|
||||
NavGrid.Node? goal = null;
|
||||
foreach (float need in new[] { SmoothClear, MustClear })
|
||||
{
|
||||
float best = float.MaxValue;
|
||||
foreach (var n in _g.Around(end.X, end.Y, 5f))
|
||||
{
|
||||
if (cost[n.Index] == float.MaxValue) continue;
|
||||
float d = Vector2.Distance(new Vector2(n.X, n.Y), new Vector2(end.X, end.Y));
|
||||
if (cost[n.Index] + d >= best) continue;
|
||||
if (!SegmentOk(Pos(n), n.CellId, end, exit, need, out _)) continue;
|
||||
best = cost[n.Index] + d; goal = n;
|
||||
}
|
||||
if (goal != null) break;
|
||||
}
|
||||
if (goal == null) { walk.Error = "no clear way to the portal from the walkable floor"; return walk; }
|
||||
|
||||
var raw = new List<Waypoint> { new(startCell, start) };
|
||||
raw.AddRange(_g.PathTo(goal.Index, prev).Select(n => new Waypoint(n.CellId, Pos(n))));
|
||||
raw.Add(new Waypoint(endCell, end));
|
||||
walk.Points = Straighten(raw, exit).Select(Rounded).ToList();
|
||||
Check(walk, exit);
|
||||
return walk;
|
||||
}
|
||||
|
||||
/// <summary>A waypoint as the file stores it (centimetres), its height put back on its cell's floor.</summary>
|
||||
private Waypoint Rounded(Waypoint w)
|
||||
{
|
||||
float x = MathF.Round(w.P.X, 2), y = MathF.Round(w.P.Y, 2);
|
||||
float z = _w.FloorZ(_w.Cells[w.Cell], x, y, w.P.Z, 0.02f) ?? w.P.Z;
|
||||
return new Waypoint(w.Cell, new Vector3(x, y, MathF.Round(z, 2)));
|
||||
}
|
||||
|
||||
/// <summary>Greedy string pulling: from each kept point, the furthest later point a clear straight segment reaches.</summary>
|
||||
private List<Waypoint> Straighten(List<Waypoint> raw, PortalZone exit)
|
||||
{
|
||||
var kept = new List<Waypoint> { raw[0] };
|
||||
int i = 0;
|
||||
while (i < raw.Count - 1)
|
||||
{
|
||||
int j = i + 1;
|
||||
// Search from the far end down in coarse steps, then refine: long clear segments are the common case.
|
||||
int lo = i + 1, hi = raw.Count - 1;
|
||||
for (int k = hi; k > lo; k = Math.Max(lo, k - Math.Max(1, (k - lo) / 2)))
|
||||
{
|
||||
if (SegmentOk(raw[i].P, raw[i].Cell, raw[k].P, exit, SmoothClear, out _)) { j = k; break; }
|
||||
if (k == lo + 1) break;
|
||||
}
|
||||
// Walk forward from there while it still holds.
|
||||
while (j + 1 < raw.Count && SegmentOk(raw[i].P, raw[i].Cell, raw[j + 1].P, exit, SmoothClear, out _)) j++;
|
||||
kept.Add(raw[j]);
|
||||
i = j;
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
/// <summary>A straight segment the walker can follow: on the floor, through doorways only, clear of walls,
|
||||
/// objects, floor edges and of every portal but its own (inside its own portal's reach the walker has
|
||||
/// already touched it, so nothing there counts).</summary>
|
||||
public bool SegmentOk(Vector3 a, uint cell, Vector3 b, PortalZone? target, float clear, out string why)
|
||||
{
|
||||
if (_w.Trace(a, b, cell, out why) == null) return false;
|
||||
float len = Vector2.Distance(new Vector2(a.X, a.Y), new Vector2(b.X, b.Y));
|
||||
int n = Math.Max(1, (int)MathF.Ceiling(len / 0.1f));
|
||||
for (int i = 0; i <= n; i++)
|
||||
{
|
||||
Vector3 p = Vector3.Lerp(a, b, i / (float)n);
|
||||
if (InReach(p, target)) continue;
|
||||
float d = _w.SolidDist(p.X, p.Y, p.Z, clear + 0.01f, out var f);
|
||||
if (d < clear) { why = $"({p.X:F2},{p.Y:F2}) {d:F2} m from {f!.Source}"; return false; }
|
||||
float pd = _w.PortalDist(p.X, p.Y, p.Z, target?.Guid, out var pz);
|
||||
if (pd < MustPortal) { why = $"({p.X:F2},{p.Y:F2}) {pd:F2} m from portal {pz!.Name}"; return false; }
|
||||
if (_g.ClearAt(p) < clear - EdgeSlack) { why = $"({p.X:F2},{p.Y:F2}) near a floor edge"; return false; }
|
||||
}
|
||||
why = "";
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Within the target portal's reach: the walker's body already touches it.</summary>
|
||||
private bool InReach(Vector3 p, PortalZone? target) =>
|
||||
target != null && Vector2.Distance(new Vector2(p.X, p.Y), new Vector2(target.Pos.X, target.Pos.Y)) < target.Radius + _w.AgentRadius;
|
||||
|
||||
/// <summary>The offline check of a finished walk: every waypoint on a floor, every segment on the floor and
|
||||
/// through doorways only, the walker never touching a wall, object or another portal.</summary>
|
||||
public void Check(Walk walk, PortalZone target)
|
||||
{
|
||||
walk.Length = 0; walk.MinClear = float.MaxValue; walk.MinPortalClear = float.MaxValue; walk.Error = null;
|
||||
var cells = new HashSet<uint>();
|
||||
for (int i = 0; i < walk.Points.Count; i++)
|
||||
{
|
||||
var wp = walk.Points[i];
|
||||
if (_w.FloorZ(_w.Cells[wp.Cell], wp.P.X, wp.P.Y, wp.P.Z, 0.02f) is not float z || MathF.Abs(z - wp.P.Z) > 0.05f)
|
||||
{ walk.Error = $"waypoint {i} ({wp.P.X:F2},{wp.P.Y:F2}) is not on the floor of {wp.Cell:X8}"; return; }
|
||||
cells.Add(wp.Cell);
|
||||
if (i == 0) continue;
|
||||
var a = walk.Points[i - 1];
|
||||
var trace = _w.Trace(a.P, wp.P, a.Cell, out string why, 0.05f);
|
||||
if (trace == null) { walk.Error = $"segment {i}: {why}"; return; }
|
||||
if (trace[^1] != wp.Cell) { walk.Error = $"segment {i} ends in {trace[^1]:X8}, its waypoint says {wp.Cell:X8}"; return; }
|
||||
foreach (var c in trace) cells.Add(c);
|
||||
float len = Vector2.Distance(new Vector2(a.P.X, a.P.Y), new Vector2(wp.P.X, wp.P.Y));
|
||||
int n = Math.Max(1, (int)MathF.Ceiling(len / 0.05f));
|
||||
for (int k = 0; k <= n; k++)
|
||||
{
|
||||
Vector3 p = Vector3.Lerp(a.P, wp.P, k / (float)n);
|
||||
float pd = _w.PortalDist(p.X, p.Y, p.Z, target.Guid, out var pz);
|
||||
walk.MinPortalClear = MathF.Min(walk.MinPortalClear, pd);
|
||||
if (pd < MustPortal) { walk.Error = $"segment {i} passes {pd:F2} m from portal {pz!.Name}"; return; }
|
||||
if (InReach(p, target)) continue;
|
||||
float d = _w.SolidDist(p.X, p.Y, p.Z, 3f, out var f);
|
||||
if (d < walk.MinClear)
|
||||
{
|
||||
walk.MinClear = d;
|
||||
float toPortal = Vector2.Distance(new Vector2(p.X, p.Y), new Vector2(target.Pos.X, target.Pos.Y));
|
||||
walk.MinClearAt = $"segment {i}/{walk.Points.Count - 1} at ({p.X:F2},{p.Y:F2}), {toPortal:F1} m from the exit, by {f?.Source}";
|
||||
}
|
||||
if (d < MustClear) { walk.Error = $"segment {i} passes {d:F2} m from {f!.Source}"; return; }
|
||||
float edge = _g.ClearAt(p);
|
||||
if (edge < MustClear - EdgeSlack) { walk.Error = $"segment {i} passes {edge:F2} m from a floor edge"; return; }
|
||||
}
|
||||
walk.Length += Vector3.Distance(a.P, wp.P);
|
||||
}
|
||||
walk.Cells = cells.Count;
|
||||
}
|
||||
}
|
||||
120
Tools/RynthNav.TownNet/WorldLoader.cs
Normal file
120
Tools/RynthNav.TownNet/WorldLoader.cs
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using System.Text.Json.Nodes;
|
||||
using DatDb = RynthCore.Plugin.RynthAi.Raycasting.DatDatabase;
|
||||
|
||||
namespace RynthNav.TownNet;
|
||||
|
||||
/// <summary>Builds the <see cref="Indoor"/> world for townnet.json from the dats and the file's portal list.</summary>
|
||||
internal static class WorldLoader
|
||||
{
|
||||
public const uint HumanSetup = 0x02000001; // the player's model: its radius is the walker's
|
||||
|
||||
public static uint Hex(JsonNode? n) => uint.Parse((string)n!, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
|
||||
public static float F(JsonNode? n) => (float)(double)n!;
|
||||
|
||||
public static Indoor Load(JsonObject doc, DatDb cellDat, DatDb portalDat, out List<uint> reachable)
|
||||
{
|
||||
var w = new Indoor();
|
||||
var models = new ModelReader(portalDat);
|
||||
// The walker's body: the player model's collision spheres (not its larger selection radius).
|
||||
var human = models.Get(HumanSetup);
|
||||
float body = human.Spheres.Select(sp => sp.Radius).Concat(human.Cylinders.Select(c => c.Radius)).DefaultIfEmpty(0).Max();
|
||||
if (body > 0.1f) w.AgentRadius = body;
|
||||
else w.Notes.Add($"setup {HumanSetup:X8} has no collision spheres; walker radius {w.AgentRadius} m assumed");
|
||||
|
||||
foreach (var lbNode in doc["landblocks"]!.AsArray())
|
||||
{
|
||||
uint lb = Hex(lbNode);
|
||||
foreach (var c in CellDat.LoadLandblock(cellDat, portalDat, lb)) w.Cells[c.Id] = c;
|
||||
}
|
||||
|
||||
// The cells someone arriving can reach through cell portals.
|
||||
var arrivalCells = doc["arrivals"]!.AsArray().Select(a => Hex(a!["cell"])).ToList();
|
||||
var seen = new HashSet<uint>();
|
||||
var queue = new Queue<uint>();
|
||||
foreach (uint c in arrivalCells)
|
||||
{
|
||||
if (!w.Cells.ContainsKey(c)) { w.Notes.Add($"arrival cell {c:X8} is not in the dats"); continue; }
|
||||
if (seen.Add(c)) queue.Enqueue(c);
|
||||
}
|
||||
while (queue.Count > 0)
|
||||
{
|
||||
var c = w.Cells[queue.Dequeue()];
|
||||
foreach (var p in c.Portals)
|
||||
{
|
||||
if (p.OtherCell == 0xFFFF) continue;
|
||||
uint o = w.Full(c, p.OtherCell);
|
||||
if (w.Cells.ContainsKey(o) && seen.Add(o)) queue.Enqueue(o);
|
||||
}
|
||||
}
|
||||
reachable = seen.OrderBy(x => x).ToList();
|
||||
|
||||
// Solid things: the cells' own walls (every physics polygon that is not a floor) and their static objects.
|
||||
int stabSolid = 0, stabPass = 0;
|
||||
foreach (uint id in reachable)
|
||||
{
|
||||
var c = w.Cells[id];
|
||||
foreach (var wall in c.Walls) w.Solids.Add(Footprint.FromPolygon(wall, $"wall {id:X8}"));
|
||||
foreach (var s in c.Stabs)
|
||||
{
|
||||
var shape = models.Get(s.Id);
|
||||
if (shape.IsEmpty) { stabPass++; continue; }
|
||||
stabSolid++;
|
||||
AddShape(w, shape, s.Origin, s.Rotation, 1f, $"object {s.Id:X8} in {id:X8}");
|
||||
}
|
||||
}
|
||||
w.Notes.Add($"{reachable.Count} cells reachable from the arrivals; {stabSolid} solid static objects, {stabPass} with no physics");
|
||||
|
||||
foreach (var n in doc["npcs"]?.AsArray() ?? new JsonArray())
|
||||
{
|
||||
if (n?["setup"] == null) continue;
|
||||
var shape = models.Get(Hex(n["setup"]));
|
||||
var pos = new Vector3(F(n["x"]), F(n["y"]), F(n["z"]));
|
||||
if (shape.Cylinders.Count + shape.Spheres.Count > 0) AddShape(w, shape, pos, Quaternion.Identity, 1f, "npc " + (string?)n["name"], polygons: false);
|
||||
else w.Solids.Add(Footprint.Disc(pos.X, pos.Y, MathF.Max(shape.Radius, 0.5f), pos.Z, pos.Z + MathF.Max(shape.Height, 1.8f), "npc " + (string?)n["name"]));
|
||||
}
|
||||
|
||||
foreach (var e in doc["exits"]!.AsArray())
|
||||
{
|
||||
float scale = e!["scale"] != null ? F(e["scale"]) : 1f;
|
||||
float r = 0;
|
||||
if (e["setup"] != null)
|
||||
{
|
||||
var shape = models.Get(Hex(e["setup"]));
|
||||
r = shape.Cylinders.Select(c => c.Radius + new Vector2(c.Origin.X, c.Origin.Y).Length())
|
||||
.Concat(shape.Spheres.Select(s => s.Radius + new Vector2(s.Center.X, s.Center.Y).Length()))
|
||||
.DefaultIfEmpty(shape.Radius).Max() * scale;
|
||||
}
|
||||
if (r <= 0.1f) { r = 1.0f; w.Notes.Add($"portal {(string?)e["name"]} has no collision radius in its setup; 1 m assumed"); }
|
||||
w.Portals.Add(new PortalZone
|
||||
{
|
||||
Guid = (string)e["guid"]!, Name = (string)e["name"]!, Cell = Hex(e["cell"]),
|
||||
Pos = new Vector3(F(e["x"]), F(e["y"]), F(e["z"])), Radius = r,
|
||||
});
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
private static void AddShape(Indoor w, ModelShape shape, Vector3 origin, Quaternion rot, float scale, string source, bool polygons = true)
|
||||
{
|
||||
if (polygons)
|
||||
foreach (var poly in shape.Polygons)
|
||||
{
|
||||
// Every polygon, tops included: Footprint.Blocks keeps only what stands between
|
||||
// step-up height and head height, so a low top you can step onto never blocks.
|
||||
var p = poly.Select(v => Vector3.Transform(v * scale, rot) + origin).ToArray();
|
||||
w.Solids.Add(Footprint.FromPolygon(p, source));
|
||||
}
|
||||
foreach (var (o, r, h) in shape.Cylinders)
|
||||
{
|
||||
var c = Vector3.Transform(o * scale, rot) + origin;
|
||||
w.Solids.Add(Footprint.Disc(c.X, c.Y, r * scale, c.Z, c.Z + h * scale, source));
|
||||
}
|
||||
foreach (var (o, r) in shape.Spheres)
|
||||
{
|
||||
var c = Vector3.Transform(o * scale, rot) + origin;
|
||||
w.Solids.Add(Footprint.Disc(c.X, c.Y, r * scale, c.Z - r * scale, c.Z + r * scale, source));
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue